diff --git a/.agents/skills/bundle-size-optimization b/.agents/skills/bundle-size-optimization new file mode 120000 index 0000000000..692e634b24 --- /dev/null +++ b/.agents/skills/bundle-size-optimization @@ -0,0 +1 @@ +../../skills/bundle-size-optimization \ No newline at end of file diff --git a/.changeset/config.json b/.changeset/config.json new file mode 100644 index 0000000000..9815b19762 --- /dev/null +++ b/.changeset/config.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://unpkg.com/@changesets/config@3.1.2/schema.json", + "changelog": [ + "@changesets/changelog-github", + { "repo": "TanStack/router", "disableThanks": true } + ], + "commit": false, + "access": "public", + "baseBranch": "main", + "updateInternalDependencies": "patch", + "fixed": [], + "linked": [], + "ignore": [], + "___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH": { + "onlyUpdatePeerDependentsWhenOutOfRange": true + } +} diff --git a/.changeset/rsbuild-manifest-module-chunks-once.md b/.changeset/rsbuild-manifest-module-chunks-once.md new file mode 100644 index 0000000000..02febd9d84 --- /dev/null +++ b/.changeset/rsbuild-manifest-module-chunks-once.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild: the Start manifest pass that runs after every client compilation (builds and each dev update) reads an imported module's chunks once per compilation and counts the module once per importing chunk, instead of once per import connection. The manifest is unchanged; the pass takes about 40 % less time (on a 333-route app, tens of milliseconds less per HMR update). diff --git a/.changeset/rsbuild-manifest-own-chunks.md b/.changeset/rsbuild-manifest-own-chunks.md new file mode 100644 index 0000000000..04e8e29928 --- /dev/null +++ b/.changeset/rsbuild-manifest-own-chunks.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild: a route's client manifest entry lists only its own chunks and CSS. When two routes shared a module in a chunk of its own, each route's entry also listed the other route's chunk as a preload and its stylesheet. diff --git a/.changeset/rsbuild-rule-use-falsy-loaders.md b/.changeset/rsbuild-rule-use-falsy-loaders.md new file mode 100644 index 0000000000..a84a054fbd --- /dev/null +++ b/.changeset/rsbuild-rule-use-falsy-loaders.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +fix: the Rsbuild RSC integration skips falsy entries in a rule's `use` array (Rspack's conditionally disabled loaders) instead of treating them as loaders. diff --git a/.changeset/rsbuild-virtual-modules-build.md b/.changeset/rsbuild-virtual-modules-build.md new file mode 100644 index 0000000000..01a0c5ee6e --- /dev/null +++ b/.changeset/rsbuild-virtual-modules-build.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild: fix the Rsbuild plugin build after two changes to its virtual modules crossed. Without this fix the package does not build, so no release could ship it. The Rsbuild dev manifest is written to its virtual module under the app's root. diff --git a/.changeset/rsbuild-virtual-modules-root.md b/.changeset/rsbuild-virtual-modules-root.md new file mode 100644 index 0000000000..427043a712 --- /dev/null +++ b/.changeset/rsbuild-virtual-modules-root.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild: Start writes its virtual modules under the app's root, not the working directory. An app built or served from another directory (`rsbuild build --root ` from a monorepo root) no longer fails with "Module not found" on the packages they import, such as RSC's serialization adapters. diff --git a/.changeset/rsc-security-floor.md b/.changeset/rsc-security-floor.md new file mode 100644 index 0000000000..9c828f13b3 --- /dev/null +++ b/.changeset/rsc-security-floor.md @@ -0,0 +1,8 @@ +--- +'@tanstack/react-start-rsc': patch +--- + +Raise the minimum RSC bundler peer dependencies to versions with the React Server Components fixes for GHSA-xqc2-xf4c-x3h3 (CVE-2026-126187, unauthenticated RCE) and GHSA-h3gv-c5rc-p453 (server function DoS): + +- `@vitejs/plugin-rsc` to `>=0.5.38` (GHSA-59pf-q495-3c99), which vendors a fixed `react-server-dom-webpack`. +- `react-server-dom-rspack` to `>=0.1.1`, the first release built from React sources that include the fix. diff --git a/.changeset/start-server-fn-custom-id-check.md b/.changeset/start-server-fn-custom-id-check.md new file mode 100644 index 0000000000..384f0ade06 --- /dev/null +++ b/.changeset/start-server-fn-custom-id-check.md @@ -0,0 +1,7 @@ +--- +'@tanstack/start-plugin-core': minor +--- + +A server function id that a custom `serverFns.generateFunctionId` returns and that never worked over HTTP now fails the build, with an error naming the file, the function and the id: whitespace, a control or non-ASCII character, any of `"`, `#`, `/`, `<`, `>`, `?`, `\`, `^`, `` ` ``, `{`, `}`, the ids `.` and `..`, and a percent-encoding the server reads as another id (`%41`, lowercase hex, `%2E`) or rejects. The client puts the id in the URL unencoded, so a `#` or `?` ended the path and a `/` cut the id short (the call silently ran another server function of the file or none), and the other characters reached the server percent-encoded and matched no function. An id embedding a non-ASCII `functionName` is one of these. One case did work and now fails the build: such an id on a server function only SSR code called. + +Ids with `%` or the other characters URLs allow (such as `:`, `@`, `+`, `=`, `,`, `;`, `!`, `*`, `(`, `)`, `&`, `'`, `|`, `[`, `]`) still build and reach their handler, with a deprecation warning (from the Vite plugin; the Rsbuild plugin does not print compiler warnings yet): the next major version rejects them, since proxies and servers may decode or rewrite them (hash the inputs instead, as the documented example does). An id with `'` no longer breaks the server bundle. diff --git a/.changeset/start-vite-root-library-discovery.md b/.changeset/start-vite-root-library-discovery.md new file mode 100644 index 0000000000..d4e8221c59 --- /dev/null +++ b/.changeset/start-vite-root-library-discovery.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Vite: Start finds the Start libraries it bundles in the SSR build from Vite's root, not the working directory. A `vite build ` run from another directory (a monorepo root, a script) no longer leaves them external and uncompiled, where their server fns returned `undefined`. diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 0000000000..21d884dbeb --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,12 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json + +reviews: + request_changes_workflow: false + slop_detection: + enabled: true + +knowledge_base: + code_guidelines: + enabled: true + filePatterns: + - 'CONTRIBUTING.md' diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000000..a4c1d62013 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,7 @@ +.github/ @TanStack/tanstack-core +.nx/ @TanStack/tanstack-core +nx.json @TanStack/tanstack-core +/scripts/nx @TanStack/tanstack-core +.changeset/config.json @TanStack/tanstack-core +scripts/ @TanStack/tanstack-core +.npmrc @TanStack/tanstack-core \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 206560136b..9dd0def7bd 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -4,16 +4,24 @@ body: - type: markdown attributes: value: | + + Thank you for reporting an issue :pray:. - This issue tracker is for reporting bugs found in `router` (https://github.com/tanstack/router). + This issue tracker is for reporting bugs found in TanStack Router and/or Start. If you have a question about how to achieve something and are struggling, please post a question inside of `router` Discussions tab: https://github.com/tanstack/router/discussions Before submitting a new bug/issue, please check the links below to see if there is a solution or question posted there already: - - `router` Issues tab: https://github.com/tanstack/router/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc - - `router` closed issues tab: https://github.com/tanstack/router/issues?q=is%3Aissue+sort%3Aupdated-desc+is%3Aclosed - - `router` Discussions tab: https://github.com/tanstack/router/discussions + - Issues tab: https://github.com/tanstack/router/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc + - closed issues tab: https://github.com/tanstack/router/issues?q=is%3Aissue+sort%3Aupdated-desc+is%3Aclosed + - Discussions tab: https://github.com/tanstack/router/discussions The more information you fill in, the better the community can help you. - type: dropdown @@ -36,21 +44,22 @@ body: - type: input id: link attributes: - label: Your Example Website or App + label: Complete minimal reproducer description: | - Which website or app were you using when the bug happened? - Note: - - Please provide a link via our pre-configured Stackblitz project ([file-based routes](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/quickstart-file-based?file=src%2Fmain.tsx)|[code-based routes](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/quickstart?file=src%2Fmain.tsx)) or a link to a repo that can reproduce the issue. - - Your bug will may get fixed much faster if we can run your code and it doesn't have dependencies other than the `router` npm package / dependency. - - To create a shareable code example you can use Stackblitz. Please no localhost URLs. - - Please read these tips for providing a minimal example: https://stackoverflow.com/help/mcve. + Bug reports need a complete minimal reproducer project. + The reproducer project must be + - either a Stackblitz project (use this pre-configured Stackblitz project ([file-based routes](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/quickstart-file-based?file=src%2Fmain.tsx)|[code-based routes](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/quickstart?file=src%2Fmain.tsx))) + - or a public git repo. + In case of a git repo, the issue must be reproducible **directly** after cloning and installing dependencies. + + If you dont supply a reproducer that meets the above requirements, this issue will be closed. placeholder: reproduction URL validations: required: true - type: textarea id: steps attributes: - label: Steps to Reproduce the Bug or Issue + label: Steps to Reproduce the Bug description: Describe the steps we have to take to reproduce the behavior. placeholder: | 1. Go to '...' diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000..a5ef10f1ff --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,22 @@ +## 🎯 Changes + + + +## ✅ Checklist + +- [ ] I have followed the steps in the [Contributing guide](https://github.com/TanStack/router/blob/main/CONTRIBUTING.md). +- [ ] I have tested code changes locally with the relevant test commands, or tests do not apply to this pull request. +- [ ] I fully understand the code in this pull request, including any code generated with AI assistance. + +## 🚀 Release Impact + +- [ ] This change affects published code, and I have generated a [changeset](https://github.com/changesets/changesets/blob/main/docs/adding-a-changeset.md). +- [ ] This change is docs/CI/dev-only (no release). + + diff --git a/.github/renovate.json b/.github/renovate.json index 03cea18d0e..6fd5aa1c86 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -3,6 +3,7 @@ "configMigration": true, "extends": [ "config:recommended", + "helpers:pinGitHubActionDigests", "group:allNonMajor", "schedule:weekly", ":approveMajorUpdates", @@ -20,7 +21,6 @@ "@types/node", "@types/react", "@types/react-dom", - "h3", "node", "react", "react-dom", diff --git a/.github/workflows/autofix.yml b/.github/workflows/autofix.yml index 4ab8d05993..78aea28c12 100644 --- a/.github/workflows/autofix.yml +++ b/.github/workflows/autofix.yml @@ -2,8 +2,6 @@ name: autofix.ci # needed to securely identify the workflow on: pull_request: - push: - branches: [main, alpha, beta] concurrency: group: ${{ github.workflow }}-${{ github.event.number || github.ref }} @@ -19,14 +17,16 @@ jobs: if: ${{ github.event_name == 'push' || !github.event.pull_request.draft }} steps: - name: Checkout - uses: actions/checkout@v6.0.1 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false - name: Setup Tools - uses: tanstack/config/.github/setup@main + uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Fix formatting run: pnpm format - name: Generate labeler config run: pnpm labeler-generate - name: Apply fixes - uses: autofix-ci/action@635ffb0c9798bd160680f18fd73371e355b85f27 + uses: autofix-ci/action@c5b2d67aa2274e7b5a18224e8171550871fc7e4a # v1.3.4 with: commit-message: 'ci: apply automated fixes' diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml new file mode 100644 index 0000000000..bbc3a1fa24 --- /dev/null +++ b/.github/workflows/benchmarks.yml @@ -0,0 +1,92 @@ +# Setup taken from https://codspeed.io/docs/benchmarks/nodejs/vitest +name: Benchmarks + +on: + push: + # Broad on purpose: CodSpeed compares each PR against the run on its + # merge-base commit. Skipping main pushes that don't touch packages/** + # (pnpm config, CI, root tooling) leaves those commits without a baseline + # run, and CodSpeed silently falls back to an older, possibly outlier run — + # which then flags phantom regressions on every PR until the next eligible + # push. Only paths that cannot affect benchmark results are excluded. + branches: + - 'main' + paths-ignore: + - 'docs/**' + - 'examples/**' + - 'e2e/**' + pull_request: + paths: + - 'packages/**' + - '!packages/**/tests/**' + - '!packages/**/__tests__/**' + - '!packages/**/*.test.*' + - 'benchmarks/**' + - '.nvmrc' + workflow_dispatch: + +concurrency: + group: benchmarks-${{ github.ref }} + cancel-in-progress: false + queue: single + +permissions: + contents: read # required for actions/checkout + id-token: write # required for OIDC authentication with CodSpeed + +env: + NX_CLOUD_ACCESS_TOKEN: ${{ secrets.NX_CLOUD_ACCESS_TOKEN }} + SERVER_PRESET: 'node-server' + NX_NO_CLOUD: true + +jobs: + benchmarks: + name: Run ${{ matrix.benchmark }}:${{ matrix.framework }} CodSpeed benchmark + strategy: + fail-fast: false + matrix: + framework: + - react + - solid + - vue + benchmark: + - client-nav + - ssr + - memory-server + - memory-client + include: + - benchmark: client-nav + mode: simulation + - benchmark: ssr + mode: simulation + - benchmark: memory-server + mode: memory + - benchmark: memory-client + mode: memory + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: Setup Tools + uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + + # Run the build outside of the CodSpeed action to avoid being slowed by intrumentation overhead. + # (and then run the task itself with --excludeTaskDependencies) + - name: Prepare ${{ matrix.benchmark }}:${{ matrix.framework }} benchmark + run: >- + pnpm nx run + @benchmarks/${{ matrix.benchmark }}:build:${{ matrix.framework }} + + - name: Run ${{ matrix.benchmark }}:${{ matrix.framework }} CodSpeed benchmark + uses: CodSpeedHQ/action@373d6868929f444bc08d901fd0eb0ad52a8875ea # v5.2.1 + timeout-minutes: 20 + with: + mode: ${{ matrix.mode }} + run: >- + WITH_INSTRUMENTATION=1 + pnpm nx run + @benchmarks/${{ matrix.benchmark }}:test:perf:${{ matrix.framework }} + --excludeTaskDependencies diff --git a/.github/workflows/bundle-size.yml b/.github/workflows/bundle-size.yml new file mode 100644 index 0000000000..51ffa28e4c --- /dev/null +++ b/.github/workflows/bundle-size.yml @@ -0,0 +1,152 @@ +name: Bundle Size + +on: + # We use `pull_request` to split trust boundaries across jobs: + # - `benchmark-pr` checks out PR merge code and runs it as untrusted with read-only permissions. + # - `comment-pr` runs trusted base-repo code with limited write access to upsert the PR comment. + pull_request: + paths: + - 'packages/**' + - 'benchmarks/**' + - 'scripts/benchmarks/bundle-size/**' + - '.nvmrc' + - 'package.json' + - 'pnpm-lock.yaml' + push: + branches: [main] + paths: + - 'packages/**' + - 'benchmarks/**' + - 'scripts/benchmarks/bundle-size/**' + - '.nvmrc' + - 'package.json' + - 'pnpm-lock.yaml' + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + NX_NO_CLOUD: true +jobs: + benchmark-pr: + name: Benchmark PR + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + outputs: + current_json_b64: ${{ steps.capture.outputs.current_json_b64 }} + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + ref: refs/pull/${{ github.event.pull_request.number }}/merge + fetch-depth: 0 + persist-credentials: false + + - name: Setup Tools + uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + + - name: Measure Bundle Size + run: pnpm benchmark:bundle-size --outputStyle=stream --skipRemoteCache + + - name: Capture Benchmark Outputs + id: capture + run: | + { + echo "current_json_b64=$(base64 -w 0 < benchmarks/bundle-size/results/current.json)" + } >> "$GITHUB_OUTPUT" + + comment-pr: + name: Upsert PR Comment + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + needs: benchmark-pr + permissions: + contents: read + pull-requests: write + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Restore Benchmark Outputs + env: + CURRENT_JSON_B64: ${{ needs.benchmark-pr.outputs.current_json_b64 }} + run: | + mkdir -p benchmarks/bundle-size/results + node -e "const fs=require('node:fs'); fs.writeFileSync('benchmarks/bundle-size/results/current.json', Buffer.from(process.env.CURRENT_JSON_B64 || '', 'base64'))" + + - name: Read Historical Data (if available) + run: | + mkdir -p benchmarks/bundle-size/results + if git fetch --depth=1 origin gh-pages; then + if git show origin/gh-pages:benchmarks/bundle-size/data.js > benchmarks/bundle-size/results/history-data.js 2>/dev/null; then + echo "Loaded bundle-size history from gh-pages." + else + rm -f benchmarks/bundle-size/results/history-data.js + echo "No bundle-size history found on gh-pages yet." + fi + fi + + - name: Build PR Report + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + REPOSITORY_NAME: ${{ github.event.repository.name }} + REPOSITORY_OWNER: ${{ github.repository_owner }} + run: | + node scripts/benchmarks/bundle-size/pr-report.mjs \ + --current benchmarks/bundle-size/results/current.json \ + --history benchmarks/bundle-size/results/history-data.js \ + --output benchmarks/bundle-size/results/pr-comment.md \ + --base-sha "$BASE_SHA" \ + --dashboard-url "https://${REPOSITORY_OWNER}.github.io/${REPOSITORY_NAME}/benchmarks/bundle-size/" + 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: | + node scripts/benchmarks/common/upsert-pr-comment.mjs \ + --pr "${{ github.event.pull_request.number }}" \ + --body-file benchmarks/bundle-size/results/pr-comment.md + + 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' + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Setup Tools + uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + + - name: Measure Bundle Size + run: pnpm benchmark:bundle-size --outputStyle=stream --skipRemoteCache + - name: Publish Benchmark Dashboard + uses: benchmark-action/github-action-benchmark@52576c92bccf6ac60c8223ec7eb2565637cae9ba # v1.22.1 + with: + tool: customSmallerIsBetter + name: Bundle Size (gzip) + output-file-path: benchmarks/bundle-size/results/benchmark-action.json + github-token: ${{ secrets.GITHUB_TOKEN }} + auto-push: true + gh-pages-branch: gh-pages + benchmark-data-dir-path: benchmarks/bundle-size + max-items-in-chart: 200 + summary-always: true + comment-on-alert: false + fail-on-alert: false diff --git a/.github/workflows/check-skills.yml b/.github/workflows/check-skills.yml new file mode 100644 index 0000000000..f00a11731b --- /dev/null +++ b/.github/workflows/check-skills.yml @@ -0,0 +1,122 @@ +# check-skills.yml — Drop this into your library repo's .github/workflows/ +# +# Validates intent skills on PRs. After a release or manual run, opens or +# updates one review PR when existing skills, artifact coverage, or workspace +# package coverage need review. +# +# Triggers: pull requests touching skills/artifacts, pushes to main affecting +# docs/source paths, new release published, or manual workflow_dispatch. +# +# intent-workflow-version: 4 +# +# Template variables (replaced by `intent setup`): +# @tanstack/router — e.g. @tanstack/query or my-workspace workspace + +name: Check Skills + +concurrency: + group: check-skills-${{ github.ref }} + cancel-in-progress: true + +on: + pull_request: + paths: + - 'skills/**' + - '**/skills/**' + - '_artifacts/**' + - '**/_artifacts/**' + push: + branches: [main] + paths: + - 'docs/**' + - 'packages/*/src/**' + release: + types: [published] + workflow_dispatch: {} + +permissions: {} + +jobs: + validate: + name: Validate intent skills + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: Setup Node + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: 24 + package-manager-cache: false + + - name: Install intent + run: npm install -g @tanstack/intent + + - name: Validate skills + run: intent validate --github-summary + + review: + name: Check intent skill coverage + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 + persist-credentials: true # review job pushes a generated branch + + - name: Setup Node + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: 24 + package-manager-cache: false + + - name: Install intent + run: npm install -g @tanstack/intent + + - name: Check skills + id: stale + run: | + intent stale --github-review --package-label "@tanstack/router" + + - name: Open or update review PR + if: steps.stale.outputs.has_review == 'true' + env: + BASE_BRANCH: ${{ github.event.repository.default_branch }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + VERSION: ${{ github.event.release.tag_name || 'manual' }} + run: | + BRANCH="skills/review-${VERSION}" + + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + + git fetch origin "$BRANCH:refs/remotes/origin/$BRANCH" || true + if git show-ref --verify --quiet "refs/remotes/origin/$BRANCH"; then + git checkout -B "$BRANCH" "origin/$BRANCH" + else + git checkout -b "$BRANCH" + git commit --allow-empty -m "chore: review intent skills for ${VERSION}" + git push origin "$BRANCH" + fi + + PR_URL="$(gh pr list --head "$BRANCH" --json url --jq '.[0].url')" + if [ -n "$PR_URL" ]; then + gh pr edit "$PR_URL" --body-file pr-body.md + else + gh pr create \ + --title "Review intent skills (${VERSION})" \ + --body-file pr-body.md \ + --head "$BRANCH" \ + --base "$BASE_BRANCH" + fi diff --git a/.github/workflows/compiler-platforms.yml b/.github/workflows/compiler-platforms.yml new file mode 100644 index 0000000000..ad70e39bb6 --- /dev/null +++ b/.github/workflows/compiler-platforms.yml @@ -0,0 +1,101 @@ +name: Compiler Platforms + +# The main PR workflow only runs on Linux x64 (glibc). The compilers load a +# native Yuku binary per platform and handle platform-specific paths, so run +# their unit tests and a Vite and Rsbuild production build on the other +# platforms we ship to. + +on: + pull_request: + paths: + - 'packages/router-utils/**' + - 'packages/router-generator/**' + - 'packages/router-plugin/**' + - 'packages/start-plugin-core/**' + - 'pnpm-lock.yaml' + - '.github/workflows/compiler-platforms.yml' + schedule: + # Weekly, to catch new Yuku releases and runner image updates + - cron: '0 6 * * 1' + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + NX_DAEMON: 'false' + NX_NO_CLOUD: 'true' + +defaults: + run: + shell: bash + +jobs: + compiler: + name: ${{ matrix.name }} + runs-on: ${{ matrix.os }} + # actions/setup-node only ships glibc builds, so musl uses Alpine's Node image + container: ${{ matrix.container }} + strategy: + fail-fast: false + matrix: + include: + - name: Windows x64 + os: windows-latest + - name: macOS arm64 + os: macos-latest + - name: Linux arm64 + os: ubuntu-24.04-arm + - name: Linux x64 musl + os: ubuntu-latest + container: node:24.8.0-alpine3.22@sha256:3e843c608bb5232f39ecb2b25e41214b958b0795914707374c8acc28487dea17 + steps: + - name: Install system packages + if: ${{ matrix.container }} + shell: sh + run: apk add --no-cache bash git + - name: Keep LF line endings + # Snapshots are stored with LF. Windows runners check out CRLF by default, + # and with `* text=auto` disabling autocrlf alone still uses the native eol + run: | + git config --global core.autocrlf false + git config --global core.eol lf + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - name: Setup pnpm + if: ${{ !matrix.container }} + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 + - name: Setup Node + if: ${{ !matrix.container }} + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version-file: .nvmrc + package-manager-cache: false + - name: Setup pnpm (container) + if: ${{ matrix.container }} + run: npm install --global "$(node -p "require('./package.json').packageManager")" + - name: Install dependencies + run: >- + pnpm install --frozen-lockfile + --filter . + --filter "@tanstack/router-utils..." + --filter "@tanstack/router-generator..." + --filter "@tanstack/router-plugin..." + --filter "@tanstack/start-plugin-core..." + --filter "tanstack-react-start-e2e-basic..." + - name: Unit tests + run: >- + pnpm nx run-many --targets=test:unit + --projects=@tanstack/router-utils,@tanstack/router-generator,@tanstack/router-plugin,@tanstack/start-plugin-core + --skip-nx-cache --outputStyle=static + - name: Production builds + run: >- + pnpm nx run-many --targets=build:vite:ssr,build:rsbuild:ssr + --projects=tanstack-react-start-e2e-basic + --skip-nx-cache --outputStyle=static diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index 222c1c7915..fde1100409 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -1,7 +1,7 @@ name: Labeler on: - - pull_request_target + pull_request: permissions: contents: read @@ -9,12 +9,12 @@ 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 - permissions: - contents: read - pull-requests: write steps: - - uses: actions/labeler@v5.0.0 + - name: Labeller + uses: actions/labeler@f27b608878404679385c85cfa523b85ccb86e213 # v6.1.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} configuration-path: labeler-config.yml diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 27afd72710..ae19b4f0d2 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -10,10 +10,16 @@ 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 - pull-requests: write jobs: test: @@ -23,33 +29,53 @@ jobs: TSR_TMP_DIR: ./tmp steps: - name: Checkout - uses: actions/checkout@v6.0.1 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: fetch-depth: 0 - - name: Start Nx Agents - run: npx nx-cloud start-ci-run --distribute-on=".nx/workflows/dynamic-changesets.yaml" + persist-credentials: false + - name: Start Nx Workers + run: npx nx-cloud start-workers - name: Setup Tools - uses: tanstack/config/.github/setup@main + uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Get base and head commits for `nx affected` - uses: nrwl/nx-set-shas@v4.4.0 + uses: nrwl/nx-set-shas@afb73a62d26e41464e9254689e1fd6122ee683c1 # v5.0.1 with: main-branch-name: main - name: Run Checks run: pnpm run test:pr --parallel=3 - - name: Stop Nx Agents + - name: Stop Nx Workers if: ${{ always() }} - run: npx nx-cloud stop-all-agents + run: npx nx-cloud stop-all-workers preview: name: Preview runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write steps: - name: Checkout - uses: actions/checkout@v6.0.1 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: fetch-depth: 0 + persist-credentials: false - name: Setup Tools - uses: tanstack/config/.github/setup@main + uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Build Packages run: pnpm run build:all - name: Publish Previews run: pnpx pkg-pr-new publish --pnpm './packages/*' --template './examples/*/*' + version-preview: + name: Version Preview + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - name: Setup Tools + uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + - name: Changeset Preview + uses: TanStack/config/.github/changeset-preview@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2ea3eddbf5..115c3445e6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,17 +1,12 @@ name: Release on: - workflow_dispatch: - inputs: - tag: - description: override release tag - required: false push: - branches: [main, alpha, beta] + branches: [main, '*-pre', '*-maint'] concurrency: - group: ${{ github.workflow }}-${{ github.event.number || github.ref }} - cancel-in-progress: true + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false env: NX_CLOUD_ACCESS_TOKEN: ${{ secrets.NX_CLOUD_ACCESS_TOKEN }} @@ -25,27 +20,45 @@ permissions: jobs: release: name: Release - if: github.repository_owner == 'TanStack' runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v6.0.1 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: fetch-depth: 0 - - name: Start Nx Agents - run: npx nx-cloud start-ci-run --distribute-on=".nx/workflows/dynamic-changesets.yaml" + persist-credentials: true # changesets/action pushes Release PR commits - name: Setup Tools - uses: tanstack/config/.github/setup@main - - name: Run Tests - run: pnpm run test:ci --parallel=3 - - name: Stop Nx Agents - if: ${{ always() }} - run: npx nx-cloud stop-all-agents - - name: Publish + uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main + - name: Run Build + run: pnpm run build:all + - name: Enter Pre-Release Mode + if: "contains(github.ref_name, '-pre') && !hashFiles('.changeset/pre.json')" + run: pnpm changeset pre enter pre + - name: Determine dist-tag + id: dist-tag run: | - git config --global user.name 'Tanner Linsley' - git config --global user.email 'tannerlinsley@users.noreply.github.com' - pnpm run cipublish + BRANCH="${GITHUB_REF_NAME}" + if [[ "$BRANCH" == *-pre ]]; then + echo "prerelease=true" >> "$GITHUB_OUTPUT" + elif [[ "$BRANCH" == *-maint ]]; then + echo "tag=maint" >> "$GITHUB_OUTPUT" + else + echo "latest=true" >> "$GITHUB_OUTPUT" + fi + - name: Create Release Pull Request or Publish + id: changesets + uses: changesets/action@63a615b9cd06ba9a3e6d13796c7fbcb080a60a0b # v1.8.0 + with: + version: pnpm run changeset:version + publish: pnpm run changeset:publish ${{ steps.dist-tag.outputs.tag && format('--tag {0}', steps.dist-tag.outputs.tag) }} + title: 'ci: Version Packages' + commit: 'ci: changeset release' env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NODE_OPTIONS: --max-old-space-size=8192 + - name: Create GitHub Release + if: steps.changesets.outputs.published == 'true' + run: node scripts/create-github-release.mjs ${{ steps.dist-tag.outputs.prerelease == 'true' && '--prerelease' }} ${{ steps.dist-tag.outputs.latest == 'true' && '--latest' }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - TAG: ${{ inputs.tag }} diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml new file mode 100644 index 0000000000..55afe41cc7 --- /dev/null +++ b/.github/workflows/zizmor.yml @@ -0,0 +1,25 @@ +name: GitHub Actions Security Analysis + +on: + push: + branches: [main] + pull_request: + branches: ['**'] + +permissions: {} + +jobs: + zizmor: + name: Run zizmor + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: Run zizmor + uses: zizmorcore/zizmor-action@5f14fd08f7cf1cb1609c1e344975f152c7ee938d # v0.5.6 + with: + advanced-security: false + annotations: true diff --git a/.gitignore b/.gitignore index 6c9f1720dc..70028b2860 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,11 @@ coverage packages/router-generator/tests/**/*.gen.ts packages/router-generator/tests/**/*.gen.js **/port*.txt +**/test-results/** + +# Playwright artifacts +**/playwright-report/ +**/blob-report/ # misc .DS_Store @@ -54,10 +59,14 @@ ts-perf /examples/*/*/package-lock.json .netlify +.vercel nx-cloud.env .nx/cache .nx/workspace-data +.nx/polygraph +.nx/self-healing +.nx/migrate-runs gpt/db.json @@ -79,3 +88,9 @@ vite.config.ts.timestamp_* **/llms **/.tanstack + +# eslint-plugin-start perf fixtures +/e2e/eslint-plugin-start/src/perf/generated + +# local memory flame profiles +benchmarks/memory/**/.profiles/ diff --git a/.nvmrc b/.nvmrc index b404027604..63f87c20ef 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -24.8.0 +26.12.1 diff --git a/.nx/ci-config.yaml b/.nx/ci-config.yaml new file mode 100644 index 0000000000..2f0783feb4 --- /dev/null +++ b/.nx/ci-config.yaml @@ -0,0 +1,5 @@ +dte: + distribute-on: + small-changeset: 6 linux-medium-js + medium-changeset: 12 linux-medium-js + large-changeset: 18 linux-medium-js diff --git a/.nx/workflows/dynamic-changesets.yaml b/.nx/workflows/dynamic-changesets.yaml deleted file mode 100644 index d3536f3ba7..0000000000 --- a/.nx/workflows/dynamic-changesets.yaml +++ /dev/null @@ -1,4 +0,0 @@ -distribute-on: - small-changeset: 3 linux-medium-js - medium-changeset: 6 linux-medium-js - large-changeset: 10 linux-medium-js diff --git a/.nx/workflows/ultracache-config.yaml b/.nx/workflows/ultracache-config.yaml new file mode 100644 index 0000000000..b3ed223621 --- /dev/null +++ b/.nx/workflows/ultracache-config.yaml @@ -0,0 +1,124 @@ +ignore-reads: + - e2e/.gitignore + - '**/src/routeTree.gen.ts' +ignore-writes: + - '**/src/routeTree.gen.ts' +task-exclusions: + - target: test:build + ignore-reads: + - LICENSE + # HMR tests edit these inputs in place and restore their original contents. + # Keep them out of cached outputs so cache replay never overwrites source. + - project: tanstack-react-start-e2e-deferred-hydration + target: test:e2e + ignore-writes: + - e2e/react-start/deferred-hydration/src/routes/components.tsx + - project: tanstack-react-start-e2e-hmr + target: test:e2e + ignore-writes: &hmr-source-writes + - e2e/react-start/hmr/src/components/AliasedRouteImportChildPanel.tsx + - e2e/react-start/hmr/src/components/AliasedRouteImportParentPanel.tsx + - e2e/react-start/hmr/src/hmr/server-fn-hmr-factory.ts + - e2e/react-start/hmr/src/routes/__root.tsx + - e2e/react-start/hmr/src/routes/child.tsx + - e2e/react-start/hmr/src/routes/component-hmr-inline-error-split.tsx + - e2e/react-start/hmr/src/routes/component-hmr-inline-nosplit.tsx + - e2e/react-start/hmr/src/routes/component-hmr-inline-split.tsx + - e2e/react-start/hmr/src/routes/component-hmr-lowercase-named-split.tsx + - e2e/react-start/hmr/src/routes/component-hmr-named-error-split.tsx + - e2e/react-start/hmr/src/routes/component-hmr-named-nosplit.tsx + - e2e/react-start/hmr/src/routes/component-hmr-named-split.tsx + - e2e/react-start/hmr/src/routes/index.tsx + - e2e/react-start/hmr/src/routes/inputs.tsx + - project: tanstack-react-start-e2e-hmr + target: test:e2e--vite-ssr + ignore-writes: *hmr-source-writes + - project: tanstack-react-start-e2e-hmr + target: test:e2e--vite-ssr--bundled-dev + ignore-writes: *hmr-source-writes + - project: tanstack-react-start-e2e-hmr + target: test:e2e--rsbuild-ssr + ignore-writes: *hmr-source-writes + - project: tanstack-react-start-e2e-rsbuild + target: test:e2e--rsbuild-ssr + ignore-writes: + - e2e/react-start/rsbuild/src/routes/index.tsx + - project: tanstack-react-start-e2e-server-functions + target: test:e2e + ignore-writes: + - e2e/react-start/server-functions/src/routes/consistent.tsx + # Scaffolding tests deliberately populate tracked empty route fixtures. + - project: '@tanstack/router-generator' + target: test:unit + ignore-writes: + - packages/router-generator/tests/generator/custom-scaffolding/routes/__root.tsx + - packages/router-generator/tests/generator/custom-scaffolding/routes/api/bar.tsx + - packages/router-generator/tests/generator/custom-scaffolding/routes/foo.lazy.tsx + - packages/router-generator/tests/generator/custom-scaffolding/routes/index.tsx + # These reads are of scratch files created by the same test invocation. + - project: tanstack-solid-start-e2e-basic-auth + target: test:e2e + ignore-reads: + - e2e/solid-start/basic-auth/.tmp/dev.db + - project: tanstack-vue-start-e2e-basic-auth + target: test:e2e + ignore-reads: + - e2e/vue-start/basic-auth/.tmp/dev.db + - project: '@tanstack/router-generator' + target: test:unit + ignore-reads: + - packages/router-generator/tests/generator/file-modification/routes/[(]test[)]/initiallyEmpty.tsx + - packages/router-generator/tests/generator/file-modification/routes/[(]test[)]/initiallyEmpty.lazy.tsx + # Mutable counters are scratch state, not artifacts to replay from cache. + - project: tanstack-react-start-e2e-basic-tsr-config + target: test:e2e + ignore-reads: + - e2e/react-start/basic-tsr-config/count.txt + ignore-writes: + - e2e/react-start/basic-tsr-config/count.txt + - project: tanstack-solid-start-e2e-basic-tsr-config + target: test:e2e + ignore-reads: + - e2e/solid-start/basic-tsr-config/count.txt + ignore-writes: + - e2e/solid-start/basic-tsr-config/count.txt + - project: tanstack-vue-start-e2e-basic-tsr-config + target: test:e2e + ignore-reads: + - e2e/vue-start/basic-tsr-config/count.txt + ignore-writes: + - e2e/vue-start/basic-tsr-config/count.txt + # Paraglide downloads compiler plugins from the URLs in settings.json. + # Ignore warm-cache reads; the settings remain inputs and cache files outputs. + - project: tanstack-react-start-e2e-i18n-paraglide + target: build + ignore-reads: + - e2e/react-start/i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-router-e2e-react-i18n-paraglide + target: build + ignore-reads: + - e2e/react-router/i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-react-start-e2e-i18n-paraglide + target: test:e2e + ignore-reads: + - e2e/react-start/i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-router-e2e-react-i18n-paraglide + target: test:e2e + ignore-reads: + - e2e/react-router/i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-router-i18n-paraglide + target: build + ignore-reads: + - examples/react/i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-start-i18n-paraglide + target: build + ignore-reads: + - examples/react/start-i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-router-solid-i18n-paraglide + target: build + ignore-reads: + - examples/solid/i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-solid-start-i18n-paraglide + target: build + ignore-reads: + - examples/solid/start-i18n-paraglide/project.inlang/cache/plugins/* diff --git a/.prettierignore b/.prettierignore index 888cf74797..de501452ad 100644 --- a/.prettierignore +++ b/.prettierignore @@ -16,3 +16,8 @@ node_modules **/tests/generator/**/routeTree*.snapshot.ts /.nx/workspace-data **/src/routeTree.gen.ts +packages/router-plugin/tests/**/test-files/** +.nx/self-healing + +# Preserve the pinned upstream URL fixtures byte for byte. +packages/router-core/tests/fixtures/wpt-url/urltestdata*.json diff --git a/AGENTS.md b/AGENTS.md index dffcd741ea..f47b5103e1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,171 +1,41 @@ # AGENTS.md -## Project overview +## Scope -TanStack Router is a type-safe router with built-in caching and URL state management for React and Solid applications. This monorepo contains two main products: +- Read applicable nested `AGENTS.md` files before editing or testing a subtree. +- Shared routing belongs in `packages/router-core`; check React, Solid, and Vue bindings for shared changes. Shared Start runtime/build logic lives in `packages/start-*-core`. -- **TanStack Router** - Core routing library with type-safe navigation, search params, and path params -- **TanStack Start** - Full-stack framework built on top of TanStack Router +## Work and validation -## Setup commands +- Start bug fixes with a failing regression test that uses only public APIs to reproduce and assert user- or developer-visible behavior. Do not manufacture bugs by mutating internals. Establish whether real usage can reach the failing state before adding runtime handling; simplify handling of states proven unreachable. +- When removing an API, option, or behavior, delete its tests. Never add tests that assert the removed thing is gone, such as `not.toHaveProperty('oldName')`, a type error for the old call, or a runtime throw. +- For suspected dependency issues, verify the upstream root cause, then propose an upstream fix to the user, including for other `@tanstack/*` packages. **Never implement a workaround in this repository unless the user explicitly authorizes it.** +- During debugging/prototyping, keep fixes aligned with the PR's intended architecture. If making a test pass requires another flag, counter, copied deadline, or duplicate completion authority, stop and consolidate state and ownership. Remove superseded paths instead of accumulating patches and bundle growth. +- Use Node from `.nvmrc` and pnpm from root `package.json`. Install at the root with `CI=1 pnpm install --frozen-lockfile`. +- For sandbox-blocked registry/store access, escalate the same command; report the blocker if unavailable. Do not change stores, delete dependencies/lockfiles, use `--force`/`--ignore-scripts`, or weaken workspace trust/build policies to bypass it. +- Never manually edit `pnpm-lock.yaml` or any `routeTree.gen.ts`. Regenerate the lockfile with `pnpm install --no-frozen-lockfile` after intentional dependency changes; regenerate route trees through app builds/dev servers or the generator fixture harness. +- Always use control-flow braces. Run `pnpm format` before validation. +- Use Nx: workspace imports consume built packages, so direct runners can test stale dependencies. Inspect resolved targets with `pnpm nx show project --json`; some are inferred. +- Run finite validation through `run-many` with explicit projects and targets, including a single project/target. Nx automatically selects `summary` output when it detects an AI agent: omit `--outputStyle` for normal runs. Read the reported full log files for failures; use `--outputStyle=summary` if agent detection is unavailable. +- Use `--outputStyle=static` or `pnpm nx run :` only when diagnosing a task and its full output is needed. Continuous/watch targets may use live output. -- Install deps: `pnpm install` -- Setup e2e testing: `pnpm exec playwright install` -- Build packages: `pnpm build` (affected) or `pnpm build:all` (force all) -- Start dev server: `pnpm dev` -- Run tests: `pnpm test` +```sh +CI=1 NX_DAEMON=false pnpm nx run-many -p -t --skipRemoteCache +``` -## Code style +- Run one Nx command at a time. For a ~20-second startup/graph stall, stop, run `pnpm nx reset`, and retry once, then escalate. Do not apply that timeout to running tests. +- For code changes, run affected packages' `test:unit`, `test:types`, and `test:eslint` where available, including affected consumers; use `test:e2e` for browser/app behavior and `test:build` for exports/build changes. Root `pnpm test` includes the full e2e suite. Published-code changes require `pnpm changeset`. -- TypeScript strict mode with extensive type safety -- Framework-agnostic core logic separated from React/Solid bindings -- Type-safe routing with search params and path params -- Use workspace protocol for internal dependencies (`workspace:*`) +## Runtime rules -## Dev environment tips +- Import `isServer` from `@tanstack/router-core/isServer`. Conditional exports select: `development` → `undefined`; server (`workerd`, `worker`, `deno`, `node`, `bun`) → `true` except `NODE_ENV=test` → `undefined`; browser/fallback → `false`. `development` wins; `NODE_ENV=development` alone does not select it. +- Keep `isServer ?? router.isServer` directly in each branch condition for dead-code elimination; negate the whole expression for client branches. Never extract it into a variable (e.g. `const serverRendering = isServer ?? router.isServer`) or helper. Without a router, inline `isServer ?? typeof window === 'undefined'` (or the existing `document` check). Keep the constant first and use `??`, never `||`. +- **Never create UI/router reactivity on the server, including development/tests.** Branch before reactive setup; use direct reads and core non-reactive stores. Required transport listeners are allowed only with request-scoped lifetimes and cleanup. +- Shared route definitions/build metadata must not acquire request/user data. Keep it on the request's Router, context, or QueryClient. +- HMR can replace code while caches and pending work survive. Invalidate derived state or bypass caching in development; reject stale async results while preserving intentional HMR identities/state. +- Gate developer diagnostics and message construction with direct `process.env.NODE_ENV !== 'production'` checks. Preserve required validation/throws in production (e.g. detailed development error, compact `invariant()` failure). `!== 'development'` also enables the guarded code in tests; preserve existing dev-server mode gates. -- This is a pnpm workspace monorepo with packages organized by functionality -- Nx provides caching, affected testing, targeting, and parallel execution for efficiency -- Use `npx nx show projects` to list all available packages -- Target specific packages: `npx nx run @tanstack/react-router:test:unit` -- Target multiple packages: `npx nx run-many --target=test:eslint --projects=@tanstack/history,@tanstack/router-core` -- Run affected tests only: `npx nx affected --target=test:unit` -- Exclude patterns: `npx 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 Vitest testing within packages:** - - Navigate first: `cd packages/react-router` - - Specific files: `npx vitest run tests/link.test.tsx tests/Scripts.test.tsx` - - Test patterns: `npx vitest run tests/ClientOnly.test.tsx -t "should render fallback"` - - Name patterns: `npx vitest run -t "navigation"` (all tests with "navigation" in name) - - Exclude patterns: `npx vitest run --exclude="**/*link*" tests/` - - List tests: `npx vitest list tests/link.test.tsx` or `npx vitest list` (all) - - Through nx: `npx nx run @tanstack/react-router:test:unit -- tests/ClientOnly.test.tsx` -- **Available test targets per package:** `test:unit`, `test:types`, `test:eslint`, `test:build`, `test:perf`, `build` -- **Testing strategy:** Package level (nx) → File level (vitest) → Test level (-t flag) → Pattern level (exclude) +## Performance and final bundle pass -## Testing instructions - -- **Critical**: Always run unit and type tests during development - do not proceed if they fail -- **Test types:** `pnpm test:unit`, `pnpm test:types`, `pnpm test:eslint`, `pnpm test:e2e`, `pnpm test:build` -- **Full CI suite:** `pnpm test:ci` -- **Fix formatting:** `pnpm format` -- **Efficient targeted testing workflow:** - 1. **Affected only:** `npx nx affected --target=test:unit` (compares to main branch) - 2. **Specific packages:** `npx nx run @tanstack/react-router:test:unit` - 3. **Specific files:** `cd packages/react-router && npx vitest run tests/link.test.tsx` - 4. **Specific patterns:** `npx vitest run tests/link.test.tsx -t "preloading"` -- **Pro tips:** - - Use `npx vitest list` to explore available tests before running - - Use `-t "pattern"` to focus on specific functionality during development - - Use `--exclude` patterns to skip unrelated tests - - Combine nx package targeting with vitest file targeting for maximum precision -- **Example workflow:** `npx nx run @tanstack/react-router:test:unit` → `cd packages/react-router && npx vitest run tests/link.test.tsx` → `npx vitest run tests/link.test.tsx -t "preloading"` - -## PR instructions - -- Always run `pnpm test:eslint`, `pnpm test:types`, and `pnpm test:unit` before committing -- Test changes in relevant example apps: `cd examples/react/basic && pnpm dev` -- Update corresponding documentation in `docs/` directory when adding features -- Add or update tests for any code changes -- Use internal docs links relative to `docs/` folder (e.g., `./guide/data-loading`) - -## Package structure - -**Core packages:** - -- `packages/router-core/` - Framework-agnostic core router logic -- `packages/react-router/`, `packages/solid-router/` - React/Solid bindings and components -- `packages/history/` - Browser history management - -**Tooling:** - -- `packages/router-cli/` - CLI tools for code generation -- `packages/router-generator/` - Route generation utilities -- `packages/router-plugin/` - Universal bundler plugins (Vite, Webpack, ESBuild, Rspack) -- `packages/virtual-file-routes/` - Virtual file routing system - -**Developer experience:** - -- `packages/router-devtools/`, `packages/*-router-devtools/` - Development tools -- `packages/eslint-plugin-router/` - ESLint rules for router - -**Validation adapters:** - -- `packages/zod-adapter/`, `packages/valibot-adapter/`, `packages/arktype-adapter/` - -**Start framework:** - -- `packages/*-start/`, `packages/start-*/` - Full-stack framework packages - -**Examples & testing:** - -- `examples/react/`, `examples/solid/` - Example applications (test changes here) -- `e2e/` - End-to-end tests (requires Playwright) -- `docs/router/`, `docs/start/` - Documentation with React/Solid subdirectories - -**Dependencies:** Uses workspace protocol (`workspace:*`) - core → framework → start packages - -## Common development tasks - -**Adding new routes:** - -- Use file-based routing in `src/routes/` directories -- Or use code-based routing with route definitions -- Run route generation with CLI tools - -**Testing changes:** - -- Build packages: `pnpm build` or `pnpm dev` (watch mode) -- Run example apps to test functionality -- Use devtools for debugging router state - -**Documentation updates:** - -- Update relevant docs in `docs/` directory -- Ensure examples reflect documentation changes -- Test documentation links and references -- Use relative links to `docs/` folder format - -## Framework-specific notes - -**React:** - -- Uses React Router components and hooks -- Supports React Server Components (RSC) -- Examples include React Query integration -- Package: `@tanstack/react-router` - -**Solid:** - -- Uses Solid Router components and primitives -- Supports Solid Start for full-stack applications -- Examples include Solid Query integration -- Package: `@tanstack/solid-router` - -## Environment requirements - -- **Node.js** - Required for development -- **pnpm** - Package manager (required for workspace features) -- **Playwright** - Required for e2e tests (`pnpm exec playwright install`) - -## Key architecture patterns - -- **Type Safety**: Extensive TypeScript for type-safe routing -- **Framework Agnostic**: Core logic separated from framework bindings -- **Plugin Architecture**: Universal bundler plugins using unplugin -- **File-based Routing**: Support for both code-based and file-based routing -- **Search Params**: First-class support for type-safe search parameters - -## Development workflow - -1. **Setup**: `pnpm install` and `pnpm exec playwright install` -2. **Build**: `pnpm build:all` or `pnpm dev` for watch mode -3. **Test**: Make changes and run relevant tests (use nx for targeted testing) -4. **Examples**: Navigate to examples and run `pnpm dev` to test changes -5. **Quality**: Run `pnpm test:eslint`, `pnpm test:types`, `pnpm test:unit` before committing - -## References - -- **Documentation**: https://tanstack.com/router -- **GitHub**: https://github.com/TanStack/router -- **Discord Community**: https://discord.com/invite/WrRKjPJ +- For runtime/memory changes, compare identical baseline/candidate workloads using the relevant [benchmark guide](benchmarks/AGENTS.md): client navigation, Start SSR, or memory. Add coverage for unmeasured mechanisms. +- **Last phase for every change affecting emitted client JavaScript**, including core/build transforms: complete the full [bundle-size-optimization skill](.agents/skills/bundle-size-optimization/SKILL.md) after correctness and performance validation. The full workflow is mandatory. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c28d01241b..4b6e808af1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,30 +1,95 @@ -# Contributing +# Contributing to TanStack Router -- Clone the repo - - `gh repo clone TanStack/router` -- Ensure `node` is installed - - https://nodejs.org/en/ -- Ensure `pnpm` is installed - - https://pnpm.io/installation - - Why? We use `pnpm` to manage workspace dependencies. It's easily the best monorepo/workspace experience available as of when this was written. -- Install dependencies - - `pnpm install` - - This installs dependencies for all of the packages in the monorepo, even examples! - - Dependencies inside of the packages and examples are automatically linked together as local/dynamic dependencies. -- Install test dependencies - - `pnpm exec playwright install` (required for e2e tests) -- Run the build or dev watcher - - `pnpm build:all` (build all packages) or - - `pnpm build` (cached build with [nx affected](https://nx.dev/nx-api/nx/documents/affected)) or - - `pnpm dev` -- Navigate to an example - - `cd examples/react/basic` -- Run the example - - `pnpm dev` -- Make changes to the code - - If you ran `pnpm dev` the dev watcher will automatically rebuild the code that has changed -- Editing the docs locally and previewing the changes - - The documentations for all the TanStack projects are hosted on [tanstack.com](https://tanstack.com), which is a TanStack Start application (https://github.com/TanStack/tanstack.com). You need to run this app locally to preview your changes in the `TanStack/router` docs. +TanStack Router is a community project. Contributions to both TanStack Router and TanStack Start are welcome. + +## Setup + +1. Clone the repository: + + ```sh + gh repo clone TanStack/router + ``` + +2. Install [Node.js](https://nodejs.org/en/) and [pnpm](https://pnpm.io/installation). This repository requires pnpm `11.x.x` or newer. +3. Install dependencies: + + ```sh + pnpm install + ``` + + This installs dependencies for the entire monorepo, including examples. Workspace dependencies are linked automatically. + +4. Install the Playwright browsers if you will run end-to-end tests: + + ```sh + pnpm exec playwright install + ``` + +5. Create a branch for your changes: + + ```sh + git checkout -b my-new-branch + ``` + +## Before you start + +- Search the [open and closed issues](https://github.com/TanStack/router/issues?q=is%3Aissue) before reporting a bug. If it has not already been reported, use the [bug report template](https://github.com/TanStack/router/issues/new?template=bug_report.yml). +- Search the [open and closed pull requests](https://github.com/TanStack/router/pulls?q=is%3Apr) before starting work to avoid duplicating an existing contribution. +- Pull requests that require API changes must first be proposed as an issue and receive maintainer sign-off before implementation begins. + +## Pull request guidelines + +Every pull request must follow the [TanStack Router pull request template](.github/pull_request_template.md). Complete its description and checklist without removing or bypassing the required sections. + +- Keep each pull request focused on one change or topic. Pull requests that combine unrelated changes will be closed with a request to split them into separately reviewable contributions. +- Write a concise description that clearly explains what changed and why. Follow the sections in the pull request template; a long, unstructured description makes a contribution harder to review. +- Every change that affects a published package must include a changeset. Create it with `pnpm changeset`; documentation, CI, examples, and development-only changes do not require one. + +## Development + +- `pnpm build:all` builds all packages. +- `pnpm build` runs the cached Nx build for affected packages. +- `pnpm dev` builds the packages and starts the development watcher. + +To run an example application, move into its directory and start its development server. For example: + +```sh +cd examples/react/basic +pnpm dev +``` + +## Testing and linting + +Run the checks relevant to your changes while developing: + +- `pnpm test:eslint` checks linting for affected packages. +- `pnpm test:types` checks types for affected packages. +- `pnpm test:unit` runs unit tests for affected packages. +- `pnpm test:build` checks builds for affected packages. +- `pnpm test:e2e` runs end-to-end tests and requires the Playwright browsers. + +Before opening a pull request, run at least: + +```sh +pnpm test:eslint +pnpm test:types +pnpm test:unit +``` + +To run the full CI test suite, use `pnpm test:ci`. For faster feedback, use an Nx target for a specific package or pass a test file or test name after `--`. For example: + +```sh +pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx +pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx -t "preloading" +``` + +Add appropriate unit tests for isolated behavior and end-to-end tests for browser or application workflows. Test relevant example applications when the change affects them. + +## Documentation + +Update the relevant documentation for user-facing changes. Documentation lives in the `docs/` directory, with separate sections for Router and Start. Use relative links within the `docs/` directory, such as `./guide/data-loading`. + +The documentation sites are hosted on [tanstack.com](https://tanstack.com), which is a [TanStack Start application](https://github.com/TanStack/tanstack.com). To preview documentation changes locally, clone both repositories as siblings: > [!NOTE] > The website fetches the doc pages from GitHub in production, and searches for them at `../router/docs` in development. Your local clone of `TanStack/router` needs to be in the same directory as the local clone of `TanStack/tanstack.com`. @@ -53,7 +118,7 @@ git clone git@github.com:TanStack/tanstack.com.git --depth=1 --single-branch --b > [!NOTE] > Your `tanstack` directory should look like this: > -> ``` +> ```text > tanstack/ > | > +-- router/ (<-- this directory cannot be called anything else!) @@ -75,6 +140,21 @@ pnpm dev > [!WARNING] > You will need to update the `docs/(router or start)config.json` file (in `TanStack/router`) if you add a new documentation page! -You can see the whole process in the screen capture below: +## AI-assisted contributions -https://github.com/fulopkovacs/form/assets/43729152/9d35a3c3-8153-4e74-9cb2-af275f7a269b + + +AI tools can be useful for exploring the codebase, drafting changes, and writing tests. They do not replace the contributor's responsibility for the result. + +1. **Keep the contribution in your own voice**. Review and rewrite generated code comments, issue reports, and pull request descriptions so they reflect what you actually mean. +2. **Keep ownership of technical decisions**. Understand every change, verify its behavior with the appropriate tests and documentation, and be ready to explain it during review. +3. **Do not paste LLM output verbatim into the codebase or a contribution**. Treat generated text and code as a draft: check its claims, adapt it to the repository, and remove anything you cannot justify. Issues or pull requests that appear to contain unreviewed LLM output may be closed without further review. +4. **Do not mass-submit unrelated or low-quality AI-generated pull requests**. We treat that behavior as spam and may close the pull requests, block the contributor, and report the GitHub account. + +AI-assisted contributions follow the same standards for correctness, testing, documentation, and review as every other contribution. diff --git a/README.md b/README.md index 774a2b096d..736715b12a 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,20 @@ - + + + + TanStack Router + ## TanStack Router @@ -23,10 +33,20 @@ A modern router designed for type safety, data‑driven navigation, and seamless - + + + + TanStack Start + ## TanStack Start @@ -69,22 +89,22 @@ A full‑stack framework built on Router, designed for server rendering, streami - -
- - - - - CodeRabbit - - + + + + + + CodeRabbit + + + - - - - Cloudflare - + + + + Cloudflare + diff --git a/_artifacts/domain_map.yaml b/_artifacts/domain_map.yaml new file mode 100644 index 0000000000..0b2672f0c6 --- /dev/null +++ b/_artifacts/domain_map.yaml @@ -0,0 +1,1093 @@ +# domain_map.yaml +# Generated by skill-domain-discovery +# Library: TanStack Router +# Version: 1.166.2 +# Date: 2026-03-07 +# Status: reviewed + +library: + name: '@tanstack/react-router' + version: '1.166.2' + repository: 'https://github.com/TanStack/router' + description: >- + Type-safe router for React and Solid with built-in SWR caching, + JSON-first search params, file-based route generation, and + end-to-end type inference. + primary_framework: 'React' + +domains: + - name: 'Defining Routes' + slug: 'defining-routes' + description: >- + Setting up route trees via file-based, code-based, or virtual + file routes, configuring the router instance, and registering + types for end-to-end inference. + + - name: 'Navigating' + slug: 'navigating' + description: >- + Moving between routes using Links, imperative navigation, + redirects, preloading, active states, and navigation blocking. + + - name: 'Managing URL State' + slug: 'managing-url-state' + description: >- + Reading and writing search params and path params with + validation, serialization, middlewares, and type-safe adapters. + + - name: 'Loading Data' + slug: 'loading-data' + description: >- + Fetching data via route loaders, coordinating external caches, + managing SWR caching, deferred loading, and error/pending states. + + - name: 'Protecting Routes' + slug: 'protecting-routes' + description: >- + Authentication guards, authorization checks, RBAC patterns, + and redirect-based access control via beforeLoad. + + - name: 'Rendering and Layout' + slug: 'rendering-and-layout' + description: >- + Outlets, nested layouts, pathless layouts, code splitting, + error boundaries, not-found handling, route masking, scroll + restoration, and document head management. + + - name: 'Type Safety' + slug: 'type-safety' + description: >- + Router type registration, inference patterns, narrowing with + from, TypeScript performance, and avoiding unnecessary type + annotations. + + - name: 'Server-Side Rendering' + slug: 'server-side-rendering' + description: >- + Non-streaming and streaming SSR setup, hydration, data + serialization, and isomorphic router creation. + +skills: + # ── Defining Routes ────────────────────────────────────────────── + - name: 'Route Setup' + slug: 'route-setup' + domain: 'defining-routes' + description: >- + Set up a TanStack Router project with file-based, code-based, + or virtual file routes, configure the router instance, and + register types. + type: core + packages: + - '@tanstack/react-router' + - '@tanstack/router-core' + - '@tanstack/router-plugin' + - '@tanstack/router-generator' + - '@tanstack/router-cli' + - '@tanstack/virtual-file-routes' + - '@tanstack/eslint-plugin-router' + covers: + - createRouter + - createRootRoute + - createRootRouteWithContext + - createRoute + - createFileRoute + - createLazyFileRoute + - addChildren + - routeTree.gen.ts + - declare module Register + - TanStackRouter bundler plugin + - tsr.config.json + - virtual file routes API + - file naming conventions + - route matching and sorting + tasks: + - 'Scaffold a new TanStack Router project' + - 'Configure file-based routing with Vite plugin' + - 'Set up code-based route tree manually' + - 'Configure virtual file routes for custom conventions' + - 'Register router types via module declaration' + - 'Set up ESLint plugin for route property ordering' + reference_candidates: + - topic: 'file naming conventions' + reason: '>10 distinct conventions (dot separator, $ token, _ prefix/suffix, () groups, [] escaping, index, route.tsx, __root)' + failure_modes: + - mistake: 'Missing router type registration' + mechanism: >- + Without declare module Register, top-level exports like + Link, useNavigate, useParams have no type safety. Code + compiles but all route paths are untyped strings. + wrong_pattern: | + const router = createRouter({ routeTree }) + // no declare module — Link to="" has no autocomplete + correct_pattern: | + const router = createRouter({ routeTree }) + declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } + } + source: 'docs/router/guide/creating-a-router.md' + priority: CRITICAL + status: active + skills: ['route-setup', 'type-safety'] + + - mistake: 'Not committing routeTree.gen.ts' + mechanism: >- + routeTree.gen.ts is runtime code, not a build artifact. + Without it in version control, other developers cannot + build or run the project. + source: 'docs/router/faq.md' + priority: HIGH + status: active + + - mistake: 'Wrong route property order breaks type inference' + mechanism: >- + Properties like beforeLoad must come before loader in + createRoute/createFileRoute calls. Incorrect order causes + context types to not flow into loader. + wrong_pattern: | + createFileRoute('/posts')({ + loader: ({ context }) => + context.queryClient.query({ ...postsQuery, staleTime: 'static' }), + beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), + }) + correct_pattern: | + createFileRoute('/posts')({ + beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), + loader: ({ context }) => + context.queryClient.query({ ...postsQuery, staleTime: 'static' }), + }) + source: 'docs/router/eslint/create-route-property-order.md' + priority: HIGH + status: active + + - mistake: 'Placing TanStackRouter plugin after framework plugin' + mechanism: >- + The TanStackRouter Vite plugin must be listed before the + React/Solid plugin in the Vite config. Wrong order causes + route generation to fail silently. + wrong_pattern: | + plugins: [react(), TanStackRouterVite()] + correct_pattern: | + plugins: [TanStackRouterVite(), react()] + source: 'docs/router/installation/with-vite.md' + priority: HIGH + status: active + + - mistake: 'Using getParentRoute incorrectly in code-based routing' + mechanism: >- + Every non-root route must reference its correct parent via + getParentRoute. Wrong parent breaks type inference for + context, search params, and path params from ancestors. + source: 'docs/router/decisions-on-dx.md' + priority: HIGH + status: active + + compositions: + - library: '@tanstack/eslint-plugin-router' + skill: null + + # ── Navigating ─────────────────────────────────────────────────── + - name: 'Navigation' + slug: 'navigation' + domain: 'navigating' + description: >- + Navigate between routes using Link, useNavigate, Navigate + component, and router.navigate. Configure preloading, active + link states, and navigation blocking. + type: core + packages: + - '@tanstack/react-router' + - '@tanstack/router-core' + covers: + - Link component + - useNavigate hook + - Navigate component + - router.navigate + - ToOptions / NavigateOptions / LinkOptions + - from / to relative navigation + - activeOptions / activeProps / inactiveProps + - preload (intent / viewport / render) + - preloadDelay / defaultPreloadDelay + - useBlocker hook + - Block component + - createLink (custom link components) + - linkOptions helper + - MatchRoute component + - scroll restoration + tasks: + - 'Create type-safe links between routes' + - 'Navigate programmatically after an action' + - 'Set up link preloading on hover intent' + - 'Style active and inactive links' + - 'Block navigation for unsaved changes' + - 'Create custom link components with createLink' + - 'Build reusable navigation options with linkOptions' + - 'Configure scroll restoration' + failure_modes: + - mistake: 'Interpolating params into the to string' + mechanism: >- + Agents build paths like to={`/posts/${id}`} instead of + using the params option. Breaks type safety and param + encoding. + wrong_pattern: | + Post + correct_pattern: | + Post + source: 'docs/router/guide/navigation.md' + priority: CRITICAL + status: active + skills: ['navigation', 'type-safety'] + + - mistake: 'Using useNavigate instead of Link for user-clickable elements' + mechanism: >- + Link renders a real with href, supports cmd/ctrl+click + and preloading. useNavigate produces no accessible element. + source: 'docs/router/guide/navigation.md' + priority: MEDIUM + status: active + + - mistake: 'Not providing from for relative navigation' + mechanism: >- + Without from, the router assumes navigation from root. + Only absolute paths are autocompleted. Relative paths + like ".." resolve from root instead of current route. + wrong_pattern: | + Back + correct_pattern: | + Back + source: 'docs/router/guide/navigation.md' + priority: HIGH + status: active + + - mistake: 'Using search as object instead of function loses existing params' + mechanism: >- + search={{ page: 2 }} replaces all search params. + Must use function form to preserve existing params. + wrong_pattern: | + Page 2 + correct_pattern: | + ({ ...prev, page: 2 })}>Page 2 + source: 'docs/router/how-to/navigate-with-search-params.md' + priority: HIGH + status: active + skills: ['navigation', 'search-params'] + + # ── Managing URL State ─────────────────────────────────────────── + - name: 'Search Params' + slug: 'search-params' + domain: 'managing-url-state' + description: >- + Validate, read, write, and transform search params with + schema validation, adapters, middlewares, and custom + serialization. + type: core + packages: + - '@tanstack/react-router' + - '@tanstack/router-core' + - '@tanstack/zod-adapter' + - '@tanstack/valibot-adapter' + - '@tanstack/arktype-adapter' + covers: + - validateSearch + - useSearch hook + - Route.useSearch + - getRouteApi().useSearch + - search middlewares + - retainSearchParams + - stripSearchParams + - custom serialization (parseSearch / stringifySearch) + - zod adapter / valibot adapter / arktype adapter + - search param inheritance from parent routes + - structural sharing for search params + tasks: + - 'Add validated search params to a route' + - 'Read search params in components' + - 'Update search params while preserving others' + - 'Share search params across parent and child routes' + - 'Set up search param middlewares for retention/stripping' + - 'Configure custom search param serialization' + - 'Handle arrays, objects, and dates in search params' + subsystems: + - name: 'Zod adapter' + package: '@tanstack/zod-adapter' + config_surface: 'zodValidator, fallback() wrapper for .catch/.default type correctness' + - name: 'Valibot adapter' + package: '@tanstack/valibot-adapter' + config_surface: 'Standard Schema compliant, requires valibot 1.0' + - name: 'ArkType adapter' + package: '@tanstack/arktype-adapter' + config_surface: 'Standard Schema compliant, requires arktype 2.0-rc, pass directly to validateSearch' + reference_candidates: + - topic: 'search param validation patterns' + reason: '>10 distinct patterns (basic, optional, arrays, objects, dates, discriminated unions, transforms, conditional, cross-route inheritance, middleware chaining)' + failure_modes: + - mistake: 'Using zod .catch() instead of adapter fallback()' + mechanism: >- + Zod .catch() makes the output type unknown, losing type + safety. The @tanstack/zod-adapter fallback() preserves + the correct inferred type. + wrong_pattern: | + z.object({ page: z.number().catch(1) }) + correct_pattern: | + import { fallback } from '@tanstack/zod-adapter' + z.object({ page: fallback(z.number(), 1) }) + source: 'docs/router/guide/search-params.md' + priority: HIGH + status: active + + - mistake: 'Returning entire search object from loaderDeps' + mechanism: >- + loaderDeps: ({ search }) => search causes loader to + re-run on ANY search param change, not just relevant ones. + Deep equality comparison fires on every unrelated change. + wrong_pattern: | + loaderDeps: ({ search }) => search + correct_pattern: | + loaderDeps: ({ search }) => ({ page: search.page }) + source: 'docs/router/guide/data-loading.md' + priority: HIGH + status: active + skills: ['search-params', 'data-loading'] + + - mistake: 'Passing Date objects in search params' + mechanism: >- + Date objects serialize to [object Object] in URLs. + Must convert to ISO strings for correct serialization. + wrong_pattern: | + + correct_pattern: | + + source: 'docs/router/how-to/arrays-objects-dates-search-params.md' + priority: HIGH + status: active + + - mistake: 'Parent route missing validateSearch blocks inheritance' + mechanism: >- + Child routes cannot access shared search params unless + the parent route defines validateSearch. Without it, + the types and runtime values are not available. + source: 'docs/router/how-to/share-search-params-across-routes.md' + priority: MEDIUM + status: active + + - name: 'Path Params' + slug: 'path-params' + domain: 'managing-url-state' + description: >- + Define and consume dynamic path segments, splat routes, + optional params, and prefix/suffix patterns. + type: core + packages: + - '@tanstack/react-router' + - '@tanstack/router-core' + covers: + - '$paramName dynamic segments' + - '$ splat / _splat' + - '{-$paramName} optional params' + - '{$paramName} prefix/suffix patterns' + - useParams hook + - params.parse / params.stringify + - pathParamsAllowedCharacters + tasks: + - 'Define routes with dynamic path parameters' + - 'Use splat routes for catch-all matching' + - 'Set up optional path parameters for i18n' + - 'Navigate with type-safe path params' + failure_modes: + - mistake: 'Interpolating path params into to string' + mechanism: >- + Same as navigation failure mode — agents build template + literal paths instead of using params option. + source: 'docs/router/guide/navigation.md' + priority: CRITICAL + status: active + skills: ['path-params', 'navigation'] + + - mistake: 'Using * for splat routes instead of $' + mechanism: >- + TanStack Router uses $ for splat routes, not * like some + other routers. The captured value is under _splat key, + not * (though * works in v1 for backwards compat, removed in v2). + source: 'docs/router/routing/routing-concepts.md' + priority: MEDIUM + status: 'fixed-but-legacy-risk' + version_context: '* works in v1 for compat but will be removed in v2' + + - mistake: 'Using curly braces for basic dynamic segments' + mechanism: >- + Basic dynamic segments use $postId (no braces). Curly + braces are only for prefix/suffix patterns like {$postId}.txt + or optional params {-$locale}. + source: 'docs/router/guide/path-params.md' + priority: MEDIUM + status: active + + # ── Loading Data ───────────────────────────────────────────────── + - name: 'Data Loading' + slug: 'data-loading' + domain: 'loading-data' + description: >- + Load data via route loaders with built-in SWR caching, + configure staleTime/gcTime, use loaderDeps for cache keys, + handle pending and error states, and inject dependencies + via router context. + type: core + packages: + - '@tanstack/react-router' + - '@tanstack/router-core' + covers: + - loader option + - loaderDeps + - staleTime / gcTime / defaultPreloadStaleTime + - pendingComponent / pendingMs / pendingMinMs + - errorComponent / onError / onCatch + - beforeLoad + - router context / createRootRouteWithContext + - router.invalidate + - Await component + - deferred data loading + tasks: + - 'Add a data loader to a route' + - 'Configure cache timing (staleTime, gcTime)' + - 'Set up loader dependencies for search-param-driven data' + - 'Show pending UI during slow loads' + - 'Handle loader errors with error boundaries' + - 'Inject dependencies via router context' + - 'Defer non-critical data with unawaited promises' + - 'Invalidate cached data after mutations' + failure_modes: + - mistake: 'Assuming loaders only run on the server' + mechanism: >- + TanStack Router is client-first. Loaders run on the client + by default (and also on the server if using TanStack Start). + Agents trained on Remix/Next assume loaders are server-only + and put server-only code (DB queries, fs access) in them. + source: 'maintainer interview' + priority: CRITICAL + status: active + skills: ['data-loading', 'ssr'] + + - mistake: 'Not understanding staleTime default is 0' + mechanism: >- + Default staleTime is 0, meaning data is always considered + stale and reloads in background on every route re-match. + Agents may not set staleTime, causing excessive refetching. + source: 'docs/router/guide/data-loading.md' + priority: MEDIUM + status: active + + - mistake: 'Using reset() instead of router.invalidate() in error components' + mechanism: >- + For loader errors, reset() only resets the error boundary + but does not re-run the loader. Must use router.invalidate() + to coordinate both reload and boundary reset. + wrong_pattern: | + function PostErrorComponent({ error, reset }) { + return + } + correct_pattern: | + function PostErrorComponent({ error, reset }) { + const router = useRouter() + return + } + source: 'docs/router/guide/data-loading.md' + priority: HIGH + status: active + + - mistake: 'Double parentheses missing on createRootRouteWithContext' + mechanism: >- + createRootRouteWithContext() is a factory — it returns + a function. Must call it twice: createRootRouteWithContext()(routeOptions). + Missing second call is a common error. + wrong_pattern: | + const rootRoute = createRootRouteWithContext<{ auth: AuthState }>({ + component: RootComponent, + }) + correct_pattern: | + const rootRoute = createRootRouteWithContext<{ auth: AuthState }>()({ + component: RootComponent, + }) + source: 'docs/router/guide/data-loading.md' + priority: HIGH + status: active + + - mistake: 'Using React hooks in beforeLoad or loader' + mechanism: >- + beforeLoad and loader are not React components — hooks + cannot be called in them. Must extract hook state in a + wrapper component and pass via router context. + source: 'docs/router/guide/router-context.md' + priority: HIGH + status: active + + compositions: + - library: '@tanstack/react-query' + skill: 'external-data-loading' + + - name: 'External Data Loading' + slug: 'external-data-loading' + domain: 'loading-data' + description: >- + Integrate TanStack Query (or other external caches) with + Router for coordinated data loading, SSR dehydration/hydration, + and streaming. + type: composition + packages: + - '@tanstack/react-router' + - '@tanstack/react-router-ssr-query' + covers: + - External cache coordination pattern + - "queryClient.query with staleTime: 'static' in loader" + - useSuspenseQuery in components + - setupRouterSsrQueryIntegration + - defaultPreloadStaleTime + - dehydrate / hydrate router options + - QueryClient per-request isolation + - Wrap router option for providers + tasks: + - 'Set up TanStack Query with Router' + - 'Preload query data in route loaders' + - 'Configure SSR dehydration/hydration with Query' + - 'Stream query data during SSR' + failure_modes: + - mistake: 'Not setting defaultPreloadStaleTime to 0 with external caches' + mechanism: >- + Router's built-in preload cache (30s default) prevents + external library from controlling freshness. Set + defaultPreloadStaleTime: 0 to let Query manage caching. + wrong_pattern: | + createRouter({ routeTree }) + correct_pattern: | + createRouter({ routeTree, defaultPreloadStaleTime: 0 }) + source: 'docs/router/guide/external-data-loading.md' + priority: HIGH + status: active + + - mistake: 'Creating QueryClient outside createRouter for SSR' + mechanism: >- + For SSR, QueryClient must be created inside createRouter + to ensure per-request isolation. A shared singleton leaks + data between requests. + wrong_pattern: | + const queryClient = new QueryClient() + const router = createRouter({ routeTree, context: { queryClient } }) + correct_pattern: | + function createAppRouter() { + const queryClient = new QueryClient() + return createRouter({ routeTree, context: { queryClient } }) + } + source: 'docs/router/guide/external-data-loading.md' + priority: HIGH + status: active + + - mistake: 'Awaiting a fire-and-forget query 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. + source: 'docs/router/integrations/query.md' + priority: MEDIUM + status: active + + # ── Protecting Routes ──────────────────────────────────────────── + - name: 'Auth and Guards' + slug: 'auth-and-guards' + domain: 'protecting-routes' + description: >- + Protect routes with authentication checks, authorization + guards, and RBAC patterns using beforeLoad redirects and + layout routes. + type: core + packages: + - '@tanstack/react-router' + - '@tanstack/router-core' + covers: + - beforeLoad for auth checks + - redirect() / throw redirect() + - isRedirect helper + - Authenticated layout routes (_authenticated) + - Non-redirect auth (inline login) + - RBAC with roles and permissions + - Auth provider integration (Auth0, Clerk, Supabase) + - Router context for auth state + tasks: + - 'Protect routes with authentication checks' + - 'Redirect unauthenticated users to login' + - 'Implement role-based access control' + - 'Integrate third-party auth providers' + - 'Pass auth state through router context' + failure_modes: + - mistake: 'Auth check in component instead of beforeLoad' + mechanism: >- + Component-level auth checks cause protected content to + flash before redirect. beforeLoad runs before any + component rendering and prevents the flash entirely. + wrong_pattern: | + component: () => { + const auth = useAuth() + if (!auth.isAuthenticated) return + return + } + correct_pattern: | + beforeLoad: ({ context }) => { + if (!context.auth.isAuthenticated) { + throw redirect({ to: '/login' }) + } + } + source: 'docs/router/how-to/setup-authentication.md' + priority: HIGH + status: active + + - mistake: 'Not re-throwing redirects in try/catch' + mechanism: >- + redirect() works by throwing. If beforeLoad has a try/catch + for error handling, the redirect gets swallowed unless + re-thrown via isRedirect() check. + wrong_pattern: | + beforeLoad: async ({ context }) => { + try { + await validateSession(context.auth) + } catch (e) { + // swallows redirect! + console.error(e) + } + } + correct_pattern: | + beforeLoad: async ({ context }) => { + try { + await validateSession(context.auth) + } catch (e) { + if (isRedirect(e)) throw e + console.error(e) + } + } + source: 'docs/router/guide/authenticated-routes.md' + priority: HIGH + status: active + + - mistake: 'Trying to conditionally render root route component' + mechanism: >- + Root route is always rendered regardless of auth state. + Use a pathless layout route (_authenticated) with + beforeLoad for conditional rendering. + source: 'docs/router/faq.md' + priority: MEDIUM + status: active + + # ── Rendering and Layout ───────────────────────────────────────── + - name: 'Code Splitting' + slug: 'code-splitting' + domain: 'rendering-and-layout' + description: >- + Split route code into lazy-loaded chunks using automatic + code splitting, .lazy.tsx files, or code-based lazy loading. + type: core + packages: + - '@tanstack/react-router' + - '@tanstack/router-plugin' + covers: + - autoCodeSplitting plugin option + - .lazy.tsx file convention + - createLazyFileRoute + - createLazyRoute + - lazyRouteComponent + - getRouteApi for code-split components + - codeSplitGroupings per-route override + - splitBehavior programmatic config + - Critical vs non-critical route properties + tasks: + - 'Enable automatic code splitting' + - 'Manually split a route with .lazy.tsx' + - 'Access typed hooks from code-split components' + - 'Customize which properties are split per route' + failure_modes: + - mistake: 'Exporting route property functions prevents code splitting' + mechanism: >- + Exported functions from route files are included in the + main bundle even with auto code splitting. Component + functions must NOT be exported. + wrong_pattern: | + export function PostsComponent() { return
Posts
} + correct_pattern: | + function PostsComponent() { return
Posts
} + source: 'docs/router/guide/automatic-code-splitting.md' + priority: HIGH + status: active + + - mistake: 'Trying to code-split the root route' + mechanism: >- + __root.tsx does not support code splitting — it is always + rendered regardless of current route. + source: 'docs/router/guide/code-splitting.md' + priority: MEDIUM + status: active + + - mistake: 'Splitting the loader adds double async cost' + mechanism: >- + Loader is already async. Splitting it requires fetching + the chunk AND then executing the loader, adding latency. + Loaders should stay in the main bundle unless there is + a specific reason to split them. + source: 'docs/router/guide/code-splitting.md' + priority: MEDIUM + status: active + + - mistake: 'Importing Route in code-split files for typed hooks' + mechanism: >- + Importing the Route object in a lazy-loaded file pulls + the route config into the lazy chunk, defeating code + splitting. Use getRouteApi('/path') instead. + wrong_pattern: | + import { Route } from './posts.tsx' + const data = Route.useLoaderData() + correct_pattern: | + import { getRouteApi } from '@tanstack/react-router' + const route = getRouteApi('/posts') + const data = route.useLoaderData() + source: 'docs/router/guide/code-splitting.md' + priority: HIGH + status: active + + - name: 'Not Found and Errors' + slug: 'not-found-and-errors' + domain: 'rendering-and-layout' + description: >- + Handle not-found routes, missing resources, and route-level + errors with notFound(), notFoundComponent, errorComponent, + and CatchBoundary. + type: core + packages: + - '@tanstack/react-router' + - '@tanstack/router-core' + covers: + - notFound() function + - notFoundComponent + - defaultNotFoundComponent + - notFoundMode (fuzzy / root) + - errorComponent + - onError / onCatch + - CatchBoundary component + - NotFoundRoute (deprecated) + tasks: + - 'Add a 404 page for unmatched routes' + - 'Throw not-found for missing resources in loaders' + - 'Configure error boundaries per route' + - 'Target specific routes with notFound()' + failure_modes: + - mistake: 'Using deprecated NotFoundRoute' + mechanism: >- + NotFoundRoute is deprecated. When present, notFound() and + notFoundComponent will NOT work. Must remove NotFoundRoute + and use notFoundComponent instead. + source: 'docs/router/guide/not-found-errors.md' + priority: HIGH + status: 'fixed-but-legacy-risk' + version_context: 'NotFoundRoute deprecated, will be removed in next major' + + - mistake: 'Expecting useLoaderData to work in notFoundComponent' + mechanism: >- + When notFoundComponent renders, the route's loader may + not have completed. useLoaderData() may return undefined. + Use useParams, useSearch, or useRouteContext instead. + source: 'docs/router/guide/not-found-errors.md' + priority: MEDIUM + status: active + + - mistake: 'Leaf route cannot handle not-found errors' + mechanism: >- + Routes without children never render Outlet and therefore + cannot catch not-found errors. Only routes with children + (or the root route) can have notFoundComponent. + source: 'docs/router/guide/not-found-errors.md' + priority: MEDIUM + status: active + + - name: 'Route Masking' + slug: 'route-masking' + domain: 'rendering-and-layout' + description: >- + Mask the browser URL while navigating to a different internal + route, with configurable unmask behavior. + type: core + packages: + - '@tanstack/react-router' + - '@tanstack/router-core' + covers: + - mask option on Link / navigate + - createRouteMask + - routeMasks router option + - unmaskOnReload + - location.maskedLocation + - location.state.__tempLocation + tasks: + - 'Show a modal route with a clean URL' + - 'Configure declarative route masks' + - 'Control unmask behavior on page reload' + failure_modes: + - mistake: 'Expecting masked URLs to survive sharing' + mechanism: >- + Masking data is stored in browser history state. When a + URL is shared or opened in a new tab, masking data is + lost and the visible URL is used directly. + source: 'docs/router/guide/route-masking.md' + priority: MEDIUM + status: active + + # ── Type Safety ────────────────────────────────────────────────── + - name: 'Type Safety' + slug: 'type-safety' + domain: 'type-safety' + description: >- + Leverage TanStack Router's fully inferred type system. + Avoid unnecessary type annotations, narrow routes with from, + and optimize TypeScript performance. + type: core + packages: + - '@tanstack/react-router' + - '@tanstack/router-core' + covers: + - Full type inference philosophy + - Register module declaration + - from narrowing on hooks and Link + - strict false for shared components + - getRouteApi for code-split typed access + - addChildren with object syntax for TS perf + - LinkProps / ValidateLinkOptions type utilities + - as const satisfies pattern + tasks: + - 'Register router types for global type safety' + - 'Narrow route types with from parameter' + - 'Use getRouteApi in code-split components' + - 'Optimize TypeScript performance in large route trees' + - 'Build type-safe link option utilities' + failure_modes: + - mistake: 'Adding type annotations or casts to inferred values' + mechanism: >- + TanStack Router is fully type-safe with full inference. + Adding as Type, generic type parameters, satisfies, or + explicit type annotations is unnecessary and can mask + real type errors or break the inference chain. + wrong_pattern: | + const search = useSearch({ from: '/posts' }) as { page: number } + correct_pattern: | + const search = useSearch({ from: '/posts' }) + // search.page is already typed as number + source: 'maintainer interview' + priority: CRITICAL + status: active + + - mistake: 'Using un-narrowed LinkProps type' + mechanism: >- + LinkProps without generics is an extremely large union type. + Using it as a variable type causes severe TS performance + degradation. Use as const satisfies or narrow with generics. + wrong_pattern: | + const props: LinkProps = { to: '/posts' } + correct_pattern: | + const props = { to: '/posts' } as const satisfies LinkProps + source: 'docs/router/guide/type-safety.md' + priority: HIGH + status: active + + - mistake: 'Not narrowing Link/useNavigate with from' + mechanism: >- + Without from, search resolves to a union of ALL routes + search params. TypeScript check time grows linearly with + route count. Always provide from to narrow. + wrong_pattern: | + + correct_pattern: | + + source: 'docs/router/guide/type-safety.md' + priority: HIGH + status: active + + # ── Server-Side Rendering ──────────────────────────────────────── + - name: 'SSR' + slug: 'ssr' + domain: 'server-side-rendering' + description: >- + Set up server-side rendering with non-streaming or streaming + approaches, manage hydration, and handle document head. + type: core + packages: + - '@tanstack/react-router' + - '@tanstack/router-core' + covers: + - RouterClient / RouterServer + - renderRouterToString / renderRouterToStream + - createRequestHandler + - defaultRenderHandler / defaultStreamHandler + - HeadContent / Scripts components + - head route option (meta, links, styles, scripts) + - ScriptOnce component + - Automatic loader dehydration/hydration + - Memory history on server + - Data serialization (Date, Error, FormData, undefined) + tasks: + - 'Set up non-streaming SSR with Express' + - 'Set up streaming SSR' + - 'Configure document head management' + - 'Handle hydration mismatches' + failure_modes: + - mistake: 'Using browser APIs in loaders without environment check' + mechanism: >- + Loaders run on both client and server when using SSR. + Browser-only APIs (window, document, localStorage) will + throw on the server. + source: 'docs/router/guide/ssr.md' + priority: HIGH + status: active + skills: ['ssr', 'data-loading'] + + - mistake: 'Using hash fragments for server-rendered content' + mechanism: >- + Hash fragments are client-only — browsers never send them + to the server. Using hash for conditional rendering causes + hydration mismatches during SSR. + source: 'docs/router/guide/navigation.md' + priority: MEDIUM + status: active + + - mistake: 'Generating Next.js or Remix SSR patterns' + mechanism: >- + Agents trained on Next.js generate getServerSideProps, + App Router patterns, or server components. Agents trained + on Remix generate server-only loader exports. TanStack + Router has its own SSR API (RouterClient/RouterServer). + source: 'maintainer interview' + priority: CRITICAL + status: active + skills: ['ssr', 'route-setup', 'data-loading'] + + # ── Migration ──────────────────────────────────────────────────── + - name: 'Migrate from React Router' + slug: 'migrate-from-react-router' + domain: 'defining-routes' + description: >- + Step-by-step migration from React Router v7 to TanStack Router, + covering route definitions, navigation, search params, and + data loading. + type: lifecycle + packages: + - '@tanstack/react-router' + - '@tanstack/router-plugin' + covers: + - Migration checklist + - Route definition conversion + - Link / useNavigate API differences + - useSearchParams to validateSearch + useSearch + - useParams with from + - Outlet replacement + - Loader conversion + - Code splitting differences + tasks: + - 'Migrate routes from React Router to TanStack Router' + - 'Convert React Router Links and navigation' + - 'Replace useSearchParams with validated search params' + - 'Convert React Router loaders' + failure_modes: + - mistake: 'Leaving React Router imports alongside TanStack Router' + mechanism: >- + React Router and TanStack Router share similar API names + (Link, useNavigate, Outlet). Leftover React Router imports + cause context errors ("cannot use useNavigate outside of + context"). Uninstall react-router-dom to surface these. + source: 'docs/router/how-to/migrate-from-react-router.md' + priority: HIGH + status: active + + - mistake: 'Using React Router useSearchParams pattern' + mechanism: >- + React Router uses useSearchParams() returning URLSearchParams. + TanStack Router uses validateSearch schema + useSearch() + returning typed objects. Agents may generate the RR pattern. + wrong_pattern: | + const [searchParams, setSearchParams] = useSearchParams() + const page = Number(searchParams.get('page')) + correct_pattern: | + // In route definition: + validateSearch: z.object({ page: fallback(z.number(), 1) }) + // In component: + const { page } = Route.useSearch() + source: 'docs/router/installation/migrate-from-react-router.md' + priority: HIGH + status: active + +tensions: + - name: 'Type safety strictness vs rapid prototyping' + skills: ['type-safety', 'route-setup'] + description: >- + Full type inference requires proper setup (Register, correct + property order, getParentRoute). This upfront cost conflicts + with quick prototyping where developers want to skip setup. + implication: >- + Agents skip Register declaration or use type casts to silence + errors, producing code that compiles but has no type safety. + + - name: 'Client-first loaders vs SSR expectations' + skills: ['data-loading', 'ssr'] + description: >- + Loaders are client-first by design but agents assume they are + server-only (Remix/Next mental model). This tension means + browser APIs work in loaders by default but break under SSR. + implication: >- + Agents either put server-only code in client loaders or avoid + browser APIs unnecessarily, depending on which framework mental + model they default to. + + - name: 'Built-in SWR cache vs external cache coordination' + skills: ['data-loading', 'external-data-loading'] + description: >- + Router has built-in caching with staleTime/gcTime defaults. + When using an external cache like React Query, the built-in + cache must be bypassed (defaultPreloadStaleTime: 0) or it + conflicts with the external library's freshness management. + implication: >- + Agents use both caches simultaneously without disabling the + built-in one, causing stale data or double-fetching. + + - name: 'Code splitting granularity vs loader performance' + skills: ['code-splitting', 'data-loading'] + description: >- + Splitting more aggressively reduces initial bundle but splitting + the loader adds a network round-trip before data can be fetched. + The optimal split point differs per route. + implication: >- + Agents split everything including loaders, adding latency to + data loading without understanding the tradeoff. + +cross_references: + - from: 'route-setup' + to: 'type-safety' + reason: 'Register declaration and property order are prerequisites for type inference' + - from: 'navigation' + to: 'search-params' + reason: 'Link search prop and navigate search option directly interact with search param validation' + - from: 'data-loading' + to: 'search-params' + reason: 'loaderDeps consumes validated search params as cache keys' + - from: 'data-loading' + to: 'external-data-loading' + reason: 'Understanding built-in caching is prerequisite for coordinating with external caches' + - from: 'auth-and-guards' + to: 'data-loading' + reason: 'beforeLoad runs before loader — auth context flows into loader via route context' + - from: 'code-splitting' + to: 'data-loading' + reason: 'Loader splitting decisions affect data loading performance' + - from: 'ssr' + to: 'data-loading' + reason: 'SSR changes where loaders execute — must handle both environments' + - from: 'ssr' + to: 'external-data-loading' + reason: 'SSR dehydration/hydration requires special setup for Query integration' + - from: 'not-found-and-errors' + to: 'data-loading' + reason: 'notFound() thrown in loaders interacts with error boundaries and loader data availability' + - from: 'migrate-from-react-router' + to: 'route-setup' + reason: 'Migration requires understanding TanStack Router route setup to replace RR patterns' + +gaps: [] diff --git a/_artifacts/skill_spec.md b/_artifacts/skill_spec.md new file mode 100644 index 0000000000..7eb9554a42 --- /dev/null +++ b/_artifacts/skill_spec.md @@ -0,0 +1,193 @@ +# TanStack Router — Skill Spec + +TanStack Router is a type-safe router for React and Solid applications with built-in SWR caching, JSON-first search params, file-based route generation, and end-to-end type inference. It is client-first/isomorphic — loaders run on the client by default and additionally on the server when used with TanStack Start. + +## Domains + +| Domain | Description | Skills | +| --------------------- | ------------------------------------------------------------------- | --------------------------------------------------- | +| Defining Routes | Setting up route trees, configuring the router, registering types | route-setup, migrate-from-react-router | +| Navigating | Links, imperative navigation, preloading, blocking | navigation | +| Managing URL State | Search params and path params with validation and serialization | search-params, path-params | +| Loading Data | Route loaders, SWR caching, external cache coordination, context/DI | data-loading, external-data-loading | +| Protecting Routes | Auth guards, RBAC, beforeLoad redirects | auth-and-guards | +| Rendering and Layout | Code splitting, error/not-found handling, route masking | code-splitting, not-found-and-errors, route-masking | +| Type Safety | Inference patterns, narrowing, TS performance | type-safety | +| Server-Side Rendering | SSR setup, hydration, head management | ssr | + +## Skill Inventory + +| Skill | Type | Domain | What it covers | Failure modes | +| ------------------------- | ----------- | --------------------- | ------------------------------------------------------------------------------------ | ------------- | +| route-setup | core | defining-routes | createRouter, file/code/virtual routing, Register, plugin config, ESLint | 5 | +| navigation | core | navigating | Link, useNavigate, Navigate, preloading, blocking, active states, scroll restoration | 4 | +| search-params | core | managing-url-state | validateSearch, useSearch, middlewares, serialization, adapters | 4 | +| path-params | core | managing-url-state | $params, splats, optional params, prefix/suffix patterns | 3 | +| data-loading | core | loading-data | loader, loaderDeps, staleTime/gcTime, pending/error, context/DI, deferred | 5 | +| external-data-loading | composition | loading-data | TanStack Query integration, SSR dehydration/hydration, streaming | 3 | +| auth-and-guards | core | protecting-routes | beforeLoad redirects, layout auth, RBAC, provider integration | 3 | +| code-splitting | core | rendering-and-layout | autoCodeSplitting, .lazy.tsx, getRouteApi, split groupings | 4 | +| not-found-and-errors | core | rendering-and-layout | notFound(), notFoundComponent, errorComponent, CatchBoundary | 3 | +| route-masking | core | rendering-and-layout | mask option, createRouteMask, unmaskOnReload | 1 | +| type-safety | core | type-safety | Register, from narrowing, TS perf, type utilities | 3 | +| ssr | core | server-side-rendering | RouterClient/Server, streaming, hydration, head management | 3 | +| migrate-from-react-router | lifecycle | defining-routes | Migration checklist, API mapping, search params conversion | 2 | + +## Failure Mode Inventory + +### route-setup (5 failure modes) + +| # | Mistake | Priority | Source | Cross-skill? | +| --- | ------------------------------------------------------ | -------- | --------------------------------------- | ------------ | +| 1 | Missing router type registration | CRITICAL | docs/guide/creating-a-router | type-safety | +| 2 | Not committing routeTree.gen.ts | HIGH | docs/faq | — | +| 3 | Wrong route property order breaks type inference | HIGH | docs/eslint/create-route-property-order | — | +| 4 | Placing TanStackRouter plugin after framework plugin | HIGH | docs/installation/with-vite | — | +| 5 | Using getParentRoute incorrectly in code-based routing | HIGH | docs/decisions-on-dx | — | + +### navigation (4 failure modes) + +| # | Mistake | Priority | Source | Cross-skill? | +| --- | -------------------------------------------------------- | -------- | --------------------------------------- | ------------- | +| 1 | Interpolating params into the to string | CRITICAL | docs/guide/navigation | type-safety | +| 2 | Using useNavigate instead of Link for clickable elements | MEDIUM | docs/guide/navigation | — | +| 3 | Not providing from for relative navigation | HIGH | docs/guide/navigation | — | +| 4 | Using search as object instead of function loses params | HIGH | docs/how-to/navigate-with-search-params | search-params | + +### search-params (4 failure modes) + +| # | Mistake | Priority | Source | Cross-skill? | +| --- | ------------------------------------------------------ | -------- | -------------------------------- | ------------ | +| 1 | Using zod .catch() instead of adapter fallback() | HIGH | docs/guide/search-params | — | +| 2 | Returning entire search object from loaderDeps | HIGH | docs/guide/data-loading | data-loading | +| 3 | Passing Date objects in search params | HIGH | docs/how-to/arrays-objects-dates | — | +| 4 | Parent route missing validateSearch blocks inheritance | MEDIUM | docs/how-to/share-search-params | — | + +### path-params (3 failure modes) + +| # | Mistake | Priority | Source | Cross-skill? | +| --- | --------------------------------------------- | -------- | ----------------------------- | ------------ | +| 1 | Interpolating path params into `to` string | CRITICAL | docs/guide/navigation | navigation | +| 2 | Using \* for splat routes instead of $ | MEDIUM | docs/routing/routing-concepts | — | +| 3 | Using curly braces for basic dynamic segments | MEDIUM | docs/guide/path-params | — | + +### data-loading (5 failure modes) + +| # | Mistake | Priority | Source | Cross-skill? | +| --- | ---------------------------------------------------------------- | -------- | ------------------------- | ------------ | +| 1 | Assuming loaders only run on the server | CRITICAL | maintainer interview | ssr | +| 2 | Not understanding staleTime default is 0 | MEDIUM | docs/guide/data-loading | — | +| 3 | Using reset() instead of router.invalidate() in error components | HIGH | docs/guide/data-loading | — | +| 4 | Double parentheses missing on createRootRouteWithContext | HIGH | docs/guide/data-loading | — | +| 5 | Using React hooks in beforeLoad or loader | HIGH | docs/guide/router-context | — | + +### 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 | — | + +### auth-and-guards (3 failure modes) + +| # | Mistake | Priority | Source | Cross-skill? | +| --- | --------------------------------------------------- | -------- | -------------------------------- | ------------ | +| 1 | Auth check in component instead of beforeLoad | HIGH | docs/how-to/setup-authentication | — | +| 2 | Not re-throwing redirects in try/catch | HIGH | docs/guide/authenticated-routes | — | +| 3 | Trying to conditionally render root route component | MEDIUM | docs/faq | — | + +### code-splitting (4 failure modes) + +| # | Mistake | Priority | Source | Cross-skill? | +| --- | ---------------------------------------------------------- | -------- | ----------------------------------- | ------------ | +| 1 | Exporting route property functions prevents code splitting | HIGH | docs/guide/automatic-code-splitting | — | +| 2 | Trying to code-split the root route | MEDIUM | docs/guide/code-splitting | — | +| 3 | Splitting the loader adds double async cost | MEDIUM | docs/guide/code-splitting | — | +| 4 | Importing Route in code-split files for typed hooks | HIGH | docs/guide/code-splitting | — | + +### not-found-and-errors (3 failure modes) + +| # | Mistake | Priority | Source | Cross-skill? | +| --- | ---------------------------------------------------- | -------- | --------------------------- | ------------ | +| 1 | Using deprecated NotFoundRoute | HIGH | docs/guide/not-found-errors | — | +| 2 | Expecting useLoaderData to work in notFoundComponent | MEDIUM | docs/guide/not-found-errors | — | +| 3 | Leaf route cannot handle not-found errors | MEDIUM | docs/guide/not-found-errors | — | + +### route-masking (1 failure mode) + +| # | Mistake | Priority | Source | Cross-skill? | +| --- | ---------------------------------------- | -------- | ------------------------ | ------------ | +| 1 | Expecting masked URLs to survive sharing | MEDIUM | docs/guide/route-masking | — | + +### type-safety (3 failure modes) + +| # | Mistake | Priority | Source | Cross-skill? | +| --- | --------------------------------------------------- | -------- | ---------------------- | ------------ | +| 1 | Adding type annotations or casts to inferred values | CRITICAL | maintainer interview | — | +| 2 | Using un-narrowed LinkProps type | HIGH | docs/guide/type-safety | — | +| 3 | Not narrowing Link/useNavigate with from | HIGH | docs/guide/type-safety | — | + +### ssr (3 failure modes) + +| # | Mistake | Priority | Source | Cross-skill? | +| --- | ------------------------------------------------------- | -------- | --------------------- | ------------------------- | +| 1 | Using browser APIs in loaders without environment check | HIGH | docs/guide/ssr | data-loading | +| 2 | Using hash fragments for server-rendered content | MEDIUM | docs/guide/navigation | — | +| 3 | Generating Next.js or Remix SSR patterns | CRITICAL | maintainer interview | route-setup, data-loading | + +### migrate-from-react-router (2 failure modes) + +| # | Mistake | Priority | Source | Cross-skill? | +| --- | ------------------------------------------------------ | -------- | ------------------------------------------- | ------------ | +| 1 | Leaving React Router imports alongside TanStack Router | HIGH | docs/how-to/migrate-from-react-router | — | +| 2 | Using React Router useSearchParams pattern | HIGH | docs/installation/migrate-from-react-router | — | + +## Tensions + +| Tension | Skills | Agent implication | +| ------------------------------------------------- | ------------------------------------ | --------------------------------------------------------------------------------- | +| Type safety strictness vs rapid prototyping | type-safety ↔ route-setup | Agents skip Register declaration or use type casts to silence errors | +| Client-first loaders vs SSR expectations | data-loading ↔ ssr | Agents put server-only code in client loaders or avoid browser APIs unnecessarily | +| Built-in SWR cache vs external cache coordination | data-loading ↔ external-data-loading | Agents use both caches simultaneously causing stale data or double-fetching | +| Code splitting granularity vs loader performance | code-splitting ↔ data-loading | Agents split everything including loaders, adding latency | + +## Cross-References + +| From | To | Reason | +| ------------------------- | --------------------- | ---------------------------------------------------------------------------------- | +| route-setup | type-safety | Register declaration and property order are prerequisites for type inference | +| navigation | search-params | Link search prop directly interacts with search param validation | +| data-loading | search-params | loaderDeps consumes validated search params as cache keys | +| data-loading | external-data-loading | Understanding built-in caching is prerequisite for external cache coordination | +| auth-and-guards | data-loading | beforeLoad runs before loader — auth context flows into loader via route context | +| code-splitting | data-loading | Loader splitting decisions affect data loading performance | +| ssr | data-loading | SSR changes where loaders execute — must handle both environments | +| ssr | external-data-loading | SSR dehydration/hydration requires special Query setup | +| not-found-and-errors | data-loading | notFound() in loaders interacts with error boundaries and loader data availability | +| migrate-from-react-router | route-setup | Migration requires understanding TanStack Router route setup | + +## Subsystems & Reference Candidates + +| Skill | Subsystems | Reference candidates | +| ------------- | --------------------------------------------- | -------------------------------------------------------- | +| route-setup | — | file naming conventions (>10 distinct conventions) | +| search-params | Zod adapter, Valibot adapter, ArkType adapter | search param validation patterns (>10 distinct patterns) | +| All others | — | — | + +## Recommended Skill File Structure + +- **Core skills:** route-setup, navigation, search-params, path-params, data-loading, code-splitting, not-found-and-errors, route-masking, type-safety, ssr, auth-and-guards +- **Framework skills:** None needed separately — React and Solid share the same core API surface. Framework-specific notes belong inline. +- **Lifecycle skills:** migrate-from-react-router +- **Composition skills:** external-data-loading (TanStack Query) +- **Reference files:** search-params (validation patterns), route-setup (file naming conventions) + +## Composition Opportunities + +| Library | Integration points | Composition skill needed? | +| --------------------- | --------------------------------------------------------- | ------------------------------------------ | +| @tanstack/react-query | Loader coordination, SSR dehydration/hydration, streaming | Yes — external-data-loading | +| Zod | Search param validation | No — covered as subsystem in search-params | +| Valibot | Search param validation | No — covered as subsystem in search-params | +| ArkType | Search param validation | No — covered as subsystem in search-params | diff --git a/_artifacts/skill_tree.yaml b/_artifacts/skill_tree.yaml new file mode 100644 index 0000000000..6f7c4c8742 --- /dev/null +++ b/_artifacts/skill_tree.yaml @@ -0,0 +1,278 @@ +# skills/_artifacts/skill_tree.yaml +library: + name: '@tanstack/router' + version: '1.166.2' + repository: 'https://github.com/TanStack/router' + description: >- + Type-safe router for React and Solid with built-in SWR caching, + JSON-first search params, and end-to-end type inference. +generated_from: + domain_map: '_artifacts/domain_map.yaml' + skill_spec: '_artifacts/skill_spec.md' +generated_at: '2026-03-07' + +skills: + # ── Router Core Skills ─────────────────────────────────────────── + - name: 'Router Core' + slug: 'router-core' + type: 'core' + domain: 'defining-routes' + path: 'skills/router-core/SKILL.md' + package: 'packages/router-core' + description: >- + Framework-agnostic core concepts for TanStack Router: route trees, + createRouter, createRoute, createRootRoute, createRootRouteWithContext, + addChildren, Register type declaration, route matching, route sorting, + file naming conventions. Entry point for all router skills. + sources: + - 'TanStack/router:docs/router/overview.md' + - 'TanStack/router:docs/router/routing/routing-concepts.md' + - 'TanStack/router:docs/router/routing/route-trees.md' + - 'TanStack/router:docs/router/routing/route-matching.md' + - 'TanStack/router:docs/router/guide/creating-a-router.md' + - 'TanStack/router:docs/router/decisions-on-dx.md' + - 'TanStack/router:packages/router-core/src' + + - name: 'Search Params' + slug: 'router-core/search-params' + type: 'sub-skill' + domain: 'managing-url-state' + path: 'skills/router-core/search-params/SKILL.md' + package: 'packages/router-core' + description: >- + validateSearch, search param validation with Zod/Valibot/ArkType adapters, + fallback(), search middlewares (retainSearchParams, stripSearchParams), + custom serialization (parseSearch, stringifySearch), search param + inheritance, loaderDeps for cache keys, reading and writing search params. + requires: + - 'router-core' + sources: + - 'TanStack/router:docs/router/guide/search-params.md' + - 'TanStack/router:docs/router/how-to/setup-basic-search-params.md' + - 'TanStack/router:docs/router/how-to/validate-search-params.md' + - 'TanStack/router:docs/router/how-to/navigate-with-search-params.md' + - 'TanStack/router:docs/router/how-to/share-search-params-across-routes.md' + - 'TanStack/router:docs/router/how-to/arrays-objects-dates-search-params.md' + - 'TanStack/router:docs/router/guide/custom-search-param-serialization.md' + subsystems: + - 'Zod adapter' + - 'Valibot adapter' + - 'ArkType adapter' + references: + - 'references/validation-patterns.md' + + - name: 'Path Params' + slug: 'router-core/path-params' + type: 'sub-skill' + domain: 'managing-url-state' + path: 'skills/router-core/path-params/SKILL.md' + package: 'packages/router-core' + description: >- + Dynamic path segments ($paramName), splat routes ($ / _splat), + optional params ({-$paramName}), prefix/suffix patterns ({$param}.ext), + useParams, params.parse/stringify, pathParamsAllowedCharacters, + i18n locale patterns. + requires: + - 'router-core' + sources: + - 'TanStack/router:docs/router/guide/path-params.md' + - 'TanStack/router:docs/router/guide/internationalization-i18n.md' + - 'TanStack/router:docs/router/routing/routing-concepts.md' + + - name: 'Navigation' + slug: 'router-core/navigation' + type: 'sub-skill' + domain: 'navigating' + path: 'skills/router-core/navigation/SKILL.md' + package: 'packages/router-core' + description: >- + Link component, useNavigate, Navigate component, router.navigate, + ToOptions/NavigateOptions/LinkOptions, from/to relative navigation, + activeOptions/activeProps, preloading (intent/viewport/render), + preloadDelay, navigation blocking (useBlocker, Block), createLink, + linkOptions helper, scroll restoration, MatchRoute. + requires: + - 'router-core' + sources: + - 'TanStack/router:docs/router/guide/navigation.md' + - 'TanStack/router:docs/router/guide/preloading.md' + - 'TanStack/router:docs/router/guide/navigation-blocking.md' + - 'TanStack/router:docs/router/guide/link-options.md' + - 'TanStack/router:docs/router/guide/custom-link.md' + - 'TanStack/router:docs/router/guide/scroll-restoration.md' + + - name: 'Data Loading' + slug: 'router-core/data-loading' + type: 'sub-skill' + domain: 'loading-data' + path: 'skills/router-core/data-loading/SKILL.md' + package: 'packages/router-core' + description: >- + Route loader option, loaderDeps for cache keys, staleTime/gcTime/ + defaultPreloadStaleTime SWR caching, pendingComponent/pendingMs/ + pendingMinMs, errorComponent/onError/onCatch, beforeLoad, router + context and createRootRouteWithContext DI pattern, router.invalidate, + Await component, deferred data loading with unawaited promises. + requires: + - 'router-core' + sources: + - 'TanStack/router:docs/router/guide/data-loading.md' + - 'TanStack/router:docs/router/guide/deferred-data-loading.md' + - 'TanStack/router:docs/router/guide/router-context.md' + - 'TanStack/router:docs/router/guide/data-mutations.md' + + - name: 'Auth and Guards' + slug: 'router-core/auth-and-guards' + type: 'sub-skill' + domain: 'protecting-routes' + path: 'skills/router-core/auth-and-guards/SKILL.md' + package: 'packages/router-core' + description: >- + Route protection with beforeLoad, redirect()/throw redirect(), + isRedirect helper, authenticated layout routes (_authenticated), + non-redirect auth (inline login), RBAC with roles and permissions, + auth provider integration (Auth0, Clerk, Supabase), router context + for auth state. + requires: + - 'router-core' + sources: + - 'TanStack/router:docs/router/guide/authenticated-routes.md' + - 'TanStack/router:docs/router/how-to/setup-authentication.md' + - 'TanStack/router:docs/router/how-to/setup-auth-providers.md' + - 'TanStack/router:docs/router/how-to/setup-rbac.md' + + - name: 'Code Splitting' + slug: 'router-core/code-splitting' + type: 'sub-skill' + domain: 'rendering-and-layout' + path: 'skills/router-core/code-splitting/SKILL.md' + package: 'packages/router-core' + description: >- + Automatic code splitting (autoCodeSplitting), .lazy.tsx convention, + createLazyFileRoute, createLazyRoute, lazyRouteComponent, getRouteApi + for typed hooks in split files, codeSplitGroupings per-route override, + splitBehavior programmatic config, critical vs non-critical properties. + requires: + - 'router-core' + sources: + - 'TanStack/router:docs/router/guide/code-splitting.md' + - 'TanStack/router:docs/router/guide/automatic-code-splitting.md' + + - name: 'Not Found and Errors' + slug: 'router-core/not-found-and-errors' + type: 'sub-skill' + domain: 'rendering-and-layout' + path: 'skills/router-core/not-found-and-errors/SKILL.md' + package: 'packages/router-core' + description: >- + notFound() function, notFoundComponent, defaultNotFoundComponent, + notFoundMode (fuzzy/root), errorComponent, onError/onCatch, + CatchBoundary, NotFoundRoute (deprecated), route masking (mask + option, createRouteMask, unmaskOnReload). + requires: + - 'router-core' + sources: + - 'TanStack/router:docs/router/guide/not-found-errors.md' + - 'TanStack/router:docs/router/guide/route-masking.md' + + - name: 'Type Safety' + slug: 'router-core/type-safety' + type: 'sub-skill' + domain: 'type-safety' + path: 'skills/router-core/type-safety/SKILL.md' + package: 'packages/router-core' + description: >- + Full type inference philosophy (never cast, never annotate inferred + values), Register module declaration, from narrowing on hooks and + Link, strict:false for shared components, getRouteApi for code-split + typed access, addChildren with object syntax for TS perf, LinkProps + and ValidateLinkOptions type utilities, as const satisfies pattern. + requires: + - 'router-core' + sources: + - 'TanStack/router:docs/router/guide/type-safety.md' + - 'TanStack/router:docs/router/guide/type-utilities.md' + - 'TanStack/router:docs/router/guide/render-optimizations.md' + + - name: 'SSR' + slug: 'router-core/ssr' + type: 'sub-skill' + domain: 'server-side-rendering' + path: 'skills/router-core/ssr/SKILL.md' + package: 'packages/router-core' + description: >- + Non-streaming and streaming SSR, RouterClient/RouterServer, + renderRouterToString/renderRouterToStream, createRequestHandler, + defaultRenderHandler/defaultStreamHandler, HeadContent/Scripts + components, head route option (meta/links/styles/scripts), + ScriptOnce, automatic loader dehydration/hydration, memory + history on server, data serialization, document head management. + requires: + - 'router-core' + - 'router-core/data-loading' + sources: + - 'TanStack/router:docs/router/guide/ssr.md' + - 'TanStack/router:docs/router/guide/document-head-management.md' + - 'TanStack/router:docs/router/how-to/setup-ssr.md' + + # ── React Router Skills ────────────────────────────────────────── + - name: 'React Router' + slug: 'react-router' + type: 'framework' + domain: 'defining-routes' + path: 'skills/react-router/SKILL.md' + package: 'packages/react-router' + description: >- + React bindings for TanStack Router: RouterProvider, useRouter, + useRouterState, useMatch, useMatches, useLocation, useSearch, + useParams, useNavigate, useLoaderData, useLoaderDeps, + useRouteContext, useBlocker, useCanGoBack, Link, Navigate, + Outlet, CatchBoundary, ErrorComponent. React-specific patterns + for hooks, providers, SSR hydration, and createLink with + forwardRef. + requires: + - 'router-core' + sources: + - 'TanStack/router:packages/react-router/src' + - 'TanStack/router:docs/router/guide/creating-a-router.md' + - 'TanStack/router:docs/router/installation/manual.md' + + # ── Composition Skills ─────────────────────────────────────────── + - name: 'External Data Loading (TanStack Query)' + slug: 'compositions/router-query' + type: 'composition' + domain: 'loading-data' + path: 'skills/compositions/router-query/SKILL.md' + package: 'packages/react-router' + description: >- + Integrating TanStack Router with TanStack Query: queryClient + in router context, static queries and fire-and-forget queries in loaders, + useSuspenseQuery in components, defaultPreloadStaleTime: 0, + setupRouterSsrQueryIntegration for SSR dehydration/hydration + and streaming, per-request QueryClient isolation. + requires: + - 'router-core' + - 'router-core/data-loading' + - 'react-router' + sources: + - 'TanStack/router:docs/router/guide/external-data-loading.md' + - 'TanStack/router:docs/router/integrations/query.md' + + # ── Lifecycle Skills ───────────────────────────────────────────── + - name: 'Migrate from React Router' + slug: 'lifecycle/migrate-from-react-router' + type: 'lifecycle' + domain: 'defining-routes' + path: 'skills/lifecycle/migrate-from-react-router/SKILL.md' + package: 'packages/react-router' + description: >- + Step-by-step migration from React Router v7 to TanStack Router: + route definition conversion, Link/useNavigate API differences, + useSearchParams to validateSearch + useSearch, useParams with from, + Outlet replacement, loader conversion, code splitting differences. + requires: + - 'router-core' + - 'react-router' + sources: + - 'TanStack/router:docs/router/how-to/migrate-from-react-router.md' + - 'TanStack/router:docs/router/installation/migrate-from-react-router.md' diff --git a/_artifacts/start_domain_map.yaml b/_artifacts/start_domain_map.yaml new file mode 100644 index 0000000000..a557901075 --- /dev/null +++ b/_artifacts/start_domain_map.yaml @@ -0,0 +1,482 @@ +# domain_map.yaml +# Generated by skill-domain-discovery +# Library: TanStack Start +# Version: 1.166.2 +# Date: 2026-03-07 +# Status: reviewed + +library: + name: '@tanstack/react-start' + version: '1.166.2' + repository: 'https://github.com/TanStack/router' + description: >- + Full-stack React framework built on TanStack Router and Vite. Adds + SSR, streaming, server functions (type-safe RPCs), middleware, + server routes, and universal deployment. Isomorphic by default — + all code runs in both environments unless explicitly constrained. + primary_framework: 'React' + +domains: + - name: 'Project Setup' + slug: 'project-setup' + description: >- + Scaffolding a Start project, configuring Vite plugin, router + setup with getRouter(), root route with document shell, client + and server entry points. + + - name: 'Server Functions' + slug: 'server-functions' + description: >- + Creating type-safe RPCs with createServerFn, input validation, + calling from loaders/components/other server functions, error + handling, streaming responses. + + - name: 'Middleware and Context' + slug: 'middleware-and-context' + description: >- + Request middleware, server function middleware, context passing + with sendContext, global middleware via createStart, middleware + factories, fetch override precedence. + + - name: 'Execution Model' + slug: 'execution-model' + description: >- + Isomorphic code execution, environment functions + (createServerFn, createServerOnlyFn, createClientOnlyFn, + createIsomorphicFn), import protection, dead code elimination, + environment variable safety. + + - name: 'Server Routes' + slug: 'server-routes' + description: >- + Server-side API endpoints defined in routes, HTTP method + handlers, handler middleware, request/response patterns. + + - name: 'Deployment and Rendering' + slug: 'deployment-and-rendering' + description: >- + Hosting providers (Cloudflare, Netlify, Vercel, Node/Docker), + selective SSR, SPA mode, static prerendering, ISR with + Cache-Control headers, SEO and head management. + +skills: + # ── Project Setup ──────────────────────────────────────────────── + - name: 'Start Setup' + slug: 'start-setup' + domain: 'project-setup' + description: >- + Scaffold a TanStack Start project, configure Vite plugin with + tanstackStart(), set up router with getRouter(), create root + route with document shell (HeadContent, Scripts, Outlet), + configure client and server entry points. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-plugin-core' + covers: + - tanstackStart Vite plugin + - getRouter() factory pattern + - Root route document shell + - HeadContent / Scripts / Outlet + - Client entry point (optional) + - Server entry point (optional) + - routeTree.gen.ts + - tsconfig configuration + tasks: + - 'Scaffold a new TanStack Start project' + - 'Configure the Vite plugin' + - 'Set up the router factory' + - 'Customize client/server entry points' + failure_modes: + - mistake: 'React plugin before Start plugin in Vite config' + mechanism: >- + Start's Vite plugin must come before React's plugin. + Wrong order causes route generation and server function + compilation to fail. + wrong_pattern: | + plugins: [react(), tanstackStart()] + correct_pattern: | + plugins: [tanstackStart(), react()] + source: 'docs/start/framework/react/build-from-scratch.md' + priority: CRITICAL + status: active + + - mistake: 'Enabling verbatimModuleSyntax in tsconfig' + mechanism: >- + verbatimModuleSyntax causes server bundles to leak into + client bundles. Must be disabled. + source: 'docs/start/framework/react/build-from-scratch.md' + priority: HIGH + status: active + + - mistake: 'Missing Scripts component in root route' + mechanism: >- + The Scripts component must be rendered in the body of + the root route for proper hydration and functionality. + Without it, client-side JavaScript does not load. + source: 'docs/start/framework/react/guide/routing.md' + priority: HIGH + status: active + + # ── Server Functions ───────────────────────────────────────────── + - name: 'Server Functions' + slug: 'server-functions' + domain: 'server-functions' + description: >- + Create type-safe RPCs with createServerFn, validate inputs + with Zod or plain functions, call from loaders/components/ + event handlers, handle errors/redirects/notFound, stream + responses with ReadableStream or async generators. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-client-core' + - '@tanstack/start-server-core' + covers: + - createServerFn (GET/POST) + - validator (Zod or function) + - useServerFn hook + - Server context utilities (getRequest, getRequestHeader, setResponseHeader, setResponseStatus) + - Error handling (throw errors, redirect, notFound) + - Streaming (ReadableStream, async generators) + - File organization (.functions.ts, .server.ts) + - FormData handling + tasks: + - 'Create a server function for data fetching' + - 'Validate server function inputs' + - 'Call server functions from components' + - 'Stream data from server functions' + - 'Handle errors in server functions' + failure_modes: + - mistake: 'Putting server-only code in loaders instead of server functions' + mechanism: >- + Loaders are ISOMORPHIC — they run on both client and server. + Database queries, file system access, and secret API keys + in loaders will either fail on the client or leak to the + client bundle. Use createServerFn for server-only logic. + wrong_pattern: | + export const Route = createFileRoute('/posts')({ + loader: async () => { + const posts = await db.query('SELECT * FROM posts') + return { posts } + }, + }) + correct_pattern: | + const getPosts = createServerFn({ method: 'GET' }) + .handler(async () => { + const posts = await db.query('SELECT * FROM posts') + return { posts } + }) + + export const Route = createFileRoute('/posts')({ + loader: () => getPosts(), + }) + source: 'maintainer interview' + priority: CRITICAL + status: active + skills: ['server-functions', 'execution-model'] + + - mistake: 'Using dynamic imports for server functions' + mechanism: >- + Dynamic imports of server functions can cause bundler + issues. Static imports are safe — the build process + replaces server implementations with RPC stubs. + wrong_pattern: | + const { getUser } = await import('~/utils/users.functions') + correct_pattern: | + import { getUser } from '~/utils/users.functions' + source: 'docs/start/framework/react/guide/server-functions.md' + priority: HIGH + status: active + + - mistake: 'Generating Next.js or Remix server patterns' + mechanism: >- + Agents generate getServerSideProps, "use server" directives, + or Remix-style loader exports. TanStack Start uses + createServerFn for server-only code. + wrong_pattern: | + 'use server' + export async function getUser() { ... } + correct_pattern: | + const getUser = createServerFn({ method: 'GET' }) + .handler(async () => { ... }) + source: 'maintainer interview' + priority: CRITICAL + status: active + + # ── Middleware and Context ─────────────────────────────────────── + - name: 'Middleware' + slug: 'middleware' + domain: 'middleware-and-context' + description: >- + Request middleware and server function middleware with + createMiddleware, context passing via next(), sendContext + for client-server transfer, global middleware via createStart + in src/start.ts, middleware factories, fetch override + precedence, header merging. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-client-core' + - '@tanstack/start-server-core' + covers: + - createMiddleware + - Request middleware (.server only) + - Server function middleware (.client + .server) + - Context passing via next({ context }) + - sendContext for client-server transfer + - Global middleware (createStart in src/start.ts) + - Middleware factories + - Fetch override precedence + - Header merging + - Method order enforcement (middleware → validator → client → server) + tasks: + - 'Add authentication middleware' + - 'Pass context through middleware chain' + - 'Configure global request middleware' + - 'Create reusable middleware factories' + failure_modes: + - mistake: 'Trusting client context without server validation' + mechanism: >- + Client context via sendContext is NOT validated by default. + Dynamic user-generated data must be validated in server-side + middleware before use. + source: 'docs/start/framework/react/guide/middleware.md' + priority: HIGH + status: active + + - mistake: 'Wrong middleware method order' + mechanism: >- + TypeScript enforces method order: middleware → validator + → client → server. Wrong order causes type errors and + runtime failures. + source: 'docs/start/framework/react/guide/middleware.md' + priority: MEDIUM + status: active + + - mistake: 'Confusing request vs server function middleware' + mechanism: >- + Request middleware runs on ALL server requests (SSR, server + routes, server functions). Server function middleware runs + only for server functions and has .client() method. Using + the wrong type causes unexpected scope. + source: 'docs/start/framework/react/guide/middleware.md' + priority: MEDIUM + status: active + + # ── Execution Model ────────────────────────────────────────────── + - name: 'Execution Model' + slug: 'execution-model' + domain: 'execution-model' + description: >- + Isomorphic code execution model, environment boundary functions + (createServerFn, createServerOnlyFn, createClientOnlyFn, + createIsomorphicFn), import protection, dead code elimination, + environment variable safety (VITE_ prefix), useHydrated hook. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-client-core' + - '@tanstack/start-server-core' + covers: + - Isomorphic-by-default principle + - createServerFn (RPC boundary) + - createServerOnlyFn (throws on client) + - createClientOnlyFn (throws on server) + - createIsomorphicFn (different impl per env) + - ClientOnly component + - useHydrated hook + - Import protection (experimental) + - Environment variables (VITE_ prefix, process.env) + - Dead code elimination / tree shaking + tasks: + - 'Protect server-only code from client bundles' + - 'Use environment-specific implementations' + - 'Handle environment variables safely' + - 'Debug import protection violations' + failure_modes: + - mistake: 'Assuming loaders are server-only' + mechanism: >- + ALL code in TanStack Start is isomorphic by default. + Loaders run on BOTH server and client. Server-only + operations must use createServerFn, createServerOnlyFn, + or server routes. + wrong_pattern: | + export const Route = createFileRoute('/dashboard')({ + loader: async () => { + const secret = process.env.API_SECRET + return fetch(`https://api.example.com/data`, { + headers: { Authorization: secret } + }) + }, + }) + correct_pattern: | + const getData = createServerFn({ method: 'GET' }) + .handler(async () => { + const secret = process.env.API_SECRET + return fetch(`https://api.example.com/data`, { + headers: { Authorization: secret } + }) + }) + + export const Route = createFileRoute('/dashboard')({ + loader: () => getData(), + }) + source: 'docs/start/framework/react/guide/execution-model.md' + priority: CRITICAL + status: active + skills: ['execution-model', 'server-functions'] + + - mistake: 'Exposing secrets via module-level process.env' + mechanism: >- + Module-level process.env access runs in both environments. + The variable value leaks into the client bundle. Access + secrets only inside createServerFn or createServerOnlyFn. + wrong_pattern: | + const apiKey = process.env.SECRET_KEY + export function fetchData() { ... } + correct_pattern: | + const fetchData = createServerFn({ method: 'GET' }) + .handler(async () => { + const apiKey = process.env.SECRET_KEY + return fetch(url, { headers: { Authorization: apiKey } }) + }) + source: 'docs/start/framework/react/guide/execution-model.md' + priority: CRITICAL + status: active + + - mistake: 'Using VITE_ prefix for server secrets' + mechanism: >- + VITE_ prefixed variables are exposed to the client bundle. + Server secrets must NOT have the VITE_ prefix. Access + them via process.env inside server functions only. + source: 'docs/start/framework/react/guide/environment-variables.md' + priority: CRITICAL + status: active + + # ── Server Routes ──────────────────────────────────────────────── + - name: 'Server Routes' + slug: 'server-routes' + domain: 'server-routes' + description: >- + Define server-side API endpoints alongside app routes using + the server property with HTTP method handlers, per-handler + middleware via createHandlers, request/response patterns. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-server-core' + covers: + - server property on createFileRoute + - handlers object (GET, POST, PUT, DELETE) + - createHandlers for per-handler middleware + - Handler context (request, params, context) + - Request body parsing (json, text, formData) + - Response helpers (Response.json) + - File naming for API routes + tasks: + - 'Create a REST API endpoint' + - 'Add middleware to server route handlers' + - 'Handle different HTTP methods' + failure_modes: + - mistake: 'Duplicate path resolution for server routes' + mechanism: >- + Each route can only have a single handler file. Having + both users.ts and users/index.ts causes errors. + source: 'docs/start/framework/react/guide/server-routes.md' + priority: MEDIUM + status: active + + # ── Deployment and Rendering ───────────────────────────────────── + - name: 'Deployment' + slug: 'deployment' + domain: 'deployment-and-rendering' + description: >- + Deploy TanStack Start to Cloudflare Workers, Netlify, Vercel, + Node.js/Docker, Bun, Railway. Configure selective SSR, SPA + mode, static prerendering, ISR with Cache-Control headers. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-plugin-core' + covers: + - Cloudflare Workers deployment + - Netlify deployment + - Vercel / Railway deployment + - Node.js / Docker deployment + - Bun deployment + - Selective SSR (ssr option per route) + - SPA mode configuration + - Static prerendering (prerender option) + - ISR with Cache-Control headers + - SEO (head property, structured data) + tasks: + - 'Deploy to Cloudflare Workers' + - 'Deploy to Netlify' + - 'Configure selective SSR per route' + - 'Enable SPA mode' + - 'Set up static prerendering' + - 'Configure ISR with cache headers' + failure_modes: + - mistake: 'Bun deployment with React 18' + mechanism: >- + Bun-specific deployment only works with React 19. + For React 18, use Node.js deployment guidelines. + source: 'docs/start/framework/react/guide/hosting.md' + priority: MEDIUM + status: active + + - mistake: 'Missing nodejs_compat flag for Cloudflare Workers' + mechanism: >- + Cloudflare Workers requires compatibility_flags: + ["nodejs_compat"] in wrangler config. Without it, + Node.js APIs used by Start fail at runtime. + source: 'docs/start/framework/react/guide/hosting.md' + priority: HIGH + status: active + + - mistake: 'Child route loosening parent SSR config' + mechanism: >- + SSR config inherits from parent and can only become MORE + restrictive (true → data-only → false). A child cannot + set ssr: true if parent has ssr: false. + source: 'docs/start/framework/react/guide/selective-ssr.md' + priority: MEDIUM + status: active + +tensions: + - name: 'Isomorphic defaults vs server-only expectations' + skills: ['execution-model', 'server-functions'] + description: >- + All code runs everywhere by default. Agents trained on + Next.js/Remix assume loaders and route code are server-only. + implication: >- + Agents put secrets, DB queries, and file system access in + loaders instead of server functions, causing client-side + failures or security leaks. + + - name: 'Simplicity of isomorphic code vs security boundaries' + skills: ['execution-model', 'middleware'] + description: >- + The isomorphic model makes code easy to write but requires + explicit boundaries for security. Agents don't realize they + need to actively constrain execution environment. + implication: >- + Agents expose secrets via module-level process.env or + forget to validate sendContext data in middleware. + +cross_references: + - from: 'server-functions' + to: 'execution-model' + reason: 'Server functions ARE the isomorphic boundary — understanding the execution model is prerequisite' + - from: 'server-functions' + to: 'middleware' + reason: 'Server function middleware chains compose with server functions' + - from: 'middleware' + to: 'server-routes' + reason: 'Server routes use the same middleware system' + - from: 'deployment' + to: 'execution-model' + reason: 'Deployment target affects which environment code runs in' + +gaps: [] diff --git a/_artifacts/start_skill_tree.yaml b/_artifacts/start_skill_tree.yaml new file mode 100644 index 0000000000..4d221068fd --- /dev/null +++ b/_artifacts/start_skill_tree.yaml @@ -0,0 +1,158 @@ +# skills/_artifacts/start_skill_tree.yaml +library: + name: '@tanstack/react-start' + version: '1.166.2' + repository: 'https://github.com/TanStack/router' + description: >- + Full-stack React framework built on TanStack Router and Vite. + Adds SSR, streaming, server functions (type-safe RPCs), middleware, + server routes, and universal deployment. Isomorphic by default — + all code runs in both environments unless explicitly constrained. +generated_from: + domain_map: '_artifacts/start_domain_map.yaml' +generated_at: '2026-03-07' + +skills: + # ── Start Core Skills ─────────────────────────────────────────── + - name: 'Start Core' + slug: 'start-core' + type: 'core' + domain: 'project-setup' + path: 'skills/start-core/SKILL.md' + package: 'packages/start-client-core' + description: >- + Core overview for TanStack Start: tanstackStart() Vite plugin, + getRouter() factory, root route document shell (HeadContent, + Scripts, Outlet), client/server entry points, routeTree.gen.ts, + tsconfig configuration. Entry point for all Start skills. + sources: + - 'TanStack/router:docs/start/framework/react/build-from-scratch.md' + - 'TanStack/router:docs/start/framework/react/quick-start.md' + - 'TanStack/router:docs/start/framework/react/guide/routing.md' + + - name: 'Server Functions' + slug: 'start-core/server-functions' + type: 'sub-skill' + domain: 'server-functions' + path: 'skills/start-core/server-functions/SKILL.md' + package: 'packages/start-client-core' + description: >- + createServerFn (GET/POST), validator (Zod or function), + useServerFn hook, server context utilities (getRequest, + getRequestHeader, setResponseHeader, setResponseStatus), error + handling (throw errors, redirect, notFound), streaming + (ReadableStream, async generators), FormData handling, file + organization (.functions.ts, .server.ts). + requires: + - 'start-core' + sources: + - 'TanStack/router:docs/start/framework/react/guide/server-functions.md' + + - name: 'Middleware' + slug: 'start-core/middleware' + type: 'sub-skill' + domain: 'middleware-and-context' + path: 'skills/start-core/middleware/SKILL.md' + package: 'packages/start-client-core' + description: >- + createMiddleware, request middleware (.server only), server + function middleware (.client + .server), context passing via + next({ context }), sendContext for client-server transfer, + global middleware via createStart in src/start.ts, middleware + factories, method order enforcement. + requires: + - 'start-core' + - 'start-core/server-functions' + sources: + - 'TanStack/router:docs/start/framework/react/guide/middleware.md' + + - name: 'Execution Model' + slug: 'start-core/execution-model' + type: 'sub-skill' + domain: 'execution-model' + path: 'skills/start-core/execution-model/SKILL.md' + package: 'packages/start-client-core' + description: >- + Isomorphic-by-default principle, environment boundary functions + (createServerFn, createServerOnlyFn, createClientOnlyFn, + createIsomorphicFn), ClientOnly component, useHydrated hook, + import protection, dead code elimination, environment variable + safety (VITE_ prefix, process.env). + requires: + - 'start-core' + sources: + - 'TanStack/router:docs/start/framework/react/guide/execution-model.md' + - 'TanStack/router:docs/start/framework/react/guide/environment-variables.md' + + - name: 'Server Routes' + slug: 'start-core/server-routes' + type: 'sub-skill' + domain: 'server-routes' + path: 'skills/start-core/server-routes/SKILL.md' + package: 'packages/start-client-core' + description: >- + Server-side API endpoints using the server property on + createFileRoute, HTTP method handlers (GET, POST, PUT, DELETE), + createHandlers for per-handler middleware, handler context + (request, params, context), request body parsing, response + helpers, file naming for API routes. + requires: + - 'start-core' + sources: + - 'TanStack/router:docs/start/framework/react/guide/server-routes.md' + + - name: 'Deployment' + slug: 'start-core/deployment' + type: 'sub-skill' + domain: 'deployment-and-rendering' + path: 'skills/start-core/deployment/SKILL.md' + package: 'packages/start-client-core' + description: >- + Deploy to Cloudflare Workers, Netlify, Vercel, Node.js/Docker, + Bun, Railway. Selective SSR (ssr option per route), SPA mode, + static prerendering, ISR with Cache-Control headers, SEO and + head management. + requires: + - 'start-core' + sources: + - 'TanStack/router:docs/start/framework/react/guide/hosting.md' + - 'TanStack/router:docs/start/framework/react/guide/selective-ssr.md' + - 'TanStack/router:docs/start/framework/react/guide/static-prerendering.md' + - 'TanStack/router:docs/start/framework/react/guide/full-stack-seo.md' + + # ── React Start Skills ────────────────────────────────────────── + - name: 'React Start' + slug: 'react-start' + type: 'framework' + domain: 'project-setup' + path: 'skills/react-start/SKILL.md' + package: 'packages/react-start' + description: >- + React bindings for TanStack Start: createStart, StartClient, + StartServer, React-specific imports, re-exports from + @tanstack/react-router, full project setup with React. + requires: + - 'start-core' + sources: + - 'TanStack/router:packages/react-start/src' + - 'TanStack/router:docs/start/framework/react/build-from-scratch.md' + + # ── Lifecycle Skills ──────────────────────────────────────────── + - name: 'Migrate from Next.js' + slug: 'lifecycle/migrate-from-nextjs' + type: 'lifecycle' + domain: 'project-setup' + path: 'skills/lifecycle/migrate-from-nextjs/SKILL.md' + package: 'packages/react-start' + description: >- + Step-by-step migration from Next.js App Router to TanStack + Start: route definition conversion, API mapping, server + function conversion from Server Actions, middleware conversion, + data fetching pattern changes. + requires: + - 'start-core' + - 'react-start' + sources: + - 'TanStack/router:docs/start/framework/react/guide/server-functions.md' + - 'TanStack/router:docs/start/framework/react/guide/middleware.md' + - 'TanStack/router:docs/start/framework/react/guide/execution-model.md' diff --git a/benchmarks/AGENTS.md b/benchmarks/AGENTS.md new file mode 100644 index 0000000000..9d56a2411a --- /dev/null +++ b/benchmarks/AGENTS.md @@ -0,0 +1,15 @@ +# Benchmarks + +Read the relevant README before running benchmarks. Compare baseline and candidate with the same workload and production builds; add a focused case when existing scenarios miss the changed mechanism. Keep workloads and benchmark names stable for historical comparisons. + +| Changed behavior | Guide | Nx project | +| ------------------------------------------ | ---------------------------------- | -------------------------------------------------------- | +| Standalone Router navigation/rendering CPU | [client-nav](client-nav/README.md) | `@benchmarks/client-nav` | +| Start request/SSR CPU | [ssr](ssr/README.md) | `@benchmarks/ssr` | +| Client/server retention and allocations | [memory](memory/README.md) | `@benchmarks/memory-client`, `@benchmarks/memory-server` | + +Use `test:perf:` through Nx. Plain memory runs only smoke-test; memory metrics require CodSpeed. Client navigation benchmarks do not cover Start hydration or client server-function calls. + +Run `vitest bench` directly only with `--mode benchmark`, as the Nx targets do. Vitest 5 otherwise uses Vite's `test` mode, where vite-plugin-solid injects a jest-dom setup file that benchmark packages cannot resolve. + +For bundle-size work, follow the full optimization skill required by the root guide. Full API fixtures are maintained manually: when public hooks/components change, update matching `bundle-size/scenarios/*-full/src/routes/__root.tsx` fixtures. Save baseline results separately because each run overwrites `bundle-size/results/current.json`; report final gzip deltas and explain remaining growth. diff --git a/benchmarks/README.md b/benchmarks/README.md new file mode 100644 index 0000000000..94d2f31802 --- /dev/null +++ b/benchmarks/README.md @@ -0,0 +1,88 @@ +# CPU simulation benchmarks + +`client-nav` measures navigation, mounting, and React/Solid hydration in +Node/jsdom; `ssr` measures server requests. +Both suites run through the CodSpeed Vitest integration in CPU simulation mode. + +## Worker runtime + +Every CPU benchmark project includes `cpuSimulationExecArgv()` from +[`cpu-simulation.ts`](./cpu-simulation.ts). It augments CodSpeed's worker flags +only during CPU simulation, including the legacy `instrumentation` mode. + +The pinned CodSpeed integration supplies `--no-opt`. In Node 24 this is an alias +for `--no-turbofan`, so Maglev can still optimize and inline hot functions. The +additional `--no-maglev` keeps the optimizing compiler out of the simulation. +`--always-sparkplug` compiles baseline code on first use, so warmup does not leave +functions approaching a later tier-up or batch-compilation threshold. The worker +regression test checks that even a once-called function receives baseline code. +The integration also omits the old `--no-scavenge-task` flag on Node 20 and +newer, where V8 renamed it to `--no-minor-gc-task`. Supplying the renamed flag +keeps minor GC tied to allocation pressure instead of scheduled foreground +tasks. Both flags follow the fixes in +[CodSpeed's Node 24 support](https://github.com/CodSpeedHQ/codspeed-node/commit/e3224e7872). + +`--initial-old-space-size=512` fixes the initial/minimum old-generation +allocation budget at 512 MiB. Removing only this override after worker isolation +left two Vue SSR scenarios with same-commit spreads above 2% in five full-suite +repetitions. The paired default-heap comparison with stock incremental-marking +tasks also exceeded 2%. Runtime comparisons and tested alternatives are recorded in +[PR #8248](https://github.com/TanStack/router/pull/8248). + +This is a GC-policy tradeoff. Minor collections and allocation work remain +measured, and CodSpeed still explicitly collects before measurement. However, +V8 can skip automatic full collections below this old-generation budget, so the +benchmark can omit some eventual full-GC CPU cost from increased object +retention. Repeatability does not establish representative production GC +frequency. The flag does not preallocate 512 MiB; the existing 4096 MiB maximum +remains. See [V8's initial/minimum heap configuration](https://github.com/nodejs/node/blob/v24.8.0/deps/v8/src/heap/heap.cc#L5071). + +The configuration preserves CodSpeed's incremental-marking task settings; the +additional `--no-incremental-marking-task` from the initial stabilization proposal +has been removed. + +The flags are intentionally absent from ordinary Vitest timing and walltime runs. + +Changing simulation compiler settings changes the measurement baseline. Compare +repeatability within each configuration before interpreting performance changes +between configurations as router improvements or regressions. + +## Worker isolation + +Keep one SSR workload in each `speed*.bench.ts` file. These projects explicitly +enable Vitest isolation; CodSpeed uses the forks pool, so every file receives a +fresh worker. Multiple workloads in one file share the worker's runtime state, +even though CodSpeed collects before each measurement. Later control cases +remained noisy after the runtime flag corrections. Running the React plain +dehydration and linked-CSS controls alone reduced their observed three-run spreads +to 0.09% and 0.02% respectively. + +Variant files keep their workload names, request counts, concurrency, payloads +and assertions. CodSpeed includes the file path in a benchmark's identity, so +moved variants start a new history. The first workload keeps `speed.bench.ts`; +the additional variants have descriptive file names alongside it. Type-check +includes cover all of these files. + +## Streaming workload + +Deferred payloads in the SSR streaming scenario resolve after two task turns on +Node. A real 1 ms timer lets elapsed host time decide which concurrent requests +resolve together. Counted turns preserve the initial loading render and deferred +payloads; the existing HTML assertions check both. These benchmarks execute in +Node and use `setImmediate` directly. + +## Repeatability checks + +Dispatch the existing `Benchmarks` workflow against an unchanged branch: + +```sh +gh workflow run benchmarks.yml --ref +``` + +Wait for each workflow run to finish before dispatching the next repetition at +the same commit. The workflow also runs memory benchmarks; exclude those results +when assessing CPU repeatability. Check that every repetition has all expected +CPU results (currently 134), rather than inherited results from an earlier run. +Compare each benchmark's minimum and maximum across repetitions; keep input data, +navigation/request counts, builds, dependencies and Node version fixed when +testing runtime configuration changes. diff --git a/benchmarks/bundle-size/.gitignore b/benchmarks/bundle-size/.gitignore new file mode 100644 index 0000000000..bd05a98cee --- /dev/null +++ b/benchmarks/bundle-size/.gitignore @@ -0,0 +1,11 @@ +node_modules +dist +dist-debug +scenarios/*/src/routeTree.gen.ts + +results/*.json +results/*.md +results/*.js +results/*.log +results/runs/ +!results/.gitkeep diff --git a/benchmarks/bundle-size/README.md b/benchmarks/bundle-size/README.md new file mode 100644 index 0000000000..2185d6b43f --- /dev/null +++ b/benchmarks/bundle-size/README.md @@ -0,0 +1,172 @@ +# Bundle Size Benchmarks + +This workspace contains deterministic bundle-size fixtures for: + +- `@tanstack/react-router` +- `@tanstack/solid-router` +- `@tanstack/vue-router` +- `@tanstack/react-start` +- `@tanstack/solid-start` + +Each package has `minimal` and `full` scenarios: + +- `minimal`: Small route app with `__root` + index route that renders `hello world` +- `full`: Same route shape plus a broad root-level harness that imports/uses the full hooks/components surface +- Start `full` scenarios also exercise `createServerFn`, `createMiddleware`, and `useServerFn` +- Start `deferred-hydration` scenarios match the minimal route shape and wrap the index route content in `Hydrate` + +## Design Notes + +- Scenarios use file-based routing as the default app style. +- Router scenarios use `@tanstack/router-plugin/vite` with `autoCodeSplitting: true`. +- Start Vite scenarios use `@tanstack/-start/plugin/vite` with router code-splitting enabled. +- React Start also includes Rsbuild scenarios using `@tanstack/react-start/plugin/rsbuild`. +- Full-surface coverage is manually maintained (no strict export-coverage gate). +- Primary metrics measure all emitted client JS chunks and are reported as raw/gzip/brotli bytes. +- Initial-load JS graph metrics are also recorded as `initialRawBytes`, `initialGzipBytes`, and `initialBrotliBytes` for context. +- Gzip for all emitted client JS is the primary tracking signal for PR deltas and historical charting. + +## Local Run + +```bash +pnpm benchmark:bundle-size:run +``` + +Run one or more scenarios during local optimization: + +```bash +pnpm benchmark:bundle-size:run --scenario react-router.minimal +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`. + +If the required packages are already built and unchanged, skip that step: + +```bash +pnpm benchmark:bundle-size:run --scenario react-router.minimal --skip-package-builds +``` + +This writes: + +- `benchmarks/bundle-size/results/measurements.json` +- `benchmarks/bundle-size/results/current.json` +- `benchmarks/bundle-size/results/benchmark-action.json` +- `benchmarks/bundle-size/results/measure.log` + +`current.json` includes run status, selected package build projects, per-scenario totals, per-file sizes, and the emitted JS files used for measurement. Dist paths use `scenarioDir`/`outDir`, e.g. `react-router.minimal` maps to `benchmarks/bundle-size/dist/react-router-minimal/`. + +The runner sets `CI=1` and `NX_DAEMON=false`. Successful runs print log locations and the existing `query` or `diff` summary. +If a step fails, the runner stops with a nonzero exit code. It prints the last 40 log lines, limited to 8,000 characters. +Full stdout and stderr stay in the log files. A positive bundle-size delta does not cause failure. + +For agent runs, use `pnpm --silent benchmark:bundle-size:run ...` to omit the package-manager command echo. + +### Phase Timings + +To diagnose measurement time, request a fresh run: + +```bash +pnpm benchmark:bundle-size:run --scenario react-router.minimal --analysis --timings +``` + +The runner directly executes `measure.mjs` on every invocation, rebuilding the selected scenarios and recording fresh timings in `measure.log`. Its package-build step still uses Nx and may restore cached packages. Use `--skip-package-builds` only when those packages are already built and unchanged. + +`measure.mjs` also accepts `--timings` directly. Alternatively, set `BUNDLE_SIZE_TIMINGS=1`. Timing lines go to stderr with the prefix `[bundle-size:timing]` followed by JSON containing `phase`, `durationMs`, and, for scenario phases, `scenario`. They are diagnostics only and do not add fields to the size metrics. + +The cached `pnpm benchmark:bundle-size` / Nx build path can replay terminal output from an earlier execution, including old timing lines. Setting `BUNDLE_SIZE_TIMINGS=1` does not invalidate that cache or guarantee fresh timings. Use the direct runner above for timing investigations; refreshing `current.json` after a cache hit does not remeasure build time. + +- `package-builds`: elapsed time for the package-build invocation, including Nx startup/cache handling; omitted when package builds are skipped. +- `scenario-build`: elapsed time for each scenario's build and cleanup. +- `manifest-resolution`: manifest discovery, parsing, entry selection, and collection of all/initial JS file lists. +- `gzip` / `brotli`: accumulated codec time across distinct files for each scenario, using Node's default compression settings. File reads and summation are excluded; initial files reuse already measured sizes. +- `analysis`: source attribution, when `--analysis` is enabled. +- `overall`: measurement execution through report/history writing. Module imports, process startup, and the outer runner's tests/report command are excluded. + +Phases that start also report elapsed work on failure; compression reports partial accumulated times before propagating the error. Timing records alone do not indicate success. `overall` contains the other phases, so nested timings must not be added to it. The phase breakdown also excludes overhead such as file reads and result writing, so its sum is not expected to equal `overall`. + +## Compare Optimization Candidates + +Before you change the implementation, save a named baseline: + +```bash +pnpm benchmark:bundle-size:run --name baseline --scenario react-router.minimal,react-router.full +``` + +After you change the implementation, compare a candidate against that baseline: + +```bash +pnpm benchmark:bundle-size:run --name candidate --baseline baseline \ + --scenario react-router.minimal,react-router.full \ + --test-projects @tanstack/router-core,@tanstack/react-router \ + -- tests/path.test.ts tests/link.test.tsx +``` + +`--test-projects` runs the selected Nx unit-test targets before measurement. Arguments after `--` go only to those tests. +Tests and measurement run sequentially. Failed tests stop the runner before measurement, so old results cannot produce a misleading diff. +Without `--test-projects`, the runner only measures bundles. Type tests, performance benchmarks, and e2e tests remain separate commands. + +Named runs store their metrics and logs in `benchmarks/bundle-size/results/runs//`. Existing named results cannot be overwritten. +Without `--name`, runs replace `current.json` and the logs for the steps they run. +Emitted bundles still use the shared `dist/` directory. To retain emitted bundles for a candidate, pass a separate `--dist-dir`. + +`--baseline` accepts a run name or a JSON file path, such as `--baseline ./baseline.json`. +With `--scenario`, the comparison reports only the scenarios measured in the current run, even when the baseline contains more scenarios. Selected scenarios missing from the baseline remain visible with `n/a` for their baseline and deltas. +Without `--scenario`, comparisons include scenarios from either result file. +`--results-dir
` changes the results root, including the location of named runs. +Use the same scenario selection and measurement flags for the baseline and candidate. + +For command reference, run: + +```bash +pnpm benchmark:bundle-size:run --help +``` + +## Local Query Tools + +```bash +pnpm benchmark:bundle-size:query --id react-router.minimal +pnpm benchmark:bundle-size:diff --baseline /tmp/base-current.json --id react-router.minimal +pnpm benchmark:bundle-size:history --id react-router.minimal --top-deltas 20 +``` + +Use `pnpm benchmark:bundle-size:diff --baseline /tmp/base-current.json --current-only` to compare only scenarios present in the current results. This applies to both text and `--json` output; an explicit `--id` takes precedence. + +For source attribution, run an analysis build. This uses hidden source maps and writes source estimates into `current.json`; those estimates are for investigation only, not tracking. + +```bash +pnpm benchmark:bundle-size:run --scenario react-router.minimal --analysis +pnpm benchmark:bundle-size:analyze --id react-router.minimal --top-sources 30 +``` + +For a named run, pass `--current benchmarks/bundle-size/results/runs//current.json` to `query`, `diff`, or `analyze`. + +## CI Reporting + +- PR workflow generates a sticky comment with: + - current gzip, initial gzip, raw, and Brotli values + - per-metric deltas from the `main` baseline + - inline sparkline trend +- Pushes to `main` publish historical chart data to GitHub Pages via `benchmark-action/github-action-benchmark`. + +## Manual Update Policy + +When router/start public hooks/components evolve, update the corresponding `*-full/src/routes/__root.tsx` harness to keep full scenarios representative. + +## Backfill Readiness + +The measurement script supports optional interfaces for historical backfilling: + +- `--sha` +- `--measured-at` +- `--append-history` +- `--scenario` +- `--analysis` +- `--sourcemap` +- `--skip-package-builds` + +These are intended for one-off scripts that replay historical commits and append results to the same history dataset shape used for chart generation. +If `--append-history` points at a `data.js` file, output is written as `window.BENCHMARK_DATA = ...` for direct GitHub Pages compatibility. diff --git a/benchmarks/bundle-size/package.json b/benchmarks/bundle-size/package.json new file mode 100644 index 0000000000..ca34cd6cd7 --- /dev/null +++ b/benchmarks/bundle-size/package.json @@ -0,0 +1,84 @@ +{ + "name": "@benchmarks/bundle-size", + "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" + }, + "nx": { + "targets": { + "measure": { + "cache": true, + "inputs": [ + "buildProduction", + "^buildProduction", + "dependentTaskOutputs", + "{workspaceRoot}/scripts/benchmarks/bundle-size/measure.mjs", + "{workspaceRoot}/scripts/benchmarks/bundle-size/compress.mjs", + "{workspaceRoot}/scripts/benchmarks/bundle-size/timings.mjs", + "{workspaceRoot}/scripts/benchmarks/bundle-size/report.mjs", + { + "runtime": "node --version" + } + ], + "outputs": [ + "{projectRoot}/dist", + "{projectRoot}/results/measurements.json", + "{projectRoot}/results/benchmark-action.json" + ], + "dependsOn": [ + { + "projects": [ + "@tanstack/react-router", + "@tanstack/react-router-ssr-query", + "@tanstack/react-start", + "@tanstack/router-plugin", + "@tanstack/solid-router", + "@tanstack/solid-start", + "@tanstack/vue-router", + "@tanstack/vue-start" + ], + "target": "build" + } + ] + }, + "test:unit": { + "dependsOn": [], + "inputs": [ + "default", + "^production", + "{workspaceRoot}/scripts/benchmarks/bundle-size/*.mjs" + ] + } + } + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "@tanstack/react-router-ssr-query": "workspace:^", + "@tanstack/solid-router": "workspace:^", + "@tanstack/vue-router": "workspace:^", + "@tanstack/react-start": "workspace:^", + "@tanstack/solid-start": "workspace:^", + "@tanstack/vue-start": "workspace:^", + "@tanstack/react-query": "catalog:", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "solid-js": "^1.9.10", + "vue": "^3.5.16" + }, + "devDependencies": { + "@rsbuild/core": "^2.3.1", + "@rsbuild/plugin-react": "^2.0.0", + "@tanstack/router-plugin": "workspace:^", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" + } +} diff --git a/benchmarks/bundle-size/results/.gitkeep b/benchmarks/bundle-size/results/.gitkeep new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/benchmarks/bundle-size/results/.gitkeep @@ -0,0 +1 @@ + diff --git a/benchmarks/bundle-size/scenarios/react-router-full/index.html b/benchmarks/bundle-size/scenarios/react-router-full/index.html new file mode 100644 index 0000000000..1117e75467 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-router-full/index.html @@ -0,0 +1,12 @@ + + + + + + react-router-full + + +
+ + + diff --git a/benchmarks/bundle-size/scenarios/react-router-full/src/main.tsx b/benchmarks/bundle-size/scenarios/react-router-full/src/main.tsx new file mode 100644 index 0000000000..ce55e38d84 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-router-full/src/main.tsx @@ -0,0 +1,22 @@ +import ReactDOM from 'react-dom/client' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ + routeTree, + scrollRestoration: true, +}) + +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +const rootElement = document.getElementById('app') +if (!rootElement) { + throw new Error('Root element `#app` not found') +} +if (!rootElement.innerHTML) { + ReactDOM.createRoot(rootElement).render() +} diff --git a/benchmarks/bundle-size/scenarios/react-router-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/react-router-full/src/routes/__root.tsx new file mode 100644 index 0000000000..d8948fdb7e --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-router-full/src/routes/__root.tsx @@ -0,0 +1,185 @@ +import { + Asset, + Await, + Block, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + HeadContent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScriptOnce, + Scripts, + ScrollRestoration, + createLink, + createRootRoute, + linkOptions, + useAwaited, + useBlocker, + useCanGoBack, + useElementScrollRestoration, + useHydrated, + useLinkProps, + useLoaderData, + useLoaderDeps, + useLocation, + useMatch, + useMatchRoute, + useMatches, + useNavigate, + useParams, + useParentMatches, + useChildMatches, + useRouteContext, + useRouter, + useRouterState, + useSearch, + useTags, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + const router = useRouter() + const hydrated = useHydrated() + const awaited = useAwaited({ promise: Promise.resolve('ready') }) + const linkProps = useLinkProps({ to: '/' } as any) + const matchRoute = useMatchRoute() + const matches = useMatches() + const parentMatches = useParentMatches() + const childMatches = useChildMatches() + const match = useMatch({ strict: false, shouldThrow: false } as any) + const loaderDeps = useLoaderDeps({ strict: false } as any) + const loaderData = useLoaderData({ strict: false } as any) + const params = useParams({ strict: false } as any) + const search = useSearch({ strict: false } as any) + const routeContext = useRouteContext({ strict: false } as any) + const routerState = useRouterState({ select: (state) => state.status } as any) + const location = useLocation() + const canGoBack = useCanGoBack() + const navigate = useNavigate() + const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) + const tags = useTags() + + useBlocker({ + shouldBlockFn: () => false, + disabled: true, + withResolver: false, + }) + + const linkFactoryResult = linkOptions({ to: '/' } as any) + const routeMatchResult = matchRoute({ to: '/' } as any) + const SvgLink = createLink('svg') + + const hooksAndComponents = [ + useAwaited, + useHydrated, + useLinkProps, + useMatchRoute, + useMatches, + useParentMatches, + useChildMatches, + useMatch, + useLoaderDeps, + useLoaderData, + useBlocker, + useNavigate, + useParams, + useSearch, + useRouteContext, + useRouter, + useRouterState, + useLocation, + useCanGoBack, + useElementScrollRestoration, + useTags, + Await, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScrollRestoration, + Block, + ScriptOnce, + Asset, + HeadContent, + Scripts, + ] + + ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { + hooksAndComponents, + } + + void awaited + void linkFactoryResult + void matches + void parentMatches + void childMatches + void match + void loaderDeps + void loaderData + void params + void search + void routeContext + void routerState + void location + void canGoBack + void navigate + void scrollEntry + void tags + void routeMatchResult + + return ( + <> + + {'window.__tsr_bundle_size = true'} + + home + + + + {() => } + }> + + + + {() => } + + false} disabled withResolver={false}> + {() => } + + }> + + + + + + + + +
+
hello world
+
+ + ) +} diff --git a/benchmarks/bundle-size/scenarios/react-router-full/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/react-router-full/src/routes/index.tsx new file mode 100644 index 0000000000..aeea465e04 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-router-full/src/routes/index.tsx @@ -0,0 +1,21 @@ +import { + createFileRoute, + retainSearchParams, + stripSearchParams, +} from '@tanstack/react-router' + +const defaultSearch = { page: 1 } + +export const Route = createFileRoute('/')({ + search: { + middlewares: [ + retainSearchParams>(['persist']), + stripSearchParams(defaultSearch), + ], + }, + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/react-router-full/vite.config.ts b/benchmarks/bundle-size/scenarios/react-router-full/vite.config.ts new file mode 100644 index 0000000000..45838fe281 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-router-full/vite.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ + target: 'react', + autoCodeSplitting: true, + }), + react(), + ], +}) diff --git a/benchmarks/bundle-size/scenarios/react-router-minimal/index.html b/benchmarks/bundle-size/scenarios/react-router-minimal/index.html new file mode 100644 index 0000000000..5de4e4e509 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-router-minimal/index.html @@ -0,0 +1,12 @@ + + + + + + react-router-minimal + + +
+ + + diff --git a/benchmarks/bundle-size/scenarios/react-router-minimal/src/main.tsx b/benchmarks/bundle-size/scenarios/react-router-minimal/src/main.tsx new file mode 100644 index 0000000000..667de2cdc7 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-router-minimal/src/main.tsx @@ -0,0 +1,19 @@ +import ReactDOM from 'react-dom/client' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ routeTree }) + +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +const rootElement = document.getElementById('app') +if (!rootElement) { + throw new Error('Root element `#app` not found') +} +if (!rootElement.innerHTML) { + ReactDOM.createRoot(rootElement).render() +} diff --git a/benchmarks/bundle-size/scenarios/react-router-minimal/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/react-router-minimal/src/routes/__root.tsx new file mode 100644 index 0000000000..889395056b --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-router-minimal/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/bundle-size/scenarios/react-router-minimal/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/react-router-minimal/src/routes/index.tsx new file mode 100644 index 0000000000..76fb363538 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-router-minimal/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/react-router-minimal/vite.config.ts b/benchmarks/bundle-size/scenarios/react-router-minimal/vite.config.ts new file mode 100644 index 0000000000..45838fe281 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-router-minimal/vite.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ + target: 'react', + autoCodeSplitting: true, + }), + react(), + ], +}) diff --git a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/router.tsx b/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/router.tsx new file mode 100644 index 0000000000..9d87d8748b --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/router.tsx @@ -0,0 +1,9 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + scrollRestoration: true, + }) +} diff --git a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/routes/__root.tsx new file mode 100644 index 0000000000..ff1da4c304 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/routes/index.tsx new file mode 100644 index 0000000000..a462508abd --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/src/routes/index.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Hydrate } from '@tanstack/react-start' +import { visible } from '@tanstack/react-start/hydration' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return ( + +
hello world
+
+ ) +} diff --git a/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/vite.config.ts b/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/vite.config.ts new file mode 100644 index 0000000000..d4e4cd980d --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-deferred-hydration/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' + +export default defineConfig({ + plugins: [tanstackStart(), viteReact()], +}) diff --git a/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts b/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts new file mode 100644 index 0000000000..349e11bec1 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts @@ -0,0 +1,36 @@ +import { defineConfig } from '@rsbuild/core' +import { pluginReact } from '@rsbuild/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' + +const outDir = process.env.BUNDLE_SIZE_DIST_DIR ?? 'dist-rsbuild' + +export default defineConfig({ + logLevel: 'silent', + plugins: [pluginReact(), tanstackStart()], + output: { + distPath: { + root: outDir, + }, + cleanDistPath: true, + minify: true, + sourceMap: false, + }, + performance: { + printFileSize: false, + }, + environments: { + client: { + output: { + manifest: { + filename: 'manifest.json', + prefix: false, + }, + }, + }, + ssr: { + output: { + manifest: false, + }, + }, + }, +}) diff --git a/benchmarks/bundle-size/scenarios/react-start-full/src/router.tsx b/benchmarks/bundle-size/scenarios/react-start-full/src/router.tsx new file mode 100644 index 0000000000..9d87d8748b --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-full/src/router.tsx @@ -0,0 +1,9 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + scrollRestoration: true, + }) +} diff --git a/benchmarks/bundle-size/scenarios/react-start-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/react-start-full/src/routes/__root.tsx new file mode 100644 index 0000000000..07fd3a40be --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-full/src/routes/__root.tsx @@ -0,0 +1,216 @@ +import { + Asset, + Await, + Block, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + HeadContent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScriptOnce, + Scripts, + ScrollRestoration, + createLink, + createRootRoute, + linkOptions, + useAwaited, + useBlocker, + useCanGoBack, + useElementScrollRestoration, + useHydrated, + useLinkProps, + useLoaderData, + useLoaderDeps, + useLocation, + useMatch, + useMatchRoute, + useMatches, + useNavigate, + useParams, + useParentMatches, + useChildMatches, + useRouteContext, + useRouter, + useRouterState, + useSearch, + useTags, +} from '@tanstack/react-router' +import { + createMiddleware, + createServerFn, + useServerFn, +} from '@tanstack/react-start' + +const requestMiddleware = createMiddleware().server(async ({ next }) => { + return next() +}) + +const functionMiddleware = createMiddleware({ type: 'function' }) + .client(async ({ next }) => { + return next() + }) + .server(async ({ next }) => { + return next() + }) + +const helloServerFn = createServerFn({ method: 'GET' }) + .middleware([requestMiddleware, functionMiddleware]) + .handler(async () => { + return 'hello from server fn' + }) + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + const router = useRouter() + const hydrated = useHydrated() + const awaited = useAwaited({ promise: Promise.resolve('ready') }) + const linkProps = useLinkProps({ to: '/' } as any) + const matchRoute = useMatchRoute() + const matches = useMatches() + const parentMatches = useParentMatches() + const childMatches = useChildMatches() + const match = useMatch({ strict: false, shouldThrow: false } as any) + const loaderDeps = useLoaderDeps({ strict: false } as any) + const loaderData = useLoaderData({ strict: false } as any) + const params = useParams({ strict: false } as any) + const search = useSearch({ strict: false } as any) + const routeContext = useRouteContext({ strict: false } as any) + const routerState = useRouterState({ select: (state) => state.status } as any) + const location = useLocation() + const canGoBack = useCanGoBack() + const navigate = useNavigate() + const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) + const tags = useTags() + const invokeServerFn = useServerFn(helloServerFn) + + useBlocker({ + shouldBlockFn: () => false, + disabled: true, + withResolver: false, + }) + + const linkFactoryResult = linkOptions({ to: '/' } as any) + const routeMatchResult = matchRoute({ to: '/' } as any) + const SvgLink = createLink('svg') + + const startSurface = [createMiddleware, createServerFn, useServerFn] + const hooksAndComponents = [ + useAwaited, + useHydrated, + useLinkProps, + useMatchRoute, + useMatches, + useParentMatches, + useChildMatches, + useMatch, + useLoaderDeps, + useLoaderData, + useBlocker, + useNavigate, + useParams, + useSearch, + useRouteContext, + useRouter, + useRouterState, + useLocation, + useCanGoBack, + useElementScrollRestoration, + useTags, + Await, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScrollRestoration, + Block, + ScriptOnce, + Asset, + HeadContent, + Scripts, + ] + + ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { + hooksAndComponents, + startSurface, + } + + void awaited + void linkFactoryResult + void matches + void parentMatches + void childMatches + void match + void loaderDeps + void loaderData + void params + void search + void routeContext + void routerState + void location + void canGoBack + void navigate + void scrollEntry + void tags + void routeMatchResult + void invokeServerFn + + return ( + + + + + + {'window.__tsr_bundle_size = true'} + + home + + + + {() => } + }> + + + + {() => } + + false} disabled withResolver={false}> + {() => } + + }> + + + + + + + + +
+
hello world
+
+ + + ) +} diff --git a/benchmarks/bundle-size/scenarios/react-start-full/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/react-start-full/src/routes/index.tsx new file mode 100644 index 0000000000..76fb363538 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-full/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/react-start-full/vite.config.ts b/benchmarks/bundle-size/scenarios/react-start-full/vite.config.ts new file mode 100644 index 0000000000..d4e4cd980d --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-full/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' + +export default defineConfig({ + plugins: [tanstackStart(), viteReact()], +}) diff --git a/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts b/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts new file mode 100644 index 0000000000..7d27421d4d --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts @@ -0,0 +1,46 @@ +import { defineConfig } from '@rsbuild/core' +import { pluginReact } from '@rsbuild/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' + +const outDir = process.env.BUNDLE_SIZE_DIST_DIR ?? 'dist-rsbuild' +const clientOutput = process.env.BUNDLE_SIZE_RSB_CLIENT_OUTPUT +const startOptions = clientOutput + ? { + rsbuild: { + client: { + output: clientOutput as 'module' | 'iife', + }, + }, + } + : undefined + +export default defineConfig({ + logLevel: 'silent', + plugins: [pluginReact(), tanstackStart(startOptions)], + output: { + distPath: { + root: outDir, + }, + cleanDistPath: true, + minify: true, + sourceMap: false, + }, + performance: { + printFileSize: false, + }, + environments: { + client: { + output: { + manifest: { + filename: 'manifest.json', + prefix: false, + }, + }, + }, + ssr: { + output: { + manifest: false, + }, + }, + }, +}) diff --git a/benchmarks/bundle-size/scenarios/react-start-minimal/src/router.tsx b/benchmarks/bundle-size/scenarios/react-start-minimal/src/router.tsx new file mode 100644 index 0000000000..9d87d8748b --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-minimal/src/router.tsx @@ -0,0 +1,9 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + scrollRestoration: true, + }) +} diff --git a/benchmarks/bundle-size/scenarios/react-start-minimal/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/react-start-minimal/src/routes/__root.tsx new file mode 100644 index 0000000000..ff1da4c304 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-minimal/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/bundle-size/scenarios/react-start-minimal/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/react-start-minimal/src/routes/index.tsx new file mode 100644 index 0000000000..76fb363538 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-minimal/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/react-start-minimal/vite.config.ts b/benchmarks/bundle-size/scenarios/react-start-minimal/vite.config.ts new file mode 100644 index 0000000000..d4e4cd980d --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-minimal/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' + +export default defineConfig({ + plugins: [tanstackStart(), viteReact()], +}) diff --git a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/router.tsx b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/router.tsx new file mode 100644 index 0000000000..93b95f3148 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/router.tsx @@ -0,0 +1,17 @@ +import { QueryClient } from '@tanstack/react-query' +import { createRouter } from '@tanstack/react-router' +import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + const queryClient = new QueryClient() + const router = createRouter({ + routeTree, + context: { queryClient }, + scrollRestoration: true, + }) + + setupRouterSsrQueryIntegration({ router, queryClient }) + + return router +} diff --git a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/__root.tsx new file mode 100644 index 0000000000..ff1da4c304 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/index.tsx new file mode 100644 index 0000000000..76fb363538 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/react-start-query-integration/vite.config.ts b/benchmarks/bundle-size/scenarios/react-start-query-integration/vite.config.ts new file mode 100644 index 0000000000..d4e4cd980d --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-query-integration/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' + +export default defineConfig({ + plugins: [tanstackStart(), viteReact()], +}) diff --git a/benchmarks/bundle-size/scenarios/solid-router-full/index.html b/benchmarks/bundle-size/scenarios/solid-router-full/index.html new file mode 100644 index 0000000000..80ef4474ee --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-router-full/index.html @@ -0,0 +1,12 @@ + + + + + + solid-router-full + + +
+ + + diff --git a/benchmarks/bundle-size/scenarios/solid-router-full/src/main.tsx b/benchmarks/bundle-size/scenarios/solid-router-full/src/main.tsx new file mode 100644 index 0000000000..505f79aee0 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-router-full/src/main.tsx @@ -0,0 +1,22 @@ +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ + routeTree, + scrollRestoration: true, +}) + +declare module '@tanstack/solid-router' { + interface Register { + router: typeof router + } +} + +const rootElement = document.getElementById('app') +if (!rootElement) { + throw new Error('Root element `#app` not found') +} +if (!rootElement.innerHTML) { + render(() => , rootElement) +} diff --git a/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/__root.tsx new file mode 100644 index 0000000000..f4c2906016 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/__root.tsx @@ -0,0 +1,185 @@ +import { + Asset, + Await, + Block, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + HeadContent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScriptOnce, + Scripts, + ScrollRestoration, + createLink, + createRootRoute, + linkOptions, + useAwaited, + useBlocker, + useCanGoBack, + useChildMatches, + useElementScrollRestoration, + useHydrated, + useLinkProps, + useLoaderData, + useLoaderDeps, + useLocation, + useMatch, + useMatchRoute, + useMatches, + useNavigate, + useParams, + useParentMatches, + useRouteContext, + useRouter, + useRouterState, + useSearch, + useTags, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + const router = useRouter() + const hydrated = useHydrated() + const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) + const linkProps = useLinkProps({ to: '/' } as any) + const matchRoute = useMatchRoute() + const matches = useMatches() + const parentMatches = useParentMatches() + const childMatches = useChildMatches() + const match = useMatch({ strict: false, shouldThrow: false } as any) + const loaderDeps = useLoaderDeps({ strict: false } as any) + const loaderData = useLoaderData({ strict: false } as any) + const params = useParams({ strict: false } as any) + const search = useSearch({ strict: false } as any) + const routeContext = useRouteContext({ strict: false } as any) + const routerState = useRouterState({ select: (state) => state.status } as any) + const location = useLocation() + const canGoBack = useCanGoBack() + const navigate = useNavigate() + const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) + const tags = useTags() + + useBlocker({ + shouldBlockFn: () => false, + disabled: true, + withResolver: false, + }) + + const linkFactoryResult = linkOptions({ to: '/' } as any) + const routeMatchResult = matchRoute({ to: '/' } as any) + const SvgLink = createLink('svg') + + const hooksAndComponents = [ + useAwaited, + useHydrated, + useLinkProps, + useMatchRoute, + useMatches, + useParentMatches, + useChildMatches, + useMatch, + useLoaderDeps, + useLoaderData, + useBlocker, + useNavigate, + useParams, + useSearch, + useRouteContext, + useRouter, + useRouterState, + useLocation, + useCanGoBack, + useElementScrollRestoration, + useTags, + Await, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScrollRestoration, + Block, + ScriptOnce, + Asset, + HeadContent, + Scripts, + ] + + ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { + hooksAndComponents, + } + + void awaited + void linkFactoryResult + void matches() + void parentMatches() + void childMatches() + void match() + void loaderDeps() + void loaderData() + void params() + void search() + void routeContext() + void routerState() + void location() + void canGoBack() + void navigate + void scrollEntry + void tags() + void routeMatchResult() + + return ( + <> + + {'window.__tsr_bundle_size = true'} + + home + + + + {() => } + }> + + + + {() => } + + false} disabled withResolver={false}> + {() => } + + }> + + + + {() => } + + + + +
+
hello world
+
+ + ) +} diff --git a/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/index.tsx new file mode 100644 index 0000000000..de52291cac --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-router-full/src/routes/index.tsx @@ -0,0 +1,21 @@ +import { + createFileRoute, + retainSearchParams, + stripSearchParams, +} from '@tanstack/solid-router' + +const defaultSearch = { page: 1 } + +export const Route = createFileRoute('/')({ + search: { + middlewares: [ + retainSearchParams>(['persist']), + stripSearchParams(defaultSearch), + ], + }, + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/solid-router-full/vite.config.ts b/benchmarks/bundle-size/scenarios/solid-router-full/vite.config.ts new file mode 100644 index 0000000000..9729ada0e8 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-router-full/vite.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vite' +import solid from 'vite-plugin-solid' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ + target: 'solid', + autoCodeSplitting: true, + }), + solid(), + ], +}) diff --git a/benchmarks/bundle-size/scenarios/solid-router-minimal/index.html b/benchmarks/bundle-size/scenarios/solid-router-minimal/index.html new file mode 100644 index 0000000000..29c6fbd787 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-router-minimal/index.html @@ -0,0 +1,12 @@ + + + + + + solid-router-minimal + + +
+ + + diff --git a/benchmarks/bundle-size/scenarios/solid-router-minimal/src/main.tsx b/benchmarks/bundle-size/scenarios/solid-router-minimal/src/main.tsx new file mode 100644 index 0000000000..210120b3f1 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-router-minimal/src/main.tsx @@ -0,0 +1,19 @@ +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ routeTree }) + +declare module '@tanstack/solid-router' { + interface Register { + router: typeof router + } +} + +const rootElement = document.getElementById('app') +if (!rootElement) { + throw new Error('Root element `#app` not found') +} +if (!rootElement.innerHTML) { + render(() => , rootElement) +} diff --git a/benchmarks/bundle-size/scenarios/solid-router-minimal/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/solid-router-minimal/src/routes/__root.tsx new file mode 100644 index 0000000000..cb8d5a688d --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-router-minimal/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/bundle-size/scenarios/solid-router-minimal/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/solid-router-minimal/src/routes/index.tsx new file mode 100644 index 0000000000..01d3b701ae --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-router-minimal/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/solid-router-minimal/vite.config.ts b/benchmarks/bundle-size/scenarios/solid-router-minimal/vite.config.ts new file mode 100644 index 0000000000..9729ada0e8 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-router-minimal/vite.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vite' +import solid from 'vite-plugin-solid' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ + target: 'solid', + autoCodeSplitting: true, + }), + solid(), + ], +}) diff --git a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/router.tsx b/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/router.tsx new file mode 100644 index 0000000000..aa7ead6752 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/router.tsx @@ -0,0 +1,9 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + scrollRestoration: true, + }) +} diff --git a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/__root.tsx new file mode 100644 index 0000000000..e59de72236 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/index.tsx new file mode 100644 index 0000000000..80362386b2 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/src/routes/index.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { Hydrate } from '@tanstack/solid-start' +import { visible } from '@tanstack/solid-start/hydration' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return ( + +
hello world
+
+ ) +} diff --git a/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/vite.config.ts b/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/vite.config.ts new file mode 100644 index 0000000000..0bd21e64f4 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-start-deferred-hydration/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import solid from 'vite-plugin-solid' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' + +export default defineConfig({ + plugins: [tanstackStart(), solid({ ssr: true })], +}) diff --git a/benchmarks/bundle-size/scenarios/solid-start-full/src/router.tsx b/benchmarks/bundle-size/scenarios/solid-start-full/src/router.tsx new file mode 100644 index 0000000000..aa7ead6752 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-start-full/src/router.tsx @@ -0,0 +1,9 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + scrollRestoration: true, + }) +} diff --git a/benchmarks/bundle-size/scenarios/solid-start-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/solid-start-full/src/routes/__root.tsx new file mode 100644 index 0000000000..3daa0019c0 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-start-full/src/routes/__root.tsx @@ -0,0 +1,225 @@ +import { + Asset, + Await, + Block, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + HeadContent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScriptOnce, + Scripts, + ScrollRestoration, + createLink, + createRootRoute, + linkOptions, + useAwaited, + useBlocker, + useCanGoBack, + useChildMatches, + useElementScrollRestoration, + useHydrated, + useLinkProps, + useLoaderData, + useLoaderDeps, + useLocation, + useMatch, + useMatchRoute, + useMatches, + useNavigate, + useParams, + useParentMatches, + useRouteContext, + useRouter, + useRouterState, + useSearch, + useTags, +} from '@tanstack/solid-router' +import { + createMiddleware, + createServerFn, + useServerFn, +} from '@tanstack/solid-start' + +type BundleSizeKeep = { + hooksAndComponents: ReadonlyArray + startSurface: ReadonlyArray +} + +declare global { + var __TANSTACK_BUNDLE_SIZE_KEEP__: BundleSizeKeep | undefined +} + +const requestMiddleware = createMiddleware().server(async ({ next }) => { + return next() +}) + +const functionMiddleware = createMiddleware({ type: 'function' }) + .client(async ({ next }) => { + return next() + }) + .server(async ({ next }) => { + return next() + }) + +const helloServerFn = createServerFn({ method: 'GET' }) + .middleware([requestMiddleware, functionMiddleware]) + .handler(async () => { + return 'hello from server fn' + }) + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + const router = useRouter() + const hydrated = useHydrated() + const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) + const linkProps = useLinkProps({ to: '/' }) + const matchRoute = useMatchRoute() + const matches = useMatches() + const parentMatches = useParentMatches() + const childMatches = useChildMatches() + const match = useMatch({ strict: false, shouldThrow: false }) + const loaderDeps = useLoaderDeps({ strict: false }) + const loaderData = useLoaderData({ strict: false }) + const params = useParams({ strict: false }) + const search = useSearch({ strict: false }) + const routeContext = useRouteContext({ strict: false }) + const routerState = useRouterState({ select: (state) => state.status }) + const location = useLocation() + const canGoBack = useCanGoBack() + const navigate = useNavigate() + const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) + const tags = useTags() + const invokeServerFn = useServerFn(helloServerFn) + + useBlocker({ + shouldBlockFn: () => false, + disabled: true, + withResolver: false, + }) + + const linkFactoryResult = linkOptions({ to: '/' }) + const routeMatchResult = matchRoute({ to: '/' }) + const SvgLink = createLink('svg') + + const startSurface = [createMiddleware, createServerFn, useServerFn] + const hooksAndComponents = [ + useAwaited, + useHydrated, + useLinkProps, + useMatchRoute, + useMatches, + useParentMatches, + useChildMatches, + useMatch, + useLoaderDeps, + useLoaderData, + useBlocker, + useNavigate, + useParams, + useSearch, + useRouteContext, + useRouter, + useRouterState, + useLocation, + useCanGoBack, + useElementScrollRestoration, + useTags, + Await, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScrollRestoration, + Block, + ScriptOnce, + Asset, + HeadContent, + Scripts, + ] + + globalThis.__TANSTACK_BUNDLE_SIZE_KEEP__ = { + hooksAndComponents, + startSurface, + } + + void awaited + void linkFactoryResult + void matches() + void parentMatches() + void childMatches() + void match() + void loaderDeps() + void loaderData() + void params() + void search() + void routeContext() + void routerState() + void location() + void canGoBack() + void navigate + void scrollEntry + void tags() + void routeMatchResult() + void invokeServerFn + + return ( + + + + + + {'window.__tsr_bundle_size = true'} + + home + + + + {() => } + }> + + + + {() => } + + false} disabled withResolver={false}> + {() => } + + }> + + + + {() => } + + + + +
+
hello world
+
+ + + ) +} diff --git a/benchmarks/bundle-size/scenarios/solid-start-full/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/solid-start-full/src/routes/index.tsx new file mode 100644 index 0000000000..01d3b701ae --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-start-full/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/solid-start-full/vite.config.ts b/benchmarks/bundle-size/scenarios/solid-start-full/vite.config.ts new file mode 100644 index 0000000000..0bd21e64f4 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-start-full/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import solid from 'vite-plugin-solid' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' + +export default defineConfig({ + plugins: [tanstackStart(), solid({ ssr: true })], +}) diff --git a/benchmarks/bundle-size/scenarios/solid-start-minimal/src/router.tsx b/benchmarks/bundle-size/scenarios/solid-start-minimal/src/router.tsx new file mode 100644 index 0000000000..aa7ead6752 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-start-minimal/src/router.tsx @@ -0,0 +1,9 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + scrollRestoration: true, + }) +} diff --git a/benchmarks/bundle-size/scenarios/solid-start-minimal/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/solid-start-minimal/src/routes/__root.tsx new file mode 100644 index 0000000000..e59de72236 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-start-minimal/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/bundle-size/scenarios/solid-start-minimal/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/solid-start-minimal/src/routes/index.tsx new file mode 100644 index 0000000000..01d3b701ae --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-start-minimal/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/solid-start-minimal/vite.config.ts b/benchmarks/bundle-size/scenarios/solid-start-minimal/vite.config.ts new file mode 100644 index 0000000000..0bd21e64f4 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/solid-start-minimal/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import solid from 'vite-plugin-solid' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' + +export default defineConfig({ + plugins: [tanstackStart(), solid({ ssr: true })], +}) diff --git a/benchmarks/bundle-size/scenarios/vue-router-full/index.html b/benchmarks/bundle-size/scenarios/vue-router-full/index.html new file mode 100644 index 0000000000..583379e36c --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-router-full/index.html @@ -0,0 +1,12 @@ + + + + + + vue-router-full + + +
+ + + diff --git a/benchmarks/bundle-size/scenarios/vue-router-full/src/main.tsx b/benchmarks/bundle-size/scenarios/vue-router-full/src/main.tsx new file mode 100644 index 0000000000..84d5f29df5 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-router-full/src/main.tsx @@ -0,0 +1,26 @@ +import { createApp } from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ + routeTree, + scrollRestoration: true, +}) + +declare module '@tanstack/vue-router' { + interface Register { + router: typeof router + } +} + +const rootElement = document.getElementById('app') +if (!rootElement) { + throw new Error('Root element `#app` not found') +} +if (!rootElement.innerHTML) { + createApp({ + setup() { + return () => + }, + }).mount('#app') +} diff --git a/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx new file mode 100644 index 0000000000..0ff40aebfc --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx @@ -0,0 +1,196 @@ +import { defineComponent } from 'vue' +import { + Asset, + Await, + Block, + Body, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + HeadContent, + Html, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScriptOnce, + Scripts, + ScrollRestoration, + createLink, + createRootRoute, + linkOptions, + useAwaited, + useBlocker, + useCanGoBack, + useChildMatches, + useElementScrollRestoration, + useLinkProps, + useLoaderData, + useLoaderDeps, + useLocation, + useMatch, + useMatchRoute, + useMatches, + useNavigate, + useParams, + useParentMatches, + useRouteContext, + useRouter, + useRouterState, + useSearch, + useTags, +} from '@tanstack/vue-router' + +const RootComponent = defineComponent({ + setup() { + const router = useRouter() + const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) + const linkProps = useLinkProps({ to: '/' } as any) + const matchRoute = useMatchRoute() + const matches = useMatches() + const parentMatches = useParentMatches() + const childMatches = useChildMatches() + const match = useMatch({ strict: false, shouldThrow: false } as any) + const loaderDeps = useLoaderDeps({ strict: false } as any) + const loaderData = useLoaderData({ strict: false } as any) + const params = useParams({ strict: false } as any) + const search = useSearch({ strict: false } as any) + const routeContext = useRouteContext({ strict: false } as any) + const routerState = useRouterState({ + select: (state) => state.status, + } as any) + const location = useLocation() + const canGoBack = useCanGoBack() + const navigate = useNavigate() + const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) + const tags = useTags() + + useBlocker({ + shouldBlockFn: () => false, + disabled: true, + withResolver: false, + }) + + const linkFactoryResult = linkOptions({ to: '/' } as any) + const routeMatchResult = matchRoute({ to: '/' } as any) + const SvgLink = createLink('svg') + + const hooksAndComponents = [ + useAwaited, + useLinkProps, + useMatchRoute, + useMatches, + useParentMatches, + useChildMatches, + useMatch, + useLoaderDeps, + useLoaderData, + useBlocker, + useNavigate, + useParams, + useSearch, + useRouteContext, + useRouter, + useRouterState, + useLocation, + useCanGoBack, + useElementScrollRestoration, + useTags, + Await, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScrollRestoration, + Block, + ScriptOnce, + Asset, + HeadContent, + Scripts, + Body, + Html, + ] + + ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { + hooksAndComponents, + } + + return () => { + void awaited + void linkFactoryResult + void matches.value + void parentMatches.value + void childMatches.value + void match.value + void loaderDeps.value + void loaderData.value + void params.value + void search.value + void routeContext.value + void routerState.value + void location.value + void canGoBack.value + void navigate + void scrollEntry + void tags() + void routeMatchResult.value + + return ( + <> + + {'window.__tsr_bundle_size = true'} + + home + + + + + {() => } + + }> + + + } + /> + false} disabled withResolver={false}> + {() => } + + }> + + + + + + + + +
+
hello world
+
+ + ) + } + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/index.tsx new file mode 100644 index 0000000000..bf165a33b5 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/index.tsx @@ -0,0 +1,21 @@ +import { + createFileRoute, + retainSearchParams, + stripSearchParams, +} from '@tanstack/vue-router' + +const defaultSearch = { page: 1 } + +export const Route = createFileRoute('/')({ + search: { + middlewares: [ + retainSearchParams>(['persist']), + stripSearchParams(defaultSearch), + ], + }, + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/vue-router-full/vite.config.ts b/benchmarks/bundle-size/scenarios/vue-router-full/vite.config.ts new file mode 100644 index 0000000000..5556bfaa07 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-router-full/vite.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ + target: 'vue', + autoCodeSplitting: true, + }), + vue(), + vueJsx(), + ], +}) diff --git a/benchmarks/bundle-size/scenarios/vue-router-minimal/index.html b/benchmarks/bundle-size/scenarios/vue-router-minimal/index.html new file mode 100644 index 0000000000..e3fe534a21 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-router-minimal/index.html @@ -0,0 +1,12 @@ + + + + + + vue-router-minimal + + +
+ + + diff --git a/benchmarks/bundle-size/scenarios/vue-router-minimal/src/main.tsx b/benchmarks/bundle-size/scenarios/vue-router-minimal/src/main.tsx new file mode 100644 index 0000000000..1fc66c27b1 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-router-minimal/src/main.tsx @@ -0,0 +1,23 @@ +import { createApp } from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ routeTree }) + +declare module '@tanstack/vue-router' { + interface Register { + router: typeof router + } +} + +const rootElement = document.getElementById('app') +if (!rootElement) { + throw new Error('Root element `#app` not found') +} +if (!rootElement.innerHTML) { + createApp({ + setup() { + return () => + }, + }).mount('#app') +} diff --git a/benchmarks/bundle-size/scenarios/vue-router-minimal/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/vue-router-minimal/src/routes/__root.tsx new file mode 100644 index 0000000000..91296e6f84 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-router-minimal/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/bundle-size/scenarios/vue-router-minimal/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/vue-router-minimal/src/routes/index.tsx new file mode 100644 index 0000000000..3899022bdd --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-router-minimal/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/vue-router-minimal/vite.config.ts b/benchmarks/bundle-size/scenarios/vue-router-minimal/vite.config.ts new file mode 100644 index 0000000000..5556bfaa07 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-router-minimal/vite.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ + target: 'vue', + autoCodeSplitting: true, + }), + vue(), + vueJsx(), + ], +}) diff --git a/benchmarks/bundle-size/scenarios/vue-start-full/src/router.tsx b/benchmarks/bundle-size/scenarios/vue-start-full/src/router.tsx new file mode 100644 index 0000000000..9b893112b4 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-start-full/src/router.tsx @@ -0,0 +1,9 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + scrollRestoration: true, + }) +} diff --git a/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/__root.tsx new file mode 100644 index 0000000000..8e8870a2ce --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/__root.tsx @@ -0,0 +1,227 @@ +import { defineComponent } from 'vue' +import { + Asset, + Await, + Block, + Body, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + HeadContent, + Html, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScriptOnce, + Scripts, + ScrollRestoration, + createLink, + createRootRoute, + linkOptions, + useAwaited, + useBlocker, + useCanGoBack, + useChildMatches, + useElementScrollRestoration, + useLinkProps, + useLoaderData, + useLoaderDeps, + useLocation, + useMatch, + useMatchRoute, + useMatches, + useNavigate, + useParams, + useParentMatches, + useRouteContext, + useRouter, + useRouterState, + useSearch, + useTags, +} from '@tanstack/vue-router' +import { + createMiddleware, + createServerFn, + useServerFn, +} from '@tanstack/vue-start' + +const requestMiddleware = createMiddleware().server(async ({ next }) => { + return next() +}) + +const functionMiddleware = createMiddleware({ type: 'function' }) + .client(async ({ next }) => { + return next() + }) + .server(async ({ next }) => { + return next() + }) + +const helloServerFn = createServerFn({ method: 'GET' }) + .middleware([requestMiddleware, functionMiddleware]) + .handler(async () => { + return 'hello from server fn' + }) + +const RootComponent = defineComponent({ + setup() { + const router = useRouter() + const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) + const linkProps = useLinkProps({ to: '/' } as any) + const matchRoute = useMatchRoute() + const matches = useMatches() + const parentMatches = useParentMatches() + const childMatches = useChildMatches() + const match = useMatch({ strict: false, shouldThrow: false } as any) + const loaderDeps = useLoaderDeps({ strict: false } as any) + const loaderData = useLoaderData({ strict: false } as any) + const params = useParams({ strict: false } as any) + const search = useSearch({ strict: false } as any) + const routeContext = useRouteContext({ strict: false } as any) + const routerState = useRouterState({ + select: (state) => state.status, + } as any) + const location = useLocation() + const canGoBack = useCanGoBack() + const navigate = useNavigate() + const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) + const tags = useTags() + const invokeServerFn = useServerFn(helloServerFn) + + useBlocker({ + shouldBlockFn: () => false, + disabled: true, + withResolver: false, + }) + + const linkFactoryResult = linkOptions({ to: '/' } as any) + const routeMatchResult = matchRoute({ to: '/' } as any) + const SvgLink = createLink('svg') + + const startSurface = [createMiddleware, createServerFn, useServerFn] + const hooksAndComponents = [ + useAwaited, + useLinkProps, + useMatchRoute, + useMatches, + useParentMatches, + useChildMatches, + useMatch, + useLoaderDeps, + useLoaderData, + useBlocker, + useNavigate, + useParams, + useSearch, + useRouteContext, + useRouter, + useRouterState, + useLocation, + useCanGoBack, + useElementScrollRestoration, + useTags, + Await, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScrollRestoration, + Block, + ScriptOnce, + Asset, + HeadContent, + Scripts, + Body, + Html, + ] + + ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { + hooksAndComponents, + startSurface, + } + + return () => { + void awaited + void linkFactoryResult + void matches.value + void parentMatches.value + void childMatches.value + void match.value + void loaderDeps.value + void loaderData.value + void params.value + void search.value + void routeContext.value + void routerState.value + void location.value + void canGoBack.value + void navigate + void scrollEntry + void tags() + void routeMatchResult.value + void invokeServerFn + + return ( + + + + + + {'window.__tsr_bundle_size = true'} + + home + + + + + {() => } + + }> + + + } + /> + false} disabled withResolver={false}> + {() => } + + }> + + + + + + + + +
+
hello world
+
+ + + ) + } + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/index.tsx new file mode 100644 index 0000000000..3899022bdd --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/vue-start-full/vite.config.ts b/benchmarks/bundle-size/scenarios/vue-start-full/vite.config.ts new file mode 100644 index 0000000000..3005d7504b --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-start-full/vite.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' + +export default defineConfig({ + plugins: [tanstackStart(), vue(), vueJsx()], +}) diff --git a/benchmarks/bundle-size/scenarios/vue-start-minimal/src/router.tsx b/benchmarks/bundle-size/scenarios/vue-start-minimal/src/router.tsx new file mode 100644 index 0000000000..9b893112b4 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-start-minimal/src/router.tsx @@ -0,0 +1,9 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + scrollRestoration: true, + }) +} diff --git a/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/__root.tsx new file mode 100644 index 0000000000..49422aac38 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/__root.tsx @@ -0,0 +1,26 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/index.tsx new file mode 100644 index 0000000000..3899022bdd --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-start-minimal/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/vue-start-minimal/vite.config.ts b/benchmarks/bundle-size/scenarios/vue-start-minimal/vite.config.ts new file mode 100644 index 0000000000..3005d7504b --- /dev/null +++ b/benchmarks/bundle-size/scenarios/vue-start-minimal/vite.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' + +export default defineConfig({ + plugins: [tanstackStart(), vue(), vueJsx()], +}) diff --git a/benchmarks/bundle-size/tsconfig.json b/benchmarks/bundle-size/tsconfig.json new file mode 100644 index 0000000000..ec9f5c598c --- /dev/null +++ b/benchmarks/bundle-size/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "target": "ESNext", + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "preserve", + "allowJs": true, + "skipLibCheck": true, + "types": ["vite/client"] + }, + "exclude": ["node_modules", "dist"] +} diff --git a/benchmarks/client-nav/README.md b/benchmarks/client-nav/README.md new file mode 100644 index 0000000000..ec34ecc0c1 --- /dev/null +++ b/benchmarks/client-nav/README.md @@ -0,0 +1,307 @@ +# Client Navigation Benchmarks + +Cross-framework client-side CPU benchmarks for: + +- `@tanstack/react-router` +- `@tanstack/solid-router` +- `@tanstack/vue-router` + +The benchmarks run in jsdom against production builds of real apps, and are +tracked in CI by CodSpeed (simulation mode). + +> **Scope:** these benchmarks cover the client router. The hydration +> scenarios also cover DOM hydration and the Router state-restoration path +> used by Start. Start-specific entry-point initialization, streamed payload +> arrival and client server-function calls are not included. Server request work +> is covered by `benchmarks/ssr`. + +## Layout + +- `react/`, `solid/`, `vue/` - baseline benchmark (mixed navigation loop) + Vitest config +- `vitest.react.config.ts`, `vitest.solid.config.ts`, `vitest.vue.config.ts` - per-framework aggregate configs that run the baseline first, then scenario projects +- `scenarios/harness.ts` - shared scenario runner (mount, link-click steps, `onRendered` synchronization) +- `scenarios//shared.ts` - framework-agnostic scenario definition (workload data, step sequence, assertions, bench options) +- `scenarios///` - isolated scenario apps + +Scenario app layout: + +```text +scenarios/// + vite.config.ts + speed.bench.ts + speed.flame.ts + setup.ts + project.json + tsconfig.json + src/ + main.tsx + routeTree.gen.ts + routes/ +``` + +Navigation scenario apps use file-based routing (`@tanstack/router-plugin`) with a +generated `routeTree.gen.ts`, like a regular user app. Each scenario uses one +app per framework instead of sharing routes in the baseline app. This keeps +route-tree size and router options isolated so one scenario cannot shift +another scenario's numbers. The existing baseline apps and bench names stay +stable for CodSpeed continuity. + +## Scenario Responsibilities + +Each scenario isolates one client-side responsibility so benchmark changes can +be attributed to a specific feature area. + +| Scenario | Client-side responsibility | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `react/`, `solid/`, `vue/` baseline apps | Mixed navigation loop: path params, search params, route context, and `useParams`/`useSearch`/`useLoaderData` selector subscriptions. | +| `async-pipeline` | The router's async pipeline via counted 0ms timer hops: async loaders (transition-held navigation), async `beforeLoad` context, and parallel nested async loaders. Component-level `Await`/Suspense is excluded: React 19 throttles Suspense reveals by ~300ms wall-clock, which is inherently non-deterministic to benchmark. | +| `control-flow` | Loader-thrown `redirect` (including a 2-hop chain), `notFound()` with `notFoundComponent`, loader errors with `errorComponent`, and boundary reset on recovery navigation. | +| `head` | `HeadContent` per-navigation work: nested route `head()` evaluation, title/meta/link dedupe across matches, and head tag DOM updates during navigation. | +| `history` | History push/replace/back/forward traversal, location masking, registered-but-never-blocking `useBlocker`, and `useCanGoBack`/`useLocation` subscriptions. | +| `hydration` | Initial DOM hydration: execute the SSR payload, restore `beforeLoad` context and loader data, and hydrate 192 ordinary and eight hash-sensitive Links through their follow-up effects in React and Solid. | +| `link-churn` | Links that depart, stay and mount: 30 `/hub` layout Links stay while 100 `/hub/list` leaf Links leave (alone, or with the layout to `/other`) and remount on return; a search-only change rebuilds updater and `to="."` Links. Unlike `links`, whose root-layout Links never depart. | +| `links` | Per-navigation cost of ~200 mounted ``s: link prop building, active-state recompute across `activeOptions` variants, `activeProps` swaps, and `useMatchRoute` probes (the `MatchRoute` component is avoided: vue-router's implementation leaks one subscription per render). | +| `loaders` | Client loader dispatch: always-stale re-runs (`staleTime: 0`), cached revisits (re-run once per lap by the `invalidate` step), `loaderDeps`-keyed caching, `router.invalidate()`, and `useLoaderData` selectors. | +| `mount` | Cold start: `createRouter` (route-tree processing) + first render + initial `router.load()` + unmount, with a fresh router per mount. | +| `nested-params` | Deep nesting (8 dynamic levels): per-level `params.parse`/`stringify`, `beforeLoad` context accumulation across matches, and per-level `useParams`/`useRouteContext` subscriptions. Param values include characters requiring percent-encoding (as do `route-tree-scale`'s), so segment encode/decode paths run on every navigation. | +| `preload` | Intent preloading from hover events, programmatic `router.preloadRoute`, deterministic preload cache behavior (`defaultPreloadStaleTime: 0`), and commit-time cache maintenance. | +| `rewrites` | Composed client-side location rewrites: router `basepath` plus a locale input/output rewrite pair, running on every href build and location parse (the client analog of the SSR `rewrites` scenario). | +| `route-tree-scale` | Route matching and link-target resolution on a wide (~40 route) tree mixing static, dynamic, prefixed-param, splat, pathless-layout, and route-group paths, with `autoCodeSplitting` enabled so navigations also resolve lazy route chunks. | +| `search-params` | `validateSearch` execution, search middlewares (`retainSearchParams`/`stripSearchParams`), functional search updaters, structural sharing, and `useSearch` selector subscriptions. | + +## Conventions + +The hydration scenario has the separate lifecycle described below. The other +scenarios follow these navigation/mount conventions: + +- Apps are built with `NODE_ENV=production` (`minify: false`) into `dist/app.js`; benches import the built bundle, so production package builds and production JSX output are measured, not dev transforms. +- Scenarios behave like a real user app: navigation happens through `` clicks dispatched on real anchor elements (unless a scenario specifically measures the imperative API), the router uses the default browser history, and `scrollRestoration` is enabled. +- Each benchmark iteration advances a fixed, circular sequence of steps; every step awaits the router's `onRendered` event, so render work is included and steps cannot overlap. No two consecutive steps may target the same location, and the sequence ends back on the initial route. +- Setup runs one warm-up lap through the sequence and asserts each step's observable output (e.g. `document.title`), so a scenario that silently stops doing its work fails instead of reporting a fast time. +- Apps are mounted and disposed outside timing by `benchLifecycle` (`benchmarks/cpu-simulation.ts`): CodSpeed measures a single invocation, so every invocation gets a freshly mounted app; plain `vitest bench` keeps one app per warmup/run phase. Bench functions must be `async` functions, because CodSpeed's Vitest 5 provider awaits only `AsyncFunction`s. +- Determinism: no wall-clock timers (async work is resolved promises or counted `setTimeout(0)` hops), `staleTime`/`gcTime` only ever `0` or effectively-infinite, no `Math.random`/`Date.now` in the measured loop. Scroll restoration uses `getScrollRestorationKey: (location) => location.pathname` so its cache stays bounded (the default random per-entry key grows one cache entry per push navigation). The `mount` scenario opts out of `scrollRestoration` entirely and destroys its history on unmount — both register page-lifetime globals that would leak across its mount/unmount loop. +- Push-only step laps grow jsdom's session-history entry list over a run (jsdom never truncates entries behind the current index). Per-push cost stays O(1) so timings are unaffected; only the `history` scenario needs — and has — a lap that is depth-stationary. +- Calibration: pick per-iteration step counts so a bench's `vitest bench` run stays roughly between 8 and 30 seconds (long enough to average out, short enough for CI). + +## Run + +Run all benchmarks through Nx so dependency builds are part of the graph: + +```bash +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf --outputStyle=stream --skipRemoteCache +``` + +Run framework-specific benchmarks (baseline + all scenarios): + +```bash +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:react --outputStyle=stream --skipRemoteCache +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:solid --outputStyle=stream --skipRemoteCache +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:vue --outputStyle=stream --skipRemoteCache +``` + +Run a single scenario app manually (after building it through Nx): + +```bash +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav--:build:client --outputStyle=stream --skipRemoteCache +cd benchmarks/client-nav && NODE_ENV=production vitest bench --mode benchmark --config ./scenarios///vite.config.ts +``` + +Run framework-specific flame benchmarks (10 second loop, profiled with `@platformatic/flame`, forced to `NODE_ENV=production`): + +```bash +# baseline +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:flame:react --outputStyle=stream --skipRemoteCache +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:flame:solid --outputStyle=stream --skipRemoteCache +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:flame:vue --outputStyle=stream --skipRemoteCache +# scenarios +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav--:test:flame --outputStyle=stream --skipRemoteCache +``` + +Typecheck benchmark sources (baseline + scenarios): + +```bash +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:types --outputStyle=stream --skipRemoteCache +``` + +## Hydration + +`scenarios/hydration/{react,solid}` provide the same initial-hydration +workload: 192 ordinary Links, eight hash-sensitive Links, and three matched +routes with three `beforeLoad` contexts and two loader results. The server URL +has no fragment; the client URL has `#details`, matching half of the hash-sensitive Links. + +```bash +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:perf --outputStyle=stream --skipRemoteCache +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:unit --outputStyle=stream --skipRemoteCache +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:types:client --outputStyle=stream --skipRemoteCache +``` + +Replace `react` with `solid` to run the other adapter. + +The build generates static HTML and its real Router SSR bootstrap scripts once +with `createRequestHandler` and the adapter's streaming renderer. Generation +fully consumes the response and runs outside the CodSpeed action. The measured +worker only reads these artifacts; it does not import a server renderer or start a server. + +Each invocation uses a fresh jsdom window and a fresh evaluation of the complete +production client bundle in that window's realm. HTML parsing, bundle evaluation, +and the initial document lifecycle finish in untimed setup. This resets module +state as well as the DOM, avoiding cached hydration promises and cross-realm +payload objects. The bundle and bootstrap scripts are compiled once, so this +measures a fresh application with warm code, not JavaScript download/parse cost. + +The timed region executes the serialized payload, creates the router and its +small code-based route tree, calls the public client `hydrate` API, and hydrates +the existing DOM with the framework's native renderer: + +- **React:** a separate completion component signals from its post-hydration + effect, after the same snapshot transition as hash-sensitive Links. The harness + awaits that signal and two idle React scheduler turns, then checks the expected + active links. The window's `performance.now()` is frozen, so React's + scheduler yields only to paint after commits, not after 5 ms of wall time, which CPU + instrumentation stretches by a runner-dependent factor. Each sample therefore + uses the same number of scheduler tasks. `Date.now()` is unchanged. A + 60-second watchdog fails a sample that never settles. +- **Solid:** execute the native hydration bootstrap and retain the server's + component/key hierarchy. Wait for mount, the router's rendered event, active-link + effects, and two idle turns. DOM identity assertions include every workload + element so template fallback cannot silently replace server nodes. + +Solid bounds settlement to 100 turns. Ending at the hydration call or the +first mount would miss post-hydration Link updates. +Timer turns use `setImmediate`; scrolling is a no-op +because this is CPU simulation rather than browser layout/paint measurement. + +Untimed assertions verify restored contexts and every loader row, zero client +`beforeLoad`/loader calls, expected hrefs/active state, original DOM-node identity, +working event handlers, and absence of hydration errors. Root unmount, pending +task cancellation, and window disposal also run outside measurement. Diagnostic +tests count Link renders or reactive evaluations and check they stop before the +measured region ends; counting is disabled in the timed workload. + +The bench's own `beforeEach`/`afterEach` hooks prepare and dispose every +sample outside timing, in both CodSpeed and ordinary Vitest runs. Per-phase +setup would let later iterations reuse an already hydrated document. The +hydration unit tests cover repeated fresh-state setup. + +Each scenario is included in its framework's aggregate build and CodSpeed run. +Land the benchmark independently to establish main's baseline before comparing a +hydration optimization. Regenerate each revision's artifacts with identical +fixture data and dependencies; do not pin an old hydration wire format forever. + +## Isolated route-tree construction + +`scenarios/route-tree-scale` measures navigation over an existing tree, not +construction. `scenarios/mount` includes construction but also rendering and +loading. To isolate initialization, use the core construction benchmark: + +```bash +CI=1 NX_DAEMON=false pnpm nx run @tanstack/router-core:test:unit --outputStyle=stream --skipRemoteCache -- bench tests/route-tree-construction.bench.ts --run --testNamePattern=1000.routes --reporter=json --outputFile=/tmp/route-tree-construction.json +``` + +It covers 100, 1,000, and 10,000 static, dynamic, nested, or mixed routes. +The processing-only case creates fresh route objects in an untimed +`beforeEach`, then measures `processRouteTree` and `route.init`. A separate +case includes route-object creation. Neither case measures first interpolation +or navigation. Remove the name filter to run all sizes. Compare identical +benchmark sources in separate checkouts and repeat fresh processes; a cached +router or repeatedly initialized tree is not a construction baseline. + +## Opt-in React Link performance suite + +`link-performance/` contains additional client-navigation and SSR workloads for +focused Link work. They are **not included** in the regular client-nav/SSR +aggregate projects or their CodSpeed build dependencies; they only run through +the dedicated `@benchmarks/react-link-performance` targets below. Use `-t` to +narrow a run to specific cases. + +```bash +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:client --outputStyle=stream --skipRemoteCache -- --run +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:ssr --outputStyle=stream --skipRemoteCache -- --run + +# Select a feature and save the normal Vitest JSON report. +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:client --outputStyle=stream --skipRemoteCache -- --run -t "updater|optional|splat" --reporter=json --outputFile=/tmp/link-perf.json +``` + +The cases cover repeated versus unique destination params, updater functions, +relative/inherited values, search middleware chains, param stringification, +optional and splat segments, encoding, masks, basepath/rewrites, and active +props with structured search. These exercise different costs: cache hits and +misses, parameter cloning, callbacks, middleware traversal, URI encoding, +building masked/public locations, active-state comparisons, and prop merging. +Existing preload, mount, and route-tree-scale scenarios remain responsible for +those separate workloads. + +- **Client:** 200 persistent measured Links, four control Links, and eight + completed navigations per timed batch. The existing client harness checks + hrefs and active state during its untimed warm-up lap. Control navigations + replace the history entry, keeping history size constant. Post-measurement + assertions also check that the measured anchors stayed mounted. +- **SSR:** four fresh-router requests per timed batch, each rendering 200 + measured Links through `RouterProvider` and `renderToString`. Router creation, + `router.load()`, rendering, and history cleanup are included. This isolates + Router SSR Link work, not Start HTTP handling, dehydration, or streaming. + HTML assertions run outside the timed batch. +- Both use the same code-based workload definitions and production JSX/library + builds. The regular Vitest entry points use at least 100 warm-up iterations, + one second of warm-up time, and five-second measurement windows. The client + and server bundles assert their resolved `isServer` environment. React and + React DOM remain external so comparisons can share the same renderer runtime. + These bundles are Node-hosted (jsdom for client mode), not browser deployments. + +Run the gate tests and typecheck separately: + +```bash +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:unit --outputStyle=stream --skipRemoteCache +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:types --outputStyle=stream --skipRemoteCache +``` + +For before/after comparisons, use identical benchmark files and dependencies +on both refs, build each ref through its Nx targets, and alternate fresh +Vitest processes. Report the actual refs, per-case means and relative margins +of error; rerun noisy or borderline results with `-t` rather than interpreting +a small difference as a proven speedup. Client and SSR times have different +batch units and should not be compared directly. + +### Stable paired comparisons + +For regression decisions, prefer the paired runner over a whole-file Vitest +run. It starts a fresh process for every case and repetition, avoiding JIT +feedback from earlier cases. Inside each process, both revisions share the +same production React installation but have separate router/app modules and +router instances. Initialization order alternates between repetitions. +Built snapshots are staged under `node_modules/.cache` so the TypeScript +harness loader does not transpile their emitted JavaScript a second time. + +```bash +# Build the baseline using these same benchmark sources in its own checkout. +# --baseline points to that checkout's link-performance/dist directory. +pnpm nx run @benchmarks/react-link-performance:test:perf:stable -- \ + --baseline /path/to/baseline/benchmarks/client-nav/link-performance/dist \ + --outputJson /tmp/paired-links.json + +# Narrow a comparison, or increase independent process repetitions. +pnpm nx run @benchmarks/react-link-performance:test:perf:stable -- \ + --baseline /path/to/baseline/benchmarks/client-nav/link-performance/dist \ + --mode ssr -t "middleware|unique-params" --repeats 6 \ + --outputJson /tmp/paired-links-ssr.json +``` + +The runner requires Node with `process.threadCpuUsage` (Node 24 works). +It fixes V8 random/hash seeds, warms each variant for at least two seconds +and 100 batches, then alternates ABBA/BAAB blocks calibrated to roughly 500 ms. +Both variants do exactly the same number of batches per block. It records +main-thread CPU time, wall time, and whole-process CPU time; GC during +measurement is not disabled or discarded. + +The default is four independent process repetitions. Reported 95% intervals +use their paired log-ratios, not the many correlated batches as independent +samples. A faster/slower verdict requires CPU and wall intervals to agree. +Intervals overlapping zero or disagreeing metrics are inconclusive; narrow +intervals entirely inside +/-2% are reported separately. + +An A/A calibration uses the current `dist` directory as `--baseline`. Its +intervals should contain zero before trusting similarly sized A/B differences. +Shared-machine contention can still make small changes unresolved. Do not +interpret a point estimate alone, or an inconclusive result, as proof that +a workload is unchanged. diff --git a/benchmarks/client-nav/jsdom.ts b/benchmarks/client-nav/jsdom.ts new file mode 100644 index 0000000000..855c2a2316 --- /dev/null +++ b/benchmarks/client-nav/jsdom.ts @@ -0,0 +1,55 @@ +import { JSDOM } from 'jsdom' + +const dom = new JSDOM('', { + url: 'http://localhost/', +}) + +const { window } = dom + +function setGlobal(name: string, value: unknown) { + Object.defineProperty(globalThis, name, { + value, + configurable: true, + writable: true, + }) +} + +setGlobal('window', window) +setGlobal('document', window.document) +setGlobal('self', window) +setGlobal('navigator', window.navigator) +setGlobal('location', window.location) +setGlobal('history', window.history) +setGlobal('HTMLElement', window.HTMLElement) +setGlobal('Element', window.Element) +setGlobal('SVGElement', window.SVGElement) +setGlobal('DocumentFragment', window.DocumentFragment) +setGlobal('Node', window.Node) +setGlobal('MouseEvent', window.MouseEvent) +setGlobal('MutationObserver', window.MutationObserver) +setGlobal('sessionStorage', window.sessionStorage) +setGlobal('localStorage', window.localStorage) +setGlobal('getComputedStyle', window.getComputedStyle.bind(window)) +setGlobal('addEventListener', window.addEventListener.bind(window)) +setGlobal('removeEventListener', window.removeEventListener.bind(window)) +setGlobal('dispatchEvent', window.dispatchEvent.bind(window)) +setGlobal('CustomEvent', window.CustomEvent) +setGlobal('Event', window.Event) + +setGlobal( + 'requestAnimationFrame', + window.requestAnimationFrame?.bind(window) ?? + ((callback: (time: number) => void) => + setTimeout(() => callback(performance.now()), 16)), +) + +setGlobal( + 'cancelAnimationFrame', + window.cancelAnimationFrame?.bind(window) ?? + ((handle: number) => clearTimeout(handle)), +) + +window.scrollTo = () => {} +setGlobal('scrollTo', () => {}) + +export { window } diff --git a/benchmarks/client-nav/link-performance/cases.ts b/benchmarks/client-nav/link-performance/cases.ts new file mode 100644 index 0000000000..a25eac563b --- /dev/null +++ b/benchmarks/client-nav/link-performance/cases.ts @@ -0,0 +1,360 @@ +export const LINK_CASES = [ + { + id: 'shared-params', + label: 'Shared string params', + description: '200 persistent Links reuse 40 string parameter values.', + }, + { + id: 'unique-params', + label: 'Unique string params', + description: '200 distinct parameter values exceed the 128-result cache.', + }, + { + id: 'param-updaters', + label: 'Parameter updaters', + description: 'Parameter functions derive destinations from current params.', + }, + { + id: 'location-updaters', + label: 'Search, hash and state updaters', + description: + 'Functions derive search, hash and history state from the source.', + }, + { + id: 'relative', + label: 'Relative targets', + description: 'Parent and child targets inherit current params and search.', + }, + { + id: 'middleware', + label: 'Search middleware chain', + description: + 'Retain a tenant, strip a default page and normalize a filter.', + }, + { + id: 'numeric-params', + label: 'Numeric params', + description: 'Parse numbers, update them numerically and stringify them.', + }, + { + id: 'optional-params', + label: 'Optional segments', + description: 'Set, inherit and explicitly clear an optional path segment.', + }, + { + id: 'splats', + label: 'Splat params', + description: 'Empty, multi-segment and encoded splat values.', + }, + { + id: 'encoding', + label: 'Allowed path characters', + description: 'Preserve allowed @, : and + while encoding other characters.', + }, + { + id: 'masks', + label: 'Explicit route masks', + description: + 'Build a different public path and search for each destination.', + }, + { + id: 'rewrites', + label: 'Basepath and rewrites', + description: 'Compose /app with input/output locale path rewrites.', + }, + { + id: 'active', + label: 'Active props and structured search', + description: + 'Exact, fuzzy and search matching with props and render children.', + }, +] as const + +export type LinkCaseId = (typeof LINK_CASES)[number]['id'] + +export const LINK_COUNT = 200 +export const NAVIGATION_STATES = [1, 2, 3, 0] as const +export const LOCALES = ['en', 'fr', 'de', 'es'] as const + +export interface Filter { + tag: string + flags: { open: boolean } + tags: Array +} + +export interface LinkSearch { + page?: number + tenant?: string + filter?: Filter +} + +export function sourceFilter(index: number): Filter { + return { + tag: `group-${index}`, + flags: { open: index % 2 === 0 }, + tags: ['links', `state-${index}`], + } +} + +export function sourceSearch( + caseId: LinkCaseId, + stateIndex: number, +): Partial { + switch (caseId) { + case 'location-updaters': + case 'relative': + case 'middleware': + case 'active': + return { + page: stateIndex + 1, + tenant: `tenant-${stateIndex}`, + filter: sourceFilter(stateIndex), + } + case 'rewrites': + return { tenant: LOCALES[stateIndex] } + default: + return {} + } +} + +export function optionalCategory(stateIndex: number) { + return stateIndex % 2 === 0 ? `category-${stateIndex}` : undefined +} + +export function splatValue(index: number) { + switch (index % 4) { + case 0: + return '' + case 1: + return `folder/sub/file-${index % 40}` + case 2: + return 'a b/100%/caf\u00e9?#' + default: + return 'literal%2F/\u{1f680}' + } +} + +export function encodedValue(index: number) { + return `user-${index % 40}@mail.test:tag+value /?#% caf\u00e9` +} + +function url(pathname: string, search: Partial = {}, hash = '') { + const result = new URL(pathname, 'http://localhost') + for (const [key, value] of Object.entries( + search, + )) { + if (value !== undefined) { + result.searchParams.set( + key, + typeof value === 'object' ? JSON.stringify(value) : String(value), + ) + } + } + result.hash = hash + return result.pathname + result.search + result.hash +} + +function sourcePath(caseId: LinkCaseId, stateIndex: number) { + switch (caseId) { + case 'relative': + return `/teams/team-${stateIndex}/item-${stateIndex}` + case 'numeric-params': + return `/numbers/${stateIndex}` + case 'optional-params': { + const category = optionalCategory(stateIndex) + return `/optional/${category ? `${category}/` : ''}item-${stateIndex}` + } + case 'splats': + return `/files/source/state-${stateIndex}` + case 'encoding': + return `/encoded/source-${stateIndex}` + case 'active': + return `/items/item-${stateIndex}/details` + default: + return `/items/item-${stateIndex}` + } +} + +export function getSourceUrl(caseId: LinkCaseId, stateIndex: number): string { + if (!Number.isInteger(stateIndex) || stateIndex < 0 || stateIndex > 3) { + throw new Error(`Invalid Link performance state: ${stateIndex}`) + } + const pathname = sourcePath(caseId, stateIndex) + if (caseId === 'rewrites') { + return `/app/${LOCALES[stateIndex]}${pathname}` + } + return url( + pathname, + sourceSearch(caseId, stateIndex), + caseId === 'location-updaters' ? `source-${stateIndex}` : '', + ) +} + +// These expectations use fixture values and platform encoding, not router APIs. +function expectedHref(caseId: LinkCaseId, stateIndex: number, index: number) { + const itemId = `item-${index % 40}` + switch (caseId) { + case 'shared-params': + return `/items/${itemId}` + case 'unique-params': + return `/items/item-${index}` + case 'param-updaters': + return `/items/item-${stateIndex}-related-${index % 40}` + case 'location-updaters': + return url( + `/items/item-${stateIndex}`, + { + ...sourceSearch(caseId, stateIndex), + page: stateIndex + 2 + (index % 5), + }, + `source-${stateIndex}-link-${index % 5}`, + ) + case 'relative': + return url( + index % 2 === 0 + ? `/teams/team-${stateIndex}` + : `/teams/team-${stateIndex}/item-${stateIndex}/details`, + sourceSearch(caseId, stateIndex), + ) + case 'middleware': + return url(`/filtered/${itemId}`, { + tenant: `tenant-${stateIndex}`, + page: index % 2 === 0 ? undefined : 2, + filter: { ...sourceFilter(index % 4), tag: `LABEL-${index % 40}` }, + }) + case 'numeric-params': + return `/numbers/${stateIndex + (index % 40)}` + case 'optional-params': { + const category = + index % 3 === 0 + ? 'fixed' + : index % 3 === 1 + ? optionalCategory(stateIndex) + : undefined + return `/optional/${category ? `${category}/` : ''}${itemId}` + } + case 'splats': { + const value = splatValue(index) + return `/files${value ? `/${value.split('/').map(encodeURIComponent).join('/')}` : ''}` + } + case 'encoding': { + const value = encodeURIComponent(encodedValue(index)) + .replaceAll('%40', '@') + .replaceAll('%3A', ':') + .replaceAll('%2B', '+') + return `/encoded/${value}` + } + case 'masks': + return url(`/public/display-${index % 40}`, { + tenant: `mask-${index % 4}`, + }) + case 'rewrites': + return url(`/app/${LOCALES[index % 4]}/items/${itemId}`, { + page: (index % 3) + 1, + }) + case 'active': { + const item = Math.floor(index / 5) + const variant = index % 5 + const search = + variant < 3 + ? { filter: sourceFilter(item % 4) } + : { + ...sourceSearch('active', item % 4), + ...(variant === 4 ? { filter: undefined } : {}), + } + return url(`/items/item-${item}${variant < 2 ? '' : '/details'}`, search) + } + } +} + +function assertUrl( + actualHref: string | null, + expectedHref: string, + label: string, +) { + if (actualHref === null) { + throw new Error(`${label}: missing href`) + } + const actual = new URL(actualHref, 'http://localhost') + const expected = new URL(expectedHref, 'http://localhost') + // Query ordering and the platform's '+' versus '%20' are immaterial here. + const query = (value: URL) => + JSON.stringify([...value.searchParams.entries()].sort()) + if ( + actual.origin !== expected.origin || + actual.pathname !== expected.pathname || + actual.hash !== expected.hash || + query(actual) !== query(expected) + ) { + throw new Error( + `${label}: expected ${expectedHref}, received ${actualHref}`, + ) + } +} + +export function assertScenario( + caseId: LinkCaseId, + stateIndex: number, + root: ParentNode, +): void { + const source = root.querySelector('[data-testid="source-path"]') + if (source?.textContent !== sourcePath(caseId, stateIndex)) { + throw new Error( + `${caseId}/${stateIndex}: unexpected source path ${source?.textContent}`, + ) + } + const links = root.querySelectorAll('a[data-perf-link]') + if (links.length !== LINK_COUNT) { + throw new Error( + `${caseId}: expected ${LINK_COUNT} Links, got ${links.length}`, + ) + } + for (const [index, link] of links.entries()) { + const label = `${caseId}/${stateIndex}/link-${index}` + if (link.getAttribute('data-perf-link') !== String(index)) { + throw new Error(`${label}: unexpected Link order`) + } + assertUrl( + link.getAttribute('href'), + expectedHref(caseId, stateIndex, index), + label, + ) + let active: boolean | undefined + if (caseId === 'shared-params') { + active = index % 40 === stateIndex + } else if (caseId === 'unique-params') { + active = index === stateIndex + } else if (caseId === 'active') { + active = + Math.floor(index / 5) === stateIndex && [0, 2, 3].includes(index % 5) + if ( + link.textContent !== `${index}:${active ? 'active' : 'inactive'}` || + link.getAttribute('title') !== (active ? 'active' : 'inactive') || + !link.classList.contains(active ? 'perf-active' : 'perf-inactive') || + link.style.color !== (active ? 'green' : 'gray') || + link.style.opacity !== '0.8' + ) { + throw new Error( + `${label}: active props or render children are incorrect`, + ) + } + } + if ( + active !== undefined && + (link.getAttribute('data-status') === 'active') !== active + ) { + throw new Error(`${label}: expected active=${active}`) + } + } + for (let state = 0; state < 4; state++) { + const control = root.querySelector(`[data-testid="go-state-${state}"]`) + if (!control || control.hasAttribute('data-perf-link')) { + throw new Error(`${caseId}: missing or measured control Link ${state}`) + } + assertUrl( + control.getAttribute('href'), + getSourceUrl(caseId, state), + `${caseId}/control-${state}`, + ) + } +} diff --git a/benchmarks/client-nav/link-performance/client.bench.ts b/benchmarks/client-nav/link-performance/client.bench.ts new file mode 100644 index 0000000000..f819fab52b --- /dev/null +++ b/benchmarks/client-nav/link-performance/client.bench.ts @@ -0,0 +1,30 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../cpu-simulation' +import { LINK_CASES } from './cases' +import { createClientScenario, samplingOptions } from './scenario' +import type * as App from './src/client' + +const appModulePath = './dist/client/app.js' +const app: typeof App = await import(/* @vite-ignore */ appModulePath) +if (app.serverEnvironment !== false) { + throw new Error('Link client benchmarks must use the production client build') +} + +for (const { id, label } of LINK_CASES) { + test(label, async ({ bench }) => { + const scenario = createClientScenario(app, id) + function finish() { + try { + scenario.check() + } finally { + scenario.teardown() + } + } + + await bench( + `client Links: ${id}`, + benchLifecycle({ before: scenario.setup, after: finish }), + scenario.batch, + ).run(samplingOptions) + }) +} diff --git a/benchmarks/client-nav/link-performance/config.test.ts b/benchmarks/client-nav/link-performance/config.test.ts new file mode 100644 index 0000000000..1a468a3169 --- /dev/null +++ b/benchmarks/client-nav/link-performance/config.test.ts @@ -0,0 +1,42 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createLinkPerformanceConfig } from './config' + +afterEach(() => vi.unstubAllEnvs()) + +describe.each(['client', 'ssr'] as const)('%s configuration', (target) => { + test('discovers only the requested suite', () => { + const config = createLinkPerformanceConfig(target) + expect(config.test?.benchmark?.include).toEqual([`${target}.bench.ts`]) + }) + + test('builds production code for the correct environment', () => { + const config = createLinkPerformanceConfig(target) + expect(config.define?.['process.env.NODE_ENV']).toBe('"production"') + expect(config.resolve?.conditions).toContain( + target === 'ssr' ? 'node' : 'browser', + ) + expect(config.build?.ssr).toBe(target === 'ssr') + expect(config.build?.outDir).toBe(`./dist/${target}`) + expect(config.build?.rolldownOptions?.platform).toBe('node') + expect(config.build?.rolldownOptions?.external).toEqual([ + 'node:module', + 'module', + /^react(?:\/|$)/, + /^react-dom(?:\/|$)/, + ]) + }) + + test('does not retransform built bundles in the test environment', () => { + vi.stubEnv('VITEST', 'true') + const config = createLinkPerformanceConfig(target) + expect(config.ssr?.noExternal).toBeUndefined() + expect(config.test?.server?.deps?.external).toEqual([ + /\/link-performance\/dist\//, + ]) + }) + + test('bundles router dependencies when building app snapshots', () => { + vi.stubEnv('VITEST', undefined) + expect(createLinkPerformanceConfig(target).ssr?.noExternal).toBe(true) + }) +}) diff --git a/benchmarks/client-nav/link-performance/config.ts b/benchmarks/client-nav/link-performance/config.ts new file mode 100644 index 0000000000..416b027057 --- /dev/null +++ b/benchmarks/client-nav/link-performance/config.ts @@ -0,0 +1,69 @@ +import { fileURLToPath } from 'node:url' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import type { UserConfig } from 'vite' + +const root = fileURLToPath(new URL('.', import.meta.url)) + +export function createLinkPerformanceConfig( + target: 'client' | 'ssr', +): UserConfig { + const server = target === 'ssr' + + return { + root, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + react(), + ], + resolve: { + conditions: [server ? 'node' : 'browser', 'production'], + }, + ssr: { + noExternal: process.env.VITEST ? undefined : true, + resolve: { + conditions: ['node', 'production'], + }, + }, + build: { + outDir: `./dist/${target}`, + emptyOutDir: true, + minify: false, + ssr: server, + lib: { + entry: `${root}src/${target}.tsx`, + formats: ['es'], + fileName: 'app', + }, + rolldownOptions: { + platform: 'node', + external: [ + 'node:module', + 'module', + /^react(?:\/|$)/, + /^react-dom(?:\/|$)/, + ], + output: { entryFileNames: 'app.js' }, + }, + }, + test: { + name: `react-link-performance-${target}`, + watch: false, + environment: server ? 'node' : 'jsdom', + setupFiles: server ? [] : ['../vitest.setup.ts'], + server: { + deps: { + external: [/\/link-performance\/dist\//], + }, + }, + include: [], + benchmark: { + include: [`${target}.bench.ts`], + }, + }, + } +} diff --git a/benchmarks/client-nav/link-performance/project.json b/benchmarks/client-nav/link-performance/project.json new file mode 100644 index 0000000000..fd1751c081 --- /dev/null +++ b/benchmarks/client-nav/link-performance/project.json @@ -0,0 +1,103 @@ +{ + "name": "@benchmarks/react-link-performance", + "projectType": "application", + "tags": ["optional-benchmark"], + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config ./link-performance/vite.client.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config ./link-performance/vite.ssr.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:perf:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./link-performance/vite.client.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:perf:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:ssr"], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./link-performance/vite.ssr.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:perf:stable": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client", "build:ssr"], + "options": { + "command": "NODE_ENV=production node --import=@swc-node/register/esm-register benchmarks/client-nav/link-performance/stable-runner.ts" + } + }, + "test:unit": { + "executor": "nx:run-commands", + "inputs": [ + "...", + "{workspaceRoot}/benchmarks/client-nav/scenarios/harness.ts", + "{workspaceRoot}/benchmarks/client-nav/scenarios/links/shared.ts", + "{workspaceRoot}/benchmarks/client-nav/setup-helpers.ts", + "{workspaceRoot}/benchmarks/client-nav/tsconfig.json" + ], + "dependsOn": [ + { + "projects": ["@tanstack/history"], + "target": "build" + } + ], + "options": { + "command": "vitest run --config ./link-performance/vitest.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:types": { + "executor": "nx:run-commands", + "inputs": [ + "...", + "{workspaceRoot}/benchmarks/client-nav/jsdom.ts", + "{workspaceRoot}/benchmarks/client-nav/scenarios/harness.ts", + "{workspaceRoot}/benchmarks/client-nav/scenarios/links/shared.ts", + "{workspaceRoot}/benchmarks/client-nav/setup-helpers.ts", + "{workspaceRoot}/benchmarks/client-nav/tsconfig.json", + "{workspaceRoot}/benchmarks/client-nav/vitest.setup.ts" + ], + "dependsOn": [ + { + "projects": ["@tanstack/react-router"], + "target": "build" + } + ], + "options": { + "command": "tsc -p ./link-performance/tsconfig.json --noEmit", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/link-performance/scenario.ts b/benchmarks/client-nav/link-performance/scenario.ts new file mode 100644 index 0000000000..f1a3fb6df7 --- /dev/null +++ b/benchmarks/client-nav/link-performance/scenario.ts @@ -0,0 +1,114 @@ +import { JSDOM } from 'jsdom' +import { createScenarioSetup } from '../scenarios/harness' +import { ticksPerIteration } from '../scenarios/links/shared' +import { NAVIGATION_STATES, assertScenario, getSourceUrl } from './cases' +import type { LinkCaseId } from './cases' +import type * as ClientApp from './src/client' +import type * as SsrApp from './src/ssr' + +export interface LinkScenario { + setup: () => Promise + batch: () => Promise + check: () => void + teardown: () => void +} + +export const samplingOptions = { + warmupIterations: 100, + warmupTime: 1_000, + time: 5_000, + throws: true, +} + +export function createClientScenario( + app: typeof ClientApp, + id: LinkCaseId, +): LinkScenario { + let mounted: ReturnType | undefined + let container: HTMLElement | undefined + let anchors: Array = [] + const test = createScenarioSetup({ + frameworkLabel: 'React', + mount: (element, history) => { + container = element + mounted = app.mountTestApp(element, history, id) + return mounted + }, + initialUrl: getSourceUrl(id, 0), + steps: NAVIGATION_STATES.map((state) => `go-state-${state}`), + assertAfterStep: (index, element) => { + assertScenario(id, NAVIGATION_STATES[index]!, element) + if (!mounted) { + throw new Error('Link benchmark app was not mounted') + } + mounted.assertStateUpdates() + }, + }) + + return { + async setup() { + await test.before() + if (!container) { + throw new Error('Link benchmark container was not created') + } + anchors = [...container.querySelectorAll('a[data-perf-link]')] + }, + async batch() { + for (let index = 0; index < ticksPerIteration; index++) { + await test.tick() + } + await test.finishBatch() + }, + check() { + if (!container || !mounted) { + throw new Error('Link benchmark app was not mounted') + } + assertScenario(id, 0, container) + mounted.assertStateUpdates() + if (mounted.router.history.length !== 1) { + throw new Error('Link benchmark history must remain bounded') + } + const current = container.querySelectorAll('a[data-perf-link]') + if (anchors.some((anchor, index) => current[index] !== anchor)) { + throw new Error('Measured Links must stay mounted across navigations') + } + }, + teardown: test.after, + } +} + +export function createSsrScenario( + app: typeof SsrApp, + id: LinkCaseId, +): LinkScenario { + let html = '' + let state = 0 + function check() { + const dom = new JSDOM(html) + try { + assertScenario(id, state, dom.window.document) + } finally { + dom.window.close() + } + } + + return { + async setup() { + for (const nextState of NAVIGATION_STATES) { + state = nextState + html = await app.renderScenario(id, state, true) + check() + } + }, + async batch() { + for (const nextState of NAVIGATION_STATES) { + state = nextState + html = await app.renderScenario(id, state) + } + }, + check, + teardown() { + html = '' + }, + } +} diff --git a/benchmarks/client-nav/link-performance/src/client.tsx b/benchmarks/client-nav/link-performance/src/client.tsx new file mode 100644 index 0000000000..a187ee8c15 --- /dev/null +++ b/benchmarks/client-nav/link-performance/src/client.tsx @@ -0,0 +1,29 @@ +import { RouterProvider } from '@tanstack/react-router' +import { isServer } from '@tanstack/router-core/isServer' +import { createRoot } from 'react-dom/client' +import { assertStateUpdates, createLinkRouter } from './workload' +import type { LinkRouter } from './workload' +import type { RouterHistory } from '@tanstack/history' +import type { LinkCaseId } from '../cases' + +export const serverEnvironment: boolean | undefined = isServer + +export function mountTestApp( + container: HTMLElement, + history: RouterHistory, + caseId: LinkCaseId, +): { + router: LinkRouter + unmount: () => void + assertStateUpdates: () => void +} { + const router = createLinkRouter(caseId, history, false) + const root = createRoot(container) + root.render() + + return { + router, + unmount: () => root.unmount(), + assertStateUpdates: () => assertStateUpdates(router), + } +} diff --git a/benchmarks/client-nav/link-performance/src/ssr.tsx b/benchmarks/client-nav/link-performance/src/ssr.tsx new file mode 100644 index 0000000000..491191b1f9 --- /dev/null +++ b/benchmarks/client-nav/link-performance/src/ssr.tsx @@ -0,0 +1,29 @@ +import { RouterProvider, createMemoryHistory } from '@tanstack/react-router' +import { isServer } from '@tanstack/router-core/isServer' +import { renderToString } from 'react-dom/server' +import { getSourceUrl } from '../cases' +import { assertStateUpdates, createLinkRouter } from './workload' +import type { LinkCaseId } from '../cases' + +export const serverEnvironment: boolean | undefined = isServer + +export async function renderScenario( + caseId: LinkCaseId, + stateIndex: number, + verify = false, +) { + const history = createMemoryHistory({ + initialEntries: [getSourceUrl(caseId, stateIndex)], + }) + const router = createLinkRouter(caseId, history, true) + try { + await router.load() + const html = renderToString() + if (verify) { + assertStateUpdates(router) + } + return html + } finally { + history.destroy() + } +} diff --git a/benchmarks/client-nav/link-performance/src/workload.tsx b/benchmarks/client-nav/link-performance/src/workload.tsx new file mode 100644 index 0000000000..8315b85b8b --- /dev/null +++ b/benchmarks/client-nav/link-performance/src/workload.tsx @@ -0,0 +1,506 @@ +import { + Link, + Outlet, + createRootRouteWithContext, + createRoute, + createRouter, + linkOptions, + retainSearchParams, + stripSearchParams, + useLocation, +} from '@tanstack/react-router' +import { + LINK_COUNT, + LOCALES, + encodedValue, + optionalCategory, + sourceFilter, + sourceSearch, + splatValue, +} from '../cases' +import type { RouterHistory } from '@tanstack/history' +import type { SearchSchemaInput } from '@tanstack/react-router' +import type { Filter, LinkCaseId, LinkSearch } from '../cases' + +interface StateUpdates { + calls: number + verifiedCalls: number + input: number + output: number + offset: number +} + +interface WorkloadContext { + caseId: LinkCaseId + stateUpdates: StateUpdates +} + +function isFilter(value: unknown): value is Filter { + return ( + typeof value === 'object' && + value !== null && + 'tag' in value && + typeof value.tag === 'string' && + 'flags' in value && + typeof value.flags === 'object' && + value.flags !== null && + 'open' in value.flags && + typeof value.flags.open === 'boolean' && + 'tags' in value && + Array.isArray(value.tags) && + value.tags.every((tag: unknown) => typeof tag === 'string') + ) +} + +const rootRoute = createRootRouteWithContext()({ + validateSearch: ( + search: Record & SearchSchemaInput, + ): LinkSearch => ({ + page: typeof search.page === 'number' ? search.page : undefined, + tenant: typeof search.tenant === 'string' ? search.tenant : undefined, + filter: isFilter(search.filter) ? search.filter : undefined, + }), + component: RootLayout, +}) + +const itemsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'items/$itemId', +}) +const detailsRoute = createRoute({ + getParentRoute: () => itemsRoute, + path: 'details', +}) +const teamRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'teams/$teamId', +}) +const teamItemRoute = createRoute({ + getParentRoute: () => teamRoute, + path: '$itemId', +}) +const teamDetailsRoute = createRoute({ + getParentRoute: () => teamItemRoute, + path: 'details', +}) +const filteredRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'filtered/$itemId', + search: { + middlewares: [ + retainSearchParams(['tenant']), + stripSearchParams({ page: 1 }), + ({ search, next }) => { + const result = next(search) + return { + ...result, + filter: result.filter + ? { ...result.filter, tag: result.filter.tag.trim().toUpperCase() } + : undefined, + } + }, + ], + }, +}) +const numericRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'numbers/$number', + params: { + parse: ({ number }) => { + const value = Number(number) + if (!Number.isFinite(value)) { + throw new Error(`Invalid number: ${number}`) + } + return { number: value } + }, + stringify: ({ number }) => ({ number: String(number) }), + }, +}) +const optionalRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'optional/{-$category}/$itemId', +}) +const splatRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'files/$', +}) +const encodedRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'encoded/$value', +}) +const publicRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'public/$itemId', +}) + +const routeTree = rootRoute.addChildren([ + itemsRoute.addChildren([detailsRoute]), + teamRoute.addChildren([teamItemRoute.addChildren([teamDetailsRoute])]), + filteredRoute, + numericRoute, + optionalRoute, + splatRoute, + encodedRoute, + publicRoute, +]) + +const localeRewrite = { + input: ({ url }: { url: URL }) => { + const match = /^\/(en|fr|de|es)(\/.*)$/.exec(url.pathname) + if (match) { + url.pathname = match[2]! + url.searchParams.set('tenant', match[1]!) + } + return url + }, + output: ({ url }: { url: URL }) => { + const locale = url.searchParams.get('tenant') + if (locale) { + url.searchParams.delete('tenant') + url.pathname = `/${locale}${url.pathname}` + } + return url + }, +} + +export function createLinkRouter( + caseId: LinkCaseId, + history: RouterHistory, + isServer: boolean, +) { + const context: WorkloadContext = { + caseId, + stateUpdates: { + calls: 0, + verifiedCalls: 0, + input: 0, + output: 0, + offset: 0, + }, + } + return createRouter({ + routeTree, + history, + isServer, + context, + scrollRestoration: false, + defaultPreload: false, + trailingSlash: 'never', + pathParamsAllowedCharacters: + caseId === 'encoding' ? ['@', ':', '+'] : undefined, + ...(caseId === 'rewrites' + ? { basepath: '/app', rewrite: localeRewrite } + : {}), + }) +} + +export type LinkRouter = ReturnType + +declare module '@tanstack/react-router' { + interface Register { + router: LinkRouter + } +} + +declare module '@tanstack/history' { + interface HistoryState { + linkPerfState?: number + } +} + +// Call alongside DOM assertions, outside the timed loop, after each sample. +export function assertStateUpdates(router: LinkRouter): void { + const { caseId, stateUpdates } = router.options.context + if (caseId !== 'location-updaters') { + return + } + const input = router.state.location.state.linkPerfState ?? 0 + if ( + stateUpdates.calls - stateUpdates.verifiedCalls < LINK_COUNT || + stateUpdates.input !== input || + stateUpdates.output !== input + stateUpdates.offset || + stateUpdates.offset < 1 || + stateUpdates.offset > 40 + ) { + throw new Error( + 'Link history-state updaters did not run with current state', + ) + } + stateUpdates.verifiedCalls = stateUpdates.calls +} + +function sourceOptions(caseId: LinkCaseId, stateIndex: number) { + const itemId = `item-${stateIndex}` + const common = { + search: sourceSearch(caseId, stateIndex), + hash: caseId === 'location-updaters' ? `source-${stateIndex}` : '', + state: { linkPerfState: stateIndex + 10 }, + } + switch (caseId) { + case 'relative': + return linkOptions({ + ...common, + to: '/teams/$teamId/$itemId', + params: { teamId: `team-${stateIndex}`, itemId }, + }) + case 'numeric-params': + return linkOptions({ + ...common, + to: '/numbers/$number', + params: { number: stateIndex }, + }) + case 'optional-params': + return linkOptions({ + ...common, + to: '/optional/{-$category}/$itemId', + params: { category: optionalCategory(stateIndex), itemId }, + }) + case 'splats': + return linkOptions({ + ...common, + to: '/files/$', + params: { _splat: `source/state-${stateIndex}` }, + }) + case 'encoding': + return linkOptions({ + ...common, + to: '/encoded/$value', + params: { value: `source-${stateIndex}` }, + }) + case 'active': + return linkOptions({ + ...common, + to: '/items/$itemId/details', + params: { itemId }, + }) + default: + return linkOptions({ + ...common, + to: '/items/$itemId', + params: { itemId }, + }) + } +} + +const indexes = Array.from({ length: LINK_COUNT }, (_, index) => index) +const controls = [0, 1, 2, 3] as const + +function SourcePath() { + const pathname = useLocation({ select: (location) => location.pathname }) + return {pathname} +} + +function RootLayout() { + const context = rootRoute.useRouteContext() + return ( + <> + + +
+ {indexes.map((index) => measuredLink(context, index))} +
+ + + ) +} + +function measuredLink( + { caseId, stateUpdates }: WorkloadContext, + index: number, +) { + const common = { + key: index, + 'data-perf-link': index, + preload: false, + children: `Link ${index}`, + } as const + const itemId = `item-${index % 40}` + switch (caseId) { + case 'shared-params': + case 'unique-params': + return ( + + ) + case 'param-updaters': + return ( + ({ + itemId: `${previous.itemId}-related-${index % 40}`, + })} + /> + ) + case 'location-updaters': + return ( + ({ + ...previous, + page: (previous.page ?? 1) + 1 + (index % 5), + })} + hash={(previous) => `${previous}-link-${index % 5}`} + state={(previous) => { + const input = previous.linkPerfState ?? 0 + const offset = (index % 40) + 1 + const output = input + offset + stateUpdates.calls++ + stateUpdates.input = input + stateUpdates.output = output + stateUpdates.offset = offset + return { ...previous, linkPerfState: output } + }} + /> + ) + case 'relative': + return ( + + ) + case 'middleware': + return ( + + ) + case 'numeric-params': + return ( + ({ number: previous.number + (index % 40) })} + /> + ) + case 'optional-params': + return ( + + ) + case 'splats': + return ( + + ) + case 'encoding': + return ( + + ) + case 'masks': + return ( + + ) + case 'rewrites': + return ( + + ) + case 'active': { + const item = Math.floor(index / 5) + const variant = index % 5 + return ( + ({ + className: 'perf-active', + title: 'active', + style: { color: 'green' }, + })} + inactiveProps={() => ({ + className: 'perf-inactive', + title: 'inactive', + style: { color: 'gray' }, + })} + > + {({ isActive }) => `${index}:${isActive ? 'active' : 'inactive'}`} + + ) + } + } +} diff --git a/benchmarks/client-nav/link-performance/ssr.bench.ts b/benchmarks/client-nav/link-performance/ssr.bench.ts new file mode 100644 index 0000000000..c30084e510 --- /dev/null +++ b/benchmarks/client-nav/link-performance/ssr.bench.ts @@ -0,0 +1,30 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../cpu-simulation' +import { LINK_CASES } from './cases' +import { createSsrScenario, samplingOptions } from './scenario' +import type * as App from './src/ssr' + +const appUrl = new URL('./dist/ssr/app.js', import.meta.url).href +const app: typeof App = await import(/* @vite-ignore */ appUrl) +if (app.serverEnvironment !== true) { + throw new Error('Link SSR benchmarks must use the production server build') +} + +for (const { id, label } of LINK_CASES) { + test(label, async ({ bench }) => { + const scenario = createSsrScenario(app, id) + function finish() { + try { + scenario.check() + } finally { + scenario.teardown() + } + } + + await bench( + `SSR Links: ${id}`, + benchLifecycle({ before: scenario.setup, after: finish }), + scenario.batch, + ).run(samplingOptions) + }) +} diff --git a/benchmarks/client-nav/link-performance/stable-runner.ts b/benchmarks/client-nav/link-performance/stable-runner.ts new file mode 100644 index 0000000000..59ccfa3cb4 --- /dev/null +++ b/benchmarks/client-nav/link-performance/stable-runner.ts @@ -0,0 +1,269 @@ +import { fork } from 'node:child_process' +import { createHash } from 'node:crypto' +import { + copyFileSync, + mkdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { parseArgs } from 'node:util' +import { LINK_CASES } from './cases' +import { createStagingDirectory } from './staging' +import { classify, mean, summarizeRatios } from './statistics' +import type { LinkCaseId } from './cases' +import type { + BlockSample, + Mode, + Variant, + WorkerRequest, + WorkerResponse, +} from './worker-protocol' + +const projectRoot = fileURLToPath(new URL('.', import.meta.url)) +const workspaceRoot = resolve(projectRoot, '../../..') + +function startWorker() { + const child = fork( + fileURLToPath(new URL('./stable-worker.ts', import.meta.url)), + { + cwd: workspaceRoot, + env: { ...process.env, NODE_ENV: 'production' }, + execArgv: [ + '--import=@swc-node/register/esm-register', + '--random-seed=42', + '--hash-seed=42', + ], + stdio: ['ignore', 'ignore', 'pipe', 'ipc'], + }, + ) + let stderr = '' + child.stderr?.on('data', (data: Buffer) => { + stderr = (stderr + data.toString()).slice(-4_096) + }) + + function request(message: WorkerRequest): Promise { + return new Promise((resolveResponse, reject) => { + const timeout = setTimeout(() => { + finish( + new Error(`Sampling worker timed out: ${message.kind}\n${stderr}`), + ) + }, 60_000) + const onExit = (code: number | null) => + finish(new Error(`Sampling worker exited (${code})\n${stderr}`)) + const onError = (error: Error) => finish(error) + const onMessage = (response: WorkerResponse) => { + if (response.kind === 'error') { + finish(new Error(response.message)) + } else { + finish(undefined, response) + } + } + function finish(error?: Error, response?: WorkerResponse) { + clearTimeout(timeout) + child.off('message', onMessage) + child.off('error', onError) + child.off('exit', onExit) + if (error) { + reject(error) + } else if (response) { + resolveResponse(response) + } + } + child.once('message', onMessage) + child.once('error', onError) + child.once('exit', onExit) + child.send(message, (error) => { + if (error) { + finish(error) + } + }) + }) + } + + return { + request, + kill: () => child.kill(), + } +} + +async function sampleReplica( + mode: Mode, + caseId: LinkCaseId, + baseline: string, + current: string, + replica: number, +) { + const worker = startWorker() + const samples: Array> = [[], []] + const ratios: Array<{ cpu: number; wall: number }> = [] + try { + const starts: Array = [] + // Balance module initialization and which variant finishes warming last. + const startupOrder: Array = replica % 2 ? [1, 0] : [0, 1] + for (const index of startupOrder) { + const ready = await worker.request({ + kind: 'init', + mode, + caseId, + bundle: index === 0 ? baseline : current, + variant: index, + }) + if (ready.kind !== 'ready') { + throw new Error('Expected a ready sampling worker') + } + starts[index] = ready.batchMs + } + const iterations = Math.max(1, Math.ceil(500 / Math.min(...starts))) + for (let round = 0; round < 2; round++) { + const block: Array> = [[], []] + const order: Array = + (round + replica) % 2 ? [1, 0, 0, 1] : [0, 1, 1, 0] + for (const index of order) { + const result = await worker.request({ + kind: 'measure', + iterations, + variant: index, + }) + if (result.kind !== 'sample') { + throw new Error('Expected a block measurement') + } + samples[index]!.push(result.sample) + block[index]!.push(result.sample) + } + ratios.push({ + cpu: + mean(block[1]!.map((s) => s.cpuMs)) / + mean(block[0]!.map((s) => s.cpuMs)), + wall: + mean(block[1]!.map((s) => s.wallMs)) / + mean(block[0]!.map((s) => s.wallMs)), + }) + } + const response = await worker.request({ kind: 'stop' }) + if (response.kind !== 'stopped') { + throw new Error('Expected successful post-measurement assertions') + } + return { + iterations, + baseline: samples[0]!, + current: samples[1]!, + cpuRatio: Math.exp(mean(ratios.map((r) => Math.log(r.cpu)))), + wallRatio: Math.exp(mean(ratios.map((r) => Math.log(r.wall)))), + } + } finally { + worker.kill() + } +} + +async function main() { + const { values } = parseArgs({ + options: { + baseline: { type: 'string' }, + current: { type: 'string', default: resolve(projectRoot, 'dist') }, + mode: { type: 'string', default: 'all' }, + repeats: { type: 'string', default: '4' }, + outputJson: { type: 'string' }, + testNamePattern: { type: 'string', short: 't' }, + }, + }) + if (!values.baseline || !values.outputJson) { + throw new Error( + 'Specify --baseline and --outputJson ', + ) + } + const repeats = Number(values.repeats) + if (!Number.isInteger(repeats) || repeats < 3 || repeats > 11) { + throw new Error('--repeats must be an integer between 3 and 11') + } + if (!['all', 'client', 'ssr'].includes(values.mode)) { + throw new Error('--mode must be all, client, or ssr') + } + const modes: Array = + values.mode === 'all' + ? ['client', 'ssr'] + : values.mode === 'client' + ? ['client'] + : ['ssr'] + const pattern = values.testNamePattern + ? new RegExp(values.testNamePattern) + : undefined + const cases = LINK_CASES.filter( + (c) => !pattern || pattern.test(`${c.label} ${c.id}`), + ) + if (!cases.length) { + throw new Error('No Link workloads match the requested pattern') + } + const report: { + protocol: string + node: string + complete: boolean + results: Array<{ + mode: Mode + caseId: LinkCaseId + baselineSha256: string + currentSha256: string + replicas: Array>> + cpu: ReturnType + wall: ReturnType + verdict: ReturnType + }> + } = { + protocol: + 'fresh process per case/replica; shared React runtime; separately loaded router variants; 2 ABBA/BAAB rounds; ~500ms calibrated fixed-work blocks; >=2s/100 batches warmup; main-thread CPU and wall time; fixed V8 random/hash seeds', + node: process.version, + complete: false, + results: [], + } + const output = resolve(values.outputJson) + mkdirSync(dirname(output), { recursive: true }) + const staging = createStagingDirectory() + try { + for (const mode of modes) { + const baselineInput = resolve(values.baseline, mode, 'app.js') + const currentInput = resolve(values.current, mode, 'app.js') + // Both snapshots resolve React from the same package installation. + const baseline = resolve(staging, `baseline-${mode}.mjs`) + const current = resolve(staging, `current-${mode}.mjs`) + copyFileSync(baselineInput, baseline) + copyFileSync(currentInput, current) + const digest = (file: string) => + createHash('sha256').update(readFileSync(file)).digest('hex') + const baselineSha256 = digest(baseline) + const currentSha256 = digest(current) + for (const { id } of cases) { + const replicas = [] + for (let replica = 0; replica < repeats; replica++) { + replicas.push( + await sampleReplica(mode, id, baseline, current, replica), + ) + } + const cpu = summarizeRatios(replicas.map((r) => r.cpuRatio)) + const wall = summarizeRatios(replicas.map((r) => r.wallRatio)) + const verdict = classify(cpu, wall) + report.results.push({ + mode, + caseId: id, + baselineSha256, + currentSha256, + replicas, + cpu, + wall, + verdict, + }) + writeFileSync(output, JSON.stringify(report, null, 2)) + console.log( + `${mode} ${id}: CPU ${cpu.changePercent.toFixed(2)}% [${cpu.low95.toFixed(2)}, ${cpu.high95.toFixed(2)}], wall ${wall.changePercent.toFixed(2)}% [${wall.low95.toFixed(2)}, ${wall.high95.toFixed(2)}] ${verdict}`, + ) + } + } + report.complete = true + writeFileSync(output, JSON.stringify(report, null, 2)) + } finally { + rmSync(staging, { recursive: true }) + } +} + +await main() diff --git a/benchmarks/client-nav/link-performance/stable-worker.test.ts b/benchmarks/client-nav/link-performance/stable-worker.test.ts new file mode 100644 index 0000000000..087b32414a --- /dev/null +++ b/benchmarks/client-nav/link-performance/stable-worker.test.ts @@ -0,0 +1,60 @@ +import { fork } from 'node:child_process' +import { rmdirSync, unlinkSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { expect, test } from 'vitest' +import { createStagingDirectory } from './staging' +import type { WorkerResponse } from './worker-protocol' + +test('loads emitted JavaScript without retranspiling it through SWC', async () => { + const directory = createStagingDirectory() + const bundle = join(directory, 'app.mjs') + const definition = 'function untouched ( ) { return 1 }' + writeFileSync( + bundle, + `${definition}\nawait Promise.resolve()\nthrow new Error(untouched.toString())`, + ) + const worker = fork( + fileURLToPath(new URL('./stable-worker.ts', import.meta.url)), + { + cwd: fileURLToPath(new URL('../../../', import.meta.url)), + execArgv: ['--import=@swc-node/register/esm-register'], + env: { ...process.env, NODE_ENV: 'production' }, + stdio: ['ignore', 'ignore', 'pipe', 'ipc'], + }, + ) + let stderr = '' + worker.stderr?.on('data', (data: Buffer) => { + stderr += data.toString() + }) + let timeout: ReturnType | undefined + try { + const result = new Promise((resolve, reject) => { + worker.once('message', (message: WorkerResponse) => resolve(message)) + worker.once('error', reject) + worker.once('exit', (code) => { + reject(new Error(`Worker exited (${code}): ${stderr}`)) + }) + timeout = setTimeout(() => { + reject(new Error(`Worker timed out: ${stderr}`)) + }, 5_000) + }) + worker.send({ + kind: 'init', + mode: 'ssr', + caseId: 'shared-params', + bundle, + variant: 0, + }) + const response = await result + expect(response.kind).toBe('error') + if (response.kind === 'error') { + expect(response.message).toContain(`Error: ${definition}`) + } + } finally { + clearTimeout(timeout) + worker.kill() + unlinkSync(bundle) + rmdirSync(directory) + } +}) diff --git a/benchmarks/client-nav/link-performance/stable-worker.ts b/benchmarks/client-nav/link-performance/stable-worker.ts new file mode 100644 index 0000000000..d98679dc15 --- /dev/null +++ b/benchmarks/client-nav/link-performance/stable-worker.ts @@ -0,0 +1,112 @@ +import { pathToFileURL } from 'node:url' +import { createClientScenario, createSsrScenario } from './scenario' +import type { LinkScenario } from './scenario' +import type { WorkerRequest, WorkerResponse } from './worker-protocol' +import type * as ClientApp from './src/client' +import type * as SsrApp from './src/ssr' + +const scenarios: Array = [] +const creationOrder: Array = [] +let closeWindow = () => {} + +function reply(response: WorkerResponse) { + if (!process.send) { + throw new Error('The Link sampling worker requires an IPC parent') + } + process.send(response) +} + +async function handle(request: WorkerRequest) { + if (request.kind === 'init') { + if (typeof process.threadCpuUsage !== 'function') { + throw new Error( + 'Stable sampling requires Node.js with process.threadCpuUsage', + ) + } + if (scenarios[request.variant]) { + throw new Error('A worker must only initialize each variant once') + } + let scenario: LinkScenario + const bundleUrl = pathToFileURL(request.bundle) + bundleUrl.searchParams.set('linkPerfVariant', String(request.variant)) + if (request.mode === 'client') { + const { window } = await import('../jsdom') + closeWindow = () => window.close() + const app: typeof ClientApp = await import(bundleUrl.href) + if (app.serverEnvironment !== false) { + throw new Error('Expected a production client bundle') + } + scenario = createClientScenario(app, request.caseId) + } else { + const app: typeof SsrApp = await import(bundleUrl.href) + if (app.serverEnvironment !== true) { + throw new Error('Expected a production SSR bundle') + } + scenario = createSsrScenario(app, request.caseId) + } + scenarios[request.variant] = scenario + creationOrder.push(scenario) + await scenario.setup() + const start = performance.now() + let iterations = 0 + do { + await scenario.batch() + iterations++ + } while (iterations < 100 || performance.now() - start < 2_000) + reply({ + kind: 'ready', + batchMs: (performance.now() - start) / iterations, + }) + return + } + if (request.kind === 'measure') { + const scenario = scenarios[request.variant] + if (!scenario) { + throw new Error('The sampling worker has not been initialized') + } + if (!Number.isInteger(request.iterations) || request.iterations < 1) { + throw new Error('Expected a positive batch count') + } + const cpuStart = process.threadCpuUsage() + const processStart = process.cpuUsage() + const start = performance.now() + for (let index = 0; index < request.iterations; index++) { + await scenario.batch() + } + const wallMs = performance.now() - start + const cpu = process.threadCpuUsage(cpuStart) + const processCpu = process.cpuUsage(processStart) + reply({ + kind: 'sample', + sample: { + iterations: request.iterations, + wallMs: wallMs / request.iterations, + cpuMs: (cpu.user + cpu.system) / 1_000 / request.iterations, + processCpuMs: + (processCpu.user + processCpu.system) / 1_000 / request.iterations, + }, + }) + return + } + try { + for (const scenario of creationOrder) { + scenario.check() + } + } finally { + for (const scenario of creationOrder.reverse()) { + scenario.teardown() + } + closeWindow() + } + reply({ kind: 'stopped' }) +} + +process.on('message', (request: WorkerRequest) => { + void handle(request).catch((error: unknown) => { + reply({ + kind: 'error', + message: + error instanceof Error ? error.stack || error.message : String(error), + }) + }) +}) diff --git a/benchmarks/client-nav/link-performance/staging.ts b/benchmarks/client-nav/link-performance/staging.ts new file mode 100644 index 0000000000..ac07d34c29 --- /dev/null +++ b/benchmarks/client-nav/link-performance/staging.ts @@ -0,0 +1,10 @@ +import { mkdirSync, mkdtempSync } from 'node:fs' +import { resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +export function createStagingDirectory() { + // SWC skips node_modules, leaving the emitted benchmark JavaScript intact. + const root = fileURLToPath(new URL('./node_modules/.cache/', import.meta.url)) + mkdirSync(root, { recursive: true }) + return mkdtempSync(resolve(root, 'link-performance-')) +} diff --git a/benchmarks/client-nav/link-performance/statistics.test.ts b/benchmarks/client-nav/link-performance/statistics.test.ts new file mode 100644 index 0000000000..8f5f37413b --- /dev/null +++ b/benchmarks/client-nav/link-performance/statistics.test.ts @@ -0,0 +1,36 @@ +import { expect, test } from 'vitest' +import { classify, mean, summarizeRatios } from './statistics' + +test('summarizes multiplicative paired changes across process replicas', () => { + const result = summarizeRatios([0.9, 0.9, 0.9, 0.9]) + expect(result.changePercent).toBeCloseTo(-10) + expect(result.low95).toBeCloseTo(-10) + expect(result.high95).toBeCloseTo(-10) + expect(result.replicas).toBe(4) +}) + +test('does not turn opposite noisy runs into a conclusive result', () => { + const result = summarizeRatios([0.9, 1.1, 0.95, 1.05]) + expect(result.low95).toBeLessThan(0) + expect(result.high95).toBeGreaterThan(0) + expect(classify(result, result)).toBe('inconclusive') +}) + +test('requires CPU and wall time to corroborate a direction', () => { + const slower = summarizeRatios([1.08, 1.09, 1.08, 1.09]) + const faster = summarizeRatios([0.9, 0.91, 0.9, 0.91]) + expect(classify(slower, slower)).toBe('slower') + expect(classify(faster, faster)).toBe('faster') + expect(classify(slower, faster)).toBe('inconclusive') + expect(classify(summarizeRatios([1, 1, 1]), summarizeRatios([1, 1, 1]))).toBe( + 'within-2%', + ) +}) + +test('rejects incomplete or invalid sampling data', () => { + expect(() => summarizeRatios([1])).toThrow() + expect(() => summarizeRatios([0, 1])).toThrow() + expect(() => summarizeRatios([NaN, 1])).toThrow() + expect(() => mean([])).toThrow() + expect(() => mean([Infinity])).toThrow() +}) diff --git a/benchmarks/client-nav/link-performance/statistics.ts b/benchmarks/client-nav/link-performance/statistics.ts new file mode 100644 index 0000000000..469bdaf65a --- /dev/null +++ b/benchmarks/client-nav/link-performance/statistics.ts @@ -0,0 +1,57 @@ +const critical95 = [ + 12.7062, 4.3027, 3.1824, 2.7764, 2.5706, 2.4469, 2.3646, 2.306, 2.2622, + 2.2281, +] + +export function mean(values: ReadonlyArray) { + if (!values.length || values.some((value) => !Number.isFinite(value))) { + throw new Error('Expected finite, nonempty samples') + } + return values.reduce((sum, value) => sum + value, 0) / values.length +} + +export function summarizeRatios(ratios: ReadonlyArray) { + if ( + ratios.length < 2 || + ratios.length > 11 || + ratios.some((value) => value <= 0) + ) { + throw new Error('Expected 2-11 independent positive process-replica ratios') + } + const logs = ratios.map(Math.log) + const center = mean(logs) + const variance = + logs.reduce((sum, value) => sum + (value - center) ** 2, 0) / + (logs.length - 1) + // Replicas, not the many correlated batches inside a worker, are the samples. + const margin = + critical95[logs.length - 2]! * Math.sqrt(variance / logs.length) + const percent = (value: number) => (Math.exp(value) - 1) * 100 + return { + changePercent: percent(center), + low95: percent(center - margin), + high95: percent(center + margin), + replicas: ratios.length, + } +} + +export function classify( + cpu: ReturnType, + wall: ReturnType, +) { + if (cpu.low95 > 0 && wall.low95 > 0) { + return 'slower' + } + if (cpu.high95 < 0 && wall.high95 < 0) { + return 'faster' + } + if ( + cpu.low95 >= -2 && + cpu.high95 <= 2 && + wall.low95 >= -2 && + wall.high95 <= 2 + ) { + return 'within-2%' + } + return 'inconclusive' +} diff --git a/benchmarks/client-nav/link-performance/tsconfig.json b/benchmarks/client-nav/link-performance/tsconfig.json new file mode 100644 index 0000000000..fbf230c977 --- /dev/null +++ b/benchmarks/client-nav/link-performance/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "./**/*.ts", + "./**/*.tsx", + "../scenarios/harness.ts", + "../setup-helpers.ts", + "../vitest.setup.ts" + ] +} diff --git a/benchmarks/client-nav/link-performance/vite.client.config.ts b/benchmarks/client-nav/link-performance/vite.client.config.ts new file mode 100644 index 0000000000..1cd45fc45e --- /dev/null +++ b/benchmarks/client-nav/link-performance/vite.client.config.ts @@ -0,0 +1,3 @@ +import { createLinkPerformanceConfig } from './config' + +export default createLinkPerformanceConfig('client') diff --git a/benchmarks/client-nav/link-performance/vite.ssr.config.ts b/benchmarks/client-nav/link-performance/vite.ssr.config.ts new file mode 100644 index 0000000000..f59148eaf6 --- /dev/null +++ b/benchmarks/client-nav/link-performance/vite.ssr.config.ts @@ -0,0 +1,3 @@ +import { createLinkPerformanceConfig } from './config' + +export default createLinkPerformanceConfig('ssr') diff --git a/benchmarks/client-nav/link-performance/vitest.config.ts b/benchmarks/client-nav/link-performance/vitest.config.ts new file mode 100644 index 0000000000..f8454c819d --- /dev/null +++ b/benchmarks/client-nav/link-performance/vitest.config.ts @@ -0,0 +1,11 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + root: fileURLToPath(new URL('.', import.meta.url)), + test: { + watch: false, + environment: 'node', + include: ['*.test.ts'], + }, +}) diff --git a/benchmarks/client-nav/link-performance/worker-protocol.ts b/benchmarks/client-nav/link-performance/worker-protocol.ts new file mode 100644 index 0000000000..474858a529 --- /dev/null +++ b/benchmarks/client-nav/link-performance/worker-protocol.ts @@ -0,0 +1,28 @@ +import type { LinkCaseId } from './cases' + +export type Mode = 'client' | 'ssr' +export type Variant = 0 | 1 + +export type WorkerRequest = + | { + kind: 'init' + mode: Mode + caseId: LinkCaseId + bundle: string + variant: Variant + } + | { kind: 'measure'; iterations: number; variant: Variant } + | { kind: 'stop' } + +export interface BlockSample { + wallMs: number + cpuMs: number + processCpuMs: number + iterations: number +} + +export type WorkerResponse = + | { kind: 'ready'; batchMs: number } + | { kind: 'sample'; sample: BlockSample } + | { kind: 'stopped' } + | { kind: 'error'; message: string } diff --git a/benchmarks/client-nav/package.json b/benchmarks/client-nav/package.json new file mode 100644 index 0000000000..1f878adc67 --- /dev/null +++ b/benchmarks/client-nav/package.json @@ -0,0 +1,245 @@ +{ + "name": "@benchmarks/client-nav", + "private": true, + "type": "module", + "scripts": { + "build:react": "NODE_ENV=production vite build --config ./react/vite.config.ts", + "build:solid": "NODE_ENV=production vite build --config ./solid/vite.config.ts", + "build:vue": "NODE_ENV=production vite build --config ./vue/vite.config.ts", + "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:types": "pnpm run test:types:react && pnpm run test:types:solid && pnpm run test:types:vue", + "test:types:react": "tsc -p ./react/tsconfig.json --noEmit", + "test:types:solid": "tsc -p ./solid/tsconfig.json --noEmit", + "test:types:vue": "tsc -p ./vue/tsconfig.json --noEmit" + }, + "dependencies": { + "@tanstack/history": "workspace:^", + "@tanstack/react-router": "workspace:^", + "@tanstack/router-core": "workspace:^", + "@tanstack/solid-router": "workspace:^", + "@tanstack/vue-router": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "solid-js": "^1.9.10", + "vue": "^3.5.16" + }, + "devDependencies": { + "@platformatic/flame": "^1.6.0", + "@codspeed/vitest-plugin": "^6.0.1", + "@tanstack/router-plugin": "workspace:^", + "@testing-library/react": "^16.2.0", + "@vitejs/plugin-react": "^6.0.1", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "@types/jsdom": "28.0.0", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@typescript/native": "npm:typescript@^7.0.2", + "jsdom": "^29.1.1", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11", + "vitest": "catalog:" + }, + "nx": { + "targets": { + "build:react": { + "cache": false, + "dependsOn": [ + { + "projects": [ + "@tanstack/react-router" + ], + "target": "build" + }, + { + "projects": [ + "@benchmarks/client-nav-async-pipeline-react", + "@benchmarks/client-nav-control-flow-react", + "@benchmarks/client-nav-head-react", + "@benchmarks/client-nav-history-react", + "@benchmarks/client-nav-hydration-react", + "@benchmarks/client-nav-link-churn-react", + "@benchmarks/client-nav-links-react", + "@benchmarks/client-nav-loaders-react", + "@benchmarks/client-nav-mount-react", + "@benchmarks/client-nav-nested-params-react", + "@benchmarks/client-nav-preload-react", + "@benchmarks/client-nav-rewrites-react", + "@benchmarks/client-nav-route-tree-scale-react", + "@benchmarks/client-nav-search-params-react" + ], + "target": "build:client" + } + ] + }, + "build:solid": { + "cache": false, + "dependsOn": [ + { + "projects": [ + "@tanstack/solid-router" + ], + "target": "build" + }, + { + "projects": [ + "@benchmarks/client-nav-async-pipeline-solid", + "@benchmarks/client-nav-control-flow-solid", + "@benchmarks/client-nav-head-solid", + "@benchmarks/client-nav-history-solid", + "@benchmarks/client-nav-hydration-solid", + "@benchmarks/client-nav-link-churn-solid", + "@benchmarks/client-nav-links-solid", + "@benchmarks/client-nav-loaders-solid", + "@benchmarks/client-nav-mount-solid", + "@benchmarks/client-nav-nested-params-solid", + "@benchmarks/client-nav-preload-solid", + "@benchmarks/client-nav-rewrites-solid", + "@benchmarks/client-nav-route-tree-scale-solid", + "@benchmarks/client-nav-search-params-solid" + ], + "target": "build:client" + } + ] + }, + "build:vue": { + "cache": false, + "dependsOn": [ + { + "projects": [ + "@tanstack/vue-router" + ], + "target": "build" + }, + { + "projects": [ + "@benchmarks/client-nav-async-pipeline-vue", + "@benchmarks/client-nav-control-flow-vue", + "@benchmarks/client-nav-head-vue", + "@benchmarks/client-nav-history-vue", + "@benchmarks/client-nav-link-churn-vue", + "@benchmarks/client-nav-links-vue", + "@benchmarks/client-nav-loaders-vue", + "@benchmarks/client-nav-mount-vue", + "@benchmarks/client-nav-nested-params-vue", + "@benchmarks/client-nav-preload-vue", + "@benchmarks/client-nav-rewrites-vue", + "@benchmarks/client-nav-route-tree-scale-vue", + "@benchmarks/client-nav-search-params-vue" + ], + "target": "build:client" + } + ] + }, + "test:perf": { + "cache": false, + "dependsOn": [ + "build:react", + "build:solid", + "build:vue" + ] + }, + "test:flame:react": { + "cache": false, + "dependsOn": [ + "build:react" + ] + }, + "test:flame:solid": { + "cache": false, + "dependsOn": [ + "build:solid" + ] + }, + "test:flame:vue": { + "cache": false, + "dependsOn": [ + "build:vue" + ] + }, + "test:perf:react": { + "cache": false, + "dependsOn": [ + "build:react" + ] + }, + "test:perf:solid": { + "cache": false, + "dependsOn": [ + "build:solid" + ] + }, + "test:perf:vue": { + "cache": false, + "dependsOn": [ + "build:vue" + ] + }, + "test:types": { + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "{workspaceRoot}/benchmarks/cpu-simulation.ts", + "dependentTaskOutputs" + ], + "dependsOn": [ + "^build", + { + "projects": [ + "@benchmarks/client-nav-async-pipeline-react", + "@benchmarks/client-nav-async-pipeline-solid", + "@benchmarks/client-nav-async-pipeline-vue", + "@benchmarks/client-nav-control-flow-react", + "@benchmarks/client-nav-control-flow-solid", + "@benchmarks/client-nav-control-flow-vue", + "@benchmarks/client-nav-head-react", + "@benchmarks/client-nav-head-solid", + "@benchmarks/client-nav-head-vue", + "@benchmarks/client-nav-history-react", + "@benchmarks/client-nav-history-solid", + "@benchmarks/client-nav-history-vue", + "@benchmarks/client-nav-hydration-react", + "@benchmarks/client-nav-hydration-solid", + "@benchmarks/client-nav-link-churn-react", + "@benchmarks/client-nav-links-react", + "@benchmarks/client-nav-link-churn-solid", + "@benchmarks/client-nav-links-solid", + "@benchmarks/client-nav-link-churn-vue", + "@benchmarks/client-nav-links-vue", + "@benchmarks/client-nav-loaders-react", + "@benchmarks/client-nav-loaders-solid", + "@benchmarks/client-nav-loaders-vue", + "@benchmarks/client-nav-mount-react", + "@benchmarks/client-nav-mount-solid", + "@benchmarks/client-nav-mount-vue", + "@benchmarks/client-nav-nested-params-react", + "@benchmarks/client-nav-nested-params-solid", + "@benchmarks/client-nav-nested-params-vue", + "@benchmarks/client-nav-preload-react", + "@benchmarks/client-nav-preload-solid", + "@benchmarks/client-nav-preload-vue", + "@benchmarks/client-nav-rewrites-react", + "@benchmarks/client-nav-route-tree-scale-react", + "@benchmarks/client-nav-rewrites-solid", + "@benchmarks/client-nav-route-tree-scale-solid", + "@benchmarks/client-nav-rewrites-vue", + "@benchmarks/client-nav-route-tree-scale-vue", + "@benchmarks/client-nav-search-params-react", + "@benchmarks/client-nav-search-params-solid", + "@benchmarks/client-nav-search-params-vue" + ], + "target": "test:types:client" + } + ] + } + } + } +} diff --git a/benchmarks/client-nav/react/app.tsx b/benchmarks/client-nav/react/app.tsx new file mode 100644 index 0000000000..cad766e26c --- /dev/null +++ b/benchmarks/client-nav/react/app.tsx @@ -0,0 +1,385 @@ +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + useParams, + useSearch, +} from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' + +function runPerfSelectorComputation(seed: number) { + let value = Math.trunc(seed) | 0 + + for (let index = 0; index < 40; index++) { + value = (value * 1664525 + 1013904223 + index) >>> 0 + } + + return value +} + +function normalizePage(value: unknown) { + const page = Number(value) + return Number.isFinite(page) && page > 0 ? Math.trunc(page) : 1 +} + +function normalizeFilter(value: unknown) { + return typeof value === 'string' && value.length > 0 ? value : 'all' +} + +const noop = () => {} +const rootSelectors = Array.from({ length: 10 }, (_, index) => index) +const routeSelectors = Array.from({ length: 6 }, (_, index) => index) +const linkGroups = Array.from({ length: 4 }, (_, index) => index) + +function RootParamsSubscriber() { + const params = useParams({ + strict: false, + select: (params) => runPerfSelectorComputation(Number(params.id ?? 0)), + }) + + void runPerfSelectorComputation(params) + return null +} + +function RootSearchSubscriber() { + const search = useSearch({ + strict: false, + select: (search) => runPerfSelectorComputation(Number(search.page ?? 0)), + }) + + void runPerfSelectorComputation(search) + return null +} + +function LinkPanel() { + return ( + <> + {linkGroups.map((groupIndex) => { + const itemsId = groupIndex === 0 ? 1 : groupIndex + 2 + const ctxId = groupIndex + 1 + + return ( +
+ + {`Items ${itemsId}`} + + + {`Items 2 alt ${groupIndex}`} + + + {`Search ${groupIndex}`} + + + {`Context ${ctxId}`} + + ({ + page: prev.page + groupIndex + 1, + filter: prev.filter, + junk: `updater-${groupIndex}`, + })} + activeOptions={{ includeSearch: true }} + > + {({ isActive }) => + isActive + ? `Search updater active ${groupIndex}` + : `Search updater inactive ${groupIndex}` + } + +
+ ) + })} + + ) +} + +function Root() { + return ( + <> + {rootSelectors.map((selector) => ( + + ))} + {rootSelectors.map((selector) => ( + + ))} + + + + ) +} + +const rootRoute = createRootRoute({ + component: Root, +}) + +const itemsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + params: { + parse: (params) => ({ + ...params, + id: normalizePage(params.id), + }), + stringify: (params) => ({ + ...params, + id: `${params.id}`, + }), + }, + onEnter: noop, + onStay: noop, + onLeave: noop, + component: ItemsPage, +}) + +const itemDetailsRoute = createRoute({ + getParentRoute: () => itemsRoute, + path: 'details', + component: ItemDetailsPage, +}) + +const searchRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/search', + validateSearch: (search: Record) => ({ + page: normalizePage(search.page), + filter: normalizeFilter(search.filter), + }), + search: { + middlewares: [ + ({ search, next }) => { + const result = next(search) + return { + page: result.page, + filter: result.filter, + } + }, + ], + }, + loaderDeps: ({ search }) => ({ + page: search.page, + filter: search.filter, + }), + loader: ({ deps }) => ({ + seed: deps.page * 31 + deps.filter.length, + checksum: deps.page * 17 + deps.filter.length, + }), + staleTime: 60_000, + gcTime: 60_000, + component: SearchPage, +}) + +const contextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/ctx/$id', + beforeLoad: ({ params }) => ({ + sectionSeed: Number(params.id) * 13 + 1, + }), + component: ContextPage, +}) + +function ItemParamsSubscriber() { + const params = itemsRoute.useParams({ + select: (params) => runPerfSelectorComputation(params.id), + }) + + void runPerfSelectorComputation(params) + return null +} + +function SearchStateSubscriber() { + const search = searchRoute.useSearch({ + select: (search) => + runPerfSelectorComputation(search.page + search.filter.length), + }) + + void runPerfSelectorComputation(search) + return null +} + +function SearchLoaderDepsSubscriber() { + const loaderDeps = searchRoute.useLoaderDeps({ + select: (loaderDeps) => + runPerfSelectorComputation(loaderDeps.page + loaderDeps.filter.length), + }) + + void runPerfSelectorComputation(loaderDeps) + return null +} + +function SearchLoaderDataSubscriber() { + const loaderData = searchRoute.useLoaderData({ + select: (loaderData) => + runPerfSelectorComputation(loaderData.seed + loaderData.checksum), + }) + + void runPerfSelectorComputation(loaderData) + return null +} + +function ContextParamsSubscriber() { + const params = contextRoute.useParams({ + select: (params) => runPerfSelectorComputation(Number(params.id)), + }) + + void runPerfSelectorComputation(params) + return null +} + +function ContextRouteSubscriber() { + const context = contextRoute.useRouteContext({ + select: (context) => runPerfSelectorComputation(context.sectionSeed), + }) + + void runPerfSelectorComputation(context) + return null +} + +function ItemsPage() { + return ( + <> + {routeSelectors.map((selector) => ( + + ))} + + Details + + + Preserve search on item + + + + ) +} + +function ItemDetailsPage() { + return ( + <> + {routeSelectors.map((selector) => ( + + ))} + + Back to item + + + ) +} + +function SearchPage() { + return ( + <> + {routeSelectors.map((selector) => ( + + ))} + {routeSelectors.map((selector) => ( + + ))} + {routeSelectors.map((selector) => ( + + ))} + ({ + page: prev.page + 1, + filter: prev.filter, + junk: 'local-updater', + })} + activeOptions={{ includeSearch: true }} + activeProps={{ className: 'active-link' }} + inactiveProps={{ className: 'inactive-link' }} + > + Next page + + + ) +} + +function ContextPage() { + return ( + <> + {routeSelectors.map((selector) => ( + + ))} + {routeSelectors.map((selector) => ( + + ))} + + ) +} + +export function mountTestApp(container: Element) { + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/items/0'], + }), + scrollRestoration: true, + routeTree: rootRoute.addChildren([ + itemsRoute.addChildren([itemDetailsRoute]), + searchRoute, + contextRoute, + ]), + }) + + const reactRoot = createRoot(container) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/react/setup.ts b/benchmarks/client-nav/react/setup.ts new file mode 100644 index 0000000000..11541383ec --- /dev/null +++ b/benchmarks/client-nav/react/setup.ts @@ -0,0 +1,112 @@ +import type { NavigateOptions } from '@tanstack/router-core' +import type * as App from './app' +import { getRequiredLink, waitForRequiredLink } from '../setup-helpers' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + if (process.env.NODE_ENV !== 'production') { + console.warn( + 'client-nav benchmark is running without NODE_ENV=production; React dev overhead will dominate results.', + ) + } + + let container: HTMLDivElement | undefined = undefined + let unmount: (() => void) | undefined = undefined + let unsub = () => {} + let stepIndex = 0 + let next: () => Promise = () => Promise.reject('Test not initialized') + + async function before() { + stepIndex = 0 + container = document.createElement('div') + document.body.append(container) + + const { router, unmount: dispose } = mountTestApp(container) + unmount = dispose + + let resolveRendered: () => void = () => {} + unsub = router.subscribe('onRendered', () => { + resolveRendered() + }) + + const navigate = (opts: NavigateOptions) => + new Promise((resolveNext) => { + resolveRendered = resolveNext + router.navigate(opts) + }) + + const click = (testId: string, cache?: Map) => + new Promise((resolveNext) => { + resolveRendered = resolveNext + + getRequiredLink(container!, testId, cache).dispatchEvent( + new MouseEvent('click', { + bubbles: true, + cancelable: true, + button: 0, + }), + ) + }) + + await router.load() + + const cachedLinks = new Map() + for (const testId of ['go-items-1', 'go-items-2', 'go-search', 'go-ctx']) { + await waitForRequiredLink(container, testId, cachedLinks) + } + + const steps = [ + () => click('go-items-1', cachedLinks), + () => click('items-details'), + () => + navigate({ + to: '/items/$id/details', + params: { id: 2 }, + replace: true, + }), + () => click('items-parent'), + () => click('go-search', cachedLinks), + () => click('search-next-page'), + () => + navigate({ + to: '/search', + search: { page: 1, filter: 'all' }, + replace: true, + }), + () => click('go-ctx', cachedLinks), + () => + navigate({ + to: '/ctx/$id', + params: { id: 2 }, + replace: true, + }), + () => click('go-items-2', cachedLinks), + ] as const + + next = () => { + const step = steps[stepIndex % steps.length]! + stepIndex += 1 + return step() + } + } + + function after() { + unmount?.() + container?.remove() + unsub() + } + + function tick() { + return next() + } + + return { + before, + tick, + after, + } +} diff --git a/benchmarks/client-nav/react/speed.bench.ts b/benchmarks/client-nav/react/speed.bench.ts new file mode 100644 index 0000000000..944f182734 --- /dev/null +++ b/benchmarks/client-nav/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { setup } from './setup' + +test('client-nav', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-side navigation loop (react)', + { beforeAll: scenario.before, afterAll: scenario.after }, + async () => { + for (let i = 0; i < 10; i++) { + await scenario.tick() + } + }, + ).run({ + warmupIterations: 100, + time: 10_000, + }) +}) diff --git a/benchmarks/client-nav/react/speed.flame.ts b/benchmarks/client-nav/react/speed.flame.ts new file mode 100644 index 0000000000..285ccc63d7 --- /dev/null +++ b/benchmarks/client-nav/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/react/tsconfig.json b/benchmarks/client-nav/react/tsconfig.json new file mode 100644 index 0000000000..046a85af51 --- /dev/null +++ b/benchmarks/client-nav/react/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "allowImportingTsExtensions": true, + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "../jsdom.ts", + "setup.ts", + "vite.config.ts", + "../vitest.setup.ts" + ] +} diff --git a/benchmarks/client-nav/react/vite.config.ts b/benchmarks/client-nav/react/vite.config.ts new file mode 100644 index 0000000000..7df3f80e71 --- /dev/null +++ b/benchmarks/client-nav/react/vite.config.ts @@ -0,0 +1,39 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { cpuSimulationExecArgv } from '../../cpu-simulation' + +// Anchor the project root to the package directory so this config resolves +// identically when run directly and as part of an aggregate `projects` config. +const rootDir = fileURLToPath(new URL('..', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + react(), + ], + build: { + outDir: './react/dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './react/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav (react)', + watch: false, + environment: 'jsdom', + setupFiles: [`${rootDir}vitest.setup.ts`], + benchmark: { include: ['react/speed.bench.ts'] }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/project.json b/benchmarks/client-nav/scenarios/async-pipeline/react/project.json new file mode 100644 index 0000000000..44ab55ccfe --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-async-pipeline-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/async-pipeline/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/setup.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/setup.ts new file mode 100644 index 0000000000..130583b190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts new file mode 100644 index 0000000000..65dab0781e --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-async-pipeline', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-async-pipeline navigation loop (react)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.flame.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx new file mode 100644 index 0000000000..cab86a1272 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx @@ -0,0 +1,39 @@ +import type { RouterHistory } from '@tanstack/history' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + defaultPendingMs: 0, + defaultPendingMinMs: 0, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const reactRoot = createRoot(container) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..9c79bab826 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routeTree.gen.ts @@ -0,0 +1,140 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as NestedRouteImport } from './routes/nested' +import { Route as CtxIdRouteImport } from './routes/ctx.$id' +import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as SlowIdRouteImport } from './routes/slow.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const NestedRoute = NestedRouteImport.update({ + id: '/nested', + path: '/nested', + getParentRoute: () => rootRouteImport, +} as any) +const CtxIdRoute = CtxIdRouteImport.update({ + id: '/ctx/$id', + path: '/ctx/$id', + getParentRoute: () => rootRouteImport, +} as any) +const NestedIdRoute = NestedIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => NestedRoute, +} as any) +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + id: '__root__' | '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + NestedRoute: typeof NestedRouteWithChildren + CtxIdRoute: typeof CtxIdRoute + SlowIdRoute: typeof SlowIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/nested': { + id: '/nested' + path: '/nested' + fullPath: '/nested' + preLoaderRoute: typeof NestedRouteImport + parentRoute: typeof rootRouteImport + } + '/ctx/$id': { + id: '/ctx/$id' + path: '/ctx/$id' + fullPath: '/ctx/$id' + preLoaderRoute: typeof CtxIdRouteImport + parentRoute: typeof rootRouteImport + } + '/nested/$id': { + id: '/nested/$id' + path: '/$id' + fullPath: '/nested/$id' + preLoaderRoute: typeof NestedIdRouteImport + parentRoute: typeof NestedRoute + } + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +interface NestedRouteChildren { + NestedIdRoute: typeof NestedIdRoute +} + +const NestedRouteChildren: NestedRouteChildren = { + NestedIdRoute: NestedIdRoute, +} + +const NestedRouteWithChildren = + NestedRoute._addFileChildren(NestedRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + NestedRoute: NestedRouteWithChildren, + CtxIdRoute: CtxIdRoute, + SlowIdRoute: SlowIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/__root.tsx new file mode 100644 index 0000000000..1cc8566678 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/__root.tsx @@ -0,0 +1,50 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +const ids = ['1', '2'] + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/ctx.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/ctx.$id.tsx new file mode 100644 index 0000000000..d644376b7b --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/ctx.$id.tsx @@ -0,0 +1,29 @@ +import { createFileRoute } from '@tanstack/react-router' +import { + ctxSeedValue, + ctxStateValue, + deferredHops, + hopDelay, +} from '../../../shared' + +export const Route = createFileRoute('/ctx/$id')({ + staleTime: 0, + gcTime: 0, + beforeLoad: async ({ params }) => { + await hopDelay(deferredHops) + return { ctxSeed: ctxSeedValue(params.id) } + }, + loader: ({ params, context }) => { + if (context.ctxSeed !== ctxSeedValue(params.id)) { + throw new Error('beforeLoad context missing in loader') + } + return { value: ctxStateValue(params.id) } + }, + component: CtxPage, +}) + +function CtxPage() { + const data = Route.useLoaderData() + + return
{data.value}
+} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/index.tsx new file mode 100644 index 0000000000..5b6d70e744 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+
home
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.$id.tsx new file mode 100644 index 0000000000..bc002c303f --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.$id.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/react-router' +import { deferredHops, hopDelay, nestedStateValue } from '../../../shared' + +export const Route = createFileRoute('/nested/$id')({ + staleTime: 0, + gcTime: 0, + loader: async ({ params }) => { + await hopDelay(deferredHops) + return { value: nestedStateValue(params.id) } + }, + component: NestedPage, +}) + +function NestedPage() { + const data = Route.useLoaderData() + + return
{data.value}
+} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.tsx new file mode 100644 index 0000000000..443f592373 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.tsx @@ -0,0 +1,23 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { deferredHops, hopDelay, nestedLayoutValue } from '../../../shared' + +export const Route = createFileRoute('/nested')({ + staleTime: 0, + gcTime: 0, + loader: async () => { + await hopDelay(deferredHops) + return { value: nestedLayoutValue() } + }, + component: NestedLayout, +}) + +function NestedLayout() { + const data = Route.useLoaderData() + + return ( +
+
{data.value}
+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/slow.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/slow.$id.tsx new file mode 100644 index 0000000000..4839b0ca6d --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/slow.$id.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/react-router' +import { deferredHops, hopDelay, slowStateValue } from '../../../shared' + +export const Route = createFileRoute('/slow/$id')({ + staleTime: 0, + gcTime: 0, + loader: async ({ params }) => { + await hopDelay(deferredHops) + return { value: slowStateValue(params.id) } + }, + component: SlowPage, +}) + +function SlowPage() { + const data = Route.useLoaderData() + + return
{data.value}
+} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/tsconfig.json b/benchmarks/client-nav/scenarios/async-pipeline/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts new file mode 100644 index 0000000000..e36a5244b1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'react', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav async-pipeline (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/shared.ts b/benchmarks/client-nav/scenarios/async-pipeline/shared.ts new file mode 100644 index 0000000000..02123309b2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/shared.ts @@ -0,0 +1,113 @@ +/** + * Shared definition of the `async-pipeline` scenario: the router's async + * load pipeline — fully async loaders (transition-held navigations), async + * `beforeLoad` context building, and parallel nested async loaders. All async + * work resolves through counted 0ms timer hops so the workload is + * deterministic. The three framework apps consume these builders so the + * workload is identical modulo the rendering layer. + * + * Note: component-level deferred consumption (`Await`/Suspense) is + * intentionally NOT covered. React throttles every Suspense reveal (with or + * without a fallback, including `pendingComponent`) by ~300ms of wall-clock + * time, which cannot be made deterministic; the async work is exercised + * through the router's own pipeline instead. + */ +import type { ScenarioStep } from '../harness' + +/** + * Resolves after exactly `hops` chained macrotask turns. Uses `setImmediate` + * rather than `setTimeout(0)`: both are counted, deterministic event-loop + * turns, but timers cost ~3-4 syscalls per hop (timerfd + epoll) and CodSpeed + * excludes syscall time from the measure — inconsistently past a threshold — + * which destabilized the hop-heavy benches. + */ +export function hopDelay(hops: number): Promise { + let promise = Promise.resolve() + for (let i = 0; i < hops; i++) { + promise = promise.then( + () => new Promise((resolve) => setImmediate(() => resolve())), + ) + } + return promise +} + +/** Number of 0ms hops every async loader/beforeLoad takes before resolving. */ +export const deferredHops = 2 + +function checksum(seed: number) { + let value = seed | 0 + for (let index = 0; index < 20; index++) { + value = (value * 1664525 + 1013904223 + index) >>> 0 + } + return value +} + +export function slowStateValue(id: string) { + return `state-${id}-${checksum(Number(id) * 71 + 3)}` +} + +export function ctxSeedValue(id: string) { + return checksum(Number(id) * 13 + 1) +} + +export function ctxStateValue(id: string) { + return `ctx-${id}-${checksum(ctxSeedValue(id) + 5)}` +} + +export function nestedLayoutValue() { + return `layout-${checksum(97)}` +} + +export function nestedStateValue(id: string) { + return `nested-${id}-${checksum(Number(id) * 41 + 11)}` +} + +function markerText(testId: string) { + return ( + document.querySelector(`[data-testid="${testId}"]`)?.textContent ?? + undefined + ) +} + +function step(testId: string, isSettled: () => boolean): ScenarioStep { + return { type: 'click', testId, isSettled } +} + +export const steps: ReadonlyArray = [ + step('go-slow-1', () => markerText('slow-state') === slowStateValue('1')), + step('go-ctx-1', () => markerText('ctx-state') === ctxStateValue('1')), + step( + 'go-nested-1', + () => + markerText('nested-layout') === nestedLayoutValue() && + markerText('nested-state') === nestedStateValue('1'), + ), + step('go-slow-2', () => markerText('slow-state') === slowStateValue('2')), + step('go-ctx-2', () => markerText('ctx-state') === ctxStateValue('2')), + step( + 'go-nested-2', + () => markerText('nested-state') === nestedStateValue('2'), + ), + step('go-home', () => markerText('home-state') === 'home'), +] + +export function assertStepResult(stepIndex: number) { + const current = steps[stepIndex]! + if (typeof current === 'string' || !('isSettled' in current)) { + return + } + if (!current.isSettled!()) { + throw new Error( + `Unexpected document state after async-pipeline step ${stepIndex}`, + ) + } +} + +// Two laps through the 7-step sequence per benchmark iteration. +export const ticksPerIteration = 14 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/project.json b/benchmarks/client-nav/scenarios/async-pipeline/solid/project.json new file mode 100644 index 0000000000..2fce426b1e --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-async-pipeline-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/async-pipeline/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/setup.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/setup.ts new file mode 100644 index 0000000000..6a46971603 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts new file mode 100644 index 0000000000..acef710469 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-async-pipeline', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-async-pipeline navigation loop (solid)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx new file mode 100644 index 0000000000..4c6d49f501 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx @@ -0,0 +1,36 @@ +import type { RouterHistory } from '@tanstack/history' +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + defaultPendingMs: 0, + defaultPendingMinMs: 0, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const unmount = render(() => , container) + + return { + router, + unmount, + } +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..27b9498b11 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts @@ -0,0 +1,140 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as NestedRouteImport } from './routes/nested' +import { Route as CtxIdRouteImport } from './routes/ctx.$id' +import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as SlowIdRouteImport } from './routes/slow.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const NestedRoute = NestedRouteImport.update({ + id: '/nested', + path: '/nested', + getParentRoute: () => rootRouteImport, +} as any) +const CtxIdRoute = CtxIdRouteImport.update({ + id: '/ctx/$id', + path: '/ctx/$id', + getParentRoute: () => rootRouteImport, +} as any) +const NestedIdRoute = NestedIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => NestedRoute, +} as any) +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + id: '__root__' | '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + NestedRoute: typeof NestedRouteWithChildren + CtxIdRoute: typeof CtxIdRoute + SlowIdRoute: typeof SlowIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/nested': { + id: '/nested' + path: '/nested' + fullPath: '/nested' + preLoaderRoute: typeof NestedRouteImport + parentRoute: typeof rootRouteImport + } + '/ctx/$id': { + id: '/ctx/$id' + path: '/ctx/$id' + fullPath: '/ctx/$id' + preLoaderRoute: typeof CtxIdRouteImport + parentRoute: typeof rootRouteImport + } + '/nested/$id': { + id: '/nested/$id' + path: '/$id' + fullPath: '/nested/$id' + preLoaderRoute: typeof NestedIdRouteImport + parentRoute: typeof NestedRoute + } + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +interface NestedRouteChildren { + NestedIdRoute: typeof NestedIdRoute +} + +const NestedRouteChildren: NestedRouteChildren = { + NestedIdRoute: NestedIdRoute, +} + +const NestedRouteWithChildren = + NestedRoute._addFileChildren(NestedRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + NestedRoute: NestedRouteWithChildren, + CtxIdRoute: CtxIdRoute, + SlowIdRoute: SlowIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..7d3647fee8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/__root.tsx @@ -0,0 +1,46 @@ +import { For } from 'solid-js' +import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +const ids = ['1', '2'] + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/ctx.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/ctx.$id.tsx new file mode 100644 index 0000000000..e757b57b9d --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/ctx.$id.tsx @@ -0,0 +1,29 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { + ctxSeedValue, + ctxStateValue, + deferredHops, + hopDelay, +} from '../../../shared' + +export const Route = createFileRoute('/ctx/$id')({ + staleTime: 0, + gcTime: 0, + beforeLoad: async ({ params }) => { + await hopDelay(deferredHops) + return { ctxSeed: ctxSeedValue(params.id) } + }, + loader: ({ params, context }) => { + if (context.ctxSeed !== ctxSeedValue(params.id)) { + throw new Error('beforeLoad context missing in loader') + } + return { value: ctxStateValue(params.id) } + }, + component: CtxPage, +}) + +function CtxPage() { + const data = Route.useLoaderData() + + return
{data().value}
+} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/index.tsx new file mode 100644 index 0000000000..12907d440d --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+
home
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.$id.tsx new file mode 100644 index 0000000000..5518ccf498 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.$id.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { deferredHops, hopDelay, nestedStateValue } from '../../../shared' + +export const Route = createFileRoute('/nested/$id')({ + staleTime: 0, + gcTime: 0, + loader: async ({ params }) => { + await hopDelay(deferredHops) + return { value: nestedStateValue(params.id) } + }, + component: NestedPage, +}) + +function NestedPage() { + const data = Route.useLoaderData() + + return
{data().value}
+} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.tsx new file mode 100644 index 0000000000..fdc939dc95 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.tsx @@ -0,0 +1,23 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { deferredHops, hopDelay, nestedLayoutValue } from '../../../shared' + +export const Route = createFileRoute('/nested')({ + staleTime: 0, + gcTime: 0, + loader: async () => { + await hopDelay(deferredHops) + return { value: nestedLayoutValue() } + }, + component: NestedLayout, +}) + +function NestedLayout() { + const data = Route.useLoaderData() + + return ( +
+
{data().value}
+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/slow.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/slow.$id.tsx new file mode 100644 index 0000000000..4c229407e1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/slow.$id.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { deferredHops, hopDelay, slowStateValue } from '../../../shared' + +export const Route = createFileRoute('/slow/$id')({ + staleTime: 0, + gcTime: 0, + loader: async ({ params }) => { + await hopDelay(deferredHops) + return { value: slowStateValue(params.id) } + }, + component: SlowPage, +}) + +function SlowPage() { + const data = Route.useLoaderData() + + return
{data().value}
+} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/tsconfig.json b/benchmarks/client-nav/scenarios/async-pipeline/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts new file mode 100644 index 0000000000..214da8042e --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts @@ -0,0 +1,50 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'solid', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav async-pipeline (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/project.json b/benchmarks/client-nav/scenarios/async-pipeline/vue/project.json new file mode 100644 index 0000000000..911bb61e38 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-async-pipeline-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/async-pipeline/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/setup.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/setup.ts new file mode 100644 index 0000000000..97b74b3892 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts new file mode 100644 index 0000000000..f0fd3e58df --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-async-pipeline', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-async-pipeline navigation loop (vue)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx new file mode 100644 index 0000000000..e1bfa5965f --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx @@ -0,0 +1,43 @@ +import type { RouterHistory } from '@tanstack/history' +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + defaultPendingMs: 0, + defaultPendingMinMs: 0, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..66b9efd7aa --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts @@ -0,0 +1,140 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as NestedRouteImport } from './routes/nested' +import { Route as CtxIdRouteImport } from './routes/ctx.$id' +import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as SlowIdRouteImport } from './routes/slow.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const NestedRoute = NestedRouteImport.update({ + id: '/nested', + path: '/nested', + getParentRoute: () => rootRouteImport, +} as any) +const CtxIdRoute = CtxIdRouteImport.update({ + id: '/ctx/$id', + path: '/ctx/$id', + getParentRoute: () => rootRouteImport, +} as any) +const NestedIdRoute = NestedIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => NestedRoute, +} as any) +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + id: '__root__' | '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + NestedRoute: typeof NestedRouteWithChildren + CtxIdRoute: typeof CtxIdRoute + SlowIdRoute: typeof SlowIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/nested': { + id: '/nested' + path: '/nested' + fullPath: '/nested' + preLoaderRoute: typeof NestedRouteImport + parentRoute: typeof rootRouteImport + } + '/ctx/$id': { + id: '/ctx/$id' + path: '/ctx/$id' + fullPath: '/ctx/$id' + preLoaderRoute: typeof CtxIdRouteImport + parentRoute: typeof rootRouteImport + } + '/nested/$id': { + id: '/nested/$id' + path: '/$id' + fullPath: '/nested/$id' + preLoaderRoute: typeof NestedIdRouteImport + parentRoute: typeof NestedRoute + } + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +interface NestedRouteChildren { + NestedIdRoute: typeof NestedIdRoute +} + +const NestedRouteChildren: NestedRouteChildren = { + NestedIdRoute: NestedIdRoute, +} + +const NestedRouteWithChildren = + NestedRoute._addFileChildren(NestedRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + NestedRoute: NestedRouteWithChildren, + CtxIdRoute: CtxIdRoute, + SlowIdRoute: SlowIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..c477ab7e68 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/__root.tsx @@ -0,0 +1,53 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' + +const ids = ['1', '2'] + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/ctx.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/ctx.$id.tsx new file mode 100644 index 0000000000..d995f1ff6c --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/ctx.$id.tsx @@ -0,0 +1,32 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { + ctxSeedValue, + ctxStateValue, + deferredHops, + hopDelay, +} from '../../../shared' + +const CtxPage = Vue.defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () =>
{data.value.value}
+ }, +}) + +export const Route = createFileRoute('/ctx/$id')({ + staleTime: 0, + gcTime: 0, + beforeLoad: async ({ params }) => { + await hopDelay(deferredHops) + return { ctxSeed: ctxSeedValue(params.id) } + }, + loader: ({ params, context }) => { + if (context.ctxSeed !== ctxSeedValue(params.id)) { + throw new Error('beforeLoad context missing in loader') + } + return { value: ctxStateValue(params.id) } + }, + component: CtxPage, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/index.tsx new file mode 100644 index 0000000000..128e132190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/index.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const HomePage = Vue.defineComponent({ + setup() { + return () => ( +
+
home
+
+ ) + }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.$id.tsx new file mode 100644 index 0000000000..bbeaaa7dd7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.$id.tsx @@ -0,0 +1,21 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { deferredHops, hopDelay, nestedStateValue } from '../../../shared' + +const NestedPage = Vue.defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () =>
{data.value.value}
+ }, +}) + +export const Route = createFileRoute('/nested/$id')({ + staleTime: 0, + gcTime: 0, + loader: async ({ params }) => { + await hopDelay(deferredHops) + return { value: nestedStateValue(params.id) } + }, + component: NestedPage, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.tsx new file mode 100644 index 0000000000..763657dfc6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.tsx @@ -0,0 +1,26 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { deferredHops, hopDelay, nestedLayoutValue } from '../../../shared' + +const NestedLayout = Vue.defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+
{data.value.value}
+ +
+ ) + }, +}) + +export const Route = createFileRoute('/nested')({ + staleTime: 0, + gcTime: 0, + loader: async () => { + await hopDelay(deferredHops) + return { value: nestedLayoutValue() } + }, + component: NestedLayout, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/slow.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/slow.$id.tsx new file mode 100644 index 0000000000..c9afccba97 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/slow.$id.tsx @@ -0,0 +1,21 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { deferredHops, hopDelay, slowStateValue } from '../../../shared' + +const SlowPage = Vue.defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () =>
{data.value.value}
+ }, +}) + +export const Route = createFileRoute('/slow/$id')({ + staleTime: 0, + gcTime: 0, + loader: async ({ params }) => { + await hopDelay(deferredHops) + return { value: slowStateValue(params.id) } + }, + component: SlowPage, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/tsconfig.json b/benchmarks/client-nav/scenarios/async-pipeline/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts new file mode 100644 index 0000000000..ce4fa7318a --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts @@ -0,0 +1,44 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav async-pipeline (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/react/project.json b/benchmarks/client-nav/scenarios/control-flow/react/project.json new file mode 100644 index 0000000000..e3e580911f --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-control-flow-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/control-flow/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/setup.ts b/benchmarks/client-nav/scenarios/control-flow/react/setup.ts new file mode 100644 index 0000000000..130583b190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts new file mode 100644 index 0000000000..d6f2190be7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-control-flow', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-control-flow navigation loop (react)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/react/speed.flame.ts b/benchmarks/client-nav/scenarios/control-flow/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx new file mode 100644 index 0000000000..da9e63d293 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx @@ -0,0 +1,39 @@ +import type { RouterHistory } from '@tanstack/history' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + // The scenario intentionally throws loader errors every lap; keep React 19's + // default per-caught-error console reporting out of the measured loop. + const reactRoot = createRoot(container, { onCaughtError: () => {} }) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..7b6db9b237 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routeTree.gen.ts @@ -0,0 +1,156 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as BrokenRouteImport } from './routes/broken' +import { Route as Hop1RouteImport } from './routes/hop1' +import { Route as Hop2RouteImport } from './routes/hop2' +import { Route as TargetRouteImport } from './routes/target' +import { Route as MissingIdRouteImport } from './routes/missing.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const BrokenRoute = BrokenRouteImport.update({ + id: '/broken', + path: '/broken', + getParentRoute: () => rootRouteImport, +} as any) +const Hop1Route = Hop1RouteImport.update({ + id: '/hop1', + path: '/hop1', + getParentRoute: () => rootRouteImport, +} as any) +const Hop2Route = Hop2RouteImport.update({ + id: '/hop2', + path: '/hop2', + getParentRoute: () => rootRouteImport, +} as any) +const TargetRoute = TargetRouteImport.update({ + id: '/target', + path: '/target', + getParentRoute: () => rootRouteImport, +} as any) +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' + id: + | '__root__' + | '/' + | '/broken' + | '/hop1' + | '/hop2' + | '/target' + | '/missing/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BrokenRoute: typeof BrokenRoute + Hop1Route: typeof Hop1Route + Hop2Route: typeof Hop2Route + TargetRoute: typeof TargetRoute + MissingIdRoute: typeof MissingIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/broken': { + id: '/broken' + path: '/broken' + fullPath: '/broken' + preLoaderRoute: typeof BrokenRouteImport + parentRoute: typeof rootRouteImport + } + '/hop1': { + id: '/hop1' + path: '/hop1' + fullPath: '/hop1' + preLoaderRoute: typeof Hop1RouteImport + parentRoute: typeof rootRouteImport + } + '/hop2': { + id: '/hop2' + path: '/hop2' + fullPath: '/hop2' + preLoaderRoute: typeof Hop2RouteImport + parentRoute: typeof rootRouteImport + } + '/target': { + id: '/target' + path: '/target' + fullPath: '/target' + preLoaderRoute: typeof TargetRouteImport + parentRoute: typeof rootRouteImport + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BrokenRoute: BrokenRoute, + Hop1Route: Hop1Route, + Hop2Route: Hop2Route, + TargetRoute: TargetRoute, + MissingIdRoute: MissingIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/__root.tsx new file mode 100644 index 0000000000..63d5feb901 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/__root.tsx @@ -0,0 +1,52 @@ +import { + Link, + Outlet, + createRootRoute, + useLocation, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function LocationMarker() { + const pathname = useLocation({ select: (location) => location.pathname }) + return {pathname} +} + +function RootComponent() { + return ( + <> + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx new file mode 100644 index 0000000000..b11bb845bc --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx @@ -0,0 +1,20 @@ +import { createFileRoute } from '@tanstack/react-router' +import { errorMessage } from '../../../shared' +import type { ErrorComponentProps } from '@tanstack/react-router' + +export const Route = createFileRoute('/broken')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw new Error(errorMessage) + }, + errorComponent: BrokenError, +}) + +function BrokenError(props: ErrorComponentProps) { + return ( +
+ {props.error instanceof Error ? props.error.message : String(props.error)} +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop1.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop1.tsx new file mode 100644 index 0000000000..aacba39384 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop1.tsx @@ -0,0 +1,9 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/hop1')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw redirect({ to: '/hop2' }) + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop2.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop2.tsx new file mode 100644 index 0000000000..db31abe9f3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop2.tsx @@ -0,0 +1,9 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/hop2')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw redirect({ to: '/target' }) + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/index.tsx new file mode 100644 index 0000000000..24e856ea15 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return
home
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/missing.$id.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/missing.$id.tsx new file mode 100644 index 0000000000..0c807bb2bc --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/missing.$id.tsx @@ -0,0 +1,23 @@ +import { createFileRoute, notFound } from '@tanstack/react-router' + +export const Route = createFileRoute('/missing/$id')({ + staleTime: 0, + gcTime: 0, + loader: ({ params }) => { + if (params.id === 'gone') { + throw notFound() + } + return { id: params.id } + }, + component: MissingPage, + notFoundComponent: MissingNotFound, +}) + +function MissingPage() { + const data = Route.useLoaderData() + return
{data.id}
+} + +function MissingNotFound() { + return
missing not found
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/target.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/target.tsx new file mode 100644 index 0000000000..280f65835e --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/target.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/target')({ + component: TargetPage, +}) + +function TargetPage() { + return
target
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/tsconfig.json b/benchmarks/client-nav/scenarios/control-flow/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts new file mode 100644 index 0000000000..1eefca0fc3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'react', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav control-flow (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/shared.ts b/benchmarks/client-nav/scenarios/control-flow/shared.ts new file mode 100644 index 0000000000..c4f368bee1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/shared.ts @@ -0,0 +1,91 @@ +/** + * Shared definition of the `control-flow` scenario: loader-thrown redirects + * (including a 2-hop chain), notFound() rendering, loader errors through the + * route error boundary, and recovery navigation resetting the boundary. + */ +import type { ScenarioStep } from '../harness' + +export const errorMessage = 'bench-error' + +export const steps: ReadonlyArray = [ + { + type: 'click', + testId: 'go-hop1', + // The click lands on /hop1 whose loader chains redirects to /target; wait + // until the post-redirect location is committed before finishing the step. + isSettled: () => + document.querySelector('[data-testid="loc"]')?.textContent === '/target', + }, + 'go-missing-ok', + 'go-missing-gone', + 'go-broken', + 'go-target', + 'go-missing-gone', + 'home', +] + +interface StepExpectation { + loc: string + present: ReadonlyArray + absent?: ReadonlyArray + errorText?: string +} + +const expectations: ReadonlyArray = [ + { loc: '/target', present: ['target-state'] }, + { loc: '/missing/exists', present: ['missing-state'] }, + { + loc: '/missing/gone', + present: ['not-found-state'], + absent: ['missing-state'], + }, + { loc: '/broken', present: ['error-state'], errorText: errorMessage }, + { loc: '/target', present: ['target-state'], absent: ['error-state'] }, + { loc: '/missing/gone', present: ['not-found-state'] }, + { loc: '/', present: ['home-state'] }, +] + +export function assertStepResult(stepIndex: number, container: HTMLElement) { + const expectation = expectations[stepIndex % expectations.length]! + + const loc = container.querySelector('[data-testid="loc"]') + if (loc?.textContent !== expectation.loc) { + throw new Error( + `Expected location "${expectation.loc}" after step ${stepIndex}, received "${loc?.textContent ?? ''}"`, + ) + } + + for (const testId of expectation.present) { + const element = container.querySelector(`[data-testid="${testId}"]`) + if (!element) { + throw new Error( + `Expected [data-testid="${testId}"] after step ${stepIndex}`, + ) + } + if ( + expectation.errorText && + !element.textContent?.includes(expectation.errorText) + ) { + throw new Error( + `Expected [data-testid="${testId}"] to include "${expectation.errorText}", received "${element.textContent}"`, + ) + } + } + + for (const testId of expectation.absent ?? []) { + if (container.querySelector(`[data-testid="${testId}"]`)) { + throw new Error( + `Expected [data-testid="${testId}"] to be absent after step ${stepIndex}`, + ) + } + } +} + +// Two laps through the 7-step sequence per benchmark iteration. +export const ticksPerIteration = 14 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/project.json b/benchmarks/client-nav/scenarios/control-flow/solid/project.json new file mode 100644 index 0000000000..2b5154d385 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-control-flow-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/control-flow/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/setup.ts b/benchmarks/client-nav/scenarios/control-flow/solid/setup.ts new file mode 100644 index 0000000000..6a46971603 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts new file mode 100644 index 0000000000..d803d2a313 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-control-flow', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-control-flow navigation loop (solid)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/control-flow/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx @@ -0,0 +1,34 @@ +import type { RouterHistory } from '@tanstack/history' +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const unmount = render(() => , container) + + return { + router, + unmount, + } +} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..cd84f99d5d --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts @@ -0,0 +1,156 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as BrokenRouteImport } from './routes/broken' +import { Route as Hop1RouteImport } from './routes/hop1' +import { Route as Hop2RouteImport } from './routes/hop2' +import { Route as TargetRouteImport } from './routes/target' +import { Route as MissingIdRouteImport } from './routes/missing.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const BrokenRoute = BrokenRouteImport.update({ + id: '/broken', + path: '/broken', + getParentRoute: () => rootRouteImport, +} as any) +const Hop1Route = Hop1RouteImport.update({ + id: '/hop1', + path: '/hop1', + getParentRoute: () => rootRouteImport, +} as any) +const Hop2Route = Hop2RouteImport.update({ + id: '/hop2', + path: '/hop2', + getParentRoute: () => rootRouteImport, +} as any) +const TargetRoute = TargetRouteImport.update({ + id: '/target', + path: '/target', + getParentRoute: () => rootRouteImport, +} as any) +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' + id: + | '__root__' + | '/' + | '/broken' + | '/hop1' + | '/hop2' + | '/target' + | '/missing/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BrokenRoute: typeof BrokenRoute + Hop1Route: typeof Hop1Route + Hop2Route: typeof Hop2Route + TargetRoute: typeof TargetRoute + MissingIdRoute: typeof MissingIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/broken': { + id: '/broken' + path: '/broken' + fullPath: '/broken' + preLoaderRoute: typeof BrokenRouteImport + parentRoute: typeof rootRouteImport + } + '/hop1': { + id: '/hop1' + path: '/hop1' + fullPath: '/hop1' + preLoaderRoute: typeof Hop1RouteImport + parentRoute: typeof rootRouteImport + } + '/hop2': { + id: '/hop2' + path: '/hop2' + fullPath: '/hop2' + preLoaderRoute: typeof Hop2RouteImport + parentRoute: typeof rootRouteImport + } + '/target': { + id: '/target' + path: '/target' + fullPath: '/target' + preLoaderRoute: typeof TargetRouteImport + parentRoute: typeof rootRouteImport + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BrokenRoute: BrokenRoute, + Hop1Route: Hop1Route, + Hop2Route: Hop2Route, + TargetRoute: TargetRoute, + MissingIdRoute: MissingIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..1bce9e8a3e --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/__root.tsx @@ -0,0 +1,52 @@ +import { + Link, + Outlet, + createRootRoute, + useLocation, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function LocationMarker() { + const pathname = useLocation({ select: (location) => location.pathname }) + return {pathname()} +} + +function RootComponent() { + return ( + <> + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/broken.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/broken.tsx new file mode 100644 index 0000000000..9931ef9c58 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/broken.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { errorMessage } from '../../../shared' +import type { ErrorComponentProps } from '@tanstack/solid-router' + +export const Route = createFileRoute('/broken')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw new Error(errorMessage) + }, + errorComponent: BrokenError, +}) + +function BrokenError(props: ErrorComponentProps) { + return
{props.error.message}
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop1.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop1.tsx new file mode 100644 index 0000000000..1aedb481ec --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop1.tsx @@ -0,0 +1,9 @@ +import { createFileRoute, redirect } from '@tanstack/solid-router' + +export const Route = createFileRoute('/hop1')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw redirect({ to: '/hop2' }) + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop2.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop2.tsx new file mode 100644 index 0000000000..91b601c516 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop2.tsx @@ -0,0 +1,9 @@ +import { createFileRoute, redirect } from '@tanstack/solid-router' + +export const Route = createFileRoute('/hop2')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw redirect({ to: '/target' }) + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/index.tsx new file mode 100644 index 0000000000..cc46764de5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return
home
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/missing.$id.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/missing.$id.tsx new file mode 100644 index 0000000000..9c0493fb48 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/missing.$id.tsx @@ -0,0 +1,23 @@ +import { createFileRoute, notFound } from '@tanstack/solid-router' + +export const Route = createFileRoute('/missing/$id')({ + staleTime: 0, + gcTime: 0, + loader: ({ params }) => { + if (params.id === 'gone') { + throw notFound() + } + return { id: params.id } + }, + component: MissingPage, + notFoundComponent: MissingNotFound, +}) + +function MissingPage() { + const data = Route.useLoaderData() + return
{data().id}
+} + +function MissingNotFound() { + return
missing not found
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/target.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/target.tsx new file mode 100644 index 0000000000..87de4e59a7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/target.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/target')({ + component: TargetPage, +}) + +function TargetPage() { + return
target
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/tsconfig.json b/benchmarks/client-nav/scenarios/control-flow/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts new file mode 100644 index 0000000000..f4fa916154 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts @@ -0,0 +1,50 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'solid', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav control-flow (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/project.json b/benchmarks/client-nav/scenarios/control-flow/vue/project.json new file mode 100644 index 0000000000..7370687988 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-control-flow-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/control-flow/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/setup.ts b/benchmarks/client-nav/scenarios/control-flow/vue/setup.ts new file mode 100644 index 0000000000..97b74b3892 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts new file mode 100644 index 0000000000..8a019945c7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-control-flow', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-control-flow navigation loop (vue)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/control-flow/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx @@ -0,0 +1,41 @@ +import type { RouterHistory } from '@tanstack/history' +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..6b53a6a203 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts @@ -0,0 +1,156 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as BrokenRouteImport } from './routes/broken' +import { Route as Hop1RouteImport } from './routes/hop1' +import { Route as Hop2RouteImport } from './routes/hop2' +import { Route as TargetRouteImport } from './routes/target' +import { Route as MissingIdRouteImport } from './routes/missing.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const BrokenRoute = BrokenRouteImport.update({ + id: '/broken', + path: '/broken', + getParentRoute: () => rootRouteImport, +} as any) +const Hop1Route = Hop1RouteImport.update({ + id: '/hop1', + path: '/hop1', + getParentRoute: () => rootRouteImport, +} as any) +const Hop2Route = Hop2RouteImport.update({ + id: '/hop2', + path: '/hop2', + getParentRoute: () => rootRouteImport, +} as any) +const TargetRoute = TargetRouteImport.update({ + id: '/target', + path: '/target', + getParentRoute: () => rootRouteImport, +} as any) +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' + id: + | '__root__' + | '/' + | '/broken' + | '/hop1' + | '/hop2' + | '/target' + | '/missing/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BrokenRoute: typeof BrokenRoute + Hop1Route: typeof Hop1Route + Hop2Route: typeof Hop2Route + TargetRoute: typeof TargetRoute + MissingIdRoute: typeof MissingIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/broken': { + id: '/broken' + path: '/broken' + fullPath: '/broken' + preLoaderRoute: typeof BrokenRouteImport + parentRoute: typeof rootRouteImport + } + '/hop1': { + id: '/hop1' + path: '/hop1' + fullPath: '/hop1' + preLoaderRoute: typeof Hop1RouteImport + parentRoute: typeof rootRouteImport + } + '/hop2': { + id: '/hop2' + path: '/hop2' + fullPath: '/hop2' + preLoaderRoute: typeof Hop2RouteImport + parentRoute: typeof rootRouteImport + } + '/target': { + id: '/target' + path: '/target' + fullPath: '/target' + preLoaderRoute: typeof TargetRouteImport + parentRoute: typeof rootRouteImport + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BrokenRoute: BrokenRoute, + Hop1Route: Hop1Route, + Hop2Route: Hop2Route, + TargetRoute: TargetRoute, + MissingIdRoute: MissingIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..9695c4b32d --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/__root.tsx @@ -0,0 +1,57 @@ +import * as Vue from 'vue' +import { + Link, + Outlet, + createRootRoute, + useLocation, +} from '@tanstack/vue-router' + +const LocationMarker = Vue.defineComponent({ + setup() { + const pathname = useLocation({ select: (location) => location.pathname }) + return () => {pathname.value} + }, +}) + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/broken.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/broken.tsx new file mode 100644 index 0000000000..c67fa2817e --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/broken.tsx @@ -0,0 +1,21 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { errorMessage } from '../../../shared' + +const BrokenError = Vue.defineComponent({ + props: { + error: { type: Error, required: true }, + }, + setup(props) { + return () =>
{props.error.message}
+ }, +}) + +export const Route = createFileRoute('/broken')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw new Error(errorMessage) + }, + errorComponent: BrokenError, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop1.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop1.tsx new file mode 100644 index 0000000000..ed00cefe3f --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop1.tsx @@ -0,0 +1,9 @@ +import { createFileRoute, redirect } from '@tanstack/vue-router' + +export const Route = createFileRoute('/hop1')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw redirect({ to: '/hop2' }) + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop2.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop2.tsx new file mode 100644 index 0000000000..f6d4b1c1e0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop2.tsx @@ -0,0 +1,9 @@ +import { createFileRoute, redirect } from '@tanstack/vue-router' + +export const Route = createFileRoute('/hop2')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw redirect({ to: '/target' }) + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/index.tsx new file mode 100644 index 0000000000..f3ffc58610 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const HomePage = Vue.defineComponent({ + setup() { + return () =>
home
+ }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/missing.$id.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/missing.$id.tsx new file mode 100644 index 0000000000..022ea656a6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/missing.$id.tsx @@ -0,0 +1,28 @@ +import * as Vue from 'vue' +import { createFileRoute, notFound } from '@tanstack/vue-router' + +const MissingPage = Vue.defineComponent({ + setup() { + const data = Route.useLoaderData() + return () =>
{data.value.id}
+ }, +}) + +const MissingNotFound = Vue.defineComponent({ + setup() { + return () =>
missing not found
+ }, +}) + +export const Route = createFileRoute('/missing/$id')({ + staleTime: 0, + gcTime: 0, + loader: ({ params }) => { + if (params.id === 'gone') { + throw notFound() + } + return { id: params.id } + }, + component: MissingPage, + notFoundComponent: MissingNotFound, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/target.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/target.tsx new file mode 100644 index 0000000000..4e22d0993a --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/target.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const TargetPage = Vue.defineComponent({ + setup() { + return () =>
target
+ }, +}) + +export const Route = createFileRoute('/target')({ + component: TargetPage, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/tsconfig.json b/benchmarks/client-nav/scenarios/control-flow/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts new file mode 100644 index 0000000000..3c2750d2a6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts @@ -0,0 +1,44 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav control-flow (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/harness.ts b/benchmarks/client-nav/scenarios/harness.ts new file mode 100644 index 0000000000..cf3c39c7e6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/harness.ts @@ -0,0 +1,534 @@ +import { + createBrowserHistory, + createMemoryHistory, + type RouterHistory, +} from '@tanstack/history' +import { JSDOM } from 'jsdom' +import { getRequiredLink, waitForRequiredLink } from '../setup-helpers' + +export interface ScenarioRouter { + load: () => Promise + subscribe: (eventType: 'onRendered', callback: () => void) => () => void + navigate: (options: any) => Promise + preloadRoute: (options: any) => Promise + invalidate: () => Promise + history: { + back: () => void + forward: () => void + go: (index: number) => void + } +} + +export interface MountedScenarioApp { + router: ScenarioRouter + unmount: () => void +} + +/** + * A single benchmark step. Plain strings are link-click steps (the common + * case). Steps that change the router location (`click`, `navigate`, `back`, + * `forward`, `go`) are awaited through the router's `onRendered` event; steps + * that do background work (`hover`, `preload`, `invalidate`) are awaited + * through a fixed number of 0ms timer hops so the loop stays deterministic. + */ +export type ScenarioStep = + | string + | { + type: 'click' + testId: string + /** + * Optional post-render settle predicate for steps that trigger work + * finishing after `onRendered` (e.g. deferred data resolving through a + * Suspense boundary). The step keeps taking 0ms timer hops until the + * predicate returns true (bounded, throws when exceeded). + */ + isSettled?: () => boolean + } + | { + /** + * Dispatches a single `mouseover` on the link, which triggers + * `preload: 'intent'` exactly once in every adapter: React synthesizes + * `mouseEnter` from `mouseover`, and Solid/Vue attach a native + * `mouseover` preload handler. (Solid/Vue also listen to `mouseenter` — + * dispatching both events would run the preload pipeline twice for them + * but only once for React.) Then settles via counted 0ms hops. + */ + type: 'hover' + testId: string + settleHops?: number + } + | { type: 'navigate'; getOptions: () => object } + | { type: 'preload'; getOptions: () => object; settleHops?: number } + | { type: 'invalidate'; settleHops?: number } + | { type: 'back' } + | { type: 'forward' } + | { type: 'go'; delta: number } + +/** + * One macrotask turn via `setImmediate` rather than `setTimeout(0)`: both + * yield deterministically to the event loop (timers, MessageChannel, React's + * Node scheduler), but a timer costs ~3-4 syscalls (timerfd + epoll) per hop + * while an immediate costs ~1. CodSpeed excludes syscall time from the + * measure — inconsistently past a threshold, which flagged the hop-heavy + * benches as "skipped" — so the loop must stay syscall-lean. + */ +const timerHop = () => + new Promise((resolve) => setImmediate(() => resolve())) + +async function settle(hops: number) { + for (let i = 0; i < hops; i++) { + await timerHop() + } +} + +const MAX_SETTLE_HOPS = 100 +const BATCH_SETTLE_HOPS = 4 + +/** + * Close the batch at a deterministic macrotask boundary. Four fixed hops give + * framework passive effects and scheduler callbacks time to run without + * changing the amount of navigation work in the batch. + */ +async function finishBatch() { + await settle(BATCH_SETTLE_HOPS) +} + +async function settleUntil(isSettled: () => boolean, label: string) { + for (let i = 0; i < MAX_SETTLE_HOPS; i++) { + if (isSettled()) { + return + } + await timerHop() + } + throw new Error( + `Step "${label}" did not settle within ${MAX_SETTLE_HOPS} timer hops`, + ) +} + +/** + * Reroute zero-delay `window.setTimeout` calls onto `setImmediate` for the + * duration of the benchmark. jsdom delivers history traversals through two + * nested `window.setTimeout(0)` tasks; Node clamps those to 1ms of wall + * time, so with nothing else pending the event loop blocks in `epoll_wait` + * until each timer expires — and that blocked wall-time is recorded as + * highly variable syscall time (5-26ms across runs), enough for CodSpeed to + * skip-warn the history benches. Zero-delay timeouts carry no ordering + * semantics a check-phase immediate doesn't satisfy, and the suite's + * conventions already forbid real-delay timers in measured code; non-zero + * delays are passed through untouched. + */ +interface TimerWindow { + setTimeout: typeof window.setTimeout + clearTimeout: typeof window.clearTimeout +} + +function patchZeroDelayTimeouts(targetWindow: TimerWindow) { + const originalSetTimeout = targetWindow.setTimeout.bind(targetWindow) + const originalClearTimeout = targetWindow.clearTimeout.bind(targetWindow) + const immediates = new Map() + // Negative ids cannot collide with real jsdom timer ids. + let nextImmediateId = -2 + + targetWindow.setTimeout = (( + handler: (...handlerArgs: Array) => void, + delay?: number, + ...args: Array + ) => { + if (!delay) { + const id = nextImmediateId-- + immediates.set( + id, + setImmediate(() => { + immediates.delete(id) + handler(...args) + }), + ) + return id + } + return originalSetTimeout(handler, delay, ...args) + }) as typeof targetWindow.setTimeout + + targetWindow.clearTimeout = ((id: number) => { + const immediate = immediates.get(id) + if (immediate) { + clearImmediate(immediate) + immediates.delete(id) + return + } + originalClearTimeout(id) + }) as typeof targetWindow.clearTimeout + + return () => { + targetWindow.setTimeout = + originalSetTimeout as typeof targetWindow.setTimeout + targetWindow.clearTimeout = + originalClearTimeout as typeof targetWindow.clearTimeout + } +} + +interface ListenerTarget { + addEventListener: ( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | AddEventListenerOptions, + ) => void + removeEventListener: ( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | EventListenerOptions, + ) => void +} + +/** + * Scroll restoration installs page-lifetime listeners without a public router + * dispose operation. Capture just those listeners while the router is created + * so per-invocation routers do not remain reachable after teardown. + */ +function captureScrollRestorationListeners() { + const captured: Array<{ + target: ListenerTarget + type: string + listener: EventListenerOrEventListenerObject | null + options?: boolean | AddEventListenerOptions + }> = [] + const patches: Array<{ + target: ListenerTarget + addEventListener: ListenerTarget['addEventListener'] + }> = [] + + const patch = (target: ListenerTarget, capturedType: string) => { + const originalAddEventListener = target.addEventListener + patches.push({ target, addEventListener: originalAddEventListener }) + + target.addEventListener = function (type, listener, options) { + if (type === capturedType) { + captured.push({ target, type, listener, options }) + } + originalAddEventListener.call(target, type, listener, options) + } + } + + patch(document as unknown as ListenerTarget, 'scroll') + patch(globalThis as unknown as ListenerTarget, 'pagehide') + + let stopped = false + const stop = () => { + if (stopped) { + return + } + stopped = true + for (const entry of patches) { + entry.target.addEventListener = entry.addEventListener + } + } + + return { + stop, + cleanup() { + stop() + for (const { target, type, listener, options } of captured) { + target.removeEventListener(type, listener, options) + } + }, + } +} + +interface ScenarioHistoryResource { + history: RouterHistory + timeoutWindow?: TimerWindow + dispose: () => void +} + +function createScenarioHistory( + mode: NonNullable, + initialUrl: string, +): ScenarioHistoryResource { + if (mode === 'browser') { + const dom = new JSDOM('', { + url: new URL(initialUrl, 'http://localhost').href, + }) + const history = createBrowserHistory({ window: dom.window }) + + return { + history, + timeoutWindow: dom.window as unknown as TimerWindow, + dispose() { + history.destroy() + dom.window.close() + }, + } + } + + const history = createMemoryHistory({ initialEntries: [initialUrl] }) + return { + history, + dispose: history.destroy, + } +} + +export interface ScenarioSetupOptions { + frameworkLabel: string + mount: (container: HTMLElement, history: RouterHistory) => MountedScenarioApp + /** + * Circular sequence of steps advanced by `tick()`. Link steps must target + * links rendered from the start (e.g. in the root layout), no two + * consecutive location-changing steps may target the same location (a + * same-location click never triggers `onRendered`), and the sequence must + * leave the app back on the initial route so the warm-up lap ends in the + * starting state. + */ + steps: ReadonlyArray + /** Sanity check run once per step during the warm-up lap in `before()`. */ + assertAfterStep?: ( + stepIndex: number, + container: HTMLElement, + history: RouterHistory, + ) => void + /** + * URL used to initialize the fresh history before mounting (default '/'). + * Scenarios whose router uses a `basepath` or an input rewrite must start on + * an external URL that maps to their initial route. + */ + initialUrl?: string + /** + * Browser history is reserved for the scenario that explicitly measures + * browser history traversal. All other scenarios use fresh memory history. + */ + historyMode?: 'memory' | 'browser' +} + +function warnAboutDevMode(frameworkLabel: string) { + if (process.env.NODE_ENV !== 'production') { + console.warn( + `client-nav scenario benchmark is running without NODE_ENV=production; ${frameworkLabel} dev overhead will dominate results.`, + ) + } +} + +/** + * Shared scenario runner: mounts the prebuilt app, then advances a circular + * sequence of steps, synchronizing each step so its work is fully part of the + * measured tick and steps cannot overlap. + */ +export function createScenarioSetup(options: ScenarioSetupOptions) { + warnAboutDevMode(options.frameworkLabel) + + let container: HTMLDivElement | undefined = undefined + let unmount: (() => void) | undefined = undefined + let unsub = () => {} + let restoreTimeouts = () => {} + let cleanupScrollRestorationListeners = () => {} + let historyResource: ScenarioHistoryResource | undefined = undefined + let stepIndex = 0 + let next: () => Promise = () => + Promise.reject(new Error('Benchmark not initialized')) + + async function before() { + stepIndex = 0 + historyResource = createScenarioHistory( + options.historyMode ?? 'memory', + options.initialUrl ?? '/', + ) + + const restoreGlobalTimeouts = patchZeroDelayTimeouts(window) + const restoreHistoryTimeouts = historyResource.timeoutWindow + ? patchZeroDelayTimeouts(historyResource.timeoutWindow) + : () => {} + restoreTimeouts = () => { + restoreHistoryTimeouts() + restoreGlobalTimeouts() + } + + container = document.createElement('div') + document.body.append(container) + + const capturedListeners = captureScrollRestorationListeners() + let mounted: MountedScenarioApp + try { + mounted = options.mount(container, historyResource.history) + } finally { + capturedListeners.stop() + cleanupScrollRestorationListeners = capturedListeners.cleanup + } + + const { router, unmount: dispose } = mounted + unmount = dispose + + let resolveRendered: () => void = () => {} + unsub = router.subscribe('onRendered', () => { + resolveRendered() + }) + + const cachedLinks = new Map() + const rendered = () => + new Promise((resolveNext) => { + resolveRendered = resolveNext + }) + + const runStep = async (step: ScenarioStep) => { + if (typeof step === 'string') { + step = { type: 'click', testId: step } + } + + switch (step.type) { + case 'click': { + const renderedPromise = rendered() + getRequiredLink(container!, step.testId, cachedLinks).dispatchEvent( + new MouseEvent('click', { + bubbles: true, + cancelable: true, + button: 0, + }), + ) + await renderedPromise + if (step.isSettled) { + await settleUntil(step.isSettled, `click ${step.testId}`) + } + return + } + case 'hover': { + const link = getRequiredLink(container!, step.testId, cachedLinks) + link.dispatchEvent( + new MouseEvent('mouseover', { bubbles: true, cancelable: true }), + ) + await settle(step.settleHops ?? 4) + return + } + case 'navigate': { + const renderedPromise = rendered() + router.navigate(step.getOptions()) + await renderedPromise + return + } + case 'preload': { + await router.preloadRoute(step.getOptions()) + await settle(step.settleHops ?? 2) + return + } + case 'invalidate': { + await router.invalidate() + await settle(step.settleHops ?? 2) + return + } + case 'back': { + const renderedPromise = rendered() + router.history.back() + await renderedPromise + return + } + case 'forward': { + const renderedPromise = rendered() + router.history.forward() + await renderedPromise + return + } + case 'go': { + const renderedPromise = rendered() + router.history.go(step.delta) + await renderedPromise + return + } + } + } + + await router.load() + + const linkTestIds = new Set() + for (const step of options.steps) { + if (typeof step === 'string') { + linkTestIds.add(step) + } else if (step.type === 'click' || step.type === 'hover') { + linkTestIds.add(step.testId) + } + } + for (const testId of linkTestIds) { + await waitForRequiredLink(container, testId, cachedLinks) + } + + // One warm-up lap that also sanity-checks each step's observable output, + // ending back on the initial route so measurement starts from a known state. + for (const [index, step] of options.steps.entries()) { + await runStep(step) + options.assertAfterStep?.(index, container, historyResource.history) + } + await finishBatch() + + next = () => { + const step = options.steps[stepIndex % options.steps.length]! + stepIndex += 1 + return runStep(step) + } + } + + function after() { + unmount?.() + container?.remove() + unsub() + cleanupScrollRestorationListeners() + restoreTimeouts() + historyResource?.dispose() + restoreTimeouts = () => {} + cleanupScrollRestorationListeners = () => {} + unmount = undefined + container = undefined + historyResource = undefined + } + + function tick() { + return next() + } + + return { + before, + tick, + finishBatch, + after, + } +} + +export interface MountLoopSetupOptions { + frameworkLabel: string + mount: (container: HTMLElement, history: RouterHistory) => MountedScenarioApp + /** Test id that must appear in the container before a mount counts as done. */ + readyTestId: string + assertReady?: (container: HTMLElement) => void +} + +/** + * Mount-loop runner for cold-start scenarios: every tick creates a fresh + * container, mounts the app (router creation included), waits for the initial + * render to commit, then unmounts and cleans up. + */ +export function createMountLoopSetup(options: MountLoopSetupOptions) { + warnAboutDevMode(options.frameworkLabel) + + async function tick() { + const container = document.createElement('div') + document.body.append(container) + const history = createMemoryHistory({ initialEntries: ['/'] }) + + const { router, unmount } = options.mount(container, history) + + try { + await router.load() + await settleUntil( + () => + container.querySelector(`[data-testid="${options.readyTestId}"]`) !== + null, + `mount ${options.readyTestId}`, + ) + options.assertReady?.(container) + } finally { + unmount() + history.destroy() + container.remove() + } + } + + return { + before: async () => {}, + tick, + finishBatch, + after: () => {}, + } +} diff --git a/benchmarks/client-nav/scenarios/head/react/project.json b/benchmarks/client-nav/scenarios/head/react/project.json new file mode 100644 index 0000000000..1becf30fb9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-head-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/head/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/head/react/setup.ts b/benchmarks/client-nav/scenarios/head/react/setup.ts new file mode 100644 index 0000000000..1a28b0ca94 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, stepTestIds } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + steps: stepTestIds, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/head/react/speed.bench.ts b/benchmarks/client-nav/scenarios/head/react/speed.bench.ts new file mode 100644 index 0000000000..d0d731a09f --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-head', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-head navigation loop (react)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/head/react/speed.flame.ts b/benchmarks/client-nav/scenarios/head/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/head/react/src/main.tsx b/benchmarks/client-nav/scenarios/head/react/src/main.tsx new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/src/main.tsx @@ -0,0 +1,37 @@ +import type { RouterHistory } from '@tanstack/history' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const reactRoot = createRoot(container) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..88867d9190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts @@ -0,0 +1,145 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as DocsRouteImport } from './routes/docs' +import { Route as SettingsRouteImport } from './routes/settings' +import { Route as ArticlesIdRouteImport } from './routes/articles.$id' +import { Route as DocsSectionRouteImport } from './routes/docs.$section' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + getParentRoute: () => rootRouteImport, +} as any) +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ArticlesIdRoute = ArticlesIdRouteImport.update({ + id: '/articles/$id', + path: '/articles/$id', + getParentRoute: () => rootRouteImport, +} as any) +const DocsSectionRoute = DocsSectionRouteImport.update({ + id: '/$section', + path: '/$section', + getParentRoute: () => DocsRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' + id: + | '__root__' + | '/' + | '/docs' + | '/settings' + | '/articles/$id' + | '/docs/$section' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DocsRoute: typeof DocsRouteWithChildren + SettingsRoute: typeof SettingsRoute + ArticlesIdRoute: typeof ArticlesIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/articles/$id': { + id: '/articles/$id' + path: '/articles/$id' + fullPath: '/articles/$id' + preLoaderRoute: typeof ArticlesIdRouteImport + parentRoute: typeof rootRouteImport + } + '/docs/$section': { + id: '/docs/$section' + path: '/$section' + fullPath: '/docs/$section' + preLoaderRoute: typeof DocsSectionRouteImport + parentRoute: typeof DocsRoute + } + } +} + +interface DocsRouteChildren { + DocsSectionRoute: typeof DocsSectionRoute +} + +const DocsRouteChildren: DocsRouteChildren = { + DocsSectionRoute: DocsSectionRoute, +} + +const DocsRouteWithChildren = DocsRoute._addFileChildren(DocsRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DocsRoute: DocsRouteWithChildren, + SettingsRoute: SettingsRoute, + ArticlesIdRoute: ArticlesIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/__root.tsx new file mode 100644 index 0000000000..3d61dad0e9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/src/routes/__root.tsx @@ -0,0 +1,59 @@ +import { + HeadContent, + Link, + Outlet, + createRootRoute, +} from '@tanstack/react-router' +import { articleIds, docsSections, rootHead } from '../../../shared' + +export const Route = createRootRoute({ + head: rootHead, + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/articles.$id.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/articles.$id.tsx new file mode 100644 index 0000000000..6f5b78d60e --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/src/routes/articles.$id.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/react-router' +import { articleDescription, articleHead, articleTitle } from '../../../shared' + +export const Route = createFileRoute('/articles/$id')({ + head: ({ params }) => articleHead(params.id), + component: ArticlePage, +}) + +function ArticlePage() { + const params = Route.useParams() + + return ( +
+

{articleTitle(params.id)}

+

{articleDescription(params.id)}

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

{docsTitle(params.section)}

+

{docsDescription(params.section)}

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

Docs

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

{homeTitle}

+

Landing page

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

{settingsTitle}

+

Account settings

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/head/react/tsconfig.json b/benchmarks/client-nav/scenarios/head/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/head/react/vite.config.ts b/benchmarks/client-nav/scenarios/head/react/vite.config.ts new file mode 100644 index 0000000000..7c8d6d4c15 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/vite.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'react', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav head (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/head/shared.ts b/benchmarks/client-nav/scenarios/head/shared.ts new file mode 100644 index 0000000000..db185d602b --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/shared.ts @@ -0,0 +1,152 @@ +/** + * Shared definition of the `head` scenario: route head() payloads, the click + * sequence, and per-step sanity assertions. The three framework apps consume + * these builders so the workload is identical modulo the rendering layer. + */ + +const siteName = 'Head Bench' + +export const docsSections = ['api', 'guide', 'cli'] as const +export const articleIds = ['1', '2', '3'] as const + +export const homeTitle = `Home | ${siteName}` +export const settingsTitle = `Settings | ${siteName}` + +export function docsTitle(section: string) { + return `Docs ${section} | ${siteName}` +} + +export function docsDescription(section: string) { + return `Documentation for the ${section} section of the head benchmark app.` +} + +export function articleTitle(id: string) { + return `Article ${id} | ${siteName}` +} + +export function articleDescription(id: string) { + return `Long-form article number ${id}, with a description sized like a realistic summary of the page content.` +} + +export function rootHead() { + return { + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { name: 'application-name', content: siteName }, + { name: 'description', content: 'Client head-management benchmark' }, + { name: 'theme-color', content: '#111827' }, + { property: 'og:type', content: 'website' }, + { property: 'og:site_name', content: siteName }, + ], + links: [ + { rel: 'icon', href: '/favicon.ico' }, + { rel: 'preconnect', href: 'https://assets.example.com' }, + ], + } +} + +export function homeHead() { + return { + meta: [ + { title: homeTitle }, + { name: 'description', content: 'Landing page of the head benchmark' }, + { property: 'og:title', content: homeTitle }, + ], + links: [{ rel: 'canonical', href: 'https://example.com/' }], + } +} + +export function docsLayoutHead() { + return { + meta: [ + // Overridden by the child section route on every docs navigation, so the + // dedupe path is exercised for both `name` and `property` entries. + { name: 'description', content: 'Documentation hub' }, + { property: 'og:title', content: `Docs | ${siteName}` }, + { name: 'docsearch:index', content: 'head-bench-docs' }, + ], + links: [{ rel: 'search', href: '/docs/opensearch.xml' }], + } +} + +export function docsSectionHead(section: string) { + return { + meta: [ + { title: docsTitle(section) }, + { name: 'description', content: docsDescription(section) }, + { name: 'keywords', content: `docs,${section},router,benchmark` }, + { property: 'og:title', content: docsTitle(section) }, + { property: 'og:description', content: docsDescription(section) }, + { property: 'og:url', content: `https://example.com/docs/${section}` }, + { name: 'twitter:card', content: 'summary' }, + { name: 'twitter:title', content: docsTitle(section) }, + ], + links: [ + { rel: 'canonical', href: `https://example.com/docs/${section}` }, + { rel: 'prev', href: `https://example.com/docs/${section}/intro` }, + ], + } +} + +export function articleHead(id: string) { + return { + meta: [ + { title: articleTitle(id) }, + { name: 'description', content: articleDescription(id) }, + { name: 'author', content: 'Bench Author' }, + { property: 'og:title', content: articleTitle(id) }, + { property: 'og:description', content: articleDescription(id) }, + { property: 'og:url', content: `https://example.com/articles/${id}` }, + { property: 'og:image', content: `https://example.com/covers/${id}.png` }, + { property: 'article:published_time', content: '2026-01-01T00:00:00Z' }, + { name: 'twitter:card', content: 'summary_large_image' }, + { name: 'twitter:title', content: articleTitle(id) }, + ], + links: [{ rel: 'canonical', href: `https://example.com/articles/${id}` }], + } +} + +export function settingsHead() { + return { + meta: [ + { title: settingsTitle }, + // Same names as root entries, so the child-wins dedupe path runs. + { name: 'description', content: 'Account settings' }, + { name: 'theme-color', content: '#f9fafb' }, + { name: 'robots', content: 'noindex' }, + ], + links: [], + } +} + +export const steps = [ + { testId: 'go-docs-api', title: docsTitle('api') }, + { testId: 'go-article-1', title: articleTitle('1') }, + { testId: 'go-docs-guide', title: docsTitle('guide') }, + { testId: 'go-settings', title: settingsTitle }, + { testId: 'go-article-2', title: articleTitle('2') }, + { testId: 'go-docs-cli', title: docsTitle('cli') }, + { testId: 'go-article-3', title: articleTitle('3') }, + { testId: 'go-home', title: homeTitle }, +] as const + +export const stepTestIds = steps.map((step) => step.testId) + +export function assertStepResult(stepIndex: number) { + const expected = steps[stepIndex]!.title + if (document.title !== expected) { + throw new Error( + `Expected document.title to be "${expected}" after step ${stepIndex}, received "${document.title}"`, + ) + } +} + +// Two laps through the 8-step sequence per benchmark iteration. +export const ticksPerIteration = 16 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/head/solid/project.json b/benchmarks/client-nav/scenarios/head/solid/project.json new file mode 100644 index 0000000000..2575a19b89 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-head-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/head/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/head/solid/setup.ts b/benchmarks/client-nav/scenarios/head/solid/setup.ts new file mode 100644 index 0000000000..4ee924acff --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, stepTestIds } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + steps: stepTestIds, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts new file mode 100644 index 0000000000..ca156c950b --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-head', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-head navigation loop (solid)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/head/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/head/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/main.tsx b/benchmarks/client-nav/scenarios/head/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/src/main.tsx @@ -0,0 +1,34 @@ +import type { RouterHistory } from '@tanstack/history' +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const unmount = render(() => , container) + + return { + router, + unmount, + } +} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..b6f217e527 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts @@ -0,0 +1,145 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as DocsRouteImport } from './routes/docs' +import { Route as SettingsRouteImport } from './routes/settings' +import { Route as ArticlesIdRouteImport } from './routes/articles.$id' +import { Route as DocsSectionRouteImport } from './routes/docs.$section' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + getParentRoute: () => rootRouteImport, +} as any) +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ArticlesIdRoute = ArticlesIdRouteImport.update({ + id: '/articles/$id', + path: '/articles/$id', + getParentRoute: () => rootRouteImport, +} as any) +const DocsSectionRoute = DocsSectionRouteImport.update({ + id: '/$section', + path: '/$section', + getParentRoute: () => DocsRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' + id: + | '__root__' + | '/' + | '/docs' + | '/settings' + | '/articles/$id' + | '/docs/$section' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DocsRoute: typeof DocsRouteWithChildren + SettingsRoute: typeof SettingsRoute + ArticlesIdRoute: typeof ArticlesIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/articles/$id': { + id: '/articles/$id' + path: '/articles/$id' + fullPath: '/articles/$id' + preLoaderRoute: typeof ArticlesIdRouteImport + parentRoute: typeof rootRouteImport + } + '/docs/$section': { + id: '/docs/$section' + path: '/$section' + fullPath: '/docs/$section' + preLoaderRoute: typeof DocsSectionRouteImport + parentRoute: typeof DocsRoute + } + } +} + +interface DocsRouteChildren { + DocsSectionRoute: typeof DocsSectionRoute +} + +const DocsRouteChildren: DocsRouteChildren = { + DocsSectionRoute: DocsSectionRoute, +} + +const DocsRouteWithChildren = DocsRoute._addFileChildren(DocsRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DocsRoute: DocsRouteWithChildren, + SettingsRoute: SettingsRoute, + ArticlesIdRoute: ArticlesIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..52ca7da373 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/src/routes/__root.tsx @@ -0,0 +1,58 @@ +import { For } from 'solid-js' +import { + HeadContent, + Link, + Outlet, + createRootRoute, +} from '@tanstack/solid-router' +import { articleIds, docsSections, rootHead } from '../../../shared' + +export const Route = createRootRoute({ + head: rootHead, + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/articles.$id.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/articles.$id.tsx new file mode 100644 index 0000000000..dab11ada18 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/src/routes/articles.$id.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { articleDescription, articleHead, articleTitle } from '../../../shared' + +export const Route = createFileRoute('/articles/$id')({ + head: ({ params }) => articleHead(params.id), + component: ArticlePage, +}) + +function ArticlePage() { + const params = Route.useParams() + + return ( +
+

{articleTitle(params().id)}

+

{articleDescription(params().id)}

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

{docsTitle(params().section)}

+

{docsDescription(params().section)}

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

Docs

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

{homeTitle}

+

Landing page

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

{settingsTitle}

+

Account settings

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/head/solid/tsconfig.json b/benchmarks/client-nav/scenarios/head/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/head/solid/vite.config.ts b/benchmarks/client-nav/scenarios/head/solid/vite.config.ts new file mode 100644 index 0000000000..986b2de2b0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/vite.config.ts @@ -0,0 +1,50 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'solid', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav head (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/head/vue/project.json b/benchmarks/client-nav/scenarios/head/vue/project.json new file mode 100644 index 0000000000..5ad7909d74 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-head-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/head/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/head/vue/setup.ts b/benchmarks/client-nav/scenarios/head/vue/setup.ts new file mode 100644 index 0000000000..3dd6bc95a5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, stepTestIds } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + steps: stepTestIds, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts new file mode 100644 index 0000000000..d188a9dd7a --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-head', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-head navigation loop (vue)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/head/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/head/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/head/vue/src/main.tsx b/benchmarks/client-nav/scenarios/head/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/src/main.tsx @@ -0,0 +1,41 @@ +import type { RouterHistory } from '@tanstack/history' +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..161f99a65c --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts @@ -0,0 +1,145 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as DocsRouteImport } from './routes/docs' +import { Route as SettingsRouteImport } from './routes/settings' +import { Route as ArticlesIdRouteImport } from './routes/articles.$id' +import { Route as DocsSectionRouteImport } from './routes/docs.$section' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + getParentRoute: () => rootRouteImport, +} as any) +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ArticlesIdRoute = ArticlesIdRouteImport.update({ + id: '/articles/$id', + path: '/articles/$id', + getParentRoute: () => rootRouteImport, +} as any) +const DocsSectionRoute = DocsSectionRouteImport.update({ + id: '/$section', + path: '/$section', + getParentRoute: () => DocsRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' + id: + | '__root__' + | '/' + | '/docs' + | '/settings' + | '/articles/$id' + | '/docs/$section' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DocsRoute: typeof DocsRouteWithChildren + SettingsRoute: typeof SettingsRoute + ArticlesIdRoute: typeof ArticlesIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/articles/$id': { + id: '/articles/$id' + path: '/articles/$id' + fullPath: '/articles/$id' + preLoaderRoute: typeof ArticlesIdRouteImport + parentRoute: typeof rootRouteImport + } + '/docs/$section': { + id: '/docs/$section' + path: '/$section' + fullPath: '/docs/$section' + preLoaderRoute: typeof DocsSectionRouteImport + parentRoute: typeof DocsRoute + } + } +} + +interface DocsRouteChildren { + DocsSectionRoute: typeof DocsSectionRoute +} + +const DocsRouteChildren: DocsRouteChildren = { + DocsSectionRoute: DocsSectionRoute, +} + +const DocsRouteWithChildren = DocsRoute._addFileChildren(DocsRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DocsRoute: DocsRouteWithChildren, + SettingsRoute: SettingsRoute, + ArticlesIdRoute: ArticlesIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..ad87699fef --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/src/routes/__root.tsx @@ -0,0 +1,58 @@ +import * as Vue from 'vue' +import { + HeadContent, + Link, + Outlet, + createRootRoute, +} from '@tanstack/vue-router' +import { articleIds, docsSections, rootHead } from '../../../shared' + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + ) + }, +}) + +export const Route = createRootRoute({ + head: rootHead, + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/articles.$id.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/articles.$id.tsx new file mode 100644 index 0000000000..43a6fade58 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/src/routes/articles.$id.tsx @@ -0,0 +1,21 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { articleDescription, articleHead, articleTitle } from '../../../shared' + +const ArticlePage = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
+

{articleTitle(params.value.id)}

+

{articleDescription(params.value.id)}

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

{docsTitle(params.value.section)}

+

{docsDescription(params.value.section)}

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

Docs

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

{homeTitle}

+

Landing page

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

{settingsTitle}

+

Account settings

+
+ ) + }, +}) + +export const Route = createFileRoute('/settings')({ + head: settingsHead, + component: SettingsPage, +}) diff --git a/benchmarks/client-nav/scenarios/head/vue/tsconfig.json b/benchmarks/client-nav/scenarios/head/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/head/vue/vite.config.ts b/benchmarks/client-nav/scenarios/head/vue/vite.config.ts new file mode 100644 index 0000000000..bb1126d85f --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/vite.config.ts @@ -0,0 +1,44 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav head (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/history/react/project.json b/benchmarks/client-nav/scenarios/history/react/project.json new file mode 100644 index 0000000000..a2fe0001be --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-history-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/history/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/history/react/setup.ts b/benchmarks/client-nav/scenarios/history/react/setup.ts new file mode 100644 index 0000000000..c26b7ffd08 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + historyMode: 'browser', + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/history/react/speed.bench.ts b/benchmarks/client-nav/scenarios/history/react/speed.bench.ts new file mode 100644 index 0000000000..6ec7031857 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-history', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-history navigation loop (react)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/history/react/speed.flame.ts b/benchmarks/client-nav/scenarios/history/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/history/react/src/main.tsx b/benchmarks/client-nav/scenarios/history/react/src/main.tsx new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/src/main.tsx @@ -0,0 +1,37 @@ +import type { RouterHistory } from '@tanstack/history' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const reactRoot = createRoot(container) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..21bb12ba35 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts @@ -0,0 +1,113 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as GalleryRouteImport } from './routes/gallery' +import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const GalleryRoute = GalleryRouteImport.update({ + id: '/gallery', + path: '/gallery', + getParentRoute: () => rootRouteImport, +} as any) +const PagesNRoute = PagesNRouteImport.update({ + id: '/pages/$n', + path: '/pages/$n', + getParentRoute: () => rootRouteImport, +} as any) +const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ + id: '/photos/$photoId', + path: '/photos/$photoId', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + id: '__root__' | '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + GalleryRoute: typeof GalleryRoute + PagesNRoute: typeof PagesNRoute + PhotosPhotoIdRoute: typeof PhotosPhotoIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/gallery': { + id: '/gallery' + path: '/gallery' + fullPath: '/gallery' + preLoaderRoute: typeof GalleryRouteImport + parentRoute: typeof rootRouteImport + } + '/pages/$n': { + id: '/pages/$n' + path: '/pages/$n' + fullPath: '/pages/$n' + preLoaderRoute: typeof PagesNRouteImport + parentRoute: typeof rootRouteImport + } + '/photos/$photoId': { + id: '/photos/$photoId' + path: '/photos/$photoId' + fullPath: '/photos/$photoId' + preLoaderRoute: typeof PhotosPhotoIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + GalleryRoute: GalleryRoute, + PagesNRoute: PagesNRoute, + PhotosPhotoIdRoute: PhotosPhotoIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/history/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/history/react/src/routes/__root.tsx new file mode 100644 index 0000000000..240d8719d4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/src/routes/__root.tsx @@ -0,0 +1,66 @@ +import { + Link, + Outlet, + createRootRoute, + useBlocker, + useCanGoBack, + useLocation, +} from '@tanstack/react-router' +import { maskedPhotoId, shouldBlockFn } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + const pathname = useLocation({ select: (location) => location.pathname }) + const canGoBack = useCanGoBack() + + useBlocker({ shouldBlockFn }) + + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/history/react/src/routes/gallery.tsx b/benchmarks/client-nav/scenarios/history/react/src/routes/gallery.tsx new file mode 100644 index 0000000000..55094556a6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/src/routes/gallery.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/gallery')({ + component: GalleryPage, +}) + +function GalleryPage() { + return ( +
+

Gallery

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

Home

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

{pageLabel(params.n)}

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

{photoLabel(params.photoId)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/history/react/tsconfig.json b/benchmarks/client-nav/scenarios/history/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/history/react/vite.config.ts b/benchmarks/client-nav/scenarios/history/react/vite.config.ts new file mode 100644 index 0000000000..bdbde9c668 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/vite.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'react', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav history (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/history/shared.ts b/benchmarks/client-nav/scenarios/history/shared.ts new file mode 100644 index 0000000000..be6096cea8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/shared.ts @@ -0,0 +1,94 @@ +/** + * Shared definition of the `history` scenario: push/replace/back/forward + * traversal, location masking, blocker registration overhead (the blocker + * never blocks), and useLocation/useCanGoBack subscriptions. + * + * The step lap is designed to keep the history depth stationary: it ends back + * on the initial entry, so the first push of the next lap truncates the stale + * forward tail and the session history never grows past 4 entries. + */ +import type { ScenarioStep } from '../harness' +import type { RouterHistory } from '@tanstack/history' + +export const pageIds = ['1', '2', '3'] as const +export const maskedPhotoId = '42' + +export function pageLabel(n: string) { + return `Page ${n}` +} + +export function photoLabel(id: string) { + return `Photo ${id}` +} + +/** Registered on every navigation, never blocks. */ +export const shouldBlockFn = () => false + +interface HistoryStepExpectation { + step: ScenarioStep + /** Expected router location pathname (the REAL location, even when masked). */ + pathname: string + /** Expected browser-history pathname when it differs (location masking). */ + windowPathname?: string + /** Marker test id that must be present in the container after the step. */ + marker?: string +} + +export const stepExpectations: ReadonlyArray = [ + { step: 'p-1', pathname: '/pages/1', marker: 'page-state' }, + { step: 'p-2', pathname: '/pages/2', marker: 'page-state' }, + { + step: 'photo-masked', + pathname: `/photos/${maskedPhotoId}`, + windowPathname: '/gallery', + marker: 'photo-state', + }, + { step: { type: 'back' }, pathname: '/pages/2', marker: 'page-state' }, + { step: { type: 'back' }, pathname: '/pages/1', marker: 'page-state' }, + { step: { type: 'forward' }, pathname: '/pages/2', marker: 'page-state' }, + { step: 'p-3-replace', pathname: '/pages/3', marker: 'page-state' }, + { step: { type: 'back' }, pathname: '/pages/1', marker: 'page-state' }, + { step: { type: 'back' }, pathname: '/', marker: 'home-state' }, +] + +export const steps = stepExpectations.map((expectation) => expectation.step) + +export function assertStepResult( + stepIndex: number, + container: HTMLElement, + history: RouterHistory, +) { + const expected = stepExpectations[stepIndex]! + + const loc = container.querySelector('[data-testid="loc"]')?.textContent + if (loc !== expected.pathname) { + throw new Error( + `Expected location marker to be "${expected.pathname}" after step ${stepIndex}, received "${loc}"`, + ) + } + + const windowPathname = expected.windowPathname ?? expected.pathname + if (history.location.pathname !== windowPathname) { + throw new Error( + `Expected history.location.pathname to be "${windowPathname}" after step ${stepIndex}, received "${history.location.pathname}"`, + ) + } + + if ( + expected.marker && + !container.querySelector(`[data-testid="${expected.marker}"]`) + ) { + throw new Error( + `Expected marker "${expected.marker}" to be rendered after step ${stepIndex}`, + ) + } +} + +// Two laps through the 9-step sequence per benchmark iteration. +export const ticksPerIteration = 18 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/history/solid/project.json b/benchmarks/client-nav/scenarios/history/solid/project.json new file mode 100644 index 0000000000..6f4bba1ca5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-history-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/history/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/history/solid/setup.ts b/benchmarks/client-nav/scenarios/history/solid/setup.ts new file mode 100644 index 0000000000..4adf55d6df --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + historyMode: 'browser', + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts new file mode 100644 index 0000000000..56af035b2b --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-history', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-history navigation loop (solid)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/history/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/history/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/main.tsx b/benchmarks/client-nav/scenarios/history/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/src/main.tsx @@ -0,0 +1,34 @@ +import type { RouterHistory } from '@tanstack/history' +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const unmount = render(() => , container) + + return { + router, + unmount, + } +} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..af253f4a15 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts @@ -0,0 +1,113 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as GalleryRouteImport } from './routes/gallery' +import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const GalleryRoute = GalleryRouteImport.update({ + id: '/gallery', + path: '/gallery', + getParentRoute: () => rootRouteImport, +} as any) +const PagesNRoute = PagesNRouteImport.update({ + id: '/pages/$n', + path: '/pages/$n', + getParentRoute: () => rootRouteImport, +} as any) +const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ + id: '/photos/$photoId', + path: '/photos/$photoId', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + id: '__root__' | '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + GalleryRoute: typeof GalleryRoute + PagesNRoute: typeof PagesNRoute + PhotosPhotoIdRoute: typeof PhotosPhotoIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/gallery': { + id: '/gallery' + path: '/gallery' + fullPath: '/gallery' + preLoaderRoute: typeof GalleryRouteImport + parentRoute: typeof rootRouteImport + } + '/pages/$n': { + id: '/pages/$n' + path: '/pages/$n' + fullPath: '/pages/$n' + preLoaderRoute: typeof PagesNRouteImport + parentRoute: typeof rootRouteImport + } + '/photos/$photoId': { + id: '/photos/$photoId' + path: '/photos/$photoId' + fullPath: '/photos/$photoId' + preLoaderRoute: typeof PhotosPhotoIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + GalleryRoute: GalleryRoute, + PagesNRoute: PagesNRoute, + PhotosPhotoIdRoute: PhotosPhotoIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/history/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..edf7368929 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/src/routes/__root.tsx @@ -0,0 +1,66 @@ +import { + Link, + Outlet, + createRootRoute, + useBlocker, + useCanGoBack, + useLocation, +} from '@tanstack/solid-router' +import { maskedPhotoId, shouldBlockFn } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + const pathname = useLocation({ select: (location) => location.pathname }) + const canGoBack = useCanGoBack() + + useBlocker({ shouldBlockFn }) + + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routes/gallery.tsx b/benchmarks/client-nav/scenarios/history/solid/src/routes/gallery.tsx new file mode 100644 index 0000000000..b72d1c6195 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/src/routes/gallery.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/gallery')({ + component: GalleryPage, +}) + +function GalleryPage() { + return ( +
+

Gallery

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

Home

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

{pageLabel(params().n)}

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

{photoLabel(params().photoId)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/history/solid/tsconfig.json b/benchmarks/client-nav/scenarios/history/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/history/solid/vite.config.ts b/benchmarks/client-nav/scenarios/history/solid/vite.config.ts new file mode 100644 index 0000000000..4da589ff0e --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/vite.config.ts @@ -0,0 +1,50 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'solid', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav history (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/history/vue/project.json b/benchmarks/client-nav/scenarios/history/vue/project.json new file mode 100644 index 0000000000..17fca887ca --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-history-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/history/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/history/vue/setup.ts b/benchmarks/client-nav/scenarios/history/vue/setup.ts new file mode 100644 index 0000000000..df689964e4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + historyMode: 'browser', + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts new file mode 100644 index 0000000000..3d36ac4cfa --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-history', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-history navigation loop (vue)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/history/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/history/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/history/vue/src/main.tsx b/benchmarks/client-nav/scenarios/history/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/src/main.tsx @@ -0,0 +1,41 @@ +import type { RouterHistory } from '@tanstack/history' +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..519aef7c8f --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts @@ -0,0 +1,113 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as GalleryRouteImport } from './routes/gallery' +import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const GalleryRoute = GalleryRouteImport.update({ + id: '/gallery', + path: '/gallery', + getParentRoute: () => rootRouteImport, +} as any) +const PagesNRoute = PagesNRouteImport.update({ + id: '/pages/$n', + path: '/pages/$n', + getParentRoute: () => rootRouteImport, +} as any) +const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ + id: '/photos/$photoId', + path: '/photos/$photoId', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + id: '__root__' | '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + GalleryRoute: typeof GalleryRoute + PagesNRoute: typeof PagesNRoute + PhotosPhotoIdRoute: typeof PhotosPhotoIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/gallery': { + id: '/gallery' + path: '/gallery' + fullPath: '/gallery' + preLoaderRoute: typeof GalleryRouteImport + parentRoute: typeof rootRouteImport + } + '/pages/$n': { + id: '/pages/$n' + path: '/pages/$n' + fullPath: '/pages/$n' + preLoaderRoute: typeof PagesNRouteImport + parentRoute: typeof rootRouteImport + } + '/photos/$photoId': { + id: '/photos/$photoId' + path: '/photos/$photoId' + fullPath: '/photos/$photoId' + preLoaderRoute: typeof PhotosPhotoIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + GalleryRoute: GalleryRoute, + PagesNRoute: PagesNRoute, + PhotosPhotoIdRoute: PhotosPhotoIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/history/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..7f7dff159c --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/src/routes/__root.tsx @@ -0,0 +1,69 @@ +import * as Vue from 'vue' +import { + Link, + Outlet, + createRootRoute, + useBlocker, + useCanGoBack, + useLocation, +} from '@tanstack/vue-router' +import { maskedPhotoId, shouldBlockFn } from '../../../shared' + +const RootComponent = Vue.defineComponent({ + setup() { + const pathname = useLocation({ select: (location) => location.pathname }) + const canGoBack = useCanGoBack() + + useBlocker({ shouldBlockFn }) + + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routes/gallery.tsx b/benchmarks/client-nav/scenarios/history/vue/src/routes/gallery.tsx new file mode 100644 index 0000000000..3a397b1843 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/src/routes/gallery.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const GalleryPage = Vue.defineComponent({ + setup() { + return () => ( +
+

Gallery

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

Home

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

{pageLabel(params.value.n)}

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

{photoLabel(params.value.photoId)}

+
+ ) + }, +}) + +export const Route = createFileRoute('/photos/$photoId')({ + component: PhotoComponent, +}) diff --git a/benchmarks/client-nav/scenarios/history/vue/tsconfig.json b/benchmarks/client-nav/scenarios/history/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/history/vue/vite.config.ts b/benchmarks/client-nav/scenarios/history/vue/vite.config.ts new file mode 100644 index 0000000000..c5f1ca9807 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/vite.config.ts @@ -0,0 +1,44 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav history (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/fixture.ts b/benchmarks/client-nav/scenarios/hydration/react/fixture.ts new file mode 100644 index 0000000000..950c870a1c --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/fixture.ts @@ -0,0 +1,31 @@ +export const ordinaryLinkCount = 192 +export const hashLinkCount = 8 +export const serverUrl = '/teams/team-7/items/item-42?view=summary' +export const clientUrl = `${serverUrl}#details` + +export interface Diagnostics { + beforeLoads: number + loaders: number + mounted: boolean + clicks: number + ordinaryRenders: number + hashRenders: number + countRenders: boolean +} + +export function createDiagnostics(countRenders = false): Diagnostics { + return { + beforeLoads: 0, + loaders: 0, + mounted: false, + clicks: 0, + ordinaryRenders: 0, + hashRenders: 0, + countRenders, + } +} + +export interface FixtureArtifact { + html: string + scripts: Array +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs b/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs new file mode 100644 index 0000000000..fbc67c5a08 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs @@ -0,0 +1,23 @@ +import assert from 'node:assert/strict' +import { writeFile } from 'node:fs/promises' +import { JSDOM } from 'jsdom' + +if (process.env.NODE_ENV !== 'production') { + throw new Error('Generate the hydration fixture in production mode') +} +const { renderFixture } = await import('./dist/server/server.js') +const html = await renderFixture() +const dom = new JSDOM(html) +try { + const scriptElements = [...dom.window.document.querySelectorAll('script')] + assert.ok(scriptElements.length > 0) + assert.ok(scriptElements.every((script) => !script.src)) + const scripts = scriptElements.map((script) => script.textContent) + assert.ok(scripts.some((script) => script.includes('$_TSR'))) + await writeFile( + new URL('./dist/fixture.json', import.meta.url), + JSON.stringify({ html, scripts }), + ) +} finally { + dom.window.close() +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts b/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts new file mode 100644 index 0000000000..7e466cbaed --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts @@ -0,0 +1,93 @@ +import { expect, test } from 'vitest' +import { hashLinkCount, ordinaryLinkCount } from './fixture' +import { setup } from './setup' +import { settleHydration } from './settle' + +const turn = () => new Promise((resolve) => setImmediate(resolve)) + +test('restores data and context into fresh DOMs and includes follow-up renders', async () => { + const scenario = setup({ countRenders: true }) + const schedulerTasks = new Set() + for (let iteration = 0; iteration < 3; iteration++) { + await scenario.before() + try { + expect(scenario.snapshot().diagnostics.mounted).toBe(false) + expect(scenario.snapshot().matches).toBeUndefined() + await scenario.run() + schedulerTasks.add(scenario.schedulerTasks()) + const completed = scenario.snapshot() + // Supports both main's extra Link update and the optimized snapshot. + expect([ordinaryLinkCount, ordinaryLinkCount * 2]).toContain( + completed.diagnostics.ordinaryRenders, + ) + expect(completed.diagnostics.hashRenders).toBeGreaterThanOrEqual( + hashLinkCount + hashLinkCount / 2, + ) + for (let index = 0; index < 4; index++) { + await turn() + } + expect(scenario.snapshot()).toEqual(completed) + await expect(scenario.run()).rejects.toThrow('newly prepared sample') + } finally { + await scenario.after() + } + } + // React yields on its pinned clock, never on wall time spent hydrating. + expect(schedulerTasks.size).toBe(1) +}) + +test('rejects an empty measurement and still releases its sample', async () => { + const scenario = setup() + await scenario.before() + await expect(scenario.after()).rejects.toThrow( + 'Hydration sample was not completed', + ) + await scenario.before() + try { + await scenario.run() + } finally { + await scenario.after() + } +}) + +test('waits for a commit and scheduler work lasting more than 100 turns', async () => { + let committed = false + const commit = (async () => { + for (let index = 0; index < 150; index++) { + await turn() + } + committed = true + })() + let remainingCallbacks = 150 + await settleHydration( + commit, + () => { + expect(committed).toBe(true) + return remainingCallbacks-- <= 0 + }, + () => 'delayed commit', + ) + expect(remainingCallbacks).toBeLessThan(0) +}) + +test('retains a watchdog for a commit that never completes', async () => { + await expect( + settleHydration( + new Promise(() => {}), + () => true, + () => 'commit pending', + 10, + ), + ).rejects.toThrow('Hydration did not settle within 10ms: commit pending') +}) + +test('retains a watchdog when scheduler work never becomes idle', async () => { + await expect( + settleHydration( + Promise.resolve(), + () => false, + () => 'callbacks pending', + 10, + ), + ).rejects.toThrow('Hydration did not settle within 10ms: callbacks pending') +}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/project.json b/benchmarks/client-nav/scenarios/hydration/react/project.json new file mode 100644 index 0000000000..ca23838c0f --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-hydration-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { "projects": ["@tanstack/react-router"], "target": "build" } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.server.config.ts && NODE_ENV=production node {projectRoot}/generate-fixture.mjs && NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:unit": { + "executor": "nx:run-commands", + "dependsOn": ["build:client"], + "options": { + "command": "vitest run --config ./scenarios/hydration/react/vite.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:perf": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --run --config ./scenarios/hydration/react/vite.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { "projects": ["@tanstack/react-router"], "target": "build" } + ], + "options": { "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" } + } + } +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/settle.ts b/benchmarks/client-nav/scenarios/hydration/react/settle.ts new file mode 100644 index 0000000000..cc4c09a72d --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/settle.ts @@ -0,0 +1,35 @@ +const turn = () => new Promise((resolve) => setImmediate(resolve)) + +export async function settleHydration( + committed: Promise, + isIdle: () => boolean, + describeProgress: () => string, + timeoutMs = 60_000, +) { + let timeoutError: Error | undefined + let watchdog: ReturnType | undefined + const timeout = new Promise((_, reject) => { + watchdog = setTimeout(() => { + timeoutError = new Error( + `Hydration did not settle within ${timeoutMs}ms: ${describeProgress()}`, + ) + reject(timeoutError) + }, timeoutMs) + }) + try { + // Concurrent hydration can need many more scheduler turns under CPU + // instrumentation. Await its commit instead of limiting successful work + // to an arbitrary number of event-loop polls. + await Promise.race([committed, timeout]) + let idleTurns = 0 + while (idleTurns < 2) { + await turn() + if (timeoutError) { + throw timeoutError + } + idleTurns = isIdle() ? idleTurns + 1 : 0 + } + } finally { + clearTimeout(watchdog) + } +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/setup.ts b/benchmarks/client-nav/scenarios/hydration/react/setup.ts new file mode 100644 index 0000000000..7c588af3fd --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/setup.ts @@ -0,0 +1,316 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { Script } from 'node:vm' +import { JSDOM, VirtualConsole } from 'jsdom' +import { clientUrl, hashLinkCount, ordinaryLinkCount } from './fixture' +import { settleHydration } from './settle' +import type { FixtureArtifact } from './fixture' +import type * as Client from './src/client' + +type ClientApp = typeof Client +const turn = () => new Promise((resolve) => setImmediate(resolve)) + +// React's scheduler ends a time slice once performance.now() has advanced 5 ms. +// Under CodSpeed's CPU simulation the wall clock advances much further per +// instruction, by a runner-dependent factor, so real time turned identical +// samples into different numbers of yields, scheduler tasks and event-loop +// turns. With a frozen clock React yields only to paint after a commit, as on +// a fast host. 1 s is past React's initial 300 ms fallback throttle. Only the +// window's performance clock is pinned: Date.now(), which the Router uses for +// match timestamps, is unchanged. +const schedulerTime = 1_000 + +export function setup({ countRenders = false } = {}) { + // Compile once, outside measurement. Evaluation below creates fresh objects + // in each window's realm; neither the payload nor module state is reused. + const artifact: FixtureArtifact = JSON.parse( + readFileSync(new URL('./dist/fixture.json', import.meta.url), 'utf8'), + ) + const clientPath = new URL('./dist/client/client.js', import.meta.url) + const clientScript = new Script(readFileSync(clientPath, 'utf8'), { + filename: fileURLToPath(clientPath), + }) + const bootstrapScripts = artifact.scripts.map( + (source, index) => + new Script(source, { + filename: `hydration-bootstrap-${index}.js`, + }), + ) + let current: Awaited> | undefined + + async function prepare() { + const errors: Array = [] + const virtualConsole = new VirtualConsole() + virtualConsole.on('jsdomError', (error) => errors.push(String(error))) + virtualConsole.on('error', (...args) => + errors.push(args.map(String).join(' ')), + ) + const dom = new JSDOM(artifact.html, { + url: `http://localhost${clientUrl}`, + runScripts: 'outside-only', + virtualConsole, + }) + const immediates = new Set() + const scheduler = { tasks: 0 } + try { + Object.assign(dom.window, { + TextEncoder, + TextDecoder, + ReadableStream, + WritableStream, + TransformStream, + // Let React's production scheduler use the same task-turn primitive as + // the existing Node client benchmarks, without a real-delay timer. + setImmediate( + callback: (...args: Array) => void, + ...args: Array + ) { + scheduler.tasks++ + const handle = setImmediate(() => { + immediates.delete(handle) + callback(...args) + }) + immediates.add(handle) + return handle + }, + clearImmediate(handle: NodeJS.Immediate) { + immediates.delete(handle) + clearImmediate(handle) + }, + fetch() { + throw new Error('Hydration attempted a network request') + }, + scrollTo() {}, + }) + dom.window.performance.now = () => schedulerTime + const context = dom.getInternalVMContext() + // jsdom has no layout/scroll implementation; only hydration CPU is measured. + dom.window.HTMLElement.prototype.scrollIntoView = () => {} + clientScript.runInContext(context) + const app = (dom.window as unknown as { HydrationBenchmark: ClientApp }) + .HydrationBenchmark + assert.equal(app.serverEnvironment, false) + const anchors = Array.from(dom.window.document.querySelectorAll('a')) + const scriptElements = Array.from( + dom.window.document.querySelectorAll('script'), + ) + const executingScript = { current: null as HTMLScriptElement | null } + Object.defineProperty(dom.window.document, 'currentScript', { + configurable: true, + get: () => executingScript.current, + }) + assert.equal(anchors.length, ordinaryLinkCount + hashLinkCount) + const content = dom.window.document.getElementById('hydration-content') + assert.ok(content) + // Finish jsdom's initial document lifecycle before opening the measure. + await turn() + assert.equal(dom.window.document.readyState, 'complete') + assert.equal(app.ready(), false) + return { + dom, + context, + app, + anchors, + content, + scriptElements, + executingScript, + immediates, + scheduler, + errors, + started: false, + completed: false, + failed: false, + } + } catch (error) { + for (const handle of immediates) { + clearImmediate(handle) + } + dom.window.close() + throw error + } + } + + async function before() { + if (current) { + throw new Error('Previous hydration sample was not disposed') + } + current = await prepare() + } + + async function run() { + const sample = current + if (!sample || sample.started) { + throw new Error('Hydration requires a newly prepared sample') + } + sample.started = true + try { + // HTML parsing/module evaluation are already done. Payload execution, + // router initialization/restoration and React hydration are measured. + for (let index = 0; index < bootstrapScripts.length; index++) { + // SSR bootstrap scripts remove their own script element after running. + sample.executingScript.current = sample.scriptElements[index]! + try { + bootstrapScripts[index]!.runInContext(sample.context) + } finally { + sample.executingScript.current = null + } + } + await settleHydration( + sample.app.start(countRenders), + () => sample.immediates.size === 0, + () => { + const progress = sample.app.snapshot() + return JSON.stringify({ + diagnostics: progress.diagnostics, + errors: [...sample.errors, ...progress.errors], + restoredMatches: progress.matches?.length, + pendingSchedulerCallbacks: sample.immediates.size, + }) + }, + ) + if (sample.errors.length) { + throw new Error(sample.errors.join('\n')) + } + assert.ok( + sample.app.ready(), + 'Hydration committed without the expected active links', + ) + sample.completed = true + } catch (error) { + sample.failed = true + throw error + } + } + + function snapshot() { + if (!current) { + throw new Error('No hydration sample') + } + // Normalize realm prototypes only for untimed assertions. + return JSON.parse(JSON.stringify(current.app.snapshot())) as ReturnType< + ClientApp['snapshot'] + > + } + + function schedulerTasks() { + if (!current) { + throw new Error('No hydration sample') + } + return current.scheduler.tasks + } + + function validate() { + assert.ok(current?.started) + const { dom, anchors, content, errors } = current + const doc = dom.window.document + const result = snapshot() + assert.deepEqual(errors, []) + assert.deepEqual(result.errors, []) + assert.equal(result.diagnostics.beforeLoads, 0) + assert.equal(result.diagnostics.loaders, 0) + assert.equal(result.diagnostics.mounted, true) + assert.equal(result.location, clientUrl) + assert.equal(result.matches?.length, 3) + for (const match of result.matches) { + assert.equal(match.status, 'success') + assert.deepEqual(match.context.viewer, { + id: 'viewer-3', + name: 'Ada', + role: 'editor', + }) + } + assert.deepEqual(result.matches[1]!.context.team, { + id: 'team-7', + member: 'viewer-3', + }) + assert.deepEqual(result.matches[2]!.context.permissions, { edit: true }) + assert.deepEqual(result.matches[1]!.loaderData, { + title: 'Team team-7', + categories: ['open', 'closed'], + }) + const data = result.matches[2]!.loaderData as { + owner: string + selected: string + rows: Array<{ + id: string + label: string + details: { score: number; open: boolean } + }> + } + assert.equal(data.owner, 'viewer-3') + assert.equal(data.selected, 'item-42') + assert.equal(data.rows.length, ordinaryLinkCount) + assert.equal(doc.getElementById('hydration-content'), content) + assert.equal(doc.querySelectorAll('a').length, anchors.length) + assert.equal(doc.getElementById('viewer')?.textContent, 'Ada') + assert.equal(doc.getElementById('permission')?.textContent, 'Editable') + for (const anchor of anchors) { + assert.equal(doc.getElementById(anchor.id), anchor) + } + for (let index = 0; index < ordinaryLinkCount; index++) { + const anchor = doc.getElementById(`ordinary-item-${index}`)! + assert.equal( + anchor.getAttribute('href'), + `/teams/team-7/items/item-${index}?view=summary`, + ) + assert.equal(anchor.textContent, `Item ${index}`) + assert.equal( + anchor.getAttribute('data-status'), + index === 42 ? 'active' : null, + ) + assert.deepEqual(data.rows[index], { + id: `item-${index}`, + label: `Item ${index}`, + details: { score: index * 3, open: index % 2 === 0 }, + }) + } + for (let index = 0; index < hashLinkCount; index++) { + assert.equal( + doc.getElementById(`hash-${index}`)?.getAttribute('data-status'), + index % 2 === 0 ? 'active' : null, + ) + } + doc + .getElementById('interactive')! + .dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })) + assert.equal( + current.app.snapshot().diagnostics.clicks, + result.diagnostics.clicks + 1, + ) + } + + async function after() { + const sample = current + if (!sample) { + return + } + try { + if (!sample.failed) { + assert.ok(sample.completed, 'Hydration sample was not completed') + validate() + } + } finally { + current = undefined + try { + sample.app.dispose() + // Unmount work and its scheduled effects stay outside the measure. + await turn() + await turn() + } finally { + for (const handle of sample.immediates) { + clearImmediate(handle) + } + sample.dom.window.close() + } + } + } + + return { + before, + run, + after, + snapshot, + schedulerTasks, + } +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts b/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts new file mode 100644 index 0000000000..643877760e --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { setup } from './setup' + +test('client-hydration', async ({ bench }) => { + const scenario = setup() + + await bench( + 'hydrate restored route state and mixed Links (react)', + { beforeEach: scenario.before, afterEach: scenario.after }, + async () => { + await scenario.run() + }, + ).run({ + time: 5000, + warmupTime: 1000, + warmupIterations: 20, + throws: true, + }) +}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx b/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx new file mode 100644 index 0000000000..e9797f71fa --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx @@ -0,0 +1,216 @@ +import { useEffect } from 'react' +import { + HeadContent, + Link, + Outlet, + Scripts, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + useHydrated, +} from '@tanstack/react-router' +import { + clientUrl, + hashLinkCount, + ordinaryLinkCount, + serverUrl, +} from '../fixture' +import type { ReactNode } from 'react' +import type { Diagnostics } from '../fixture' + +export function createFixtureRouter( + server: boolean, + diagnostics: Diagnostics, + onHydrated: () => void = () => {}, +) { + function beforeLoad() { + diagnostics.beforeLoads++ + if (!server) { + throw new Error('Hydration reran beforeLoad instead of restoring context') + } + } + + function loader() { + diagnostics.loaders++ + if (!server) { + throw new Error('Hydration reran a loader instead of restoring data') + } + } + + const root = createRootRoute({ + beforeLoad: () => { + beforeLoad() + return { viewer: { id: 'viewer-3', name: 'Ada', role: 'editor' } } + }, + head: () => ({ + meta: [{ charSet: 'utf-8' }, { title: 'Hydration benchmark' }], + }), + shellComponent: Document, + }) + const team = createRoute({ + getParentRoute: () => root, + path: '/teams/$teamId', + beforeLoad: ({ context, params }) => { + beforeLoad() + return { team: { id: params.teamId, member: context.viewer.id } } + }, + loader: ({ context }) => { + loader() + return { + title: `Team ${context.team.id}`, + categories: ['open', 'closed'], + } + }, + component: Team, + }) + const items = createRoute({ + getParentRoute: () => team, + path: 'items/$itemId', + validateSearch: (search: Record) => ({ + view: search.view === 'details' ? 'details' : 'summary', + }), + beforeLoad: ({ context }) => { + beforeLoad() + return { permissions: { edit: context.viewer.role === 'editor' } } + }, + loader: ({ context, params }) => { + loader() + return { + selected: params.itemId, + owner: context.team.member, + rows: Array.from({ length: ordinaryLinkCount }, (_, index) => ({ + id: `item-${index}`, + label: `Item ${index}`, + details: { score: index * 3, open: index % 2 === 0 }, + })), + } + }, + component: Items, + }) + + function Document({ children }: { children: ReactNode }) { + return ( + + + + + + {children} + + + + ) + } + + function Team() { + const context = team.useRouteContext() + const data = team.useLoaderData() + return ( +
+

{data.title}

+

{context.viewer.name}

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

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

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

{data().title}

+

{context().viewer.name}

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

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

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

{detailMarker(params.id)}

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

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

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

{otherMarker}

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

{detailMarker(params().id)}

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

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

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

{otherMarker}

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

{detailMarker(params.value.id)}

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

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

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

{otherMarker}

+
+ ) + }, +}) + +export const Route = createFileRoute('/other')({ + component: OtherPage, +}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json b/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts b/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts new file mode 100644 index 0000000000..8f56734e04 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts @@ -0,0 +1,44 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav link-churn (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/links/react/project.json b/benchmarks/client-nav/scenarios/links/react/project.json new file mode 100644 index 0000000000..52c9df8a68 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-links-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/links/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/links/react/setup.ts b/benchmarks/client-nav/scenarios/links/react/setup.ts new file mode 100644 index 0000000000..5409df903c --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, scenarioSteps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + steps: scenarioSteps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/links/react/speed.bench.ts b/benchmarks/client-nav/scenarios/links/react/speed.bench.ts new file mode 100644 index 0000000000..75f5f725d4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-links', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-links navigation loop (react)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/links/react/speed.flame.ts b/benchmarks/client-nav/scenarios/links/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/links/react/src/main.tsx b/benchmarks/client-nav/scenarios/links/react/src/main.tsx new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/src/main.tsx @@ -0,0 +1,37 @@ +import type { RouterHistory } from '@tanstack/history' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const reactRoot = createRoot(container) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..6e0c29ca88 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' +import { Route as ItemsIdRouteImport } from './routes/items.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) +const ItemsIdRoute = ItemsIdRouteImport.update({ + id: '/items/$id', + path: '/items/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/about' | '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/about' | '/items/$id' + id: '__root__' | '/' | '/about' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AboutRoute: typeof AboutRoute + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } + '/items/$id': { + id: '/items/$id' + path: '/items/$id' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AboutRoute: AboutRoute, + ItemsIdRoute: ItemsIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/links/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/links/react/src/routes/__root.tsx new file mode 100644 index 0000000000..7a48510e8a --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/src/routes/__root.tsx @@ -0,0 +1,104 @@ +import { + Link, + Outlet, + createRootRoute, + useMatchRoute, +} from '@tanstack/react-router' +import { + itemIds, + matchProbeIds, + stepItemIds, + variantSearch, +} from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function StatusPanel() { + const matchRoute = useMatchRoute() + + return ( + + ) +} + +function LinkGrid() { + return ( +
+ {itemIds.map((id) => ( +
+ + {`Item ${id}`} + + + {`Item ${id} exact`} + + + {`Item ${id} search`} + + + {`Item ${id} hash`} + + + {({ isActive }) => (isActive ? `Item ${id} on` : `Item ${id} off`)} + +
+ ))} +
+ ) +} + +function RootComponent() { + return ( + <> + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/links/react/src/routes/about.tsx b/benchmarks/client-nav/scenarios/links/react/src/routes/about.tsx new file mode 100644 index 0000000000..0e4afc9297 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/src/routes/about.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' +import { aboutMarker } from '../../../shared' + +export const Route = createFileRoute('/about')({ + component: AboutPage, +}) + +function AboutPage() { + return ( +
+

{aboutMarker}

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

{homeMarker}

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

{itemMarker(params.id)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/links/react/tsconfig.json b/benchmarks/client-nav/scenarios/links/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/links/react/vite.config.ts b/benchmarks/client-nav/scenarios/links/react/vite.config.ts new file mode 100644 index 0000000000..69de10b5b7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/vite.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'react', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav links (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/links/shared.ts b/benchmarks/client-nav/scenarios/links/shared.ts new file mode 100644 index 0000000000..6e75ea045c --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/shared.ts @@ -0,0 +1,133 @@ +/** + * Shared definition of the `links` scenario: a large persistent grid of + * ``s in the root layout so every navigation recomputes link props and + * active state across many activeOptions variants, plus `useMatchRoute` / + * `MatchRoute` consumers. The three framework apps consume these constants so + * the workload is identical modulo the rendering layer. + */ +import type { ScenarioStep } from '../harness' + +// 40 item ids x 5 link variants = 200 links mounted in the root layout. +export const LINK_ITEM_COUNT = 40 +export const LINK_VARIANT_COUNT = 5 + +export const itemIds = Array.from({ length: LINK_ITEM_COUNT }, (_, index) => + String(index + 1), +) + +// Static search object attached to the includeSearch:false variant. +export const variantSearch = { tab: 'specs', page: 2 } + +// Item ids that get a `go-item-` test id on their plain variant link. +export const stepItemIds = ['1', '7', '13', '25', '40'] + +// Ids probed by the useMatchRoute checks in the root StatusPanel. +export const matchProbeIds = [ + '1', + '5', + '7', + '13', + '20', + '25', + '30', + '35', + '40', + '2', +] + +export function itemMarker(id: string) { + return `item-${id}` +} + +export const homeMarker = 'home' +export const aboutMarker = 'about' + +interface StepDef { + testId: string + marker: string + /** Expected number of `.active-link` elements after the step. */ + activeCount: number + /** When one link is active, its href must include this substring. */ + activeHrefPart?: string +} + +export const stepDefs: ReadonlyArray = [ + { + testId: 'go-item-1', + marker: itemMarker('1'), + activeCount: 1, + activeHrefPart: '/items/1', + }, + { + testId: 'go-item-7', + marker: itemMarker('7'), + activeCount: 1, + activeHrefPart: '/items/7', + }, + { testId: 'go-about', marker: aboutMarker, activeCount: 0 }, + { + testId: 'go-item-13', + marker: itemMarker('13'), + activeCount: 1, + activeHrefPart: '/items/13', + }, + { + testId: 'go-item-25', + marker: itemMarker('25'), + activeCount: 1, + activeHrefPart: '/items/25', + }, + { + testId: 'go-item-40', + marker: itemMarker('40'), + activeCount: 1, + activeHrefPart: '/items/40', + }, + { + testId: 'go-item-7', + marker: itemMarker('7'), + activeCount: 1, + activeHrefPart: '/items/7', + }, + { testId: 'go-home', marker: homeMarker, activeCount: 0 }, +] + +export const scenarioSteps: ReadonlyArray = stepDefs.map( + (step) => step.testId, +) + +export function assertStepResult(stepIndex: number, container: HTMLElement) { + const step = stepDefs[stepIndex]! + + const marker = container.querySelector('[data-testid="page-state"]') + if (marker?.textContent !== step.marker) { + throw new Error( + `Expected page marker "${step.marker}" after step ${stepIndex}, received "${marker?.textContent}"`, + ) + } + + const activeLinks = container.querySelectorAll('a.active-link') + if (activeLinks.length !== step.activeCount) { + throw new Error( + `Expected ${step.activeCount} active link(s) after step ${stepIndex}, received ${activeLinks.length}`, + ) + } + if (step.activeHrefPart) { + const href = activeLinks[0]!.getAttribute('href') ?? '' + if (!href.includes(step.activeHrefPart)) { + throw new Error( + `Expected the active link href to include "${step.activeHrefPart}" after step ${stepIndex}, received "${href}"`, + ) + } + } +} + +// One lap through the 8-step sequence per benchmark iteration; each step +// recomputes all 200 links plus the match probes. +export const ticksPerIteration = 8 + +export const benchOptions = { + warmupIterations: 50, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/links/solid/project.json b/benchmarks/client-nav/scenarios/links/solid/project.json new file mode 100644 index 0000000000..ef1dab4c50 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-links-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/links/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/links/solid/setup.ts b/benchmarks/client-nav/scenarios/links/solid/setup.ts new file mode 100644 index 0000000000..34270fe8a4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, scenarioSteps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + steps: scenarioSteps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts new file mode 100644 index 0000000000..fc7f3e71e7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-links', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-links navigation loop (solid)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/links/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/links/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/links/solid/src/main.tsx b/benchmarks/client-nav/scenarios/links/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/src/main.tsx @@ -0,0 +1,34 @@ +import type { RouterHistory } from '@tanstack/history' +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const unmount = render(() => , container) + + return { + router, + unmount, + } +} diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..0da70513e8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' +import { Route as ItemsIdRouteImport } from './routes/items.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) +const ItemsIdRoute = ItemsIdRouteImport.update({ + id: '/items/$id', + path: '/items/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/about' | '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/about' | '/items/$id' + id: '__root__' | '/' | '/about' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AboutRoute: typeof AboutRoute + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } + '/items/$id': { + id: '/items/$id' + path: '/items/$id' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AboutRoute: AboutRoute, + ItemsIdRoute: ItemsIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/links/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..a889a26854 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/src/routes/__root.tsx @@ -0,0 +1,119 @@ +import { For } from 'solid-js' +import { + Link, + Outlet, + createRootRoute, + useMatchRoute, +} from '@tanstack/solid-router' +import { + itemIds, + matchProbeIds, + stepItemIds, + variantSearch, +} from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function StatusPanel() { + const matchRoute = useMatchRoute() + + return ( + + ) +} + +function LinkGrid() { + return ( +
+ + {(id) => ( +
+ + {`Item ${id}`} + + + {`Item ${id} exact`} + + + {`Item ${id} search`} + + + {`Item ${id} hash`} + + + {({ isActive }) => + isActive ? `Item ${id} on` : `Item ${id} off` + } + +
+ )} +
+
+ ) +} + +function RootComponent() { + return ( + <> + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routes/about.tsx b/benchmarks/client-nav/scenarios/links/solid/src/routes/about.tsx new file mode 100644 index 0000000000..a2a71678b7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/src/routes/about.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { aboutMarker } from '../../../shared' + +export const Route = createFileRoute('/about')({ + component: AboutPage, +}) + +function AboutPage() { + return ( +
+

{aboutMarker}

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

{homeMarker}

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

{itemMarker(params().id)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/links/solid/tsconfig.json b/benchmarks/client-nav/scenarios/links/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/links/solid/vite.config.ts b/benchmarks/client-nav/scenarios/links/solid/vite.config.ts new file mode 100644 index 0000000000..e37342ffc3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/vite.config.ts @@ -0,0 +1,50 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'solid', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav links (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/links/vue/project.json b/benchmarks/client-nav/scenarios/links/vue/project.json new file mode 100644 index 0000000000..fe1e68fad3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-links-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/links/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/links/vue/setup.ts b/benchmarks/client-nav/scenarios/links/vue/setup.ts new file mode 100644 index 0000000000..f70a154909 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, scenarioSteps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + steps: scenarioSteps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts new file mode 100644 index 0000000000..2ace7a8409 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-links', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-links navigation loop (vue)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/links/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/links/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/links/vue/src/main.tsx b/benchmarks/client-nav/scenarios/links/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/src/main.tsx @@ -0,0 +1,41 @@ +import type { RouterHistory } from '@tanstack/history' +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..7d2b1e9bbb --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' +import { Route as ItemsIdRouteImport } from './routes/items.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) +const ItemsIdRoute = ItemsIdRouteImport.update({ + id: '/items/$id', + path: '/items/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/about' | '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/about' | '/items/$id' + id: '__root__' | '/' | '/about' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AboutRoute: typeof AboutRoute + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } + '/items/$id': { + id: '/items/$id' + path: '/items/$id' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AboutRoute: AboutRoute, + ItemsIdRoute: ItemsIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/links/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..04f99677fd --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/src/routes/__root.tsx @@ -0,0 +1,120 @@ +import * as Vue from 'vue' +import { + Link, + Outlet, + createRootRoute, + useMatchRoute, +} from '@tanstack/vue-router' +import { + itemIds, + matchProbeIds, + stepItemIds, + variantSearch, +} from '../../../shared' + +const StatusPanel = Vue.defineComponent({ + setup() { + const matchRoute = useMatchRoute() + const probes = matchProbeIds.map((id) => ({ + id, + match: matchRoute({ to: '/items/$id', params: { id } }), + })) + // Static probes use the setup-scoped matchRoute instead of : + // vue-router's MatchRoute creates an undisposed watcher per render (one + // leaked subscription per navigation), so all three apps use + // useMatchRoute for cross-framework parity. + const atHome = matchRoute({ to: '/' }) + const atAbout = matchRoute({ to: '/about' }) + const underRoot = matchRoute({ to: '/', fuzzy: true }) + const underAbout = matchRoute({ to: '/about', fuzzy: true }) + const aboutSearch = matchRoute({ to: '/about', includeSearch: true }) + + return () => ( + + ) + }, +}) + +const LinkGrid = Vue.defineComponent({ + setup() { + return () => ( +
+ {itemIds.map((id) => ( +
+ + {`Item ${id}`} + + + {`Item ${id} exact`} + + + {`Item ${id} search`} + + + {`Item ${id} hash`} + + + {({ isActive }: { isActive: boolean }) => + isActive ? `Item ${id} on` : `Item ${id} off` + } + +
+ ))} +
+ ) + }, +}) + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routes/about.tsx b/benchmarks/client-nav/scenarios/links/vue/src/routes/about.tsx new file mode 100644 index 0000000000..5cc1473bff --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/src/routes/about.tsx @@ -0,0 +1,17 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { aboutMarker } from '../../../shared' + +const AboutPage = Vue.defineComponent({ + setup() { + return () => ( +
+

{aboutMarker}

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

{homeMarker}

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

{itemMarker(params.value.id)}

+
+ ) + }, +}) + +export const Route = createFileRoute('/items/$id')({ + component: ItemPage, +}) diff --git a/benchmarks/client-nav/scenarios/links/vue/tsconfig.json b/benchmarks/client-nav/scenarios/links/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/links/vue/vite.config.ts b/benchmarks/client-nav/scenarios/links/vue/vite.config.ts new file mode 100644 index 0000000000..ad89a49d70 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/vite.config.ts @@ -0,0 +1,44 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav links (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/loaders/react/project.json b/benchmarks/client-nav/scenarios/loaders/react/project.json new file mode 100644 index 0000000000..d3dbe585d4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-loaders-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/loaders/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/setup.ts b/benchmarks/client-nav/scenarios/loaders/react/setup.ts new file mode 100644 index 0000000000..130583b190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts new file mode 100644 index 0000000000..8bcc53b88e --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-loaders', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-loaders navigation loop (react)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/loaders/react/speed.flame.ts b/benchmarks/client-nav/scenarios/loaders/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx @@ -0,0 +1,37 @@ +import type { RouterHistory } from '@tanstack/history' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const reactRoot = createRoot(container) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..35908a225f --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts @@ -0,0 +1,113 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as DepsRouteImport } from './routes/deps' +import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as FreshIdRouteImport } from './routes/fresh.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DepsRoute = DepsRouteImport.update({ + id: '/deps', + path: '/deps', + getParentRoute: () => rootRouteImport, +} as any) +const CachedIdRoute = CachedIdRouteImport.update({ + id: '/cached/$id', + path: '/cached/$id', + getParentRoute: () => rootRouteImport, +} as any) +const FreshIdRoute = FreshIdRouteImport.update({ + id: '/fresh/$id', + path: '/fresh/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/deps' | '/cached/$id' | '/fresh/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/deps' | '/cached/$id' | '/fresh/$id' + id: '__root__' | '/' | '/deps' | '/cached/$id' | '/fresh/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DepsRoute: typeof DepsRoute + CachedIdRoute: typeof CachedIdRoute + FreshIdRoute: typeof FreshIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/deps': { + id: '/deps' + path: '/deps' + fullPath: '/deps' + preLoaderRoute: typeof DepsRouteImport + parentRoute: typeof rootRouteImport + } + '/cached/$id': { + id: '/cached/$id' + path: '/cached/$id' + fullPath: '/cached/$id' + preLoaderRoute: typeof CachedIdRouteImport + parentRoute: typeof rootRouteImport + } + '/fresh/$id': { + id: '/fresh/$id' + path: '/fresh/$id' + fullPath: '/fresh/$id' + preLoaderRoute: typeof FreshIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DepsRoute: DepsRoute, + CachedIdRoute: CachedIdRoute, + FreshIdRoute: FreshIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/routes/__root.tsx new file mode 100644 index 0000000000..6309763cf3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/src/routes/__root.tsx @@ -0,0 +1,70 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routes/cached.$id.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/routes/cached.$id.tsx new file mode 100644 index 0000000000..9b954185cc --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/src/routes/cached.$id.tsx @@ -0,0 +1,55 @@ +import { createFileRoute } from '@tanstack/react-router' +import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' + +export const Route = createFileRoute('/cached/$id')({ + loader: ({ params }) => { + const items = makeItems(`cached-${params.id}`) + return { items, checksum: itemsChecksum(items) } + }, + staleTime: 1e9, + gcTime: 1e9, + component: CachedPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function SumSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.checksum), + }) + + void computeChecksum(value) + return null +} + +function FirstItemSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.items[0]?.value ?? 0), + }) + + void computeChecksum(value) + return null +} + +function CachedPage() { + const params = Route.useParams() + const loaderData = Route.useLoaderData() + + return ( +
+ {subscriberIndexes.map((index) => ( + + ))} + {subscriberIndexes.map((index) => ( + + ))} +

Cached

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

Deps

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

Fresh

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

Loaders Bench

+
home
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/tsconfig.json b/benchmarks/client-nav/scenarios/loaders/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts new file mode 100644 index 0000000000..818b224130 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'react', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav loaders (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/loaders/shared.ts b/benchmarks/client-nav/scenarios/loaders/shared.ts new file mode 100644 index 0000000000..f744246160 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/shared.ts @@ -0,0 +1,134 @@ +/** + * Shared definition of the `loaders` scenario: deterministic loader data + * derivation, the click sequence, and per-step sanity assertions. The three + * framework apps consume these builders so the workload is identical modulo + * the rendering layer. + * + * Isolates: client loader dispatch — always-stale re-runs (staleTime 0), + * pure cache hits (staleTime 1e9), loaderDeps-keyed caching, + * router.invalidate(), and useLoaderData selector subscriptions. + */ + +import type { ScenarioStep } from '../harness' + +export function computeChecksum(seed: number) { + let value = Math.trunc(seed) | 0 + + for (let index = 0; index < 40; index++) { + value = (value * 1664525 + 1013904223 + index) >>> 0 + } + + return value +} + +export interface LoaderItem { + id: string + name: string + value: number + flag: boolean +} + +export function makeItems(seedText: string): Array { + let seed = 0 + for (let index = 0; index < seedText.length; index++) { + seed = (seed * 31 + seedText.charCodeAt(index)) >>> 0 + } + + const items: Array = [] + let value = seed + + for (let index = 0; index < 50; index++) { + value = (value * 1664525 + 1013904223) >>> 0 + items.push({ + id: `${seedText}-${index}`, + name: `Item ${index} of ${seedText}`, + value: value % 100000, + flag: value % 3 === 0, + }) + } + + return items +} + +export function itemsChecksum(items: Array) { + let sum = 0 + for (const item of items) { + sum = (sum + item.value + (item.flag ? 1 : 0)) >>> 0 + } + return sum +} + +export function normalizePage(value: unknown) { + const page = Number(value) + return Number.isFinite(page) && page > 0 ? Math.trunc(page) : 1 +} + +export function freshMarkerText(id: string) { + return `f-${id}-${itemsChecksum(makeItems(`fresh-${id}`))}` +} + +export function cachedMarkerText(id: string) { + return `c-${id}-${itemsChecksum(makeItems(`cached-${id}`))}` +} + +export function depsMarkerText(page: number) { + return `d-${page}-${itemsChecksum(makeItems(`deps-${page}`))}` +} + +export const steps: ReadonlyArray = [ + 'go-fresh-1', + 'go-fresh-2', + 'go-cached-1', + 'go-cached-2', + 'go-deps-1', + 'go-deps-2', + // Invalidates the currently matched routes (the deps route), re-running its + // loader with unchanged deps. Note: this also marks the cached fresh/cached + // matches invalid, so each of those loaders re-runs once per lap on its next + // visit — deterministic, identical work every lap. + { type: 'invalidate' }, + 'go-home', +] + +interface ExpectedState { + testId: string + text?: string +} + +const expectedStates: ReadonlyArray = [ + { testId: 'fresh-state', text: freshMarkerText('1') }, + { testId: 'fresh-state', text: freshMarkerText('2') }, + { testId: 'cached-state', text: cachedMarkerText('1') }, + { testId: 'cached-state', text: cachedMarkerText('2') }, + { testId: 'deps-state', text: depsMarkerText(1) }, + { testId: 'deps-state', text: depsMarkerText(2) }, + // After invalidate the deps loader re-ran with the same deps. + { testId: 'deps-state', text: depsMarkerText(2) }, + { testId: 'home-state' }, +] + +export function assertStepResult(stepIndex: number, container: HTMLElement) { + const expected = expectedStates[stepIndex]! + const element = container.querySelector(`[data-testid="${expected.testId}"]`) + + if (!element) { + throw new Error( + `Expected marker "${expected.testId}" to exist after step ${stepIndex}`, + ) + } + + if (expected.text !== undefined && element.textContent !== expected.text) { + throw new Error( + `Expected marker "${expected.testId}" to read "${expected.text}" after step ${stepIndex}, received "${element.textContent}"`, + ) + } +} + +// Two laps through the 8-step sequence per benchmark iteration. +export const ticksPerIteration = 16 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/project.json b/benchmarks/client-nav/scenarios/loaders/solid/project.json new file mode 100644 index 0000000000..071e6bc385 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-loaders-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/loaders/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/setup.ts b/benchmarks/client-nav/scenarios/loaders/solid/setup.ts new file mode 100644 index 0000000000..6a46971603 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts new file mode 100644 index 0000000000..953a17b31a --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-loaders', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-loaders navigation loop (solid)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/loaders/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/loaders/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx @@ -0,0 +1,34 @@ +import type { RouterHistory } from '@tanstack/history' +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const unmount = render(() => , container) + + return { + router, + unmount, + } +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..fa5d032141 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts @@ -0,0 +1,113 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as DepsRouteImport } from './routes/deps' +import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as FreshIdRouteImport } from './routes/fresh.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DepsRoute = DepsRouteImport.update({ + id: '/deps', + path: '/deps', + getParentRoute: () => rootRouteImport, +} as any) +const CachedIdRoute = CachedIdRouteImport.update({ + id: '/cached/$id', + path: '/cached/$id', + getParentRoute: () => rootRouteImport, +} as any) +const FreshIdRoute = FreshIdRouteImport.update({ + id: '/fresh/$id', + path: '/fresh/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/deps' | '/cached/$id' | '/fresh/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/deps' | '/cached/$id' | '/fresh/$id' + id: '__root__' | '/' | '/deps' | '/cached/$id' | '/fresh/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DepsRoute: typeof DepsRoute + CachedIdRoute: typeof CachedIdRoute + FreshIdRoute: typeof FreshIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/deps': { + id: '/deps' + path: '/deps' + fullPath: '/deps' + preLoaderRoute: typeof DepsRouteImport + parentRoute: typeof rootRouteImport + } + '/cached/$id': { + id: '/cached/$id' + path: '/cached/$id' + fullPath: '/cached/$id' + preLoaderRoute: typeof CachedIdRouteImport + parentRoute: typeof rootRouteImport + } + '/fresh/$id': { + id: '/fresh/$id' + path: '/fresh/$id' + fullPath: '/fresh/$id' + preLoaderRoute: typeof FreshIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DepsRoute: DepsRoute, + CachedIdRoute: CachedIdRoute, + FreshIdRoute: FreshIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..30350f7907 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/__root.tsx @@ -0,0 +1,66 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/cached.$id.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/cached.$id.tsx new file mode 100644 index 0000000000..aab6be74dc --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/cached.$id.tsx @@ -0,0 +1,62 @@ +import { For, createRenderEffect } from 'solid-js' +import { createFileRoute } from '@tanstack/solid-router' +import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' + +export const Route = createFileRoute('/cached/$id')({ + loader: ({ params }) => { + const items = makeItems(`cached-${params.id}`) + return { items, checksum: itemsChecksum(items) } + }, + staleTime: 1e9, + gcTime: 1e9, + component: CachedPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function PerfValue(props: { value: () => number }) { + createRenderEffect(() => { + void props.value() + }) + + return null +} + +function SumSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.checksum), + }) + + return computeChecksum(value())} /> +} + +function FirstItemSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.items[0]?.value ?? 0), + }) + + return computeChecksum(value())} /> +} + +function CachedPage() { + const params = Route.useParams() + const loaderData = Route.useLoaderData() + + return ( +
+ {subscriberIndexes.map(() => ( + + ))} + {subscriberIndexes.map(() => ( + + ))} +

Cached

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

Deps

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

Fresh

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

Loaders Bench

+
home
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/tsconfig.json b/benchmarks/client-nav/scenarios/loaders/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts new file mode 100644 index 0000000000..90584d3b7e --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts @@ -0,0 +1,50 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'solid', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav loaders (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/project.json b/benchmarks/client-nav/scenarios/loaders/vue/project.json new file mode 100644 index 0000000000..69bd95837d --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-loaders-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/loaders/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/setup.ts b/benchmarks/client-nav/scenarios/loaders/vue/setup.ts new file mode 100644 index 0000000000..97b74b3892 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts new file mode 100644 index 0000000000..1ae2f89a56 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-loaders', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-loaders navigation loop (vue)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/loaders/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx @@ -0,0 +1,41 @@ +import type { RouterHistory } from '@tanstack/history' +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..10cb8f2aca --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts @@ -0,0 +1,113 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as DepsRouteImport } from './routes/deps' +import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as FreshIdRouteImport } from './routes/fresh.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DepsRoute = DepsRouteImport.update({ + id: '/deps', + path: '/deps', + getParentRoute: () => rootRouteImport, +} as any) +const CachedIdRoute = CachedIdRouteImport.update({ + id: '/cached/$id', + path: '/cached/$id', + getParentRoute: () => rootRouteImport, +} as any) +const FreshIdRoute = FreshIdRouteImport.update({ + id: '/fresh/$id', + path: '/fresh/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/deps' | '/cached/$id' | '/fresh/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/deps' | '/cached/$id' | '/fresh/$id' + id: '__root__' | '/' | '/deps' | '/cached/$id' | '/fresh/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DepsRoute: typeof DepsRoute + CachedIdRoute: typeof CachedIdRoute + FreshIdRoute: typeof FreshIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/deps': { + id: '/deps' + path: '/deps' + fullPath: '/deps' + preLoaderRoute: typeof DepsRouteImport + parentRoute: typeof rootRouteImport + } + '/cached/$id': { + id: '/cached/$id' + path: '/cached/$id' + fullPath: '/cached/$id' + preLoaderRoute: typeof CachedIdRouteImport + parentRoute: typeof rootRouteImport + } + '/fresh/$id': { + id: '/fresh/$id' + path: '/fresh/$id' + fullPath: '/fresh/$id' + preLoaderRoute: typeof FreshIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DepsRoute: DepsRoute, + CachedIdRoute: CachedIdRoute, + FreshIdRoute: FreshIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..b9102a92c4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/__root.tsx @@ -0,0 +1,69 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/cached.$id.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/cached.$id.tsx new file mode 100644 index 0000000000..a426e35765 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/cached.$id.tsx @@ -0,0 +1,68 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +const SumSubscriber = Vue.defineComponent({ + setup() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.checksum), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const FirstItemSubscriber = Vue.defineComponent({ + setup() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.items[0]?.value ?? 0), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const CachedPage = Vue.defineComponent({ + setup() { + const params = Route.useParams() + const loaderData = Route.useLoaderData() + + return () => ( +
+ {subscriberIndexes.map((index) => ( + + ))} + {subscriberIndexes.map((index) => ( + + ))} +

Cached

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

Deps

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

Fresh

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

Loaders Bench

+
home
+
+ ) + }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/tsconfig.json b/benchmarks/client-nav/scenarios/loaders/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts new file mode 100644 index 0000000000..ecf4cce139 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts @@ -0,0 +1,44 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav loaders (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/mount/react/project.json b/benchmarks/client-nav/scenarios/mount/react/project.json new file mode 100644 index 0000000000..61839943b3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-mount-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/mount/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/mount/react/setup.ts b/benchmarks/client-nav/scenarios/mount/react/setup.ts new file mode 100644 index 0000000000..ed0426c696 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/setup.ts @@ -0,0 +1,17 @@ +import { createMountLoopSetup } from '../../harness' +import { assertReady, readyTestId } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createMountLoopSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + readyTestId, + assertReady, + }) +} diff --git a/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts new file mode 100644 index 0000000000..6c3a64b026 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-mount', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-mount loop (react)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/mount/react/speed.flame.ts b/benchmarks/client-nav/scenarios/mount/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/main.tsx b/benchmarks/client-nav/scenarios/mount/react/src/main.tsx new file mode 100644 index 0000000000..4e45ed7ef3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/main.tsx @@ -0,0 +1,38 @@ +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' +import type { RouterHistory } from '@tanstack/history' + +/** + * Unlike the other scenarios, this app is mounted and unmounted in a loop, so + * it must not register page-lifetime globals that have no dispose path: + * - the harness injects and destroys a fresh memory history per mount; + * - `scrollRestoration` stays off — enabling it registers per-router + * document/window listeners that retain every router ever created. + */ +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const reactRoot = createRoot(container) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..f9b7e5c268 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routeTree.gen.ts @@ -0,0 +1,264 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' +import { Route as BlogRouteImport } from './routes/blog' +import { Route as SearchRouteImport } from './routes/search' +import { Route as SettingsRouteImport } from './routes/settings' +import { Route as ShopRouteImport } from './routes/shop' +import { Route as BlogIndexRouteImport } from './routes/blog.index' +import { Route as BlogSlugRouteImport } from './routes/blog.$slug' +import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', + getParentRoute: () => rootRouteImport, +} as any) +const SearchRoute = SearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, +} as any) +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ShopRoute = ShopRouteImport.update({ + id: '/shop', + path: '/shop', + getParentRoute: () => rootRouteImport, +} as any) +const BlogIndexRoute = BlogIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => BlogRoute, +} as any) +const BlogSlugRoute = BlogSlugRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => BlogRoute, +} as any) +const ShopIndexRoute = ShopIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => ShopRoute, +} as any) +const ShopProductIdRoute = ShopProductIdRouteImport.update({ + id: '/$productId', + path: '/$productId', + getParentRoute: () => ShopRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/blog': typeof BlogRouteWithChildren + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/shop': typeof ShopRouteWithChildren + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog/': typeof BlogIndexRoute + '/shop/': typeof ShopIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog': typeof BlogIndexRoute + '/shop': typeof ShopIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/blog': typeof BlogRouteWithChildren + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/shop': typeof ShopRouteWithChildren + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog/': typeof BlogIndexRoute + '/shop/': typeof ShopIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/about' + | '/blog' + | '/search' + | '/settings' + | '/shop' + | '/blog/$slug' + | '/shop/$productId' + | '/blog/' + | '/shop/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/about' + | '/search' + | '/settings' + | '/blog/$slug' + | '/shop/$productId' + | '/blog' + | '/shop' + id: + | '__root__' + | '/' + | '/about' + | '/blog' + | '/search' + | '/settings' + | '/shop' + | '/blog/$slug' + | '/shop/$productId' + | '/blog/' + | '/shop/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AboutRoute: typeof AboutRoute + BlogRoute: typeof BlogRouteWithChildren + SearchRoute: typeof SearchRoute + SettingsRoute: typeof SettingsRoute + ShopRoute: typeof ShopRouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport + parentRoute: typeof rootRouteImport + } + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteImport + parentRoute: typeof rootRouteImport + } + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/shop': { + id: '/shop' + path: '/shop' + fullPath: '/shop' + preLoaderRoute: typeof ShopRouteImport + parentRoute: typeof rootRouteImport + } + '/blog/': { + id: '/blog/' + path: '/' + fullPath: '/blog/' + preLoaderRoute: typeof BlogIndexRouteImport + parentRoute: typeof BlogRoute + } + '/blog/$slug': { + id: '/blog/$slug' + path: '/$slug' + fullPath: '/blog/$slug' + preLoaderRoute: typeof BlogSlugRouteImport + parentRoute: typeof BlogRoute + } + '/shop/': { + id: '/shop/' + path: '/' + fullPath: '/shop/' + preLoaderRoute: typeof ShopIndexRouteImport + parentRoute: typeof ShopRoute + } + '/shop/$productId': { + id: '/shop/$productId' + path: '/$productId' + fullPath: '/shop/$productId' + preLoaderRoute: typeof ShopProductIdRouteImport + parentRoute: typeof ShopRoute + } + } +} + +interface BlogRouteChildren { + BlogSlugRoute: typeof BlogSlugRoute + BlogIndexRoute: typeof BlogIndexRoute +} + +const BlogRouteChildren: BlogRouteChildren = { + BlogSlugRoute: BlogSlugRoute, + BlogIndexRoute: BlogIndexRoute, +} + +const BlogRouteWithChildren = BlogRoute._addFileChildren(BlogRouteChildren) + +interface ShopRouteChildren { + ShopProductIdRoute: typeof ShopProductIdRoute + ShopIndexRoute: typeof ShopIndexRoute +} + +const ShopRouteChildren: ShopRouteChildren = { + ShopProductIdRoute: ShopProductIdRoute, + ShopIndexRoute: ShopIndexRoute, +} + +const ShopRouteWithChildren = ShopRoute._addFileChildren(ShopRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AboutRoute: AboutRoute, + BlogRoute: BlogRouteWithChildren, + SearchRoute: SearchRoute, + SettingsRoute: SettingsRoute, + ShopRoute: ShopRouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/__root.tsx new file mode 100644 index 0000000000..0deab171d8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routes/__root.tsx @@ -0,0 +1,41 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/about.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/about.tsx new file mode 100644 index 0000000000..3fedde283b --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routes/about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/about')({ + component: AboutPage, +}) + +function AboutPage() { + return

About

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

All articles

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

Blog

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

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

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

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

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

Settings

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

All products

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

Shop

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/mount/react/tsconfig.json b/benchmarks/client-nav/scenarios/mount/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/mount/react/vite.config.ts b/benchmarks/client-nav/scenarios/mount/react/vite.config.ts new file mode 100644 index 0000000000..e197d33a9e --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/vite.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'react', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav mount (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/mount/shared.ts b/benchmarks/client-nav/scenarios/mount/shared.ts new file mode 100644 index 0000000000..a8f3d2c7bd --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/shared.ts @@ -0,0 +1,75 @@ +/** + * Shared definition of the `mount` scenario: cold start of a moderate, + * realistic app — router creation (processRouteTree), first render, initial + * `router.load()`, and unmount. This is the only scenario where router + * construction is inside the measured loop; the wider tree exists as + * realistic route-processing weight even though only the index route loads. + */ + +export const readyTestId = 'mount-ready' + +export const homeItemCount = 5 + +export function homeItems() { + return Array.from({ length: homeItemCount }, (_, index) => ({ + id: `item-${index}`, + label: `Featured item ${index}`, + score: index * 17 + 3, + })) +} + +export const homeReadyText = `Home (${homeItemCount} items)` + +export function shopContext() { + return { shopSeed: 7 } +} + +export function blogContext() { + return { blogSeed: 13 } +} + +export function productData(productId: string) { + return { + id: productId, + name: `Product ${productId}`, + price: productId.length * 100 + 42, + } +} + +export function articleData(slug: string) { + return { + slug, + title: `Article ${slug}`, + words: slug.length * 250, + } +} + +export function normalizePage(value: unknown) { + const page = Number(value) + return Number.isFinite(page) && page > 0 ? Math.trunc(page) : 1 +} + +export function normalizeQuery(value: unknown) { + return typeof value === 'string' ? value : '' +} + +export function assertReady(container: HTMLElement) { + const marker = container.querySelector(`[data-testid="${readyTestId}"]`) + if (marker?.textContent !== homeReadyText) { + throw new Error( + `Expected mount marker to be "${homeReadyText}", received "${marker?.textContent}"`, + ) + } +} + +// Mounts per benchmark iteration. +// 6 mounts per iteration: a single mount simulates to only ~8ms of CPU, and +// very short measures amplify the relative impact of allocator/GC +// quantization; 6 keeps the measure comfortably above ~50ms simulated. +export const ticksPerIteration = 6 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/project.json b/benchmarks/client-nav/scenarios/mount/solid/project.json new file mode 100644 index 0000000000..4349570654 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-mount-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/mount/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/setup.ts b/benchmarks/client-nav/scenarios/mount/solid/setup.ts new file mode 100644 index 0000000000..810ea38c91 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/setup.ts @@ -0,0 +1,17 @@ +import { createMountLoopSetup } from '../../harness' +import { assertReady, readyTestId } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createMountLoopSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + readyTestId, + assertReady, + }) +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts new file mode 100644 index 0000000000..236f875f57 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-mount', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-mount loop (solid)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/mount/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/mount/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx new file mode 100644 index 0000000000..2586872f5c --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx @@ -0,0 +1,37 @@ +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' +import type { RouterHistory } from '@tanstack/history' + +/** + * Unlike the other scenarios, this app is mounted and unmounted in a loop, so + * it must not register page-lifetime globals that have no dispose path: + * - the harness injects and destroys a fresh memory history per mount; + * - `scrollRestoration` stays off — enabling it registers per-router + * document/window listeners that retain every router ever created. + */ +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const dispose = render(() => , container) + + return { + router, + unmount() { + dispose() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..30247636dd --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts @@ -0,0 +1,264 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' +import { Route as BlogRouteImport } from './routes/blog' +import { Route as SearchRouteImport } from './routes/search' +import { Route as SettingsRouteImport } from './routes/settings' +import { Route as ShopRouteImport } from './routes/shop' +import { Route as BlogIndexRouteImport } from './routes/blog.index' +import { Route as BlogSlugRouteImport } from './routes/blog.$slug' +import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', + getParentRoute: () => rootRouteImport, +} as any) +const SearchRoute = SearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, +} as any) +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ShopRoute = ShopRouteImport.update({ + id: '/shop', + path: '/shop', + getParentRoute: () => rootRouteImport, +} as any) +const BlogIndexRoute = BlogIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => BlogRoute, +} as any) +const BlogSlugRoute = BlogSlugRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => BlogRoute, +} as any) +const ShopIndexRoute = ShopIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => ShopRoute, +} as any) +const ShopProductIdRoute = ShopProductIdRouteImport.update({ + id: '/$productId', + path: '/$productId', + getParentRoute: () => ShopRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/blog': typeof BlogRouteWithChildren + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/shop': typeof ShopRouteWithChildren + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog/': typeof BlogIndexRoute + '/shop/': typeof ShopIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog': typeof BlogIndexRoute + '/shop': typeof ShopIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/blog': typeof BlogRouteWithChildren + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/shop': typeof ShopRouteWithChildren + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog/': typeof BlogIndexRoute + '/shop/': typeof ShopIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/about' + | '/blog' + | '/search' + | '/settings' + | '/shop' + | '/blog/$slug' + | '/shop/$productId' + | '/blog/' + | '/shop/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/about' + | '/search' + | '/settings' + | '/blog/$slug' + | '/shop/$productId' + | '/blog' + | '/shop' + id: + | '__root__' + | '/' + | '/about' + | '/blog' + | '/search' + | '/settings' + | '/shop' + | '/blog/$slug' + | '/shop/$productId' + | '/blog/' + | '/shop/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AboutRoute: typeof AboutRoute + BlogRoute: typeof BlogRouteWithChildren + SearchRoute: typeof SearchRoute + SettingsRoute: typeof SettingsRoute + ShopRoute: typeof ShopRouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport + parentRoute: typeof rootRouteImport + } + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteImport + parentRoute: typeof rootRouteImport + } + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/shop': { + id: '/shop' + path: '/shop' + fullPath: '/shop' + preLoaderRoute: typeof ShopRouteImport + parentRoute: typeof rootRouteImport + } + '/blog/': { + id: '/blog/' + path: '/' + fullPath: '/blog/' + preLoaderRoute: typeof BlogIndexRouteImport + parentRoute: typeof BlogRoute + } + '/blog/$slug': { + id: '/blog/$slug' + path: '/$slug' + fullPath: '/blog/$slug' + preLoaderRoute: typeof BlogSlugRouteImport + parentRoute: typeof BlogRoute + } + '/shop/': { + id: '/shop/' + path: '/' + fullPath: '/shop/' + preLoaderRoute: typeof ShopIndexRouteImport + parentRoute: typeof ShopRoute + } + '/shop/$productId': { + id: '/shop/$productId' + path: '/$productId' + fullPath: '/shop/$productId' + preLoaderRoute: typeof ShopProductIdRouteImport + parentRoute: typeof ShopRoute + } + } +} + +interface BlogRouteChildren { + BlogSlugRoute: typeof BlogSlugRoute + BlogIndexRoute: typeof BlogIndexRoute +} + +const BlogRouteChildren: BlogRouteChildren = { + BlogSlugRoute: BlogSlugRoute, + BlogIndexRoute: BlogIndexRoute, +} + +const BlogRouteWithChildren = BlogRoute._addFileChildren(BlogRouteChildren) + +interface ShopRouteChildren { + ShopProductIdRoute: typeof ShopProductIdRoute + ShopIndexRoute: typeof ShopIndexRoute +} + +const ShopRouteChildren: ShopRouteChildren = { + ShopProductIdRoute: ShopProductIdRoute, + ShopIndexRoute: ShopIndexRoute, +} + +const ShopRouteWithChildren = ShopRoute._addFileChildren(ShopRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AboutRoute: AboutRoute, + BlogRoute: BlogRouteWithChildren, + SearchRoute: SearchRoute, + SettingsRoute: SettingsRoute, + ShopRoute: ShopRouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..f5c3be2641 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routes/__root.tsx @@ -0,0 +1,41 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/about.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/about.tsx new file mode 100644 index 0000000000..f74d85aa06 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routes/about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/about')({ + component: AboutPage, +}) + +function AboutPage() { + return

About

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

All articles

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

Blog

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

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

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

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

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

Settings

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

All products

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

Shop

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/tsconfig.json b/benchmarks/client-nav/scenarios/mount/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts b/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts new file mode 100644 index 0000000000..5b586dd128 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts @@ -0,0 +1,50 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'solid', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav mount (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/project.json b/benchmarks/client-nav/scenarios/mount/vue/project.json new file mode 100644 index 0000000000..f2dbd10440 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-mount-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/mount/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/mount/vue/setup.ts b/benchmarks/client-nav/scenarios/mount/vue/setup.ts new file mode 100644 index 0000000000..3976e71c51 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/setup.ts @@ -0,0 +1,17 @@ +import { createMountLoopSetup } from '../../harness' +import { assertReady, readyTestId } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createMountLoopSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + readyTestId, + assertReady, + }) +} diff --git a/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts new file mode 100644 index 0000000000..d9268ba91b --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts @@ -0,0 +1,15 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-mount', async ({ bench }) => { + const scenario = setup() + + await bench('client-mount loop (vue)', benchLifecycle(scenario), async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/mount/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx new file mode 100644 index 0000000000..fc493c10a5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx @@ -0,0 +1,42 @@ +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' +import type { RouterHistory } from '@tanstack/history' + +/** + * Unlike the other scenarios, this app is mounted and unmounted in a loop, so + * it must not register page-lifetime globals that have no dispose path: + * - the harness injects and destroys a fresh memory history per mount; + * - `scrollRestoration` stays off — enabling it registers per-router + * document/window listeners that retain every router ever created. + */ +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..cd27c917e1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts @@ -0,0 +1,264 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' +import { Route as BlogRouteImport } from './routes/blog' +import { Route as SearchRouteImport } from './routes/search' +import { Route as SettingsRouteImport } from './routes/settings' +import { Route as ShopRouteImport } from './routes/shop' +import { Route as BlogIndexRouteImport } from './routes/blog.index' +import { Route as BlogSlugRouteImport } from './routes/blog.$slug' +import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', + getParentRoute: () => rootRouteImport, +} as any) +const SearchRoute = SearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, +} as any) +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ShopRoute = ShopRouteImport.update({ + id: '/shop', + path: '/shop', + getParentRoute: () => rootRouteImport, +} as any) +const BlogIndexRoute = BlogIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => BlogRoute, +} as any) +const BlogSlugRoute = BlogSlugRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => BlogRoute, +} as any) +const ShopIndexRoute = ShopIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => ShopRoute, +} as any) +const ShopProductIdRoute = ShopProductIdRouteImport.update({ + id: '/$productId', + path: '/$productId', + getParentRoute: () => ShopRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/blog': typeof BlogRouteWithChildren + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/shop': typeof ShopRouteWithChildren + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog/': typeof BlogIndexRoute + '/shop/': typeof ShopIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog': typeof BlogIndexRoute + '/shop': typeof ShopIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/blog': typeof BlogRouteWithChildren + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/shop': typeof ShopRouteWithChildren + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog/': typeof BlogIndexRoute + '/shop/': typeof ShopIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/about' + | '/blog' + | '/search' + | '/settings' + | '/shop' + | '/blog/$slug' + | '/shop/$productId' + | '/blog/' + | '/shop/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/about' + | '/search' + | '/settings' + | '/blog/$slug' + | '/shop/$productId' + | '/blog' + | '/shop' + id: + | '__root__' + | '/' + | '/about' + | '/blog' + | '/search' + | '/settings' + | '/shop' + | '/blog/$slug' + | '/shop/$productId' + | '/blog/' + | '/shop/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AboutRoute: typeof AboutRoute + BlogRoute: typeof BlogRouteWithChildren + SearchRoute: typeof SearchRoute + SettingsRoute: typeof SettingsRoute + ShopRoute: typeof ShopRouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport + parentRoute: typeof rootRouteImport + } + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteImport + parentRoute: typeof rootRouteImport + } + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/shop': { + id: '/shop' + path: '/shop' + fullPath: '/shop' + preLoaderRoute: typeof ShopRouteImport + parentRoute: typeof rootRouteImport + } + '/blog/': { + id: '/blog/' + path: '/' + fullPath: '/blog/' + preLoaderRoute: typeof BlogIndexRouteImport + parentRoute: typeof BlogRoute + } + '/blog/$slug': { + id: '/blog/$slug' + path: '/$slug' + fullPath: '/blog/$slug' + preLoaderRoute: typeof BlogSlugRouteImport + parentRoute: typeof BlogRoute + } + '/shop/': { + id: '/shop/' + path: '/' + fullPath: '/shop/' + preLoaderRoute: typeof ShopIndexRouteImport + parentRoute: typeof ShopRoute + } + '/shop/$productId': { + id: '/shop/$productId' + path: '/$productId' + fullPath: '/shop/$productId' + preLoaderRoute: typeof ShopProductIdRouteImport + parentRoute: typeof ShopRoute + } + } +} + +interface BlogRouteChildren { + BlogSlugRoute: typeof BlogSlugRoute + BlogIndexRoute: typeof BlogIndexRoute +} + +const BlogRouteChildren: BlogRouteChildren = { + BlogSlugRoute: BlogSlugRoute, + BlogIndexRoute: BlogIndexRoute, +} + +const BlogRouteWithChildren = BlogRoute._addFileChildren(BlogRouteChildren) + +interface ShopRouteChildren { + ShopProductIdRoute: typeof ShopProductIdRoute + ShopIndexRoute: typeof ShopIndexRoute +} + +const ShopRouteChildren: ShopRouteChildren = { + ShopProductIdRoute: ShopProductIdRoute, + ShopIndexRoute: ShopIndexRoute, +} + +const ShopRouteWithChildren = ShopRoute._addFileChildren(ShopRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AboutRoute: AboutRoute, + BlogRoute: BlogRouteWithChildren, + SearchRoute: SearchRoute, + SettingsRoute: SettingsRoute, + ShopRoute: ShopRouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..5c2b7b52d0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routes/__root.tsx @@ -0,0 +1,44 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/about.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/about.tsx new file mode 100644 index 0000000000..254ecca29c --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routes/about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const AboutPage = Vue.defineComponent({ + setup() { + return () =>

About

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

All articles

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

Blog

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

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

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

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

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

Settings

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

All products

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

Shop

+ +
+ ) + }, +}) + +export const Route = createFileRoute('/shop')({ + beforeLoad: () => shopContext(), + component: ShopLayout, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/tsconfig.json b/benchmarks/client-nav/scenarios/mount/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts b/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts new file mode 100644 index 0000000000..8d4005f339 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts @@ -0,0 +1,44 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav mount (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/react/project.json b/benchmarks/client-nav/scenarios/nested-params/react/project.json new file mode 100644 index 0000000000..800f8af9a8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-nested-params-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/nested-params/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/setup.ts b/benchmarks/client-nav/scenarios/nested-params/react/setup.ts new file mode 100644 index 0000000000..130583b190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts new file mode 100644 index 0000000000..fa5809c1fd --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-nested-params', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-nested-params navigation loop (react)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/react/speed.flame.ts b/benchmarks/client-nav/scenarios/nested-params/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx @@ -0,0 +1,37 @@ +import type { RouterHistory } from '@tanstack/history' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const reactRoot = createRoot(container) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/nested-params/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..95d4b46623 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routeTree.gen.ts @@ -0,0 +1,291 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as LARouteImport } from './routes/l.$a' +import { Route as LABRouteImport } from './routes/l.$a.$b' +import { Route as LABCRouteImport } from './routes/l.$a.$b.$c' +import { Route as LABCDRouteImport } from './routes/l.$a.$b.$c.$d' +import { Route as LABCDERouteImport } from './routes/l.$a.$b.$c.$d.$e' +import { Route as LABCDEFRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f' +import { Route as LABCDEFGRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g' +import { Route as LABCDEFGHRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g.$h' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LARoute = LARouteImport.update({ + id: '/l/$a', + path: '/l/$a', + getParentRoute: () => rootRouteImport, +} as any) +const LABRoute = LABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => LARoute, +} as any) +const LABCRoute = LABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => LABRoute, +} as any) +const LABCDRoute = LABCDRouteImport.update({ + id: '/$d', + path: '/$d', + getParentRoute: () => LABCRoute, +} as any) +const LABCDERoute = LABCDERouteImport.update({ + id: '/$e', + path: '/$e', + getParentRoute: () => LABCDRoute, +} as any) +const LABCDEFRoute = LABCDEFRouteImport.update({ + id: '/$f', + path: '/$f', + getParentRoute: () => LABCDERoute, +} as any) +const LABCDEFGRoute = LABCDEFGRouteImport.update({ + id: '/$g', + path: '/$g', + getParentRoute: () => LABCDEFRoute, +} as any) +const LABCDEFGHRoute = LABCDEFGHRouteImport.update({ + id: '/$h', + path: '/$h', + getParentRoute: () => LABCDEFGRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + id: + | '__root__' + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LARoute: typeof LARouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/l/$a': { + id: '/l/$a' + path: '/l/$a' + fullPath: '/l/$a' + preLoaderRoute: typeof LARouteImport + parentRoute: typeof rootRouteImport + } + '/l/$a/$b': { + id: '/l/$a/$b' + path: '/$b' + fullPath: '/l/$a/$b' + preLoaderRoute: typeof LABRouteImport + parentRoute: typeof LARoute + } + '/l/$a/$b/$c': { + id: '/l/$a/$b/$c' + path: '/$c' + fullPath: '/l/$a/$b/$c' + preLoaderRoute: typeof LABCRouteImport + parentRoute: typeof LABRoute + } + '/l/$a/$b/$c/$d': { + id: '/l/$a/$b/$c/$d' + path: '/$d' + fullPath: '/l/$a/$b/$c/$d' + preLoaderRoute: typeof LABCDRouteImport + parentRoute: typeof LABCRoute + } + '/l/$a/$b/$c/$d/$e': { + id: '/l/$a/$b/$c/$d/$e' + path: '/$e' + fullPath: '/l/$a/$b/$c/$d/$e' + preLoaderRoute: typeof LABCDERouteImport + parentRoute: typeof LABCDRoute + } + '/l/$a/$b/$c/$d/$e/$f': { + id: '/l/$a/$b/$c/$d/$e/$f' + path: '/$f' + fullPath: '/l/$a/$b/$c/$d/$e/$f' + preLoaderRoute: typeof LABCDEFRouteImport + parentRoute: typeof LABCDERoute + } + '/l/$a/$b/$c/$d/$e/$f/$g': { + id: '/l/$a/$b/$c/$d/$e/$f/$g' + path: '/$g' + fullPath: '/l/$a/$b/$c/$d/$e/$f/$g' + preLoaderRoute: typeof LABCDEFGRouteImport + parentRoute: typeof LABCDEFRoute + } + '/l/$a/$b/$c/$d/$e/$f/$g/$h': { + id: '/l/$a/$b/$c/$d/$e/$f/$g/$h' + path: '/$h' + fullPath: '/l/$a/$b/$c/$d/$e/$f/$g/$h' + preLoaderRoute: typeof LABCDEFGHRouteImport + parentRoute: typeof LABCDEFGRoute + } + } +} + +interface LABCDEFGRouteChildren { + LABCDEFGHRoute: typeof LABCDEFGHRoute +} + +const LABCDEFGRouteChildren: LABCDEFGRouteChildren = { + LABCDEFGHRoute: LABCDEFGHRoute, +} + +const LABCDEFGRouteWithChildren = LABCDEFGRoute._addFileChildren( + LABCDEFGRouteChildren, +) + +interface LABCDEFRouteChildren { + LABCDEFGRoute: typeof LABCDEFGRouteWithChildren +} + +const LABCDEFRouteChildren: LABCDEFRouteChildren = { + LABCDEFGRoute: LABCDEFGRouteWithChildren, +} + +const LABCDEFRouteWithChildren = + LABCDEFRoute._addFileChildren(LABCDEFRouteChildren) + +interface LABCDERouteChildren { + LABCDEFRoute: typeof LABCDEFRouteWithChildren +} + +const LABCDERouteChildren: LABCDERouteChildren = { + LABCDEFRoute: LABCDEFRouteWithChildren, +} + +const LABCDERouteWithChildren = + LABCDERoute._addFileChildren(LABCDERouteChildren) + +interface LABCDRouteChildren { + LABCDERoute: typeof LABCDERouteWithChildren +} + +const LABCDRouteChildren: LABCDRouteChildren = { + LABCDERoute: LABCDERouteWithChildren, +} + +const LABCDRouteWithChildren = LABCDRoute._addFileChildren(LABCDRouteChildren) + +interface LABCRouteChildren { + LABCDRoute: typeof LABCDRouteWithChildren +} + +const LABCRouteChildren: LABCRouteChildren = { + LABCDRoute: LABCDRouteWithChildren, +} + +const LABCRouteWithChildren = LABCRoute._addFileChildren(LABCRouteChildren) + +interface LABRouteChildren { + LABCRoute: typeof LABCRouteWithChildren +} + +const LABRouteChildren: LABRouteChildren = { + LABCRoute: LABCRouteWithChildren, +} + +const LABRouteWithChildren = LABRoute._addFileChildren(LABRouteChildren) + +interface LARouteChildren { + LABRoute: typeof LABRouteWithChildren +} + +const LARouteChildren: LARouteChildren = { + LABRoute: LABRouteWithChildren, +} + +const LARouteWithChildren = LARoute._addFileChildren(LARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LARoute: LARouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/__root.tsx new file mode 100644 index 0000000000..ef2c7b1b18 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/__root.tsx @@ -0,0 +1,50 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' +import { leafParamSets, midParams } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/index.tsx new file mode 100644 index 0000000000..24e856ea15 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return
home
+} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx new file mode 100644 index 0000000000..9789e28040 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx @@ -0,0 +1,63 @@ +import { createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g/$h')({ + params: { + parse: (params) => ({ ...params, h: normalizeParam(params.h) }), + stringify: (params) => ({ ...params, h: String(params.h) }), + }, + beforeLoad: ({ params }) => ({ ctxH: smallHash(params.h) }), + component: LevelH, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.h) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.h}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxH }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxH * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelH() { + const params = Route.useParams() + return ( + <> + + + + +
+ {[ + params.a, + params.b, + params.c, + params.d, + params.e, + params.f, + params.g, + params.h, + ].join('.')} +
+ + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx new file mode 100644 index 0000000000..650b32ce96 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx @@ -0,0 +1,51 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g')({ + params: { + parse: (params) => ({ ...params, g: normalizeParam(params.g) }), + stringify: (params) => ({ ...params, g: String(params.g) }), + }, + beforeLoad: ({ params }) => ({ ctxG: smallHash(params.g) }), + component: LevelG, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.g) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.g}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxG }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxG * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelG() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.tsx new file mode 100644 index 0000000000..ca18e3ccd2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.tsx @@ -0,0 +1,51 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f')({ + params: { + parse: (params) => ({ ...params, f: normalizeParam(params.f) }), + stringify: (params) => ({ ...params, f: String(params.f) }), + }, + beforeLoad: ({ params }) => ({ ctxF: smallHash(params.f) }), + component: LevelF, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.f) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.f}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxF }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxF * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelF() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.tsx new file mode 100644 index 0000000000..782c1808c7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.tsx @@ -0,0 +1,51 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e')({ + params: { + parse: (params) => ({ ...params, e: normalizeParam(params.e) }), + stringify: (params) => ({ ...params, e: String(params.e) }), + }, + beforeLoad: ({ params }) => ({ ctxE: smallHash(params.e) }), + component: LevelE, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.e) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.e}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxE }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxE * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelE() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.tsx new file mode 100644 index 0000000000..a874bbcb63 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.tsx @@ -0,0 +1,55 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d')({ + params: { + parse: (params) => ({ ...params, d: normalizeParam(params.d) }), + stringify: (params) => ({ ...params, d: String(params.d) }), + }, + beforeLoad: ({ params }) => ({ ctxD: smallHash(params.d) }), + component: LevelD, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.d) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.d}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxD }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxD * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelD() { + const params = Route.useParams() + return ( + <> + + + + +
+ {[params.a, params.b, params.c, params.d].join('.')} +
+ + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.tsx new file mode 100644 index 0000000000..94aba79453 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.tsx @@ -0,0 +1,51 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c')({ + params: { + parse: (params) => ({ ...params, c: normalizeParam(params.c) }), + stringify: (params) => ({ ...params, c: String(params.c) }), + }, + beforeLoad: ({ params }) => ({ ctxC: smallHash(params.c) }), + component: LevelC, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.c) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.c}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxC }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxC * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelC() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.tsx new file mode 100644 index 0000000000..1960b68276 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.tsx @@ -0,0 +1,51 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b')({ + params: { + parse: (params) => ({ ...params, b: normalizeParam(params.b) }), + stringify: (params) => ({ ...params, b: String(params.b) }), + }, + beforeLoad: ({ params }) => ({ ctxB: smallHash(params.b) }), + component: LevelB, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.b) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.b}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxB }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxB * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelB() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.tsx new file mode 100644 index 0000000000..85d1de6f68 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.tsx @@ -0,0 +1,51 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a')({ + params: { + parse: (params) => ({ ...params, a: normalizeParam(params.a) }), + stringify: (params) => ({ ...params, a: String(params.a) }), + }, + beforeLoad: ({ params }) => ({ ctxA: smallHash(params.a) }), + component: LevelA, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.a) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.a}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxA }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxA * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelA() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/tsconfig.json b/benchmarks/client-nav/scenarios/nested-params/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts new file mode 100644 index 0000000000..a99060bf1c --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'react', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav nested-params (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/shared.ts b/benchmarks/client-nav/scenarios/nested-params/shared.ts new file mode 100644 index 0000000000..06c968bb18 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/shared.ts @@ -0,0 +1,143 @@ +/** + * Shared definition of the `nested-params` scenario: deep dynamic nesting with + * per-level params.parse/stringify, beforeLoad context accumulation, and + * useParams/useRouteContext subscribers at every level. The three framework + * apps consume these builders so the workload is identical modulo the + * rendering layer. + */ + +export interface LeafParams { + a: string + b: string + c: string + d: string + e: string + f: string + g: string + h: string +} + +// Several values need percent-encoding in the URL (spaces, `&`, `%`, `+`, +// unicode) so every navigation exercises the param encode/decode paths, not +// just plain-ASCII interpolation. +const baseParams: LeafParams = { + a: 'alpha', + b: 'bravo & co', + c: 'charlie 100%', + d: 'delta', + e: 'écho-café', + f: 'foxtrot+one', + g: 'golf', + h: 'hôtel', +} + +/** + * set 0: base; set 1: only the deepest param differs (only the leaf re-runs); + * set 2: a mid param differs (levels d..h re-run); set 3: the top param + * differs (every level re-runs). + */ +export const leafParamSets: ReadonlyArray = [ + baseParams, + { ...baseParams, h: 'hilton' }, + { ...baseParams, d: 'dover' }, + { ...baseParams, a: 'axel' }, +] + +export const midParams = { + a: baseParams.a, + b: baseParams.b, + c: baseParams.c, + d: baseParams.d, +} + +export function normalizeParam(value: unknown) { + const raw = String(value) + return raw.length > 24 ? raw.slice(0, 24) : raw +} + +export function smallHash(value: string | number) { + const input = `${value}` + let hash = 5381 + for (let index = 0; index < input.length; index++) { + hash = ((hash * 33) ^ input.charCodeAt(index)) >>> 0 + } + return hash +} + +export function leafMarker(params: LeafParams) { + return [ + params.a, + params.b, + params.c, + params.d, + params.e, + params.f, + params.g, + params.h, + ] + .map(normalizeParam) + .join('.') +} + +export function midMarker(params: typeof midParams) { + return [params.a, params.b, params.c, params.d].map(normalizeParam).join('.') +} + +export const steps = [ + 'leaf-1', + 'leaf-2', + 'leaf-3', + 'leaf-4', + 'mid-4', + 'home', +] as const + +function requireText(container: HTMLElement, testId: string, expected: string) { + const element = container.querySelector(`[data-testid="${testId}"]`) + if (!element || element.textContent !== expected) { + throw new Error( + `Expected [data-testid="${testId}"] to render "${expected}", received "${element?.textContent ?? ''}"`, + ) + } +} + +function requireAbsent(container: HTMLElement, testId: string) { + if (container.querySelector(`[data-testid="${testId}"]`)) { + throw new Error(`Expected [data-testid="${testId}"] to be absent`) + } +} + +export function assertStepResult(stepIndex: number, container: HTMLElement) { + const step = steps[stepIndex % steps.length]! + switch (step) { + case 'leaf-1': + requireText(container, 'leaf-state', leafMarker(leafParamSets[0]!)) + break + case 'leaf-2': + requireText(container, 'leaf-state', leafMarker(leafParamSets[1]!)) + break + case 'leaf-3': + requireText(container, 'leaf-state', leafMarker(leafParamSets[2]!)) + break + case 'leaf-4': + requireText(container, 'leaf-state', leafMarker(leafParamSets[3]!)) + break + case 'mid-4': + requireAbsent(container, 'leaf-state') + requireText(container, 'mid-state', midMarker(midParams)) + break + case 'home': + requireAbsent(container, 'leaf-state') + requireAbsent(container, 'mid-state') + break + } +} + +// Three laps through the 6-step sequence per benchmark iteration. +export const ticksPerIteration = 18 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/project.json b/benchmarks/client-nav/scenarios/nested-params/solid/project.json new file mode 100644 index 0000000000..eb0b91bd6c --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-nested-params-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/nested-params/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/setup.ts b/benchmarks/client-nav/scenarios/nested-params/solid/setup.ts new file mode 100644 index 0000000000..6a46971603 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts new file mode 100644 index 0000000000..2c64d9a221 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-nested-params', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-nested-params navigation loop (solid)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/nested-params/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx @@ -0,0 +1,34 @@ +import type { RouterHistory } from '@tanstack/history' +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const unmount = render(() => , container) + + return { + router, + unmount, + } +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/nested-params/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..9065c9294f --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routeTree.gen.ts @@ -0,0 +1,291 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as LARouteImport } from './routes/l.$a' +import { Route as LABRouteImport } from './routes/l.$a.$b' +import { Route as LABCRouteImport } from './routes/l.$a.$b.$c' +import { Route as LABCDRouteImport } from './routes/l.$a.$b.$c.$d' +import { Route as LABCDERouteImport } from './routes/l.$a.$b.$c.$d.$e' +import { Route as LABCDEFRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f' +import { Route as LABCDEFGRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g' +import { Route as LABCDEFGHRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g.$h' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LARoute = LARouteImport.update({ + id: '/l/$a', + path: '/l/$a', + getParentRoute: () => rootRouteImport, +} as any) +const LABRoute = LABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => LARoute, +} as any) +const LABCRoute = LABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => LABRoute, +} as any) +const LABCDRoute = LABCDRouteImport.update({ + id: '/$d', + path: '/$d', + getParentRoute: () => LABCRoute, +} as any) +const LABCDERoute = LABCDERouteImport.update({ + id: '/$e', + path: '/$e', + getParentRoute: () => LABCDRoute, +} as any) +const LABCDEFRoute = LABCDEFRouteImport.update({ + id: '/$f', + path: '/$f', + getParentRoute: () => LABCDERoute, +} as any) +const LABCDEFGRoute = LABCDEFGRouteImport.update({ + id: '/$g', + path: '/$g', + getParentRoute: () => LABCDEFRoute, +} as any) +const LABCDEFGHRoute = LABCDEFGHRouteImport.update({ + id: '/$h', + path: '/$h', + getParentRoute: () => LABCDEFGRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + id: + | '__root__' + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LARoute: typeof LARouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/l/$a': { + id: '/l/$a' + path: '/l/$a' + fullPath: '/l/$a' + preLoaderRoute: typeof LARouteImport + parentRoute: typeof rootRouteImport + } + '/l/$a/$b': { + id: '/l/$a/$b' + path: '/$b' + fullPath: '/l/$a/$b' + preLoaderRoute: typeof LABRouteImport + parentRoute: typeof LARoute + } + '/l/$a/$b/$c': { + id: '/l/$a/$b/$c' + path: '/$c' + fullPath: '/l/$a/$b/$c' + preLoaderRoute: typeof LABCRouteImport + parentRoute: typeof LABRoute + } + '/l/$a/$b/$c/$d': { + id: '/l/$a/$b/$c/$d' + path: '/$d' + fullPath: '/l/$a/$b/$c/$d' + preLoaderRoute: typeof LABCDRouteImport + parentRoute: typeof LABCRoute + } + '/l/$a/$b/$c/$d/$e': { + id: '/l/$a/$b/$c/$d/$e' + path: '/$e' + fullPath: '/l/$a/$b/$c/$d/$e' + preLoaderRoute: typeof LABCDERouteImport + parentRoute: typeof LABCDRoute + } + '/l/$a/$b/$c/$d/$e/$f': { + id: '/l/$a/$b/$c/$d/$e/$f' + path: '/$f' + fullPath: '/l/$a/$b/$c/$d/$e/$f' + preLoaderRoute: typeof LABCDEFRouteImport + parentRoute: typeof LABCDERoute + } + '/l/$a/$b/$c/$d/$e/$f/$g': { + id: '/l/$a/$b/$c/$d/$e/$f/$g' + path: '/$g' + fullPath: '/l/$a/$b/$c/$d/$e/$f/$g' + preLoaderRoute: typeof LABCDEFGRouteImport + parentRoute: typeof LABCDEFRoute + } + '/l/$a/$b/$c/$d/$e/$f/$g/$h': { + id: '/l/$a/$b/$c/$d/$e/$f/$g/$h' + path: '/$h' + fullPath: '/l/$a/$b/$c/$d/$e/$f/$g/$h' + preLoaderRoute: typeof LABCDEFGHRouteImport + parentRoute: typeof LABCDEFGRoute + } + } +} + +interface LABCDEFGRouteChildren { + LABCDEFGHRoute: typeof LABCDEFGHRoute +} + +const LABCDEFGRouteChildren: LABCDEFGRouteChildren = { + LABCDEFGHRoute: LABCDEFGHRoute, +} + +const LABCDEFGRouteWithChildren = LABCDEFGRoute._addFileChildren( + LABCDEFGRouteChildren, +) + +interface LABCDEFRouteChildren { + LABCDEFGRoute: typeof LABCDEFGRouteWithChildren +} + +const LABCDEFRouteChildren: LABCDEFRouteChildren = { + LABCDEFGRoute: LABCDEFGRouteWithChildren, +} + +const LABCDEFRouteWithChildren = + LABCDEFRoute._addFileChildren(LABCDEFRouteChildren) + +interface LABCDERouteChildren { + LABCDEFRoute: typeof LABCDEFRouteWithChildren +} + +const LABCDERouteChildren: LABCDERouteChildren = { + LABCDEFRoute: LABCDEFRouteWithChildren, +} + +const LABCDERouteWithChildren = + LABCDERoute._addFileChildren(LABCDERouteChildren) + +interface LABCDRouteChildren { + LABCDERoute: typeof LABCDERouteWithChildren +} + +const LABCDRouteChildren: LABCDRouteChildren = { + LABCDERoute: LABCDERouteWithChildren, +} + +const LABCDRouteWithChildren = LABCDRoute._addFileChildren(LABCDRouteChildren) + +interface LABCRouteChildren { + LABCDRoute: typeof LABCDRouteWithChildren +} + +const LABCRouteChildren: LABCRouteChildren = { + LABCDRoute: LABCDRouteWithChildren, +} + +const LABCRouteWithChildren = LABCRoute._addFileChildren(LABCRouteChildren) + +interface LABRouteChildren { + LABCRoute: typeof LABCRouteWithChildren +} + +const LABRouteChildren: LABRouteChildren = { + LABCRoute: LABCRouteWithChildren, +} + +const LABRouteWithChildren = LABRoute._addFileChildren(LABRouteChildren) + +interface LARouteChildren { + LABRoute: typeof LABRouteWithChildren +} + +const LARouteChildren: LARouteChildren = { + LABRoute: LABRouteWithChildren, +} + +const LARouteWithChildren = LARoute._addFileChildren(LARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LARoute: LARouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..6fe7ab3e3d --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/__root.tsx @@ -0,0 +1,50 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' +import { leafParamSets, midParams } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/index.tsx new file mode 100644 index 0000000000..cc46764de5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return
home
+} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx new file mode 100644 index 0000000000..7dc55db0e4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx @@ -0,0 +1,72 @@ +import { createRenderEffect } from 'solid-js' +import { createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g/$h')({ + params: { + parse: (params) => ({ ...params, h: normalizeParam(params.h) }), + stringify: (params) => ({ ...params, h: String(params.h) }), + }, + beforeLoad: ({ params }) => ({ ctxH: smallHash(params.h) }), + component: LevelH, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.h) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.h}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxH }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxH * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelH() { + const params = Route.useParams() + return ( + <> + + + + +
+ {[ + params().a, + params().b, + params().c, + params().d, + params().e, + params().f, + params().g, + params().h, + ].join('.')} +
+ + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx new file mode 100644 index 0000000000..d9c6c9429b --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx @@ -0,0 +1,60 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g')({ + params: { + parse: (params) => ({ ...params, g: normalizeParam(params.g) }), + stringify: (params) => ({ ...params, g: String(params.g) }), + }, + beforeLoad: ({ params }) => ({ ctxG: smallHash(params.g) }), + component: LevelG, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.g) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.g}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxG }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxG * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelG() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.tsx new file mode 100644 index 0000000000..010f89bc4d --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.tsx @@ -0,0 +1,60 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f')({ + params: { + parse: (params) => ({ ...params, f: normalizeParam(params.f) }), + stringify: (params) => ({ ...params, f: String(params.f) }), + }, + beforeLoad: ({ params }) => ({ ctxF: smallHash(params.f) }), + component: LevelF, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.f) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.f}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxF }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxF * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelF() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.tsx new file mode 100644 index 0000000000..08c107f0c6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.tsx @@ -0,0 +1,60 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e')({ + params: { + parse: (params) => ({ ...params, e: normalizeParam(params.e) }), + stringify: (params) => ({ ...params, e: String(params.e) }), + }, + beforeLoad: ({ params }) => ({ ctxE: smallHash(params.e) }), + component: LevelE, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.e) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.e}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxE }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxE * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelE() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.tsx new file mode 100644 index 0000000000..1b64edd58b --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.tsx @@ -0,0 +1,64 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d')({ + params: { + parse: (params) => ({ ...params, d: normalizeParam(params.d) }), + stringify: (params) => ({ ...params, d: String(params.d) }), + }, + beforeLoad: ({ params }) => ({ ctxD: smallHash(params.d) }), + component: LevelD, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.d) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.d}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxD }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxD * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelD() { + const params = Route.useParams() + return ( + <> + + + + +
+ {[params().a, params().b, params().c, params().d].join('.')} +
+ + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.tsx new file mode 100644 index 0000000000..e509ea82c6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.tsx @@ -0,0 +1,60 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c')({ + params: { + parse: (params) => ({ ...params, c: normalizeParam(params.c) }), + stringify: (params) => ({ ...params, c: String(params.c) }), + }, + beforeLoad: ({ params }) => ({ ctxC: smallHash(params.c) }), + component: LevelC, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.c) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.c}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxC }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxC * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelC() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.tsx new file mode 100644 index 0000000000..ada853b845 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.tsx @@ -0,0 +1,60 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b')({ + params: { + parse: (params) => ({ ...params, b: normalizeParam(params.b) }), + stringify: (params) => ({ ...params, b: String(params.b) }), + }, + beforeLoad: ({ params }) => ({ ctxB: smallHash(params.b) }), + component: LevelB, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.b) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.b}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxB }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxB * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelB() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.tsx new file mode 100644 index 0000000000..5ecf004fae --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.tsx @@ -0,0 +1,60 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a')({ + params: { + parse: (params) => ({ ...params, a: normalizeParam(params.a) }), + stringify: (params) => ({ ...params, a: String(params.a) }), + }, + beforeLoad: ({ params }) => ({ ctxA: smallHash(params.a) }), + component: LevelA, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.a) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.a}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxA }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxA * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelA() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/tsconfig.json b/benchmarks/client-nav/scenarios/nested-params/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts new file mode 100644 index 0000000000..9897e2c199 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts @@ -0,0 +1,50 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'solid', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav nested-params (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/project.json b/benchmarks/client-nav/scenarios/nested-params/vue/project.json new file mode 100644 index 0000000000..83c234382c --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-nested-params-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/nested-params/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/setup.ts b/benchmarks/client-nav/scenarios/nested-params/vue/setup.ts new file mode 100644 index 0000000000..97b74b3892 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts new file mode 100644 index 0000000000..bd3e82e070 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-nested-params', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-nested-params navigation loop (vue)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/nested-params/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx @@ -0,0 +1,41 @@ +import type { RouterHistory } from '@tanstack/history' +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/nested-params/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..a7d1049b49 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routeTree.gen.ts @@ -0,0 +1,291 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as LARouteImport } from './routes/l.$a' +import { Route as LABRouteImport } from './routes/l.$a.$b' +import { Route as LABCRouteImport } from './routes/l.$a.$b.$c' +import { Route as LABCDRouteImport } from './routes/l.$a.$b.$c.$d' +import { Route as LABCDERouteImport } from './routes/l.$a.$b.$c.$d.$e' +import { Route as LABCDEFRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f' +import { Route as LABCDEFGRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g' +import { Route as LABCDEFGHRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g.$h' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LARoute = LARouteImport.update({ + id: '/l/$a', + path: '/l/$a', + getParentRoute: () => rootRouteImport, +} as any) +const LABRoute = LABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => LARoute, +} as any) +const LABCRoute = LABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => LABRoute, +} as any) +const LABCDRoute = LABCDRouteImport.update({ + id: '/$d', + path: '/$d', + getParentRoute: () => LABCRoute, +} as any) +const LABCDERoute = LABCDERouteImport.update({ + id: '/$e', + path: '/$e', + getParentRoute: () => LABCDRoute, +} as any) +const LABCDEFRoute = LABCDEFRouteImport.update({ + id: '/$f', + path: '/$f', + getParentRoute: () => LABCDERoute, +} as any) +const LABCDEFGRoute = LABCDEFGRouteImport.update({ + id: '/$g', + path: '/$g', + getParentRoute: () => LABCDEFRoute, +} as any) +const LABCDEFGHRoute = LABCDEFGHRouteImport.update({ + id: '/$h', + path: '/$h', + getParentRoute: () => LABCDEFGRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + id: + | '__root__' + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LARoute: typeof LARouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/l/$a': { + id: '/l/$a' + path: '/l/$a' + fullPath: '/l/$a' + preLoaderRoute: typeof LARouteImport + parentRoute: typeof rootRouteImport + } + '/l/$a/$b': { + id: '/l/$a/$b' + path: '/$b' + fullPath: '/l/$a/$b' + preLoaderRoute: typeof LABRouteImport + parentRoute: typeof LARoute + } + '/l/$a/$b/$c': { + id: '/l/$a/$b/$c' + path: '/$c' + fullPath: '/l/$a/$b/$c' + preLoaderRoute: typeof LABCRouteImport + parentRoute: typeof LABRoute + } + '/l/$a/$b/$c/$d': { + id: '/l/$a/$b/$c/$d' + path: '/$d' + fullPath: '/l/$a/$b/$c/$d' + preLoaderRoute: typeof LABCDRouteImport + parentRoute: typeof LABCRoute + } + '/l/$a/$b/$c/$d/$e': { + id: '/l/$a/$b/$c/$d/$e' + path: '/$e' + fullPath: '/l/$a/$b/$c/$d/$e' + preLoaderRoute: typeof LABCDERouteImport + parentRoute: typeof LABCDRoute + } + '/l/$a/$b/$c/$d/$e/$f': { + id: '/l/$a/$b/$c/$d/$e/$f' + path: '/$f' + fullPath: '/l/$a/$b/$c/$d/$e/$f' + preLoaderRoute: typeof LABCDEFRouteImport + parentRoute: typeof LABCDERoute + } + '/l/$a/$b/$c/$d/$e/$f/$g': { + id: '/l/$a/$b/$c/$d/$e/$f/$g' + path: '/$g' + fullPath: '/l/$a/$b/$c/$d/$e/$f/$g' + preLoaderRoute: typeof LABCDEFGRouteImport + parentRoute: typeof LABCDEFRoute + } + '/l/$a/$b/$c/$d/$e/$f/$g/$h': { + id: '/l/$a/$b/$c/$d/$e/$f/$g/$h' + path: '/$h' + fullPath: '/l/$a/$b/$c/$d/$e/$f/$g/$h' + preLoaderRoute: typeof LABCDEFGHRouteImport + parentRoute: typeof LABCDEFGRoute + } + } +} + +interface LABCDEFGRouteChildren { + LABCDEFGHRoute: typeof LABCDEFGHRoute +} + +const LABCDEFGRouteChildren: LABCDEFGRouteChildren = { + LABCDEFGHRoute: LABCDEFGHRoute, +} + +const LABCDEFGRouteWithChildren = LABCDEFGRoute._addFileChildren( + LABCDEFGRouteChildren, +) + +interface LABCDEFRouteChildren { + LABCDEFGRoute: typeof LABCDEFGRouteWithChildren +} + +const LABCDEFRouteChildren: LABCDEFRouteChildren = { + LABCDEFGRoute: LABCDEFGRouteWithChildren, +} + +const LABCDEFRouteWithChildren = + LABCDEFRoute._addFileChildren(LABCDEFRouteChildren) + +interface LABCDERouteChildren { + LABCDEFRoute: typeof LABCDEFRouteWithChildren +} + +const LABCDERouteChildren: LABCDERouteChildren = { + LABCDEFRoute: LABCDEFRouteWithChildren, +} + +const LABCDERouteWithChildren = + LABCDERoute._addFileChildren(LABCDERouteChildren) + +interface LABCDRouteChildren { + LABCDERoute: typeof LABCDERouteWithChildren +} + +const LABCDRouteChildren: LABCDRouteChildren = { + LABCDERoute: LABCDERouteWithChildren, +} + +const LABCDRouteWithChildren = LABCDRoute._addFileChildren(LABCDRouteChildren) + +interface LABCRouteChildren { + LABCDRoute: typeof LABCDRouteWithChildren +} + +const LABCRouteChildren: LABCRouteChildren = { + LABCDRoute: LABCDRouteWithChildren, +} + +const LABCRouteWithChildren = LABCRoute._addFileChildren(LABCRouteChildren) + +interface LABRouteChildren { + LABCRoute: typeof LABCRouteWithChildren +} + +const LABRouteChildren: LABRouteChildren = { + LABCRoute: LABCRouteWithChildren, +} + +const LABRouteWithChildren = LABRoute._addFileChildren(LABRouteChildren) + +interface LARouteChildren { + LABRoute: typeof LABRouteWithChildren +} + +const LARouteChildren: LARouteChildren = { + LABRoute: LABRouteWithChildren, +} + +const LARouteWithChildren = LARoute._addFileChildren(LARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LARoute: LARouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..28dd4e847a --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/__root.tsx @@ -0,0 +1,53 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' +import { leafParamSets, midParams } from '../../../shared' + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/index.tsx new file mode 100644 index 0000000000..f3ffc58610 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const HomePage = Vue.defineComponent({ + setup() { + return () =>
home
+ }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx new file mode 100644 index 0000000000..756c31e1a9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx @@ -0,0 +1,86 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.h), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.h}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxH, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxH * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelH = Vue.defineComponent({ + setup() { + const params = Route.useParams() + return () => ( + <> + + + + +
+ {[ + params.value.a, + params.value.b, + params.value.c, + params.value.d, + params.value.e, + params.value.f, + params.value.g, + params.value.h, + ].join('.')} +
+ + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g/$h')({ + params: { + parse: (params) => ({ ...params, h: normalizeParam(params.h) }), + stringify: (params) => ({ ...params, h: String(params.h) }), + }, + beforeLoad: ({ params }) => ({ ctxH: smallHash(params.h) }), + component: LevelH, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx new file mode 100644 index 0000000000..d6b9ccde83 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx @@ -0,0 +1,74 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.g), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.g}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxG, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxG * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelG = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g')({ + params: { + parse: (params) => ({ ...params, g: normalizeParam(params.g) }), + stringify: (params) => ({ ...params, g: String(params.g) }), + }, + beforeLoad: ({ params }) => ({ ctxG: smallHash(params.g) }), + component: LevelG, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.tsx new file mode 100644 index 0000000000..76ed24904c --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.tsx @@ -0,0 +1,74 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.f), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.f}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxF, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxF * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelF = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f')({ + params: { + parse: (params) => ({ ...params, f: normalizeParam(params.f) }), + stringify: (params) => ({ ...params, f: String(params.f) }), + }, + beforeLoad: ({ params }) => ({ ctxF: smallHash(params.f) }), + component: LevelF, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.tsx new file mode 100644 index 0000000000..e24d3dc373 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.tsx @@ -0,0 +1,74 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.e), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.e}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxE, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxE * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelE = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e')({ + params: { + parse: (params) => ({ ...params, e: normalizeParam(params.e) }), + stringify: (params) => ({ ...params, e: String(params.e) }), + }, + beforeLoad: ({ params }) => ({ ctxE: smallHash(params.e) }), + component: LevelE, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.tsx new file mode 100644 index 0000000000..7785638ee7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.tsx @@ -0,0 +1,83 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.d), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.d}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxD, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxD * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelD = Vue.defineComponent({ + setup() { + const params = Route.useParams() + return () => ( + <> + + + + +
+ {[ + params.value.a, + params.value.b, + params.value.c, + params.value.d, + ].join('.')} +
+ + + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b/$c/$d')({ + params: { + parse: (params) => ({ ...params, d: normalizeParam(params.d) }), + stringify: (params) => ({ ...params, d: String(params.d) }), + }, + beforeLoad: ({ params }) => ({ ctxD: smallHash(params.d) }), + component: LevelD, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.tsx new file mode 100644 index 0000000000..0d0adc65ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.tsx @@ -0,0 +1,74 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.c), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.c}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxC, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxC * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelC = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b/$c')({ + params: { + parse: (params) => ({ ...params, c: normalizeParam(params.c) }), + stringify: (params) => ({ ...params, c: String(params.c) }), + }, + beforeLoad: ({ params }) => ({ ctxC: smallHash(params.c) }), + component: LevelC, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.tsx new file mode 100644 index 0000000000..f013d865af --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.tsx @@ -0,0 +1,74 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.b), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.b}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxB, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxB * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelB = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b')({ + params: { + parse: (params) => ({ ...params, b: normalizeParam(params.b) }), + stringify: (params) => ({ ...params, b: String(params.b) }), + }, + beforeLoad: ({ params }) => ({ ctxB: smallHash(params.b) }), + component: LevelB, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.tsx new file mode 100644 index 0000000000..d5764c0985 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.tsx @@ -0,0 +1,74 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.a), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.a}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxA, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxA * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelA = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + + ) + }, +}) + +export const Route = createFileRoute('/l/$a')({ + params: { + parse: (params) => ({ ...params, a: normalizeParam(params.a) }), + stringify: (params) => ({ ...params, a: String(params.a) }), + }, + beforeLoad: ({ params }) => ({ ctxA: smallHash(params.a) }), + component: LevelA, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/tsconfig.json b/benchmarks/client-nav/scenarios/nested-params/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts new file mode 100644 index 0000000000..0d74eb7a7c --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts @@ -0,0 +1,44 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav nested-params (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/preload/react/project.json b/benchmarks/client-nav/scenarios/preload/react/project.json new file mode 100644 index 0000000000..f095228746 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-preload-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/preload/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/preload/react/setup.ts b/benchmarks/client-nav/scenarios/preload/react/setup.ts new file mode 100644 index 0000000000..5409df903c --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, scenarioSteps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + steps: scenarioSteps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts new file mode 100644 index 0000000000..5c210b2fd7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-preload', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-preload interaction loop (react)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/preload/react/speed.flame.ts b/benchmarks/client-nav/scenarios/preload/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/preload/react/src/main.tsx b/benchmarks/client-nav/scenarios/preload/react/src/main.tsx new file mode 100644 index 0000000000..395867f674 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/src/main.tsx @@ -0,0 +1,40 @@ +import type { RouterHistory } from '@tanstack/history' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + defaultPreload: 'intent', + defaultPreloadDelay: 0, + defaultPreloadStaleTime: 0, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const reactRoot = createRoot(container) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/preload/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..20619341c0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as DocsRouteImport } from './routes/docs' +import { Route as SectionsSectionRouteImport } from './routes/sections.$section' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + getParentRoute: () => rootRouteImport, +} as any) +const SectionsSectionRoute = SectionsSectionRouteImport.update({ + id: '/sections/$section', + path: '/sections/$section', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/docs' | '/sections/$section' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/docs' | '/sections/$section' + id: '__root__' | '/' | '/docs' | '/sections/$section' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DocsRoute: typeof DocsRoute + SectionsSectionRoute: typeof SectionsSectionRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } + '/sections/$section': { + id: '/sections/$section' + path: '/sections/$section' + fullPath: '/sections/$section' + preLoaderRoute: typeof SectionsSectionRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DocsRoute: DocsRoute, + SectionsSectionRoute: SectionsSectionRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/preload/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/preload/react/src/routes/__root.tsx new file mode 100644 index 0000000000..b659fe4d26 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/src/routes/__root.tsx @@ -0,0 +1,32 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' +import { sections } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/preload/react/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/preload/react/src/routes/docs.tsx new file mode 100644 index 0000000000..1f87530bac --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/src/routes/docs.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' +import { docsMarker } from '../../../shared' + +export const Route = createFileRoute('/docs')({ + component: DocsPage, +}) + +function DocsPage() { + return ( +
+

{docsMarker}

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

{homeMarker}

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

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

+
    + {data.items.map((item) => ( +
  • {`${item.name}=${item.value}`}
  • + ))} +
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/preload/react/tsconfig.json b/benchmarks/client-nav/scenarios/preload/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/preload/react/vite.config.ts b/benchmarks/client-nav/scenarios/preload/react/vite.config.ts new file mode 100644 index 0000000000..8a41fc8707 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/vite.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'react', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav preload (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/preload/shared.ts b/benchmarks/client-nav/scenarios/preload/shared.ts new file mode 100644 index 0000000000..d061f99451 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/shared.ts @@ -0,0 +1,119 @@ +/** + * Shared definition of the `preload` scenario: intent preloading via link + * hover, programmatic `router.preloadRoute`, and commit-time preload-cache + * maintenance. The router is configured with `defaultPreload: 'intent'`, + * `defaultPreloadDelay: 0` (no wall-clock debounce timer) and + * `defaultPreloadStaleTime: 0` — the default 30s wall-clock threshold would + * flip cache-hit behavior mid-run; with 0 every hover re-runs the preload + * work, keeping the loop stationary. + * + * Hover-intent preloading was verified manually per adapter (standalone jsdom + * run inspecting the router's cached matches after dispatching `mouseover` on + * a link). The harness hover step dispatches a single `mouseover`, which + * triggers the preload pipeline exactly once in every adapter: React + * synthesizes mouseEnter from it, Solid/Vue attach a native `mouseover` + * handler. (Solid/Vue also listen to `mouseenter`; dispatching both events + * would preload twice for them but once for React.) + */ +import type { ScenarioStep } from '../harness' + +export const sections = ['a', 'b', 'c', 'd', 'e'] as const + +export const SECTION_ITEM_COUNT = 30 + +/** Deterministic LCG stream seeded from a string — no Math.random. */ +function seededValues(seedText: string, count: number) { + let value = 0 + for (let i = 0; i < seedText.length; i++) { + value = (value * 31 + seedText.charCodeAt(i)) >>> 0 + } + + const values: Array = [] + for (let i = 0; i < count; i++) { + value = (value * 1664525 + 1013904223) >>> 0 + values.push(value % 100_000) + } + return values +} + +export interface SectionItem { + name: string + value: number +} + +export function sectionItems(section: string): Array { + return seededValues(`section-${section}`, SECTION_ITEM_COUNT).map( + (value, index) => ({ + name: `item-${section}-${index}`, + value, + }), + ) +} + +export function sectionChecksum(section: string) { + return sectionItems(section).reduce( + (sum, item) => (sum + item.value) % 1_000_000_007, + 0, + ) +} + +export function sectionMarker(section: string) { + return `${section}:${sectionChecksum(section)}` +} + +export const docsMarker = 'docs' +export const homeMarker = 'home' + +interface StepDef { + step: ScenarioStep + /** Expected page marker after the step; undefined for non-navigation steps. */ + marker?: string +} + +export const stepDefs: ReadonlyArray = [ + { step: { type: 'hover', testId: 's-a' } }, + { step: { type: 'hover', testId: 's-b' } }, + { step: 's-a', marker: sectionMarker('a') }, + { step: { type: 'hover', testId: 's-c' } }, + { step: 's-c', marker: sectionMarker('c') }, + { + step: { + type: 'preload', + getOptions: () => ({ + to: '/sections/$section', + params: { section: 'd' }, + }), + }, + }, + { step: 's-d', marker: sectionMarker('d') }, + { step: { type: 'hover', testId: 's-e' } }, + { step: 'go-docs', marker: docsMarker }, + { step: 'go-home', marker: homeMarker }, +] + +export const scenarioSteps: ReadonlyArray = stepDefs.map( + (def) => def.step, +) + +export function assertStepResult(stepIndex: number, container: HTMLElement) { + const def = stepDefs[stepIndex]! + if (!def.marker) { + return + } + + const marker = container.querySelector('[data-testid="page-state"]') + if (marker?.textContent !== def.marker) { + throw new Error( + `Expected page marker "${def.marker}" after step ${stepIndex}, received "${marker?.textContent}"`, + ) + } +} + +// Two laps through the 10-step sequence per benchmark iteration. +export const ticksPerIteration = 20 + +export const benchOptions = { + warmupIterations: 50, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/project.json b/benchmarks/client-nav/scenarios/preload/solid/project.json new file mode 100644 index 0000000000..a186879335 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-preload-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/preload/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/setup.ts b/benchmarks/client-nav/scenarios/preload/solid/setup.ts new file mode 100644 index 0000000000..34270fe8a4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, scenarioSteps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + steps: scenarioSteps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts new file mode 100644 index 0000000000..f835b4a7b9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-preload', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-preload interaction loop (solid)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/preload/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/preload/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx new file mode 100644 index 0000000000..3791156c64 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx @@ -0,0 +1,37 @@ +import type { RouterHistory } from '@tanstack/history' +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + defaultPreload: 'intent', + defaultPreloadDelay: 0, + defaultPreloadStaleTime: 0, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const unmount = render(() => , container) + + return { + router, + unmount, + } +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..97e215b6da --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as DocsRouteImport } from './routes/docs' +import { Route as SectionsSectionRouteImport } from './routes/sections.$section' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + getParentRoute: () => rootRouteImport, +} as any) +const SectionsSectionRoute = SectionsSectionRouteImport.update({ + id: '/sections/$section', + path: '/sections/$section', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/docs' | '/sections/$section' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/docs' | '/sections/$section' + id: '__root__' | '/' | '/docs' | '/sections/$section' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DocsRoute: typeof DocsRoute + SectionsSectionRoute: typeof SectionsSectionRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } + '/sections/$section': { + id: '/sections/$section' + path: '/sections/$section' + fullPath: '/sections/$section' + preLoaderRoute: typeof SectionsSectionRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DocsRoute: DocsRoute, + SectionsSectionRoute: SectionsSectionRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..a805ed0feb --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/src/routes/__root.tsx @@ -0,0 +1,34 @@ +import { For } from 'solid-js' +import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' +import { sections } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/routes/docs.tsx new file mode 100644 index 0000000000..b077cfd18f --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/src/routes/docs.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { docsMarker } from '../../../shared' + +export const Route = createFileRoute('/docs')({ + component: DocsPage, +}) + +function DocsPage() { + return ( +
+

{docsMarker}

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

{homeMarker}

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

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

+
    + + {(item) =>
  • {`${item.name}=${item.value}`}
  • } +
    +
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/tsconfig.json b/benchmarks/client-nav/scenarios/preload/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts b/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts new file mode 100644 index 0000000000..07014e6124 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts @@ -0,0 +1,50 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'solid', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav preload (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/project.json b/benchmarks/client-nav/scenarios/preload/vue/project.json new file mode 100644 index 0000000000..404476723d --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-preload-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/preload/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/preload/vue/setup.ts b/benchmarks/client-nav/scenarios/preload/vue/setup.ts new file mode 100644 index 0000000000..f70a154909 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, scenarioSteps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + steps: scenarioSteps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts new file mode 100644 index 0000000000..e0ec83619b --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-preload', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-preload interaction loop (vue)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/preload/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx new file mode 100644 index 0000000000..3da20b2cbf --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx @@ -0,0 +1,44 @@ +import type { RouterHistory } from '@tanstack/history' +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + defaultPreload: 'intent', + defaultPreloadDelay: 0, + defaultPreloadStaleTime: 0, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..5f95d09da0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as DocsRouteImport } from './routes/docs' +import { Route as SectionsSectionRouteImport } from './routes/sections.$section' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + getParentRoute: () => rootRouteImport, +} as any) +const SectionsSectionRoute = SectionsSectionRouteImport.update({ + id: '/sections/$section', + path: '/sections/$section', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/docs' | '/sections/$section' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/docs' | '/sections/$section' + id: '__root__' | '/' | '/docs' | '/sections/$section' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DocsRoute: typeof DocsRoute + SectionsSectionRoute: typeof SectionsSectionRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } + '/sections/$section': { + id: '/sections/$section' + path: '/sections/$section' + fullPath: '/sections/$section' + preLoaderRoute: typeof SectionsSectionRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DocsRoute: DocsRoute, + SectionsSectionRoute: SectionsSectionRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..bf91ba3770 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/src/routes/__root.tsx @@ -0,0 +1,35 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' +import { sections } from '../../../shared' + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/routes/docs.tsx new file mode 100644 index 0000000000..07d0a989ad --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/src/routes/docs.tsx @@ -0,0 +1,17 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { docsMarker } from '../../../shared' + +const DocsPage = Vue.defineComponent({ + setup() { + return () => ( +
+

{docsMarker}

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

{homeMarker}

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

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

+
    + {data.value.items.map((item) => ( +
  • {`${item.name}=${item.value}`}
  • + ))} +
+
+ ) + }, +}) + +export const Route = createFileRoute('/sections/$section')({ + loader: ({ params }) => { + const items = sectionItems(params.section) + const checksum = items.reduce( + (sum, item) => (sum + item.value) % 1_000_000_007, + 0, + ) + return { items, checksum } + }, + staleTime: 0, + gcTime: 0, + component: SectionPage, +}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/tsconfig.json b/benchmarks/client-nav/scenarios/preload/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts b/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts new file mode 100644 index 0000000000..8d00e66378 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts @@ -0,0 +1,44 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav preload (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/react/project.json b/benchmarks/client-nav/scenarios/rewrites/react/project.json new file mode 100644 index 0000000000..d98c6e1412 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-rewrites-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/rewrites/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/setup.ts b/benchmarks/client-nav/scenarios/rewrites/react/setup.ts new file mode 100644 index 0000000000..0c5df273ed --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, initialUrl, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + initialUrl, + }) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts new file mode 100644 index 0000000000..dd1b6f3686 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-rewrites', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-rewrites navigation loop (react)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/react/speed.flame.ts b/benchmarks/client-nav/scenarios/rewrites/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx new file mode 100644 index 0000000000..28020ce373 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx @@ -0,0 +1,40 @@ +import type { RouterHistory } from '@tanstack/history' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' +import { basepath, localeRewrite } from '../../shared' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + basepath, + rewrite: localeRewrite, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const reactRoot = createRoot(container) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/rewrites/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..b6ab8c8be4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/src/routeTree.gen.ts @@ -0,0 +1,103 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as PARouteImport } from './routes/p.$a' +import { Route as PABRouteImport } from './routes/p.$a.$b' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PARoute = PARouteImport.update({ + id: '/p/$a', + path: '/p/$a', + getParentRoute: () => rootRouteImport, +} as any) +const PABRoute = PABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => PARoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/p/$a' | '/p/$a/$b' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/p/$a' | '/p/$a/$b' + id: '__root__' | '/' | '/p/$a' | '/p/$a/$b' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + PARoute: typeof PARouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a': { + id: '/p/$a' + path: '/p/$a' + fullPath: '/p/$a' + preLoaderRoute: typeof PARouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a/$b': { + id: '/p/$a/$b' + path: '/$b' + fullPath: '/p/$a/$b' + preLoaderRoute: typeof PABRouteImport + parentRoute: typeof PARoute + } + } +} + +interface PARouteChildren { + PABRoute: typeof PABRoute +} + +const PARouteChildren: PARouteChildren = { + PABRoute: PABRoute, +} + +const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + PARoute: PARouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/__root.tsx new file mode 100644 index 0000000000..ad14ff51f1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/__root.tsx @@ -0,0 +1,61 @@ +import { + Link, + Outlet, + createRootRoute, + useLocation, +} from '@tanstack/react-router' +import type { SearchSchemaInput } from '@tanstack/react-router' + +export const Route = createRootRoute({ + validateSearch: (search: Record & SearchSchemaInput) => + ({ + _locale: typeof search._locale === 'string' ? search._locale : undefined, + }) as { _locale?: string }, + component: RootComponent, +}) + +function RootComponent() { + const pathname = useLocation({ select: (location) => location.pathname }) + + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/index.tsx new file mode 100644 index 0000000000..821cfe4a7c --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

Home

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

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

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

{sectionLabel(params.a)}

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/tsconfig.json b/benchmarks/client-nav/scenarios/rewrites/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts new file mode 100644 index 0000000000..e79e8522e9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'react', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav rewrites (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/shared.ts b/benchmarks/client-nav/scenarios/rewrites/shared.ts new file mode 100644 index 0000000000..0ca0a7ceb9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/shared.ts @@ -0,0 +1,106 @@ +/** + * Shared definition of the `rewrites` scenario: composed client-side location + * rewrites — router `basepath` plus a locale input/output rewrite (the client + * analog of the SSR `rewrites` scenario). Externally URLs look like + * `/app/{locale}/p/...`; internally the router sees `/p/...` with the locale + * carried in the `_locale` search param. Every navigation runs the composed + * output rewrite when building hrefs/committing and the input rewrite when + * parsing the committed location. + */ +import type { ScenarioStep } from '../harness' +import type { RouterHistory } from '@tanstack/history' + +export const basepath = '/app' +export const defaultLocale = 'en' + +const localePrefixRe = /^\/(fr|de|es)(\/.*)$/ + +// Framework-agnostic rewrite pair consumed by all three apps' createRouter. +export const localeRewrite = { + input: ({ url }: { url: URL }) => { + const match = url.pathname.match(localePrefixRe) + + if (match) { + url.pathname = match[2]! + url.searchParams.set('_locale', match[1]!) + return url + } + + return undefined + }, + output: ({ url }: { url: URL }) => { + const locale = url.searchParams.get('_locale') + + if (locale) { + url.searchParams.delete('_locale') + url.pathname = `/${locale}${url.pathname}` + } + + return url + }, +} + +export function sectionLabel(a: string) { + return `Section ${a}` +} + +export function itemLabel(a: string, b: string) { + return `Item ${a}/${b}` +} + +interface StepDef { + testId: string + /** Internal router pathname expected after the step. */ + routerPath: string + /** External history pathname expected after the step. */ + windowPath: string +} + +// Circular lap: alternates sections, depths, and locales so every step runs +// the composed rewrites in both directions, then returns to the start. +export const stepDefs: ReadonlyArray = [ + { testId: 'go-x', routerPath: '/p/x', windowPath: '/app/p/x' }, + { testId: 'go-x-1-fr', routerPath: '/p/x/1', windowPath: '/app/fr/p/x/1' }, + { testId: 'go-y-de', routerPath: '/p/y', windowPath: '/app/de/p/y' }, + { testId: 'go-y-2', routerPath: '/p/y/2', windowPath: '/app/p/y/2' }, + { testId: 'go-x-es', routerPath: '/p/x', windowPath: '/app/es/p/x' }, + { testId: 'go-home', routerPath: '/', windowPath: '/app/' }, +] as const + +export const steps: ReadonlyArray = stepDefs.map( + (step) => step.testId, +) + +export function assertStepResult( + stepIndex: number, + container: HTMLElement, + history: RouterHistory, +) { + const expected = stepDefs[stepIndex]! + const marker = container.querySelector('[data-testid="loc"]') + const routerPath = marker?.textContent + + if (routerPath !== expected.routerPath) { + throw new Error( + `Expected router pathname "${expected.routerPath}" after step ${stepIndex}, received "${routerPath}"`, + ) + } + + if (history.location.pathname !== expected.windowPath) { + throw new Error( + `Expected history pathname "${expected.windowPath}" after step ${stepIndex}, received "${history.location.pathname}"`, + ) + } +} + +// The app starts on the external root inside the basepath. +export const initialUrl = '/app' + +// Three laps through the 6-step sequence per benchmark iteration. +export const ticksPerIteration = 18 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/project.json b/benchmarks/client-nav/scenarios/rewrites/solid/project.json new file mode 100644 index 0000000000..4b2f763032 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-rewrites-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/rewrites/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/setup.ts b/benchmarks/client-nav/scenarios/rewrites/solid/setup.ts new file mode 100644 index 0000000000..5796df712d --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, initialUrl, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + initialUrl, + }) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts new file mode 100644 index 0000000000..9c4313e2ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-rewrites', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-rewrites navigation loop (solid)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/rewrites/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx new file mode 100644 index 0000000000..31f1d07650 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx @@ -0,0 +1,37 @@ +import type { RouterHistory } from '@tanstack/history' +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' +import { basepath, localeRewrite } from '../../shared' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + basepath, + rewrite: localeRewrite, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const unmount = render(() => , container) + + return { + router, + unmount, + } +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/rewrites/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..2d35f899c9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/src/routeTree.gen.ts @@ -0,0 +1,103 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as PARouteImport } from './routes/p.$a' +import { Route as PABRouteImport } from './routes/p.$a.$b' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PARoute = PARouteImport.update({ + id: '/p/$a', + path: '/p/$a', + getParentRoute: () => rootRouteImport, +} as any) +const PABRoute = PABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => PARoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/p/$a' | '/p/$a/$b' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/p/$a' | '/p/$a/$b' + id: '__root__' | '/' | '/p/$a' | '/p/$a/$b' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + PARoute: typeof PARouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a': { + id: '/p/$a' + path: '/p/$a' + fullPath: '/p/$a' + preLoaderRoute: typeof PARouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a/$b': { + id: '/p/$a/$b' + path: '/$b' + fullPath: '/p/$a/$b' + preLoaderRoute: typeof PABRouteImport + parentRoute: typeof PARoute + } + } +} + +interface PARouteChildren { + PABRoute: typeof PABRoute +} + +const PARouteChildren: PARouteChildren = { + PABRoute: PABRoute, +} + +const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + PARoute: PARouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..3a78f2c3cf --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/__root.tsx @@ -0,0 +1,61 @@ +import { + Link, + Outlet, + createRootRoute, + useLocation, +} from '@tanstack/solid-router' +import type { SearchSchemaInput } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + validateSearch: (search: Record & SearchSchemaInput) => + ({ + _locale: typeof search._locale === 'string' ? search._locale : undefined, + }) as { _locale?: string }, + component: RootComponent, +}) + +function RootComponent() { + const pathname = useLocation({ select: (location) => location.pathname }) + + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/index.tsx new file mode 100644 index 0000000000..5ee381ff05 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

Home

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

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

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

{sectionLabel(params().a)}

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/tsconfig.json b/benchmarks/client-nav/scenarios/rewrites/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts new file mode 100644 index 0000000000..c9e99b7d60 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts @@ -0,0 +1,50 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'solid', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav rewrites (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/project.json b/benchmarks/client-nav/scenarios/rewrites/vue/project.json new file mode 100644 index 0000000000..9b7cb5d198 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-rewrites-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/rewrites/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/setup.ts b/benchmarks/client-nav/scenarios/rewrites/vue/setup.ts new file mode 100644 index 0000000000..e26b4d05ca --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, initialUrl, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + initialUrl, + }) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts new file mode 100644 index 0000000000..e96aff39eb --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-rewrites', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-rewrites navigation loop (vue)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/rewrites/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx new file mode 100644 index 0000000000..6695e82dbb --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx @@ -0,0 +1,44 @@ +import type { RouterHistory } from '@tanstack/history' +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' +import { basepath, localeRewrite } from '../../shared' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + basepath, + rewrite: localeRewrite, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/rewrites/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..6eca4e8ce5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/src/routeTree.gen.ts @@ -0,0 +1,103 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as PARouteImport } from './routes/p.$a' +import { Route as PABRouteImport } from './routes/p.$a.$b' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PARoute = PARouteImport.update({ + id: '/p/$a', + path: '/p/$a', + getParentRoute: () => rootRouteImport, +} as any) +const PABRoute = PABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => PARoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/p/$a' | '/p/$a/$b' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/p/$a' | '/p/$a/$b' + id: '__root__' | '/' | '/p/$a' | '/p/$a/$b' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + PARoute: typeof PARouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a': { + id: '/p/$a' + path: '/p/$a' + fullPath: '/p/$a' + preLoaderRoute: typeof PARouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a/$b': { + id: '/p/$a/$b' + path: '/$b' + fullPath: '/p/$a/$b' + preLoaderRoute: typeof PABRouteImport + parentRoute: typeof PARoute + } + } +} + +interface PARouteChildren { + PABRoute: typeof PABRoute +} + +const PARouteChildren: PARouteChildren = { + PABRoute: PABRoute, +} + +const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + PARoute: PARouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..ae89645005 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/__root.tsx @@ -0,0 +1,64 @@ +import * as Vue from 'vue' +import { + Link, + Outlet, + createRootRoute, + useLocation, +} from '@tanstack/vue-router' +import type { SearchSchemaInput } from '@tanstack/vue-router' + +const RootComponent = Vue.defineComponent({ + setup() { + const pathname = useLocation({ select: (location) => location.pathname }) + + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + validateSearch: (search: Record & SearchSchemaInput) => + ({ + _locale: typeof search._locale === 'string' ? search._locale : undefined, + }) as { _locale?: string }, + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/index.tsx new file mode 100644 index 0000000000..d5405b52d2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/index.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const HomePage = Vue.defineComponent({ + setup() { + return () => ( +
+

Home

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

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

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

{sectionLabel(params.value.a)}

+ +
+ ) + }, +}) + +export const Route = createFileRoute('/p/$a')({ + component: SectionPage, +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/tsconfig.json b/benchmarks/client-nav/scenarios/rewrites/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts new file mode 100644 index 0000000000..1a795a4e1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts @@ -0,0 +1,44 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav rewrites (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/project.json b/benchmarks/client-nav/scenarios/route-tree-scale/react/project.json new file mode 100644 index 0000000000..3291738f79 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-route-tree-scale-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/route-tree-scale/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/setup.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/setup.ts new file mode 100644 index 0000000000..130583b190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts new file mode 100644 index 0000000000..6f4b448775 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-route-tree-scale', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-route-tree-scale navigation loop (react)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.flame.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx @@ -0,0 +1,37 @@ +import type { RouterHistory } from '@tanstack/history' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const reactRoot = createRoot(container) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..f8eeb73dda --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts @@ -0,0 +1,881 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as SecARouteImport } from './routes/sec-a' +import { Route as SecBRouteImport } from './routes/sec-b' +import { Route as SecCRouteImport } from './routes/sec-c' +import { Route as SecDRouteImport } from './routes/sec-d' +import { Route as SecERouteImport } from './routes/sec-e' +import { Route as SecFRouteImport } from './routes/sec-f' +import { Route as marketingPricingRouteImport } from './routes/(marketing)/pricing' +import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' +import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' +import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' +import { Route as FilesSplatRouteImport } from './routes/files.$' +import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' +import { Route as SecAIndexRouteImport } from './routes/sec-a.index' +import { Route as SecAIdRouteImport } from './routes/sec-a.$id' +import { Route as SecAAboutRouteImport } from './routes/sec-a.about' +import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' +import { Route as SecBIndexRouteImport } from './routes/sec-b.index' +import { Route as SecBIdRouteImport } from './routes/sec-b.$id' +import { Route as SecBAboutRouteImport } from './routes/sec-b.about' +import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' +import { Route as SecCIndexRouteImport } from './routes/sec-c.index' +import { Route as SecCIdRouteImport } from './routes/sec-c.$id' +import { Route as SecCAboutRouteImport } from './routes/sec-c.about' +import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' +import { Route as SecDIndexRouteImport } from './routes/sec-d.index' +import { Route as SecDIdRouteImport } from './routes/sec-d.$id' +import { Route as SecDAboutRouteImport } from './routes/sec-d.about' +import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' +import { Route as SecEIndexRouteImport } from './routes/sec-e.index' +import { Route as SecEIdRouteImport } from './routes/sec-e.$id' +import { Route as SecEAboutRouteImport } from './routes/sec-e.about' +import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' +import { Route as SecFIndexRouteImport } from './routes/sec-f.index' +import { Route as SecFIdRouteImport } from './routes/sec-f.$id' +import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecFSettingsRouteImport } from './routes/sec-f.settings' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const SecARoute = SecARouteImport.update({ + id: '/sec-a', + path: '/sec-a', + getParentRoute: () => rootRouteImport, +} as any) +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', + getParentRoute: () => rootRouteImport, +} as any) +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', + getParentRoute: () => rootRouteImport, +} as any) +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', + getParentRoute: () => rootRouteImport, +} as any) +const SecERoute = SecERouteImport.update({ + id: '/sec-e', + path: '/sec-e', + getParentRoute: () => rootRouteImport, +} as any) +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, +} as any) +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, +} as any) +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, +} as any) +const ReleaseVChar123versionChar125Route = + ReleaseVChar123versionChar125RouteImport.update({ + id: '/release/v{$version}', + path: '/release/v{$version}', + getParentRoute: () => rootRouteImport, + } as any) +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, +} as any) +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, +} as any) +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, +} as any) +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, +} as any) +const SecBIndexRoute = SecBIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecBRoute, +} as any) +const SecBIdRoute = SecBIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecBRoute, +} as any) +const SecBAboutRoute = SecBAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecBRoute, +} as any) +const SecBSettingsRoute = SecBSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecBRoute, +} as any) +const SecCIndexRoute = SecCIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecCRoute, +} as any) +const SecCIdRoute = SecCIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecCRoute, +} as any) +const SecCAboutRoute = SecCAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecCRoute, +} as any) +const SecCSettingsRoute = SecCSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecCRoute, +} as any) +const SecDIndexRoute = SecDIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecDRoute, +} as any) +const SecDIdRoute = SecDIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecDRoute, +} as any) +const SecDAboutRoute = SecDAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecDRoute, +} as any) +const SecDSettingsRoute = SecDSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecDRoute, +} as any) +const SecEIndexRoute = SecEIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecERoute, +} as any) +const SecEIdRoute = SecEIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecERoute, +} as any) +const SecEAboutRoute = SecEAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecERoute, +} as any) +const SecESettingsRoute = SecESettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecERoute, +} as any) +const SecFIndexRoute = SecFIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecFRoute, +} as any) +const SecFIdRoute = SecFIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecFRoute, +} as any) +const SecFAboutRoute = SecFAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecFRoute, +} as any) +const SecFSettingsRoute = SecFSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecFRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/sec-a': typeof SecARouteWithChildren + '/sec-b': typeof SecBRouteWithChildren + '/sec-c': typeof SecCRouteWithChildren + '/sec-d': typeof SecDRouteWithChildren + '/sec-e': typeof SecERouteWithChildren + '/sec-f': typeof SecFRouteWithChildren + '/pricing': typeof marketingPricingRoute + '/promo': typeof marketingPromoRoute + '/alpha': typeof LayoutAlphaRoute + '/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a/': typeof SecAIndexRoute + '/sec-b/': typeof SecBIndexRoute + '/sec-c/': typeof SecCIndexRoute + '/sec-d/': typeof SecDIndexRoute + '/sec-e/': typeof SecEIndexRoute + '/sec-f/': typeof SecFIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/pricing': typeof marketingPricingRoute + '/promo': typeof marketingPromoRoute + '/alpha': typeof LayoutAlphaRoute + '/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a': typeof SecAIndexRoute + '/sec-b': typeof SecBIndexRoute + '/sec-c': typeof SecCIndexRoute + '/sec-d': typeof SecDIndexRoute + '/sec-e': typeof SecEIndexRoute + '/sec-f': typeof SecFIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/_layout': typeof LayoutRouteWithChildren + '/sec-a': typeof SecARouteWithChildren + '/sec-b': typeof SecBRouteWithChildren + '/sec-c': typeof SecCRouteWithChildren + '/sec-d': typeof SecDRouteWithChildren + '/sec-e': typeof SecERouteWithChildren + '/sec-f': typeof SecFRouteWithChildren + '/(marketing)/pricing': typeof marketingPricingRoute + '/(marketing)/promo': typeof marketingPromoRoute + '/_layout/alpha': typeof LayoutAlphaRoute + '/_layout/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a/': typeof SecAIndexRoute + '/sec-b/': typeof SecBIndexRoute + '/sec-c/': typeof SecCIndexRoute + '/sec-d/': typeof SecDIndexRoute + '/sec-e/': typeof SecEIndexRoute + '/sec-f/': typeof SecFIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + | '/pricing' + | '/promo' + | '/alpha' + | '/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a/' + | '/sec-b/' + | '/sec-c/' + | '/sec-d/' + | '/sec-e/' + | '/sec-f/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/pricing' + | '/promo' + | '/alpha' + | '/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + id: + | '__root__' + | '/' + | '/_layout' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + | '/(marketing)/pricing' + | '/(marketing)/promo' + | '/_layout/alpha' + | '/_layout/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a/' + | '/sec-b/' + | '/sec-c/' + | '/sec-d/' + | '/sec-e/' + | '/sec-f/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LayoutRoute: typeof LayoutRouteWithChildren + SecARoute: typeof SecARouteWithChildren + SecBRoute: typeof SecBRouteWithChildren + SecCRoute: typeof SecCRouteWithChildren + SecDRoute: typeof SecDRouteWithChildren + SecERoute: typeof SecERouteWithChildren + SecFRoute: typeof SecFRouteWithChildren + marketingPricingRoute: typeof marketingPricingRoute + marketingPromoRoute: typeof marketingPromoRoute + FilesSplatRoute: typeof FilesSplatRoute + ReleaseVChar123versionChar125Route: typeof ReleaseVChar123versionChar125Route +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport + parentRoute: typeof rootRouteImport + } + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-e': { + id: '/sec-e' + path: '/sec-e' + fullPath: '/sec-e' + preLoaderRoute: typeof SecERouteImport + parentRoute: typeof rootRouteImport + } + '/sec-f': { + id: '/sec-f' + path: '/sec-f' + fullPath: '/sec-f' + preLoaderRoute: typeof SecFRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/pricing': { + id: '/(marketing)/pricing' + path: '/pricing' + fullPath: '/pricing' + preLoaderRoute: typeof marketingPricingRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/promo': { + id: '/(marketing)/promo' + path: '/promo' + fullPath: '/promo' + preLoaderRoute: typeof marketingPromoRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/alpha': { + id: '/_layout/alpha' + path: '/alpha' + fullPath: '/alpha' + preLoaderRoute: typeof LayoutAlphaRouteImport + parentRoute: typeof LayoutRoute + } + '/_layout/beta': { + id: '/_layout/beta' + path: '/beta' + fullPath: '/beta' + preLoaderRoute: typeof LayoutBetaRouteImport + parentRoute: typeof LayoutRoute + } + '/files/$': { + id: '/files/$' + path: '/files/$' + fullPath: '/files/$' + preLoaderRoute: typeof FilesSplatRouteImport + parentRoute: typeof rootRouteImport + } + '/release/v{$version}': { + id: '/release/v{$version}' + path: '/release/v{$version}' + fullPath: '/release/v{$version}' + preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + parentRoute: typeof rootRouteImport + } + '/sec-a/': { + id: '/sec-a/' + path: '/' + fullPath: '/sec-a/' + preLoaderRoute: typeof SecAIndexRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/$id': { + id: '/sec-a/$id' + path: '/$id' + fullPath: '/sec-a/$id' + preLoaderRoute: typeof SecAIdRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute + } + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/settings': { + id: '/sec-b/settings' + path: '/settings' + fullPath: '/sec-b/settings' + preLoaderRoute: typeof SecBSettingsRouteImport + parentRoute: typeof SecBRoute + } + '/sec-c/': { + id: '/sec-c/' + path: '/' + fullPath: '/sec-c/' + preLoaderRoute: typeof SecCIndexRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/$id': { + id: '/sec-c/$id' + path: '/$id' + fullPath: '/sec-c/$id' + preLoaderRoute: typeof SecCIdRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/about': { + id: '/sec-c/about' + path: '/about' + fullPath: '/sec-c/about' + preLoaderRoute: typeof SecCAboutRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/settings': { + id: '/sec-c/settings' + path: '/settings' + fullPath: '/sec-c/settings' + preLoaderRoute: typeof SecCSettingsRouteImport + parentRoute: typeof SecCRoute + } + '/sec-d/': { + id: '/sec-d/' + path: '/' + fullPath: '/sec-d/' + preLoaderRoute: typeof SecDIndexRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/$id': { + id: '/sec-d/$id' + path: '/$id' + fullPath: '/sec-d/$id' + preLoaderRoute: typeof SecDIdRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/about': { + id: '/sec-d/about' + path: '/about' + fullPath: '/sec-d/about' + preLoaderRoute: typeof SecDAboutRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/settings': { + id: '/sec-d/settings' + path: '/settings' + fullPath: '/sec-d/settings' + preLoaderRoute: typeof SecDSettingsRouteImport + parentRoute: typeof SecDRoute + } + '/sec-e/': { + id: '/sec-e/' + path: '/' + fullPath: '/sec-e/' + preLoaderRoute: typeof SecEIndexRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/$id': { + id: '/sec-e/$id' + path: '/$id' + fullPath: '/sec-e/$id' + preLoaderRoute: typeof SecEIdRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/about': { + id: '/sec-e/about' + path: '/about' + fullPath: '/sec-e/about' + preLoaderRoute: typeof SecEAboutRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/settings': { + id: '/sec-e/settings' + path: '/settings' + fullPath: '/sec-e/settings' + preLoaderRoute: typeof SecESettingsRouteImport + parentRoute: typeof SecERoute + } + '/sec-f/': { + id: '/sec-f/' + path: '/' + fullPath: '/sec-f/' + preLoaderRoute: typeof SecFIndexRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/$id': { + id: '/sec-f/$id' + path: '/$id' + fullPath: '/sec-f/$id' + preLoaderRoute: typeof SecFIdRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/about': { + id: '/sec-f/about' + path: '/about' + fullPath: '/sec-f/about' + preLoaderRoute: typeof SecFAboutRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/settings': { + id: '/sec-f/settings' + path: '/settings' + fullPath: '/sec-f/settings' + preLoaderRoute: typeof SecFSettingsRouteImport + parentRoute: typeof SecFRoute + } + } +} + +interface LayoutRouteChildren { + LayoutAlphaRoute: typeof LayoutAlphaRoute + LayoutBetaRoute: typeof LayoutBetaRoute +} + +const LayoutRouteChildren: LayoutRouteChildren = { + LayoutAlphaRoute: LayoutAlphaRoute, + LayoutBetaRoute: LayoutBetaRoute, +} + +const LayoutRouteWithChildren = + LayoutRoute._addFileChildren(LayoutRouteChildren) + +interface SecARouteChildren { + SecAIdRoute: typeof SecAIdRoute + SecAAboutRoute: typeof SecAAboutRoute + SecASettingsRoute: typeof SecASettingsRoute + SecAIndexRoute: typeof SecAIndexRoute +} + +const SecARouteChildren: SecARouteChildren = { + SecAIdRoute: SecAIdRoute, + SecAAboutRoute: SecAAboutRoute, + SecASettingsRoute: SecASettingsRoute, + SecAIndexRoute: SecAIndexRoute, +} + +const SecARouteWithChildren = SecARoute._addFileChildren(SecARouteChildren) + +interface SecBRouteChildren { + SecBIdRoute: typeof SecBIdRoute + SecBAboutRoute: typeof SecBAboutRoute + SecBSettingsRoute: typeof SecBSettingsRoute + SecBIndexRoute: typeof SecBIndexRoute +} + +const SecBRouteChildren: SecBRouteChildren = { + SecBIdRoute: SecBIdRoute, + SecBAboutRoute: SecBAboutRoute, + SecBSettingsRoute: SecBSettingsRoute, + SecBIndexRoute: SecBIndexRoute, +} + +const SecBRouteWithChildren = SecBRoute._addFileChildren(SecBRouteChildren) + +interface SecCRouteChildren { + SecCIdRoute: typeof SecCIdRoute + SecCAboutRoute: typeof SecCAboutRoute + SecCSettingsRoute: typeof SecCSettingsRoute + SecCIndexRoute: typeof SecCIndexRoute +} + +const SecCRouteChildren: SecCRouteChildren = { + SecCIdRoute: SecCIdRoute, + SecCAboutRoute: SecCAboutRoute, + SecCSettingsRoute: SecCSettingsRoute, + SecCIndexRoute: SecCIndexRoute, +} + +const SecCRouteWithChildren = SecCRoute._addFileChildren(SecCRouteChildren) + +interface SecDRouteChildren { + SecDIdRoute: typeof SecDIdRoute + SecDAboutRoute: typeof SecDAboutRoute + SecDSettingsRoute: typeof SecDSettingsRoute + SecDIndexRoute: typeof SecDIndexRoute +} + +const SecDRouteChildren: SecDRouteChildren = { + SecDIdRoute: SecDIdRoute, + SecDAboutRoute: SecDAboutRoute, + SecDSettingsRoute: SecDSettingsRoute, + SecDIndexRoute: SecDIndexRoute, +} + +const SecDRouteWithChildren = SecDRoute._addFileChildren(SecDRouteChildren) + +interface SecERouteChildren { + SecEIdRoute: typeof SecEIdRoute + SecEAboutRoute: typeof SecEAboutRoute + SecESettingsRoute: typeof SecESettingsRoute + SecEIndexRoute: typeof SecEIndexRoute +} + +const SecERouteChildren: SecERouteChildren = { + SecEIdRoute: SecEIdRoute, + SecEAboutRoute: SecEAboutRoute, + SecESettingsRoute: SecESettingsRoute, + SecEIndexRoute: SecEIndexRoute, +} + +const SecERouteWithChildren = SecERoute._addFileChildren(SecERouteChildren) + +interface SecFRouteChildren { + SecFIdRoute: typeof SecFIdRoute + SecFAboutRoute: typeof SecFAboutRoute + SecFSettingsRoute: typeof SecFSettingsRoute + SecFIndexRoute: typeof SecFIndexRoute +} + +const SecFRouteChildren: SecFRouteChildren = { + SecFIdRoute: SecFIdRoute, + SecFAboutRoute: SecFAboutRoute, + SecFSettingsRoute: SecFSettingsRoute, + SecFIndexRoute: SecFIndexRoute, +} + +const SecFRouteWithChildren = SecFRoute._addFileChildren(SecFRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LayoutRoute: LayoutRouteWithChildren, + SecARoute: SecARouteWithChildren, + SecBRoute: SecBRouteWithChildren, + SecCRoute: SecCRouteWithChildren, + SecDRoute: SecDRouteWithChildren, + SecERoute: SecERouteWithChildren, + SecFRoute: SecFRouteWithChildren, + marketingPricingRoute: marketingPricingRoute, + marketingPromoRoute: marketingPromoRoute, + FilesSplatRoute: FilesSplatRoute, + ReleaseVChar123versionChar125Route: ReleaseVChar123versionChar125Route, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/pricing.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/pricing.tsx new file mode 100644 index 0000000000..ac2a376549 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/pricing.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/(marketing)/pricing')({ + component: Page, +}) + +function Page() { + return
pricing
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/promo.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/promo.tsx new file mode 100644 index 0000000000..b71962254e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/promo.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/(marketing)/promo')({ + component: Page, +}) + +function Page() { + return
promo
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/__root.tsx new file mode 100644 index 0000000000..7ed47da924 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/__root.tsx @@ -0,0 +1,58 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.alpha.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.alpha.tsx new file mode 100644 index 0000000000..893419cef5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.alpha.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_layout/alpha')({ + component: Page, +}) + +function Page() { + return
alpha
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.beta.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.beta.tsx new file mode 100644 index 0000000000..d20c6007ee --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.beta.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_layout/beta')({ + component: Page, +}) + +function Page() { + return
beta
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.tsx new file mode 100644 index 0000000000..961feb50f1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_layout')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/files.$.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/files.$.tsx new file mode 100644 index 0000000000..028aa43d5a --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/files.$.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/files/$')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`files:${params._splat}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/index.tsx new file mode 100644 index 0000000000..8a7ffca9e7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: Page, +}) + +function Page() { + return
home
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/release.v{$version}.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/release.v{$version}.tsx new file mode 100644 index 0000000000..dfe8e31905 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/release.v{$version}.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/release/v{$version}')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`release:${params.version}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.$id.tsx new file mode 100644 index 0000000000..8be053a040 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-a/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-a:${params.id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.about.tsx new file mode 100644 index 0000000000..54c1b28618 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-a/about')({ + component: Page, +}) + +function Page() { + return
sec-a:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.index.tsx new file mode 100644 index 0000000000..3c793a94f5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-a/')({ + component: Page, +}) + +function Page() { + return
sec-a:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.settings.tsx new file mode 100644 index 0000000000..0037f6463d --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-a/settings')({ + component: Page, +}) + +function Page() { + return
sec-a:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.tsx new file mode 100644 index 0000000000..846f96b67b --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-a')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.$id.tsx new file mode 100644 index 0000000000..0dd7f94feb --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-b/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-b:${params.id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.about.tsx new file mode 100644 index 0000000000..fde4647472 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-b/about')({ + component: Page, +}) + +function Page() { + return
sec-b:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.index.tsx new file mode 100644 index 0000000000..51b69cf664 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-b/')({ + component: Page, +}) + +function Page() { + return
sec-b:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.settings.tsx new file mode 100644 index 0000000000..977b7438b1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-b/settings')({ + component: Page, +}) + +function Page() { + return
sec-b:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.tsx new file mode 100644 index 0000000000..77d7e6475d --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-b')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.$id.tsx new file mode 100644 index 0000000000..eb3be796c0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-c/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-c:${params.id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.about.tsx new file mode 100644 index 0000000000..7910acf332 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-c/about')({ + component: Page, +}) + +function Page() { + return
sec-c:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.index.tsx new file mode 100644 index 0000000000..f6ae102f2d --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-c/')({ + component: Page, +}) + +function Page() { + return
sec-c:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.settings.tsx new file mode 100644 index 0000000000..bf2be30788 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-c/settings')({ + component: Page, +}) + +function Page() { + return
sec-c:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.tsx new file mode 100644 index 0000000000..77ac5644c6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-c')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.$id.tsx new file mode 100644 index 0000000000..d34aee8972 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-d/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-d:${params.id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.about.tsx new file mode 100644 index 0000000000..1f095cb2ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-d/about')({ + component: Page, +}) + +function Page() { + return
sec-d:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.index.tsx new file mode 100644 index 0000000000..8fc698a4d4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-d/')({ + component: Page, +}) + +function Page() { + return
sec-d:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.settings.tsx new file mode 100644 index 0000000000..76c7a178ea --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-d/settings')({ + component: Page, +}) + +function Page() { + return
sec-d:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.tsx new file mode 100644 index 0000000000..5f3d281b5e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-d')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.$id.tsx new file mode 100644 index 0000000000..6e31d0c5d1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-e/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-e:${params.id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.about.tsx new file mode 100644 index 0000000000..5a2835917b --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-e/about')({ + component: Page, +}) + +function Page() { + return
sec-e:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.index.tsx new file mode 100644 index 0000000000..0f23b8d484 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-e/')({ + component: Page, +}) + +function Page() { + return
sec-e:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.settings.tsx new file mode 100644 index 0000000000..b566a1ffaa --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-e/settings')({ + component: Page, +}) + +function Page() { + return
sec-e:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.tsx new file mode 100644 index 0000000000..e573a71d98 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-e')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.$id.tsx new file mode 100644 index 0000000000..a71c17f96e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-f/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-f:${params.id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.about.tsx new file mode 100644 index 0000000000..06831063ad --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-f/about')({ + component: Page, +}) + +function Page() { + return
sec-f:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.index.tsx new file mode 100644 index 0000000000..4cd54b6a7f --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-f/')({ + component: Page, +}) + +function Page() { + return
sec-f:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.settings.tsx new file mode 100644 index 0000000000..92bdca5e44 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-f/settings')({ + component: Page, +}) + +function Page() { + return
sec-f:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.tsx new file mode 100644 index 0000000000..2fa27873e8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-f')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/tsconfig.json b/benchmarks/client-nav/scenarios/route-tree-scale/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts new file mode 100644 index 0000000000..0f588fda53 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts @@ -0,0 +1,45 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'react', + // Real file-based apps code-split by default; this scenario keeps it on + // so navigations also exercise lazy route-chunk resolution. + autoCodeSplitting: true, + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav route-tree-scale (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/shared.ts b/benchmarks/client-nav/scenarios/route-tree-scale/shared.ts new file mode 100644 index 0000000000..8af5996804 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/shared.ts @@ -0,0 +1,64 @@ +/** + * Shared definition of the `route-tree-scale` scenario: route matching, + * location building, and link-target resolution over a wide route tree + * (~40 routes) mixing static segments, dynamic params, prefixed params, + * splats, pathless layouts, and route groups. Navigations jump between + * distant branches so matching cannot reuse the previous branch. + */ + +export const sections = [ + 'sec-a', + 'sec-b', + 'sec-c', + 'sec-d', + 'sec-e', + 'sec-f', +] as const + +export const steps = [ + 'go-sec-a-id', + 'go-sec-f-settings', + 'go-files', + 'go-release', + 'go-alpha', + 'go-promo', + 'go-sec-c-id', + 'go-sec-d-about', + 'go-home', +] as const + +// The dynamic ids and the splat carry characters that need percent-encoding +// (spaces, `&`, `%`, `+`, unicode) so matching also exercises the segment +// encode/decode paths. +const expectedMarkers = [ + 'sec-a:item 11%', + 'sec-f:settings', + 'files:x/ü y/z', + 'release:9', + 'alpha', + 'promo', + 'sec-c:q&a+42', + 'sec-d:about', + 'home', +] as const + +export function assertStepResult(stepIndex: number) { + const expected = expectedMarkers[stepIndex]! + const actual = document.querySelector( + '[data-testid="scale-state"]', + )?.textContent + if (actual !== expected) { + throw new Error( + `Expected scale-state marker "${expected}" after step ${stepIndex}, received "${actual}"`, + ) + } +} + +// Three laps through the 9-step sequence per benchmark iteration. +export const ticksPerIteration = 27 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/project.json b/benchmarks/client-nav/scenarios/route-tree-scale/solid/project.json new file mode 100644 index 0000000000..c568e41196 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-route-tree-scale-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/route-tree-scale/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/setup.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/setup.ts new file mode 100644 index 0000000000..6a46971603 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts new file mode 100644 index 0000000000..9244ef1350 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-route-tree-scale', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-route-tree-scale navigation loop (solid)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx @@ -0,0 +1,34 @@ +import type { RouterHistory } from '@tanstack/history' +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const unmount = render(() => , container) + + return { + router, + unmount, + } +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..e6f3596562 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts @@ -0,0 +1,881 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as SecARouteImport } from './routes/sec-a' +import { Route as SecBRouteImport } from './routes/sec-b' +import { Route as SecCRouteImport } from './routes/sec-c' +import { Route as SecDRouteImport } from './routes/sec-d' +import { Route as SecERouteImport } from './routes/sec-e' +import { Route as SecFRouteImport } from './routes/sec-f' +import { Route as marketingPricingRouteImport } from './routes/(marketing)/pricing' +import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' +import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' +import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' +import { Route as FilesSplatRouteImport } from './routes/files.$' +import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' +import { Route as SecAIndexRouteImport } from './routes/sec-a.index' +import { Route as SecAIdRouteImport } from './routes/sec-a.$id' +import { Route as SecAAboutRouteImport } from './routes/sec-a.about' +import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' +import { Route as SecBIndexRouteImport } from './routes/sec-b.index' +import { Route as SecBIdRouteImport } from './routes/sec-b.$id' +import { Route as SecBAboutRouteImport } from './routes/sec-b.about' +import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' +import { Route as SecCIndexRouteImport } from './routes/sec-c.index' +import { Route as SecCIdRouteImport } from './routes/sec-c.$id' +import { Route as SecCAboutRouteImport } from './routes/sec-c.about' +import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' +import { Route as SecDIndexRouteImport } from './routes/sec-d.index' +import { Route as SecDIdRouteImport } from './routes/sec-d.$id' +import { Route as SecDAboutRouteImport } from './routes/sec-d.about' +import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' +import { Route as SecEIndexRouteImport } from './routes/sec-e.index' +import { Route as SecEIdRouteImport } from './routes/sec-e.$id' +import { Route as SecEAboutRouteImport } from './routes/sec-e.about' +import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' +import { Route as SecFIndexRouteImport } from './routes/sec-f.index' +import { Route as SecFIdRouteImport } from './routes/sec-f.$id' +import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecFSettingsRouteImport } from './routes/sec-f.settings' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const SecARoute = SecARouteImport.update({ + id: '/sec-a', + path: '/sec-a', + getParentRoute: () => rootRouteImport, +} as any) +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', + getParentRoute: () => rootRouteImport, +} as any) +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', + getParentRoute: () => rootRouteImport, +} as any) +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', + getParentRoute: () => rootRouteImport, +} as any) +const SecERoute = SecERouteImport.update({ + id: '/sec-e', + path: '/sec-e', + getParentRoute: () => rootRouteImport, +} as any) +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, +} as any) +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, +} as any) +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, +} as any) +const ReleaseVChar123versionChar125Route = + ReleaseVChar123versionChar125RouteImport.update({ + id: '/release/v{$version}', + path: '/release/v{$version}', + getParentRoute: () => rootRouteImport, + } as any) +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, +} as any) +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, +} as any) +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, +} as any) +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, +} as any) +const SecBIndexRoute = SecBIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecBRoute, +} as any) +const SecBIdRoute = SecBIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecBRoute, +} as any) +const SecBAboutRoute = SecBAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecBRoute, +} as any) +const SecBSettingsRoute = SecBSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecBRoute, +} as any) +const SecCIndexRoute = SecCIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecCRoute, +} as any) +const SecCIdRoute = SecCIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecCRoute, +} as any) +const SecCAboutRoute = SecCAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecCRoute, +} as any) +const SecCSettingsRoute = SecCSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecCRoute, +} as any) +const SecDIndexRoute = SecDIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecDRoute, +} as any) +const SecDIdRoute = SecDIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecDRoute, +} as any) +const SecDAboutRoute = SecDAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecDRoute, +} as any) +const SecDSettingsRoute = SecDSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecDRoute, +} as any) +const SecEIndexRoute = SecEIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecERoute, +} as any) +const SecEIdRoute = SecEIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecERoute, +} as any) +const SecEAboutRoute = SecEAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecERoute, +} as any) +const SecESettingsRoute = SecESettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecERoute, +} as any) +const SecFIndexRoute = SecFIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecFRoute, +} as any) +const SecFIdRoute = SecFIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecFRoute, +} as any) +const SecFAboutRoute = SecFAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecFRoute, +} as any) +const SecFSettingsRoute = SecFSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecFRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/sec-a': typeof SecARouteWithChildren + '/sec-b': typeof SecBRouteWithChildren + '/sec-c': typeof SecCRouteWithChildren + '/sec-d': typeof SecDRouteWithChildren + '/sec-e': typeof SecERouteWithChildren + '/sec-f': typeof SecFRouteWithChildren + '/pricing': typeof marketingPricingRoute + '/promo': typeof marketingPromoRoute + '/alpha': typeof LayoutAlphaRoute + '/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a/': typeof SecAIndexRoute + '/sec-b/': typeof SecBIndexRoute + '/sec-c/': typeof SecCIndexRoute + '/sec-d/': typeof SecDIndexRoute + '/sec-e/': typeof SecEIndexRoute + '/sec-f/': typeof SecFIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/pricing': typeof marketingPricingRoute + '/promo': typeof marketingPromoRoute + '/alpha': typeof LayoutAlphaRoute + '/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a': typeof SecAIndexRoute + '/sec-b': typeof SecBIndexRoute + '/sec-c': typeof SecCIndexRoute + '/sec-d': typeof SecDIndexRoute + '/sec-e': typeof SecEIndexRoute + '/sec-f': typeof SecFIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/_layout': typeof LayoutRouteWithChildren + '/sec-a': typeof SecARouteWithChildren + '/sec-b': typeof SecBRouteWithChildren + '/sec-c': typeof SecCRouteWithChildren + '/sec-d': typeof SecDRouteWithChildren + '/sec-e': typeof SecERouteWithChildren + '/sec-f': typeof SecFRouteWithChildren + '/(marketing)/pricing': typeof marketingPricingRoute + '/(marketing)/promo': typeof marketingPromoRoute + '/_layout/alpha': typeof LayoutAlphaRoute + '/_layout/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a/': typeof SecAIndexRoute + '/sec-b/': typeof SecBIndexRoute + '/sec-c/': typeof SecCIndexRoute + '/sec-d/': typeof SecDIndexRoute + '/sec-e/': typeof SecEIndexRoute + '/sec-f/': typeof SecFIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + | '/pricing' + | '/promo' + | '/alpha' + | '/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a/' + | '/sec-b/' + | '/sec-c/' + | '/sec-d/' + | '/sec-e/' + | '/sec-f/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/pricing' + | '/promo' + | '/alpha' + | '/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + id: + | '__root__' + | '/' + | '/_layout' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + | '/(marketing)/pricing' + | '/(marketing)/promo' + | '/_layout/alpha' + | '/_layout/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a/' + | '/sec-b/' + | '/sec-c/' + | '/sec-d/' + | '/sec-e/' + | '/sec-f/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LayoutRoute: typeof LayoutRouteWithChildren + SecARoute: typeof SecARouteWithChildren + SecBRoute: typeof SecBRouteWithChildren + SecCRoute: typeof SecCRouteWithChildren + SecDRoute: typeof SecDRouteWithChildren + SecERoute: typeof SecERouteWithChildren + SecFRoute: typeof SecFRouteWithChildren + marketingPricingRoute: typeof marketingPricingRoute + marketingPromoRoute: typeof marketingPromoRoute + FilesSplatRoute: typeof FilesSplatRoute + ReleaseVChar123versionChar125Route: typeof ReleaseVChar123versionChar125Route +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport + parentRoute: typeof rootRouteImport + } + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-e': { + id: '/sec-e' + path: '/sec-e' + fullPath: '/sec-e' + preLoaderRoute: typeof SecERouteImport + parentRoute: typeof rootRouteImport + } + '/sec-f': { + id: '/sec-f' + path: '/sec-f' + fullPath: '/sec-f' + preLoaderRoute: typeof SecFRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/pricing': { + id: '/(marketing)/pricing' + path: '/pricing' + fullPath: '/pricing' + preLoaderRoute: typeof marketingPricingRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/promo': { + id: '/(marketing)/promo' + path: '/promo' + fullPath: '/promo' + preLoaderRoute: typeof marketingPromoRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/alpha': { + id: '/_layout/alpha' + path: '/alpha' + fullPath: '/alpha' + preLoaderRoute: typeof LayoutAlphaRouteImport + parentRoute: typeof LayoutRoute + } + '/_layout/beta': { + id: '/_layout/beta' + path: '/beta' + fullPath: '/beta' + preLoaderRoute: typeof LayoutBetaRouteImport + parentRoute: typeof LayoutRoute + } + '/files/$': { + id: '/files/$' + path: '/files/$' + fullPath: '/files/$' + preLoaderRoute: typeof FilesSplatRouteImport + parentRoute: typeof rootRouteImport + } + '/release/v{$version}': { + id: '/release/v{$version}' + path: '/release/v{$version}' + fullPath: '/release/v{$version}' + preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + parentRoute: typeof rootRouteImport + } + '/sec-a/': { + id: '/sec-a/' + path: '/' + fullPath: '/sec-a/' + preLoaderRoute: typeof SecAIndexRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/$id': { + id: '/sec-a/$id' + path: '/$id' + fullPath: '/sec-a/$id' + preLoaderRoute: typeof SecAIdRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute + } + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/settings': { + id: '/sec-b/settings' + path: '/settings' + fullPath: '/sec-b/settings' + preLoaderRoute: typeof SecBSettingsRouteImport + parentRoute: typeof SecBRoute + } + '/sec-c/': { + id: '/sec-c/' + path: '/' + fullPath: '/sec-c/' + preLoaderRoute: typeof SecCIndexRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/$id': { + id: '/sec-c/$id' + path: '/$id' + fullPath: '/sec-c/$id' + preLoaderRoute: typeof SecCIdRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/about': { + id: '/sec-c/about' + path: '/about' + fullPath: '/sec-c/about' + preLoaderRoute: typeof SecCAboutRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/settings': { + id: '/sec-c/settings' + path: '/settings' + fullPath: '/sec-c/settings' + preLoaderRoute: typeof SecCSettingsRouteImport + parentRoute: typeof SecCRoute + } + '/sec-d/': { + id: '/sec-d/' + path: '/' + fullPath: '/sec-d/' + preLoaderRoute: typeof SecDIndexRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/$id': { + id: '/sec-d/$id' + path: '/$id' + fullPath: '/sec-d/$id' + preLoaderRoute: typeof SecDIdRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/about': { + id: '/sec-d/about' + path: '/about' + fullPath: '/sec-d/about' + preLoaderRoute: typeof SecDAboutRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/settings': { + id: '/sec-d/settings' + path: '/settings' + fullPath: '/sec-d/settings' + preLoaderRoute: typeof SecDSettingsRouteImport + parentRoute: typeof SecDRoute + } + '/sec-e/': { + id: '/sec-e/' + path: '/' + fullPath: '/sec-e/' + preLoaderRoute: typeof SecEIndexRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/$id': { + id: '/sec-e/$id' + path: '/$id' + fullPath: '/sec-e/$id' + preLoaderRoute: typeof SecEIdRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/about': { + id: '/sec-e/about' + path: '/about' + fullPath: '/sec-e/about' + preLoaderRoute: typeof SecEAboutRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/settings': { + id: '/sec-e/settings' + path: '/settings' + fullPath: '/sec-e/settings' + preLoaderRoute: typeof SecESettingsRouteImport + parentRoute: typeof SecERoute + } + '/sec-f/': { + id: '/sec-f/' + path: '/' + fullPath: '/sec-f/' + preLoaderRoute: typeof SecFIndexRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/$id': { + id: '/sec-f/$id' + path: '/$id' + fullPath: '/sec-f/$id' + preLoaderRoute: typeof SecFIdRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/about': { + id: '/sec-f/about' + path: '/about' + fullPath: '/sec-f/about' + preLoaderRoute: typeof SecFAboutRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/settings': { + id: '/sec-f/settings' + path: '/settings' + fullPath: '/sec-f/settings' + preLoaderRoute: typeof SecFSettingsRouteImport + parentRoute: typeof SecFRoute + } + } +} + +interface LayoutRouteChildren { + LayoutAlphaRoute: typeof LayoutAlphaRoute + LayoutBetaRoute: typeof LayoutBetaRoute +} + +const LayoutRouteChildren: LayoutRouteChildren = { + LayoutAlphaRoute: LayoutAlphaRoute, + LayoutBetaRoute: LayoutBetaRoute, +} + +const LayoutRouteWithChildren = + LayoutRoute._addFileChildren(LayoutRouteChildren) + +interface SecARouteChildren { + SecAIdRoute: typeof SecAIdRoute + SecAAboutRoute: typeof SecAAboutRoute + SecASettingsRoute: typeof SecASettingsRoute + SecAIndexRoute: typeof SecAIndexRoute +} + +const SecARouteChildren: SecARouteChildren = { + SecAIdRoute: SecAIdRoute, + SecAAboutRoute: SecAAboutRoute, + SecASettingsRoute: SecASettingsRoute, + SecAIndexRoute: SecAIndexRoute, +} + +const SecARouteWithChildren = SecARoute._addFileChildren(SecARouteChildren) + +interface SecBRouteChildren { + SecBIdRoute: typeof SecBIdRoute + SecBAboutRoute: typeof SecBAboutRoute + SecBSettingsRoute: typeof SecBSettingsRoute + SecBIndexRoute: typeof SecBIndexRoute +} + +const SecBRouteChildren: SecBRouteChildren = { + SecBIdRoute: SecBIdRoute, + SecBAboutRoute: SecBAboutRoute, + SecBSettingsRoute: SecBSettingsRoute, + SecBIndexRoute: SecBIndexRoute, +} + +const SecBRouteWithChildren = SecBRoute._addFileChildren(SecBRouteChildren) + +interface SecCRouteChildren { + SecCIdRoute: typeof SecCIdRoute + SecCAboutRoute: typeof SecCAboutRoute + SecCSettingsRoute: typeof SecCSettingsRoute + SecCIndexRoute: typeof SecCIndexRoute +} + +const SecCRouteChildren: SecCRouteChildren = { + SecCIdRoute: SecCIdRoute, + SecCAboutRoute: SecCAboutRoute, + SecCSettingsRoute: SecCSettingsRoute, + SecCIndexRoute: SecCIndexRoute, +} + +const SecCRouteWithChildren = SecCRoute._addFileChildren(SecCRouteChildren) + +interface SecDRouteChildren { + SecDIdRoute: typeof SecDIdRoute + SecDAboutRoute: typeof SecDAboutRoute + SecDSettingsRoute: typeof SecDSettingsRoute + SecDIndexRoute: typeof SecDIndexRoute +} + +const SecDRouteChildren: SecDRouteChildren = { + SecDIdRoute: SecDIdRoute, + SecDAboutRoute: SecDAboutRoute, + SecDSettingsRoute: SecDSettingsRoute, + SecDIndexRoute: SecDIndexRoute, +} + +const SecDRouteWithChildren = SecDRoute._addFileChildren(SecDRouteChildren) + +interface SecERouteChildren { + SecEIdRoute: typeof SecEIdRoute + SecEAboutRoute: typeof SecEAboutRoute + SecESettingsRoute: typeof SecESettingsRoute + SecEIndexRoute: typeof SecEIndexRoute +} + +const SecERouteChildren: SecERouteChildren = { + SecEIdRoute: SecEIdRoute, + SecEAboutRoute: SecEAboutRoute, + SecESettingsRoute: SecESettingsRoute, + SecEIndexRoute: SecEIndexRoute, +} + +const SecERouteWithChildren = SecERoute._addFileChildren(SecERouteChildren) + +interface SecFRouteChildren { + SecFIdRoute: typeof SecFIdRoute + SecFAboutRoute: typeof SecFAboutRoute + SecFSettingsRoute: typeof SecFSettingsRoute + SecFIndexRoute: typeof SecFIndexRoute +} + +const SecFRouteChildren: SecFRouteChildren = { + SecFIdRoute: SecFIdRoute, + SecFAboutRoute: SecFAboutRoute, + SecFSettingsRoute: SecFSettingsRoute, + SecFIndexRoute: SecFIndexRoute, +} + +const SecFRouteWithChildren = SecFRoute._addFileChildren(SecFRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LayoutRoute: LayoutRouteWithChildren, + SecARoute: SecARouteWithChildren, + SecBRoute: SecBRouteWithChildren, + SecCRoute: SecCRouteWithChildren, + SecDRoute: SecDRouteWithChildren, + SecERoute: SecERouteWithChildren, + SecFRoute: SecFRouteWithChildren, + marketingPricingRoute: marketingPricingRoute, + marketingPromoRoute: marketingPromoRoute, + FilesSplatRoute: FilesSplatRoute, + ReleaseVChar123versionChar125Route: ReleaseVChar123versionChar125Route, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/pricing.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/pricing.tsx new file mode 100644 index 0000000000..0965507de6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/pricing.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/(marketing)/pricing')({ + component: Page, +}) + +function Page() { + return
pricing
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/promo.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/promo.tsx new file mode 100644 index 0000000000..220bd06a68 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/promo.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/(marketing)/promo')({ + component: Page, +}) + +function Page() { + return
promo
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..a4e4113d9a --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/__root.tsx @@ -0,0 +1,58 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.alpha.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.alpha.tsx new file mode 100644 index 0000000000..234b8488a9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.alpha.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/_layout/alpha')({ + component: Page, +}) + +function Page() { + return
alpha
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.beta.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.beta.tsx new file mode 100644 index 0000000000..39bc716efa --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.beta.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/_layout/beta')({ + component: Page, +}) + +function Page() { + return
beta
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.tsx new file mode 100644 index 0000000000..f1e499d3b3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/_layout')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/files.$.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/files.$.tsx new file mode 100644 index 0000000000..47b1a5eea9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/files.$.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/files/$')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`files:${params()._splat}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/index.tsx new file mode 100644 index 0000000000..25b1c03c1a --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: Page, +}) + +function Page() { + return
home
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/release.v{$version}.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/release.v{$version}.tsx new file mode 100644 index 0000000000..0dbcee35ca --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/release.v{$version}.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/release/v{$version}')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`release:${params().version}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.$id.tsx new file mode 100644 index 0000000000..18731a2844 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-a/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-a:${params().id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.about.tsx new file mode 100644 index 0000000000..1699360a1c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-a/about')({ + component: Page, +}) + +function Page() { + return
sec-a:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.index.tsx new file mode 100644 index 0000000000..e71e525d07 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-a/')({ + component: Page, +}) + +function Page() { + return
sec-a:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.settings.tsx new file mode 100644 index 0000000000..49d470190e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-a/settings')({ + component: Page, +}) + +function Page() { + return
sec-a:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.tsx new file mode 100644 index 0000000000..2861169fb9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-a')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.$id.tsx new file mode 100644 index 0000000000..86fe71d7c0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-b/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-b:${params().id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.about.tsx new file mode 100644 index 0000000000..586b829cd0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-b/about')({ + component: Page, +}) + +function Page() { + return
sec-b:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.index.tsx new file mode 100644 index 0000000000..7098416658 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-b/')({ + component: Page, +}) + +function Page() { + return
sec-b:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.settings.tsx new file mode 100644 index 0000000000..c2e0f47650 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-b/settings')({ + component: Page, +}) + +function Page() { + return
sec-b:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.tsx new file mode 100644 index 0000000000..f2905da9ca --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-b')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.$id.tsx new file mode 100644 index 0000000000..3e07e8033a --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-c/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-c:${params().id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.about.tsx new file mode 100644 index 0000000000..86ed5043a3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-c/about')({ + component: Page, +}) + +function Page() { + return
sec-c:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.index.tsx new file mode 100644 index 0000000000..aa9ed2dc6c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-c/')({ + component: Page, +}) + +function Page() { + return
sec-c:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.settings.tsx new file mode 100644 index 0000000000..d0dd3e952c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-c/settings')({ + component: Page, +}) + +function Page() { + return
sec-c:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.tsx new file mode 100644 index 0000000000..fa53825238 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-c')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.$id.tsx new file mode 100644 index 0000000000..3722012d7c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-d/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-d:${params().id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.about.tsx new file mode 100644 index 0000000000..860d2b9e5b --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-d/about')({ + component: Page, +}) + +function Page() { + return
sec-d:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.index.tsx new file mode 100644 index 0000000000..ec7b8eaf2c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-d/')({ + component: Page, +}) + +function Page() { + return
sec-d:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.settings.tsx new file mode 100644 index 0000000000..d83e3885fd --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-d/settings')({ + component: Page, +}) + +function Page() { + return
sec-d:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.tsx new file mode 100644 index 0000000000..e71391e2a3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-d')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.$id.tsx new file mode 100644 index 0000000000..e58d9d77ac --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-e/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-e:${params().id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.about.tsx new file mode 100644 index 0000000000..3ef4d2c763 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-e/about')({ + component: Page, +}) + +function Page() { + return
sec-e:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.index.tsx new file mode 100644 index 0000000000..88bf7ca271 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-e/')({ + component: Page, +}) + +function Page() { + return
sec-e:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.settings.tsx new file mode 100644 index 0000000000..8a9945926d --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-e/settings')({ + component: Page, +}) + +function Page() { + return
sec-e:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.tsx new file mode 100644 index 0000000000..8b5ef24519 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-e')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.$id.tsx new file mode 100644 index 0000000000..2b81ef96ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-f/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-f:${params().id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.about.tsx new file mode 100644 index 0000000000..1c4e3a5474 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-f/about')({ + component: Page, +}) + +function Page() { + return
sec-f:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.index.tsx new file mode 100644 index 0000000000..65803ee848 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-f/')({ + component: Page, +}) + +function Page() { + return
sec-f:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.settings.tsx new file mode 100644 index 0000000000..5761138262 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-f/settings')({ + component: Page, +}) + +function Page() { + return
sec-f:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.tsx new file mode 100644 index 0000000000..c7f25eecdd --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-f')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/tsconfig.json b/benchmarks/client-nav/scenarios/route-tree-scale/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts new file mode 100644 index 0000000000..542ede131b --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts @@ -0,0 +1,53 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'solid', + // Real file-based apps code-split by default; this scenario keeps it on + // so navigations also exercise lazy route-chunk resolution. + autoCodeSplitting: true, + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav route-tree-scale (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/project.json b/benchmarks/client-nav/scenarios/route-tree-scale/vue/project.json new file mode 100644 index 0000000000..f613070038 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-route-tree-scale-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/route-tree-scale/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/setup.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/setup.ts new file mode 100644 index 0000000000..97b74b3892 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts new file mode 100644 index 0000000000..331e8e008f --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-route-tree-scale', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-route-tree-scale navigation loop (vue)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx @@ -0,0 +1,41 @@ +import type { RouterHistory } from '@tanstack/history' +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..a12f981bb4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts @@ -0,0 +1,881 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as SecARouteImport } from './routes/sec-a' +import { Route as SecBRouteImport } from './routes/sec-b' +import { Route as SecCRouteImport } from './routes/sec-c' +import { Route as SecDRouteImport } from './routes/sec-d' +import { Route as SecERouteImport } from './routes/sec-e' +import { Route as SecFRouteImport } from './routes/sec-f' +import { Route as marketingPricingRouteImport } from './routes/(marketing)/pricing' +import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' +import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' +import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' +import { Route as FilesSplatRouteImport } from './routes/files.$' +import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' +import { Route as SecAIndexRouteImport } from './routes/sec-a.index' +import { Route as SecAIdRouteImport } from './routes/sec-a.$id' +import { Route as SecAAboutRouteImport } from './routes/sec-a.about' +import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' +import { Route as SecBIndexRouteImport } from './routes/sec-b.index' +import { Route as SecBIdRouteImport } from './routes/sec-b.$id' +import { Route as SecBAboutRouteImport } from './routes/sec-b.about' +import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' +import { Route as SecCIndexRouteImport } from './routes/sec-c.index' +import { Route as SecCIdRouteImport } from './routes/sec-c.$id' +import { Route as SecCAboutRouteImport } from './routes/sec-c.about' +import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' +import { Route as SecDIndexRouteImport } from './routes/sec-d.index' +import { Route as SecDIdRouteImport } from './routes/sec-d.$id' +import { Route as SecDAboutRouteImport } from './routes/sec-d.about' +import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' +import { Route as SecEIndexRouteImport } from './routes/sec-e.index' +import { Route as SecEIdRouteImport } from './routes/sec-e.$id' +import { Route as SecEAboutRouteImport } from './routes/sec-e.about' +import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' +import { Route as SecFIndexRouteImport } from './routes/sec-f.index' +import { Route as SecFIdRouteImport } from './routes/sec-f.$id' +import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecFSettingsRouteImport } from './routes/sec-f.settings' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const SecARoute = SecARouteImport.update({ + id: '/sec-a', + path: '/sec-a', + getParentRoute: () => rootRouteImport, +} as any) +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', + getParentRoute: () => rootRouteImport, +} as any) +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', + getParentRoute: () => rootRouteImport, +} as any) +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', + getParentRoute: () => rootRouteImport, +} as any) +const SecERoute = SecERouteImport.update({ + id: '/sec-e', + path: '/sec-e', + getParentRoute: () => rootRouteImport, +} as any) +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, +} as any) +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, +} as any) +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, +} as any) +const ReleaseVChar123versionChar125Route = + ReleaseVChar123versionChar125RouteImport.update({ + id: '/release/v{$version}', + path: '/release/v{$version}', + getParentRoute: () => rootRouteImport, + } as any) +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, +} as any) +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, +} as any) +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, +} as any) +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, +} as any) +const SecBIndexRoute = SecBIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecBRoute, +} as any) +const SecBIdRoute = SecBIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecBRoute, +} as any) +const SecBAboutRoute = SecBAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecBRoute, +} as any) +const SecBSettingsRoute = SecBSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecBRoute, +} as any) +const SecCIndexRoute = SecCIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecCRoute, +} as any) +const SecCIdRoute = SecCIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecCRoute, +} as any) +const SecCAboutRoute = SecCAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecCRoute, +} as any) +const SecCSettingsRoute = SecCSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecCRoute, +} as any) +const SecDIndexRoute = SecDIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecDRoute, +} as any) +const SecDIdRoute = SecDIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecDRoute, +} as any) +const SecDAboutRoute = SecDAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecDRoute, +} as any) +const SecDSettingsRoute = SecDSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecDRoute, +} as any) +const SecEIndexRoute = SecEIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecERoute, +} as any) +const SecEIdRoute = SecEIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecERoute, +} as any) +const SecEAboutRoute = SecEAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecERoute, +} as any) +const SecESettingsRoute = SecESettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecERoute, +} as any) +const SecFIndexRoute = SecFIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecFRoute, +} as any) +const SecFIdRoute = SecFIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecFRoute, +} as any) +const SecFAboutRoute = SecFAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecFRoute, +} as any) +const SecFSettingsRoute = SecFSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecFRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/sec-a': typeof SecARouteWithChildren + '/sec-b': typeof SecBRouteWithChildren + '/sec-c': typeof SecCRouteWithChildren + '/sec-d': typeof SecDRouteWithChildren + '/sec-e': typeof SecERouteWithChildren + '/sec-f': typeof SecFRouteWithChildren + '/pricing': typeof marketingPricingRoute + '/promo': typeof marketingPromoRoute + '/alpha': typeof LayoutAlphaRoute + '/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a/': typeof SecAIndexRoute + '/sec-b/': typeof SecBIndexRoute + '/sec-c/': typeof SecCIndexRoute + '/sec-d/': typeof SecDIndexRoute + '/sec-e/': typeof SecEIndexRoute + '/sec-f/': typeof SecFIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/pricing': typeof marketingPricingRoute + '/promo': typeof marketingPromoRoute + '/alpha': typeof LayoutAlphaRoute + '/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a': typeof SecAIndexRoute + '/sec-b': typeof SecBIndexRoute + '/sec-c': typeof SecCIndexRoute + '/sec-d': typeof SecDIndexRoute + '/sec-e': typeof SecEIndexRoute + '/sec-f': typeof SecFIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/_layout': typeof LayoutRouteWithChildren + '/sec-a': typeof SecARouteWithChildren + '/sec-b': typeof SecBRouteWithChildren + '/sec-c': typeof SecCRouteWithChildren + '/sec-d': typeof SecDRouteWithChildren + '/sec-e': typeof SecERouteWithChildren + '/sec-f': typeof SecFRouteWithChildren + '/(marketing)/pricing': typeof marketingPricingRoute + '/(marketing)/promo': typeof marketingPromoRoute + '/_layout/alpha': typeof LayoutAlphaRoute + '/_layout/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a/': typeof SecAIndexRoute + '/sec-b/': typeof SecBIndexRoute + '/sec-c/': typeof SecCIndexRoute + '/sec-d/': typeof SecDIndexRoute + '/sec-e/': typeof SecEIndexRoute + '/sec-f/': typeof SecFIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + | '/pricing' + | '/promo' + | '/alpha' + | '/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a/' + | '/sec-b/' + | '/sec-c/' + | '/sec-d/' + | '/sec-e/' + | '/sec-f/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/pricing' + | '/promo' + | '/alpha' + | '/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + id: + | '__root__' + | '/' + | '/_layout' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + | '/(marketing)/pricing' + | '/(marketing)/promo' + | '/_layout/alpha' + | '/_layout/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a/' + | '/sec-b/' + | '/sec-c/' + | '/sec-d/' + | '/sec-e/' + | '/sec-f/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LayoutRoute: typeof LayoutRouteWithChildren + SecARoute: typeof SecARouteWithChildren + SecBRoute: typeof SecBRouteWithChildren + SecCRoute: typeof SecCRouteWithChildren + SecDRoute: typeof SecDRouteWithChildren + SecERoute: typeof SecERouteWithChildren + SecFRoute: typeof SecFRouteWithChildren + marketingPricingRoute: typeof marketingPricingRoute + marketingPromoRoute: typeof marketingPromoRoute + FilesSplatRoute: typeof FilesSplatRoute + ReleaseVChar123versionChar125Route: typeof ReleaseVChar123versionChar125Route +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport + parentRoute: typeof rootRouteImport + } + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-e': { + id: '/sec-e' + path: '/sec-e' + fullPath: '/sec-e' + preLoaderRoute: typeof SecERouteImport + parentRoute: typeof rootRouteImport + } + '/sec-f': { + id: '/sec-f' + path: '/sec-f' + fullPath: '/sec-f' + preLoaderRoute: typeof SecFRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/pricing': { + id: '/(marketing)/pricing' + path: '/pricing' + fullPath: '/pricing' + preLoaderRoute: typeof marketingPricingRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/promo': { + id: '/(marketing)/promo' + path: '/promo' + fullPath: '/promo' + preLoaderRoute: typeof marketingPromoRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/alpha': { + id: '/_layout/alpha' + path: '/alpha' + fullPath: '/alpha' + preLoaderRoute: typeof LayoutAlphaRouteImport + parentRoute: typeof LayoutRoute + } + '/_layout/beta': { + id: '/_layout/beta' + path: '/beta' + fullPath: '/beta' + preLoaderRoute: typeof LayoutBetaRouteImport + parentRoute: typeof LayoutRoute + } + '/files/$': { + id: '/files/$' + path: '/files/$' + fullPath: '/files/$' + preLoaderRoute: typeof FilesSplatRouteImport + parentRoute: typeof rootRouteImport + } + '/release/v{$version}': { + id: '/release/v{$version}' + path: '/release/v{$version}' + fullPath: '/release/v{$version}' + preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + parentRoute: typeof rootRouteImport + } + '/sec-a/': { + id: '/sec-a/' + path: '/' + fullPath: '/sec-a/' + preLoaderRoute: typeof SecAIndexRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/$id': { + id: '/sec-a/$id' + path: '/$id' + fullPath: '/sec-a/$id' + preLoaderRoute: typeof SecAIdRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute + } + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/settings': { + id: '/sec-b/settings' + path: '/settings' + fullPath: '/sec-b/settings' + preLoaderRoute: typeof SecBSettingsRouteImport + parentRoute: typeof SecBRoute + } + '/sec-c/': { + id: '/sec-c/' + path: '/' + fullPath: '/sec-c/' + preLoaderRoute: typeof SecCIndexRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/$id': { + id: '/sec-c/$id' + path: '/$id' + fullPath: '/sec-c/$id' + preLoaderRoute: typeof SecCIdRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/about': { + id: '/sec-c/about' + path: '/about' + fullPath: '/sec-c/about' + preLoaderRoute: typeof SecCAboutRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/settings': { + id: '/sec-c/settings' + path: '/settings' + fullPath: '/sec-c/settings' + preLoaderRoute: typeof SecCSettingsRouteImport + parentRoute: typeof SecCRoute + } + '/sec-d/': { + id: '/sec-d/' + path: '/' + fullPath: '/sec-d/' + preLoaderRoute: typeof SecDIndexRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/$id': { + id: '/sec-d/$id' + path: '/$id' + fullPath: '/sec-d/$id' + preLoaderRoute: typeof SecDIdRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/about': { + id: '/sec-d/about' + path: '/about' + fullPath: '/sec-d/about' + preLoaderRoute: typeof SecDAboutRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/settings': { + id: '/sec-d/settings' + path: '/settings' + fullPath: '/sec-d/settings' + preLoaderRoute: typeof SecDSettingsRouteImport + parentRoute: typeof SecDRoute + } + '/sec-e/': { + id: '/sec-e/' + path: '/' + fullPath: '/sec-e/' + preLoaderRoute: typeof SecEIndexRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/$id': { + id: '/sec-e/$id' + path: '/$id' + fullPath: '/sec-e/$id' + preLoaderRoute: typeof SecEIdRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/about': { + id: '/sec-e/about' + path: '/about' + fullPath: '/sec-e/about' + preLoaderRoute: typeof SecEAboutRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/settings': { + id: '/sec-e/settings' + path: '/settings' + fullPath: '/sec-e/settings' + preLoaderRoute: typeof SecESettingsRouteImport + parentRoute: typeof SecERoute + } + '/sec-f/': { + id: '/sec-f/' + path: '/' + fullPath: '/sec-f/' + preLoaderRoute: typeof SecFIndexRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/$id': { + id: '/sec-f/$id' + path: '/$id' + fullPath: '/sec-f/$id' + preLoaderRoute: typeof SecFIdRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/about': { + id: '/sec-f/about' + path: '/about' + fullPath: '/sec-f/about' + preLoaderRoute: typeof SecFAboutRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/settings': { + id: '/sec-f/settings' + path: '/settings' + fullPath: '/sec-f/settings' + preLoaderRoute: typeof SecFSettingsRouteImport + parentRoute: typeof SecFRoute + } + } +} + +interface LayoutRouteChildren { + LayoutAlphaRoute: typeof LayoutAlphaRoute + LayoutBetaRoute: typeof LayoutBetaRoute +} + +const LayoutRouteChildren: LayoutRouteChildren = { + LayoutAlphaRoute: LayoutAlphaRoute, + LayoutBetaRoute: LayoutBetaRoute, +} + +const LayoutRouteWithChildren = + LayoutRoute._addFileChildren(LayoutRouteChildren) + +interface SecARouteChildren { + SecAIdRoute: typeof SecAIdRoute + SecAAboutRoute: typeof SecAAboutRoute + SecASettingsRoute: typeof SecASettingsRoute + SecAIndexRoute: typeof SecAIndexRoute +} + +const SecARouteChildren: SecARouteChildren = { + SecAIdRoute: SecAIdRoute, + SecAAboutRoute: SecAAboutRoute, + SecASettingsRoute: SecASettingsRoute, + SecAIndexRoute: SecAIndexRoute, +} + +const SecARouteWithChildren = SecARoute._addFileChildren(SecARouteChildren) + +interface SecBRouteChildren { + SecBIdRoute: typeof SecBIdRoute + SecBAboutRoute: typeof SecBAboutRoute + SecBSettingsRoute: typeof SecBSettingsRoute + SecBIndexRoute: typeof SecBIndexRoute +} + +const SecBRouteChildren: SecBRouteChildren = { + SecBIdRoute: SecBIdRoute, + SecBAboutRoute: SecBAboutRoute, + SecBSettingsRoute: SecBSettingsRoute, + SecBIndexRoute: SecBIndexRoute, +} + +const SecBRouteWithChildren = SecBRoute._addFileChildren(SecBRouteChildren) + +interface SecCRouteChildren { + SecCIdRoute: typeof SecCIdRoute + SecCAboutRoute: typeof SecCAboutRoute + SecCSettingsRoute: typeof SecCSettingsRoute + SecCIndexRoute: typeof SecCIndexRoute +} + +const SecCRouteChildren: SecCRouteChildren = { + SecCIdRoute: SecCIdRoute, + SecCAboutRoute: SecCAboutRoute, + SecCSettingsRoute: SecCSettingsRoute, + SecCIndexRoute: SecCIndexRoute, +} + +const SecCRouteWithChildren = SecCRoute._addFileChildren(SecCRouteChildren) + +interface SecDRouteChildren { + SecDIdRoute: typeof SecDIdRoute + SecDAboutRoute: typeof SecDAboutRoute + SecDSettingsRoute: typeof SecDSettingsRoute + SecDIndexRoute: typeof SecDIndexRoute +} + +const SecDRouteChildren: SecDRouteChildren = { + SecDIdRoute: SecDIdRoute, + SecDAboutRoute: SecDAboutRoute, + SecDSettingsRoute: SecDSettingsRoute, + SecDIndexRoute: SecDIndexRoute, +} + +const SecDRouteWithChildren = SecDRoute._addFileChildren(SecDRouteChildren) + +interface SecERouteChildren { + SecEIdRoute: typeof SecEIdRoute + SecEAboutRoute: typeof SecEAboutRoute + SecESettingsRoute: typeof SecESettingsRoute + SecEIndexRoute: typeof SecEIndexRoute +} + +const SecERouteChildren: SecERouteChildren = { + SecEIdRoute: SecEIdRoute, + SecEAboutRoute: SecEAboutRoute, + SecESettingsRoute: SecESettingsRoute, + SecEIndexRoute: SecEIndexRoute, +} + +const SecERouteWithChildren = SecERoute._addFileChildren(SecERouteChildren) + +interface SecFRouteChildren { + SecFIdRoute: typeof SecFIdRoute + SecFAboutRoute: typeof SecFAboutRoute + SecFSettingsRoute: typeof SecFSettingsRoute + SecFIndexRoute: typeof SecFIndexRoute +} + +const SecFRouteChildren: SecFRouteChildren = { + SecFIdRoute: SecFIdRoute, + SecFAboutRoute: SecFAboutRoute, + SecFSettingsRoute: SecFSettingsRoute, + SecFIndexRoute: SecFIndexRoute, +} + +const SecFRouteWithChildren = SecFRoute._addFileChildren(SecFRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LayoutRoute: LayoutRouteWithChildren, + SecARoute: SecARouteWithChildren, + SecBRoute: SecBRouteWithChildren, + SecCRoute: SecCRouteWithChildren, + SecDRoute: SecDRouteWithChildren, + SecERoute: SecERouteWithChildren, + SecFRoute: SecFRouteWithChildren, + marketingPricingRoute: marketingPricingRoute, + marketingPromoRoute: marketingPromoRoute, + FilesSplatRoute: FilesSplatRoute, + ReleaseVChar123versionChar125Route: ReleaseVChar123versionChar125Route, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/pricing.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/pricing.tsx new file mode 100644 index 0000000000..f606c10b4b --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/pricing.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
pricing
+ }, +}) + +export const Route = createFileRoute('/(marketing)/pricing')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/promo.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/promo.tsx new file mode 100644 index 0000000000..61c3eb3ec9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/promo.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
promo
+ }, +}) + +export const Route = createFileRoute('/(marketing)/promo')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..d2e1483106 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/__root.tsx @@ -0,0 +1,61 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.alpha.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.alpha.tsx new file mode 100644 index 0000000000..ff6ad5350e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.alpha.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
alpha
+ }, +}) + +export const Route = createFileRoute('/_layout/alpha')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.beta.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.beta.tsx new file mode 100644 index 0000000000..2f7cab6c0a --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.beta.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
beta
+ }, +}) + +export const Route = createFileRoute('/_layout/beta')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.tsx new file mode 100644 index 0000000000..e8221f0f65 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/_layout')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/files.$.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/files.$.tsx new file mode 100644 index 0000000000..221fae01be --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/files.$.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`files:${params.value._splat}`}
+ ) + }, +}) + +export const Route = createFileRoute('/files/$')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/index.tsx new file mode 100644 index 0000000000..b3e94f37c4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
home
+ }, +}) + +export const Route = createFileRoute('/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/release.v{$version}.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/release.v{$version}.tsx new file mode 100644 index 0000000000..86b1a2c8f0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/release.v{$version}.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`release:${params.value.version}`}
+ ) + }, +}) + +export const Route = createFileRoute('/release/v{$version}')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.$id.tsx new file mode 100644 index 0000000000..864074940d --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.$id.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`sec-a:${params.value.id}`}
+ ) + }, +}) + +export const Route = createFileRoute('/sec-a/$id')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.about.tsx new file mode 100644 index 0000000000..715ab9548c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-a:about
+ }, +}) + +export const Route = createFileRoute('/sec-a/about')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.index.tsx new file mode 100644 index 0000000000..baef08547c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-a:index
+ }, +}) + +export const Route = createFileRoute('/sec-a/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.settings.tsx new file mode 100644 index 0000000000..9e6a56b913 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.settings.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-a:settings
+ }, +}) + +export const Route = createFileRoute('/sec-a/settings')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.tsx new file mode 100644 index 0000000000..a9fb557aea --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/sec-a')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.$id.tsx new file mode 100644 index 0000000000..9a03a8fe01 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.$id.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`sec-b:${params.value.id}`}
+ ) + }, +}) + +export const Route = createFileRoute('/sec-b/$id')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.about.tsx new file mode 100644 index 0000000000..2ef1100995 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-b:about
+ }, +}) + +export const Route = createFileRoute('/sec-b/about')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.index.tsx new file mode 100644 index 0000000000..652e5f895c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-b:index
+ }, +}) + +export const Route = createFileRoute('/sec-b/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.settings.tsx new file mode 100644 index 0000000000..e8fa36377e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.settings.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-b:settings
+ }, +}) + +export const Route = createFileRoute('/sec-b/settings')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.tsx new file mode 100644 index 0000000000..ba31612633 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/sec-b')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.$id.tsx new file mode 100644 index 0000000000..7f0407d84e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.$id.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`sec-c:${params.value.id}`}
+ ) + }, +}) + +export const Route = createFileRoute('/sec-c/$id')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.about.tsx new file mode 100644 index 0000000000..d26776d439 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-c:about
+ }, +}) + +export const Route = createFileRoute('/sec-c/about')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.index.tsx new file mode 100644 index 0000000000..1835eff9b7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-c:index
+ }, +}) + +export const Route = createFileRoute('/sec-c/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.settings.tsx new file mode 100644 index 0000000000..1bf85fd6d9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.settings.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-c:settings
+ }, +}) + +export const Route = createFileRoute('/sec-c/settings')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.tsx new file mode 100644 index 0000000000..009f814b93 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/sec-c')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.$id.tsx new file mode 100644 index 0000000000..ff5aab05e3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.$id.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`sec-d:${params.value.id}`}
+ ) + }, +}) + +export const Route = createFileRoute('/sec-d/$id')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.about.tsx new file mode 100644 index 0000000000..25a8078626 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-d:about
+ }, +}) + +export const Route = createFileRoute('/sec-d/about')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.index.tsx new file mode 100644 index 0000000000..cd9b89664a --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-d:index
+ }, +}) + +export const Route = createFileRoute('/sec-d/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.settings.tsx new file mode 100644 index 0000000000..8e4309de32 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.settings.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-d:settings
+ }, +}) + +export const Route = createFileRoute('/sec-d/settings')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.tsx new file mode 100644 index 0000000000..6b12b514da --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/sec-d')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.$id.tsx new file mode 100644 index 0000000000..4525051967 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.$id.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`sec-e:${params.value.id}`}
+ ) + }, +}) + +export const Route = createFileRoute('/sec-e/$id')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.about.tsx new file mode 100644 index 0000000000..71a32bd36b --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-e:about
+ }, +}) + +export const Route = createFileRoute('/sec-e/about')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.index.tsx new file mode 100644 index 0000000000..9b467ca53e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-e:index
+ }, +}) + +export const Route = createFileRoute('/sec-e/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.settings.tsx new file mode 100644 index 0000000000..a01066488c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.settings.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-e:settings
+ }, +}) + +export const Route = createFileRoute('/sec-e/settings')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.tsx new file mode 100644 index 0000000000..38f4da91fb --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/sec-e')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.$id.tsx new file mode 100644 index 0000000000..c740f9d223 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.$id.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`sec-f:${params.value.id}`}
+ ) + }, +}) + +export const Route = createFileRoute('/sec-f/$id')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.about.tsx new file mode 100644 index 0000000000..229dab22a2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-f:about
+ }, +}) + +export const Route = createFileRoute('/sec-f/about')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.index.tsx new file mode 100644 index 0000000000..14e3f46a13 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-f:index
+ }, +}) + +export const Route = createFileRoute('/sec-f/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.settings.tsx new file mode 100644 index 0000000000..da2c7483b9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.settings.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-f:settings
+ }, +}) + +export const Route = createFileRoute('/sec-f/settings')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.tsx new file mode 100644 index 0000000000..3b389c8144 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/sec-f')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/tsconfig.json b/benchmarks/client-nav/scenarios/route-tree-scale/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts new file mode 100644 index 0000000000..189ba1de99 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts @@ -0,0 +1,47 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + // Real file-based apps code-split by default; this scenario keeps it on + // so navigations also exercise lazy route-chunk resolution. + autoCodeSplitting: true, + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav route-tree-scale (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/search-params/react/project.json b/benchmarks/client-nav/scenarios/search-params/react/project.json new file mode 100644 index 0000000000..f2d743f5f9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-search-params-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/search-params/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/search-params/react/setup.ts b/benchmarks/client-nav/scenarios/search-params/react/setup.ts new file mode 100644 index 0000000000..130583b190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts new file mode 100644 index 0000000000..0b38f7bddb --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-search-params', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-search-params navigation loop (react)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/search-params/react/speed.flame.ts b/benchmarks/client-nav/scenarios/search-params/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx new file mode 100644 index 0000000000..b10d53554b --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx @@ -0,0 +1,38 @@ +import type { RouterHistory } from '@tanstack/history' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + defaultStructuralSharing: true, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const reactRoot = createRoot(container) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..cff9dca167 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as CatalogRouteImport } from './routes/catalog' +import { Route as ProductsRouteImport } from './routes/products' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const CatalogRoute = CatalogRouteImport.update({ + id: '/catalog', + path: '/catalog', + getParentRoute: () => rootRouteImport, +} as any) +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/catalog' | '/products' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/catalog' | '/products' + id: '__root__' | '/' | '/catalog' | '/products' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + CatalogRoute: typeof CatalogRoute + ProductsRoute: typeof ProductsRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/catalog': { + id: '/catalog' + path: '/catalog' + fullPath: '/catalog' + preLoaderRoute: typeof CatalogRouteImport + parentRoute: typeof rootRouteImport + } + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + CatalogRoute: CatalogRoute, + ProductsRoute: ProductsRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/routes/__root.tsx new file mode 100644 index 0000000000..86399d0175 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/src/routes/__root.tsx @@ -0,0 +1,116 @@ +import { + Link, + Outlet, + createRootRoute, + useSearch, +} from '@tanstack/react-router' +import { + changedCategories, + computeChecksum, + initialProductsSearch, +} from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +const rootSubscribers = Array.from({ length: 4 }, (_, index) => index) + +function RootSearchSubscriber() { + const value = useSearch({ + strict: false, + select: (search) => computeChecksum(Number(search.page ?? 0)), + }) + + void computeChecksum(value) + return null +} + +function RootComponent() { + return ( + <> + {rootSubscribers.map((index) => ( + + ))} + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/routes/catalog.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/routes/catalog.tsx new file mode 100644 index 0000000000..73f59c13b0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/src/routes/catalog.tsx @@ -0,0 +1,42 @@ +import { createFileRoute, retainSearchParams } from '@tanstack/react-router' +import type { SearchSchemaInput } from '@tanstack/react-router' +import { + catalogMarkerText, + computeChecksum, + normalizeCatalogSearch, +} from '../../../shared' + +export const Route = createFileRoute('/catalog')({ + validateSearch: (search: Record & SearchSchemaInput) => + normalizeCatalogSearch(search), + search: { + middlewares: [retainSearchParams(['perPage', 'sort'])], + }, + component: CatalogPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function ViewSubscriber() { + const value = Route.useSearch({ + select: (search) => + computeChecksum(search.view.length * 5 + search.page * 11), + }) + + void computeChecksum(value) + return null +} + +function CatalogPage() { + const search = Route.useSearch() + + return ( +
+ {subscriberIndexes.map((index) => ( + + ))} +

Catalog

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

Search Params Bench

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

Products

+
{productsMarkerText(search)}
+

{`checksum ${loaderData.checksum}`}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/search-params/react/tsconfig.json b/benchmarks/client-nav/scenarios/search-params/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts new file mode 100644 index 0000000000..0318a10815 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'react', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav search-params (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/search-params/shared.ts b/benchmarks/client-nav/scenarios/search-params/shared.ts new file mode 100644 index 0000000000..343e319ded --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/shared.ts @@ -0,0 +1,200 @@ +/** + * Shared definition of the `search-params` scenario: search schema + * normalizers, the click sequence, and per-step sanity assertions. The three + * framework apps consume these builders so the workload is identical modulo + * the rendering layer. + * + * Isolates: validateSearch execution, search middlewares + * (retainSearchParams/stripSearchParams), parse/stringify of medium-complex + * search objects, functional search updaters, structural sharing, and + * useSearch selector subscriptions. + */ + +import type { ScenarioStep } from '../harness' + +export function computeChecksum(seed: number) { + let value = Math.trunc(seed) | 0 + + for (let index = 0; index < 40; index++) { + value = (value * 1664525 + 1013904223 + index) >>> 0 + } + + return value +} + +export interface ProductsSearch { + page: number + perPage: number + sort: 'asc' | 'desc' + q: string + filters: { + categories: Array + price: { min: number; max: number } + tags: Array + } +} + +export interface CatalogSearch { + view: 'grid' | 'list' + page: number + perPage: number + sort: 'asc' | 'desc' +} + +function normalizeNumber(value: unknown, fallback: number) { + const num = Number(value) + return Number.isFinite(num) && num >= 0 ? Math.trunc(num) : fallback +} + +function normalizeString(value: unknown, fallback: string) { + return typeof value === 'string' ? value : fallback +} + +function normalizeSort(value: unknown): 'asc' | 'desc' { + return value === 'desc' ? 'desc' : 'asc' +} + +function normalizeStringArray(value: unknown): Array { + if (!Array.isArray(value)) { + return [] + } + return value.filter((entry): entry is string => typeof entry === 'string') +} + +export function normalizeProductsSearch( + search: Record, +): ProductsSearch { + const filters = + typeof search.filters === 'object' && search.filters !== null + ? (search.filters as Record) + : {} + const price = + typeof filters.price === 'object' && filters.price !== null + ? (filters.price as Record) + : {} + + return { + page: Math.max(1, normalizeNumber(search.page, 1)), + perPage: Math.max(1, normalizeNumber(search.perPage, 20)), + sort: normalizeSort(search.sort), + q: normalizeString(search.q, ''), + filters: { + categories: normalizeStringArray(filters.categories), + price: { + min: normalizeNumber(price.min, 0), + max: normalizeNumber(price.max, 1000), + }, + tags: normalizeStringArray(filters.tags), + }, + } +} + +export function normalizeCatalogSearch( + search: Record, +): CatalogSearch { + return { + view: search.view === 'list' ? 'list' : 'grid', + page: Math.max(1, normalizeNumber(search.page, 1)), + perPage: Math.max(1, normalizeNumber(search.perPage, 20)), + sort: normalizeSort(search.sort), + } +} + +export const initialProductsSearch = { + page: 2, + perPage: 50, + sort: 'desc', + q: 'gadget', + filters: { + categories: ['audio', 'video'], + price: { min: 10, max: 200 }, + tags: ['new', 'sale'], + }, +} satisfies ProductsSearch + +export const changedCategories = ['x-ray', 'yield', 'zeta'] + +export function productsMarkerText(search: ProductsSearch) { + return `${search.page}|${search.sort}|${search.filters.categories.join(',')}` +} + +export function catalogMarkerText(search: CatalogSearch) { + return `${search.view}|${search.page}|${search.perPage}|${search.sort}` +} + +export function productsLoaderChecksum(deps: { + page: number + sort: string + filters: ProductsSearch['filters'] +}) { + return computeChecksum( + deps.page * 31 + + deps.sort.length * 7 + + deps.filters.categories.join('').length * 13 + + deps.filters.tags.length * 3 + + (deps.filters.price.max - deps.filters.price.min), + ) +} + +export const steps: ReadonlyArray = [ + 'go-products', + 'products-next-page', + 'products-categories', + 'products-sort', + 'products-reset', + 'go-catalog', + 'catalog-next-page', + 'products-partial', + 'go-home', +] + +interface ExpectedState { + testId: string + text?: string +} + +const expectedStates: ReadonlyArray = [ + // Full search literal from home. + { testId: 'products-state', text: '2|desc|audio,video' }, + // Functional updater bumping the page. + { testId: 'products-state', text: '3|desc|audio,video' }, + // Functional updater replacing filters.categories. + { testId: 'products-state', text: '3|desc|x-ray,yield,zeta' }, + // Functional updater flipping sort desc -> asc. + { testId: 'products-state', text: '3|asc|x-ray,yield,zeta' }, + // Functional updater resetting page to 1 (stripSearchParams removes it). + { testId: 'products-state', text: '1|asc|x-ray,yield,zeta' }, + // search: true carries the current products search into catalog. + { testId: 'catalog-state', text: 'grid|1|50|asc' }, + // Functional updater bumping the catalog page. + { testId: 'catalog-state', text: 'grid|2|50|asc' }, + // Partial search literal; retainSearchParams fills perPage/sort from catalog. + { testId: 'products-state', text: '1|asc|' }, + { testId: 'home-state' }, +] + +export function assertStepResult(stepIndex: number, container: HTMLElement) { + const expected = expectedStates[stepIndex]! + const element = container.querySelector(`[data-testid="${expected.testId}"]`) + + if (!element) { + throw new Error( + `Expected marker "${expected.testId}" to exist after step ${stepIndex}`, + ) + } + + if (expected.text !== undefined && element.textContent !== expected.text) { + throw new Error( + `Expected marker "${expected.testId}" to read "${expected.text}" after step ${stepIndex}, received "${element.textContent}"`, + ) + } +} + +// Two laps through the 9-step sequence per benchmark iteration. +export const ticksPerIteration = 18 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/project.json b/benchmarks/client-nav/scenarios/search-params/solid/project.json new file mode 100644 index 0000000000..af48217e03 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-search-params-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/search-params/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/setup.ts b/benchmarks/client-nav/scenarios/search-params/solid/setup.ts new file mode 100644 index 0000000000..6a46971603 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts new file mode 100644 index 0000000000..caa626c596 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-search-params', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-search-params navigation loop (solid)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/search-params/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/search-params/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx new file mode 100644 index 0000000000..25071f7979 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx @@ -0,0 +1,35 @@ +import type { RouterHistory } from '@tanstack/history' +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + defaultStructuralSharing: true, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const unmount = render(() => , container) + + return { + router, + unmount, + } +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..b15beed09b --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as CatalogRouteImport } from './routes/catalog' +import { Route as ProductsRouteImport } from './routes/products' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const CatalogRoute = CatalogRouteImport.update({ + id: '/catalog', + path: '/catalog', + getParentRoute: () => rootRouteImport, +} as any) +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/catalog' | '/products' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/catalog' | '/products' + id: '__root__' | '/' | '/catalog' | '/products' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + CatalogRoute: typeof CatalogRoute + ProductsRoute: typeof ProductsRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/catalog': { + id: '/catalog' + path: '/catalog' + fullPath: '/catalog' + preLoaderRoute: typeof CatalogRouteImport + parentRoute: typeof rootRouteImport + } + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + CatalogRoute: CatalogRoute, + ProductsRoute: ProductsRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..30c042f9c5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/__root.tsx @@ -0,0 +1,120 @@ +import { createRenderEffect } from 'solid-js' +import { + Link, + Outlet, + createRootRoute, + useSearch, +} from '@tanstack/solid-router' +import { + changedCategories, + computeChecksum, + initialProductsSearch, +} from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +const rootSubscribers = Array.from({ length: 4 }, (_, index) => index) + +function PerfValue(props: { value: () => number }) { + createRenderEffect(() => { + void props.value() + }) + + return null +} + +function RootSearchSubscriber() { + const value = useSearch({ + strict: false, + select: (search) => computeChecksum(Number(search.page ?? 0)), + }) + + return computeChecksum(value())} /> +} + +function RootComponent() { + return ( + <> + {rootSubscribers.map(() => ( + + ))} + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/catalog.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/catalog.tsx new file mode 100644 index 0000000000..60cf8e7896 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/catalog.tsx @@ -0,0 +1,50 @@ +import { createRenderEffect } from 'solid-js' +import { createFileRoute, retainSearchParams } from '@tanstack/solid-router' +import type { SearchSchemaInput } from '@tanstack/solid-router' +import { + catalogMarkerText, + computeChecksum, + normalizeCatalogSearch, +} from '../../../shared' + +export const Route = createFileRoute('/catalog')({ + validateSearch: (search: Record & SearchSchemaInput) => + normalizeCatalogSearch(search), + search: { + middlewares: [retainSearchParams(['perPage', 'sort'])], + }, + component: CatalogPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function PerfValue(props: { value: () => number }) { + createRenderEffect(() => { + void props.value() + }) + + return null +} + +function ViewSubscriber() { + const value = Route.useSearch({ + select: (search) => + computeChecksum(search.view.length * 5 + search.page * 11), + }) + + return computeChecksum(value())} /> +} + +function CatalogPage() { + const search = Route.useSearch() + + return ( +
+ {subscriberIndexes.map(() => ( + + ))} +

Catalog

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

Search Params Bench

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

Products

+
{productsMarkerText(search())}
+

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

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/tsconfig.json b/benchmarks/client-nav/scenarios/search-params/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts new file mode 100644 index 0000000000..511fd49466 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts @@ -0,0 +1,50 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'solid', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav search-params (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/project.json b/benchmarks/client-nav/scenarios/search-params/vue/project.json new file mode 100644 index 0000000000..47b9712a2c --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-search-params-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/search-params/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/search-params/vue/setup.ts b/benchmarks/client-nav/scenarios/search-params/vue/setup.ts new file mode 100644 index 0000000000..97b74b3892 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + steps, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts new file mode 100644 index 0000000000..728d2779e8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-search-params', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-search-params navigation loop (vue)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/search-params/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx new file mode 100644 index 0000000000..65bade775c --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx @@ -0,0 +1,42 @@ +import type { RouterHistory } from '@tanstack/history' +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + defaultStructuralSharing: true, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..f73b84ebe7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as CatalogRouteImport } from './routes/catalog' +import { Route as ProductsRouteImport } from './routes/products' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const CatalogRoute = CatalogRouteImport.update({ + id: '/catalog', + path: '/catalog', + getParentRoute: () => rootRouteImport, +} as any) +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/catalog' | '/products' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/catalog' | '/products' + id: '__root__' | '/' | '/catalog' | '/products' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + CatalogRoute: typeof CatalogRoute + ProductsRoute: typeof ProductsRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/catalog': { + id: '/catalog' + path: '/catalog' + fullPath: '/catalog' + preLoaderRoute: typeof CatalogRouteImport + parentRoute: typeof rootRouteImport + } + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + CatalogRoute: CatalogRoute, + ProductsRoute: ProductsRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..b4cb07f2ae --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/__root.tsx @@ -0,0 +1,114 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute, useSearch } from '@tanstack/vue-router' +import { + changedCategories, + computeChecksum, + initialProductsSearch, +} from '../../../shared' + +const rootSubscribers = Array.from({ length: 4 }, (_, index) => index) + +const RootSearchSubscriber = Vue.defineComponent({ + setup() { + const value = useSearch({ + strict: false, + select: (search) => computeChecksum(Number(search.page ?? 0)), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + {rootSubscribers.map((index) => ( + + ))} + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/catalog.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/catalog.tsx new file mode 100644 index 0000000000..6a09efdd4a --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/catalog.tsx @@ -0,0 +1,49 @@ +import * as Vue from 'vue' +import { createFileRoute, retainSearchParams } from '@tanstack/vue-router' +import type { SearchSchemaInput } from '@tanstack/vue-router' +import { + catalogMarkerText, + computeChecksum, + normalizeCatalogSearch, +} from '../../../shared' + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +const ViewSubscriber = Vue.defineComponent({ + setup() { + const value = Route.useSearch({ + select: (search) => + computeChecksum(search.view.length * 5 + search.page * 11), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const CatalogPage = Vue.defineComponent({ + setup() { + const search = Route.useSearch() + + return () => ( +
+ {subscriberIndexes.map((index) => ( + + ))} +

Catalog

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

Search Params Bench

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

Products

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

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

+
+ ) + }, +}) + +export const Route = createFileRoute('/products')({ + validateSearch: (search: Record & SearchSchemaInput) => + normalizeProductsSearch(search), + search: { + middlewares: [ + retainSearchParams(['perPage', 'sort']), + stripSearchParams({ page: 1 }), + ], + }, + loaderDeps: ({ search }) => ({ + page: search.page, + sort: search.sort, + filters: search.filters, + }), + loader: ({ deps }) => ({ + checksum: productsLoaderChecksum(deps), + }), + staleTime: 1e9, + gcTime: 1e9, + component: ProductsPage, +}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/tsconfig.json b/benchmarks/client-nav/scenarios/search-params/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts new file mode 100644 index 0000000000..27490b276a --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts @@ -0,0 +1,44 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav search-params (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/setup-helpers.ts b/benchmarks/client-nav/setup-helpers.ts new file mode 100644 index 0000000000..c070018743 --- /dev/null +++ b/benchmarks/client-nav/setup-helpers.ts @@ -0,0 +1,43 @@ +export function getRequiredLink( + container: ParentNode, + testId: string, + cache?: Map, +) { + const cachedLink = cache?.get(testId) + if (cachedLink) { + return cachedLink + } + + const link = container.querySelector( + `[data-testid="${testId}"]`, + ) + if (!link) { + throw new Error(`Unable to find benchmark link: ${testId}`) + } + + cache?.set(testId, link) + return link +} + +export async function waitForRequiredLink( + container: ParentNode, + testId: string, + cache?: Map, +) { + for (let attempt = 0; attempt < 10; attempt++) { + const link = container.querySelector( + `[data-testid="${testId}"]`, + ) + + if (link) { + cache?.set(testId, link) + return link + } + + await new Promise((resolve) => { + requestAnimationFrame(() => resolve()) + }) + } + + return getRequiredLink(container, testId, cache) +} diff --git a/benchmarks/client-nav/solid/app.tsx b/benchmarks/client-nav/solid/app.tsx new file mode 100644 index 0000000000..ef90130f5e --- /dev/null +++ b/benchmarks/client-nav/solid/app.tsx @@ -0,0 +1,367 @@ +import { For, createRenderEffect } from 'solid-js' +import { render } from 'solid-js/web' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + useParams, + useSearch, +} from '@tanstack/solid-router' + +function runPerfSelectorComputation(seed: number) { + let value = Math.trunc(seed) | 0 + + for (let index = 0; index < 40; index++) { + value = (value * 1664525 + 1013904223 + index) >>> 0 + } + + return value +} + +function normalizePage(value: unknown) { + const page = Number(value) + return Number.isFinite(page) && page > 0 ? Math.trunc(page) : 1 +} + +function normalizeFilter(value: unknown) { + return typeof value === 'string' && value.length > 0 ? value : 'all' +} + +const noop = () => {} +const rootSelectors = Array.from({ length: 10 }, (_, index) => index) +const routeSelectors = Array.from({ length: 6 }, (_, index) => index) +const linkGroups = Array.from({ length: 4 }, (_, index) => index) + +function PerfValue(props: { value: () => number }) { + createRenderEffect(() => { + void props.value() + }) + + return null +} + +function RootParamsSubscriber() { + const params = useParams({ + strict: false, + select: (params) => runPerfSelectorComputation(Number(params.id ?? 0)), + }) + + return runPerfSelectorComputation(params())} /> +} + +function RootSearchSubscriber() { + const search = useSearch({ + strict: false, + select: (search) => runPerfSelectorComputation(Number(search.page ?? 0)), + }) + + return runPerfSelectorComputation(search())} /> +} + +function LinkPanel() { + return ( + <> + + {(groupIndex) => { + const itemsId = groupIndex === 0 ? 1 : groupIndex + 2 + const ctxId = groupIndex + 1 + + return ( +
+ + {`Items ${itemsId}`} + + + {`Items 2 alt ${groupIndex}`} + + + {`Search ${groupIndex}`} + + + {`Context ${ctxId}`} + + ({ + page: prev.page + groupIndex + 1, + filter: prev.filter, + junk: `updater-${groupIndex}`, + })} + activeOptions={{ includeSearch: true }} + > + {({ isActive }) => + isActive + ? `Search updater active ${groupIndex}` + : `Search updater inactive ${groupIndex}` + } + +
+ ) + }} +
+ + ) +} + +function Root() { + return ( + <> + {() => } + {() => } + + + + ) +} + +const rootRoute = createRootRoute({ + component: Root, +}) + +const itemsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + params: { + parse: (params) => ({ + ...params, + id: normalizePage(params.id), + }), + stringify: (params) => ({ + ...params, + id: `${params.id}`, + }), + }, + onEnter: noop, + onStay: noop, + onLeave: noop, + component: ItemsPage, +}) + +const itemDetailsRoute = createRoute({ + getParentRoute: () => itemsRoute, + path: 'details', + component: ItemDetailsPage, +}) + +const searchRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/search', + validateSearch: (search: Record) => ({ + page: normalizePage(search.page), + filter: normalizeFilter(search.filter), + }), + search: { + middlewares: [ + ({ search, next }) => { + const result = next(search) + return { + page: result.page, + filter: result.filter, + } + }, + ], + }, + loaderDeps: ({ search }) => ({ + page: search.page, + filter: search.filter, + }), + loader: ({ deps }) => ({ + seed: deps.page * 31 + deps.filter.length, + checksum: deps.page * 17 + deps.filter.length, + }), + staleTime: 60_000, + gcTime: 60_000, + component: SearchPage, +}) + +const contextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/ctx/$id', + beforeLoad: ({ params }) => ({ + sectionSeed: Number(params.id) * 13 + 1, + }), + component: ContextPage, +}) + +function ItemParamsSubscriber() { + const params = itemsRoute.useParams({ + select: (params) => runPerfSelectorComputation(params.id), + }) + + return runPerfSelectorComputation(params())} /> +} + +function SearchStateSubscriber() { + const search = searchRoute.useSearch({ + select: (search) => + runPerfSelectorComputation(search.page + search.filter.length), + }) + + return runPerfSelectorComputation(search())} /> +} + +function SearchLoaderDepsSubscriber() { + const loaderDeps = searchRoute.useLoaderDeps({ + select: (loaderDeps) => + runPerfSelectorComputation(loaderDeps.page + loaderDeps.filter.length), + }) + + return runPerfSelectorComputation(loaderDeps())} /> +} + +function SearchLoaderDataSubscriber() { + const loaderData = searchRoute.useLoaderData({ + select: (loaderData) => + runPerfSelectorComputation(loaderData.seed + loaderData.checksum), + }) + + return runPerfSelectorComputation(loaderData())} /> +} + +function ContextParamsSubscriber() { + const params = contextRoute.useParams({ + select: (params) => runPerfSelectorComputation(Number(params.id)), + }) + + return runPerfSelectorComputation(params())} /> +} + +function ContextRouteSubscriber() { + const context = contextRoute.useRouteContext({ + select: (context) => runPerfSelectorComputation(context.sectionSeed), + }) + + return runPerfSelectorComputation(context())} /> +} + +function ItemsPage() { + return ( + <> + {() => } + + Details + + + Preserve search on item + + + + ) +} + +function ItemDetailsPage() { + return ( + <> + {() => } + + Back to item + + + ) +} + +function SearchPage() { + return ( + <> + {() => } + {() => } + {() => } + ({ + page: prev.page + 1, + filter: prev.filter, + junk: 'local-updater', + })} + activeOptions={{ includeSearch: true }} + activeProps={{ class: 'active-link' }} + inactiveProps={{ class: 'inactive-link' }} + > + Next page + + + ) +} + +function ContextPage() { + return ( + <> + {() => } + {() => } + + ) +} + +export function mountTestApp(container: Element) { + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/items/0'], + }), + scrollRestoration: true, + routeTree: rootRoute.addChildren([ + itemsRoute.addChildren([itemDetailsRoute]), + searchRoute, + contextRoute, + ]), + }) + + const unmount = render(() => , container) + + return { + router, + unmount, + } +} diff --git a/benchmarks/client-nav/solid/setup.ts b/benchmarks/client-nav/solid/setup.ts new file mode 100644 index 0000000000..9b532a466a --- /dev/null +++ b/benchmarks/client-nav/solid/setup.ts @@ -0,0 +1,112 @@ +import type { NavigateOptions } from '@tanstack/router-core' +import type * as App from './app' +import { getRequiredLink, waitForRequiredLink } from '../setup-helpers' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + if (process.env.NODE_ENV !== 'production') { + console.warn( + 'client-nav benchmark is running without NODE_ENV=production; Solid dev overhead will dominate results.', + ) + } + + let container: HTMLDivElement | undefined = undefined + let unmount: (() => void) | undefined = undefined + let unsub = () => {} + let stepIndex = 0 + let next: () => Promise = () => Promise.reject('Test not initialized') + + async function before() { + stepIndex = 0 + container = document.createElement('div') + document.body.append(container) + + const { router, unmount: dispose } = mountTestApp(container) + unmount = dispose + + let resolveRendered: () => void = () => {} + unsub = router.subscribe('onRendered', () => { + resolveRendered() + }) + + const navigate = (opts: NavigateOptions) => + new Promise((resolveNext) => { + resolveRendered = resolveNext + router.navigate(opts) + }) + + const click = (testId: string, cache?: Map) => + new Promise((resolveNext) => { + resolveRendered = resolveNext + + getRequiredLink(container!, testId, cache).dispatchEvent( + new MouseEvent('click', { + bubbles: true, + cancelable: true, + button: 0, + }), + ) + }) + + await router.load() + + const cachedLinks = new Map() + for (const testId of ['go-items-1', 'go-items-2', 'go-search', 'go-ctx']) { + await waitForRequiredLink(container, testId, cachedLinks) + } + + const steps = [ + () => click('go-items-1', cachedLinks), + () => click('items-details'), + () => + navigate({ + to: '/items/$id/details', + params: { id: 2 }, + replace: true, + }), + () => click('items-parent'), + () => click('go-search', cachedLinks), + () => click('search-next-page'), + () => + navigate({ + to: '/search', + search: { page: 1, filter: 'all' }, + replace: true, + }), + () => click('go-ctx', cachedLinks), + () => + navigate({ + to: '/ctx/$id', + params: { id: 2 }, + replace: true, + }), + () => click('go-items-2', cachedLinks), + ] as const + + next = () => { + const step = steps[stepIndex % steps.length]! + stepIndex += 1 + return step() + } + } + + function after() { + unmount?.() + container?.remove() + unsub() + } + + function tick() { + return next() + } + + return { + before, + tick, + after, + } +} diff --git a/benchmarks/client-nav/solid/speed.bench.ts b/benchmarks/client-nav/solid/speed.bench.ts new file mode 100644 index 0000000000..d629da17a8 --- /dev/null +++ b/benchmarks/client-nav/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { setup } from './setup' + +test('client-nav', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-side navigation loop (solid)', + { beforeAll: scenario.before, afterAll: scenario.after }, + async () => { + for (let i = 0; i < 10; i++) { + await scenario.tick() + } + }, + ).run({ + warmupIterations: 100, + time: 10_000, + }) +}) diff --git a/benchmarks/client-nav/solid/speed.flame.ts b/benchmarks/client-nav/solid/speed.flame.ts new file mode 100644 index 0000000000..285ccc63d7 --- /dev/null +++ b/benchmarks/client-nav/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/solid/tsconfig.json b/benchmarks/client-nav/solid/tsconfig.json new file mode 100644 index 0000000000..4c500d0793 --- /dev/null +++ b/benchmarks/client-nav/solid/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "../jsdom.ts", + "setup.ts", + "vite.config.ts", + "../vitest.setup.ts" + ] +} diff --git a/benchmarks/client-nav/solid/vite.config.ts b/benchmarks/client-nav/solid/vite.config.ts new file mode 100644 index 0000000000..0c26b32f5f --- /dev/null +++ b/benchmarks/client-nav/solid/vite.config.ts @@ -0,0 +1,47 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { cpuSimulationExecArgv } from '../../cpu-simulation' + +// Anchor the project root to the package directory so this config resolves +// identically when run directly and as part of an aggregate `projects` config. +const rootDir = fileURLToPath(new URL('..', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './solid/dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './solid/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav (solid)', + watch: false, + environment: 'jsdom', + setupFiles: [`${rootDir}vitest.setup.ts`], + benchmark: { include: ['solid/speed.bench.ts'] }, + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/tsconfig.json b/benchmarks/client-nav/tsconfig.json new file mode 100644 index 0000000000..f657f504d4 --- /dev/null +++ b/benchmarks/client-nav/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": ["vitest.setup.ts"] +} diff --git a/benchmarks/client-nav/vitest.config.ts b/benchmarks/client-nav/vitest.config.ts new file mode 100644 index 0000000000..808e7fc724 --- /dev/null +++ b/benchmarks/client-nav/vitest.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + projects: [ + './react/vite.config.ts', + './solid/vite.config.ts', + './vue/vite.config.ts', + './scenarios/*/react/vite.config.ts', + './scenarios/*/solid/vite.config.ts', + './scenarios/*/vue/vite.config.ts', + ], + }, +}) diff --git a/benchmarks/client-nav/vitest.react.config.ts b/benchmarks/client-nav/vitest.react.config.ts new file mode 100644 index 0000000000..a397ad929e --- /dev/null +++ b/benchmarks/client-nav/vitest.react.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + projects: ['./react/vite.config.ts', './scenarios/*/react/vite.config.ts'], + }, +}) diff --git a/benchmarks/client-nav/vitest.setup.ts b/benchmarks/client-nav/vitest.setup.ts new file mode 100644 index 0000000000..9bac58bd41 --- /dev/null +++ b/benchmarks/client-nav/vitest.setup.ts @@ -0,0 +1,6 @@ +import { vi } from 'vitest' + +// @ts-expect-error +global.IS_REACT_ACT_ENVIRONMENT = true + +window.scrollTo = vi.fn() diff --git a/benchmarks/client-nav/vitest.solid.config.ts b/benchmarks/client-nav/vitest.solid.config.ts new file mode 100644 index 0000000000..b8827b86aa --- /dev/null +++ b/benchmarks/client-nav/vitest.solid.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + projects: ['./solid/vite.config.ts', './scenarios/*/solid/vite.config.ts'], + }, +}) diff --git a/benchmarks/client-nav/vitest.vue.config.ts b/benchmarks/client-nav/vitest.vue.config.ts new file mode 100644 index 0000000000..17960d7569 --- /dev/null +++ b/benchmarks/client-nav/vitest.vue.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + projects: ['./vue/vite.config.ts', './scenarios/*/vue/vite.config.ts'], + }, +}) diff --git a/benchmarks/client-nav/vue/app.tsx b/benchmarks/client-nav/vue/app.tsx new file mode 100644 index 0000000000..f88eee8129 --- /dev/null +++ b/benchmarks/client-nav/vue/app.tsx @@ -0,0 +1,433 @@ +import * as Vue from 'vue' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + useParams, + useSearch, +} from '@tanstack/vue-router' + +function runPerfSelectorComputation(seed: number) { + let value = Math.trunc(seed) | 0 + + for (let index = 0; index < 40; index++) { + value = (value * 1664525 + 1013904223 + index) >>> 0 + } + + return value +} + +function normalizePage(value: unknown) { + const page = Number(value) + return Number.isFinite(page) && page > 0 ? Math.trunc(page) : 1 +} + +function normalizeFilter(value: unknown) { + return typeof value === 'string' && value.length > 0 ? value : 'all' +} + +const noop = () => {} +const rootSelectors = Array.from({ length: 10 }, (_, index) => index) +const routeSelectors = Array.from({ length: 6 }, (_, index) => index) +const linkGroups = Array.from({ length: 4 }, (_, index) => index) + +const RootParamsSubscriber = Vue.defineComponent({ + setup() { + const params = useParams({ + strict: false, + select: (params) => runPerfSelectorComputation(Number(params.id ?? 0)), + }) + + return () => { + void runPerfSelectorComputation(params.value) + return null + } + }, +}) + +const RootSearchSubscriber = Vue.defineComponent({ + setup() { + const search = useSearch({ + strict: false, + select: (search) => runPerfSelectorComputation(Number(search.page ?? 0)), + }) + + return () => { + void runPerfSelectorComputation(search.value) + return null + } + }, +}) + +const LinkPanel = Vue.defineComponent({ + setup() { + return () => ( + <> + {linkGroups.map((groupIndex) => { + const itemsId = groupIndex === 0 ? 1 : groupIndex + 2 + const ctxId = groupIndex + 1 + + return ( +
+ + {`Items ${itemsId}`} + + + {`Items 2 alt ${groupIndex}`} + + + {`Search ${groupIndex}`} + + + {`Context ${ctxId}`} + + ({ + page: prev.page + groupIndex + 1, + filter: prev.filter, + junk: `updater-${groupIndex}`, + })} + activeOptions={{ includeSearch: true }} + > + {({ isActive }: { isActive: boolean }) => + isActive + ? `Search updater active ${groupIndex}` + : `Search updater inactive ${groupIndex}` + } + +
+ ) + })} + + ) + }, +}) + +const Root = Vue.defineComponent({ + setup() { + return () => ( + <> + {rootSelectors.map((selector) => ( + + ))} + {rootSelectors.map((selector) => ( + + ))} + + + + ) + }, +}) + +const rootRoute = createRootRoute({ + component: Root, +}) + +const ItemParamsSubscriber = Vue.defineComponent({ + setup() { + const params = itemsRoute.useParams({ + select: (params) => runPerfSelectorComputation(params.id), + }) + + return () => { + void runPerfSelectorComputation(params.value) + return null + } + }, +}) + +const SearchStateSubscriber = Vue.defineComponent({ + setup() { + const search = searchRoute.useSearch({ + select: (search) => + runPerfSelectorComputation(search.page + search.filter.length), + }) + + return () => { + void runPerfSelectorComputation(search.value) + return null + } + }, +}) + +const SearchLoaderDepsSubscriber = Vue.defineComponent({ + setup() { + const loaderDeps = searchRoute.useLoaderDeps({ + select: (loaderDeps) => + runPerfSelectorComputation(loaderDeps.page + loaderDeps.filter.length), + }) + + return () => { + void runPerfSelectorComputation(loaderDeps.value) + return null + } + }, +}) + +const SearchLoaderDataSubscriber = Vue.defineComponent({ + setup() { + const loaderData = searchRoute.useLoaderData({ + select: (loaderData) => + runPerfSelectorComputation(loaderData.seed + loaderData.checksum), + }) + + return () => { + void runPerfSelectorComputation(loaderData.value) + return null + } + }, +}) + +const ContextParamsSubscriber = Vue.defineComponent({ + setup() { + const params = contextRoute.useParams({ + select: (params) => runPerfSelectorComputation(Number(params.id)), + }) + + return () => { + void runPerfSelectorComputation(params.value) + return null + } + }, +}) + +const ContextRouteSubscriber = Vue.defineComponent({ + setup() { + const context = contextRoute.useRouteContext({ + select: (context) => runPerfSelectorComputation(context.sectionSeed), + }) + + return () => { + void runPerfSelectorComputation(context.value) + return null + } + }, +}) + +const ItemsPage = Vue.defineComponent({ + setup() { + return () => ( + <> + {routeSelectors.map((selector) => ( + + ))} + + Details + + + Preserve search on item + + + + ) + }, +}) + +const ItemDetailsPage = Vue.defineComponent({ + setup() { + return () => ( + <> + {routeSelectors.map((selector) => ( + + ))} + + Back to item + + + ) + }, +}) + +const SearchPage = Vue.defineComponent({ + setup() { + return () => ( + <> + {routeSelectors.map((selector) => ( + + ))} + {routeSelectors.map((selector) => ( + + ))} + {routeSelectors.map((selector) => ( + + ))} + ({ + page: prev.page + 1, + filter: prev.filter, + junk: 'local-updater', + })} + activeOptions={{ includeSearch: true }} + activeProps={{ class: 'active-link' }} + inactiveProps={{ class: 'inactive-link' }} + > + Next page + + + ) + }, +}) + +const ContextPage = Vue.defineComponent({ + setup() { + return () => ( + <> + {routeSelectors.map((selector) => ( + + ))} + {routeSelectors.map((selector) => ( + + ))} + + ) + }, +}) + +const itemsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + params: { + parse: (params) => ({ + ...params, + id: normalizePage(params.id), + }), + stringify: (params) => ({ + ...params, + id: `${params.id}`, + }), + }, + onEnter: noop, + onStay: noop, + onLeave: noop, + component: ItemsPage, +}) + +const itemDetailsRoute = createRoute({ + getParentRoute: () => itemsRoute, + path: 'details', + component: ItemDetailsPage, +}) + +const searchRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/search', + validateSearch: (search: Record) => ({ + page: normalizePage(search.page), + filter: normalizeFilter(search.filter), + }), + search: { + middlewares: [ + ({ search, next }) => { + const result = next(search) + return { + page: result.page, + filter: result.filter, + } + }, + ], + }, + loaderDeps: ({ search }) => ({ + page: search.page, + filter: search.filter, + }), + loader: ({ deps }) => ({ + seed: deps.page * 31 + deps.filter.length, + checksum: deps.page * 17 + deps.filter.length, + }), + staleTime: 60_000, + gcTime: 60_000, + component: SearchPage, +}) + +const contextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/ctx/$id', + beforeLoad: ({ params }) => ({ + sectionSeed: Number(params.id) * 13 + 1, + }), + component: ContextPage, +}) + +export function mountTestApp(container: Element) { + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/items/0'], + }), + scrollRestoration: true, + routeTree: rootRoute.addChildren([ + itemsRoute.addChildren([itemDetailsRoute]), + searchRoute, + contextRoute, + ]), + }) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/vue/setup.ts b/benchmarks/client-nav/vue/setup.ts new file mode 100644 index 0000000000..75a633f629 --- /dev/null +++ b/benchmarks/client-nav/vue/setup.ts @@ -0,0 +1,112 @@ +import type { NavigateOptions } from '@tanstack/router-core' +import type * as App from './app' +import { getRequiredLink, waitForRequiredLink } from '../setup-helpers' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + if (process.env.NODE_ENV !== 'production') { + console.warn( + 'client-nav benchmark is running without NODE_ENV=production; Vue dev overhead will dominate results.', + ) + } + + let container: HTMLDivElement | undefined = undefined + let unmount: (() => void) | undefined = undefined + let unsub = () => {} + let stepIndex = 0 + let next: () => Promise = () => Promise.reject('Test not initialized') + + async function before() { + stepIndex = 0 + container = document.createElement('div') + document.body.append(container) + + const { router, unmount: dispose } = mountTestApp(container) + unmount = dispose + + let resolveRendered: () => void = () => {} + unsub = router.subscribe('onRendered', () => { + resolveRendered() + }) + + const navigate = (opts: NavigateOptions) => + new Promise((resolveNext) => { + resolveRendered = resolveNext + router.navigate(opts) + }) + + const click = (testId: string, cache?: Map) => + new Promise((resolveNext) => { + resolveRendered = resolveNext + + getRequiredLink(container!, testId, cache).dispatchEvent( + new MouseEvent('click', { + bubbles: true, + cancelable: true, + button: 0, + }), + ) + }) + + await router.load() + + const cachedLinks = new Map() + for (const testId of ['go-items-1', 'go-items-2', 'go-search', 'go-ctx']) { + await waitForRequiredLink(container, testId, cachedLinks) + } + + const steps = [ + () => click('go-items-1', cachedLinks), + () => click('items-details'), + () => + navigate({ + to: '/items/$id/details', + params: { id: 2 }, + replace: true, + }), + () => click('items-parent'), + () => click('go-search', cachedLinks), + () => click('search-next-page'), + () => + navigate({ + to: '/search', + search: { page: 1, filter: 'all' }, + replace: true, + }), + () => click('go-ctx', cachedLinks), + () => + navigate({ + to: '/ctx/$id', + params: { id: 2 }, + replace: true, + }), + () => click('go-items-2', cachedLinks), + ] as const + + next = () => { + const step = steps[stepIndex % steps.length]! + stepIndex += 1 + return step() + } + } + + function after() { + unmount?.() + container?.remove() + unsub() + } + + function tick() { + return next() + } + + return { + before, + tick, + after, + } +} diff --git a/benchmarks/client-nav/vue/speed.bench.ts b/benchmarks/client-nav/vue/speed.bench.ts new file mode 100644 index 0000000000..503e91e7b7 --- /dev/null +++ b/benchmarks/client-nav/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { setup } from './setup' + +test('client-nav', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-side navigation loop (vue)', + { beforeAll: scenario.before, afterAll: scenario.after }, + async () => { + for (let i = 0; i < 10; i++) { + await scenario.tick() + } + }, + ).run({ + warmupIterations: 100, + time: 10_000, + }) +}) diff --git a/benchmarks/client-nav/vue/speed.flame.ts b/benchmarks/client-nav/vue/speed.flame.ts new file mode 100644 index 0000000000..285ccc63d7 --- /dev/null +++ b/benchmarks/client-nav/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/vue/tsconfig.json b/benchmarks/client-nav/vue/tsconfig.json new file mode 100644 index 0000000000..d8c92cfc17 --- /dev/null +++ b/benchmarks/client-nav/vue/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "../jsdom.ts", + "setup.ts", + "vite.config.ts", + "../vitest.setup.ts" + ] +} diff --git a/benchmarks/client-nav/vue/vite.config.ts b/benchmarks/client-nav/vue/vite.config.ts new file mode 100644 index 0000000000..78d8ae5638 --- /dev/null +++ b/benchmarks/client-nav/vue/vite.config.ts @@ -0,0 +1,41 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { cpuSimulationExecArgv } from '../../cpu-simulation' + +// Anchor the project root to the package directory so this config resolves +// identically when run directly and as part of an aggregate `projects` config. +const rootDir = fileURLToPath(new URL('..', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + vue(), + vueJsx(), + ], + build: { + outDir: './vue/dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './vue/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav (vue)', + watch: false, + environment: 'jsdom', + setupFiles: [`${rootDir}vitest.setup.ts`], + benchmark: { include: ['vue/speed.bench.ts'] }, + }, +}) diff --git a/benchmarks/cpu-simulation.ts b/benchmarks/cpu-simulation.ts new file mode 100644 index 0000000000..9b8859f74d --- /dev/null +++ b/benchmarks/cpu-simulation.ts @@ -0,0 +1,53 @@ +function codspeedRunnerMode() { + return process.env.CODSPEED_ENV === undefined + ? undefined + : process.env.CODSPEED_RUNNER_MODE +} + +/** + * Whether CodSpeed's simulation or memory instrument drives the run. Both + * measure one invocation after a few warmup calls instead of sampling. + */ +export function isCodSpeedAnalysis() { + const mode = codspeedRunnerMode() + return ( + mode === 'simulation' || mode === 'instrumentation' || mode === 'memory' + ) +} + +/** Extra worker flags for CodSpeed CPU simulation, not walltime benchmarks. */ +export function cpuSimulationExecArgv() { + const mode = codspeedRunnerMode() + if (mode === 'simulation' || mode === 'instrumentation') { + // CodSpeed supplies --no-opt, which only disables TurboFan on Node 24. + // Maglev can still compile and inline hot functions between measured runs. + // Compile baseline code on first use, so warmup does not leave functions + // near Sparkplug's later tier-up/batch-compilation thresholds. + // V8 renamed --scavenge-task in Node 20; CodSpeed's old flag is omitted. + // Keep minor GC tied to allocations instead of scheduled foreground tasks. + // Fix the initial/minimum old-generation allocation budget. This can skip + // automatic full collections below the budget; minor GC remains enabled. + return [ + '--no-maglev', + '--always-sparkplug', + '--no-minor-gc-task', + '--initial-old-space-size=512', + ] + } + return [] +} + +/** + * Per-bench lifecycle for apps that a bench prepares and disposes outside + * timing. CodSpeed measures one invocation, so each invocation gets fresh + * state. Tinybench samples thousands of iterations and keeps one instance per + * warmup/run phase instead of preparing it for every iteration. + */ +export function benchLifecycle(hooks: { + before: () => Promise | void + after: () => Promise | void +}) { + return isCodSpeedAnalysis() + ? { beforeEach: hooks.before, afterEach: hooks.after } + : { beforeAll: hooks.before, afterAll: hooks.after } +} diff --git a/benchmarks/memory/README.md b/benchmarks/memory/README.md new file mode 100644 index 0000000000..18b68768f9 --- /dev/null +++ b/benchmarks/memory/README.md @@ -0,0 +1,273 @@ +# Memory Benchmarks + +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 +push to `main` except docs/examples/e2e-only pushes: CodSpeed compares a PR +against the run on its merge-base commit, and a main commit without a run makes +CodSpeed silently fall back to an older base — a single outlier base run then +flags phantom regressions on every PR until the next run lands. (Falling back +across a docs-only commit is safe: the previous run's benchmark-relevant code +is identical.) Two separate benchmarks: + +- `server/` (`@benchmarks/memory-server`) — React/Solid/Vue Start apps, requests against + the built server handler (`handler.fetch`), Node environment. +- `client/` (`@benchmarks/memory-client`) — router-only React/Solid/Vue apps in jsdom. + +These deliberately do **not** reuse the CPU scenarios in `benchmarks/ssr` and +`benchmarks/client-nav`: memory benches need their own iteration counts, +payload sizes, and route shapes, and tuning those must never shift the CPU +baselines. Each scenario keeps a framework level (`react/`, `solid/`, `vue/`) +so framework ports can be added without renames. + +## Layout + +```text +benchmarks/memory// + package.json Nx targets: build:, test:perf:, test:flame:, test:types + bench-utils.ts memoryBenchOptions, seeded LCG (+ sequential request loop on the server side) + vitest..config.ts aggregates scenarios/*//vite.config.ts + scenarios/// + one isolated app per scenario + setup.ts + memory.bench.ts + memory.flame.ts +``` + +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. + +## How the memory instrument executes a bench + +- The bench function is warmed up, then **measured exactly once**, starting + 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. +- Worker flags live in `runtime.ts` and apply only to the CodSpeed memory + instrument. They supplement the integration's predictable execution flags; + the retained overrides are described below. +- Before each CodSpeed invocation, the `beforeEach` hook yields to the event + loop, outside the measurement marker and before CodSpeed forces GC. Promise-only + warmup chains can keep WeakRef targets alive through a collection in the same + job. Client app setup also runs before the forced GC. +- Do not force GC inside a measured request loop or poll `heapUsed` to choose + how much work to do. Both introduce allocator activity from the harness into + the measurement. Footprint scenarios run exactly one large request per + invocation; churn scenarios retain their fixed sequential request counts. +- Error-path cases use separate isolated workers so one case's module and + allocator history cannot contaminate the next case. +- Keep each bench under **~1.5M allocations** (instrument overhead grows past + 2M); this is the main constraint when tuning iteration counts. + +## Worker settings + +All scenarios use [`memoryConfig`](./runtime.ts). It adds these flags only in +memory mode: + +- `--no-maglev` +- `--no-flush-bytecode` +- `--no-minor-gc-task` +- `--no-incremental-marking` +- `--initial-old-space-size=512` + +`--jitless` was removed after repeated CI comparisons. Ten unchanged-commit +repetitions with the last four flags kept all 48 peak-memory results within 1% +(worst spread: 0.834%). With JIT enabled, all 16 subsets of the four flags were +tested. Removing bytecode, minor-GC-task, incremental-marking, or heap-budget +overrides from this profile produced worst client peak spreads of 6.616%, 2.714%, +2.109%, and 10.669%, respectively. Smaller combinations also exceeded 1% in at +least one tracked metric. This supports retaining the four-flag profile; it does +not establish that every override is required in every individual scenario. + +A server-only heap-budget profile initially passed five repetitions, but further +confirmation produced a 24.46% server peak outlier. That configuration was +rejected. Allocated bytes and allocation counts remain imperfectly repeatable: +a client confirmation with the retained four flags showed a 6.77% allocated-byte +spread and a 5.91% allocation-count spread. Client peaks remained within 0.834% +across all 15 observations with the retained profile. Experiment details and CI runs are recorded in +[PR #8260](https://github.com/TanStack/router/pull/8260). + +These settings trade production GC behavior for repeatable regression signals. +They suppress bytecode reclamation and change collection scheduling. The 512 MiB +initial/minimum old-generation allocation budget can postpone automatic full +collections. This does not preallocate 512 MiB, and the smallest sufficient budget +was not determined. Results describe this controlled worker profile, not a +production application's absolute memory footprint. + +CodSpeed's `--no-opt` only disables TurboFan on Node 24 (V8 13); Maglev still +compiles. Under CodSpeed's `--predictable` there is no background compilation, +so Maglev compiles run synchronously inside whichever request triggers them, and +the forced GC before the measured call can discard optimized code so recompiles +land inside the measured window. Maglev's malloc'd Zone scratch (32 KiB +segments) then dominates allocation metrics, and its size depends on +per-process feedback state. `--no-maglev` was added for this: the bimodal ++32,792 B / +1 allocation in `mem server error-paths unmatched (react)` was one +Maglev Zone segment allocated while compiling React Fizz's per-request stream +`write` closure, and compiler scratch made up ~97% of that bench's allocated +bytes. Retained-object measurements are unaffected because Zone memory is freed +after each compile. The repeatability figures above predate this flag. + +## Bench shapes and signals + +- **Churn:** a fixed number of sequential operations, measuring native + allocation activity and peak outstanding native allocations. +- **Peak (footprint):** one large operation, measuring its native footprint. + +CodSpeed reports native allocator activity, not individual JavaScript object +allocations or retained JS heap size. V8 can reuse heap pages without a visible +native allocation. These benchmarks can detect native buffering and allocator +regressions, but a flat graph does not establish that route data or JS objects +are collectable. Absolute numbers include Node/framework/jsdom activity under +benchmark-specific V8 settings; compare identical harness versions. + +## Scenarios + +### Server + +| Scenario | Shape | Exercises | +| ----------------------- | ----- | --------------------------------------------------------- | +| `request-churn` | churn | cross-request retention in document SSR (unique URLs) | +| `server-fn-churn` | churn | retention in the server-function RPC path | +| `error-paths` | churn | redirect/notFound/error/unmatched paths pinning contexts | +| `aborted-requests` | churn | dangling streams/listeners after mid-stream client aborts | +| `peak-large-page` | peak | per-request peak scaling with page size | +| `streaming-peak` | peak | streaming buffering O(document) instead of O(chunk) | +| `serialization-payload` | peak | double-buffering / string-copy blowups in dehydration | + +### Client + +| Scenario | Shape | Exercises | +| ------------------------- | ----- | -------------------------------------------------------- | +| `navigation-churn` | churn | per-navigation retention at steady state | +| `unique-location-churn` | churn | unbounded href/search-keyed caches (never-repeated URLs) | +| `preload-churn` | churn | preload-cache eviction not releasing memory | +| `loader-data-retention` | churn | departed routes' loader data staying pinned (gcTime 0) | +| `mount-unmount` | churn | router instances not collectable after dispose | +| `interrupted-navigations` | churn | superseded navigations retaining closures/contexts | + +## Conventions + +- Strictly sequential work: at most one request/navigation in flight; each + server response is fully consumed before the next request. Pairing a single + navigation with its render signal via `Promise.all([navigate, rendered])` + is fine — never overlap distinct work items. +- Randomness only via the seeded LCG in `bench-utils.ts`. Deferred streaming + uses counted zero-delay timer hops to stage work. Timers still depend on the + event loop, so validate repeatability on CI instead of assuming deterministic + ordering from a zero delay alone. +- Sanity assertions run once at module load and throw on wrong + status/markers, so a bench can never silently measure the wrong thing. +- Server requests follow `benchmarks/ssr` conventions: document GETs send + `accept: text/html`, server-fn requests send `sec-fetch-site: same-origin` + with bodies precomputed at module level. +- Client apps export `mountTestApp` from `app.tsx`; benches import the built + `dist/app.js`; navigations use `replace: true`; unmount does full teardown + (framework root, `__TSR_ROUTER__`, `history.destroy()`); large loader payloads + are never rendered into the DOM. +- `NODE_ENV=production` everywhere (the Nx targets set it). + +## Run + +Smoke-test the CodSpeed/Vitest benchmark entrypoints and typecheck the +scenarios: + +```bash +pnpm nx run @benchmarks/memory-server:test:perf:react --outputStyle=stream --skipRemoteCache +pnpm nx run @benchmarks/memory-server:test:perf:solid --outputStyle=stream --skipRemoteCache +pnpm nx run @benchmarks/memory-server:test:perf:vue --outputStyle=stream --skipRemoteCache +pnpm nx run @benchmarks/memory-client:test:perf:react --outputStyle=stream --skipRemoteCache +pnpm nx run @benchmarks/memory-client:test:perf:solid --outputStyle=stream --skipRemoteCache +pnpm nx run @benchmarks/memory-client:test:perf:vue --outputStyle=stream --skipRemoteCache +pnpm nx run @benchmarks/memory-server:test:types --outputStyle=stream --skipRemoteCache +pnpm nx run @benchmarks/memory-client:test:types --outputStyle=stream --skipRemoteCache +``` + +Local attribution profiling, without CodSpeed CLI/login/sudo/upload, uses +`@datadog/pprof` heap sampling and `@platformatic/flame` only to render the +captured pprof files as HTML/Markdown. These targets rebuild the scenarios with +`--sourcemap true` so the generated profile reports can point back to source; +the normal CodSpeed benchmark builds are unchanged. Local aggregate scripts run +with `--parallel=1`, and scenario `test:flame` targets opt out of Nx parallelism +so profiling workloads do not overlap and bias each other. The Vitest aggregate +configs also set `fileParallelism: false` so benchmark files run sequentially +inside `test:perf:react`. + +```bash +pnpm benchmark:memory:server:flame +pnpm benchmark:memory:client:flame +pnpm benchmark:memory:server:flame:solid +pnpm benchmark:memory:client:flame:solid +pnpm benchmark:memory:server:flame:vue +pnpm benchmark:memory:client:flame:vue +``` + +To profile one scenario, run its `test:flame` target directly: + +```bash +pnpm nx run @benchmarks/memory-server-request-churn-react:test:flame --outputStyle=stream --skipRemoteCache +pnpm nx run @benchmarks/memory-client-navigation-churn-react:test:flame --outputStyle=stream --skipRemoteCache +``` + +Flame writes reports under the scenario's ignored `.profiles//` +directory, including `heap-profile-*.html` and `heap-profile-*.md`. The +`memory.flame.ts` entrypoints run the same workload shape as `memory.bench.ts` +but manually start profiling after sanity/setup work and stop it after the +measured workload. Treat these profiles as diagnostic heap-sampling attribution; +they are not CodSpeed memory metrics such as peak memory, allocated bytes, or +allocation counts. The heap sampler is stopped before profile conversion and +Flame report generation, so Flame/pprof report-generation work should not appear +as part of the captured workload. Flame runs do not force GC before profiling; +doing so would perturb the workload and still would not make heap sampling +equivalent to CodSpeed memory metrics. + +Clean local Flame profile output with: + +```bash +pnpm --filter @benchmarks/memory-server clean:profiles +pnpm --filter @benchmarks/memory-client clean:profiles +``` + +Client memory benches are useful for regression tracking of router/React/jsdom +integration behavior and native allocation activity. They are not pure +browser-memory measurements, and local Flame attribution can include jsdom, +React DOM, and profiler shutdown frames. + +Real memory measurement, locally (requires the CodSpeed CLI, `codspeed setup` +once to install the memory executor, and sudo; **uploads results to the +CodSpeed dashboard** — local runs do not affect PR baselines): + +```bash +WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-server:test:perf:react +WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-server:test:perf:solid +WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-server:test:perf:vue +WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-client:test:perf:react +WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-client:test:perf:solid +WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-client:test:perf:vue +``` + +Run the benchmark workflow on an experiment branch: + +```bash +gh workflow run benchmarks.yml --ref +``` + +Repeat at the same commit, using distinct branch names if runs should overlap +(the workflow serializes runs on the same ref). Compare all 48 fresh memory +results: 18 client and 30 server. Exclude CPU simulation results, inherited +CodSpeed results, and failed or incomplete repetitions. For each workload, calculate +`100 * (max / min - 1)` across runs for peak bytes, allocated bytes, and +allocation counts; aggregate averages hide unstable cases. + +Observed spreads below 1% establish repeatability in the tested sample, not a +bound on future runs. Changes to worker flags or workload lifecycles establish +new measurement baselines. diff --git a/benchmarks/memory/client/bench-utils.ts b/benchmarks/memory/client/bench-utils.ts new file mode 100644 index 0000000000..785e8fac7f --- /dev/null +++ b/benchmarks/memory/client/bench-utils.ts @@ -0,0 +1,22 @@ +export { memoryBenchHooks } from '../turn' + +export const memoryBenchOptions = { + iterations: 1, + warmupIterations: 1, + time: 0, + warmupTime: 0, + throws: true, +} + +export function createDeterministicRandom(seed: number) { + let state = seed >>> 0 + + return () => { + state = (state * 1664525 + 1013904223) >>> 0 + return state / 0x100000000 + } +} + +export function randomSegment(random: () => number) { + return Math.floor(random() * 1_000_000_000).toString(36) +} diff --git a/benchmarks/memory/client/benchmark.ts b/benchmarks/memory/client/benchmark.ts new file mode 100644 index 0000000000..463047f4d9 --- /dev/null +++ b/benchmarks/memory/client/benchmark.ts @@ -0,0 +1,11 @@ +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/flame-runner.ts b/benchmarks/memory/client/flame-runner.ts new file mode 100644 index 0000000000..04941fda67 --- /dev/null +++ b/benchmarks/memory/client/flame-runner.ts @@ -0,0 +1,14 @@ +import { profileFlameWorkload } from '../flame-control.ts' +import { window } from './jsdom.ts' +import type { ClientMemoryWorkload } from './benchmark.ts' + +export async function runClientFlameBenchmark(workload: ClientMemoryWorkload) { + try { + await workload.sanity() + await workload.before?.() + await profileFlameWorkload(workload.run, workload.name) + } finally { + await workload.after?.() + window.close() + } +} diff --git a/benchmarks/memory/client/jsdom.ts b/benchmarks/memory/client/jsdom.ts new file mode 100644 index 0000000000..4df480df68 --- /dev/null +++ b/benchmarks/memory/client/jsdom.ts @@ -0,0 +1,51 @@ +import { JSDOM } from 'jsdom' + +const dom = new JSDOM('', { + url: 'http://localhost/', +}) + +const { window } = dom + +function setGlobal(name: string, value: unknown) { + Object.defineProperty(globalThis, name, { + value, + configurable: true, + writable: true, + }) +} + +setGlobal('window', window) +setGlobal('document', window.document) +setGlobal('self', window) +setGlobal('navigator', window.navigator) +setGlobal('location', window.location) +setGlobal('history', window.history) +setGlobal('HTMLElement', window.HTMLElement) +setGlobal('Element', window.Element) +setGlobal('SVGElement', window.SVGElement) +setGlobal('DocumentFragment', window.DocumentFragment) +setGlobal('Node', window.Node) +setGlobal('MouseEvent', window.MouseEvent) +setGlobal('MutationObserver', window.MutationObserver) +setGlobal('sessionStorage', window.sessionStorage) +setGlobal('localStorage', window.localStorage) +setGlobal('getComputedStyle', window.getComputedStyle.bind(window)) + +setGlobal( + 'requestAnimationFrame', + window.requestAnimationFrame?.bind(window) ?? + ((callback: (time: number) => void) => + setTimeout(() => callback(performance.now()), 16)), +) + +setGlobal( + 'cancelAnimationFrame', + window.cancelAnimationFrame?.bind(window) ?? + ((handle: number) => clearTimeout(handle)), +) + +const scrollTo = () => {} +window.scrollTo = scrollTo +setGlobal('scrollTo', scrollTo) + +export { window } diff --git a/benchmarks/memory/client/lifecycle.ts b/benchmarks/memory/client/lifecycle.ts new file mode 100644 index 0000000000..c4a62f0f96 --- /dev/null +++ b/benchmarks/memory/client/lifecycle.ts @@ -0,0 +1,46 @@ +export type Framework = 'react' | 'solid' | 'vue' + +export type MountedApp = { + router: unknown + unmount: () => void +} + +export type MountTestApp = (container: HTMLDivElement) => MountedApp + +const frameworkNames = { + react: 'React', + solid: 'Solid', + vue: 'Vue', +} satisfies Record + +export function noop() {} + +export function warnClientMemoryDevMode(framework: Framework) { + if (process.env.NODE_ENV !== 'production') { + console.warn( + `memory client benchmark is running without NODE_ENV=production; ${frameworkNames[framework]} dev overhead will dominate results.`, + ) + } +} + +export function createBenchContainer() { + const container = document.createElement('div') + document.body.append(container) + + return container +} + +export function removeBenchContainer(container: HTMLDivElement | undefined) { + container?.remove() +} + +export function nextAnimationFrame() { + return new Promise((resolve) => { + requestAnimationFrame(() => resolve()) + }) +} + +export async function drainMicrotasks() { + await Promise.resolve() + await Promise.resolve() +} diff --git a/benchmarks/memory/client/package.json b/benchmarks/memory/client/package.json new file mode 100644 index 0000000000..4dc6246183 --- /dev/null +++ b/benchmarks/memory/client/package.json @@ -0,0 +1,274 @@ +{ + "name": "@benchmarks/memory-client", + "private": true, + "type": "module", + "scripts": { + "clean:profiles": "rm -rf scenarios/*/*/.profiles" + }, + "imports": { + "#memory-client/benchmark": "./benchmark.ts", + "#memory-client/bench-utils": "./bench-utils.ts", + "#memory-client/flame-runner": "./flame-runner.ts", + "#memory-client/lifecycle": "./lifecycle.ts" + }, + "dependencies": { + "@tanstack/react-router": "workspace:*", + "@tanstack/router-core": "workspace:*", + "@tanstack/solid-router": "workspace:*", + "@tanstack/vue-router": "workspace:*", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "solid-js": "^1.9.10", + "vue": "^3.5.16" + }, + "devDependencies": { + "@codspeed/vitest-plugin": "^6.0.1", + "@datadog/pprof": "^5.13.2", + "@platformatic/flame": "^1.6.0", + "@testing-library/react": "^16.2.0", + "@vitejs/plugin-react": "^6.0.1", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "@types/jsdom": "28.0.0", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "jsdom": "29.1.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11", + "vitest": "catalog:" + }, + "nx": { + "targets": { + "build:react": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-client-navigation-churn-react", + "@benchmarks/memory-client-unique-location-churn-react", + "@benchmarks/memory-client-preload-churn-react", + "@benchmarks/memory-client-loader-data-retention-react", + "@benchmarks/memory-client-mount-unmount-react", + "@benchmarks/memory-client-interrupted-navigations-react" + ], + "target": "build:client" + } + ] + }, + "build:solid": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-client-navigation-churn-solid", + "@benchmarks/memory-client-unique-location-churn-solid", + "@benchmarks/memory-client-preload-churn-solid", + "@benchmarks/memory-client-loader-data-retention-solid", + "@benchmarks/memory-client-mount-unmount-solid", + "@benchmarks/memory-client-interrupted-navigations-solid" + ], + "target": "build:client" + } + ] + }, + "build:vue": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-client-navigation-churn-vue", + "@benchmarks/memory-client-unique-location-churn-vue", + "@benchmarks/memory-client-preload-churn-vue", + "@benchmarks/memory-client-loader-data-retention-vue", + "@benchmarks/memory-client-mount-unmount-vue", + "@benchmarks/memory-client-interrupted-navigations-vue" + ], + "target": "build:client" + } + ] + }, + "build:react:flame": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-client-navigation-churn-react", + "@benchmarks/memory-client-unique-location-churn-react", + "@benchmarks/memory-client-preload-churn-react", + "@benchmarks/memory-client-loader-data-retention-react", + "@benchmarks/memory-client-mount-unmount-react", + "@benchmarks/memory-client-interrupted-navigations-react" + ], + "target": "build:client:flame" + } + ] + }, + "build:solid:flame": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-client-navigation-churn-solid", + "@benchmarks/memory-client-unique-location-churn-solid", + "@benchmarks/memory-client-preload-churn-solid", + "@benchmarks/memory-client-loader-data-retention-solid", + "@benchmarks/memory-client-mount-unmount-solid", + "@benchmarks/memory-client-interrupted-navigations-solid" + ], + "target": "build:client:flame" + } + ] + }, + "build:vue:flame": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-client-navigation-churn-vue", + "@benchmarks/memory-client-unique-location-churn-vue", + "@benchmarks/memory-client-preload-churn-vue", + "@benchmarks/memory-client-loader-data-retention-vue", + "@benchmarks/memory-client-mount-unmount-vue", + "@benchmarks/memory-client-interrupted-navigations-vue" + ], + "target": "build:client:flame" + } + ] + }, + "test:flame:react": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-client-navigation-churn-react", + "@benchmarks/memory-client-unique-location-churn-react", + "@benchmarks/memory-client-preload-churn-react", + "@benchmarks/memory-client-loader-data-retention-react", + "@benchmarks/memory-client-mount-unmount-react", + "@benchmarks/memory-client-interrupted-navigations-react" + ], + "target": "test:flame" + } + ] + }, + "test:flame:solid": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-client-navigation-churn-solid", + "@benchmarks/memory-client-unique-location-churn-solid", + "@benchmarks/memory-client-preload-churn-solid", + "@benchmarks/memory-client-loader-data-retention-solid", + "@benchmarks/memory-client-mount-unmount-solid", + "@benchmarks/memory-client-interrupted-navigations-solid" + ], + "target": "test:flame" + } + ] + }, + "test:flame:vue": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-client-navigation-churn-vue", + "@benchmarks/memory-client-unique-location-churn-vue", + "@benchmarks/memory-client-preload-churn-vue", + "@benchmarks/memory-client-loader-data-retention-vue", + "@benchmarks/memory-client-mount-unmount-vue", + "@benchmarks/memory-client-interrupted-navigations-vue" + ], + "target": "test:flame" + } + ] + }, + "test:perf:react": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": [ + "build:react" + ], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", + "cwd": "benchmarks/memory/client" + } + }, + "test:perf:solid": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": [ + "build:solid" + ], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", + "cwd": "benchmarks/memory/client" + } + }, + "test:perf:vue": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": [ + "build:vue" + ], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", + "cwd": "benchmarks/memory/client" + } + }, + "test:types": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-client-navigation-churn-react", + "@benchmarks/memory-client-unique-location-churn-react", + "@benchmarks/memory-client-preload-churn-react", + "@benchmarks/memory-client-loader-data-retention-react", + "@benchmarks/memory-client-mount-unmount-react", + "@benchmarks/memory-client-interrupted-navigations-react", + "@benchmarks/memory-client-navigation-churn-solid", + "@benchmarks/memory-client-unique-location-churn-solid", + "@benchmarks/memory-client-preload-churn-solid", + "@benchmarks/memory-client-loader-data-retention-solid", + "@benchmarks/memory-client-mount-unmount-solid", + "@benchmarks/memory-client-interrupted-navigations-solid", + "@benchmarks/memory-client-navigation-churn-vue", + "@benchmarks/memory-client-unique-location-churn-vue", + "@benchmarks/memory-client-preload-churn-vue", + "@benchmarks/memory-client-loader-data-retention-vue", + "@benchmarks/memory-client-mount-unmount-vue", + "@benchmarks/memory-client-interrupted-navigations-vue" + ], + "target": "test:types:client" + } + ], + "options": { + "command": "tsc -p ./tsconfig.json --noEmit", + "cwd": "benchmarks/memory/client" + }, + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "dependentTaskOutputs", + "{workspaceRoot}/benchmarks/memory/*.ts" + ] + } + } + } +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.flame.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/project.json b/benchmarks/memory/client/scenarios/interrupted-navigations/react/project.json new file mode 100644 index 0000000000..0ed437c9ca --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-interrupted-navigations-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.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "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/memory/client/scenarios/interrupted-navigations/react/setup.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/react/setup.ts new file mode 100644 index 0000000000..6e072ad5f3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/setup.ts @@ -0,0 +1,19 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { + mountTestApp, + resolveAllSlowLoaders, + resolveSlowLoader, + slowLoaderRegistry, +} = (await import(/* @vite-ignore */ appModulePath)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'react', + mountTestApp, + resolveAllSlowLoaders, + resolveSlowLoader, + slowLoaderRegistry, +) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/app.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/app.tsx new file mode 100644 index 0000000000..bd605a78ee --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/app.tsx @@ -0,0 +1,37 @@ +import { RouterProvider } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { getRouter } from './router' + +export { + resolveAllSlowLoaders, + resolveSlowLoader, + slowLoaderRegistry, +} from '../../slow-loaders' + +export function mountTestApp(container: Element) { + const router = getRouter() + const reactRoot = createRoot(container) + let didUnmount = false + + reactRoot.render() + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + reactRoot.unmount() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..475085a433 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as SlowIdRouteImport } from './routes/slow.$id' +import { Route as FastIdRouteImport } from './routes/fast.$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 FastIdRoute = FastIdRouteImport.update({ + id: '/fast/$id', + path: '/fast/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/fast/$id': typeof FastIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/fast/$id': typeof FastIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/fast/$id': typeof FastIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/fast/$id' | '/slow/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/fast/$id' | '/slow/$id' + id: '__root__' | '/' | '/fast/$id' | '/slow/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + FastIdRoute: typeof FastIdRoute + SlowIdRoute: typeof SlowIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + 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 + } + '/fast/$id': { + id: '/fast/$id' + path: '/fast/$id' + fullPath: '/fast/$id' + preLoaderRoute: typeof FastIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + FastIdRoute: FastIdRoute, + SlowIdRoute: SlowIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/router.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/router.tsx new file mode 100644 index 0000000000..ac27b20f79 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/router.tsx @@ -0,0 +1,17 @@ +import { createMemoryHistory, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/__root.tsx new file mode 100644 index 0000000000..889395056b --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/fast.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/fast.$id.tsx new file mode 100644 index 0000000000..d5fd7ade46 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/fast.$id.tsx @@ -0,0 +1,21 @@ +import { createFileRoute } from '@tanstack/react-router' +import { fixedTimestamp } from '../../../slow-loaders' + +export const Route = createFileRoute('/fast/$id')({ + loader: ({ params }) => ({ + id: params.id, + kind: 'fast' as const, + ts: fixedTimestamp, + }), + component: FastComponent, +}) + +function FastComponent() { + const data = Route.useLoaderData() + + return ( +
+ {`${data.kind}:${data.id}:${data.ts}`} +
+ ) +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/index.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/index.tsx new file mode 100644 index 0000000000..a425ac79c4 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
shell
+} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/slow.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/slow.$id.tsx new file mode 100644 index 0000000000..61bbf328b7 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/src/routes/slow.$id.tsx @@ -0,0 +1,21 @@ +import { createFileRoute } from '@tanstack/react-router' +import { getSlowLoaderDeferred } from '../../../slow-loaders' + +export const Route = createFileRoute('/slow/$id')({ + loader: async ({ params }) => { + const deferred = getSlowLoaderDeferred(params.id) + + return await deferred.promise + }, + component: SlowComponent, +}) + +function SlowComponent() { + const data = Route.useLoaderData() + + return ( +
+ {`${data.kind}:${data.id}:${data.ts}`} +
+ ) +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/tsconfig.json b/benchmarks/memory/client/scenarios/interrupted-navigations/react/tsconfig.json new file mode 100644 index 0000000000..ea566061d9 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "allowImportingTsExtensions": true, + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts new file mode 100644 index 0000000000..0f05cedf40 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client interrupted-navigations (react)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts new file mode 100644 index 0000000000..80f234f0c8 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts @@ -0,0 +1,297 @@ +import { + createDeterministicRandom, + randomSegment, +} from '#memory-client/bench-utils' +import { + createBenchContainer, + drainMicrotasks, + nextAnimationFrame, + noop, + removeBenchContainer, + warnClientMemoryDevMode, +} from '#memory-client/lifecycle' +import type { Framework, MountTestApp } from '#memory-client/lifecycle' + +type NavigationSettlement = + | { + status: 'fulfilled' + value: void + } + | { + status: 'rejected' + reason: unknown + } + +type ResolveAllSlowLoaders = () => void +type ResolveSlowLoader = (id: string) => void +type SlowLoaderRegistry = { + has: (id: string) => boolean +} + +type RenderedEvent = { + toLocation: { + pathname: string + } +} + +type InterruptedNavigationRouter = { + load: () => Promise + navigate: (options: { + to: '/fast/$id' | '/slow/$id' + params: { id: string } + replace: true + }) => Promise + subscribe: ( + event: 'onRendered', + listener: (event: RenderedEvent) => void, + ) => () => void +} + +const interruptedNavigationIterations = 150 +const interruptedNavigationPairs = createInterruptedNavigationPairs( + interruptedNavigationIterations, +) + +const uninitialized = () => + Promise.reject( + new Error('interrupted-navigations benchmark is not initialized'), + ) + +const uninitializedSettlement = () => + Promise.resolve({ + status: 'rejected', + reason: new Error('interrupted-navigations benchmark is not initialized'), + }) + +function createInterruptedNavigationPairs(iterations: number) { + const random = createDeterministicRandom(13) + + return Array.from({ length: iterations }, (_, index) => ({ + slowId: `slow-${index}-${randomSegment(random)}`, + fastId: `fast-${index}-${randomSegment(random)}`, + })) +} + +function formatReason(reason: unknown) { + if (reason instanceof Error) { + return `${reason.name}: ${reason.message}` + } + + return String(reason) +} + +function assertSlowNavigationSettlement(settlement: NavigationSettlement) { + if (settlement.status === 'fulfilled') { + if (settlement.value !== undefined) { + throw new Error('Expected slow navigation to fulfill with undefined') + } + + return + } + + if ( + reasonHasAbortShape(settlement.reason) || + reasonHasCancellationShape(settlement.reason) + ) { + return + } + + throw new Error( + `Expected slow navigation to settle as void or cancellation, got ${formatReason( + settlement.reason, + )}`, + ) +} + +function reasonHasAbortShape(reason: unknown) { + return reason instanceof DOMException && reason.name === 'AbortError' +} + +function reasonHasCancellationShape(reason: unknown) { + return ( + reason instanceof Error && + (reason.name === 'AbortError' || reason.name === 'CancelledError') + ) +} + +export function createWorkload( + framework: Framework, + mountTestApp: MountTestApp, + resolveAllSlowLoaders: ResolveAllSlowLoaders, + resolveSlowLoader: ResolveSlowLoader, + slowLoaderRegistry: SlowLoaderRegistry, +) { + warnClientMemoryDevMode(framework) + + let container: HTMLDivElement | undefined = undefined + let unmount = noop + let unsub = noop + let resolveRendered: () => void = noop + let expectedRenderedPath: string | undefined = undefined + let navigateFast: (id: string) => Promise = uninitialized + let startSlowNavigation: (id: string) => Promise = + uninitializedSettlement + + function assertRenderedPage(page: 'shell' | 'fast', id?: string) { + const element = container?.querySelector('[data-bench-page]') + const actualPage = element?.dataset.benchPage + const actualId = element?.dataset.benchId + + if (actualPage !== page) { + throw new Error(`Expected rendered page ${page}, got ${actualPage}`) + } + + if (id !== undefined && actualId !== id) { + throw new Error(`Expected rendered id ${id}, got ${actualId}`) + } + } + + async function waitForRenderedPage(page: 'shell' | 'fast', id?: string) { + for (let attempt = 0; attempt < 10; attempt++) { + try { + assertRenderedPage(page, id) + return + } catch { + await nextAnimationFrame() + } + } + + assertRenderedPage(page, id) + } + + async function waitForSlowLoader(id: string) { + for (let attempt = 0; attempt < 20; attempt++) { + if (slowLoaderRegistry.has(id)) { + return + } + + await drainMicrotasks() + } + + throw new Error(`Slow loader was not registered for id: ${id}`) + } + + function waitForNextRender(pathname: string) { + expectedRenderedPath = pathname + + return new Promise((resolve) => { + resolveRendered = resolve + }) + } + + async function before() { + if (container) { + after() + } + + container = createBenchContainer() + + const mounted = mountTestApp(container) + const router = mounted.router as InterruptedNavigationRouter + unmount = mounted.unmount + + unsub = router.subscribe('onRendered', (event) => { + if ( + expectedRenderedPath && + event.toLocation.pathname !== expectedRenderedPath + ) { + return + } + + const resolve = resolveRendered + resolveRendered = noop + expectedRenderedPath = undefined + resolve() + }) + + navigateFast = async (id) => { + const rendered = waitForNextRender(`/fast/${id}`) + await Promise.all([ + router.navigate({ + to: '/fast/$id', + params: { id }, + replace: true, + }), + rendered, + ]) + } + + startSlowNavigation = (id) => { + const navigation = router.navigate({ + to: '/slow/$id', + params: { id }, + replace: true, + }) + + return navigation + .then((value): NavigationSettlement => ({ status: 'fulfilled', value })) + .catch( + (reason: unknown): NavigationSettlement => ({ + status: 'rejected', + reason, + }), + ) + } + + await router.load() + await waitForRenderedPage('shell') + } + + function after() { + resolveAllSlowLoaders() + unmount() + removeBenchContainer(container) + unsub() + + container = undefined + unmount = noop + unsub = noop + resolveRendered = noop + expectedRenderedPath = undefined + navigateFast = uninitialized + startSlowNavigation = uninitializedSettlement + } + + async function interrupt( + slowId: string, + fastId: string, + assertSettlement = true, + ) { + const slowNavigation = startSlowNavigation(slowId) + + await waitForSlowLoader(slowId) + await navigateFast(fastId) + resolveSlowLoader(slowId) + + const settlement = await slowNavigation + + if (assertSettlement) { + assertSlowNavigationSettlement(settlement) + } + + await drainMicrotasks() + } + + return { + name: `mem client interrupted-navigations (${framework})`, + before, + interrupt, + async run() { + for (const pair of interruptedNavigationPairs) { + await interrupt(pair.slowId, pair.fastId) + } + }, + async sanity() { + await before() + + try { + assertRenderedPage('shell') + await interrupt('sanity-slow', 'sanity-fast', false) + assertRenderedPage('fast', 'sanity-fast') + } finally { + after() + } + }, + after, + } +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/slow-loaders.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/slow-loaders.ts new file mode 100644 index 0000000000..c70ccac3da --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/slow-loaders.ts @@ -0,0 +1,54 @@ +export const fixedTimestamp = 1_700_000_000_000 + +type SlowLoaderPayload = { + id: string + kind: 'slow' + ts: number +} + +type SlowLoaderDeferred = { + promise: Promise + resolve: () => void +} + +export const slowLoaderRegistry = new Map() + +export function getSlowLoaderDeferred(id: string) { + const existing = slowLoaderRegistry.get(id) + + if (existing) { + return existing + } + + let resolvePromise!: (payload: SlowLoaderPayload) => void + const promise = new Promise((resolve) => { + resolvePromise = resolve + }) + + const deferred: SlowLoaderDeferred = { + promise, + resolve() { + slowLoaderRegistry.delete(id) + resolvePromise({ id, kind: 'slow', ts: fixedTimestamp }) + }, + } + + slowLoaderRegistry.set(id, deferred) + return deferred +} + +export function resolveSlowLoader(id: string) { + const deferred = slowLoaderRegistry.get(id) + + if (!deferred) { + throw new Error(`No pending slow loader for id: ${id}`) + } + + deferred.resolve() +} + +export function resolveAllSlowLoaders() { + for (const id of Array.from(slowLoaderRegistry.keys())) { + resolveSlowLoader(id) + } +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.flame.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/project.json b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/project.json new file mode 100644 index 0000000000..4aff39500e --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-interrupted-navigations-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.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "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/memory/client/scenarios/interrupted-navigations/solid/setup.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/setup.ts new file mode 100644 index 0000000000..e736111663 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/setup.ts @@ -0,0 +1,19 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { + mountTestApp, + resolveAllSlowLoaders, + resolveSlowLoader, + slowLoaderRegistry, +} = (await import(/* @vite-ignore */ appModulePath)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'solid', + mountTestApp, + resolveAllSlowLoaders, + resolveSlowLoader, + slowLoaderRegistry, +) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/app.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/app.tsx new file mode 100644 index 0000000000..6288b5fab1 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/app.tsx @@ -0,0 +1,35 @@ +import { RouterProvider } from '@tanstack/solid-router' +import { render } from 'solid-js/web' +import { getRouter } from './router' + +export { + resolveAllSlowLoaders, + resolveSlowLoader, + slowLoaderRegistry, +} from '../../slow-loaders' + +export function mountTestApp(container: Element) { + const router = getRouter() + const dispose = render(() => , container) + let didUnmount = false + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + dispose() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..f42255963c --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as SlowIdRouteImport } from './routes/slow.$id' +import { Route as FastIdRouteImport } from './routes/fast.$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 FastIdRoute = FastIdRouteImport.update({ + id: '/fast/$id', + path: '/fast/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/fast/$id': typeof FastIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/fast/$id': typeof FastIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/fast/$id': typeof FastIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/fast/$id' | '/slow/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/fast/$id' | '/slow/$id' + id: '__root__' | '/' | '/fast/$id' | '/slow/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + FastIdRoute: typeof FastIdRoute + SlowIdRoute: typeof SlowIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + 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 + } + '/fast/$id': { + id: '/fast/$id' + path: '/fast/$id' + fullPath: '/fast/$id' + preLoaderRoute: typeof FastIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + FastIdRoute: FastIdRoute, + SlowIdRoute: SlowIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/router.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/router.tsx new file mode 100644 index 0000000000..884aa3438f --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/router.tsx @@ -0,0 +1,17 @@ +import { createMemoryHistory, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..cb8d5a688d --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/fast.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/fast.$id.tsx new file mode 100644 index 0000000000..511e4712b7 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/fast.$id.tsx @@ -0,0 +1,21 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { fixedTimestamp } from '../../../slow-loaders' + +export const Route = createFileRoute('/fast/$id')({ + loader: ({ params }) => ({ + id: params.id, + kind: 'fast' as const, + ts: fixedTimestamp, + }), + component: FastComponent, +}) + +function FastComponent() { + const data = Route.useLoaderData() + + return ( +
+ {`${data().kind}:${data().id}:${data().ts}`} +
+ ) +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/index.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/index.tsx new file mode 100644 index 0000000000..592b2d666e --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
shell
+} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/slow.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/slow.$id.tsx new file mode 100644 index 0000000000..9aaaef5568 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/src/routes/slow.$id.tsx @@ -0,0 +1,21 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { getSlowLoaderDeferred } from '../../../slow-loaders' + +export const Route = createFileRoute('/slow/$id')({ + loader: async ({ params }) => { + const deferred = getSlowLoaderDeferred(params.id) + + return await deferred.promise + }, + component: SlowComponent, +}) + +function SlowComponent() { + const data = Route.useLoaderData() + + return ( +
+ {`${data().kind}:${data().id}:${data().ts}`} +
+ ) +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/tsconfig.json b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/tsconfig.json new file mode 100644 index 0000000000..b12dcb7ade --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts new file mode 100644 index 0000000000..26ff0b5c8c --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client interrupted-navigations (solid)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.flame.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/project.json b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/project.json new file mode 100644 index 0000000000..01288cb235 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-interrupted-navigations-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/setup.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/setup.ts new file mode 100644 index 0000000000..260e45b64b --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/setup.ts @@ -0,0 +1,19 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { + mountTestApp, + resolveAllSlowLoaders, + resolveSlowLoader, + slowLoaderRegistry, +} = (await import(/* @vite-ignore */ appModulePath)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'vue', + mountTestApp, + resolveAllSlowLoaders, + resolveSlowLoader, + slowLoaderRegistry, +) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/app.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/app.tsx new file mode 100644 index 0000000000..1abb4410dc --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/app.tsx @@ -0,0 +1,42 @@ +import { RouterProvider } from '@tanstack/vue-router' +import { createApp } from 'vue' +import { getRouter } from './router' +import type {} from '@tanstack/router-core' + +export { + resolveAllSlowLoaders, + resolveSlowLoader, + slowLoaderRegistry, +} from '../../slow-loaders' + +export function mountTestApp(container: Element) { + const router = getRouter() + const vueApp = createApp({ + setup() { + return () => + }, + }) + let didUnmount = false + + vueApp.mount(container) + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + vueApp.unmount() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..5ea61a89a3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as SlowIdRouteImport } from './routes/slow.$id' +import { Route as FastIdRouteImport } from './routes/fast.$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 FastIdRoute = FastIdRouteImport.update({ + id: '/fast/$id', + path: '/fast/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/fast/$id': typeof FastIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/fast/$id': typeof FastIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/fast/$id': typeof FastIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/fast/$id' | '/slow/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/fast/$id' | '/slow/$id' + id: '__root__' | '/' | '/fast/$id' | '/slow/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + FastIdRoute: typeof FastIdRoute + SlowIdRoute: typeof SlowIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + 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 + } + '/fast/$id': { + id: '/fast/$id' + path: '/fast/$id' + fullPath: '/fast/$id' + preLoaderRoute: typeof FastIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + FastIdRoute: FastIdRoute, + SlowIdRoute: SlowIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/router.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/router.tsx new file mode 100644 index 0000000000..4655fe8424 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/router.tsx @@ -0,0 +1,17 @@ +import { createMemoryHistory, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..91296e6f84 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/fast.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/fast.$id.tsx new file mode 100644 index 0000000000..f6dc9ac3bd --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/fast.$id.tsx @@ -0,0 +1,24 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { fixedTimestamp } from '../../../slow-loaders' + +const FastComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+ {`${data.value.kind}:${data.value.id}:${data.value.ts}`} +
+ ) + }, +}) + +export const Route = createFileRoute('/fast/$id')({ + loader: ({ params }: { params: { id: string } }) => ({ + id: params.id, + kind: 'fast' as const, + ts: fixedTimestamp, + }), + component: FastComponent, +}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/index.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/index.tsx new file mode 100644 index 0000000000..c30a51e1e5 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
shell
+} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/slow.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/slow.$id.tsx new file mode 100644 index 0000000000..3b5bb75ede --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/slow.$id.tsx @@ -0,0 +1,24 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { getSlowLoaderDeferred } from '../../../slow-loaders' + +const SlowComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+ {`${data.value.kind}:${data.value.id}:${data.value.ts}`} +
+ ) + }, +}) + +export const Route = createFileRoute('/slow/$id')({ + loader: async ({ params }: { params: { id: string } }) => { + const deferred = getSlowLoaderDeferred(params.id) + + return await deferred.promise + }, + component: SlowComponent, +}) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/tsconfig.json b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/tsconfig.json new file mode 100644 index 0000000000..9a5872a4c0 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts new file mode 100644 index 0000000000..02574908d2 --- /dev/null +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client interrupted-navigations (vue)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/loader-data.ts b/benchmarks/memory/client/scenarios/loader-data-retention/loader-data.ts new file mode 100644 index 0000000000..3bd59c82ef --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/loader-data.ts @@ -0,0 +1,48 @@ +import { + createDeterministicRandom, + randomSegment, +} from '#memory-client/bench-utils' + +export const loaderPayloadRecordCount = 512 + +const loaderPayloadCharsPerRecord = 1024 + +type LoaderRecord = { + key: string + value: string +} + +export function createLoaderData(id: string) { + const random = createDeterministicRandom(hashId(id)) + const records: Array = [] + + for (let index = 0; index < loaderPayloadRecordCount; index++) { + records.push({ + key: `${id}:${index}:${randomSegment(random)}`, + value: createRecordValue(id, index, random), + }) + } + + return { id, records } +} + +function createRecordValue(id: string, index: number, random: () => number) { + const firstSegment = randomSegment(random) + const secondSegment = randomSegment(random) + const segment = `${id}:${index}:${firstSegment}:${secondSegment}:` + + return segment + .repeat(Math.ceil(loaderPayloadCharsPerRecord / segment.length)) + .slice(0, loaderPayloadCharsPerRecord) +} + +function hashId(id: string) { + let hash = 2166136261 + + for (let index = 0; index < id.length; index++) { + hash ^= id.charCodeAt(index) + hash = Math.imul(hash, 16777619) + } + + return hash >>> 0 +} 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 new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.flame.ts b/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/project.json b/benchmarks/memory/client/scenarios/loader-data-retention/react/project.json new file mode 100644 index 0000000000..713038e20f --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-loader-data-retention-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.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "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/memory/client/scenarios/loader-data-retention/react/setup.ts b/benchmarks/memory/client/scenarios/loader-data-retention/react/setup.ts new file mode 100644 index 0000000000..fafaf13e6f --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/setup.ts @@ -0,0 +1,14 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { loaderPayloadRecordCount, mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'react', + mountTestApp, + loaderPayloadRecordCount, +) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/app.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/app.tsx new file mode 100644 index 0000000000..5eef150c2c --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/app.tsx @@ -0,0 +1,33 @@ +import { RouterProvider } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { getRouter } from './router' + +export { loaderPayloadRecordCount } from '../../loader-data' + +export function mountTestApp(container: Element) { + const router = getRouter() + const reactRoot = createRoot(container) + let didUnmount = false + + reactRoot.render() + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + reactRoot.unmount() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..ea96d809c8 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routeTree.gen.ts @@ -0,0 +1,102 @@ +/* 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 ShellRouteImport } from './routes/shell' +import { Route as PageIdRouteImport } from './routes/page.$id' +import { Route as ShellIndexRouteImport } from './routes/shell.index' + +const ShellRoute = ShellRouteImport.update({ + id: '/shell', + path: '/shell', + getParentRoute: () => rootRouteImport, +} as any) +const PageIdRoute = PageIdRouteImport.update({ + id: '/page/$id', + path: '/page/$id', + getParentRoute: () => rootRouteImport, +} as any) +const ShellIndexRoute = ShellIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => ShellRoute, +} as any) + +export interface FileRoutesByFullPath { + '/shell': typeof ShellRouteWithChildren + '/page/$id': typeof PageIdRoute + '/shell/': typeof ShellIndexRoute +} +export interface FileRoutesByTo { + '/page/$id': typeof PageIdRoute + '/shell': typeof ShellIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/shell': typeof ShellRouteWithChildren + '/page/$id': typeof PageIdRoute + '/shell/': typeof ShellIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/shell' | '/page/$id' | '/shell/' + fileRoutesByTo: FileRoutesByTo + to: '/page/$id' | '/shell' + id: '__root__' | '/shell' | '/page/$id' | '/shell/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ShellRoute: typeof ShellRouteWithChildren + PageIdRoute: typeof PageIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/shell': { + id: '/shell' + path: '/shell' + fullPath: '/shell' + preLoaderRoute: typeof ShellRouteImport + parentRoute: typeof rootRouteImport + } + '/page/$id': { + id: '/page/$id' + path: '/page/$id' + fullPath: '/page/$id' + preLoaderRoute: typeof PageIdRouteImport + parentRoute: typeof rootRouteImport + } + '/shell/': { + id: '/shell/' + path: '/' + fullPath: '/shell/' + preLoaderRoute: typeof ShellIndexRouteImport + parentRoute: typeof ShellRoute + } + } +} + +interface ShellRouteChildren { + ShellIndexRoute: typeof ShellIndexRoute +} + +const ShellRouteChildren: ShellRouteChildren = { + ShellIndexRoute: ShellIndexRoute, +} + +const ShellRouteWithChildren = ShellRoute._addFileChildren(ShellRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + ShellRoute: ShellRouteWithChildren, + PageIdRoute: PageIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/router.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/router.tsx new file mode 100644 index 0000000000..5a5c8210d9 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/router.tsx @@ -0,0 +1,19 @@ +import { createMemoryHistory, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/shell'], + }), + routeTree, + defaultGcTime: 0, + defaultPreloadGcTime: 0, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/__root.tsx new file mode 100644 index 0000000000..889395056b --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/page.$id.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/page.$id.tsx new file mode 100644 index 0000000000..63af9ed429 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/page.$id.tsx @@ -0,0 +1,21 @@ +import { createFileRoute } from '@tanstack/react-router' +import { createLoaderData } from '../../../loader-data' + +export const Route = createFileRoute('/page/$id')({ + loader: ({ params }) => createLoaderData(params.id), + component: PageComponent, +}) + +function PageComponent() { + const data = Route.useLoaderData() + + return ( +
+ {`${data.id}:${data.records.length}`} +
+ ) +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.index.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.index.tsx new file mode 100644 index 0000000000..d78bb8bfb9 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/shell/')({ + component: ShellIndexComponent, +}) + +function ShellIndexComponent() { + return
ready
+} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.tsx new file mode 100644 index 0000000000..024a58c243 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/src/routes/shell.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/shell')({ + component: ShellComponent, +}) + +function ShellComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/tsconfig.json b/benchmarks/memory/client/scenarios/loader-data-retention/react/tsconfig.json new file mode 100644 index 0000000000..ea566061d9 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "allowImportingTsExtensions": true, + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/vite.config.ts b/benchmarks/memory/client/scenarios/loader-data-retention/react/vite.config.ts new file mode 100644 index 0000000000..8630417936 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client loader-data-retention (react)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/shared.ts b/benchmarks/memory/client/scenarios/loader-data-retention/shared.ts new file mode 100644 index 0000000000..bd90c023f0 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/shared.ts @@ -0,0 +1,187 @@ +import { + createDeterministicRandom, + randomSegment, +} from '#memory-client/bench-utils' +import { + createBenchContainer, + nextAnimationFrame, + noop, + removeBenchContainer, + warnClientMemoryDevMode, +} from '#memory-client/lifecycle' +import type { Framework, MountTestApp } from '#memory-client/lifecycle' + +type RenderEvent = { + toLocation: { + pathname: string + } +} + +type LoaderDataRouter = { + load: () => Promise + navigate: (options: { + to: '/page/$id' + params: { id: string } + replace: true + }) => Promise + subscribe: ( + event: 'onRendered', + listener: (event: RenderEvent) => void, + ) => () => void +} + +const loaderDataRetentionNavigationCount = 20 +const pageIds = createPageIds() + +const uninitialized = () => + Promise.reject( + new Error('loader-data-retention benchmark is not initialized'), + ) + +function createPageIds() { + const random = createDeterministicRandom(11) + + return Array.from( + { length: loaderDataRetentionNavigationCount }, + (_, index) => `${index}-${randomSegment(random)}`, + ) +} + +export function createWorkload( + framework: Framework, + mountTestApp: MountTestApp, + loaderPayloadRecordCount: number, +) { + warnClientMemoryDevMode(framework) + + let container: HTMLDivElement | undefined = undefined + let unmount = noop + let unsub = noop + let resolveRendered: () => void = noop + let expectedRenderedPath: string | undefined = undefined + let navigateTo: (id: string) => Promise = uninitialized + + function assertRenderedShell() { + const actual = + container?.querySelector('[data-bench-page]')?.dataset + .benchPage + + if (actual !== 'shell') { + throw new Error(`Expected rendered shell page, got ${actual}`) + } + } + + function assertRenderedPage(id: string) { + const page = container?.querySelector( + '[data-bench-page="page"]', + ) + const actualId = page?.dataset.benchId + const actualCount = page?.dataset.benchCount + const expectedCount = String(loaderPayloadRecordCount) + + if (actualId !== id || actualCount !== expectedCount) { + throw new Error( + `Expected rendered page ${id}:${expectedCount}, got ${actualId}:${actualCount}`, + ) + } + } + + async function waitForRenderedShell() { + for (let attempt = 0; attempt < 10; attempt++) { + try { + assertRenderedShell() + return + } catch { + await nextAnimationFrame() + } + } + + assertRenderedShell() + } + + function waitForNextRender(pathname: string) { + expectedRenderedPath = pathname + + return new Promise((resolve) => { + resolveRendered = resolve + }) + } + + async function before() { + if (container) { + after() + } + + container = createBenchContainer() + + const mounted = mountTestApp(container) + const router = mounted.router as LoaderDataRouter + unmount = mounted.unmount + + unsub = router.subscribe('onRendered', (event) => { + if ( + expectedRenderedPath && + event.toLocation.pathname !== expectedRenderedPath + ) { + return + } + + const resolve = resolveRendered + resolveRendered = noop + expectedRenderedPath = undefined + resolve() + }) + + navigateTo = async (id) => { + const pathname = `/page/${id}` + const rendered = waitForNextRender(pathname) + + await router.navigate({ + to: '/page/$id', + params: { id }, + replace: true, + }) + await rendered + assertRenderedPage(id) + } + + await router.load() + await waitForRenderedShell() + } + + function after() { + unmount() + removeBenchContainer(container) + unsub() + + container = undefined + unmount = noop + unsub = noop + resolveRendered = noop + expectedRenderedPath = undefined + navigateTo = uninitialized + } + + return { + name: `mem client loader-data-retention (${framework})`, + before, + navigate: (id: string) => navigateTo(id), + async run() { + for (const id of pageIds) { + await navigateTo(id) + } + }, + async sanity() { + await before() + + try { + assertRenderedShell() + await navigateTo('sanity-a') + assertRenderedPage('sanity-a') + } finally { + after() + } + }, + after, + } +} 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 new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.flame.ts b/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/project.json b/benchmarks/memory/client/scenarios/loader-data-retention/solid/project.json new file mode 100644 index 0000000000..6c85f51896 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-loader-data-retention-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.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "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/memory/client/scenarios/loader-data-retention/solid/setup.ts b/benchmarks/memory/client/scenarios/loader-data-retention/solid/setup.ts new file mode 100644 index 0000000000..b7c80a3e49 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/setup.ts @@ -0,0 +1,14 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { loaderPayloadRecordCount, mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'solid', + mountTestApp, + loaderPayloadRecordCount, +) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/app.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/app.tsx new file mode 100644 index 0000000000..4315a4b15c --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/app.tsx @@ -0,0 +1,31 @@ +import { RouterProvider } from '@tanstack/solid-router' +import { render } from 'solid-js/web' +import { getRouter } from './router' + +export { loaderPayloadRecordCount } from '../../loader-data' + +export function mountTestApp(container: Element) { + const router = getRouter() + const dispose = render(() => , container) + let didUnmount = false + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + dispose() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..a1946d187d --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routeTree.gen.ts @@ -0,0 +1,102 @@ +/* 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 ShellRouteImport } from './routes/shell' +import { Route as ShellIndexRouteImport } from './routes/shell.index' +import { Route as PageIdRouteImport } from './routes/page.$id' + +const ShellRoute = ShellRouteImport.update({ + id: '/shell', + path: '/shell', + getParentRoute: () => rootRouteImport, +} as any) +const ShellIndexRoute = ShellIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => ShellRoute, +} as any) +const PageIdRoute = PageIdRouteImport.update({ + id: '/page/$id', + path: '/page/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/shell': typeof ShellRouteWithChildren + '/page/$id': typeof PageIdRoute + '/shell/': typeof ShellIndexRoute +} +export interface FileRoutesByTo { + '/page/$id': typeof PageIdRoute + '/shell': typeof ShellIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/shell': typeof ShellRouteWithChildren + '/page/$id': typeof PageIdRoute + '/shell/': typeof ShellIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/shell' | '/page/$id' | '/shell/' + fileRoutesByTo: FileRoutesByTo + to: '/page/$id' | '/shell' + id: '__root__' | '/shell' | '/page/$id' | '/shell/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ShellRoute: typeof ShellRouteWithChildren + PageIdRoute: typeof PageIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/shell': { + id: '/shell' + path: '/shell' + fullPath: '/shell' + preLoaderRoute: typeof ShellRouteImport + parentRoute: typeof rootRouteImport + } + '/shell/': { + id: '/shell/' + path: '/' + fullPath: '/shell/' + preLoaderRoute: typeof ShellIndexRouteImport + parentRoute: typeof ShellRoute + } + '/page/$id': { + id: '/page/$id' + path: '/page/$id' + fullPath: '/page/$id' + preLoaderRoute: typeof PageIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +interface ShellRouteChildren { + ShellIndexRoute: typeof ShellIndexRoute +} + +const ShellRouteChildren: ShellRouteChildren = { + ShellIndexRoute: ShellIndexRoute, +} + +const ShellRouteWithChildren = ShellRoute._addFileChildren(ShellRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + ShellRoute: ShellRouteWithChildren, + PageIdRoute: PageIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/router.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/router.tsx new file mode 100644 index 0000000000..06afdb10d3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/router.tsx @@ -0,0 +1,19 @@ +import { createMemoryHistory, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/shell'], + }), + routeTree, + defaultGcTime: 0, + defaultPreloadGcTime: 0, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..cb8d5a688d --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/page.$id.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/page.$id.tsx new file mode 100644 index 0000000000..fb6c438fa5 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/page.$id.tsx @@ -0,0 +1,21 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { createLoaderData } from '../../../loader-data' + +export const Route = createFileRoute('/page/$id')({ + loader: ({ params }) => createLoaderData(params.id), + component: PageComponent, +}) + +function PageComponent() { + const data = Route.useLoaderData() + + return ( +
+ {`${data().id}:${data().records.length}`} +
+ ) +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.index.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.index.tsx new file mode 100644 index 0000000000..2f4f5daee2 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/shell/')({ + component: ShellIndexComponent, +}) + +function ShellIndexComponent() { + return
ready
+} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.tsx new file mode 100644 index 0000000000..c1e38a1aaf --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/src/routes/shell.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/shell')({ + component: ShellComponent, +}) + +function ShellComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/tsconfig.json b/benchmarks/memory/client/scenarios/loader-data-retention/solid/tsconfig.json new file mode 100644 index 0000000000..b12dcb7ade --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/vite.config.ts b/benchmarks/memory/client/scenarios/loader-data-retention/solid/vite.config.ts new file mode 100644 index 0000000000..5dfd5b53fe --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client loader-data-retention (solid)', + watch: false, + environment: 'jsdom', + }, +}) 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 new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.flame.ts b/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/project.json b/benchmarks/memory/client/scenarios/loader-data-retention/vue/project.json new file mode 100644 index 0000000000..22504c906f --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-loader-data-retention-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/setup.ts b/benchmarks/memory/client/scenarios/loader-data-retention/vue/setup.ts new file mode 100644 index 0000000000..a83a1f70d1 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/setup.ts @@ -0,0 +1,14 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { loaderPayloadRecordCount, mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'vue', + mountTestApp, + loaderPayloadRecordCount, +) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/app.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/app.tsx new file mode 100644 index 0000000000..c843b4feb5 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/app.tsx @@ -0,0 +1,38 @@ +import { RouterProvider } from '@tanstack/vue-router' +import { createApp } from 'vue' +import { getRouter } from './router' +import type {} from '@tanstack/router-core' + +export { loaderPayloadRecordCount } from '../../loader-data' + +export function mountTestApp(container: Element) { + const router = getRouter() + const vueApp = createApp({ + setup() { + return () => + }, + }) + let didUnmount = false + + vueApp.mount(container) + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + vueApp.unmount() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..5b09d365e7 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routeTree.gen.ts @@ -0,0 +1,102 @@ +/* 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 ShellRouteImport } from './routes/shell' +import { Route as PageIdRouteImport } from './routes/page.$id' +import { Route as ShellIndexRouteImport } from './routes/shell.index' + +const ShellRoute = ShellRouteImport.update({ + id: '/shell', + path: '/shell', + getParentRoute: () => rootRouteImport, +} as any) +const PageIdRoute = PageIdRouteImport.update({ + id: '/page/$id', + path: '/page/$id', + getParentRoute: () => rootRouteImport, +} as any) +const ShellIndexRoute = ShellIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => ShellRoute, +} as any) + +export interface FileRoutesByFullPath { + '/shell': typeof ShellRouteWithChildren + '/page/$id': typeof PageIdRoute + '/shell/': typeof ShellIndexRoute +} +export interface FileRoutesByTo { + '/page/$id': typeof PageIdRoute + '/shell': typeof ShellIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/shell': typeof ShellRouteWithChildren + '/page/$id': typeof PageIdRoute + '/shell/': typeof ShellIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/shell' | '/page/$id' | '/shell/' + fileRoutesByTo: FileRoutesByTo + to: '/page/$id' | '/shell' + id: '__root__' | '/shell' | '/page/$id' | '/shell/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ShellRoute: typeof ShellRouteWithChildren + PageIdRoute: typeof PageIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/shell': { + id: '/shell' + path: '/shell' + fullPath: '/shell' + preLoaderRoute: typeof ShellRouteImport + parentRoute: typeof rootRouteImport + } + '/page/$id': { + id: '/page/$id' + path: '/page/$id' + fullPath: '/page/$id' + preLoaderRoute: typeof PageIdRouteImport + parentRoute: typeof rootRouteImport + } + '/shell/': { + id: '/shell/' + path: '/' + fullPath: '/shell/' + preLoaderRoute: typeof ShellIndexRouteImport + parentRoute: typeof ShellRoute + } + } +} + +interface ShellRouteChildren { + ShellIndexRoute: typeof ShellIndexRoute +} + +const ShellRouteChildren: ShellRouteChildren = { + ShellIndexRoute: ShellIndexRoute, +} + +const ShellRouteWithChildren = ShellRoute._addFileChildren(ShellRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + ShellRoute: ShellRouteWithChildren, + PageIdRoute: PageIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/router.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/router.tsx new file mode 100644 index 0000000000..84286e1dae --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/router.tsx @@ -0,0 +1,19 @@ +import { createMemoryHistory, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/shell'], + }), + routeTree, + defaultGcTime: 0, + defaultPreloadGcTime: 0, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..91296e6f84 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/page.$id.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/page.$id.tsx new file mode 100644 index 0000000000..38f1d2614c --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/page.$id.tsx @@ -0,0 +1,25 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { createLoaderData } from '../../../loader-data' + +const PageComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+ {`${data.value.id}:${data.value.records.length}`} +
+ ) + }, +}) + +export const Route = createFileRoute('/page/$id')({ + loader: ({ params }: { params: { id: string } }) => + createLoaderData(params.id), + component: PageComponent, +}) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.index.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.index.tsx new file mode 100644 index 0000000000..640ffeeb5c --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/shell/')({ + component: ShellIndexComponent, +}) + +function ShellIndexComponent() { + return
ready
+} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.tsx new file mode 100644 index 0000000000..f8a598bc34 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/shell.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/shell')({ + component: ShellComponent, +}) + +function ShellComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/tsconfig.json b/benchmarks/memory/client/scenarios/loader-data-retention/vue/tsconfig.json new file mode 100644 index 0000000000..9a5872a4c0 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/vite.config.ts b/benchmarks/memory/client/scenarios/loader-data-retention/vue/vite.config.ts new file mode 100644 index 0000000000..006636eaa0 --- /dev/null +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client loader-data-retention (vue)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.flame.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/project.json b/benchmarks/memory/client/scenarios/mount-unmount/react/project.json new file mode 100644 index 0000000000..05d8aaa4bf --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-mount-unmount-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.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "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/memory/client/scenarios/mount-unmount/react/setup.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/setup.ts new file mode 100644 index 0000000000..70603b5c34 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/setup.ts @@ -0,0 +1,13 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'react', + mountTestApp, +) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/src/app.tsx b/benchmarks/memory/client/scenarios/mount-unmount/react/src/app.tsx new file mode 100644 index 0000000000..bdf76eaa24 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/src/app.tsx @@ -0,0 +1,29 @@ +import { RouterProvider } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { getRouter } from './router' + +export function mountTestApp(container: Element) { + const router = getRouter() + const reactRoot = createRoot(container) + let didUnmount = false + + reactRoot.render() + + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + reactRoot.unmount() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..5efcb2cf72 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/src/routeTree.gen.ts @@ -0,0 +1,59 @@ +/* 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 ARouteImport } from './routes/a' + +const ARoute = ARouteImport.update({ + id: '/a', + path: '/a', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/a': typeof ARoute +} +export interface FileRoutesByTo { + '/a': typeof ARoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/a': typeof ARoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/a' + fileRoutesByTo: FileRoutesByTo + to: '/a' + id: '__root__' | '/a' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/a': { + id: '/a' + path: '/a' + fullPath: '/a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/src/router.tsx b/benchmarks/memory/client/scenarios/mount-unmount/react/src/router.tsx new file mode 100644 index 0000000000..9cb85c5a1b --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/src/router.tsx @@ -0,0 +1,17 @@ +import { createMemoryHistory, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/a'], + }), + routeTree, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/__root.tsx new file mode 100644 index 0000000000..889395056b --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/a.tsx b/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/a.tsx new file mode 100644 index 0000000000..1e268d3c42 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/src/routes/a.tsx @@ -0,0 +1,12 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/a')({ + loader: () => ({ id: 'a' }), + component: AComponent, +}) + +function AComponent() { + const data = Route.useLoaderData() + + return
{data.id}
+} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/tsconfig.json b/benchmarks/memory/client/scenarios/mount-unmount/react/tsconfig.json new file mode 100644 index 0000000000..ea566061d9 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "allowImportingTsExtensions": true, + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts new file mode 100644 index 0000000000..a08352a837 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client mount-unmount (react)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/shared.ts b/benchmarks/memory/client/scenarios/mount-unmount/shared.ts new file mode 100644 index 0000000000..01cfe8c46a --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/shared.ts @@ -0,0 +1,74 @@ +import { + createBenchContainer, + drainMicrotasks, + noop, + removeBenchContainer, + warnClientMemoryDevMode, +} from '#memory-client/lifecycle' +import type { Framework, MountTestApp } from '#memory-client/lifecycle' + +type RenderRouter = { + load: () => Promise + subscribe: (event: 'onRendered', listener: () => void) => () => void +} + +const mountUnmountIterations = 100 + +function assertEmptyBody() { + if (document.body.childNodes.length !== 0) { + throw new Error( + `Expected document.body to be empty, found ${document.body.childNodes.length} child node(s)`, + ) + } +} + +export function createWorkload( + framework: Framework, + mountTestApp: MountTestApp, +) { + warnClientMemoryDevMode(framework) + + async function cycle() { + const container = createBenchContainer() + + let unmount = noop + let unsubscribe = noop + + try { + const mounted = mountTestApp(container) + const router = mounted.router as RenderRouter + unmount = mounted.unmount + + const rendered = new Promise((resolve) => { + unsubscribe = router.subscribe('onRendered', () => { + resolve() + }) + }) + + await router.load() + await rendered + unsubscribe() + unsubscribe = noop + } finally { + unmount() + removeBenchContainer(container) + unsubscribe() + await drainMicrotasks() + } + } + + return { + name: `mem client mount-unmount (${framework})`, + cycle, + async run() { + for (let index = 0; index < mountUnmountIterations; index++) { + await cycle() + } + }, + async sanity() { + assertEmptyBody() + await cycle() + assertEmptyBody() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.flame.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/project.json b/benchmarks/memory/client/scenarios/mount-unmount/solid/project.json new file mode 100644 index 0000000000..63e8e950db --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-mount-unmount-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.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "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/memory/client/scenarios/mount-unmount/solid/setup.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/setup.ts new file mode 100644 index 0000000000..493425c6a2 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/setup.ts @@ -0,0 +1,13 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'solid', + mountTestApp, +) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/app.tsx b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/app.tsx new file mode 100644 index 0000000000..b23bc126d5 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/app.tsx @@ -0,0 +1,27 @@ +import { RouterProvider } from '@tanstack/solid-router' +import { render } from 'solid-js/web' +import { getRouter } from './router' + +export function mountTestApp(container: Element) { + const router = getRouter() + const dispose = render(() => , container) + let didUnmount = false + + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + dispose() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..a3f9739290 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routeTree.gen.ts @@ -0,0 +1,59 @@ +/* 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 ARouteImport } from './routes/a' + +const ARoute = ARouteImport.update({ + id: '/a', + path: '/a', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/a': typeof ARoute +} +export interface FileRoutesByTo { + '/a': typeof ARoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/a': typeof ARoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/a' + fileRoutesByTo: FileRoutesByTo + to: '/a' + id: '__root__' | '/a' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/a': { + id: '/a' + path: '/a' + fullPath: '/a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/router.tsx b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/router.tsx new file mode 100644 index 0000000000..e8c14f12f6 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/router.tsx @@ -0,0 +1,17 @@ +import { createMemoryHistory, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/a'], + }), + routeTree, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..cb8d5a688d --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/a.tsx b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/a.tsx new file mode 100644 index 0000000000..36c4be538c --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/src/routes/a.tsx @@ -0,0 +1,12 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/a')({ + loader: () => ({ id: 'a' }), + component: AComponent, +}) + +function AComponent() { + const data = Route.useLoaderData() + + return
{data().id}
+} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/tsconfig.json b/benchmarks/memory/client/scenarios/mount-unmount/solid/tsconfig.json new file mode 100644 index 0000000000..b12dcb7ade --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts new file mode 100644 index 0000000000..33699639de --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client mount-unmount (solid)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.flame.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/project.json b/benchmarks/memory/client/scenarios/mount-unmount/vue/project.json new file mode 100644 index 0000000000..157673cf16 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-mount-unmount-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/setup.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/setup.ts new file mode 100644 index 0000000000..a38df04788 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/setup.ts @@ -0,0 +1,13 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'vue', + mountTestApp, +) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/app.tsx b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/app.tsx new file mode 100644 index 0000000000..27b82fcbe1 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/app.tsx @@ -0,0 +1,34 @@ +import { RouterProvider } from '@tanstack/vue-router' +import { createApp } from 'vue' +import { getRouter } from './router' +import type {} from '@tanstack/router-core' + +export function mountTestApp(container: Element) { + const router = getRouter() + const vueApp = createApp({ + setup() { + return () => + }, + }) + let didUnmount = false + + vueApp.mount(container) + + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + vueApp.unmount() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..1a54b81033 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routeTree.gen.ts @@ -0,0 +1,59 @@ +/* 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 ARouteImport } from './routes/a' + +const ARoute = ARouteImport.update({ + id: '/a', + path: '/a', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/a': typeof ARoute +} +export interface FileRoutesByTo { + '/a': typeof ARoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/a': typeof ARoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/a' + fileRoutesByTo: FileRoutesByTo + to: '/a' + id: '__root__' | '/a' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/a': { + id: '/a' + path: '/a' + fullPath: '/a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/router.tsx b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/router.tsx new file mode 100644 index 0000000000..e083495cd2 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/router.tsx @@ -0,0 +1,17 @@ +import { createMemoryHistory, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/a'], + }), + routeTree, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..91296e6f84 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/a.tsx b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/a.tsx new file mode 100644 index 0000000000..0dd650e1dd --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/a.tsx @@ -0,0 +1,15 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const AComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () =>
{data.value.id}
+ }, +}) + +export const Route = createFileRoute('/a')({ + loader: () => ({ id: 'a' }), + component: AComponent, +}) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/tsconfig.json b/benchmarks/memory/client/scenarios/mount-unmount/vue/tsconfig.json new file mode 100644 index 0000000000..9a5872a4c0 --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts new file mode 100644 index 0000000000..a3f0eeaa8c --- /dev/null +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client mount-unmount (vue)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.flame.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/project.json b/benchmarks/memory/client/scenarios/navigation-churn/react/project.json new file mode 100644 index 0000000000..b424277bc6 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-navigation-churn-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.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "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/memory/client/scenarios/navigation-churn/react/setup.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/setup.ts new file mode 100644 index 0000000000..70603b5c34 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/setup.ts @@ -0,0 +1,13 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'react', + mountTestApp, +) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/src/app.tsx b/benchmarks/memory/client/scenarios/navigation-churn/react/src/app.tsx new file mode 100644 index 0000000000..d714e7bfdd --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/src/app.tsx @@ -0,0 +1,31 @@ +import { RouterProvider } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { getRouter } from './router' + +export function mountTestApp(container: Element) { + const router = getRouter() + const reactRoot = createRoot(container) + let didUnmount = false + + reactRoot.render() + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + reactRoot.unmount() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..3cca81cabb --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/src/routeTree.gen.ts @@ -0,0 +1,77 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as BRouteImport } from './routes/b' +import { Route as ARouteImport } from './routes/a' + +const BRoute = BRouteImport.update({ + id: '/b', + path: '/b', + getParentRoute: () => rootRouteImport, +} as any) +const ARoute = ARouteImport.update({ + id: '/a', + path: '/a', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/a': typeof ARoute + '/b': typeof BRoute +} +export interface FileRoutesByTo { + '/a': typeof ARoute + '/b': typeof BRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/a': typeof ARoute + '/b': typeof BRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/a' | '/b' + fileRoutesByTo: FileRoutesByTo + to: '/a' | '/b' + id: '__root__' | '/a' | '/b' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARoute + BRoute: typeof BRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/b': { + id: '/b' + path: '/b' + fullPath: '/b' + preLoaderRoute: typeof BRouteImport + parentRoute: typeof rootRouteImport + } + '/a': { + id: '/a' + path: '/a' + fullPath: '/a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARoute, + BRoute: BRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/src/router.tsx b/benchmarks/memory/client/scenarios/navigation-churn/react/src/router.tsx new file mode 100644 index 0000000000..9cb85c5a1b --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/src/router.tsx @@ -0,0 +1,17 @@ +import { createMemoryHistory, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/a'], + }), + routeTree, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/__root.tsx new file mode 100644 index 0000000000..889395056b --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/a.tsx b/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/a.tsx new file mode 100644 index 0000000000..bdd32d0b81 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/a.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' + +const fixedTimestamp = 1_700_000_000_000 + +export const Route = createFileRoute('/a')({ + loader: () => ({ name: 'a', ts: fixedTimestamp }), + component: AComponent, +}) + +function AComponent() { + const data = Route.useLoaderData() + + return
{`${data.name}:${data.ts}`}
+} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/b.tsx b/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/b.tsx new file mode 100644 index 0000000000..05deef729d --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/src/routes/b.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' + +const fixedTimestamp = 1_700_000_000_000 + +export const Route = createFileRoute('/b')({ + loader: () => ({ name: 'b', ts: fixedTimestamp }), + component: BComponent, +}) + +function BComponent() { + const data = Route.useLoaderData() + + return
{`${data.name}:${data.ts}`}
+} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/tsconfig.json b/benchmarks/memory/client/scenarios/navigation-churn/react/tsconfig.json new file mode 100644 index 0000000000..ea566061d9 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "allowImportingTsExtensions": true, + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts new file mode 100644 index 0000000000..eef60a658e --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client navigation-churn (react)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/shared.ts b/benchmarks/memory/client/scenarios/navigation-churn/shared.ts new file mode 100644 index 0000000000..7eaf1a8b66 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/shared.ts @@ -0,0 +1,129 @@ +import { + createBenchContainer, + nextAnimationFrame, + noop, + removeBenchContainer, + warnClientMemoryDevMode, +} from '#memory-client/lifecycle' +import type { Framework, MountTestApp } from '#memory-client/lifecycle' + +type Target = '/a' | '/b' + +type NavigationRouter = { + load: () => Promise + navigate: (options: { to: Target; replace: true }) => Promise + subscribe: (event: 'onRendered', listener: () => void) => () => void +} + +const navigationChurnIterations = 300 + +const uninitialized = () => + Promise.reject(new Error('navigation-churn benchmark is not initialized')) + +export function createWorkload( + framework: Framework, + mountTestApp: MountTestApp, +) { + warnClientMemoryDevMode(framework) + + let container: HTMLDivElement | undefined = undefined + let unmount = noop + let unsub = noop + let resolveRendered: () => void = noop + let navigateTo: (target: Target) => Promise = uninitialized + + function assertRenderedPage(target: Target) { + const expected = target.slice(1) + const actual = + container?.querySelector('[data-bench-page]')?.dataset + .benchPage + + if (actual !== expected) { + throw new Error(`Expected rendered page ${expected}, got ${actual}`) + } + } + + async function waitForRenderedPage(target: Target) { + for (let attempt = 0; attempt < 10; attempt++) { + try { + assertRenderedPage(target) + return + } catch { + await nextAnimationFrame() + } + } + + assertRenderedPage(target) + } + + function waitForNextRender() { + return new Promise((resolve) => { + resolveRendered = resolve + }) + } + + async function before() { + if (container) { + after() + } + + container = createBenchContainer() + + const mounted = mountTestApp(container) + const router = mounted.router as NavigationRouter + unmount = mounted.unmount + + unsub = router.subscribe('onRendered', () => { + resolveRendered() + }) + + navigateTo = async (target) => { + const rendered = waitForNextRender() + await Promise.all([ + router.navigate({ + to: target, + replace: true, + }), + rendered, + ]) + } + + await router.load() + await waitForRenderedPage('/a') + } + + function after() { + unmount() + removeBenchContainer(container) + unsub() + + container = undefined + unmount = noop + unsub = noop + resolveRendered = noop + navigateTo = uninitialized + } + + return { + name: `mem client navigation-churn (${framework})`, + before, + navigate: (target: Target) => navigateTo(target), + async run() { + for (let index = 0; index < navigationChurnIterations; index++) { + await navigateTo(index % 2 === 0 ? '/b' : '/a') + } + }, + async sanity() { + await before() + + try { + assertRenderedPage('/a') + await navigateTo('/b') + assertRenderedPage('/b') + } finally { + after() + } + }, + after, + } +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.flame.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/project.json b/benchmarks/memory/client/scenarios/navigation-churn/solid/project.json new file mode 100644 index 0000000000..2c581e6188 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-navigation-churn-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.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "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/memory/client/scenarios/navigation-churn/solid/setup.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/setup.ts new file mode 100644 index 0000000000..493425c6a2 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/setup.ts @@ -0,0 +1,13 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'solid', + mountTestApp, +) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/app.tsx b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/app.tsx new file mode 100644 index 0000000000..16000c90a1 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/app.tsx @@ -0,0 +1,29 @@ +import { RouterProvider } from '@tanstack/solid-router' +import { render } from 'solid-js/web' +import { getRouter } from './router' + +export function mountTestApp(container: Element) { + const router = getRouter() + const dispose = render(() => , container) + let didUnmount = false + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + dispose() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..59d7fad058 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routeTree.gen.ts @@ -0,0 +1,77 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as BRouteImport } from './routes/b' +import { Route as ARouteImport } from './routes/a' + +const BRoute = BRouteImport.update({ + id: '/b', + path: '/b', + getParentRoute: () => rootRouteImport, +} as any) +const ARoute = ARouteImport.update({ + id: '/a', + path: '/a', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/a': typeof ARoute + '/b': typeof BRoute +} +export interface FileRoutesByTo { + '/a': typeof ARoute + '/b': typeof BRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/a': typeof ARoute + '/b': typeof BRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/a' | '/b' + fileRoutesByTo: FileRoutesByTo + to: '/a' | '/b' + id: '__root__' | '/a' | '/b' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARoute + BRoute: typeof BRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/b': { + id: '/b' + path: '/b' + fullPath: '/b' + preLoaderRoute: typeof BRouteImport + parentRoute: typeof rootRouteImport + } + '/a': { + id: '/a' + path: '/a' + fullPath: '/a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARoute, + BRoute: BRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/router.tsx b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/router.tsx new file mode 100644 index 0000000000..e8c14f12f6 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/router.tsx @@ -0,0 +1,17 @@ +import { createMemoryHistory, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/a'], + }), + routeTree, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..cb8d5a688d --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/a.tsx b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/a.tsx new file mode 100644 index 0000000000..0b7838fdbe --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/a.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' + +const fixedTimestamp = 1_700_000_000_000 + +export const Route = createFileRoute('/a')({ + loader: () => ({ name: 'a', ts: fixedTimestamp }), + component: AComponent, +}) + +function AComponent() { + const data = Route.useLoaderData() + + return
{`${data().name}:${data().ts}`}
+} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/b.tsx b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/b.tsx new file mode 100644 index 0000000000..ec9b513ba9 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/src/routes/b.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' + +const fixedTimestamp = 1_700_000_000_000 + +export const Route = createFileRoute('/b')({ + loader: () => ({ name: 'b', ts: fixedTimestamp }), + component: BComponent, +}) + +function BComponent() { + const data = Route.useLoaderData() + + return
{`${data().name}:${data().ts}`}
+} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/tsconfig.json b/benchmarks/memory/client/scenarios/navigation-churn/solid/tsconfig.json new file mode 100644 index 0000000000..b12dcb7ade --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts new file mode 100644 index 0000000000..7dfb186b2e --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client navigation-churn (solid)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.flame.ts b/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/project.json b/benchmarks/memory/client/scenarios/navigation-churn/vue/project.json new file mode 100644 index 0000000000..f96d03d7d3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-navigation-churn-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/setup.ts b/benchmarks/memory/client/scenarios/navigation-churn/vue/setup.ts new file mode 100644 index 0000000000..a38df04788 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/setup.ts @@ -0,0 +1,13 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'vue', + mountTestApp, +) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/app.tsx b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/app.tsx new file mode 100644 index 0000000000..fad2251cc0 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/app.tsx @@ -0,0 +1,36 @@ +import { RouterProvider } from '@tanstack/vue-router' +import { createApp } from 'vue' +import { getRouter } from './router' +import type {} from '@tanstack/router-core' + +export function mountTestApp(container: Element) { + const router = getRouter() + const vueApp = createApp({ + setup() { + return () => + }, + }) + let didUnmount = false + + vueApp.mount(container) + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + vueApp.unmount() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..12c9640358 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routeTree.gen.ts @@ -0,0 +1,77 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as BRouteImport } from './routes/b' +import { Route as ARouteImport } from './routes/a' + +const BRoute = BRouteImport.update({ + id: '/b', + path: '/b', + getParentRoute: () => rootRouteImport, +} as any) +const ARoute = ARouteImport.update({ + id: '/a', + path: '/a', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/a': typeof ARoute + '/b': typeof BRoute +} +export interface FileRoutesByTo { + '/a': typeof ARoute + '/b': typeof BRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/a': typeof ARoute + '/b': typeof BRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/a' | '/b' + fileRoutesByTo: FileRoutesByTo + to: '/a' | '/b' + id: '__root__' | '/a' | '/b' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARoute + BRoute: typeof BRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/b': { + id: '/b' + path: '/b' + fullPath: '/b' + preLoaderRoute: typeof BRouteImport + parentRoute: typeof rootRouteImport + } + '/a': { + id: '/a' + path: '/a' + fullPath: '/a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARoute, + BRoute: BRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/router.tsx b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/router.tsx new file mode 100644 index 0000000000..e083495cd2 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/router.tsx @@ -0,0 +1,17 @@ +import { createMemoryHistory, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/a'], + }), + routeTree, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..91296e6f84 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/a.tsx b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/a.tsx new file mode 100644 index 0000000000..c1a9cfb244 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/a.tsx @@ -0,0 +1,19 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const fixedTimestamp = 1_700_000_000_000 + +const AComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
{`${data.value.name}:${data.value.ts}`}
+ ) + }, +}) + +export const Route = createFileRoute('/a')({ + loader: () => ({ name: 'a', ts: fixedTimestamp }), + component: AComponent, +}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/b.tsx b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/b.tsx new file mode 100644 index 0000000000..3a20799f3b --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/b.tsx @@ -0,0 +1,19 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const fixedTimestamp = 1_700_000_000_000 + +const BComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
{`${data.value.name}:${data.value.ts}`}
+ ) + }, +}) + +export const Route = createFileRoute('/b')({ + loader: () => ({ name: 'b', ts: fixedTimestamp }), + component: BComponent, +}) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/tsconfig.json b/benchmarks/memory/client/scenarios/navigation-churn/vue/tsconfig.json new file mode 100644 index 0000000000..9a5872a4c0 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts b/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts new file mode 100644 index 0000000000..b3bdd39dd2 --- /dev/null +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client navigation-churn (vue)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/item-payload.ts b/benchmarks/memory/client/scenarios/preload-churn/item-payload.ts new file mode 100644 index 0000000000..4a86ea7244 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/item-payload.ts @@ -0,0 +1,51 @@ +const payloadByteLength = 20 * 1024 +const payloadChunkCount = 32 +const payloadChunkSize = payloadByteLength / payloadChunkCount +const trackedLoaderIdPrefix = 'sanity-' +const trackedItemLoaderCalls = new Map() + +export function createItemPayload(id: string) { + let seed = hashId(id) + const chunks = new Array(payloadChunkCount) + + for (let index = 0; index < payloadChunkCount; index++) { + seed = (seed * 1664525 + 1013904223) >>> 0 + chunks[index] = createPayloadChunk(id, index, seed) + } + + return { + id, + chunks, + byteLength: payloadByteLength, + } +} + +export function trackItemLoaderCall(id: string) { + if (!id.startsWith(trackedLoaderIdPrefix)) { + return + } + + trackedItemLoaderCalls.set(id, (trackedItemLoaderCalls.get(id) ?? 0) + 1) +} + +export function getTrackedItemLoaderCount(id: string) { + return trackedItemLoaderCalls.get(id) ?? 0 +} + +function createPayloadChunk(id: string, index: number, seed: number) { + const token = `${id}:${index.toString(36)}:${seed.toString(36)}:` + const repeatCount = Math.ceil(payloadChunkSize / token.length) + + return token.repeat(repeatCount).slice(0, payloadChunkSize) +} + +function hashId(id: string) { + let hash = 2166136261 + + for (let index = 0; index < id.length; index++) { + hash ^= id.charCodeAt(index) + hash = Math.imul(hash, 16777619) + } + + return hash >>> 0 +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts b/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/memory.flame.ts b/benchmarks/memory/client/scenarios/preload-churn/react/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/react/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/project.json b/benchmarks/memory/client/scenarios/preload-churn/react/project.json new file mode 100644 index 0000000000..238d98c816 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/react/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-preload-churn-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.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "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/memory/client/scenarios/preload-churn/react/setup.ts b/benchmarks/memory/client/scenarios/preload-churn/react/setup.ts new file mode 100644 index 0000000000..31cd97d135 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/react/setup.ts @@ -0,0 +1,14 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { getTrackedItemLoaderCount, mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'react', + mountTestApp, + getTrackedItemLoaderCount, +) diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/src/app.tsx b/benchmarks/memory/client/scenarios/preload-churn/react/src/app.tsx new file mode 100644 index 0000000000..b75d1fe34d --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/react/src/app.tsx @@ -0,0 +1,33 @@ +import { RouterProvider } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { getRouter } from './router' + +export { getTrackedItemLoaderCount } from '../../item-payload' + +export function mountTestApp(container: Element) { + const router = getRouter() + const reactRoot = createRoot(container) + let didUnmount = false + + reactRoot.render() + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + reactRoot.unmount() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/preload-churn/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..84aaebb9c9 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/react/src/routeTree.gen.ts @@ -0,0 +1,77 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as ItemsIdRouteImport } from './routes/items.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ItemsIdRoute = ItemsIdRouteImport.update({ + id: '/items/$id', + path: '/items/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/items/$id' + id: '__root__' | '/' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/items/$id': { + id: '/items/$id' + path: '/items/$id' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ItemsIdRoute: ItemsIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/src/router.tsx b/benchmarks/memory/client/scenarios/preload-churn/react/src/router.tsx new file mode 100644 index 0000000000..69e3180173 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/react/src/router.tsx @@ -0,0 +1,18 @@ +import { createMemoryHistory, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree, + defaultPreloadGcTime: 0, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/__root.tsx new file mode 100644 index 0000000000..889395056b --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/index.tsx b/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/index.tsx new file mode 100644 index 0000000000..af735d705b --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
index
+} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/items.$id.tsx new file mode 100644 index 0000000000..2f52acd528 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/react/src/routes/items.$id.tsx @@ -0,0 +1,20 @@ +import { createFileRoute } from '@tanstack/react-router' +import { createItemPayload, trackItemLoaderCall } from '../../../item-payload' + +export const Route = createFileRoute('/items/$id')({ + loader: ({ params }) => { + trackItemLoaderCall(params.id) + return createItemPayload(params.id) + }, + component: ItemComponent, +}) + +function ItemComponent() { + const data = Route.useLoaderData() + + return ( +
+ {`${data.id}:${data.byteLength}`} +
+ ) +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/tsconfig.json b/benchmarks/memory/client/scenarios/preload-churn/react/tsconfig.json new file mode 100644 index 0000000000..ea566061d9 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/react/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "allowImportingTsExtensions": true, + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts b/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts new file mode 100644 index 0000000000..c12995f68e --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client preload-churn (react)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/shared.ts b/benchmarks/memory/client/scenarios/preload-churn/shared.ts new file mode 100644 index 0000000000..68fdfedd3f --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/shared.ts @@ -0,0 +1,216 @@ +import { + createDeterministicRandom, + randomSegment, +} from '#memory-client/bench-utils' +import { + createBenchContainer, + drainMicrotasks, + nextAnimationFrame, + noop, + removeBenchContainer, + warnClientMemoryDevMode, +} from '#memory-client/lifecycle' +import type { Framework, MountTestApp } from '#memory-client/lifecycle' + +type GetTrackedItemLoaderCount = (id: string) => number + +type PreloadRouter = { + load: () => Promise + preloadRoute: (options: { + to: '/items/$id' + params: { id: string } + }) => Promise + navigate: ( + options: + | { + to: '/items/$id' + params: { id: string } + replace: true + } + | { + to: '/' + replace: true + }, + ) => Promise + subscribe: (event: 'onRendered', listener: () => void) => () => void +} + +// Reuse one navigation target while evicting the distinct preloaded routes. +const evictionItemId = 'nav-evict' +const preloadChurnIterations = 200 +// A navigation commit is what triggers the router's clearExpiredCache -- +// preloaded matches (defaultPreloadGcTime: 0) are only evicted then, never +// during a preload-only loop. Interleave navigation to exercise eviction. +const preloadsPerEvictionNavigation = 10 +// Keep generated URLs unique across warmup and measured invocations. +const benchmarkRandom = createDeterministicRandom(0x706c6f61) +let preloadCounter = 0 + +const uninitialized = async (_id: string) => { + throw new Error('preload-churn benchmark is not initialized') +} + +export function createWorkload( + framework: Framework, + mountTestApp: MountTestApp, + getTrackedItemLoaderCount: GetTrackedItemLoaderCount, +) { + warnClientMemoryDevMode(framework) + + let container: HTMLDivElement | undefined = undefined + let router: PreloadRouter | undefined = undefined + let unmount = noop + let unsub = noop + let resolveRendered = noop + let evictionParity = 0 + let preloadItem: (id: string) => Promise = uninitialized + let navigateToItem: (id: string) => Promise = uninitialized + let navigateToIndex: () => Promise = () => + uninitialized('navigate-to-index') + + function assertRenderedIndex() { + const actual = + container?.querySelector('[data-bench-page]')?.dataset + .benchPage + + if (actual !== 'index') { + throw new Error(`Expected rendered index page, got ${actual}`) + } + } + + async function waitForRenderedIndex() { + for (let attempt = 0; attempt < 10; attempt++) { + try { + assertRenderedIndex() + return + } catch { + await nextAnimationFrame() + } + } + + assertRenderedIndex() + } + + function waitForNextRender() { + return new Promise((resolve) => { + resolveRendered = resolve + }) + } + + async function before() { + if (container) { + after() + } + + container = createBenchContainer() + + const mounted = mountTestApp(container) + router = mounted.router as PreloadRouter + unmount = mounted.unmount + + unsub = router.subscribe('onRendered', () => { + resolveRendered() + }) + + preloadItem = async (id) => { + await router!.preloadRoute({ + to: '/items/$id', + params: { id }, + }) + await drainMicrotasks() + } + + navigateToItem = async (id) => { + const rendered = waitForNextRender() + await Promise.all([ + router!.navigate({ + to: '/items/$id', + params: { id }, + replace: true, + }), + rendered, + ]) + } + + navigateToIndex = async () => { + const rendered = waitForNextRender() + await Promise.all([ + router!.navigate({ + to: '/', + replace: true, + }), + rendered, + ]) + } + + await router.load() + await waitForRenderedIndex() + } + + function after() { + unmount() + removeBenchContainer(container) + unsub() + + container = undefined + router = undefined + unmount = noop + unsub = noop + resolveRendered = noop + evictionParity = 0 + preloadItem = uninitialized + navigateToItem = uninitialized + navigateToIndex = () => uninitialized('navigate-to-index') + } + + // Alternate between two distinct locations so every eviction navigation + // changes the href (a same-href navigate would never commit or render). + async function evictPreloads() { + evictionParity = (evictionParity + 1) % 2 + + if (evictionParity === 1) { + await navigateToItem(evictionItemId) + } else { + await navigateToIndex() + } + } + + return { + name: `mem client preload-churn (${framework})`, + before, + preload: (id: string) => preloadItem(id), + evictPreloads, + async run() { + for (let index = 0; index < preloadChurnIterations; index++) { + await preloadItem( + `${(preloadCounter++).toString(36)}-${randomSegment(benchmarkRandom)}`, + ) + + if ((index + 1) % preloadsPerEvictionNavigation === 0) { + await evictPreloads() + } + } + }, + async sanity() { + await before() + + try { + assertRenderedIndex() + + const id = 'sanity-preloaded-item' + const initialLoaderCount = getTrackedItemLoaderCount(id) + await preloadItem(id) + + const preloadedLoaderCount = getTrackedItemLoaderCount(id) + if (preloadedLoaderCount !== initialLoaderCount + 1) { + throw new Error( + `Expected preload to run item loader once, got ${preloadedLoaderCount - initialLoaderCount}`, + ) + } + } finally { + after() + } + }, + after, + } +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.flame.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/project.json b/benchmarks/memory/client/scenarios/preload-churn/solid/project.json new file mode 100644 index 0000000000..16ef8af968 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-preload-churn-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.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "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/memory/client/scenarios/preload-churn/solid/setup.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/setup.ts new file mode 100644 index 0000000000..4db457f561 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/setup.ts @@ -0,0 +1,14 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { getTrackedItemLoaderCount, mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'solid', + mountTestApp, + getTrackedItemLoaderCount, +) diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/src/app.tsx b/benchmarks/memory/client/scenarios/preload-churn/solid/src/app.tsx new file mode 100644 index 0000000000..18ad5b97e4 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/src/app.tsx @@ -0,0 +1,31 @@ +import { RouterProvider } from '@tanstack/solid-router' +import { render } from 'solid-js/web' +import { getRouter } from './router' + +export { getTrackedItemLoaderCount } from '../../item-payload' + +export function mountTestApp(container: Element) { + const router = getRouter() + const dispose = render(() => , container) + let didUnmount = false + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + dispose() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..27749ab2af --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/src/routeTree.gen.ts @@ -0,0 +1,77 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as ItemsIdRouteImport } from './routes/items.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ItemsIdRoute = ItemsIdRouteImport.update({ + id: '/items/$id', + path: '/items/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/items/$id' + id: '__root__' | '/' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/items/$id': { + id: '/items/$id' + path: '/items/$id' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ItemsIdRoute: ItemsIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/src/router.tsx b/benchmarks/memory/client/scenarios/preload-churn/solid/src/router.tsx new file mode 100644 index 0000000000..faed87f1f4 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/src/router.tsx @@ -0,0 +1,18 @@ +import { createMemoryHistory, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree, + defaultPreloadGcTime: 0, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..cb8d5a688d --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/index.tsx b/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/index.tsx new file mode 100644 index 0000000000..b870b8bfd5 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
index
+} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/items.$id.tsx new file mode 100644 index 0000000000..15fa2a34ab --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/src/routes/items.$id.tsx @@ -0,0 +1,20 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { createItemPayload, trackItemLoaderCall } from '../../../item-payload' + +export const Route = createFileRoute('/items/$id')({ + loader: ({ params }) => { + trackItemLoaderCall(params.id) + return createItemPayload(params.id) + }, + component: ItemComponent, +}) + +function ItemComponent() { + const data = Route.useLoaderData() + + return ( +
+ {`${data().id}:${data().byteLength}`} +
+ ) +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/tsconfig.json b/benchmarks/memory/client/scenarios/preload-churn/solid/tsconfig.json new file mode 100644 index 0000000000..b12dcb7ade --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts new file mode 100644 index 0000000000..efc75d2b93 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client preload-churn (solid)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.flame.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/project.json b/benchmarks/memory/client/scenarios/preload-churn/vue/project.json new file mode 100644 index 0000000000..e13388890f --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-preload-churn-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/setup.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/setup.ts new file mode 100644 index 0000000000..4aad4af31e --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/setup.ts @@ -0,0 +1,14 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { getTrackedItemLoaderCount, mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'vue', + mountTestApp, + getTrackedItemLoaderCount, +) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/src/app.tsx b/benchmarks/memory/client/scenarios/preload-churn/vue/src/app.tsx new file mode 100644 index 0000000000..890447d88b --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/src/app.tsx @@ -0,0 +1,38 @@ +import { RouterProvider } from '@tanstack/vue-router' +import { createApp } from 'vue' +import { getRouter } from './router' +import type {} from '@tanstack/router-core' + +export { getTrackedItemLoaderCount } from '../../item-payload' + +export function mountTestApp(container: Element) { + const router = getRouter() + const vueApp = createApp({ + setup() { + return () => + }, + }) + let didUnmount = false + + vueApp.mount(container) + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + vueApp.unmount() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..a2216f2b67 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routeTree.gen.ts @@ -0,0 +1,77 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as ItemsIdRouteImport } from './routes/items.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ItemsIdRoute = ItemsIdRouteImport.update({ + id: '/items/$id', + path: '/items/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/items/$id' + id: '__root__' | '/' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/items/$id': { + id: '/items/$id' + path: '/items/$id' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ItemsIdRoute: ItemsIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/src/router.tsx b/benchmarks/memory/client/scenarios/preload-churn/vue/src/router.tsx new file mode 100644 index 0000000000..86534112d7 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/src/router.tsx @@ -0,0 +1,18 @@ +import { createMemoryHistory, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree, + defaultPreloadGcTime: 0, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..91296e6f84 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/index.tsx b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/index.tsx new file mode 100644 index 0000000000..b4f871306c --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
index
+} diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/items.$id.tsx new file mode 100644 index 0000000000..08254e173e --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/items.$id.tsx @@ -0,0 +1,23 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { createItemPayload, trackItemLoaderCall } from '../../../item-payload' + +const ItemComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+ {`${data.value.id}:${data.value.byteLength}`} +
+ ) + }, +}) + +export const Route = createFileRoute('/items/$id')({ + loader: ({ params }: { params: { id: string } }) => { + trackItemLoaderCall(params.id) + return createItemPayload(params.id) + }, + component: ItemComponent, +}) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/tsconfig.json b/benchmarks/memory/client/scenarios/preload-churn/vue/tsconfig.json new file mode 100644 index 0000000000..9a5872a4c0 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts new file mode 100644 index 0000000000..3d56089ba7 --- /dev/null +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client preload-churn (vue)', + watch: false, + environment: 'jsdom', + }, +}) 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 new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.flame.ts b/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/project.json b/benchmarks/memory/client/scenarios/unique-location-churn/react/project.json new file mode 100644 index 0000000000..1572552650 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-unique-location-churn-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.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "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/memory/client/scenarios/unique-location-churn/react/setup.ts b/benchmarks/memory/client/scenarios/unique-location-churn/react/setup.ts new file mode 100644 index 0000000000..70603b5c34 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/setup.ts @@ -0,0 +1,13 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'react', + mountTestApp, +) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/app.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/app.tsx new file mode 100644 index 0000000000..d714e7bfdd --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/app.tsx @@ -0,0 +1,31 @@ +import { RouterProvider } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { getRouter } from './router' + +export function mountTestApp(container: Element) { + const router = getRouter() + const reactRoot = createRoot(container) + let didUnmount = false + + reactRoot.render() + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + reactRoot.unmount() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..1165f57523 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routeTree.gen.ts @@ -0,0 +1,59 @@ +/* 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 ItemsIdRouteImport } from './routes/items.$id' + +const ItemsIdRoute = ItemsIdRouteImport.update({ + id: '/items/$id', + path: '/items/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/items/$id' + id: '__root__' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/items/$id': { + id: '/items/$id' + path: '/items/$id' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + ItemsIdRoute: ItemsIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/router.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/router.tsx new file mode 100644 index 0000000000..50ad269060 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/router.tsx @@ -0,0 +1,17 @@ +import { createMemoryHistory, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/items/initial?q=q-initial'], + }), + routeTree, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/__root.tsx new file mode 100644 index 0000000000..889395056b --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/items.$id.tsx new file mode 100644 index 0000000000..c9e823f6c2 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/src/routes/items.$id.tsx @@ -0,0 +1,28 @@ +import { createFileRoute } from '@tanstack/react-router' + +type ItemSearch = { + q: string +} + +export const Route = createFileRoute('/items/$id')({ + validateSearch: (search: Record): ItemSearch => ({ + q: typeof search.q === 'string' ? search.q : '', + }), + loaderDeps: ({ search }) => ({ q: search.q }), + loader: ({ params, deps }) => ({ + id: params.id, + q: deps.q, + checksum: params.id.length + deps.q.length, + }), + component: ItemComponent, +}) + +function ItemComponent() { + const data = Route.useLoaderData() + + return ( +
{`${data.id}:${data.q}:${data.checksum}`}
+ ) +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/tsconfig.json b/benchmarks/memory/client/scenarios/unique-location-churn/react/tsconfig.json new file mode 100644 index 0000000000..ea566061d9 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "allowImportingTsExtensions": true, + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/vite.config.ts b/benchmarks/memory/client/scenarios/unique-location-churn/react/vite.config.ts new file mode 100644 index 0000000000..7ee67bfe30 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client unique-location-churn (react)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/shared.ts b/benchmarks/memory/client/scenarios/unique-location-churn/shared.ts new file mode 100644 index 0000000000..3b36c7811e --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/shared.ts @@ -0,0 +1,149 @@ +import { + createDeterministicRandom, + randomSegment, +} from '#memory-client/bench-utils' +import { + createBenchContainer, + nextAnimationFrame, + noop, + removeBenchContainer, + warnClientMemoryDevMode, +} from '#memory-client/lifecycle' +import type { Framework, MountTestApp } from '#memory-client/lifecycle' + +type ItemLocation = { + id: string + q: string +} + +type NavigationRouter = { + load: () => Promise + navigate: (options: { + to: '/items/$id' + params: { id: string } + search: { q: string } + replace: true + }) => Promise + subscribe: (event: 'onRendered', listener: () => void) => () => void +} + +const uniqueLocationChurnIterations = 300 +// Module-level so ids stay unique across runner invocations on one mount; the +// counter prefix removes any residual LCG birthday-collision risk. +const benchmarkRandom = createDeterministicRandom(0xdecafbad) +let locationCounter = 0 + +const uninitialized = () => + Promise.reject( + new Error('unique-location-churn benchmark is not initialized'), + ) + +export function createWorkload( + framework: Framework, + mountTestApp: MountTestApp, +) { + warnClientMemoryDevMode(framework) + + let container: HTMLDivElement | undefined = undefined + let unmount = noop + let unsub = noop + let resolveRendered: () => void = noop + let navigateTo: (location: ItemLocation) => Promise = uninitialized + + function assertRenderedId(expected: string) { + const actual = + container?.querySelector('[data-bench-id]')?.dataset.benchId + + if (actual !== expected) { + throw new Error(`Expected rendered item id ${expected}, got ${actual}`) + } + } + + async function waitForRenderedId(expected: string) { + for (let attempt = 0; attempt < 10; attempt++) { + try { + assertRenderedId(expected) + return + } catch { + await nextAnimationFrame() + } + } + + assertRenderedId(expected) + } + + function waitForNextRender() { + return new Promise((resolve) => { + resolveRendered = resolve + }) + } + + async function before() { + if (container) { + after() + } + + container = createBenchContainer() + + const mounted = mountTestApp(container) + const router = mounted.router as NavigationRouter + unmount = mounted.unmount + + unsub = router.subscribe('onRendered', () => { + resolveRendered() + }) + + navigateTo = async (location) => { + const rendered = waitForNextRender() + await Promise.all([ + router.navigate({ + to: '/items/$id', + params: { id: location.id }, + search: { q: location.q }, + replace: true, + }), + rendered, + ]) + } + + await router.load() + await waitForRenderedId('initial') + } + + function after() { + unmount() + removeBenchContainer(container) + unsub() + + container = undefined + unmount = noop + unsub = noop + resolveRendered = noop + navigateTo = uninitialized + } + + return { + name: `mem client unique-location-churn (${framework})`, + before, + navigate: (location: ItemLocation) => navigateTo(location), + async run() { + for (let index = 0; index < uniqueLocationChurnIterations; index++) { + const id = `${(locationCounter++).toString(36)}-${randomSegment(benchmarkRandom)}` + const q = `q-${randomSegment(benchmarkRandom)}` + + await navigateTo({ id, q }) + } + }, + async sanity() { + await before() + + try { + await navigateTo({ id: 'sanity-one', q: 'q-sanity-one' }) + assertRenderedId('sanity-one') + } finally { + after() + } + }, + after, + } +} 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 new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.flame.ts b/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/project.json b/benchmarks/memory/client/scenarios/unique-location-churn/solid/project.json new file mode 100644 index 0000000000..5be22de7a4 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-unique-location-churn-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.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "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/memory/client/scenarios/unique-location-churn/solid/setup.ts b/benchmarks/memory/client/scenarios/unique-location-churn/solid/setup.ts new file mode 100644 index 0000000000..493425c6a2 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/setup.ts @@ -0,0 +1,13 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'solid', + mountTestApp, +) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/app.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/app.tsx new file mode 100644 index 0000000000..16000c90a1 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/app.tsx @@ -0,0 +1,29 @@ +import { RouterProvider } from '@tanstack/solid-router' +import { render } from 'solid-js/web' +import { getRouter } from './router' + +export function mountTestApp(container: Element) { + const router = getRouter() + const dispose = render(() => , container) + let didUnmount = false + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + dispose() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..4a451735ff --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routeTree.gen.ts @@ -0,0 +1,59 @@ +/* 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 ItemsIdRouteImport } from './routes/items.$id' + +const ItemsIdRoute = ItemsIdRouteImport.update({ + id: '/items/$id', + path: '/items/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/items/$id' + id: '__root__' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/items/$id': { + id: '/items/$id' + path: '/items/$id' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + ItemsIdRoute: ItemsIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/router.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/router.tsx new file mode 100644 index 0000000000..2969b06914 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/router.tsx @@ -0,0 +1,17 @@ +import { createMemoryHistory, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/items/initial?q=q-initial'], + }), + routeTree, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..cb8d5a688d --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/items.$id.tsx new file mode 100644 index 0000000000..9724922b8d --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/src/routes/items.$id.tsx @@ -0,0 +1,28 @@ +import { createFileRoute } from '@tanstack/solid-router' + +type ItemSearch = { + q: string +} + +export const Route = createFileRoute('/items/$id')({ + validateSearch: (search: Record): ItemSearch => ({ + q: typeof search.q === 'string' ? search.q : '', + }), + loaderDeps: ({ search }) => ({ q: search.q }), + loader: ({ params, deps }) => ({ + id: params.id, + q: deps.q, + checksum: params.id.length + deps.q.length, + }), + component: ItemComponent, +}) + +function ItemComponent() { + const data = Route.useLoaderData() + + return ( +
{`${data().id}:${data().q}:${data().checksum}`}
+ ) +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/tsconfig.json b/benchmarks/memory/client/scenarios/unique-location-churn/solid/tsconfig.json new file mode 100644 index 0000000000..b12dcb7ade --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/vite.config.ts b/benchmarks/memory/client/scenarios/unique-location-churn/solid/vite.config.ts new file mode 100644 index 0000000000..4db90da2d2 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client unique-location-churn (solid)', + watch: false, + environment: 'jsdom', + }, +}) 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 new file mode 100644 index 0000000000..43ab822de3 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.bench.ts @@ -0,0 +1,14 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + 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, + ) +}) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.flame.ts b/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.flame.ts new file mode 100644 index 0000000000..952fd9a62c --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.flame.ts @@ -0,0 +1,4 @@ +import { runClientFlameBenchmark } from '#memory-client/flame-runner' +import { workload } from './setup.ts' + +await runClientFlameBenchmark(workload) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/project.json b/benchmarks/memory/client/scenarios/unique-location-churn/vue/project.json new file mode 100644 index 0000000000..6c05cf80b0 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-client-unique-location-churn-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:client:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:client:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/setup.ts b/benchmarks/memory/client/scenarios/unique-location-churn/vue/setup.ts new file mode 100644 index 0000000000..a38df04788 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/setup.ts @@ -0,0 +1,13 @@ +import type { ClientMemoryWorkload } from '#memory-client/benchmark' +import type * as App from './src/app' +import { createWorkload } from '../shared.ts' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export const workload: ClientMemoryWorkload = createWorkload( + 'vue', + mountTestApp, +) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/app.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/app.tsx new file mode 100644 index 0000000000..fad2251cc0 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/app.tsx @@ -0,0 +1,36 @@ +import { RouterProvider } from '@tanstack/vue-router' +import { createApp } from 'vue' +import { getRouter } from './router' +import type {} from '@tanstack/router-core' + +export function mountTestApp(container: Element) { + const router = getRouter() + const vueApp = createApp({ + setup() { + return () => + }, + }) + let didUnmount = false + + vueApp.mount(container) + + // Full teardown mirrors the mount-unmount scenario: guard double-unmounts, + // release the devtools global, and detach history listeners. + return { + router, + unmount() { + if (didUnmount) { + return + } + + didUnmount = true + vueApp.unmount() + + if (typeof self !== 'undefined' && self.__TSR_ROUTER__ === router) { + self.__TSR_ROUTER__ = undefined + } + + router.history.destroy() + }, + } +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routeTree.gen.ts b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..d3e9db0345 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routeTree.gen.ts @@ -0,0 +1,59 @@ +/* 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 ItemsIdRouteImport } from './routes/items.$id' + +const ItemsIdRoute = ItemsIdRouteImport.update({ + id: '/items/$id', + path: '/items/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/items/$id' + id: '__root__' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/items/$id': { + id: '/items/$id' + path: '/items/$id' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + ItemsIdRoute: ItemsIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/router.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/router.tsx new file mode 100644 index 0000000000..72f9ab565b --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/router.tsx @@ -0,0 +1,17 @@ +import { createMemoryHistory, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + history: createMemoryHistory({ + initialEntries: ['/items/initial?q=q-initial'], + }), + routeTree, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/__root.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..91296e6f84 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import { Outlet, createRootRoute } from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/items.$id.tsx new file mode 100644 index 0000000000..e796ee14d1 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/items.$id.tsx @@ -0,0 +1,37 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +type ItemSearch = { + q: string +} + +const ItemComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
{`${data.value.id}:${data.value.q}:${data.value.checksum}`}
+ ) + }, +}) + +export const Route = createFileRoute('/items/$id')({ + validateSearch: (search: Record): ItemSearch => ({ + q: typeof search.q === 'string' ? search.q : '', + }), + loaderDeps: ({ search }: { search: ItemSearch }) => ({ q: search.q }), + loader: ({ + params, + deps, + }: { + params: { id: string } + deps: { q: string } + }) => ({ + id: params.id, + q: deps.q, + checksum: params.id.length + deps.q.length, + }), + component: ItemComponent, +}) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/tsconfig.json b/benchmarks/memory/client/scenarios/unique-location-churn/vue/tsconfig.json new file mode 100644 index 0000000000..9a5872a4c0 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "allowImportingTsExtensions": true, + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../../vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/vite.config.ts b/benchmarks/memory/client/scenarios/unique-location-churn/vue/vite.config.ts new file mode 100644 index 0000000000..d074d571b9 --- /dev/null +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/app.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + ...memoryConfig('client'), + name: '@benchmarks/memory-client unique-location-churn (vue)', + watch: false, + environment: 'jsdom', + }, +}) diff --git a/benchmarks/memory/client/tsconfig.json b/benchmarks/memory/client/tsconfig.json new file mode 100644 index 0000000000..eefc5c581e --- /dev/null +++ b/benchmarks/memory/client/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "bench-utils.ts", + "lifecycle.ts", + "vitest.setup.ts", + "scenarios/*/shared.ts" + ] +} diff --git a/benchmarks/memory/client/vitest.react.config.ts b/benchmarks/memory/client/vitest.react.config.ts new file mode 100644 index 0000000000..44643b4d60 --- /dev/null +++ b/benchmarks/memory/client/vitest.react.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + fileParallelism: false, + projects: ['./scenarios/*/react/vite.config.ts'], + }, +}) diff --git a/benchmarks/memory/client/vitest.setup.ts b/benchmarks/memory/client/vitest.setup.ts new file mode 100644 index 0000000000..ce3127275a --- /dev/null +++ b/benchmarks/memory/client/vitest.setup.ts @@ -0,0 +1,9 @@ +// @ts-expect-error +global.IS_REACT_ACT_ENVIRONMENT = true + +const scrollTo = () => {} + +window.scrollTo = scrollTo +globalThis.scrollTo = scrollTo + +export {} diff --git a/benchmarks/memory/client/vitest.solid.config.ts b/benchmarks/memory/client/vitest.solid.config.ts new file mode 100644 index 0000000000..5c8185cdd9 --- /dev/null +++ b/benchmarks/memory/client/vitest.solid.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + fileParallelism: false, + projects: ['./scenarios/*/solid/vite.config.ts'], + }, +}) diff --git a/benchmarks/memory/client/vitest.vue.config.ts b/benchmarks/memory/client/vitest.vue.config.ts new file mode 100644 index 0000000000..01768185ee --- /dev/null +++ b/benchmarks/memory/client/vitest.vue.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + fileParallelism: false, + projects: ['./scenarios/*/vue/vite.config.ts'], + }, +}) diff --git a/benchmarks/memory/flame-control.ts b/benchmarks/memory/flame-control.ts new file mode 100644 index 0000000000..0d6f42df33 --- /dev/null +++ b/benchmarks/memory/flame-control.ts @@ -0,0 +1,123 @@ +import fs from 'node:fs' +import { createRequire } from 'node:module' +import path from 'node:path' + +const flameEnabled = process.env.TSR_MEMORY_FLAME === '1' +const heapIntervalBytes = 512 * 1024 +const heapStackDepth = 64 + +interface HeapProfile { + encode: () => Uint8Array +} + +interface HeapProfiler { + start: (intervalBytes: number, stackDepth: number) => void + stop: () => void + v8Profile: () => unknown + convertProfile: ( + v8Profile: unknown, + ignoreSamplePath?: string, + sourceMapper?: unknown, + ) => HeapProfile +} + +interface SourceMapperConstructor { + create: (searchDirs: Array) => Promise +} + +interface PprofModule { + heap: HeapProfiler + SourceMapper: SourceMapperConstructor +} + +function loadPprof() { + const requireFrom = process.env.TSR_MEMORY_REQUIRE_FROM + ? path.resolve(process.env.TSR_MEMORY_REQUIRE_FROM) + : import.meta.url + const require = createRequire(requireFrom) + + return require('@datadog/pprof') as PprofModule +} + +function getSourcemapDirs() { + return (process.env.TSR_MEMORY_SOURCEMAP_DIRS ?? '') + .split(path.delimiter) + .filter(Boolean) +} + +async function createSourceMapper(pprof: PprofModule) { + const sourcemapDirs = getSourcemapDirs() + + if (sourcemapDirs.length === 0) { + return undefined + } + + return pprof.SourceMapper.create(sourcemapDirs) +} + +function formatTimestamp() { + return new Date().toISOString().replace(/[:.]/g, '-') +} + +function formatProfileFileName(profileName?: string) { + const profileNameSlug = profileName + ?.trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + const profileNamePart = profileNameSlug ? `${profileNameSlug}-` : '' + + return `heap-profile-${profileNamePart}${formatTimestamp()}.pb` +} + +export async function profileFlameWorkload( + workload: () => Promise | void, + profileName?: string, +) { + if (!flameEnabled) { + await workload() + return + } + + const profileDir = process.env.TSR_MEMORY_PROFILE_DIR + + if (!profileDir) { + throw new Error('TSR_MEMORY_PROFILE_DIR must be set for flame profiling') + } + + fs.mkdirSync(profileDir, { recursive: true }) + + const pprof = loadPprof() + const sourceMapper = await createSourceMapper(pprof) + + pprof.heap.start(heapIntervalBytes, heapStackDepth) + + let workloadError: unknown = undefined + let v8Profile: unknown = undefined + + try { + await workload() + } catch (error) { + workloadError = error + } finally { + try { + v8Profile = pprof.heap.v8Profile() + } finally { + pprof.heap.stop() + } + } + + const heapProfile = pprof.heap.convertProfile( + v8Profile, + undefined, + sourceMapper, + ) + const profilePath = path.join(profileDir, formatProfileFileName(profileName)) + + fs.writeFileSync(profilePath, heapProfile.encode()) + console.log(`Heap profile written to: ${profilePath}`) + + if (workloadError) { + throw workloadError + } +} diff --git a/benchmarks/memory/run-flame.mjs b/benchmarks/memory/run-flame.mjs new file mode 100644 index 0000000000..cc568f3f77 --- /dev/null +++ b/benchmarks/memory/run-flame.mjs @@ -0,0 +1,117 @@ +#!/usr/bin/env node +import { spawn } from 'node:child_process' +import fs from 'node:fs' +import { createRequire } from 'node:module' +import path from 'node:path' +import process from 'node:process' + +const [, , entrypointArg, sourcemapDirArg] = process.argv + +if (!entrypointArg || !sourcemapDirArg) { + console.error( + 'Usage: node benchmarks/memory/run-flame.mjs ', + ) + process.exit(1) +} + +const entrypointPath = path.resolve(entrypointArg) +const sourcemapDirPath = path.resolve(sourcemapDirArg) + +if (!fs.existsSync(entrypointPath)) { + console.error(`Flame entrypoint not found: ${entrypointPath}`) + process.exit(1) +} + +if (!fs.existsSync(sourcemapDirPath)) { + console.error(`Flame sourcemap directory not found: ${sourcemapDirPath}`) + process.exit(1) +} + +const profileDir = path.join( + path.dirname(entrypointPath), + '.profiles', + new Date().toISOString().replace(/[:.]/g, '-'), +) + +fs.mkdirSync(profileDir, { recursive: true }) + +const entrypointRequire = createRequire(entrypointPath) +const { generateFlamegraph, generateMarkdown } = entrypointRequire( + '@platformatic/flame', +) + +process.env.NODE_ENV = 'production' + +console.log(`Flame profile directory: ${profileDir}`) + +const childProcess = spawn(process.execPath, [entrypointPath], { + cwd: profileDir, + env: { + ...process.env, + NODE_ENV: 'production', + TSR_MEMORY_FLAME: '1', + TSR_MEMORY_PROFILE_DIR: profileDir, + TSR_MEMORY_REQUIRE_FROM: entrypointPath, + TSR_MEMORY_SOURCEMAP_DIRS: sourcemapDirPath, + }, + stdio: 'inherit', +}) + +console.log(`Flame profiling process: ${childProcess.pid}`) + +const childCode = await new Promise((resolve) => { + childProcess.on('error', (error) => { + console.error(`Failed to start Flame profiled process: ${error.message}`) + resolve(1) + }) + + childProcess.on('close', (code, signal) => { + if (signal) { + console.error(`Flame profiled process exited via signal ${signal}`) + resolve(1) + return + } + + resolve(code ?? 0) + }) +}) + +const heapProfilePaths = fs + .readdirSync(profileDir) + .filter((fileName) => /^heap-profile-.*\.pb$/.test(fileName)) + .sort() + .map((fileName) => path.join(profileDir, fileName)) + +for (const heapProfilePath of heapProfilePaths) { + const htmlPath = heapProfilePath.replace(/\.pb$/, '.html') + const mdPath = heapProfilePath.replace(/\.pb$/, '.md') + + console.log(`Generating heap flamegraph: ${htmlPath}`) + try { + await generateFlamegraph(heapProfilePath, htmlPath) + } catch (error) { + console.warn(`Failed to generate heap flamegraph: ${error.message}`) + } + + console.log(`Generating heap markdown: ${mdPath}`) + try { + await generateMarkdown(heapProfilePath, mdPath, { format: 'detailed' }) + } catch (error) { + console.warn(`Failed to generate heap markdown: ${error.message}`) + } +} + +const heapReportPaths = fs + .readdirSync(profileDir) + .filter((fileName) => /^heap-profile-.*\.(?:html|md)$/.test(fileName)) + .sort() + .map((fileName) => path.join(profileDir, fileName)) + +if (heapReportPaths.length > 0) { + console.log('Generated heap profile reports:') + for (const heapReportPath of heapReportPaths) { + console.log(` ${heapReportPath}`) + } +} + +process.exit(childCode) diff --git a/benchmarks/memory/runtime.ts b/benchmarks/memory/runtime.ts new file mode 100644 index 0000000000..010149b4df --- /dev/null +++ b/benchmarks/memory/runtime.ts @@ -0,0 +1,36 @@ +import { fileURLToPath } from 'node:url' +import { isMemoryInstrumented } from './turn' + +/** Worker settings for the CodSpeed memory instrument. */ +export function memoryExecArgv() { + if (!isMemoryInstrumented()) { + return [] + } + + // CodSpeed supplies --no-opt, which only disables TurboFan on Node 24. + // Under --predictable, Maglev compilations run synchronously inside the + // request that triggers them, and the forced GC before the measured call can + // discard optimized code so recompiles land in the measured window. Their + // malloc'd Zone scratch (32 KiB segments) then dominates allocation metrics + // and depends on per-process feedback state. + // Limit variation from GC scheduling and bytecode reclamation; keep a + // fixed initial old-generation budget. + return [ + '--no-maglev', + '--no-flush-bytecode', + '--no-minor-gc-task', + '--no-incremental-marking', + '--initial-old-space-size=512', + ] +} + +export function memoryConfig(side: 'client' | 'server') { + const execArgv = memoryExecArgv() + return { + execArgv, + setupFiles: + side === 'client' + ? [fileURLToPath(new URL('./client/vitest.setup.ts', import.meta.url))] + : [], + } +} diff --git a/benchmarks/memory/server/bench-utils.ts b/benchmarks/memory/server/bench-utils.ts new file mode 100644 index 0000000000..9caaf63384 --- /dev/null +++ b/benchmarks/memory/server/bench-utils.ts @@ -0,0 +1,99 @@ +export { memoryBenchHooks } from '../turn' + +export interface StartRequestHandler { + fetch: (request: Request) => Promise | Response +} + +type RunSequentialRequestLoopRandomOptions = + | { + seed: number + random?: never + } + | { + random: () => number + seed?: never + } + +export type RunSequentialRequestLoopOptions = + RunSequentialRequestLoopRandomOptions & { + iterations?: number + buildRequest: (random: () => number, index: number) => Request + validateResponse?: (response: Response, request: Request) => void + } + +export const memoryBenchOptions = { + iterations: 1, + warmupIterations: 1, + time: 0, + warmupTime: 0, + throws: true, +} + +export function createDeterministicRandom(seed: number) { + let state = seed >>> 0 + + return () => { + state = (state * 1664525 + 1013904223) >>> 0 + return state / 0x100000000 + } +} + +export function randomSegment(random: () => number) { + return Math.floor(random() * 1_000_000_000).toString(36) +} + +export async function drainResponse(response: Response) { + const reader = response.body?.getReader() + + if (!reader) { + return + } + + try { + for (;;) { + const result = await reader.read() + + if (result.done) { + break + } + } + } finally { + reader.releaseLock() + } +} + +export async function runSequentialRequestLoop( + handler: StartRequestHandler, + options: RunSequentialRequestLoopOptions, +) { + const { iterations = 10, buildRequest, validateResponse } = options + const random = + options.seed !== undefined + ? createDeterministicRandom(options.seed) + : options.random + const validate = + validateResponse ?? + ((response: Response, request: Request) => { + if (response.status !== 200) { + throw new Error( + `Request failed with non-200 status ${response.status} (${request.url})`, + ) + } + }) + + for (let index = 0; index < iterations; index++) { + const request = buildRequest(random, index) + const response = await handler.fetch(request) + + validate(response, request) + + await drainResponse(response) + } +} + +// Cancellation can leave deferred loaders and renderer teardown queued. +export async function settle() { + for (let turn = 0; turn < 16; turn++) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } +} diff --git a/benchmarks/memory/server/benchmark.ts b/benchmarks/memory/server/benchmark.ts new file mode 100644 index 0000000000..9b8dc2c76f --- /dev/null +++ b/benchmarks/memory/server/benchmark.ts @@ -0,0 +1,13 @@ +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 +} + +export interface ServerMemoryWorkloadGroup { + sanity: () => Promise | void + workloads: Array +} diff --git a/benchmarks/memory/server/flame-runner.ts b/benchmarks/memory/server/flame-runner.ts new file mode 100644 index 0000000000..1930085aad --- /dev/null +++ b/benchmarks/memory/server/flame-runner.ts @@ -0,0 +1,12 @@ +import { profileFlameWorkload } from '../flame-control.ts' +import type { ServerMemoryWorkloadGroup } from './benchmark.ts' + +export async function runServerFlameBenchmark( + workloadGroup: ServerMemoryWorkloadGroup, +) { + await workloadGroup.sanity() + + for (const workload of workloadGroup.workloads) { + await profileFlameWorkload(workload.run, workload.name) + } +} diff --git a/benchmarks/memory/server/package.json b/benchmarks/memory/server/package.json new file mode 100644 index 0000000000..d09343c7b6 --- /dev/null +++ b/benchmarks/memory/server/package.json @@ -0,0 +1,283 @@ +{ + "name": "@benchmarks/memory-server", + "private": true, + "type": "module", + "scripts": { + "clean:profiles": "rm -rf scenarios/*/*/.profiles" + }, + "imports": { + "#memory-server/benchmark": "./benchmark.ts", + "#memory-server/bench-utils": "./bench-utils.ts", + "#memory-server/flame-runner": "./flame-runner.ts" + }, + "dependencies": { + "@tanstack/react-router": "workspace:*", + "@tanstack/react-start": "workspace:*", + "@tanstack/solid-router": "workspace:*", + "@tanstack/solid-start": "workspace:*", + "@tanstack/vue-router": "workspace:*", + "@tanstack/vue-start": "workspace:*", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "solid-js": "^1.9.10", + "vue": "^3.5.16" + }, + "devDependencies": { + "@codspeed/vitest-plugin": "^6.0.1", + "@datadog/pprof": "^5.13.2", + "@platformatic/flame": "^1.6.0", + "@vitejs/plugin-react": "^6.0.1", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "@types/react": "catalog:", + "@typescript/native": "npm:typescript@^7.0.2", + "jsdom": "29.1.1", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11", + "vitest": "catalog:" + }, + "nx": { + "targets": { + "build:react": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-server-request-churn-react", + "@benchmarks/memory-server-server-fn-churn-react", + "@benchmarks/memory-server-error-paths-react", + "@benchmarks/memory-server-aborted-requests-react", + "@benchmarks/memory-server-peak-large-page-react", + "@benchmarks/memory-server-streaming-peak-react", + "@benchmarks/memory-server-serialization-payload-react" + ], + "target": "build:ssr" + } + ] + }, + "build:solid": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-server-request-churn-solid", + "@benchmarks/memory-server-server-fn-churn-solid", + "@benchmarks/memory-server-error-paths-solid", + "@benchmarks/memory-server-aborted-requests-solid", + "@benchmarks/memory-server-peak-large-page-solid", + "@benchmarks/memory-server-streaming-peak-solid", + "@benchmarks/memory-server-serialization-payload-solid" + ], + "target": "build:ssr" + } + ] + }, + "build:vue": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-server-request-churn-vue", + "@benchmarks/memory-server-server-fn-churn-vue", + "@benchmarks/memory-server-error-paths-vue", + "@benchmarks/memory-server-aborted-requests-vue", + "@benchmarks/memory-server-peak-large-page-vue", + "@benchmarks/memory-server-streaming-peak-vue", + "@benchmarks/memory-server-serialization-payload-vue" + ], + "target": "build:ssr" + } + ] + }, + "build:react:flame": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-server-request-churn-react", + "@benchmarks/memory-server-server-fn-churn-react", + "@benchmarks/memory-server-error-paths-react", + "@benchmarks/memory-server-aborted-requests-react", + "@benchmarks/memory-server-peak-large-page-react", + "@benchmarks/memory-server-streaming-peak-react", + "@benchmarks/memory-server-serialization-payload-react" + ], + "target": "build:ssr:flame" + } + ] + }, + "build:solid:flame": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-server-request-churn-solid", + "@benchmarks/memory-server-server-fn-churn-solid", + "@benchmarks/memory-server-error-paths-solid", + "@benchmarks/memory-server-aborted-requests-solid", + "@benchmarks/memory-server-peak-large-page-solid", + "@benchmarks/memory-server-streaming-peak-solid", + "@benchmarks/memory-server-serialization-payload-solid" + ], + "target": "build:ssr:flame" + } + ] + }, + "build:vue:flame": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-server-request-churn-vue", + "@benchmarks/memory-server-server-fn-churn-vue", + "@benchmarks/memory-server-error-paths-vue", + "@benchmarks/memory-server-aborted-requests-vue", + "@benchmarks/memory-server-peak-large-page-vue", + "@benchmarks/memory-server-streaming-peak-vue", + "@benchmarks/memory-server-serialization-payload-vue" + ], + "target": "build:ssr:flame" + } + ] + }, + "test:flame:react": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-server-request-churn-react", + "@benchmarks/memory-server-server-fn-churn-react", + "@benchmarks/memory-server-error-paths-react", + "@benchmarks/memory-server-aborted-requests-react", + "@benchmarks/memory-server-peak-large-page-react", + "@benchmarks/memory-server-streaming-peak-react", + "@benchmarks/memory-server-serialization-payload-react" + ], + "target": "test:flame" + } + ] + }, + "test:flame:solid": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-server-request-churn-solid", + "@benchmarks/memory-server-server-fn-churn-solid", + "@benchmarks/memory-server-error-paths-solid", + "@benchmarks/memory-server-aborted-requests-solid", + "@benchmarks/memory-server-peak-large-page-solid", + "@benchmarks/memory-server-streaming-peak-solid", + "@benchmarks/memory-server-serialization-payload-solid" + ], + "target": "test:flame" + } + ] + }, + "test:flame:vue": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-server-request-churn-vue", + "@benchmarks/memory-server-server-fn-churn-vue", + "@benchmarks/memory-server-error-paths-vue", + "@benchmarks/memory-server-aborted-requests-vue", + "@benchmarks/memory-server-peak-large-page-vue", + "@benchmarks/memory-server-streaming-peak-vue", + "@benchmarks/memory-server-serialization-payload-vue" + ], + "target": "test:flame" + } + ] + }, + "test:perf:react": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": [ + "build:react" + ], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", + "cwd": "benchmarks/memory/server" + } + }, + "test:perf:solid": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": [ + "build:solid" + ], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", + "cwd": "benchmarks/memory/server" + } + }, + "test:perf:vue": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": [ + "build:vue" + ], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", + "cwd": "benchmarks/memory/server" + } + }, + "test:types": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": [ + "@benchmarks/memory-server-request-churn-react", + "@benchmarks/memory-server-server-fn-churn-react", + "@benchmarks/memory-server-error-paths-react", + "@benchmarks/memory-server-aborted-requests-react", + "@benchmarks/memory-server-peak-large-page-react", + "@benchmarks/memory-server-streaming-peak-react", + "@benchmarks/memory-server-serialization-payload-react", + "@benchmarks/memory-server-request-churn-solid", + "@benchmarks/memory-server-server-fn-churn-solid", + "@benchmarks/memory-server-error-paths-solid", + "@benchmarks/memory-server-aborted-requests-solid", + "@benchmarks/memory-server-peak-large-page-solid", + "@benchmarks/memory-server-streaming-peak-solid", + "@benchmarks/memory-server-serialization-payload-solid", + "@benchmarks/memory-server-request-churn-vue", + "@benchmarks/memory-server-server-fn-churn-vue", + "@benchmarks/memory-server-error-paths-vue", + "@benchmarks/memory-server-aborted-requests-vue", + "@benchmarks/memory-server-peak-large-page-vue", + "@benchmarks/memory-server-streaming-peak-vue", + "@benchmarks/memory-server-serialization-payload-vue" + ], + "target": "test:types:ssr" + } + ], + "options": { + "command": "tsc -p ./tsconfig.json --noEmit", + "cwd": "benchmarks/memory/server" + }, + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "dependentTaskOutputs", + "{workspaceRoot}/benchmarks/memory/*.ts" + ] + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts b/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts new file mode 100644 index 0000000000..7a1cd6d254 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts @@ -0,0 +1,57 @@ +const recordCount = 20 + +export type RecordGroup = 'alpha' | 'beta' + +export interface DeferredRecord { + id: string + label: string +} + +export function makeAbortedRequestRecords( + id: string, + group: RecordGroup, +): Array { + return Array.from({ length: recordCount }, (_, index) => ({ + id: `${group}-${id}-${index}`, + label: `deferred-${group}-${id}-${index}`, + })) +} + +// Abort probes keep their deferred payload pending until the request is +// cancelled. Timer chains can outlive cancellation and spill into the next +// measured request; route-loader signals stop observing the request after load. +export function makeDeferredRecords( + id: string, + group: RecordGroup, + signal: AbortSignal, +): Promise> { + return new Promise((resolve) => { + if (signal.aborted) { + resolve([]) + return + } + + let timeoutId: ReturnType | undefined + const onAbort = () => { + clearTimeout(timeoutId) + resolve([]) + } + signal.addEventListener('abort', onAbort, { once: true }) + + if (id === 'sanity-mid-stream' || id.startsWith('abort-')) { + return + } + + let remaining = group === 'alpha' ? 4 : 6 + const step = () => { + remaining -= 1 + if (remaining === 0) { + signal.removeEventListener('abort', onAbort) + resolve(makeAbortedRequestRecords(id, group)) + return + } + timeoutId = setTimeout(step, 0) + } + timeoutId = setTimeout(step, 0) + }) +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts b/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/memory.flame.ts b/benchmarks/memory/server/scenarios/aborted-requests/react/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/project.json b/benchmarks/memory/server/scenarios/aborted-requests/react/project.json new file mode 100644 index 0000000000..bea90c8766 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-aborted-requests-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/setup.ts b/benchmarks/memory/server/scenarios/aborted-requests/react/setup.ts new file mode 100644 index 0000000000..0c98f54ddd --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/aborted-requests/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..fbbc25ecfb --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/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 StreamIdRouteImport } from './routes/stream.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const StreamIdRoute = StreamIdRouteImport.update({ + id: '/stream/$id', + path: '/stream/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/stream/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/stream/$id' + id: '__root__' | '/' | '/stream/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + StreamIdRoute: typeof StreamIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/stream/$id': { + id: '/stream/$id' + path: '/stream/$id' + fullPath: '/stream/$id' + preLoaderRoute: typeof StreamIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + StreamIdRoute: StreamIdRoute, +} +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/benchmarks/memory/server/scenarios/aborted-requests/react/src/router.tsx b/benchmarks/memory/server/scenarios/aborted-requests/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/__root.tsx new file mode 100644 index 0000000000..c5f9de6922 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/index.tsx b/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/index.tsx new file mode 100644 index 0000000000..08d534a779 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
aborted-requests-index
+} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/stream.$id.tsx new file mode 100644 index 0000000000..ecd9ef524d --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/src/routes/stream.$id.tsx @@ -0,0 +1,66 @@ +import { Await, createFileRoute } from '@tanstack/react-router' +import { Suspense } from 'react' +import { makeAbortedRequestRecords } from '../../../deferred-records' + +function resolveAfterMicrotasks(microtasks: number, value: () => T) { + let promise = Promise.resolve() + + for (let index = 0; index < microtasks; index++) { + promise = promise.then(() => undefined) + } + + return promise.then(value) +} + +export const Route = createFileRoute('/stream/$id')({ + loader: ({ params }) => ({ + eager: `eager-${params.id}`, + alpha: resolveAfterMicrotasks(32, () => + makeAbortedRequestRecords(params.id, 'alpha'), + ), + beta: resolveAfterMicrotasks(64, () => + makeAbortedRequestRecords(params.id, 'beta'), + ), + }), + component: StreamComponent, +}) + +function StreamComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data.eager}

+ loading-alpha

+ } + > + + {(records) => ( +
    + {records.map((record) => ( +
  • {record.label}
  • + ))} +
+ )} +
+
+ loading-beta

+ } + > + + {(records) => ( +
    + {records.map((record) => ( +
  • {record.label}
  • + ))} +
+ )} +
+
+
+ ) +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/tsconfig.json b/benchmarks/memory/server/scenarios/aborted-requests/react/tsconfig.json new file mode 100644 index 0000000000..11ddcce4ea --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts b/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts new file mode 100644 index 0000000000..eff0d0e043 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts @@ -0,0 +1,31 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server aborted-requests (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/shared.ts b/benchmarks/memory/server/scenarios/aborted-requests/shared.ts new file mode 100644 index 0000000000..29eca99e00 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/shared.ts @@ -0,0 +1,235 @@ +import { settle } from '#memory-server/bench-utils' +import type { StartRequestHandler } from '#memory-server/bench-utils' + +export type { StartRequestHandler } + +type Framework = 'react' | 'solid' | 'vue' + +type AbortedRequestReadMode = 'first-chunk' | 'shell-before-deferred' +const abortedRequestIterations = 40 +let abortedRequestCounter = 0 +const eagerMarker = 'data-bench="aborted-requests-eager"' +const alphaFallbackMarker = 'data-bench="aborted-requests-alpha-fallback"' +const betaFallbackMarker = 'data-bench="aborted-requests-beta-fallback"' +const alphaFirstRecord = (id: string) => `deferred-alpha-${id}-0` +const alphaLastRecord = (id: string) => `deferred-alpha-${id}-19` +const betaFirstRecord = (id: string) => `deferred-beta-${id}-0` +const betaLastRecord = (id: string) => `deferred-beta-${id}-19` + +const textDecoder = new TextDecoder() +const abortedRequestModes: Record = { + react: 'first-chunk', + solid: 'first-chunk', + vue: 'shell-before-deferred', +} + +const documentRequestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +function buildStreamRequest(id: string, signal?: AbortSignal) { + const init: RequestInit = { ...documentRequestInit } + + if (signal) { + init.signal = signal + } + + return new Request(`http://localhost/stream/${id}`, init) +} + +function validateDocumentResponse(response: Response, request: Request) { + if (response.status !== 200) { + throw new Error( + `Expected status 200 for ${request.url}, got ${response.status}`, + ) + } +} + +async function readFirstChunk(response: Response, request: Request) { + if (!response.body) { + throw new Error(`Expected response body for ${request.url}`) + } + + const reader = response.body.getReader() + const result = await reader.read() + const value = result.value + + if (result.done || !value || value.byteLength === 0) { + await reader.cancel() + throw new Error(`Expected a non-empty first chunk for ${request.url}`) + } + + return { + reader, + value, + } +} + +async function readShellBeforeDeferred( + response: Response, + request: Request, + id: string, +) { + if (!response.body) { + throw new Error(`Expected response body for ${request.url}`) + } + + const reader = response.body.getReader() + let text = '' + + for (;;) { + const result = await reader.read() + const value = result.value + + if (result.done || !value || value.byteLength === 0) { + await reader.cancel() + throw new Error(`Expected shell content for ${request.url}`) + } + + text += textDecoder.decode(value, { stream: true }) + + for (const marker of [ + alphaFirstRecord(id), + alphaLastRecord(id), + betaFirstRecord(id), + betaLastRecord(id), + ]) { + if (text.includes(marker)) { + await reader.cancel() + throw new Error( + `Shell chunks already included deferred content ${marker}`, + ) + } + } + + if ( + text.includes(eagerMarker) && + text.includes(alphaFallbackMarker) && + text.includes(betaFallbackMarker) + ) { + return { + reader, + text, + } + } + } +} + +async function readSanityStream( + response: Response, + request: Request, + mode: AbortedRequestReadMode, + id: string, +) { + if (mode === 'shell-before-deferred') { + return readShellBeforeDeferred(response, request, id) + } + + const { reader, value } = await readFirstChunk(response, request) + + return { + reader, + text: textDecoder.decode(value), + } +} + +function readLoopStream( + mode: AbortedRequestReadMode, + response: Response, + request: Request, + id: string, +) { + if (mode === 'shell-before-deferred') { + return readShellBeforeDeferred(response, request, id) + } + + return readFirstChunk(response, request) +} + +async function cancelReader(reader: ReadableStreamDefaultReader) { + try { + await reader.cancel() + } catch (error) { + if (!(error instanceof DOMException && error.name === 'AbortError')) { + throw error + } + } +} + +async function assertAbortedRequestsSanity( + handler: StartRequestHandler, + mode: AbortedRequestReadMode, +) { + const fullId = 'sanity-full' + const fullRequest = buildStreamRequest(fullId) + const fullResponse = await handler.fetch(fullRequest) + validateDocumentResponse(fullResponse, fullRequest) + + const fullBody = await fullResponse.text() + + if (!fullBody.includes(eagerMarker)) { + throw new Error('Expected full sanity response to include the eager marker') + } + + const midStreamId = 'sanity-mid-stream' + const controller = new AbortController() + const midStreamRequest = buildStreamRequest(midStreamId, controller.signal) + const midStreamResponse = await handler.fetch(midStreamRequest) + validateDocumentResponse(midStreamResponse, midStreamRequest) + + const { reader, text } = await readSanityStream( + midStreamResponse, + midStreamRequest, + mode, + midStreamId, + ) + + if (!text.includes(eagerMarker)) { + throw new Error('Expected sanity stream to include the eager marker') + } + + // reader.cancel() is the response-stream cancellation path if the handler + // does not observe Request.signal for this in-process request. + controller.abort() + await cancelReader(reader) + await settle() +} + +async function runAbortedRequestLoop( + handler: StartRequestHandler, + mode: AbortedRequestReadMode, +) { + for (let index = 0; index < abortedRequestIterations; index++) { + const controller = new AbortController() + const id = `abort-${(abortedRequestCounter++).toString(36)}` + const request = buildStreamRequest(id, controller.signal) + const response = await handler.fetch(request) + validateDocumentResponse(response, request) + + const { reader } = await readLoopStream(mode, response, request, id) + controller.abort() + await cancelReader(reader) + await settle() + } +} + +export function createWorkloadGroup( + framework: Framework, + handler: StartRequestHandler, +) { + const mode = abortedRequestModes[framework] + const run = async () => runAbortedRequestLoop(handler, mode) + + return { + sanity: () => assertAbortedRequestsSanity(handler, mode), + workloads: [ + { + name: `mem server aborted-requests (${framework})`, + run, + }, + ], + } +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.flame.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/project.json b/benchmarks/memory/server/scenarios/aborted-requests/solid/project.json new file mode 100644 index 0000000000..345fcc0720 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-aborted-requests-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/setup.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/setup.ts new file mode 100644 index 0000000000..4fe85c3f00 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..04ebed80f0 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/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 StreamIdRouteImport } from './routes/stream.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const StreamIdRoute = StreamIdRouteImport.update({ + id: '/stream/$id', + path: '/stream/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/stream/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/stream/$id' + id: '__root__' | '/' | '/stream/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + StreamIdRoute: typeof StreamIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/stream/$id': { + id: '/stream/$id' + path: '/stream/$id' + fullPath: '/stream/$id' + preLoaderRoute: typeof StreamIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + StreamIdRoute: StreamIdRoute, +} +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/benchmarks/memory/server/scenarios/aborted-requests/solid/src/router.tsx b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..aaf7dfdd89 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' +import { HydrationScript } from 'solid-js/web' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charset: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/index.tsx b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/index.tsx new file mode 100644 index 0000000000..3aac56e824 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
aborted-requests-index
+} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/stream.$id.tsx new file mode 100644 index 0000000000..bf6af17f31 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/stream.$id.tsx @@ -0,0 +1,69 @@ +import { createServerOnlyFn } from '@tanstack/solid-start' +import { getRequest } from '@tanstack/solid-start/server' +import { createFileRoute } from '@tanstack/solid-router' +import { Show, Suspense, createResource } from 'solid-js' +import { makeDeferredRecords } from '../../../deferred-records' +import type { DeferredRecord } from '../../../deferred-records' + +const getRequestSignal = createServerOnlyFn(() => getRequest().signal) + +export const Route = createFileRoute('/stream/$id')({ + loader: ({ params }) => ({ + eager: `eager-${params.id}`, + alpha: makeDeferredRecords(params.id, 'alpha', getRequestSignal()), + beta: makeDeferredRecords(params.id, 'beta', getRequestSignal()), + }), + component: StreamComponent, +}) + +function StreamComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data().eager}

+ loading-alpha

+ } + > + +
+ loading-beta

+ } + > + +
+
+ ) +} + +function DeferredRecords(props: { + promise: Promise> + dataBench: string +}) { + const [records] = createResource( + () => props.promise, + (promise) => promise, + ) + + return ( + + {(resolvedRecords) => ( +
    + {resolvedRecords().map((record) => ( +
  • {record.label}
  • + ))} +
+ )} +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/tsconfig.json b/benchmarks/memory/server/scenarios/aborted-requests/solid/tsconfig.json new file mode 100644 index 0000000000..4b61264e11 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts new file mode 100644 index 0000000000..d7fd3459ee --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts @@ -0,0 +1,36 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server aborted-requests (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.flame.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/project.json b/benchmarks/memory/server/scenarios/aborted-requests/vue/project.json new file mode 100644 index 0000000000..8ca7d84660 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-aborted-requests-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/setup.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/setup.ts new file mode 100644 index 0000000000..6683dafe6b --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..192f1d6dc7 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/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 StreamIdRouteImport } from './routes/stream.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const StreamIdRoute = StreamIdRouteImport.update({ + id: '/stream/$id', + path: '/stream/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/stream/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/stream/$id' + id: '__root__' | '/' | '/stream/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + StreamIdRoute: typeof StreamIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/stream/$id': { + id: '/stream/$id' + path: '/stream/$id' + fullPath: '/stream/$id' + preLoaderRoute: typeof StreamIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + StreamIdRoute: StreamIdRoute, +} +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/benchmarks/memory/server/scenarios/aborted-requests/vue/src/router.tsx b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..de29ee1612 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/index.tsx b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/index.tsx new file mode 100644 index 0000000000..af662b29f7 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
aborted-requests-index
+} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/stream.$id.tsx new file mode 100644 index 0000000000..e41af03c16 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/stream.$id.tsx @@ -0,0 +1,65 @@ +import { createServerOnlyFn } from '@tanstack/vue-start' +import { getRequest } from '@tanstack/vue-start/server' +import { Await, createFileRoute } from '@tanstack/vue-router' +import { Suspense, defineComponent } from 'vue' +import { makeDeferredRecords } from '../../../deferred-records' +import type { DeferredRecord } from '../../../deferred-records' + +const getRequestSignal = createServerOnlyFn(() => getRequest().signal) + +const StreamComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

{data.value.eager}

+

loading-alpha

+

loading-beta

+ + {{ + default: () => ( + ) => ( +
    + {records.map((record) => ( +
  • {record.label}
  • + ))} +
+ )} + /> + ), + fallback: () => null, + }} +
+ + {{ + default: () => ( + ) => ( +
    + {records.map((record) => ( +
  • {record.label}
  • + ))} +
+ )} + /> + ), + fallback: () => null, + }} +
+
+ ) + }, +}) + +export const Route = createFileRoute('/stream/$id')({ + loader: ({ params }) => ({ + eager: `eager-${params.id}`, + alpha: makeDeferredRecords(params.id, 'alpha', getRequestSignal()), + beta: makeDeferredRecords(params.id, 'beta', getRequestSignal()), + }), + component: StreamComponent, +}) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/tsconfig.json b/benchmarks/memory/server/scenarios/aborted-requests/vue/tsconfig.json new file mode 100644 index 0000000000..9ad6481342 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts new file mode 100644 index 0000000000..e4e1eb66d4 --- /dev/null +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts @@ -0,0 +1,31 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server aborted-requests (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts new file mode 100644 index 0000000000..a6f07b97be --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[0]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts new file mode 100644 index 0000000000..89071137c3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[2]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/memory.flame.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/memory.not-found.bench.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.not-found.bench.ts new file mode 100644 index 0000000000..fa6a6693ed --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.not-found.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[1]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts new file mode 100644 index 0000000000..b2c3d24200 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[3]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/project.json b/benchmarks/memory/server/scenarios/error-paths/react/project.json new file mode 100644 index 0000000000..6a399fe41e --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-error-paths-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/setup.ts b/benchmarks/memory/server/scenarios/error-paths/react/setup.ts new file mode 100644 index 0000000000..0c98f54ddd --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/error-paths/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..4e8e4ce0e4 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/src/routeTree.gen.ts @@ -0,0 +1,146 @@ +/* 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 BoomIdRouteImport } from './routes/boom.$id' +import { Route as FromIdRouteImport } from './routes/from.$id' +import { Route as MissingIdRouteImport } from './routes/missing.$id' +import { Route as TargetIdRouteImport } from './routes/target.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const 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 MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/boom/$id' | '/from/$id' | '/missing/$id' | '/target/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/boom/$id' | '/from/$id' | '/missing/$id' | '/target/$id' + id: + | '__root__' + | '/' + | '/boom/$id' + | '/from/$id' + | '/missing/$id' + | '/target/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BoomIdRoute: typeof BoomIdRoute + FromIdRoute: typeof FromIdRoute + MissingIdRoute: typeof MissingIdRoute + TargetIdRoute: typeof TargetIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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 + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BoomIdRoute: BoomIdRoute, + FromIdRoute: FromIdRoute, + MissingIdRoute: MissingIdRoute, + TargetIdRoute: TargetIdRoute, +} +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/benchmarks/memory/server/scenarios/error-paths/react/src/router.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/router.tsx new file mode 100644 index 0000000000..e31bd0abf7 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/src/router.tsx @@ -0,0 +1,23 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + defaultNotFoundComponent: DefaultNotFound, + }) +} + +// Without this, every unmatched-URL request logs a router warning in +// non-production ad-hoc runs. +function DefaultNotFound() { + return

error-paths-unmatched

+} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/__root.tsx new file mode 100644 index 0000000000..c5f9de6922 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/boom.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/boom.$id.tsx new file mode 100644 index 0000000000..fafa81a9bb --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/boom.$id.tsx @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/boom/$id')({ + loader: ({ params }) => { + throw new Error(`boom-${params.id}`) + }, + errorComponent: BoomErrorComponent, + component: BoomComponent, +}) + +function BoomErrorComponent() { + return
error-paths-error-boundary
+} + +function BoomComponent() { + return null +} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/from.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/from.$id.tsx new file mode 100644 index 0000000000..4c45e76c92 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/from.$id.tsx @@ -0,0 +1,14 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/from/$id')({ + loader: ({ params }) => { + const { id } = params + + throw redirect({ to: '/target/$id', params: { id }, statusCode: 302 }) + }, + component: FromComponent, +}) + +function FromComponent() { + return null +} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/index.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/index.tsx new file mode 100644 index 0000000000..c5492486b4 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
error-paths-index
+} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/missing.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/missing.$id.tsx new file mode 100644 index 0000000000..84640e9712 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/missing.$id.tsx @@ -0,0 +1,19 @@ +import { createFileRoute, notFound } from '@tanstack/react-router' + +export const Route = createFileRoute('/missing/$id')({ + loader: () => { + throw notFound() + }, + notFoundComponent: MissingNotFoundComponent, + component: MissingComponent, +}) + +function MissingNotFoundComponent() { + return ( +
error-paths-not-found-boundary
+ ) +} + +function MissingComponent() { + return null +} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routes/target.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/target.$id.tsx new file mode 100644 index 0000000000..1c13394cb2 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/src/routes/target.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/target/$id')({ + component: TargetComponent, +}) + +function TargetComponent() { + const params = Route.useParams() + + return
{`target-${params.id}`}
+} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json b/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json new file mode 100644 index 0000000000..2dba47fc99 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory*.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts b/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts new file mode 100644 index 0000000000..c00de7727a --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + isolate: true, + ...memoryConfig('server'), + name: '@benchmarks/memory-server error-paths (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/shared.ts b/benchmarks/memory/server/scenarios/error-paths/shared.ts new file mode 100644 index 0000000000..11ed293d22 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/shared.ts @@ -0,0 +1,192 @@ +import { + createDeterministicRandom, + randomSegment, + runSequentialRequestLoop, +} from '#memory-server/bench-utils' +import type { StartRequestHandler } from '#memory-server/bench-utils' + +export type { StartRequestHandler } + +type Framework = 'react' | 'solid' | 'vue' + +const errorPathsIterations = 18 +const redirectSeed = 0xdecafbad +const notFoundSeed = 0xdecafb0d +const errorSeed = 0xdecafbed +const unmatchedSeed = 0xdecaf00d +const redirectStatus = 302 +const notFoundStatus = 404 +const errorStatus = 500 +// Module-level so each error-path bench keeps advancing across runner invocations. +const redirectRandom = createDeterministicRandom(redirectSeed) +const notFoundRandom = createDeterministicRandom(notFoundSeed) +const errorRandom = createDeterministicRandom(errorSeed) +const unmatchedRandom = createDeterministicRandom(unmatchedSeed) +let redirectCounter = 0 +let notFoundCounter = 0 +let errorCounter = 0 +let unmatchedCounter = 0 + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +function buildRedirectRequest(random: () => number) { + const id = `${(redirectCounter++).toString(36)}-${randomSegment(random)}` + + return new Request(`http://localhost/from/${id}`, requestInit) +} + +function buildNotFoundRequest(random: () => number) { + const id = `${(notFoundCounter++).toString(36)}-${randomSegment(random)}` + + return new Request(`http://localhost/missing/${id}`, requestInit) +} + +function buildErrorRequest(random: () => number) { + const id = `${(errorCounter++).toString(36)}-${randomSegment(random)}` + + return new Request(`http://localhost/boom/${id}`, requestInit) +} + +function buildUnmatchedRequest(random: () => number) { + const id = `${(unmatchedCounter++).toString(36)}-${randomSegment(random)}` + + return new Request(`http://localhost/nope/${id}`, requestInit) +} + +function getRequestId(request: Request) { + const id = new URL(request.url).pathname.split('/').pop() + + if (!id) { + throw new Error(`Expected request id in ${request.url}`) + } + + return id +} + +function validateRedirectResponse(response: Response, request: Request) { + if (response.status !== redirectStatus) { + throw new Error( + `Expected status ${redirectStatus} for ${request.url}, got ${response.status}`, + ) + } + + const id = getRequestId(request) + const location = response.headers.get('location') + + if (location !== `/target/${id}`) { + throw new Error(`Expected redirect location /target/${id}, got ${location}`) + } +} + +function validateNotFoundResponse(response: Response, request: Request) { + if (response.status !== notFoundStatus) { + throw new Error( + `Expected status ${notFoundStatus} for ${request.url}, got ${response.status}`, + ) + } +} + +function validateErrorResponse(response: Response, request: Request) { + if (response.status !== errorStatus) { + throw new Error( + `Expected status ${errorStatus} for ${request.url}, got ${response.status}`, + ) + } +} + +async function assertStatusSanity( + handler: StartRequestHandler, + request: Request, + validateResponse: (response: Response, request: Request) => void, +) { + const response = await handler.fetch(request) + validateResponse(response, request) + await response.text() +} + +async function assertErrorPathsSanity(handler: StartRequestHandler) { + await assertStatusSanity( + handler, + new Request('http://localhost/from/sanity-redirect', requestInit), + validateRedirectResponse, + ) + await assertStatusSanity( + handler, + new Request('http://localhost/missing/sanity-missing', requestInit), + validateNotFoundResponse, + ) + await assertStatusSanity( + handler, + new Request('http://localhost/boom/sanity-error', requestInit), + validateErrorResponse, + ) + await assertStatusSanity( + handler, + new Request('http://localhost/nope/sanity-unmatched', requestInit), + validateNotFoundResponse, + ) +} + +export function createWorkloadGroup( + framework: Framework, + handler: StartRequestHandler, +) { + const runRedirect = async () => + runSequentialRequestLoop(handler, { + random: redirectRandom, + iterations: errorPathsIterations, + buildRequest: buildRedirectRequest, + validateResponse: validateRedirectResponse, + }) + + const runNotFound = async () => + runSequentialRequestLoop(handler, { + random: notFoundRandom, + iterations: errorPathsIterations, + buildRequest: buildNotFoundRequest, + validateResponse: validateNotFoundResponse, + }) + + const runError = async () => + runSequentialRequestLoop(handler, { + random: errorRandom, + iterations: errorPathsIterations, + buildRequest: buildErrorRequest, + validateResponse: validateErrorResponse, + }) + + const runUnmatched = async () => + runSequentialRequestLoop(handler, { + random: unmatchedRandom, + iterations: errorPathsIterations, + buildRequest: buildUnmatchedRequest, + validateResponse: validateNotFoundResponse, + }) + + return { + sanity: () => assertErrorPathsSanity(handler), + workloads: [ + { + name: `mem server error-paths redirect (${framework})`, + run: runRedirect, + }, + { + name: `mem server error-paths not-found (${framework})`, + run: runNotFound, + }, + { + name: `mem server error-paths error (${framework})`, + run: runError, + }, + { + name: `mem server error-paths unmatched (${framework})`, + run: runUnmatched, + }, + ], + } +} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts new file mode 100644 index 0000000000..a6f07b97be --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[0]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts new file mode 100644 index 0000000000..89071137c3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[2]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.flame.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.not-found.bench.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.not-found.bench.ts new file mode 100644 index 0000000000..fa6a6693ed --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.not-found.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[1]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts new file mode 100644 index 0000000000..b2c3d24200 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[3]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/project.json b/benchmarks/memory/server/scenarios/error-paths/solid/project.json new file mode 100644 index 0000000000..77fcfaf578 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-error-paths-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/setup.ts b/benchmarks/memory/server/scenarios/error-paths/solid/setup.ts new file mode 100644 index 0000000000..4fe85c3f00 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/error-paths/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..32a4d56d3a --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/src/routeTree.gen.ts @@ -0,0 +1,146 @@ +/* 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 TargetIdRouteImport } from './routes/target.$id' +import { Route as MissingIdRouteImport } from './routes/missing.$id' +import { Route as FromIdRouteImport } from './routes/from.$id' +import { Route as BoomIdRouteImport } from './routes/boom.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', + getParentRoute: () => rootRouteImport, +} as any) +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) +const 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) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/boom/$id' | '/from/$id' | '/missing/$id' | '/target/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/boom/$id' | '/from/$id' | '/missing/$id' | '/target/$id' + id: + | '__root__' + | '/' + | '/boom/$id' + | '/from/$id' + | '/missing/$id' + | '/target/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BoomIdRoute: typeof BoomIdRoute + FromIdRoute: typeof FromIdRoute + MissingIdRoute: typeof MissingIdRoute + TargetIdRoute: typeof TargetIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport + parentRoute: typeof rootRouteImport + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + '/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 + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BoomIdRoute: BoomIdRoute, + FromIdRoute: FromIdRoute, + MissingIdRoute: MissingIdRoute, + TargetIdRoute: TargetIdRoute, +} +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/benchmarks/memory/server/scenarios/error-paths/solid/src/router.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/router.tsx new file mode 100644 index 0000000000..ae51f8b5e9 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/src/router.tsx @@ -0,0 +1,23 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + defaultNotFoundComponent: DefaultNotFound, + }) +} + +// Without this, every unmatched-URL request logs a router warning in +// non-production ad-hoc runs. +function DefaultNotFound() { + return

error-paths-unmatched

+} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..aaf7dfdd89 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' +import { HydrationScript } from 'solid-js/web' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charset: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/boom.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/boom.$id.tsx new file mode 100644 index 0000000000..bebc638caa --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/boom.$id.tsx @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/boom/$id')({ + loader: ({ params }) => { + throw new Error(`boom-${params.id}`) + }, + errorComponent: BoomErrorComponent, + component: BoomComponent, +}) + +function BoomErrorComponent() { + return
error-paths-error-boundary
+} + +function BoomComponent() { + return null +} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/from.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/from.$id.tsx new file mode 100644 index 0000000000..e96b7864f2 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/from.$id.tsx @@ -0,0 +1,14 @@ +import { createFileRoute, redirect } from '@tanstack/solid-router' + +export const Route = createFileRoute('/from/$id')({ + loader: ({ params }) => { + const { id } = params + + throw redirect({ to: '/target/$id', params: { id }, statusCode: 302 }) + }, + component: FromComponent, +}) + +function FromComponent() { + return null +} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/index.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/index.tsx new file mode 100644 index 0000000000..43282af801 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
error-paths-index
+} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/missing.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/missing.$id.tsx new file mode 100644 index 0000000000..1b9ec5e29d --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/missing.$id.tsx @@ -0,0 +1,19 @@ +import { createFileRoute, notFound } from '@tanstack/solid-router' + +export const Route = createFileRoute('/missing/$id')({ + loader: () => { + throw notFound() + }, + notFoundComponent: MissingNotFoundComponent, + component: MissingComponent, +}) + +function MissingNotFoundComponent() { + return ( +
error-paths-not-found-boundary
+ ) +} + +function MissingComponent() { + return null +} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/target.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/target.$id.tsx new file mode 100644 index 0000000000..4196fc1183 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/src/routes/target.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/target/$id')({ + component: TargetComponent, +}) + +function TargetComponent() { + const params = Route.useParams() + + return
{`target-${params().id}`}
+} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json b/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json new file mode 100644 index 0000000000..1e8103127a --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory*.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts b/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts new file mode 100644 index 0000000000..d7a0bb51b0 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + isolate: true, + ...memoryConfig('server'), + name: '@benchmarks/memory-server error-paths (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts new file mode 100644 index 0000000000..a6f07b97be --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[0]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts new file mode 100644 index 0000000000..89071137c3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[2]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.flame.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.not-found.bench.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.not-found.bench.ts new file mode 100644 index 0000000000..fa6a6693ed --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.not-found.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[1]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts new file mode 100644 index 0000000000..b2c3d24200 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[3]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/project.json b/benchmarks/memory/server/scenarios/error-paths/vue/project.json new file mode 100644 index 0000000000..8472470bde --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-error-paths-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/setup.ts b/benchmarks/memory/server/scenarios/error-paths/vue/setup.ts new file mode 100644 index 0000000000..6683dafe6b --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/error-paths/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..ea5bafa386 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/src/routeTree.gen.ts @@ -0,0 +1,146 @@ +/* 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 TargetIdRouteImport } from './routes/target.$id' +import { Route as MissingIdRouteImport } from './routes/missing.$id' +import { Route as FromIdRouteImport } from './routes/from.$id' +import { Route as BoomIdRouteImport } from './routes/boom.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', + getParentRoute: () => rootRouteImport, +} as any) +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) +const 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) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/boom/$id' | '/from/$id' | '/missing/$id' | '/target/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/boom/$id' | '/from/$id' | '/missing/$id' | '/target/$id' + id: + | '__root__' + | '/' + | '/boom/$id' + | '/from/$id' + | '/missing/$id' + | '/target/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BoomIdRoute: typeof BoomIdRoute + FromIdRoute: typeof FromIdRoute + MissingIdRoute: typeof MissingIdRoute + TargetIdRoute: typeof TargetIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport + parentRoute: typeof rootRouteImport + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + '/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 + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BoomIdRoute: BoomIdRoute, + FromIdRoute: FromIdRoute, + MissingIdRoute: MissingIdRoute, + TargetIdRoute: TargetIdRoute, +} +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/benchmarks/memory/server/scenarios/error-paths/vue/src/router.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..de29ee1612 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/boom.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/boom.$id.tsx new file mode 100644 index 0000000000..d933b93df2 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/boom.$id.tsx @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/boom/$id')({ + loader: ({ params }) => { + throw new Error(`boom-${params.id}`) + }, + errorComponent: BoomErrorComponent, + component: BoomComponent, +}) + +function BoomErrorComponent() { + return
error-paths-error-boundary
+} + +function BoomComponent() { + return <> +} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/from.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/from.$id.tsx new file mode 100644 index 0000000000..6ffba96bce --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/from.$id.tsx @@ -0,0 +1,14 @@ +import { createFileRoute, redirect } from '@tanstack/vue-router' + +export const Route = createFileRoute('/from/$id')({ + loader: ({ params }) => { + const { id } = params + + throw redirect({ to: '/target/$id', params: { id }, statusCode: 302 }) + }, + component: FromComponent, +}) + +function FromComponent() { + return <> +} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/index.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/index.tsx new file mode 100644 index 0000000000..53fb604c60 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
error-paths-index
+} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/missing.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/missing.$id.tsx new file mode 100644 index 0000000000..0e4972f5c6 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/missing.$id.tsx @@ -0,0 +1,19 @@ +import { createFileRoute, notFound } from '@tanstack/vue-router' + +export const Route = createFileRoute('/missing/$id')({ + loader: () => { + throw notFound() + }, + notFoundComponent: MissingNotFoundComponent, + component: MissingComponent, +}) + +function MissingNotFoundComponent() { + return ( +
error-paths-not-found-boundary
+ ) +} + +function MissingComponent() { + return <> +} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/target.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/target.$id.tsx new file mode 100644 index 0000000000..0bbf4a3dc6 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/target.$id.tsx @@ -0,0 +1,14 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const TargetComponent = defineComponent({ + setup() { + const params = Route.useParams() + + return () =>
{`target-${params.value.id}`}
+ }, +}) + +export const Route = createFileRoute('/target/$id')({ + component: TargetComponent, +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json b/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json new file mode 100644 index 0000000000..af8b83005c --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory*.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts b/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts new file mode 100644 index 0000000000..3dc0762aa0 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + isolate: true, + ...memoryConfig('server'), + name: '@benchmarks/memory-server error-paths (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/large-page-data.ts b/benchmarks/memory/server/scenarios/peak-large-page/large-page-data.ts new file mode 100644 index 0000000000..8f77c58731 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/large-page-data.ts @@ -0,0 +1,111 @@ +export interface LargePageRecord { + id: string + name: string + description: string +} + +export interface LargePageLevelData { + level: number + marker: string + records: Array +} + +const recordCount = 200 +const descriptionLength = 104 + +export function makeLargePageLevelData(level: number, seed: number) { + const random = createDeterministicRandom(seed) + + return { + level, + marker: makeLargePageMarker(level), + records: Array.from({ length: recordCount }, (_, index) => { + const idToken = randomSegment(random) + const descriptionTokenA = randomSegment(random) + const descriptionTokenB = randomSegment(random) + + return { + id: `l${level}-${index}-${idToken}`, + name: makeLargePageRecordName(level, index), + description: makeDescription( + level, + index, + descriptionTokenA, + descriptionTokenB, + ), + } + }), + } satisfies LargePageLevelData +} + +export function makeLargePageHead(loaderData: LargePageLevelData | undefined) { + if (!loaderData) { + return { + meta: [{ title: 'Peak Large Page' }], + } + } + + const first = loaderData.records[0]! + const last = loaderData.records[loaderData.records.length - 1]! + + return { + meta: [ + { title: `Peak Large Page L${loaderData.level} ${first.name}` }, + { + name: `peak-large-page-l${loaderData.level}-count`, + content: String(loaderData.records.length), + }, + { + name: `peak-large-page-l${loaderData.level}-first-id`, + content: first.id, + }, + { + name: `peak-large-page-l${loaderData.level}-first-name`, + content: first.name, + }, + { + name: `peak-large-page-l${loaderData.level}-last-id`, + content: last.id, + }, + { + name: `peak-large-page-l${loaderData.level}-description`, + content: first.description, + }, + ], + } +} + +function makeLargePageRecordName(level: number, index: number) { + return `peak-large-page-l${level}-record-${index}` +} + +function makeLargePageMarker(level: number) { + return `peak-large-page-level-${level}` +} + +function makeDescription( + level: number, + index: number, + tokenA: string, + tokenB: string, +) { + return `Level ${level} record ${index} uses seeded fragments ${tokenA} and ${tokenB} to keep a fresh deterministic loader payload.`.padEnd( + descriptionLength, + 'x', + ) +} + +// Local copy of the LCG from benchmarks/memory/server/bench-utils.ts - app +// source cannot import from outside the app root. Keep in sync. +function createDeterministicRandom(seed: number) { + let state = seed >>> 0 + + return () => { + state = (state * 1664525 + 1013904223) >>> 0 + return state / 0x100000000 + } +} + +function randomSegment(random: () => number) { + return Math.floor(random() * 1_000_000_000).toString(36) +} 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 new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/memory.flame.ts b/benchmarks/memory/server/scenarios/peak-large-page/react/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/project.json b/benchmarks/memory/server/scenarios/peak-large-page/react/project.json new file mode 100644 index 0000000000..699a243a03 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-peak-large-page-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/setup.ts b/benchmarks/memory/server/scenarios/peak-large-page/react/setup.ts new file mode 100644 index 0000000000..0c98f54ddd --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..6004590f9b --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routeTree.gen.ts @@ -0,0 +1,305 @@ +/* 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 L1RouteImport } from './routes/l1' +import { Route as L1L2RouteImport } from './routes/l1.l2' +import { Route as L1L2L3RouteImport } from './routes/l1.l2.l3' +import { Route as L1L2L3L4RouteImport } from './routes/l1.l2.l3.l4' +import { Route as L1L2L3L4L5RouteImport } from './routes/l1.l2.l3.l4.l5' +import { Route as L1L2L3L4L5L6RouteImport } from './routes/l1.l2.l3.l4.l5.l6' +import { Route as L1L2L3L4L5L6L7RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7' +import { Route as L1L2L3L4L5L6L7L8RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7.l8' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const L1Route = L1RouteImport.update({ + id: '/l1', + path: '/l1', + getParentRoute: () => rootRouteImport, +} as any) +const L1L2Route = L1L2RouteImport.update({ + id: '/l2', + path: '/l2', + getParentRoute: () => L1Route, +} as any) +const L1L2L3Route = L1L2L3RouteImport.update({ + id: '/l3', + path: '/l3', + getParentRoute: () => L1L2Route, +} as any) +const L1L2L3L4Route = L1L2L3L4RouteImport.update({ + id: '/l4', + path: '/l4', + getParentRoute: () => L1L2L3Route, +} as any) +const L1L2L3L4L5Route = L1L2L3L4L5RouteImport.update({ + id: '/l5', + path: '/l5', + getParentRoute: () => L1L2L3L4Route, +} as any) +const L1L2L3L4L5L6Route = L1L2L3L4L5L6RouteImport.update({ + id: '/l6', + path: '/l6', + getParentRoute: () => L1L2L3L4L5Route, +} as any) +const L1L2L3L4L5L6L7Route = L1L2L3L4L5L6L7RouteImport.update({ + id: '/l7', + path: '/l7', + getParentRoute: () => L1L2L3L4L5L6Route, +} as any) +const L1L2L3L4L5L6L7L8Route = L1L2L3L4L5L6L7L8RouteImport.update({ + id: '/l8', + path: '/l8', + getParentRoute: () => L1L2L3L4L5L6L7Route, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/l1': typeof L1RouteWithChildren + '/l1/l2': typeof L1L2RouteWithChildren + '/l1/l2/l3': typeof L1L2L3RouteWithChildren + '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren + '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren + '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/l1': typeof L1RouteWithChildren + '/l1/l2': typeof L1L2RouteWithChildren + '/l1/l2/l3': typeof L1L2L3RouteWithChildren + '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren + '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren + '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/l1': typeof L1RouteWithChildren + '/l1/l2': typeof L1L2RouteWithChildren + '/l1/l2/l3': typeof L1L2L3RouteWithChildren + '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren + '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren + '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/l1' + | '/l1/l2' + | '/l1/l2/l3' + | '/l1/l2/l3/l4' + | '/l1/l2/l3/l4/l5' + | '/l1/l2/l3/l4/l5/l6' + | '/l1/l2/l3/l4/l5/l6/l7' + | '/l1/l2/l3/l4/l5/l6/l7/l8' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/l1' + | '/l1/l2' + | '/l1/l2/l3' + | '/l1/l2/l3/l4' + | '/l1/l2/l3/l4/l5' + | '/l1/l2/l3/l4/l5/l6' + | '/l1/l2/l3/l4/l5/l6/l7' + | '/l1/l2/l3/l4/l5/l6/l7/l8' + id: + | '__root__' + | '/' + | '/l1' + | '/l1/l2' + | '/l1/l2/l3' + | '/l1/l2/l3/l4' + | '/l1/l2/l3/l4/l5' + | '/l1/l2/l3/l4/l5/l6' + | '/l1/l2/l3/l4/l5/l6/l7' + | '/l1/l2/l3/l4/l5/l6/l7/l8' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + L1Route: typeof L1RouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/l1': { + id: '/l1' + path: '/l1' + fullPath: '/l1' + preLoaderRoute: typeof L1RouteImport + parentRoute: typeof rootRouteImport + } + '/l1/l2': { + id: '/l1/l2' + path: '/l2' + fullPath: '/l1/l2' + preLoaderRoute: typeof L1L2RouteImport + parentRoute: typeof L1Route + } + '/l1/l2/l3': { + id: '/l1/l2/l3' + path: '/l3' + fullPath: '/l1/l2/l3' + preLoaderRoute: typeof L1L2L3RouteImport + parentRoute: typeof L1L2Route + } + '/l1/l2/l3/l4': { + id: '/l1/l2/l3/l4' + path: '/l4' + fullPath: '/l1/l2/l3/l4' + preLoaderRoute: typeof L1L2L3L4RouteImport + parentRoute: typeof L1L2L3Route + } + '/l1/l2/l3/l4/l5': { + id: '/l1/l2/l3/l4/l5' + path: '/l5' + fullPath: '/l1/l2/l3/l4/l5' + preLoaderRoute: typeof L1L2L3L4L5RouteImport + parentRoute: typeof L1L2L3L4Route + } + '/l1/l2/l3/l4/l5/l6': { + id: '/l1/l2/l3/l4/l5/l6' + path: '/l6' + fullPath: '/l1/l2/l3/l4/l5/l6' + preLoaderRoute: typeof L1L2L3L4L5L6RouteImport + parentRoute: typeof L1L2L3L4L5Route + } + '/l1/l2/l3/l4/l5/l6/l7': { + id: '/l1/l2/l3/l4/l5/l6/l7' + path: '/l7' + fullPath: '/l1/l2/l3/l4/l5/l6/l7' + preLoaderRoute: typeof L1L2L3L4L5L6L7RouteImport + parentRoute: typeof L1L2L3L4L5L6Route + } + '/l1/l2/l3/l4/l5/l6/l7/l8': { + id: '/l1/l2/l3/l4/l5/l6/l7/l8' + path: '/l8' + fullPath: '/l1/l2/l3/l4/l5/l6/l7/l8' + preLoaderRoute: typeof L1L2L3L4L5L6L7L8RouteImport + parentRoute: typeof L1L2L3L4L5L6L7Route + } + } +} + +interface L1L2L3L4L5L6L7RouteChildren { + L1L2L3L4L5L6L7L8Route: typeof L1L2L3L4L5L6L7L8Route +} + +const L1L2L3L4L5L6L7RouteChildren: L1L2L3L4L5L6L7RouteChildren = { + L1L2L3L4L5L6L7L8Route: L1L2L3L4L5L6L7L8Route, +} + +const L1L2L3L4L5L6L7RouteWithChildren = L1L2L3L4L5L6L7Route._addFileChildren( + L1L2L3L4L5L6L7RouteChildren, +) + +interface L1L2L3L4L5L6RouteChildren { + L1L2L3L4L5L6L7Route: typeof L1L2L3L4L5L6L7RouteWithChildren +} + +const L1L2L3L4L5L6RouteChildren: L1L2L3L4L5L6RouteChildren = { + L1L2L3L4L5L6L7Route: L1L2L3L4L5L6L7RouteWithChildren, +} + +const L1L2L3L4L5L6RouteWithChildren = L1L2L3L4L5L6Route._addFileChildren( + L1L2L3L4L5L6RouteChildren, +) + +interface L1L2L3L4L5RouteChildren { + L1L2L3L4L5L6Route: typeof L1L2L3L4L5L6RouteWithChildren +} + +const L1L2L3L4L5RouteChildren: L1L2L3L4L5RouteChildren = { + L1L2L3L4L5L6Route: L1L2L3L4L5L6RouteWithChildren, +} + +const L1L2L3L4L5RouteWithChildren = L1L2L3L4L5Route._addFileChildren( + L1L2L3L4L5RouteChildren, +) + +interface L1L2L3L4RouteChildren { + L1L2L3L4L5Route: typeof L1L2L3L4L5RouteWithChildren +} + +const L1L2L3L4RouteChildren: L1L2L3L4RouteChildren = { + L1L2L3L4L5Route: L1L2L3L4L5RouteWithChildren, +} + +const L1L2L3L4RouteWithChildren = L1L2L3L4Route._addFileChildren( + L1L2L3L4RouteChildren, +) + +interface L1L2L3RouteChildren { + L1L2L3L4Route: typeof L1L2L3L4RouteWithChildren +} + +const L1L2L3RouteChildren: L1L2L3RouteChildren = { + L1L2L3L4Route: L1L2L3L4RouteWithChildren, +} + +const L1L2L3RouteWithChildren = + L1L2L3Route._addFileChildren(L1L2L3RouteChildren) + +interface L1L2RouteChildren { + L1L2L3Route: typeof L1L2L3RouteWithChildren +} + +const L1L2RouteChildren: L1L2RouteChildren = { + L1L2L3Route: L1L2L3RouteWithChildren, +} + +const L1L2RouteWithChildren = L1L2Route._addFileChildren(L1L2RouteChildren) + +interface L1RouteChildren { + L1L2Route: typeof L1L2RouteWithChildren +} + +const L1RouteChildren: L1RouteChildren = { + L1L2Route: L1L2RouteWithChildren, +} + +const L1RouteWithChildren = L1Route._addFileChildren(L1RouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + L1Route: L1RouteWithChildren, +} +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/benchmarks/memory/server/scenarios/peak-large-page/react/src/router.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/__root.tsx new file mode 100644 index 0000000000..c5f9de6922 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/index.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/index.tsx new file mode 100644 index 0000000000..25099720e4 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
peak-large-page-index
+} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx new file mode 100644 index 0000000000..0651ba886d --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx @@ -0,0 +1,28 @@ +import { createFileRoute } from '@tanstack/react-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6/l7/l8')({ + loader: () => makeLargePageLevelData(8, 0x5eed_1008), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelEightComponent, +}) + +function LevelEightComponent() { + const data = Route.useLoaderData() + const first = data.records[0]! + + return ( +
+

{data.marker}

+

records: {data.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx new file mode 100644 index 0000000000..1f89e6f454 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6/l7')({ + loader: () => makeLargePageLevelData(7, 0x5eed_1007), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelSevenComponent, +}) + +function LevelSevenComponent() { + const data = Route.useLoaderData() + const first = data.records[0]! + + return ( +
+

{data.marker}

+

records: {data.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.tsx new file mode 100644 index 0000000000..1a8c98ceb2 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.l6.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6')({ + loader: () => makeLargePageLevelData(6, 0x5eed_1006), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelSixComponent, +}) + +function LevelSixComponent() { + const data = Route.useLoaderData() + const first = data.records[0]! + + return ( +
+

{data.marker}

+

records: {data.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.tsx new file mode 100644 index 0000000000..3e9afad0b9 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.l5.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2/l3/l4/l5')({ + loader: () => makeLargePageLevelData(5, 0x5eed_1005), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelFiveComponent, +}) + +function LevelFiveComponent() { + const data = Route.useLoaderData() + const first = data.records[0]! + + return ( +
+

{data.marker}

+

records: {data.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.tsx new file mode 100644 index 0000000000..73c29bc402 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.l4.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2/l3/l4')({ + loader: () => makeLargePageLevelData(4, 0x5eed_1004), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelFourComponent, +}) + +function LevelFourComponent() { + const data = Route.useLoaderData() + const first = data.records[0]! + + return ( +
+

{data.marker}

+

records: {data.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.tsx new file mode 100644 index 0000000000..e5b57463ad --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.l3.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2/l3')({ + loader: () => makeLargePageLevelData(3, 0x5eed_1003), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelThreeComponent, +}) + +function LevelThreeComponent() { + const data = Route.useLoaderData() + const first = data.records[0]! + + return ( +
+

{data.marker}

+

records: {data.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.tsx new file mode 100644 index 0000000000..18999233cc --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.l2.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2')({ + loader: () => makeLargePageLevelData(2, 0x5eed_1002), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelTwoComponent, +}) + +function LevelTwoComponent() { + const data = Route.useLoaderData() + const first = data.records[0]! + + return ( +
+

{data.marker}

+

records: {data.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.tsx b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.tsx new file mode 100644 index 0000000000..8fa7a5e0dc --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routes/l1.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1')({ + loader: () => makeLargePageLevelData(1, 0x5eed_1001), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelOneComponent, +}) + +function LevelOneComponent() { + const data = Route.useLoaderData() + const first = data.records[0]! + + return ( +
+

{data.marker}

+

records: {data.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/tsconfig.json b/benchmarks/memory/server/scenarios/peak-large-page/react/tsconfig.json new file mode 100644 index 0000000000..11ddcce4ea --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/vite.config.ts b/benchmarks/memory/server/scenarios/peak-large-page/react/vite.config.ts new file mode 100644 index 0000000000..dcfcf1f92b --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/vite.config.ts @@ -0,0 +1,31 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server peak-large-page (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/shared.ts b/benchmarks/memory/server/scenarios/peak-large-page/shared.ts new file mode 100644 index 0000000000..085e576244 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/shared.ts @@ -0,0 +1,68 @@ +import { runSequentialRequestLoop } from '#memory-server/bench-utils' +import type { StartRequestHandler } from '#memory-server/bench-utils' + +export type { StartRequestHandler } + +type Framework = 'react' | 'solid' | 'vue' + +const benchmarkSeed = 0x5eed_0005 +const peakLargePageIterations = 1 +const peakLargePageUrl = 'http://localhost/l1/l2/l3/l4/l5/l6/l7/l8' +const levelEightMarker = 'data-bench="peak-large-page-level-8"' + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +function buildPeakLargePageRequest() { + return new Request(peakLargePageUrl, requestInit) +} + +function validatePeakLargePageResponse(response: Response, request: Request) { + if (response.status !== 200) { + throw new Error( + `Expected status 200 for ${request.url}, got ${response.status}`, + ) + } +} + +function validatePeakLargePageBody(body: string) { + if (!body.includes(levelEightMarker)) { + throw new Error('Expected peak-large-page level-8 marker in response body') + } +} + +async function assertPeakLargePageSanity(handler: StartRequestHandler) { + const request = new Request(peakLargePageUrl, requestInit) + const response = await handler.fetch(request) + const body = await response.text() + + validatePeakLargePageResponse(response, request) + validatePeakLargePageBody(body) +} + +export function createWorkloadGroup( + framework: Framework, + handler: StartRequestHandler, +) { + const run = async () => + runSequentialRequestLoop(handler, { + seed: benchmarkSeed, + iterations: peakLargePageIterations, + buildRequest: buildPeakLargePageRequest, + validateResponse: validatePeakLargePageResponse, + }) + + return { + sanity: () => assertPeakLargePageSanity(handler), + workloads: [ + { + name: `mem server peak-large-page (${framework})`, + run, + }, + ], + } +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.flame.ts b/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/project.json b/benchmarks/memory/server/scenarios/peak-large-page/solid/project.json new file mode 100644 index 0000000000..85e8f83224 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-peak-large-page-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/setup.ts b/benchmarks/memory/server/scenarios/peak-large-page/solid/setup.ts new file mode 100644 index 0000000000..4fe85c3f00 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..c3ccdaaa0e --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routeTree.gen.ts @@ -0,0 +1,305 @@ +/* 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 L1RouteImport } from './routes/l1' +import { Route as IndexRouteImport } from './routes/index' +import { Route as L1L2RouteImport } from './routes/l1.l2' +import { Route as L1L2L3RouteImport } from './routes/l1.l2.l3' +import { Route as L1L2L3L4RouteImport } from './routes/l1.l2.l3.l4' +import { Route as L1L2L3L4L5RouteImport } from './routes/l1.l2.l3.l4.l5' +import { Route as L1L2L3L4L5L6RouteImport } from './routes/l1.l2.l3.l4.l5.l6' +import { Route as L1L2L3L4L5L6L7RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7' +import { Route as L1L2L3L4L5L6L7L8RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7.l8' + +const L1Route = L1RouteImport.update({ + id: '/l1', + path: '/l1', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const L1L2Route = L1L2RouteImport.update({ + id: '/l2', + path: '/l2', + getParentRoute: () => L1Route, +} as any) +const L1L2L3Route = L1L2L3RouteImport.update({ + id: '/l3', + path: '/l3', + getParentRoute: () => L1L2Route, +} as any) +const L1L2L3L4Route = L1L2L3L4RouteImport.update({ + id: '/l4', + path: '/l4', + getParentRoute: () => L1L2L3Route, +} as any) +const L1L2L3L4L5Route = L1L2L3L4L5RouteImport.update({ + id: '/l5', + path: '/l5', + getParentRoute: () => L1L2L3L4Route, +} as any) +const L1L2L3L4L5L6Route = L1L2L3L4L5L6RouteImport.update({ + id: '/l6', + path: '/l6', + getParentRoute: () => L1L2L3L4L5Route, +} as any) +const L1L2L3L4L5L6L7Route = L1L2L3L4L5L6L7RouteImport.update({ + id: '/l7', + path: '/l7', + getParentRoute: () => L1L2L3L4L5L6Route, +} as any) +const L1L2L3L4L5L6L7L8Route = L1L2L3L4L5L6L7L8RouteImport.update({ + id: '/l8', + path: '/l8', + getParentRoute: () => L1L2L3L4L5L6L7Route, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/l1': typeof L1RouteWithChildren + '/l1/l2': typeof L1L2RouteWithChildren + '/l1/l2/l3': typeof L1L2L3RouteWithChildren + '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren + '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren + '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/l1': typeof L1RouteWithChildren + '/l1/l2': typeof L1L2RouteWithChildren + '/l1/l2/l3': typeof L1L2L3RouteWithChildren + '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren + '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren + '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/l1': typeof L1RouteWithChildren + '/l1/l2': typeof L1L2RouteWithChildren + '/l1/l2/l3': typeof L1L2L3RouteWithChildren + '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren + '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren + '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/l1' + | '/l1/l2' + | '/l1/l2/l3' + | '/l1/l2/l3/l4' + | '/l1/l2/l3/l4/l5' + | '/l1/l2/l3/l4/l5/l6' + | '/l1/l2/l3/l4/l5/l6/l7' + | '/l1/l2/l3/l4/l5/l6/l7/l8' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/l1' + | '/l1/l2' + | '/l1/l2/l3' + | '/l1/l2/l3/l4' + | '/l1/l2/l3/l4/l5' + | '/l1/l2/l3/l4/l5/l6' + | '/l1/l2/l3/l4/l5/l6/l7' + | '/l1/l2/l3/l4/l5/l6/l7/l8' + id: + | '__root__' + | '/' + | '/l1' + | '/l1/l2' + | '/l1/l2/l3' + | '/l1/l2/l3/l4' + | '/l1/l2/l3/l4/l5' + | '/l1/l2/l3/l4/l5/l6' + | '/l1/l2/l3/l4/l5/l6/l7' + | '/l1/l2/l3/l4/l5/l6/l7/l8' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + L1Route: typeof L1RouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/l1': { + id: '/l1' + path: '/l1' + fullPath: '/l1' + preLoaderRoute: typeof L1RouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/l1/l2': { + id: '/l1/l2' + path: '/l2' + fullPath: '/l1/l2' + preLoaderRoute: typeof L1L2RouteImport + parentRoute: typeof L1Route + } + '/l1/l2/l3': { + id: '/l1/l2/l3' + path: '/l3' + fullPath: '/l1/l2/l3' + preLoaderRoute: typeof L1L2L3RouteImport + parentRoute: typeof L1L2Route + } + '/l1/l2/l3/l4': { + id: '/l1/l2/l3/l4' + path: '/l4' + fullPath: '/l1/l2/l3/l4' + preLoaderRoute: typeof L1L2L3L4RouteImport + parentRoute: typeof L1L2L3Route + } + '/l1/l2/l3/l4/l5': { + id: '/l1/l2/l3/l4/l5' + path: '/l5' + fullPath: '/l1/l2/l3/l4/l5' + preLoaderRoute: typeof L1L2L3L4L5RouteImport + parentRoute: typeof L1L2L3L4Route + } + '/l1/l2/l3/l4/l5/l6': { + id: '/l1/l2/l3/l4/l5/l6' + path: '/l6' + fullPath: '/l1/l2/l3/l4/l5/l6' + preLoaderRoute: typeof L1L2L3L4L5L6RouteImport + parentRoute: typeof L1L2L3L4L5Route + } + '/l1/l2/l3/l4/l5/l6/l7': { + id: '/l1/l2/l3/l4/l5/l6/l7' + path: '/l7' + fullPath: '/l1/l2/l3/l4/l5/l6/l7' + preLoaderRoute: typeof L1L2L3L4L5L6L7RouteImport + parentRoute: typeof L1L2L3L4L5L6Route + } + '/l1/l2/l3/l4/l5/l6/l7/l8': { + id: '/l1/l2/l3/l4/l5/l6/l7/l8' + path: '/l8' + fullPath: '/l1/l2/l3/l4/l5/l6/l7/l8' + preLoaderRoute: typeof L1L2L3L4L5L6L7L8RouteImport + parentRoute: typeof L1L2L3L4L5L6L7Route + } + } +} + +interface L1L2L3L4L5L6L7RouteChildren { + L1L2L3L4L5L6L7L8Route: typeof L1L2L3L4L5L6L7L8Route +} + +const L1L2L3L4L5L6L7RouteChildren: L1L2L3L4L5L6L7RouteChildren = { + L1L2L3L4L5L6L7L8Route: L1L2L3L4L5L6L7L8Route, +} + +const L1L2L3L4L5L6L7RouteWithChildren = L1L2L3L4L5L6L7Route._addFileChildren( + L1L2L3L4L5L6L7RouteChildren, +) + +interface L1L2L3L4L5L6RouteChildren { + L1L2L3L4L5L6L7Route: typeof L1L2L3L4L5L6L7RouteWithChildren +} + +const L1L2L3L4L5L6RouteChildren: L1L2L3L4L5L6RouteChildren = { + L1L2L3L4L5L6L7Route: L1L2L3L4L5L6L7RouteWithChildren, +} + +const L1L2L3L4L5L6RouteWithChildren = L1L2L3L4L5L6Route._addFileChildren( + L1L2L3L4L5L6RouteChildren, +) + +interface L1L2L3L4L5RouteChildren { + L1L2L3L4L5L6Route: typeof L1L2L3L4L5L6RouteWithChildren +} + +const L1L2L3L4L5RouteChildren: L1L2L3L4L5RouteChildren = { + L1L2L3L4L5L6Route: L1L2L3L4L5L6RouteWithChildren, +} + +const L1L2L3L4L5RouteWithChildren = L1L2L3L4L5Route._addFileChildren( + L1L2L3L4L5RouteChildren, +) + +interface L1L2L3L4RouteChildren { + L1L2L3L4L5Route: typeof L1L2L3L4L5RouteWithChildren +} + +const L1L2L3L4RouteChildren: L1L2L3L4RouteChildren = { + L1L2L3L4L5Route: L1L2L3L4L5RouteWithChildren, +} + +const L1L2L3L4RouteWithChildren = L1L2L3L4Route._addFileChildren( + L1L2L3L4RouteChildren, +) + +interface L1L2L3RouteChildren { + L1L2L3L4Route: typeof L1L2L3L4RouteWithChildren +} + +const L1L2L3RouteChildren: L1L2L3RouteChildren = { + L1L2L3L4Route: L1L2L3L4RouteWithChildren, +} + +const L1L2L3RouteWithChildren = + L1L2L3Route._addFileChildren(L1L2L3RouteChildren) + +interface L1L2RouteChildren { + L1L2L3Route: typeof L1L2L3RouteWithChildren +} + +const L1L2RouteChildren: L1L2RouteChildren = { + L1L2L3Route: L1L2L3RouteWithChildren, +} + +const L1L2RouteWithChildren = L1L2Route._addFileChildren(L1L2RouteChildren) + +interface L1RouteChildren { + L1L2Route: typeof L1L2RouteWithChildren +} + +const L1RouteChildren: L1RouteChildren = { + L1L2Route: L1L2RouteWithChildren, +} + +const L1RouteWithChildren = L1Route._addFileChildren(L1RouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + L1Route: L1RouteWithChildren, +} +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/benchmarks/memory/server/scenarios/peak-large-page/solid/src/router.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..aaf7dfdd89 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' +import { HydrationScript } from 'solid-js/web' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charset: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/index.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/index.tsx new file mode 100644 index 0000000000..111ffaa36a --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
peak-large-page-index
+} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx new file mode 100644 index 0000000000..b0f94893fb --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx @@ -0,0 +1,28 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6/l7/l8')({ + loader: () => makeLargePageLevelData(8, 0x5eed_1008), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelEightComponent, +}) + +function LevelEightComponent() { + const data = Route.useLoaderData() + const first = () => data().records[0]! + + return ( +
+

{data().marker}

+

records: {data().records.length}

+
+

{first().name}

+

{first().id}

+

{first().description}

+
+
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx new file mode 100644 index 0000000000..f8a3819c85 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6/l7')({ + loader: () => makeLargePageLevelData(7, 0x5eed_1007), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelSevenComponent, +}) + +function LevelSevenComponent() { + const data = Route.useLoaderData() + const first = () => data().records[0]! + + return ( +
+

{data().marker}

+

records: {data().records.length}

+
+

{first().name}

+

{first().id}

+

{first().description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.tsx new file mode 100644 index 0000000000..7a438ddbd2 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.l6.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6')({ + loader: () => makeLargePageLevelData(6, 0x5eed_1006), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelSixComponent, +}) + +function LevelSixComponent() { + const data = Route.useLoaderData() + const first = () => data().records[0]! + + return ( +
+

{data().marker}

+

records: {data().records.length}

+
+

{first().name}

+

{first().id}

+

{first().description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.tsx new file mode 100644 index 0000000000..2e05985ac5 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.l5.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2/l3/l4/l5')({ + loader: () => makeLargePageLevelData(5, 0x5eed_1005), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelFiveComponent, +}) + +function LevelFiveComponent() { + const data = Route.useLoaderData() + const first = () => data().records[0]! + + return ( +
+

{data().marker}

+

records: {data().records.length}

+
+

{first().name}

+

{first().id}

+

{first().description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.tsx new file mode 100644 index 0000000000..4f38f0cb76 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.l4.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2/l3/l4')({ + loader: () => makeLargePageLevelData(4, 0x5eed_1004), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelFourComponent, +}) + +function LevelFourComponent() { + const data = Route.useLoaderData() + const first = () => data().records[0]! + + return ( +
+

{data().marker}

+

records: {data().records.length}

+
+

{first().name}

+

{first().id}

+

{first().description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.tsx new file mode 100644 index 0000000000..3f1f113fe3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.l3.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2/l3')({ + loader: () => makeLargePageLevelData(3, 0x5eed_1003), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelThreeComponent, +}) + +function LevelThreeComponent() { + const data = Route.useLoaderData() + const first = () => data().records[0]! + + return ( +
+

{data().marker}

+

records: {data().records.length}

+
+

{first().name}

+

{first().id}

+

{first().description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.tsx new file mode 100644 index 0000000000..bd338fd53f --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.l2.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1/l2')({ + loader: () => makeLargePageLevelData(2, 0x5eed_1002), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelTwoComponent, +}) + +function LevelTwoComponent() { + const data = Route.useLoaderData() + const first = () => data().records[0]! + + return ( +
+

{data().marker}

+

records: {data().records.length}

+
+

{first().name}

+

{first().id}

+

{first().description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.tsx b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.tsx new file mode 100644 index 0000000000..9dcfd7448a --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/src/routes/l1.tsx @@ -0,0 +1,29 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +export const Route = createFileRoute('/l1')({ + loader: () => makeLargePageLevelData(1, 0x5eed_1001), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelOneComponent, +}) + +function LevelOneComponent() { + const data = Route.useLoaderData() + const first = () => data().records[0]! + + return ( +
+

{data().marker}

+

records: {data().records.length}

+
+

{first().name}

+

{first().id}

+

{first().description}

+
+ +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/tsconfig.json b/benchmarks/memory/server/scenarios/peak-large-page/solid/tsconfig.json new file mode 100644 index 0000000000..4b61264e11 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/vite.config.ts b/benchmarks/memory/server/scenarios/peak-large-page/solid/vite.config.ts new file mode 100644 index 0000000000..15b8c3a571 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/vite.config.ts @@ -0,0 +1,36 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server peak-large-page (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) 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 new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.flame.ts b/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/project.json b/benchmarks/memory/server/scenarios/peak-large-page/vue/project.json new file mode 100644 index 0000000000..f424a2134f --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-peak-large-page-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/setup.ts b/benchmarks/memory/server/scenarios/peak-large-page/vue/setup.ts new file mode 100644 index 0000000000..6683dafe6b --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..26cc9f6058 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routeTree.gen.ts @@ -0,0 +1,305 @@ +/* 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 L1RouteImport } from './routes/l1' +import { Route as IndexRouteImport } from './routes/index' +import { Route as L1L2RouteImport } from './routes/l1.l2' +import { Route as L1L2L3RouteImport } from './routes/l1.l2.l3' +import { Route as L1L2L3L4RouteImport } from './routes/l1.l2.l3.l4' +import { Route as L1L2L3L4L5RouteImport } from './routes/l1.l2.l3.l4.l5' +import { Route as L1L2L3L4L5L6RouteImport } from './routes/l1.l2.l3.l4.l5.l6' +import { Route as L1L2L3L4L5L6L7RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7' +import { Route as L1L2L3L4L5L6L7L8RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7.l8' + +const L1Route = L1RouteImport.update({ + id: '/l1', + path: '/l1', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const L1L2Route = L1L2RouteImport.update({ + id: '/l2', + path: '/l2', + getParentRoute: () => L1Route, +} as any) +const L1L2L3Route = L1L2L3RouteImport.update({ + id: '/l3', + path: '/l3', + getParentRoute: () => L1L2Route, +} as any) +const L1L2L3L4Route = L1L2L3L4RouteImport.update({ + id: '/l4', + path: '/l4', + getParentRoute: () => L1L2L3Route, +} as any) +const L1L2L3L4L5Route = L1L2L3L4L5RouteImport.update({ + id: '/l5', + path: '/l5', + getParentRoute: () => L1L2L3L4Route, +} as any) +const L1L2L3L4L5L6Route = L1L2L3L4L5L6RouteImport.update({ + id: '/l6', + path: '/l6', + getParentRoute: () => L1L2L3L4L5Route, +} as any) +const L1L2L3L4L5L6L7Route = L1L2L3L4L5L6L7RouteImport.update({ + id: '/l7', + path: '/l7', + getParentRoute: () => L1L2L3L4L5L6Route, +} as any) +const L1L2L3L4L5L6L7L8Route = L1L2L3L4L5L6L7L8RouteImport.update({ + id: '/l8', + path: '/l8', + getParentRoute: () => L1L2L3L4L5L6L7Route, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/l1': typeof L1RouteWithChildren + '/l1/l2': typeof L1L2RouteWithChildren + '/l1/l2/l3': typeof L1L2L3RouteWithChildren + '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren + '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren + '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/l1': typeof L1RouteWithChildren + '/l1/l2': typeof L1L2RouteWithChildren + '/l1/l2/l3': typeof L1L2L3RouteWithChildren + '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren + '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren + '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/l1': typeof L1RouteWithChildren + '/l1/l2': typeof L1L2RouteWithChildren + '/l1/l2/l3': typeof L1L2L3RouteWithChildren + '/l1/l2/l3/l4': typeof L1L2L3L4RouteWithChildren + '/l1/l2/l3/l4/l5': typeof L1L2L3L4L5RouteWithChildren + '/l1/l2/l3/l4/l5/l6': typeof L1L2L3L4L5L6RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7': typeof L1L2L3L4L5L6L7RouteWithChildren + '/l1/l2/l3/l4/l5/l6/l7/l8': typeof L1L2L3L4L5L6L7L8Route +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/l1' + | '/l1/l2' + | '/l1/l2/l3' + | '/l1/l2/l3/l4' + | '/l1/l2/l3/l4/l5' + | '/l1/l2/l3/l4/l5/l6' + | '/l1/l2/l3/l4/l5/l6/l7' + | '/l1/l2/l3/l4/l5/l6/l7/l8' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/l1' + | '/l1/l2' + | '/l1/l2/l3' + | '/l1/l2/l3/l4' + | '/l1/l2/l3/l4/l5' + | '/l1/l2/l3/l4/l5/l6' + | '/l1/l2/l3/l4/l5/l6/l7' + | '/l1/l2/l3/l4/l5/l6/l7/l8' + id: + | '__root__' + | '/' + | '/l1' + | '/l1/l2' + | '/l1/l2/l3' + | '/l1/l2/l3/l4' + | '/l1/l2/l3/l4/l5' + | '/l1/l2/l3/l4/l5/l6' + | '/l1/l2/l3/l4/l5/l6/l7' + | '/l1/l2/l3/l4/l5/l6/l7/l8' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + L1Route: typeof L1RouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/l1': { + id: '/l1' + path: '/l1' + fullPath: '/l1' + preLoaderRoute: typeof L1RouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/l1/l2': { + id: '/l1/l2' + path: '/l2' + fullPath: '/l1/l2' + preLoaderRoute: typeof L1L2RouteImport + parentRoute: typeof L1Route + } + '/l1/l2/l3': { + id: '/l1/l2/l3' + path: '/l3' + fullPath: '/l1/l2/l3' + preLoaderRoute: typeof L1L2L3RouteImport + parentRoute: typeof L1L2Route + } + '/l1/l2/l3/l4': { + id: '/l1/l2/l3/l4' + path: '/l4' + fullPath: '/l1/l2/l3/l4' + preLoaderRoute: typeof L1L2L3L4RouteImport + parentRoute: typeof L1L2L3Route + } + '/l1/l2/l3/l4/l5': { + id: '/l1/l2/l3/l4/l5' + path: '/l5' + fullPath: '/l1/l2/l3/l4/l5' + preLoaderRoute: typeof L1L2L3L4L5RouteImport + parentRoute: typeof L1L2L3L4Route + } + '/l1/l2/l3/l4/l5/l6': { + id: '/l1/l2/l3/l4/l5/l6' + path: '/l6' + fullPath: '/l1/l2/l3/l4/l5/l6' + preLoaderRoute: typeof L1L2L3L4L5L6RouteImport + parentRoute: typeof L1L2L3L4L5Route + } + '/l1/l2/l3/l4/l5/l6/l7': { + id: '/l1/l2/l3/l4/l5/l6/l7' + path: '/l7' + fullPath: '/l1/l2/l3/l4/l5/l6/l7' + preLoaderRoute: typeof L1L2L3L4L5L6L7RouteImport + parentRoute: typeof L1L2L3L4L5L6Route + } + '/l1/l2/l3/l4/l5/l6/l7/l8': { + id: '/l1/l2/l3/l4/l5/l6/l7/l8' + path: '/l8' + fullPath: '/l1/l2/l3/l4/l5/l6/l7/l8' + preLoaderRoute: typeof L1L2L3L4L5L6L7L8RouteImport + parentRoute: typeof L1L2L3L4L5L6L7Route + } + } +} + +interface L1L2L3L4L5L6L7RouteChildren { + L1L2L3L4L5L6L7L8Route: typeof L1L2L3L4L5L6L7L8Route +} + +const L1L2L3L4L5L6L7RouteChildren: L1L2L3L4L5L6L7RouteChildren = { + L1L2L3L4L5L6L7L8Route: L1L2L3L4L5L6L7L8Route, +} + +const L1L2L3L4L5L6L7RouteWithChildren = L1L2L3L4L5L6L7Route._addFileChildren( + L1L2L3L4L5L6L7RouteChildren, +) + +interface L1L2L3L4L5L6RouteChildren { + L1L2L3L4L5L6L7Route: typeof L1L2L3L4L5L6L7RouteWithChildren +} + +const L1L2L3L4L5L6RouteChildren: L1L2L3L4L5L6RouteChildren = { + L1L2L3L4L5L6L7Route: L1L2L3L4L5L6L7RouteWithChildren, +} + +const L1L2L3L4L5L6RouteWithChildren = L1L2L3L4L5L6Route._addFileChildren( + L1L2L3L4L5L6RouteChildren, +) + +interface L1L2L3L4L5RouteChildren { + L1L2L3L4L5L6Route: typeof L1L2L3L4L5L6RouteWithChildren +} + +const L1L2L3L4L5RouteChildren: L1L2L3L4L5RouteChildren = { + L1L2L3L4L5L6Route: L1L2L3L4L5L6RouteWithChildren, +} + +const L1L2L3L4L5RouteWithChildren = L1L2L3L4L5Route._addFileChildren( + L1L2L3L4L5RouteChildren, +) + +interface L1L2L3L4RouteChildren { + L1L2L3L4L5Route: typeof L1L2L3L4L5RouteWithChildren +} + +const L1L2L3L4RouteChildren: L1L2L3L4RouteChildren = { + L1L2L3L4L5Route: L1L2L3L4L5RouteWithChildren, +} + +const L1L2L3L4RouteWithChildren = L1L2L3L4Route._addFileChildren( + L1L2L3L4RouteChildren, +) + +interface L1L2L3RouteChildren { + L1L2L3L4Route: typeof L1L2L3L4RouteWithChildren +} + +const L1L2L3RouteChildren: L1L2L3RouteChildren = { + L1L2L3L4Route: L1L2L3L4RouteWithChildren, +} + +const L1L2L3RouteWithChildren = + L1L2L3Route._addFileChildren(L1L2L3RouteChildren) + +interface L1L2RouteChildren { + L1L2L3Route: typeof L1L2L3RouteWithChildren +} + +const L1L2RouteChildren: L1L2RouteChildren = { + L1L2L3Route: L1L2L3RouteWithChildren, +} + +const L1L2RouteWithChildren = L1L2Route._addFileChildren(L1L2RouteChildren) + +interface L1RouteChildren { + L1L2Route: typeof L1L2RouteWithChildren +} + +const L1RouteChildren: L1RouteChildren = { + L1L2Route: L1L2RouteWithChildren, +} + +const L1RouteWithChildren = L1Route._addFileChildren(L1RouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + L1Route: L1RouteWithChildren, +} +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/benchmarks/memory/server/scenarios/peak-large-page/vue/src/router.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..de29ee1612 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/index.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/index.tsx new file mode 100644 index 0000000000..e9a57d46fd --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
peak-large-page-index
+} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx new file mode 100644 index 0000000000..7f7a42d645 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx @@ -0,0 +1,34 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +const LevelEightComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+
+ ) + } + }, +}) + +export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6/l7/l8')({ + loader: () => makeLargePageLevelData(8, 0x5eed_1008), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelEightComponent, +}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx new file mode 100644 index 0000000000..a99c56e529 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx @@ -0,0 +1,35 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +const LevelSevenComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + +export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6/l7')({ + loader: () => makeLargePageLevelData(7, 0x5eed_1007), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelSevenComponent, +}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.tsx new file mode 100644 index 0000000000..3de3f03427 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.tsx @@ -0,0 +1,35 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +const LevelSixComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + +export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6')({ + loader: () => makeLargePageLevelData(6, 0x5eed_1006), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelSixComponent, +}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.tsx new file mode 100644 index 0000000000..5d936f83b5 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.tsx @@ -0,0 +1,35 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +const LevelFiveComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + +export const Route = createFileRoute('/l1/l2/l3/l4/l5')({ + loader: () => makeLargePageLevelData(5, 0x5eed_1005), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelFiveComponent, +}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.tsx new file mode 100644 index 0000000000..8e10331f2d --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.tsx @@ -0,0 +1,35 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +const LevelFourComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + +export const Route = createFileRoute('/l1/l2/l3/l4')({ + loader: () => makeLargePageLevelData(4, 0x5eed_1004), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelFourComponent, +}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.tsx new file mode 100644 index 0000000000..d69529c50c --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.tsx @@ -0,0 +1,35 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +const LevelThreeComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + +export const Route = createFileRoute('/l1/l2/l3')({ + loader: () => makeLargePageLevelData(3, 0x5eed_1003), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelThreeComponent, +}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.tsx new file mode 100644 index 0000000000..d04bc7f827 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.tsx @@ -0,0 +1,35 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +const LevelTwoComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + +export const Route = createFileRoute('/l1/l2')({ + loader: () => makeLargePageLevelData(2, 0x5eed_1002), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelTwoComponent, +}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.tsx new file mode 100644 index 0000000000..a95ae7f9b0 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.tsx @@ -0,0 +1,35 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { + makeLargePageHead, + makeLargePageLevelData, +} from '../../../large-page-data' + +const LevelOneComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + +export const Route = createFileRoute('/l1')({ + loader: () => makeLargePageLevelData(1, 0x5eed_1001), + head: ({ loaderData }) => makeLargePageHead(loaderData), + component: LevelOneComponent, +}) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/tsconfig.json b/benchmarks/memory/server/scenarios/peak-large-page/vue/tsconfig.json new file mode 100644 index 0000000000..9ad6481342 --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/vite.config.ts b/benchmarks/memory/server/scenarios/peak-large-page/vue/vite.config.ts new file mode 100644 index 0000000000..3fab2aff9e --- /dev/null +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/vite.config.ts @@ -0,0 +1,31 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server peak-large-page (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts b/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/request-churn/react/memory.flame.ts b/benchmarks/memory/server/scenarios/request-churn/react/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/react/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/request-churn/react/project.json b/benchmarks/memory/server/scenarios/request-churn/react/project.json new file mode 100644 index 0000000000..d997054b95 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/react/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-request-churn-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/request-churn/react/setup.ts b/benchmarks/memory/server/scenarios/request-churn/react/setup.ts new file mode 100644 index 0000000000..0c98f54ddd --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/react/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/request-churn/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/request-churn/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..d22f1bee18 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/react/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 ItemsIdRouteImport } from './routes/items.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ItemsIdRoute = ItemsIdRouteImport.update({ + id: '/items/$id', + path: '/items/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/items/$id' + id: '__root__' | '/' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/items/$id': { + id: '/items/$id' + path: '/items/$id' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ItemsIdRoute: ItemsIdRoute, +} +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/benchmarks/memory/server/scenarios/request-churn/react/src/router.tsx b/benchmarks/memory/server/scenarios/request-churn/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/request-churn/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/request-churn/react/src/routes/__root.tsx new file mode 100644 index 0000000000..c5f9de6922 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/react/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/request-churn/react/src/routes/index.tsx b/benchmarks/memory/server/scenarios/request-churn/react/src/routes/index.tsx new file mode 100644 index 0000000000..e6335b0d83 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
request-churn-index
+} diff --git a/benchmarks/memory/server/scenarios/request-churn/react/src/routes/items.$id.tsx b/benchmarks/memory/server/scenarios/request-churn/react/src/routes/items.$id.tsx new file mode 100644 index 0000000000..5fd86ee5fb --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/react/src/routes/items.$id.tsx @@ -0,0 +1,40 @@ +import { createFileRoute } from '@tanstack/react-router' + +const itemIndexes = Array.from({ length: 5 }, (_, index) => index) + +type ItemSearch = { + q: string +} + +export const Route = createFileRoute('/items/$id')({ + validateSearch: (search: Record): ItemSearch => ({ + q: typeof search.q === 'string' ? search.q : '', + }), + loaderDeps: ({ search }) => ({ q: search.q }), + loader: ({ params, deps }) => ({ + id: params.id, + title: `Item ${params.id}`, + q: deps.q, + items: itemIndexes.map((index) => ({ + id: `${params.id}-${index}`, + label: `${deps.q}-${index}`, + })), + }), + component: ItemComponent, +}) + +function ItemComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data.title}

+

{data.q}

+
    + {data.items.map((item) => ( +
  • {item.label}
  • + ))} +
+
+ ) +} diff --git a/benchmarks/memory/server/scenarios/request-churn/react/tsconfig.json b/benchmarks/memory/server/scenarios/request-churn/react/tsconfig.json new file mode 100644 index 0000000000..11ddcce4ea --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/react/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts b/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts new file mode 100644 index 0000000000..35adf6a249 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts @@ -0,0 +1,31 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server request-churn (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/scenarios/request-churn/shared.ts b/benchmarks/memory/server/scenarios/request-churn/shared.ts new file mode 100644 index 0000000000..b200c96ed6 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/shared.ts @@ -0,0 +1,82 @@ +import { + createDeterministicRandom, + randomSegment, + runSequentialRequestLoop, +} from '#memory-server/bench-utils' +import type { StartRequestHandler } from '#memory-server/bench-utils' + +export type { StartRequestHandler } + +type Framework = 'react' | 'solid' | 'vue' + +const benchmarkSeed = 0xdecafbad +const requestChurnIterations = 40 +const itemPageMarker = 'data-bench="request-churn-item"' +// Module-level so CodSpeed warmups and measurement never replay URLs. +const benchmarkRandom = createDeterministicRandom(benchmarkSeed) +let requestCounter = 0 + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +function validateItemResponse(response: Response, request: Request) { + if (response.status !== 200) { + throw new Error( + `Expected status 200 for ${request.url}, got ${response.status}`, + ) + } +} + +function validateItemBody(body: string) { + if (!body.includes(itemPageMarker)) { + throw new Error('Expected request-churn item marker in response body') + } +} + +async function assertRequestChurnSanity(handler: StartRequestHandler) { + const response = await handler.fetch( + new Request('http://localhost/items/sanity-item?q=q-sanity', requestInit), + ) + const body = await response.text() + + if (response.status !== 200) { + throw new Error(`Expected sanity status 200, got ${response.status}`) + } + + validateItemBody(body) +} + +export function createWorkloadGroup( + framework: Framework, + handler: StartRequestHandler, +) { + function buildItemRequest(random: () => number) { + const counter = (requestCounter++).toString(36) + const id = `${counter}-${randomSegment(random)}` + const q = `q-${randomSegment(random)}` + + return new Request(`http://localhost/items/${id}?q=${q}`, requestInit) + } + + const run = async () => + runSequentialRequestLoop(handler, { + random: benchmarkRandom, + iterations: requestChurnIterations, + buildRequest: buildItemRequest, + validateResponse: validateItemResponse, + }) + + return { + sanity: () => assertRequestChurnSanity(handler), + workloads: [ + { + name: `mem server request-churn (${framework})`, + run, + }, + ], + } +} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/memory.flame.ts b/benchmarks/memory/server/scenarios/request-churn/solid/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/solid/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/project.json b/benchmarks/memory/server/scenarios/request-churn/solid/project.json new file mode 100644 index 0000000000..3f3434ee24 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/solid/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-request-churn-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/setup.ts b/benchmarks/memory/server/scenarios/request-churn/solid/setup.ts new file mode 100644 index 0000000000..4fe85c3f00 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/solid/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/request-churn/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..8f49ec5d1f --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/solid/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 ItemsIdRouteImport } from './routes/items.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ItemsIdRoute = ItemsIdRouteImport.update({ + id: '/items/$id', + path: '/items/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/items/$id' + id: '__root__' | '/' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/items/$id': { + id: '/items/$id' + path: '/items/$id' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ItemsIdRoute: ItemsIdRoute, +} +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/benchmarks/memory/server/scenarios/request-churn/solid/src/router.tsx b/benchmarks/memory/server/scenarios/request-churn/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..aaf7dfdd89 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' +import { HydrationScript } from 'solid-js/web' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charset: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/index.tsx b/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/index.tsx new file mode 100644 index 0000000000..d32d31f301 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
request-churn-index
+} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/items.$id.tsx b/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/items.$id.tsx new file mode 100644 index 0000000000..e687e22741 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/solid/src/routes/items.$id.tsx @@ -0,0 +1,40 @@ +import { createFileRoute } from '@tanstack/solid-router' + +const itemIndexes = Array.from({ length: 5 }, (_, index) => index) + +type ItemSearch = { + q: string +} + +export const Route = createFileRoute('/items/$id')({ + validateSearch: (search: Record): ItemSearch => ({ + q: typeof search.q === 'string' ? search.q : '', + }), + loaderDeps: ({ search }) => ({ q: search.q }), + loader: ({ params, deps }) => ({ + id: params.id, + title: `Item ${params.id}`, + q: deps.q, + items: itemIndexes.map((index) => ({ + id: `${params.id}-${index}`, + label: `${deps.q}-${index}`, + })), + }), + component: ItemComponent, +}) + +function ItemComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data().title}

+

{data().q}

+
    + {data().items.map((item) => ( +
  • {item.label}
  • + ))} +
+
+ ) +} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/tsconfig.json b/benchmarks/memory/server/scenarios/request-churn/solid/tsconfig.json new file mode 100644 index 0000000000..4b61264e11 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/solid/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts b/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts new file mode 100644 index 0000000000..6601309a74 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts @@ -0,0 +1,36 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server request-churn (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/memory.flame.ts b/benchmarks/memory/server/scenarios/request-churn/vue/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/vue/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/project.json b/benchmarks/memory/server/scenarios/request-churn/vue/project.json new file mode 100644 index 0000000000..11eb1d868b --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/vue/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-request-churn-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/setup.ts b/benchmarks/memory/server/scenarios/request-churn/vue/setup.ts new file mode 100644 index 0000000000..6683dafe6b --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/vue/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/request-churn/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..86ccc14a0c --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/vue/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 ItemsIdRouteImport } from './routes/items.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ItemsIdRoute = ItemsIdRouteImport.update({ + id: '/items/$id', + path: '/items/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/items/$id' + id: '__root__' | '/' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/items/$id': { + id: '/items/$id' + path: '/items/$id' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ItemsIdRoute: ItemsIdRoute, +} +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/benchmarks/memory/server/scenarios/request-churn/vue/src/router.tsx b/benchmarks/memory/server/scenarios/request-churn/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..de29ee1612 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/index.tsx b/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/index.tsx new file mode 100644 index 0000000000..30751100a4 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
request-churn-index
+} diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/items.$id.tsx b/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/items.$id.tsx new file mode 100644 index 0000000000..570561f2a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/items.$id.tsx @@ -0,0 +1,43 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const itemIndexes = Array.from({ length: 5 }, (_, index) => index) + +type ItemSearch = { + q: string +} + +const ItemComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

{data.value.title}

+

{data.value.q}

+
    + {data.value.items.map((item) => ( +
  • {item.label}
  • + ))} +
+
+ ) + }, +}) + +export const Route = createFileRoute('/items/$id')({ + validateSearch: (search: Record): ItemSearch => ({ + q: typeof search.q === 'string' ? search.q : '', + }), + loaderDeps: ({ search }) => ({ q: search.q }), + loader: ({ params, deps }) => ({ + id: params.id, + title: `Item ${params.id}`, + q: deps.q, + items: itemIndexes.map((index) => ({ + id: `${params.id}-${index}`, + label: `${deps.q}-${index}`, + })), + }), + component: ItemComponent, +}) diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/tsconfig.json b/benchmarks/memory/server/scenarios/request-churn/vue/tsconfig.json new file mode 100644 index 0000000000..9ad6481342 --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/vue/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts b/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts new file mode 100644 index 0000000000..7f15c5c7af --- /dev/null +++ b/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts @@ -0,0 +1,31 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server request-churn (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts b/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/memory.flame.ts b/benchmarks/memory/server/scenarios/serialization-payload/react/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/project.json b/benchmarks/memory/server/scenarios/serialization-payload/react/project.json new file mode 100644 index 0000000000..467b40d734 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-serialization-payload-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/setup.ts b/benchmarks/memory/server/scenarios/serialization-payload/react/setup.ts new file mode 100644 index 0000000000..0c98f54ddd --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/serialization-payload/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..7e370fd84c --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/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 DataIdRouteImport } from './routes/data.$id' + +const DataIdRoute = DataIdRouteImport.update({ + id: '/data/$id', + path: '/data/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/data/$id': typeof DataIdRoute +} +export interface FileRoutesByTo { + '/data/$id': typeof DataIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/data/$id': typeof DataIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/data/$id' + fileRoutesByTo: FileRoutesByTo + to: '/data/$id' + id: '__root__' | '/data/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + DataIdRoute: typeof DataIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/data/$id': { + id: '/data/$id' + path: '/data/$id' + fullPath: '/data/$id' + preLoaderRoute: typeof DataIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + DataIdRoute: DataIdRoute, +} +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/benchmarks/memory/server/scenarios/serialization-payload/react/src/router.tsx b/benchmarks/memory/server/scenarios/serialization-payload/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/__root.tsx new file mode 100644 index 0000000000..c5f9de6922 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/data.$id.tsx b/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/data.$id.tsx new file mode 100644 index 0000000000..cfba0dbd62 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/src/routes/data.$id.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' +import { makeSerializationPayload } from '../../../serialization-payload' + +export const Route = createFileRoute('/data/$id')({ + loader: ({ params }) => makeSerializationPayload(params.id), + component: DataComponent, +}) + +function DataComponent() { + const data = Route.useLoaderData() + + return ( +
Map size: {data.lookup.size}
+ ) +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/tsconfig.json b/benchmarks/memory/server/scenarios/serialization-payload/react/tsconfig.json new file mode 100644 index 0000000000..11ddcce4ea --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts b/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts new file mode 100644 index 0000000000..1ed3bcc335 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts @@ -0,0 +1,31 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server serialization-payload (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/serialization-payload.ts b/benchmarks/memory/server/scenarios/serialization-payload/serialization-payload.ts new file mode 100644 index 0000000000..b6f401640e --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/serialization-payload.ts @@ -0,0 +1,115 @@ +const mapEntryCount = 500 +const setEntryCount = 500 +const temporalEntryCount = 500 +const nestedTreeDepth = 5 +const nestedTreeBreadth = 6 +const payloadTextLength = 150 + +export interface MapPayloadValue { + index: number + label: string + createdAt: Date + count: bigint + text: string +} + +export interface NestedPayloadNode { + id: string + depth: number + text: string + values: Array + children: Array +} + +export interface SerializationPayload { + id: string + lookup: Map + tags: Set + dates: Array + bigints: Array + tree: NestedPayloadNode +} + +export function makeSerializationPayload(id: string): SerializationPayload { + const hash = hashId(id) + const baseTimestamp = Date.UTC(2024, 0, 1) + hash + + return { + id, + lookup: new Map( + Array.from( + { length: mapEntryCount }, + (_, index): [string, MapPayloadValue] => [ + makeMapKey(id, index), + { + index, + label: `${id}-map-${index}`, + createdAt: new Date(baseTimestamp + index * 1_000), + count: BigInt(hash) * 10_000n + BigInt(index), + text: makePayloadText(id, `map-${index}`), + }, + ], + ), + ), + tags: new Set( + Array.from({ length: setEntryCount }, (_, index) => + makePayloadText(id, `set-${index}`), + ), + ), + dates: Array.from( + { length: temporalEntryCount }, + (_, index) => new Date(baseTimestamp + index * 60_000), + ), + bigints: Array.from( + { length: temporalEntryCount }, + (_, index) => BigInt(hash) * 1_000_000n + BigInt(index), + ), + tree: makeNestedTree(id, 0, 'root', hash), + } +} + +function makeMapKey(id: string, index: number) { + return `map-${id}-${index.toString().padStart(3, '0')}` +} + +function makeNestedTree( + id: string, + depth: number, + path: string, + hash: number, +): NestedPayloadNode { + return { + id: `${id}-node-${path}`, + depth, + text: makePayloadText(id, `tree-${depth}-${path}`), + values: [hash, depth, path.length], + children: + depth === nestedTreeDepth + ? [] + : Array.from({ length: nestedTreeBreadth }, (_, index) => + makeNestedTree(id, depth + 1, `${path}-${index}`, hash), + ), + } +} + +function makePayloadText(id: string, segment: string) { + const filler = 'abcdefghijklmnopqrstuvwxyz0123456789' + let value = `${id}|${segment}|` + + while (value.length < payloadTextLength) { + value += filler + } + + return value.slice(0, payloadTextLength) +} + +function hashId(id: string) { + let hash = 2_166_136_261 + + for (let index = 0; index < id.length; index++) { + hash ^= id.charCodeAt(index) + hash = Math.imul(hash, 16_777_619) + } + + return hash >>> 0 +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/shared.ts b/benchmarks/memory/server/scenarios/serialization-payload/shared.ts new file mode 100644 index 0000000000..14ec8f7e0a --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/shared.ts @@ -0,0 +1,75 @@ +import { + randomSegment, + runSequentialRequestLoop, +} from '#memory-server/bench-utils' +import type { StartRequestHandler } from '#memory-server/bench-utils' + +export type { StartRequestHandler } + +type Framework = 'react' | 'solid' | 'vue' + +const benchmarkSeed = 0x51eaa11 +const serializationPayloadIterations = 1 +const payloadPageMarker = 'data-bench="serialization-payload"' + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +function buildPayloadRequest(random: () => number, index: number) { + const id = `payload-${index}-${randomSegment(random)}` + + return new Request(`http://localhost/data/${id}`, requestInit) +} + +function validatePayloadResponse(response: Response, request: Request) { + if (response.status !== 200) { + throw new Error( + `Expected status 200 for ${request.url}, got ${response.status}`, + ) + } +} + +function validatePayloadBody(body: string) { + if (!body.includes(payloadPageMarker)) { + throw new Error('Expected serialization-payload marker in response body') + } +} + +async function assertSerializationPayloadSanity(handler: StartRequestHandler) { + const request = new Request( + 'http://localhost/data/sanity-payload', + requestInit, + ) + const response = await handler.fetch(request) + const body = await response.text() + + validatePayloadResponse(response, request) + validatePayloadBody(body) +} + +export function createWorkloadGroup( + framework: Framework, + handler: StartRequestHandler, +) { + const run = async () => + runSequentialRequestLoop(handler, { + seed: benchmarkSeed, + iterations: serializationPayloadIterations, + buildRequest: buildPayloadRequest, + validateResponse: validatePayloadResponse, + }) + + return { + sanity: () => assertSerializationPayloadSanity(handler), + workloads: [ + { + name: `mem server serialization-payload (${framework})`, + run, + }, + ], + } +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.flame.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/project.json b/benchmarks/memory/server/scenarios/serialization-payload/solid/project.json new file mode 100644 index 0000000000..6f381ef389 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-serialization-payload-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/setup.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/setup.ts new file mode 100644 index 0000000000..4fe85c3f00 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..082cbb290c --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/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 DataIdRouteImport } from './routes/data.$id' + +const DataIdRoute = DataIdRouteImport.update({ + id: '/data/$id', + path: '/data/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/data/$id': typeof DataIdRoute +} +export interface FileRoutesByTo { + '/data/$id': typeof DataIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/data/$id': typeof DataIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/data/$id' + fileRoutesByTo: FileRoutesByTo + to: '/data/$id' + id: '__root__' | '/data/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + DataIdRoute: typeof DataIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/data/$id': { + id: '/data/$id' + path: '/data/$id' + fullPath: '/data/$id' + preLoaderRoute: typeof DataIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + DataIdRoute: DataIdRoute, +} +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/benchmarks/memory/server/scenarios/serialization-payload/solid/src/router.tsx b/benchmarks/memory/server/scenarios/serialization-payload/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..aaf7dfdd89 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' +import { HydrationScript } from 'solid-js/web' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charset: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/data.$id.tsx b/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/data.$id.tsx new file mode 100644 index 0000000000..8cdbdb9046 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/src/routes/data.$id.tsx @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { makeSerializationPayload } from '../../../serialization-payload' + +export const Route = createFileRoute('/data/$id')({ + loader: ({ params }) => makeSerializationPayload(params.id), + component: DataComponent, +}) + +function DataComponent() { + const data = Route.useLoaderData() + + return ( +
+ Map size: {data().lookup.size} +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/tsconfig.json b/benchmarks/memory/server/scenarios/serialization-payload/solid/tsconfig.json new file mode 100644 index 0000000000..4b61264e11 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts new file mode 100644 index 0000000000..a2d04b986c --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts @@ -0,0 +1,36 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server serialization-payload (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.flame.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/project.json b/benchmarks/memory/server/scenarios/serialization-payload/vue/project.json new file mode 100644 index 0000000000..425b50a0d5 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-serialization-payload-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/setup.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/setup.ts new file mode 100644 index 0000000000..6683dafe6b --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..8adce01d75 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/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 DataIdRouteImport } from './routes/data.$id' + +const DataIdRoute = DataIdRouteImport.update({ + id: '/data/$id', + path: '/data/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/data/$id': typeof DataIdRoute +} +export interface FileRoutesByTo { + '/data/$id': typeof DataIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/data/$id': typeof DataIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/data/$id' + fileRoutesByTo: FileRoutesByTo + to: '/data/$id' + id: '__root__' | '/data/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + DataIdRoute: typeof DataIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/data/$id': { + id: '/data/$id' + path: '/data/$id' + fullPath: '/data/$id' + preLoaderRoute: typeof DataIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + DataIdRoute: DataIdRoute, +} +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/benchmarks/memory/server/scenarios/serialization-payload/vue/src/router.tsx b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..de29ee1612 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/data.$id.tsx b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/data.$id.tsx new file mode 100644 index 0000000000..37b1a590e4 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/data.$id.tsx @@ -0,0 +1,20 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { makeSerializationPayload } from '../../../serialization-payload' + +const DataComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+ Map size: {data.value.lookup.size} +
+ ) + }, +}) + +export const Route = createFileRoute('/data/$id')({ + loader: ({ params }) => makeSerializationPayload(params.id), + component: DataComponent, +}) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/tsconfig.json b/benchmarks/memory/server/scenarios/serialization-payload/vue/tsconfig.json new file mode 100644 index 0000000000..9ad6481342 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts new file mode 100644 index 0000000000..b63a561228 --- /dev/null +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts @@ -0,0 +1,31 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server serialization-payload (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.bench.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.flame.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/project.json b/benchmarks/memory/server/scenarios/server-fn-churn/react/project.json new file mode 100644 index 0000000000..841bbedca0 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-server-fn-churn-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/setup.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/setup.ts new file mode 100644 index 0000000000..0c98f54ddd --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/fns.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/fns.ts new file mode 100644 index 0000000000..22770278cd --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/fns.ts @@ -0,0 +1,24 @@ +import { createMiddleware, createServerFn } from '@tanstack/react-start' +import { + makeServerFnChurnPayload, + validateServerFnInput, +} from '../../server-fn-payload' + +const contextMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => + next({ + context: { + ctx: 'ctx-server-fn-churn', + }, + }), +) + +export const churnGet = createServerFn({ method: 'GET' }) + .middleware([contextMiddleware]) + .validator(validateServerFnInput) + .handler(({ data, context }) => makeServerFnChurnPayload(data, context)) + +export const churnPost = createServerFn({ method: 'POST' }) + .middleware([contextMiddleware]) + .validator(validateServerFnInput) + .handler(({ data, context }) => makeServerFnChurnPayload(data, context)) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..10e933da3d --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/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 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) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/fn-urls' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/fn-urls' + id: '__root__' | '/' | '/api/fn-urls' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiFnUrlsRoute: typeof ApiFnUrlsRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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 + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiFnUrlsRoute: ApiFnUrlsRoute, +} +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/benchmarks/memory/server/scenarios/server-fn-churn/react/src/router.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/__root.tsx new file mode 100644 index 0000000000..c5f9de6922 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/api.fn-urls.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/api.fn-urls.ts new file mode 100644 index 0000000000..da74a20f62 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/api.fn-urls.ts @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' +import { churnGet, churnPost } from '../fns' + +export const Route = createFileRoute('/api/fn-urls')({ + server: { + handlers: { + GET: () => + Response.json({ + get: churnGet.url, + post: churnPost.url, + }), + }, + }, +}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/index.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/index.tsx new file mode 100644 index 0000000000..de0acfc2b3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/src/routes/index.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/react-router' +import { churnGet, churnPost } from '../fns' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return ( +
+ memory-server-fn-churn-index +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/tsconfig.json b/benchmarks/memory/server/scenarios/server-fn-churn/react/tsconfig.json new file mode 100644 index 0000000000..11ddcce4ea --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/vite.config.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/vite.config.ts new file mode 100644 index 0000000000..f72cc53d6f --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/vite.config.ts @@ -0,0 +1,31 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server server-fn-churn (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/server-fn-payload.ts b/benchmarks/memory/server/scenarios/server-fn-churn/server-fn-payload.ts new file mode 100644 index 0000000000..0f23390a6c --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/server-fn-payload.ts @@ -0,0 +1,33 @@ +export type ServerFnInput = { + id: string +} + +export type ServerFnChurnContext = { + ctx: string +} + +const recordIndexes = Array.from({ length: 5 }, (_, index) => index) + +export function validateServerFnInput(input: unknown): ServerFnInput { + const payload = input as Partial | null + + if (typeof payload?.id !== 'string') { + throw new Error('invalid server-fn churn input') + } + + return { id: payload.id } +} + +export function makeServerFnChurnPayload( + data: ServerFnInput, + context: ServerFnChurnContext, +) { + return { + id: data.id, + ctx: context.ctx, + payload: recordIndexes.map((index) => ({ + id: `${data.id}-${index}`, + label: `record-${index}`, + })), + } +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts b/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts new file mode 100644 index 0000000000..167b24d3b6 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts @@ -0,0 +1,232 @@ +import { + createDeterministicRandom, + randomSegment, + runSequentialRequestLoop, +} from '#memory-server/bench-utils' +import type { StartRequestHandler } from '#memory-server/bench-utils' + +export type { StartRequestHandler } + +type Framework = 'react' | 'solid' | 'vue' + +type FnUrls = { + get: string + post: string +} + +type PayloadFixture = { + id: string + body: string + query: string +} + +type SerovalNode = + | { + t: 1 + s: string + } + | { + t: 10 + i: number + p: { + k: Array + v: Array + } + o: number + } + +const benchmarkSeed = 0xdecafbad +const payloadSeed = 0x51f0cafe +const fixtureCount = 16 +const serverFnChurnIterations = 30 +const origin = 'http://localhost' +const tssContentTypeFramed = 'application/x-tss-framed' +const acceptHeader = `${tssContentTypeFramed}, application/x-ndjson, application/json` +const xTssSerialized = 'x-tss-serialized' +const contextMarker = 'ctx-server-fn-churn' + +const commonHeaders = { + 'x-tsr-serverFn': 'true', + 'sec-fetch-site': 'same-origin', + accept: acceptHeader, +} satisfies HeadersInit + +const postHeaders = { + ...commonHeaders, + 'content-type': 'application/json', +} satisfies HeadersInit + +// Hand-rolled copy of Start's seroval RPC wire format so POST bodies can be +// precomputed at module level. Coupled to the internal protocol on purpose; +// the module-load sanity check below throws loudly if the protocol drifts. +function stringNode(value: string): SerovalNode { + return { t: 1, s: value } +} + +function objectNode( + id: number, + entries: Array, +): SerovalNode { + return { + t: 10, + i: id, + p: { + k: entries.map(([key]) => key), + v: entries.map(([, value]) => value), + }, + o: 0, + } +} + +function serializePayload(id: string) { + return JSON.stringify({ + t: objectNode(0, [['data', objectNode(1, [['id', stringNode(id)]])]]), + f: 63, + m: [], + }) +} + +function createFixtures(kind: 'get' | 'post') { + const random = createDeterministicRandom(payloadSeed ^ kind.length) + + return Array.from({ length: fixtureCount }, (_, index): PayloadFixture => { + const id = [kind, index, randomSegment(random), randomSegment(random)].join( + '-', + ) + const body = serializePayload(id) + + return { + id, + body, + query: `?${new URLSearchParams({ payload: body })}`, + } + }) +} + +const getFixtures = createFixtures('get') +const postFixtures = createFixtures('post') + +async function discoverUrls(handler: StartRequestHandler) { + const response = await handler.fetch(new Request(`${origin}/api/fn-urls`)) + const text = await response.text() + + if (response.status !== 200) { + throw new Error( + `URL discovery failed with status ${response.status}: ${text}`, + ) + } + + let urls: Partial + + try { + urls = JSON.parse(text) as Partial + } catch (error) { + throw new Error(`URL discovery returned invalid JSON: ${text}`, { + cause: error, + }) + } + + if (typeof urls.get !== 'string' || typeof urls.post !== 'string') { + throw new Error(`URL discovery returned invalid payload: ${text}`) + } + + return urls as FnUrls +} + +function buildGetRequest(url: string, fixture: PayloadFixture) { + return new Request(`${origin}${url}${fixture.query}`, { + method: 'GET', + headers: commonHeaders, + }) +} + +function buildPostRequest(url: string, fixture: PayloadFixture) { + return new Request(`${origin}${url}`, { + method: 'POST', + headers: postHeaders, + body: fixture.body, + }) +} + +function validateServerFnResponse(response: Response, request: Request) { + if (response.status !== 200) { + throw new Error( + `Expected status 200 for ${request.url}, got ${response.status}`, + ) + } + + if (!response.headers.get(xTssSerialized)) { + throw new Error(`Expected ${xTssSerialized} header for ${request.url}`) + } +} + +function validateEchoedBody( + body: string, + request: Request, + expectedId: string, +) { + if (!body.includes(expectedId)) { + throw new Error(`Expected echoed id ${expectedId} in ${request.url}`) + } + + if (!body.includes(contextMarker)) { + throw new Error( + `Expected context marker ${contextMarker} in ${request.url}`, + ) + } +} + +async function assertServerFnChurnSanity( + handler: StartRequestHandler, + urls: FnUrls, +) { + const getFixture = getFixtures[0]! + const getRequest = buildGetRequest(urls.get, getFixture) + const getResponse = await handler.fetch(getRequest) + const getBody = await getResponse.text() + + validateServerFnResponse(getResponse, getRequest) + validateEchoedBody(getBody, getRequest, getFixture.id) + + const postFixture = postFixtures[0]! + const postRequest = buildPostRequest(urls.post, postFixture) + const postResponse = await handler.fetch(postRequest) + const postBody = await postResponse.text() + + validateServerFnResponse(postResponse, postRequest) + validateEchoedBody(postBody, postRequest, postFixture.id) +} + +export async function createWorkloadGroup( + framework: Framework, + handler: StartRequestHandler, +) { + const urls = await discoverUrls(handler) + const run = async () => + runSequentialRequestLoop(handler, { + seed: benchmarkSeed, + iterations: serverFnChurnIterations, + buildRequest: (_random, index) => { + const fixtureIndex = Math.floor(index / 2) % fixtureCount + + if (index % 2 === 0) { + const fixture = getFixtures[fixtureIndex]! + return buildGetRequest(urls.get, fixture) + } else { + const fixture = postFixtures[fixtureIndex]! + return buildPostRequest(urls.post, fixture) + } + }, + validateResponse: validateServerFnResponse, + }) + + return { + sanity: () => assertServerFnChurnSanity(handler, urls), + workloads: [ + { + name: `mem server server-fn-churn (${framework})`, + run, + }, + ], + } +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.flame.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/project.json b/benchmarks/memory/server/scenarios/server-fn-churn/solid/project.json new file mode 100644 index 0000000000..53aca0cea6 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-server-fn-churn-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/setup.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/setup.ts new file mode 100644 index 0000000000..4fe85c3f00 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/fns.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/fns.ts new file mode 100644 index 0000000000..31669dff50 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/fns.ts @@ -0,0 +1,24 @@ +import { createMiddleware, createServerFn } from '@tanstack/solid-start' +import { + makeServerFnChurnPayload, + validateServerFnInput, +} from '../../server-fn-payload' + +const contextMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => + next({ + context: { + ctx: 'ctx-server-fn-churn', + }, + }), +) + +export const churnGet = createServerFn({ method: 'GET' }) + .middleware([contextMiddleware]) + .validator(validateServerFnInput) + .handler(({ data, context }) => makeServerFnChurnPayload(data, context)) + +export const churnPost = createServerFn({ method: 'POST' }) + .middleware([contextMiddleware]) + .validator(validateServerFnInput) + .handler(({ data, context }) => makeServerFnChurnPayload(data, context)) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..298ac3168d --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/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 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) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/fn-urls' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/fn-urls' + id: '__root__' | '/' | '/api/fn-urls' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiFnUrlsRoute: typeof ApiFnUrlsRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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 + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiFnUrlsRoute: ApiFnUrlsRoute, +} +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/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/router.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..aaf7dfdd89 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' +import { HydrationScript } from 'solid-js/web' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charset: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/api.fn-urls.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/api.fn-urls.ts new file mode 100644 index 0000000000..2063684034 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/api.fn-urls.ts @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { churnGet, churnPost } from '../fns' + +export const Route = createFileRoute('/api/fn-urls')({ + server: { + handlers: { + GET: () => + Response.json({ + get: churnGet.url, + post: churnPost.url, + }), + }, + }, +}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/index.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/index.tsx new file mode 100644 index 0000000000..99fea371f8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/src/routes/index.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { churnGet, churnPost } from '../fns' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return ( +
+ memory-server-fn-churn-index +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/tsconfig.json b/benchmarks/memory/server/scenarios/server-fn-churn/solid/tsconfig.json new file mode 100644 index 0000000000..4b61264e11 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/vite.config.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/vite.config.ts new file mode 100644 index 0000000000..4fba196bd2 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/vite.config.ts @@ -0,0 +1,36 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server server-fn-churn (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) 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 new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.flame.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/project.json b/benchmarks/memory/server/scenarios/server-fn-churn/vue/project.json new file mode 100644 index 0000000000..c5809a259b --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-server-fn-churn-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/setup.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/setup.ts new file mode 100644 index 0000000000..6683dafe6b --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/fns.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/fns.ts new file mode 100644 index 0000000000..0fa679f76f --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/fns.ts @@ -0,0 +1,24 @@ +import { createMiddleware, createServerFn } from '@tanstack/vue-start' +import { + makeServerFnChurnPayload, + validateServerFnInput, +} from '../../server-fn-payload' + +const contextMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => + next({ + context: { + ctx: 'ctx-server-fn-churn', + }, + }), +) + +export const churnGet = createServerFn({ method: 'GET' }) + .middleware([contextMiddleware]) + .validator(validateServerFnInput) + .handler(({ data, context }) => makeServerFnChurnPayload(data, context)) + +export const churnPost = createServerFn({ method: 'POST' }) + .middleware([contextMiddleware]) + .validator(validateServerFnInput) + .handler(({ data, context }) => makeServerFnChurnPayload(data, context)) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..b226f0a25a --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/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 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) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/fn-urls' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/fn-urls' + id: '__root__' | '/' | '/api/fn-urls' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiFnUrlsRoute: typeof ApiFnUrlsRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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 + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiFnUrlsRoute: ApiFnUrlsRoute, +} +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/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/router.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..de29ee1612 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/api.fn-urls.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/api.fn-urls.ts new file mode 100644 index 0000000000..ff99e89e4c --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/api.fn-urls.ts @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { churnGet, churnPost } from '../fns' + +export const Route = createFileRoute('/api/fn-urls')({ + server: { + handlers: { + GET: () => + Response.json({ + get: churnGet.url, + post: churnPost.url, + }), + }, + }, +}) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/index.tsx b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/index.tsx new file mode 100644 index 0000000000..0a39b9301c --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/src/routes/index.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { churnGet, churnPost } from '../fns' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return ( +
+ memory-server-fn-churn-index +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/tsconfig.json b/benchmarks/memory/server/scenarios/server-fn-churn/vue/tsconfig.json new file mode 100644 index 0000000000..9ad6481342 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/vite.config.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/vite.config.ts new file mode 100644 index 0000000000..5ab5ec37e3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/vite.config.ts @@ -0,0 +1,31 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server server-fn-churn (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/deferred-section-data.ts b/benchmarks/memory/server/scenarios/streaming-peak/deferred-section-data.ts new file mode 100644 index 0000000000..b30352ef39 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/deferred-section-data.ts @@ -0,0 +1,37 @@ +const deferredRecordCount = 250 +const recordValueLength = 128 + +interface DeferredRecord { + id: string + value: string +} + +export interface DeferredSectionPayload { + index: number + records: Array +} + +export function makeDeferredSectionPayload( + id: string, + sectionIndex: number, +): DeferredSectionPayload { + return { + index: sectionIndex, + records: Array.from({ length: deferredRecordCount }, (_, recordIndex) => ({ + id: `${id}-${sectionIndex}-${recordIndex}`, + value: makeRecordValue(id, sectionIndex, recordIndex), + })), + } +} + +function makeRecordValue( + id: string, + sectionIndex: number, + recordIndex: number, +) { + const token = `${id}:${sectionIndex}:${recordIndex}:streaming-peak-record;` + + return token + .repeat(Math.ceil(recordValueLength / token.length)) + .slice(0, recordValueLength) +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.flame.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/project.json b/benchmarks/memory/server/scenarios/streaming-peak/react/project.json new file mode 100644 index 0000000000..6fc1dcdda0 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-streaming-peak-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/setup.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/setup.ts new file mode 100644 index 0000000000..0c98f54ddd --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('react', handler) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..fbbc25ecfb --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/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 StreamIdRouteImport } from './routes/stream.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const StreamIdRoute = StreamIdRouteImport.update({ + id: '/stream/$id', + path: '/stream/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/stream/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/stream/$id' + id: '__root__' | '/' | '/stream/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + StreamIdRoute: typeof StreamIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/stream/$id': { + id: '/stream/$id' + path: '/stream/$id' + fullPath: '/stream/$id' + preLoaderRoute: typeof StreamIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + StreamIdRoute: StreamIdRoute, +} +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/benchmarks/memory/server/scenarios/streaming-peak/react/src/router.tsx b/benchmarks/memory/server/scenarios/streaming-peak/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/__root.tsx new file mode 100644 index 0000000000..c5f9de6922 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/index.tsx b/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/index.tsx new file mode 100644 index 0000000000..669fdef2e1 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
streaming-peak-index
+} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/stream.$id.tsx new file mode 100644 index 0000000000..886cb64d45 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/stream.$id.tsx @@ -0,0 +1,98 @@ +import { Await, createFileRoute } from '@tanstack/react-router' +import { Suspense } from 'react' +import { + makeDeferredSectionPayload, + type DeferredSectionPayload, +} from '../../../deferred-section-data' + +const fallbackFlushTicks = 4 + +export const Route = createFileRoute('/stream/$id')({ + loader: ({ params }) => ({ + eager: `streaming-peak-eager-${params.id}`, + deferred0: makeDeferredSection(params.id, 0), + deferred1: makeDeferredSection(params.id, 1), + deferred2: makeDeferredSection(params.id, 2), + deferred3: makeDeferredSection(params.id, 3), + }), + component: StreamComponent, +}) + +// Deferred sections must settle strictly AFTER React's shell flush, which +// React schedules via setImmediate internally. Microtask chains drain during +// router load (sections resolve before the Suspense boundaries are even +// reached) and setImmediate chains registered at loader time win the race +// against React's flush — either way no fallback ever streams and the bench +// stops exercising multi-flush streaming. Timers-phase callbacks reliably +// lose that race, but a millisecond delay makes the loss margin wall-clock +// dependent, so this chains 0ms hops instead: each hop yields one full +// event-loop turn (immediates and microtasks included), making the flush +// ordering a function of turn count, not runner speed. Distinct hop counts +// keep section ordering deterministic. +function afterFallbackFlush(sectionIndex: number) { + return new Promise((resolve) => { + let remaining = fallbackFlushTicks + sectionIndex + + const step = () => { + remaining -= 1 + + if (remaining <= 0) { + resolve() + return + } + + setTimeout(step, 0) + } + + setTimeout(step, 0) + }) +} + +function makeDeferredSection(id: string, sectionIndex: number) { + return afterFallbackFlush(sectionIndex).then(() => + makeDeferredSectionPayload(id, sectionIndex), + ) +} + +function StreamComponent() { + const data = Route.useLoaderData() + const deferredSections = [ + { index: 0, promise: data.deferred0 }, + { index: 1, promise: data.deferred1 }, + { index: 2, promise: data.deferred2 }, + { index: 3, promise: data.deferred3 }, + ] as const + + return ( +
+

{data.eager}

+ {deferredSections.map(({ index, promise }) => ( + + streaming-peak-fallback-{index} +

+ } + > + + {(section) => } + +
+ ))} +
+ ) +} + +function DeferredSection({ section }: { section: DeferredSectionPayload }) { + const marker = `streaming-peak-deferred-${section.index}` + + return ( +
+

{marker}

+ {section.records.map((record) => ( +

{record.value}

+ ))} +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/tsconfig.json b/benchmarks/memory/server/scenarios/streaming-peak/react/tsconfig.json new file mode 100644 index 0000000000..11ddcce4ea --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts new file mode 100644 index 0000000000..5d555441b6 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts @@ -0,0 +1,31 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server streaming-peak (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/shared.ts b/benchmarks/memory/server/scenarios/streaming-peak/shared.ts new file mode 100644 index 0000000000..c027047408 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/shared.ts @@ -0,0 +1,117 @@ +import { + randomSegment, + runSequentialRequestLoop, +} from '#memory-server/bench-utils' +import type { StartRequestHandler } from '#memory-server/bench-utils' + +export type { StartRequestHandler } + +type Framework = 'react' | 'solid' | 'vue' + +const benchmarkSeed = 0xdecafbad +const streamingPeakIterations = 1 +const fallbackMarker = 'streaming-peak-fallback-0' + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +function buildStreamingRequest(random: () => number, index: number) { + return new Request( + `http://localhost/stream/${index}-${randomSegment(random)}`, + requestInit, + ) +} + +function validateStreamingResponse(response: Response, request: Request) { + if (response.status !== 200) { + throw new Error( + `Expected status 200 for ${request.url}, got ${response.status}`, + ) + } +} + +function getResponseReader(response: Response) { + const reader = response.body?.getReader() + + if (!reader) { + throw new Error('Expected streaming response body') + } + + return reader +} + +async function readStreamingBody(response: Response) { + const reader = getResponseReader(response) + const decoder = new TextDecoder() + let body = '' + let chunkCount = 0 + + for (;;) { + const result = await reader.read() + + if (result.done) { + break + } + + chunkCount++ + body += decoder.decode(result.value, { stream: true }) + } + + body += decoder.decode() + + return { body, chunkCount } +} + +async function assertStreamingPeakSanity(handler: StartRequestHandler) { + const chunkedRequest = new Request( + 'http://localhost/stream/sanity-chunked', + requestInit, + ) + const chunkedResponse = await handler.fetch(chunkedRequest) + + validateStreamingResponse(chunkedResponse, chunkedRequest) + + const chunked = await readStreamingBody(chunkedResponse) + + if (chunked.chunkCount <= 1) { + throw new Error( + `Expected chunked sanity response to produce multiple chunks, got ${chunked.chunkCount}`, + ) + } + + if (!chunked.body.includes(fallbackMarker)) { + throw new Error('Expected streaming-peak fallback marker in response body') + } +} + +export function createWorkloadGroup( + framework: Framework, + handler: StartRequestHandler, +) { + const run = async () => + runSequentialRequestLoop(handler, { + seed: benchmarkSeed, + iterations: streamingPeakIterations, + buildRequest: buildStreamingRequest, + validateResponse: validateStreamingResponse, + }) + + return { + sanity: async () => { + // Import the route chunks before checking streaming. Cold disk I/O can + // otherwise outlast the deferred payload and collapse the first response. + await run() + await assertStreamingPeakSanity(handler) + }, + workloads: [ + { + name: `mem server streaming-peak chunked (${framework})`, + run, + }, + ], + } +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.flame.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/project.json b/benchmarks/memory/server/scenarios/streaming-peak/solid/project.json new file mode 100644 index 0000000000..80f44d1063 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-streaming-peak-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/setup.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/setup.ts new file mode 100644 index 0000000000..4fe85c3f00 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('solid', handler) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..04ebed80f0 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/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 StreamIdRouteImport } from './routes/stream.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const StreamIdRoute = StreamIdRouteImport.update({ + id: '/stream/$id', + path: '/stream/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/stream/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/stream/$id' + id: '__root__' | '/' | '/stream/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + StreamIdRoute: typeof StreamIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/stream/$id': { + id: '/stream/$id' + path: '/stream/$id' + fullPath: '/stream/$id' + preLoaderRoute: typeof StreamIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + StreamIdRoute: StreamIdRoute, +} +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/benchmarks/memory/server/scenarios/streaming-peak/solid/src/router.tsx b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..aaf7dfdd89 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' +import { HydrationScript } from 'solid-js/web' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charset: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/index.tsx b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/index.tsx new file mode 100644 index 0000000000..5815e36b3d --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
streaming-peak-index
+} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/stream.$id.tsx new file mode 100644 index 0000000000..977f43061e --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/stream.$id.tsx @@ -0,0 +1,91 @@ +import { Await, createFileRoute } from '@tanstack/solid-router' +import { Suspense } from 'solid-js' +import { + makeDeferredSectionPayload, + type DeferredSectionPayload, +} from '../../../deferred-section-data' + +const fallbackFlushTicks = 12 + +export const Route = createFileRoute('/stream/$id')({ + loader: ({ params }) => ({ + eager: `streaming-peak-eager-${params.id}`, + deferred0: makeDeferredSection(params.id, 0), + deferred1: makeDeferredSection(params.id, 1), + deferred2: makeDeferredSection(params.id, 2), + deferred3: makeDeferredSection(params.id, 3), + }), + component: StreamComponent, +}) + +// Deferred sections must settle after the framework shell flush so the bench +// continues exercising multi-flush streaming with visible fallback chunks. +// Chained 0ms timers-phase hops give the renderer a deterministic number of +// full event-loop turns to flush, instead of a wall-clock delay whose margin +// varies with runner load; distinct hop counts keep section ordering stable. +function afterFallbackFlush(sectionIndex: number) { + return new Promise((resolve) => { + let remaining = fallbackFlushTicks + sectionIndex + + const step = () => { + remaining -= 1 + + if (remaining <= 0) { + resolve() + return + } + + setTimeout(step, 0) + } + + setTimeout(step, 0) + }) +} + +function makeDeferredSection(id: string, sectionIndex: number) { + return afterFallbackFlush(sectionIndex).then(() => + makeDeferredSectionPayload(id, sectionIndex), + ) +} + +function StreamComponent() { + const data = Route.useLoaderData() + const deferredSections = () => + [ + { index: 0, promise: data().deferred0 }, + { index: 1, promise: data().deferred1 }, + { index: 2, promise: data().deferred2 }, + { index: 3, promise: data().deferred3 }, + ] as const + + return ( +
+

{data().eager}

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

+ streaming-peak-fallback-{index} +

+ + + {(section) => } + + + + ))} +
+ ) +} + +function DeferredSection(props: { section: DeferredSectionPayload }) { + const marker = () => `streaming-peak-deferred-${props.section.index}` + + return ( +
+

{marker()}

+ {props.section.records.map((record) => ( +

{record.value}

+ ))} +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/tsconfig.json b/benchmarks/memory/server/scenarios/streaming-peak/solid/tsconfig.json new file mode 100644 index 0000000000..4b61264e11 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts new file mode 100644 index 0000000000..5fbdb48c23 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts @@ -0,0 +1,36 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server streaming-peak (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts new file mode 100644 index 0000000000..8b5f16ad63 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +test('memory', async ({ bench }) => { + for (const workload of workloadGroup.workloads) { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) + } +}) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.flame.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.flame.ts new file mode 100644 index 0000000000..0182c472a8 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.flame.ts @@ -0,0 +1,4 @@ +import { runServerFlameBenchmark } from '#memory-server/flame-runner' +import { workloadGroup } from './setup.ts' + +await runServerFlameBenchmark(workloadGroup) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/project.json b/benchmarks/memory/server/scenarios/streaming-peak/vue/project.json new file mode 100644 index 0000000000..55771aebe3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/project.json @@ -0,0 +1,54 @@ +{ + "name": "@benchmarks/memory-server-streaming-peak-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "build:ssr:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts --sourcemap true" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "parallelism": false, + "cache": false, + "dependsOn": ["build:ssr:flame"], + "options": { + "command": "NODE_ENV=production node benchmarks/memory/run-flame.mjs {projectRoot}/memory.flame.ts {projectRoot}/dist", + "cwd": "." + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/setup.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/setup.ts new file mode 100644 index 0000000000..6683dafe6b --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/setup.ts @@ -0,0 +1,14 @@ +import type { ServerMemoryWorkloadGroup } from '#memory-server/benchmark' +import { createWorkloadGroup } from '../shared.ts' +import type { StartRequestHandler } from '../shared.ts' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +export const workloadGroup: ServerMemoryWorkloadGroup = + await createWorkloadGroup('vue', handler) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..192f1d6dc7 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/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 StreamIdRouteImport } from './routes/stream.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const StreamIdRoute = StreamIdRouteImport.update({ + id: '/stream/$id', + path: '/stream/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/stream/$id': typeof StreamIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/stream/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/stream/$id' + id: '__root__' | '/' | '/stream/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + StreamIdRoute: typeof StreamIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/stream/$id': { + id: '/stream/$id' + path: '/stream/$id' + fullPath: '/stream/$id' + preLoaderRoute: typeof StreamIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + StreamIdRoute: StreamIdRoute, +} +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/benchmarks/memory/server/scenarios/streaming-peak/vue/src/router.tsx b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/__root.tsx b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..de29ee1612 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [{ charSet: 'utf-8' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/index.tsx b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/index.tsx new file mode 100644 index 0000000000..bc55b49adc --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
streaming-peak-index
+} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/stream.$id.tsx new file mode 100644 index 0000000000..750d1cb47d --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/stream.$id.tsx @@ -0,0 +1,103 @@ +import { Await, createFileRoute } from '@tanstack/vue-router' +import { Suspense, defineComponent } from 'vue' +import { + makeDeferredSectionPayload, + type DeferredSectionPayload, +} from '../../../deferred-section-data' + +const fallbackFlushTicks = 20 + +const StreamComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const deferredSections = [ + { index: 0, promise: data.value.deferred0 }, + { index: 1, promise: data.value.deferred1 }, + { index: 2, promise: data.value.deferred2 }, + { index: 3, promise: data.value.deferred3 }, + ] as const + + return ( +
+

{data.value.eager}

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

+ streaming-peak-fallback-{index} +

+ + {{ + default: () => ( + ( + + )} + /> + ), + fallback: () => null, + }} + + + ))} +
+ ) + } + }, +}) + +export const Route = createFileRoute('/stream/$id')({ + loader: ({ params }) => ({ + eager: `streaming-peak-eager-${params.id}`, + deferred0: makeDeferredSection(params.id, 0), + deferred1: makeDeferredSection(params.id, 1), + deferred2: makeDeferredSection(params.id, 2), + deferred3: makeDeferredSection(params.id, 3), + }), + component: StreamComponent, +}) + +// Deferred sections must settle strictly AFTER Vue's shell has a chance to +// flush, so fallbacks are emitted before deferred section content. +// Chained 0ms timers-phase hops give the renderer a deterministic number of +// full event-loop turns to flush, instead of a wall-clock delay whose margin +// varies with runner load; distinct hop counts keep section ordering stable. +function afterFallbackFlush(sectionIndex: number) { + return new Promise((resolve) => { + let remaining = fallbackFlushTicks + sectionIndex + + const step = () => { + remaining -= 1 + + if (remaining <= 0) { + resolve() + return + } + + setTimeout(step, 0) + } + + setTimeout(step, 0) + }) +} + +function makeDeferredSection(id: string, sectionIndex: number) { + return afterFallbackFlush(sectionIndex).then(() => + makeDeferredSectionPayload(id, sectionIndex), + ) +} + +function DeferredSection({ section }: { section: DeferredSectionPayload }) { + const marker = `streaming-peak-deferred-${section.index}` + + return ( +
+

{marker}

+ {section.records.map((record) => ( +

{record.value}

+ ))} +
+ ) +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/tsconfig.json b/benchmarks/memory/server/scenarios/streaming-peak/vue/tsconfig.json new file mode 100644 index 0000000000..9ad6481342 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../../../../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "memory.bench.ts", + "memory.flame.ts", + "setup.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts new file mode 100644 index 0000000000..cd848584a5 --- /dev/null +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts @@ -0,0 +1,31 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + ...memoryConfig('server'), + name: '@benchmarks/memory-server streaming-peak (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/memory/server/tsconfig.json b/benchmarks/memory/server/tsconfig.json new file mode 100644 index 0000000000..86d36f047a --- /dev/null +++ b/benchmarks/memory/server/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "bench-utils.ts", + "scenarios/*/shared.ts", + "../runtime.ts", + "vitest.setup.ts" + ] +} diff --git a/benchmarks/memory/server/vitest.react.config.ts b/benchmarks/memory/server/vitest.react.config.ts new file mode 100644 index 0000000000..44643b4d60 --- /dev/null +++ b/benchmarks/memory/server/vitest.react.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + fileParallelism: false, + projects: ['./scenarios/*/react/vite.config.ts'], + }, +}) diff --git a/benchmarks/memory/server/vitest.solid.config.ts b/benchmarks/memory/server/vitest.solid.config.ts new file mode 100644 index 0000000000..5c8185cdd9 --- /dev/null +++ b/benchmarks/memory/server/vitest.solid.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + fileParallelism: false, + projects: ['./scenarios/*/solid/vite.config.ts'], + }, +}) diff --git a/benchmarks/memory/server/vitest.vue.config.ts b/benchmarks/memory/server/vitest.vue.config.ts new file mode 100644 index 0000000000..01768185ee --- /dev/null +++ b/benchmarks/memory/server/vitest.vue.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + fileParallelism: false, + projects: ['./scenarios/*/vue/vite.config.ts'], + }, +}) diff --git a/benchmarks/memory/tsconfig.json b/benchmarks/memory/tsconfig.json new file mode 100644 index 0000000000..5a325f3b6c --- /dev/null +++ b/benchmarks/memory/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["runtime.ts"] +} diff --git a/benchmarks/memory/turn.ts b/benchmarks/memory/turn.ts new file mode 100644 index 0000000000..08729685fe --- /dev/null +++ b/benchmarks/memory/turn.ts @@ -0,0 +1,34 @@ +export function isMemoryInstrumented() { + return ( + process.env.CODSPEED_ENV !== undefined && + process.env.CODSPEED_RUNNER_MODE === 'memory' + ) +} + +// CodSpeed calls beforeEach before its forced GC and measurement marker. End +// the previous warmup's job so WeakRef targets can be released by that GC. +export function endMemoryTurn() { + return new Promise((resolve) => setImmediate(resolve)) +} + +/** + * Per-invocation bench hooks. CodSpeed runs them around every warmup + * invocation and the measured one, outside the measurement marker: the turn + * ends first, then the workload prepares fresh state before the forced GC. + */ +export function memoryBenchHooks( + workload: { + before?: () => Promise | void + after?: () => Promise | void + } = {}, +) { + return { + async beforeEach() { + if (isMemoryInstrumented()) { + await endMemoryTurn() + } + await workload.before?.() + }, + afterEach: workload.after, + } +} diff --git a/benchmarks/ssr/README.md b/benchmarks/ssr/README.md new file mode 100644 index 0000000000..3d90af1598 --- /dev/null +++ b/benchmarks/ssr/README.md @@ -0,0 +1,115 @@ +# SSR Benchmarks + +Cross-framework SSR request-loop benchmarks for: + +- `@tanstack/react-start` +- `@tanstack/solid-start` +- `@tanstack/vue-start` + +Each benchmark builds a Start app with file-based routes and runs Vitest benches against the built server handler. + +## Layout + +- `react/` - React Start baseline benchmark + Vitest config +- `solid/` - Solid Start baseline benchmark + Vitest config +- `vue/` - Vue Start baseline benchmark + Vitest config +- `vitest.react.config.ts`, `vitest.solid.config.ts`, `vitest.vue.config.ts` - per-framework aggregate configs that run the baseline first, then scenario projects +- `scenarios///` - isolated scenario apps + +Scenario app layout: + +```text +scenarios/// + vite.config.ts + speed.bench.ts + tsconfig.json + src/ + router.tsx + routes/ + routeTree.gen.ts +``` + +Each scenario uses one app per framework instead of sharing routes in the baseline app. This keeps route-tree size, middleware, Start options, and generated route trees isolated so one scenario cannot shift another scenario's numbers. The existing baseline apps and bench names stay stable for CodSpeed continuity. + +## Scenario Responsibilities + +Each scenario isolates one Start server-side responsibility so benchmark changes can be attributed to a specific feature area. + +| Scenario | Start server-side responsibility | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `react/`, `solid/`, `vue/` baseline apps | Document SSR for nested file routes, route matching, search parsing, and full-page HTML response generation. | +| `assets` | Per-request asset pipeline work: CSS inlining, CDN asset URL transforms with uncached manifest resolution, and response `Link` header collection for early hints. | +| `before-load` | Nested `beforeLoad` execution: sequential per-match context building, context merging across matches, and context consumption by loaders during document SSR. | +| `control-flow` | Loader-thrown `redirect`, `notFound`, plain errors, unmatched routes, and route `headers()` emission, including HTTP status selection, redirect `location` headers, route error boundaries, and not-found HTML rendering. | +| `global-middleware` | Global `createStart` middleware registration: request middleware wrapping document SSR, server-function, and server-route requests, plus global function middleware on server functions. | +| `head` | Nested route `head` evaluation, title/meta/link serialization, and head-entry deduplication during SSR. | +| `loaders` | Nested route loader execution, loader deps from search params, router context reads, and dehydrated loader payload generation. | +| `rewrites` | Composed location rewrites from router `basepath` plus locale input/output rewrites; unprefixed URLs redirect to `/app/*` when the basepath output rewrite canonicalizes them. | +| `serialization` | Dehydration and RPC serialization of rich non-plain-JSON types: seroval native types in loader payloads, custom serialization adapters, and shallow-error serialization. | +| `selective-ssr` | Route-level `ssr` modes: rendered server HTML with `ssr: true`, dehydrated data without HTML with `ssr: 'data-only'`, and client-only omission with `ssr: false`. | +| `server-fn-transport` | Non-JSON server-function transport: multipart/FormData request decoding, raw `Response` returns, and `RawStream` streamed responses through the binary frame protocol. | +| `server-fns` | `createServerFn` GET/POST request handling, thrown redirect/notFound results, sendContext serialization, SSR-time direct calls, middleware context, input validation, and URL discovery. | +| `server-routes` | File route `server.handlers` dispatch for parameterized JSON API routes without document HTML rendering. | +| `server-routes-middleware` | Server route request middleware chains, middleware-provided context merging, and handler access to accumulated context. | +| `streaming` | Deferred loader data, `Await`/Suspense fallback output, larger streamed HTML body scanning, streamed HTML ordering, and later dehydration payload emission. | + +## Run + +Run all benchmarks through Nx so dependency builds are part of the graph: + +```bash +pnpm nx run @benchmarks/ssr:test:perf --outputStyle=stream --skipRemoteCache +``` + +Run framework-specific benchmarks: + +```bash +pnpm nx run @benchmarks/ssr:test:perf:react --outputStyle=stream --skipRemoteCache +pnpm nx run @benchmarks/ssr:test:perf:solid --outputStyle=stream --skipRemoteCache +pnpm nx run @benchmarks/ssr:test:perf:vue --outputStyle=stream --skipRemoteCache +``` + +Build framework-specific benchmark apps: + +```bash +pnpm nx run @benchmarks/ssr:build:react --outputStyle=stream --skipRemoteCache +pnpm nx run @benchmarks/ssr:build:solid --outputStyle=stream --skipRemoteCache +pnpm nx run @benchmarks/ssr:build:vue --outputStyle=stream --skipRemoteCache +``` + +Typecheck benchmark sources: + +```bash +pnpm nx run @benchmarks/ssr:test:types --outputStyle=stream --skipRemoteCache +``` + +Run one scenario app manually through Nx: + +```bash +pnpm nx run @benchmarks/ssr--:build:ssr --outputStyle=stream --skipRemoteCache +pnpm nx run @benchmarks/ssr--:test:types:ssr --outputStyle=stream --skipRemoteCache +``` + +Use `react`, `solid`, or `vue` for ``. The baseline projects use `@benchmarks/ssr-` without a scenario segment. + +## Request Conventions + +- Document GET loops use `accept: text/html`, matching the baseline request shape. +- Server-function loops must include `sec-fetch-site: same-origin` so the default CSRF middleware accepts the request. +- Loops that expect non-200 responses pass a custom `validateResponse` to `runRequestLoop`. +- Bench loops must build deterministic requests from the seeded random helper and consume response bodies through `runRequestLoop` or `runSsrRequestLoop`. + +## Optional React Link workloads + +The [opt-in Link suite](../client-nav/README.md#opt-in-react-link-performance-suite) +adds focused standalone React Router SSR coverage for params/updaters, +inheritance, search middlewares, optional/splat segments, encoding, masks, +rewrites, and active props. Each timed batch creates four fresh routers and +renders their Links to HTML; it does not measure Start HTTP/streaming overhead. + +```bash +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:ssr --outputStyle=stream --skipRemoteCache -- --run +``` + +These cases are excluded from this directory's aggregate projects and normal +CodSpeed dependency graph; they only run through the dedicated target above. diff --git a/benchmarks/ssr/bench-utils.test.ts b/benchmarks/ssr/bench-utils.test.ts new file mode 100644 index 0000000000..c6a520447b --- /dev/null +++ b/benchmarks/ssr/bench-utils.test.ts @@ -0,0 +1,145 @@ +import { describe, expect, it } from 'vitest' +import { buildRequestSequences, runRequestLoop } from './bench-utils' +import type { StartRequestHandler } from './bench-utils' + +function deferred() { + let resolve = () => {} + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise + }) + return { promise, resolve } +} + +describe('runRequestLoop', () => { + it('caps fixed concurrency and waits for every streaming body', async () => { + const concurrency = 4 + const totalRequests = 20 + const firstWaveStarted = deferred() + let builtRequests = 0 + let executedRequests = 0 + let validatedResponses = 0 + let finishedBodies = 0 + let inFlightRequests = 0 + let maximumInFlightRequests = 0 + + const handler: StartRequestHandler = { + fetch() { + expect(builtRequests).toBe(totalRequests) + executedRequests += 1 + inFlightRequests += 1 + maximumInFlightRequests = Math.max( + maximumInFlightRequests, + inFlightRequests, + ) + + if (inFlightRequests === concurrency) { + firstWaveStarted.resolve() + } + + const body = new ReadableStream({ + async start(controller) { + await firstWaveStarted.promise + controller.enqueue(new Uint8Array([1])) + controller.close() + finishedBodies += 1 + inFlightRequests -= 1 + }, + }) + + return new Response(body) + }, + } + + await runRequestLoop(handler, { + seed: 123, + concurrency, + totalRequests, + buildRequest: (_random, index) => { + builtRequests += 1 + return new Request(`http://localhost/request/${index}`) + }, + validateResponse: () => { + validatedResponses += 1 + }, + }) + + expect(builtRequests).toBe(totalRequests) + expect(executedRequests).toBe(totalRequests) + expect(validatedResponses).toBe(totalRequests) + expect(maximumInFlightRequests).toBe(concurrency) + expect(inFlightRequests).toBe(0) + expect(finishedBodies).toBe(totalRequests) + }) + + it('builds identical predetermined worker sequences from identical seeds', () => { + const buildSequences = (seed: number) => + buildRequestSequences({ + seed, + concurrency: 4, + totalRequests: 12, + buildRequest: (random, index) => + new Request( + `http://localhost/request/${index}?value=${random().toString(36)}`, + ), + }).map((requests) => requests.map((request) => request.url)) + + const first = buildSequences(456) + const second = buildSequences(456) + + expect(second).toEqual(first) + expect(first.map((requests) => requests.map(requestIndex))).toEqual([ + [0, 4, 8], + [1, 5, 9], + [2, 6, 10], + [3, 7, 11], + ]) + }) + + it('drains every started body before reporting a worker failure', async () => { + const concurrency = 4 + const firstWaveStarted = deferred() + let executedRequests = 0 + let finishedBodies = 0 + let inFlightRequests = 0 + + const handler: StartRequestHandler = { + fetch(request) { + executedRequests += 1 + inFlightRequests += 1 + if (inFlightRequests === concurrency) { + firstWaveStarted.resolve() + } + + const body = new ReadableStream({ + async start(controller) { + await firstWaveStarted.promise + controller.close() + finishedBodies += 1 + inFlightRequests -= 1 + }, + }) + + return new Response(body, { + status: request.url.endsWith('/0') ? 500 : 200, + }) + }, + } + + await expect( + runRequestLoop(handler, { + seed: 789, + concurrency, + totalRequests: 12, + buildRequest: (_random, index) => + new Request(`http://localhost/request/${index}`), + }), + ).rejects.toThrow('non-200 status 500') + + expect(finishedBodies).toBe(executedRequests) + expect(inFlightRequests).toBe(0) + }) +}) + +function requestIndex(url: string) { + return Number(new URL(url).pathname.split('/').at(-1)) +} diff --git a/benchmarks/ssr/bench-utils.ts b/benchmarks/ssr/bench-utils.ts new file mode 100644 index 0000000000..7a54fce897 --- /dev/null +++ b/benchmarks/ssr/bench-utils.ts @@ -0,0 +1,205 @@ +export interface StartRequestHandler { + fetch: (request: Request) => Promise | Response +} + +export interface RunSsrRequestLoopOptions { + seed: number + iterations?: number +} + +export interface RunRequestLoopOptions { + seed: number + concurrency: number + totalRequests: number + buildRequest: (random: () => number, index: number) => Request + validateResponse?: (response: Response, request: Request) => void +} + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +function createDeterministicRandom(seed: number) { + let state = seed >>> 0 + + return () => { + state = (state * 1664525 + 1013904223) >>> 0 + return state / 0x100000000 + } +} + +function randomSegment(random: () => number) { + return Math.floor(random() * 1_000_000_000).toString(36) +} + +export { createDeterministicRandom, randomSegment } + +export async function drainResponse(response: Response) { + const reader = response.body?.getReader() + + if (!reader) { + return + } + + try { + while (true) { + const result = await reader.read() + + if (result.done) { + break + } + } + } finally { + reader.releaseLock() + } +} + +function randomSearchValue(random: () => number) { + return `q-${randomSegment(random)}` +} + +function randomRequestUrl(random: () => number) { + const a = randomSegment(random) + const b = randomSegment(random) + const c = randomSegment(random) + const d = randomSegment(random) + const q = randomSearchValue(random) + + return `http://localhost/${a}/${b}/${c}/${d}?q=${q}` +} + +export async function runSsrRequestLoop( + handler: StartRequestHandler, + { seed, iterations = 10 }: RunSsrRequestLoopOptions, +) { + const random = createDeterministicRandom(seed) + const pendingBodyReads: Array> = [] + + for (let index = 0; index < iterations; index++) { + const requestUrl = randomRequestUrl(random) + const response = await handler.fetch(new Request(requestUrl, requestInit)) + + if (response.status !== 200) { + await Promise.allSettled(pendingBodyReads) + + throw new Error( + `Request failed with non-200 status ${response.status} (${requestUrl})`, + ) + } + + pendingBodyReads.push(drainResponse(response)) + } + + await Promise.all(pendingBodyReads) +} + +export async function runRequestLoop( + handler: StartRequestHandler, + { + seed, + concurrency, + totalRequests, + buildRequest, + validateResponse, + }: RunRequestLoopOptions, +) { + const requestSequences = buildRequestSequences({ + seed, + concurrency, + totalRequests, + buildRequest, + }) + const validate = + validateResponse ?? + ((response: Response, request: Request) => { + if (response.status !== 200) { + throw new Error( + `Request failed with non-200 status ${response.status} (${request.url})`, + ) + } + }) + + let startWorkers = () => {} + const startBarrier = new Promise((resolve) => { + startWorkers = resolve + }) + + const workers = requestSequences.map(async (requests) => { + await startBarrier + + for (const request of requests) { + const response = await handler.fetch(request) + let validationFailure: { error: unknown } | undefined + + try { + validate(response, request) + } catch (error) { + validationFailure = { error } + } + + await drainResponse(response) + + if (validationFailure) { + throw validationFailure.error + } + } + }) + + startWorkers() + const results = await Promise.allSettled(workers) + const failedWorker = results.find( + (result): result is PromiseRejectedResult => result.status === 'rejected', + ) + + if (failedWorker) { + throw failedWorker.reason + } +} + +export type BuildRequestSequencesOptions = Pick< + RunRequestLoopOptions, + 'seed' | 'concurrency' | 'totalRequests' | 'buildRequest' +> + +/** + * Build the entire seeded workload before any request starts, then partition + * it round-robin so completion timing can never change a worker's next input. + */ +export function buildRequestSequences({ + seed, + concurrency, + totalRequests, + buildRequest, +}: BuildRequestSequencesOptions): Array> { + assertPositiveInteger('concurrency', concurrency) + assertPositiveInteger('totalRequests', totalRequests) + + if (concurrency > totalRequests) { + throw new RangeError( + `concurrency (${concurrency}) cannot exceed totalRequests (${totalRequests})`, + ) + } + + const random = createDeterministicRandom(seed) + const requestSequences = Array.from( + { length: concurrency }, + () => new Array(), + ) + + for (let index = 0; index < totalRequests; index++) { + requestSequences[index % concurrency]!.push(buildRequest(random, index)) + } + + return requestSequences +} + +function assertPositiveInteger(name: string, value: number) { + if (!Number.isSafeInteger(value) || value < 1) { + throw new RangeError( + `${name} must be a positive integer; received ${value}`, + ) + } +} diff --git a/benchmarks/ssr/package.json b/benchmarks/ssr/package.json new file mode 100644 index 0000000000..20c1837468 --- /dev/null +++ b/benchmarks/ssr/package.json @@ -0,0 +1,231 @@ +{ + "name": "@benchmarks/ssr", + "private": true, + "type": "module", + "dependencies": { + "@tanstack/react-router": "workspace:^", + "@tanstack/react-start": "workspace:^", + "@tanstack/solid-router": "workspace:^", + "@tanstack/solid-start": "workspace:^", + "@tanstack/vue-router": "workspace:^", + "@tanstack/vue-start": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "solid-js": "^1.9.10", + "vue": "^3.5.16" + }, + "devDependencies": { + "@codspeed/vitest-plugin": "^6.0.1", + "@vitejs/plugin-react": "^6.0.1", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "@types/react": "catalog:", + "seroval": "^1.6.7", + "@typescript/native": "npm:typescript@^7.0.2", + "jsdom": "29.1.1", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11", + "vitest": "catalog:" + }, + "nx": { + "targets": { + "build:react": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/ssr-react", + "@benchmarks/ssr-assets-react", + "@benchmarks/ssr-before-load-react", + "@benchmarks/ssr-control-flow-react", + "@benchmarks/ssr-global-middleware-react", + "@benchmarks/ssr-head-react", + "@benchmarks/ssr-loaders-react", + "@benchmarks/ssr-rewrites-react", + "@benchmarks/ssr-serialization-react", + "@benchmarks/ssr-selective-ssr-react", + "@benchmarks/ssr-server-fn-transport-react", + "@benchmarks/ssr-server-fns-react", + "@benchmarks/ssr-server-routes-react", + "@benchmarks/ssr-server-routes-middleware-react", + "@benchmarks/ssr-streaming-react" + ], + "target": "build:ssr" + } + ] + }, + "build:solid": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/ssr-solid", + "@benchmarks/ssr-assets-solid", + "@benchmarks/ssr-before-load-solid", + "@benchmarks/ssr-control-flow-solid", + "@benchmarks/ssr-global-middleware-solid", + "@benchmarks/ssr-head-solid", + "@benchmarks/ssr-loaders-solid", + "@benchmarks/ssr-rewrites-solid", + "@benchmarks/ssr-serialization-solid", + "@benchmarks/ssr-selective-ssr-solid", + "@benchmarks/ssr-server-fn-transport-solid", + "@benchmarks/ssr-server-fns-solid", + "@benchmarks/ssr-server-routes-solid", + "@benchmarks/ssr-server-routes-middleware-solid", + "@benchmarks/ssr-streaming-solid" + ], + "target": "build:ssr" + } + ] + }, + "build:vue": { + "executor": "nx:noop", + "cache": false, + "dependsOn": [ + { + "projects": [ + "@benchmarks/ssr-vue", + "@benchmarks/ssr-assets-vue", + "@benchmarks/ssr-before-load-vue", + "@benchmarks/ssr-control-flow-vue", + "@benchmarks/ssr-global-middleware-vue", + "@benchmarks/ssr-head-vue", + "@benchmarks/ssr-loaders-vue", + "@benchmarks/ssr-rewrites-vue", + "@benchmarks/ssr-serialization-vue", + "@benchmarks/ssr-selective-ssr-vue", + "@benchmarks/ssr-server-fn-transport-vue", + "@benchmarks/ssr-server-fns-vue", + "@benchmarks/ssr-server-routes-vue", + "@benchmarks/ssr-server-routes-middleware-vue", + "@benchmarks/ssr-streaming-vue" + ], + "target": "build:ssr" + } + ] + }, + "test:perf": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + "build:react", + "build:solid", + "build:vue" + ], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark", + "cwd": "benchmarks/ssr" + } + }, + "test:unit": { + "executor": "nx:run-commands", + "options": { + "command": "vitest run --config ./vitest.unit.config.ts", + "cwd": "benchmarks/ssr" + } + }, + "test:perf:react": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + "build:react" + ], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", + "cwd": "benchmarks/ssr" + } + }, + "test:perf:solid": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + "build:solid" + ], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", + "cwd": "benchmarks/ssr" + } + }, + "test:perf:vue": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + "build:vue" + ], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", + "cwd": "benchmarks/ssr" + } + }, + "test:types": { + "executor": "nx:run-commands", + "options": { + "command": "tsc -p ./tsconfig.json --noEmit", + "cwd": "benchmarks/ssr" + }, + "dependsOn": [ + { + "projects": [ + "@benchmarks/ssr-react", + "@benchmarks/ssr-assets-react", + "@benchmarks/ssr-before-load-react", + "@benchmarks/ssr-control-flow-react", + "@benchmarks/ssr-global-middleware-react", + "@benchmarks/ssr-head-react", + "@benchmarks/ssr-loaders-react", + "@benchmarks/ssr-rewrites-react", + "@benchmarks/ssr-serialization-react", + "@benchmarks/ssr-selective-ssr-react", + "@benchmarks/ssr-server-fn-transport-react", + "@benchmarks/ssr-server-fns-react", + "@benchmarks/ssr-server-routes-react", + "@benchmarks/ssr-server-routes-middleware-react", + "@benchmarks/ssr-streaming-react", + "@benchmarks/ssr-solid", + "@benchmarks/ssr-assets-solid", + "@benchmarks/ssr-before-load-solid", + "@benchmarks/ssr-control-flow-solid", + "@benchmarks/ssr-global-middleware-solid", + "@benchmarks/ssr-head-solid", + "@benchmarks/ssr-loaders-solid", + "@benchmarks/ssr-rewrites-solid", + "@benchmarks/ssr-serialization-solid", + "@benchmarks/ssr-selective-ssr-solid", + "@benchmarks/ssr-server-fn-transport-solid", + "@benchmarks/ssr-server-fns-solid", + "@benchmarks/ssr-server-routes-solid", + "@benchmarks/ssr-server-routes-middleware-solid", + "@benchmarks/ssr-streaming-solid", + "@benchmarks/ssr-vue", + "@benchmarks/ssr-assets-vue", + "@benchmarks/ssr-before-load-vue", + "@benchmarks/ssr-control-flow-vue", + "@benchmarks/ssr-global-middleware-vue", + "@benchmarks/ssr-head-vue", + "@benchmarks/ssr-loaders-vue", + "@benchmarks/ssr-rewrites-vue", + "@benchmarks/ssr-serialization-vue", + "@benchmarks/ssr-selective-ssr-vue", + "@benchmarks/ssr-server-fn-transport-vue", + "@benchmarks/ssr-server-fns-vue", + "@benchmarks/ssr-server-routes-vue", + "@benchmarks/ssr-server-routes-middleware-vue", + "@benchmarks/ssr-streaming-vue" + ], + "target": "test:types:ssr" + } + ], + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "{workspaceRoot}/benchmarks/cpu-simulation.ts", + "dependentTaskOutputs" + ] + } + } + } +} diff --git a/benchmarks/ssr/react/project.json b/benchmarks/ssr/react/project.json new file mode 100644 index 0000000000..d7f674cc83 --- /dev/null +++ b/benchmarks/ssr/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/react/speed.bench.ts b/benchmarks/ssr/react/speed.bench.ts new file mode 100644 index 0000000000..6825a7ddfb --- /dev/null +++ b/benchmarks/ssr/react/speed.bench.ts @@ -0,0 +1,22 @@ +import { test } from 'vitest' +import { runSsrRequestLoop } from '../bench-utils' +import type { StartRequestHandler } from '../bench-utils' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href +const benchmarkSeed = 0xdecafbad + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + 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, + }) +}) diff --git a/benchmarks/ssr/react/src/routeTree.gen.ts b/benchmarks/ssr/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..9f110bba31 --- /dev/null +++ b/benchmarks/ssr/react/src/routeTree.gen.ts @@ -0,0 +1,146 @@ +/* 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 ARouteImport } from './routes/$a' +import { Route as ABRouteImport } from './routes/$a.$b' +import { Route as ABCRouteImport } from './routes/$a.$b.$c' +import { Route as ABCDRouteImport } from './routes/$a.$b.$c.$d' + +const ARoute = ARouteImport.update({ + id: '/$a', + path: '/$a', + getParentRoute: () => rootRouteImport, +} as any) +const ABRoute = ABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => ARoute, +} as any) +const ABCRoute = ABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => ABRoute, +} as any) +const ABCDRoute = ABCDRouteImport.update({ + id: '/$d', + path: '/$d', + getParentRoute: () => ABCRoute, +} as any) + +export interface FileRoutesByFullPath { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRouteWithChildren + '/$a/$b/$c/$d': typeof ABCDRoute +} +export interface FileRoutesByTo { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRouteWithChildren + '/$a/$b/$c/$d': typeof ABCDRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRouteWithChildren + '/$a/$b/$c/$d': typeof ABCDRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' + fileRoutesByTo: FileRoutesByTo + to: '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' + id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/$a': { + id: '/$a' + path: '/$a' + fullPath: '/$a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + '/$a/$b': { + id: '/$a/$b' + path: '/$b' + fullPath: '/$a/$b' + preLoaderRoute: typeof ABRouteImport + parentRoute: typeof ARoute + } + '/$a/$b/$c': { + id: '/$a/$b/$c' + path: '/$c' + fullPath: '/$a/$b/$c' + preLoaderRoute: typeof ABCRouteImport + parentRoute: typeof ABRoute + } + '/$a/$b/$c/$d': { + id: '/$a/$b/$c/$d' + path: '/$d' + fullPath: '/$a/$b/$c/$d' + preLoaderRoute: typeof ABCDRouteImport + parentRoute: typeof ABCRoute + } + } +} + +interface ABCRouteChildren { + ABCDRoute: typeof ABCDRoute +} + +const ABCRouteChildren: ABCRouteChildren = { + ABCDRoute: ABCDRoute, +} + +const ABCRouteWithChildren = ABCRoute._addFileChildren(ABCRouteChildren) + +interface ABRouteChildren { + ABCRoute: typeof ABCRouteWithChildren +} + +const ABRouteChildren: ABRouteChildren = { + ABCRoute: ABCRouteWithChildren, +} + +const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) + +interface ARouteChildren { + ABRoute: typeof ABRouteWithChildren +} + +const ARouteChildren: ARouteChildren = { + ABRoute: ABRouteWithChildren, +} + +const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARouteWithChildren, +} +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/benchmarks/ssr/react/src/router.tsx b/benchmarks/ssr/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/react/src/routes/$a.$b.$c.$d.tsx b/benchmarks/ssr/react/src/routes/$a.$b.$c.$d.tsx new file mode 100644 index 0000000000..056f1c308e --- /dev/null +++ b/benchmarks/ssr/react/src/routes/$a.$b.$c.$d.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/react-router' +import { RouteWorkload } from '../workload' + +export const Route = createFileRoute('/$a/$b/$c/$d')({ + component: LevelDComponent, +}) + +function LevelDComponent() { + return +} diff --git a/benchmarks/ssr/react/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/react/src/routes/$a.$b.$c.tsx new file mode 100644 index 0000000000..b73ede60f4 --- /dev/null +++ b/benchmarks/ssr/react/src/routes/$a.$b.$c.tsx @@ -0,0 +1,15 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { RouteWorkload } from '../workload' + +export const Route = createFileRoute('/$a/$b/$c')({ + component: LevelCComponent, +}) + +function LevelCComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/ssr/react/src/routes/$a.$b.tsx b/benchmarks/ssr/react/src/routes/$a.$b.tsx new file mode 100644 index 0000000000..649b0f0a46 --- /dev/null +++ b/benchmarks/ssr/react/src/routes/$a.$b.tsx @@ -0,0 +1,15 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { RouteWorkload } from '../workload' + +export const Route = createFileRoute('/$a/$b')({ + component: LevelBComponent, +}) + +function LevelBComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/ssr/react/src/routes/$a.tsx b/benchmarks/ssr/react/src/routes/$a.tsx new file mode 100644 index 0000000000..cc2fa1483b --- /dev/null +++ b/benchmarks/ssr/react/src/routes/$a.tsx @@ -0,0 +1,15 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { RouteWorkload } from '../workload' + +export const Route = createFileRoute('/$a')({ + component: LevelAComponent, +}) + +function LevelAComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/ssr/react/src/routes/__root.tsx b/benchmarks/ssr/react/src/routes/__root.tsx new file mode 100644 index 0000000000..1973ca20bb --- /dev/null +++ b/benchmarks/ssr/react/src/routes/__root.tsx @@ -0,0 +1,25 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/react/src/workload.tsx b/benchmarks/ssr/react/src/workload.tsx new file mode 100644 index 0000000000..2cc5c9f1ae --- /dev/null +++ b/benchmarks/ssr/react/src/workload.tsx @@ -0,0 +1,81 @@ +import { Link, useParams, useSearch } from '@tanstack/react-router' + +const probes = Array.from({ length: 10 }, (_, index) => index) + +function runSelectorWork(input: string, salt: number) { + let value = salt + + for (let index = 0; index < input.length; index++) { + value = (value * 33 + input.charCodeAt(index) + index) >>> 0 + } + + for (let index = 0; index < 16; index++) { + value = (value ^ (value << 13)) >>> 0 + value = (value ^ (value >> 17)) >>> 0 + value = (value ^ (value << 5)) >>> 0 + } + + return value +} + +function ParamsProbe({ salt }: { salt: number }) { + const params = useParams({ + strict: false, + select: (nextParams) => + runSelectorWork( + `${nextParams.a ?? ''}/${nextParams.b ?? ''}/${nextParams.c ?? ''}/${nextParams.d ?? ''}`, + salt, + ), + }) + + void params + + return null +} + +function SearchProbe({ salt }: { salt: number }) { + const search = useSearch({ + strict: false, + select: (nextSearch) => runSelectorWork(String(nextSearch.q ?? ''), salt), + }) + + void search + + return null +} + +function LinkProbe({ salt }: { salt: number }) { + const value = String((salt % 97) + 1) + + return ( + + Link + + ) +} + +export function RouteWorkload() { + return ( + <> + {probes.map((probe) => ( + + ))} + {probes.map((probe) => ( + + ))} + {probes.map((probe) => ( + + ))} + + ) +} diff --git a/benchmarks/ssr/react/tsconfig.json b/benchmarks/ssr/react/tsconfig.json new file mode 100644 index 0000000000..4de88f2eb4 --- /dev/null +++ b/benchmarks/ssr/react/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/react/vite.config.ts b/benchmarks/ssr/react/vite.config.ts new file mode 100644 index 0000000000..e607db366b --- /dev/null +++ b/benchmarks/ssr/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/assets/react/project.json b/benchmarks/ssr/scenarios/assets/react/project.json new file mode 100644 index 0000000000..a2d5a6c8ba --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-assets-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/assets/react/speed.assets-linked-css-control.bench.ts b/benchmarks/ssr/scenarios/assets/react/speed.assets-linked-css-control.bench.ts new file mode 100644 index 0000000000..0496613afb --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/speed.assets-linked-css-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertAssetsScenario, + assetsBenchOptions, + runAssetsLinkedControlLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertAssetsScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr assets linked-css control (react)', async () => + runAssetsLinkedControlLoop(handler), + ).run(assetsBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/assets/react/speed.bench.ts b/benchmarks/ssr/scenarios/assets/react/speed.bench.ts new file mode 100644 index 0000000000..7dc57d89f1 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertAssetsScenario, + assetsBenchOptions, + runAssetsInlineLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertAssetsScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr assets inline-css cdn (react)', async () => + runAssetsInlineLoop(handler), + ).run(assetsBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/assets/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/assets/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..201df5fd3b --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/src/routeTree.gen.ts @@ -0,0 +1,94 @@ +/* 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 AXRouteImport } from './routes/a.$x' +import { Route as AXYRouteImport } from './routes/a.$x.$y' + +const AXRoute = AXRouteImport.update({ + id: '/a/$x', + path: '/a/$x', + getParentRoute: () => rootRouteImport, +} as any) +const AXYRoute = AXYRouteImport.update({ + id: '/$y', + path: '/$y', + getParentRoute: () => AXRoute, +} as any) + +export interface FileRoutesByFullPath { + '/a/$x': typeof AXRouteWithChildren + '/a/$x/$y': typeof AXYRoute +} +export interface FileRoutesByTo { + '/a/$x': typeof AXRouteWithChildren + '/a/$x/$y': typeof AXYRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/a/$x': typeof AXRouteWithChildren + '/a/$x/$y': typeof AXYRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/a/$x' | '/a/$x/$y' + fileRoutesByTo: FileRoutesByTo + to: '/a/$x' | '/a/$x/$y' + id: '__root__' | '/a/$x' | '/a/$x/$y' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + AXRoute: typeof AXRouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/a/$x': { + id: '/a/$x' + path: '/a/$x' + fullPath: '/a/$x' + preLoaderRoute: typeof AXRouteImport + parentRoute: typeof rootRouteImport + } + '/a/$x/$y': { + id: '/a/$x/$y' + path: '/$y' + fullPath: '/a/$x/$y' + preLoaderRoute: typeof AXYRouteImport + parentRoute: typeof AXRoute + } + } +} + +interface AXRouteChildren { + AXYRoute: typeof AXYRoute +} + +const AXRouteChildren: AXRouteChildren = { + AXYRoute: AXYRoute, +} + +const AXRouteWithChildren = AXRoute._addFileChildren(AXRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + AXRoute: AXRouteWithChildren, +} +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/benchmarks/ssr/scenarios/assets/react/src/router.tsx b/benchmarks/ssr/scenarios/assets/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/assets/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/assets/react/src/routes/__root.tsx new file mode 100644 index 0000000000..8c46c7060a --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/src/routes/__root.tsx @@ -0,0 +1,31 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { name: 'application-name', content: 'SSR assets benchmark' }, + ], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.$y.tsx b/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.$y.tsx new file mode 100644 index 0000000000..be709e53e6 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.$y.tsx @@ -0,0 +1,26 @@ +import { createFileRoute } from '@tanstack/react-router' +import '../styles/assets-leaf.css' + +export const Route = createFileRoute('/a/$x/$y')({ + head: ({ params }) => ({ + meta: [{ title: `SSR Assets ${params.x} ${params.y}` }], + links: Array.from({ length: 3 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/asset-preload/${params.y}-${index}.png`, + })), + }), + component: LeafComponent, +}) + +function LeafComponent() { + const { x, y } = Route.useParams() + + return ( +
+

+ assets-leaf-{x}-{y} +

+
+ ) +} diff --git a/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.tsx b/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.tsx new file mode 100644 index 0000000000..ecc7de680a --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/src/routes/a.$x.tsx @@ -0,0 +1,25 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import '../styles/assets-a.css' + +export const Route = createFileRoute('/a/$x')({ + head: ({ params }) => ({ + meta: [{ title: `SSR Assets ${params.x}` }], + links: Array.from({ length: 2 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/asset-preload/${params.x}-${index}.png`, + })), + }), + component: LevelAComponent, +}) + +function LevelAComponent() { + const { x } = Route.useParams() + + return ( +
+

assets-level-a-{x}

+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/assets/react/src/server.ts b/benchmarks/ssr/scenarios/assets/react/src/server.ts new file mode 100644 index 0000000000..64fb21708c --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/src/server.ts @@ -0,0 +1,45 @@ +import { + createStartHandler, + defaultStreamHandler, +} from '@tanstack/react-start/server' +import { createServerEntry } from '@tanstack/react-start/server-entry' +import type { + TransformAssets, + TransformAssetsFn, +} from '@tanstack/react-start/server' + +type CreateTransformContext = + | { warmup: true } + | { request: Request; warmup: false } + +const cdnOrigin = 'https://cdn.example.com' + +const createCdnTransform = (prefix: string): TransformAssetsFn => { + return ({ url }) => `${prefix}${url}` +} + +const transformAssets: TransformAssets = { + createTransform: (ctx: CreateTransformContext) => { + const prefix = ctx.warmup + ? cdnOrigin + : (ctx.request.headers.get('x-assets-cdn') ?? cdnOrigin) + + return createCdnTransform(prefix) + }, + cache: false, +} + +const handler = createStartHandler({ + handler: defaultStreamHandler, + inlineCss: true, + transformAssets, +}) + +export default createServerEntry({ + fetch(request) { + return handler(request, { + inlineCss: request.headers.get('x-inline-css') !== 'false', + responseLinkHeader: true, + }) + }, +}) diff --git a/benchmarks/ssr/scenarios/assets/react/src/styles/assets-a.css b/benchmarks/ssr/scenarios/assets/react/src/styles/assets-a.css new file mode 100644 index 0000000000..d3511ddd85 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/src/styles/assets-a.css @@ -0,0 +1,8 @@ +.assets-level-a { + color: #1f2937; + background-image: url('/asset-bg-a.svg'); +} + +.assets-level-a::before { + content: 'assets-level-a-css'; +} diff --git a/benchmarks/ssr/scenarios/assets/react/src/styles/assets-leaf.css b/benchmarks/ssr/scenarios/assets/react/src/styles/assets-leaf.css new file mode 100644 index 0000000000..55e051b9a5 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/src/styles/assets-leaf.css @@ -0,0 +1,8 @@ +.assets-leaf { + border-color: #2563eb; + background-image: url('/asset-bg-leaf.svg'); +} + +.assets-leaf::before { + content: 'assets-leaf-css'; +} diff --git a/benchmarks/ssr/scenarios/assets/react/tsconfig.json b/benchmarks/ssr/scenarios/assets/react/tsconfig.json new file mode 100644 index 0000000000..cf14e1d440 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/assets/react/vite.config.ts b/benchmarks/ssr/scenarios/assets/react/vite.config.ts new file mode 100644 index 0000000000..5990bba6d3 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + server: { + build: { + inlineCss: { enabled: true, transformAssets: true }, + }, + }, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr assets (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/assets/shared.ts b/benchmarks/ssr/scenarios/assets/shared.ts new file mode 100644 index 0000000000..ec811794e3 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/shared.ts @@ -0,0 +1,88 @@ +import { expect } from 'vitest' +import { randomSegment, runRequestLoop } from '../../bench-utils' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +const benchmarkSeed = 0xdecafbad +const origin = 'http://localhost' +const cdnOrigin = 'https://cdn.example.com' +const inlineCssLoopTotalRequests = 32 +const linkedCssLoopTotalRequests = 32 + +const inlineRequestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +const linkedRequestInit = { + method: 'GET', + headers: { + accept: 'text/html', + 'x-inline-css': 'false', + }, +} satisfies RequestInit + +export const assetsBenchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} + +function buildAssetsRequest(random: () => number, requestInit: RequestInit) { + return new Request( + `${origin}/a/${randomSegment(random)}/${randomSegment(random)}`, + requestInit, + ) +} + +export function runAssetsInlineLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: inlineCssLoopTotalRequests, + buildRequest: (random) => buildAssetsRequest(random, inlineRequestInit), + }) +} + +export function runAssetsLinkedControlLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: linkedCssLoopTotalRequests, + buildRequest: (random) => buildAssetsRequest(random, linkedRequestInit), + }) +} + +export async function assertAssetsScenario(handler: StartRequestHandler) { + const inlineResponse = await handler.fetch( + new Request(`${origin}/a/sanity-x/sanity-y`, inlineRequestInit), + ) + const inlineBody = await inlineResponse.text() + const inlineLinkHeader = inlineResponse.headers.get('link') ?? '' + + expect(inlineResponse.status).toBe(200) + expect(inlineBody).toContain('SSR Assets sanity-x sanity-y') + expect(inlineBody).toContain(' { + await bench('ssr assets linked-css control (solid)', async () => + runAssetsLinkedControlLoop(handler), + ).run(assetsBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts b/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts new file mode 100644 index 0000000000..47f483df11 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertAssetsScenario, + assetsBenchOptions, + runAssetsInlineLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertAssetsScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr assets inline-css cdn (solid)', async () => + runAssetsInlineLoop(handler), + ).run(assetsBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/assets/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/assets/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..f6f7ffe57e --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/solid/src/routeTree.gen.ts @@ -0,0 +1,94 @@ +/* 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 AXRouteImport } from './routes/a.$x' +import { Route as AXYRouteImport } from './routes/a.$x.$y' + +const AXRoute = AXRouteImport.update({ + id: '/a/$x', + path: '/a/$x', + getParentRoute: () => rootRouteImport, +} as any) +const AXYRoute = AXYRouteImport.update({ + id: '/$y', + path: '/$y', + getParentRoute: () => AXRoute, +} as any) + +export interface FileRoutesByFullPath { + '/a/$x': typeof AXRouteWithChildren + '/a/$x/$y': typeof AXYRoute +} +export interface FileRoutesByTo { + '/a/$x': typeof AXRouteWithChildren + '/a/$x/$y': typeof AXYRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/a/$x': typeof AXRouteWithChildren + '/a/$x/$y': typeof AXYRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/a/$x' | '/a/$x/$y' + fileRoutesByTo: FileRoutesByTo + to: '/a/$x' | '/a/$x/$y' + id: '__root__' | '/a/$x' | '/a/$x/$y' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + AXRoute: typeof AXRouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/a/$x': { + id: '/a/$x' + path: '/a/$x' + fullPath: '/a/$x' + preLoaderRoute: typeof AXRouteImport + parentRoute: typeof rootRouteImport + } + '/a/$x/$y': { + id: '/a/$x/$y' + path: '/$y' + fullPath: '/a/$x/$y' + preLoaderRoute: typeof AXYRouteImport + parentRoute: typeof AXRoute + } + } +} + +interface AXRouteChildren { + AXYRoute: typeof AXYRoute +} + +const AXRouteChildren: AXRouteChildren = { + AXYRoute: AXYRoute, +} + +const AXRouteWithChildren = AXRoute._addFileChildren(AXRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + AXRoute: AXRouteWithChildren, +} +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/benchmarks/ssr/scenarios/assets/solid/src/router.tsx b/benchmarks/ssr/scenarios/assets/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/assets/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/assets/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..ca760406ce --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/solid/src/routes/__root.tsx @@ -0,0 +1,31 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { name: 'application-name', content: 'SSR assets benchmark' }, + ], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.$y.tsx b/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.$y.tsx new file mode 100644 index 0000000000..2a3d35cb68 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.$y.tsx @@ -0,0 +1,26 @@ +import { createFileRoute } from '@tanstack/solid-router' +import '../styles/assets-leaf.css' + +export const Route = createFileRoute('/a/$x/$y')({ + head: ({ params }) => ({ + meta: [{ title: `SSR Assets ${params.x} ${params.y}` }], + links: Array.from({ length: 3 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/asset-preload/${params.y}-${index}.png`, + })), + }), + component: LeafComponent, +}) + +function LeafComponent() { + const params = Route.useParams() + + return ( +
+

+ assets-leaf-{params().x}-{params().y} +

+
+ ) +} diff --git a/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.tsx b/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.tsx new file mode 100644 index 0000000000..2209addcbe --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/solid/src/routes/a.$x.tsx @@ -0,0 +1,25 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import '../styles/assets-a.css' + +export const Route = createFileRoute('/a/$x')({ + head: ({ params }) => ({ + meta: [{ title: `SSR Assets ${params.x}` }], + links: Array.from({ length: 2 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/asset-preload/${params.x}-${index}.png`, + })), + }), + component: LevelAComponent, +}) + +function LevelAComponent() { + const params = Route.useParams() + + return ( +
+

assets-level-a-{params().x}

+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/assets/solid/src/server.ts b/benchmarks/ssr/scenarios/assets/solid/src/server.ts new file mode 100644 index 0000000000..541e776a79 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/solid/src/server.ts @@ -0,0 +1,45 @@ +import { + createStartHandler, + defaultStreamHandler, +} from '@tanstack/solid-start/server' +import { createServerEntry } from '@tanstack/solid-start/server-entry' +import type { + TransformAssets, + TransformAssetsFn, +} from '@tanstack/solid-start/server' + +type CreateTransformContext = + | { warmup: true } + | { request: Request; warmup: false } + +const cdnOrigin = 'https://cdn.example.com' + +const createCdnTransform = (prefix: string): TransformAssetsFn => { + return ({ url }) => `${prefix}${url}` +} + +const transformAssets: TransformAssets = { + createTransform: (ctx: CreateTransformContext) => { + const prefix = ctx.warmup + ? cdnOrigin + : (ctx.request.headers.get('x-assets-cdn') ?? cdnOrigin) + + return createCdnTransform(prefix) + }, + cache: false, +} + +const handler = createStartHandler({ + handler: defaultStreamHandler, + inlineCss: true, + transformAssets, +}) + +export default createServerEntry({ + fetch(request) { + return handler(request, { + inlineCss: request.headers.get('x-inline-css') !== 'false', + responseLinkHeader: true, + }) + }, +}) diff --git a/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-a.css b/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-a.css new file mode 100644 index 0000000000..d3511ddd85 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-a.css @@ -0,0 +1,8 @@ +.assets-level-a { + color: #1f2937; + background-image: url('/asset-bg-a.svg'); +} + +.assets-level-a::before { + content: 'assets-level-a-css'; +} diff --git a/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-leaf.css b/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-leaf.css new file mode 100644 index 0000000000..55e051b9a5 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/solid/src/styles/assets-leaf.css @@ -0,0 +1,8 @@ +.assets-leaf { + border-color: #2563eb; + background-image: url('/asset-bg-leaf.svg'); +} + +.assets-leaf::before { + content: 'assets-leaf-css'; +} diff --git a/benchmarks/ssr/scenarios/assets/solid/tsconfig.json b/benchmarks/ssr/scenarios/assets/solid/tsconfig.json new file mode 100644 index 0000000000..42c3a2160f --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/solid/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/assets/solid/vite.config.ts b/benchmarks/ssr/scenarios/assets/solid/vite.config.ts new file mode 100644 index 0000000000..3ee54e5ae2 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/solid/vite.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + server: { + build: { + inlineCss: { enabled: true, transformAssets: true }, + }, + }, + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr assets (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/assets/vue/project.json b/benchmarks/ssr/scenarios/assets/vue/project.json new file mode 100644 index 0000000000..9667ff902c --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-assets-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/assets/vue/speed.assets-linked-css-control.bench.ts b/benchmarks/ssr/scenarios/assets/vue/speed.assets-linked-css-control.bench.ts new file mode 100644 index 0000000000..e56d41df6b --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/speed.assets-linked-css-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertAssetsScenario, + assetsBenchOptions, + runAssetsLinkedControlLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertAssetsScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr assets linked-css control (vue)', async () => + runAssetsLinkedControlLoop(handler), + ).run(assetsBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts b/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts new file mode 100644 index 0000000000..3f77a0dcc1 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertAssetsScenario, + assetsBenchOptions, + runAssetsInlineLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertAssetsScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr assets inline-css cdn (vue)', async () => + runAssetsInlineLoop(handler), + ).run(assetsBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/assets/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/assets/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..2a6eb91f50 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/src/routeTree.gen.ts @@ -0,0 +1,94 @@ +/* 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 AXRouteImport } from './routes/a.$x' +import { Route as AXYRouteImport } from './routes/a.$x.$y' + +const AXRoute = AXRouteImport.update({ + id: '/a/$x', + path: '/a/$x', + getParentRoute: () => rootRouteImport, +} as any) +const AXYRoute = AXYRouteImport.update({ + id: '/$y', + path: '/$y', + getParentRoute: () => AXRoute, +} as any) + +export interface FileRoutesByFullPath { + '/a/$x': typeof AXRouteWithChildren + '/a/$x/$y': typeof AXYRoute +} +export interface FileRoutesByTo { + '/a/$x': typeof AXRouteWithChildren + '/a/$x/$y': typeof AXYRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/a/$x': typeof AXRouteWithChildren + '/a/$x/$y': typeof AXYRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/a/$x' | '/a/$x/$y' + fileRoutesByTo: FileRoutesByTo + to: '/a/$x' | '/a/$x/$y' + id: '__root__' | '/a/$x' | '/a/$x/$y' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + AXRoute: typeof AXRouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/a/$x': { + id: '/a/$x' + path: '/a/$x' + fullPath: '/a/$x' + preLoaderRoute: typeof AXRouteImport + parentRoute: typeof rootRouteImport + } + '/a/$x/$y': { + id: '/a/$x/$y' + path: '/$y' + fullPath: '/a/$x/$y' + preLoaderRoute: typeof AXYRouteImport + parentRoute: typeof AXRoute + } + } +} + +interface AXRouteChildren { + AXYRoute: typeof AXYRoute +} + +const AXRouteChildren: AXRouteChildren = { + AXYRoute: AXYRoute, +} + +const AXRouteWithChildren = AXRoute._addFileChildren(AXRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + AXRoute: AXRouteWithChildren, +} +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/benchmarks/ssr/scenarios/assets/vue/src/router.tsx b/benchmarks/ssr/scenarios/assets/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/assets/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/assets/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..760545d248 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/src/routes/__root.tsx @@ -0,0 +1,33 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { name: 'application-name', content: 'SSR assets benchmark' }, + ], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.$y.tsx b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.$y.tsx new file mode 100644 index 0000000000..a29fe59f22 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.$y.tsx @@ -0,0 +1,29 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import '../styles/assets-leaf.css' + +const LeafComponent = defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
+

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

+
+ ) + }, +}) + +export const Route = createFileRoute('/a/$x/$y')({ + head: ({ params }) => ({ + meta: [{ title: `SSR Assets ${params.x} ${params.y}` }], + links: Array.from({ length: 3 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/asset-preload/${params.y}-${index}.png`, + })), + }), + component: LeafComponent, +}) diff --git a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx new file mode 100644 index 0000000000..e1fe0418e4 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx @@ -0,0 +1,28 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import '../styles/assets-a.css' + +const LevelAComponent = defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
+

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

+ +
+ ) + }, +}) + +export const Route = createFileRoute('/a/$x')({ + head: ({ params }) => ({ + meta: [{ title: `SSR Assets ${params.x}` }], + links: Array.from({ length: 2 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/asset-preload/${params.x}-${index}.png`, + })), + }), + component: LevelAComponent, +}) diff --git a/benchmarks/ssr/scenarios/assets/vue/src/server.ts b/benchmarks/ssr/scenarios/assets/vue/src/server.ts new file mode 100644 index 0000000000..fd1e83d6b8 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/src/server.ts @@ -0,0 +1,45 @@ +import { + createStartHandler, + defaultStreamHandler, +} from '@tanstack/vue-start/server' +import { createServerEntry } from '@tanstack/vue-start/server-entry' +import type { + TransformAssets, + TransformAssetsFn, +} from '@tanstack/vue-start/server' + +type CreateTransformContext = + | { warmup: true } + | { request: Request; warmup: false } + +const cdnOrigin = 'https://cdn.example.com' + +const createCdnTransform = (prefix: string): TransformAssetsFn => { + return ({ url }) => `${prefix}${url}` +} + +const transformAssets: TransformAssets = { + createTransform: (ctx: CreateTransformContext) => { + const prefix = ctx.warmup + ? cdnOrigin + : (ctx.request.headers.get('x-assets-cdn') ?? cdnOrigin) + + return createCdnTransform(prefix) + }, + cache: false, +} + +const handler = createStartHandler({ + handler: defaultStreamHandler, + inlineCss: true, + transformAssets, +}) + +export default createServerEntry({ + fetch(request) { + return handler(request, { + inlineCss: request.headers.get('x-inline-css') !== 'false', + responseLinkHeader: true, + }) + }, +}) diff --git a/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-a.css b/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-a.css new file mode 100644 index 0000000000..d3511ddd85 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-a.css @@ -0,0 +1,8 @@ +.assets-level-a { + color: #1f2937; + background-image: url('/asset-bg-a.svg'); +} + +.assets-level-a::before { + content: 'assets-level-a-css'; +} diff --git a/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-leaf.css b/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-leaf.css new file mode 100644 index 0000000000..55e051b9a5 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/src/styles/assets-leaf.css @@ -0,0 +1,8 @@ +.assets-leaf { + border-color: #2563eb; + background-image: url('/asset-bg-leaf.svg'); +} + +.assets-leaf::before { + content: 'assets-leaf-css'; +} diff --git a/benchmarks/ssr/scenarios/assets/vue/tsconfig.json b/benchmarks/ssr/scenarios/assets/vue/tsconfig.json new file mode 100644 index 0000000000..08c94853f4 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/assets/vue/vite.config.ts b/benchmarks/ssr/scenarios/assets/vue/vite.config.ts new file mode 100644 index 0000000000..e664b9b02b --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + server: { + build: { + inlineCss: { enabled: true, transformAssets: true }, + }, + }, + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr assets (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/before-load/react/project.json b/benchmarks/ssr/scenarios/before-load/react/project.json new file mode 100644 index 0000000000..df2004f1f5 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-before-load-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts new file mode 100644 index 0000000000..8a4355a168 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertBeforeLoadScenario, + beforeLoadBenchOptions, + runBeforeLoadLoop, + type StartRequestHandler, +} from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertBeforeLoadScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr before-load chain (react)', async () => + runBeforeLoadLoop(handler), + ).run(beforeLoadBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/before-load/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/before-load/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..068b5a5433 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/react/src/routeTree.gen.ts @@ -0,0 +1,120 @@ +/* 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 ARouteImport } from './routes/$a' +import { Route as ABRouteImport } from './routes/$a.$b' +import { Route as ABCRouteImport } from './routes/$a.$b.$c' + +const ARoute = ARouteImport.update({ + id: '/$a', + path: '/$a', + getParentRoute: () => rootRouteImport, +} as any) +const ABRoute = ABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => ARoute, +} as any) +const ABCRoute = ABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => ABRoute, +} as any) + +export interface FileRoutesByFullPath { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRoutesByTo { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' + fileRoutesByTo: FileRoutesByTo + to: '/$a' | '/$a/$b' | '/$a/$b/$c' + id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/$a': { + id: '/$a' + path: '/$a' + fullPath: '/$a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + '/$a/$b': { + id: '/$a/$b' + path: '/$b' + fullPath: '/$a/$b' + preLoaderRoute: typeof ABRouteImport + parentRoute: typeof ARoute + } + '/$a/$b/$c': { + id: '/$a/$b/$c' + path: '/$c' + fullPath: '/$a/$b/$c' + preLoaderRoute: typeof ABCRouteImport + parentRoute: typeof ABRoute + } + } +} + +interface ABRouteChildren { + ABCRoute: typeof ABCRoute +} + +const ABRouteChildren: ABRouteChildren = { + ABCRoute: ABCRoute, +} + +const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) + +interface ARouteChildren { + ABRoute: typeof ABRouteWithChildren +} + +const ARouteChildren: ARouteChildren = { + ABRoute: ABRouteWithChildren, +} + +const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARouteWithChildren, +} +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/benchmarks/ssr/scenarios/before-load/react/src/router.tsx b/benchmarks/ssr/scenarios/before-load/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.$c.tsx new file mode 100644 index 0000000000..71719a4f88 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.$c.tsx @@ -0,0 +1,23 @@ +import { createFileRoute } from '@tanstack/react-router' +import { makeBeforeLoadMarker, type BeforeLoadContext } from '../../../shared' + +export const Route = createFileRoute('/$a/$b/$c')({ + beforeLoad: ({ params, context }) => { + const parent = context as BeforeLoadContext + + return { + chainToken: `${parent.chainToken}.${params.c}`, + ctxC: params.c, + } + }, + loader: ({ context }) => ({ + marker: makeBeforeLoadMarker(context as BeforeLoadContext), + }), + component: LevelCComponent, +}) + +function LevelCComponent() { + const data = Route.useLoaderData() + + return
{data.marker}
+} diff --git a/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.tsx new file mode 100644 index 0000000000..1a148e05fa --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.$b.tsx @@ -0,0 +1,18 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import type { BeforeLoadContext } from '../../../shared' + +export const Route = createFileRoute('/$a/$b')({ + beforeLoad: ({ params, context }) => { + const parent = context as BeforeLoadContext + + return { + chainToken: `${parent.chainToken}.${params.b}`, + ctxB: params.b, + } + }, + component: LevelBComponent, +}) + +function LevelBComponent() { + return +} diff --git a/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.tsx b/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.tsx new file mode 100644 index 0000000000..b5dcca33c3 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/react/src/routes/$a.tsx @@ -0,0 +1,13 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/$a')({ + beforeLoad: ({ params }) => ({ + chainToken: params.a, + ctxA: params.a, + }), + component: LevelAComponent, +}) + +function LevelAComponent() { + return +} diff --git a/benchmarks/ssr/scenarios/before-load/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/before-load/react/src/routes/__root.tsx new file mode 100644 index 0000000000..ff1da4c304 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/react/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/before-load/react/tsconfig.json b/benchmarks/ssr/scenarios/before-load/react/tsconfig.json new file mode 100644 index 0000000000..232763bbe1 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/react/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared.ts", + "../shared-bench.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/before-load/react/vite.config.ts b/benchmarks/ssr/scenarios/before-load/react/vite.config.ts new file mode 100644 index 0000000000..3fd72c5f1d --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr before-load (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/before-load/shared-bench.ts b/benchmarks/ssr/scenarios/before-load/shared-bench.ts new file mode 100644 index 0000000000..cf3a02f114 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/shared-bench.ts @@ -0,0 +1,64 @@ +import { makeBeforeLoadMarker } from './shared' +import { randomSegment, runRequestLoop } from '../../bench-utils' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +const benchmarkSeed = 0xdecafbad +const beforeLoadLoopTotalRequests = 32 + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +function buildBeforeLoadRequest(random: () => number, index: number) { + const suffix = index.toString(36) + const a = `${randomSegment(random)}-${suffix}` + const b = `${randomSegment(random)}-${suffix}` + const c = `${randomSegment(random)}-${suffix}` + + return new Request(`http://localhost/${a}/${b}/${c}`, requestInit) +} + +export async function assertBeforeLoadScenario(handler: StartRequestHandler) { + const response = await handler.fetch( + new Request('http://localhost/a-sanity/b-sanity/c-sanity', requestInit), + ) + const body = await response.text() + const expectedMarker = makeBeforeLoadMarker({ + ctxA: 'a-sanity', + ctxB: 'b-sanity', + ctxC: 'c-sanity', + chainToken: 'a-sanity.b-sanity.c-sanity', + }) + + if (response.status !== 200) { + throw new Error( + `Expected beforeLoad setup status 200, received ${response.status}`, + ) + } + + if (!body.includes(expectedMarker)) { + throw new Error( + `Expected beforeLoad setup response to include ${expectedMarker}`, + ) + } +} + +export const beforeLoadBenchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} + +export function runBeforeLoadLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: beforeLoadLoopTotalRequests, + buildRequest: buildBeforeLoadRequest, + }) +} diff --git a/benchmarks/ssr/scenarios/before-load/shared.ts b/benchmarks/ssr/scenarios/before-load/shared.ts new file mode 100644 index 0000000000..3c895aca03 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/shared.ts @@ -0,0 +1,10 @@ +export interface BeforeLoadContext { + chainToken?: string + ctxA?: string + ctxB?: string + ctxC?: string +} + +export function makeBeforeLoadMarker(context: BeforeLoadContext) { + return `ctx:${context.ctxA}:${context.ctxB}:${context.ctxC}:${context.chainToken}` +} diff --git a/benchmarks/ssr/scenarios/before-load/solid/project.json b/benchmarks/ssr/scenarios/before-load/solid/project.json new file mode 100644 index 0000000000..804cd9c1b0 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/solid/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-before-load-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts new file mode 100644 index 0000000000..27e0d3a64c --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertBeforeLoadScenario, + beforeLoadBenchOptions, + runBeforeLoadLoop, + type StartRequestHandler, +} from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertBeforeLoadScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr before-load chain (solid)', async () => + runBeforeLoadLoop(handler), + ).run(beforeLoadBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/before-load/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/before-load/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..7b299cfcd1 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/solid/src/routeTree.gen.ts @@ -0,0 +1,120 @@ +/* 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 ARouteImport } from './routes/$a' +import { Route as ABRouteImport } from './routes/$a.$b' +import { Route as ABCRouteImport } from './routes/$a.$b.$c' + +const ARoute = ARouteImport.update({ + id: '/$a', + path: '/$a', + getParentRoute: () => rootRouteImport, +} as any) +const ABRoute = ABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => ARoute, +} as any) +const ABCRoute = ABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => ABRoute, +} as any) + +export interface FileRoutesByFullPath { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRoutesByTo { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' + fileRoutesByTo: FileRoutesByTo + to: '/$a' | '/$a/$b' | '/$a/$b/$c' + id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/$a': { + id: '/$a' + path: '/$a' + fullPath: '/$a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + '/$a/$b': { + id: '/$a/$b' + path: '/$b' + fullPath: '/$a/$b' + preLoaderRoute: typeof ABRouteImport + parentRoute: typeof ARoute + } + '/$a/$b/$c': { + id: '/$a/$b/$c' + path: '/$c' + fullPath: '/$a/$b/$c' + preLoaderRoute: typeof ABCRouteImport + parentRoute: typeof ABRoute + } + } +} + +interface ABRouteChildren { + ABCRoute: typeof ABCRoute +} + +const ABRouteChildren: ABRouteChildren = { + ABCRoute: ABCRoute, +} + +const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) + +interface ARouteChildren { + ABRoute: typeof ABRouteWithChildren +} + +const ARouteChildren: ARouteChildren = { + ABRoute: ABRouteWithChildren, +} + +const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARouteWithChildren, +} +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/benchmarks/ssr/scenarios/before-load/solid/src/router.tsx b/benchmarks/ssr/scenarios/before-load/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.$c.tsx new file mode 100644 index 0000000000..7966bcc4c2 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.$c.tsx @@ -0,0 +1,23 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { makeBeforeLoadMarker, type BeforeLoadContext } from '../../../shared' + +export const Route = createFileRoute('/$a/$b/$c')({ + beforeLoad: ({ params, context }) => { + const parent = context as BeforeLoadContext + + return { + chainToken: `${parent.chainToken}.${params.c}`, + ctxC: params.c, + } + }, + loader: ({ context }) => ({ + marker: makeBeforeLoadMarker(context as BeforeLoadContext), + }), + component: LevelCComponent, +}) + +function LevelCComponent() { + const data = Route.useLoaderData() + + return
{data().marker}
+} diff --git a/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.tsx new file mode 100644 index 0000000000..90656dc7a1 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.$b.tsx @@ -0,0 +1,18 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import type { BeforeLoadContext } from '../../../shared' + +export const Route = createFileRoute('/$a/$b')({ + beforeLoad: ({ params, context }) => { + const parent = context as BeforeLoadContext + + return { + chainToken: `${parent.chainToken}.${params.b}`, + ctxB: params.b, + } + }, + component: LevelBComponent, +}) + +function LevelBComponent() { + return +} diff --git a/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.tsx b/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.tsx new file mode 100644 index 0000000000..6336f56640 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/solid/src/routes/$a.tsx @@ -0,0 +1,13 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/$a')({ + beforeLoad: ({ params }) => ({ + chainToken: params.a, + ctxA: params.a, + }), + component: LevelAComponent, +}) + +function LevelAComponent() { + return +} diff --git a/benchmarks/ssr/scenarios/before-load/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/before-load/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..e59de72236 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/solid/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/before-load/solid/tsconfig.json b/benchmarks/ssr/scenarios/before-load/solid/tsconfig.json new file mode 100644 index 0000000000..0995292743 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/solid/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared.ts", + "../shared-bench.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts b/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts new file mode 100644 index 0000000000..a20e32742e --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr before-load (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/before-load/vue/project.json b/benchmarks/ssr/scenarios/before-load/vue/project.json new file mode 100644 index 0000000000..92d724821e --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-before-load-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts new file mode 100644 index 0000000000..8684c159eb --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertBeforeLoadScenario, + beforeLoadBenchOptions, + runBeforeLoadLoop, + type StartRequestHandler, +} from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertBeforeLoadScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr before-load chain (vue)', async () => + runBeforeLoadLoop(handler), + ).run(beforeLoadBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/before-load/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/before-load/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..24ee6c3b9d --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/vue/src/routeTree.gen.ts @@ -0,0 +1,120 @@ +/* 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 ARouteImport } from './routes/$a' +import { Route as ABRouteImport } from './routes/$a.$b' +import { Route as ABCRouteImport } from './routes/$a.$b.$c' + +const ARoute = ARouteImport.update({ + id: '/$a', + path: '/$a', + getParentRoute: () => rootRouteImport, +} as any) +const ABRoute = ABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => ARoute, +} as any) +const ABCRoute = ABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => ABRoute, +} as any) + +export interface FileRoutesByFullPath { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRoutesByTo { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' + fileRoutesByTo: FileRoutesByTo + to: '/$a' | '/$a/$b' | '/$a/$b/$c' + id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/$a': { + id: '/$a' + path: '/$a' + fullPath: '/$a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + '/$a/$b': { + id: '/$a/$b' + path: '/$b' + fullPath: '/$a/$b' + preLoaderRoute: typeof ABRouteImport + parentRoute: typeof ARoute + } + '/$a/$b/$c': { + id: '/$a/$b/$c' + path: '/$c' + fullPath: '/$a/$b/$c' + preLoaderRoute: typeof ABCRouteImport + parentRoute: typeof ABRoute + } + } +} + +interface ABRouteChildren { + ABCRoute: typeof ABCRoute +} + +const ABRouteChildren: ABRouteChildren = { + ABCRoute: ABCRoute, +} + +const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) + +interface ARouteChildren { + ABRoute: typeof ABRouteWithChildren +} + +const ARouteChildren: ARouteChildren = { + ABRoute: ABRouteWithChildren, +} + +const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARouteWithChildren, +} +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/benchmarks/ssr/scenarios/before-load/vue/src/router.tsx b/benchmarks/ssr/scenarios/before-load/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.$c.tsx new file mode 100644 index 0000000000..178d4071eb --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.$c.tsx @@ -0,0 +1,26 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { makeBeforeLoadMarker, type BeforeLoadContext } from '../../../shared' + +const LevelCComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () =>
{data.value.marker}
+ }, +}) + +export const Route = createFileRoute('/$a/$b/$c')({ + beforeLoad: ({ params, context }) => { + const parent = context as BeforeLoadContext + + return { + chainToken: `${parent.chainToken}.${params.c}`, + ctxC: params.c, + } + }, + loader: ({ context }) => ({ + marker: makeBeforeLoadMarker(context as BeforeLoadContext), + }), + component: LevelCComponent, +}) diff --git a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.tsx new file mode 100644 index 0000000000..43ea0dcf87 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.tsx @@ -0,0 +1,18 @@ +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import type { BeforeLoadContext } from '../../../shared' + +export const Route = createFileRoute('/$a/$b')({ + beforeLoad: ({ params, context }) => { + const parent = context as BeforeLoadContext + + return { + chainToken: `${parent.chainToken}.${params.b}`, + ctxB: params.b, + } + }, + component: LevelBComponent, +}) + +function LevelBComponent() { + return +} diff --git a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.tsx b/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.tsx new file mode 100644 index 0000000000..7f036dceac --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.tsx @@ -0,0 +1,13 @@ +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/$a')({ + beforeLoad: ({ params }) => ({ + chainToken: params.a, + ctxA: params.a, + }), + component: LevelAComponent, +}) + +function LevelAComponent() { + return +} diff --git a/benchmarks/ssr/scenarios/before-load/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/before-load/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..49422aac38 --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/vue/src/routes/__root.tsx @@ -0,0 +1,26 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/before-load/vue/tsconfig.json b/benchmarks/ssr/scenarios/before-load/vue/tsconfig.json new file mode 100644 index 0000000000..33e5cc442d --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/vue/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared.ts", + "../shared-bench.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts b/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts new file mode 100644 index 0000000000..093776869f --- /dev/null +++ b/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr before-load (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/control-flow/react/project.json b/benchmarks/ssr/scenarios/control-flow/react/project.json new file mode 100644 index 0000000000..80086788eb --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-control-flow-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts new file mode 100644 index 0000000000..899f400799 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runRedirectLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr redirect (react)', async () => runRedirectLoop(handler)).run( + controlFlowBenchOptions, + ) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-error-500.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-error-500.bench.ts new file mode 100644 index 0000000000..0a93c5eac3 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-error-500.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runErrorLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow error 500 (react)', async () => + runErrorLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-route-headers.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-route-headers.bench.ts new file mode 100644 index 0000000000..53e09fd34e --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-route-headers.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runRouteHeadersLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow route headers (react)', async () => + runRouteHeadersLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-unmatched-404.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-unmatched-404.bench.ts new file mode 100644 index 0000000000..1cd7c1044c --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-unmatched-404.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runUnmatchedLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow unmatched 404 (react)', async () => + runUnmatchedLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts new file mode 100644 index 0000000000..1e8abfd318 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runNotFoundLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr not-found (react)', async () => + runNotFoundLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/control-flow/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..4d4424c222 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/src/routeTree.gen.ts @@ -0,0 +1,177 @@ +/* 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 BoomIdRouteImport } from './routes/boom.$id' +import { Route as FromIdRouteImport } from './routes/from.$id' +import { Route as HeadersIdRouteImport } from './routes/headers.$id' +import { Route as MissingIdRouteImport } from './routes/missing.$id' +import { Route as TargetIdRouteImport } from './routes/target.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const 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', + getParentRoute: () => rootRouteImport, +} as any) +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/headers/$id': typeof HeadersIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/headers/$id': typeof HeadersIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/headers/$id': typeof HeadersIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/boom/$id' + | '/from/$id' + | '/headers/$id' + | '/missing/$id' + | '/target/$id' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/boom/$id' + | '/from/$id' + | '/headers/$id' + | '/missing/$id' + | '/target/$id' + id: + | '__root__' + | '/' + | '/boom/$id' + | '/from/$id' + | '/headers/$id' + | '/missing/$id' + | '/target/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BoomIdRoute: typeof BoomIdRoute + FromIdRoute: typeof FromIdRoute + HeadersIdRoute: typeof HeadersIdRoute + MissingIdRoute: typeof MissingIdRoute + TargetIdRoute: typeof TargetIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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 + parentRoute: typeof rootRouteImport + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BoomIdRoute: BoomIdRoute, + FromIdRoute: FromIdRoute, + HeadersIdRoute: HeadersIdRoute, + MissingIdRoute: MissingIdRoute, + TargetIdRoute: TargetIdRoute, +} +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/benchmarks/ssr/scenarios/control-flow/react/src/router.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/__root.tsx new file mode 100644 index 0000000000..e08ff06361 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/src/routes/__root.tsx @@ -0,0 +1,30 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, + notFoundComponent: RootNotFoundComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootNotFoundComponent() { + return
root-not-found-marker
+} + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/boom.$id.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/boom.$id.tsx new file mode 100644 index 0000000000..eb47d34070 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/src/routes/boom.$id.tsx @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/boom/$id')({ + loader: ({ params }) => { + throw new Error(`boom-${params.id}`) + }, + errorComponent: BoomErrorComponent, + component: BoomComponent, +}) + +function BoomErrorComponent() { + return
control-flow-error-boundary
+} + +function BoomComponent() { + return null +} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/from.$id.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/from.$id.tsx new file mode 100644 index 0000000000..e9289fce30 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/src/routes/from.$id.tsx @@ -0,0 +1,14 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/from/$id')({ + loader: ({ params }) => { + const { id } = params + + throw redirect({ to: '/target/$id', params: { id } }) + }, + component: FromComponent, +}) + +function FromComponent() { + return null +} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/headers.$id.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/headers.$id.tsx new file mode 100644 index 0000000000..412d056d85 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/src/routes/headers.$id.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/headers/$id')({ + headers: ({ params }) => ({ + 'x-bench-route-header': `route-header-${params.id}`, + 'x-bench-route-static': 'control-flow-route-headers', + }), + component: HeadersComponent, +}) + +function HeadersComponent() { + const params = Route.useParams() + + return
{`headers-${params.id}`}
+} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/index.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/index.tsx new file mode 100644 index 0000000000..e9886f60c4 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
control-flow-index
+} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/missing.$id.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/missing.$id.tsx new file mode 100644 index 0000000000..b7d760e562 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/src/routes/missing.$id.tsx @@ -0,0 +1,12 @@ +import { createFileRoute, notFound } from '@tanstack/react-router' + +export const Route = createFileRoute('/missing/$id')({ + loader: () => { + throw notFound() + }, + component: MissingComponent, +}) + +function MissingComponent() { + return null +} diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routes/target.$id.tsx b/benchmarks/ssr/scenarios/control-flow/react/src/routes/target.$id.tsx new file mode 100644 index 0000000000..1c13394cb2 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/src/routes/target.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/target/$id')({ + component: TargetComponent, +}) + +function TargetComponent() { + const params = Route.useParams() + + return
{`target-${params.id}`}
+} diff --git a/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json b/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json new file mode 100644 index 0000000000..cf14e1d440 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/control-flow/react/vite.config.ts b/benchmarks/ssr/scenarios/control-flow/react/vite.config.ts new file mode 100644 index 0000000000..273d7d9d80 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr control-flow (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/control-flow/shared.ts b/benchmarks/ssr/scenarios/control-flow/shared.ts new file mode 100644 index 0000000000..307665d59d --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/shared.ts @@ -0,0 +1,230 @@ +import { expect } from 'vitest' +import { randomSegment, runRequestLoop } from '../../bench-utils' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +const benchmarkSeed = 0xdecafbad +const redirectLoopTotalRequests = 112 +const notFoundLoopTotalRequests = 48 +const errorLoopTotalRequests = 48 +const unmatchedLoopTotalRequests = 64 +const routeHeadersLoopTotalRequests = 64 + +// Pinned to the current built handler responses for these control-flow routes. +const OK_STATUS = 200 +const REDIRECT_STATUS = 307 +const NOT_FOUND_STATUS = 404 +const ERROR_STATUS = 500 +const ROUTE_HEADERS_STATIC_VALUE = 'control-flow-route-headers' + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +export const controlFlowBenchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} + +function buildRedirectRequest(random: () => number) { + return new Request( + `http://localhost/from/${randomSegment(random)}`, + requestInit, + ) +} + +function buildNotFoundRequest(random: () => number) { + return new Request( + `http://localhost/missing/${randomSegment(random)}`, + requestInit, + ) +} + +function buildErrorRequest(random: () => number) { + return new Request( + `http://localhost/boom/${randomSegment(random)}`, + requestInit, + ) +} + +function buildUnmatchedRequest(random: () => number) { + return new Request( + `http://localhost/definitely-not-a-route/${randomSegment(random)}`, + requestInit, + ) +} + +function buildRouteHeadersRequest(random: () => number) { + return new Request( + `http://localhost/headers/${randomSegment(random)}`, + requestInit, + ) +} + +function getRequestId(request: Request) { + const id = new URL(request.url).pathname.split('/').pop() + + if (!id) { + throw new Error(`expected request id in ${request.url}`) + } + + return id +} + +function validateRedirectResponse(response: Response) { + if (response.status !== REDIRECT_STATUS) { + throw new Error(`expected ${REDIRECT_STATUS}, got ${response.status}`) + } +} + +function validateNotFoundResponse(response: Response) { + if (response.status !== NOT_FOUND_STATUS) { + throw new Error(`expected ${NOT_FOUND_STATUS}, got ${response.status}`) + } +} + +function validateErrorResponse(response: Response) { + if (response.status !== ERROR_STATUS) { + throw new Error(`expected ${ERROR_STATUS}, got ${response.status}`) + } +} + +function validateUnmatchedResponse(response: Response) { + if (response.status !== NOT_FOUND_STATUS) { + throw new Error(`expected ${NOT_FOUND_STATUS}, got ${response.status}`) + } +} + +function validateRouteHeadersResponse(response: Response, request: Request) { + if (response.status !== OK_STATUS) { + throw new Error(`expected ${OK_STATUS}, got ${response.status}`) + } + + const id = getRequestId(request) + const routeHeader = response.headers.get('x-bench-route-header') + + if (routeHeader !== `route-header-${id}`) { + throw new Error(`expected route header for ${id}, got ${routeHeader}`) + } + + const staticHeader = response.headers.get('x-bench-route-static') + + if (staticHeader !== ROUTE_HEADERS_STATIC_VALUE) { + throw new Error( + `expected route static header ${ROUTE_HEADERS_STATIC_VALUE}, got ${staticHeader}`, + ) + } +} + +export function runRedirectLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: redirectLoopTotalRequests, + buildRequest: buildRedirectRequest, + validateResponse: validateRedirectResponse, + }) +} + +export function runNotFoundLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: notFoundLoopTotalRequests, + buildRequest: buildNotFoundRequest, + validateResponse: validateNotFoundResponse, + }) +} + +export function runErrorLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: errorLoopTotalRequests, + buildRequest: buildErrorRequest, + validateResponse: validateErrorResponse, + }) +} + +export function runUnmatchedLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: unmatchedLoopTotalRequests, + buildRequest: buildUnmatchedRequest, + validateResponse: validateUnmatchedResponse, + }) +} + +export function runRouteHeadersLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: routeHeadersLoopTotalRequests, + buildRequest: buildRouteHeadersRequest, + validateResponse: validateRouteHeadersResponse, + }) +} + +export async function assertControlFlowSanity(handler: StartRequestHandler) { + const redirectId = 'sanity-redirect' + const redirectResponse = await handler.fetch( + new Request(`http://localhost/from/${redirectId}`, requestInit), + ) + + expect(redirectResponse.status).toBe(REDIRECT_STATUS) + expect(redirectResponse.headers.get('location')).toBe(`/target/${redirectId}`) + + const notFoundResponse = await handler.fetch( + new Request('http://localhost/missing/sanity-missing', requestInit), + ) + const notFoundBody = await notFoundResponse.text() + + expect(notFoundResponse.status).toBe(NOT_FOUND_STATUS) + expect(notFoundBody).toContain('root-not-found-marker') + + const errorId = 'sanity-error' + const errorResponse = await handler.fetch( + new Request(`http://localhost/boom/${errorId}`, requestInit), + ) + const errorBody = await errorResponse.text() + + expect(errorResponse.status).toBe(ERROR_STATUS) + expect(errorBody).toContain('data-bench="error-boundary"') + const firstScriptIndex = errorBody.indexOf(' { + await bench('ssr redirect (solid)', async () => runRedirectLoop(handler)).run( + controlFlowBenchOptions, + ) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-error-500.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-error-500.bench.ts new file mode 100644 index 0000000000..57a2f0fbe9 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-error-500.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runErrorLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow error 500 (solid)', async () => + runErrorLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-route-headers.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-route-headers.bench.ts new file mode 100644 index 0000000000..6581e92b39 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-route-headers.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runRouteHeadersLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow route headers (solid)', async () => + runRouteHeadersLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-unmatched-404.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-unmatched-404.bench.ts new file mode 100644 index 0000000000..40f1679320 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-unmatched-404.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runUnmatchedLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow unmatched 404 (solid)', async () => + runUnmatchedLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts new file mode 100644 index 0000000000..efcb7cc229 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runNotFoundLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr not-found (solid)', async () => + runNotFoundLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/control-flow/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..3cec17d9c8 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/src/routeTree.gen.ts @@ -0,0 +1,177 @@ +/* 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 BoomIdRouteImport } from './routes/boom.$id' +import { Route as FromIdRouteImport } from './routes/from.$id' +import { Route as HeadersIdRouteImport } from './routes/headers.$id' +import { Route as MissingIdRouteImport } from './routes/missing.$id' +import { Route as TargetIdRouteImport } from './routes/target.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const 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', + getParentRoute: () => rootRouteImport, +} as any) +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/headers/$id': typeof HeadersIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/headers/$id': typeof HeadersIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/headers/$id': typeof HeadersIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/boom/$id' + | '/from/$id' + | '/headers/$id' + | '/missing/$id' + | '/target/$id' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/boom/$id' + | '/from/$id' + | '/headers/$id' + | '/missing/$id' + | '/target/$id' + id: + | '__root__' + | '/' + | '/boom/$id' + | '/from/$id' + | '/headers/$id' + | '/missing/$id' + | '/target/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BoomIdRoute: typeof BoomIdRoute + FromIdRoute: typeof FromIdRoute + HeadersIdRoute: typeof HeadersIdRoute + MissingIdRoute: typeof MissingIdRoute + TargetIdRoute: typeof TargetIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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 + parentRoute: typeof rootRouteImport + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BoomIdRoute: BoomIdRoute, + FromIdRoute: FromIdRoute, + HeadersIdRoute: HeadersIdRoute, + MissingIdRoute: MissingIdRoute, + TargetIdRoute: TargetIdRoute, +} +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/benchmarks/ssr/scenarios/control-flow/solid/src/router.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..dc8b783e76 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/__root.tsx @@ -0,0 +1,30 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, + notFoundComponent: RootNotFoundComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootNotFoundComponent() { + return
root-not-found-marker
+} + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/boom.$id.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/boom.$id.tsx new file mode 100644 index 0000000000..0bcc4dc02b --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/boom.$id.tsx @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/boom/$id')({ + loader: ({ params }) => { + throw new Error(`boom-${params.id}`) + }, + errorComponent: BoomErrorComponent, + component: BoomComponent, +}) + +function BoomErrorComponent() { + return
control-flow-error-boundary
+} + +function BoomComponent() { + return null +} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/from.$id.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/from.$id.tsx new file mode 100644 index 0000000000..a319375db3 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/from.$id.tsx @@ -0,0 +1,14 @@ +import { createFileRoute, redirect } from '@tanstack/solid-router' + +export const Route = createFileRoute('/from/$id')({ + loader: ({ params }) => { + const { id } = params + + throw redirect({ to: '/target/$id', params: { id } }) + }, + component: FromComponent, +}) + +function FromComponent() { + return null +} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/headers.$id.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/headers.$id.tsx new file mode 100644 index 0000000000..9d87b4a354 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/headers.$id.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/headers/$id')({ + headers: ({ params }) => ({ + 'x-bench-route-header': `route-header-${params.id}`, + 'x-bench-route-static': 'control-flow-route-headers', + }), + component: HeadersComponent, +}) + +function HeadersComponent() { + const params = Route.useParams() + + return
{`headers-${params().id}`}
+} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/index.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/index.tsx new file mode 100644 index 0000000000..96b26a2d6c --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
control-flow-index
+} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/missing.$id.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/missing.$id.tsx new file mode 100644 index 0000000000..e5c42b56dc --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/missing.$id.tsx @@ -0,0 +1,12 @@ +import { createFileRoute, notFound } from '@tanstack/solid-router' + +export const Route = createFileRoute('/missing/$id')({ + loader: () => { + throw notFound() + }, + component: MissingComponent, +}) + +function MissingComponent() { + return null +} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routes/target.$id.tsx b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/target.$id.tsx new file mode 100644 index 0000000000..4196fc1183 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/src/routes/target.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/target/$id')({ + component: TargetComponent, +}) + +function TargetComponent() { + const params = Route.useParams() + + return
{`target-${params().id}`}
+} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json b/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json new file mode 100644 index 0000000000..42c3a2160f --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/control-flow/solid/vite.config.ts b/benchmarks/ssr/scenarios/control-flow/solid/vite.config.ts new file mode 100644 index 0000000000..c75c957466 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr control-flow (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/project.json b/benchmarks/ssr/scenarios/control-flow/vue/project.json new file mode 100644 index 0000000000..e0e014e588 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-control-flow-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts new file mode 100644 index 0000000000..0b95f426f2 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runRedirectLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr redirect (vue)', async () => runRedirectLoop(handler)).run( + controlFlowBenchOptions, + ) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-error-500.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-error-500.bench.ts new file mode 100644 index 0000000000..262ca951af --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-error-500.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runErrorLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow error 500 (vue)', async () => + runErrorLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-route-headers.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-route-headers.bench.ts new file mode 100644 index 0000000000..bf8c90a8a1 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-route-headers.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runRouteHeadersLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow route headers (vue)', async () => + runRouteHeadersLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-unmatched-404.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-unmatched-404.bench.ts new file mode 100644 index 0000000000..d7f8ebeb9e --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-unmatched-404.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runUnmatchedLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow unmatched 404 (vue)', async () => + runUnmatchedLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts new file mode 100644 index 0000000000..4b84fb594c --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runNotFoundLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr not-found (vue)', async () => runNotFoundLoop(handler)).run( + controlFlowBenchOptions, + ) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/control-flow/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..6dcf0d095e --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routeTree.gen.ts @@ -0,0 +1,177 @@ +/* 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 BoomIdRouteImport } from './routes/boom.$id' +import { Route as FromIdRouteImport } from './routes/from.$id' +import { Route as HeadersIdRouteImport } from './routes/headers.$id' +import { Route as MissingIdRouteImport } from './routes/missing.$id' +import { Route as TargetIdRouteImport } from './routes/target.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const 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', + getParentRoute: () => rootRouteImport, +} as any) +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/headers/$id': typeof HeadersIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/headers/$id': typeof HeadersIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/boom/$id': typeof BoomIdRoute + '/from/$id': typeof FromIdRoute + '/headers/$id': typeof HeadersIdRoute + '/missing/$id': typeof MissingIdRoute + '/target/$id': typeof TargetIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/boom/$id' + | '/from/$id' + | '/headers/$id' + | '/missing/$id' + | '/target/$id' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/boom/$id' + | '/from/$id' + | '/headers/$id' + | '/missing/$id' + | '/target/$id' + id: + | '__root__' + | '/' + | '/boom/$id' + | '/from/$id' + | '/headers/$id' + | '/missing/$id' + | '/target/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BoomIdRoute: typeof BoomIdRoute + FromIdRoute: typeof FromIdRoute + HeadersIdRoute: typeof HeadersIdRoute + MissingIdRoute: typeof MissingIdRoute + TargetIdRoute: typeof TargetIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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 + parentRoute: typeof rootRouteImport + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BoomIdRoute: BoomIdRoute, + FromIdRoute: FromIdRoute, + HeadersIdRoute: HeadersIdRoute, + MissingIdRoute: MissingIdRoute, + TargetIdRoute: TargetIdRoute, +} +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/benchmarks/ssr/scenarios/control-flow/vue/src/router.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..815466918a --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/__root.tsx @@ -0,0 +1,32 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, + notFoundComponent: RootNotFoundComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootNotFoundComponent() { + return
root-not-found-marker
+} + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/boom.$id.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/boom.$id.tsx new file mode 100644 index 0000000000..dfae636ae7 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/boom.$id.tsx @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/boom/$id')({ + loader: ({ params }) => { + throw new Error(`boom-${params.id}`) + }, + errorComponent: BoomErrorComponent, + component: BoomComponent, +}) + +function BoomErrorComponent() { + return
control-flow-error-boundary
+} + +function BoomComponent() { + return <> +} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/from.$id.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/from.$id.tsx new file mode 100644 index 0000000000..dfb90a51f8 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/from.$id.tsx @@ -0,0 +1,14 @@ +import { createFileRoute, redirect } from '@tanstack/vue-router' + +export const Route = createFileRoute('/from/$id')({ + loader: ({ params }) => { + const { id } = params + + throw redirect({ to: '/target/$id', params: { id } }) + }, + component: FromComponent, +}) + +function FromComponent() { + return <> +} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/headers.$id.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/headers.$id.tsx new file mode 100644 index 0000000000..20c1bbe5ac --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/headers.$id.tsx @@ -0,0 +1,18 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const HeadersComponent = defineComponent({ + setup() { + const params = Route.useParams() + + return () =>
{`headers-${params.value.id}`}
+ }, +}) + +export const Route = createFileRoute('/headers/$id')({ + headers: ({ params }) => ({ + 'x-bench-route-header': `route-header-${params.id}`, + 'x-bench-route-static': 'control-flow-route-headers', + }), + component: HeadersComponent, +}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/index.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/index.tsx new file mode 100644 index 0000000000..51a503a1d1 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
control-flow-index
+} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/missing.$id.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/missing.$id.tsx new file mode 100644 index 0000000000..b15333f5a3 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/missing.$id.tsx @@ -0,0 +1,12 @@ +import { createFileRoute, notFound } from '@tanstack/vue-router' + +export const Route = createFileRoute('/missing/$id')({ + loader: () => { + throw notFound() + }, + component: MissingComponent, +}) + +function MissingComponent() { + return <> +} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/target.$id.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/target.$id.tsx new file mode 100644 index 0000000000..0bbf4a3dc6 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/target.$id.tsx @@ -0,0 +1,14 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const TargetComponent = defineComponent({ + setup() { + const params = Route.useParams() + + return () =>
{`target-${params.value.id}`}
+ }, +}) + +export const Route = createFileRoute('/target/$id')({ + component: TargetComponent, +}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json b/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json new file mode 100644 index 0000000000..08c94853f4 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/vite.config.ts b/benchmarks/ssr/scenarios/control-flow/vue/vite.config.ts new file mode 100644 index 0000000000..1b77968d96 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr control-flow (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/bench.ts b/benchmarks/ssr/scenarios/global-middleware/bench.ts new file mode 100644 index 0000000000..d2784aed38 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/bench.ts @@ -0,0 +1,309 @@ +import { toJSONAsync } from 'seroval' +import { + createDeterministicRandom, + randomSegment, + runRequestLoop, +} from '../../bench-utils' +import { + expectedFunctionTotal, + expectedRequestTotal, + getExpectedRequestContext, + makeDocumentMarker, + makeServerFnMarker, + makeServerRouteMarker, + setRequestMiddlewareCount, +} from './shared' +import type { RequestMiddlewareCount } from './shared' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +type Payload = { + q: string + n: number + nested: { list: Array } +} + +type FnUrls = { + post: string +} + +export interface GlobalMiddlewareBenchContext { + urls: FnUrls + bodies: Array + expectedFnMarker: string +} + +const benchmarkSeed = 0xdecafbad +const origin = 'http://localhost' +const tssContentTypeFramed = 'application/x-tss-framed' +const xTssSerialized = 'x-tss-serialized' +const acceptHeader = `${tssContentTypeFramed}, application/x-ndjson, application/json` +const documentRequestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit +const apiRequestInit = { + method: 'GET', + headers: { + accept: 'application/json', + }, +} satisfies RequestInit +const postHeaders = { + 'x-tsr-serverFn': 'true', + 'sec-fetch-site': 'same-origin', + accept: acceptHeader, + 'content-type': 'application/json', +} satisfies HeadersInit +const documentLoopTotalRequests = 64 +const serverFnLoopTotalRequests = 128 +const serverRouteLoopTotalRequests = 256 + +export const globalMiddlewareBenchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} as const + +function createPayloads() { + const random = createDeterministicRandom(benchmarkSeed) + + return Array.from({ length: 10 }, (_, index): Payload => { + const queryParts = Array.from({ length: 6 }, () => randomSegment(random)) + + return { + q: `q-${index}-${queryParts.join('-')}`, + n: 100 + index, + nested: { + list: Array.from( + { length: 5 }, + () => `l-${index}-${randomSegment(random)}-${randomSegment(random)}`, + ), + }, + } + }) +} + +async function createBodies(payloads: Array) { + return await Promise.all( + payloads.map(async (payload) => + JSON.stringify(await toJSONAsync({ data: payload })), + ), + ) +} + +async function discoverUrls(handler: StartRequestHandler) { + const response = await handler.fetch(new Request(`${origin}/api/fn-urls`)) + + if (response.status === 404) { + throw new Error('URL discovery route returned 404 for /api/fn-urls') + } + + if (response.status !== 200) { + throw new Error( + `URL discovery failed with status ${response.status}: ${await response.text()}`, + ) + } + + const urls = (await response.json()) as Partial + + if (typeof urls.post !== 'string') { + throw new Error( + `URL discovery returned invalid payload: ${JSON.stringify(urls)}`, + ) + } + + return { post: urls.post } +} + +function buildDocumentRequest(random: () => number, index: number) { + return new Request( + `${origin}/page/${randomSegment(random)}-${index.toString(36)}`, + documentRequestInit, + ) +} + +function buildServerRouteRequest(random: () => number, index: number) { + return new Request( + `${origin}/api/ping/${randomSegment(random)}-${index.toString(36)}`, + apiRequestInit, + ) +} + +function buildPostRequest(urls: FnUrls, bodies: Array, index: number) { + return new Request(`${origin}${urls.post}`, { + method: 'POST', + headers: postHeaders, + body: bodies[index % bodies.length], + }) +} + +export async function setupGlobalMiddlewareBench( + handler: StartRequestHandler, +): Promise { + setRequestMiddlewareCount(3) + const urls = await discoverUrls(handler) + const payloads = createPayloads() + const bodies = await createBodies(payloads) + const expectedFnMarker = makeServerFnMarker(payloads[0]!.q, { + requestTrace: 'req.r1.r2.r3', + requestTotal: expectedRequestTotal, + functionTrace: 'fn.f1.f2', + functionTotal: expectedFunctionTotal, + }) + + return { urls, bodies, expectedFnMarker } +} + +async function assertDocumentResponse(handler: StartRequestHandler) { + setRequestMiddlewareCount(3) + const id = 'page-sanity' + const response = await handler.fetch( + new Request(`${origin}/page/${id}`, documentRequestInit), + ) + const body = await response.text() + const expectedMarker = makeDocumentMarker(id, { + requestTrace: 'req.r1.r2.r3', + requestTotal: expectedRequestTotal, + }) + + if (response.status !== 200) { + throw new Error(`Expected document status 200, received ${response.status}`) + } + + if (!body.includes(expectedMarker)) { + throw new Error( + `Expected document response to include global middleware marker ${expectedMarker}`, + ) + } +} + +async function assertServerRouteResponseForCount( + handler: StartRequestHandler, + count: RequestMiddlewareCount, +) { + setRequestMiddlewareCount(count) + const id = 'route-sanity' + const response = await handler.fetch( + new Request(`${origin}/api/ping/${id}`, apiRequestInit), + ) + + if (response.status !== 200) { + throw new Error( + `Expected server route status 200, received ${response.status}`, + ) + } + + const contentType = response.headers.get('content-type') + + if (!contentType?.includes('application/json')) { + throw new Error( + `Expected JSON server route response, received ${contentType}`, + ) + } + + const body = (await response.json()) as { + marker?: string + requestTotal?: number + } + const expectedContext = getExpectedRequestContext(count) + const expectedMarker = makeServerRouteMarker(id, expectedContext) + + if (body.marker !== expectedMarker) { + throw new Error( + `Expected server route marker ${expectedMarker}, received ${body.marker}`, + ) + } + + if (body.requestTotal !== expectedContext.requestTotal) { + throw new Error( + `Expected server route requestTotal ${expectedContext.requestTotal}, received ${body.requestTotal}`, + ) + } +} + +async function assertServerFnResponse( + handler: StartRequestHandler, + context: GlobalMiddlewareBenchContext, +) { + setRequestMiddlewareCount(3) + const response = await handler.fetch( + buildPostRequest(context.urls, context.bodies, 0), + ) + const text = await response.text() + + if (response.status === 403) { + throw new Error('Server function sanity check failed with 403') + } + + if (response.status === 404) { + throw new Error('Server function sanity check failed with 404') + } + + if (response.status !== 200) { + throw new Error( + `Server function sanity check failed with status ${response.status}: ${text}`, + ) + } + + if (!response.headers.get(xTssSerialized)) { + throw new Error(`Server function response missing ${xTssSerialized} header`) + } + + if (!text.includes(context.expectedFnMarker)) { + throw new Error( + `Expected server function response to include ${context.expectedFnMarker}: ${text}`, + ) + } +} + +export async function assertGlobalMiddlewareScenario( + handler: StartRequestHandler, + context: GlobalMiddlewareBenchContext, +) { + await assertDocumentResponse(handler) + await assertServerFnResponse(handler, context) + for (const count of [0, 1, 2, 3] as const) { + await assertServerRouteResponseForCount(handler, count) + } + setRequestMiddlewareCount(3) +} + +export function runGlobalMiddlewareDocumentLoop(handler: StartRequestHandler) { + setRequestMiddlewareCount(3) + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: documentLoopTotalRequests, + buildRequest: buildDocumentRequest, + }) +} + +export function runGlobalMiddlewareServerFnLoop( + handler: StartRequestHandler, + context: GlobalMiddlewareBenchContext, +) { + setRequestMiddlewareCount(3) + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: serverFnLoopTotalRequests, + buildRequest: (_random, index) => + buildPostRequest(context.urls, context.bodies, index), + }) +} + +export function runGlobalMiddlewareServerRouteLoop( + handler: StartRequestHandler, + count: RequestMiddlewareCount = 3, +) { + setRequestMiddlewareCount(count) + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: serverRouteLoopTotalRequests, + buildRequest: buildServerRouteRequest, + }) +} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/project.json b/benchmarks/ssr/scenarios/global-middleware/react/project.json new file mode 100644 index 0000000000..bded6925fd --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-global-middleware-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts new file mode 100644 index 0000000000..cb3f9f427c --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareDocumentLoop, + 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 document (react)', async () => + runGlobalMiddlewareDocumentLoop(handler), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-fn.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-fn.bench.ts new file mode 100644 index 0000000000..48c444de77 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-fn.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerFnLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-fn (react)', async () => + runGlobalMiddlewareServerFnLoop(handler, context), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-0-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-0-middleware.bench.ts new file mode 100644 index 0000000000..22f53883ee --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-0-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 0 middleware (react)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 0), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts new file mode 100644 index 0000000000..f01b48d66e --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 1 middleware (react)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 1), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts new file mode 100644 index 0000000000..b01957f806 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 2 middlewares (react)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 2), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts new file mode 100644 index 0000000000..08d97fcaf6 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 3 middlewares (react)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 3), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/fns.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/fns.ts new file mode 100644 index 0000000000..68cfd992c6 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/fns.ts @@ -0,0 +1,34 @@ +import { createServerFn } from '@tanstack/react-start' +import { makeServerFnMarker, type GlobalMiddlewareContext } from '../../shared' + +type Payload = { q: string; n: number; nested: { list: Array } } + +const validate = (input: unknown): Payload => { + const payload = input as Payload + + if ( + typeof payload?.q !== 'string' || + typeof payload?.n !== 'number' || + !Array.isArray(payload?.nested?.list) + ) { + throw new Error('invalid payload') + } + + return payload +} + +export const echoPost = createServerFn({ method: 'POST' }) + .validator(validate) + .handler(({ data, context }) => { + const middlewareContext = (context ?? {}) as GlobalMiddlewareContext + + return { + echoed: data, + marker: makeServerFnMarker(data.q, middlewareContext), + sum: + data.n + + (middlewareContext.requestTotal ?? 0) + + (middlewareContext.functionTotal ?? 0), + list: data.nested.list.map((item) => `global-${item}`), + } + }) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..8dfaa80562 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/routeTree.gen.ts @@ -0,0 +1,123 @@ +/* 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 ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as PageIdRouteImport } from './routes/page.$id' +import { Route as ApiPingIdRouteImport } from './routes/api.ping.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + 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 ApiPingIdRoute = ApiPingIdRouteImport.update({ + id: '/api/ping/$id', + path: '/api/ping/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/page/$id': typeof PageIdRoute + '/api/ping/$id': typeof ApiPingIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/page/$id': typeof PageIdRoute + '/api/ping/$id': typeof ApiPingIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/page/$id': typeof PageIdRoute + '/api/ping/$id': typeof ApiPingIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' + id: '__root__' | '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiFnUrlsRoute: typeof ApiFnUrlsRoute + PageIdRoute: typeof PageIdRoute + ApiPingIdRoute: typeof ApiPingIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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' + fullPath: '/page/$id' + preLoaderRoute: typeof PageIdRouteImport + parentRoute: typeof rootRouteImport + } + '/api/ping/$id': { + id: '/api/ping/$id' + path: '/api/ping/$id' + fullPath: '/api/ping/$id' + preLoaderRoute: typeof ApiPingIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiFnUrlsRoute: ApiFnUrlsRoute, + PageIdRoute: PageIdRoute, + ApiPingIdRoute: ApiPingIdRoute, +} +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/benchmarks/ssr/scenarios/global-middleware/react/src/router.tsx b/benchmarks/ssr/scenarios/global-middleware/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/__root.tsx new file mode 100644 index 0000000000..ff1da4c304 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.fn-urls.ts new file mode 100644 index 0000000000..bcb2111930 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.fn-urls.ts @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/react-router' +import { echoPost } from '../fns' + +export const Route = createFileRoute('/api/fn-urls')({ + server: { + handlers: { + GET: () => Response.json({ post: echoPost.url }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.ping.$id.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.ping.$id.ts new file mode 100644 index 0000000000..434833f018 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/api.ping.$id.ts @@ -0,0 +1,22 @@ +import { createFileRoute } from '@tanstack/react-router' +import { + makeServerRouteMarker, + type GlobalMiddlewareContext, +} from '../../../shared' + +export const Route = createFileRoute('/api/ping/$id')({ + server: { + handlers: { + GET: ({ params, context }) => { + const middlewareContext = (context ?? {}) as GlobalMiddlewareContext + + return Response.json({ + id: params.id, + marker: makeServerRouteMarker(params.id, middlewareContext), + requestTrace: middlewareContext.requestTrace, + requestTotal: middlewareContext.requestTotal, + }) + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/index.tsx b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/index.tsx new file mode 100644 index 0000000000..a0d3aec869 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/index.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/react-router' +import { echoPost } from '../fns' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
global-middleware
+} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/routes/page.$id.tsx b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/page.$id.tsx new file mode 100644 index 0000000000..6b7a42c12e --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/routes/page.$id.tsx @@ -0,0 +1,22 @@ +import { createFileRoute } from '@tanstack/react-router' +import { + getGlobalMiddlewareContext, + makeDocumentMarker, + type GlobalMiddlewareContext, +} from '../../../shared' + +export const Route = createFileRoute('/page/$id')({ + beforeLoad: ({ serverContext }) => ({ + globalMiddlewareContext: (serverContext ?? {}) as GlobalMiddlewareContext, + }), + loader: ({ params, context }) => ({ + marker: makeDocumentMarker(params.id, getGlobalMiddlewareContext(context)), + }), + component: PageComponent, +}) + +function PageComponent() { + const data = Route.useLoaderData() + + return
{data.marker}
+} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts new file mode 100644 index 0000000000..8dfb2dd3c4 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts @@ -0,0 +1,88 @@ +import { createMiddleware, createStart } from '@tanstack/react-start' +import { getRequestMiddlewareCount } from '../../shared' +import type { GlobalMiddlewareContext } from '../../shared' + +function appendTrace( + trace: string | undefined, + fallback: string, + label: string, +) { + return `${trace ?? fallback}.${label}` +} + +const requestMiddlewareA = createMiddleware({ type: 'request' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + requestTrace: appendTrace(ctx.requestTrace, 'req', 'r1'), + requestTotal: (ctx.requestTotal ?? 0) + 1, + }, + }) + }, +) + +const requestMiddlewareB = createMiddleware({ type: 'request' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + requestTrace: appendTrace(ctx.requestTrace, 'req', 'r2'), + requestTotal: (ctx.requestTotal ?? 0) + 2, + }, + }) + }, +) + +const requestMiddlewareC = createMiddleware({ type: 'request' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + requestTrace: appendTrace(ctx.requestTrace, 'req', 'r3'), + requestTotal: (ctx.requestTotal ?? 0) + 3, + }, + }) + }, +) + +const requestMiddlewareSets: Array> = [ + [], + [requestMiddlewareA], + [requestMiddlewareA, requestMiddlewareB], + [requestMiddlewareA, requestMiddlewareB, requestMiddlewareC], +] + +const functionMiddlewareA = createMiddleware({ type: 'function' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + functionTrace: appendTrace(ctx.functionTrace, 'fn', 'f1'), + functionTotal: (ctx.functionTotal ?? 0) + 10, + }, + }) + }, +) + +const functionMiddlewareB = createMiddleware({ type: 'function' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + functionTrace: appendTrace(ctx.functionTrace, 'fn', 'f2'), + functionTotal: (ctx.functionTotal ?? 0) + 20, + }, + }) + }, +) + +export const startInstance = createStart(() => ({ + requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], + functionMiddleware: [functionMiddlewareA, functionMiddlewareB], +})) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/tsconfig.json b/benchmarks/ssr/scenarios/global-middleware/react/tsconfig.json new file mode 100644 index 0000000000..de4a3204b9 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared.ts", + "../bench.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts b/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts new file mode 100644 index 0000000000..968a8a24e9 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr global-middleware (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/shared.ts b/benchmarks/ssr/scenarios/global-middleware/shared.ts new file mode 100644 index 0000000000..8fbe788911 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/shared.ts @@ -0,0 +1,77 @@ +export interface GlobalMiddlewareContext { + requestTrace?: string + requestTotal?: number + functionTrace?: string + functionTotal?: number +} + +export interface GlobalMiddlewareRouteContext extends GlobalMiddlewareContext { + serverContext?: 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, +) { + return `document:${context.requestTrace}:${id}:${context.requestTotal}` +} + +export function getGlobalMiddlewareContext(context: unknown) { + const routeContext = (context ?? {}) as GlobalMiddlewareRouteContext + + return ( + routeContext.globalMiddlewareContext ?? + routeContext.serverContext ?? + routeContext + ) +} + +export function makeServerRouteMarker( + id: string, + context: GlobalMiddlewareContext, +) { + return `route:${context.requestTrace}:${id}:${context.requestTotal}` +} + +export function makeServerFnMarker( + q: string, + context: GlobalMiddlewareContext, +) { + return `fn:${context.requestTrace}:${context.functionTrace}:${q}:${context.requestTotal}:${context.functionTotal}` +} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/project.json b/benchmarks/ssr/scenarios/global-middleware/solid/project.json new file mode 100644 index 0000000000..d325c15527 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-global-middleware-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts new file mode 100644 index 0000000000..0e5f504090 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareDocumentLoop, + 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 document (solid)', async () => + runGlobalMiddlewareDocumentLoop(handler), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-fn.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-fn.bench.ts new file mode 100644 index 0000000000..915507ef9f --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-fn.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerFnLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-fn (solid)', async () => + runGlobalMiddlewareServerFnLoop(handler, context), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-0-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-0-middleware.bench.ts new file mode 100644 index 0000000000..a791145935 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-0-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 0 middleware (solid)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 0), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts new file mode 100644 index 0000000000..1baab0f344 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 1 middleware (solid)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 1), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts new file mode 100644 index 0000000000..d6fde20764 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 2 middlewares (solid)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 2), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts new file mode 100644 index 0000000000..558ebeb9a4 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 3 middlewares (solid)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 3), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/fns.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/fns.ts new file mode 100644 index 0000000000..667baf9f54 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/fns.ts @@ -0,0 +1,34 @@ +import { createServerFn } from '@tanstack/solid-start' +import { makeServerFnMarker, type GlobalMiddlewareContext } from '../../shared' + +type Payload = { q: string; n: number; nested: { list: Array } } + +const validate = (input: unknown): Payload => { + const payload = input as Payload + + if ( + typeof payload?.q !== 'string' || + typeof payload?.n !== 'number' || + !Array.isArray(payload?.nested?.list) + ) { + throw new Error('invalid payload') + } + + return payload +} + +export const echoPost = createServerFn({ method: 'POST' }) + .validator(validate) + .handler(({ data, context }) => { + const middlewareContext = (context ?? {}) as GlobalMiddlewareContext + + return { + echoed: data, + marker: makeServerFnMarker(data.q, middlewareContext), + sum: + data.n + + (middlewareContext.requestTotal ?? 0) + + (middlewareContext.functionTotal ?? 0), + list: data.nested.list.map((item) => `global-${item}`), + } + }) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..65f7fa5848 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts @@ -0,0 +1,123 @@ +/* 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 ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as PageIdRouteImport } from './routes/page.$id' +import { Route as ApiPingIdRouteImport } from './routes/api.ping.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + 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 ApiPingIdRoute = ApiPingIdRouteImport.update({ + id: '/api/ping/$id', + path: '/api/ping/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/page/$id': typeof PageIdRoute + '/api/ping/$id': typeof ApiPingIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/page/$id': typeof PageIdRoute + '/api/ping/$id': typeof ApiPingIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/page/$id': typeof PageIdRoute + '/api/ping/$id': typeof ApiPingIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' + id: '__root__' | '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiFnUrlsRoute: typeof ApiFnUrlsRoute + PageIdRoute: typeof PageIdRoute + ApiPingIdRoute: typeof ApiPingIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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' + fullPath: '/page/$id' + preLoaderRoute: typeof PageIdRouteImport + parentRoute: typeof rootRouteImport + } + '/api/ping/$id': { + id: '/api/ping/$id' + path: '/api/ping/$id' + fullPath: '/api/ping/$id' + preLoaderRoute: typeof ApiPingIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiFnUrlsRoute: ApiFnUrlsRoute, + PageIdRoute: PageIdRoute, + ApiPingIdRoute: ApiPingIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { startInstance } from './start.ts' +declare module '@tanstack/solid-start' { + interface Register { + ssr: true + router: Awaited> + config: Awaited> + } +} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/router.tsx b/benchmarks/ssr/scenarios/global-middleware/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..e59de72236 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.fn-urls.ts new file mode 100644 index 0000000000..7166ea3030 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.fn-urls.ts @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { echoPost } from '../fns' + +export const Route = createFileRoute('/api/fn-urls')({ + server: { + handlers: { + GET: () => Response.json({ post: echoPost.url }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.ping.$id.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.ping.$id.ts new file mode 100644 index 0000000000..b92bcea5b0 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/api.ping.$id.ts @@ -0,0 +1,22 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { + makeServerRouteMarker, + type GlobalMiddlewareContext, +} from '../../../shared' + +export const Route = createFileRoute('/api/ping/$id')({ + server: { + handlers: { + GET: ({ params, context }) => { + const middlewareContext = (context ?? {}) as GlobalMiddlewareContext + + return Response.json({ + id: params.id, + marker: makeServerRouteMarker(params.id, middlewareContext), + requestTrace: middlewareContext.requestTrace, + requestTotal: middlewareContext.requestTotal, + }) + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/index.tsx b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/index.tsx new file mode 100644 index 0000000000..c293004539 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/index.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { echoPost } from '../fns' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
global-middleware
+} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/page.$id.tsx b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/page.$id.tsx new file mode 100644 index 0000000000..a5781b1a6a --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/routes/page.$id.tsx @@ -0,0 +1,22 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { + getGlobalMiddlewareContext, + makeDocumentMarker, + type GlobalMiddlewareContext, +} from '../../../shared' + +export const Route = createFileRoute('/page/$id')({ + beforeLoad: ({ serverContext }) => ({ + globalMiddlewareContext: (serverContext ?? {}) as GlobalMiddlewareContext, + }), + loader: ({ params, context }) => ({ + marker: makeDocumentMarker(params.id, getGlobalMiddlewareContext(context)), + }), + component: PageComponent, +}) + +function PageComponent() { + const data = Route.useLoaderData() + + return
{data().marker}
+} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts new file mode 100644 index 0000000000..a6f6214b82 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts @@ -0,0 +1,88 @@ +import { createMiddleware, createStart } from '@tanstack/solid-start' +import { getRequestMiddlewareCount } from '../../shared' +import type { GlobalMiddlewareContext } from '../../shared' + +function appendTrace( + trace: string | undefined, + fallback: string, + label: string, +) { + return `${trace ?? fallback}.${label}` +} + +const requestMiddlewareA = createMiddleware({ type: 'request' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + requestTrace: appendTrace(ctx.requestTrace, 'req', 'r1'), + requestTotal: (ctx.requestTotal ?? 0) + 1, + }, + }) + }, +) + +const requestMiddlewareB = createMiddleware({ type: 'request' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + requestTrace: appendTrace(ctx.requestTrace, 'req', 'r2'), + requestTotal: (ctx.requestTotal ?? 0) + 2, + }, + }) + }, +) + +const requestMiddlewareC = createMiddleware({ type: 'request' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + requestTrace: appendTrace(ctx.requestTrace, 'req', 'r3'), + requestTotal: (ctx.requestTotal ?? 0) + 3, + }, + }) + }, +) + +const requestMiddlewareSets: Array> = [ + [], + [requestMiddlewareA], + [requestMiddlewareA, requestMiddlewareB], + [requestMiddlewareA, requestMiddlewareB, requestMiddlewareC], +] + +const functionMiddlewareA = createMiddleware({ type: 'function' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + functionTrace: appendTrace(ctx.functionTrace, 'fn', 'f1'), + functionTotal: (ctx.functionTotal ?? 0) + 10, + }, + }) + }, +) + +const functionMiddlewareB = createMiddleware({ type: 'function' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + functionTrace: appendTrace(ctx.functionTrace, 'fn', 'f2'), + functionTotal: (ctx.functionTotal ?? 0) + 20, + }, + }) + }, +) + +export const startInstance = createStart(() => ({ + requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], + functionMiddleware: [functionMiddlewareA, functionMiddlewareB], +})) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/tsconfig.json b/benchmarks/ssr/scenarios/global-middleware/solid/tsconfig.json new file mode 100644 index 0000000000..dce3ceae30 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared.ts", + "../bench.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts b/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts new file mode 100644 index 0000000000..f3597b25d5 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr global-middleware (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/project.json b/benchmarks/ssr/scenarios/global-middleware/vue/project.json new file mode 100644 index 0000000000..6dbc003aae --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-global-middleware-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts new file mode 100644 index 0000000000..9660f29d07 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareDocumentLoop, + 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 document (vue)', async () => + runGlobalMiddlewareDocumentLoop(handler), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-fn.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-fn.bench.ts new file mode 100644 index 0000000000..297e8cee7b --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-fn.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerFnLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-fn (vue)', async () => + runGlobalMiddlewareServerFnLoop(handler, context), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-0-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-0-middleware.bench.ts new file mode 100644 index 0000000000..d023dd458a --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-0-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 0 middleware (vue)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 0), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts new file mode 100644 index 0000000000..5018163631 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 1 middleware (vue)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 1), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts new file mode 100644 index 0000000000..f9abd8eb60 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 2 middlewares (vue)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 2), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts new file mode 100644 index 0000000000..adcec3019f --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 3 middlewares (vue)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 3), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/fns.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/fns.ts new file mode 100644 index 0000000000..557f6ee849 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/fns.ts @@ -0,0 +1,34 @@ +import { createServerFn } from '@tanstack/vue-start' +import { makeServerFnMarker, type GlobalMiddlewareContext } from '../../shared' + +type Payload = { q: string; n: number; nested: { list: Array } } + +const validate = (input: unknown): Payload => { + const payload = input as Payload + + if ( + typeof payload?.q !== 'string' || + typeof payload?.n !== 'number' || + !Array.isArray(payload?.nested?.list) + ) { + throw new Error('invalid payload') + } + + return payload +} + +export const echoPost = createServerFn({ method: 'POST' }) + .validator(validate) + .handler(({ data, context }) => { + const middlewareContext = (context ?? {}) as GlobalMiddlewareContext + + return { + echoed: data, + marker: makeServerFnMarker(data.q, middlewareContext), + sum: + data.n + + (middlewareContext.requestTotal ?? 0) + + (middlewareContext.functionTotal ?? 0), + list: data.nested.list.map((item) => `global-${item}`), + } + }) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..3118848e4d --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts @@ -0,0 +1,123 @@ +/* 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 ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as PageIdRouteImport } from './routes/page.$id' +import { Route as ApiPingIdRouteImport } from './routes/api.ping.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + 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 ApiPingIdRoute = ApiPingIdRouteImport.update({ + id: '/api/ping/$id', + path: '/api/ping/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/page/$id': typeof PageIdRoute + '/api/ping/$id': typeof ApiPingIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/page/$id': typeof PageIdRoute + '/api/ping/$id': typeof ApiPingIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/page/$id': typeof PageIdRoute + '/api/ping/$id': typeof ApiPingIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' + id: '__root__' | '/' | '/api/fn-urls' | '/page/$id' | '/api/ping/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiFnUrlsRoute: typeof ApiFnUrlsRoute + PageIdRoute: typeof PageIdRoute + ApiPingIdRoute: typeof ApiPingIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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' + fullPath: '/page/$id' + preLoaderRoute: typeof PageIdRouteImport + parentRoute: typeof rootRouteImport + } + '/api/ping/$id': { + id: '/api/ping/$id' + path: '/api/ping/$id' + fullPath: '/api/ping/$id' + preLoaderRoute: typeof ApiPingIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiFnUrlsRoute: ApiFnUrlsRoute, + PageIdRoute: PageIdRoute, + ApiPingIdRoute: ApiPingIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { startInstance } from './start.ts' +declare module '@tanstack/vue-start' { + interface Register { + ssr: true + router: Awaited> + config: Awaited> + } +} diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/router.tsx b/benchmarks/ssr/scenarios/global-middleware/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..49422aac38 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/__root.tsx @@ -0,0 +1,26 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.fn-urls.ts new file mode 100644 index 0000000000..af51ea6aa3 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.fn-urls.ts @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { echoPost } from '../fns' + +export const Route = createFileRoute('/api/fn-urls')({ + server: { + handlers: { + GET: () => Response.json({ post: echoPost.url }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.ping.$id.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.ping.$id.ts new file mode 100644 index 0000000000..f599ce1e49 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/api.ping.$id.ts @@ -0,0 +1,22 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { + makeServerRouteMarker, + type GlobalMiddlewareContext, +} from '../../../shared' + +export const Route = createFileRoute('/api/ping/$id')({ + server: { + handlers: { + GET: ({ params, context }) => { + const middlewareContext = (context ?? {}) as GlobalMiddlewareContext + + return Response.json({ + id: params.id, + marker: makeServerRouteMarker(params.id, middlewareContext), + requestTrace: middlewareContext.requestTrace, + requestTotal: middlewareContext.requestTotal, + }) + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/index.tsx b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/index.tsx new file mode 100644 index 0000000000..85d3de69a4 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/index.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { echoPost } from '../fns' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
global-middleware
+} diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/page.$id.tsx b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/page.$id.tsx new file mode 100644 index 0000000000..6e837ef0a0 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/page.$id.tsx @@ -0,0 +1,25 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { + getGlobalMiddlewareContext, + makeDocumentMarker, + type GlobalMiddlewareContext, +} from '../../../shared' + +const PageComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () =>
{data.value.marker}
+ }, +}) + +export const Route = createFileRoute('/page/$id')({ + beforeLoad: ({ serverContext }) => ({ + globalMiddlewareContext: (serverContext ?? {}) as GlobalMiddlewareContext, + }), + loader: ({ params, context }) => ({ + marker: makeDocumentMarker(params.id, getGlobalMiddlewareContext(context)), + }), + component: PageComponent, +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts new file mode 100644 index 0000000000..6e4eb2c5ef --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts @@ -0,0 +1,88 @@ +import { createMiddleware, createStart } from '@tanstack/vue-start' +import { getRequestMiddlewareCount } from '../../shared' +import type { GlobalMiddlewareContext } from '../../shared' + +function appendTrace( + trace: string | undefined, + fallback: string, + label: string, +) { + return `${trace ?? fallback}.${label}` +} + +const requestMiddlewareA = createMiddleware({ type: 'request' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + requestTrace: appendTrace(ctx.requestTrace, 'req', 'r1'), + requestTotal: (ctx.requestTotal ?? 0) + 1, + }, + }) + }, +) + +const requestMiddlewareB = createMiddleware({ type: 'request' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + requestTrace: appendTrace(ctx.requestTrace, 'req', 'r2'), + requestTotal: (ctx.requestTotal ?? 0) + 2, + }, + }) + }, +) + +const requestMiddlewareC = createMiddleware({ type: 'request' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + requestTrace: appendTrace(ctx.requestTrace, 'req', 'r3'), + requestTotal: (ctx.requestTotal ?? 0) + 3, + }, + }) + }, +) + +const requestMiddlewareSets: Array> = [ + [], + [requestMiddlewareA], + [requestMiddlewareA, requestMiddlewareB], + [requestMiddlewareA, requestMiddlewareB, requestMiddlewareC], +] + +const functionMiddlewareA = createMiddleware({ type: 'function' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + functionTrace: appendTrace(ctx.functionTrace, 'fn', 'f1'), + functionTotal: (ctx.functionTotal ?? 0) + 10, + }, + }) + }, +) + +const functionMiddlewareB = createMiddleware({ type: 'function' }).server( + ({ next, context }) => { + const ctx = (context ?? {}) as GlobalMiddlewareContext + + return next({ + context: { + functionTrace: appendTrace(ctx.functionTrace, 'fn', 'f2'), + functionTotal: (ctx.functionTotal ?? 0) + 20, + }, + }) + }, +) + +export const startInstance = createStart(() => ({ + requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], + functionMiddleware: [functionMiddlewareA, functionMiddlewareB], +})) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/tsconfig.json b/benchmarks/ssr/scenarios/global-middleware/vue/tsconfig.json new file mode 100644 index 0000000000..56800fd29e --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared.ts", + "../bench.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts b/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts new file mode 100644 index 0000000000..8e29c5ee98 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr global-middleware (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/head/react/project.json b/benchmarks/ssr/scenarios/head/react/project.json new file mode 100644 index 0000000000..093046fe39 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-head-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/head/react/speed.bench.ts b/benchmarks/ssr/scenarios/head/react/speed.bench.ts new file mode 100644 index 0000000000..f75008506e --- /dev/null +++ b/benchmarks/ssr/scenarios/head/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertHeadSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr head (react)', async () => runHeadLoop(handler)).run( + headBenchOptions, + ) +}) diff --git a/benchmarks/ssr/scenarios/head/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/head/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..3786e2137d --- /dev/null +++ b/benchmarks/ssr/scenarios/head/react/src/routeTree.gen.ts @@ -0,0 +1,120 @@ +/* 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 HARouteImport } from './routes/h.$a' +import { Route as HABRouteImport } from './routes/h.$a.$b' +import { Route as HABCRouteImport } from './routes/h.$a.$b.$c' + +const HARoute = HARouteImport.update({ + id: '/h/$a', + path: '/h/$a', + getParentRoute: () => rootRouteImport, +} as any) +const HABRoute = HABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => HARoute, +} as any) +const HABCRoute = HABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => HABRoute, +} as any) + +export interface FileRoutesByFullPath { + '/h/$a': typeof HARouteWithChildren + '/h/$a/$b': typeof HABRouteWithChildren + '/h/$a/$b/$c': typeof HABCRoute +} +export interface FileRoutesByTo { + '/h/$a': typeof HARouteWithChildren + '/h/$a/$b': typeof HABRouteWithChildren + '/h/$a/$b/$c': typeof HABCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/h/$a': typeof HARouteWithChildren + '/h/$a/$b': typeof HABRouteWithChildren + '/h/$a/$b/$c': typeof HABCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' + fileRoutesByTo: FileRoutesByTo + to: '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' + id: '__root__' | '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + HARoute: typeof HARouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/h/$a': { + id: '/h/$a' + path: '/h/$a' + fullPath: '/h/$a' + preLoaderRoute: typeof HARouteImport + parentRoute: typeof rootRouteImport + } + '/h/$a/$b': { + id: '/h/$a/$b' + path: '/$b' + fullPath: '/h/$a/$b' + preLoaderRoute: typeof HABRouteImport + parentRoute: typeof HARoute + } + '/h/$a/$b/$c': { + id: '/h/$a/$b/$c' + path: '/$c' + fullPath: '/h/$a/$b/$c' + preLoaderRoute: typeof HABCRouteImport + parentRoute: typeof HABRoute + } + } +} + +interface HABRouteChildren { + HABCRoute: typeof HABCRoute +} + +const HABRouteChildren: HABRouteChildren = { + HABCRoute: HABCRoute, +} + +const HABRouteWithChildren = HABRoute._addFileChildren(HABRouteChildren) + +interface HARouteChildren { + HABRoute: typeof HABRouteWithChildren +} + +const HARouteChildren: HARouteChildren = { + HABRoute: HABRouteWithChildren, +} + +const HARouteWithChildren = HARoute._addFileChildren(HARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + HARoute: HARouteWithChildren, +} +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/benchmarks/ssr/scenarios/head/react/src/router.tsx b/benchmarks/ssr/scenarios/head/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/scenarios/head/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/head/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/head/react/src/routes/__root.tsx new file mode 100644 index 0000000000..93f68352ab --- /dev/null +++ b/benchmarks/ssr/scenarios/head/react/src/routes/__root.tsx @@ -0,0 +1,35 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { name: 'application-name', content: 'SSR head benchmark' }, + { name: 'description', content: 'Head-heavy SSR benchmark scenario' }, + { name: 'theme-color', content: '#111827' }, + { property: 'og:type', content: 'website' }, + ], + }), + component: RootComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.$c.tsx b/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.$c.tsx new file mode 100644 index 0000000000..ee39349452 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.$c.tsx @@ -0,0 +1,26 @@ +import { createFileRoute } from '@tanstack/react-router' + +const dedupedMetaName = 'head-benchmark-shared' + +export const Route = createFileRoute('/h/$a/$b/$c')({ + head: ({ params }) => ({ + meta: [ + { title: `SSR Head L3 ${params.a} ${params.b} ${params.c}` }, + ...Array.from({ length: 10 }, (_, index) => ({ + name: index === 0 ? dedupedMetaName : `level-3-meta-${index}`, + content: + index === 0 ? `shared-${params.c}-level-3` : `c-${params.c}-${index}`, + })), + ], + links: Array.from({ length: 4 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/img/${params.c}-${index}.png`, + })), + }), + component: LevelCComponent, +}) + +function LevelCComponent() { + return

head-level-c

+} diff --git a/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.tsx b/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.tsx new file mode 100644 index 0000000000..b0658c87eb --- /dev/null +++ b/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.$b.tsx @@ -0,0 +1,31 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +const dedupedMetaName = 'head-benchmark-shared' + +export const Route = createFileRoute('/h/$a/$b')({ + head: ({ params }) => ({ + meta: [ + { title: `SSR Head L2 ${params.a} ${params.b}` }, + ...Array.from({ length: 10 }, (_, index) => ({ + name: index === 0 ? dedupedMetaName : `level-2-meta-${index}`, + content: + index === 0 ? `shared-${params.b}-level-2` : `c-${params.b}-${index}`, + })), + ], + links: Array.from({ length: 4 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/img/${params.b}-${index}.png`, + })), + }), + component: LevelBComponent, +}) + +function LevelBComponent() { + return ( + <> +

head-level-b

+ + + ) +} diff --git a/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.tsx b/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.tsx new file mode 100644 index 0000000000..acd5f3c3ce --- /dev/null +++ b/benchmarks/ssr/scenarios/head/react/src/routes/h.$a.tsx @@ -0,0 +1,31 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +const dedupedMetaName = 'head-benchmark-shared' + +export const Route = createFileRoute('/h/$a')({ + head: ({ params }) => ({ + meta: [ + { title: `SSR Head L1 ${params.a}` }, + ...Array.from({ length: 10 }, (_, index) => ({ + name: index === 0 ? dedupedMetaName : `level-1-meta-${index}`, + content: + index === 0 ? `shared-${params.a}-level-1` : `c-${params.a}-${index}`, + })), + ], + links: Array.from({ length: 4 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/img/${params.a}-${index}.png`, + })), + }), + component: LevelAComponent, +}) + +function LevelAComponent() { + return ( + <> +

head-level-a

+ + + ) +} diff --git a/benchmarks/ssr/scenarios/head/react/tsconfig.json b/benchmarks/ssr/scenarios/head/react/tsconfig.json new file mode 100644 index 0000000000..91027bfc88 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/react/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/head/react/vite.config.ts b/benchmarks/ssr/scenarios/head/react/vite.config.ts new file mode 100644 index 0000000000..d24fc850a1 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr head (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/head/shared.ts b/benchmarks/ssr/scenarios/head/shared.ts new file mode 100644 index 0000000000..033ca47c22 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/shared.ts @@ -0,0 +1,55 @@ +import { expect } from 'vitest' +import { randomSegment, runRequestLoop } from '../../bench-utils' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +const benchmarkSeed = 0xdecafbad +const origin = 'http://localhost' +const dedupedMetaName = 'head-benchmark-shared' +const headLoopTotalRequests = 32 + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +export const headBenchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} + +function buildHeadRequest(random: () => number) { + return new Request( + `${origin}/h/${randomSegment(random)}/${randomSegment(random)}/${randomSegment(random)}`, + requestInit, + ) +} + +export function runHeadLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: headLoopTotalRequests, + buildRequest: buildHeadRequest, + }) +} + +export async function assertHeadSanity(handler: StartRequestHandler) { + const a = 'sanity-a' + const b = 'sanity-b' + const c = 'sanity-c' + const response = await handler.fetch( + new Request(`${origin}/h/${a}/${b}/${c}`, requestInit), + ) + const body = await response.text() + const dedupedMetaCount = body.split(dedupedMetaName).length - 1 + + expect(response.status).toBe(200) + expect(body).toContain(`c-${c}-9`) + expect(dedupedMetaCount).toBe(1) + expect(body).toContain(`SSR Head L3 ${a} ${b} ${c}`) +} diff --git a/benchmarks/ssr/scenarios/head/solid/project.json b/benchmarks/ssr/scenarios/head/solid/project.json new file mode 100644 index 0000000000..c6df39998b --- /dev/null +++ b/benchmarks/ssr/scenarios/head/solid/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-head-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/head/solid/speed.bench.ts b/benchmarks/ssr/scenarios/head/solid/speed.bench.ts new file mode 100644 index 0000000000..333e2f091b --- /dev/null +++ b/benchmarks/ssr/scenarios/head/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertHeadSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr head (solid)', async () => runHeadLoop(handler)).run( + headBenchOptions, + ) +}) diff --git a/benchmarks/ssr/scenarios/head/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/head/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..ceba45e94d --- /dev/null +++ b/benchmarks/ssr/scenarios/head/solid/src/routeTree.gen.ts @@ -0,0 +1,120 @@ +/* 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 HARouteImport } from './routes/h.$a' +import { Route as HABRouteImport } from './routes/h.$a.$b' +import { Route as HABCRouteImport } from './routes/h.$a.$b.$c' + +const HARoute = HARouteImport.update({ + id: '/h/$a', + path: '/h/$a', + getParentRoute: () => rootRouteImport, +} as any) +const HABRoute = HABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => HARoute, +} as any) +const HABCRoute = HABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => HABRoute, +} as any) + +export interface FileRoutesByFullPath { + '/h/$a': typeof HARouteWithChildren + '/h/$a/$b': typeof HABRouteWithChildren + '/h/$a/$b/$c': typeof HABCRoute +} +export interface FileRoutesByTo { + '/h/$a': typeof HARouteWithChildren + '/h/$a/$b': typeof HABRouteWithChildren + '/h/$a/$b/$c': typeof HABCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/h/$a': typeof HARouteWithChildren + '/h/$a/$b': typeof HABRouteWithChildren + '/h/$a/$b/$c': typeof HABCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' + fileRoutesByTo: FileRoutesByTo + to: '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' + id: '__root__' | '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + HARoute: typeof HARouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/h/$a': { + id: '/h/$a' + path: '/h/$a' + fullPath: '/h/$a' + preLoaderRoute: typeof HARouteImport + parentRoute: typeof rootRouteImport + } + '/h/$a/$b': { + id: '/h/$a/$b' + path: '/$b' + fullPath: '/h/$a/$b' + preLoaderRoute: typeof HABRouteImport + parentRoute: typeof HARoute + } + '/h/$a/$b/$c': { + id: '/h/$a/$b/$c' + path: '/$c' + fullPath: '/h/$a/$b/$c' + preLoaderRoute: typeof HABCRouteImport + parentRoute: typeof HABRoute + } + } +} + +interface HABRouteChildren { + HABCRoute: typeof HABCRoute +} + +const HABRouteChildren: HABRouteChildren = { + HABCRoute: HABCRoute, +} + +const HABRouteWithChildren = HABRoute._addFileChildren(HABRouteChildren) + +interface HARouteChildren { + HABRoute: typeof HABRouteWithChildren +} + +const HARouteChildren: HARouteChildren = { + HABRoute: HABRouteWithChildren, +} + +const HARouteWithChildren = HARoute._addFileChildren(HARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + HARoute: HARouteWithChildren, +} +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/benchmarks/ssr/scenarios/head/solid/src/router.tsx b/benchmarks/ssr/scenarios/head/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/scenarios/head/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/head/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/head/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..2dde9d0ddf --- /dev/null +++ b/benchmarks/ssr/scenarios/head/solid/src/routes/__root.tsx @@ -0,0 +1,35 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { name: 'application-name', content: 'SSR head benchmark' }, + { name: 'description', content: 'Head-heavy SSR benchmark scenario' }, + { name: 'theme-color', content: '#111827' }, + { property: 'og:type', content: 'website' }, + ], + }), + component: RootComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.$c.tsx b/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.$c.tsx new file mode 100644 index 0000000000..7ec132e9a6 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.$c.tsx @@ -0,0 +1,26 @@ +import { createFileRoute } from '@tanstack/solid-router' + +const dedupedMetaName = 'head-benchmark-shared' + +export const Route = createFileRoute('/h/$a/$b/$c')({ + head: ({ params }) => ({ + meta: [ + { title: `SSR Head L3 ${params.a} ${params.b} ${params.c}` }, + ...Array.from({ length: 10 }, (_, index) => ({ + name: index === 0 ? dedupedMetaName : `level-3-meta-${index}`, + content: + index === 0 ? `shared-${params.c}-level-3` : `c-${params.c}-${index}`, + })), + ], + links: Array.from({ length: 4 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/img/${params.c}-${index}.png`, + })), + }), + component: LevelCComponent, +}) + +function LevelCComponent() { + return

head-level-c

+} diff --git a/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.tsx b/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.tsx new file mode 100644 index 0000000000..25d443ad4e --- /dev/null +++ b/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.$b.tsx @@ -0,0 +1,31 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +const dedupedMetaName = 'head-benchmark-shared' + +export const Route = createFileRoute('/h/$a/$b')({ + head: ({ params }) => ({ + meta: [ + { title: `SSR Head L2 ${params.a} ${params.b}` }, + ...Array.from({ length: 10 }, (_, index) => ({ + name: index === 0 ? dedupedMetaName : `level-2-meta-${index}`, + content: + index === 0 ? `shared-${params.b}-level-2` : `c-${params.b}-${index}`, + })), + ], + links: Array.from({ length: 4 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/img/${params.b}-${index}.png`, + })), + }), + component: LevelBComponent, +}) + +function LevelBComponent() { + return ( + <> +

head-level-b

+ + + ) +} diff --git a/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.tsx b/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.tsx new file mode 100644 index 0000000000..6c994ffed6 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/solid/src/routes/h.$a.tsx @@ -0,0 +1,31 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +const dedupedMetaName = 'head-benchmark-shared' + +export const Route = createFileRoute('/h/$a')({ + head: ({ params }) => ({ + meta: [ + { title: `SSR Head L1 ${params.a}` }, + ...Array.from({ length: 10 }, (_, index) => ({ + name: index === 0 ? dedupedMetaName : `level-1-meta-${index}`, + content: + index === 0 ? `shared-${params.a}-level-1` : `c-${params.a}-${index}`, + })), + ], + links: Array.from({ length: 4 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/img/${params.a}-${index}.png`, + })), + }), + component: LevelAComponent, +}) + +function LevelAComponent() { + return ( + <> +

head-level-a

+ + + ) +} diff --git a/benchmarks/ssr/scenarios/head/solid/tsconfig.json b/benchmarks/ssr/scenarios/head/solid/tsconfig.json new file mode 100644 index 0000000000..b1806caa67 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/solid/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/head/solid/vite.config.ts b/benchmarks/ssr/scenarios/head/solid/vite.config.ts new file mode 100644 index 0000000000..7a870bbd77 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr head (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/head/vue/project.json b/benchmarks/ssr/scenarios/head/vue/project.json new file mode 100644 index 0000000000..62b17b1216 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-head-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/head/vue/speed.bench.ts b/benchmarks/ssr/scenarios/head/vue/speed.bench.ts new file mode 100644 index 0000000000..936735a909 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertHeadSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr head (vue)', async () => runHeadLoop(handler)).run( + headBenchOptions, + ) +}) diff --git a/benchmarks/ssr/scenarios/head/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/head/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..9ec1029664 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/vue/src/routeTree.gen.ts @@ -0,0 +1,120 @@ +/* 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 HARouteImport } from './routes/h.$a' +import { Route as HABRouteImport } from './routes/h.$a.$b' +import { Route as HABCRouteImport } from './routes/h.$a.$b.$c' + +const HARoute = HARouteImport.update({ + id: '/h/$a', + path: '/h/$a', + getParentRoute: () => rootRouteImport, +} as any) +const HABRoute = HABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => HARoute, +} as any) +const HABCRoute = HABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => HABRoute, +} as any) + +export interface FileRoutesByFullPath { + '/h/$a': typeof HARouteWithChildren + '/h/$a/$b': typeof HABRouteWithChildren + '/h/$a/$b/$c': typeof HABCRoute +} +export interface FileRoutesByTo { + '/h/$a': typeof HARouteWithChildren + '/h/$a/$b': typeof HABRouteWithChildren + '/h/$a/$b/$c': typeof HABCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/h/$a': typeof HARouteWithChildren + '/h/$a/$b': typeof HABRouteWithChildren + '/h/$a/$b/$c': typeof HABCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' + fileRoutesByTo: FileRoutesByTo + to: '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' + id: '__root__' | '/h/$a' | '/h/$a/$b' | '/h/$a/$b/$c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + HARoute: typeof HARouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/h/$a': { + id: '/h/$a' + path: '/h/$a' + fullPath: '/h/$a' + preLoaderRoute: typeof HARouteImport + parentRoute: typeof rootRouteImport + } + '/h/$a/$b': { + id: '/h/$a/$b' + path: '/$b' + fullPath: '/h/$a/$b' + preLoaderRoute: typeof HABRouteImport + parentRoute: typeof HARoute + } + '/h/$a/$b/$c': { + id: '/h/$a/$b/$c' + path: '/$c' + fullPath: '/h/$a/$b/$c' + preLoaderRoute: typeof HABCRouteImport + parentRoute: typeof HABRoute + } + } +} + +interface HABRouteChildren { + HABCRoute: typeof HABCRoute +} + +const HABRouteChildren: HABRouteChildren = { + HABCRoute: HABCRoute, +} + +const HABRouteWithChildren = HABRoute._addFileChildren(HABRouteChildren) + +interface HARouteChildren { + HABRoute: typeof HABRouteWithChildren +} + +const HARouteChildren: HARouteChildren = { + HABRoute: HABRouteWithChildren, +} + +const HARouteWithChildren = HARoute._addFileChildren(HARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + HARoute: HARouteWithChildren, +} +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/benchmarks/ssr/scenarios/head/vue/src/router.tsx b/benchmarks/ssr/scenarios/head/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/head/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/head/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..9b95d2c48e --- /dev/null +++ b/benchmarks/ssr/scenarios/head/vue/src/routes/__root.tsx @@ -0,0 +1,37 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { name: 'application-name', content: 'SSR head benchmark' }, + { name: 'description', content: 'Head-heavy SSR benchmark scenario' }, + { name: 'theme-color', content: '#111827' }, + { property: 'og:type', content: 'website' }, + ], + }), + component: RootComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.$c.tsx b/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.$c.tsx new file mode 100644 index 0000000000..91b8f03f7d --- /dev/null +++ b/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.$c.tsx @@ -0,0 +1,26 @@ +import { createFileRoute } from '@tanstack/vue-router' + +const dedupedMetaName = 'head-benchmark-shared' + +export const Route = createFileRoute('/h/$a/$b/$c')({ + head: ({ params }) => ({ + meta: [ + { title: `SSR Head L3 ${params.a} ${params.b} ${params.c}` }, + ...Array.from({ length: 10 }, (_, index) => ({ + name: index === 0 ? dedupedMetaName : `level-3-meta-${index}`, + content: + index === 0 ? `shared-${params.c}-level-3` : `c-${params.c}-${index}`, + })), + ], + links: Array.from({ length: 4 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/img/${params.c}-${index}.png`, + })), + }), + component: LevelCComponent, +}) + +function LevelCComponent() { + return

head-level-c

+} diff --git a/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.tsx b/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.tsx new file mode 100644 index 0000000000..e92a619435 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.$b.tsx @@ -0,0 +1,31 @@ +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const dedupedMetaName = 'head-benchmark-shared' + +export const Route = createFileRoute('/h/$a/$b')({ + head: ({ params }) => ({ + meta: [ + { title: `SSR Head L2 ${params.a} ${params.b}` }, + ...Array.from({ length: 10 }, (_, index) => ({ + name: index === 0 ? dedupedMetaName : `level-2-meta-${index}`, + content: + index === 0 ? `shared-${params.b}-level-2` : `c-${params.b}-${index}`, + })), + ], + links: Array.from({ length: 4 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/img/${params.b}-${index}.png`, + })), + }), + component: LevelBComponent, +}) + +function LevelBComponent() { + return ( + <> +

head-level-b

+ + + ) +} diff --git a/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.tsx b/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.tsx new file mode 100644 index 0000000000..ddf407e9ae --- /dev/null +++ b/benchmarks/ssr/scenarios/head/vue/src/routes/h.$a.tsx @@ -0,0 +1,31 @@ +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const dedupedMetaName = 'head-benchmark-shared' + +export const Route = createFileRoute('/h/$a')({ + head: ({ params }) => ({ + meta: [ + { title: `SSR Head L1 ${params.a}` }, + ...Array.from({ length: 10 }, (_, index) => ({ + name: index === 0 ? dedupedMetaName : `level-1-meta-${index}`, + content: + index === 0 ? `shared-${params.a}-level-1` : `c-${params.a}-${index}`, + })), + ], + links: Array.from({ length: 4 }, (_, index) => ({ + rel: 'preload', + as: 'image', + href: `/img/${params.a}-${index}.png`, + })), + }), + component: LevelAComponent, +}) + +function LevelAComponent() { + return ( + <> +

head-level-a

+ + + ) +} diff --git a/benchmarks/ssr/scenarios/head/vue/tsconfig.json b/benchmarks/ssr/scenarios/head/vue/tsconfig.json new file mode 100644 index 0000000000..4fe3ccecb1 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/vue/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/head/vue/vite.config.ts b/benchmarks/ssr/scenarios/head/vue/vite.config.ts new file mode 100644 index 0000000000..1434d26069 --- /dev/null +++ b/benchmarks/ssr/scenarios/head/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr head (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/loaders/react/project.json b/benchmarks/ssr/scenarios/loaders/react/project.json new file mode 100644 index 0000000000..0455f80c87 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-loaders-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts new file mode 100644 index 0000000000..7acd43c635 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertLoadersSanity, + benchOptions, + runLoadersLoop, + type StartRequestHandler, +} from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertLoadersSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr loaders (react)', async () => runLoadersLoop(handler)).run( + benchOptions, + ) +}) diff --git a/benchmarks/ssr/scenarios/loaders/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/loaders/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..068b5a5433 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/react/src/routeTree.gen.ts @@ -0,0 +1,120 @@ +/* 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 ARouteImport } from './routes/$a' +import { Route as ABRouteImport } from './routes/$a.$b' +import { Route as ABCRouteImport } from './routes/$a.$b.$c' + +const ARoute = ARouteImport.update({ + id: '/$a', + path: '/$a', + getParentRoute: () => rootRouteImport, +} as any) +const ABRoute = ABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => ARoute, +} as any) +const ABCRoute = ABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => ABRoute, +} as any) + +export interface FileRoutesByFullPath { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRoutesByTo { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' + fileRoutesByTo: FileRoutesByTo + to: '/$a' | '/$a/$b' | '/$a/$b/$c' + id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/$a': { + id: '/$a' + path: '/$a' + fullPath: '/$a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + '/$a/$b': { + id: '/$a/$b' + path: '/$b' + fullPath: '/$a/$b' + preLoaderRoute: typeof ABRouteImport + parentRoute: typeof ARoute + } + '/$a/$b/$c': { + id: '/$a/$b/$c' + path: '/$c' + fullPath: '/$a/$b/$c' + preLoaderRoute: typeof ABCRouteImport + parentRoute: typeof ABRoute + } + } +} + +interface ABRouteChildren { + ABCRoute: typeof ABCRoute +} + +const ABRouteChildren: ABRouteChildren = { + ABCRoute: ABCRoute, +} + +const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) + +interface ARouteChildren { + ABRoute: typeof ABRouteWithChildren +} + +const ARouteChildren: ARouteChildren = { + ABRoute: ABRouteWithChildren, +} + +const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARouteWithChildren, +} +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/benchmarks/ssr/scenarios/loaders/react/src/router.tsx b/benchmarks/ssr/scenarios/loaders/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.$c.tsx new file mode 100644 index 0000000000..746a26aeb6 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.$c.tsx @@ -0,0 +1,32 @@ +import { createFileRoute } from '@tanstack/react-router' +import { makeLevelData } from '../../../shared-data' + +export const Route = createFileRoute('/$a/$b/$c')({ + beforeLoad: ({ params, context }) => { + void context + + return { ctxC: `v-${params.c}` } + }, + loaderDeps: ({ search }) => ({ page: search.page }), + loader: async ({ params, deps, context }) => { + void context + + return makeLevelData(params.c, deps.page) + }, + component: LevelCComponent, +}) + +function LevelCComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data.meta.label}

+
    + {data.items.slice(0, 10).map((item) => ( +
  • {item.name}
  • + ))} +
+
+ ) +} diff --git a/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.tsx new file mode 100644 index 0000000000..79c10c06b0 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.$b.tsx @@ -0,0 +1,33 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { makeLevelData } from '../../../shared-data' + +export const Route = createFileRoute('/$a/$b')({ + beforeLoad: ({ params, context }) => { + void context + + return { ctxB: `v-${params.b}` } + }, + loaderDeps: ({ search }) => ({ page: search.page }), + loader: async ({ params, deps, context }) => { + void context + + return makeLevelData(params.b, deps.page) + }, + component: LevelBComponent, +}) + +function LevelBComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data.meta.label}

+
    + {data.items.slice(0, 10).map((item) => ( +
  • {item.name}
  • + ))} +
+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.tsx b/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.tsx new file mode 100644 index 0000000000..980a495c32 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/react/src/routes/$a.tsx @@ -0,0 +1,33 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { makeLevelData } from '../../../shared-data' + +export const Route = createFileRoute('/$a')({ + beforeLoad: ({ params, context }) => { + void context + + return { ctxA: `v-${params.a}` } + }, + loaderDeps: ({ search }) => ({ page: search.page }), + loader: async ({ params, deps, context }) => { + void context + + return makeLevelData(params.a, deps.page) + }, + component: LevelAComponent, +}) + +function LevelAComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data.meta.label}

+
    + {data.items.slice(0, 10).map((item) => ( +
  • {item.name}
  • + ))} +
+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/loaders/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/loaders/react/src/routes/__root.tsx new file mode 100644 index 0000000000..001639cb39 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/react/src/routes/__root.tsx @@ -0,0 +1,28 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s: Record) => ({ + page: typeof s.page === 'number' ? s.page : 0, + tags: Array.isArray(s.tags) ? (s.tags as Array) : [], + }), +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/loaders/react/tsconfig.json b/benchmarks/ssr/scenarios/loaders/react/tsconfig.json new file mode 100644 index 0000000000..8800818162 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/react/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared-data.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/loaders/react/vite.config.ts b/benchmarks/ssr/scenarios/loaders/react/vite.config.ts new file mode 100644 index 0000000000..e761426c84 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr loaders (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/loaders/shared-bench.ts b/benchmarks/ssr/scenarios/loaders/shared-bench.ts new file mode 100644 index 0000000000..f52c51dccd --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/shared-bench.ts @@ -0,0 +1,75 @@ +import { makeLevelData } from './shared-data' +import { randomSegment, runRequestLoop } from '../../bench-utils' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +const benchmarkSeed = 0xdecafbad +const loadersLoopTotalRequests = 16 + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +function buildLoaderRequest(random: () => number, index: number) { + const suffix = index.toString(36) + const a = `${randomSegment(random)}-${suffix}` + const b = `${randomSegment(random)}-${suffix}` + const c = `${randomSegment(random)}-${suffix}` + const page = Math.floor(random() * 10) + const tags = JSON.stringify([ + `t-${randomSegment(random)}-${suffix}`, + `t-${randomSegment(random)}-${suffix}`, + ]) + + return new Request( + `http://localhost/${a}/${b}/${c}?page=${page}&tags=${encodeURIComponent(tags)}`, + requestInit, + ) +} + +export async function assertLoadersSanity(handler: StartRequestHandler) { + const page = 3 + const leafSource = 'c-sanity' + const tags = JSON.stringify(['t-x', 't-y']) + const response = await handler.fetch( + new Request( + `http://localhost/a-sanity/b-sanity/${leafSource}?page=${page}&tags=${encodeURIComponent(tags)}`, + requestInit, + ), + ) + const body = await response.text() + const leafMarker = makeLevelData(leafSource, page).items[0]?.name + + if (response.status !== 200) { + throw new Error( + `Expected setup request status 200, received ${response.status}`, + ) + } + + if (!leafMarker || !body.includes(leafMarker)) { + throw new Error('Expected setup response to include the leaf loader item') + } + + if (!body.includes('$_TSR')) { + throw new Error('Expected setup response to include the dehydration marker') + } +} + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} + +export function runLoadersLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: loadersLoopTotalRequests, + buildRequest: buildLoaderRequest, + }) +} diff --git a/benchmarks/ssr/scenarios/loaders/shared-data.ts b/benchmarks/ssr/scenarios/loaders/shared-data.ts new file mode 100644 index 0000000000..d907f7d66c --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/shared-data.ts @@ -0,0 +1,54 @@ +export interface LevelDataItem { + id: string + name: string + flags: number +} + +export interface LevelData { + items: Array + meta: { + source: string + page: number + label: string + } +} + +function hashLevelInput(input: string, salt: number) { + let value = salt >>> 0 + + for (let index = 0; index < input.length; index++) { + value = (value * 33 + input.charCodeAt(index) + index) >>> 0 + } + + for (let index = 0; index < 16; index++) { + value = (value ^ (value << 13)) >>> 0 + value = (value ^ (value >> 17)) >>> 0 + value = (value ^ (value << 5)) >>> 0 + } + + return value +} + +export function makeLevelData(source: string, page: number): LevelData { + const safePage = page | 0 + const seedInput = `${source}:${safePage}` + const seed = hashLevelInput(seedInput, 0x9e3779b9) + + return { + items: Array.from({ length: 50 }, (_, index) => { + const hash = hashLevelInput(`${seedInput}:${index}`, seed + index) + const hashLabel = (hash & 0xffff).toString(36) + + return { + id: `${index.toString(36)}-${hashLabel}`, + name: `${source}:${safePage}:item-${index}`, + flags: hash & 15, + } + }), + meta: { + source, + page: safePage, + label: `source ${source} page ${safePage}`, + }, + } +} diff --git a/benchmarks/ssr/scenarios/loaders/solid/project.json b/benchmarks/ssr/scenarios/loaders/solid/project.json new file mode 100644 index 0000000000..2cb0e92acd --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/solid/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-loaders-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts new file mode 100644 index 0000000000..7fc8d88389 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertLoadersSanity, + benchOptions, + runLoadersLoop, + type StartRequestHandler, +} from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertLoadersSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr loaders (solid)', async () => runLoadersLoop(handler)).run( + benchOptions, + ) +}) diff --git a/benchmarks/ssr/scenarios/loaders/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/loaders/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..7b299cfcd1 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/solid/src/routeTree.gen.ts @@ -0,0 +1,120 @@ +/* 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 ARouteImport } from './routes/$a' +import { Route as ABRouteImport } from './routes/$a.$b' +import { Route as ABCRouteImport } from './routes/$a.$b.$c' + +const ARoute = ARouteImport.update({ + id: '/$a', + path: '/$a', + getParentRoute: () => rootRouteImport, +} as any) +const ABRoute = ABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => ARoute, +} as any) +const ABCRoute = ABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => ABRoute, +} as any) + +export interface FileRoutesByFullPath { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRoutesByTo { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' + fileRoutesByTo: FileRoutesByTo + to: '/$a' | '/$a/$b' | '/$a/$b/$c' + id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/$a': { + id: '/$a' + path: '/$a' + fullPath: '/$a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + '/$a/$b': { + id: '/$a/$b' + path: '/$b' + fullPath: '/$a/$b' + preLoaderRoute: typeof ABRouteImport + parentRoute: typeof ARoute + } + '/$a/$b/$c': { + id: '/$a/$b/$c' + path: '/$c' + fullPath: '/$a/$b/$c' + preLoaderRoute: typeof ABCRouteImport + parentRoute: typeof ABRoute + } + } +} + +interface ABRouteChildren { + ABCRoute: typeof ABCRoute +} + +const ABRouteChildren: ABRouteChildren = { + ABCRoute: ABCRoute, +} + +const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) + +interface ARouteChildren { + ABRoute: typeof ABRouteWithChildren +} + +const ARouteChildren: ARouteChildren = { + ABRoute: ABRouteWithChildren, +} + +const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARouteWithChildren, +} +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/benchmarks/ssr/scenarios/loaders/solid/src/router.tsx b/benchmarks/ssr/scenarios/loaders/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.$c.tsx new file mode 100644 index 0000000000..9ead32440a --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.$c.tsx @@ -0,0 +1,34 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { makeLevelData } from '../../../shared-data' + +export const Route = createFileRoute('/$a/$b/$c')({ + beforeLoad: ({ params, context }) => { + void context + + return { ctxC: `v-${params.c}` } + }, + loaderDeps: ({ search }) => ({ page: search.page }), + loader: async ({ params, deps, context }) => { + void context + + return makeLevelData(params.c, deps.page) + }, + component: LevelCComponent, +}) + +function LevelCComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data().meta.label}

+
    + {data() + .items.slice(0, 10) + .map((item) => ( +
  • {item.name}
  • + ))} +
+
+ ) +} diff --git a/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.tsx new file mode 100644 index 0000000000..c0abf3da87 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.$b.tsx @@ -0,0 +1,35 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { makeLevelData } from '../../../shared-data' + +export const Route = createFileRoute('/$a/$b')({ + beforeLoad: ({ params, context }) => { + void context + + return { ctxB: `v-${params.b}` } + }, + loaderDeps: ({ search }) => ({ page: search.page }), + loader: async ({ params, deps, context }) => { + void context + + return makeLevelData(params.b, deps.page) + }, + component: LevelBComponent, +}) + +function LevelBComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data().meta.label}

+
    + {data() + .items.slice(0, 10) + .map((item) => ( +
  • {item.name}
  • + ))} +
+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.tsx b/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.tsx new file mode 100644 index 0000000000..d4608523b8 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/solid/src/routes/$a.tsx @@ -0,0 +1,35 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { makeLevelData } from '../../../shared-data' + +export const Route = createFileRoute('/$a')({ + beforeLoad: ({ params, context }) => { + void context + + return { ctxA: `v-${params.a}` } + }, + loaderDeps: ({ search }) => ({ page: search.page }), + loader: async ({ params, deps, context }) => { + void context + + return makeLevelData(params.a, deps.page) + }, + component: LevelAComponent, +}) + +function LevelAComponent() { + const data = Route.useLoaderData() + + return ( +
+

{data().meta.label}

+
    + {data() + .items.slice(0, 10) + .map((item) => ( +
  • {item.name}
  • + ))} +
+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/loaders/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/loaders/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..2f4b1de410 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/solid/src/routes/__root.tsx @@ -0,0 +1,28 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s: Record) => ({ + page: typeof s.page === 'number' ? s.page : 0, + tags: Array.isArray(s.tags) ? (s.tags as Array) : [], + }), +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/loaders/solid/tsconfig.json b/benchmarks/ssr/scenarios/loaders/solid/tsconfig.json new file mode 100644 index 0000000000..47f264ba4f --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/solid/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared-data.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts b/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts new file mode 100644 index 0000000000..64f52159c3 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr loaders (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/loaders/vue/project.json b/benchmarks/ssr/scenarios/loaders/vue/project.json new file mode 100644 index 0000000000..2a98cb57f9 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-loaders-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts new file mode 100644 index 0000000000..321350d98c --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertLoadersSanity, + benchOptions, + runLoadersLoop, + type StartRequestHandler, +} from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertLoadersSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr loaders (vue)', async () => runLoadersLoop(handler)).run( + benchOptions, + ) +}) diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/loaders/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..24ee6c3b9d --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/vue/src/routeTree.gen.ts @@ -0,0 +1,120 @@ +/* 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 ARouteImport } from './routes/$a' +import { Route as ABRouteImport } from './routes/$a.$b' +import { Route as ABCRouteImport } from './routes/$a.$b.$c' + +const ARoute = ARouteImport.update({ + id: '/$a', + path: '/$a', + getParentRoute: () => rootRouteImport, +} as any) +const ABRoute = ABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => ARoute, +} as any) +const ABCRoute = ABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => ABRoute, +} as any) + +export interface FileRoutesByFullPath { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRoutesByTo { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' + fileRoutesByTo: FileRoutesByTo + to: '/$a' | '/$a/$b' | '/$a/$b/$c' + id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/$a': { + id: '/$a' + path: '/$a' + fullPath: '/$a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + '/$a/$b': { + id: '/$a/$b' + path: '/$b' + fullPath: '/$a/$b' + preLoaderRoute: typeof ABRouteImport + parentRoute: typeof ARoute + } + '/$a/$b/$c': { + id: '/$a/$b/$c' + path: '/$c' + fullPath: '/$a/$b/$c' + preLoaderRoute: typeof ABCRouteImport + parentRoute: typeof ABRoute + } + } +} + +interface ABRouteChildren { + ABCRoute: typeof ABCRoute +} + +const ABRouteChildren: ABRouteChildren = { + ABCRoute: ABCRoute, +} + +const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) + +interface ARouteChildren { + ABRoute: typeof ABRouteWithChildren +} + +const ARouteChildren: ARouteChildren = { + ABRoute: ABRouteWithChildren, +} + +const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARouteWithChildren, +} +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/benchmarks/ssr/scenarios/loaders/vue/src/router.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.$c.tsx new file mode 100644 index 0000000000..0a52b9c542 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.$c.tsx @@ -0,0 +1,35 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { makeLevelData } from '../../../shared-data' + +const LevelCComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

{data.value.meta.label}

+
    + {data.value.items.slice(0, 10).map((item) => ( +
  • {item.name}
  • + ))} +
+
+ ) + }, +}) + +export const Route = createFileRoute('/$a/$b/$c')({ + beforeLoad: ({ params, context }) => { + void context + + return { ctxC: `v-${params.c}` } + }, + loaderDeps: ({ search }) => ({ page: search.page }), + loader: async ({ params, deps, context }) => { + void context + + return makeLevelData(params.c, deps.page) + }, + component: LevelCComponent, +}) diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx new file mode 100644 index 0000000000..f3943d58e7 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx @@ -0,0 +1,36 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { makeLevelData } from '../../../shared-data' + +const LevelBComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

{data.value.meta.label}

+
    + {data.value.items.slice(0, 10).map((item) => ( +
  • {item.name}
  • + ))} +
+ +
+ ) + }, +}) + +export const Route = createFileRoute('/$a/$b')({ + beforeLoad: ({ params, context }) => { + void context + + return { ctxB: `v-${params.b}` } + }, + loaderDeps: ({ search }) => ({ page: search.page }), + loader: async ({ params, deps, context }) => { + void context + + return makeLevelData(params.b, deps.page) + }, + component: LevelBComponent, +}) diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx new file mode 100644 index 0000000000..63bb36949f --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx @@ -0,0 +1,36 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { makeLevelData } from '../../../shared-data' + +const LevelAComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

{data.value.meta.label}

+
    + {data.value.items.slice(0, 10).map((item) => ( +
  • {item.name}
  • + ))} +
+ +
+ ) + }, +}) + +export const Route = createFileRoute('/$a')({ + beforeLoad: ({ params, context }) => { + void context + + return { ctxA: `v-${params.a}` } + }, + loaderDeps: ({ search }) => ({ page: search.page }), + loader: async ({ params, deps, context }) => { + void context + + return makeLevelData(params.a, deps.page) + }, + component: LevelAComponent, +}) diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..0479fb1af4 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/vue/src/routes/__root.tsx @@ -0,0 +1,30 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s: Record) => ({ + page: typeof s.page === 'number' ? s.page : 0, + tags: Array.isArray(s.tags) ? (s.tags as Array) : [], + }), +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/loaders/vue/tsconfig.json b/benchmarks/ssr/scenarios/loaders/vue/tsconfig.json new file mode 100644 index 0000000000..c302f63770 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/vue/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared-data.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts b/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts new file mode 100644 index 0000000000..92bf3e60f0 --- /dev/null +++ b/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr loaders (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/rewrites/react/project.json b/benchmarks/ssr/scenarios/rewrites/react/project.json new file mode 100644 index 0000000000..84d4846ec5 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-rewrites-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts new file mode 100644 index 0000000000..920186c5db --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertRewriteScenario, + rewriteBenchOptions, + runRewriteLocalizedLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertRewriteScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr rewrite localized (react)', async () => + runRewriteLocalizedLoop(handler), + ).run(rewriteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts b/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts new file mode 100644 index 0000000000..f5d09089a6 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertRewriteScenario, + rewriteBenchOptions, + runRewritePassthroughLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertRewriteScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr rewrite passthrough (react)', async () => + runRewritePassthroughLoop(handler), + ).run(rewriteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/rewrites/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/rewrites/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..e893d06a57 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/react/src/routeTree.gen.ts @@ -0,0 +1,94 @@ +/* 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 PARouteImport } from './routes/p.$a' +import { Route as PABRouteImport } from './routes/p.$a.$b' + +const PARoute = PARouteImport.update({ + id: '/p/$a', + path: '/p/$a', + getParentRoute: () => rootRouteImport, +} as any) +const PABRoute = PABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => PARoute, +} as any) + +export interface FileRoutesByFullPath { + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesByTo { + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/p/$a' | '/p/$a/$b' + fileRoutesByTo: FileRoutesByTo + to: '/p/$a' | '/p/$a/$b' + id: '__root__' | '/p/$a' | '/p/$a/$b' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + PARoute: typeof PARouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/p/$a': { + id: '/p/$a' + path: '/p/$a' + fullPath: '/p/$a' + preLoaderRoute: typeof PARouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a/$b': { + id: '/p/$a/$b' + path: '/$b' + fullPath: '/p/$a/$b' + preLoaderRoute: typeof PABRouteImport + parentRoute: typeof PARoute + } + } +} + +interface PARouteChildren { + PABRoute: typeof PABRoute +} + +const PARouteChildren: PARouteChildren = { + PABRoute: PABRoute, +} + +const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + PARoute: PARouteWithChildren, +} +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/benchmarks/ssr/scenarios/rewrites/react/src/router.tsx b/benchmarks/ssr/scenarios/rewrites/react/src/router.tsx new file mode 100644 index 0000000000..e9e0b2ce9a --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/react/src/router.tsx @@ -0,0 +1,42 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const localePrefixRe = /^\/(fr|de|es)(\/.*)$/ + +export function getRouter() { + return createRouter({ + routeTree, + basepath: '/app', + defaultPreload: false, + scrollRestoration: false, + rewrite: { + input: ({ url }) => { + const match = url.pathname.match(localePrefixRe) + + if (match) { + url.pathname = match[2]! + url.searchParams.set('_locale', match[1]!) + return url + } + + return undefined + }, + output: ({ url }) => { + const locale = url.searchParams.get('_locale') + + if (locale) { + url.searchParams.delete('_locale') + url.pathname = `/${locale}${url.pathname}` + } + + return url + }, + }, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/rewrites/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/rewrites/react/src/routes/__root.tsx new file mode 100644 index 0000000000..7cdcfe1a37 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/react/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s: Record) => ({ + _locale: typeof s._locale === 'string' ? s._locale : undefined, + }), +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.$b.tsx b/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.$b.tsx new file mode 100644 index 0000000000..756109b844 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.$b.tsx @@ -0,0 +1,39 @@ +import { Link, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/p/$a/$b')({ + loader: ({ params }) => ({ + a: params.a, + b: params.b, + nextB: `next-${params.b}`, + }), + component: LeafComponent, +}) + +function LeafComponent() { + const data = Route.useLoaderData() + + return ( +
+

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

+ + leaf-self-link + + + leaf-next-link + + + leaf-parent-link + +
+ ) +} diff --git a/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.tsx b/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.tsx new file mode 100644 index 0000000000..7b0a778a18 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/react/src/routes/p.$a.tsx @@ -0,0 +1,27 @@ +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/p/$a')({ + loader: ({ params }) => ({ + a: params.a, + nextB: `branch-${params.a}`, + }), + component: ParentComponent, +}) + +function ParentComponent() { + const data = Route.useLoaderData() + + return ( +
+

rewrite-parent {data.a}

+ + parent-branch-link + + +
+ ) +} diff --git a/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json b/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json new file mode 100644 index 0000000000..cf14e1d440 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/rewrites/react/vite.config.ts b/benchmarks/ssr/scenarios/rewrites/react/vite.config.ts new file mode 100644 index 0000000000..7b20340ec6 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/react/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + router: { + basepath: '/app', + }, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr rewrites (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/rewrites/shared.ts b/benchmarks/ssr/scenarios/rewrites/shared.ts new file mode 100644 index 0000000000..9b29bc0249 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/shared.ts @@ -0,0 +1,91 @@ +import { expect } from 'vitest' +import { randomSegment, runRequestLoop } from '../../bench-utils' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +const benchmarkSeed = 0xdecafbad +const origin = 'http://localhost' +const localizedLoopTotalRequests = 32 +const passthroughLoopTotalRequests = 32 + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +export const rewriteBenchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} + +function buildLocalizedRequest(random: () => number) { + return new Request( + `${origin}/app/fr/p/${randomSegment(random)}/${randomSegment(random)}`, + requestInit, + ) +} + +function buildPassthroughRequest(random: () => number) { + return new Request( + `${origin}/app/p/${randomSegment(random)}/${randomSegment(random)}`, + requestInit, + ) +} + +export function runRewriteLocalizedLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: localizedLoopTotalRequests, + buildRequest: buildLocalizedRequest, + }) +} + +export function runRewritePassthroughLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: passthroughLoopTotalRequests, + buildRequest: buildPassthroughRequest, + }) +} + +export async function assertRewriteScenario(handler: StartRequestHandler) { + const localizedResponse = await handler.fetch( + new Request(`${origin}/app/fr/p/sanity-a/sanity-b`, requestInit), + ) + const localizedBody = await localizedResponse.text() + + expect(localizedResponse.status).toBe(200) + expect(localizedBody).toContain('rewrite-leaf') + expect(localizedBody).toContain('sanity-a') + expect(localizedBody).toContain('sanity-b') + expect(localizedBody).toContain('href="/app/fr/p/sanity-a/sanity-b"') + expect(localizedBody).toContain('href="/app/fr/p/sanity-a/next-sanity-b"') + + const passthroughResponse = await handler.fetch( + new Request(`${origin}/app/p/sanity-a/sanity-b`, requestInit), + ) + const passthroughBody = await passthroughResponse.text() + + expect(passthroughResponse.status).toBe(200) + expect(passthroughBody).toContain('rewrite-leaf') + expect(passthroughBody).toContain('sanity-a') + expect(passthroughBody).toContain('sanity-b') + expect(passthroughBody).toContain('href="/app/fr/p/sanity-a/sanity-b"') + expect(passthroughBody).toContain('href="/app/fr/p/sanity-a/next-sanity-b"') + + const unprefixedResponse = await handler.fetch( + new Request(`${origin}/p/sanity-a/sanity-b`, requestInit), + ) + await unprefixedResponse.text() + + expect(unprefixedResponse.status).toBe(307) + expect(unprefixedResponse.headers.get('location')).toBe( + '/app/p/sanity-a/sanity-b', + ) +} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/project.json b/benchmarks/ssr/scenarios/rewrites/solid/project.json new file mode 100644 index 0000000000..7c993a1404 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/solid/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-rewrites-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts new file mode 100644 index 0000000000..488fb2ca52 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertRewriteScenario, + rewriteBenchOptions, + runRewriteLocalizedLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertRewriteScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr rewrite localized (solid)', async () => + runRewriteLocalizedLoop(handler), + ).run(rewriteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts b/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts new file mode 100644 index 0000000000..7b86e2ba11 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertRewriteScenario, + rewriteBenchOptions, + runRewritePassthroughLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertRewriteScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr rewrite passthrough (solid)', async () => + runRewritePassthroughLoop(handler), + ).run(rewriteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/rewrites/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/rewrites/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..b3b6b24a38 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/solid/src/routeTree.gen.ts @@ -0,0 +1,94 @@ +/* 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 PARouteImport } from './routes/p.$a' +import { Route as PABRouteImport } from './routes/p.$a.$b' + +const PARoute = PARouteImport.update({ + id: '/p/$a', + path: '/p/$a', + getParentRoute: () => rootRouteImport, +} as any) +const PABRoute = PABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => PARoute, +} as any) + +export interface FileRoutesByFullPath { + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesByTo { + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/p/$a' | '/p/$a/$b' + fileRoutesByTo: FileRoutesByTo + to: '/p/$a' | '/p/$a/$b' + id: '__root__' | '/p/$a' | '/p/$a/$b' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + PARoute: typeof PARouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/p/$a': { + id: '/p/$a' + path: '/p/$a' + fullPath: '/p/$a' + preLoaderRoute: typeof PARouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a/$b': { + id: '/p/$a/$b' + path: '/$b' + fullPath: '/p/$a/$b' + preLoaderRoute: typeof PABRouteImport + parentRoute: typeof PARoute + } + } +} + +interface PARouteChildren { + PABRoute: typeof PABRoute +} + +const PARouteChildren: PARouteChildren = { + PABRoute: PABRoute, +} + +const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + PARoute: PARouteWithChildren, +} +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/benchmarks/ssr/scenarios/rewrites/solid/src/router.tsx b/benchmarks/ssr/scenarios/rewrites/solid/src/router.tsx new file mode 100644 index 0000000000..9806e59d0e --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/solid/src/router.tsx @@ -0,0 +1,42 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +const localePrefixRe = /^\/(fr|de|es)(\/.*)$/ + +export function getRouter() { + return createRouter({ + routeTree, + basepath: '/app', + defaultPreload: false, + scrollRestoration: false, + rewrite: { + input: ({ url }) => { + const match = url.pathname.match(localePrefixRe) + + if (match) { + url.pathname = match[2]! + url.searchParams.set('_locale', match[1]!) + return url + } + + return undefined + }, + output: ({ url }) => { + const locale = url.searchParams.get('_locale') + + if (locale) { + url.searchParams.delete('_locale') + url.pathname = `/${locale}${url.pathname}` + } + + return url + }, + }, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/rewrites/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..1a9cd6c423 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/solid/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s: Record) => ({ + _locale: typeof s._locale === 'string' ? s._locale : undefined, + }), +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx b/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx new file mode 100644 index 0000000000..eacb45a841 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx @@ -0,0 +1,39 @@ +import { Link, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/p/$a/$b')({ + loader: ({ params }) => ({ + a: params.a, + b: params.b, + nextB: `next-${params.b}`, + }), + component: LeafComponent, +}) + +function LeafComponent() { + const data = Route.useLoaderData() + + return ( +
+

+ rewrite-leaf {data().a} {data().b} +

+ + leaf-self-link + + + leaf-next-link + + + leaf-parent-link + +
+ ) +} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.tsx b/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.tsx new file mode 100644 index 0000000000..1845e3ebba --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/solid/src/routes/p.$a.tsx @@ -0,0 +1,27 @@ +import { Link, Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/p/$a')({ + loader: ({ params }) => ({ + a: params.a, + nextB: `branch-${params.a}`, + }), + component: ParentComponent, +}) + +function ParentComponent() { + const data = Route.useLoaderData() + + return ( +
+

rewrite-parent {data().a}

+ + parent-branch-link + + +
+ ) +} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json b/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json new file mode 100644 index 0000000000..42c3a2160f --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/rewrites/solid/vite.config.ts b/benchmarks/ssr/scenarios/rewrites/solid/vite.config.ts new file mode 100644 index 0000000000..963fe7132b --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/solid/vite.config.ts @@ -0,0 +1,40 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + router: { + basepath: '/app', + }, + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr rewrites (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/project.json b/benchmarks/ssr/scenarios/rewrites/vue/project.json new file mode 100644 index 0000000000..10fd6f4f34 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-rewrites-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts new file mode 100644 index 0000000000..5fd4da9d3e --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertRewriteScenario, + rewriteBenchOptions, + runRewriteLocalizedLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertRewriteScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr rewrite localized (vue)', async () => + runRewriteLocalizedLoop(handler), + ).run(rewriteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts b/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts new file mode 100644 index 0000000000..f3664b5f21 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertRewriteScenario, + rewriteBenchOptions, + runRewritePassthroughLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertRewriteScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr rewrite passthrough (vue)', async () => + runRewritePassthroughLoop(handler), + ).run(rewriteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/rewrites/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..4440c1cfda --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/vue/src/routeTree.gen.ts @@ -0,0 +1,94 @@ +/* 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 PARouteImport } from './routes/p.$a' +import { Route as PABRouteImport } from './routes/p.$a.$b' + +const PARoute = PARouteImport.update({ + id: '/p/$a', + path: '/p/$a', + getParentRoute: () => rootRouteImport, +} as any) +const PABRoute = PABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => PARoute, +} as any) + +export interface FileRoutesByFullPath { + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesByTo { + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/p/$a' | '/p/$a/$b' + fileRoutesByTo: FileRoutesByTo + to: '/p/$a' | '/p/$a/$b' + id: '__root__' | '/p/$a' | '/p/$a/$b' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + PARoute: typeof PARouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/p/$a': { + id: '/p/$a' + path: '/p/$a' + fullPath: '/p/$a' + preLoaderRoute: typeof PARouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a/$b': { + id: '/p/$a/$b' + path: '/$b' + fullPath: '/p/$a/$b' + preLoaderRoute: typeof PABRouteImport + parentRoute: typeof PARoute + } + } +} + +interface PARouteChildren { + PABRoute: typeof PABRoute +} + +const PARouteChildren: PARouteChildren = { + PABRoute: PABRoute, +} + +const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + PARoute: PARouteWithChildren, +} +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/benchmarks/ssr/scenarios/rewrites/vue/src/router.tsx b/benchmarks/ssr/scenarios/rewrites/vue/src/router.tsx new file mode 100644 index 0000000000..3a7389a5be --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/vue/src/router.tsx @@ -0,0 +1,42 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +const localePrefixRe = /^\/(fr|de|es)(\/.*)$/ + +export function getRouter() { + return createRouter({ + routeTree, + basepath: '/app', + defaultPreload: false, + scrollRestoration: false, + rewrite: { + input: ({ url }) => { + const match = url.pathname.match(localePrefixRe) + + if (match) { + url.pathname = match[2]! + url.searchParams.set('_locale', match[1]!) + return url + } + + return undefined + }, + output: ({ url }) => { + const locale = url.searchParams.get('_locale') + + if (locale) { + url.searchParams.delete('_locale') + url.pathname = `/${locale}${url.pathname}` + } + + return url + }, + }, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..ed4cf1300d --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s: Record) => ({ + _locale: typeof s._locale === 'string' ? s._locale : undefined, + }), +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx new file mode 100644 index 0000000000..3c9de1806e --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx @@ -0,0 +1,46 @@ +import { defineComponent } from 'vue' +import { Link, createFileRoute } from '@tanstack/vue-router' + +const LeafComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

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

+ + leaf-self-link + + + leaf-next-link + + + leaf-parent-link + +
+ ) + }, +}) + +export const Route = createFileRoute('/p/$a/$b')({ + loader: ({ params }) => ({ + a: params.a, + b: params.b, + nextB: `next-${params.b}`, + }), + component: LeafComponent, +}) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx new file mode 100644 index 0000000000..9702ebedd7 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx @@ -0,0 +1,30 @@ +import { defineComponent } from 'vue' +import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' + +const ParentComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

rewrite-parent {data.value.a}

+ + parent-branch-link + + +
+ ) + }, +}) + +export const Route = createFileRoute('/p/$a')({ + loader: ({ params }) => ({ + a: params.a, + nextB: `branch-${params.a}`, + }), + component: ParentComponent, +}) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json b/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json new file mode 100644 index 0000000000..08c94853f4 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/rewrites/vue/vite.config.ts b/benchmarks/ssr/scenarios/rewrites/vue/vite.config.ts new file mode 100644 index 0000000000..22399ec6b2 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/vue/vite.config.ts @@ -0,0 +1,35 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + router: { + basepath: '/app', + }, + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr rewrites (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/project.json b/benchmarks/ssr/scenarios/selective-ssr/react/project.json new file mode 100644 index 0000000000..77858e2246 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-selective-ssr-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts new file mode 100644 index 0000000000..ba6bd4a61d --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSelectiveSanity, + benchOptions, + runSelectiveLoop, + type StartRequestHandler, +} from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSelectiveSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr selective (react)', async () => + runSelectiveLoop(handler), + ).run(benchOptions) +}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/selective-ssr/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..95395c294e --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/react/src/routeTree.gen.ts @@ -0,0 +1,120 @@ +/* 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 MixARouteImport } from './routes/mix.$a' +import { Route as MixABRouteImport } from './routes/mix.$a.$b' +import { Route as MixABCRouteImport } from './routes/mix.$a.$b.$c' + +const MixARoute = MixARouteImport.update({ + id: '/mix/$a', + path: '/mix/$a', + getParentRoute: () => rootRouteImport, +} as any) +const MixABRoute = MixABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => MixARoute, +} as any) +const MixABCRoute = MixABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => MixABRoute, +} as any) + +export interface FileRoutesByFullPath { + '/mix/$a': typeof MixARouteWithChildren + '/mix/$a/$b': typeof MixABRouteWithChildren + '/mix/$a/$b/$c': typeof MixABCRoute +} +export interface FileRoutesByTo { + '/mix/$a': typeof MixARouteWithChildren + '/mix/$a/$b': typeof MixABRouteWithChildren + '/mix/$a/$b/$c': typeof MixABCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/mix/$a': typeof MixARouteWithChildren + '/mix/$a/$b': typeof MixABRouteWithChildren + '/mix/$a/$b/$c': typeof MixABCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' + fileRoutesByTo: FileRoutesByTo + to: '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' + id: '__root__' | '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + MixARoute: typeof MixARouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/mix/$a': { + id: '/mix/$a' + path: '/mix/$a' + fullPath: '/mix/$a' + preLoaderRoute: typeof MixARouteImport + parentRoute: typeof rootRouteImport + } + '/mix/$a/$b': { + id: '/mix/$a/$b' + path: '/$b' + fullPath: '/mix/$a/$b' + preLoaderRoute: typeof MixABRouteImport + parentRoute: typeof MixARoute + } + '/mix/$a/$b/$c': { + id: '/mix/$a/$b/$c' + path: '/$c' + fullPath: '/mix/$a/$b/$c' + preLoaderRoute: typeof MixABCRouteImport + parentRoute: typeof MixABRoute + } + } +} + +interface MixABRouteChildren { + MixABCRoute: typeof MixABCRoute +} + +const MixABRouteChildren: MixABRouteChildren = { + MixABCRoute: MixABCRoute, +} + +const MixABRouteWithChildren = MixABRoute._addFileChildren(MixABRouteChildren) + +interface MixARouteChildren { + MixABRoute: typeof MixABRouteWithChildren +} + +const MixARouteChildren: MixARouteChildren = { + MixABRoute: MixABRouteWithChildren, +} + +const MixARouteWithChildren = MixARoute._addFileChildren(MixARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + MixARoute: MixARouteWithChildren, +} +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/benchmarks/ssr/scenarios/selective-ssr/react/src/router.tsx b/benchmarks/ssr/scenarios/selective-ssr/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/__root.tsx new file mode 100644 index 0000000000..1973ca20bb --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/__root.tsx @@ -0,0 +1,25 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.$c.tsx b/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.$c.tsx new file mode 100644 index 0000000000..e3df06149d --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.$c.tsx @@ -0,0 +1,25 @@ +import { createFileRoute } from '@tanstack/react-router' +import { makeLevelData } from '../../../../loaders/shared-data' + +export const Route = createFileRoute('/mix/$a/$b/$c')({ + ssr: false, + loader: async ({ params }) => { + return { + marker: `level-c-loader-${params.c}`, + data: makeLevelData(`level-c-data-${params.c}`, 3), + } + }, + component: LevelCComponent, +}) + +function LevelCComponent() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return ( +
+

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

+

{data.marker}

+
+ ) +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.tsx b/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.tsx new file mode 100644 index 0000000000..3fe26dd70e --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.$b.tsx @@ -0,0 +1,26 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { makeLevelData } from '../../../../loaders/shared-data' + +export const Route = createFileRoute('/mix/$a/$b')({ + ssr: 'data-only', + loader: async ({ params }) => { + return { + marker: `level-b-loader-${params.b}`, + data: makeLevelData(`level-b-data-${params.b}`, 2), + } + }, + component: LevelBComponent, +}) + +function LevelBComponent() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return ( +
+

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

+

{data.marker}

+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.tsx b/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.tsx new file mode 100644 index 0000000000..a06c9ad1b9 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/react/src/routes/mix.$a.tsx @@ -0,0 +1,23 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { makeLevelData } from '../../../../loaders/shared-data' + +export const Route = createFileRoute('/mix/$a')({ + ssr: true, + loader: async ({ params }) => { + return makeLevelData(`level-a-loader-${params.a}`, 1) + }, + component: LevelAComponent, +}) + +function LevelAComponent() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return ( +
+

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

+

{data.items[0]?.name}

+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/tsconfig.json b/benchmarks/ssr/scenarios/selective-ssr/react/tsconfig.json new file mode 100644 index 0000000000..399fe944f9 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/react/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../loaders/shared-data.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts b/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts new file mode 100644 index 0000000000..70c67cff81 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr selective-ssr (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/shared-bench.ts b/benchmarks/ssr/scenarios/selective-ssr/shared-bench.ts new file mode 100644 index 0000000000..5b2530ccab --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/shared-bench.ts @@ -0,0 +1,95 @@ +import { makeLevelData } from '../loaders/shared-data' +import { randomSegment, runRequestLoop } from '../../bench-utils' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +const benchmarkSeed = 0xdecafbad +const selectiveLoopTotalRequests = 32 + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +function buildSelectiveRequest(random: () => number) { + const a = randomSegment(random) + const b = randomSegment(random) + const c = randomSegment(random) + + return new Request(`http://localhost/mix/${a}/${b}/${c}`, requestInit) +} + +export async function assertSelectiveSanity(handler: StartRequestHandler) { + const a = 'a-sanity' + const b = 'b-sanity' + const c = 'c-sanity' + const response = await handler.fetch( + new Request(`http://localhost/mix/${a}/${b}/${c}`, requestInit), + ) + const body = await response.text() + const levelARenderedMarker = `level-a-rendered-${a}` + const levelALoaderMarker = makeLevelData(`level-a-loader-${a}`, 1).items[0] + ?.name + const dataOnlyRenderedMarker = `data-only-rendered-${b}` + const levelBLoaderMarker = `level-b-loader-${b}` + const csrRenderedMarker = `csr-rendered-${c}` + const levelCLoaderMarker = `level-c-loader-${c}` + + if (response.status !== 200) { + throw new Error( + `Expected setup request status 200, received ${response.status}`, + ) + } + + if (!body.includes(levelARenderedMarker)) { + throw new Error( + 'Expected setup response to include level-a rendered content', + ) + } + + if (!levelALoaderMarker || !body.includes(levelALoaderMarker)) { + throw new Error('Expected setup response to include level-a loader content') + } + + if (body.includes(dataOnlyRenderedMarker)) { + throw new Error( + 'Expected data-only route component to be absent from SSR HTML', + ) + } + + const hydrationIndex = body.indexOf('$_TSR') + + if (hydrationIndex === -1) { + throw new Error('Expected setup response to include the dehydration marker') + } + + if (!body.slice(hydrationIndex).includes(levelBLoaderMarker)) { + throw new Error('Expected level-b loader marker in the dehydration payload') + } + + if (body.includes(csrRenderedMarker)) { + throw new Error('Expected csr route component to be absent from SSR HTML') + } + + if (body.includes(levelCLoaderMarker)) { + throw new Error('Expected level-c loader marker to be absent from SSR HTML') + } +} + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} + +export function runSelectiveLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: selectiveLoopTotalRequests, + buildRequest: buildSelectiveRequest, + }) +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/project.json b/benchmarks/ssr/scenarios/selective-ssr/solid/project.json new file mode 100644 index 0000000000..358cc97323 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-selective-ssr-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts new file mode 100644 index 0000000000..76265397ab --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSelectiveSanity, + benchOptions, + runSelectiveLoop, + type StartRequestHandler, +} from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSelectiveSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr selective (solid)', async () => + runSelectiveLoop(handler), + ).run(benchOptions) +}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..22560063f6 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routeTree.gen.ts @@ -0,0 +1,120 @@ +/* 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 MixARouteImport } from './routes/mix.$a' +import { Route as MixABRouteImport } from './routes/mix.$a.$b' +import { Route as MixABCRouteImport } from './routes/mix.$a.$b.$c' + +const MixARoute = MixARouteImport.update({ + id: '/mix/$a', + path: '/mix/$a', + getParentRoute: () => rootRouteImport, +} as any) +const MixABRoute = MixABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => MixARoute, +} as any) +const MixABCRoute = MixABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => MixABRoute, +} as any) + +export interface FileRoutesByFullPath { + '/mix/$a': typeof MixARouteWithChildren + '/mix/$a/$b': typeof MixABRouteWithChildren + '/mix/$a/$b/$c': typeof MixABCRoute +} +export interface FileRoutesByTo { + '/mix/$a': typeof MixARouteWithChildren + '/mix/$a/$b': typeof MixABRouteWithChildren + '/mix/$a/$b/$c': typeof MixABCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/mix/$a': typeof MixARouteWithChildren + '/mix/$a/$b': typeof MixABRouteWithChildren + '/mix/$a/$b/$c': typeof MixABCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' + fileRoutesByTo: FileRoutesByTo + to: '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' + id: '__root__' | '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + MixARoute: typeof MixARouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/mix/$a': { + id: '/mix/$a' + path: '/mix/$a' + fullPath: '/mix/$a' + preLoaderRoute: typeof MixARouteImport + parentRoute: typeof rootRouteImport + } + '/mix/$a/$b': { + id: '/mix/$a/$b' + path: '/$b' + fullPath: '/mix/$a/$b' + preLoaderRoute: typeof MixABRouteImport + parentRoute: typeof MixARoute + } + '/mix/$a/$b/$c': { + id: '/mix/$a/$b/$c' + path: '/$c' + fullPath: '/mix/$a/$b/$c' + preLoaderRoute: typeof MixABCRouteImport + parentRoute: typeof MixABRoute + } + } +} + +interface MixABRouteChildren { + MixABCRoute: typeof MixABCRoute +} + +const MixABRouteChildren: MixABRouteChildren = { + MixABCRoute: MixABCRoute, +} + +const MixABRouteWithChildren = MixABRoute._addFileChildren(MixABRouteChildren) + +interface MixARouteChildren { + MixABRoute: typeof MixABRouteWithChildren +} + +const MixARouteChildren: MixARouteChildren = { + MixABRoute: MixABRouteWithChildren, +} + +const MixARouteWithChildren = MixARoute._addFileChildren(MixARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + MixARoute: MixARouteWithChildren, +} +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/benchmarks/ssr/scenarios/selective-ssr/solid/src/router.tsx b/benchmarks/ssr/scenarios/selective-ssr/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..15de858e78 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/__root.tsx @@ -0,0 +1,25 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.$c.tsx b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.$c.tsx new file mode 100644 index 0000000000..f6a85bfdc2 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.$c.tsx @@ -0,0 +1,25 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { makeLevelData } from '../../../../loaders/shared-data' + +export const Route = createFileRoute('/mix/$a/$b/$c')({ + ssr: false, + loader: async ({ params }) => { + return { + marker: `level-c-loader-${params.c}`, + data: makeLevelData(`level-c-data-${params.c}`, 3), + } + }, + component: LevelCComponent, +}) + +function LevelCComponent() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return ( +
+

{`csr-rendered-${params().c}`}

+

{data().marker}

+
+ ) +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.tsx b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.tsx new file mode 100644 index 0000000000..f735b1395f --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.$b.tsx @@ -0,0 +1,26 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { makeLevelData } from '../../../../loaders/shared-data' + +export const Route = createFileRoute('/mix/$a/$b')({ + ssr: 'data-only', + loader: async ({ params }) => { + return { + marker: `level-b-loader-${params.b}`, + data: makeLevelData(`level-b-data-${params.b}`, 2), + } + }, + component: LevelBComponent, +}) + +function LevelBComponent() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return ( +
+

{`data-only-rendered-${params().b}`}

+

{data().marker}

+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.tsx b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.tsx new file mode 100644 index 0000000000..c8c80a7a6d --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/src/routes/mix.$a.tsx @@ -0,0 +1,23 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { makeLevelData } from '../../../../loaders/shared-data' + +export const Route = createFileRoute('/mix/$a')({ + ssr: true, + loader: async ({ params }) => { + return makeLevelData(`level-a-loader-${params.a}`, 1) + }, + component: LevelAComponent, +}) + +function LevelAComponent() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return ( +
+

{`level-a-rendered-${params().a}`}

+

{data().items[0]?.name}

+ +
+ ) +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/tsconfig.json b/benchmarks/ssr/scenarios/selective-ssr/solid/tsconfig.json new file mode 100644 index 0000000000..f386c3f996 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../loaders/shared-data.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts b/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts new file mode 100644 index 0000000000..2c0042c1ed --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr selective-ssr (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/project.json b/benchmarks/ssr/scenarios/selective-ssr/vue/project.json new file mode 100644 index 0000000000..9ff4d99323 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-selective-ssr-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts new file mode 100644 index 0000000000..ff60341b27 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSelectiveSanity, + benchOptions, + runSelectiveLoop, + type StartRequestHandler, +} from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSelectiveSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr selective (vue)', async () => runSelectiveLoop(handler)).run( + benchOptions, + ) +}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..b77209b48b --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routeTree.gen.ts @@ -0,0 +1,120 @@ +/* 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 MixARouteImport } from './routes/mix.$a' +import { Route as MixABRouteImport } from './routes/mix.$a.$b' +import { Route as MixABCRouteImport } from './routes/mix.$a.$b.$c' + +const MixARoute = MixARouteImport.update({ + id: '/mix/$a', + path: '/mix/$a', + getParentRoute: () => rootRouteImport, +} as any) +const MixABRoute = MixABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => MixARoute, +} as any) +const MixABCRoute = MixABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => MixABRoute, +} as any) + +export interface FileRoutesByFullPath { + '/mix/$a': typeof MixARouteWithChildren + '/mix/$a/$b': typeof MixABRouteWithChildren + '/mix/$a/$b/$c': typeof MixABCRoute +} +export interface FileRoutesByTo { + '/mix/$a': typeof MixARouteWithChildren + '/mix/$a/$b': typeof MixABRouteWithChildren + '/mix/$a/$b/$c': typeof MixABCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/mix/$a': typeof MixARouteWithChildren + '/mix/$a/$b': typeof MixABRouteWithChildren + '/mix/$a/$b/$c': typeof MixABCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' + fileRoutesByTo: FileRoutesByTo + to: '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' + id: '__root__' | '/mix/$a' | '/mix/$a/$b' | '/mix/$a/$b/$c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + MixARoute: typeof MixARouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/mix/$a': { + id: '/mix/$a' + path: '/mix/$a' + fullPath: '/mix/$a' + preLoaderRoute: typeof MixARouteImport + parentRoute: typeof rootRouteImport + } + '/mix/$a/$b': { + id: '/mix/$a/$b' + path: '/$b' + fullPath: '/mix/$a/$b' + preLoaderRoute: typeof MixABRouteImport + parentRoute: typeof MixARoute + } + '/mix/$a/$b/$c': { + id: '/mix/$a/$b/$c' + path: '/$c' + fullPath: '/mix/$a/$b/$c' + preLoaderRoute: typeof MixABCRouteImport + parentRoute: typeof MixABRoute + } + } +} + +interface MixABRouteChildren { + MixABCRoute: typeof MixABCRoute +} + +const MixABRouteChildren: MixABRouteChildren = { + MixABCRoute: MixABCRoute, +} + +const MixABRouteWithChildren = MixABRoute._addFileChildren(MixABRouteChildren) + +interface MixARouteChildren { + MixABRoute: typeof MixABRouteWithChildren +} + +const MixARouteChildren: MixARouteChildren = { + MixABRoute: MixABRouteWithChildren, +} + +const MixARouteWithChildren = MixARoute._addFileChildren(MixARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + MixARoute: MixARouteWithChildren, +} +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/benchmarks/ssr/scenarios/selective-ssr/vue/src/router.tsx b/benchmarks/ssr/scenarios/selective-ssr/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..4b03519823 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.$c.tsx b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.$c.tsx new file mode 100644 index 0000000000..8ae7d468f1 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.$c.tsx @@ -0,0 +1,28 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { makeLevelData } from '../../../../loaders/shared-data' + +const LevelCComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return () => ( +
+

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

+

{data.value.marker}

+
+ ) + }, +}) + +export const Route = createFileRoute('/mix/$a/$b/$c')({ + ssr: false, + loader: async ({ params }) => { + return { + marker: `level-c-loader-${params.c}`, + data: makeLevelData(`level-c-data-${params.c}`, 3), + } + }, + component: LevelCComponent, +}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.tsx b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.tsx new file mode 100644 index 0000000000..c10751489e --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.tsx @@ -0,0 +1,29 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { makeLevelData } from '../../../../loaders/shared-data' + +const LevelBComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return () => ( +
+

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

+

{data.value.marker}

+ +
+ ) + }, +}) + +export const Route = createFileRoute('/mix/$a/$b')({ + ssr: 'data-only', + loader: async ({ params }) => { + return { + marker: `level-b-loader-${params.b}`, + data: makeLevelData(`level-b-data-${params.b}`, 2), + } + }, + component: LevelBComponent, +}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.tsx b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.tsx new file mode 100644 index 0000000000..c96165c6d6 --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.tsx @@ -0,0 +1,26 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { makeLevelData } from '../../../../loaders/shared-data' + +const LevelAComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return () => ( +
+

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

+

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

+ +
+ ) + }, +}) + +export const Route = createFileRoute('/mix/$a')({ + ssr: true, + loader: async ({ params }) => { + return makeLevelData(`level-a-loader-${params.a}`, 1) + }, + component: LevelAComponent, +}) diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/tsconfig.json b/benchmarks/ssr/scenarios/selective-ssr/vue/tsconfig.json new file mode 100644 index 0000000000..3f2809bd5a --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../../loaders/shared-data.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts b/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts new file mode 100644 index 0000000000..09bb36cb0b --- /dev/null +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr selective-ssr (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/serialization/react/project.json b/benchmarks/ssr/scenarios/serialization/react/project.json new file mode 100644 index 0000000000..652f87cb44 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-serialization-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts new file mode 100644 index 0000000000..8be07d2643 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSerializationScenario, + runRichSerializationLoop, + serializationBenchOptions, +} from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSerializationScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate rich types (react)', async () => + runRichSerializationLoop(handler), + ).run(serializationBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts b/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts new file mode 100644 index 0000000000..c70fddc6c4 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSerializationScenario, + runPlainSerializationLoop, + serializationBenchOptions, +} from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSerializationScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate plain control (react)', async () => + runPlainSerializationLoop(handler), + ).run(serializationBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/serialization/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/serialization/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..49bdbd036b --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/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 PlainIdRouteImport } from './routes/plain.$id' +import { Route as RichIdRouteImport } from './routes/rich.$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) + +export interface FileRoutesByFullPath { + '/plain/$id': typeof PlainIdRoute + '/rich/$id': typeof RichIdRoute +} +export interface FileRoutesByTo { + '/plain/$id': typeof PlainIdRoute + '/rich/$id': typeof RichIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/plain/$id': typeof PlainIdRoute + '/rich/$id': typeof RichIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/plain/$id' | '/rich/$id' + fileRoutesByTo: FileRoutesByTo + to: '/plain/$id' | '/rich/$id' + id: '__root__' | '/plain/$id' | '/rich/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + PlainIdRoute: typeof PlainIdRoute + RichIdRoute: typeof RichIdRoute +} + +declare module '@tanstack/react-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' + fullPath: '/rich/$id' + preLoaderRoute: typeof RichIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + PlainIdRoute: PlainIdRoute, + RichIdRoute: RichIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { startInstance } from './start.tsx' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + config: Awaited> + } +} diff --git a/benchmarks/ssr/scenarios/serialization/react/src/router.tsx b/benchmarks/ssr/scenarios/serialization/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/serialization/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/serialization/react/src/routes/__root.tsx new file mode 100644 index 0000000000..ff1da4c304 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/serialization/react/src/routes/plain.$id.tsx b/benchmarks/ssr/scenarios/serialization/react/src/routes/plain.$id.tsx new file mode 100644 index 0000000000..88a8a0e11f --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/src/routes/plain.$id.tsx @@ -0,0 +1,26 @@ +import { createFileRoute } from '@tanstack/react-router' +import { makePlainSerializationData } from '../../../shared-data' + +export const Route = createFileRoute('/plain/$id')({ + loader: ({ params }) => makePlainSerializationData(params.id), + component: PlainComponent, +}) + +function PlainComponent() { + const data = Route.useLoaderData() + const firstMapEntry = data.lookup[0]?.[1] + const firstTag = data.tags[0] + + return ( +
+

{data.label}

+

{data.createdAt}

+

{firstMapEntry?.label}

+

{firstTag}

+

{data.count}

+

{data.nested[0]?.id}

+

{data.points[0]?.label}

+

{data.problem.message}

+
+ ) +} diff --git a/benchmarks/ssr/scenarios/serialization/react/src/routes/rich.$id.tsx b/benchmarks/ssr/scenarios/serialization/react/src/routes/rich.$id.tsx new file mode 100644 index 0000000000..a9bb264c48 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/src/routes/rich.$id.tsx @@ -0,0 +1,26 @@ +import { createFileRoute } from '@tanstack/react-router' +import { makeRichSerializationData } from '../../../shared-data' + +export const Route = createFileRoute('/rich/$id')({ + loader: ({ params }) => makeRichSerializationData(params.id), + component: RichComponent, +}) + +function RichComponent() { + const data = Route.useLoaderData() + const firstMapEntry = data.lookup.get('k0') + const firstTag = Array.from(data.tags)[0] + + return ( +
+

{data.label}

+

{data.createdAt.toISOString()}

+

{firstMapEntry?.label}

+

{firstTag}

+

{data.count.toString()}

+

{data.nested[0]?.id}

+

{data.points[0]?.label}

+

{data.problem.message}

+
+ ) +} diff --git a/benchmarks/ssr/scenarios/serialization/react/src/serialization.ts b/benchmarks/ssr/scenarios/serialization/react/src/serialization.ts new file mode 100644 index 0000000000..0a73c69be1 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/src/serialization.ts @@ -0,0 +1,10 @@ +import { createSerializationAdapter } from '@tanstack/react-router' +import { BenchPoint, benchPointAdapterKey } from '../../shared-data' + +export const benchPointAdapter = createSerializationAdapter({ + key: benchPointAdapterKey, + test: (value): value is BenchPoint => value instanceof BenchPoint, + toSerializable: (point) => ({ x: point.x, y: point.y }), + fromSerializable: (value: { x: number; y: number }) => + new BenchPoint(value.x, value.y), +}) diff --git a/benchmarks/ssr/scenarios/serialization/react/src/start.tsx b/benchmarks/ssr/scenarios/serialization/react/src/start.tsx new file mode 100644 index 0000000000..ea4513df4d --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/src/start.tsx @@ -0,0 +1,9 @@ +import { createStart } from '@tanstack/react-start' +import { benchPointAdapter } from './serialization' + +export const startInstance = createStart(() => { + return { + defaultSsr: true, + serializationAdapters: [benchPointAdapter], + } +}) diff --git a/benchmarks/ssr/scenarios/serialization/react/tsconfig.json b/benchmarks/ssr/scenarios/serialization/react/tsconfig.json new file mode 100644 index 0000000000..59499356d6 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared-bench.ts", + "../shared-data.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/serialization/react/vite.config.ts b/benchmarks/ssr/scenarios/serialization/react/vite.config.ts new file mode 100644 index 0000000000..64568ccb7e --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr serialization (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/serialization/shared-bench.ts b/benchmarks/ssr/scenarios/serialization/shared-bench.ts new file mode 100644 index 0000000000..25ed478f03 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/shared-bench.ts @@ -0,0 +1,107 @@ +import { benchPointAdapterKey, richDateIso } from './shared-data' +import { randomSegment, runRequestLoop } from '../../bench-utils' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +const benchmarkSeed = 0xdecafbad +const richSerializationLoopTotalRequests = 32 +const plainSerializationLoopTotalRequests = 32 + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit + +function buildSerializationRequest( + route: 'plain' | 'rich', + random: () => number, + index: number, +) { + const suffix = index.toString(36) + const id = `${randomSegment(random)}-${suffix}` + + return new Request(`http://localhost/${route}/${id}`, requestInit) +} + +async function fetchScenarioBody( + handler: StartRequestHandler, + route: 'plain' | 'rich', +) { + const response = await handler.fetch( + new Request(`http://localhost/${route}/sanity`, requestInit), + ) + const body = await response.text() + + if (response.status !== 200) { + throw new Error( + `Expected ${route} sanity request status 200, received ${response.status}: ${body}`, + ) + } + + if (!body.includes('$_TSR')) { + throw new Error(`Expected ${route} response to include dehydration marker`) + } + + return body +} + +function assertIncludes(body: string, marker: string, label: string) { + if (!body.includes(marker)) { + throw new Error(`Expected ${label} response to include ${marker}`) + } +} + +function assertExcludes(body: string, marker: string, label: string) { + if (body.includes(marker)) { + throw new Error(`Expected ${label} response not to include ${marker}`) + } +} + +export async function assertSerializationScenario( + handler: StartRequestHandler, +) { + const richBody = await fetchScenarioBody(handler, 'rich') + const plainBody = await fetchScenarioBody(handler, 'plain') + + assertIncludes(richBody, 'rich-sanity', 'rich') + assertIncludes(richBody, benchPointAdapterKey, 'rich') + assertIncludes(richBody, richDateIso, 'rich') + assertIncludes(richBody, 'new Date', 'rich') + assertIncludes(richBody, 'new Map', 'rich') + assertIncludes(richBody, 'new Error', 'rich') + + assertIncludes(plainBody, 'plain-sanity', 'plain') + assertExcludes(plainBody, benchPointAdapterKey, 'plain') + assertExcludes(plainBody, 'new Date', 'plain') + assertExcludes(plainBody, 'new Map', 'plain') + assertExcludes(plainBody, 'new Error', 'plain') +} + +export const serializationBenchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} + +export function runRichSerializationLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: richSerializationLoopTotalRequests, + buildRequest: (random, index) => + buildSerializationRequest('rich', random, index), + }) +} + +export function runPlainSerializationLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: plainSerializationLoopTotalRequests, + buildRequest: (random, index) => + buildSerializationRequest('plain', random, index), + }) +} diff --git a/benchmarks/ssr/scenarios/serialization/shared-data.ts b/benchmarks/ssr/scenarios/serialization/shared-data.ts new file mode 100644 index 0000000000..dc1dc90b1f --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/shared-data.ts @@ -0,0 +1,101 @@ +export class BenchPoint { + constructor( + public x: number, + public y: number, + ) {} + + get label() { + return `${this.x}:${this.y}` + } +} + +export interface PlainSerializationPayload { + label: string + createdAt: string + lookup: Array<[string, { index: number; label: string }]> + tags: Array + count: string + nested: Array<{ id: string; values: Array; flag: boolean }> + points: Array<{ x: number; y: number; label: string }> + problem: { message: string } +} + +export interface RichSerializationPayload { + label: string + createdAt: Date + lookup: Map + tags: Set + count: bigint + nested: Array<{ id: string; values: Array; flag: boolean }> + points: Array + problem: Error +} + +export const benchPointAdapterKey = '$bench/point' +export const richDateIso = '2024-02-03T04:05:06.000Z' + +function makeNested(id: string) { + return Array.from({ length: 16 }, (_, index) => ({ + id: `${id}-nested-${index}`, + values: [index, index + 1, index + 2], + flag: index % 2 === 0, + })) +} + +function makeLookup( + id: string, +): Array<[string, { index: number; label: string }]> { + return Array.from( + { length: 8 }, + (_, index): [string, { index: number; label: string }] => { + const key = `k${index}` + + return [key, { index, label: `${id}-map-${index}` }] + }, + ) +} + +function makeTags(id: string) { + return Array.from({ length: 8 }, (_, index) => `${id}-tag-${index}`) +} + +function makePlainPoints() { + return Array.from({ length: 4 }, (_, index) => { + const point = new BenchPoint(index * 10, index * 10 + 5) + + return { x: point.x, y: point.y, label: point.label } + }) +} + +export function makeRichSerializationData( + id: string, +): RichSerializationPayload { + return { + label: `rich-${id}`, + createdAt: new Date(richDateIso), + lookup: new Map(makeLookup(id)), + tags: new Set(makeTags(id)), + count: 9_007_199_254_740_993n, + nested: makeNested(id), + points: Array.from( + { length: 4 }, + (_, index) => new BenchPoint(index * 10, index * 10 + 5), + ), + problem: new Error(`rich-problem-${id}`), + } +} + +export function makePlainSerializationData( + id: string, +): PlainSerializationPayload { + return { + label: `plain-${id}`, + createdAt: richDateIso, + lookup: makeLookup(id), + tags: makeTags(id), + count: '9007199254740993', + nested: makeNested(id), + points: makePlainPoints(), + problem: { message: `rich-problem-${id}` }, + } +} diff --git a/benchmarks/ssr/scenarios/serialization/solid/project.json b/benchmarks/ssr/scenarios/serialization/solid/project.json new file mode 100644 index 0000000000..80a4b146ac --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-serialization-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts new file mode 100644 index 0000000000..70bda8c7af --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSerializationScenario, + runRichSerializationLoop, + serializationBenchOptions, +} from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSerializationScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate rich types (solid)', async () => + runRichSerializationLoop(handler), + ).run(serializationBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts b/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts new file mode 100644 index 0000000000..d7ccb16f6f --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSerializationScenario, + runPlainSerializationLoop, + serializationBenchOptions, +} from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSerializationScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate plain control (solid)', async () => + runPlainSerializationLoop(handler), + ).run(serializationBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..b9e25f918e --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/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 PlainIdRouteImport } from './routes/plain.$id' +import { Route as RichIdRouteImport } from './routes/rich.$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) + +export interface FileRoutesByFullPath { + '/plain/$id': typeof PlainIdRoute + '/rich/$id': typeof RichIdRoute +} +export interface FileRoutesByTo { + '/plain/$id': typeof PlainIdRoute + '/rich/$id': typeof RichIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/plain/$id': typeof PlainIdRoute + '/rich/$id': typeof RichIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/plain/$id' | '/rich/$id' + fileRoutesByTo: FileRoutesByTo + to: '/plain/$id' | '/rich/$id' + id: '__root__' | '/plain/$id' | '/rich/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + PlainIdRoute: typeof PlainIdRoute + RichIdRoute: typeof RichIdRoute +} + +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' + fullPath: '/rich/$id' + preLoaderRoute: typeof RichIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + PlainIdRoute: PlainIdRoute, + RichIdRoute: RichIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { startInstance } from './start.tsx' +declare module '@tanstack/solid-start' { + interface Register { + ssr: true + router: Awaited> + config: Awaited> + } +} diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/router.tsx b/benchmarks/ssr/scenarios/serialization/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/serialization/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..e59de72236 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/routes/plain.$id.tsx b/benchmarks/ssr/scenarios/serialization/solid/src/routes/plain.$id.tsx new file mode 100644 index 0000000000..c16f73dc3f --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/src/routes/plain.$id.tsx @@ -0,0 +1,26 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { makePlainSerializationData } from '../../../shared-data' + +export const Route = createFileRoute('/plain/$id')({ + loader: ({ params }) => makePlainSerializationData(params.id), + component: PlainComponent, +}) + +function PlainComponent() { + const data = Route.useLoaderData() + const firstMapEntry = () => data().lookup[0]?.[1] + const firstTag = () => data().tags[0] + + return ( +
+

{data().label}

+

{data().createdAt}

+

{firstMapEntry()?.label}

+

{firstTag()}

+

{data().count}

+

{data().nested[0]?.id}

+

{data().points[0]?.label}

+

{data().problem.message}

+
+ ) +} diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/routes/rich.$id.tsx b/benchmarks/ssr/scenarios/serialization/solid/src/routes/rich.$id.tsx new file mode 100644 index 0000000000..e08b1e4834 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/src/routes/rich.$id.tsx @@ -0,0 +1,26 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { makeRichSerializationData } from '../../../shared-data' + +export const Route = createFileRoute('/rich/$id')({ + loader: ({ params }) => makeRichSerializationData(params.id), + component: RichComponent, +}) + +function RichComponent() { + const data = Route.useLoaderData() + const firstMapEntry = () => data().lookup.get('k0') + const firstTag = () => Array.from(data().tags)[0] + + return ( +
+

{data().label}

+

{data().createdAt.toISOString()}

+

{firstMapEntry()?.label}

+

{firstTag()}

+

{data().count.toString()}

+

{data().nested[0]?.id}

+

{data().points[0]?.label}

+

{data().problem.message}

+
+ ) +} diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/serialization.ts b/benchmarks/ssr/scenarios/serialization/solid/src/serialization.ts new file mode 100644 index 0000000000..ae84f12c9f --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/src/serialization.ts @@ -0,0 +1,10 @@ +import { createSerializationAdapter } from '@tanstack/solid-router' +import { BenchPoint, benchPointAdapterKey } from '../../shared-data' + +export const benchPointAdapter = createSerializationAdapter({ + key: benchPointAdapterKey, + test: (value): value is BenchPoint => value instanceof BenchPoint, + toSerializable: (point) => ({ x: point.x, y: point.y }), + fromSerializable: (value: { x: number; y: number }) => + new BenchPoint(value.x, value.y), +}) diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/start.tsx b/benchmarks/ssr/scenarios/serialization/solid/src/start.tsx new file mode 100644 index 0000000000..a539f2b168 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/src/start.tsx @@ -0,0 +1,9 @@ +import { createStart } from '@tanstack/solid-start' +import { benchPointAdapter } from './serialization' + +export const startInstance = createStart(() => { + return { + defaultSsr: true, + serializationAdapters: [benchPointAdapter], + } +}) diff --git a/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json b/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json new file mode 100644 index 0000000000..3ea91b977f --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared-bench.ts", + "../shared-data.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts b/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts new file mode 100644 index 0000000000..db81e2ab74 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr serialization (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/project.json b/benchmarks/ssr/scenarios/serialization/vue/project.json new file mode 100644 index 0000000000..728b5c15cc --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-serialization-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts new file mode 100644 index 0000000000..7f733dd601 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSerializationScenario, + runRichSerializationLoop, + serializationBenchOptions, +} from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSerializationScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate rich types (vue)', async () => + runRichSerializationLoop(handler), + ).run(serializationBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts b/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts new file mode 100644 index 0000000000..8efdeb6c79 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSerializationScenario, + runPlainSerializationLoop, + serializationBenchOptions, +} from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSerializationScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate plain control (vue)', async () => + runPlainSerializationLoop(handler), + ).run(serializationBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..cd7b0b449b --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/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 PlainIdRouteImport } from './routes/plain.$id' +import { Route as RichIdRouteImport } from './routes/rich.$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) + +export interface FileRoutesByFullPath { + '/plain/$id': typeof PlainIdRoute + '/rich/$id': typeof RichIdRoute +} +export interface FileRoutesByTo { + '/plain/$id': typeof PlainIdRoute + '/rich/$id': typeof RichIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/plain/$id': typeof PlainIdRoute + '/rich/$id': typeof RichIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/plain/$id' | '/rich/$id' + fileRoutesByTo: FileRoutesByTo + to: '/plain/$id' | '/rich/$id' + id: '__root__' | '/plain/$id' | '/rich/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + PlainIdRoute: typeof PlainIdRoute + RichIdRoute: typeof RichIdRoute +} + +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' + fullPath: '/rich/$id' + preLoaderRoute: typeof RichIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + PlainIdRoute: PlainIdRoute, + RichIdRoute: RichIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { startInstance } from './start.tsx' +declare module '@tanstack/vue-start' { + interface Register { + ssr: true + router: Awaited> + config: Awaited> + } +} diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/router.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..49422aac38 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/src/routes/__root.tsx @@ -0,0 +1,26 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx new file mode 100644 index 0000000000..47fdeb971f --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx @@ -0,0 +1,27 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { makePlainSerializationData } from '../../../shared-data' + +const PlainComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

{data.value.label}

+

{data.value.createdAt}

+

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

+

{data.value.tags[0]}

+

{data.value.count}

+

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

+

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

+

{data.value.problem.message}

+
+ ) + }, +}) + +export const Route = createFileRoute('/plain/$id')({ + loader: ({ params }) => makePlainSerializationData(params.id), + component: PlainComponent, +}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx new file mode 100644 index 0000000000..1ee86cefd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx @@ -0,0 +1,27 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { makeRichSerializationData } from '../../../shared-data' + +const RichComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

{data.value.label}

+

{data.value.createdAt.toISOString()}

+

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

+

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

+

{data.value.count.toString()}

+

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

+

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

+

{data.value.problem.message}

+
+ ) + }, +}) + +export const Route = createFileRoute('/rich/$id')({ + loader: ({ params }) => makeRichSerializationData(params.id), + component: RichComponent, +}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/serialization.ts b/benchmarks/ssr/scenarios/serialization/vue/src/serialization.ts new file mode 100644 index 0000000000..f8b2d8cb43 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/src/serialization.ts @@ -0,0 +1,10 @@ +import { createSerializationAdapter } from '@tanstack/vue-router' +import { BenchPoint, benchPointAdapterKey } from '../../shared-data' + +export const benchPointAdapter = createSerializationAdapter({ + key: benchPointAdapterKey, + test: (value): value is BenchPoint => value instanceof BenchPoint, + toSerializable: (point) => ({ x: point.x, y: point.y }), + fromSerializable: (value: { x: number; y: number }) => + new BenchPoint(value.x, value.y), +}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/start.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/start.tsx new file mode 100644 index 0000000000..ee27feb084 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/src/start.tsx @@ -0,0 +1,9 @@ +import { createStart } from '@tanstack/vue-start' +import { benchPointAdapter } from './serialization' + +export const startInstance = createStart(() => { + return { + defaultSsr: true, + serializationAdapters: [benchPointAdapter], + } +}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json b/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json new file mode 100644 index 0000000000..5d8c7b5b62 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared-bench.ts", + "../shared-data.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts b/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts new file mode 100644 index 0000000000..b89537fa18 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr serialization (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/bench.ts new file mode 100644 index 0000000000..4274c724ca --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/bench.ts @@ -0,0 +1,556 @@ +import { toJSONAsync } from 'seroval' +import { + createDeterministicRandom, + randomSegment, + runRequestLoop, +} from '../../bench-utils' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +type FnUrls = { + form: string + raw: string + stream: string +} + +type MultipartPayloadSpec = { + alpha: string + beta: string + gamma: string + fileName: string + fileContents: string +} + +type MultipartPayload = MultipartPayloadSpec & { + body: ArrayBuffer + contentType: string +} + +type QueryPayload = { + query: string + expectedBody: string +} + +type FrameStats = { + jsonFrames: number + chunkFrames: number + endFrames: number + errorFrames: number + chunkBytes: number +} + +export type ServerFnTransportBenchContext = { + urls: FnUrls + multipartPayloads: Array + rawPayloads: Array + streamPayloads: Array + rawExpectedBodiesByUrl: Map +} + +const benchmarkSeed = 0xdecafbad +const origin = 'http://localhost' +const tssContentTypeFramed = 'application/x-tss-framed' +const xTssSerialized = 'x-tss-serialized' +const xTssRawResponse = 'x-tss-raw' +const acceptHeader = `${tssContentTypeFramed}, application/x-ndjson, application/json` +const frameHeaderSize = 9 +const frameTypeJson = 0 +const frameTypeChunk = 1 +const frameTypeEnd = 2 +const frameTypeError = 3 +const streamChunkCount = 8 +const streamChunkSize = 1024 +const multipartFileSize = 1024 +const commonHeaders = { + 'x-tsr-serverFn': 'true', + 'sec-fetch-site': 'same-origin', + accept: acceptHeader, +} satisfies HeadersInit +const serverFnMultipartLoopTotalRequests = 128 +const serverFnRawResponseLoopTotalRequests = 176 +const serverFnRawStreamLoopTotalRequests = 112 + +export const serverFnTransportBenchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} as const + +function makeFixedSizeString(seed: string, size: number) { + let value = '' + + while (value.length < size) { + value += `${seed}:${value.length.toString(36)};` + } + + return value.slice(0, size) +} + +function createMultipartPayloadSpecs() { + const random = createDeterministicRandom(benchmarkSeed) + + return Array.from({ length: 10 }, (_, index): MultipartPayloadSpec => { + const alpha = `alpha-${index}-${randomSegment(random)}` + const beta = `beta-${index}-${randomSegment(random)}` + const gamma = `gamma-${index}-${randomSegment(random)}` + + return { + alpha, + beta, + gamma, + fileName: `bench-${index}.txt`, + fileContents: makeFixedSizeString( + `${alpha}:${beta}:${gamma}`, + multipartFileSize, + ), + } + }) +} + +async function createMultipartPayload( + spec: MultipartPayloadSpec, +): Promise { + const formData = new FormData() + formData.set('alpha', spec.alpha) + formData.set('beta', spec.beta) + formData.set('gamma', spec.gamma) + formData.set( + 'upload', + new File([spec.fileContents], spec.fileName, { type: 'text/plain' }), + ) + + const request = new Request(`${origin}/__multipart-encode`, { + method: 'POST', + body: formData, + }) + const contentType = request.headers.get('content-type') + + if (!contentType?.includes('multipart/form-data')) { + throw new Error(`Expected multipart content type, received ${contentType}`) + } + + return { + ...spec, + body: await request.arrayBuffer(), + contentType, + } +} + +async function createMultipartPayloads() { + return await Promise.all( + createMultipartPayloadSpecs().map((spec) => createMultipartPayload(spec)), + ) +} + +function createTransportInputs(prefix: string) { + const random = createDeterministicRandom(benchmarkSeed ^ prefix.length) + + return Array.from( + { length: 10 }, + (_, index) => + `${prefix}-${index}-${randomSegment(random)}-${randomSegment(random)}`, + ) +} + +async function createQueryPayloads( + inputs: Array, + expectedBody: (input: string) => string, +) { + return await Promise.all( + inputs.map(async (input): Promise => { + const body = JSON.stringify(await toJSONAsync({ data: input })) + const query = `?${new URLSearchParams({ payload: body })}` + + return { + query, + expectedBody: expectedBody(input), + } + }), + ) +} + +async function discoverUrls(handler: StartRequestHandler) { + const response = await handler.fetch(new Request(`${origin}/api/fn-urls`)) + + if (response.status === 404) { + throw new Error('URL discovery route returned 404 for /api/fn-urls') + } + + if (response.status !== 200) { + throw new Error( + `URL discovery failed with status ${response.status}: ${await response.text()}`, + ) + } + + const urls = (await response.json()) as Partial + + if ( + typeof urls.form !== 'string' || + typeof urls.raw !== 'string' || + typeof urls.stream !== 'string' + ) { + throw new Error( + `URL discovery returned invalid payload: ${JSON.stringify(urls)}`, + ) + } + + return { form: urls.form, raw: urls.raw, stream: urls.stream } +} + +function buildMultipartRequest( + urls: FnUrls, + payloads: Array, + index: number, +) { + const payload = payloads[index % payloads.length]! + + return new Request(`${origin}${urls.form}`, { + method: 'POST', + headers: { + ...commonHeaders, + 'content-type': payload.contentType, + }, + body: payload.body, + }) +} + +function buildRawResponseRequest( + urls: FnUrls, + payloads: Array, + index: number, +) { + const payload = payloads[index % payloads.length]! + + return new Request(`${origin}${urls.raw}${payload.query}`, { + method: 'GET', + headers: commonHeaders, + }) +} + +function buildRawStreamRequest( + urls: FnUrls, + payloads: Array, + index: number, +) { + const payload = payloads[index % payloads.length]! + + return new Request(`${origin}${urls.stream}${payload.query}`, { + method: 'GET', + headers: commonHeaders, + }) +} + +async function assertSerializedResponse({ + response, + label, +}: { + response: Response + label: string +}) { + const text = await response.text() + + if (response.status === 403) { + throw new Error( + `${label} sanity check failed with 403. Check CSRF headers.`, + ) + } + + if (response.status === 404) { + throw new Error( + `${label} sanity check failed with 404. The discovered server function URL is stale.`, + ) + } + + if (response.status !== 200) { + throw new Error( + `${label} sanity check failed with status ${response.status}: ${text}`, + ) + } + + if (!response.headers.get(xTssSerialized)) { + throw new Error(`${label} sanity check missing ${xTssSerialized} header`) + } + + return text +} + +function assertMultipartBody(text: string, payload: MultipartPayload) { + const expectedMarkers = [ + payload.alpha, + payload.beta, + payload.gamma, + payload.fileName, + 'fileSize', + multipartFileSize.toString(), + ] + + for (const marker of expectedMarkers) { + if (!text.includes(marker)) { + throw new Error( + `Multipart sanity check missing marker ${marker}: ${text}`, + ) + } + } +} + +async function assertRawResponse(response: Response, expectedBody: string) { + const text = await response.text() + + if (response.status !== 200) { + throw new Error( + `raw-response sanity check failed with status ${response.status}: ${text}`, + ) + } + + if (response.headers.get(xTssRawResponse) !== 'true') { + throw new Error( + `raw-response sanity check missing ${xTssRawResponse} header`, + ) + } + + if (text !== expectedBody) { + throw new Error( + `raw-response sanity check expected ${expectedBody}, received ${text}`, + ) + } +} + +function readUint32(bytes: Uint8Array, offset: number) { + return ( + (((bytes[offset] ?? 0) << 24) | + ((bytes[offset + 1] ?? 0) << 16) | + ((bytes[offset + 2] ?? 0) << 8) | + (bytes[offset + 3] ?? 0)) >>> + 0 + ) +} + +function decodeFrameStats(buffer: ArrayBuffer): FrameStats { + const bytes = new Uint8Array(buffer) + let offset = 0 + const stats: FrameStats = { + jsonFrames: 0, + chunkFrames: 0, + endFrames: 0, + errorFrames: 0, + chunkBytes: 0, + } + + while (offset < bytes.length) { + if (offset + frameHeaderSize > bytes.length) { + throw new Error(`Incomplete frame header at byte ${offset}`) + } + + const type = bytes[offset] + const length = readUint32(bytes, offset + 5) + const payloadStart = offset + frameHeaderSize + const payloadEnd = payloadStart + length + + if (payloadEnd > bytes.length) { + throw new Error(`Incomplete frame payload at byte ${offset}`) + } + + if (type === frameTypeJson) { + stats.jsonFrames++ + } else if (type === frameTypeChunk) { + stats.chunkFrames++ + stats.chunkBytes += length + } else if (type === frameTypeEnd) { + stats.endFrames++ + } else if (type === frameTypeError) { + stats.errorFrames++ + } else { + throw new Error(`Unknown frame type ${type} at byte ${offset}`) + } + + offset = payloadEnd + } + + return stats +} + +async function assertRawStream(response: Response) { + if (response.status !== 200) { + throw new Error( + `raw-stream sanity check failed with status ${response.status}: ${await response.text()}`, + ) + } + + const contentType = response.headers.get('content-type') + if (!contentType?.includes(tssContentTypeFramed)) { + throw new Error( + `raw-stream sanity check expected framed content type, received ${contentType}`, + ) + } + + if (!response.headers.get(xTssSerialized)) { + throw new Error(`raw-stream sanity check missing ${xTssSerialized} header`) + } + + const stats = decodeFrameStats(await response.arrayBuffer()) + const expectedChunkBytes = streamChunkCount * streamChunkSize + + if (stats.jsonFrames < 1) { + throw new Error('raw-stream sanity check expected at least one JSON frame') + } + + if (stats.chunkFrames !== streamChunkCount) { + throw new Error( + `raw-stream sanity check expected ${streamChunkCount} chunk frames, received ${stats.chunkFrames}`, + ) + } + + if (stats.endFrames !== 1) { + throw new Error( + `raw-stream sanity check expected one END frame, received ${stats.endFrames}`, + ) + } + + if (stats.errorFrames !== 0) { + throw new Error( + `raw-stream sanity check received ${stats.errorFrames} ERROR frames`, + ) + } + + if (stats.chunkBytes !== expectedChunkBytes) { + throw new Error( + `raw-stream sanity check expected ${expectedChunkBytes} chunk bytes, received ${stats.chunkBytes}`, + ) + } +} + +function validateStatus(response: Response, request: Request) { + if (response.status !== 200) { + throw new Error( + `Request failed with non-200 status ${response.status} (${request.url})`, + ) + } +} + +function validateSerializedResponse(response: Response, request: Request) { + validateStatus(response, request) + + if (!response.headers.get(xTssSerialized)) { + throw new Error(`Request missing ${xTssSerialized} header (${request.url})`) + } +} + +function validateRawResponse(response: Response, request: Request) { + validateStatus(response, request) + + if (response.headers.get(xTssRawResponse) !== 'true') { + throw new Error( + `Request missing ${xTssRawResponse} header (${request.url})`, + ) + } +} + +function validateRawStreamResponse(response: Response, request: Request) { + validateSerializedResponse(response, request) + + const contentType = response.headers.get('content-type') + if (!contentType?.includes(tssContentTypeFramed)) { + throw new Error( + `Request missing framed content type (${request.url}): ${contentType}`, + ) + } +} + +export async function setupServerFnTransportBench( + handler: StartRequestHandler, +) { + const urls = await discoverUrls(handler) + const multipartPayloads = await createMultipartPayloads() + const rawPayloads = await createQueryPayloads( + createTransportInputs('raw'), + (input) => `raw-${input}`, + ) + const streamPayloads = await createQueryPayloads( + createTransportInputs('stream'), + (input) => `stream-${input}`, + ) + const rawExpectedBodiesByUrl = new Map( + rawPayloads.map((payload) => [ + `${origin}${urls.raw}${payload.query}`, + payload.expectedBody, + ]), + ) + + return { + urls, + multipartPayloads, + rawPayloads, + streamPayloads, + rawExpectedBodiesByUrl, + } +} + +export async function assertServerFnTransportScenario( + handler: StartRequestHandler, + context: ServerFnTransportBenchContext, +) { + const multipartPayload = context.multipartPayloads[0]! + const multipartText = await assertSerializedResponse({ + response: await handler.fetch( + buildMultipartRequest(context.urls, context.multipartPayloads, 0), + ), + label: 'multipart', + }) + assertMultipartBody(multipartText, multipartPayload) + + await assertRawResponse( + await handler.fetch( + buildRawResponseRequest(context.urls, context.rawPayloads, 0), + ), + context.rawPayloads[0]!.expectedBody, + ) + + await assertRawStream( + await handler.fetch( + buildRawStreamRequest(context.urls, context.streamPayloads, 0), + ), + ) +} + +export function runServerFnMultipartRequestLoop( + handler: StartRequestHandler, + context: ServerFnTransportBenchContext, +) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: serverFnMultipartLoopTotalRequests, + buildRequest: (_random, index) => + buildMultipartRequest(context.urls, context.multipartPayloads, index), + validateResponse: validateSerializedResponse, + }) +} + +export function runServerFnRawResponseRequestLoop( + handler: StartRequestHandler, + context: ServerFnTransportBenchContext, +) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: serverFnRawResponseLoopTotalRequests, + buildRequest: (_random, index) => + buildRawResponseRequest(context.urls, context.rawPayloads, index), + validateResponse: validateRawResponse, + }) +} + +export function runServerFnRawStreamRequestLoop( + handler: StartRequestHandler, + context: ServerFnTransportBenchContext, +) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: serverFnRawStreamLoopTotalRequests, + buildRequest: (_random, index) => + buildRawStreamRequest(context.urls, context.streamPayloads, index), + validateResponse: validateRawStreamResponse, + }) +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/project.json b/benchmarks/ssr/scenarios/server-fn-transport/react/project.json new file mode 100644 index 0000000000..a3012549ca --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-server-fn-transport-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts new file mode 100644 index 0000000000..fa80cdb690 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnMultipartRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn multipart (react)', async () => + runServerFnMultipartRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-response.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-response.bench.ts new file mode 100644 index 0000000000..fd535ee313 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-response.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawResponseRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn raw-response (react)', async () => + runServerFnRawResponseRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-stream.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-stream.bench.ts new file mode 100644 index 0000000000..8fbce405dd --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-stream.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawStreamRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn raw-stream (react)', async () => + runServerFnRawStreamRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/src/fns.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/src/fns.ts new file mode 100644 index 0000000000..79ecb50e87 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/src/fns.ts @@ -0,0 +1,101 @@ +import { RawStream, createServerFn } from '@tanstack/react-start' + +type FormEchoData = { + alpha: string + beta: string + gamma: string + upload: File +} + +const streamChunkCount = 8 +const streamChunkSize = 1024 + +function getStringField(formData: FormData, field: string) { + const value = formData.get(field) + + if (typeof value !== 'string') { + throw new Error(`Expected ${field} to be a string`) + } + + return value +} + +function validateFormData(input: unknown): FormEchoData { + if (!(input instanceof FormData)) { + throw new Error('Expected FormData input') + } + + const upload = input.get('upload') + if (!(upload instanceof File)) { + throw new Error('Expected upload to be a File') + } + + return { + alpha: getStringField(input, 'alpha'), + beta: getStringField(input, 'beta'), + gamma: getStringField(input, 'gamma'), + upload, + } +} + +function validateString(input: unknown) { + if (typeof input !== 'string' || input.length === 0) { + throw new Error('Expected non-empty string input') + } + + return input +} + +function createDeterministicStream(seed: string) { + return new ReadableStream({ + start(controller) { + for (let chunkIndex = 0; chunkIndex < streamChunkCount; chunkIndex++) { + const chunk = new Uint8Array(streamChunkSize) + + for (let byteIndex = 0; byteIndex < chunk.length; byteIndex++) { + chunk[byteIndex] = + (seed.charCodeAt(byteIndex % seed.length) + + byteIndex + + chunkIndex) & + 0xff + } + + controller.enqueue(chunk) + } + + controller.close() + }, + }) +} + +export const formEcho = createServerFn({ method: 'POST' }) + .validator(validateFormData) + .handler(async ({ data }) => { + const contents = await data.upload.text() + + return { + alpha: data.alpha, + beta: data.beta, + gamma: data.gamma, + fileName: data.upload.name, + fileSize: data.upload.size, + filePreview: contents.slice(0, 32), + } + }) + +export const rawResp = createServerFn({ method: 'GET' }) + .validator(validateString) + .handler(({ data }) => { + return new Response(`raw-${data}`, { + headers: { 'content-type': 'text/plain' }, + }) + }) + +export const streamOut = createServerFn({ method: 'GET' }) + .validator(validateString) + .handler(({ data }) => { + return { + label: `stream-${data}`, + data: new RawStream(createDeterministicStream(data)), + } + }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..10e933da3d --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/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 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) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/fn-urls' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/fn-urls' + id: '__root__' | '/' | '/api/fn-urls' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiFnUrlsRoute: typeof ApiFnUrlsRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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 + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiFnUrlsRoute: ApiFnUrlsRoute, +} +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/benchmarks/ssr/scenarios/server-fn-transport/react/src/router.tsx b/benchmarks/ssr/scenarios/server-fn-transport/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/__root.tsx new file mode 100644 index 0000000000..ff1da4c304 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/api.fn-urls.ts new file mode 100644 index 0000000000..02260e5098 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/api.fn-urls.ts @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' +import { formEcho, rawResp, streamOut } from '../fns' + +export const Route = createFileRoute('/api/fn-urls')({ + server: { + handlers: { + GET: () => + Response.json({ + form: formEcho.url, + raw: rawResp.url, + stream: streamOut.url, + }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/index.tsx new file mode 100644 index 0000000000..baa0026378 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/src/routes/index.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/react-router' +import { formEcho, rawResp, streamOut } from '../fns' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return ( +
+ server-fn transport benchmark +
+ ) +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json b/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json new file mode 100644 index 0000000000..4f3cc314af --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../bench.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts new file mode 100644 index 0000000000..c37fde0c4b --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr server-fn-transport (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/project.json b/benchmarks/ssr/scenarios/server-fn-transport/solid/project.json new file mode 100644 index 0000000000..16fc151b11 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-server-fn-transport-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts new file mode 100644 index 0000000000..adac07cb22 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnMultipartRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn multipart (solid)', async () => + runServerFnMultipartRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-response.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-response.bench.ts new file mode 100644 index 0000000000..843a4c97ce --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-response.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawResponseRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn raw-response (solid)', async () => + runServerFnRawResponseRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-stream.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-stream.bench.ts new file mode 100644 index 0000000000..aa24d55e79 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-stream.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawStreamRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn raw-stream (solid)', async () => + runServerFnRawStreamRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/fns.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/fns.ts new file mode 100644 index 0000000000..3c586fa2ee --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/fns.ts @@ -0,0 +1,101 @@ +import { RawStream, createServerFn } from '@tanstack/solid-start' + +type FormEchoData = { + alpha: string + beta: string + gamma: string + upload: File +} + +const streamChunkCount = 8 +const streamChunkSize = 1024 + +function getStringField(formData: FormData, field: string) { + const value = formData.get(field) + + if (typeof value !== 'string') { + throw new Error(`Expected ${field} to be a string`) + } + + return value +} + +function validateFormData(input: unknown): FormEchoData { + if (!(input instanceof FormData)) { + throw new Error('Expected FormData input') + } + + const upload = input.get('upload') + if (!(upload instanceof File)) { + throw new Error('Expected upload to be a File') + } + + return { + alpha: getStringField(input, 'alpha'), + beta: getStringField(input, 'beta'), + gamma: getStringField(input, 'gamma'), + upload, + } +} + +function validateString(input: unknown) { + if (typeof input !== 'string' || input.length === 0) { + throw new Error('Expected non-empty string input') + } + + return input +} + +function createDeterministicStream(seed: string) { + return new ReadableStream({ + start(controller) { + for (let chunkIndex = 0; chunkIndex < streamChunkCount; chunkIndex++) { + const chunk = new Uint8Array(streamChunkSize) + + for (let byteIndex = 0; byteIndex < chunk.length; byteIndex++) { + chunk[byteIndex] = + (seed.charCodeAt(byteIndex % seed.length) + + byteIndex + + chunkIndex) & + 0xff + } + + controller.enqueue(chunk) + } + + controller.close() + }, + }) +} + +export const formEcho = createServerFn({ method: 'POST' }) + .validator(validateFormData) + .handler(async ({ data }) => { + const contents = await data.upload.text() + + return { + alpha: data.alpha, + beta: data.beta, + gamma: data.gamma, + fileName: data.upload.name, + fileSize: data.upload.size, + filePreview: contents.slice(0, 32), + } + }) + +export const rawResp = createServerFn({ method: 'GET' }) + .validator(validateString) + .handler(({ data }) => { + return new Response(`raw-${data}`, { + headers: { 'content-type': 'text/plain' }, + }) + }) + +export const streamOut = createServerFn({ method: 'GET' }) + .validator(validateString) + .handler(({ data }) => { + return { + label: `stream-${data}`, + data: new RawStream(createDeterministicStream(data)), + } + }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..298ac3168d --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/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 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) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/fn-urls' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/fn-urls' + id: '__root__' | '/' | '/api/fn-urls' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiFnUrlsRoute: typeof ApiFnUrlsRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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 + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiFnUrlsRoute: ApiFnUrlsRoute, +} +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/benchmarks/ssr/scenarios/server-fn-transport/solid/src/router.tsx b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..e59de72236 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/api.fn-urls.ts new file mode 100644 index 0000000000..353a732637 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/api.fn-urls.ts @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { formEcho, rawResp, streamOut } from '../fns' + +export const Route = createFileRoute('/api/fn-urls')({ + server: { + handlers: { + GET: () => + Response.json({ + form: formEcho.url, + raw: rawResp.url, + stream: streamOut.url, + }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/index.tsx new file mode 100644 index 0000000000..6e0e5d8d6b --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/src/routes/index.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { formEcho, rawResp, streamOut } from '../fns' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return ( +
+ server-fn transport benchmark +
+ ) +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json b/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json new file mode 100644 index 0000000000..0af78df33d --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../bench.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts new file mode 100644 index 0000000000..a8af4a6b50 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr server-fn-transport (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/project.json b/benchmarks/ssr/scenarios/server-fn-transport/vue/project.json new file mode 100644 index 0000000000..abdd85c6b7 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-server-fn-transport-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts new file mode 100644 index 0000000000..24305cf1bc --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnMultipartRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn multipart (vue)', async () => + runServerFnMultipartRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-response.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-response.bench.ts new file mode 100644 index 0000000000..2eeb9a4f6b --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-response.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawResponseRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn raw-response (vue)', async () => + runServerFnRawResponseRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-stream.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-stream.bench.ts new file mode 100644 index 0000000000..a73905004d --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-stream.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawStreamRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn raw-stream (vue)', async () => + runServerFnRawStreamRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/fns.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/fns.ts new file mode 100644 index 0000000000..f7e1a1217a --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/fns.ts @@ -0,0 +1,101 @@ +import { RawStream, createServerFn } from '@tanstack/vue-start' + +type FormEchoData = { + alpha: string + beta: string + gamma: string + upload: File +} + +const streamChunkCount = 8 +const streamChunkSize = 1024 + +function getStringField(formData: FormData, field: string) { + const value = formData.get(field) + + if (typeof value !== 'string') { + throw new Error(`Expected ${field} to be a string`) + } + + return value +} + +function validateFormData(input: unknown): FormEchoData { + if (!(input instanceof FormData)) { + throw new Error('Expected FormData input') + } + + const upload = input.get('upload') + if (!(upload instanceof File)) { + throw new Error('Expected upload to be a File') + } + + return { + alpha: getStringField(input, 'alpha'), + beta: getStringField(input, 'beta'), + gamma: getStringField(input, 'gamma'), + upload, + } +} + +function validateString(input: unknown) { + if (typeof input !== 'string' || input.length === 0) { + throw new Error('Expected non-empty string input') + } + + return input +} + +function createDeterministicStream(seed: string) { + return new ReadableStream({ + start(controller) { + for (let chunkIndex = 0; chunkIndex < streamChunkCount; chunkIndex++) { + const chunk = new Uint8Array(streamChunkSize) + + for (let byteIndex = 0; byteIndex < chunk.length; byteIndex++) { + chunk[byteIndex] = + (seed.charCodeAt(byteIndex % seed.length) + + byteIndex + + chunkIndex) & + 0xff + } + + controller.enqueue(chunk) + } + + controller.close() + }, + }) +} + +export const formEcho = createServerFn({ method: 'POST' }) + .validator(validateFormData) + .handler(async ({ data }) => { + const contents = await data.upload.text() + + return { + alpha: data.alpha, + beta: data.beta, + gamma: data.gamma, + fileName: data.upload.name, + fileSize: data.upload.size, + filePreview: contents.slice(0, 32), + } + }) + +export const rawResp = createServerFn({ method: 'GET' }) + .validator(validateString) + .handler(({ data }) => { + return new Response(`raw-${data}`, { + headers: { 'content-type': 'text/plain' }, + }) + }) + +export const streamOut = createServerFn({ method: 'GET' }) + .validator(validateString) + .handler(({ data }) => { + return { + label: `stream-${data}`, + data: new RawStream(createDeterministicStream(data)), + } + }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..b226f0a25a --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/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 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) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/fn-urls' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/fn-urls' + id: '__root__' | '/' | '/api/fn-urls' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiFnUrlsRoute: typeof ApiFnUrlsRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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 + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiFnUrlsRoute: ApiFnUrlsRoute, +} +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/benchmarks/ssr/scenarios/server-fn-transport/vue/src/router.tsx b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..49422aac38 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/__root.tsx @@ -0,0 +1,26 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/api.fn-urls.ts new file mode 100644 index 0000000000..2db00972bb --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/api.fn-urls.ts @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { formEcho, rawResp, streamOut } from '../fns' + +export const Route = createFileRoute('/api/fn-urls')({ + server: { + handlers: { + GET: () => + Response.json({ + form: formEcho.url, + raw: rawResp.url, + stream: streamOut.url, + }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/index.tsx new file mode 100644 index 0000000000..d53731eb23 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/src/routes/index.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { formEcho, rawResp, streamOut } from '../fns' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return ( +
+ server-fn transport benchmark +
+ ) +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json b/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json new file mode 100644 index 0000000000..5b7742b414 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../bench.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts new file mode 100644 index 0000000000..0f3e2ce84d --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr server-fn-transport (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/server-fns/bench.ts b/benchmarks/ssr/scenarios/server-fns/bench.ts new file mode 100644 index 0000000000..1461ce2bfd --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/bench.ts @@ -0,0 +1,533 @@ +import { fromCrossJSON, toJSONAsync } from 'seroval' +import { + createDeterministicRandom, + randomSegment, + runRequestLoop, +} from '../../bench-utils' +import type { StartRequestHandler } from '../../bench-utils' +import type { SerovalNode } from 'seroval' + +export type { StartRequestHandler } + +type Payload = { + q: string + n: number + nested: { list: Array } +} + +type FnUrls = { + get: string + post: string + redirect: string + notFound: string + context: string +} + +export type ServerFnBenchContext = { + urls: FnUrls + bodies: Array + getQueries: Array + expectedMarker: string + contextBodies: Array + contextExpectedMarkers: Array + contextExpectedStamps: Array +} + +const benchmarkSeed = 0xdecafbad +const origin = 'http://localhost' +const tssContentTypeFramed = 'application/x-tss-framed' +const xTssSerialized = 'x-tss-serialized' +const acceptHeader = `${tssContentTypeFramed}, application/x-ndjson, application/json` +const commonHeaders = { + 'x-tsr-serverFn': 'true', + 'sec-fetch-site': 'same-origin', + accept: acceptHeader, +} satisfies HeadersInit +const postHeaders = { + ...commonHeaders, + 'content-type': 'application/json', +} satisfies HeadersInit +const documentRequestInit = { + method: 'GET', + headers: { + accept: 'text/html', + }, +} satisfies RequestInit +const serverFnGetLoopTotalRequests = 112 +const serverFnPostLoopTotalRequests = 160 +const serverFnRedirectLoopTotalRequests = 128 +const serverFnNotFoundLoopTotalRequests = 208 +const serverFnSendContextLoopTotalRequests = 176 +const serverFnDocumentSsrLoopTotalRequests = 48 + +export const serverFnBenchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} as const + +function createPayloads() { + const random = createDeterministicRandom(benchmarkSeed) + + return Array.from({ length: 10 }, (_, index): Payload => { + const queryParts = Array.from({ length: 6 }, () => randomSegment(random)) + + return { + q: `q-${index}-${queryParts.join('-')}`, + n: 100 + index, + nested: { + list: Array.from( + { length: 5 }, + () => `l-${index}-${randomSegment(random)}-${randomSegment(random)}`, + ), + }, + } + }) +} + +async function createBodies(payloads: Array) { + return await Promise.all( + payloads.map(async (payload) => + JSON.stringify(await toJSONAsync({ data: payload })), + ), + ) +} + +function createContextToken(payload: Payload) { + return `token-${payload.q}-${payload.nested.list[0]}` +} + +async function createContextFixtures(payloads: Array) { + return await Promise.all( + payloads.map(async (payload) => { + const token = createContextToken(payload) + + return { + body: JSON.stringify( + await toJSONAsync({ data: payload, context: { token } }), + ), + marker: `ctx-${token}-${payload.nested.list[0]}`, + stamp: `stamp-${token}`, + } + }), + ) +} + +function createGetQueries(bodies: Array) { + return bodies.map((body) => `?${new URLSearchParams({ payload: body })}`) +} + +async function discoverUrls(handler: StartRequestHandler) { + const response = await handler.fetch(new Request(`${origin}/api/fn-urls`)) + + if (response.status === 404) { + throw new Error('URL discovery route returned 404 for /api/fn-urls') + } + + if (response.status !== 200) { + throw new Error( + `URL discovery failed with status ${response.status}: ${await response.text()}`, + ) + } + + const urls = (await response.json()) as Partial + const requiredKeys = [ + 'get', + 'post', + 'redirect', + 'notFound', + 'context', + ] as const + + for (const key of requiredKeys) { + if (typeof urls[key] !== 'string') { + throw new Error( + `URL discovery returned invalid payload: ${JSON.stringify(urls)}`, + ) + } + } + + return urls as FnUrls +} + +function validateSerializedResponse(response: Response, label: string) { + if (response.status === 403) { + throw new Error( + `${label} sanity check failed with 403. Check CSRF headers.`, + ) + } + + if (response.status === 404) { + throw new Error( + `${label} sanity check failed with 404. The discovered server function URL is stale.`, + ) + } + + if (response.status !== 200) { + throw new Error(`${label} request failed with status ${response.status}`) + } + + if (!response.headers.get(xTssSerialized)) { + throw new Error(`${label} response missing ${xTssSerialized} header`) + } +} + +function validateRedirectResponse(response: Response) { + if (response.status !== 200) { + throw new Error(`redirect request failed with status ${response.status}`) + } + + const contentType = response.headers.get('content-type') + + if (!contentType?.includes('application/json')) { + throw new Error(`redirect response was not JSON: ${contentType}`) + } +} + +function validateDocumentResponse(response: Response) { + if (response.status !== 200) { + throw new Error(`document request failed with status ${response.status}`) + } + + const contentType = response.headers.get('content-type') + + if (!contentType?.includes('text/html')) { + throw new Error(`document response was not HTML: ${contentType}`) + } +} + +async function readSerializedServerFnResult(response: Response, label: string) { + const text = await response.text() + + validateSerializedResponse(response, label) + + let json: unknown + + try { + json = JSON.parse(text) + } catch (error) { + throw new Error(`${label} sanity check returned invalid JSON: ${text}`, { + cause: error, + }) + } + + return { text, decoded: fromCrossJSON(json as SerovalNode, {}) } +} + +async function assertServerFnResponse({ + response, + label, + expectedMarker, +}: { + response: Response + label: string + expectedMarker: string +}) { + const { text } = await readSerializedServerFnResult(response, label) + + if (!text.includes(expectedMarker)) { + throw new Error( + `${label} sanity check did not include expected marker ${expectedMarker}: ${text}`, + ) + } +} + +async function assertServerFnRedirectResponse(response: Response) { + const text = await response.text() + + if (response.status !== 200) { + throw new Error( + `redirect sanity check failed with status ${response.status}: ${text}`, + ) + } + + let payload: { + href?: string + isSerializedRedirect?: boolean + statusCode?: number + } + + try { + payload = JSON.parse(text) as typeof payload + } catch (error) { + throw new Error(`redirect sanity check returned invalid JSON: ${text}`, { + cause: error, + }) + } + + if ( + payload.href !== '/' || + payload.statusCode !== 307 || + payload.isSerializedRedirect !== true + ) { + throw new Error( + `redirect sanity check expected serialized redirect to /, got ${text}`, + ) + } +} + +async function assertServerFnNotFoundResponse(response: Response) { + const { decoded } = await readSerializedServerFnResult(response, 'not-found') + const payload = decoded as { error?: { isNotFound?: boolean } } + + if (payload.error?.isNotFound !== true) { + throw new Error( + `not-found sanity check did not include isNotFound error: ${JSON.stringify(decoded)}`, + ) + } +} + +async function assertServerFnContextResponse({ + response, + expectedMarker, + expectedStamp, +}: { + response: Response + expectedMarker: string + expectedStamp: string +}) { + const { decoded } = await readSerializedServerFnResult( + response, + 'send-context', + ) + const payload = decoded as { + result?: { marker?: string; token?: string } + context?: { stamp?: string } + } + + if (payload.result?.marker !== expectedMarker) { + throw new Error( + `send-context sanity check expected result marker ${expectedMarker}, got ${JSON.stringify(decoded)}`, + ) + } + + if (payload.context?.stamp !== expectedStamp) { + throw new Error( + `send-context sanity check expected response context ${expectedStamp}, got ${JSON.stringify(decoded)}`, + ) + } +} + +async function assertDocumentServerFnCallResponse(response: Response) { + const text = await response.text() + const expectedMarker = 'out-ssr-call-sanity-ssr' + + if (response.status !== 200) { + throw new Error( + `SSR-call sanity check failed with status ${response.status}: ${text}`, + ) + } + + const contentType = response.headers.get('content-type') + + if (!contentType?.includes('text/html')) { + throw new Error(`SSR-call sanity check was not HTML: ${contentType}`) + } + + if (response.headers.get(xTssSerialized)) { + throw new Error('SSR-call sanity check returned a server-fn RPC response') + } + + if (!text.includes('data-bench="server-fn-ssr-call"')) { + throw new Error('SSR-call sanity check missing document marker') + } + + if (!text.includes(expectedMarker)) { + throw new Error( + `SSR-call sanity check missing expected marker ${expectedMarker}`, + ) + } +} + +function buildGetRequest(urls: FnUrls, queries: Array, index: number) { + return new Request(`${origin}${urls.get}${queries[index % queries.length]}`, { + method: 'GET', + headers: commonHeaders, + }) +} + +function buildPostUrlRequest( + url: string, + bodies: Array, + index: number, +) { + return new Request(`${origin}${url}`, { + method: 'POST', + headers: postHeaders, + body: bodies[index % bodies.length], + }) +} + +function buildPostRequest(urls: FnUrls, bodies: Array, index: number) { + return buildPostUrlRequest(urls.post, bodies, index) +} + +function buildRedirectRequest( + urls: FnUrls, + bodies: Array, + index: number, +) { + return buildPostUrlRequest(urls.redirect, bodies, index) +} + +function buildNotFoundRequest( + urls: FnUrls, + bodies: Array, + index: number, +) { + return buildPostUrlRequest(urls.notFound, bodies, index) +} + +function buildContextRequest( + urls: FnUrls, + contextBodies: Array, + index: number, +) { + return buildPostUrlRequest(urls.context, contextBodies, index) +} + +function buildSsrCallRequest(random: () => number) { + return new Request( + `${origin}/ssr-call/${randomSegment(random)}`, + documentRequestInit, + ) +} + +export async function setupServerFnBench(handler: StartRequestHandler) { + const urls = await discoverUrls(handler) + const payloads = createPayloads() + const bodies = await createBodies(payloads) + const contextFixtures = await createContextFixtures(payloads) + const getQueries = createGetQueries(bodies) + const expectedMarker = `out-${payloads[0]!.nested.list[0]}` + + return { + urls, + bodies, + getQueries, + expectedMarker, + contextBodies: contextFixtures.map((fixture) => fixture.body), + contextExpectedMarkers: contextFixtures.map((fixture) => fixture.marker), + contextExpectedStamps: contextFixtures.map((fixture) => fixture.stamp), + } +} + +export async function assertServerFnScenario( + handler: StartRequestHandler, + context: ServerFnBenchContext, +) { + await assertServerFnResponse({ + response: await handler.fetch( + buildGetRequest(context.urls, context.getQueries, 0), + ), + label: 'GET', + expectedMarker: context.expectedMarker, + }) + await assertServerFnResponse({ + response: await handler.fetch( + buildPostRequest(context.urls, context.bodies, 0), + ), + label: 'POST', + expectedMarker: context.expectedMarker, + }) + await assertServerFnRedirectResponse( + await handler.fetch(buildRedirectRequest(context.urls, context.bodies, 0)), + ) + await assertServerFnNotFoundResponse( + await handler.fetch(buildNotFoundRequest(context.urls, context.bodies, 0)), + ) + await assertServerFnContextResponse({ + response: await handler.fetch( + buildContextRequest(context.urls, context.contextBodies, 0), + ), + expectedMarker: context.contextExpectedMarkers[0]!, + expectedStamp: context.contextExpectedStamps[0]!, + }) + await assertDocumentServerFnCallResponse( + await handler.fetch( + new Request(`${origin}/ssr-call/sanity-ssr`, documentRequestInit), + ), + ) +} + +export function runServerFnGetRequestLoop( + handler: StartRequestHandler, + context: ServerFnBenchContext, +) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: serverFnGetLoopTotalRequests, + buildRequest: (_random, index) => + buildGetRequest(context.urls, context.getQueries, index), + }) +} + +export function runServerFnPostRequestLoop( + handler: StartRequestHandler, + context: ServerFnBenchContext, +) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: serverFnPostLoopTotalRequests, + buildRequest: (_random, index) => + buildPostRequest(context.urls, context.bodies, index), + }) +} + +export function runServerFnRedirectRequestLoop( + handler: StartRequestHandler, + context: ServerFnBenchContext, +) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: serverFnRedirectLoopTotalRequests, + buildRequest: (_random, index) => + buildRedirectRequest(context.urls, context.bodies, index), + validateResponse: validateRedirectResponse, + }) +} + +export function runServerFnNotFoundRequestLoop( + handler: StartRequestHandler, + context: ServerFnBenchContext, +) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: serverFnNotFoundLoopTotalRequests, + buildRequest: (_random, index) => + buildNotFoundRequest(context.urls, context.bodies, index), + validateResponse: (response) => + validateSerializedResponse(response, 'not-found'), + }) +} + +export function runServerFnSendContextRequestLoop( + handler: StartRequestHandler, + context: ServerFnBenchContext, +) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: serverFnSendContextLoopTotalRequests, + buildRequest: (_random, index) => + buildContextRequest(context.urls, context.contextBodies, index), + validateResponse: (response) => + validateSerializedResponse(response, 'send-context'), + }) +} + +export function runServerFnDocumentSsrRequestLoop( + handler: StartRequestHandler, +) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: serverFnDocumentSsrLoopTotalRequests, + buildRequest: buildSsrCallRequest, + validateResponse: validateDocumentResponse, + }) +} diff --git a/benchmarks/ssr/scenarios/server-fns/react/project.json b/benchmarks/ssr/scenarios/server-fns/react/project.json new file mode 100644 index 0000000000..8858309f35 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-server-fns-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts new file mode 100644 index 0000000000..c876772ad1 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnGetRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn GET (react)', async () => + runServerFnGetRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-during-document-ssr.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-during-document-ssr.bench.ts new file mode 100644 index 0000000000..6a0cb55f78 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-during-document-ssr.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnDocumentSsrRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn during document ssr (react)', async () => + runServerFnDocumentSsrRequestLoop(handler), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-not-found.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-not-found.bench.ts new file mode 100644 index 0000000000..96f1160078 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnNotFoundRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn not-found (react)', async () => + runServerFnNotFoundRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-post.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-post.bench.ts new file mode 100644 index 0000000000..e85d5debd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-post.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnPostRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn POST (react)', async () => + runServerFnPostRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-redirect.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-redirect.bench.ts new file mode 100644 index 0000000000..5dae598549 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-redirect.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnRedirectRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn redirect (react)', async () => + runServerFnRedirectRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-send-context.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-send-context.bench.ts new file mode 100644 index 0000000000..40d6961206 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-send-context.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnSendContextRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn send-context (react)', async () => + runServerFnSendContextRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/src/fns.ts b/benchmarks/ssr/scenarios/server-fns/react/src/fns.ts new file mode 100644 index 0000000000..ce2ba48c5b --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/src/fns.ts @@ -0,0 +1,87 @@ +import { createMiddleware, createServerFn } from '@tanstack/react-start' +import { notFound, redirect } from '@tanstack/react-router' + +const mwA = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { a: 1 } }), +) +const mwB = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { b: 2 } }), +) + +const sendContextMw = createMiddleware({ type: 'function' }) + .client(({ data, next }) => { + return next({ + sendContext: { token: createContextToken(data as unknown as Payload) }, + }) + }) + .server(({ context, next }) => { + const { token } = context as { token?: string } + + if (typeof token !== 'string') { + throw new Error('missing sendContext token') + } + + return next({ + context: { token }, + sendContext: { stamp: `stamp-${token}` }, + }) + }) + +type Payload = { q: string; n: number; nested: { list: Array } } + +function createContextToken(data: Payload) { + return `token-${data.q}-${data.nested.list[0]}` +} + +const validate = (input: unknown): Payload => { + const p = input as Payload + + if ( + typeof p?.q !== 'string' || + typeof p?.n !== 'number' || + !Array.isArray(p?.nested?.list) + ) { + throw new Error('invalid payload') + } + + return p +} + +function echo(data: Payload, context: { a: number; b: number }) { + return { + echoed: data, + sum: data.n + context.a + context.b, + list: data.nested.list.map((s) => `out-${s}`), + } +} + +export const echoGet = createServerFn({ method: 'GET' }) + .middleware([mwA, mwB]) + .validator(validate) + .handler(({ data, context }) => echo(data, context)) + +export const echoPost = createServerFn({ method: 'POST' }) + .middleware([mwA, mwB]) + .validator(validate) + .handler(({ data, context }) => echo(data, context)) + +export const redirector = createServerFn({ method: 'POST' }).handler(() => { + throw redirect({ to: '/', statusCode: 307 }) +}) + +export const notFounder = createServerFn({ method: 'POST' }).handler(() => { + throw notFound() +}) + +export const ctxEcho = createServerFn({ method: 'POST' }) + .middleware([sendContextMw]) + .validator(validate) + .handler(({ data, context }) => { + const { token } = context as { token: string } + + return { + marker: `ctx-${token}-${data.nested.list[0]}`, + q: data.q, + token, + } + }) diff --git a/benchmarks/ssr/scenarios/server-fns/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fns/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..4daa5f03b0 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/src/routeTree.gen.ts @@ -0,0 +1,104 @@ +/* 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 ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ + id: '/api/fn-urls', + path: '/api/fn-urls', + getParentRoute: () => rootRouteImport, +} as any) +const SsrCallIdRoute = SsrCallIdRouteImport.update({ + id: '/ssr-call/$id', + path: '/ssr-call/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/ssr-call/$id': typeof SsrCallIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/ssr-call/$id': typeof SsrCallIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/ssr-call/$id': typeof SsrCallIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/fn-urls' | '/ssr-call/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/fn-urls' | '/ssr-call/$id' + id: '__root__' | '/' | '/api/fn-urls' | '/ssr-call/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiFnUrlsRoute: typeof ApiFnUrlsRoute + SsrCallIdRoute: typeof SsrCallIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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' + fullPath: '/ssr-call/$id' + preLoaderRoute: typeof SsrCallIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiFnUrlsRoute: ApiFnUrlsRoute, + SsrCallIdRoute: SsrCallIdRoute, +} +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/benchmarks/ssr/scenarios/server-fns/react/src/router.tsx b/benchmarks/ssr/scenarios/server-fns/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/server-fns/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-fns/react/src/routes/__root.tsx new file mode 100644 index 0000000000..ff1da4c304 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/server-fns/react/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/server-fns/react/src/routes/api.fn-urls.ts new file mode 100644 index 0000000000..ed3d9a9b7b --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/src/routes/api.fn-urls.ts @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/react-router' +import { ctxEcho, echoGet, echoPost, notFounder, redirector } from '../fns' + +export const Route = createFileRoute('/api/fn-urls')({ + server: { + handlers: { + GET: () => + Response.json({ + get: echoGet.url, + post: echoPost.url, + redirect: redirector.url, + notFound: notFounder.url, + context: ctxEcho.url, + }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-fns/react/src/routes/index.tsx new file mode 100644 index 0000000000..45636ef30e --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/src/routes/index.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' +import { echoGet, echoPost } from '../fns' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return ( +
+ server-fns +
+ ) +} diff --git a/benchmarks/ssr/scenarios/server-fns/react/src/routes/ssr-call.$id.tsx b/benchmarks/ssr/scenarios/server-fns/react/src/routes/ssr-call.$id.tsx new file mode 100644 index 0000000000..0f8a39f69d --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/src/routes/ssr-call.$id.tsx @@ -0,0 +1,23 @@ +import { createFileRoute } from '@tanstack/react-router' +import { echoGet } from '../fns' + +export const Route = createFileRoute('/ssr-call/$id')({ + loader: async ({ params }) => { + const result = await echoGet({ + data: { + q: `ssr-${params.id}`, + n: 300, + nested: { list: [`ssr-call-${params.id}`] }, + }, + }) + + return { marker: result.list[0] } + }, + component: SsrCallComponent, +}) + +function SsrCallComponent() { + const data = Route.useLoaderData() + + return
{data.marker}
+} diff --git a/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json b/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json new file mode 100644 index 0000000000..cf14e1d440 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/server-fns/react/vite.config.ts b/benchmarks/ssr/scenarios/server-fns/react/vite.config.ts new file mode 100644 index 0000000000..cd56edda95 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr server-fns (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/project.json b/benchmarks/ssr/scenarios/server-fns/solid/project.json new file mode 100644 index 0000000000..f1e9581897 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-server-fns-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts new file mode 100644 index 0000000000..f6bbdc9e73 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnGetRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn GET (solid)', async () => + runServerFnGetRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-during-document-ssr.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-during-document-ssr.bench.ts new file mode 100644 index 0000000000..933f61b59c --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-during-document-ssr.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnDocumentSsrRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn during document ssr (solid)', async () => + runServerFnDocumentSsrRequestLoop(handler), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-not-found.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-not-found.bench.ts new file mode 100644 index 0000000000..513b69f4ba --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnNotFoundRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn not-found (solid)', async () => + runServerFnNotFoundRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-post.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-post.bench.ts new file mode 100644 index 0000000000..e2ce8ad9ee --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-post.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnPostRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn POST (solid)', async () => + runServerFnPostRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-redirect.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-redirect.bench.ts new file mode 100644 index 0000000000..14353f1290 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-redirect.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnRedirectRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn redirect (solid)', async () => + runServerFnRedirectRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-send-context.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-send-context.bench.ts new file mode 100644 index 0000000000..76d3a554bd --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-send-context.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnSendContextRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn send-context (solid)', async () => + runServerFnSendContextRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/fns.ts b/benchmarks/ssr/scenarios/server-fns/solid/src/fns.ts new file mode 100644 index 0000000000..e9a81ad06e --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/src/fns.ts @@ -0,0 +1,87 @@ +import { createMiddleware, createServerFn } from '@tanstack/solid-start' +import { notFound, redirect } from '@tanstack/solid-router' + +const mwA = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { a: 1 } }), +) +const mwB = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { b: 2 } }), +) + +const sendContextMw = createMiddleware({ type: 'function' }) + .client(({ data, next }) => { + return next({ + sendContext: { token: createContextToken(data as unknown as Payload) }, + }) + }) + .server(({ context, next }) => { + const { token } = context as { token?: string } + + if (typeof token !== 'string') { + throw new Error('missing sendContext token') + } + + return next({ + context: { token }, + sendContext: { stamp: `stamp-${token}` }, + }) + }) + +type Payload = { q: string; n: number; nested: { list: Array } } + +function createContextToken(data: Payload) { + return `token-${data.q}-${data.nested.list[0]}` +} + +const validate = (input: unknown): Payload => { + const p = input as Payload + + if ( + typeof p?.q !== 'string' || + typeof p?.n !== 'number' || + !Array.isArray(p?.nested?.list) + ) { + throw new Error('invalid payload') + } + + return p +} + +function echo(data: Payload, context: { a: number; b: number }) { + return { + echoed: data, + sum: data.n + context.a + context.b, + list: data.nested.list.map((s) => `out-${s}`), + } +} + +export const echoGet = createServerFn({ method: 'GET' }) + .middleware([mwA, mwB]) + .validator(validate) + .handler(({ data, context }) => echo(data, context)) + +export const echoPost = createServerFn({ method: 'POST' }) + .middleware([mwA, mwB]) + .validator(validate) + .handler(({ data, context }) => echo(data, context)) + +export const redirector = createServerFn({ method: 'POST' }).handler(() => { + throw redirect({ to: '/', statusCode: 307 }) +}) + +export const notFounder = createServerFn({ method: 'POST' }).handler(() => { + throw notFound() +}) + +export const ctxEcho = createServerFn({ method: 'POST' }) + .middleware([sendContextMw]) + .validator(validate) + .handler(({ data, context }) => { + const { token } = context as { token: string } + + return { + marker: `ctx-${token}-${data.nested.list[0]}`, + q: data.q, + token, + } + }) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..3d0bd34eaa --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts @@ -0,0 +1,104 @@ +/* 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 ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ + id: '/api/fn-urls', + path: '/api/fn-urls', + getParentRoute: () => rootRouteImport, +} as any) +const SsrCallIdRoute = SsrCallIdRouteImport.update({ + id: '/ssr-call/$id', + path: '/ssr-call/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/ssr-call/$id': typeof SsrCallIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/ssr-call/$id': typeof SsrCallIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/ssr-call/$id': typeof SsrCallIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/fn-urls' | '/ssr-call/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/fn-urls' | '/ssr-call/$id' + id: '__root__' | '/' | '/api/fn-urls' | '/ssr-call/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiFnUrlsRoute: typeof ApiFnUrlsRoute + SsrCallIdRoute: typeof SsrCallIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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' + fullPath: '/ssr-call/$id' + preLoaderRoute: typeof SsrCallIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiFnUrlsRoute: ApiFnUrlsRoute, + SsrCallIdRoute: SsrCallIdRoute, +} +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/benchmarks/ssr/scenarios/server-fns/solid/src/router.tsx b/benchmarks/ssr/scenarios/server-fns/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-fns/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..e59de72236 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/server-fns/solid/src/routes/api.fn-urls.ts new file mode 100644 index 0000000000..7e18f6a03b --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/src/routes/api.fn-urls.ts @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { ctxEcho, echoGet, echoPost, notFounder, redirector } from '../fns' + +export const Route = createFileRoute('/api/fn-urls')({ + server: { + handlers: { + GET: () => + Response.json({ + get: echoGet.url, + post: echoPost.url, + redirect: redirector.url, + notFound: notFounder.url, + context: ctxEcho.url, + }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-fns/solid/src/routes/index.tsx new file mode 100644 index 0000000000..83e7b22372 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/src/routes/index.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { echoGet, echoPost } from '../fns' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return ( +
+ server-fns +
+ ) +} diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/routes/ssr-call.$id.tsx b/benchmarks/ssr/scenarios/server-fns/solid/src/routes/ssr-call.$id.tsx new file mode 100644 index 0000000000..abc5571a59 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/src/routes/ssr-call.$id.tsx @@ -0,0 +1,23 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { echoGet } from '../fns' + +export const Route = createFileRoute('/ssr-call/$id')({ + loader: async ({ params }) => { + const result = await echoGet({ + data: { + q: `ssr-${params.id}`, + n: 300, + nested: { list: [`ssr-call-${params.id}`] }, + }, + }) + + return { marker: result.list[0] } + }, + component: SsrCallComponent, +}) + +function SsrCallComponent() { + const data = Route.useLoaderData() + + return
{data().marker}
+} diff --git a/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json b/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json new file mode 100644 index 0000000000..42c3a2160f --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/server-fns/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-fns/solid/vite.config.ts new file mode 100644 index 0000000000..2f2f78b75c --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr server-fns (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/project.json b/benchmarks/ssr/scenarios/server-fns/vue/project.json new file mode 100644 index 0000000000..ad6f053838 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-server-fns-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts new file mode 100644 index 0000000000..3f67c1a500 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnGetRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn GET (vue)', async () => + runServerFnGetRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-during-document-ssr.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-during-document-ssr.bench.ts new file mode 100644 index 0000000000..56c9addca5 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-during-document-ssr.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnDocumentSsrRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn during document ssr (vue)', async () => + runServerFnDocumentSsrRequestLoop(handler), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-not-found.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-not-found.bench.ts new file mode 100644 index 0000000000..e9a6e31617 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnNotFoundRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn not-found (vue)', async () => + runServerFnNotFoundRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-post.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-post.bench.ts new file mode 100644 index 0000000000..df9312ccd1 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-post.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnPostRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn POST (vue)', async () => + runServerFnPostRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-redirect.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-redirect.bench.ts new file mode 100644 index 0000000000..67c4611644 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-redirect.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnRedirectRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn redirect (vue)', async () => + runServerFnRedirectRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-send-context.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-send-context.bench.ts new file mode 100644 index 0000000000..6f51ef4bab --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-send-context.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnSendContextRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn send-context (vue)', async () => + runServerFnSendContextRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/fns.ts b/benchmarks/ssr/scenarios/server-fns/vue/src/fns.ts new file mode 100644 index 0000000000..fc08b2b9bf --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/src/fns.ts @@ -0,0 +1,87 @@ +import { createMiddleware, createServerFn } from '@tanstack/vue-start' +import { notFound, redirect } from '@tanstack/vue-router' + +const mwA = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { a: 1 } }), +) +const mwB = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { b: 2 } }), +) + +const sendContextMw = createMiddleware({ type: 'function' }) + .client(({ data, next }) => { + return next({ + sendContext: { token: createContextToken(data as unknown as Payload) }, + }) + }) + .server(({ context, next }) => { + const { token } = context as { token?: string } + + if (typeof token !== 'string') { + throw new Error('missing sendContext token') + } + + return next({ + context: { token }, + sendContext: { stamp: `stamp-${token}` }, + }) + }) + +type Payload = { q: string; n: number; nested: { list: Array } } + +function createContextToken(data: Payload) { + return `token-${data.q}-${data.nested.list[0]}` +} + +const validate = (input: unknown): Payload => { + const p = input as Payload + + if ( + typeof p?.q !== 'string' || + typeof p?.n !== 'number' || + !Array.isArray(p?.nested?.list) + ) { + throw new Error('invalid payload') + } + + return p +} + +function echo(data: Payload, context: { a: number; b: number }) { + return { + echoed: data, + sum: data.n + context.a + context.b, + list: data.nested.list.map((s) => `out-${s}`), + } +} + +export const echoGet = createServerFn({ method: 'GET' }) + .middleware([mwA, mwB]) + .validator(validate) + .handler(({ data, context }) => echo(data, context)) + +export const echoPost = createServerFn({ method: 'POST' }) + .middleware([mwA, mwB]) + .validator(validate) + .handler(({ data, context }) => echo(data, context)) + +export const redirector = createServerFn({ method: 'POST' }).handler(() => { + throw redirect({ to: '/', statusCode: 307 }) +}) + +export const notFounder = createServerFn({ method: 'POST' }).handler(() => { + throw notFound() +}) + +export const ctxEcho = createServerFn({ method: 'POST' }) + .middleware([sendContextMw]) + .validator(validate) + .handler(({ data, context }) => { + const { token } = context as { token: string } + + return { + marker: `ctx-${token}-${data.nested.list[0]}`, + q: data.q, + token, + } + }) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..0e24cd9c15 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts @@ -0,0 +1,104 @@ +/* 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 ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ + id: '/api/fn-urls', + path: '/api/fn-urls', + getParentRoute: () => rootRouteImport, +} as any) +const SsrCallIdRoute = SsrCallIdRouteImport.update({ + id: '/ssr-call/$id', + path: '/ssr-call/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/ssr-call/$id': typeof SsrCallIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/ssr-call/$id': typeof SsrCallIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/fn-urls': typeof ApiFnUrlsRoute + '/ssr-call/$id': typeof SsrCallIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/fn-urls' | '/ssr-call/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/fn-urls' | '/ssr-call/$id' + id: '__root__' | '/' | '/api/fn-urls' | '/ssr-call/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiFnUrlsRoute: typeof ApiFnUrlsRoute + SsrCallIdRoute: typeof SsrCallIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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' + fullPath: '/ssr-call/$id' + preLoaderRoute: typeof SsrCallIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiFnUrlsRoute: ApiFnUrlsRoute, + SsrCallIdRoute: SsrCallIdRoute, +} +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/benchmarks/ssr/scenarios/server-fns/vue/src/router.tsx b/benchmarks/ssr/scenarios/server-fns/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..49422aac38 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/__root.tsx @@ -0,0 +1,26 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/api.fn-urls.ts b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/api.fn-urls.ts new file mode 100644 index 0000000000..0199e7f1d3 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/api.fn-urls.ts @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { ctxEcho, echoGet, echoPost, notFounder, redirector } from '../fns' + +export const Route = createFileRoute('/api/fn-urls')({ + server: { + handlers: { + GET: () => + Response.json({ + get: echoGet.url, + post: echoPost.url, + redirect: redirector.url, + notFound: notFounder.url, + context: ctxEcho.url, + }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/index.tsx new file mode 100644 index 0000000000..e72e667bc5 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/index.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { echoGet, echoPost } from '../fns' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return ( +
+ server-fns +
+ ) +} diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/ssr-call.$id.tsx b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/ssr-call.$id.tsx new file mode 100644 index 0000000000..45fad23dc0 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/ssr-call.$id.tsx @@ -0,0 +1,28 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { echoGet } from '../fns' + +const SsrCallComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
{data.value.marker}
+ ) + }, +}) + +export const Route = createFileRoute('/ssr-call/$id')({ + loader: async ({ params }) => { + const result = await echoGet({ + data: { + q: `ssr-${params.id}`, + n: 300, + nested: { list: [`ssr-call-${params.id}`] }, + }, + }) + + return { marker: result.list[0] } + }, + component: SsrCallComponent, +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json b/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json new file mode 100644 index 0000000000..08c94853f4 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed*.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/server-fns/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-fns/vue/vite.config.ts new file mode 100644 index 0000000000..5f3e3ca4b5 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr server-fns (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/project.json b/benchmarks/ssr/scenarios/server-routes-middleware/react/project.json new file mode 100644 index 0000000000..e5f11d0a57 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-server-routes-middleware-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts new file mode 100644 index 0000000000..6331216522 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerRouteMiddlewareResponse, + runServerRouteMiddlewareLoop, + serverRouteMiddlewareBenchOptions, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertServerRouteMiddlewareResponse(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr server-route middleware (react)', async () => + runServerRouteMiddlewareLoop(handler), + ).run(serverRouteMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/middleware.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/middleware.ts new file mode 100644 index 0000000000..1e8c428696 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/middleware.ts @@ -0,0 +1,16 @@ +import { createMiddleware } from '@tanstack/react-start' + +const make = (key: TKey, value: number) => + createMiddleware({ type: 'request' }).server(({ next }) => + next({ context: { [key]: value } as Record }), + ) + +export const routeMws = [ + make('r1', 1), + make('r2', 2), + make('r3', 3), + make('r4', 4), + make('r5', 5), +] as const + +export const methodMws = [make('m1', 6), make('m2', 7)] as const diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..7a63a799a1 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/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 ApiChainIdRouteImport } from './routes/api.chain.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ApiChainIdRoute = ApiChainIdRouteImport.update({ + id: '/api/chain/$id', + path: '/api/chain/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/chain/$id': typeof ApiChainIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/chain/$id': typeof ApiChainIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/chain/$id': typeof ApiChainIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/chain/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/chain/$id' + id: '__root__' | '/' | '/api/chain/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiChainIdRoute: typeof ApiChainIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/api/chain/$id': { + id: '/api/chain/$id' + path: '/api/chain/$id' + fullPath: '/api/chain/$id' + preLoaderRoute: typeof ApiChainIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiChainIdRoute: ApiChainIdRoute, +} +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/benchmarks/ssr/scenarios/server-routes-middleware/react/src/router.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/__root.tsx new file mode 100644 index 0000000000..ff1da4c304 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/api.chain.$id.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/api.chain.$id.ts new file mode 100644 index 0000000000..5a9f5d5035 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/api.chain.$id.ts @@ -0,0 +1,24 @@ +import { createFileRoute } from '@tanstack/react-router' +import { methodMws, routeMws } from '../middleware' + +const allMws = [...routeMws, ...methodMws] as const + +export const Route = createFileRoute('/api/chain/$id')({ + server: { + middleware: allMws, + handlers: { + GET: ({ params, context }) => + Response.json({ + id: params.id, + total: + context.r1 + + context.r2 + + context.r3 + + context.r4 + + context.r5 + + context.m1 + + context.m2, + }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/index.tsx new file mode 100644 index 0000000000..9fe98b6851 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return
server routes middleware
+} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/tsconfig.json b/benchmarks/ssr/scenarios/server-routes-middleware/react/tsconfig.json new file mode 100644 index 0000000000..91027bfc88 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts new file mode 100644 index 0000000000..f6998c2ac8 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr server-routes-middleware (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/shared.ts b/benchmarks/ssr/scenarios/server-routes-middleware/shared.ts new file mode 100644 index 0000000000..663ca09294 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/shared.ts @@ -0,0 +1,58 @@ +import { randomSegment, runRequestLoop } from '../../bench-utils' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +const benchmarkSeed = 0xdecafbad +const loopTotalRequests = 160 + +const apiRequestInit = { + method: 'GET', + headers: { + accept: 'application/json', + }, +} satisfies RequestInit + +export const serverRouteMiddlewareBenchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} + +export function runServerRouteMiddlewareLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: loopTotalRequests, + buildRequest: (random) => + new Request( + `http://localhost/api/chain/${randomSegment(random)}`, + apiRequestInit, + ), + }) +} + +export async function assertServerRouteMiddlewareResponse( + handler: StartRequestHandler, +) { + const id = 'sanity' + const response = await handler.fetch( + new Request(`http://localhost/api/chain/${id}`, apiRequestInit), + ) + + if (response.status !== 200) { + throw new Error(`Expected status 200, received ${response.status}`) + } + + const contentType = response.headers.get('content-type') + + if (!contentType?.includes('application/json')) { + throw new Error(`Expected JSON response, received ${contentType}`) + } + + const body = (await response.json()) as { total?: number } + + if (body.total !== 28) { + throw new Error(`Expected total 28, received ${body.total}`) + } +} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/project.json b/benchmarks/ssr/scenarios/server-routes-middleware/solid/project.json new file mode 100644 index 0000000000..0bde91f794 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-server-routes-middleware-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts new file mode 100644 index 0000000000..77d58e7b19 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerRouteMiddlewareResponse, + runServerRouteMiddlewareLoop, + serverRouteMiddlewareBenchOptions, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertServerRouteMiddlewareResponse(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr server-route middleware (solid)', async () => + runServerRouteMiddlewareLoop(handler), + ).run(serverRouteMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/middleware.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/middleware.ts new file mode 100644 index 0000000000..fcaf3d08f7 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/middleware.ts @@ -0,0 +1,16 @@ +import { createMiddleware } from '@tanstack/solid-start' + +const make = (key: TKey, value: number) => + createMiddleware({ type: 'request' }).server(({ next }) => + next({ context: { [key]: value } as Record }), + ) + +export const routeMws = [ + make('r1', 1), + make('r2', 2), + make('r3', 3), + make('r4', 4), + make('r5', 5), +] as const + +export const methodMws = [make('m1', 6), make('m2', 7)] as const diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..b8c91b9134 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/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 ApiChainIdRouteImport } from './routes/api.chain.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ApiChainIdRoute = ApiChainIdRouteImport.update({ + id: '/api/chain/$id', + path: '/api/chain/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/chain/$id': typeof ApiChainIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/chain/$id': typeof ApiChainIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/chain/$id': typeof ApiChainIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/chain/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/chain/$id' + id: '__root__' | '/' | '/api/chain/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiChainIdRoute: typeof ApiChainIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/api/chain/$id': { + id: '/api/chain/$id' + path: '/api/chain/$id' + fullPath: '/api/chain/$id' + preLoaderRoute: typeof ApiChainIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiChainIdRoute: ApiChainIdRoute, +} +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/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/router.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..e59de72236 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/api.chain.$id.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/api.chain.$id.ts new file mode 100644 index 0000000000..fabdb9de85 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/api.chain.$id.ts @@ -0,0 +1,24 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { methodMws, routeMws } from '../middleware' + +const allMws = [...routeMws, ...methodMws] as const + +export const Route = createFileRoute('/api/chain/$id')({ + server: { + middleware: allMws, + handlers: { + GET: ({ params, context }) => + Response.json({ + id: params.id, + total: + context.r1 + + context.r2 + + context.r3 + + context.r4 + + context.r5 + + context.m1 + + context.m2, + }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/index.tsx new file mode 100644 index 0000000000..e2357b558d --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return
server routes middleware
+} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/tsconfig.json b/benchmarks/ssr/scenarios/server-routes-middleware/solid/tsconfig.json new file mode 100644 index 0000000000..b1806caa67 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts new file mode 100644 index 0000000000..800cf9db9f --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr server-routes-middleware (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/project.json b/benchmarks/ssr/scenarios/server-routes-middleware/vue/project.json new file mode 100644 index 0000000000..2a21b81bf9 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-server-routes-middleware-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts new file mode 100644 index 0000000000..3d03b9c1fa --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerRouteMiddlewareResponse, + runServerRouteMiddlewareLoop, + serverRouteMiddlewareBenchOptions, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertServerRouteMiddlewareResponse(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr server-route middleware (vue)', async () => + runServerRouteMiddlewareLoop(handler), + ).run(serverRouteMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/middleware.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/middleware.ts new file mode 100644 index 0000000000..05e7a86be9 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/middleware.ts @@ -0,0 +1,16 @@ +import { createMiddleware } from '@tanstack/vue-start' + +const make = (key: TKey, value: number) => + createMiddleware({ type: 'request' }).server(({ next }) => + next({ context: { [key]: value } as Record }), + ) + +export const routeMws = [ + make('r1', 1), + make('r2', 2), + make('r3', 3), + make('r4', 4), + make('r5', 5), +] as const + +export const methodMws = [make('m1', 6), make('m2', 7)] as const diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..db4f072a69 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/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 ApiChainIdRouteImport } from './routes/api.chain.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ApiChainIdRoute = ApiChainIdRouteImport.update({ + id: '/api/chain/$id', + path: '/api/chain/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/chain/$id': typeof ApiChainIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/chain/$id': typeof ApiChainIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/chain/$id': typeof ApiChainIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/chain/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/chain/$id' + id: '__root__' | '/' | '/api/chain/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiChainIdRoute: typeof ApiChainIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/api/chain/$id': { + id: '/api/chain/$id' + path: '/api/chain/$id' + fullPath: '/api/chain/$id' + preLoaderRoute: typeof ApiChainIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiChainIdRoute: ApiChainIdRoute, +} +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/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/router.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..49422aac38 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/__root.tsx @@ -0,0 +1,26 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/api.chain.$id.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/api.chain.$id.ts new file mode 100644 index 0000000000..d643a339c5 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/api.chain.$id.ts @@ -0,0 +1,24 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { methodMws, routeMws } from '../middleware' + +const allMws = [...routeMws, ...methodMws] as const + +export const Route = createFileRoute('/api/chain/$id')({ + server: { + middleware: allMws, + handlers: { + GET: ({ params, context }) => + Response.json({ + id: params.id, + total: + context.r1 + + context.r2 + + context.r3 + + context.r4 + + context.r5 + + context.m1 + + context.m2, + }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/index.tsx new file mode 100644 index 0000000000..60e9d08e6d --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return
server routes middleware
+} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/tsconfig.json b/benchmarks/ssr/scenarios/server-routes-middleware/vue/tsconfig.json new file mode 100644 index 0000000000..4fe3ccecb1 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts new file mode 100644 index 0000000000..909b7cca50 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr server-routes-middleware (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes/react/project.json b/benchmarks/ssr/scenarios/server-routes/react/project.json new file mode 100644 index 0000000000..a16cb3e537 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-server-routes-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts new file mode 100644 index 0000000000..631314148a --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerRouteResponse, + runServerRouteLoop, + serverRouteBenchOptions, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertServerRouteResponse(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr server-route (react)', async () => + runServerRouteLoop(handler), + ).run(serverRouteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-routes/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-routes/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..6615cc0611 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/react/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 ApiUsersIdRouteImport } from './routes/api.users.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/api/users/$id', + path: '/api/users/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/users/$id': typeof ApiUsersIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/users/$id': typeof ApiUsersIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/users/$id': typeof ApiUsersIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/users/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/users/$id' + id: '__root__' | '/' | '/api/users/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiUsersIdRoute: typeof ApiUsersIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/api/users/$id': { + id: '/api/users/$id' + path: '/api/users/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiUsersIdRoute: ApiUsersIdRoute, +} +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/benchmarks/ssr/scenarios/server-routes/react/src/router.tsx b/benchmarks/ssr/scenarios/server-routes/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/server-routes/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-routes/react/src/routes/__root.tsx new file mode 100644 index 0000000000..ff1da4c304 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/react/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/server-routes/react/src/routes/api.users.$id.ts b/benchmarks/ssr/scenarios/server-routes/react/src/routes/api.users.$id.ts new file mode 100644 index 0000000000..b43275a5c6 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/react/src/routes/api.users.$id.ts @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/api/users/$id')({ + server: { + handlers: { + GET: ({ params }) => + Response.json({ + id: params.id, + name: `user-${params.id}`, + roles: ['a', 'b', 'c'], + }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes/react/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-routes/react/src/routes/index.tsx new file mode 100644 index 0000000000..f5a19839f9 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return
server routes
+} diff --git a/benchmarks/ssr/scenarios/server-routes/react/tsconfig.json b/benchmarks/ssr/scenarios/server-routes/react/tsconfig.json new file mode 100644 index 0000000000..91027bfc88 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/react/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts b/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts new file mode 100644 index 0000000000..2c723c749c --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr server-routes (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes/shared.ts b/benchmarks/ssr/scenarios/server-routes/shared.ts new file mode 100644 index 0000000000..ce33faaefe --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/shared.ts @@ -0,0 +1,56 @@ +import { randomSegment, runRequestLoop } from '../../bench-utils' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +const benchmarkSeed = 0xdecafbad +const loopTotalRequests = 208 + +const apiRequestInit = { + method: 'GET', + headers: { + accept: 'application/json', + }, +} satisfies RequestInit + +export const serverRouteBenchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} + +export function runServerRouteLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: loopTotalRequests, + buildRequest: (random) => + new Request( + `http://localhost/api/users/${randomSegment(random)}`, + apiRequestInit, + ), + }) +} + +export async function assertServerRouteResponse(handler: StartRequestHandler) { + const id = 'sanity' + const response = await handler.fetch( + new Request(`http://localhost/api/users/${id}`, apiRequestInit), + ) + + if (response.status !== 200) { + throw new Error(`Expected status 200, received ${response.status}`) + } + + const contentType = response.headers.get('content-type') + + if (!contentType?.includes('application/json')) { + throw new Error(`Expected JSON response, received ${contentType}`) + } + + const body = (await response.json()) as { name?: string } + + if (body.name !== `user-${id}`) { + throw new Error(`Expected user-${id}, received ${body.name}`) + } +} diff --git a/benchmarks/ssr/scenarios/server-routes/solid/project.json b/benchmarks/ssr/scenarios/server-routes/solid/project.json new file mode 100644 index 0000000000..9c4bf7e230 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/solid/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-server-routes-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts new file mode 100644 index 0000000000..4788d31854 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerRouteResponse, + runServerRouteLoop, + serverRouteBenchOptions, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertServerRouteResponse(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr server-route (solid)', async () => + runServerRouteLoop(handler), + ).run(serverRouteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-routes/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-routes/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..1d7fee0d2b --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/solid/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 ApiUsersIdRouteImport } from './routes/api.users.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/api/users/$id', + path: '/api/users/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/users/$id': typeof ApiUsersIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/users/$id': typeof ApiUsersIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/users/$id': typeof ApiUsersIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/users/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/users/$id' + id: '__root__' | '/' | '/api/users/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiUsersIdRoute: typeof ApiUsersIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/api/users/$id': { + id: '/api/users/$id' + path: '/api/users/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiUsersIdRoute: ApiUsersIdRoute, +} +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/benchmarks/ssr/scenarios/server-routes/solid/src/router.tsx b/benchmarks/ssr/scenarios/server-routes/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/server-routes/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-routes/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..e59de72236 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/solid/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/server-routes/solid/src/routes/api.users.$id.ts b/benchmarks/ssr/scenarios/server-routes/solid/src/routes/api.users.$id.ts new file mode 100644 index 0000000000..516af1cc15 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/solid/src/routes/api.users.$id.ts @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/api/users/$id')({ + server: { + handlers: { + GET: ({ params }) => + Response.json({ + id: params.id, + name: `user-${params.id}`, + roles: ['a', 'b', 'c'], + }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes/solid/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-routes/solid/src/routes/index.tsx new file mode 100644 index 0000000000..87eb6a178f --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return
server routes
+} diff --git a/benchmarks/ssr/scenarios/server-routes/solid/tsconfig.json b/benchmarks/ssr/scenarios/server-routes/solid/tsconfig.json new file mode 100644 index 0000000000..b1806caa67 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/solid/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts new file mode 100644 index 0000000000..994e04f1d6 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr server-routes (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes/vue/project.json b/benchmarks/ssr/scenarios/server-routes/vue/project.json new file mode 100644 index 0000000000..a92a9ad40e --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-server-routes-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts new file mode 100644 index 0000000000..09c0bbe90b --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerRouteResponse, + runServerRouteLoop, + serverRouteBenchOptions, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertServerRouteResponse(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr server-route (vue)', async () => + runServerRouteLoop(handler), + ).run(serverRouteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-routes/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-routes/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..b12a446b9f --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/vue/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 ApiUsersIdRouteImport } from './routes/api.users.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/api/users/$id', + path: '/api/users/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/api/users/$id': typeof ApiUsersIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/api/users/$id': typeof ApiUsersIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/api/users/$id': typeof ApiUsersIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/api/users/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/api/users/$id' + id: '__root__' | '/' | '/api/users/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ApiUsersIdRoute: typeof ApiUsersIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/api/users/$id': { + id: '/api/users/$id' + path: '/api/users/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ApiUsersIdRoute: ApiUsersIdRoute, +} +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/benchmarks/ssr/scenarios/server-routes/vue/src/router.tsx b/benchmarks/ssr/scenarios/server-routes/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/server-routes/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/server-routes/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..49422aac38 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/vue/src/routes/__root.tsx @@ -0,0 +1,26 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/server-routes/vue/src/routes/api.users.$id.ts b/benchmarks/ssr/scenarios/server-routes/vue/src/routes/api.users.$id.ts new file mode 100644 index 0000000000..7766b52acc --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/vue/src/routes/api.users.$id.ts @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/api/users/$id')({ + server: { + handlers: { + GET: ({ params }) => + Response.json({ + id: params.id, + name: `user-${params.id}`, + roles: ['a', 'b', 'c'], + }), + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/server-routes/vue/src/routes/index.tsx b/benchmarks/ssr/scenarios/server-routes/vue/src/routes/index.tsx new file mode 100644 index 0000000000..39d1e2f935 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/vue/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return
server routes
+} diff --git a/benchmarks/ssr/scenarios/server-routes/vue/tsconfig.json b/benchmarks/ssr/scenarios/server-routes/vue/tsconfig.json new file mode 100644 index 0000000000..4fe3ccecb1 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/vue/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts new file mode 100644 index 0000000000..0457453532 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr server-routes (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/streaming/react/project.json b/benchmarks/ssr/scenarios/streaming/react/project.json new file mode 100644 index 0000000000..a905aa3474 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/react/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-streaming-react", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts new file mode 100644 index 0000000000..eb4c9dc1d6 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertStreamingSanity, + benchOptions, + runStreamingLoop, + type StartRequestHandler, +} from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertStreamingSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr streaming deferred (react)', async () => + runStreamingLoop(handler), + ).run(benchOptions) +}) diff --git a/benchmarks/ssr/scenarios/streaming/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/streaming/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..eb1af78a41 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/react/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 StreamIdRouteImport } from './routes/stream.$id' + +const StreamIdRoute = StreamIdRouteImport.update({ + id: '/stream/$id', + path: '/stream/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesByTo { + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/stream/$id': typeof StreamIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/stream/$id' + fileRoutesByTo: FileRoutesByTo + to: '/stream/$id' + id: '__root__' | '/stream/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + StreamIdRoute: typeof StreamIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/stream/$id': { + id: '/stream/$id' + path: '/stream/$id' + fullPath: '/stream/$id' + preLoaderRoute: typeof StreamIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + StreamIdRoute: StreamIdRoute, +} +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/benchmarks/ssr/scenarios/streaming/react/src/router.tsx b/benchmarks/ssr/scenarios/streaming/react/src/router.tsx new file mode 100644 index 0000000000..7c4eb0babe --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/react/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/streaming/react/src/routes/__root.tsx b/benchmarks/ssr/scenarios/streaming/react/src/routes/__root.tsx new file mode 100644 index 0000000000..1973ca20bb --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/react/src/routes/__root.tsx @@ -0,0 +1,25 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/streaming/react/src/routes/stream.$id.tsx b/benchmarks/ssr/scenarios/streaming/react/src/routes/stream.$id.tsx new file mode 100644 index 0000000000..342f7ceb0c --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/react/src/routes/stream.$id.tsx @@ -0,0 +1,39 @@ +import { Await, createFileRoute } from '@tanstack/react-router' +import { Suspense } from 'react' +import { makeBigPayload, sleep0 } from '../../../shared-data' + +export const Route = createFileRoute('/stream/$id')({ + loader: ({ params }) => ({ + fast: { label: `fast-${params.id}` }, + slowSmall: sleep0().then(() => ({ label: `slow-small-${params.id}` })), + slowBig: sleep0().then(() => makeBigPayload(params.id)), + }), + component: StreamComponent, +}) + +function StreamComponent() { + const data = Route.useLoaderData() + + return ( + <> +

{data.fast.label}

+

loading-small

+ + {(d) =>

{d.label}

}
+
+

loading-big

+ + + {(d) => ( +
+

{d.label}

+ {d.chunks.map((chunk) => ( +

{chunk.value}

+ ))} +
+ )} +
+
+ + ) +} diff --git a/benchmarks/ssr/scenarios/streaming/react/tsconfig.json b/benchmarks/ssr/scenarios/streaming/react/tsconfig.json new file mode 100644 index 0000000000..8800818162 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/react/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared-data.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/streaming/react/vite.config.ts b/benchmarks/ssr/scenarios/streaming/react/vite.config.ts new file mode 100644 index 0000000000..e1cc5f534b --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/react/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr streaming (react)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/scenarios/streaming/shared-bench.ts b/benchmarks/ssr/scenarios/streaming/shared-bench.ts new file mode 100644 index 0000000000..cc45062e1b --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/shared-bench.ts @@ -0,0 +1,78 @@ +import { expect } from 'vitest' +import { streamChunkCount } from './shared-data' +import { randomSegment, runRequestLoop } from '../../bench-utils' +import type { StartRequestHandler } from '../../bench-utils' + +export type { StartRequestHandler } + +const benchmarkSeed = 0xdecafbad + +export const CHROME_UA = + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36' + +const requestInit = { + method: 'GET', + headers: { + accept: 'text/html', + 'user-agent': CHROME_UA, + }, +} satisfies RequestInit + +function buildStreamingRequest(random: () => number) { + return new Request( + `http://localhost/stream/${randomSegment(random)}`, + requestInit, + ) +} + +function getMarkerIndexes(body: string, marker: string) { + const indexes: Array = [] + let index = body.indexOf(marker) + + while (index !== -1) { + indexes.push(index) + index = body.indexOf(marker, index + marker.length) + } + + return indexes +} + +export async function assertStreamingSanity(handler: StartRequestHandler) { + const id = 'sanity-stream' + const response = await handler.fetch( + new Request(`http://localhost/stream/${id}`, requestInit), + ) + const body = await response.text() + const loadingSmallIndexes = getMarkerIndexes(body, 'loading-small') + const loadingBigIndexes = getMarkerIndexes(body, 'loading-big') + const tsrIndex = body.indexOf('$_TSR') + + expect(response.status).toBe(200) + expect(loadingSmallIndexes).toHaveLength(1) + expect(loadingBigIndexes).toHaveLength(1) + expect(body).toContain(`slow-small-${id}`) + expect(body).toContain(`slow-big-${id}`) + expect(body).toContain(`${id}:0:`) + expect(body).toContain(`${id}:${streamChunkCount - 1}:`) + + const loadingSmallIndex = loadingSmallIndexes[0]! + const loadingBigIndex = loadingBigIndexes[0]! + + expect(loadingBigIndex).toBeGreaterThan(loadingSmallIndex) + expect(tsrIndex).toBeGreaterThan(loadingBigIndex) +} + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} + +export function runStreamingLoop(handler: StartRequestHandler) { + return runRequestLoop(handler, { + seed: benchmarkSeed, + concurrency: 16, + totalRequests: 16, + buildRequest: buildStreamingRequest, + }) +} diff --git a/benchmarks/ssr/scenarios/streaming/shared-data.ts b/benchmarks/ssr/scenarios/streaming/shared-data.ts new file mode 100644 index 0000000000..695ed107c6 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/shared-data.ts @@ -0,0 +1,69 @@ +export interface SmallPayload { + label: string +} + +export interface BigPayload { + label: string + chunks: Array<{ + index: number + value: string + }> +} + +const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789' +export const streamChunkCount = 96 +export const streamChunkLength = 192 + +export function sleep0() { + // Give SSR a render turn before resolving deferred values. Counted turns + // avoid grouping concurrent requests by wall-clock timer expiration. + return new Promise((resolve) => { + setImmediate(() => setImmediate(resolve)) + }) +} + +function hashId(id: string) { + let state = 2166136261 + + for (let index = 0; index < id.length; index++) { + state ^= id.charCodeAt(index) + state = Math.imul(state, 16777619) >>> 0 + } + + return state || 1 +} + +function nextState(state: number) { + return (state * 1664525 + 1013904223) >>> 0 +} + +function makeChunk(seed: number) { + let state = seed + let value = '' + + for (let index = 0; index < streamChunkLength; index++) { + state = nextState(state) + value += alphabet[state % alphabet.length] + } + + return { state, value } +} + +export function makeBigPayload(id: string): BigPayload { + let state = hashId(id) + const chunks: BigPayload['chunks'] = [] + + for (let index = 0; index < streamChunkCount; index++) { + const chunk = makeChunk(state + index) + state = chunk.state + chunks.push({ + index, + value: `${id}:${index}:${chunk.value}`, + }) + } + + return { + label: `slow-big-${id}`, + chunks, + } +} diff --git a/benchmarks/ssr/scenarios/streaming/solid/project.json b/benchmarks/ssr/scenarios/streaming/solid/project.json new file mode 100644 index 0000000000..15e5f21103 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/solid/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-streaming-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts new file mode 100644 index 0000000000..19d5817d32 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertStreamingSanity, + benchOptions, + runStreamingLoop, + type StartRequestHandler, +} from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertStreamingSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr streaming deferred (solid)', async () => + runStreamingLoop(handler), + ).run(benchOptions) +}) diff --git a/benchmarks/ssr/scenarios/streaming/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/streaming/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..e015aee737 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/solid/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 StreamIdRouteImport } from './routes/stream.$id' + +const StreamIdRoute = StreamIdRouteImport.update({ + id: '/stream/$id', + path: '/stream/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesByTo { + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/stream/$id': typeof StreamIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/stream/$id' + fileRoutesByTo: FileRoutesByTo + to: '/stream/$id' + id: '__root__' | '/stream/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + StreamIdRoute: typeof StreamIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/stream/$id': { + id: '/stream/$id' + path: '/stream/$id' + fullPath: '/stream/$id' + preLoaderRoute: typeof StreamIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + StreamIdRoute: StreamIdRoute, +} +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/benchmarks/ssr/scenarios/streaming/solid/src/router.tsx b/benchmarks/ssr/scenarios/streaming/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/streaming/solid/src/routes/__root.tsx b/benchmarks/ssr/scenarios/streaming/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..15de858e78 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/solid/src/routes/__root.tsx @@ -0,0 +1,25 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/streaming/solid/src/routes/stream.$id.tsx b/benchmarks/ssr/scenarios/streaming/solid/src/routes/stream.$id.tsx new file mode 100644 index 0000000000..1a65fff950 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/solid/src/routes/stream.$id.tsx @@ -0,0 +1,39 @@ +import { Await, createFileRoute } from '@tanstack/solid-router' +import { Suspense } from 'solid-js' +import { makeBigPayload, sleep0 } from '../../../shared-data' + +export const Route = createFileRoute('/stream/$id')({ + loader: ({ params }) => ({ + fast: { label: `fast-${params.id}` }, + slowSmall: sleep0().then(() => ({ label: `slow-small-${params.id}` })), + slowBig: sleep0().then(() => makeBigPayload(params.id)), + }), + component: StreamComponent, +}) + +function StreamComponent() { + const data = Route.useLoaderData() + + return ( + <> +

{data().fast.label}

+

loading-small

+ + {(d) =>

{d.label}

}
+
+

loading-big

+ + + {(d) => ( +
+

{d.label}

+ {d.chunks.map((chunk) => ( +

{chunk.value}

+ ))} +
+ )} +
+
+ + ) +} diff --git a/benchmarks/ssr/scenarios/streaming/solid/tsconfig.json b/benchmarks/ssr/scenarios/streaming/solid/tsconfig.json new file mode 100644 index 0000000000..47f264ba4f --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/solid/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared-data.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts b/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts new file mode 100644 index 0000000000..353c21f552 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr streaming (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/scenarios/streaming/vue/project.json b/benchmarks/ssr/scenarios/streaming/vue/project.json new file mode 100644 index 0000000000..acaa7c460c --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-streaming-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts new file mode 100644 index 0000000000..42473fc694 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertStreamingSanity, + benchOptions, + runStreamingLoop, + type StartRequestHandler, +} from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertStreamingSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr streaming deferred (vue)', async () => + runStreamingLoop(handler), + ).run(benchOptions) +}) diff --git a/benchmarks/ssr/scenarios/streaming/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/streaming/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..2ec10975f2 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/vue/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 StreamIdRouteImport } from './routes/stream.$id' + +const StreamIdRoute = StreamIdRouteImport.update({ + id: '/stream/$id', + path: '/stream/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesByTo { + '/stream/$id': typeof StreamIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/stream/$id': typeof StreamIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/stream/$id' + fileRoutesByTo: FileRoutesByTo + to: '/stream/$id' + id: '__root__' | '/stream/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + StreamIdRoute: typeof StreamIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/stream/$id': { + id: '/stream/$id' + path: '/stream/$id' + fullPath: '/stream/$id' + preLoaderRoute: typeof StreamIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + StreamIdRoute: StreamIdRoute, +} +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/benchmarks/ssr/scenarios/streaming/vue/src/router.tsx b/benchmarks/ssr/scenarios/streaming/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/scenarios/streaming/vue/src/routes/__root.tsx b/benchmarks/ssr/scenarios/streaming/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..4b03519823 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/vue/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/scenarios/streaming/vue/src/routes/stream.$id.tsx b/benchmarks/ssr/scenarios/streaming/vue/src/routes/stream.$id.tsx new file mode 100644 index 0000000000..d627fa56c9 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/vue/src/routes/stream.$id.tsx @@ -0,0 +1,56 @@ +import { Await, createFileRoute } from '@tanstack/vue-router' +import { Suspense, defineComponent } from 'vue' +import { makeBigPayload, sleep0 } from '../../../shared-data' +import type { BigPayload, SmallPayload } from '../../../shared-data' + +const StreamComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( + <> +

{data.value.fast.label}

+

loading-small

+ + {{ + default: () => ( +

{d.label}

} + /> + ), + fallback: () => null, + }} +
+

loading-big

+ + {{ + default: () => ( + ( +
+

{d.label}

+ {d.chunks.map((chunk) => ( +

{chunk.value}

+ ))} +
+ )} + /> + ), + fallback: () => null, + }} +
+ + ) + }, +}) + +export const Route = createFileRoute('/stream/$id')({ + loader: ({ params }) => ({ + fast: { label: `fast-${params.id}` }, + slowSmall: sleep0().then(() => ({ label: `slow-small-${params.id}` })), + slowBig: sleep0().then(() => makeBigPayload(params.id)), + }), + component: StreamComponent, +}) diff --git a/benchmarks/ssr/scenarios/streaming/vue/tsconfig.json b/benchmarks/ssr/scenarios/streaming/vue/tsconfig.json new file mode 100644 index 0000000000..c302f63770 --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/vue/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../../../bench-utils.ts", + "../shared-data.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts b/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts new file mode 100644 index 0000000000..a09a30076f --- /dev/null +++ b/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr streaming (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/ssr/solid/project.json b/benchmarks/ssr/solid/project.json new file mode 100644 index 0000000000..0f19144d3b --- /dev/null +++ b/benchmarks/ssr/solid/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-solid", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/solid/speed.bench.ts b/benchmarks/ssr/solid/speed.bench.ts new file mode 100644 index 0000000000..2f72977612 --- /dev/null +++ b/benchmarks/ssr/solid/speed.bench.ts @@ -0,0 +1,22 @@ +import { test } from 'vitest' +import { runSsrRequestLoop } from '../bench-utils' +import type { StartRequestHandler } from '../bench-utils' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href +const benchmarkSeed = 0xcafebabe + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + 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, + }) +}) diff --git a/benchmarks/ssr/solid/src/routeTree.gen.ts b/benchmarks/ssr/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..27cbe59476 --- /dev/null +++ b/benchmarks/ssr/solid/src/routeTree.gen.ts @@ -0,0 +1,146 @@ +/* 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 ARouteImport } from './routes/$a' +import { Route as ABRouteImport } from './routes/$a.$b' +import { Route as ABCRouteImport } from './routes/$a.$b.$c' +import { Route as ABCDRouteImport } from './routes/$a.$b.$c.$d' + +const ARoute = ARouteImport.update({ + id: '/$a', + path: '/$a', + getParentRoute: () => rootRouteImport, +} as any) +const ABRoute = ABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => ARoute, +} as any) +const ABCRoute = ABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => ABRoute, +} as any) +const ABCDRoute = ABCDRouteImport.update({ + id: '/$d', + path: '/$d', + getParentRoute: () => ABCRoute, +} as any) + +export interface FileRoutesByFullPath { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRouteWithChildren + '/$a/$b/$c/$d': typeof ABCDRoute +} +export interface FileRoutesByTo { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRouteWithChildren + '/$a/$b/$c/$d': typeof ABCDRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRouteWithChildren + '/$a/$b/$c/$d': typeof ABCDRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' + fileRoutesByTo: FileRoutesByTo + to: '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' + id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/$a': { + id: '/$a' + path: '/$a' + fullPath: '/$a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + '/$a/$b': { + id: '/$a/$b' + path: '/$b' + fullPath: '/$a/$b' + preLoaderRoute: typeof ABRouteImport + parentRoute: typeof ARoute + } + '/$a/$b/$c': { + id: '/$a/$b/$c' + path: '/$c' + fullPath: '/$a/$b/$c' + preLoaderRoute: typeof ABCRouteImport + parentRoute: typeof ABRoute + } + '/$a/$b/$c/$d': { + id: '/$a/$b/$c/$d' + path: '/$d' + fullPath: '/$a/$b/$c/$d' + preLoaderRoute: typeof ABCDRouteImport + parentRoute: typeof ABCRoute + } + } +} + +interface ABCRouteChildren { + ABCDRoute: typeof ABCDRoute +} + +const ABCRouteChildren: ABCRouteChildren = { + ABCDRoute: ABCDRoute, +} + +const ABCRouteWithChildren = ABCRoute._addFileChildren(ABCRouteChildren) + +interface ABRouteChildren { + ABCRoute: typeof ABCRouteWithChildren +} + +const ABRouteChildren: ABRouteChildren = { + ABCRoute: ABCRouteWithChildren, +} + +const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) + +interface ARouteChildren { + ABRoute: typeof ABRouteWithChildren +} + +const ARouteChildren: ARouteChildren = { + ABRoute: ABRouteWithChildren, +} + +const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARouteWithChildren, +} +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/benchmarks/ssr/solid/src/router.tsx b/benchmarks/ssr/solid/src/router.tsx new file mode 100644 index 0000000000..038ec0ab5e --- /dev/null +++ b/benchmarks/ssr/solid/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/solid/src/routes/$a.$b.$c.$d.tsx b/benchmarks/ssr/solid/src/routes/$a.$b.$c.$d.tsx new file mode 100644 index 0000000000..9bab038f37 --- /dev/null +++ b/benchmarks/ssr/solid/src/routes/$a.$b.$c.$d.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { RouteWorkload } from '../workload' + +export const Route = createFileRoute('/$a/$b/$c/$d')({ + component: LevelDComponent, +}) + +function LevelDComponent() { + return +} diff --git a/benchmarks/ssr/solid/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/solid/src/routes/$a.$b.$c.tsx new file mode 100644 index 0000000000..e10b9da6df --- /dev/null +++ b/benchmarks/ssr/solid/src/routes/$a.$b.$c.tsx @@ -0,0 +1,15 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { RouteWorkload } from '../workload' + +export const Route = createFileRoute('/$a/$b/$c')({ + component: LevelCComponent, +}) + +function LevelCComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/ssr/solid/src/routes/$a.$b.tsx b/benchmarks/ssr/solid/src/routes/$a.$b.tsx new file mode 100644 index 0000000000..cd2d0e9754 --- /dev/null +++ b/benchmarks/ssr/solid/src/routes/$a.$b.tsx @@ -0,0 +1,15 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { RouteWorkload } from '../workload' + +export const Route = createFileRoute('/$a/$b')({ + component: LevelBComponent, +}) + +function LevelBComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/ssr/solid/src/routes/$a.tsx b/benchmarks/ssr/solid/src/routes/$a.tsx new file mode 100644 index 0000000000..a2f0200882 --- /dev/null +++ b/benchmarks/ssr/solid/src/routes/$a.tsx @@ -0,0 +1,15 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { RouteWorkload } from '../workload' + +export const Route = createFileRoute('/$a')({ + component: LevelAComponent, +}) + +function LevelAComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/ssr/solid/src/routes/__root.tsx b/benchmarks/ssr/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..15de858e78 --- /dev/null +++ b/benchmarks/ssr/solid/src/routes/__root.tsx @@ -0,0 +1,25 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/solid/src/workload.tsx b/benchmarks/ssr/solid/src/workload.tsx new file mode 100644 index 0000000000..76fcae555a --- /dev/null +++ b/benchmarks/ssr/solid/src/workload.tsx @@ -0,0 +1,81 @@ +import { For, createEffect } from 'solid-js' +import { Link, useParams, useSearch } from '@tanstack/solid-router' + +const probes = Array.from({ length: 10 }, (_, index) => index) + +function runSelectorWork(input: string, salt: number) { + let value = salt + + for (let index = 0; index < input.length; index++) { + value = (value * 33 + input.charCodeAt(index) + index) >>> 0 + } + + for (let index = 0; index < 16; index++) { + value = (value ^ (value << 13)) >>> 0 + value = (value ^ (value >> 17)) >>> 0 + value = (value ^ (value << 5)) >>> 0 + } + + return value +} + +function ParamsProbe(props: { salt: number }) { + const params = useParams({ + strict: false, + select: (nextParams) => + runSelectorWork( + `${nextParams.a ?? ''}/${nextParams.b ?? ''}/${nextParams.c ?? ''}/${nextParams.d ?? ''}`, + props.salt, + ), + }) + + createEffect(() => { + void params() + }) + + return null +} + +function SearchProbe(props: { salt: number }) { + const search = useSearch({ + strict: false, + select: (nextSearch) => + runSelectorWork(String(nextSearch.q ?? ''), props.salt), + }) + + createEffect(() => { + void search() + }) + + return null +} + +function LinkProbe(props: { salt: number }) { + const value = String((props.salt % 97) + 1) + + return ( + + Link + + ) +} + +export function RouteWorkload() { + return ( + <> + {(probe) => } + {(probe) => } + {(probe) => } + + ) +} diff --git a/benchmarks/ssr/solid/tsconfig.json b/benchmarks/ssr/solid/tsconfig.json new file mode 100644 index 0000000000..6c87e995c7 --- /dev/null +++ b/benchmarks/ssr/solid/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/solid/vite.config.ts b/benchmarks/ssr/solid/vite.config.ts new file mode 100644 index 0000000000..dfd82d9192 --- /dev/null +++ b/benchmarks/ssr/solid/vite.config.ts @@ -0,0 +1,37 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/solid-start/plugin/vite' +import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + solid({ ssr: true, hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr (solid)', + watch: false, + environment: 'node', + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/ssr/tsconfig.json b/benchmarks/ssr/tsconfig.json new file mode 100644 index 0000000000..7279177023 --- /dev/null +++ b/benchmarks/ssr/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "bench-utils.ts", + "bench-utils.test.ts", + "scenarios/streaming/shared-data.ts", + "vitest.unit.config.ts" + ] +} diff --git a/benchmarks/ssr/vitest.config.ts b/benchmarks/ssr/vitest.config.ts new file mode 100644 index 0000000000..a91eae4967 --- /dev/null +++ b/benchmarks/ssr/vitest.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + projects: [ + './react/vite.config.ts', + './solid/vite.config.ts', + './vue/vite.config.ts', + './scenarios/*/*/vite.config.ts', + ], + }, +}) diff --git a/benchmarks/ssr/vitest.react.config.ts b/benchmarks/ssr/vitest.react.config.ts new file mode 100644 index 0000000000..a397ad929e --- /dev/null +++ b/benchmarks/ssr/vitest.react.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + projects: ['./react/vite.config.ts', './scenarios/*/react/vite.config.ts'], + }, +}) diff --git a/benchmarks/ssr/vitest.solid.config.ts b/benchmarks/ssr/vitest.solid.config.ts new file mode 100644 index 0000000000..b8827b86aa --- /dev/null +++ b/benchmarks/ssr/vitest.solid.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + projects: ['./solid/vite.config.ts', './scenarios/*/solid/vite.config.ts'], + }, +}) diff --git a/benchmarks/ssr/vitest.unit.config.ts b/benchmarks/ssr/vitest.unit.config.ts new file mode 100644 index 0000000000..cbba6db9ef --- /dev/null +++ b/benchmarks/ssr/vitest.unit.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + name: '@benchmarks/ssr unit', + environment: 'node', + include: ['bench-utils.test.ts'], + }, +}) diff --git a/benchmarks/ssr/vitest.vue.config.ts b/benchmarks/ssr/vitest.vue.config.ts new file mode 100644 index 0000000000..17960d7569 --- /dev/null +++ b/benchmarks/ssr/vitest.vue.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + projects: ['./vue/vite.config.ts', './scenarios/*/vue/vite.config.ts'], + }, +}) diff --git a/benchmarks/ssr/vue/project.json b/benchmarks/ssr/vue/project.json new file mode 100644 index 0000000000..930d6c2e22 --- /dev/null +++ b/benchmarks/ssr/vue/project.json @@ -0,0 +1,31 @@ +{ + "name": "@benchmarks/ssr-vue", + "projectType": "application", + "targets": { + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:ssr": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-start"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + } + } +} diff --git a/benchmarks/ssr/vue/speed.bench.ts b/benchmarks/ssr/vue/speed.bench.ts new file mode 100644 index 0000000000..57b59e0504 --- /dev/null +++ b/benchmarks/ssr/vue/speed.bench.ts @@ -0,0 +1,22 @@ +import { test } from 'vitest' +import { runSsrRequestLoop } from '../bench-utils' +import type { StartRequestHandler } from '../bench-utils' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href +const benchmarkSeed = 0xdeadbeef + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + 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, + }) +}) diff --git a/benchmarks/ssr/vue/src/routeTree.gen.ts b/benchmarks/ssr/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..a6dfb5853e --- /dev/null +++ b/benchmarks/ssr/vue/src/routeTree.gen.ts @@ -0,0 +1,146 @@ +/* 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 ARouteImport } from './routes/$a' +import { Route as ABRouteImport } from './routes/$a.$b' +import { Route as ABCRouteImport } from './routes/$a.$b.$c' +import { Route as ABCDRouteImport } from './routes/$a.$b.$c.$d' + +const ARoute = ARouteImport.update({ + id: '/$a', + path: '/$a', + getParentRoute: () => rootRouteImport, +} as any) +const ABRoute = ABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => ARoute, +} as any) +const ABCRoute = ABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => ABRoute, +} as any) +const ABCDRoute = ABCDRouteImport.update({ + id: '/$d', + path: '/$d', + getParentRoute: () => ABCRoute, +} as any) + +export interface FileRoutesByFullPath { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRouteWithChildren + '/$a/$b/$c/$d': typeof ABCDRoute +} +export interface FileRoutesByTo { + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRouteWithChildren + '/$a/$b/$c/$d': typeof ABCDRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/$a': typeof ARouteWithChildren + '/$a/$b': typeof ABRouteWithChildren + '/$a/$b/$c': typeof ABCRouteWithChildren + '/$a/$b/$c/$d': typeof ABCDRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' + fileRoutesByTo: FileRoutesByTo + to: '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' + id: '__root__' | '/$a' | '/$a/$b' | '/$a/$b/$c' | '/$a/$b/$c/$d' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + ARoute: typeof ARouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/$a': { + id: '/$a' + path: '/$a' + fullPath: '/$a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + '/$a/$b': { + id: '/$a/$b' + path: '/$b' + fullPath: '/$a/$b' + preLoaderRoute: typeof ABRouteImport + parentRoute: typeof ARoute + } + '/$a/$b/$c': { + id: '/$a/$b/$c' + path: '/$c' + fullPath: '/$a/$b/$c' + preLoaderRoute: typeof ABCRouteImport + parentRoute: typeof ABRoute + } + '/$a/$b/$c/$d': { + id: '/$a/$b/$c/$d' + path: '/$d' + fullPath: '/$a/$b/$c/$d' + preLoaderRoute: typeof ABCDRouteImport + parentRoute: typeof ABCRoute + } + } +} + +interface ABCRouteChildren { + ABCDRoute: typeof ABCDRoute +} + +const ABCRouteChildren: ABCRouteChildren = { + ABCDRoute: ABCDRoute, +} + +const ABCRouteWithChildren = ABCRoute._addFileChildren(ABCRouteChildren) + +interface ABRouteChildren { + ABCRoute: typeof ABCRouteWithChildren +} + +const ABRouteChildren: ABRouteChildren = { + ABCRoute: ABCRouteWithChildren, +} + +const ABRouteWithChildren = ABRoute._addFileChildren(ABRouteChildren) + +interface ARouteChildren { + ABRoute: typeof ABRouteWithChildren +} + +const ARouteChildren: ARouteChildren = { + ABRoute: ABRouteWithChildren, +} + +const ARouteWithChildren = ARoute._addFileChildren(ARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + ARoute: ARouteWithChildren, +} +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/benchmarks/ssr/vue/src/router.tsx b/benchmarks/ssr/vue/src/router.tsx new file mode 100644 index 0000000000..4290e7cdd3 --- /dev/null +++ b/benchmarks/ssr/vue/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: false, + scrollRestoration: false, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/ssr/vue/src/routes/$a.$b.$c.$d.tsx b/benchmarks/ssr/vue/src/routes/$a.$b.$c.$d.tsx new file mode 100644 index 0000000000..36c2896840 --- /dev/null +++ b/benchmarks/ssr/vue/src/routes/$a.$b.$c.$d.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { RouteWorkload } from '../workload' + +export const Route = createFileRoute('/$a/$b/$c/$d')({ + component: LevelDComponent, +}) + +function LevelDComponent() { + return +} diff --git a/benchmarks/ssr/vue/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/vue/src/routes/$a.$b.$c.tsx new file mode 100644 index 0000000000..3249876970 --- /dev/null +++ b/benchmarks/ssr/vue/src/routes/$a.$b.$c.tsx @@ -0,0 +1,15 @@ +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { RouteWorkload } from '../workload' + +export const Route = createFileRoute('/$a/$b/$c')({ + component: LevelCComponent, +}) + +function LevelCComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/ssr/vue/src/routes/$a.$b.tsx b/benchmarks/ssr/vue/src/routes/$a.$b.tsx new file mode 100644 index 0000000000..fe50f88736 --- /dev/null +++ b/benchmarks/ssr/vue/src/routes/$a.$b.tsx @@ -0,0 +1,15 @@ +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { RouteWorkload } from '../workload' + +export const Route = createFileRoute('/$a/$b')({ + component: LevelBComponent, +}) + +function LevelBComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/ssr/vue/src/routes/$a.tsx b/benchmarks/ssr/vue/src/routes/$a.tsx new file mode 100644 index 0000000000..51310ce063 --- /dev/null +++ b/benchmarks/ssr/vue/src/routes/$a.tsx @@ -0,0 +1,15 @@ +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { RouteWorkload } from '../workload' + +export const Route = createFileRoute('/$a')({ + component: LevelAComponent, +}) + +function LevelAComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/ssr/vue/src/routes/__root.tsx b/benchmarks/ssr/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..4b03519823 --- /dev/null +++ b/benchmarks/ssr/vue/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + component: RootComponent, + validateSearch: (s) => s as { q?: string }, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/ssr/vue/src/workload.tsx b/benchmarks/ssr/vue/src/workload.tsx new file mode 100644 index 0000000000..3266aff694 --- /dev/null +++ b/benchmarks/ssr/vue/src/workload.tsx @@ -0,0 +1,111 @@ +import * as Vue from 'vue' +import { Link, useParams, useSearch } from '@tanstack/vue-router' + +const probes = Array.from({ length: 10 }, (_, index) => index) + +function runSelectorWork(input: string, salt: number) { + let value = salt + + for (let index = 0; index < input.length; index++) { + value = (value * 33 + input.charCodeAt(index) + index) >>> 0 + } + + for (let index = 0; index < 16; index++) { + value = (value ^ (value << 13)) >>> 0 + value = (value ^ (value >> 17)) >>> 0 + value = (value ^ (value << 5)) >>> 0 + } + + return value +} + +const ParamsProbe = Vue.defineComponent({ + props: { + salt: { + type: Number, + required: true, + }, + }, + setup(props) { + const params = useParams({ + strict: false, + select: (nextParams) => + runSelectorWork( + `${nextParams.a ?? ''}/${nextParams.b ?? ''}/${nextParams.c ?? ''}/${nextParams.d ?? ''}`, + props.salt, + ), + }) + + return () => { + void params.value + return null + } + }, +}) + +const SearchProbe = Vue.defineComponent({ + props: { + salt: { + type: Number, + required: true, + }, + }, + setup(props) { + const search = useSearch({ + strict: false, + select: (nextSearch) => + runSelectorWork(String(nextSearch.q ?? ''), props.salt), + }) + + return () => { + void search.value + return null + } + }, +}) + +const LinkProbe = Vue.defineComponent({ + props: { + salt: { + type: Number, + required: true, + }, + }, + setup(props) { + const value = String((props.salt % 97) + 1) + + return () => ( + + Link + + ) + }, +}) + +export const RouteWorkload = Vue.defineComponent({ + setup() { + return () => ( + <> + {probes.map((probe) => ( + + ))} + {probes.map((probe) => ( + + ))} + {probes.map((probe) => ( + + ))} + + ) + }, +}) diff --git a/benchmarks/ssr/vue/tsconfig.json b/benchmarks/ssr/vue/tsconfig.json new file mode 100644 index 0000000000..1895164239 --- /dev/null +++ b/benchmarks/ssr/vue/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "vite.config.ts", + "../bench-utils.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/ssr/vue/vite.config.ts b/benchmarks/ssr/vue/vite.config.ts new file mode 100644 index 0000000000..b2b9fc8a09 --- /dev/null +++ b/benchmarks/ssr/vue/vite.config.ts @@ -0,0 +1,32 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackStart({ + srcDirectory: 'src', + }), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + }, + test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, + name: '@benchmarks/ssr (vue)', + watch: false, + environment: 'node', + }, +}) diff --git a/benchmarks/tsconfig.json b/benchmarks/tsconfig.json new file mode 100644 index 0000000000..5e9ff9a8e1 --- /dev/null +++ b/benchmarks/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["cpu-simulation.ts"] +} diff --git a/docs/AGENTS.md b/docs/AGENTS.md new file mode 100644 index 0000000000..ab2d4117e2 --- /dev/null +++ b/docs/AGENTS.md @@ -0,0 +1,4 @@ +# Documentation + +- Register new published pages in `router/config.json` or `start/config.json`; drafts need not be registered. +- Run `pnpm test:docs` from the repository root for Markdown link validation. It checks `docs/**/*.md`, not Markdown elsewhere. Relative links resolve from the containing file. diff --git a/docs/router/api/file-based-routing.md b/docs/router/api/file-based-routing.md index 55a37a8c67..7c94d484d1 100644 --- a/docs/router/api/file-based-routing.md +++ b/docs/router/api/file-based-routing.md @@ -101,6 +101,34 @@ src/routes/posts.route.tsx -> /posts src/routes/posts/route.tsx -> /posts ``` +#### Using regex patterns for `routeToken` + +You can use a regular expression pattern instead of a literal string to match multiple layout route naming conventions. This is useful when you want more flexibility in your file naming. + +**In `tsr.config.json`** (JSON config), use an object with `regex` and optional `flags` properties: + +```json +{ + "routeToken": { "regex": "[a-z]+-layout", "flags": "i" } +} +``` + +**In code** (inline config), you can use a native `RegExp`: + +```ts +{ + routeToken: /[a-z]+-layout/i +} +``` + +With the regex pattern `[a-z]+-layout`, filenames like `dashboard.main-layout.tsx`, `posts.protected-layout.tsx`, or `admin.settings-layout.tsx` would all be recognized as layout routes. + +> [!NOTE] +> The regex is matched against the **entire** final segment of the route path. For example, with `routeToken: { "regex": "[a-z]+-layout" }`: +> +> - `dashboard.main-layout.tsx` matches (`main-layout` is the full segment) +> - `dashboard.my-layout-extra.tsx` does NOT match (the segment is `my-layout-extra`, not just `my-layout`) + ### `indexToken` As mentioned in the Routing Concepts guide, an index route is a route that is matched when the URL path is exactly the same as the parent route. The `indexToken` is used to identify the index route file in the route directory. @@ -114,6 +142,32 @@ src/routes/posts.index.tsx -> /posts/ src/routes/posts/index.tsx -> /posts/ ``` +#### Using regex patterns for `indexToken` + +Similar to `routeToken`, you can use a regular expression pattern for `indexToken` to match multiple index route naming conventions. + +**In `tsr.config.json`** (JSON config): + +```json +{ + "indexToken": { "regex": "[a-z]+-page" } +} +``` + +**In code** (inline config): + +```ts +{ + indexToken: /[a-z]+-page/ +} +``` + +With the regex pattern `[a-z]+-page`, filenames like `home-page.tsx`, `posts.list-page.tsx`, or `dashboard.overview-page.tsx` would all be recognized as index routes. + +#### Escaping regex tokens + +When using regex tokens, you can still escape a segment to prevent it from being treated as a token by wrapping it in square brackets. For example, if your `indexToken` is `{ "regex": "[a-z]+-page" }` and you want a literal route segment called `home-page`, name your file `[home-page].tsx`. + ### `quoteStyle` When your generated route tree is generated and when you first create a new route, those files will be formatted with the quote style you specify here. @@ -134,7 +188,7 @@ By default, this value is set to `false`. ### `autoCodeSplitting` -This feature is only available if you are using the TanStack Router Bundler Plugin. +This feature is only available if you are using the TanStack Router Bundler Plugin with Vite, Rspack/Rsbuild or Webpack. With Esbuild, setting it to `true` is an error. This option is used to enable automatic code-splitting for non-critical route configuration items. See the "Automatic Code-Splitting" guide for more information. @@ -153,9 +207,23 @@ By default, this value is set to `false`. ### `addExtensions` -This option adds file extensions to the route names in the generated route tree. +- Type: `boolean | string` +- Default: `false` -By default, this value is set to `false`. +This option controls file extensions on import paths in the generated route tree. + +- `false` — Extensions are stripped from import paths (e.g. `'./routes/posts'`) +- `true` — The original file extensions are kept (e.g. `'./routes/posts.tsx'`) +- `string` — The original extension is replaced with the provided one (e.g. `'js'` produces `'./routes/posts.js'`) + +Passing a string is useful when your project uses ESM, since Node.js ESM requires `.js` extensions for imports even when the source files are `.ts` or `.tsx`. + +```ts +// Example: replace .tsx/.ts extensions with .js in generated imports +TanStackRouterVite({ + addExtensions: 'js', +}) +``` ### `disableLogging` diff --git a/docs/router/framework/react/api/router.md b/docs/router/api/router.md similarity index 98% rename from docs/router/framework/react/api/router.md rename to docs/router/api/router.md index 950c493f8a..2c5ede186c 100644 --- a/docs/router/framework/react/api/router.md +++ b/docs/router/api/router.md @@ -37,7 +37,7 @@ title: Router API - Hooks - [`useAwaited`](./router/useAwaitedHook.md) - [`useBlocker`](./router/useBlockerHook.md) - - [`useCanGoBack`](./router//useCanGoBack.md) + - [`useCanGoBack`](./router/useCanGoBack.md) - [`useChildMatches`](./router/useChildMatchesHook.md) - [`useLinkProps`](./router/useLinkPropsHook.md) - [`useLoaderData`](./router/useLoaderDataHook.md) diff --git a/docs/router/framework/react/api/router/ActiveLinkOptionsType.md b/docs/router/api/router/ActiveLinkOptionsType.md similarity index 100% rename from docs/router/framework/react/api/router/ActiveLinkOptionsType.md rename to docs/router/api/router/ActiveLinkOptionsType.md diff --git a/docs/router/framework/react/api/router/AsyncRouteComponentType.md b/docs/router/api/router/AsyncRouteComponentType.md similarity index 100% rename from docs/router/framework/react/api/router/AsyncRouteComponentType.md rename to docs/router/api/router/AsyncRouteComponentType.md diff --git a/docs/router/framework/react/api/router/FileRouteClass.md b/docs/router/api/router/FileRouteClass.md similarity index 100% rename from docs/router/framework/react/api/router/FileRouteClass.md rename to docs/router/api/router/FileRouteClass.md diff --git a/docs/router/framework/react/api/router/LinkOptionsType.md b/docs/router/api/router/LinkOptionsType.md similarity index 80% rename from docs/router/framework/react/api/router/LinkOptionsType.md rename to docs/router/api/router/LinkOptionsType.md index 481a5b4a3d..9d3d3fe8d8 100644 --- a/docs/router/framework/react/api/router/LinkOptionsType.md +++ b/docs/router/api/router/LinkOptionsType.md @@ -9,7 +9,7 @@ The `LinkOptions` type extends the [`NavigateOptions`](./NavigateOptionsType.md) type LinkOptions = NavigateOptions & { target?: HTMLAnchorElement['target'] activeOptions?: ActiveOptions - preload?: false | 'intent' + preload?: false | 'intent' | 'viewport' | 'render' preloadDelay?: number disabled?: boolean } @@ -42,7 +42,7 @@ The `LinkOptions` object accepts/contains the following properties: - Type: `number` - Optional -- Delay intent preloading by this many milliseconds. If the intent exits before this delay, the preload will be cancelled. +- Delay focus, hover, and viewport preloading by this many milliseconds. Touch intent preloads immediately. If focus or hover ends, or the link leaves the viewport before the delay, the preload will be cancelled. ### `disabled` diff --git a/docs/router/framework/react/api/router/LinkPropsType.md b/docs/router/api/router/LinkPropsType.md similarity index 100% rename from docs/router/framework/react/api/router/LinkPropsType.md rename to docs/router/api/router/LinkPropsType.md diff --git a/docs/router/framework/react/api/router/MatchRouteOptionsType.md b/docs/router/api/router/MatchRouteOptionsType.md similarity index 100% rename from docs/router/framework/react/api/router/MatchRouteOptionsType.md rename to docs/router/api/router/MatchRouteOptionsType.md diff --git a/docs/router/framework/react/api/router/NavigateOptionsType.md b/docs/router/api/router/NavigateOptionsType.md similarity index 100% rename from docs/router/framework/react/api/router/NavigateOptionsType.md rename to docs/router/api/router/NavigateOptionsType.md diff --git a/docs/router/framework/react/api/router/NotFoundErrorType.md b/docs/router/api/router/NotFoundErrorType.md similarity index 93% rename from docs/router/framework/react/api/router/NotFoundErrorType.md rename to docs/router/api/router/NotFoundErrorType.md index bad29f9f70..1f4fbe4c74 100644 --- a/docs/router/framework/react/api/router/NotFoundErrorType.md +++ b/docs/router/api/router/NotFoundErrorType.md @@ -29,7 +29,7 @@ The `NotFoundError` object accepts/contains the following properties: - Type: `any` - Optional -- Custom data that is passed into to `notFoundComponent` when the not-found error is handled +- Custom data that is passed into `notFoundComponent` when the not-found error is handled ### `throw` property @@ -37,7 +37,7 @@ The `NotFoundError` object accepts/contains the following properties: - Optional - `default: false` - If provided, will throw the not-found object instead of returning it. This can be useful in places where `throwing` in a function might cause it to have a return type of `never`. In that case, you can use `notFound({ throw: true })` to throw the not-found object instead of returning it. -### `route` property +### `routeId` property - Type: `string` - Optional diff --git a/docs/router/framework/react/api/router/NotFoundRouteClass.md b/docs/router/api/router/NotFoundRouteClass.md similarity index 100% rename from docs/router/framework/react/api/router/NotFoundRouteClass.md rename to docs/router/api/router/NotFoundRouteClass.md diff --git a/docs/router/framework/react/api/router/ParsedHistoryStateType.md b/docs/router/api/router/ParsedHistoryStateType.md similarity index 100% rename from docs/router/framework/react/api/router/ParsedHistoryStateType.md rename to docs/router/api/router/ParsedHistoryStateType.md diff --git a/docs/router/framework/react/api/router/ParsedLocationType.md b/docs/router/api/router/ParsedLocationType.md similarity index 100% rename from docs/router/framework/react/api/router/ParsedLocationType.md rename to docs/router/api/router/ParsedLocationType.md diff --git a/docs/router/framework/react/api/router/RedirectType.md b/docs/router/api/router/RedirectType.md similarity index 100% rename from docs/router/framework/react/api/router/RedirectType.md rename to docs/router/api/router/RedirectType.md diff --git a/docs/router/framework/react/api/router/RegisterType.md b/docs/router/api/router/RegisterType.md similarity index 100% rename from docs/router/framework/react/api/router/RegisterType.md rename to docs/router/api/router/RegisterType.md diff --git a/docs/router/framework/react/api/router/RootRouteClass.md b/docs/router/api/router/RootRouteClass.md similarity index 100% rename from docs/router/framework/react/api/router/RootRouteClass.md rename to docs/router/api/router/RootRouteClass.md diff --git a/docs/router/framework/react/api/router/RouteApiClass.md b/docs/router/api/router/RouteApiClass.md similarity index 100% rename from docs/router/framework/react/api/router/RouteApiClass.md rename to docs/router/api/router/RouteApiClass.md diff --git a/docs/router/framework/react/api/router/RouteApiType.md b/docs/router/api/router/RouteApiType.md similarity index 87% rename from docs/router/framework/react/api/router/RouteApiType.md rename to docs/router/api/router/RouteApiType.md index a5d806397b..a8ba9d4b5a 100644 --- a/docs/router/framework/react/api/router/RouteApiType.md +++ b/docs/router/api/router/RouteApiType.md @@ -149,3 +149,35 @@ The `RouteApi` has the following properties and methods: ``` - A type-safe version of [`useNavigate`](./useNavigateHook.md) that is pre-bound to the route ID that the `RouteApi` instance was created with. + +### `redirect` method + +```tsx + redirect(opts?: RedirectOptions): Redirect +``` + +- A type-safe version of the [`redirect`](./redirectFunction.md) function that is pre-bound to the route ID that the `RouteApi` instance was created with. +- The `from` parameter is automatically set to the route ID, enabling type-safe relative redirects. +- Options + - All options from [`redirect`](./redirectFunction.md) except `from`, which is automatically provided. +- Returns + - A `Redirect` object that can be thrown from `beforeLoad` or `loader` callbacks. + +#### Example + +```tsx +import { getRouteApi } from '@tanstack/react-router' + +const routeApi = getRouteApi('/dashboard/settings') + +export const Route = createFileRoute('/dashboard/settings')({ + beforeLoad: ({ context }) => { + if (!context.user) { + // Type-safe redirect - 'from' is automatically '/dashboard/settings' + throw routeApi.redirect({ + to: '../login', // Relative path to sibling route + }) + } + }, +}) +``` diff --git a/docs/router/framework/react/api/router/RouteClass.md b/docs/router/api/router/RouteClass.md similarity index 100% rename from docs/router/framework/react/api/router/RouteClass.md rename to docs/router/api/router/RouteClass.md diff --git a/docs/router/framework/react/api/router/RouteMaskType.md b/docs/router/api/router/RouteMaskType.md similarity index 100% rename from docs/router/framework/react/api/router/RouteMaskType.md rename to docs/router/api/router/RouteMaskType.md diff --git a/docs/router/api/router/RouteMatchType.md b/docs/router/api/router/RouteMatchType.md new file mode 100644 index 0000000000..b5009ebe68 --- /dev/null +++ b/docs/router/api/router/RouteMatchType.md @@ -0,0 +1,36 @@ +--- +id: RouteMatchType +title: RouteMatch type +--- + +The `RouteMatch` type represents a route match in TanStack Router. + +```tsx +interface RouteMatch { + id: string + routeId: string + pathname: string + params: Route['allParams'] + status: 'pending' | 'success' | 'error' | 'notFound' + isFetching: false | 'beforeLoad' | 'loader' + error: unknown + paramsError: unknown + searchError: unknown + updatedAt: number + loaderData?: Route['loaderData'] + context: Route['allContext'] + search: Route['fullSearchSchema'] + abortController: AbortController + cause: 'preload' | 'enter' | 'stay' + ssr?: boolean | 'data-only' +} +``` + +`status` describes the match's render state. `isFetching` independently exposes +active `beforeLoad` or loader work. In particular, a successful match can report +`isFetching: 'loader'` while stale data remains visible during a background +reload. + +The router state can contain matches below the pending, error, or not-found +boundary. Those matches remain observable as part of the structurally matched +lane even though the route renderer stops at the boundary. diff --git a/docs/router/api/router/RouteOptionsType.md b/docs/router/api/router/RouteOptionsType.md new file mode 100644 index 0000000000..2adfc6e5c6 --- /dev/null +++ b/docs/router/api/router/RouteOptionsType.md @@ -0,0 +1,402 @@ +--- +id: RouteOptionsType +title: RouteOptions type +--- + +The `RouteOptions` type is used to describe the options that can be used when creating a route. + +## RouteOptions properties + +The `RouteOptions` type accepts an object with the following properties: + +### `getParentRoute` method + +- Type: `() => TParentRoute` +- Required +- A function that returns the parent route of the route being created. This is required to provide full type safety to child route configurations and to ensure that the route tree is built correctly. + +### `path` property + +- Type: `string` +- Required, unless an `id` is provided to configure the route as a pathless layout route +- The path segment that will be used to match the route. + +### `id` property + +- Type: `string` +- Optional, but required if a `path` is not provided +- The unique identifier for the route if it is to be configured as a pathless layout route. If provided, the route will not match against the location pathname and its routes will be flattened into its parent route for matching. + +### `component` property + +- Type: `RouteComponent` or `LazyRouteComponent` +- Optional - Defaults to `` +- The content to be rendered when the route is matched. + +### `errorComponent` property + +- Type: `RouteComponent` or `LazyRouteComponent` +- Optional - Defaults to `routerOptions.defaultErrorComponent` +- The content to be rendered when the route encounters an error. + +### `pendingComponent` property + +- Type: `RouteComponent` or `LazyRouteComponent` +- Optional - Defaults to `routerOptions.defaultPendingComponent` +- The content to be rendered if and when the route is pending and has reached its pendingMs threshold. + +### `notFoundComponent` property + +- Type: `NotFoundRouteComponent` or `LazyRouteComponent` +- Optional - Defaults to `routerOptions.defaultNotFoundComponent` +- The content to be rendered when the route is not found. + +### `validateSearch` method + +- Type: `(rawSearchParams: unknown) => TSearchSchema` +- Optional +- A function that will be called when this route is matched and passed the raw search params from the current location and return valid parsed search params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's search params and the return type will be inferred into the rest of the router. +- This is a planning callback. It must be deterministic and side-effect-free for the same input; do not navigate or mutate application/router state from it. +- Optionally, the parameter type can be tagged with the `SearchSchemaInput` type like this: `(searchParams: TSearchSchemaInput & SearchSchemaInput) => TSearchSchema`. If this tag is present, `TSearchSchemaInput` will be used to type the `search` property of `` and `navigate()` **instead of** `TSearchSchema`. The difference between `TSearchSchemaInput` and `TSearchSchema` can be useful, for example, to express optional search parameters. + +### `search.middlewares` property + +- Type: `(({search: TSearchSchema, next: (newSearch: TSearchSchema) => TSearchSchema}) => TSearchSchema)[]` +- Optional +- Search middlewares are functions that transform the search parameters when generating new links for a route or its descendants. +- A search middleware is passed in the current search (if it is the first middleware to run) or is invoked by the previous middleware calling `next`. + +### `parseParams` method (⚠️ deprecated, use `params.parse` instead) + +- Type: `(rawParams: Record) => TParams` +- Optional +- A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router. +- This is a planning callback. It must be deterministic and side-effect-free for the same input. + +### `stringifyParams` method (⚠️ deprecated, use `params.stringify` instead) + +- Type: `(params: TParams) => Record` +- Required if `parseParams` is provided +- A function that will be called when this route's parsed params are being used to build a location. This function should return a valid object of `Record` mapping. + +### `params.parse` method + +- Type: `(rawParams: Record) => TParams | false` +- Optional +- A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function returns parsed params, its return value will be used as the route's params and the return type will be inferred into the rest of the router. +- This is a planning callback. It must be deterministic and side-effect-free for the same input. +- Experimental: returning `false` during incoming route matching skips this route and allows matching to continue to another candidate route. + +### `params.priority` property + +- Type: `number` +- Optional +- Defaults to `0` +- Controls the matching order when multiple route candidates with `params.parse` can match the same URL segment. Higher numbers are tried first. If a higher-priority route's `params.parse` returns `false`, matching continues to the next candidate. +- This only affects competing candidates that use `params.parse`; normal route specificity still applies, so static routes continue to match before dynamic, optional, or wildcard routes. + +### `params.stringify` method + +- Type: `(params: TParams) => Record` +- A function that will be called when this route's parsed params are being used to build a location. This function should return a valid object of `Record` mapping. + +### `beforeLoad` method + +- Type: + +```tsx +type beforeLoad = ( + opts: RouteMatch & { + search: TFullSearchSchema + abortController: AbortController + preload: boolean + params: TAllParams + context: TParentContext + location: ParsedLocation + navigate: NavigateFn // @deprecated + buildLocation: BuildLocationFn + cause: 'preload' | 'enter' | 'stay' + }, +) => Promise | TRouteContext | void +``` + +- Optional +- [`ParsedLocation`](./ParsedLocationType.md) +- This async function is called before a route is loaded. If it fails, the route's loader and its descendants will not run. During navigation, ordinary errors become the match's error state and are passed to the `onError` function. During a preload, ordinary errors and not-found results are represented in the returned speculative match lane instead of rejecting the `preloadRoute` promise. +- If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the `pendingComponent` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render. +- If this function returns a `TRouteContext` object, that object will be merged into the route's context and be made available in the `loader` and other related route components/methods. +- It's common to use this function to check if a user is authenticated and redirect them to a login page if they are not. To do this, you can either return or throw a `redirect` object from this function. + +> 🚧 `opts.navigate` has been deprecated and will be removed in the next major release. Use `throw redirect({ to: '/somewhere' })` instead. Read more about the `redirect` function [here](./redirectFunction.md). + +### `loader` method + +- Type: + +```tsx +type loaderFn = ( + opts: RouteMatch & { + abortController: AbortController + cause: 'preload' | 'enter' | 'stay' + context: TAllContext + deps: TLoaderDeps + location: ParsedLocation + params: TAllParams + preload: boolean + parentMatchPromise: Promise> + navigate: NavigateFn // @deprecated + route: AnyRoute + }, +) => Promise | TLoaderData | void + +type loader = + | loaderFn + | { + handler: loaderFn + staleReloadMode?: 'background' | 'blocking' + } +``` + +- Optional +- [`ParsedLocation`](./ParsedLocationType.md) +- This async function is called when a route is matched and passed the route's match object. During navigation, ordinary errors become the match's error state and are passed to the `onError` function. During a preload, ordinary errors and not-found results are represented in the returned speculative match lane instead of rejecting the `preloadRoute` promise. +- If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the `pendingComponent` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render. +- If this function returns a `TLoaderData` object, that object will be stored on the route match and can remain available in the in-memory cache after the match becomes inactive. Navigation-owned data uses `gcTime` for retention, while preload-owned data uses `preloadGcTime`. It can be accessed using the `useLoaderData` hook in any component that is a child of the route match before another `` is rendered. +- Deps must be returned by your `loaderDeps` function in order to appear. +- Use the object form to configure loader-specific behavior like `staleReloadMode`. +- `staleReloadMode: 'background'` preserves stale-while-revalidate behavior for stale successful matches. +- `staleReloadMode: 'blocking'` waits for the stale loader reload to complete before continuing. + +> 🚧 `opts.navigate` has been deprecated and will be removed in the next major release. Use `throw redirect({ to: '/somewhere' })` instead. Read more about the `redirect` function [here](./redirectFunction.md). + +### `loaderDeps` method + +- Type: + +```tsx +type loaderDeps = (opts: { search: TFullSearchSchema }) => Record +``` + +- Optional +- A function that will be called before this route is matched to provide additional unique identification to the route match and serve as a dependency tracker for when the match should be reloaded. It should return any serializable value that can uniquely identify the route match from navigation to navigation. +- This is a planning callback and cache-key function. It must be deterministic and side-effect-free for the same validated search input. The returned value and any serialization methods on it, such as `toJSON`, must also be side-effect-free. +- By default, path params are already used to uniquely identify a route match, so it's unnecessary to return these here. +- If your route match relies on search params for unique identification, it's required that you return them here so they can be made available in the `loader`'s `deps` argument. + +### `staleTime` property + +- Type: `number` +- Optional +- Defaults to `routerOptions.defaultStaleTime`, which defaults to `0` +- The amount of time in milliseconds that a route match's loader data will be considered fresh. If a route match is matched again within this time frame, its loader data will not be reloaded. + +### `preload` property + +- Type: `boolean` +- Optional +- Defaults to `true` +- If `false`, speculative preloads still run this route's `beforeLoad` function but skip its `loader`. A navigation runs both `beforeLoad` and the skipped `loader` normally. + +### `preloadStaleTime` property + +- Type: `number` +- Optional +- Defaults to `routerOptions.defaultPreloadStaleTime`, which defaults to `30_000` ms (30 seconds) +- The amount of time in milliseconds that loader data produced by a preload is considered fresh. Another preload or the first navigation can reuse it within this interval. After navigation accepts the generation, subsequent freshness uses `staleTime`. + +### `gcTime` property + +- Type: `number` +- Optional +- Defaults to `routerOptions.defaultGcTime`, which defaults to 5 minutes. +- The retention window in milliseconds for unused loader data from an ordinary load. Once the data is older than this value, it is eligible for pruning during a later cache reconciliation. + +### `shouldReload` property + +- Type: `boolean | ((args: LoaderArgs) => boolean)` +- Optional +- If `false` or returns `false`, the route match's loader data will not be reloaded on subsequent matches. +- If `true` or returns `true`, the route match's loader data will be reloaded on subsequent matches. +- If `undefined` or returns `undefined`, the route match's loader data will adhere to the default stale-while-revalidate behavior. + +### `caseSensitive` property + +- Type: `boolean` +- Optional +- If `true`, this route will be matched as case-sensitive. + +### `wrapInSuspense` property + +- Type: `boolean` +- Optional +- If `true`, this route will be forcefully wrapped in a suspense boundary, regardless if a reason is found to do so from inspecting its provided components. + +### `pendingMs` property + +- Type: `number` +- Optional +- Defaults to `routerOptions.defaultPendingMs`, which defaults to `1000` +- The threshold in milliseconds that a route must be pending before its `pendingComponent` is shown. + +### `pendingMinMs` property + +- Type: `number` +- Optional +- Defaults to `routerOptions.defaultPendingMinMs` which defaults to `500` +- The minimum amount of time in milliseconds that the pending component will be shown for if it is shown. This is useful to prevent the pending component from flashing on the screen for a split second. + +### `preloadGcTime` property + +- Type: `number` +- Optional +- Defaults to `routerOptions.defaultPreloadGcTime`, which defaults to 5 minutes. +- The retention window in milliseconds for unused loader data produced by a preload. Once the data is older than this value, it is eligible for pruning during a later cache reconciliation. Use `preloadStaleTime` to control whether retained data is fresh enough to reuse without reloading. + +### `preSearchFilters` property (⚠️ deprecated, use `search.middlewares` instead) + +- Type: `((search: TFullSearchSchema) => TFullSearchSchema)[]` +- Optional +- An array of functions that will be called when generating any new links to this route or its grandchildren. +- Each function will be called with the current search params and should return a new search params object that will be used to generate the link. +- It has a `pre` prefix because it is called before the user-provided function that is passed to `navigate`/`Link` etc has a chance to modify the search params. + +### `postSearchFilters` property (⚠️ deprecated, use `search.middlewares` instead) + +- Type: `((search: TFullSearchSchema) => TFullSearchSchema)[]` +- Optional +- An array of functions that will be called when generating any new links to this route or its grandchildren. +- Each function will be called with the current search params and should return a new search params object that will be used to generate the link. +- It has a `post` prefix because it is called after the user-provided function that is passed to `navigate`/`Link` etc has modified the search params. + +### `onError` property + +- Type: `(error: any) => void` +- Optional +- A function that will be called when an error is thrown during a navigation or preload event. +- If this function throws a [`redirect`](./redirectFunction.md), the redirect replaces the original error and becomes control flow for the current navigation or preload operation. If it throws a not-found result, that result replaces the original error in the current match lane. + +### `onEnter` property + +- Type: `(match: RouteMatch) => void` +- Optional +- A function that will be called when a route is matched and loaded after not being matched in the previous location. +- Routes below an error or not-found boundary do not enter the active route lifecycle. The boundary itself remains active. A previously hidden route receives `onEnter` when a navigation makes it active again. + +### `onStay` property + +- Type: `(match: RouteMatch) => void` +- Optional +- A function that will be called when a route is matched and loaded after being matched in the previous location. +- Both navigations must include the route in the active branch, through the first error or not-found boundary. + +### `onLeave` property + +- Type: `(match: RouteMatch) => void` +- Optional +- A function that will be called when a route is no longer matched after being matched in the previous location. +- This also runs when a navigation hides a previously active route below an error or not-found boundary, even if the route remains structurally matched. +- Background reloads update route data without dispatching these lifecycle callbacks. + +### `onCatch` property + +- Type: `(error: unknown) => void` in React and Vue; `(error: Error) => void` in Solid +- Optional - Defaults to `routerOptions.defaultOnCatch` +- A function that will be called when errors are caught when the route encounters an error. + +### `remountDeps` method + +- Type: + +```tsx +type remountDeps = (opts: RemountDepsOptions) => any + +interface RemountDepsOptions< + in out TRouteId, + in out TFullSearchSchema, + in out TAllParams, + in out TLoaderDeps, +> { + routeId: TRouteId + search: TFullSearchSchema + params: TAllParams + loaderDeps: TLoaderDeps +} +``` + +- Optional +- A function that will be called to determine whether a route component shall be remounted after navigation. If this function returns a different value than previously, it will remount. +- The return value needs to be JSON serializable. +- By default, a route component will not be remounted if it stays active after a navigation. + +Example: +If you want to configure to remount a route component upon `params` change, use: + +```tsx +remountDeps: ({ params }) => params +``` + +### `headers` method + +- Type: + +```tsx +type headers = (opts: { + matches: Array + match: RouteMatch + params: TAllParams + loaderData?: TLoaderData +}) => Promise> | Record +``` + +- Optional +- Allows you to specify custom HTTP headers to be sent when this route is rendered during SSR. The function receives the current match context and should return a plain object of header name/value pairs. + +### `head` method + +- Type: + +```tsx +type head = (ctx: { + matches: Array + match: RouteMatch + params: TAllParams + loaderData?: TLoaderData +}) => + | Promise<{ + links?: RouteMatch['links'] + scripts?: RouteMatch['headScripts'] + meta?: RouteMatch['meta'] + styles?: RouteMatch['styles'] + }> + | { + links?: RouteMatch['links'] + scripts?: RouteMatch['headScripts'] + meta?: RouteMatch['meta'] + styles?: RouteMatch['styles'] + } +``` + +- Optional +- Returns additional elements to inject into the document `` for this route. Use it to add route-level SEO metadata, preload links, inline styles, or custom scripts. + +### `scripts` method + +- Type: + +```tsx +type scripts = (ctx: { + matches: Array + match: RouteMatch + params: TAllParams + loaderData?: TLoaderData +}) => Promise | RouteMatch['scripts'] +``` + +- Optional +- A shorthand helper to return only ` + + diff --git a/e2e/react-router/i18n-paraglide/messages/de.json b/e2e/react-router/i18n-paraglide/messages/de.json new file mode 100644 index 0000000000..11498bd8b6 --- /dev/null +++ b/e2e/react-router/i18n-paraglide/messages/de.json @@ -0,0 +1,7 @@ +{ + "$schema": "https://inlang.com/schema/inlang-message-format", + "example_message": "Guten Tag {username}", + "hello_about": "Hallo /ueber!", + "home_page": "Startseite", + "about_page": "Über uns" +} diff --git a/e2e/react-router/i18n-paraglide/messages/en.json b/e2e/react-router/i18n-paraglide/messages/en.json new file mode 100644 index 0000000000..8a85ed03fc --- /dev/null +++ b/e2e/react-router/i18n-paraglide/messages/en.json @@ -0,0 +1,7 @@ +{ + "$schema": "https://inlang.com/schema/inlang-message-format", + "example_message": "Hello world {username}", + "hello_about": "Hello /about!", + "home_page": "Home page", + "about_page": "About page" +} diff --git a/e2e/react-router/i18n-paraglide/package.json b/e2e/react-router/i18n-paraglide/package.json new file mode 100644 index 0000000000..d1af160f10 --- /dev/null +++ b/e2e/react-router/i18n-paraglide/package.json @@ -0,0 +1,51 @@ +{ + "name": "tanstack-router-e2e-react-i18n-paraglide", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --port 3000", + "dev:e2e": "vite", + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "start": "vite", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "tailwindcss": "^4.2.2" + }, + "devDependencies": { + "@inlang/paraglide-js": "^2.4.0", + "@playwright/test": "^1.61.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@tanstack/router-plugin": "workspace:^", + "@types/node": "^22.10.2", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "@typescript/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 new file mode 100644 index 0000000000..8e94d5f9a1 --- /dev/null +++ b/e2e/react-router/i18n-paraglide/playwright.config.ts @@ -0,0 +1,34 @@ +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}` + +/** + * 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: `VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-router/i18n-paraglide/project.inlang/.gitignore b/e2e/react-router/i18n-paraglide/project.inlang/.gitignore new file mode 100644 index 0000000000..06cf65390f --- /dev/null +++ b/e2e/react-router/i18n-paraglide/project.inlang/.gitignore @@ -0,0 +1 @@ +cache diff --git a/e2e/react-router/i18n-paraglide/project.inlang/project_id b/e2e/react-router/i18n-paraglide/project.inlang/project_id new file mode 100644 index 0000000000..203a95649e --- /dev/null +++ b/e2e/react-router/i18n-paraglide/project.inlang/project_id @@ -0,0 +1 @@ +apLjNFHNH2yAHYTN5d \ No newline at end of file diff --git a/e2e/react-router/i18n-paraglide/project.inlang/settings.json b/e2e/react-router/i18n-paraglide/project.inlang/settings.json new file mode 100644 index 0000000000..9bdce4c8cc --- /dev/null +++ b/e2e/react-router/i18n-paraglide/project.inlang/settings.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://inlang.com/schema/project-settings", + "baseLocale": "en", + "locales": ["en", "de"], + "modules": [ + "https://cdn.jsdelivr.net/npm/@inlang/plugin-message-format@4/dist/index.js", + "https://cdn.jsdelivr.net/npm/@inlang/plugin-m-function-matcher@2/dist/index.js" + ], + "plugin.inlang.messageFormat": { + "pathPattern": "./messages/{locale}.json" + } +} diff --git a/e2e/react-router/i18n-paraglide/src/main.tsx b/e2e/react-router/i18n-paraglide/src/main.tsx new file mode 100644 index 0000000000..b30558a947 --- /dev/null +++ b/e2e/react-router/i18n-paraglide/src/main.tsx @@ -0,0 +1,40 @@ +import { StrictMode } from 'react' +import ReactDOM from 'react-dom/client' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import './styles.css' +// Import the generated route tree +import { routeTree } from './routeTree.gen' +import { deLocalizeUrl, localizeUrl } from './paraglide/runtime.js' + +// Create a new router instance +const router = createRouter({ + routeTree, + context: {}, + defaultPreload: 'intent', + scrollRestoration: true, + defaultStructuralSharing: true, + defaultPreloadStaleTime: 0, + + rewrite: { + input: ({ url }) => deLocalizeUrl(url), + output: ({ url }) => localizeUrl(url), + }, +}) + +// Register the router instance for type safety +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +// Render the app +const rootElement = document.getElementById('app') +if (rootElement && !rootElement.innerHTML) { + const root = ReactDOM.createRoot(rootElement) + root.render( + + + , + ) +} diff --git a/e2e/react-router/i18n-paraglide/src/routes/__root.tsx b/e2e/react-router/i18n-paraglide/src/routes/__root.tsx new file mode 100644 index 0000000000..6f50edef00 --- /dev/null +++ b/e2e/react-router/i18n-paraglide/src/routes/__root.tsx @@ -0,0 +1,68 @@ +import { Link, Outlet, createRootRoute, redirect } from '@tanstack/react-router' +import { + getLocale, + locales, + setLocale, + shouldRedirect, +} from '@/paraglide/runtime' +import { m } from '@/paraglide/messages' + +export const Route = createRootRoute({ + beforeLoad: async () => { + document.documentElement.setAttribute('lang', getLocale()) + + const decision = await shouldRedirect({ url: window.location.href }) + + if (decision.redirectUrl) { + throw redirect({ href: decision.redirectUrl.href }) + } + }, + component: () => ( + <> +
+
+ + {m.home_page()} + + + + {m.about_page()} + +
+ +
+ {locales.map((locale) => ( + + ))} +
+
+ +
+ +
+ +
+ + ), +}) diff --git a/e2e/react-router/i18n-paraglide/src/routes/about.tsx b/e2e/react-router/i18n-paraglide/src/routes/about.tsx new file mode 100644 index 0000000000..93cfdb3bd7 --- /dev/null +++ b/e2e/react-router/i18n-paraglide/src/routes/about.tsx @@ -0,0 +1,10 @@ +import { m } from '@/paraglide/messages' +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/about')({ + component: RouteComponent, +}) + +function RouteComponent() { + return
{m.hello_about()}
+} diff --git a/e2e/react-router/i18n-paraglide/src/routes/index.tsx b/e2e/react-router/i18n-paraglide/src/routes/index.tsx new file mode 100644 index 0000000000..accd04a1a1 --- /dev/null +++ b/e2e/react-router/i18n-paraglide/src/routes/index.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/react-router' +import { m } from '@/paraglide/messages' + +export const Route = createFileRoute('/')({ + component: App, +}) + +function App() { + return ( +
+

+ {m.example_message({ + username: 'TanStack Router!', + })} +

+
+ ) +} diff --git a/e2e/react-router/i18n-paraglide/src/styles.css b/e2e/react-router/i18n-paraglide/src/styles.css new file mode 100644 index 0000000000..23fa2415ca --- /dev/null +++ b/e2e/react-router/i18n-paraglide/src/styles.css @@ -0,0 +1 @@ +@import 'tailwindcss' source('../'); diff --git a/e2e/react-router/i18n-paraglide/src/vite-env.d.ts b/e2e/react-router/i18n-paraglide/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/react-router/i18n-paraglide/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/react-router/i18n-paraglide/tests/navigation.spec.ts b/e2e/react-router/i18n-paraglide/tests/navigation.spec.ts new file mode 100644 index 0000000000..8ec0d82292 --- /dev/null +++ b/e2e/react-router/i18n-paraglide/tests/navigation.spec.ts @@ -0,0 +1,246 @@ +import { expect, test } from '@playwright/test' + +// These tests verify that client-side i18n rewrites work correctly in a pure SPA +// (no server-side rendering). The router uses the rewrite API to: +// - input: de-localize URLs for route matching (e.g., /de/ueber -> /about) +// - output: localize URLs for display (e.g., /about -> /de/ueber) + +test.describe('Client-side i18n navigation', () => { + test('should load the home page without redirect loops', async ({ page }) => { + // Navigate to root - should work without any redirect loop issues + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Verify the page loaded successfully + await expect(page.getByTestId('home-content')).toBeVisible() + await expect(page.getByTestId('home-content')).toContainText('Hello world') + }) + + test('should load the German home page (/de)', async ({ page }) => { + await page.goto('/de') + await page.waitForLoadState('networkidle') + + // Verify we're on the German page + await expect(page.getByTestId('home-content')).toBeVisible() + await expect(page.getByTestId('home-content')).toContainText('Guten Tag') + + // URL should remain /de + expect(page.url()).toContain('/de') + }) + + test('should navigate to about page and update URL correctly', async ({ + page, + }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Click on about link + await page.getByTestId('about-link').click() + await page.waitForLoadState('networkidle') + + // Verify we're on the about page + await expect(page.getByTestId('about-content')).toBeVisible() + await expect(page.getByTestId('about-content')).toContainText( + 'Hello /about!', + ) + + // URL should be /about (English) + expect(page.url()).toContain('/about') + }) + + test('should navigate to German about page with translated URL', async ({ + page, + }) => { + await page.goto('/de') + await page.waitForLoadState('networkidle') + + // Click on about link (should navigate to /de/ueber) + await page.getByTestId('about-link').click() + await page.waitForLoadState('networkidle') + + // Verify we're on the about page with German content + await expect(page.getByTestId('about-content')).toBeVisible() + await expect(page.getByTestId('about-content')).toContainText( + 'Hallo /ueber!', + ) + + // URL should be /de/ueber (German translated path) + expect(page.url()).toContain('/de/ueber') + }) + + test('should directly access German about page (/de/ueber)', async ({ + page, + }) => { + // Direct navigation to translated URL + await page.goto('/de/ueber') + await page.waitForLoadState('networkidle') + + // Verify the page loaded correctly + await expect(page.getByTestId('about-content')).toBeVisible() + await expect(page.getByTestId('about-content')).toContainText( + 'Hallo /ueber!', + ) + + // URL should stay /de/ueber + expect(page.url()).toContain('/de/ueber') + }) + + test('should switch locale and update URLs accordingly', async ({ page }) => { + // Start at English home page + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Verify English content + await expect(page.getByTestId('home-content')).toContainText('Hello world') + + // Switch to German + await page.getByTestId('locale-de').click() + await page.waitForLoadState('networkidle') + + // Verify German content + await expect(page.getByTestId('home-content')).toContainText('Guten Tag') + + // URL should now include /de + expect(page.url()).toContain('/de') + }) + + test('should switch locale on about page and update translated URL', async ({ + page, + }) => { + // Start at English about page + await page.goto('/about') + await page.waitForLoadState('networkidle') + + // Verify English content + await expect(page.getByTestId('about-content')).toContainText( + 'Hello /about!', + ) + + // Switch to German + await page.getByTestId('locale-de').click() + await page.waitForLoadState('networkidle') + + // Verify German content + await expect(page.getByTestId('about-content')).toContainText( + 'Hallo /ueber!', + ) + + // URL should now be /de/ueber (translated path) + expect(page.url()).toContain('/de/ueber') + }) + + test('should maintain correct links after locale switch', async ({ + page, + }) => { + // Start at German home page + await page.goto('/de') + await page.waitForLoadState('networkidle') + + // Verify about link has German translated href + const aboutLink = page.getByTestId('about-link') + await expect(aboutLink).toHaveAttribute('href', '/de/ueber') + + // Switch to English + await page.getByTestId('locale-en').click() + await page.waitForLoadState('networkidle') + + // Verify about link now has English href + await expect(aboutLink).toHaveAttribute('href', '/about') + }) +}) + +test.describe('Client-side navigation without redirect loops', () => { + test('navigating back and forth should not cause issues', async ({ + page, + }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate to about + await page.getByTestId('about-link').click() + await page.waitForLoadState('networkidle') + await expect(page.getByTestId('about-content')).toBeVisible() + + // Navigate back to home + await page.getByTestId('home-link').click() + await page.waitForLoadState('networkidle') + await expect(page.getByTestId('home-content')).toBeVisible() + + // Navigate to about again + await page.getByTestId('about-link').click() + await page.waitForLoadState('networkidle') + await expect(page.getByTestId('about-content')).toBeVisible() + }) + + test('switching locales multiple times should work correctly', async ({ + page, + }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Switch to German + await page.getByTestId('locale-de').click() + await page.waitForLoadState('networkidle') + await expect(page.getByTestId('home-content')).toContainText('Guten Tag') + + // Switch back to English + await page.getByTestId('locale-en').click() + await page.waitForLoadState('networkidle') + await expect(page.getByTestId('home-content')).toContainText('Hello world') + + // Switch to German again + await page.getByTestId('locale-de').click() + await page.waitForLoadState('networkidle') + await expect(page.getByTestId('home-content')).toContainText('Guten Tag') + }) + + test('browser back/forward should work with locale changes', async ({ + page, + }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate to about + await page.getByTestId('about-link').click() + await page.waitForLoadState('networkidle') + + // Switch to German + await page.getByTestId('locale-de').click() + await page.waitForLoadState('networkidle') + expect(page.url()).toContain('/de/ueber') + + // Go back + await page.goBack() + await page.waitForLoadState('networkidle') + + // Should be on about page (English or previous state) + await expect(page.getByTestId('about-content')).toBeVisible() + }) +}) + +test.describe('URL rewrite consistency', () => { + test('internal navigation should use rewritten URLs in links', async ({ + page, + }) => { + await page.goto('/de') + await page.waitForLoadState('networkidle') + + // Check that links are properly localized + const homeLink = page.getByTestId('home-link') + const aboutLink = page.getByTestId('about-link') + + await expect(homeLink).toHaveAttribute('href', '/de') + await expect(aboutLink).toHaveAttribute('href', '/de/ueber') + }) + + test('English links should not have locale prefix', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + const homeLink = page.getByTestId('home-link') + const aboutLink = page.getByTestId('about-link') + + await expect(homeLink).toHaveAttribute('href', '/') + await expect(aboutLink).toHaveAttribute('href', '/about') + }) +}) diff --git a/e2e/react-router/i18n-paraglide/tsconfig.json b/e2e/react-router/i18n-paraglide/tsconfig.json new file mode 100644 index 0000000000..c478245689 --- /dev/null +++ b/e2e/react-router/i18n-paraglide/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "strict": true, + "noImplicitAny": false, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "resolveJsonModule": true, + "allowSyntheticDefaultImports": true, + "skipLibCheck": true, + "allowJs": true, + "paths": { + "@/*": ["./src/*"] + } + }, + "include": ["src", "tests"] +} diff --git a/e2e/react-router/i18n-paraglide/vite.config.ts b/e2e/react-router/i18n-paraglide/vite.config.ts new file mode 100644 index 0000000000..97e9dda7bc --- /dev/null +++ b/e2e/react-router/i18n-paraglide/vite.config.ts @@ -0,0 +1,49 @@ +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { resolve } from 'node:path' +import { paraglideVitePlugin } from '@inlang/paraglide-js' +import tailwindcss from '@tailwindcss/vite' + +export default defineConfig({ + plugins: [ + tailwindcss(), + paraglideVitePlugin({ + project: './project.inlang', + outdir: './src/paraglide', + outputStructure: 'message-modules', + cookieName: 'PARAGLIDE_LOCALE', + strategy: ['url', 'cookie', 'preferredLanguage', 'baseLocale'], + urlPatterns: [ + { + pattern: '/', + localized: [ + ['en', '/'], + ['de', '/de'], + ], + }, + { + pattern: '/about', + localized: [ + ['en', '/about'], + ['de', '/de/ueber'], + ], + }, + { + pattern: '/:path(.*)?', + localized: [ + ['en', '/:path(.*)?'], + ['de', '/de/:path(.*)?'], + ], + }, + ], + }), + tanstackRouter({ autoCodeSplitting: true }), + viteReact(), + ], + resolve: { + alias: { + '@': resolve(__dirname, './src'), + }, + }, +}) diff --git a/e2e/react-router/issue-4759/index.html b/e2e/react-router/issue-4759/index.html new file mode 100644 index 0000000000..9609ea710b --- /dev/null +++ b/e2e/react-router/issue-4759/index.html @@ -0,0 +1,62 @@ + + + + + + Issue 4759 + + + +
+
HTML fallback
+
+ + + + diff --git a/e2e/react-router/issue-4759/package.json b/e2e/react-router/issue-4759/package.json new file mode 100644 index 0000000000..ee6a105ad5 --- /dev/null +++ b/e2e/react-router/issue-4759/package.json @@ -0,0 +1,26 @@ +{ + "name": "tanstack-router-e2e-react-issue-4759", + "private": true, + "type": "module", + "scripts": { + "build": "vite build && tsc --noEmit", + "dev": "vite --port 3000", + "dev:e2e": "vite", + "preview": "vite preview", + "start": "vite", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.14" + } +} diff --git a/e2e/react-router/issue-4759/playwright.config.ts b/e2e/react-router/issue-4759/playwright.config.ts new file mode 100644 index 0000000000..a301f62881 --- /dev/null +++ b/e2e/react-router/issue-4759/playwright.config.ts @@ -0,0 +1,24 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + use: { baseURL }, + webServer: { + command: `VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-router/issue-4759/src/main.tsx b/e2e/react-router/issue-4759/src/main.tsx new file mode 100644 index 0000000000..e251178045 --- /dev/null +++ b/e2e/react-router/issue-4759/src/main.tsx @@ -0,0 +1,74 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '@tanstack/react-router' + +const rootRoute = createRootRoute({ + context: () => ({ locale: 'en' }), + component: RootComponent, +}) +function RootComponent() { + const { locale } = rootRoute.useRouteContext() + return ( +
+ +
+ ) +} +const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: () => new Promise((resolve) => setTimeout(resolve, 1_000)), + component: () =>
loaded
, +}) +const routePendingRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/route-pending', + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: RoutePending, + loader: () => new Promise((resolve) => setTimeout(resolve, 1_000)), + component: () =>
loaded
, +}) +function RoutePending() { + const { locale } = routePendingRoute.useRouteContext() + return ( +
+ route pending +
+ ) +} +const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, routePendingRoute]), +}) +const usesRoutePending = window.location.pathname === '/route-pending' +function DefaultPending() { + const { locale } = indexRoute.useRouteContext() + return ( +
+ default pending +
+ ) +} + +createRoot(document.getElementById('app')!).render( + +
+ +
+
, +) diff --git a/e2e/react-router/issue-4759/tests/issue-4759.spec.ts b/e2e/react-router/issue-4759/tests/issue-4759.spec.ts new file mode 100644 index 0000000000..95689010c8 --- /dev/null +++ b/e2e/react-router/issue-4759/tests/issue-4759.spec.ts @@ -0,0 +1,39 @@ +import { expect, test } from '@playwright/test' +import type { Page } from '@playwright/test' + +async function expectNoBlankFrame( + page: Page, + pendingSource: 'default' | 'route', +) { + const pending = page.locator( + `[data-state="pending"][data-pending-source="${pendingSource}"]`, + ) + await expect(pending).toBeVisible() + await expect(pending).toHaveAttribute('data-locale', 'en') + await expect(page.locator('[data-root-locale="en"]')).toBeVisible() + + const paintStates = await page.evaluate( + () => + (globalThis as typeof globalThis & { __paintStates: Array }) + .__paintStates, + ) + + expect(paintStates).toContain('pending') + expect(paintStates).not.toContain('shell') + expect(paintStates).not.toContain('empty') + await expect(page.locator('[data-state="loaded"]')).toBeVisible() +} + +test('#4759: the initial default pending component has no blank frame before it', async ({ + page, +}) => { + await page.goto('/') + await expectNoBlankFrame(page, 'default') +}) + +test('an initial route pending component has no blank frame before it', async ({ + page, +}) => { + await page.goto('/route-pending') + await expectNoBlankFrame(page, 'route') +}) diff --git a/e2e/react-router/issue-4759/tsconfig.json b/e2e/react-router/issue-4759/tsconfig.json new file mode 100644 index 0000000000..e4ba4788a3 --- /dev/null +++ b/e2e/react-router/issue-4759/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "strict": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "resolveJsonModule": true, + "skipLibCheck": true, + "types": ["vite/client"] + }, + "exclude": ["node_modules", "dist"] +} diff --git a/e2e/react-router/issue-4759/vite.config.ts b/e2e/react-router/issue-4759/vite.config.ts new file mode 100644 index 0000000000..9ffcc67574 --- /dev/null +++ b/e2e/react-router/issue-4759/vite.config.ts @@ -0,0 +1,6 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [react()], +}) diff --git a/e2e/react-router/issue-7120/index.html b/e2e/react-router/issue-7120/index.html new file mode 100644 index 0000000000..04a3530c9d --- /dev/null +++ b/e2e/react-router/issue-7120/index.html @@ -0,0 +1,10 @@ + + + + + + Issues 7120 and 7367 + + + + diff --git a/e2e/react-router/issue-7120/package.json b/e2e/react-router/issue-7120/package.json new file mode 100644 index 0000000000..979b32556c --- /dev/null +++ b/e2e/react-router/issue-7120/package.json @@ -0,0 +1,27 @@ +{ + "name": "tanstack-router-e2e-react-issue-7120", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --port 3000", + "dev:e2e": "vite", + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "start": "vite", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "@tanstack/router-plugin": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.14" + } +} diff --git a/e2e/react-router/issue-7120/playwright.config.ts b/e2e/react-router/issue-7120/playwright.config.ts new file mode 100644 index 0000000000..a8ba116fb4 --- /dev/null +++ b/e2e/react-router/issue-7120/playwright.config.ts @@ -0,0 +1,24 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + use: { baseURL }, + webServer: { + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-router/issue-7120/src/main.tsx b/e2e/react-router/issue-7120/src/main.tsx new file mode 100644 index 0000000000..0c983251af --- /dev/null +++ b/e2e/react-router/issue-7120/src/main.tsx @@ -0,0 +1,21 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ + routeTree, + defaultViewTransition: true, +}) + +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +createRoot(document.getElementById('root')!).render( + + + , +) diff --git a/e2e/react-router/issue-7120/src/redirectGate.ts b/e2e/react-router/issue-7120/src/redirectGate.ts new file mode 100644 index 0000000000..399d303aac --- /dev/null +++ b/e2e/react-router/issue-7120/src/redirectGate.ts @@ -0,0 +1,35 @@ +type RedirectGate = { + waiting: boolean + released: boolean + release: () => void +} + +declare global { + interface Window { + redirectGate: RedirectGate + } +} + +let releasePromise!: () => void +const promise = new Promise((resolve) => { + releasePromise = resolve +}) + +const redirectGate: RedirectGate = { + waiting: false, + released: false, + release: () => { + if (!redirectGate.released) { + redirectGate.released = true + releasePromise() + } + }, +} + +window.redirectGate = redirectGate + +export async function waitForRedirectGate() { + redirectGate.waiting = true + await promise + redirectGate.waiting = false +} diff --git a/e2e/react-router/issue-7120/src/routeTree.gen.ts b/e2e/react-router/issue-7120/src/routeTree.gen.ts new file mode 100644 index 0000000000..e8c6d92110 --- /dev/null +++ b/e2e/react-router/issue-7120/src/routeTree.gen.ts @@ -0,0 +1,77 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as PostsRouteImport } from './routes/posts' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any).lazy(() => import('./routes/posts.lazy').then((d) => d.Route)) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/posts': typeof PostsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/posts': typeof PostsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/posts': typeof PostsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/posts' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/posts' + id: '__root__' | '/' | '/posts' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + PostsRoute: typeof PostsRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + PostsRoute: PostsRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/e2e/react-router/issue-7120/src/routes/__root.tsx b/e2e/react-router/issue-7120/src/routes/__root.tsx new file mode 100644 index 0000000000..2f01516a55 --- /dev/null +++ b/e2e/react-router/issue-7120/src/routes/__root.tsx @@ -0,0 +1,33 @@ +import { Outlet, createRootRoute, redirect } from '@tanstack/react-router' +import { waitForRedirectGate } from '../redirectGate' + +let shouldRedirect = true + +export const Route = createRootRoute({ + pendingMs: 0, + pendingMinMs: 500, + pendingComponent: RootPendingComponent, + beforeLoad: async ({ location }) => { + if (location.pathname !== '/' || !shouldRedirect) { + return + } + + await waitForRedirectGate() + + if (!shouldRedirect) { + return + } + + shouldRedirect = false + throw redirect({ to: '/posts', replace: true }) + }, + component: () => , +}) + +function RootPendingComponent() { + return ( +
+ Loading route +
+ ) +} diff --git a/e2e/react-router/issue-7120/src/routes/index.tsx b/e2e/react-router/issue-7120/src/routes/index.tsx new file mode 100644 index 0000000000..1626ce706b --- /dev/null +++ b/e2e/react-router/issue-7120/src/routes/index.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: () =>
Home
, +}) diff --git a/e2e/react-router/issue-7120/src/routes/posts.lazy.tsx b/e2e/react-router/issue-7120/src/routes/posts.lazy.tsx new file mode 100644 index 0000000000..dc0b0cfd7f --- /dev/null +++ b/e2e/react-router/issue-7120/src/routes/posts.lazy.tsx @@ -0,0 +1,14 @@ +import { createLazyFileRoute } from '@tanstack/react-router' + +export const Route = createLazyFileRoute('/posts')({ + component: PostsComponent, +}) + +function PostsComponent() { + return ( +
+

Posts loaded

+

The redirected lazy route rendered.

+
+ ) +} diff --git a/e2e/react-router/issue-7120/src/routes/posts.tsx b/e2e/react-router/issue-7120/src/routes/posts.tsx new file mode 100644 index 0000000000..cc0519b74e --- /dev/null +++ b/e2e/react-router/issue-7120/src/routes/posts.tsx @@ -0,0 +1,3 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts')({}) diff --git a/e2e/react-router/issue-7120/src/vite-env.d.ts b/e2e/react-router/issue-7120/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/react-router/issue-7120/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts b/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts new file mode 100644 index 0000000000..081ae73691 --- /dev/null +++ b/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts @@ -0,0 +1,33 @@ +import { expect, test } from '@playwright/test' + +test('#7120 / #7367: a root redirect cannot commit a stale match during a view transition', async ({ + page, +}) => { + const pageErrors: Array = [] + const consoleErrors: Array = [] + + page.on('pageerror', (error) => { + pageErrors.push(error.message || String(error)) + }) + page.on('console', (message) => { + if (message.type() === 'error') { + consoleErrors.push(message.text()) + } + }) + + await page.goto('/') + + const pending = page.getByTestId('root-pending') + await expect(pending).toBeVisible() + expect(await page.evaluate(() => window.redirectGate.waiting)).toBe(true) + + await page.evaluate(() => window.redirectGate.release()) + + await expect(page).toHaveURL(/\/posts$/) + await expect( + page.getByRole('heading', { name: 'Posts loaded' }), + ).toBeVisible() + await expect(pending).not.toBeVisible() + expect(pageErrors).toEqual([]) + expect(consoleErrors).toEqual([]) +}) diff --git a/e2e/react-router/issue-7120/tsconfig.json b/e2e/react-router/issue-7120/tsconfig.json new file mode 100644 index 0000000000..4f6089bc08 --- /dev/null +++ b/e2e/react-router/issue-7120/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "resolveJsonModule": true, + "allowJs": true, + "skipLibCheck": true, + "types": ["vite/client"] + }, + "exclude": ["node_modules", "dist"] +} diff --git a/e2e/react-router/issue-7120/vite.config.ts b/e2e/react-router/issue-7120/vite.config.ts new file mode 100644 index 0000000000..5b1c613906 --- /dev/null +++ b/e2e/react-router/issue-7120/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [tanstackRouter({ target: 'react' }), react()], +}) diff --git a/e2e/react-router/issue-7457/index.html b/e2e/react-router/issue-7457/index.html new file mode 100644 index 0000000000..76369b5957 --- /dev/null +++ b/e2e/react-router/issue-7457/index.html @@ -0,0 +1,10 @@ + + + + + + Issue 7457 + + + + diff --git a/e2e/react-router/issue-7457/package.json b/e2e/react-router/issue-7457/package.json new file mode 100644 index 0000000000..838f5173e2 --- /dev/null +++ b/e2e/react-router/issue-7457/package.json @@ -0,0 +1,28 @@ +{ + "name": "tanstack-router-e2e-react-issue-7457", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --port 3000", + "dev:e2e": "vite", + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "start": "vite", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-query": "^5.99.0", + "@tanstack/react-router": "workspace:^", + "@tanstack/router-plugin": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.14" + } +} diff --git a/e2e/react-router/issue-7457/playwright.config.ts b/e2e/react-router/issue-7457/playwright.config.ts new file mode 100644 index 0000000000..a8ba116fb4 --- /dev/null +++ b/e2e/react-router/issue-7457/playwright.config.ts @@ -0,0 +1,24 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + use: { baseURL }, + webServer: { + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-router/issue-7457/src/main.tsx b/e2e/react-router/issue-7457/src/main.tsx new file mode 100644 index 0000000000..1b6805edc0 --- /dev/null +++ b/e2e/react-router/issue-7457/src/main.tsx @@ -0,0 +1,32 @@ +import { StrictMode, useEffect } from 'react' +import { createRoot } from 'react-dom/client' +import { QueryClient } from '@tanstack/react-query' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const queryClient = new QueryClient() +const router = createRouter({ + routeTree, + context: { queryClient }, + defaultPendingComponent: DefaultPendingComponent, + defaultPreloadStaleTime: 0, +}) + +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +function DefaultPendingComponent() { + useEffect(() => { + ;(globalThis as any).__pendingSeen = true + }, []) + return
loading
+} + +createRoot(document.body).render( + + + , +) diff --git a/e2e/react-router/issue-7457/src/routeTree.gen.ts b/e2e/react-router/issue-7457/src/routeTree.gen.ts new file mode 100644 index 0000000000..04a2c94ce8 --- /dev/null +++ b/e2e/react-router/issue-7457/src/routeTree.gen.ts @@ -0,0 +1,77 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as AnotherRouteImport } from './routes/another' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AnotherRoute = AnotherRouteImport.update({ + id: '/another', + path: '/another', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/another': typeof AnotherRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/another': typeof AnotherRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/another': typeof AnotherRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/another' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/another' + id: '__root__' | '/' | '/another' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AnotherRoute: typeof AnotherRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/another': { + id: '/another' + path: '/another' + fullPath: '/another' + preLoaderRoute: typeof AnotherRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AnotherRoute: AnotherRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/e2e/react-router/issue-7457/src/routes/__root.tsx b/e2e/react-router/issue-7457/src/routes/__root.tsx new file mode 100644 index 0000000000..988ba76263 --- /dev/null +++ b/e2e/react-router/issue-7457/src/routes/__root.tsx @@ -0,0 +1,25 @@ +import { Outlet, createRootRouteWithContext } from '@tanstack/react-router' +import type { QueryClient } from '@tanstack/react-query' + +export const Route = createRootRouteWithContext<{ + queryClient: QueryClient +}>()({ + beforeLoad: async ({ context }) => { + await context.queryClient.ensureQueryData({ + queryKey: ['issue-7457-root'], + queryFn: async () => { + await new Promise((resolve) => setTimeout(resolve, 1_500)) + return true + }, + }) + }, + component: RootComponent, +}) + +function RootComponent() { + return ( +
+ +
+ ) +} diff --git a/e2e/react-router/issue-7457/src/routes/another.tsx b/e2e/react-router/issue-7457/src/routes/another.tsx new file mode 100644 index 0000000000..6b6caa55b3 --- /dev/null +++ b/e2e/react-router/issue-7457/src/routes/another.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/another')({ + component: () =>
Hello "/another"!
, +}) diff --git a/e2e/react-router/issue-7457/src/routes/index.tsx b/e2e/react-router/issue-7457/src/routes/index.tsx new file mode 100644 index 0000000000..daaae2aeed --- /dev/null +++ b/e2e/react-router/issue-7457/src/routes/index.tsx @@ -0,0 +1,8 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + beforeLoad: () => { + throw redirect({ to: '/another', replace: true }) + }, + component: () =>
You should never see this!
, +}) diff --git a/e2e/react-router/issue-7457/src/vite-env.d.ts b/e2e/react-router/issue-7457/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/react-router/issue-7457/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts b/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts new file mode 100644 index 0000000000..8b20fac1eb --- /dev/null +++ b/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts @@ -0,0 +1,35 @@ +import { expect, test } from '@playwright/test' + +test('#7457: initial child redirect after async root beforeLoad does not blank', async ({ + page, +}) => { + const pageErrors: Array = [] + const consoleErrors: Array = [] + page.on('pageerror', (error) => + pageErrors.push(error.message || String(error)), + ) + page.on('console', (message) => { + if (message.type() === 'error') { + consoleErrors.push(message.text()) + } + }) + + await page.goto('/') + + await expect(page).toHaveURL(/\/another$/) + const target = page.getByText('Hello "/another"!') + await expect + .poll(async () => ({ + targetCount: await target.count(), + pageErrors: [...pageErrors], + consoleErrors: [...consoleErrors], + })) + .toEqual({ targetCount: 1, pageErrors: [], consoleErrors: [] }) + await expect(target).toBeVisible() + await expect + .poll(() => page.evaluate(() => (globalThis as any).__pendingSeen)) + .toBe(true) + await expect(page.getByTestId('app-pending')).not.toBeVisible() + expect(pageErrors).toEqual([]) + expect(consoleErrors).toEqual([]) +}) diff --git a/e2e/react-router/issue-7457/tsconfig.json b/e2e/react-router/issue-7457/tsconfig.json new file mode 100644 index 0000000000..4f6089bc08 --- /dev/null +++ b/e2e/react-router/issue-7457/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "resolveJsonModule": true, + "allowJs": true, + "skipLibCheck": true, + "types": ["vite/client"] + }, + "exclude": ["node_modules", "dist"] +} diff --git a/e2e/react-router/issue-7457/vite.config.js b/e2e/react-router/issue-7457/vite.config.js new file mode 100644 index 0000000000..9e39ea83d9 --- /dev/null +++ b/e2e/react-router/issue-7457/vite.config.js @@ -0,0 +1,10 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ target: 'react', autoCodeSplitting: true }), + react(), + ], +}) diff --git a/e2e/react-router/js-only-file-based/.devcontainer/devcontainer.json b/e2e/react-router/js-only-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/react-router/js-only-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/react-router/js-only-file-based/package.json b/e2e/react-router/js-only-file-based/package.json index bb6dd24aef..39742d9c84 100644 --- a/e2e/react-router/js-only-file-based/package.json +++ b/e2e/react-router/js-only-file-based/package.json @@ -8,25 +8,24 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", - "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17" + "redaxios": "catalog:", + "tailwindcss": "^4.2.2" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.14" } } diff --git a/e2e/react-router/js-only-file-based/playwright.config.ts b/e2e/react-router/js-only-file-based/playwright.config.ts index 4f93bc1413..0925936d55 100644 --- a/e2e/react-router/js-only-file-based/playwright.config.ts +++ b/e2e/react-router/js-only-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,18 +13,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/js-only-file-based/postcss.config.mjs b/e2e/react-router/js-only-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/react-router/js-only-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/react-router/js-only-file-based/src/posts.js b/e2e/react-router/js-only-file-based/src/posts.js index 979e5e381c..36c1c281f6 100644 --- a/e2e/react-router/js-only-file-based/src/posts.js +++ b/e2e/react-router/js-only-file-based/src/posts.js @@ -2,11 +2,7 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/react-router/js-only-file-based/src/routeTree.gen.js b/e2e/react-router/js-only-file-based/src/routeTree.gen.js index f2d42e5a6c..80683abb30 100644 --- a/e2e/react-router/js-only-file-based/src/routeTree.gen.js +++ b/e2e/react-router/js-only-file-based/src/routeTree.gen.js @@ -9,15 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +}) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -27,11 +32,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, }) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -}) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + }) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,10 +47,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, }) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, }) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -53,12 +59,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, }) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - }) const PostsRouteRouteChildren = { PostsPostIdRoute: PostsPostIdRoute, diff --git a/e2e/react-router/js-only-file-based/src/styles.css b/e2e/react-router/js-only-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/e2e/react-router/js-only-file-based/src/styles.css +++ b/e2e/react-router/js-only-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/react-router/js-only-file-based/src/vite-env.d.ts b/e2e/react-router/js-only-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/react-router/js-only-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/react-router/js-only-file-based/tests/app.spec.ts b/e2e/react-router/js-only-file-based/tests/app.spec.ts index 5a83a314f2..ced5ac9310 100644 --- a/e2e/react-router/js-only-file-based/tests/app.spec.ts +++ b/e2e/react-router/js-only-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts b/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts b/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/js-only-file-based/vite.config.js b/e2e/react-router/js-only-file-based/vite.config.js index 6e4d6d8e1d..db4a4f7edf 100644 --- a/e2e/react-router/js-only-file-based/vite.config.js +++ b/e2e/react-router/js-only-file-based/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', disableTypes: true, diff --git a/e2e/react-router/match-params/.gitignore b/e2e/react-router/match-params/.gitignore new file mode 100644 index 0000000000..4d2da67b50 --- /dev/null +++ b/e2e/react-router/match-params/.gitignore @@ -0,0 +1,11 @@ +node_modules +.DS_Store +dist +dist-hash +dist-ssr +*.local + +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ diff --git a/e2e/react-router/match-params/index.html b/e2e/react-router/match-params/index.html new file mode 100644 index 0000000000..cee534dbdb --- /dev/null +++ b/e2e/react-router/match-params/index.html @@ -0,0 +1,12 @@ + + + + + + Match Params + + +
+ + + diff --git a/e2e/react-router/match-params/package.json b/e2e/react-router/match-params/package.json new file mode 100644 index 0000000000..908be67a9d --- /dev/null +++ b/e2e/react-router/match-params/package.json @@ -0,0 +1,23 @@ +{ + "name": "tanstack-router-e2e-react-match-params", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --port 3000", + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "vite": "^8.0.14" + } +} diff --git a/e2e/react-router/match-params/playwright.config.ts b/e2e/react-router/match-params/playwright.config.ts new file mode 100644 index 0000000000..9e8c1fab2b --- /dev/null +++ b/e2e/react-router/match-params/playwright.config.ts @@ -0,0 +1,26 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + use: { + baseURL, + }, + webServer: { + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-router/match-params/src/main.tsx b/e2e/react-router/match-params/src/main.tsx new file mode 100644 index 0000000000..33709cfcc2 --- /dev/null +++ b/e2e/react-router/match-params/src/main.tsx @@ -0,0 +1,229 @@ +import ReactDOM from 'react-dom/client' +import { + Link, + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '@tanstack/react-router' + +const rootRoute = createRootRoute({ + component: RootComponent, + notFoundComponent: () =>

Root not found

, +}) + +function RootComponent() { + return ( + <> + + + + ) +} + +const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>

Match params e2e

, +}) + +const matchLanguageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/match/{$language}', + params: { + parse: ({ language }) => { + if (language === 'en') return { language: 'en-US' as const } + if (language === 'pl') return { language: 'pl-PL' as const } + return false + }, + stringify: ({ language }) => { + if (language === 'en-US') return { language: 'en' } + if (language === 'pl-PL') return { language: 'pl' } + return { language } + }, + }, + component: MatchLanguageComponent, +}) + +function MatchLanguageComponent() { + const params = matchLanguageRoute.useParams() + return

Match language {params.language}

+} + +const usersRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/users', +}) + +const numericUserRoute = createRoute({ + getParentRoute: () => usersRoute, + path: '$userId', + params: { + parse: ({ userId }) => { + const parsed = Number(userId) + if (!Number.isInteger(parsed)) return false + return { userId: parsed } + }, + stringify: ({ userId }) => ({ userId: String(userId) }), + }, + component: NumericUserComponent, +}) + +function NumericUserComponent() { + const params = numericUserRoute.useParams() + return

Numeric user {params.userId}

+} + +const usernameRoute = createRoute({ + getParentRoute: () => usersRoute, + path: '$username', + component: UsernameComponent, +}) + +function UsernameComponent() { + const params = usernameRoute.useParams() + return

Username {params.username}

+} + +const numericOrgRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/orgs/$orgId', + params: { + parse: ({ orgId }) => { + const parsed = Number(orgId) + if (!Number.isInteger(parsed)) return false + return { orgId: parsed } + }, + stringify: ({ orgId }) => ({ orgId: String(orgId) }), + }, +}) + +const orgSettingsRoute = createRoute({ + getParentRoute: () => numericOrgRoute, + path: 'settings', + component: OrgSettingsComponent, +}) + +function OrgSettingsComponent() { + const params = orgSettingsRoute.useParams() + return

Org settings {params.orgId}

+} + +const orgAboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/orgs/$slug/about', + component: OrgAboutComponent, +}) + +function OrgAboutComponent() { + const params = orgAboutRoute.useParams() + return

Org about {params.slug}

+} + +const ambiguousRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/ambiguous', +}) + +const ambiguousDollarRoute = createRoute({ + getParentRoute: () => ambiguousRoute, + path: '$value', + params: { + parse: ({ value }) => { + if (!value.startsWith('dollar-')) return false + return { value: value.slice(7) } + }, + stringify: ({ value }) => ({ value: `dollar-${value}` }), + }, + component: AmbiguousDollarComponent, +}) + +function AmbiguousDollarComponent() { + const params = ambiguousDollarRoute.useParams() + return

Dollar {params.value}

+} + +const ambiguousCurlyRoute = createRoute({ + getParentRoute: () => ambiguousRoute, + path: '{$value}', + params: { + parse: ({ value }) => { + if (!value.startsWith('curly-')) return false + return { value: value.slice(6) } + }, + stringify: ({ value }) => ({ value: `curly-${value}` }), + }, + component: AmbiguousCurlyComponent, +}) + +function AmbiguousCurlyComponent() { + const params = ambiguousCurlyRoute.useParams() + return

Curly {params.value}

+} + +const routeTree = rootRoute.addChildren([ + indexRoute, + matchLanguageRoute, + usersRoute.addChildren([numericUserRoute, usernameRoute]), + numericOrgRoute.addChildren([orgSettingsRoute]), + orgAboutRoute, + ambiguousRoute.addChildren([ambiguousDollarRoute, ambiguousCurlyRoute]), +]) + +const router = createRouter({ routeTree }) + +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +const rootElement = document.getElementById('app')! + +if (!rootElement.innerHTML) { + ReactDOM.createRoot(rootElement).render() +} diff --git a/e2e/react-router/match-params/tests/match-params.spec.ts b/e2e/react-router/match-params/tests/match-params.spec.ts new file mode 100644 index 0000000000..9b57061911 --- /dev/null +++ b/e2e/react-router/match-params/tests/match-params.spec.ts @@ -0,0 +1,81 @@ +import { expect, test } from '@playwright/test' + +test.beforeEach(async ({ page }) => { + await page.goto('/') +}) + +test('params.parse stringifies links and parses concrete params', async ({ + page, +}) => { + await expect(page.getByTestId('match-en-link')).toHaveAttribute( + 'href', + '/match/en', + ) + + await page.getByTestId('match-en-link').click() + await expect(page.getByTestId('match-language')).toHaveText( + 'Match language en-US', + ) + + await page.goto('/match/pl') + await expect(page.getByTestId('match-language')).toHaveText( + 'Match language pl-PL', + ) + + await page.goto('/match/en-US') + await expect(page.getByTestId('not-found')).toHaveText('Root not found') +}) + +test('params.parse can fall through to sibling dynamic routes', async ({ + page, +}) => { + await expect(page.getByTestId('numeric-user-link')).toHaveAttribute( + 'href', + '/users/456', + ) + await expect(page.getByTestId('username-link')).toHaveAttribute( + 'href', + '/users/alice', + ) + + await page.goto('/users/123') + await expect(page.getByTestId('numeric-user')).toHaveText('Numeric user 123') + + await page.goto('/users/alice') + await expect(page.getByTestId('username')).toHaveText('Username alice') +}) + +test('params.parse can gate child routes', async ({ page }) => { + await expect(page.getByTestId('org-settings-link')).toHaveAttribute( + 'href', + '/orgs/42/settings', + ) + + await page.goto('/orgs/42/settings') + await expect(page.getByTestId('org-settings')).toHaveText('Org settings 42') + + await page.goto('/orgs/acme/about') + await expect(page.getByTestId('org-about')).toHaveText('Org about acme') + + await page.goto('/orgs/acme/settings') + await expect(page.getByTestId('not-found')).toHaveText('Root not found') +}) + +test('buildLocation uses exact route templates before matching paths', async ({ + page, +}) => { + await expect(page.getByTestId('ambiguous-dollar-link')).toHaveAttribute( + 'href', + '/ambiguous/dollar-alpha', + ) + await expect(page.getByTestId('ambiguous-curly-link')).toHaveAttribute( + 'href', + '/ambiguous/curly-alpha', + ) + + await page.getByTestId('ambiguous-dollar-link').click() + await expect(page.getByTestId('ambiguous-dollar')).toHaveText('Dollar alpha') + + await page.getByTestId('ambiguous-curly-link').click() + await expect(page.getByTestId('ambiguous-curly')).toHaveText('Curly alpha') +}) diff --git a/e2e/react-router/match-params/tsconfig.json b/e2e/react-router/match-params/tsconfig.json new file mode 100644 index 0000000000..4f6089bc08 --- /dev/null +++ b/e2e/react-router/match-params/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "resolveJsonModule": true, + "allowJs": true, + "skipLibCheck": true, + "types": ["vite/client"] + }, + "exclude": ["node_modules", "dist"] +} diff --git a/e2e/react-router/match-params/vite.config.js b/e2e/react-router/match-params/vite.config.js new file mode 100644 index 0000000000..4f1b25a0c3 --- /dev/null +++ b/e2e/react-router/match-params/vite.config.js @@ -0,0 +1,3 @@ +import { defineConfig } from 'vite' + +export default defineConfig({}) diff --git a/e2e/react-router/react-compiler/index.html b/e2e/react-router/react-compiler/index.html new file mode 100644 index 0000000000..0c5b6b471c --- /dev/null +++ b/e2e/react-router/react-compiler/index.html @@ -0,0 +1,12 @@ + + + + + + React Compiler useMatchRoute test + + +
+ + + diff --git a/e2e/react-router/react-compiler/package.json b/e2e/react-router/react-compiler/package.json new file mode 100644 index 0000000000..82e6fbf86b --- /dev/null +++ b/e2e/react-router/react-compiler/package.json @@ -0,0 +1,29 @@ +{ + "name": "tanstack-router-e2e-react-compiler", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --port 3000", + "dev:e2e": "vite", + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "start": "vite", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@babel/core": "^7.29.0", + "@playwright/test": "^1.61.0", + "@rolldown/plugin-babel": "^0.2.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "babel-plugin-react-compiler": "^1.0.0", + "vite": "^8.0.14" + } +} diff --git a/e2e/react-router/react-compiler/playwright.config.ts b/e2e/react-router/react-compiler/playwright.config.ts new file mode 100644 index 0000000000..a8ba116fb4 --- /dev/null +++ b/e2e/react-router/react-compiler/playwright.config.ts @@ -0,0 +1,24 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + use: { baseURL }, + webServer: { + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-router/react-compiler/src/main.tsx b/e2e/react-router/react-compiler/src/main.tsx new file mode 100644 index 0000000000..e6e549da83 --- /dev/null +++ b/e2e/react-router/react-compiler/src/main.tsx @@ -0,0 +1,73 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import { + Link, + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, + linkOptions, + useMatchRoute, +} from '@tanstack/react-router' + +const links = linkOptions([ + { to: '/home', label: 'Home' }, + { to: '/about', label: 'About' }, +]) + +function useRouteName() { + const matchRoute = useMatchRoute() + + return links.find((link) => matchRoute(link))?.label ?? 'Unknown' +} + +function RootComponent() { + const matchedRoute = useRouteName() + + return ( + <> + +

+ Matched route: {matchedRoute} +

+ + + ) +} + +const rootRoute = createRootRoute({ component: RootComponent }) +const homeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/home', +}) +const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', +}) +const router = createRouter({ + routeTree: rootRoute.addChildren([homeRoute, aboutRoute]), +}) + +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +const rootElement = document.getElementById('app') +if (!rootElement) { + throw new Error('Root element not found') +} + +createRoot(rootElement).render( + + + , +) diff --git a/e2e/react-router/react-compiler/tests/use-match-route.spec.ts b/e2e/react-router/react-compiler/tests/use-match-route.spec.ts new file mode 100644 index 0000000000..b800e3c908 --- /dev/null +++ b/e2e/react-router/react-compiler/tests/use-match-route.spec.ts @@ -0,0 +1,16 @@ +import { expect, test } from '@playwright/test' + +test('useMatchRoute updates after navigation with React Compiler', async ({ + page, +}) => { + await page.goto('/home') + await expect(page.getByTestId('matched-route')).toHaveText('Home') + + await page.getByRole('link', { name: 'About' }).click() + await expect(page).toHaveURL(/\/about$/) + await expect(page.getByTestId('matched-route')).toHaveText('About') + + await page.getByRole('link', { name: 'Home' }).click() + await expect(page).toHaveURL(/\/home$/) + await expect(page.getByTestId('matched-route')).toHaveText('Home') +}) diff --git a/e2e/react-router/react-compiler/tsconfig.json b/e2e/react-router/react-compiler/tsconfig.json new file mode 100644 index 0000000000..4f6089bc08 --- /dev/null +++ b/e2e/react-router/react-compiler/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "resolveJsonModule": true, + "allowJs": true, + "skipLibCheck": true, + "types": ["vite/client"] + }, + "exclude": ["node_modules", "dist"] +} diff --git a/e2e/react-router/react-compiler/vite.config.js b/e2e/react-router/react-compiler/vite.config.js new file mode 100644 index 0000000000..b4478aced4 --- /dev/null +++ b/e2e/react-router/react-compiler/vite.config.js @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import react, { reactCompilerPreset } from '@vitejs/plugin-react' +import babel from '@rolldown/plugin-babel' + +export default defineConfig({ + plugins: [react(), babel({ presets: [reactCompilerPreset()] })], +}) diff --git a/e2e/react-router/rspack-basic-file-based/.devcontainer/devcontainer.json b/e2e/react-router/rspack-basic-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/react-router/rspack-basic-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/react-router/rspack-basic-file-based/package.json b/e2e/react-router/rspack-basic-file-based/package.json index aa6cc7d247..5ec9ed9862 100644 --- a/e2e/react-router/rspack-basic-file-based/package.json +++ b/e2e/react-router/rspack-basic-file-based/package.json @@ -7,26 +7,27 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@rsbuild/core": "^1.2.4", - "@rsbuild/plugin-react": "^1.1.0", - "@tailwindcss/postcss": "^4.1.15", + "@playwright/test": "^1.61.0", + "@rsbuild/core": "^2.3.1", + "@rsbuild/plugin-react": "^2.0.0", + "@tailwindcss/postcss": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2" + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2" } } diff --git a/e2e/react-router/rspack-basic-file-based/playwright.config.ts b/e2e/react-router/rspack-basic-file-based/playwright.config.ts index decceaef2f..4eead86444 100644 --- a/e2e/react-router/rspack-basic-file-based/playwright.config.ts +++ b/e2e/react-router/rspack-basic-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/rspack-basic-file-based/src/posts.tsx b/e2e/react-router/rspack-basic-file-based/src/posts.tsx index a1225b7fe7..97c96d77eb 100644 --- a/e2e/react-router/rspack-basic-file-based/src/posts.tsx +++ b/e2e/react-router/rspack-basic-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.PUBLIC_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/rspack-basic-file-based/src/styles.css b/e2e/react-router/rspack-basic-file-based/src/styles.css index 4fea791308..0bd1287c82 100644 --- a/e2e/react-router/rspack-basic-file-based/src/styles.css +++ b/e2e/react-router/rspack-basic-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @source './**/*.{js,jsx,ts,tsx}'; diff --git a/e2e/react-router/rspack-basic-file-based/src/vite-env.d.ts b/e2e/react-router/rspack-basic-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/react-router/rspack-basic-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts b/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts index 10beff655f..d230263bfe 100644 --- a/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts +++ b/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts b/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts b/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/rspack-basic-file-based/tsconfig.json b/e2e/react-router/rspack-basic-file-based/tsconfig.json index 76f578eb54..2f5f67eac7 100644 --- a/e2e/react-router/rspack-basic-file-based/tsconfig.json +++ b/e2e/react-router/rspack-basic-file-based/tsconfig.json @@ -12,6 +12,6 @@ "useDefineForClassFields": true, "allowJs": true }, - "include": ["src", "playwright.config.ts", "tests"], + "include": ["src", "tests"], "exclude": ["node_modules", "dist"] } diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} 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 0808478b10..30c62d0af1 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json @@ -7,27 +7,28 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@rsbuild/core": "^1.2.4", - "@rsbuild/plugin-react": "^1.1.0", - "@tailwindcss/postcss": "^4.1.15", + "@playwright/test": "^1.61.0", + "@rsbuild/core": "^2.3.1", + "@rsbuild/plugin-react": "^2.0.0", + "@tailwindcss/postcss": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@tanstack/virtual-file-routes": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2" + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2" } } diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts index bf3adc082c..1c1d021f2f 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm start --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm start --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx index b196982420..cc3cb0f9c8 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.PUBLIC_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/styles.css b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/styles.css index 4fea791308..0bd1287c82 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/styles.css +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @source './**/*.{js,jsx,ts,tsx}'; diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts index a689f459e3..8b808782f6 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json index 7dc6d51cf9..a32f07a8ef 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json @@ -12,6 +12,6 @@ "useDefineForClassFields": true, "allowJs": true }, - "include": ["src", "playwright.config.ts", "tests", "./routes.ts"], + "include": ["src", "tests", "./routes.ts"], "exclude": ["node_modules", "dist"] } diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/.devcontainer/devcontainer.json b/e2e/react-router/scroll-restoration-sandbox-vite/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/react-router/scroll-restoration-sandbox-vite/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/package.json b/e2e/react-router/scroll-restoration-sandbox-vite/package.json index ccc356473c..51e9e70cc5 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/react-router/scroll-restoration-sandbox-vite/package.json @@ -11,27 +11,35 @@ "start": "vite", "test:e2e:browser": "VITE_APP_HISTORY=browser playwright test --config=playwright.browser.config.ts --project=chromium", "test:e2e:hash": "VITE_APP_HISTORY=hash playwright test --config=playwright.hash.config.ts --project=chromium", - "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/router-plugin": "workspace:^", - "@tanstack/zod-adapter": "workspace:^", - "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "redaxios": "catalog:", + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.14" + }, + "nx": { + "targets": { + "test:e2e": { + "outputs": [ + "...", + "{projectRoot}/dist-hash" + ] + } + } } } diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts index 972124647c..eb31d94080 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts @@ -1,15 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, - resolveRuntimeSuffix, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - packageJson.name + `-${resolveRuntimeSuffix('browser')}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,18 +13,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm build && VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `VITE_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts index a6fa77afbf..6b160e3908 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts @@ -1,15 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, - resolveRuntimeSuffix, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - packageJson.name + `-${resolveRuntimeSuffix('hash')}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,18 +13,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/postcss.config.mjs b/e2e/react-router/scroll-restoration-sandbox-vite/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx index e45ef52969..c4a2d0dcca 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -10,11 +10,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export class PostNotFoundError extends Error {} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts b/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts index 6664a9ddf7..0c6823c368 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts @@ -12,10 +12,12 @@ import { createFileRoute } from '@tanstack/react-router' import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as testsPageWithSearchRouteImport } from './routes/(tests)/page-with-search' -import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' -import { Route as testsLazyWithLoaderPageRouteImport } from './routes/(tests)/lazy-with-loader-page' +import { Route as testsIssue7040SourceRouteImport } from './routes/(tests)/issue-7040-source' +import { Route as testsIssue7040TargetRouteImport } from './routes/(tests)/issue-7040-target' import { Route as testsLazyPageRouteImport } from './routes/(tests)/lazy-page' +import { Route as testsLazyWithLoaderPageRouteImport } from './routes/(tests)/lazy-with-loader-page' +import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' +import { Route as testsPageWithSearchRouteImport } from './routes/(tests)/page-with-search' const testsVirtualPageLazyRouteImport = createFileRoute( '/(tests)/virtual-page', @@ -26,23 +28,23 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -const testsVirtualPageLazyRoute = testsVirtualPageLazyRouteImport +const testsIssue7040SourceRoute = testsIssue7040SourceRouteImport.update({ + id: '/(tests)/issue-7040-source', + path: '/issue-7040-source', + getParentRoute: () => rootRouteImport, +} as any) +const testsIssue7040TargetRoute = testsIssue7040TargetRouteImport.update({ + id: '/(tests)/issue-7040-target', + path: '/issue-7040-target', + getParentRoute: () => rootRouteImport, +} as any) +const testsLazyPageRoute = testsLazyPageRouteImport .update({ - id: '/(tests)/virtual-page', - path: '/virtual-page', + id: '/(tests)/lazy-page', + path: '/lazy-page', getParentRoute: () => rootRouteImport, } as any) - .lazy(() => import('./routes/(tests)/virtual-page.lazy').then((d) => d.Route)) -const testsPageWithSearchRoute = testsPageWithSearchRouteImport.update({ - id: '/(tests)/page-with-search', - path: '/page-with-search', - getParentRoute: () => rootRouteImport, -} as any) -const testsNormalPageRoute = testsNormalPageRouteImport.update({ - id: '/(tests)/normal-page', - path: '/normal-page', - getParentRoute: () => rootRouteImport, -} as any) + .lazy(() => import('./routes/(tests)/lazy-page.lazy').then((d) => d.Route)) const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .update({ id: '/(tests)/lazy-with-loader-page', @@ -52,16 +54,28 @@ const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .lazy(() => import('./routes/(tests)/lazy-with-loader-page.lazy').then((d) => d.Route), ) -const testsLazyPageRoute = testsLazyPageRouteImport +const testsNormalPageRoute = testsNormalPageRouteImport.update({ + id: '/(tests)/normal-page', + path: '/normal-page', + getParentRoute: () => rootRouteImport, +} as any) +const testsPageWithSearchRoute = testsPageWithSearchRouteImport.update({ + id: '/(tests)/page-with-search', + path: '/page-with-search', + getParentRoute: () => rootRouteImport, +} as any) +const testsVirtualPageLazyRoute = testsVirtualPageLazyRouteImport .update({ - id: '/(tests)/lazy-page', - path: '/lazy-page', + id: '/(tests)/virtual-page', + path: '/virtual-page', getParentRoute: () => rootRouteImport, } as any) - .lazy(() => import('./routes/(tests)/lazy-page.lazy').then((d) => d.Route)) + .lazy(() => import('./routes/(tests)/virtual-page.lazy').then((d) => d.Route)) export interface FileRoutesByFullPath { '/': typeof IndexRoute + '/issue-7040-source': typeof testsIssue7040SourceRoute + '/issue-7040-target': typeof testsIssue7040TargetRoute '/lazy-page': typeof testsLazyPageRoute '/lazy-with-loader-page': typeof testsLazyWithLoaderPageRoute '/normal-page': typeof testsNormalPageRoute @@ -70,6 +84,8 @@ export interface FileRoutesByFullPath { } export interface FileRoutesByTo { '/': typeof IndexRoute + '/issue-7040-source': typeof testsIssue7040SourceRoute + '/issue-7040-target': typeof testsIssue7040TargetRoute '/lazy-page': typeof testsLazyPageRoute '/lazy-with-loader-page': typeof testsLazyWithLoaderPageRoute '/normal-page': typeof testsNormalPageRoute @@ -79,6 +95,8 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute + '/(tests)/issue-7040-source': typeof testsIssue7040SourceRoute + '/(tests)/issue-7040-target': typeof testsIssue7040TargetRoute '/(tests)/lazy-page': typeof testsLazyPageRoute '/(tests)/lazy-with-loader-page': typeof testsLazyWithLoaderPageRoute '/(tests)/normal-page': typeof testsNormalPageRoute @@ -89,6 +107,8 @@ export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: | '/' + | '/issue-7040-source' + | '/issue-7040-target' | '/lazy-page' | '/lazy-with-loader-page' | '/normal-page' @@ -97,6 +117,8 @@ export interface FileRouteTypes { fileRoutesByTo: FileRoutesByTo to: | '/' + | '/issue-7040-source' + | '/issue-7040-target' | '/lazy-page' | '/lazy-with-loader-page' | '/normal-page' @@ -105,6 +127,8 @@ export interface FileRouteTypes { id: | '__root__' | '/' + | '/(tests)/issue-7040-source' + | '/(tests)/issue-7040-target' | '/(tests)/lazy-page' | '/(tests)/lazy-with-loader-page' | '/(tests)/normal-page' @@ -114,6 +138,8 @@ export interface FileRouteTypes { } export interface RootRouteChildren { IndexRoute: typeof IndexRoute + testsIssue7040SourceRoute: typeof testsIssue7040SourceRoute + testsIssue7040TargetRoute: typeof testsIssue7040TargetRoute testsLazyPageRoute: typeof testsLazyPageRoute testsLazyWithLoaderPageRoute: typeof testsLazyWithLoaderPageRoute testsNormalPageRoute: typeof testsNormalPageRoute @@ -130,32 +156,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/virtual-page': { - id: '/(tests)/virtual-page' - path: '/virtual-page' - fullPath: '/virtual-page' - preLoaderRoute: typeof testsVirtualPageLazyRouteImport + '/(tests)/issue-7040-source': { + id: '/(tests)/issue-7040-source' + path: '/issue-7040-source' + fullPath: '/issue-7040-source' + preLoaderRoute: typeof testsIssue7040SourceRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/page-with-search': { - id: '/(tests)/page-with-search' - path: '/page-with-search' - fullPath: '/page-with-search' - preLoaderRoute: typeof testsPageWithSearchRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/normal-page': { - id: '/(tests)/normal-page' - path: '/normal-page' - fullPath: '/normal-page' - preLoaderRoute: typeof testsNormalPageRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/lazy-with-loader-page': { - id: '/(tests)/lazy-with-loader-page' - path: '/lazy-with-loader-page' - fullPath: '/lazy-with-loader-page' - preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport + '/(tests)/issue-7040-target': { + id: '/(tests)/issue-7040-target' + path: '/issue-7040-target' + fullPath: '/issue-7040-target' + preLoaderRoute: typeof testsIssue7040TargetRouteImport parentRoute: typeof rootRouteImport } '/(tests)/lazy-page': { @@ -165,11 +177,41 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof testsLazyPageRouteImport parentRoute: typeof rootRouteImport } + '/(tests)/lazy-with-loader-page': { + id: '/(tests)/lazy-with-loader-page' + path: '/lazy-with-loader-page' + fullPath: '/lazy-with-loader-page' + preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/normal-page': { + id: '/(tests)/normal-page' + path: '/normal-page' + fullPath: '/normal-page' + preLoaderRoute: typeof testsNormalPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/page-with-search': { + id: '/(tests)/page-with-search' + path: '/page-with-search' + fullPath: '/page-with-search' + preLoaderRoute: typeof testsPageWithSearchRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/virtual-page': { + id: '/(tests)/virtual-page' + path: '/virtual-page' + fullPath: '/virtual-page' + preLoaderRoute: typeof testsVirtualPageLazyRouteImport + parentRoute: typeof rootRouteImport + } } } const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, + testsIssue7040SourceRoute: testsIssue7040SourceRoute, + testsIssue7040TargetRoute: testsIssue7040TargetRoute, testsLazyPageRoute: testsLazyPageRoute, testsLazyWithLoaderPageRoute: testsLazyWithLoaderPageRoute, testsNormalPageRoute: testsNormalPageRoute, diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-source.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-source.tsx new file mode 100644 index 0000000000..3c1702a942 --- /dev/null +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-source.tsx @@ -0,0 +1,49 @@ +import * as React from 'react' +import { Link, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/(tests)/issue-7040-source')({ + component: Component, +}) + +const sectionCount = 180 + +function Component() { + return ( +
+
+

issue-7040-source

+

+ Tall page for reproducing the scroll restoration race. +

+
+ + + Go to issue-7040-target + + +
+ {Array.from({ length: sectionCount }).map((_, index) => ( +
+

Section {index + 1}

+

+ This section adds vertical space so the page can be scrolled far + enough to reproduce issue #7040. +

+
+ ))} +
+ +
+ Bottom of issue-7040-source +
+
+ ) +} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-target.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-target.tsx new file mode 100644 index 0000000000..df541c6dbb --- /dev/null +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-target.tsx @@ -0,0 +1,40 @@ +import * as React from 'react' +import { createFileRoute } from '@tanstack/react-router' +import { sleep } from '../../posts' + +export const Route = createFileRoute('/(tests)/issue-7040-target')({ + loader: async () => { + await sleep(250) + return null + }, + component: Component, +}) + +function Component() { + return ( +
+
+

issue-7040-target

+

+ Short page that should reset to top on navigation. +

+
+ +
+ {Array.from({ length: 18 }).map((_, index) => ( +
+

Target section {index + 1}

+

This page is intentionally much shorter than the source page.

+
+ ))} +
+ +
+ Bottom of issue-7040-target +
+
+ ) +} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx index d9591671f5..427b6f12b0 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx @@ -1,10 +1,9 @@ import { createFileRoute } from '@tanstack/react-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' import { ScrollBlock } from '../-components/scroll-block' export const Route = createFileRoute('/(tests)/page-with-search')({ - validateSearch: zodValidator(z.object({ where: z.string() })), + validateSearch: z.object({ where: z.string() }), component: Component, }) diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/__root.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/__root.tsx index 18726e1168..ed80300a68 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/__root.tsx +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/__root.tsx @@ -45,6 +45,8 @@ function Nav({ type }: { type: 'header' | 'footer' }) { linkOptions({ to: '/virtual-page' }), linkOptions({ to: '/lazy-with-loader-page' }), linkOptions({ to: '/page-with-search', search: { where: type } }), + linkOptions({ to: '/issue-7040-source' }), + linkOptions({ to: '/issue-7040-target' }), ] as const ).map((options, i) => ( {( [ + linkOptions({ to: '/issue-7040-source' }), + linkOptions({ to: '/issue-7040-target' }), linkOptions({ to: '/normal-page' }), linkOptions({ to: '/lazy-page' }), linkOptions({ to: '/virtual-page' }), diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/styles.css b/e2e/react-router/scroll-restoration-sandbox-vite/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/styles.css +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts b/e2e/react-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts @@ -0,0 +1 @@ +/// 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 6b59842625..e396c28686 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts @@ -1,7 +1,23 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import { linkOptions } from '@tanstack/react-router' import { toRuntimePath } from '@tanstack/router-e2e-utils' +type ScrollPaintTestState = { + sourceFrameScrollYs: Array + sourceWasReset: boolean + destinationMounted: boolean + destinationCommitScrollY: number | null + destinationFrameScrollYs: Array + cleanup: () => void +} + +declare global { + interface Window { + __scrollPaintTestState?: ScrollPaintTestState + } +} + test('Smoke - Renders home', async ({ page }) => { await page.goto(toRuntimePath('/')) await expect( @@ -9,6 +25,236 @@ test('Smoke - Renders home', async ({ page }) => { ).toBeVisible() }) +test('PUSH resets scroll before the destination can render a frame (#7815)', async ({ + page, +}) => { + await page.goto(toRuntimePath('/issue-7040-source')) + await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() + + const sourceScrollY = await page.evaluate(async () => { + window.scrollTo(0, 500) + await new Promise((resolve) => requestAnimationFrame(() => resolve())) + return window.scrollY + }) + + expect(sourceScrollY).toBeGreaterThan(0) + + await page.evaluate((expectedSourceScrollY) => { + const root = document.querySelector('#app') + if (!root) { + throw new Error('App root not found') + } + + const geometry = document.createElement('div') + geometry.setAttribute('aria-hidden', 'true') + geometry.style.height = `${window.innerHeight + expectedSourceScrollY + 100}px` + geometry.style.pointerEvents = 'none' + geometry.style.width = '1px' + document.body.append(geometry) + + const state: ScrollPaintTestState = { + sourceFrameScrollYs: [], + sourceWasReset: false, + destinationMounted: false, + destinationCommitScrollY: null, + destinationFrameScrollYs: [], + cleanup: () => {}, + } + + const getDestinationHeading = () => + Array.from(document.querySelectorAll('h3')).find( + (heading) => heading.textContent === 'normal-page', + ) + + const commitObserver = new MutationObserver(() => { + const destinationHeading = getDestinationHeading() + + if (!destinationHeading) { + return + } + + commitObserver.disconnect() + state.destinationMounted = true + state.destinationCommitScrollY = window.scrollY + }) + + commitObserver.observe(root, { childList: true, subtree: true }) + + const handleScroll = () => { + if ( + document.querySelector('[data-testid="issue-7040-source-top"]') && + Math.abs(window.scrollY - expectedSourceScrollY) > 1 + ) { + state.sourceWasReset = true + } + } + window.addEventListener('scroll', handleScroll, { passive: true }) + + const originalScrollTo = window.scrollTo + window.scrollTo = ((...args: Array) => { + const requestedTop = + typeof args[0] === 'number' + ? args[1] + : typeof args[0] === 'object' && args[0] !== null + ? (args[0] as ScrollToOptions).top + : undefined + if ( + typeof requestedTop === 'number' && + Math.abs(requestedTop - expectedSourceScrollY) > 1 && + document.querySelector('[data-testid="issue-7040-source-top"]') + ) { + state.sourceWasReset = true + } + Reflect.apply(originalScrollTo, window, args) + }) as typeof window.scrollTo + + let animationFrameId = 0 + const recordFrame = () => { + if (getDestinationHeading()) { + state.destinationFrameScrollYs.push(window.scrollY) + } else if ( + document.querySelector('[data-testid="issue-7040-source-top"]') + ) { + state.sourceFrameScrollYs.push(window.scrollY) + } + animationFrameId = requestAnimationFrame(recordFrame) + } + animationFrameId = requestAnimationFrame(recordFrame) + + state.cleanup = () => { + commitObserver.disconnect() + cancelAnimationFrame(animationFrameId) + window.removeEventListener('scroll', handleScroll) + window.scrollTo = originalScrollTo + geometry.remove() + delete window.__scrollPaintTestState + } + window.__scrollPaintTestState = state + }, sourceScrollY) + + await page.evaluate( + () => + new Promise((resolve) => { + requestAnimationFrame(() => resolve()) + }), + ) + expect(await page.evaluate(() => window.scrollY)).toBe(sourceScrollY) + + await page + .getByRole('link', { name: 'Head-/normal-page' }) + .dispatchEvent('click') + + await page.waitForFunction(() => { + const state = window.__scrollPaintTestState + if (!state?.destinationMounted) { + return false + } + + const lastFrames = state.destinationFrameScrollYs.slice(-2) + return ( + lastFrames.length === 2 && + lastFrames.every((scrollY) => Math.abs(scrollY) <= 1) + ) + }) + + const observation = await page.evaluate(() => { + const state = window.__scrollPaintTestState + if (!state) { + throw new Error('Scroll paint observer not found') + } + + return { + sourceFrameScrollYs: state.sourceFrameScrollYs, + sourceWasReset: state.sourceWasReset, + destinationCommitScrollY: state.destinationCommitScrollY, + destinationFrameScrollYs: state.destinationFrameScrollYs, + destinationMaxScrollY: + document.documentElement.scrollHeight - window.innerHeight, + finalScrollY: window.scrollY, + } + }) + + expect(observation.sourceFrameScrollYs.length).toBeGreaterThan(0) + expect( + observation.sourceFrameScrollYs.every( + (scrollY) => Math.abs(scrollY - sourceScrollY) <= 1, + ), + ).toBe(true) + expect(observation.sourceWasReset).toBe(false) + expect(observation.destinationMaxScrollY).toBeGreaterThanOrEqual( + sourceScrollY, + ) + expect(observation.finalScrollY).toBe(0) + expect(observation.destinationFrameScrollYs.length).toBeGreaterThanOrEqual(2) + expect( + observation.destinationFrameScrollYs.every( + (scrollY) => Math.abs(scrollY) <= 1, + ), + `Destination paint opportunities: ${observation.destinationFrameScrollYs.join(', ')}, commit: ${observation.destinationCommitScrollY}, final: ${observation.finalScrollY}`, + ).toBe(true) +}) + +test('restores the prior scroll position after browser back then forward', async ({ + page, +}) => { + await page.goto(toRuntimePath('/')) + await page.getByRole('link', { name: 'Head-/normal-page' }).click() + await page.waitForURL('**/normal-page') + await expect(page.getByTestId('at-the-top')).toBeInViewport() + + const scrollY = await page.evaluate(async () => { + window.scrollTo(0, document.documentElement.scrollHeight) + await new Promise((resolve) => requestAnimationFrame(() => resolve(null))) + return window.scrollY + }) + + expect(scrollY).toBeGreaterThan(0) + await expect(page.getByTestId('at-the-bottom')).toBeInViewport() + + await page.goBack() + await expect( + page.getByRole('heading', { name: 'Welcome Home!' }), + ).toBeVisible() + + await page.goForward() + await page.waitForURL('**/normal-page') + await page.waitForFunction( + (expectedScrollY) => Math.abs(window.scrollY - expectedScrollY) <= 2, + scrollY, + ) + await expect(page.getByTestId('at-the-bottom')).toBeInViewport() +}) + +test('restores the prior scroll position after browser back navigation', async ({ + page, +}) => { + await page.goto(toRuntimePath('/normal-page')) + await expect(page.getByTestId('at-the-top')).toBeInViewport() + + const scrollY = await page.evaluate(async () => { + window.scrollTo(0, document.documentElement.scrollHeight) + await new Promise((resolve) => requestAnimationFrame(() => resolve(null))) + return window.scrollY + }) + + expect(scrollY).toBeGreaterThan(0) + await expect(page.getByTestId('at-the-bottom')).toBeInViewport() + + await page.getByRole('link', { name: 'Foot-/', exact: true }).click() + await page.waitForURL('**/') + await expect( + page.getByRole('heading', { name: 'Welcome Home!' }), + ).toBeVisible() + + await page.goBack() + await page.waitForURL('**/normal-page') + await page.waitForFunction( + (expectedScrollY) => Math.abs(window.scrollY - expectedScrollY) <= 2, + scrollY, + ) + await expect(page.getByTestId('at-the-bottom')).toBeInViewport() +}) + const pages = [ linkOptions({ to: '/normal-page' }), linkOptions({ to: '/lazy-page' }), diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts new file mode 100644 index 0000000000..2db25517c8 --- /dev/null +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts @@ -0,0 +1,152 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import type { Page } from '@playwright/test' +import { toRuntimePath } from '@tanstack/router-e2e-utils' + +const attemptCount = 3 +const sourceScrollTargetY = 6000 +const fastScrollStepPx = 220 +const fastScrollDelayMs = 3 +const maxFastScrollSteps = 80 +const preClickReverseScrollPx = 60 + +type ReproAttempt = { + attempt: number + before: { + sourceKey: string + sourceScrollY: number + sourceHeight: number + } + after: { + destinationKey: string + destinationScrollY: number + destinationHeight: number + destinationMaxScrollY: number + } +} + +async function openFreshSourcePage(page: Page) { + await page.goto(toRuntimePath('/issue-7040-source')) + await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() + + await page.evaluate(() => { + sessionStorage.clear() + window.scrollTo(0, 0) + }) + + await page.reload() + await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() +} + +async function fastScrollSourcePage(page: Page) { + await page.evaluate( + async ({ targetScrollY, stepPx, stepDelayMs, maxSteps }) => { + const sleep = (ms: number) => + new Promise((resolve) => setTimeout(resolve, ms)) + + window.scrollTo(0, 0) + + let steps = 0 + + while (window.scrollY < targetScrollY && steps < maxSteps) { + window.scrollBy(0, stepPx) + steps += 1 + await sleep(stepDelayMs) + } + + if (window.scrollY < targetScrollY) { + throw new Error( + `Could not reach source scroll target ${targetScrollY}; got ${window.scrollY}`, + ) + } + }, + { + targetScrollY: sourceScrollTargetY, + stepPx: fastScrollStepPx, + stepDelayMs: fastScrollDelayMs, + maxSteps: maxFastScrollSteps, + }, + ) +} + +async function clickTargetLinkImmediatelyAfterScroll(page: Page) { + await page.evaluate( + ({ reverseScrollPx }) => { + const link = document.querySelector( + '[data-testid="issue-7040-target-link"]', + ) + + if (!(link instanceof HTMLAnchorElement)) { + throw new Error('issue-7040 target link not found') + } + + // Trigger one more browser scroll update immediately before navigation + // so the test stays focused on the stale-scroll race. + window.scrollBy(0, -reverseScrollPx) + link.dispatchEvent( + new MouseEvent('click', { + bubbles: true, + cancelable: true, + view: window, + }), + ) + }, + { reverseScrollPx: preClickReverseScrollPx }, + ) +} + +async function waitForTargetPageToSettle(page: Page) { + await page.waitForURL('**/issue-7040-target') + await expect(page.getByTestId('issue-7040-target-top')).toBeVisible() + await page.waitForFunction(() => window.scrollY === 0) +} + +test('Issue #7040 repro: fast scroll then click can restore target below top', async ({ + page, +}) => { + const attempts: Array = [] + + for (let attempt = 0; attempt < attemptCount; attempt++) { + await openFreshSourcePage(page) + await fastScrollSourcePage(page) + + const before = await page.evaluate(() => { + return { + sourceKey: window.history.state.__TSR_key, + sourceScrollY: window.scrollY, + sourceHeight: document.documentElement.scrollHeight, + } + }) + + await clickTargetLinkImmediatelyAfterScroll(page) + await waitForTargetPageToSettle(page) + + const after = await page.evaluate(() => { + return { + destinationKey: window.history.state.__TSR_key, + destinationScrollY: window.scrollY, + destinationHeight: document.documentElement.scrollHeight, + destinationMaxScrollY: + document.documentElement.scrollHeight - window.innerHeight, + } + }) + + attempts.push({ attempt, before, after }) + } + + for (const attempt of attempts) { + expect(attempt.before.sourceHeight).toBeGreaterThan(15000) + expect(attempt.before.sourceScrollY).toBeGreaterThan(sourceScrollTargetY) + expect(attempt.before.sourceKey).not.toBe(attempt.after.destinationKey) + expect(attempt.before.sourceScrollY).toBeGreaterThan( + attempt.after.destinationMaxScrollY, + ) + expect(attempt.after.destinationHeight).toBeLessThan( + attempt.before.sourceHeight, + ) + expect(attempt.after.destinationScrollY).toBe(0) + expect(attempt.after.destinationScrollY).toBeLessThanOrEqual( + attempt.after.destinationMaxScrollY, + ) + } +}) diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json b/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json index f33b5a7aa3..5d58406b2e 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json @@ -11,5 +11,5 @@ "allowJs": true, "types": ["vite/client", "node"] }, - "exclude": ["node_modules", "dist"] + "exclude": ["node_modules", "dist", "dist-hash"] } diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/vite.config.js b/e2e/react-router/scroll-restoration-sandbox-vite/vite.config.js index 172112dd72..39e3bb69c2 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/vite.config.js +++ b/e2e/react-router/scroll-restoration-sandbox-vite/vite.config.js @@ -1,8 +1,9 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [tanstackRouter({ target: 'react' }), react()], + plugins: [tailwindcss(), tanstackRouter({ target: 'react' }), react()], }) diff --git a/e2e/react-router/sentry-integration/.devcontainer/devcontainer.json b/e2e/react-router/sentry-integration/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/react-router/sentry-integration/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/react-router/sentry-integration/package.json b/e2e/react-router/sentry-integration/package.json index ece4d00567..5ebbdf31d9 100644 --- a/e2e/react-router/sentry-integration/package.json +++ b/e2e/react-router/sentry-integration/package.json @@ -8,27 +8,26 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@sentry/react": "^10.32.0", "@sentry/tracing": "^7.120.4", "@sentry/vite-plugin": "^4.6.1", - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", - "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17" + "redaxios": "catalog:", + "tailwindcss": "^4.2.2" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.14" } } diff --git a/e2e/react-router/sentry-integration/playwright.config.ts b/e2e/react-router/sentry-integration/playwright.config.ts index 0c5cee43e4..6a684ac89e 100644 --- a/e2e/react-router/sentry-integration/playwright.config.ts +++ b/e2e/react-router/sentry-integration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/sentry-integration/postcss.config.mjs b/e2e/react-router/sentry-integration/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/react-router/sentry-integration/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/react-router/sentry-integration/src/styles.css b/e2e/react-router/sentry-integration/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/e2e/react-router/sentry-integration/src/styles.css +++ b/e2e/react-router/sentry-integration/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/react-router/sentry-integration/src/vite-env.d.ts b/e2e/react-router/sentry-integration/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/react-router/sentry-integration/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/react-router/sentry-integration/vite.config.js b/e2e/react-router/sentry-integration/vite.config.js index 72e65e2d82..d123e60865 100644 --- a/e2e/react-router/sentry-integration/vite.config.js +++ b/e2e/react-router/sentry-integration/vite.config.js @@ -1,8 +1,9 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { sentryVitePlugin } from '@sentry/vite-plugin' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react(), sentryVitePlugin()], + plugins: [tailwindcss(), react(), sentryVitePlugin()], }) diff --git a/e2e/react-router/view-transitions/.devcontainer/devcontainer.json b/e2e/react-router/view-transitions/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/react-router/view-transitions/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/react-router/view-transitions/package.json b/e2e/react-router/view-transitions/package.json index bb81b3ecdf..e2d7a181e1 100644 --- a/e2e/react-router/view-transitions/package.json +++ b/e2e/react-router/view-transitions/package.json @@ -8,27 +8,27 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/router-plugin": "workspace:^", - "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "redaxios": "catalog:", + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/e2e/react-router/view-transitions/playwright.config.ts b/e2e/react-router/view-transitions/playwright.config.ts index c5de6b5611..4eead86444 100644 --- a/e2e/react-router/view-transitions/playwright.config.ts +++ b/e2e/react-router/view-transitions/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -22,13 +17,10 @@ export default defineConfig({ baseURL, }, - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/view-transitions/postcss.config.mjs b/e2e/react-router/view-transitions/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/react-router/view-transitions/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/react-router/view-transitions/src/routeTree.gen.ts b/e2e/react-router/view-transitions/src/routeTree.gen.ts index 20ee76a1a5..8982fca68f 100644 --- a/e2e/react-router/view-transitions/src/routeTree.gen.ts +++ b/e2e/react-router/view-transitions/src/routeTree.gen.ts @@ -9,16 +9,16 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as HowItWorksRouteImport } from './routes/how-it-works' -import { Route as ExploreRouteImport } from './routes/explore' -import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as IndexRouteImport } from './routes/index' +import { Route as ExploreRouteImport } from './routes/explore' +import { Route as HowItWorksRouteImport } from './routes/how-it-works' +import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const HowItWorksRoute = HowItWorksRouteImport.update({ - id: '/how-it-works', - path: '/how-it-works', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const ExploreRoute = ExploreRouteImport.update({ @@ -26,16 +26,16 @@ const ExploreRoute = ExploreRouteImport.update({ path: '/explore', getParentRoute: () => rootRouteImport, } as any) +const HowItWorksRoute = HowItWorksRouteImport.update({ + id: '/how-it-works', + path: '/how-it-works', + getParentRoute: () => rootRouteImport, +} as any) const PostsRouteRoute = PostsRouteRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -101,11 +101,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/how-it-works': { - id: '/how-it-works' - path: '/how-it-works' - fullPath: '/how-it-works' - preLoaderRoute: typeof HowItWorksRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/explore': { @@ -115,6 +115,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ExploreRouteImport parentRoute: typeof rootRouteImport } + '/how-it-works': { + id: '/how-it-works' + path: '/how-it-works' + fullPath: '/how-it-works' + preLoaderRoute: typeof HowItWorksRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -122,13 +129,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' diff --git a/e2e/react-router/view-transitions/src/styles.css b/e2e/react-router/view-transitions/src/styles.css index 818667133d..b51e6e1244 100644 --- a/e2e/react-router/view-transitions/src/styles.css +++ b/e2e/react-router/view-transitions/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/react-router/view-transitions/src/vite-env.d.ts b/e2e/react-router/view-transitions/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/react-router/view-transitions/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/react-router/view-transitions/tests/app.spec.ts b/e2e/react-router/view-transitions/tests/app.spec.ts index 472bd6ed0b..6c1ccf1a6e 100644 --- a/e2e/react-router/view-transitions/tests/app.spec.ts +++ b/e2e/react-router/view-transitions/tests/app.spec.ts @@ -1,4 +1,4 @@ -import { test } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/view-transitions/tests/setup/global.setup.ts b/e2e/react-router/view-transitions/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/view-transitions/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/view-transitions/tests/setup/global.teardown.ts b/e2e/react-router/view-transitions/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/view-transitions/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/view-transitions/vite.config.js b/e2e/react-router/view-transitions/vite.config.js index 47e327b746..e6a8f48b5f 100644 --- a/e2e/react-router/view-transitions/vite.config.js +++ b/e2e/react-router/view-transitions/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true, diff --git a/e2e/react-start/basic-auth/.devcontainer/devcontainer.json b/e2e/react-start/basic-auth/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/react-start/basic-auth/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/react-start/basic-auth/package.json b/e2e/react-start/basic-auth/package.json index e9d1d7c469..f7ff609e76 100644 --- a/e2e/react-start/basic-auth/package.json +++ b/e2e/react-start/basic-auth/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "start": "node .output/server/index.mjs", "prisma-generate": "prisma generate", - "test:e2e": "exit 0; rm -rf port*.txt; pnpm run prisma-generate && playwright test --project=chromium" + "test:e2e": "exit 0; pnpm run prisma-generate && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,25 +19,25 @@ "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/react-start": "workspace:^", + "iron-session": "^9.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "vite": "^7.1.7" + "redaxios": "catalog:", + "tailwind-merge": "^3.6.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@tailwindcss/postcss": "^4.1.15", + "@playwright/test": "^1.61.0", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", + "@vitejs/plugin-react": "^6.0.1", "dotenv": "^17.2.3", - "postcss": "^8.5.1", "prisma": "^7.0.0", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite-tsconfig-paths": "^5.1.4" + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/e2e/react-start/basic-auth/playwright.config.ts b/e2e/react-start/basic-auth/playwright.config.ts index 18b8905468..82678ac00b 100644 --- a/e2e/react-start/basic-auth/playwright.config.ts +++ b/e2e/react-start/basic-auth/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-auth/postcss.config.mjs b/e2e/react-start/basic-auth/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/react-start/basic-auth/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/react-start/basic-auth/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic-auth/src/components/DefaultCatchBoundary.tsx index ef2daa1ea1..405fb5f4a7 100644 --- a/e2e/react-start/basic-auth/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/basic-auth/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error(error) diff --git a/e2e/react-start/basic-auth/src/prisma-generated/client.ts b/e2e/react-start/basic-auth/src/prisma-generated/client.ts index 1b9d548165..2be7866ae3 100644 --- a/e2e/react-start/basic-auth/src/prisma-generated/client.ts +++ b/e2e/react-start/basic-auth/src/prisma-generated/client.ts @@ -37,10 +37,10 @@ export * from './enums' export const PrismaClient = $Class.getPrismaClientClass() export type PrismaClient< LogOpts extends Prisma.LogLevel = never, - OmitOpts extends - Prisma.PrismaClientOptions['omit'] = Prisma.PrismaClientOptions['omit'], - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + OmitOpts extends Prisma.PrismaClientOptions['omit'] = + Prisma.PrismaClientOptions['omit'], + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = $Class.PrismaClient export { Prisma } diff --git a/e2e/react-start/basic-auth/src/prisma-generated/internal/class.ts b/e2e/react-start/basic-auth/src/prisma-generated/internal/class.ts index 95cb7864ef..594896a020 100644 --- a/e2e/react-start/basic-auth/src/prisma-generated/internal/class.ts +++ b/e2e/react-start/basic-auth/src/prisma-generated/internal/class.ts @@ -44,9 +44,8 @@ config.compilerWasm = { await import('@prisma/client/runtime/query_compiler_bg.sqlite.mjs'), getQueryCompilerWasmModule: async () => { - const { wasm } = await import( - '@prisma/client/runtime/query_compiler_bg.sqlite.wasm-base64.mjs' - ) + const { wasm } = + await import('@prisma/client/runtime/query_compiler_bg.sqlite.wasm-base64.mjs') return await decodeBase64AsWasm(wasm) }, } @@ -81,8 +80,8 @@ export interface PrismaClientConstructor { } ? U : Prisma.PrismaClientOptions['omit'], - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, >( options: Prisma.Subset, ): PrismaClient @@ -105,8 +104,8 @@ export interface PrismaClientConstructor { export interface PrismaClient< in LogOpts extends Prisma.LogLevel = never, in out OmitOpts extends Prisma.PrismaClientOptions['omit'] = undefined, - in out ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + in out ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > { [K: symbol]: { types: Prisma.TypeMap['other'] } diff --git a/e2e/react-start/basic-auth/src/prisma-generated/internal/prismaNamespace.ts b/e2e/react-start/basic-auth/src/prisma-generated/internal/prismaNamespace.ts index fc96903a35..f420c55329 100644 --- a/e2e/react-start/basic-auth/src/prisma-generated/internal/prismaNamespace.ts +++ b/e2e/react-start/basic-auth/src/prisma-generated/internal/prismaNamespace.ts @@ -417,17 +417,17 @@ export const ModelName = { export type ModelName = (typeof ModelName)[keyof typeof ModelName] -export interface TypeMapCb - extends runtime.Types.Utils.Fn< - { extArgs: runtime.Types.Extensions.InternalArgs }, - runtime.Types.Utils.Record - > { +export interface TypeMapCb extends runtime.Types.Utils + .Fn< + { extArgs: runtime.Types.Extensions.InternalArgs }, + runtime.Types.Utils.Record +> { returns: TypeMap } export type TypeMap< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}, > = { globalOmitOptions: { diff --git a/e2e/react-start/basic-auth/src/prisma-generated/models/User.ts b/e2e/react-start/basic-auth/src/prisma-generated/models/User.ts index 14c9ca5fb9..4312db9bd9 100644 --- a/e2e/react-start/basic-auth/src/prisma-generated/models/User.ts +++ b/e2e/react-start/basic-auth/src/prisma-generated/models/User.ts @@ -57,8 +57,8 @@ export type UserCountAggregateInputType = { } export type UserAggregateArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Filter which User to aggregate. @@ -119,8 +119,8 @@ export type GetUserAggregateType = { } export type UserGroupByArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { where?: Prisma.UserWhereInput orderBy?: @@ -254,8 +254,8 @@ export type StringFieldUpdateOperationsInput = { } export type UserSelect< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetSelect< { email?: boolean @@ -265,8 +265,8 @@ export type UserSelect< > export type UserSelectCreateManyAndReturn< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetSelect< { email?: boolean @@ -276,8 +276,8 @@ export type UserSelectCreateManyAndReturn< > export type UserSelectUpdateManyAndReturn< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetSelect< { email?: boolean @@ -292,16 +292,16 @@ export type UserSelectScalar = { } export type UserOmit< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetOmit< 'email' | 'password', ExtArgs['result']['user'] > export type $UserPayload< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { name: 'User' objects: {} @@ -320,15 +320,15 @@ export type UserGetPayload< > = runtime.Types.Result.GetResult export type UserCountArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = Omit & { select?: UserCountAggregateInputType | true } export interface UserDelegate< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}, > { [K: symbol]: { @@ -854,8 +854,8 @@ export interface UserDelegate< export interface Prisma__UserClient< T, Null = never, - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}, > extends Prisma.PrismaPromise { readonly [Symbol.toStringTag]: 'PrismaPromise' @@ -910,8 +910,8 @@ export interface UserFieldRefs { * User findUnique */ export type UserFindUniqueArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -931,8 +931,8 @@ export type UserFindUniqueArgs< * User findUniqueOrThrow */ export type UserFindUniqueOrThrowArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -952,8 +952,8 @@ export type UserFindUniqueOrThrowArgs< * User findFirst */ export type UserFindFirstArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1005,8 +1005,8 @@ export type UserFindFirstArgs< * User findFirstOrThrow */ export type UserFindFirstOrThrowArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1058,8 +1058,8 @@ export type UserFindFirstOrThrowArgs< * User findMany */ export type UserFindManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1106,8 +1106,8 @@ export type UserFindManyArgs< * User create */ export type UserCreateArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1127,8 +1127,8 @@ export type UserCreateArgs< * User createMany */ export type UserCreateManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * The data used to create many Users. @@ -1140,8 +1140,8 @@ export type UserCreateManyArgs< * User createManyAndReturn */ export type UserCreateManyAndReturnArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1161,8 +1161,8 @@ export type UserCreateManyAndReturnArgs< * User update */ export type UserUpdateArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1186,8 +1186,8 @@ export type UserUpdateArgs< * User updateMany */ export type UserUpdateManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * The data used to update Users. @@ -1210,8 +1210,8 @@ export type UserUpdateManyArgs< * User updateManyAndReturn */ export type UserUpdateManyAndReturnArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1242,8 +1242,8 @@ export type UserUpdateManyAndReturnArgs< * User upsert */ export type UserUpsertArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1271,8 +1271,8 @@ export type UserUpsertArgs< * User delete */ export type UserDeleteArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1292,8 +1292,8 @@ export type UserDeleteArgs< * User deleteMany */ export type UserDeleteManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Filter which Users to delete @@ -1309,8 +1309,8 @@ export type UserDeleteManyArgs< * User without action */ export type UserDefaultArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User diff --git a/e2e/react-start/basic-auth/src/routeTree.gen.ts b/e2e/react-start/basic-auth/src/routeTree.gen.ts index 9e96fafa6a..998d34a709 100644 --- a/e2e/react-start/basic-auth/src/routeTree.gen.ts +++ b/e2e/react-start/basic-auth/src/routeTree.gen.ts @@ -9,23 +9,22 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as SignupRouteImport } from './routes/signup' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as SignupRouteImport } from './routes/signup' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -33,13 +32,14 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,18 +120,18 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } '/login': { @@ -141,18 +141,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthedRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/e2e/react-start/basic-auth/src/routes/__root.tsx b/e2e/react-start/basic-auth/src/routes/__root.tsx index 76e5f8b1d6..fb7868435d 100644 --- a/e2e/react-start/basic-auth/src/routes/__root.tsx +++ b/e2e/react-start/basic-auth/src/routes/__root.tsx @@ -14,18 +14,18 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { useAppSession } from '~/utils/session.js' +import { getAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await useAppSession() + const session = await getAppSession() - if (!session.data.userEmail) { + if (!session.userEmail) { return null } return { - email: session.data.userEmail, + email: session.userEmail, } }) diff --git a/e2e/react-start/basic-auth/src/routes/_authed.tsx b/e2e/react-start/basic-auth/src/routes/_authed.tsx index 221627851a..fe73185136 100644 --- a/e2e/react-start/basic-auth/src/routes/_authed.tsx +++ b/e2e/react-start/basic-auth/src/routes/_authed.tsx @@ -3,12 +3,12 @@ import { createServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', }) - .inputValidator((payload: { email: string; password: string }) => payload) + .validator((payload: { email: string; password: string }) => payload) .handler(async ({ data }) => { // Find the user const user = await prismaClient.user.findUnique({ @@ -37,12 +37,11 @@ export const loginFn = createServerFn({ } // Create a session - const session = await useAppSession() + const session = await getAppSession() // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + session.userEmail = user.email + await session.save() }) export const Route = createFileRoute('/_authed')({ @@ -52,7 +51,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return } diff --git a/e2e/react-start/basic-auth/src/routes/logout.tsx b/e2e/react-start/basic-auth/src/routes/logout.tsx index a08f9c737e..0f86b0d4e3 100644 --- a/e2e/react-start/basic-auth/src/routes/logout.tsx +++ b/e2e/react-start/basic-auth/src/routes/logout.tsx @@ -1,12 +1,12 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await useAppSession() + const session = await getAppSession() - session.clear() + session.destroy() throw redirect({ href: '/', diff --git a/e2e/react-start/basic-auth/src/routes/signup.tsx b/e2e/react-start/basic-auth/src/routes/signup.tsx index d6ef153786..d7d5d40129 100644 --- a/e2e/react-start/basic-auth/src/routes/signup.tsx +++ b/e2e/react-start/basic-auth/src/routes/signup.tsx @@ -4,12 +4,12 @@ import { createServerFn, useServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST', }) - .inputValidator( + .validator( (data: { email: string; password: string; redirectUrl?: string }) => data, ) .handler(async ({ data: payload }) => { @@ -24,7 +24,7 @@ export const signupFn = createServerFn({ const password = await hashPassword(payload.password) // Create a session - const session = await useAppSession() + const session = await getAppSession() if (found) { if (found.password !== password) { @@ -36,9 +36,8 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - await session.update({ - userEmail: found.email, - }) + session.userEmail = found.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -55,9 +54,8 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + session.userEmail = user.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/e2e/react-start/basic-auth/src/styles/app.css b/e2e/react-start/basic-auth/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/e2e/react-start/basic-auth/src/styles/app.css +++ b/e2e/react-start/basic-auth/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/react-start/basic-auth/src/utils/posts.ts b/e2e/react-start/basic-auth/src/utils/posts.ts index b30810a5a3..532e883ac0 100644 --- a/e2e/react-start/basic-auth/src/utils/posts.ts +++ b/e2e/react-start/basic-auth/src/utils/posts.ts @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) + .validator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/e2e/react-start/basic-auth/src/utils/session.ts b/e2e/react-start/basic-auth/src/utils/session.ts index c38bac1e48..f1deacf85b 100644 --- a/e2e/react-start/basic-auth/src/utils/session.ts +++ b/e2e/react-start/basic-auth/src/utils/session.ts @@ -1,13 +1,25 @@ -// src/services/session.server.ts -import { useSession } from '@tanstack/react-start/server' +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/react-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function useAppSession() { - return useSession({ - password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', - }) +export function getAppSession() { + return getIronSession( + { read: getCookie, write: setCookie }, + { + cookieName: 'test-auth-session', + // This fixture only runs locally with test credentials. + password: 'local-e2e-only-session-password-at-least-32-characters', + ttl: 60 * 60, + cookieOptions: { + httpOnly: true, + secure: false, + sameSite: 'lax', + path: '/', + }, + }, + ) } diff --git a/e2e/react-start/basic-auth/tsconfig.json b/e2e/react-start/basic-auth/tsconfig.json index 3a9fb7cd71..cef9369516 100644 --- a/e2e/react-start/basic-auth/tsconfig.json +++ b/e2e/react-start/basic-auth/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/basic-auth/vite.config.ts b/e2e/react-start/basic-auth/vite.config.ts index dc57f144e4..6c9a4c347a 100644 --- a/e2e/react-start/basic-auth/vite.config.ts +++ b/e2e/react-start/basic-auth/vite.config.ts @@ -1,14 +1,9 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], + resolve: { tsconfigPaths: true }, + plugins: [tailwindcss(), tanstackStart(), viteReact()], }) diff --git a/e2e/react-start/basic-cloudflare/.devcontainer/devcontainer.json b/e2e/react-start/basic-cloudflare/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/react-start/basic-cloudflare/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/react-start/basic-cloudflare/package.json b/e2e/react-start/basic-cloudflare/package.json index 246d99d559..b9b8031ac4 100644 --- a/e2e/react-start/basic-cloudflare/package.json +++ b/e2e/react-start/basic-cloudflare/package.json @@ -9,8 +9,8 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "cf-typegen": "wrangler types", - "postinstall": "npm run cf-typegen", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen", + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -20,19 +20,28 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@cloudflare/vite-plugin": "^1.15.1", - "@playwright/test": "^1.50.1", - "@tailwindcss/postcss": "^4.1.15", + "@cloudflare/vite-plugin": "^1.29.0", + "@playwright/test": "^1.61.0", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4", - "wrangler": "^4.49.1" + "@vitejs/plugin-react": "^6.0.1", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "wrangler": "^4.74.0" + }, + "nx": { + "targets": { + "test:e2e": { + "outputs": [ + "...", + "{projectRoot}/.wrangler/deploy" + ] + } + } } } diff --git a/e2e/react-start/basic-cloudflare/playwright.config.ts b/e2e/react-start/basic-cloudflare/playwright.config.ts index a545dff891..0925936d55 100644 --- a/e2e/react-start/basic-cloudflare/playwright.config.ts +++ b/e2e/react-start/basic-cloudflare/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -14,9 +13,6 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -24,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-cloudflare/postcss.config.mjs b/e2e/react-start/basic-cloudflare/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/react-start/basic-cloudflare/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/react-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx index ef2daa1ea1..405fb5f4a7 100644 --- a/e2e/react-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error(error) diff --git a/e2e/react-start/basic-cloudflare/src/routeTree.gen.ts b/e2e/react-start/basic-cloudflare/src/routeTree.gen.ts index 4219501f5e..b29f0d8d68 100644 --- a/e2e/react-start/basic-cloudflare/src/routeTree.gen.ts +++ b/e2e/react-start/basic-cloudflare/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as StaticRouteImport } from './routes/static' import { Route as IndexRouteImport } from './routes/index' +import { Route as StaticRouteImport } from './routes/static' -const StaticRoute = StaticRouteImport.update({ - id: '/static', - path: '/static', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const StaticRoute = StaticRouteImport.update({ + id: '/static', + path: '/static', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/static': { - id: '/static' - path: '/static' - fullPath: '/static' - preLoaderRoute: typeof StaticRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/static': { + id: '/static' + path: '/static' + fullPath: '/static' + preLoaderRoute: typeof StaticRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/react-start/basic-cloudflare/src/styles/app.css b/e2e/react-start/basic-cloudflare/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/e2e/react-start/basic-cloudflare/src/styles/app.css +++ b/e2e/react-start/basic-cloudflare/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/react-start/basic-cloudflare/tests/app.spec.ts b/e2e/react-start/basic-cloudflare/tests/app.spec.ts index add28cb73e..c9497070dd 100644 --- a/e2e/react-start/basic-cloudflare/tests/app.spec.ts +++ b/e2e/react-start/basic-cloudflare/tests/app.spec.ts @@ -1,3 +1,5 @@ +import { execFileSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' import { existsSync } from 'node:fs' import { join } from 'node:path' import { expect } from '@playwright/test' @@ -29,3 +31,19 @@ test('prerender with Cloudflare Workers runtime', async ({ page }) => { 'The value is Hello from Cloudflare', ) }) + +test('the built Cloudflare app passes a deployment dry run', () => { + const wrangler = fileURLToPath( + new URL('../node_modules/wrangler/bin/wrangler.js', import.meta.url), + ) + const output = execFileSync( + process.execPath, + [wrangler, 'deploy', '--dry-run'], + { + encoding: 'utf8', + env: { ...process.env, WRANGLER_SEND_METRICS: 'false' }, + }, + ) + expect(output).toContain('dist/server/wrangler.json') + expect(output).toContain('--dry-run: exiting now.') +}) diff --git a/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts b/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts b/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-start/basic-cloudflare/tsconfig.json b/e2e/react-start/basic-cloudflare/tsconfig.json index 3a9fb7cd71..cef9369516 100644 --- a/e2e/react-start/basic-cloudflare/tsconfig.json +++ b/e2e/react-start/basic-cloudflare/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/basic-cloudflare/vite.config.ts b/e2e/react-start/basic-cloudflare/vite.config.ts index e6074f714b..d19ab50ea5 100644 --- a/e2e/react-start/basic-cloudflare/vite.config.ts +++ b/e2e/react-start/basic-cloudflare/vite.config.ts @@ -1,14 +1,13 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { cloudflare } from '@cloudflare/vite-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + resolve: { tsconfigPaths: true }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), + tailwindcss(), cloudflare({ viteEnvironment: { name: 'ssr' }, inspectorPort: false }), tanstackStart({ prerender: { diff --git a/e2e/react-start/basic-cloudflare/worker-configuration.d.ts b/e2e/react-start/basic-cloudflare/worker-configuration.d.ts index bdfccc2017..f7a8f16397 100644 --- a/e2e/react-start/basic-cloudflare/worker-configuration.d.ts +++ b/e2e/react-start/basic-cloudflare/worker-configuration.d.ts @@ -1,6 +1,6 @@ /* eslint-disable */ // Generated by Wrangler by running `wrangler types` (hash: b11df627d8b3c51b1bf3230a546b0f20) -// Runtime types generated with workerd@1.20251118.0 2025-09-24 nodejs_compat +// Runtime types generated with workerd@1.20260317.1 2025-09-24 nodejs_compat declare namespace Cloudflare { interface Env { MY_VAR: "Hello from Cloudflare"; @@ -436,22 +436,22 @@ interface ExecutionContext { passThroughOnException(): void; readonly props: Props; } -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; -type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; +type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; +type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; +type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; +interface ExportedHandler { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; } interface StructuredSerializeOptions { transfer?: any[]; @@ -499,8 +499,10 @@ interface DurableObjectNamespaceNewUniqueIdOptions { jurisdiction?: DurableObjectJurisdiction; } type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; +type DurableObjectRoutingMode = "primary-only"; interface DurableObjectNamespaceGetDurableObjectOptions { locationHint?: DurableObjectLocationHint; + routingMode?: DurableObjectRoutingMode; } interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { } @@ -1387,6 +1389,12 @@ declare abstract class PromiseRejectionEvent extends Event { */ declare class FormData { constructor(); + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string | Blob): void; /** * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. * @@ -1423,6 +1431,12 @@ declare class FormData { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) */ has(name: string): boolean; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string | Blob): void; /** * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. * @@ -1749,7 +1763,7 @@ interface Request> e * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) */ signal: AbortSignal; - cf: Cf | undefined; + cf?: Cf; /** * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. * @@ -2084,6 +2098,8 @@ interface Transformer { expectedLength?: number; } interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; /** * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. * @@ -2102,8 +2118,6 @@ interface StreamPipeOptions { * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. */ preventClose?: boolean; - preventAbort?: boolean; - preventCancel?: boolean; signal?: AbortSignal; } type ReadableStreamReadResult = { @@ -2378,13 +2392,13 @@ declare abstract class TransformStreamDefaultController { terminate(): void; } interface ReadableWritablePair { + readable: ReadableStream; /** * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ writable: WritableStream; - readable: ReadableStream; } /** * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. @@ -3032,7 +3046,7 @@ declare var WebSocket: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ interface WebSocket extends EventTarget { - accept(): void; + accept(options?: WebSocketAcceptOptions): void; /** * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. * @@ -3071,6 +3085,22 @@ interface WebSocket extends EventTarget { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) */ extensions: string | null; + /** + * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) + */ + binaryType: "blob" | "arraybuffer"; +} +interface WebSocketAcceptOptions { + /** + * When set to `true`, receiving a server-initiated WebSocket Close frame will not + * automatically send a reciprocal Close frame, leaving the connection in a half-open + * state. This is useful for proxying scenarios where you need to coordinate closing + * both sides independently. Defaults to `false` when the + * `no_web_socket_half_open_by_default` compatibility flag is enabled. + */ + allowHalfOpen?: boolean; } declare const WebSocketPair: { new (): { @@ -3189,6 +3219,8 @@ interface Container { signal(signo: number): void; getTcpPort(port: number): Fetcher; setInactivityTimeout(durationMs: number | bigint): Promise; + interceptOutboundHttp(addr: string, binding: Fetcher): Promise; + interceptAllOutboundHttp(binding: Fetcher): Promise; } interface ContainerStartupOptions { entrypoint?: string[]; @@ -3281,7 +3313,8 @@ interface WorkerStubEntrypointOptions { props?: any; } interface WorkerLoader { - get(name: string, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; + get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; + load(code: WorkerLoaderWorkerCode): WorkerStub; } interface WorkerLoaderModule { js?: string; @@ -3314,6 +3347,181 @@ declare abstract class Performance { get timeOrigin(): number; /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ now(): number; + /** + * The **`toJSON()`** method of the Performance interface is a Serialization; it returns a JSON representation of the Performance object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON) + */ + toJSON(): object; +} +// AI Search V2 API Error Interfaces +interface AiSearchInternalError extends Error { +} +interface AiSearchNotFoundError extends Error { +} +interface AiSearchNameNotSetError extends Error { +} +// AI Search V2 Request Types +type AiSearchSearchRequest = { + messages: Array<{ + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + }>; + ai_search_options?: { + retrieval?: { + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + /** Maximum number of results (1-50, default 10) */ + max_num_results?: number; + filters?: VectorizeVectorMetadataFilter; + /** Context expansion (0-3, default 0) */ + context_expansion?: number; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + /** Enable reranking (default false) */ + enabled?: boolean; + model?: '@cf/baai/bge-reranker-base' | ''; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + [key: string]: unknown; + }; + [key: string]: unknown; + }; +}; +type AiSearchChatCompletionsRequest = { + messages: Array<{ + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + }>; + model?: string; + stream?: boolean; + ai_search_options?: { + retrieval?: { + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + match_threshold?: number; + max_num_results?: number; + filters?: VectorizeVectorMetadataFilter; + context_expansion?: number; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + enabled?: boolean; + model?: '@cf/baai/bge-reranker-base' | ''; + match_threshold?: number; + [key: string]: unknown; + }; + [key: string]: unknown; + }; + [key: string]: unknown; +}; +// AI Search V2 Response Types +type AiSearchSearchResponse = { + search_query: string; + chunks: Array<{ + id: string; + type: string; + /** Match score (0-1) */ + score: number; + text: string; + item: { + timestamp?: number; + key: string; + metadata?: Record; + }; + scoring_details?: { + /** Keyword match score (0-1) */ + keyword_score?: number; + /** Vector similarity score (0-1) */ + vector_score?: number; + }; + }>; +}; +type AiSearchListResponse = Array<{ + id: string; + internal_id?: string; + account_id?: string; + account_tag?: string; + /** Whether the instance is enabled (default true) */ + enable?: boolean; + type?: 'r2' | 'web-crawler'; + source?: string; + [key: string]: unknown; +}>; +type AiSearchConfig = { + /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ + id: string; + type: 'r2' | 'web-crawler'; + source: string; + source_params?: object; + /** Token ID (UUID format) */ + token_id?: string; + ai_gateway_id?: string; + /** Enable query rewriting (default false) */ + rewrite_query?: boolean; + /** Enable reranking (default false) */ + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; +}; +type AiSearchInstance = { + id: string; + enable?: boolean; + type?: 'r2' | 'web-crawler'; + source?: string; + [key: string]: unknown; +}; +// AI Search Instance Service - Instance-level operations +declare abstract class AiSearchInstanceService { + /** + * Search the AI Search instance for relevant chunks. + * @param params Search request with messages and AI search options + * @returns Search response with matching chunks + */ + search(params: AiSearchSearchRequest): Promise; + /** + * Generate chat completions with AI Search context. + * @param params Chat completions request with optional streaming + * @returns Response object (if streaming) or chat completion result + */ + chatCompletions(params: AiSearchChatCompletionsRequest): Promise; + /** + * Delete this AI Search instance. + */ + delete(): Promise; +} +// AI Search Account Service - Account-level operations +declare abstract class AiSearchAccountService { + /** + * List all AI Search instances in the account. + * @returns Array of AI Search instances + */ + list(): Promise; + /** + * Get an AI Search instance by ID. + * @param name Instance ID + * @returns Instance service for performing operations + */ + get(name: string): AiSearchInstanceService; + /** + * Create a new AI Search instance. + * @param config Instance configuration + * @returns Instance service for performing operations + */ + create(config: AiSearchConfig): Promise; } type AiImageClassificationInput = { image: number[]; @@ -3578,6 +3786,363 @@ declare abstract class BaseAiTranslation { inputs: AiTranslationInput; postProcessedOutputs: AiTranslationOutput; } +/** + * Workers AI support for OpenAI's Responses API + * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts + * + * It's a stripped down version from its source. + * It currently supports basic function calling, json mode and accepts images as input. + * + * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. + * We plan to add those incrementally as model + platform capabilities evolve. + */ +type ResponsesInput = { + background?: boolean | null; + conversation?: string | ResponseConversationParam | null; + include?: Array | null; + input?: string | ResponseInput; + instructions?: string | null; + max_output_tokens?: number | null; + parallel_tool_calls?: boolean | null; + previous_response_id?: string | null; + prompt_cache_key?: string; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + stream?: boolean | null; + stream_options?: StreamOptions | null; + temperature?: number | null; + text?: ResponseTextConfig; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + truncation?: "auto" | "disabled" | null; +}; +type ResponsesOutput = { + id?: string; + created_at?: number; + output_text?: string; + error?: ResponseError | null; + incomplete_details?: ResponseIncompleteDetails | null; + instructions?: string | Array | null; + object?: "response"; + output?: Array; + parallel_tool_calls?: boolean; + temperature?: number | null; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + max_output_tokens?: number | null; + previous_response_id?: string | null; + prompt?: ResponsePrompt | null; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + status?: ResponseStatus; + text?: ResponseTextConfig; + truncation?: "auto" | "disabled" | null; + usage?: ResponseUsage; +}; +type EasyInputMessage = { + content: string | ResponseInputMessageContentList; + role: "user" | "assistant" | "system" | "developer"; + type?: "message"; +}; +type ResponsesFunctionTool = { + name: string; + parameters: { + [key: string]: unknown; + } | null; + strict: boolean | null; + type: "function"; + description?: string | null; +}; +type ResponseIncompleteDetails = { + reason?: "max_output_tokens" | "content_filter"; +}; +type ResponsePrompt = { + id: string; + variables?: { + [key: string]: string | ResponseInputText | ResponseInputImage; + } | null; + version?: string | null; +}; +type Reasoning = { + effort?: ReasoningEffort | null; + generate_summary?: "auto" | "concise" | "detailed" | null; + summary?: "auto" | "concise" | "detailed" | null; +}; +type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText; +type ResponseContentReasoningText = { + text: string; + type: "reasoning_text"; +}; +type ResponseConversationParam = { + id: string; +}; +type ResponseCreatedEvent = { + response: Response; + sequence_number: number; + type: "response.created"; +}; +type ResponseCustomToolCallOutput = { + call_id: string; + output: string | Array; + type: "custom_tool_call_output"; + id?: string; +}; +type ResponseError = { + code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found"; + message: string; +}; +type ResponseErrorEvent = { + code: string | null; + message: string; + param: string | null; + sequence_number: number; + type: "error"; +}; +type ResponseFailedEvent = { + response: Response; + sequence_number: number; + type: "response.failed"; +}; +type ResponseFormatText = { + type: "text"; +}; +type ResponseFormatJSONObject = { + type: "json_object"; +}; +type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; +type ResponseFormatTextJSONSchemaConfig = { + name: string; + schema: { + [key: string]: unknown; + }; + type: "json_schema"; + description?: string; + strict?: boolean | null; +}; +type ResponseFunctionCallArgumentsDeltaEvent = { + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.delta"; +}; +type ResponseFunctionCallArgumentsDoneEvent = { + arguments: string; + item_id: string; + name: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.done"; +}; +type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; +type ResponseFunctionCallOutputItemList = Array; +type ResponseFunctionToolCall = { + arguments: string; + call_id: string; + name: string; + type: "function_call"; + id?: string; + status?: "in_progress" | "completed" | "incomplete"; +}; +interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { + id: string; +} +type ResponseFunctionToolCallOutputItem = { + id: string; + call_id: string; + output: string | Array; + type: "function_call_output"; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs"; +type ResponseIncompleteEvent = { + response: Response; + sequence_number: number; + type: "response.incomplete"; +}; +type ResponseInput = Array; +type ResponseInputContent = ResponseInputText | ResponseInputImage; +type ResponseInputImage = { + detail: "low" | "high" | "auto"; + type: "input_image"; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputImageContent = { + type: "input_image"; + detail?: "low" | "high" | "auto" | null; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem; +type ResponseInputItemFunctionCallOutput = { + call_id: string; + output: string | ResponseFunctionCallOutputItemList; + type: "function_call_output"; + id?: string | null; + status?: "in_progress" | "completed" | "incomplete" | null; +}; +type ResponseInputItemMessage = { + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputMessageContentList = Array; +type ResponseInputMessageItem = { + id: string; + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputText = { + text: string; + type: "input_text"; +}; +type ResponseInputTextContent = { + text: string; + type: "input_text"; +}; +type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; +type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; +type ResponseOutputItemAddedEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.added"; +}; +type ResponseOutputItemDoneEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.done"; +}; +type ResponseOutputMessage = { + id: string; + content: Array; + role: "assistant"; + status: "in_progress" | "completed" | "incomplete"; + type: "message"; +}; +type ResponseOutputRefusal = { + refusal: string; + type: "refusal"; +}; +type ResponseOutputText = { + text: string; + type: "output_text"; + logprobs?: Array; +}; +type ResponseReasoningItem = { + id: string; + summary: Array; + type: "reasoning"; + content?: Array; + encrypted_content?: string | null; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseReasoningSummaryItem = { + text: string; + type: "summary_text"; +}; +type ResponseReasoningContentItem = { + text: string; + type: "reasoning_text"; +}; +type ResponseReasoningTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.reasoning_text.delta"; +}; +type ResponseReasoningTextDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + sequence_number: number; + text: string; + type: "response.reasoning_text.done"; +}; +type ResponseRefusalDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.refusal.delta"; +}; +type ResponseRefusalDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + refusal: string; + sequence_number: number; + type: "response.refusal.done"; +}; +type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete"; +type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent; +type ResponseCompletedEvent = { + response: Response; + sequence_number: number; + type: "response.completed"; +}; +type ResponseTextConfig = { + format?: ResponseFormatTextConfig; + verbosity?: "low" | "medium" | "high" | null; +}; +type ResponseTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + type: "response.output_text.delta"; +}; +type ResponseTextDoneEvent = { + content_index: number; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + text: string; + type: "response.output_text.done"; +}; +type Logprob = { + token: string; + logprob: number; + top_logprobs?: Array; +}; +type TopLogprob = { + token?: string; + logprob?: number; +}; +type ResponseUsage = { + input_tokens: number; + output_tokens: number; + total_tokens: number; +}; +type Tool = ResponsesFunctionTool; +type ToolChoiceFunction = { + name: string; + type: "function"; +}; +type ToolChoiceOptions = "none"; +type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; +type StreamOptions = { + include_obfuscation?: boolean; +}; type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { text: string | string[]; /** @@ -3606,8 +4171,8 @@ type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = { * The pooling method used in the embedding process. */ pooling?: "mean" | "cls"; -} | AsyncResponse; -interface AsyncResponse { +} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { /** * The async request id that can be used to obtain the results. */ @@ -3683,7 +4248,13 @@ type Ai_Cf_Meta_M2M100_1_2B_Output = { * The translated text in the target language */ translated_text?: string; -} | AsyncResponse; +} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; +interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { inputs: Ai_Cf_Meta_M2M100_1_2B_Input; postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; @@ -3716,7 +4287,13 @@ type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = { * The pooling method used in the embedding process. */ pooling?: "mean" | "cls"; -} | AsyncResponse; +} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; @@ -3749,7 +4326,13 @@ type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = { * The pooling method used in the embedding process. */ pooling?: "mean" | "cls"; -} | AsyncResponse; +} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; @@ -3935,13 +4518,13 @@ declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; } -type Ai_Cf_Baai_Bge_M3_Input = BGEM3InputQueryAndContexts | BGEM3InputEmbedding | { +type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | { /** * Batch of the embeddings requests to run using async-queue */ - requests: (BGEM3InputQueryAndContexts1 | BGEM3InputEmbedding1)[]; + requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[]; }; -interface BGEM3InputQueryAndContexts { +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { /** * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts */ @@ -3960,14 +4543,14 @@ interface BGEM3InputQueryAndContexts { */ truncate_inputs?: boolean; } -interface BGEM3InputEmbedding { +interface Ai_Cf_Baai_Bge_M3_Input_Embedding { text: string | string[]; /** * When provided with too long context should the model error out or truncate the context to fit? */ truncate_inputs?: boolean; } -interface BGEM3InputQueryAndContexts1 { +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { /** * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts */ @@ -3986,15 +4569,15 @@ interface BGEM3InputQueryAndContexts1 { */ truncate_inputs?: boolean; } -interface BGEM3InputEmbedding1 { +interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { text: string | string[]; /** * When provided with too long context should the model error out or truncate the context to fit? */ truncate_inputs?: boolean; } -type Ai_Cf_Baai_Bge_M3_Output = BGEM3OuputQuery | BGEM3OutputEmbeddingForContexts | BGEM3OuputEmbedding | AsyncResponse; -interface BGEM3OuputQuery { +type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Ouput_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Ouput_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse; +interface Ai_Cf_Baai_Bge_M3_Ouput_Query { response?: { /** * Index of the context in the request @@ -4006,7 +4589,7 @@ interface BGEM3OuputQuery { score?: number; }[]; } -interface BGEM3OutputEmbeddingForContexts { +interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { response?: number[][]; shape?: number[]; /** @@ -4014,7 +4597,7 @@ interface BGEM3OutputEmbeddingForContexts { */ pooling?: "mean" | "cls"; } -interface BGEM3OuputEmbedding { +interface Ai_Cf_Baai_Bge_M3_Ouput_Embedding { shape?: number[]; /** * Embeddings of the requested text values @@ -4025,6 +4608,12 @@ interface BGEM3OuputEmbedding { */ pooling?: "mean" | "cls"; } +interface Ai_Cf_Baai_Bge_M3_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Baai_Bge_M3 { inputs: Ai_Cf_Baai_Bge_M3_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; @@ -4049,8 +4638,8 @@ declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; } -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Prompt | Messages; -interface Prompt { +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4101,7 +4690,7 @@ interface Prompt { */ lora?: string; } -interface Messages { +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -4292,8 +4881,8 @@ declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; } -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | AsyncBatch; -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4302,7 +4891,7 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4344,11 +4933,11 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { */ presence_penalty?: number; } -interface JSONMode { +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { type?: "json_object" | "json_schema"; json_schema?: unknown; } -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { /** * An array of message objects representing the conversation history. */ @@ -4453,7 +5042,7 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { }; }; })[]; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4495,7 +5084,11 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { */ presence_penalty?: number; } -interface AsyncBatch { +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { requests?: { /** * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. @@ -4537,9 +5130,13 @@ interface AsyncBatch { * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; }[]; } +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { /** * The generated text response from the model @@ -4575,7 +5172,13 @@ type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { */ name?: string; }[]; -} | string | AsyncResponse; +} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; @@ -4679,8 +5282,8 @@ declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; } -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Qwen2_5_Coder_32B_Instruct_Prompt | Qwen2_5_Coder_32B_Instruct_Messages; -interface Qwen2_5_Coder_32B_Instruct_Prompt { +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4689,7 +5292,7 @@ interface Qwen2_5_Coder_32B_Instruct_Prompt { * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string; - response_format?: JSONMode; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4731,7 +5334,11 @@ interface Qwen2_5_Coder_32B_Instruct_Prompt { */ presence_penalty?: number; } -interface Qwen2_5_Coder_32B_Instruct_Messages { +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -4836,7 +5443,7 @@ interface Qwen2_5_Coder_32B_Instruct_Messages { }; }; })[]; - response_format?: JSONMode; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4878,6 +5485,10 @@ interface Qwen2_5_Coder_32B_Instruct_Messages { */ presence_penalty?: number; } +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { /** * The generated text response from the model @@ -4918,8 +5529,8 @@ declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; } -type Ai_Cf_Qwen_Qwq_32B_Input = Qwen_Qwq_32B_Prompt | Qwen_Qwq_32B_Messages; -interface Qwen_Qwq_32B_Prompt { +type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; +interface Ai_Cf_Qwen_Qwq_32B_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4969,7 +5580,7 @@ interface Qwen_Qwq_32B_Prompt { */ presence_penalty?: number; } -interface Qwen_Qwq_32B_Messages { +interface Ai_Cf_Qwen_Qwq_32B_Messages { /** * An array of message objects representing the conversation history. */ @@ -5100,7 +5711,7 @@ interface Qwen_Qwq_32B_Messages { }; })[]; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5184,8 +5795,8 @@ declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { inputs: Ai_Cf_Qwen_Qwq_32B_Input; postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; } -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Mistral_Small_3_1_24B_Instruct_Prompt | Mistral_Small_3_1_24B_Instruct_Messages; -interface Mistral_Small_3_1_24B_Instruct_Prompt { +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -5235,7 +5846,7 @@ interface Mistral_Small_3_1_24B_Instruct_Prompt { */ presence_penalty?: number; } -interface Mistral_Small_3_1_24B_Instruct_Messages { +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -5366,7 +5977,7 @@ interface Mistral_Small_3_1_24B_Instruct_Messages { }; })[]; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5450,14 +6061,14 @@ declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; } -type Ai_Cf_Google_Gemma_3_12B_It_Input = Google_Gemma_3_12B_It_Prompt | Google_Gemma_3_12B_It_Messages; -interface Google_Gemma_3_12B_It_Prompt { +type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages; +interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5501,7 +6112,7 @@ interface Google_Gemma_3_12B_It_Prompt { */ presence_penalty?: number; } -interface Google_Gemma_3_12B_It_Messages { +interface Ai_Cf_Google_Gemma_3_12B_It_Messages { /** * An array of message objects representing the conversation history. */ @@ -5522,19 +6133,7 @@ interface Google_Gemma_3_12B_It_Messages { */ url?: string; }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; + }[]; }[]; functions?: { name: string; @@ -5628,7 +6227,7 @@ interface Google_Gemma_3_12B_It_Messages { }; })[]; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5712,8 +6311,8 @@ declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; } -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Prompt | Ai_Cf_Meta_Llama_4_Messages | Ai_Cf_Meta_Llama_4_Async_Batch; -interface Ai_Cf_Meta_Llama_4_Prompt { +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -5722,7 +6321,7 @@ interface Ai_Cf_Meta_Llama_4_Prompt { * JSON schema that should be fulfilled for the response. */ guided_json?: object; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -5764,7 +6363,11 @@ interface Ai_Cf_Meta_Llama_4_Prompt { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Messages { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -5894,9 +6497,9 @@ interface Ai_Cf_Meta_Llama_4_Messages { }; }; })[]; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5940,10 +6543,10 @@ interface Ai_Cf_Meta_Llama_4_Messages { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Async_Batch { - requests: (Ai_Cf_Meta_Llama_4_Prompt_Inner | Ai_Cf_Meta_Llama_4_Messages_Inner)[]; +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { + requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[]; } -interface Ai_Cf_Meta_Llama_4_Prompt_Inner { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { /** * The input text prompt for the model to generate a response. */ @@ -5952,7 +6555,7 @@ interface Ai_Cf_Meta_Llama_4_Prompt_Inner { * JSON schema that should be fulfilled for the response. */ guided_json?: object; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -5994,7 +6597,7 @@ interface Ai_Cf_Meta_Llama_4_Prompt_Inner { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Messages_Inner { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { /** * An array of message objects representing the conversation history. */ @@ -6124,9 +6727,9 @@ interface Ai_Cf_Meta_Llama_4_Messages_Inner { }; }; })[]; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -6223,6 +6826,597 @@ declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; } +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { + requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { + inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; +} interface Ai_Cf_Deepgram_Nova_3_Input { audio: { body: object; @@ -6406,6 +7600,23 @@ declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { inputs: Ai_Cf_Deepgram_Nova_3_Input; postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; } +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { + queries?: string | string[]; + /** + * Optional instruction for the task + */ + instruction?: string; + documents?: string | string[]; + text?: string | string[]; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { + data?: number[][]; + shape?: number[]; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { + inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; +} type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = { /** * readable stream with audio data and content-type specified for that data @@ -6442,85 +7653,13 @@ declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; } -type Ai_Cf_Openai_Gpt_Oss_120B_Input = GPT_OSS_120B_Responses | GPT_OSS_120B_Responses_Async; -interface GPT_OSS_120B_Responses { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; -} -interface GPT_OSS_120B_Responses_Async { - requests: { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; - }[]; -} -type Ai_Cf_Openai_Gpt_Oss_120B_Output = {} | (string & NonNullable); declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { - inputs: Ai_Cf_Openai_Gpt_Oss_120B_Input; - postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_120B_Output; + inputs: ResponsesInput; + postProcessedOutputs: ResponsesOutput; } -type Ai_Cf_Openai_Gpt_Oss_20B_Input = GPT_OSS_20B_Responses | GPT_OSS_20B_Responses_Async; -interface GPT_OSS_20B_Responses { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; -} -interface GPT_OSS_20B_Responses_Async { - requests: { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; - }[]; -} -type Ai_Cf_Openai_Gpt_Oss_20B_Output = {} | (string & NonNullable); declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { - inputs: Ai_Cf_Openai_Gpt_Oss_20B_Input; - postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_20B_Output; + inputs: ResponsesInput; + postProcessedOutputs: ResponsesOutput; } interface Ai_Cf_Leonardo_Phoenix_1_0_Input { /** @@ -6634,6 +7773,799 @@ declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { inputs: Ai_Cf_Deepgram_Aura_1_Input; postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; } +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { + /** + * Input text to translate. Can be a single string or a list of strings. + */ + text: string | string[]; + /** + * Target language to translate to + */ + target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva"; +} +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { + /** + * Translated texts + */ + translations: string[]; +} +declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { + inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; + postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { + requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[]; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { + inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; + postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { + /** + * Input text to embed. Can be a single string or a list of strings. + */ + text: string | string[]; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { + /** + * Embedding vectors, where each vector is a list of floats. + */ + data: number[][]; + /** + * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. + * + * @minItems 2 + * @maxItems 2 + */ + shape: [ + number, + number + ]; +} +declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { + inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; + postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; +} +interface Ai_Cf_Deepgram_Flux_Input { + /** + * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. + */ + encoding: "linear16"; + /** + * Sample rate of the audio stream in Hz. + */ + sample_rate: string; + /** + * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. + */ + eager_eot_threshold?: string; + /** + * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. + */ + eot_threshold?: string; + /** + * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. + */ + eot_timeout_ms?: string; + /** + * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. + */ + keyterm?: string; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip + */ + mip_opt_out?: "true" | "false"; + /** + * Label your requests for the purpose of identification during usage reporting + */ + tag?: string; +} +/** + * Output will be returned as websocket messages. + */ +interface Ai_Cf_Deepgram_Flux_Output { + /** + * The unique identifier of the request (uuid) + */ + request_id?: string; + /** + * Starts at 0 and increments for each message the server sends to the client. + */ + sequence_id?: number; + /** + * The type of event being reported. + */ + event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn"; + /** + * The index of the current turn + */ + turn_index?: number; + /** + * Start time in seconds of the audio range that was transcribed + */ + audio_window_start?: number; + /** + * End time in seconds of the audio range that was transcribed + */ + audio_window_end?: number; + /** + * Text that was said over the course of the current turn + */ + transcript?: string; + /** + * The words in the transcript + */ + words?: { + /** + * The individual punctuated, properly-cased word from the transcript + */ + word: string; + /** + * Confidence that this word was transcribed correctly + */ + confidence: number; + }[]; + /** + * Confidence that no more speech is coming in this turn + */ + end_of_turn_confidence?: number; +} +declare abstract class Base_Ai_Cf_Deepgram_Flux { + inputs: Ai_Cf_Deepgram_Flux_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; +} +interface Ai_Cf_Deepgram_Aura_2_En_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_En_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { + inputs: Ai_Cf_Deepgram_Aura_2_En_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; +} +interface Ai_Cf_Deepgram_Aura_2_Es_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_Es_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { + inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; +} interface AiModels { "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; @@ -6677,12 +8609,12 @@ interface AiModels { "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; - "@hf/meta-llama/meta-llama-3-8b-instruct": BaseAiTextGeneration; "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; + "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration; "@cf/facebook/bart-large-cnn": BaseAiSummarization; "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; @@ -6704,13 +8636,21 @@ interface AiModels { "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; + "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; + "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; + "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; + "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; + "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; + "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux; + "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En; + "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es; } type AiOptions = { /** @@ -6722,6 +8662,16 @@ type AiOptions = { * Establish websocket connections, only works for supported models */ websocket?: boolean; + /** + * Tag your requests to group and view them in Cloudflare dashboard. + * + * Rules: + * Tags must only contain letters, numbers, and the symbols: : - . / @ + * Each tag can have maximum 50 characters. + * Maximum 5 tags are allowed each request. + * Duplicate tags will removed. + */ + tags?: string[]; gateway?: GatewayOptions; returnRawResponse?: boolean; prefix?: string; @@ -6760,6 +8710,48 @@ type AiModelListType = Record; declare abstract class Ai { aiGatewayLogId: string | null; gateway(gatewayId: string): AiGateway; + /** + * Access the AI Search API for managing AI-powered search instances. + * + * This is the new API that replaces AutoRAG with better namespace separation: + * - Account-level operations: `list()`, `create()` + * - Instance-level operations: `get(id).search()`, `get(id).chatCompletions()`, `get(id).delete()` + * + * @example + * ```typescript + * // List all AI Search instances + * const instances = await env.AI.aiSearch.list(); + * + * // Search an instance + * const results = await env.AI.aiSearch.get('my-search').search({ + * messages: [{ role: 'user', content: 'What is the policy?' }], + * ai_search_options: { + * retrieval: { max_num_results: 10 } + * } + * }); + * + * // Generate chat completions with AI Search context + * const response = await env.AI.aiSearch.get('my-search').chatCompletions({ + * messages: [{ role: 'user', content: 'What is the policy?' }], + * model: '@cf/meta/llama-3.3-70b-instruct-fp8-fast' + * }); + * ``` + */ + aiSearch(): AiSearchAccountService; + /** + * @deprecated AutoRAG has been replaced by AI Search. + * Use `env.AI.aiSearch` instead for better API design and new features. + * + * Migration guide: + * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` + * - `env.AI.autorag('id').search({ query: '...' })` → `env.AI.aiSearch.get('id').search({ messages: [{ role: 'user', content: '...' }] })` + * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` + * + * Note: The old API continues to work for backwards compatibility, but new projects should use AI Search. + * + * @see AiSearchAccountService + * @param autoragId Optional instance ID (omit for account-level operations) + */ autorag(autoragId: string): AutoRAG; run(model: Name, inputs: InputOptions, options?: Options): Promise; getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line } +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchInternalError instead. + * @see AiSearchInternalError + */ interface AutoRAGInternalError extends Error { } +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNotFoundError instead. + * @see AiSearchNotFoundError + */ interface AutoRAGNotFoundError extends Error { } +/** + * @deprecated This error type is no longer used in the AI Search API. + */ interface AutoRAGUnauthorizedError extends Error { } +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNameNotSetError instead. + * @see AiSearchNameNotSetError + */ interface AutoRAGNameNotSetError extends Error { } type ComparisonFilter = { @@ -6885,6 +8892,11 @@ type CompoundFilter = { type: 'and' | 'or'; filters: ComparisonFilter[]; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchSearchRequest with the new API instead. + * @see AiSearchSearchRequest + */ type AutoRagSearchRequest = { query: string; filters?: CompoundFilter | ComparisonFilter; @@ -6899,13 +8911,28 @@ type AutoRagSearchRequest = { }; rewrite_query?: boolean; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchChatCompletionsRequest with the new API instead. + * @see AiSearchChatCompletionsRequest + */ type AutoRagAiSearchRequest = AutoRagSearchRequest & { stream?: boolean; system_prompt?: string; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchChatCompletionsRequest with stream: true instead. + * @see AiSearchChatCompletionsRequest + */ type AutoRagAiSearchRequestStreaming = Omit & { stream: true; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchSearchResponse with the new API instead. + * @see AiSearchSearchResponse + */ type AutoRagSearchResponse = { object: 'vector_store.search_results.page'; search_query: string; @@ -6922,6 +8949,11 @@ type AutoRagSearchResponse = { has_more: boolean; next_page: string | null; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchListResponse with the new API instead. + * @see AiSearchListResponse + */ type AutoRagListResponse = { id: string; enable: boolean; @@ -6931,14 +8963,51 @@ type AutoRagListResponse = { paused: boolean; status: string; }[]; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * The new API returns different response formats for chat completions. + */ type AutoRagAiSearchResponse = AutoRagSearchResponse & { response: string; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use the new AI Search API instead: `env.AI.aiSearch` + * + * Migration guide: + * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` + * - `env.AI.autorag('id').search(...)` → `env.AI.aiSearch.get('id').search(...)` + * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` + * + * @see AiSearchAccountService + * @see AiSearchInstanceService + */ declare abstract class AutoRAG { + /** + * @deprecated Use `env.AI.aiSearch.list()` instead. + * @see AiSearchAccountService.list + */ list(): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).search(...)` instead. + * Note: The new API uses a messages array instead of a query string. + * @see AiSearchInstanceService.search + */ search(params: AutoRagSearchRequest): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ aiSearch(params: AutoRagAiSearchRequest): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ aiSearch(params: AutoRagAiSearchRequest): Promise; } interface BasicImageTransformations { @@ -7689,6 +9758,10 @@ interface D1Meta { * The region of the database instance that executed the query. */ served_by_region?: string; + /** + * The three letters airport code of the colo that executed the query. + */ + served_by_colo?: string; /** * True if-and-only-if the database instance that executed the query was the primary. */ @@ -7777,6 +9850,15 @@ declare abstract class D1PreparedStatement { // ignored when `Disposable` is included in the standard lib. interface Disposable { } +/** + * The returned data after sending an email + */ +interface EmailSendResult { + /** + * The Email Message ID + */ + messageId: string; +} /** * An email message that can be sent from a Worker. */ @@ -7818,24 +9900,55 @@ interface ForwardableEmailMessage extends EmailMessage { * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). * @returns A promise that resolves when the email message is forwarded. */ - forward(rcptTo: string, headers?: Headers): Promise; + forward(rcptTo: string, headers?: Headers): Promise; /** * Reply to the sender of this email message with a new EmailMessage object. * @param message The reply message. * @returns A promise that resolves when the email message is replied. */ - reply(message: EmailMessage): Promise; + reply(message: EmailMessage): Promise; +} +/** A file attachment for an email message */ +type EmailAttachment = { + disposition: 'inline'; + contentId: string; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; +} | { + disposition: 'attachment'; + contentId?: undefined; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; +}; +/** An Email Address */ +interface EmailAddress { + name: string; + email: string; } /** * A binding that allows a Worker to send email messages. */ interface SendEmail { - send(message: EmailMessage): Promise; + send(message: EmailMessage): Promise; + send(builder: { + from: string | EmailAddress; + to: string | string[]; + subject: string; + replyTo?: string | EmailAddress; + cc?: string | string[]; + bcc?: string | string[]; + headers?: Record; + text?: string; + html?: string; + attachments?: EmailAttachment[]; + }): Promise; } declare abstract class EmailEvent extends ExtendableEvent { readonly message: ForwardableEmailMessage; } -declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; +declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; declare module "cloudflare:email" { let _EmailMessage: { prototype: EmailMessage; @@ -7863,7 +9976,7 @@ interface Hyperdrive { /** * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. * - * Calling this method returns an idential socket to if you call + * Calling this method returns an identical socket to if you call * `connect("host:port")` using the `host` and `port` fields from this object. * Pick whichever approach works better with your preferred DB client library. * @@ -7976,6 +10089,83 @@ type ImageOutputOptions = { background?: string; anim?: boolean; }; +interface ImageMetadata { + id: string; + filename?: string; + uploaded?: string; + requireSignedURLs: boolean; + meta?: Record; + variants: string[]; + draft?: boolean; + creator?: string; +} +interface ImageUploadOptions { + id?: string; + filename?: string; + requireSignedURLs?: boolean; + metadata?: Record; + creator?: string; + encoding?: 'base64'; +} +interface ImageUpdateOptions { + requireSignedURLs?: boolean; + metadata?: Record; + creator?: string; +} +interface ImageListOptions { + limit?: number; + cursor?: string; + sortOrder?: 'asc' | 'desc'; + creator?: string; +} +interface ImageList { + images: ImageMetadata[]; + cursor?: string; + listComplete: boolean; +} +interface HostedImagesBinding { + /** + * Get detailed metadata for a hosted image + * @param imageId The ID of the image (UUID or custom ID) + * @returns Image metadata, or null if not found + */ + details(imageId: string): Promise; + /** + * Get the raw image data for a hosted image + * @param imageId The ID of the image (UUID or custom ID) + * @returns ReadableStream of image bytes, or null if not found + */ + image(imageId: string): Promise | null>; + /** + * Upload a new hosted image + * @param image The image file to upload + * @param options Upload configuration + * @returns Metadata for the uploaded image + * @throws {@link ImagesError} if upload fails + */ + upload(image: ReadableStream | ArrayBuffer, options?: ImageUploadOptions): Promise; + /** + * Update hosted image metadata + * @param imageId The ID of the image + * @param options Properties to update + * @returns Updated image metadata + * @throws {@link ImagesError} if update fails + */ + update(imageId: string, options: ImageUpdateOptions): Promise; + /** + * Delete a hosted image + * @param imageId The ID of the image + * @returns True if deleted, false if not found + */ + delete(imageId: string): Promise; + /** + * List hosted images with pagination + * @param options List configuration + * @returns List of images with pagination info + * @throws {@link ImagesError} if list fails + */ + list(options?: ImageListOptions): Promise; +} interface ImagesBinding { /** * Get image metadata (type, width and height) @@ -7989,6 +10179,10 @@ interface ImagesBinding { * @returns A transform handle */ input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; + /** + * Access hosted images CRUD operations + */ + readonly hosted: HostedImagesBinding; } interface ImageTransformer { /** @@ -8055,7 +10249,13 @@ interface MediaTransformer { * @param transform - Configuration for how the media should be transformed * @returns A generator for producing the transformed media output */ - transform(transform: MediaTransformationInputOptions): MediaTransformationGenerator; + transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator; + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; } /** * Generator for producing media transformation results. @@ -8067,7 +10267,7 @@ interface MediaTransformationGenerator { * @param output - Configuration for the output format and parameters * @returns The final transformation result containing the transformed media */ - output(output: MediaTransformationOutputOptions): MediaTransformationResult; + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; } /** * Result of a media transformation operation. @@ -8076,19 +10276,19 @@ interface MediaTransformationGenerator { interface MediaTransformationResult { /** * Returns the transformed media as a readable stream of bytes. - * @returns A stream containing the transformed media data + * @returns A promise containing a readable stream with the transformed media */ - media(): ReadableStream; + media(): Promise>; /** * Returns the transformed media as an HTTP response object. - * @returns The transformed media as a Response, ready to store in cache or return to users + * @returns The transformed media as a Promise, ready to store in cache or return to users */ - response(): Response; + response(): Promise; /** * Returns the MIME type of the transformed media. - * @returns The content type string (e.g., 'image/jpeg', 'video/mp4') + * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4') */ - contentType(): string; + contentType(): Promise; } /** * Configuration options for transforming media input. @@ -8196,7 +10396,7 @@ declare module "cloudflare:pipelines" { protected ctx: ExecutionContext; constructor(ctx: ExecutionContext, env: Env); /** - * run recieves an array of PipelineRecord which can be + * run receives an array of PipelineRecord which can be * transformed and returned to the pipeline * @param records Incoming records from the pipeline to be transformed * @param metadata Information about the specific pipeline calling the transformation entrypoint @@ -8362,9 +10562,9 @@ declare namespace Rpc { // Base type for all other types providing RPC-like interfaces. // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. - export type Provider = MaybeCallableProvider & { - [K in Exclude>]: MethodOrProperty; - }; + export type Provider = MaybeCallableProvider & Pick<{ + [K in keyof T]: MethodOrProperty; + }, Exclude>>; } declare namespace Cloudflare { // Type of `env`. @@ -8467,9 +10667,12 @@ declare namespace CloudflareWorkersModule { timestamp: Date; type: string; }; + export type WorkflowStepContext = { + attempt: number; + }; export abstract class WorkflowStep { - do>(name: string, callback: () => Promise): Promise; - do>(name: string, config: WorkflowStepConfig, callback: () => Promise): Promise; + do>(name: string, callback: (ctx: WorkflowStepContext) => Promise): Promise; + do>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise): Promise; sleep: (name: string, duration: WorkflowSleepDuration) => Promise; sleepUntil: (name: string, timestamp: Date | number) => Promise; waitForEvent>(name: string, options: { @@ -8477,6 +10680,7 @@ declare namespace CloudflareWorkersModule { timeout?: WorkflowTimeoutDuration | number; }): Promise>; } + export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown'; export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; protected ctx: ExecutionContext; @@ -8485,7 +10689,11 @@ declare namespace CloudflareWorkersModule { run(event: Readonly>, step: WorkflowStep): Promise; } export function waitUntil(promise: Promise): void; + export function withEnv(newEnv: unknown, fn: () => unknown): unknown; + export function withExports(newExports: unknown, fn: () => unknown): unknown; + export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown; export const env: Cloudflare.Env; + export const exports: Cloudflare.Exports; } declare module 'cloudflare:workers' { export = CloudflareWorkersModule; @@ -8501,17 +10709,765 @@ declare module "cloudflare:sockets" { function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; export { _connect as connect }; } +/** + * Binding entrypoint for Cloudflare Stream. + * + * Usage: + * - Binding-level operations: + * `await env.STREAM.videos.upload` + * `await env.STREAM.videos.createDirectUpload` + * `await env.STREAM.videos.*` + * `await env.STREAM.watermarks.*` + * - Per-video operations: + * `await env.STREAM.video(id).downloads.*` + * `await env.STREAM.video(id).captions.*` + * + * Example usage: + * ```ts + * await env.STREAM.video(id).downloads.generate(); + * + * const video = env.STREAM.video(id) + * const captions = video.captions.list(); + * const videoDetails = video.details() + * ``` + */ +interface StreamBinding { + /** + * Returns a handle scoped to a single video for per-video operations. + * @param id The unique identifier for the video. + * @returns A handle for per-video operations. + */ + video(id: string): StreamVideoHandle; + /** + * Uploads a new video from a File. + * @param file The video file to upload. + * @returns The uploaded video details. + * @throws {BadRequestError} if the upload parameter is invalid + * @throws {QuotaReachedError} if the account storage capacity is exceeded + * @throws {MaxFileSizeError} if the file size is too large + * @throws {RateLimitedError} if the server received too many requests + * @throws {InternalError} if an unexpected error occurs + */ + upload(file: File): Promise; + /** + * Uploads a new video from a provided URL. + * @param url The URL to upload from. + * @param params Optional upload parameters. + * @returns The uploaded video details. + * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid + * @throws {QuotaReachedError} if the account storage capacity is exceeded + * @throws {MaxFileSizeError} if the file size is too large + * @throws {RateLimitedError} if the server received too many requests + * @throws {AlreadyUploadedError} if a video was already uploaded to this URL + * @throws {InternalError} if an unexpected error occurs + */ + upload(url: string, params?: StreamUrlUploadParams): Promise; + /** + * Creates a direct upload that allows video uploads without an API key. + * @param params Parameters for the direct upload + * @returns The direct upload details. + * @throws {BadRequestError} if the parameters are invalid + * @throws {RateLimitedError} if the server received too many requests + * @throws {InternalError} if an unexpected error occurs + */ + createDirectUpload(params: StreamDirectUploadCreateParams): Promise; + videos: StreamVideos; + watermarks: StreamWatermarks; +} +/** + * Handle for operations scoped to a single Stream video. + */ +interface StreamVideoHandle { + /** + * The unique identifier for the video. + */ + id: string; + /** + * Get a full videos details + * @returns The full video details. + * @throws {NotFoundError} if the video is not found + * @throws {InternalError} if an unexpected error occurs + */ + details(): Promise; + /** + * Update details for a single video. + * @param params The fields to update for the video. + * @returns The updated video details. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the parameters are invalid + * @throws {InternalError} if an unexpected error occurs + */ + update(params: StreamUpdateVideoParams): Promise; + /** + * Deletes a video and its copies from Cloudflare Stream. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(): Promise; + /** + * Creates a signed URL token for a video. + * @returns The signed token that was created. + * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed + */ + generateToken(): Promise; + downloads: StreamScopedDownloads; + captions: StreamScopedCaptions; +} +interface StreamVideo { + /** + * The unique identifier for the video. + */ + id: string; + /** + * A user-defined identifier for the media creator. + */ + creator: string | null; + /** + * The thumbnail URL for the video. + */ + thumbnail: string; + /** + * The thumbnail timestamp percentage. + */ + thumbnailTimestampPct: number; + /** + * Indicates whether the video is ready to stream. + */ + readyToStream: boolean; + /** + * The date and time the video became ready to stream. + */ + readyToStreamAt: string | null; + /** + * Processing status information. + */ + status: StreamVideoStatus; + /** + * A user modifiable key-value store. + */ + meta: Record; + /** + * The date and time the video was created. + */ + created: string; + /** + * The date and time the video was last modified. + */ + modified: string; + /** + * The date and time at which the video will be deleted. + */ + scheduledDeletion: string | null; + /** + * The size of the video in bytes. + */ + size: number; + /** + * The preview URL for the video. + */ + preview?: string; + /** + * Origins allowed to display the video. + */ + allowedOrigins: Array; + /** + * Indicates whether signed URLs are required. + */ + requireSignedURLs: boolean | null; + /** + * The date and time the video was uploaded. + */ + uploaded: string | null; + /** + * The date and time when the upload URL expires. + */ + uploadExpiry: string | null; + /** + * The maximum size in bytes for direct uploads. + */ + maxSizeBytes: number | null; + /** + * The maximum duration in seconds for direct uploads. + */ + maxDurationSeconds: number | null; + /** + * The video duration in seconds. -1 indicates unknown. + */ + duration: number; + /** + * Input metadata for the original upload. + */ + input: StreamVideoInput; + /** + * Playback URLs for the video. + */ + hlsPlaybackUrl: string; + dashPlaybackUrl: string; + /** + * The watermark applied to the video, if any. + */ + watermark: StreamWatermark | null; + /** + * The live input id associated with the video, if any. + */ + liveInputId?: string | null; + /** + * The source video id if this is a clip. + */ + clippedFromId: string | null; + /** + * Public details associated with the video. + */ + publicDetails: StreamPublicDetails | null; +} +type StreamVideoStatus = { + /** + * The current processing state. + */ + state: string; + /** + * The current processing step. + */ + step?: string; + /** + * The percent complete as a string. + */ + pctComplete?: string; + /** + * An error reason code, if applicable. + */ + errorReasonCode: string; + /** + * An error reason text, if applicable. + */ + errorReasonText: string; +}; +type StreamVideoInput = { + /** + * The input width in pixels. + */ + width: number; + /** + * The input height in pixels. + */ + height: number; +}; +type StreamPublicDetails = { + /** + * The public title for the video. + */ + title: string | null; + /** + * The public share link. + */ + share_link: string | null; + /** + * The public channel link. + */ + channel_link: string | null; + /** + * The public logo URL. + */ + logo: string | null; +}; +type StreamDirectUpload = { + /** + * The URL an unauthenticated upload can use for a single multipart request. + */ + uploadURL: string; + /** + * A Cloudflare-generated unique identifier for a media item. + */ + id: string; + /** + * The watermark profile applied to the upload. + */ + watermark: StreamWatermark | null; + /** + * The scheduled deletion time, if any. + */ + scheduledDeletion: string | null; +}; +type StreamDirectUploadCreateParams = { + /** + * The maximum duration in seconds for a video upload. + */ + maxDurationSeconds: number; + /** + * The date and time after upload when videos will not be accepted. + */ + expiry?: string; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * A user modifiable key-value store used to reference other systems of record for + * managing videos. + */ + meta?: Record; + /** + * Lists the origins allowed to display the video. + */ + allowedOrigins?: Array; + /** + * Indicates whether the video can be accessed using the id. When set to `true`, + * a signed token must be generated with a signing key to view the video. + */ + requireSignedURLs?: boolean; + /** + * The thumbnail timestamp percentage. + */ + thumbnailTimestampPct?: number; + /** + * The date and time at which the video will be deleted. Include `null` to remove + * a scheduled deletion. + */ + scheduledDeletion?: string | null; + /** + * The watermark profile to apply. + */ + watermark?: StreamDirectUploadWatermark; +}; +type StreamDirectUploadWatermark = { + /** + * The unique identifier for the watermark profile. + */ + id: string; +}; +type StreamUrlUploadParams = { + /** + * Lists the origins allowed to display the video. Enter allowed origin + * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the + * video to be viewed on any origin. + */ + allowedOrigins?: Array; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * A user modifiable key-value store used to reference other systems of + * record for managing videos. + */ + meta?: Record; + /** + * Indicates whether the video can be a accessed using the id. When + * set to `true`, a signed token must be generated with a signing key to view the + * video. + */ + requireSignedURLs?: boolean; + /** + * Indicates the date and time at which the video will be deleted. Omit + * the field to indicate no change, or include with a `null` value to remove an + * existing scheduled deletion. If specified, must be at least 30 days from upload + * time. + */ + scheduledDeletion?: string | null; + /** + * The timestamp for a thumbnail image calculated as a percentage value + * of the video's duration. To convert from a second-wise timestamp to a + * percentage, divide the desired timestamp by the total duration of the video. If + * this value is not set, the default thumbnail image is taken from 0s of the + * video. + */ + thumbnailTimestampPct?: number; + /** + * The identifier for the watermark profile + */ + watermarkId?: string; +}; +interface StreamScopedCaptions { + /** + * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language. + * One caption or subtitle file per language is allowed. + * @param language The BCP 47 language tag for the caption or subtitle. + * @param file The caption or subtitle file to upload. + * @returns The created caption entry. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the language or file is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {InternalError} if an unexpected error occurs + */ + upload(language: string, file: File): Promise; + /** + * Generate captions or subtitles for the provided language via AI. + * @param language The BCP 47 language tag to generate. + * @returns The generated caption entry. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the language is invalid + * @throws {StreamError} if a generated caption already exists + * @throws {StreamError} if the video duration is too long + * @throws {StreamError} if the video is missing audio + * @throws {StreamError} if the requested language is not supported + * @throws {InternalError} if an unexpected error occurs + */ + generate(language: string): Promise; + /** + * Lists the captions or subtitles. + * Use the language parameter to filter by a specific language. + * @param language The optional BCP 47 language tag to filter by. + * @returns The list of captions or subtitles. + * @throws {NotFoundError} if the video or caption is not found + * @throws {InternalError} if an unexpected error occurs + */ + list(language?: string): Promise; + /** + * Removes the captions or subtitles from a video. + * @param language The BCP 47 language tag to remove. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video or caption is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(language: string): Promise; +} +interface StreamScopedDownloads { + /** + * Generates a download for a video when a video is ready to view. Available + * types are `default` and `audio`. Defaults to `default` when omitted. + * @param downloadType The download type to create. + * @returns The current downloads for the video. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the download type is invalid + * @throws {StreamError} if the video duration is too long to generate a download + * @throws {StreamError} if the video is not ready to stream + * @throws {InternalError} if an unexpected error occurs + */ + generate(downloadType?: StreamDownloadType): Promise; + /** + * Lists the downloads created for a video. + * @returns The current downloads for the video. + * @throws {NotFoundError} if the video or downloads are not found + * @throws {InternalError} if an unexpected error occurs + */ + get(): Promise; + /** + * Delete the downloads for a video. Available types are `default` and `audio`. + * Defaults to `default` when omitted. + * @param downloadType The download type to delete. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video or downloads are not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(downloadType?: StreamDownloadType): Promise; +} +interface StreamVideos { + /** + * Lists all videos in a users account. + * @returns The list of videos. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InternalError} if an unexpected error occurs + */ + list(params?: StreamVideosListParams): Promise; +} +interface StreamWatermarks { + /** + * Generate a new watermark profile + * @param file The image file to upload + * @param params The watermark creation parameters. + * @returns The created watermark profile. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InvalidURLError} if the URL is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached + * @throws {InternalError} if an unexpected error occurs + */ + generate(file: File, params: StreamWatermarkCreateParams): Promise; + /** + * Generate a new watermark profile + * @param url The image url to upload + * @param params The watermark creation parameters. + * @returns The created watermark profile. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InvalidURLError} if the URL is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached + * @throws {InternalError} if an unexpected error occurs + */ + generate(url: string, params: StreamWatermarkCreateParams): Promise; + /** + * Lists all watermark profiles for an account. + * @returns The list of watermark profiles. + * @throws {InternalError} if an unexpected error occurs + */ + list(): Promise; + /** + * Retrieves details for a single watermark profile. + * @param watermarkId The watermark profile identifier. + * @returns The watermark profile details. + * @throws {NotFoundError} if the watermark is not found + * @throws {InternalError} if an unexpected error occurs + */ + get(watermarkId: string): Promise; + /** + * Deletes a watermark profile. + * @param watermarkId The watermark profile identifier. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the watermark is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(watermarkId: string): Promise; +} +type StreamUpdateVideoParams = { + /** + * Lists the origins allowed to display the video. Enter allowed origin + * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the + * video to be viewed on any origin. + */ + allowedOrigins?: Array; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * The maximum duration in seconds for a video upload. Can be set for a + * video that is not yet uploaded to limit its duration. Uploads that exceed the + * specified duration will fail during processing. A value of `-1` means the value + * is unknown. + */ + maxDurationSeconds?: number; + /** + * A user modifiable key-value store used to reference other systems of + * record for managing videos. + */ + meta?: Record; + /** + * Indicates whether the video can be a accessed using the id. When + * set to `true`, a signed token must be generated with a signing key to view the + * video. + */ + requireSignedURLs?: boolean; + /** + * Indicates the date and time at which the video will be deleted. Omit + * the field to indicate no change, or include with a `null` value to remove an + * existing scheduled deletion. If specified, must be at least 30 days from upload + * time. + */ + scheduledDeletion?: string | null; + /** + * The timestamp for a thumbnail image calculated as a percentage value + * of the video's duration. To convert from a second-wise timestamp to a + * percentage, divide the desired timestamp by the total duration of the video. If + * this value is not set, the default thumbnail image is taken from 0s of the + * video. + */ + thumbnailTimestampPct?: number; +}; +type StreamCaption = { + /** + * Whether the caption was generated via AI. + */ + generated?: boolean; + /** + * The language label displayed in the native language to users. + */ + label: string; + /** + * The language tag in BCP 47 format. + */ + language: string; + /** + * The status of a generated caption. + */ + status?: 'ready' | 'inprogress' | 'error'; +}; +type StreamDownloadStatus = 'ready' | 'inprogress' | 'error'; +type StreamDownloadType = 'default' | 'audio'; +type StreamDownload = { + /** + * Indicates the progress as a percentage between 0 and 100. + */ + percentComplete: number; + /** + * The status of a generated download. + */ + status: StreamDownloadStatus; + /** + * The URL to access the generated download. + */ + url?: string; +}; +/** + * An object with download type keys. Each key is optional and only present if that + * download type has been created. + */ +type StreamDownloadGetResponse = { + /** + * The audio-only download. Only present if this download type has been created. + */ + audio?: StreamDownload; + /** + * The default video download. Only present if this download type has been created. + */ + default?: StreamDownload; +}; +type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center'; +type StreamWatermark = { + /** + * The unique identifier for a watermark profile. + */ + id: string; + /** + * The size of the image in bytes. + */ + size: number; + /** + * The height of the image in pixels. + */ + height: number; + /** + * The width of the image in pixels. + */ + width: number; + /** + * The date and a time a watermark profile was created. + */ + created: string; + /** + * The source URL for a downloaded image. If the watermark profile was created via + * direct upload, this field is null. + */ + downloadedFrom: string | null; + /** + * A short description of the watermark profile. + */ + name: string; + /** + * The translucency of the image. A value of `0.0` makes the image completely + * transparent, and `1.0` makes the image completely opaque. Note that if the image + * is already semi-transparent, setting this to `1.0` will not make the image + * completely opaque. + */ + opacity: number; + /** + * The whitespace between the adjacent edges (determined by position) of the video + * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded + * video width or length, as determined by the algorithm. + */ + padding: number; + /** + * The size of the image relative to the overall size of the video. This parameter + * will adapt to horizontal and vertical videos automatically. `0.0` indicates no + * scaling (use the size of the image as-is), and `1.0 `fills the entire video. + */ + scale: number; + /** + * The location of the image. Valid positions are: `upperRight`, `upperLeft`, + * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the + * `padding` parameter. + */ + position: StreamWatermarkPosition; +}; +type StreamWatermarkCreateParams = { + /** + * A short description of the watermark profile. + */ + name?: string; + /** + * The translucency of the image. A value of `0.0` makes the image completely + * transparent, and `1.0` makes the image completely opaque. Note that if the + * image is already semi-transparent, setting this to `1.0` will not make the + * image completely opaque. + */ + opacity?: number; + /** + * The whitespace between the adjacent edges (determined by position) of the + * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully + * padded video width or length, as determined by the algorithm. + */ + padding?: number; + /** + * The size of the image relative to the overall size of the video. This + * parameter will adapt to horizontal and vertical videos automatically. `0.0` + * indicates no scaling (use the size of the image as-is), and `1.0 `fills the + * entire video. + */ + scale?: number; + /** + * The location of the image. + */ + position?: StreamWatermarkPosition; +}; +type StreamVideosListParams = { + /** + * The maximum number of videos to return. + */ + limit?: number; + /** + * Return videos created before this timestamp. + * (RFC3339/RFC3339Nano) + */ + before?: string; + /** + * Comparison operator for the `before` field. + * @default 'lt' + */ + beforeComp?: StreamPaginationComparison; + /** + * Return videos created after this timestamp. + * (RFC3339/RFC3339Nano) + */ + after?: string; + /** + * Comparison operator for the `after` field. + * @default 'gte' + */ + afterComp?: StreamPaginationComparison; +}; +type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte'; +/** + * Error object for Stream binding operations. + */ +interface StreamError extends Error { + readonly code: number; + readonly statusCode: number; + readonly message: string; + readonly stack?: string; +} +interface InternalError extends StreamError { + name: 'InternalError'; +} +interface BadRequestError extends StreamError { + name: 'BadRequestError'; +} +interface NotFoundError extends StreamError { + name: 'NotFoundError'; +} +interface ForbiddenError extends StreamError { + name: 'ForbiddenError'; +} +interface RateLimitedError extends StreamError { + name: 'RateLimitedError'; +} +interface QuotaReachedError extends StreamError { + name: 'QuotaReachedError'; +} +interface MaxFileSizeError extends StreamError { + name: 'MaxFileSizeError'; +} +interface InvalidURLError extends StreamError { + name: 'InvalidURLError'; +} +interface AlreadyUploadedError extends StreamError { + name: 'AlreadyUploadedError'; +} +interface TooManyWatermarksError extends StreamError { + name: 'TooManyWatermarksError'; +} type MarkdownDocument = { name: string; blob: Blob; }; type ConversionResponse = { + id: string; name: string; mimeType: string; format: 'markdown'; tokens: number; data: string; } | { + id: string; name: string; mimeType: string; format: 'error'; @@ -8529,6 +11485,8 @@ type ConversionOptions = { images?: EmbeddedImageConversionOptions & { convertOGImage?: boolean; }; + hostname?: string; + cssSelector?: string; }; docx?: { images?: EmbeddedImageConversionOptions; @@ -8666,6 +11624,15 @@ declare namespace TailStream { readonly level: "debug" | "error" | "info" | "log" | "warn"; readonly message: object; } + interface DroppedEventsDiagnostic { + readonly diagnosticsType: "droppedEvents"; + readonly count: number; + } + interface StreamDiagnostic { + readonly type: 'streamDiagnostic'; + // To add new diagnostic types, define a new interface and add it to this union type. + readonly diagnostic: DroppedEventsDiagnostic; + } // This marks the worker handler return information. // This is separate from Outcome because the worker invocation can live for a long time after // returning. For example - Websockets that return an http upgrade response but then continue @@ -8682,7 +11649,7 @@ declare namespace TailStream { readonly type: "attributes"; readonly info: Attribute[]; } - type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | Return | Attributes; + type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes; // Context in which this trace event lives. interface SpanContext { // Single id for the entire top-level invocation @@ -8696,7 +11663,7 @@ declare namespace TailStream { // For Hibernate and Mark this would be the span under which they were emitted. // spanId is not set ONLY if: // 1. This is an Onset event - // 2. We are not inherting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) + // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) readonly spanId?: string; } interface TailEvent { @@ -9062,8 +12029,11 @@ type InstanceStatus = { | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish | 'waitingForPause' // instance is finishing the current work to pause | 'unknown'; - error?: string; - output?: object; + error?: { + name: string; + message: string; + }; + output?: unknown; }; interface WorkflowError { code?: number; diff --git a/e2e/react-start/basic-react-query/.devcontainer/devcontainer.json b/e2e/react-start/basic-react-query/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/react-start/basic-react-query/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/react-start/basic-react-query/package.json b/e2e/react-start/basic-react-query/package.json index 18cccdaece..ee37b82ba6 100644 --- a/e2e/react-start/basic-react-query/package.json +++ b/e2e/react-start/basic-react-query/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.90.0", @@ -20,23 +20,22 @@ "@tanstack/react-start": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "vite": "^7.1.7", - "zod": "^4.1.12" + "redaxios": "catalog:", + "tailwind-merge": "^3.6.0", + "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@tailwindcss/postcss": "^4.1.15", + "@playwright/test": "^1.61.0", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "postcss": "^8.5.1", - "srvx": "^0.9.8", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-react": "^6.0.1", + "srvx": "^1.0.0", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/e2e/react-start/basic-react-query/playwright.config.ts b/e2e/react-start/basic-react-query/playwright.config.ts index fd2150e435..216fade4d5 100644 --- a/e2e/react-start/basic-react-query/playwright.config.ts +++ b/e2e/react-start/basic-react-query/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,19 +13,19 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', + env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, + }, }, projects: [ diff --git a/e2e/react-start/basic-react-query/postcss.config.mjs b/e2e/react-start/basic-react-query/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/react-start/basic-react-query/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/react-start/basic-react-query/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic-react-query/src/components/DefaultCatchBoundary.tsx index ef2daa1ea1..405fb5f4a7 100644 --- a/e2e/react-start/basic-react-query/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/basic-react-query/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error(error) diff --git a/e2e/react-start/basic-react-query/src/routeTree.gen.ts b/e2e/react-start/basic-react-query/src/routeTree.gen.ts index c140825485..72bd9579f6 100644 --- a/e2e/react-start/basic-react-query/src/routeTree.gen.ts +++ b/e2e/react-start/basic-react-query/src/routeTree.gen.ts @@ -9,43 +9,32 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as UsersRouteImport } from './routes/users' -import { Route as SuspenseTransitionRouteImport } from './routes/suspense-transition' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as SuspenseTransitionRouteImport } from './routes/suspense-transition' +import { Route as UsersRouteImport } from './routes/users' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as TransitionCountQueryRouteImport } from './routes/transition/count/query' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as TransitionCountQueryRouteImport } from './routes/transition/count/query' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ - id: '/suspense-transition', - path: '/suspense-transition', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -53,68 +42,79 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ + id: '/suspense-transition', + path: '/suspense-transition', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const LayoutLayout2Route = LayoutLayout2RouteImport.update({ id: '/_layout-2', getParentRoute: () => LayoutRoute, } as any) -const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ - id: '/transition/count/query', - path: '/transition/count/query', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) +const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ + id: '/transition/count/query', + path: '/transition/count/query', + getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { @@ -244,32 +244,18 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/suspense-transition': { - id: '/suspense-transition' - path: '/suspense-transition' - fullPath: '/suspense-transition' - preLoaderRoute: typeof SuspenseTransitionRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -279,47 +265,40 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/_layout': { - id: '/_layout' + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/suspense-transition': { + id: '/suspense-transition' + path: '/suspense-transition' + fullPath: '/suspense-transition' + preLoaderRoute: typeof SuspenseTransitionRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' path: '' - fullPath: '' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute } '/api/users': { id: '/api/users' @@ -328,33 +307,40 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/transition/count/query': { - id: '/transition/count/query' - path: '/transition/count/query' - fullPath: '/transition/count/query' - preLoaderRoute: typeof TransitionCountQueryRouteImport - parentRoute: typeof rootRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' @@ -363,12 +349,26 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport + } + '/transition/count/query': { + id: '/transition/count/query' + path: '/transition/count/query' + fullPath: '/transition/count/query' + preLoaderRoute: typeof TransitionCountQueryRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/e2e/react-start/basic-react-query/src/routes/api.users.ts b/e2e/react-start/basic-react-query/src/routes/api.users.ts index 454aca50a0..924c5b6860 100644 --- a/e2e/react-start/basic-react-query/src/routes/api.users.ts +++ b/e2e/react-start/basic-react-query/src/routes/api.users.ts @@ -1,13 +1,8 @@ import { createFileRoute } from '@tanstack/react-router' -import { json } from '@tanstack/react-start' import axios from 'redaxios' import type { User } from '../utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users')({ server: { @@ -16,7 +11,7 @@ export const Route = createFileRoute('/api/users')({ console.info('Fetching users... @', request.url) const res = await axios.get>(`${queryURL}/users`) const list = res.data.slice(0, 10) - return json( + return Response.json( list.map((u) => ({ id: u.id, name: u.name, email: u.email })), ) }, 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 70ad77d76b..febea309ea 100644 --- a/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts +++ b/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts @@ -1,13 +1,8 @@ import { createFileRoute } from '@tanstack/react-router' -import { json } from '@tanstack/react-start' import axios from 'redaxios' import type { User } from '../../utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users/$id')({ server: { @@ -16,14 +11,14 @@ export const Route = createFileRoute('/api/users/$id')({ console.info(`Fetching users by id=${params.id}... @`, request.url) try { const res = await axios.get(`${queryURL}/users/` + params.id) - return json({ + return Response.json({ id: res.data.id, name: res.data.name, email: res.data.email, }) } catch (e) { console.error(e) - return json({ error: 'User not found' }, { status: 404 }) + return Response.json({ error: 'User not found' }, { status: 404 }) } }, }, diff --git a/e2e/react-start/basic-react-query/src/routes/deferred.tsx b/e2e/react-start/basic-react-query/src/routes/deferred.tsx index 0380f79aca..11af82ed27 100644 --- a/e2e/react-start/basic-react-query/src/routes/deferred.tsx +++ b/e2e/react-start/basic-react-query/src/routes/deferred.tsx @@ -1,6 +1,5 @@ import { createFileRoute } from '@tanstack/react-router' import { queryOptions, useSuspenseQuery } from '@tanstack/react-query' -import {} from '@tanstack/react-router' import { Suspense, useState } from 'react' const deferredQueryOptions = () => diff --git a/e2e/react-start/basic-react-query/src/styles/app.css b/e2e/react-start/basic-react-query/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/e2e/react-start/basic-react-query/src/styles/app.css +++ b/e2e/react-start/basic-react-query/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, 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 2574bf10d1..abb6e95b92 100644 --- a/e2e/react-start/basic-react-query/src/utils/posts.tsx +++ b/e2e/react-start/basic-react-query/src/utils/posts.tsx @@ -9,11 +9,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { @@ -31,7 +27,7 @@ export const postsQueryOptions = () => }) export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) + .validator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/e2e/react-start/basic-react-query/src/utils/users.tsx b/e2e/react-start/basic-react-query/src/utils/users.tsx index 26b934fcb3..15216680e9 100644 --- a/e2e/react-start/basic-react-query/src/utils/users.tsx +++ b/e2e/react-start/basic-react-query/src/utils/users.tsx @@ -1,4 +1,6 @@ import { queryOptions } from '@tanstack/react-query' +import { createIsomorphicFn } from '@tanstack/react-start' +import { getRequestUrl } from '@tanstack/react-start/server' import axios from 'redaxios' export type User = { @@ -7,17 +9,16 @@ export type User = { email: string } -const PORT = - import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` +const getOrigin = createIsomorphicFn() + .server(() => getRequestUrl().origin) + .client(() => window.location.origin) export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(DEPLOY_URL + '/api/users') + .get>(getOrigin() + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -29,7 +30,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(DEPLOY_URL + '/api/users/' + id) + .get(getOrigin() + '/api/users/' + id) .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch user') diff --git a/e2e/react-start/basic-react-query/tests/setup/global.setup.ts b/e2e/react-start/basic-react-query/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-start/basic-react-query/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts b/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-start/basic-react-query/tsconfig.json b/e2e/react-start/basic-react-query/tsconfig.json index a07911fe5f..c7a0597e4b 100644 --- a/e2e/react-start/basic-react-query/tsconfig.json +++ b/e2e/react-start/basic-react-query/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/react-start/basic-react-query/vite.config.ts b/e2e/react-start/basic-react-query/vite.config.ts index dc57f144e4..6c9a4c347a 100644 --- a/e2e/react-start/basic-react-query/vite.config.ts +++ b/e2e/react-start/basic-react-query/vite.config.ts @@ -1,14 +1,9 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], + resolve: { tsconfigPaths: true }, + plugins: [tailwindcss(), tanstackStart(), viteReact()], }) diff --git a/e2e/react-start/basic-rsc/.gitignore b/e2e/react-start/basic-rsc/.gitignore deleted file mode 100644 index 3c8e6870b3..0000000000 --- a/e2e/react-start/basic-rsc/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.env -.vercel -.output -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin diff --git a/e2e/react-start/basic-rsc/package.json b/e2e/react-start/basic-rsc/package.json deleted file mode 100644 index ba9cce783b..0000000000 --- a/e2e/react-start/basic-rsc/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "tanstack-react-start-e2e-basic-rsc", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "exit 0; vite build", - "start": "node .output/server/index.mjs" - }, - "dependencies": { - "@babel/plugin-syntax-typescript": "^7.25.9", - "@tanstack/react-router": "workspace:^", - "@tanstack/react-router-devtools": "workspace:^", - "@tanstack/react-start": "workspace:^", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "vite": "^7.1.7" - }, - "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "autoprefixer": "^10.4.20", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite-tsconfig-paths": "^5.1.4" - }, - "overrides": { - "react": "0.0.0-experimental-035a41c4e-20230704", - "react-dom": "0.0.0-experimental-035a41c4e-20230704" - } -} diff --git a/e2e/react-start/basic-rsc/postcss.config.mjs b/e2e/react-start/basic-rsc/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/react-start/basic-rsc/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/react-start/basic-rsc/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic-rsc/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index ef2daa1ea1..0000000000 --- a/e2e/react-start/basic-rsc/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { - ErrorComponent, - Link, - rootRouteId, - useMatch, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error(error) - - return ( -
- -
- - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} diff --git a/e2e/react-start/basic-rsc/src/routeTree.gen.ts b/e2e/react-start/basic-rsc/src/routeTree.gen.ts deleted file mode 100644 index 500f71a9f7..0000000000 --- a/e2e/react-start/basic-rsc/src/routeTree.gen.ts +++ /dev/null @@ -1,254 +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 PostsRouteImport } from './routes/posts' -import { Route as LayoutRouteImport } from './routes/_layout' -import { Route as IndexRouteImport } from './routes/index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' - -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, -} as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, -} as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/posts': typeof PostsRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/posts/': typeof PostsIndexRoute - '/layout-a': typeof LayoutLayout2LayoutARoute - '/layout-b': typeof LayoutLayout2LayoutBRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/posts/$postId': typeof PostsPostIdRoute - '/posts': typeof PostsIndexRoute - '/layout-a': typeof LayoutLayout2LayoutARoute - '/layout-b': typeof LayoutLayout2LayoutBRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_layout': typeof LayoutRouteWithChildren - '/posts': typeof PostsRouteWithChildren - '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/posts/': typeof PostsIndexRoute - '/_layout/_layout-2/layout-a': typeof LayoutLayout2LayoutARoute - '/_layout/_layout-2/layout-b': typeof LayoutLayout2LayoutBRoute - '/posts_/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/posts' - | '/posts/$postId' - | '/posts/' - | '/layout-a' - | '/layout-b' - | '/posts/$postId/deep' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/posts/$postId' - | '/posts' - | '/layout-a' - | '/layout-b' - | '/posts/$postId/deep' - id: - | '__root__' - | '/' - | '/_layout' - | '/posts' - | '/_layout/_layout-2' - | '/posts/$postId' - | '/posts/' - | '/_layout/_layout-2/layout-a' - | '/_layout/_layout-2/layout-b' - | '/posts_/$postId/deep' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - LayoutRoute: typeof LayoutRouteWithChildren - PostsRoute: typeof PostsRouteWithChildren - PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route - } - } -} - -interface LayoutLayout2RouteChildren { - LayoutLayout2LayoutARoute: typeof LayoutLayout2LayoutARoute - LayoutLayout2LayoutBRoute: typeof LayoutLayout2LayoutBRoute -} - -const LayoutLayout2RouteChildren: LayoutLayout2RouteChildren = { - LayoutLayout2LayoutARoute: LayoutLayout2LayoutARoute, - LayoutLayout2LayoutBRoute: LayoutLayout2LayoutBRoute, -} - -const LayoutLayout2RouteWithChildren = LayoutLayout2Route._addFileChildren( - LayoutLayout2RouteChildren, -) - -interface LayoutRouteChildren { - LayoutLayout2Route: typeof LayoutLayout2RouteWithChildren -} - -const LayoutRouteChildren: LayoutRouteChildren = { - LayoutLayout2Route: LayoutLayout2RouteWithChildren, -} - -const LayoutRouteWithChildren = - LayoutRoute._addFileChildren(LayoutRouteChildren) - -interface PostsRouteChildren { - PostsPostIdRoute: typeof PostsPostIdRoute - PostsIndexRoute: typeof PostsIndexRoute -} - -const PostsRouteChildren: PostsRouteChildren = { - PostsPostIdRoute: PostsPostIdRoute, - PostsIndexRoute: PostsIndexRoute, -} - -const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - LayoutRoute: LayoutRouteWithChildren, - PostsRoute: PostsRouteWithChildren, - PostsPostIdDeepRoute: PostsPostIdDeepRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' -declare module '@tanstack/react-start' { - interface Register { - router: Awaited> - } -} diff --git a/e2e/react-start/basic-rsc/src/router.tsx b/e2e/react-start/basic-rsc/src/router.tsx deleted file mode 100644 index fef35c9e06..0000000000 --- a/e2e/react-start/basic-rsc/src/router.tsx +++ /dev/null @@ -1,16 +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() { - const router = createRouter({ - routeTree, - scrollRestoration: true, - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - }) - - return router -} diff --git a/e2e/react-start/basic-rsc/src/routes/__root.tsx b/e2e/react-start/basic-rsc/src/routes/__root.tsx deleted file mode 100644 index 7e5ac89786..0000000000 --- a/e2e/react-start/basic-rsc/src/routes/__root.tsx +++ /dev/null @@ -1,125 +0,0 @@ -/// -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import * as React from 'react' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' -import { NotFound } from '~/components/NotFound' -import appCss from '~/styles/app.css?url' -import { seo } from '~/utils/seo' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ...seo({ - title: - 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', - description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, - }), - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - }), - errorComponent: (props) => { - return ( - - - - ) - }, - notFoundComponent: () => , - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
- - Home - {' '} - - Posts - - - Layout - - - This Route Does Not Exist - -
-
- {/* {children} */} - {children} - - - - - ) -} diff --git a/e2e/react-start/basic-rsc/src/routes/_layout.tsx b/e2e/react-start/basic-rsc/src/routes/_layout.tsx deleted file mode 100644 index 02ddbb1cd9..0000000000 --- a/e2e/react-start/basic-rsc/src/routes/_layout.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout')({ - component: LayoutComponent, -}) - -function LayoutComponent() { - return ( -
-
I'm a layout
-
- -
-
- ) -} diff --git a/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2.tsx b/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2.tsx deleted file mode 100644 index 3b7dbf2903..0000000000 --- a/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/_layout/_layout-2')({ - component: LayoutComponent, -}) - -function LayoutComponent() { - return ( -
-
I'm a nested layout
-
- - Layout A - - - Layout B - -
-
- -
-
- ) -} diff --git a/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-a.tsx b/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-a.tsx deleted file mode 100644 index ed2dea8800..0000000000 --- a/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-a.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/_layout-2/layout-a')({ - component: LayoutAComponent, -}) - -function LayoutAComponent() { - return
I'm layout A!
-} diff --git a/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-b.tsx b/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-b.tsx deleted file mode 100644 index 4799d403e9..0000000000 --- a/e2e/react-start/basic-rsc/src/routes/_layout/_layout-2/layout-b.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/_layout/_layout-2/layout-b')({ - component: LayoutBComponent, -}) - -function LayoutBComponent() { - return
I'm layout B!
-} diff --git a/e2e/react-start/basic-rsc/src/routes/index.tsx b/e2e/react-start/basic-rsc/src/routes/index.tsx deleted file mode 100644 index d531858f8c..0000000000 --- a/e2e/react-start/basic-rsc/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Welcome Home!

-
- ) -} diff --git a/e2e/react-start/basic-rsc/src/routes/posts.$postId.tsx b/e2e/react-start/basic-rsc/src/routes/posts.$postId.tsx deleted file mode 100644 index a7f2a551b2..0000000000 --- a/e2e/react-start/basic-rsc/src/routes/posts.$postId.tsx +++ /dev/null @@ -1,46 +0,0 @@ -import { ErrorComponent, Link, createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import type { ErrorComponentProps } from '@tanstack/react-router' - -import { fetchPost } from '~/utils/posts' -import { NotFound } from '~/components/NotFound' - -const renderPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) - .handler(async ({ data: postId }) => { - const post = await fetchPost(postId) - - return ( -
-

{post.title}

-
{post.body}
- - Deep View - -
- ) - }) - -export const Route = createFileRoute('/posts/$postId')({ - loader: async ({ params: { postId } }) => renderPost({ data: postId }), - errorComponent: PostErrorComponent, - component: PostComponent, - notFoundComponent: () => { - return Post not found - }, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} - -function PostComponent() { - return Route.useLoaderData() -} diff --git a/e2e/react-start/basic-rsc/src/routes/posts.index.tsx b/e2e/react-start/basic-rsc/src/routes/posts.index.tsx deleted file mode 100644 index c659274567..0000000000 --- a/e2e/react-start/basic-rsc/src/routes/posts.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/')({ - component: PostsIndexComponent, -}) - -function PostsIndexComponent() { - return
Select a post.
-} diff --git a/e2e/react-start/basic-rsc/src/routes/posts.tsx b/e2e/react-start/basic-rsc/src/routes/posts.tsx deleted file mode 100644 index a3ef2a2e20..0000000000 --- a/e2e/react-start/basic-rsc/src/routes/posts.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createServerFn, renderRsc } from '@tanstack/react-start' -import { renderPosts } from '~/utils/renderPosts' - -export const serverRenderPosts = createServerFn({ method: 'GET' }).handler( - renderPosts, -) - -export const Route = createFileRoute('/posts')({ - loader: async () => serverRenderPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - return renderRsc(Route.useLoaderData()) -} diff --git a/e2e/react-start/basic-rsc/src/routes/posts_.$postId.deep.tsx b/e2e/react-start/basic-rsc/src/routes/posts_.$postId.deep.tsx deleted file mode 100644 index 13d368cf9c..0000000000 --- a/e2e/react-start/basic-rsc/src/routes/posts_.$postId.deep.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '../utils/posts' -import { PostErrorComponent } from './posts.$postId' - -export const Route = createFileRoute('/posts_/$postId/deep')({ - loader: async ({ params: { postId } }) => fetchPost(postId), - errorComponent: PostErrorComponent, - component: PostDeepComponent, -}) - -function PostDeepComponent() { - const post = Route.useLoaderData() - - return ( -
- - ← All Posts - -

{post.title}

-
{post.body}
-
- ) -} diff --git a/e2e/react-start/basic-rsc/src/utils/posts.tsx b/e2e/react-start/basic-rsc/src/utils/posts.tsx deleted file mode 100644 index 16fc1744e6..0000000000 --- a/e2e/react-start/basic-rsc/src/utils/posts.tsx +++ /dev/null @@ -1,35 +0,0 @@ -// import { notFound } from '@tanstack/react-router' -// import { createServerFn } from '@tanstack/react-start' -import axios from 'redaxios' - -export type PostType = { - id: string - title: string - body: string -} - -export const fetchPost = async (postId: string) => { - 'use server' - console.info(`Fetching post with id ${postId}...`) - await new Promise((r) => setTimeout(r, 500)) - const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) - .then((r) => r.data) - .catch((err) => { - if (err.status === 404) { - // throw notFound() - } - throw err - }) - - return post -} - -export const fetchPosts = async () => { - 'use server' - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -} diff --git a/e2e/react-start/basic-rsc/src/utils/renderPosts.tsx b/e2e/react-start/basic-rsc/src/utils/renderPosts.tsx deleted file mode 100644 index 37c0661217..0000000000 --- a/e2e/react-start/basic-rsc/src/utils/renderPosts.tsx +++ /dev/null @@ -1,63 +0,0 @@ -'use server' - -import React from 'react' -import { fetchPosts } from './posts' - -export async function renderPosts() { - const posts = await fetchPosts() - - posts.state = posts.state || { - status: 'pending', - promise: Promise.resolve(), - } - - return ( -
-
    - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }]?.map( - (post) => { - return ( -
  • - {post.title.substring(0, 20)} - {/* -
    {post.title.substring(0, 20)}
    - */} -
  • - ) - }, - )} -
-
- Loading...
}> - - - - ) -} - -function DelayedDateViaSuspense({ state }) { - // a component that will suspend for 1 second and then show the current date - if (state.status === 'pending') { - state.promise = new Promise((resolve) => { - setTimeout(() => { - state.status = 'success' - resolve() - }, 5000) - }) - throw state.promise - } - - return
{new Date().toISOString().replace('T', ' ').split('.')[0]}
-} - -// ...fetchPosts -// posts -// ...5000 -// timestamp diff --git a/e2e/react-start/basic-rsc/vite.config.ts b/e2e/react-start/basic-rsc/vite.config.ts deleted file mode 100644 index dc57f144e4..0000000000 --- a/e2e/react-start/basic-rsc/vite.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import viteReact from '@vitejs/plugin-react' - -export default defineConfig({ - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], -}) diff --git a/e2e/react-start/basic-tsr-config/.devcontainer/devcontainer.json b/e2e/react-start/basic-tsr-config/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/react-start/basic-tsr-config/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/react-start/basic-tsr-config/package.json b/e2e/react-start/basic-tsr-config/package.json index f6b15fd80f..99e681ac9d 100644 --- a/e2e/react-start/basic-tsr-config/package.json +++ b/e2e/react-start/basic-tsr-config/package.json @@ -8,21 +8,23 @@ "dev:e2e": "vite dev", "build": "rimraf ./count.txt && vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-start": "workspace:^", "react": "^19.0.0", - "react-dom": "^19.0.0", - "vite": "^7.1.7" + "react-dom": "^19.0.0" }, "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "srvx": "^0.9.8", - "typescript": "^5.7.2" + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "rimraf": "catalog:" } } diff --git a/e2e/react-start/basic-tsr-config/playwright.config.ts b/e2e/react-start/basic-tsr-config/playwright.config.ts index 18b8905468..82678ac00b 100644 --- a/e2e/react-start/basic-tsr-config/playwright.config.ts +++ b/e2e/react-start/basic-tsr-config/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-tsr-config/src/routes/index.tsx b/e2e/react-start/basic-tsr-config/src/routes/index.tsx index 413617217d..aaa4bdfdb3 100644 --- a/e2e/react-start/basic-tsr-config/src/routes/index.tsx +++ b/e2e/react-start/basic-tsr-config/src/routes/index.tsx @@ -12,7 +12,7 @@ const getCount = createServerFn({ }) const updateCount = createServerFn({ method: 'POST' }) - .inputValidator((d: number) => d) + .validator((d: number) => d) .handler(async ({ data }) => { const count = await getCount() await fs.promises.writeFile(filePath, `${count + data}`) diff --git a/e2e/react-start/basic-tsr-config/tsconfig.json b/e2e/react-start/basic-tsr-config/tsconfig.json index 3558337b0c..f3895f6eb1 100644 --- a/e2e/react-start/basic-tsr-config/tsconfig.json +++ b/e2e/react-start/basic-tsr-config/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/app/*"] }, diff --git a/e2e/react-start/basic/.devcontainer/devcontainer.json b/e2e/react-start/basic/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/react-start/basic/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/react-start/basic/.gitignore b/e2e/react-start/basic/.gitignore index a79d5cf129..a5f07919aa 100644 --- a/e2e/react-start/basic/.gitignore +++ b/e2e/react-start/basic/.gitignore @@ -18,3 +18,5 @@ yarn.lock /playwright-report/ /blob-report/ /playwright/.cache/ +/dist-vite-*/ +/dist-rsbuild-*/ \ No newline at end of file diff --git a/e2e/react-start/basic/package.json b/e2e/react-start/basic/package.json index 645683c342..3a1a4ea9c8 100644 --- a/e2e/react-start/basic/package.json +++ b/e2e/react-start/basic/package.json @@ -4,50 +4,129 @@ "sideEffects": false, "type": "module", "scripts": { - "dev": "vite dev --port 3000", - "dev:e2e": "vite dev", - "build": "vite build && tsc --noEmit", - "build:spa": "MODE=spa vite build && tsc --noEmit", - "build:prerender": "MODE=prerender vite build && tsc --noEmit", + "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": "pnpx srvx --prod -s ../client dist/server/server.js", - "start:spa": "node server.js", - "test:e2e:startDummyServer": "node -e 'import(\"./tests/setup/global.setup.ts\").then(m => m.default())' &", - "test:e2e:stopDummyServer": "node -e 'import(\"./tests/setup/global.teardown.ts\").then(m => m.default())'", - "test:e2e:spaMode": "rm -rf port*.txt; MODE=spa playwright test --project=chromium", - "test:e2e:ssrMode": "rm -rf port*.txt; playwright test --project=chromium", - "test:e2e:prerender": "rm -rf port*.txt; MODE=prerender playwright test --project=chromium", - "test:e2e:preview": "rm -rf port*.txt; MODE=preview playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:spaMode && pnpm run test:e2e:ssrMode && pnpm run test:e2e:prerender && pnpm run test:e2e:preview" + "preview:rsbuild": "rsbuild preview", + "start": "node server.js", + "test:e2e:local": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/react-start": "workspace:^", - "express": "^5.1.0", + "express": "^5.2.1", "http-proxy-middleware": "^3.0.5", + "iron-session": "^9.0.1", "js-cookie": "^3.0.5", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0" + "redaxios": "catalog:", + "tailwind-merge": "^3.6.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@tailwindcss/postcss": "^4.1.15", + "@playwright/test": "^1.61.0", + "@rsbuild/core": "^2.3.1", + "@rsbuild/plugin-react": "^2.0.0", + "@tailwindcss/postcss": "^4.2.2", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/js-cookie": "^3.0.6", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", + "@vitejs/plugin-react": "^6.0.1", "combinate": "^1.1.11", - "postcss": "^8.5.1", - "srvx": "^0.9.8", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4", - "zod": "^3.24.2" + "srvx": "^1.0.0", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "zod": "^4.4.3" + }, + "nx": { + "targets": { + "test:e2e--vite-spa--dev": { + "dependsOn": [ + "^build" + ] + }, + "test:e2e--rsbuild-spa--dev": { + "dependsOn": [ + "^build" + ] + } + }, + "metadata": { + "playwrightModes": [ + { + "toolchain": "vite", + "mode": "ssr" + }, + { + "toolchain": "vite", + "mode": "spa" + }, + { + "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" + } + }, + { + "toolchain": "vite", + "mode": "preview" + }, + { + "toolchain": "rsbuild", + "mode": "ssr" + }, + { + "toolchain": "rsbuild", + "mode": "ssr", + "name": "iife", + "env": { + "TSS_RSB_CLIENT_OUTPUT": "iife" + } + }, + { + "toolchain": "rsbuild", + "mode": "spa" + }, + { + "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" + } + }, + { + "toolchain": "rsbuild", + "mode": "preview" + } + ] + } } } diff --git a/e2e/react-start/basic/playwright.config.ts b/e2e/react-start/basic/playwright.config.ts index aa29067f46..bb4c2cb761 100644 --- a/e2e/react-start/basic/playwright.config.ts +++ b/e2e/react-start/basic/playwright.config.ts @@ -1,63 +1,62 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import { isSpaMode } from './tests/utils/isSpaMode' -import { isPrerender } from './tests/utils/isPrerender' -import { isPreview } from './tests/utils/isPreview' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - `${packageJson.name}${isSpaMode ? '_spa' : ''}${isPreview ? '_preview' : ''}`, -) -const START_PORT = await getTestServerPort( - `${packageJson.name}${isSpaMode ? '_spa_start' : ''}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const mode = process.env.MODE ?? 'ssr' +const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' + +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) const baseURL = `http://localhost:${PORT}` -const spaModeCommand = `pnpm build:spa && pnpm start:spa` -const ssrModeCommand = `pnpm build && pnpm start` -const prerenderModeCommand = `pnpm run test:e2e:startDummyServer && pnpm build:prerender && pnpm run test:e2e:stopDummyServer && pnpm start` -const previewModeCommand = `pnpm build && pnpm preview --port ${PORT}` - -const getCommand = () => { - if (isSpaMode) return spaModeCommand - if (isPrerender) return prerenderModeCommand - if (isPreview) return previewModeCommand - return ssrModeCommand -} -console.log('running in spa mode: ', isSpaMode.toString()) -console.log('running in prerender mode: ', isPrerender.toString()) -console.log('running in preview mode: ', isPreview.toString()) +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' /** * 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']], - 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: getCommand(), - url: baseURL, - reuseExistingServer: !process.env.CI, + command: commandByMode, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { - MODE: process.env.MODE || '', - VITE_NODE_ENV: 'test', - VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), - VITE_SERVER_PORT: String(PORT), - START_PORT: String(START_PORT), + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, + MODE: mode, + E2E_TOOLCHAIN: toolchain, + START_PORT: '0', PORT: String(PORT), + E2E_DIST_DIR: distDir, + ...(process.env.TSS_RSB_CLIENT_OUTPUT + ? { TSS_RSB_CLIENT_OUTPUT: process.env.TSS_RSB_CLIENT_OUTPUT } + : {}), }, }, diff --git a/e2e/react-start/basic/public/async-user-script.js b/e2e/react-start/basic/public/async-user-script.js new file mode 100644 index 0000000000..34f4c034c0 --- /dev/null +++ b/e2e/react-start/basic/public/async-user-script.js @@ -0,0 +1,2 @@ +console.log('ASYNC_USER_SCRIPT loaded') +window.ASYNC_USER_SCRIPT = true diff --git a/e2e/react-start/basic/public/before-scripts-async-script.js b/e2e/react-start/basic/public/before-scripts-async-script.js new file mode 100644 index 0000000000..7d082fea1c --- /dev/null +++ b/e2e/react-start/basic/public/before-scripts-async-script.js @@ -0,0 +1,2 @@ +console.log('BEFORE_SCRIPTS_ASYNC_SCRIPT loaded') +window.BEFORE_SCRIPTS_ASYNC_SCRIPT = true diff --git a/e2e/react-start/basic/public/before-scripts-script.js b/e2e/react-start/basic/public/before-scripts-script.js new file mode 100644 index 0000000000..7150d19d40 --- /dev/null +++ b/e2e/react-start/basic/public/before-scripts-script.js @@ -0,0 +1,2 @@ +console.log('BEFORE_SCRIPTS_SCRIPT loaded') +window.BEFORE_SCRIPTS_SCRIPT = true diff --git a/e2e/react-start/basic/public/head-async-script.js b/e2e/react-start/basic/public/head-async-script.js new file mode 100644 index 0000000000..3da8a928cd --- /dev/null +++ b/e2e/react-start/basic/public/head-async-script.js @@ -0,0 +1,2 @@ +console.log('HEAD_ASYNC_SCRIPT loaded') +window.HEAD_ASYNC_SCRIPT = true diff --git a/e2e/react-start/basic/public/head-script.js b/e2e/react-start/basic/public/head-script.js new file mode 100644 index 0000000000..3a64b23438 --- /dev/null +++ b/e2e/react-start/basic/public/head-script.js @@ -0,0 +1,2 @@ +console.log('HEAD_SCRIPT loaded') +window.HEAD_SCRIPT = true diff --git a/e2e/react-start/basic/public/user-script.js b/e2e/react-start/basic/public/user-script.js new file mode 100644 index 0000000000..8d06a610c0 --- /dev/null +++ b/e2e/react-start/basic/public/user-script.js @@ -0,0 +1,2 @@ +console.log('USER_SCRIPT loaded') +window.USER_SCRIPT = true diff --git a/e2e/react-start/basic/rsbuild.config.ts b/e2e/react-start/basic/rsbuild.config.ts new file mode 100644 index 0000000000..23072b6c1b --- /dev/null +++ b/e2e/react-start/basic/rsbuild.config.ts @@ -0,0 +1,16 @@ +import { defineConfig } from '@rsbuild/core' +import { pluginReact } from '@rsbuild/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' +import { getStartModeConfig } from './start-mode-config' + +const outDir = process.env.E2E_DIST_DIR ?? 'dist' +const startModeConfig = getStartModeConfig() + +export default defineConfig({ + plugins: [pluginReact(), tanstackStart(startModeConfig)], + output: { + distPath: { + root: outDir, + }, + }, +}) diff --git a/e2e/react-start/basic/server.js b/e2e/react-start/basic/server.js index d618ab4bce..3e1ddab400 100644 --- a/e2e/react-start/basic/server.js +++ b/e2e/react-start/basic/server.js @@ -1,19 +1,42 @@ -import { toNodeHandler } from 'srvx/node' +import fs from 'node:fs' import path from 'node:path' +import { toNodeHandler } from 'srvx/node' import express from 'express' import { createProxyMiddleware } from 'http-proxy-middleware' -const port = process.env.PORT || 3000 +const port = Number(process.env.PORT ?? 3000) -const startPort = process.env.START_PORT || 3001 +const startPort = Number(process.env.START_PORT ?? 0) + +const isSpaMode = process.env.MODE === 'spa' +const isPrerender = process.env.MODE === 'prerender' +const distDir = process.env.E2E_DIST_DIR || 'dist' +const distClientDir = 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 async function createStartServer() { - const server = (await import('./dist/server/server.js')).default + const distServerEntryPath = resolveDistServerEntryPath() + const server = (await import(distServerEntryPath)).default const nodeHandler = toNodeHandler(server.fetch) const app = express() - app.use(express.static('./dist/client')) + // to keep testing uniform stop express from redirecting /posts to /posts/ + // when serving pre-rendered pages + app.use(express.static(distClientDir, { redirect: !isPrerender })) app.use(async (req, res, next) => { try { @@ -26,13 +49,13 @@ export async function createStartServer() { return { app } } -export async function createSpaServer() { +export async function createSpaServer(backendPort) { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${startPort}/api`, // Replace with your target server's URL + target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -40,28 +63,36 @@ export async function createSpaServer() { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) - app.use(express.static('./dist/client')) + app.use(express.static(distClientDir)) app.get('/{*splat}', (req, res) => { - res.sendFile(path.resolve('./dist/client/index.html')) + res.sendFile('index.html', { root: distClientDir }) }) return { app } } -createSpaServer().then(async ({ app }) => - app.listen(port, () => { - console.info(`Client Server: http://localhost:${port}`) - }), -) - -createStartServer().then(async ({ app }) => - app.listen(startPort, () => { - console.info(`Start Server: http://localhost:${startPort}`) - }), -) +// Bind the backend first so the SPA proxy receives the port actually held by it. +const { app: startApp } = await createStartServer() +const backend = startApp.listen(isSpaMode ? startPort : port, async (error) => { + if (error) { + throw error + } + const backendPort = backend.address().port + if (isSpaMode) { + const { app } = await createSpaServer(backendPort) + const frontend = app.listen(port, (frontendError) => { + if (frontendError) { + throw frontendError + } + console.info(`E2E app: http://localhost:${frontend.address().port}`) + }) + } else { + console.info(`E2E app: http://localhost:${backendPort}`) + } +}) diff --git a/e2e/react-start/basic/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/basic/src/components/DefaultCatchBoundary.tsx index ef2daa1ea1..405fb5f4a7 100644 --- a/e2e/react-start/basic/src/components/DefaultCatchBoundary.tsx +++ b/e2e/react-start/basic/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error(error) diff --git a/e2e/react-start/basic/src/components/WindowSize.tsx b/e2e/react-start/basic/src/components/WindowSize.tsx new file mode 100644 index 0000000000..5365cec5c9 --- /dev/null +++ b/e2e/react-start/basic/src/components/WindowSize.tsx @@ -0,0 +1,19 @@ +/** + * This component accesses `window` at module scope, which would throw + * if this module is ever imported on the server. The compiler optimization + * for ensures this module is DCE'd from the server bundle + * entirely, preventing the error. + */ + +// This throws at module import time on the server since `window` doesn't exist +const initialWidth = window.innerWidth +const initialHeight = window.innerHeight + +export function WindowSize() { + return ( +
+

Window width: {initialWidth}

+

Window height: {initialHeight}

+
+ ) +} diff --git a/e2e/react-start/basic/src/components/throwRedirect.ts b/e2e/react-start/basic/src/components/throwRedirect.ts index 0081a3c560..6a7a011912 100644 --- a/e2e/react-start/basic/src/components/throwRedirect.ts +++ b/e2e/react-start/basic/src/components/throwRedirect.ts @@ -2,7 +2,7 @@ import { redirect } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' export const throwRedirect = createServerFn() - .inputValidator( + .validator( (opts: { target: 'internal' | 'external' reloadDocument?: boolean diff --git a/e2e/react-start/basic/src/raw-stream-fns.ts b/e2e/react-start/basic/src/raw-stream-fns.ts new file mode 100644 index 0000000000..912837c218 --- /dev/null +++ b/e2e/react-start/basic/src/raw-stream-fns.ts @@ -0,0 +1,567 @@ +import { createServerFn, RawStream } from '@tanstack/react-start' + +// Helper to create a delayed Uint8Array stream +function createDelayedStream( + chunks: Array, + delayMs: number, +): ReadableStream { + return new ReadableStream({ + async start(controller) { + for (const chunk of chunks) { + await new Promise((resolve) => setTimeout(resolve, delayMs)) + controller.enqueue(chunk) + } + controller.close() + }, + }) +} + +// Helper to create a stream with variable delays per chunk +// Each entry is [chunk, delayBeforeMs] - delay happens BEFORE enqueueing the chunk +function createVariableDelayStream( + chunksWithDelays: Array<[Uint8Array, number]>, +): ReadableStream { + return new ReadableStream({ + async start(controller) { + for (const [chunk, delayMs] of chunksWithDelays) { + await new Promise((resolve) => setTimeout(resolve, delayMs)) + controller.enqueue(chunk) + } + controller.close() + }, + }) +} + +// Helper to encode text to Uint8Array +function encode(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +// Export helpers for use in components and SSR routes +export { encode, createDelayedStream, concatBytes } + +// Expected data for hint tests - defined here for both server and client verification +// Test 7: Text hint with pure text +export const TEST7_CHUNKS = [ + encode('Hello, '), + encode('World! '), + encode('This is text.'), +] +export const TEST7_EXPECTED = concatBytes(TEST7_CHUNKS) + +// Test 8: Text hint with pure binary (invalid UTF-8) +export const TEST8_CHUNKS = [ + new Uint8Array([0xff, 0xfe, 0x00, 0x01, 0x80, 0x90]), + new Uint8Array([0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0]), +] +export const TEST8_EXPECTED = concatBytes(TEST8_CHUNKS) + +// Test 9: Text hint with mixed content +export const TEST9_CHUNKS = [ + encode('Valid UTF-8 text'), + new Uint8Array([0xff, 0xfe, 0x80, 0x90]), // Invalid UTF-8 + encode(' More text'), +] +export const TEST9_EXPECTED = concatBytes(TEST9_CHUNKS) + +// Test 10: Binary hint with text data +export const TEST10_CHUNKS = [encode('This is text but using binary hint')] +export const TEST10_EXPECTED = concatBytes(TEST10_CHUNKS) + +// Test 11: Binary hint with pure binary +export const TEST11_CHUNKS = [ + new Uint8Array([0x00, 0x01, 0x02, 0xff, 0xfe, 0xfd]), +] +export const TEST11_EXPECTED = concatBytes(TEST11_CHUNKS) + +// Helper to concatenate byte arrays +function concatBytes(chunks: Array): Uint8Array { + const totalLength = chunks.reduce((acc, c) => acc + c.length, 0) + const result = new Uint8Array(totalLength) + let offset = 0 + for (const chunk of chunks) { + result.set(chunk, offset) + offset += chunk.length + } + return result +} + +// Test 1: Simple single raw stream +export const singleRawStreamFn = createServerFn().handler(async () => { + const stream = createDelayedStream( + [encode('chunk1'), encode('chunk2'), encode('chunk3')], + 50, + ) + return { + message: 'Single stream test', + data: new RawStream(stream), + } +}) + +// Test 2: Multiple raw streams +export const multipleRawStreamsFn = createServerFn().handler(async () => { + const stream1 = createDelayedStream( + [encode('stream1-a'), encode('stream1-b')], + 30, + ) + const stream2 = createDelayedStream( + [encode('stream2-a'), encode('stream2-b')], + 50, + ) + return { + message: 'Multiple streams test', + first: new RawStream(stream1), + second: new RawStream(stream2), + } +}) + +// Test 3: JSON streaming ends before raw stream +export const jsonEndsFirstFn = createServerFn().handler(async () => { + // Slow raw stream (takes 500ms total) + const slowStream = createDelayedStream( + [encode('slow-1'), encode('slow-2'), encode('slow-3'), encode('slow-4')], + 125, + ) + return { + message: 'JSON ends first test', + timestamp: Date.now(), + slowData: new RawStream(slowStream), + } +}) + +// Test 4: Raw stream ends before JSON streaming (fast stream, deferred JSON) +export const rawEndsFirstFn = createServerFn().handler(async () => { + // Fast raw stream (completes quickly) + const fastStream = createDelayedStream([encode('fast-done')], 10) + + // Deferred promise - NOT awaited, so it streams as deferred JSON + const deferredData = new Promise((resolve) => + setTimeout(() => resolve('deferred-json-data'), 200), + ) + + return { + message: 'Raw ends first test', + deferredData, + fastData: new RawStream(fastStream), + } +}) + +// Test 5: Large binary data +export const largeBinaryFn = createServerFn().handler(async () => { + // Create 1KB chunks + const chunk = new Uint8Array(1024) + for (let i = 0; i < chunk.length; i++) { + chunk[i] = i % 256 + } + + const stream = createDelayedStream([chunk, chunk, chunk], 20) + + return { + message: 'Large binary test', + size: 3072, + binary: new RawStream(stream), + } +}) + +// Test 6: Mixed streaming (promise + raw stream) +export const mixedStreamingFn = createServerFn().handler(async () => { + const rawStream = createDelayedStream( + [encode('mixed-raw-1'), encode('mixed-raw-2')], + 50, + ) + + return { + immediate: 'immediate-value', + deferred: new Promise((resolve) => + setTimeout(() => resolve('deferred-value'), 100), + ), + raw: new RawStream(rawStream), + } +}) + +// Test 7: Text hint with pure text data (should use UTF-8 encoding) +export const textHintPureTextFn = createServerFn().handler(async () => { + const stream = createDelayedStream(TEST7_CHUNKS, 30) + return { + message: 'Text hint with pure text', + data: new RawStream(stream, { hint: 'text' }), + } +}) + +// Test 8: Text hint with pure binary data (should fallback to base64) +export const textHintPureBinaryFn = createServerFn().handler(async () => { + const stream = createDelayedStream(TEST8_CHUNKS, 30) + return { + message: 'Text hint with pure binary', + data: new RawStream(stream, { hint: 'text' }), + } +}) + +// Test 9: Text hint with mixed content (some UTF-8, some binary) +export const textHintMixedFn = createServerFn().handler(async () => { + const stream = createDelayedStream(TEST9_CHUNKS, 30) + return { + message: 'Text hint with mixed content', + data: new RawStream(stream, { hint: 'text' }), + } +}) + +// Test 10: Binary hint with text data (should still use base64) +export const binaryHintTextFn = createServerFn().handler(async () => { + const stream = createDelayedStream(TEST10_CHUNKS, 30) + return { + message: 'Binary hint with text data', + data: new RawStream(stream, { hint: 'binary' }), + } +}) + +// Test 11: Binary hint with pure binary data +export const binaryHintBinaryFn = createServerFn().handler(async () => { + const stream = createDelayedStream(TEST11_CHUNKS, 30) + return { + message: 'Binary hint with binary data', + data: new RawStream(stream, { hint: 'binary' }), + } +}) + +// ============================================================================ +// MULTIPLEXING TESTS - Verify correct interleaving of multiple streams +// ============================================================================ + +// Expected data for multiplexing tests +// Test 12: Two streams with interleaved timing +// Stream A: sends at 0ms, 150ms, 200ms (3 chunks with pauses) +// Stream B: sends at 50ms, 100ms, 250ms (3 chunks, different rhythm) +export const TEST12_STREAM_A_CHUNKS: Array<[Uint8Array, number]> = [ + [encode('A1-first'), 0], // immediate + [encode('A2-after-pause'), 150], // 150ms pause + [encode('A3-quick'), 50], // 50ms after A2 +] +export const TEST12_STREAM_B_CHUNKS: Array<[Uint8Array, number]> = [ + [encode('B1-start'), 50], // 50ms after start + [encode('B2-continue'), 50], // 50ms after B1 + [encode('B3-final'), 150], // 150ms pause then final +] +export const TEST12_STREAM_A_EXPECTED = concatBytes( + TEST12_STREAM_A_CHUNKS.map(([chunk]) => chunk), +) +export const TEST12_STREAM_B_EXPECTED = concatBytes( + TEST12_STREAM_B_CHUNKS.map(([chunk]) => chunk), +) + +// Test 13: Burst-pause-burst pattern (single stream) +// 3 chunks quickly, long pause, 3 more chunks quickly +export const TEST13_CHUNKS: Array<[Uint8Array, number]> = [ + [encode('burst1-a'), 10], + [encode('burst1-b'), 10], + [encode('burst1-c'), 10], + [encode('pause-then-burst2-a'), 200], // long pause + [encode('burst2-b'), 10], + [encode('burst2-c'), 10], +] +export const TEST13_EXPECTED = concatBytes( + TEST13_CHUNKS.map(([chunk]) => chunk), +) + +// Test 14: Three concurrent streams with different patterns +// Stream A: fast steady (every 30ms) +// Stream B: slow steady (every 100ms) +// Stream C: burst pattern (quick-pause-quick) +export const TEST14_STREAM_A_CHUNKS: Array<[Uint8Array, number]> = [ + [encode('A1'), 30], + [encode('A2'), 30], + [encode('A3'), 30], + [encode('A4'), 30], +] +export const TEST14_STREAM_B_CHUNKS: Array<[Uint8Array, number]> = [ + [encode('B1-slow'), 100], + [encode('B2-slow'), 100], +] +export const TEST14_STREAM_C_CHUNKS: Array<[Uint8Array, number]> = [ + [encode('C1-burst'), 20], + [encode('C2-burst'), 20], + [encode('C3-after-pause'), 150], +] +export const TEST14_STREAM_A_EXPECTED = concatBytes( + TEST14_STREAM_A_CHUNKS.map(([chunk]) => chunk), +) +export const TEST14_STREAM_B_EXPECTED = concatBytes( + TEST14_STREAM_B_CHUNKS.map(([chunk]) => chunk), +) +export const TEST14_STREAM_C_EXPECTED = concatBytes( + TEST14_STREAM_C_CHUNKS.map(([chunk]) => chunk), +) + +// Test 12: Interleaved multiplexing - two streams with variable delays +export const interleavedStreamsFn = createServerFn().handler(async () => { + const streamA = createVariableDelayStream(TEST12_STREAM_A_CHUNKS) + const streamB = createVariableDelayStream(TEST12_STREAM_B_CHUNKS) + + return { + message: 'Interleaved streams test', + streamA: new RawStream(streamA), + streamB: new RawStream(streamB), + } +}) + +// Test 13: Burst-pause-burst pattern +export const burstPauseBurstFn = createServerFn().handler(async () => { + const stream = createVariableDelayStream(TEST13_CHUNKS) + + return { + message: 'Burst-pause-burst test', + data: new RawStream(stream), + } +}) + +// Test 14: Three concurrent streams +export const threeStreamsFn = createServerFn().handler(async () => { + const streamA = createVariableDelayStream(TEST14_STREAM_A_CHUNKS) + const streamB = createVariableDelayStream(TEST14_STREAM_B_CHUNKS) + const streamC = createVariableDelayStream(TEST14_STREAM_C_CHUNKS) + + return { + message: 'Three concurrent streams test', + fast: new RawStream(streamA), + slow: new RawStream(streamB), + burst: new RawStream(streamC), + } +}) + +// ============================================================================ +// EDGE CASE TESTS +// ============================================================================ + +// Test 15: Empty stream (zero bytes) +export const emptyStreamFn = createServerFn().handler(async () => { + // Stream that immediately closes with no data + const stream = new ReadableStream({ + start(controller) { + controller.close() + }, + }) + + return { + message: 'Empty stream test', + data: new RawStream(stream), + } +}) + +// Test 16: Stream that errors mid-flight +export const errorStreamFn = createServerFn().handler(async () => { + // Stream that sends some data then errors + const stream = new ReadableStream({ + async start(controller) { + controller.enqueue(encode('chunk-before-error')) + await new Promise((resolve) => setTimeout(resolve, 50)) + controller.error(new Error('Intentional stream error')) + }, + }) + + return { + message: 'Error stream test', + data: new RawStream(stream), + } +}) + +// ============================================================================ +// LATE RAWSTREAM TESTS - RawStream inside Promise (discovered after initial serialization) +// ============================================================================ + +// Expected data for late stream tests +export const LATE_STREAM_CHUNKS = [ + encode('late-1'), + encode('late-2'), + encode('late-3'), +] +export const LATE_STREAM_EXPECTED = concatBytes(LATE_STREAM_CHUNKS) + +export const LATE_STREAM_A_CHUNKS = [encode('lateA-1'), encode('lateA-2')] +export const LATE_STREAM_A_EXPECTED = concatBytes(LATE_STREAM_A_CHUNKS) + +export const LATE_STREAM_B_CHUNKS = [encode('lateB-1'), encode('lateB-2')] +export const LATE_STREAM_B_EXPECTED = concatBytes(LATE_STREAM_B_CHUNKS) + +export const IMMEDIATE_STREAM_CHUNKS = [ + encode('immediate-1'), + encode('immediate-2'), +] +export const IMMEDIATE_STREAM_EXPECTED = concatBytes(IMMEDIATE_STREAM_CHUNKS) + +// Test 17: Single late RawStream (Promise) +// The RawStream is wrapped in a Promise, so it's not discovered during initial serialization +export const lateRawStreamFn = createServerFn().handler(async () => { + // Promise that resolves to a RawStream after a delay + const lateStream = new Promise((resolve) => { + setTimeout(() => { + const stream = createDelayedStream(LATE_STREAM_CHUNKS, 30) + resolve(new RawStream(stream)) + }, 100) + }) + + return { + message: 'Late stream test', + lateData: lateStream, + } +}) + +// Test 18: Multiple late RawStreams with different delays +export const multipleLateStreamsFn = createServerFn().handler(async () => { + // Two Promises resolving to RawStreams at different times + const lateStreamA = new Promise((resolve) => { + setTimeout(() => { + const stream = createDelayedStream(LATE_STREAM_A_CHUNKS, 20) + resolve(new RawStream(stream)) + }, 50) + }) + + const lateStreamB = new Promise((resolve) => { + setTimeout(() => { + const stream = createDelayedStream(LATE_STREAM_B_CHUNKS, 20) + resolve(new RawStream(stream)) + }, 150) + }) + + return { + message: 'Multiple late streams test', + streamA: lateStreamA, + streamB: lateStreamB, + } +}) + +// Test 19: Mixed immediate and late RawStreams +// One RawStream is immediate (discovered during initial serialization) +// One is wrapped in Promise (discovered after initial serialization) +export const mixedImmediateLateFn = createServerFn().handler(async () => { + // Immediate RawStream - discovered during initial serialization + const immediateStream = createDelayedStream(IMMEDIATE_STREAM_CHUNKS, 30) + + // Late RawStream - wrapped in Promise, discovered after initial serialization + const lateStream = new Promise((resolve) => { + setTimeout(() => { + const stream = createDelayedStream(LATE_STREAM_CHUNKS, 30) + resolve(new RawStream(stream)) + }, 100) + }) + + return { + message: 'Mixed immediate and late test', + immediate: new RawStream(immediateStream), + late: lateStream, + } +}) + +// Helpers for consuming streams (exported for use in components) +// Note: RawStream is the marker class used in loaders/server functions, +// but after SSR deserialization it becomes ReadableStream. +// We accept both types to handle the TypeScript mismatch. +export function createStreamConsumer() { + const decoder = new TextDecoder() + + return async function consumeStream( + stream: ReadableStream | RawStream, + ): Promise { + // Handle both RawStream (from type system) and ReadableStream (runtime) + const actualStream = + stream instanceof RawStream + ? stream.stream + : (stream as ReadableStream) + const reader = actualStream.getReader() + const chunks: Array = [] + + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (true) { + const { done, value } = await reader.read() + if (done) break + chunks.push(decoder.decode(value, { stream: true })) + } + + return chunks.join('') + } +} + +export async function consumeBinaryStream( + stream: ReadableStream | RawStream, +): Promise { + // Handle both RawStream (from type system) and ReadableStream (runtime) + const actualStream = + stream instanceof RawStream + ? stream.stream + : (stream as ReadableStream) + const reader = actualStream.getReader() + let totalBytes = 0 + + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (true) { + const { done, value } = await reader.read() + if (done) break + totalBytes += value.length + } + + return totalBytes +} + +// Helper to collect all bytes from a stream +export async function collectBytes( + stream: ReadableStream | RawStream, +): Promise { + const actualStream = + stream instanceof RawStream + ? stream.stream + : (stream as ReadableStream) + const reader = actualStream.getReader() + const chunks: Array = [] + let totalLength = 0 + + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (true) { + const { done, value } = await reader.read() + if (done) break + chunks.push(value) + totalLength += value.length + } + + const result = new Uint8Array(totalLength) + let pos = 0 + for (const chunk of chunks) { + result.set(chunk, pos) + pos += chunk.length + } + return result +} + +// Compare two Uint8Arrays byte-by-byte +export function compareBytes( + actual: Uint8Array, + expected: Uint8Array, +): { + match: boolean + mismatchIndex: number | null + actualLength: number + expectedLength: number +} { + if (actual.length !== expected.length) { + return { + match: false, + mismatchIndex: -1, // -1 indicates length mismatch + actualLength: actual.length, + expectedLength: expected.length, + } + } + for (let i = 0; i < actual.length; i++) { + if (actual[i] !== expected[i]) { + return { + match: false, + mismatchIndex: i, + actualLength: actual.length, + expectedLength: expected.length, + } + } + } + return { + match: true, + mismatchIndex: null, + actualLength: actual.length, + expectedLength: expected.length, + } +} diff --git a/e2e/react-start/basic/src/routeTree.gen.ts b/e2e/react-start/basic/src/routeTree.gen.ts index a4c81f99f3..b6603dd01d 100644 --- a/e2e/react-start/basic/src/routeTree.gen.ts +++ b/e2e/react-start/basic/src/routeTree.gen.ts @@ -9,83 +9,105 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' -import { Route as UsersRouteImport } from './routes/users' -import { Route as StreamRouteImport } from './routes/stream' -import { Route as ScriptsRouteImport } from './routes/scripts' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as LinksRouteImport } from './routes/links' -import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as LayoutRouteImport } from './routes/_layout' -import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' -import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' -import { Route as RedirectIndexRouteImport } from './routes/redirect/index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' -import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' -import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' -import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' -import { Route as NotFoundViaHeadRouteImport } from './routes/not-found/via-head' -import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' -import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' -import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as AsyncScriptsRouteImport } from './routes/async-scripts' +import { Route as AuthDocsRouteImport } from './routes/auth-docs' +import { Route as ClientOnlyRouteImport } from './routes/client-only' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as ExecutionLocalRouteImport } from './routes/execution-local' +import { Route as ExecutionRpcRouteImport } from './routes/execution-rpc' +import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' +import { Route as LinksRouteImport } from './routes/links' +import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' +import { Route as PlainTsTypeAssertionRouteImport } from './routes/plain-ts-type-assertion' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as PrimitiveBeforeloadErrorRouteImport } from './routes/primitive-beforeload-error' +import { Route as RawStreamRouteImport } from './routes/raw-stream' +import { Route as ScriptsRouteImport } from './routes/scripts' +import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' +import { Route as SpecialCharsRouteRouteImport } from './routes/specialChars/route' +import { Route as StreamRouteImport } from './routes/stream' +import { Route as TypeOnlyReexportRouteImport } from './routes/type-only-reexport' +import { Route as UsersRouteImport } from './routes/users' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' -import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' -import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as AuthDocsPrivateRouteImport } from './routes/auth-docs.private' +import { Route as Issue6221DashboardRouteImport } from './routes/issue-6221.dashboard' +import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' +import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' +import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' +import { Route as NotFoundDeepRouteRouteImport } from './routes/not-found/deep/route' +import { Route as NotFoundParentBoundaryRouteRouteImport } from './routes/not-found/parent-boundary/route' +import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' +import { Route as NotFoundViaBeforeLoadTargetRootRouteImport } from './routes/not-found/via-beforeLoad-target-root' +import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as RawStreamIndexRouteImport } from './routes/raw-stream/index' +import { Route as RawStreamClientCallRouteImport } from './routes/raw-stream/client-call' +import { Route as RawStreamSsrBinaryHintRouteImport } from './routes/raw-stream/ssr-binary-hint' +import { Route as RawStreamSsrMixedRouteImport } from './routes/raw-stream/ssr-mixed' +import { Route as RawStreamSsrMultipleRouteImport } from './routes/raw-stream/ssr-multiple' +import { Route as RawStreamSsrSingleRouteImport } from './routes/raw-stream/ssr-single' +import { Route as RawStreamSsrTextHintRouteImport } from './routes/raw-stream/ssr-text-hint' +import { Route as RedirectIndexRouteImport } from './routes/redirect/index' +import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' +import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' +import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' +import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' +import { Route as SpecialCharsParamRouteImport } from './routes/specialChars/$param' +import { Route as SpecialCharsHashRouteImport } from './routes/specialChars/hash' +import { Route as SpecialCharsMalformedRouteRouteImport } from './routes/specialChars/malformed/route' +import { Route as SpecialCharsSearchRouteImport } from './routes/specialChars/search' +import { Route as SpecialCharsChar45824Char54620Char48124Char44397RouteImport } from './routes/specialChars/대한민국' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as RedirectTargetServerFnIndexRouteImport } from './routes/redirect/$target/serverFn/index' -import { Route as RedirectTargetServerFnViaUseServerFnRouteImport } from './routes/redirect/$target/serverFn/via-useServerFn' -import { Route as RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' -import { Route as RedirectTargetServerFnViaBeforeLoadRouteImport } from './routes/redirect/$target/serverFn/via-beforeLoad' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as Issue6221ArticleIdRouteImport } from './routes/issue-6221.article.$id' +import { Route as NotFoundDeepIndexRouteImport } from './routes/not-found/deep/index' +import { Route as NotFoundDeepBRouteRouteImport } from './routes/not-found/deep/b/route' +import { Route as NotFoundParentBoundaryIndexRouteImport } from './routes/not-found/parent-boundary/index' +import { Route as NotFoundParentBoundaryViaBeforeLoadRouteImport } from './routes/not-found/parent-boundary/via-beforeLoad' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' +import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' +import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' +import { Route as SpecialCharsMalformedParamRouteImport } from './routes/specialChars/malformed/$param' +import { Route as SpecialCharsMalformedSearchRouteImport } from './routes/specialChars/malformed/search' import { Route as FooBarQuxHereRouteImport } from './routes/foo/$bar/$qux/_here' +import { Route as NotFoundDeepBCRouteRouteImport } from './routes/not-found/deep/b/c/route' +import { Route as RedirectTargetServerFnIndexRouteImport } from './routes/redirect/$target/serverFn/index' +import { Route as RedirectTargetServerFnViaBeforeLoadRouteImport } from './routes/redirect/$target/serverFn/via-beforeLoad' +import { Route as RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' +import { Route as RedirectTargetServerFnViaUseServerFnRouteImport } from './routes/redirect/$target/serverFn/via-useServerFn' import { Route as FooBarQuxHereIndexRouteImport } from './routes/foo/$bar/$qux/_here/index' +import { Route as NotFoundDeepBCDRouteImport } from './routes/not-found/deep/b/c/d' -const Char45824Char54620Char48124Char44397Route = - Char45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => rootRouteImport, - } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const StreamRoute = StreamRouteImport.update({ - id: '/stream', - path: '/stream', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const ScriptsRoute = ScriptsRouteImport.update({ - id: '/scripts', - path: '/scripts', +const AsyncScriptsRoute = AsyncScriptsRouteImport.update({ + id: '/async-scripts', + path: '/async-scripts', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const AuthDocsRoute = AuthDocsRouteImport.update({ + id: '/auth-docs', + path: '/auth-docs', getParentRoute: () => rootRouteImport, } as any) -const LinksRoute = LinksRouteImport.update({ - id: '/links', - path: '/links', - getParentRoute: () => rootRouteImport, -} as any) -const InlineScriptsRoute = InlineScriptsRouteImport.update({ - id: '/inline-scripts', - path: '/inline-scripts', +const ClientOnlyRoute = ClientOnlyRouteImport.update({ + id: '/client-only', + path: '/client-only', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -93,13 +115,24 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const ExecutionLocalRoute = ExecutionLocalRouteImport.update({ + id: '/execution-local', + path: '/execution-local', getParentRoute: () => rootRouteImport, } as any) -const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ - id: '/search-params', - path: '/search-params', +const ExecutionRpcRoute = ExecutionRpcRouteImport.update({ + id: '/execution-rpc', + path: '/execution-rpc', + getParentRoute: () => rootRouteImport, +} as any) +const InlineScriptsRoute = InlineScriptsRouteImport.update({ + id: '/inline-scripts', + path: '/inline-scripts', + getParentRoute: () => rootRouteImport, +} as any) +const LinksRoute = LinksRouteImport.update({ + id: '/links', + path: '/links', getParentRoute: () => rootRouteImport, } as any) const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ @@ -107,35 +140,75 @@ const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ path: '/not-found', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PlainTsTypeAssertionRoute = PlainTsTypeAssertionRouteImport.update({ + id: '/plain-ts-type-assertion', + path: '/plain-ts-type-assertion', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SearchParamsRouteRoute, -} as any) -const RedirectIndexRoute = RedirectIndexRouteImport.update({ - id: '/redirect/', - path: '/redirect/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, +const PrimitiveBeforeloadErrorRoute = + PrimitiveBeforeloadErrorRouteImport.update({ + id: '/primitive-beforeload-error', + path: '/primitive-beforeload-error', + getParentRoute: () => rootRouteImport, + } as any) +const RawStreamRoute = RawStreamRouteImport.update({ + id: '/raw-stream', + path: '/raw-stream', + getParentRoute: () => rootRouteImport, } as any) -const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NotFoundRouteRoute, +const ScriptsRoute = ScriptsRouteImport.update({ + id: '/scripts', + path: '/scripts', + getParentRoute: () => rootRouteImport, +} as any) +const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ + id: '/search-params', + path: '/search-params', + getParentRoute: () => rootRouteImport, +} as any) +const SpecialCharsRouteRoute = SpecialCharsRouteRouteImport.update({ + id: '/specialChars', + path: '/specialChars', + getParentRoute: () => rootRouteImport, +} as any) +const StreamRoute = StreamRouteImport.update({ + id: '/stream', + path: '/stream', + getParentRoute: () => rootRouteImport, +} as any) +const TypeOnlyReexportRoute = TypeOnlyReexportRouteImport.update({ + id: '/type-only-reexport', + path: '/type-only-reexport', + getParentRoute: () => rootRouteImport, +} as any) +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, +} as any) +const AuthDocsPrivateRoute = AuthDocsPrivateRouteImport.update({ + id: '/private', + path: '/private', + getParentRoute: () => AuthDocsRoute, +} as any) +const Issue6221DashboardRoute = Issue6221DashboardRouteImport.update({ + id: '/issue-6221/dashboard', + path: '/issue-6221/dashboard', + getParentRoute: () => rootRouteImport, } as any) const MultiCookieRedirectIndexRoute = MultiCookieRedirectIndexRouteImport.update({ @@ -143,10 +216,108 @@ const MultiCookieRedirectIndexRoute = path: '/multi-cookie-redirect/', getParentRoute: () => rootRouteImport, } as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, +const MultiCookieRedirectTargetRoute = + MultiCookieRedirectTargetRouteImport.update({ + id: '/multi-cookie-redirect/target', + path: '/multi-cookie-redirect/target', + getParentRoute: () => rootRouteImport, + } as any) +const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NotFoundRouteRoute, +} as any) +const NotFoundDeepRouteRoute = NotFoundDeepRouteRouteImport.update({ + id: '/deep', + path: '/deep', + getParentRoute: () => NotFoundRouteRoute, +} as any) +const NotFoundParentBoundaryRouteRoute = + NotFoundParentBoundaryRouteRouteImport.update({ + id: '/parent-boundary', + path: '/parent-boundary', + getParentRoute: () => NotFoundRouteRoute, + } as any) +const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', + getParentRoute: () => NotFoundRouteRoute, +} as any) +const NotFoundViaBeforeLoadTargetRootRoute = + NotFoundViaBeforeLoadTargetRootRouteImport.update({ + id: '/via-beforeLoad-target-root', + path: '/via-beforeLoad-target-root', + getParentRoute: () => NotFoundRouteRoute, + } as any) +const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', + getParentRoute: () => NotFoundRouteRoute, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const RawStreamIndexRoute = RawStreamIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamClientCallRoute = RawStreamClientCallRouteImport.update({ + id: '/client-call', + path: '/client-call', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrBinaryHintRoute = RawStreamSsrBinaryHintRouteImport.update({ + id: '/ssr-binary-hint', + path: '/ssr-binary-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMixedRoute = RawStreamSsrMixedRouteImport.update({ + id: '/ssr-mixed', + path: '/ssr-mixed', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMultipleRoute = RawStreamSsrMultipleRouteImport.update({ + id: '/ssr-multiple', + path: '/ssr-multiple', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrSingleRoute = RawStreamSsrSingleRouteImport.update({ + id: '/ssr-single', + path: '/ssr-single', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrTextHintRoute = RawStreamSsrTextHintRouteImport.update({ + id: '/ssr-text-hint', + path: '/ssr-text-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectTargetRoute = RedirectTargetRouteImport.update({ + id: '/redirect/$target', + path: '/redirect/$target', + getParentRoute: () => rootRouteImport, +} as any) +const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SearchParamsRouteRoute, +} as any) +const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ + id: '/default', + path: '/default', + getParentRoute: () => SearchParamsRouteRoute, } as any) const SearchParamsLoaderThrowsRedirectRoute = SearchParamsLoaderThrowsRedirectRouteImport.update({ @@ -154,86 +325,127 @@ const SearchParamsLoaderThrowsRedirectRoute = path: '/loader-throws-redirect', getParentRoute: () => SearchParamsRouteRoute, } as any) -const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ - id: '/default', - path: '/default', - getParentRoute: () => SearchParamsRouteRoute, +const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const RedirectTargetRoute = RedirectTargetRouteImport.update({ - id: '/redirect/$target', - path: '/redirect/$target', - getParentRoute: () => rootRouteImport, +const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ + id: '/hash', + path: '/hash', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', - getParentRoute: () => NotFoundRouteRoute, -} as any) -const NotFoundViaHeadRoute = NotFoundViaHeadRouteImport.update({ - id: '/via-head', - path: '/via-head', - getParentRoute: () => NotFoundRouteRoute, -} as any) -const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', - getParentRoute: () => NotFoundRouteRoute, -} as any) -const MultiCookieRedirectTargetRoute = - MultiCookieRedirectTargetRouteImport.update({ - id: '/multi-cookie-redirect/target', - path: '/multi-cookie-redirect/target', - getParentRoute: () => rootRouteImport, +const SpecialCharsMalformedRouteRoute = + SpecialCharsMalformedRouteRouteImport.update({ + id: '/malformed', + path: '/malformed', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsRouteRoute, +} as any) +const SpecialCharsChar45824Char54620Char48124Char44397Route = + SpecialCharsChar45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => SpecialCharsRouteRoute, + } as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const Issue6221ArticleIdRoute = Issue6221ArticleIdRouteImport.update({ + id: '/issue-6221/article/$id', + path: '/issue-6221/article/$id', getParentRoute: () => rootRouteImport, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const NotFoundDeepIndexRoute = NotFoundDeepIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NotFoundDeepRouteRoute, +} as any) +const NotFoundDeepBRouteRoute = NotFoundDeepBRouteRouteImport.update({ + id: '/b', + path: '/b', + getParentRoute: () => NotFoundDeepRouteRoute, +} as any) +const NotFoundParentBoundaryIndexRoute = + NotFoundParentBoundaryIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NotFoundParentBoundaryRouteRoute, + } as any) +const NotFoundParentBoundaryViaBeforeLoadRoute = + NotFoundParentBoundaryViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', + getParentRoute: () => NotFoundParentBoundaryRouteRoute, + } as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, } as any) const RedirectTargetIndexRoute = RedirectTargetIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', - getParentRoute: () => RedirectTargetRoute, -} as any) const RedirectTargetViaBeforeLoadRoute = RedirectTargetViaBeforeLoadRouteImport.update({ id: '/via-beforeLoad', path: '/via-beforeLoad', getParentRoute: () => RedirectTargetRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', + getParentRoute: () => RedirectTargetRoute, +} as any) +const SpecialCharsMalformedParamRoute = + SpecialCharsMalformedParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsMalformedRouteRoute, + } as any) +const SpecialCharsMalformedSearchRoute = + SpecialCharsMalformedSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsMalformedRouteRoute, + } as any) +const FooBarQuxHereRoute = FooBarQuxHereRouteImport.update({ + id: '/foo/$bar/$qux/_here', + path: '/foo/$bar/$qux', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, -} as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, -} as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const NotFoundDeepBCRouteRoute = NotFoundDeepBCRouteRouteImport.update({ + id: '/c', + path: '/c', + getParentRoute: () => NotFoundDeepBRouteRoute, } as any) const RedirectTargetServerFnIndexRoute = RedirectTargetServerFnIndexRouteImport.update({ @@ -241,111 +453,176 @@ const RedirectTargetServerFnIndexRoute = path: '/serverFn/', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetServerFnViaUseServerFnRoute = - RedirectTargetServerFnViaUseServerFnRouteImport.update({ - id: '/serverFn/via-useServerFn', - path: '/serverFn/via-useServerFn', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetServerFnViaLoaderRoute = - RedirectTargetServerFnViaLoaderRouteImport.update({ - id: '/serverFn/via-loader', - path: '/serverFn/via-loader', - getParentRoute: () => RedirectTargetRoute, - } as any) const RedirectTargetServerFnViaBeforeLoadRoute = RedirectTargetServerFnViaBeforeLoadRouteImport.update({ id: '/serverFn/via-beforeLoad', path: '/serverFn/via-beforeLoad', getParentRoute: () => RedirectTargetRoute, } as any) -const FooBarQuxHereRoute = FooBarQuxHereRouteImport.update({ - id: '/foo/$bar/$qux/_here', - path: '/foo/$bar/$qux', - getParentRoute: () => rootRouteImport, -} as any) +const RedirectTargetServerFnViaLoaderRoute = + RedirectTargetServerFnViaLoaderRouteImport.update({ + id: '/serverFn/via-loader', + path: '/serverFn/via-loader', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetServerFnViaUseServerFnRoute = + RedirectTargetServerFnViaUseServerFnRouteImport.update({ + id: '/serverFn/via-useServerFn', + path: '/serverFn/via-useServerFn', + getParentRoute: () => RedirectTargetRoute, + } as any) const FooBarQuxHereIndexRoute = FooBarQuxHereIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => FooBarQuxHereRoute, } as any) +const NotFoundDeepBCDRoute = NotFoundDeepBCDRouteImport.update({ + id: '/d', + path: '/d', + getParentRoute: () => NotFoundDeepBCRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute '/not-found': typeof NotFoundRouteRouteWithChildren '/search-params': typeof SearchParamsRouteRouteWithChildren + '/specialChars': typeof SpecialCharsRouteRouteWithChildren + '/async-scripts': typeof AsyncScriptsRoute + '/auth-docs': typeof AuthDocsRouteWithChildren + '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute + '/execution-local': typeof ExecutionLocalRoute + '/execution-rpc': typeof ExecutionRpcRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute + '/plain-ts-type-assertion': typeof PlainTsTypeAssertionRoute '/posts': typeof PostsRouteWithChildren + '/primitive-beforeload-error': typeof PrimitiveBeforeloadErrorRoute + '/raw-stream': typeof RawStreamRouteWithChildren '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute + '/type-only-reexport': typeof TypeOnlyReexportRoute '/users': typeof UsersRouteWithChildren - '/대한민국': typeof Char45824Char54620Char48124Char44397Route + '/not-found/deep': typeof NotFoundDeepRouteRouteWithChildren + '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren + '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren + '/auth-docs/private': typeof AuthDocsPrivateRoute + '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute - '/not-found/via-head': typeof NotFoundViaHeadRoute + '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute '/not-found/via-loader': typeof NotFoundViaLoaderRoute '/posts/$postId': typeof PostsPostIdRoute + '/raw-stream/client-call': typeof RawStreamClientCallRoute + '/raw-stream/ssr-binary-hint': typeof RawStreamSsrBinaryHintRoute + '/raw-stream/ssr-mixed': typeof RawStreamSsrMixedRoute + '/raw-stream/ssr-multiple': typeof RawStreamSsrMultipleRoute + '/raw-stream/ssr-single': typeof RawStreamSsrSingleRoute + '/raw-stream/ssr-text-hint': typeof RawStreamSsrTextHintRoute '/redirect/$target': typeof RedirectTargetRouteWithChildren '/search-params/default': typeof SearchParamsDefaultRoute '/search-params/loader-throws-redirect': typeof SearchParamsLoaderThrowsRedirectRoute + '/specialChars/$param': typeof SpecialCharsParamRoute + '/specialChars/hash': typeof SpecialCharsHashRoute + '/specialChars/search': typeof SpecialCharsSearchRoute + '/specialChars/대한민국': typeof SpecialCharsChar45824Char54620Char48124Char44397Route '/users/$userId': typeof UsersUserIdRoute - '/multi-cookie-redirect': typeof MultiCookieRedirectIndexRoute + '/multi-cookie-redirect/': typeof MultiCookieRedirectIndexRoute '/not-found/': typeof NotFoundIndexRoute '/posts/': typeof PostsIndexRoute - '/redirect': typeof RedirectIndexRoute + '/raw-stream/': typeof RawStreamIndexRoute + '/redirect/': typeof RedirectIndexRoute '/search-params/': typeof SearchParamsIndexRoute '/users/': typeof UsersIndexRoute + '/not-found/deep/b': typeof NotFoundDeepBRouteRouteWithChildren '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute + '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute + '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute '/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute + '/specialChars/malformed/$param': typeof SpecialCharsMalformedParamRoute + '/specialChars/malformed/search': typeof SpecialCharsMalformedSearchRoute + '/not-found/deep/': typeof NotFoundDeepIndexRoute + '/not-found/parent-boundary/': typeof NotFoundParentBoundaryIndexRoute '/redirect/$target/': typeof RedirectTargetIndexRoute + '/not-found/deep/b/c': typeof NotFoundDeepBCRouteRouteWithChildren '/foo/$bar/$qux': typeof FooBarQuxHereRouteWithChildren '/redirect/$target/serverFn/via-beforeLoad': typeof RedirectTargetServerFnViaBeforeLoadRoute '/redirect/$target/serverFn/via-loader': typeof RedirectTargetServerFnViaLoaderRoute '/redirect/$target/serverFn/via-useServerFn': typeof RedirectTargetServerFnViaUseServerFnRoute - '/redirect/$target/serverFn': typeof RedirectTargetServerFnIndexRoute + '/redirect/$target/serverFn/': typeof RedirectTargetServerFnIndexRoute + '/not-found/deep/b/c/d': typeof NotFoundDeepBCDRoute '/foo/$bar/$qux/': typeof FooBarQuxHereIndexRoute } export interface FileRoutesByTo { '/': typeof IndexRoute + '/specialChars': typeof SpecialCharsRouteRouteWithChildren + '/async-scripts': typeof AsyncScriptsRoute + '/auth-docs': typeof AuthDocsRouteWithChildren + '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute + '/execution-local': typeof ExecutionLocalRoute + '/execution-rpc': typeof ExecutionRpcRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute + '/plain-ts-type-assertion': typeof PlainTsTypeAssertionRoute + '/primitive-beforeload-error': typeof PrimitiveBeforeloadErrorRoute '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute - '/대한민국': typeof Char45824Char54620Char48124Char44397Route + '/type-only-reexport': typeof TypeOnlyReexportRoute + '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren + '/auth-docs/private': typeof AuthDocsPrivateRoute + '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute - '/not-found/via-head': typeof NotFoundViaHeadRoute + '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute '/not-found/via-loader': typeof NotFoundViaLoaderRoute '/posts/$postId': typeof PostsPostIdRoute + '/raw-stream/client-call': typeof RawStreamClientCallRoute + '/raw-stream/ssr-binary-hint': typeof RawStreamSsrBinaryHintRoute + '/raw-stream/ssr-mixed': typeof RawStreamSsrMixedRoute + '/raw-stream/ssr-multiple': typeof RawStreamSsrMultipleRoute + '/raw-stream/ssr-single': typeof RawStreamSsrSingleRoute + '/raw-stream/ssr-text-hint': typeof RawStreamSsrTextHintRoute '/search-params/default': typeof SearchParamsDefaultRoute '/search-params/loader-throws-redirect': typeof SearchParamsLoaderThrowsRedirectRoute + '/specialChars/$param': typeof SpecialCharsParamRoute + '/specialChars/hash': typeof SpecialCharsHashRoute + '/specialChars/search': typeof SpecialCharsSearchRoute + '/specialChars/대한민국': typeof SpecialCharsChar45824Char54620Char48124Char44397Route '/users/$userId': typeof UsersUserIdRoute '/multi-cookie-redirect': typeof MultiCookieRedirectIndexRoute '/not-found': typeof NotFoundIndexRoute '/posts': typeof PostsIndexRoute + '/raw-stream': typeof RawStreamIndexRoute '/redirect': typeof RedirectIndexRoute '/search-params': typeof SearchParamsIndexRoute '/users': typeof UsersIndexRoute + '/not-found/deep/b': typeof NotFoundDeepBRouteRouteWithChildren '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute + '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute + '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute '/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute + '/specialChars/malformed/$param': typeof SpecialCharsMalformedParamRoute + '/specialChars/malformed/search': typeof SpecialCharsMalformedSearchRoute + '/not-found/deep': typeof NotFoundDeepIndexRoute + '/not-found/parent-boundary': typeof NotFoundParentBoundaryIndexRoute '/redirect/$target': typeof RedirectTargetIndexRoute + '/not-found/deep/b/c': typeof NotFoundDeepBCRouteRouteWithChildren '/redirect/$target/serverFn/via-beforeLoad': typeof RedirectTargetServerFnViaBeforeLoadRoute '/redirect/$target/serverFn/via-loader': typeof RedirectTargetServerFnViaLoaderRoute '/redirect/$target/serverFn/via-useServerFn': typeof RedirectTargetServerFnViaUseServerFnRoute '/redirect/$target/serverFn': typeof RedirectTargetServerFnIndexRoute + '/not-found/deep/b/c/d': typeof NotFoundDeepBCDRoute '/foo/$bar/$qux': typeof FooBarQuxHereIndexRoute } export interface FileRoutesById { @@ -353,44 +630,78 @@ export interface FileRoutesById { '/': typeof IndexRoute '/not-found': typeof NotFoundRouteRouteWithChildren '/search-params': typeof SearchParamsRouteRouteWithChildren + '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/_layout': typeof LayoutRouteWithChildren + '/async-scripts': typeof AsyncScriptsRoute + '/auth-docs': typeof AuthDocsRouteWithChildren + '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute + '/execution-local': typeof ExecutionLocalRoute + '/execution-rpc': typeof ExecutionRpcRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute + '/plain-ts-type-assertion': typeof PlainTsTypeAssertionRoute '/posts': typeof PostsRouteWithChildren + '/primitive-beforeload-error': typeof PrimitiveBeforeloadErrorRoute + '/raw-stream': typeof RawStreamRouteWithChildren '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute + '/type-only-reexport': typeof TypeOnlyReexportRoute '/users': typeof UsersRouteWithChildren - '/대한민국': typeof Char45824Char54620Char48124Char44397Route + '/not-found/deep': typeof NotFoundDeepRouteRouteWithChildren + '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren + '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren + '/auth-docs/private': typeof AuthDocsPrivateRoute + '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute - '/not-found/via-head': typeof NotFoundViaHeadRoute + '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute '/not-found/via-loader': typeof NotFoundViaLoaderRoute '/posts/$postId': typeof PostsPostIdRoute + '/raw-stream/client-call': typeof RawStreamClientCallRoute + '/raw-stream/ssr-binary-hint': typeof RawStreamSsrBinaryHintRoute + '/raw-stream/ssr-mixed': typeof RawStreamSsrMixedRoute + '/raw-stream/ssr-multiple': typeof RawStreamSsrMultipleRoute + '/raw-stream/ssr-single': typeof RawStreamSsrSingleRoute + '/raw-stream/ssr-text-hint': typeof RawStreamSsrTextHintRoute '/redirect/$target': typeof RedirectTargetRouteWithChildren '/search-params/default': typeof SearchParamsDefaultRoute '/search-params/loader-throws-redirect': typeof SearchParamsLoaderThrowsRedirectRoute + '/specialChars/$param': typeof SpecialCharsParamRoute + '/specialChars/hash': typeof SpecialCharsHashRoute + '/specialChars/search': typeof SpecialCharsSearchRoute + '/specialChars/대한민국': typeof SpecialCharsChar45824Char54620Char48124Char44397Route '/users/$userId': typeof UsersUserIdRoute '/multi-cookie-redirect/': typeof MultiCookieRedirectIndexRoute '/not-found/': typeof NotFoundIndexRoute '/posts/': typeof PostsIndexRoute + '/raw-stream/': typeof RawStreamIndexRoute '/redirect/': typeof RedirectIndexRoute '/search-params/': typeof SearchParamsIndexRoute '/users/': typeof UsersIndexRoute + '/not-found/deep/b': typeof NotFoundDeepBRouteRouteWithChildren '/_layout/_layout-2/layout-a': typeof LayoutLayout2LayoutARoute '/_layout/_layout-2/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute + '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute + '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts_/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute '/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute + '/specialChars/malformed/$param': typeof SpecialCharsMalformedParamRoute + '/specialChars/malformed/search': typeof SpecialCharsMalformedSearchRoute + '/not-found/deep/': typeof NotFoundDeepIndexRoute + '/not-found/parent-boundary/': typeof NotFoundParentBoundaryIndexRoute '/redirect/$target/': typeof RedirectTargetIndexRoute + '/not-found/deep/b/c': typeof NotFoundDeepBCRouteRouteWithChildren '/foo/$bar/$qux/_here': typeof FooBarQuxHereRouteWithChildren '/redirect/$target/serverFn/via-beforeLoad': typeof RedirectTargetServerFnViaBeforeLoadRoute '/redirect/$target/serverFn/via-loader': typeof RedirectTargetServerFnViaLoaderRoute '/redirect/$target/serverFn/via-useServerFn': typeof RedirectTargetServerFnViaUseServerFnRoute '/redirect/$target/serverFn/': typeof RedirectTargetServerFnIndexRoute + '/not-found/deep/b/c/d': typeof NotFoundDeepBCDRoute '/foo/$bar/$qux/_here/': typeof FooBarQuxHereIndexRoute } export interface FileRouteTypes { @@ -399,122 +710,221 @@ export interface FileRouteTypes { | '/' | '/not-found' | '/search-params' + | '/specialChars' + | '/async-scripts' + | '/auth-docs' + | '/client-only' | '/deferred' + | '/execution-local' + | '/execution-rpc' | '/inline-scripts' | '/links' + | '/plain-ts-type-assertion' | '/posts' + | '/primitive-beforeload-error' + | '/raw-stream' | '/scripts' | '/stream' + | '/type-only-reexport' | '/users' - | '/대한민국' + | '/not-found/deep' + | '/not-found/parent-boundary' + | '/specialChars/malformed' | '/api/users' + | '/auth-docs/private' + | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' - | '/not-found/via-head' + | '/not-found/via-beforeLoad-target-root' | '/not-found/via-loader' | '/posts/$postId' + | '/raw-stream/client-call' + | '/raw-stream/ssr-binary-hint' + | '/raw-stream/ssr-mixed' + | '/raw-stream/ssr-multiple' + | '/raw-stream/ssr-single' + | '/raw-stream/ssr-text-hint' | '/redirect/$target' | '/search-params/default' | '/search-params/loader-throws-redirect' + | '/specialChars/$param' + | '/specialChars/hash' + | '/specialChars/search' + | '/specialChars/대한민국' | '/users/$userId' - | '/multi-cookie-redirect' + | '/multi-cookie-redirect/' | '/not-found/' | '/posts/' - | '/redirect' + | '/raw-stream/' + | '/redirect/' | '/search-params/' | '/users/' + | '/not-found/deep/b' | '/layout-a' | '/layout-b' | '/api/users/$id' + | '/issue-6221/article/$id' + | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' | '/redirect/$target/via-loader' + | '/specialChars/malformed/$param' + | '/specialChars/malformed/search' + | '/not-found/deep/' + | '/not-found/parent-boundary/' | '/redirect/$target/' + | '/not-found/deep/b/c' | '/foo/$bar/$qux' | '/redirect/$target/serverFn/via-beforeLoad' | '/redirect/$target/serverFn/via-loader' | '/redirect/$target/serverFn/via-useServerFn' - | '/redirect/$target/serverFn' + | '/redirect/$target/serverFn/' + | '/not-found/deep/b/c/d' | '/foo/$bar/$qux/' fileRoutesByTo: FileRoutesByTo to: | '/' + | '/specialChars' + | '/async-scripts' + | '/auth-docs' + | '/client-only' | '/deferred' + | '/execution-local' + | '/execution-rpc' | '/inline-scripts' | '/links' + | '/plain-ts-type-assertion' + | '/primitive-beforeload-error' | '/scripts' | '/stream' - | '/대한민국' + | '/type-only-reexport' + | '/specialChars/malformed' | '/api/users' + | '/auth-docs/private' + | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' - | '/not-found/via-head' + | '/not-found/via-beforeLoad-target-root' | '/not-found/via-loader' | '/posts/$postId' + | '/raw-stream/client-call' + | '/raw-stream/ssr-binary-hint' + | '/raw-stream/ssr-mixed' + | '/raw-stream/ssr-multiple' + | '/raw-stream/ssr-single' + | '/raw-stream/ssr-text-hint' | '/search-params/default' | '/search-params/loader-throws-redirect' + | '/specialChars/$param' + | '/specialChars/hash' + | '/specialChars/search' + | '/specialChars/대한민국' | '/users/$userId' | '/multi-cookie-redirect' | '/not-found' | '/posts' + | '/raw-stream' | '/redirect' | '/search-params' | '/users' + | '/not-found/deep/b' | '/layout-a' | '/layout-b' | '/api/users/$id' + | '/issue-6221/article/$id' + | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' | '/redirect/$target/via-loader' + | '/specialChars/malformed/$param' + | '/specialChars/malformed/search' + | '/not-found/deep' + | '/not-found/parent-boundary' | '/redirect/$target' + | '/not-found/deep/b/c' | '/redirect/$target/serverFn/via-beforeLoad' | '/redirect/$target/serverFn/via-loader' | '/redirect/$target/serverFn/via-useServerFn' | '/redirect/$target/serverFn' + | '/not-found/deep/b/c/d' | '/foo/$bar/$qux' id: | '__root__' | '/' | '/not-found' | '/search-params' + | '/specialChars' | '/_layout' + | '/async-scripts' + | '/auth-docs' + | '/client-only' | '/deferred' + | '/execution-local' + | '/execution-rpc' | '/inline-scripts' | '/links' + | '/plain-ts-type-assertion' | '/posts' + | '/primitive-beforeload-error' + | '/raw-stream' | '/scripts' | '/stream' + | '/type-only-reexport' | '/users' - | '/대한민국' + | '/not-found/deep' + | '/not-found/parent-boundary' + | '/specialChars/malformed' | '/_layout/_layout-2' | '/api/users' + | '/auth-docs/private' + | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' - | '/not-found/via-head' + | '/not-found/via-beforeLoad-target-root' | '/not-found/via-loader' | '/posts/$postId' + | '/raw-stream/client-call' + | '/raw-stream/ssr-binary-hint' + | '/raw-stream/ssr-mixed' + | '/raw-stream/ssr-multiple' + | '/raw-stream/ssr-single' + | '/raw-stream/ssr-text-hint' | '/redirect/$target' | '/search-params/default' | '/search-params/loader-throws-redirect' + | '/specialChars/$param' + | '/specialChars/hash' + | '/specialChars/search' + | '/specialChars/대한민국' | '/users/$userId' | '/multi-cookie-redirect/' | '/not-found/' | '/posts/' + | '/raw-stream/' | '/redirect/' | '/search-params/' | '/users/' + | '/not-found/deep/b' | '/_layout/_layout-2/layout-a' | '/_layout/_layout-2/layout-b' | '/api/users/$id' + | '/issue-6221/article/$id' + | '/not-found/parent-boundary/via-beforeLoad' | '/posts_/$postId/deep' | '/redirect/$target/via-beforeLoad' | '/redirect/$target/via-loader' + | '/specialChars/malformed/$param' + | '/specialChars/malformed/search' + | '/not-found/deep/' + | '/not-found/parent-boundary/' | '/redirect/$target/' + | '/not-found/deep/b/c' | '/foo/$bar/$qux/_here' | '/redirect/$target/serverFn/via-beforeLoad' | '/redirect/$target/serverFn/via-loader' | '/redirect/$target/serverFn/via-useServerFn' | '/redirect/$target/serverFn/' + | '/not-found/deep/b/c/d' | '/foo/$bar/$qux/_here/' fileRoutesById: FileRoutesById } @@ -522,73 +932,70 @@ export interface RootRouteChildren { IndexRoute: typeof IndexRoute NotFoundRouteRoute: typeof NotFoundRouteRouteWithChildren SearchParamsRouteRoute: typeof SearchParamsRouteRouteWithChildren + SpecialCharsRouteRoute: typeof SpecialCharsRouteRouteWithChildren LayoutRoute: typeof LayoutRouteWithChildren + AsyncScriptsRoute: typeof AsyncScriptsRoute + AuthDocsRoute: typeof AuthDocsRouteWithChildren + ClientOnlyRoute: typeof ClientOnlyRoute DeferredRoute: typeof DeferredRoute + ExecutionLocalRoute: typeof ExecutionLocalRoute + ExecutionRpcRoute: typeof ExecutionRpcRoute InlineScriptsRoute: typeof InlineScriptsRoute LinksRoute: typeof LinksRoute + PlainTsTypeAssertionRoute: typeof PlainTsTypeAssertionRoute PostsRoute: typeof PostsRouteWithChildren + PrimitiveBeforeloadErrorRoute: typeof PrimitiveBeforeloadErrorRoute + RawStreamRoute: typeof RawStreamRouteWithChildren ScriptsRoute: typeof ScriptsRoute StreamRoute: typeof StreamRoute + TypeOnlyReexportRoute: typeof TypeOnlyReexportRoute UsersRoute: typeof UsersRouteWithChildren - Char45824Char54620Char48124Char44397Route: typeof Char45824Char54620Char48124Char44397Route ApiUsersRoute: typeof ApiUsersRouteWithChildren + Issue6221DashboardRoute: typeof Issue6221DashboardRoute MultiCookieRedirectTargetRoute: typeof MultiCookieRedirectTargetRoute RedirectTargetRoute: typeof RedirectTargetRouteWithChildren MultiCookieRedirectIndexRoute: typeof MultiCookieRedirectIndexRoute RedirectIndexRoute: typeof RedirectIndexRoute + Issue6221ArticleIdRoute: typeof Issue6221ArticleIdRoute PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute FooBarQuxHereRoute: typeof FooBarQuxHereRouteWithChildren } declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/stream': { - id: '/stream' - path: '/stream' - fullPath: '/stream' - preLoaderRoute: typeof StreamRouteImport + '/async-scripts': { + id: '/async-scripts' + path: '/async-scripts' + fullPath: '/async-scripts' + preLoaderRoute: typeof AsyncScriptsRouteImport parentRoute: typeof rootRouteImport } - '/scripts': { - id: '/scripts' - path: '/scripts' - fullPath: '/scripts' - preLoaderRoute: typeof ScriptsRouteImport + '/auth-docs': { + id: '/auth-docs' + path: '/auth-docs' + fullPath: '/auth-docs' + preLoaderRoute: typeof AuthDocsRouteImport parentRoute: typeof rootRouteImport } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/links': { - id: '/links' - path: '/links' - fullPath: '/links' - preLoaderRoute: typeof LinksRouteImport - parentRoute: typeof rootRouteImport - } - '/inline-scripts': { - id: '/inline-scripts' - path: '/inline-scripts' - fullPath: '/inline-scripts' - preLoaderRoute: typeof InlineScriptsRouteImport + '/client-only': { + id: '/client-only' + path: '/client-only' + fullPath: '/client-only' + preLoaderRoute: typeof ClientOnlyRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -598,18 +1005,32 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutRouteImport + '/execution-local': { + id: '/execution-local' + path: '/execution-local' + fullPath: '/execution-local' + preLoaderRoute: typeof ExecutionLocalRouteImport parentRoute: typeof rootRouteImport } - '/search-params': { - id: '/search-params' - path: '/search-params' - fullPath: '/search-params' - preLoaderRoute: typeof SearchParamsRouteRouteImport + '/execution-rpc': { + id: '/execution-rpc' + path: '/execution-rpc' + fullPath: '/execution-rpc' + preLoaderRoute: typeof ExecutionRpcRouteImport + parentRoute: typeof rootRouteImport + } + '/inline-scripts': { + id: '/inline-scripts' + path: '/inline-scripts' + fullPath: '/inline-scripts' + preLoaderRoute: typeof InlineScriptsRouteImport + parentRoute: typeof rootRouteImport + } + '/links': { + id: '/links' + path: '/links' + fullPath: '/links' + preLoaderRoute: typeof LinksRouteImport parentRoute: typeof rootRouteImport } '/not-found': { @@ -619,40 +1040,117 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NotFoundRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' + '/plain-ts-type-assertion': { + id: '/plain-ts-type-assertion' + path: '/plain-ts-type-assertion' + fullPath: '/plain-ts-type-assertion' + preLoaderRoute: typeof PlainTsTypeAssertionRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/primitive-beforeload-error': { + id: '/primitive-beforeload-error' + path: '/primitive-beforeload-error' + fullPath: '/primitive-beforeload-error' + preLoaderRoute: typeof PrimitiveBeforeloadErrorRouteImport + parentRoute: typeof rootRouteImport + } + '/raw-stream': { + id: '/raw-stream' + path: '/raw-stream' + fullPath: '/raw-stream' + preLoaderRoute: typeof RawStreamRouteImport + parentRoute: typeof rootRouteImport + } + '/scripts': { + id: '/scripts' + path: '/scripts' + fullPath: '/scripts' + preLoaderRoute: typeof ScriptsRouteImport + parentRoute: typeof rootRouteImport + } + '/search-params': { + id: '/search-params' + path: '/search-params' + fullPath: '/search-params' + preLoaderRoute: typeof SearchParamsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/specialChars': { + id: '/specialChars' + path: '/specialChars' + fullPath: '/specialChars' + preLoaderRoute: typeof SpecialCharsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/stream': { + id: '/stream' + path: '/stream' + fullPath: '/stream' + preLoaderRoute: typeof StreamRouteImport + parentRoute: typeof rootRouteImport + } + '/type-only-reexport': { + id: '/type-only-reexport' + path: '/type-only-reexport' + fullPath: '/type-only-reexport' + preLoaderRoute: typeof TypeOnlyReexportRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/auth-docs/private': { + id: '/auth-docs/private' + path: '/private' + fullPath: '/auth-docs/private' + preLoaderRoute: typeof AuthDocsPrivateRouteImport + parentRoute: typeof AuthDocsRoute } - '/search-params/': { - id: '/search-params/' - path: '/' - fullPath: '/search-params/' - preLoaderRoute: typeof SearchParamsIndexRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectIndexRouteImport + '/issue-6221/dashboard': { + id: '/issue-6221/dashboard' + path: '/issue-6221/dashboard' + fullPath: '/issue-6221/dashboard' + preLoaderRoute: typeof Issue6221DashboardRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute + '/multi-cookie-redirect/': { + id: '/multi-cookie-redirect/' + path: '/multi-cookie-redirect' + fullPath: '/multi-cookie-redirect/' + preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/multi-cookie-redirect/target': { + id: '/multi-cookie-redirect/target' + path: '/multi-cookie-redirect/target' + fullPath: '/multi-cookie-redirect/target' + preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport + parentRoute: typeof rootRouteImport } '/not-found/': { id: '/not-found/' @@ -661,60 +1159,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NotFoundIndexRouteImport parentRoute: typeof NotFoundRouteRoute } - '/multi-cookie-redirect/': { - id: '/multi-cookie-redirect/' - path: '/multi-cookie-redirect' - fullPath: '/multi-cookie-redirect' - preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/search-params/loader-throws-redirect': { - id: '/search-params/loader-throws-redirect' - path: '/loader-throws-redirect' - fullPath: '/search-params/loader-throws-redirect' - preLoaderRoute: typeof SearchParamsLoaderThrowsRedirectRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/search-params/default': { - id: '/search-params/default' - path: '/default' - fullPath: '/search-params/default' - preLoaderRoute: typeof SearchParamsDefaultRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/redirect/$target': { - id: '/redirect/$target' - path: '/redirect/$target' - fullPath: '/redirect/$target' - preLoaderRoute: typeof RedirectTargetRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/not-found/via-loader': { - id: '/not-found/via-loader' - path: '/via-loader' - fullPath: '/not-found/via-loader' - preLoaderRoute: typeof NotFoundViaLoaderRouteImport + '/not-found/deep': { + id: '/not-found/deep' + path: '/deep' + fullPath: '/not-found/deep' + preLoaderRoute: typeof NotFoundDeepRouteRouteImport parentRoute: typeof NotFoundRouteRoute } - '/not-found/via-head': { - id: '/not-found/via-head' - path: '/via-head' - fullPath: '/not-found/via-head' - preLoaderRoute: typeof NotFoundViaHeadRouteImport + '/not-found/parent-boundary': { + id: '/not-found/parent-boundary' + path: '/parent-boundary' + fullPath: '/not-found/parent-boundary' + preLoaderRoute: typeof NotFoundParentBoundaryRouteRouteImport parentRoute: typeof NotFoundRouteRoute } '/not-found/via-beforeLoad': { @@ -724,26 +1180,229 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport parentRoute: typeof NotFoundRouteRoute } - '/multi-cookie-redirect/target': { - id: '/multi-cookie-redirect/target' - path: '/multi-cookie-redirect/target' - fullPath: '/multi-cookie-redirect/target' - preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport + '/not-found/via-beforeLoad-target-root': { + id: '/not-found/via-beforeLoad-target-root' + path: '/via-beforeLoad-target-root' + fullPath: '/not-found/via-beforeLoad-target-root' + preLoaderRoute: typeof NotFoundViaBeforeLoadTargetRootRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/not-found/via-loader': { + id: '/not-found/via-loader' + path: '/via-loader' + fullPath: '/not-found/via-loader' + preLoaderRoute: typeof NotFoundViaLoaderRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/raw-stream/': { + id: '/raw-stream/' + path: '/' + fullPath: '/raw-stream/' + preLoaderRoute: typeof RawStreamIndexRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/client-call': { + id: '/raw-stream/client-call' + path: '/client-call' + fullPath: '/raw-stream/client-call' + preLoaderRoute: typeof RawStreamClientCallRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-binary-hint': { + id: '/raw-stream/ssr-binary-hint' + path: '/ssr-binary-hint' + fullPath: '/raw-stream/ssr-binary-hint' + preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-mixed': { + id: '/raw-stream/ssr-mixed' + path: '/ssr-mixed' + fullPath: '/raw-stream/ssr-mixed' + preLoaderRoute: typeof RawStreamSsrMixedRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-multiple': { + id: '/raw-stream/ssr-multiple' + path: '/ssr-multiple' + fullPath: '/raw-stream/ssr-multiple' + preLoaderRoute: typeof RawStreamSsrMultipleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-single': { + id: '/raw-stream/ssr-single' + path: '/ssr-single' + fullPath: '/raw-stream/ssr-single' + preLoaderRoute: typeof RawStreamSsrSingleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-text-hint': { + id: '/raw-stream/ssr-text-hint' + path: '/ssr-text-hint' + fullPath: '/raw-stream/ssr-text-hint' + preLoaderRoute: typeof RawStreamSsrTextHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport parentRoute: typeof rootRouteImport } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/redirect/$target': { + id: '/redirect/$target' + path: '/redirect/$target' + fullPath: '/redirect/$target' + preLoaderRoute: typeof RedirectTargetRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute + '/search-params/': { + id: '/search-params/' + path: '/' + fullPath: '/search-params/' + preLoaderRoute: typeof SearchParamsIndexRouteImport + parentRoute: typeof SearchParamsRouteRoute + } + '/search-params/default': { + id: '/search-params/default' + path: '/default' + fullPath: '/search-params/default' + preLoaderRoute: typeof SearchParamsDefaultRouteImport + parentRoute: typeof SearchParamsRouteRoute + } + '/search-params/loader-throws-redirect': { + id: '/search-params/loader-throws-redirect' + path: '/loader-throws-redirect' + fullPath: '/search-params/loader-throws-redirect' + preLoaderRoute: typeof SearchParamsLoaderThrowsRedirectRouteImport + parentRoute: typeof SearchParamsRouteRoute + } + '/specialChars/$param': { + id: '/specialChars/$param' + path: '/$param' + fullPath: '/specialChars/$param' + preLoaderRoute: typeof SpecialCharsParamRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/hash': { + id: '/specialChars/hash' + path: '/hash' + fullPath: '/specialChars/hash' + preLoaderRoute: typeof SpecialCharsHashRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/malformed': { + id: '/specialChars/malformed' + path: '/malformed' + fullPath: '/specialChars/malformed' + preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/search': { + id: '/specialChars/search' + path: '/search' + fullPath: '/specialChars/search' + preLoaderRoute: typeof SpecialCharsSearchRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/대한민국': { + id: '/specialChars/대한민국' + path: '/대한민국' + fullPath: '/specialChars/대한민국' + preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/issue-6221/article/$id': { + id: '/issue-6221/article/$id' + path: '/issue-6221/article/$id' + fullPath: '/issue-6221/article/$id' + preLoaderRoute: typeof Issue6221ArticleIdRouteImport + parentRoute: typeof rootRouteImport + } + '/not-found/deep/': { + id: '/not-found/deep/' + path: '/' + fullPath: '/not-found/deep/' + preLoaderRoute: typeof NotFoundDeepIndexRouteImport + parentRoute: typeof NotFoundDeepRouteRoute + } + '/not-found/deep/b': { + id: '/not-found/deep/b' + path: '/b' + fullPath: '/not-found/deep/b' + preLoaderRoute: typeof NotFoundDeepBRouteRouteImport + parentRoute: typeof NotFoundDeepRouteRoute + } + '/not-found/parent-boundary/': { + id: '/not-found/parent-boundary/' + path: '/' + fullPath: '/not-found/parent-boundary/' + preLoaderRoute: typeof NotFoundParentBoundaryIndexRouteImport + parentRoute: typeof NotFoundParentBoundaryRouteRoute + } + '/not-found/parent-boundary/via-beforeLoad': { + id: '/not-found/parent-boundary/via-beforeLoad' + path: '/via-beforeLoad' + fullPath: '/not-found/parent-boundary/via-beforeLoad' + preLoaderRoute: typeof NotFoundParentBoundaryViaBeforeLoadRouteImport + parentRoute: typeof NotFoundParentBoundaryRouteRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } '/redirect/$target/': { id: '/redirect/$target/' @@ -752,13 +1411,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectTargetIndexRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/via-loader': { - id: '/redirect/$target/via-loader' - path: '/via-loader' - fullPath: '/redirect/$target/via-loader' - preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport - parentRoute: typeof RedirectTargetRoute - } '/redirect/$target/via-beforeLoad': { id: '/redirect/$target/via-beforeLoad' path: '/via-beforeLoad' @@ -766,55 +1418,48 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectTargetViaBeforeLoadRouteImport parentRoute: typeof RedirectTargetRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport + '/redirect/$target/via-loader': { + id: '/redirect/$target/via-loader' + path: '/via-loader' + fullPath: '/redirect/$target/via-loader' + preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/specialChars/malformed/$param': { + id: '/specialChars/malformed/$param' + path: '/$param' + fullPath: '/specialChars/malformed/$param' + preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute + } + '/specialChars/malformed/search': { + id: '/specialChars/malformed/search' + path: '/search' + fullPath: '/specialChars/malformed/search' + preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute + } + '/foo/$bar/$qux/_here': { + id: '/foo/$bar/$qux/_here' + path: '/foo/$bar/$qux' + fullPath: '/foo/$bar/$qux' + preLoaderRoute: typeof FooBarQuxHereRouteImport parentRoute: typeof rootRouteImport } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute - } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/not-found/deep/b/c': { + id: '/not-found/deep/b/c' + path: '/c' + fullPath: '/not-found/deep/b/c' + preLoaderRoute: typeof NotFoundDeepBCRouteRouteImport + parentRoute: typeof NotFoundDeepBRouteRoute } '/redirect/$target/serverFn/': { id: '/redirect/$target/serverFn/' path: '/serverFn' - fullPath: '/redirect/$target/serverFn' + fullPath: '/redirect/$target/serverFn/' preLoaderRoute: typeof RedirectTargetServerFnIndexRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/serverFn/via-useServerFn': { - id: '/redirect/$target/serverFn/via-useServerFn' - path: '/serverFn/via-useServerFn' - fullPath: '/redirect/$target/serverFn/via-useServerFn' - preLoaderRoute: typeof RedirectTargetServerFnViaUseServerFnRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/serverFn/via-loader': { - id: '/redirect/$target/serverFn/via-loader' - path: '/serverFn/via-loader' - fullPath: '/redirect/$target/serverFn/via-loader' - preLoaderRoute: typeof RedirectTargetServerFnViaLoaderRouteImport - parentRoute: typeof RedirectTargetRoute - } '/redirect/$target/serverFn/via-beforeLoad': { id: '/redirect/$target/serverFn/via-beforeLoad' path: '/serverFn/via-beforeLoad' @@ -822,12 +1467,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport parentRoute: typeof RedirectTargetRoute } - '/foo/$bar/$qux/_here': { - id: '/foo/$bar/$qux/_here' - path: '/foo/$bar/$qux' - fullPath: '/foo/$bar/$qux' - preLoaderRoute: typeof FooBarQuxHereRouteImport - parentRoute: typeof rootRouteImport + '/redirect/$target/serverFn/via-loader': { + id: '/redirect/$target/serverFn/via-loader' + path: '/serverFn/via-loader' + fullPath: '/redirect/$target/serverFn/via-loader' + preLoaderRoute: typeof RedirectTargetServerFnViaLoaderRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/serverFn/via-useServerFn': { + id: '/redirect/$target/serverFn/via-useServerFn' + path: '/serverFn/via-useServerFn' + fullPath: '/redirect/$target/serverFn/via-useServerFn' + preLoaderRoute: typeof RedirectTargetServerFnViaUseServerFnRouteImport + parentRoute: typeof RedirectTargetRoute } '/foo/$bar/$qux/_here/': { id: '/foo/$bar/$qux/_here/' @@ -836,19 +1488,83 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof FooBarQuxHereIndexRouteImport parentRoute: typeof FooBarQuxHereRoute } + '/not-found/deep/b/c/d': { + id: '/not-found/deep/b/c/d' + path: '/d' + fullPath: '/not-found/deep/b/c/d' + preLoaderRoute: typeof NotFoundDeepBCDRouteImport + parentRoute: typeof NotFoundDeepBCRouteRoute + } } } +interface NotFoundDeepBCRouteRouteChildren { + NotFoundDeepBCDRoute: typeof NotFoundDeepBCDRoute +} + +const NotFoundDeepBCRouteRouteChildren: NotFoundDeepBCRouteRouteChildren = { + NotFoundDeepBCDRoute: NotFoundDeepBCDRoute, +} + +const NotFoundDeepBCRouteRouteWithChildren = + NotFoundDeepBCRouteRoute._addFileChildren(NotFoundDeepBCRouteRouteChildren) + +interface NotFoundDeepBRouteRouteChildren { + NotFoundDeepBCRouteRoute: typeof NotFoundDeepBCRouteRouteWithChildren +} + +const NotFoundDeepBRouteRouteChildren: NotFoundDeepBRouteRouteChildren = { + NotFoundDeepBCRouteRoute: NotFoundDeepBCRouteRouteWithChildren, +} + +const NotFoundDeepBRouteRouteWithChildren = + NotFoundDeepBRouteRoute._addFileChildren(NotFoundDeepBRouteRouteChildren) + +interface NotFoundDeepRouteRouteChildren { + NotFoundDeepBRouteRoute: typeof NotFoundDeepBRouteRouteWithChildren + NotFoundDeepIndexRoute: typeof NotFoundDeepIndexRoute +} + +const NotFoundDeepRouteRouteChildren: NotFoundDeepRouteRouteChildren = { + NotFoundDeepBRouteRoute: NotFoundDeepBRouteRouteWithChildren, + NotFoundDeepIndexRoute: NotFoundDeepIndexRoute, +} + +const NotFoundDeepRouteRouteWithChildren = + NotFoundDeepRouteRoute._addFileChildren(NotFoundDeepRouteRouteChildren) + +interface NotFoundParentBoundaryRouteRouteChildren { + NotFoundParentBoundaryViaBeforeLoadRoute: typeof NotFoundParentBoundaryViaBeforeLoadRoute + NotFoundParentBoundaryIndexRoute: typeof NotFoundParentBoundaryIndexRoute +} + +const NotFoundParentBoundaryRouteRouteChildren: NotFoundParentBoundaryRouteRouteChildren = + { + NotFoundParentBoundaryViaBeforeLoadRoute: + NotFoundParentBoundaryViaBeforeLoadRoute, + NotFoundParentBoundaryIndexRoute: NotFoundParentBoundaryIndexRoute, + } + +const NotFoundParentBoundaryRouteRouteWithChildren = + NotFoundParentBoundaryRouteRoute._addFileChildren( + NotFoundParentBoundaryRouteRouteChildren, + ) + interface NotFoundRouteRouteChildren { + NotFoundDeepRouteRoute: typeof NotFoundDeepRouteRouteWithChildren + NotFoundParentBoundaryRouteRoute: typeof NotFoundParentBoundaryRouteRouteWithChildren NotFoundViaBeforeLoadRoute: typeof NotFoundViaBeforeLoadRoute - NotFoundViaHeadRoute: typeof NotFoundViaHeadRoute + NotFoundViaBeforeLoadTargetRootRoute: typeof NotFoundViaBeforeLoadTargetRootRoute NotFoundViaLoaderRoute: typeof NotFoundViaLoaderRoute NotFoundIndexRoute: typeof NotFoundIndexRoute } const NotFoundRouteRouteChildren: NotFoundRouteRouteChildren = { + NotFoundDeepRouteRoute: NotFoundDeepRouteRouteWithChildren, + NotFoundParentBoundaryRouteRoute: + NotFoundParentBoundaryRouteRouteWithChildren, NotFoundViaBeforeLoadRoute: NotFoundViaBeforeLoadRoute, - NotFoundViaHeadRoute: NotFoundViaHeadRoute, + NotFoundViaBeforeLoadTargetRootRoute: NotFoundViaBeforeLoadTargetRootRoute, NotFoundViaLoaderRoute: NotFoundViaLoaderRoute, NotFoundIndexRoute: NotFoundIndexRoute, } @@ -872,6 +1588,42 @@ const SearchParamsRouteRouteChildren: SearchParamsRouteRouteChildren = { const SearchParamsRouteRouteWithChildren = SearchParamsRouteRoute._addFileChildren(SearchParamsRouteRouteChildren) +interface SpecialCharsMalformedRouteRouteChildren { + SpecialCharsMalformedParamRoute: typeof SpecialCharsMalformedParamRoute + SpecialCharsMalformedSearchRoute: typeof SpecialCharsMalformedSearchRoute +} + +const SpecialCharsMalformedRouteRouteChildren: SpecialCharsMalformedRouteRouteChildren = + { + SpecialCharsMalformedParamRoute: SpecialCharsMalformedParamRoute, + SpecialCharsMalformedSearchRoute: SpecialCharsMalformedSearchRoute, + } + +const SpecialCharsMalformedRouteRouteWithChildren = + SpecialCharsMalformedRouteRoute._addFileChildren( + SpecialCharsMalformedRouteRouteChildren, + ) + +interface SpecialCharsRouteRouteChildren { + SpecialCharsMalformedRouteRoute: typeof SpecialCharsMalformedRouteRouteWithChildren + SpecialCharsParamRoute: typeof SpecialCharsParamRoute + SpecialCharsHashRoute: typeof SpecialCharsHashRoute + SpecialCharsSearchRoute: typeof SpecialCharsSearchRoute + SpecialCharsChar45824Char54620Char48124Char44397Route: typeof SpecialCharsChar45824Char54620Char48124Char44397Route +} + +const SpecialCharsRouteRouteChildren: SpecialCharsRouteRouteChildren = { + SpecialCharsMalformedRouteRoute: SpecialCharsMalformedRouteRouteWithChildren, + SpecialCharsParamRoute: SpecialCharsParamRoute, + SpecialCharsHashRoute: SpecialCharsHashRoute, + SpecialCharsSearchRoute: SpecialCharsSearchRoute, + SpecialCharsChar45824Char54620Char48124Char44397Route: + SpecialCharsChar45824Char54620Char48124Char44397Route, +} + +const SpecialCharsRouteRouteWithChildren = + SpecialCharsRouteRoute._addFileChildren(SpecialCharsRouteRouteChildren) + interface LayoutLayout2RouteChildren { LayoutLayout2LayoutARoute: typeof LayoutLayout2LayoutARoute LayoutLayout2LayoutBRoute: typeof LayoutLayout2LayoutBRoute @@ -897,6 +1649,18 @@ const LayoutRouteChildren: LayoutRouteChildren = { const LayoutRouteWithChildren = LayoutRoute._addFileChildren(LayoutRouteChildren) +interface AuthDocsRouteChildren { + AuthDocsPrivateRoute: typeof AuthDocsPrivateRoute +} + +const AuthDocsRouteChildren: AuthDocsRouteChildren = { + AuthDocsPrivateRoute: AuthDocsPrivateRoute, +} + +const AuthDocsRouteWithChildren = AuthDocsRoute._addFileChildren( + AuthDocsRouteChildren, +) + interface PostsRouteChildren { PostsPostIdRoute: typeof PostsPostIdRoute PostsIndexRoute: typeof PostsIndexRoute @@ -909,6 +1673,30 @@ const PostsRouteChildren: PostsRouteChildren = { const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) +interface RawStreamRouteChildren { + RawStreamClientCallRoute: typeof RawStreamClientCallRoute + RawStreamSsrBinaryHintRoute: typeof RawStreamSsrBinaryHintRoute + RawStreamSsrMixedRoute: typeof RawStreamSsrMixedRoute + RawStreamSsrMultipleRoute: typeof RawStreamSsrMultipleRoute + RawStreamSsrSingleRoute: typeof RawStreamSsrSingleRoute + RawStreamSsrTextHintRoute: typeof RawStreamSsrTextHintRoute + RawStreamIndexRoute: typeof RawStreamIndexRoute +} + +const RawStreamRouteChildren: RawStreamRouteChildren = { + RawStreamClientCallRoute: RawStreamClientCallRoute, + RawStreamSsrBinaryHintRoute: RawStreamSsrBinaryHintRoute, + RawStreamSsrMixedRoute: RawStreamSsrMixedRoute, + RawStreamSsrMultipleRoute: RawStreamSsrMultipleRoute, + RawStreamSsrSingleRoute: RawStreamSsrSingleRoute, + RawStreamSsrTextHintRoute: RawStreamSsrTextHintRoute, + RawStreamIndexRoute: RawStreamIndexRoute, +} + +const RawStreamRouteWithChildren = RawStreamRoute._addFileChildren( + RawStreamRouteChildren, +) + interface UsersRouteChildren { UsersUserIdRoute: typeof UsersUserIdRoute UsersIndexRoute: typeof UsersIndexRoute @@ -975,21 +1763,31 @@ const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, NotFoundRouteRoute: NotFoundRouteRouteWithChildren, SearchParamsRouteRoute: SearchParamsRouteRouteWithChildren, + SpecialCharsRouteRoute: SpecialCharsRouteRouteWithChildren, LayoutRoute: LayoutRouteWithChildren, + AsyncScriptsRoute: AsyncScriptsRoute, + AuthDocsRoute: AuthDocsRouteWithChildren, + ClientOnlyRoute: ClientOnlyRoute, DeferredRoute: DeferredRoute, + ExecutionLocalRoute: ExecutionLocalRoute, + ExecutionRpcRoute: ExecutionRpcRoute, InlineScriptsRoute: InlineScriptsRoute, LinksRoute: LinksRoute, + PlainTsTypeAssertionRoute: PlainTsTypeAssertionRoute, PostsRoute: PostsRouteWithChildren, + PrimitiveBeforeloadErrorRoute: PrimitiveBeforeloadErrorRoute, + RawStreamRoute: RawStreamRouteWithChildren, ScriptsRoute: ScriptsRoute, StreamRoute: StreamRoute, + TypeOnlyReexportRoute: TypeOnlyReexportRoute, UsersRoute: UsersRouteWithChildren, - Char45824Char54620Char48124Char44397Route: - Char45824Char54620Char48124Char44397Route, ApiUsersRoute: ApiUsersRouteWithChildren, + Issue6221DashboardRoute: Issue6221DashboardRoute, MultiCookieRedirectTargetRoute: MultiCookieRedirectTargetRoute, RedirectTargetRoute: RedirectTargetRouteWithChildren, MultiCookieRedirectIndexRoute: MultiCookieRedirectIndexRoute, RedirectIndexRoute: RedirectIndexRoute, + Issue6221ArticleIdRoute: Issue6221ArticleIdRoute, PostsPostIdDeepRoute: PostsPostIdDeepRoute, FooBarQuxHereRoute: FooBarQuxHereRouteWithChildren, } diff --git a/e2e/react-start/basic/src/routes/__root.tsx b/e2e/react-start/basic/src/routes/__root.tsx index c7d87cad18..ed521817d6 100644 --- a/e2e/react-start/basic/src/routes/__root.tsx +++ b/e2e/react-start/basic/src/routes/__root.tsx @@ -1,16 +1,18 @@ /// import * as React from 'react' import { + ClientOnly, HeadContent, Link, Outlet, Scripts, createRootRoute, + useRouterState, } from '@tanstack/react-router' import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' import { NotFound } from '~/components/NotFound' -import appCss from '~/styles/app.css?url' +import '~/styles/app.css' import { seo } from '~/utils/seo' export const Route = createRootRoute({ @@ -30,7 +32,6 @@ export const Route = createRootRoute({ }), ], links: [ - { rel: 'stylesheet', href: appCss }, { rel: 'apple-touch-icon', sizes: '180x180', @@ -93,10 +94,17 @@ const RouterDevtools = ) function RootDocument({ children }: { children: React.ReactNode }) { + const { isLoading, status } = useRouterState({ + select: (state) => ({ isLoading: state.isLoading, status: state.status }), + structuralSharing: true, + }) + return ( + ', endIndex) + const scriptCloseIndex = html.indexOf('', endIndex) + const bodyCloseIndex = html.indexOf('', scriptCloseIndex) + const htmlCloseIndex = html.indexOf('', bodyCloseIndex) + + expect(endIndex).toBeGreaterThan(-1) + expect(scriptOpenIndex).toBeGreaterThan(previousScriptCloseIndex) + expect(scriptCloseIndex).toBeGreaterThan(endIndex) + expect(payloadIndex).toBeGreaterThan(-1) + expect(payloadIndex).toBeLessThan(endIndex) + expect(html.slice(endIndex, scriptCloseIndex)).toContain(LATE_RECORD_CLOSE) + expect(scriptCloseIndex).toBeLessThan(bodyCloseIndex) + expect(bodyCloseIndex).toBeLessThan(htmlCloseIndex) +} + +async function verifyHydration( + page: Page, + { timeout = 10_000 }: { timeout?: number } = {}, +) { + const button = page.getByTestId('hydration-check-btn') + const status = page.getByTestId('hydration-status') + + await expect(button).toBeVisible() + await expect(async () => { + await button.click() + await expect(status).toHaveText('hydrated', { timeout: 100 }) + }).toPass({ timeout }) + + await expect(page.locator(STREAM_PART_SELECTOR)).toHaveCount(0) + await expect( + page.locator('script').filter({ hasText: STREAM_BOUNDARY_MARKER }), + ).toHaveCount(0) +} + +export { test } + +export const testWithHydration = test.extend({ + page: async ({ page }, use) => { + await use(page) + await verifyHydration(page) + }, +}) + +export { expect } diff --git a/e2e/streaming-ssr-fixtures/index.ts b/e2e/streaming-ssr-fixtures/index.ts new file mode 100644 index 0000000000..a70ef94459 --- /dev/null +++ b/e2e/streaming-ssr-fixtures/index.ts @@ -0,0 +1,381 @@ +export type SourceMarker = 'server' | 'client' + +export type ServerData = { + name: string + timestamp: number + source: 'server' +} + +export type DeferredMessage = { + message: string + source: SourceMarker +} + +export type QueryType = 'sync' | 'fast-async' | 'slow-async' + +export type QueryData = { + type: QueryType + id: number + value: string + source: SourceMarker +} + +export const deferredDataMessage = 'Deferred data loaded!' +export const deferredDataDelay = 1000 +export const deferredServerDelay = 800 +export const deferredImmediateName = 'Fast User' +export const deferredSlowName = 'Slow User' +export const deferredErrorMessage = 'Error in deferred object' + +export const fastSerialStaticData = 'This is static data' +export const fastSerialSmallValue = 'small-data' + +export const syncOnlyMessage = 'Hello from sync loader!' +export const syncOnlyItems = ['item-1', 'item-2', 'item-3'] as const + +export const slowRenderDeferredMessage = 'Deferred resolved!' +export const slowRenderDeferredDelay = 50 +export const slowRenderQuickName = 'Quick data' +export const slowRenderComponents = [ + 'Slow component 1', + 'Slow component 2', + 'Slow component 3', +] as const + +export const nestedLevelDelays = [200, 400, 600] as const +export const nestedPlainDelay = 300 +export const nestedPlainMessage = 'Plain deferred resolved!' + +export const streamPromiseValue = 'promise-resolved' +export const streamPromiseDelay = 150 +export const streamChunkDelay = 200 +export const streamChunks = Array.from({ length: 5 }, (_, i) => `chunk-${i}`) + +export const routerHtmlPayloadChars = 17 * 1024 * 1024 +export const routerHtmlPayloadChar = 'x' +export const routerHtmlPayloadDelay = 100 + +export const manyPromiseItems = [ + { + key: 'immediate1', + testId: 'immediate-1', + label: 'Immediate 1', + value: 'immediate-1', + delayMs: 0, + }, + { + key: 'immediate2', + testId: 'immediate-2', + label: 'Immediate 2', + value: 'immediate-2', + delayMs: 10, + }, + { + key: 'immediate3', + testId: 'immediate-3', + label: 'Immediate 3', + value: 'immediate-3', + delayMs: 20, + }, + { + key: 'fast1', + testId: 'fast-1', + label: 'Fast 1', + value: 'fast-1', + delayMs: 50, + }, + { + key: 'fast2', + testId: 'fast-2', + label: 'Fast 2', + value: 'fast-2', + delayMs: 75, + }, + { + key: 'fast3', + testId: 'fast-3', + label: 'Fast 3', + value: 'fast-3', + delayMs: 100, + }, + { + key: 'fast4', + testId: 'fast-4', + label: 'Fast 4', + value: 'fast-4', + delayMs: 125, + }, + { + key: 'medium1', + testId: 'medium-1', + label: 'Medium 1', + value: 'medium-1', + delayMs: 150, + }, + { + key: 'medium2', + testId: 'medium-2', + label: 'Medium 2', + value: 'medium-2', + delayMs: 200, + }, + { + key: 'medium3', + testId: 'medium-3', + label: 'Medium 3', + value: 'medium-3', + delayMs: 250, + }, + { + key: 'slow1', + testId: 'slow-1', + label: 'Slow 1', + value: 'slow-1', + delayMs: 300, + }, + { + key: 'slow2', + testId: 'slow-2', + label: 'Slow 2', + value: 'slow-2', + delayMs: 400, + }, + { + key: 'slow3', + testId: 'slow-3', + label: 'Slow 3', + value: 'slow-3', + delayMs: 500, + }, + { + key: 'verySlow1', + testId: 'very-slow-1', + label: 'Very Slow 1', + value: 'very-slow-1', + delayMs: 600, + }, + { + key: 'verySlow2', + testId: 'very-slow-2', + label: 'Very Slow 2', + value: 'very-slow-2', + delayMs: 800, + }, +] as const + +export const concurrentBatchCount = 5 +export const concurrentBatchDelays = [100, 200, 300] as const + +export const queryHeavyItems = [ + { + type: 'sync', + id: 1, + value: 'sync-value-1', + delayMs: 0, + testId: 'sync-query-1', + fallback: 'Loading sync 1...', + }, + { + type: 'sync', + id: 2, + value: 'sync-value-2', + delayMs: 0, + testId: 'sync-query-2', + fallback: 'Loading sync 2...', + }, + { + type: 'sync', + id: 3, + value: 'sync-value-3', + delayMs: 0, + testId: 'sync-query-3', + fallback: 'Loading sync 3...', + }, + { + type: 'fast-async', + id: 1, + value: 'fast-async-1', + delayMs: 50, + testId: 'fast-async-query-1', + fallback: 'Loading fast 1...', + }, + { + type: 'fast-async', + id: 2, + value: 'fast-async-2', + delayMs: 75, + testId: 'fast-async-query-2', + fallback: 'Loading fast 2...', + }, + { + type: 'fast-async', + id: 3, + value: 'fast-async-3', + delayMs: 100, + testId: 'fast-async-query-3', + fallback: 'Loading fast 3...', + }, + { + type: 'slow-async', + id: 1, + value: 'slow-async-1', + delayMs: 200, + testId: 'slow-async-query-1', + fallback: 'Loading slow 1...', + }, + { + type: 'slow-async', + id: 2, + value: 'slow-async-2', + delayMs: 300, + testId: 'slow-async-query-2', + fallback: 'Loading slow 2...', + }, + { + type: 'slow-async', + id: 3, + value: 'slow-async-3', + delayMs: 400, + testId: 'slow-async-query-3', + fallback: 'Loading slow 3...', + }, +] as const + +export function sourceMarker(): SourceMarker { + return typeof window === 'undefined' ? 'server' : 'client' +} + +export function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +export function makeServerData(name: string): ServerData { + return { + name, + timestamp: Date.now(), + source: 'server', + } +} + +export function makeDeferred(value: T, delayMs: number): Promise { + return new Promise((resolve) => setTimeout(() => resolve(value), delayMs)) +} + +export function makeDeferredMessage( + message: string, + delayMs: number, +): Promise { + return makeDeferred({ message, source: sourceMarker() }, delayMs) +} + +export function makeFastSerialSmallData() { + return { + value: fastSerialSmallValue, + timestamp: Date.now(), + source: 'server' as const, + } +} + +export function makeSyncOnlyData() { + return { + message: syncOnlyMessage, + timestamp: Date.now(), + items: syncOnlyItems, + source: sourceMarker(), + } +} + +export function makeLevelData(level: number) { + return { level, timestamp: Date.now() } +} + +export function makeQueryData(item: { + type: QueryType + id: number + value: string +}): QueryData { + return { + type: item.type, + id: item.id, + value: item.value, + source: sourceMarker(), + } +} + +export function createManyPromises() { + return Object.fromEntries( + manyPromiseItems.map((item) => [ + item.key, + makeDeferred(item.value, item.delayMs), + ]), + ) as Record<(typeof manyPromiseItems)[number]['key'], Promise> +} + +export function createConcurrentPromises( + count: number, + delayMs: number, +): Array> { + const sharedPromise = delay(delayMs) + return Array.from({ length: count }, (_, i) => + sharedPromise.then(() => `concurrent-${i + 1}`), + ) +} + +export function createConcurrentLoaderData() { + const batch1 = createConcurrentPromises( + concurrentBatchCount, + concurrentBatchDelays[0], + ) + const batch2 = createConcurrentPromises( + concurrentBatchCount, + concurrentBatchDelays[1], + ) + const batch3 = createConcurrentPromises( + concurrentBatchCount, + concurrentBatchDelays[2], + ) + + return { + concurrent1_1: batch1[0], + concurrent1_2: batch1[1], + concurrent1_3: batch1[2], + concurrent1_4: batch1[3], + concurrent1_5: batch1[4], + concurrent2_1: batch2[0], + concurrent2_2: batch2[1], + concurrent2_3: batch2[2], + concurrent2_4: batch2[3], + concurrent2_5: batch2[4], + concurrent3_1: batch3[0], + concurrent3_2: batch3[1], + concurrent3_3: batch3[2], + concurrent3_4: batch3[3], + concurrent3_5: batch3[4], + } +} + +export function createStreamPromise(): Promise { + return makeDeferred(streamPromiseValue, streamPromiseDelay) +} + +export function createChunkStream(): ReadableStream { + return new ReadableStream({ + async start(controller) { + for (const chunk of streamChunks) { + await delay(streamChunkDelay) + controller.enqueue(chunk) + } + controller.close() + }, + }) +} + +export function createRouterHtmlPayload() { + return makeDeferred( + { + value: routerHtmlPayloadChar.repeat(routerHtmlPayloadChars), + source: sourceMarker(), + }, + routerHtmlPayloadDelay, + ) +} diff --git a/e2e/streaming-ssr-specs/client-navigation.ts b/e2e/streaming-ssr-specs/client-navigation.ts new file mode 100644 index 0000000000..759f8e0282 --- /dev/null +++ b/e2e/streaming-ssr-specs/client-navigation.ts @@ -0,0 +1,372 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +test.describe('Client-side navigation between all routes', () => { + test.beforeEach(async ({ page }) => { + // Start from home page + await page.goto('/') + await page.waitForLoadState('networkidle') + }) + + test('home -> sync-only -> home works', async ({ page }) => { + // Navigate to sync-only + await page + .getByRole('navigation') + .getByRole('link', { name: 'Sync Only' }) + .click() + await expect(page).toHaveURL('/sync-only') + await expect(page.getByTestId('sync-message')).toBeVisible() + + // Navigate back to home + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + await expect(page.getByTestId('index-title')).toBeVisible() + }) + + test('home -> deferred -> home works', async ({ page }) => { + // Navigate to deferred (use exact: true to avoid matching "Nested Deferred") + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + await expect(page.getByTestId('immediate-data')).toBeVisible() + + // Wait for deferred data + await expect(page.getByTestId('deferred-data')).toBeVisible({ + timeout: 5000, + }) + + // Navigate back to home + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('home -> stream -> home works (no stream locking error)', async ({ + page, + }) => { + // This test specifically validates the ReadableStream locking fix + // Console errors are monitored by the fixture automatically + + // Navigate to stream + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + // Wait for stream to start (at least one chunk or promise resolved) + await expect(page.getByTestId('promise-data')).toBeVisible({ + timeout: 5000, + }) + + // Navigate back without waiting for stream completion. + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('home -> stream -> wait for completion -> home works', async ({ + page, + }) => { + // Navigate to stream + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + // Wait for stream to complete + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + + // Navigate back to home + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + await expect(page.getByTestId('index-title')).toBeVisible() + }) + + test('home -> stream -> home -> stream again works (fresh stream each time)', async ({ + page, + }) => { + // Console errors are monitored by the fixture automatically + + // First navigation to stream + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + await expect(page.getByTestId('promise-data')).toBeVisible({ + timeout: 5000, + }) + + // Navigate back to home + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + + // Second navigation to stream - should get fresh stream without errors + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + // Wait for stream to complete + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + + // Verify all chunks are present + await expect(page.getByTestId('stream-chunk-0')).toBeVisible() + await expect(page.getByTestId('stream-chunk-4')).toBeVisible() + }) + + test('home -> fast-serial -> home works', async ({ page }) => { + await page + .getByRole('navigation') + .getByRole('link', { name: 'Fast Serial' }) + .click() + await expect(page).toHaveURL('/fast-serial') + await expect(page.getByTestId('server-data')).toBeVisible() + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('home -> slow-render -> home works', async ({ page }) => { + await page + .getByRole('navigation') + .getByRole('link', { name: 'Slow Render' }) + .click() + await expect(page).toHaveURL('/slow-render') + await expect(page.getByTestId('quick-data')).toBeVisible() + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('home -> nested-deferred -> home works', async ({ page }) => { + await page + .getByRole('navigation') + .getByRole('link', { name: 'Nested Deferred' }) + .click() + await expect(page).toHaveURL('/nested-deferred') + + // Wait for all levels to load + await expect(page.getByTestId('level3-data')).toBeVisible({ timeout: 5000 }) + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('navigation without waiting for route data works', async ({ page }) => { + // Console errors are monitored by the fixture automatically + + // Change routes as soon as each URL updates, without waiting for route data. + await page + .getByRole('navigation') + .getByRole('link', { name: 'Sync Only' }) + .click() + await expect(page).toHaveURL('/sync-only') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Fast Serial' }) + .click() + await expect(page).toHaveURL('/fast-serial') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Slow Render' }) + .click() + await expect(page).toHaveURL('/slow-render') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Nested Deferred' }) + .click() + await expect(page).toHaveURL('/nested-deferred') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) +}) + +test.describe('Direct navigation followed by client navigation', () => { + test('direct to stream -> client nav to deferred works', async ({ page }) => { + // Direct navigation to stream + await page.goto('/stream') + await expect(page.getByTestId('promise-data')).toBeVisible({ + timeout: 5000, + }) + + // Client navigation to deferred (use exact: true) + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + await expect(page.getByTestId('immediate-data')).toBeVisible() + }) + + test('direct to deferred -> client nav to stream works', async ({ page }) => { + // Console errors are monitored by the fixture automatically + + // Direct navigation to deferred + await page.goto('/deferred') + await expect(page.getByTestId('immediate-data')).toBeVisible() + + // Client navigation to stream + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + }) + + test('direct to sync-only -> client nav to all routes works', async ({ + page, + }) => { + await page.goto('/sync-only') + await expect(page.getByTestId('sync-message')).toBeVisible() + + // Navigate through all routes + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Fast Serial' }) + .click() + await expect(page).toHaveURL('/fast-serial') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) +}) + +testWithHydration.describe('Hydration after client navigation', () => { + testWithHydration( + 'interactive elements work after navigating to deferred', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + + // Wait for the page to be fully loaded + await expect(page.getByTestId('immediate-data')).toBeVisible() + }, + ) + + testWithHydration( + 'interactive elements work after navigating to fast-serial', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Fast Serial' }) + .click() + await expect(page).toHaveURL('/fast-serial') + + // Wait for page to load + await expect(page.getByTestId('server-data')).toBeVisible() + }, + ) + + testWithHydration( + 'interactive elements work after navigating to nested-deferred', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Nested Deferred' }) + .click() + await expect(page).toHaveURL('/nested-deferred') + + // Wait for page to load + await expect(page.getByTestId('plain-deferred')).toBeVisible({ + timeout: 5000, + }) + }, + ) + + testWithHydration( + 'interactive elements work after navigating to slow-render', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Slow Render' }) + .click() + await expect(page).toHaveURL('/slow-render') + + // Wait for page to load (slow-render has blocking loops) + await expect(page.getByTestId('quick-data')).toBeVisible() + }, + ) +}) diff --git a/e2e/streaming-ssr-specs/concurrent.ts b/e2e/streaming-ssr-specs/concurrent.ts new file mode 100644 index 0000000000..ef14f80367 --- /dev/null +++ b/e2e/streaming-ssr-specs/concurrent.ts @@ -0,0 +1,86 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +test.describe('Concurrent promise resolution (15 promises in 3 batches)', () => { + test('all concurrent promises resolve correctly', async ({ page }) => { + await page.goto('/concurrent') + + // Batch 1 (5 promises at 100ms) + await expect(page.getByTestId('concurrent-1-1')).toContainText( + 'concurrent-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-1-2')).toContainText( + 'concurrent-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-1-3')).toContainText( + 'concurrent-3', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-1-4')).toContainText( + 'concurrent-4', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-1-5')).toContainText( + 'concurrent-5', + { timeout: 5000 }, + ) + + // Batch 2 (5 promises at 200ms) + await expect(page.getByTestId('concurrent-2-1')).toContainText( + 'concurrent-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-2-2')).toContainText( + 'concurrent-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-2-3')).toContainText( + 'concurrent-3', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-2-4')).toContainText( + 'concurrent-4', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-2-5')).toContainText( + 'concurrent-5', + { timeout: 5000 }, + ) + + // Batch 3 (5 promises at 300ms) + await expect(page.getByTestId('concurrent-3-1')).toContainText( + 'concurrent-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-3-2')).toContainText( + 'concurrent-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-3-3')).toContainText( + 'concurrent-3', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-3-4')).toContainText( + 'concurrent-4', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-3-5')).toContainText( + 'concurrent-5', + { timeout: 5000 }, + ) + }) + + testWithHydration( + 'hydration works with concurrent resolutions', + async ({ page }) => { + await page.goto('/concurrent') + await page.waitForLoadState('networkidle') + + // Wait for all batches + await expect(page.getByTestId('concurrent-3-5')).toBeVisible({ + timeout: 5000, + }) + }, + ) +}) diff --git a/e2e/streaming-ssr-specs/deferred-rejection.ts b/e2e/streaming-ssr-specs/deferred-rejection.ts new file mode 100644 index 0000000000..3e944b1c0c --- /dev/null +++ b/e2e/streaming-ssr-specs/deferred-rejection.ts @@ -0,0 +1,21 @@ +import { expect, test } from '../streaming-ssr-assertions' + +test.use({ + whitelistErrors: ['Error in deferred object'], +}) + +test('rejected deferred Await renders the route error boundary without killing SSR', async ({ + page, +}) => { + await page.goto('/deferred-rejection') + + await expect(page.getByTestId('deferred-error-boundary')).toContainText( + 'Error in deferred object', + { timeout: 5000 }, + ) + + await page.goto('/sync-only') + await expect(page.getByTestId('sync-message')).toContainText( + 'Hello from sync loader!', + ) +}) diff --git a/e2e/streaming-ssr-specs/deferred.ts b/e2e/streaming-ssr-specs/deferred.ts new file mode 100644 index 0000000000..abece0b43e --- /dev/null +++ b/e2e/streaming-ssr-specs/deferred.ts @@ -0,0 +1,113 @@ +import { + expect, + expectDeferredRouteResponseOrder, + test, + testWithHydration, +} from '../streaming-ssr-assertions' + +test.describe('Deferred data streaming', () => { + test('finishes the router stream after renderer output', async ({ + baseURL, + }) => { + await expectDeferredRouteResponseOrder(baseURL) + }) + + test('renders immediate and deferred server data', async ({ page }) => { + await page.goto('/deferred') + + // Immediate loader data is rendered. + await expect(page.getByTestId('immediate-data')).toBeVisible() + await expect(page.getByTestId('immediate-data')).toContainText( + 'Immediate: Fast User', + ) + + // Verify immediate data came from server + await expect(page.getByTestId('immediate-source')).toContainText( + 'Immediate source: server', + ) + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + + // Deferred data should eventually appear with server source + await expect(page.getByTestId('deferred-data')).toContainText( + 'Deferred data loaded!', + { timeout: 5000 }, + ) + await expect(page.getByTestId('deferred-data')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('deferred-server-data')).toContainText( + 'Server: Slow User', + { timeout: 5000 }, + ) + await expect(page.getByTestId('deferred-server-data')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + }) + + testWithHydration( + 'hydration works - interactive elements respond', + async ({ page }) => { + await page.goto('/deferred') + await page.waitForLoadState('networkidle') + + // Wait for all deferred content to load + await expect(page.getByTestId('deferred-data')).toBeVisible({ + timeout: 5000, + }) + + // Verify all data came from server after hydration + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + await expect(page.getByTestId('deferred-data')).toContainText( + 'source: server', + ) + }, + ) + + test('client-side navigation to deferred route works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via client-side routing using nav link + await page.getByRole('link', { name: 'Deferred' }).first().click() + await expect(page).toHaveURL('/deferred') + + // Data should load + await expect(page.getByTestId('immediate-data')).toContainText('Fast User') + await expect(page.getByTestId('deferred-data')).toContainText( + 'Deferred data loaded!', + { timeout: 5000 }, + ) + }) + + test('all data sources are server', async ({ page }) => { + await page.goto('/deferred') + + // Wait for all deferred content + await expect(page.getByTestId('deferred-data')).toBeVisible({ + timeout: 5000, + }) + await expect(page.getByTestId('deferred-server-data')).toBeVisible({ + timeout: 5000, + }) + + // Count all elements showing 'server' source - should be 4: + // 1. immediate-source + // 2. loader-source + // 3. deferred-data (contains "source: server") + // 4. deferred-server-data (contains "source: server") + await expect(page.getByTestId('immediate-source')).toContainText('server') + await expect(page.getByTestId('loader-source')).toContainText('server') + await expect(page.getByTestId('deferred-data')).toContainText( + 'source: server', + ) + await expect(page.getByTestId('deferred-server-data')).toContainText( + 'source: server', + ) + }) +}) diff --git a/e2e/streaming-ssr-specs/fast-serial.ts b/e2e/streaming-ssr-specs/fast-serial.ts new file mode 100644 index 0000000000..03201f0a55 --- /dev/null +++ b/e2e/streaming-ssr-specs/fast-serial.ts @@ -0,0 +1,74 @@ +import { + expect, + expectRouterHydrationMarkers, + test, + testWithHydration, +} from '../streaming-ssr-assertions' + +test.describe('Fast serialization (serialization completes before render)', () => { + test('initial HTML contains router bootstrap + barrier', async ({ page }) => { + let responseHtml = '' + await page.route('/fast-serial', async (route) => { + const response = await route.fetch() + responseHtml = await response.text() + await route.fulfill({ response }) + }) + + await page.goto('/fast-serial') + await expect(page.getByTestId('server-data')).toBeVisible() + + expectRouterHydrationMarkers(responseHtml) + }) + + test('renders all server data', async ({ page }) => { + await page.goto('/fast-serial') + await page.waitForLoadState('networkidle') + + // All data should be visible + await expect(page.getByTestId('server-data')).toContainText('small-data') + await expect(page.getByTestId('static-data')).toContainText( + 'This is static data', + ) + await expect(page.getByTestId('loader-timestamp')).toBeVisible() + + // Verify the loader and server function ran during SSR. + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + await expect(page.getByTestId('server-fn-source')).toContainText( + 'Server function source: server', + ) + }) + + testWithHydration('hydration works correctly', async ({ page }) => { + await page.goto('/fast-serial') + await page.waitForLoadState('networkidle') + + // Verify data came from server after hydration + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + }) + + test('direct navigation renders correctly', async ({ page }) => { + // Direct navigation (SSR) + await page.goto('/fast-serial') + + // Should render without errors and show server source + await expect(page.getByTestId('server-data')).toBeVisible() + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + }) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Fast Serial' }).first().click() + await expect(page).toHaveURL('/fast-serial') + + await expect(page.getByTestId('server-data')).toContainText('small-data') + }) +}) diff --git a/e2e/streaming-ssr-specs/home.ts b/e2e/streaming-ssr-specs/home.ts new file mode 100644 index 0000000000..d85e19bfa7 --- /dev/null +++ b/e2e/streaming-ssr-specs/home.ts @@ -0,0 +1,34 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +test.describe('Home page', () => { + testWithHydration( + 'renders index page with all navigation links', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await expect(page.getByTestId('index-title')).toContainText( + 'Streaming SSR Test Scenarios', + ) + // Check links exist (they're in the nav and the body) + await expect( + page.getByRole('link', { name: 'Deferred' }).first(), + ).toBeVisible() + await expect( + page.getByRole('link', { name: 'Stream' }).first(), + ).toBeVisible() + }, + ) + + testWithHydration( + 'navigation from home to routes works', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Use the link in the content (not nav) + await page.getByTestId('link-deferred').click() + await expect(page).toHaveURL('/deferred') + }, + ) +}) diff --git a/e2e/streaming-ssr-specs/many-promises.ts b/e2e/streaming-ssr-specs/many-promises.ts new file mode 100644 index 0000000000..768859c7e4 --- /dev/null +++ b/e2e/streaming-ssr-specs/many-promises.ts @@ -0,0 +1,82 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +test.describe('Many promises streaming (15 deferred)', () => { + test('all 15 promises eventually resolve', async ({ page }) => { + await page.goto('/many-promises') + + // Immediate group (0-20ms) + await expect(page.getByTestId('immediate-1')).toContainText('immediate-1', { + timeout: 5000, + }) + await expect(page.getByTestId('immediate-2')).toContainText('immediate-2', { + timeout: 5000, + }) + await expect(page.getByTestId('immediate-3')).toContainText('immediate-3', { + timeout: 5000, + }) + + // Fast group (50-125ms) + await expect(page.getByTestId('fast-1')).toContainText('fast-1', { + timeout: 5000, + }) + await expect(page.getByTestId('fast-2')).toContainText('fast-2', { + timeout: 5000, + }) + await expect(page.getByTestId('fast-3')).toContainText('fast-3', { + timeout: 5000, + }) + await expect(page.getByTestId('fast-4')).toContainText('fast-4', { + timeout: 5000, + }) + + // Medium group (150-250ms) + await expect(page.getByTestId('medium-1')).toContainText('medium-1', { + timeout: 5000, + }) + await expect(page.getByTestId('medium-2')).toContainText('medium-2', { + timeout: 5000, + }) + await expect(page.getByTestId('medium-3')).toContainText('medium-3', { + timeout: 5000, + }) + + // Slow group (300-500ms) + await expect(page.getByTestId('slow-1')).toContainText('slow-1', { + timeout: 5000, + }) + await expect(page.getByTestId('slow-2')).toContainText('slow-2', { + timeout: 5000, + }) + await expect(page.getByTestId('slow-3')).toContainText('slow-3', { + timeout: 5000, + }) + + // Very slow group (600-800ms) + await expect(page.getByTestId('very-slow-1')).toContainText('very-slow-1', { + timeout: 5000, + }) + await expect(page.getByTestId('very-slow-2')).toContainText('very-slow-2', { + timeout: 5000, + }) + }) + + testWithHydration('hydration works with many promises', async ({ page }) => { + await page.goto('/many-promises') + await page.waitForLoadState('networkidle') + + // Wait for all promises to resolve + await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) + }) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Many Promises' }).click() + await expect(page).toHaveURL('/many-promises') + + // All promises should eventually resolve + await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) + }) +}) diff --git a/e2e/streaming-ssr-specs/nested-deferred.ts b/e2e/streaming-ssr-specs/nested-deferred.ts new file mode 100644 index 0000000000..0146a23162 --- /dev/null +++ b/e2e/streaming-ssr-specs/nested-deferred.ts @@ -0,0 +1,52 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +test.describe('Nested deferred (multiple levels of deferred data)', () => { + test('all levels of deferred data eventually resolve', async ({ page }) => { + await page.goto('/nested-deferred') + + // All deferred values should eventually resolve. + await expect(page.getByTestId('plain-deferred')).toContainText( + 'Plain deferred resolved!', + { timeout: 5000 }, + ) + + await expect(page.getByTestId('level1-data')).toContainText('Level 1:', { + timeout: 5000, + }) + + await expect(page.getByTestId('level2-data')).toContainText('Level 2:', { + timeout: 5000, + }) + + await expect(page.getByTestId('level3-data')).toContainText('Level 3:', { + timeout: 5000, + }) + }) + + testWithHydration( + 'hydration works with nested deferred', + async ({ page }) => { + await page.goto('/nested-deferred') + await page.waitForLoadState('networkidle') + + // Wait for all data + await expect(page.getByTestId('level3-data')).toBeVisible({ + timeout: 10000, + }) + }, + ) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Nested Deferred' }).first().click() + await expect(page).toHaveURL('/nested-deferred') + + // All levels should eventually render + await expect(page.getByTestId('level3-data')).toBeVisible({ + timeout: 10000, + }) + }) +}) diff --git a/e2e/streaming-ssr-specs/preview-streaming.ts b/e2e/streaming-ssr-specs/preview-streaming.ts new file mode 100644 index 0000000000..5087dff730 --- /dev/null +++ b/e2e/streaming-ssr-specs/preview-streaming.ts @@ -0,0 +1,13 @@ +import { + expectDeferredRouteResponseOrder, + test, +} from '../streaming-ssr-assertions' + +test.skip( + process.env.MODE !== 'preview', + 'Only runs against vite preview: pnpm test:e2e:preview', +) + +test('vite preview preserves deferred HTML order', async ({ baseURL }) => { + await expectDeferredRouteResponseOrder(baseURL) +}) diff --git a/e2e/streaming-ssr-specs/query-heavy.ts b/e2e/streaming-ssr-specs/query-heavy.ts new file mode 100644 index 0000000000..b33a64f366 --- /dev/null +++ b/e2e/streaming-ssr-specs/query-heavy.ts @@ -0,0 +1,142 @@ +import { + expect, + expectQueryHeavyRouteStreamOrder, + test, + testWithHydration, +} from '../streaming-ssr-assertions' + +test.describe('Query heavy route (9 queries)', () => { + test('emits the complete router stream before document closes', async ({ + baseURL, + }) => { + await expectQueryHeavyRouteStreamOrder(baseURL) + }) + + test('all queries resolve with server data', async ({ page }) => { + await page.goto('/query-heavy') + + // Sync queries should show server source + await expect(page.getByTestId('sync-query-1')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('sync-query-2')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('sync-query-3')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + + // Fast async queries should show server source + await expect(page.getByTestId('fast-async-query-1')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('fast-async-query-2')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('fast-async-query-3')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + + // Slow async queries should show server source + await expect(page.getByTestId('slow-async-query-1')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('slow-async-query-2')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('slow-async-query-3')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + }) + + test('sync queries have correct values', async ({ page }) => { + await page.goto('/query-heavy') + + await expect(page.getByTestId('sync-query-1')).toContainText('sync-value-1') + await expect(page.getByTestId('sync-query-2')).toContainText('sync-value-2') + await expect(page.getByTestId('sync-query-3')).toContainText('sync-value-3') + }) + + test('async queries have correct values', async ({ page }) => { + await page.goto('/query-heavy') + + await expect(page.getByTestId('fast-async-query-1')).toContainText( + 'fast-async-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('fast-async-query-2')).toContainText( + 'fast-async-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('fast-async-query-3')).toContainText( + 'fast-async-3', + { timeout: 5000 }, + ) + + await expect(page.getByTestId('slow-async-query-1')).toContainText( + 'slow-async-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('slow-async-query-2')).toContainText( + 'slow-async-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('slow-async-query-3')).toContainText( + 'slow-async-3', + { timeout: 5000 }, + ) + }) + + testWithHydration('hydration works with many queries', async ({ page }) => { + await page.goto('/query-heavy') + await page.waitForLoadState('networkidle') + + // Wait for all queries to resolve + await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ + timeout: 5000, + }) + }) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Query Heavy' }).click() + await expect(page).toHaveURL('/query-heavy') + + // All queries should eventually resolve (on client) + await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ + timeout: 5000, + }) + }) + + test('server query data hydrates without client refetch', async ({ + page, + }) => { + // If hydration missed the server data, these queries would re-execute on + // the client and show "client" as their source. + await page.goto('/query-heavy') + + // Wait for all queries + await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ + timeout: 5000, + }) + + // Verify that all server results hydrated without a client refetch. + const serverSourceCount = await page + .locator('[data-testid*="query-"]') + .filter({ hasText: 'source: server' }) + .count() + expect(serverSourceCount).toBe(9) + }) +}) diff --git a/e2e/streaming-ssr-specs/slow-render.ts b/e2e/streaming-ssr-specs/slow-render.ts new file mode 100644 index 0000000000..117559701e --- /dev/null +++ b/e2e/streaming-ssr-specs/slow-render.ts @@ -0,0 +1,71 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +test.describe('Slow render (render takes longer than serialization)', () => { + test('all data eventually renders with server source', async ({ page }) => { + await page.goto('/slow-render') + await page.waitForLoadState('networkidle') + + // Quick data should be available with server source + await expect(page.getByTestId('quick-data')).toContainText('Quick:') + await expect(page.getByTestId('quick-source')).toContainText( + 'Quick data source: server', + ) + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + + // Deferred data should resolve with server source + await expect(page.getByTestId('deferred-resolved')).toContainText( + 'Deferred resolved!', + { timeout: 5000 }, + ) + await expect(page.getByTestId('deferred-resolved')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + + // Slow components should have rendered + await expect(page.getByTestId('slow-component-1')).toBeVisible() + await expect(page.getByTestId('slow-component-2')).toBeVisible() + await expect(page.getByTestId('slow-component-3')).toBeVisible() + }) + + testWithHydration('hydration works after slow render', async ({ page }) => { + await page.goto('/slow-render') + await page.waitForLoadState('networkidle') + + // Wait for content and verify server source + await expect(page.getByTestId('slow-component-1')).toBeVisible() + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + }) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Slow Render' }).first().click() + await expect(page).toHaveURL('/slow-render') + + await expect(page.getByTestId('quick-data')).toBeVisible({ timeout: 10000 }) + }) + + test('all data sources are server', async ({ page }) => { + await page.goto('/slow-render') + await page.waitForLoadState('networkidle') + + // Wait for deferred content + await expect(page.getByTestId('deferred-resolved')).toBeVisible({ + timeout: 5000, + }) + + // Verify all sources are server + await expect(page.getByTestId('quick-source')).toContainText('server') + await expect(page.getByTestId('loader-source')).toContainText('server') + await expect(page.getByTestId('deferred-resolved')).toContainText( + 'source: server', + ) + }) +}) diff --git a/e2e/streaming-ssr-specs/stream.ts b/e2e/streaming-ssr-specs/stream.ts new file mode 100644 index 0000000000..ee61f170de --- /dev/null +++ b/e2e/streaming-ssr-specs/stream.ts @@ -0,0 +1,55 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +const expectedStreamChunks = [ + 'chunk-0', + 'chunk-1', + 'chunk-2', + 'chunk-3', + 'chunk-4', +] + +test.describe('ReadableStream deserialization', () => { + testWithHydration('promise data deserializes correctly', async ({ page }) => { + await page.goto('/stream') + + await expect(page.getByTestId('promise-data')).toContainText( + 'promise-resolved', + { timeout: 5000 }, + ) + }) + + testWithHydration( + 'stream chunks deserialize in source order', + async ({ page }) => { + await page.goto('/stream') + + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + + const chunks = page + .getByTestId('stream-data') + .locator('[data-testid^="stream-chunk-"]') + await expect(chunks).toHaveText(expectedStreamChunks) + + // This browser assertion covers deserialization and source order. The + // raw `/deferred` assertion covers server-response and router ordering. + }, + ) + + testWithHydration( + 'client-side navigation to stream route works', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Stream' }).first().click() + await expect(page).toHaveURL('/stream') + + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + }, + ) +}) diff --git a/e2e/streaming-ssr-specs/sync-only.ts b/e2e/streaming-ssr-specs/sync-only.ts new file mode 100644 index 0000000000..9850265109 --- /dev/null +++ b/e2e/streaming-ssr-specs/sync-only.ts @@ -0,0 +1,80 @@ +import { + expect, + expectRouterHydrationMarkers, + test, + testWithHydration, +} from '../streaming-ssr-assertions' + +/** + * Tests for synchronous serialization - no deferred data, no streaming. + * This is the most common case where all loader data is immediately available. + * The hydration scripts should be included in the initial HTML response. + */ + +test('Sync-only route renders with loader data', async ({ page }) => { + await page.goto('/sync-only') + + // Verify the page content is rendered + await expect(page.getByTestId('sync-title')).toContainText( + 'Synchronous Serialization Test', + ) + await expect(page.getByTestId('sync-message')).toContainText( + 'Hello from sync loader!', + ) + + // Verify loader data items are rendered + await expect(page.getByTestId('sync-item-item-1')).toBeVisible() + await expect(page.getByTestId('sync-item-item-2')).toBeVisible() + await expect(page.getByTestId('sync-item-item-3')).toBeVisible() + + // Verify the loader ran during SSR. + await expect(page.getByTestId('sync-source')).toContainText('Source: server') +}) + +testWithHydration('Sync-only route hydrates correctly', async ({ page }) => { + await page.goto('/sync-only') + + // Verify client-side navigation works (proves hydration succeeded) + await page.getByRole('navigation').getByRole('link', { name: 'Home' }).click() + await expect(page.getByTestId('index-title')).toBeVisible() + + // Navigate back to sync-only via client-side navigation (use nav link to be specific) + await page + .getByRole('navigation') + .getByRole('link', { name: 'Sync Only' }) + .click() + await expect(page.getByTestId('sync-title')).toBeVisible() +}) + +test('Sync-only route has bootstrap scripts in initial HTML', async ({ + page, +}) => { + // Intercept the response to check the raw HTML + let responseHtml = '' + await page.route('/sync-only', async (route) => { + const response = await route.fetch() + responseHtml = await response.text() + await route.fulfill({ response }) + }) + + await page.goto('/sync-only') + + // Wait for page to load + await expect(page.getByTestId('sync-title')).toBeVisible() + + // Bootstrap, end record, and the boundary rendered by . + expectRouterHydrationMarkers(responseHtml) +}) + +test('Navigating to sync-only from home page', async ({ page }) => { + await page.goto('/') + + await page.getByTestId('link-sync-only').click() + + await expect(page.getByTestId('sync-title')).toContainText( + 'Synchronous Serialization Test', + ) + await expect(page.getByTestId('sync-message')).toContainText( + 'Hello from sync loader!', + ) +}) diff --git a/e2e/vue-router/basepath-file-based/.devcontainer/devcontainer.json b/e2e/vue-router/basepath-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-router/basepath-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-router/basepath-file-based/package.json b/e2e/vue-router/basepath-file-based/package.json index c46fe08228..3af9176e83 100644 --- a/e2e/vue-router/basepath-file-based/package.json +++ b/e2e/vue-router/basepath-file-based/package.json @@ -8,27 +8,26 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-query": "^5.90.0", "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "postcss": "^8.5.1", - "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", + "redaxios": "catalog:", + "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^5.2.3", - "@vitejs/plugin-vue-jsx": "^4.1.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^7.1.7", - "vue-tsc": "^3.1.5" + "vite": "^8.0.14", + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basepath-file-based/playwright.config.ts b/e2e/vue-router/basepath-file-based/playwright.config.ts index 6069bbe59f..4eead86444 100644 --- a/e2e/vue-router/basepath-file-based/playwright.config.ts +++ b/e2e/vue-router/basepath-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basepath-file-based/src/routeTree.gen.ts b/e2e/vue-router/basepath-file-based/src/routeTree.gen.ts index 82b561baf1..75b8119285 100644 --- a/e2e/vue-router/basepath-file-based/src/routeTree.gen.ts +++ b/e2e/vue-router/basepath-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basepath-file-based/vite.config.js b/e2e/vue-router/basepath-file-based/vite.config.js index 1ee80a8b80..baab325d8c 100644 --- a/e2e/vue-router/basepath-file-based/vite.config.js +++ b/e2e/vue-router/basepath-file-based/vite.config.js @@ -2,11 +2,13 @@ import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ base: '/app/', plugins: [ + tailwindcss(), tanstackRouter({ target: 'vue', autoCodeSplitting: true, diff --git a/e2e/vue-router/basic-esbuild-file-based/.devcontainer/devcontainer.json b/e2e/vue-router/basic-esbuild-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-router/basic-esbuild-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-router/basic-esbuild-file-based/package.json b/e2e/vue-router/basic-esbuild-file-based/package.json index 866969a75e..a51cf9149c 100644 --- a/e2e/vue-router/basic-esbuild-file-based/package.json +++ b/e2e/vue-router/basic-esbuild-file-based/package.json @@ -7,29 +7,29 @@ "build": "node src/esbuild.run.js build && vue-tsc --noEmit", "preview": "node src/esbuild.run.js preview", "start": "pnpm dev", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "@tanstack/zod-adapter": "workspace:^", "postcss": "^8.5.1", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.16", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { "@eslint/js": "^9.36.0", - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@typescript-eslint/eslint-plugin": "^8.44.1", "@typescript-eslint/parser": "^8.44.1", - "esbuild": "^0.25.0", + "esbuild": "^0.27.4", "esbuild-plugin-vue3": "^0.5.1", "eslint-plugin-vue": "^9.33.0", - "typescript": "^5.8.3", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vue-eslint-parser": "^9.4.3", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts b/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts index 836ea41bd8..9d9c8d49a3 100644 --- a/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js index c4aba8798e..16f6fbca44 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js +++ b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js @@ -9,7 +9,6 @@ export default { }), tanstackRouter({ target: 'vue', - autoCodeSplitting: true, }), ], } diff --git a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js index 19e882c1a9..0ab294f2bf 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js +++ b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js @@ -1,8 +1,7 @@ -import * as esbuild from 'esbuild' import http from 'node:http' -import { createReadStream } from 'node:fs' -import { promises as fs } from 'node:fs' +import { createReadStream, promises as fs } from 'node:fs' import path from 'node:path' +import * as esbuild from 'esbuild' import esbuildConfig from './esbuild.config.js' const args = process.argv.slice(2) @@ -18,7 +17,7 @@ function getPort() { const fromArg = getArgValue('--port') const fromEnv = process.env.VITE_SERVER_PORT const port = Number(fromArg ?? fromEnv ?? 5601) - if (!Number.isFinite(port) || port <= 0) { + if (!Number.isFinite(port) || port < 0) { throw new Error(`Invalid port: ${String(fromArg ?? fromEnv)}`) } return port @@ -138,7 +137,7 @@ function startStaticServer({ port }) { return new Promise((resolve) => { server.listen(port, () => { - console.log(`http://localhost:${port}`) + console.log(`E2E app: http://localhost:${server.address().port}`) resolve(server) }) }) diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx index 83036509ba..8869cefc01 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx @@ -1,28 +1,32 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' + +const OnlyRouteInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ + from: '/(another-group)/onlyrouteinside', + }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), component: OnlyRouteInsideComponent, }) const routeApi = getRouteApi('/(another-group)/onlyrouteinside') - -function OnlyRouteInsideComponent() { - const searchViaHook = useSearch({ from: '/(another-group)/onlyrouteinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx index 557503a0c2..f2998803fd 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx @@ -1,28 +1,30 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' + +const InsideLayoutComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) export const Route = createFileRoute('/(group)/_layout/insidelayout')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), component: InsideLayoutComponent, }) const routeApi = getRouteApi('/(group)/_layout/insidelayout') - -function InsideLayoutComponent() { - const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx index bec12d8de2..20e0d5afdb 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx @@ -1,28 +1,30 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' + +const InsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) export const Route = createFileRoute('/(group)/inside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), component: InsideComponent, }) const routeApi = getRouteApi('/(group)/inside') - -function InsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx index 56d8d6cae8..a46da658d6 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx @@ -1,28 +1,30 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' + +const LazyInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) export const Route = createFileRoute('/(group)/lazyinside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), component: LazyInsideComponent, }) const routeApi = getRouteApi('/(group)/lazyinside') - -function LazyInsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx index b4487d163d..715d2cc972 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx @@ -1,28 +1,30 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' + +const SubfolderInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) export const Route = createFileRoute('/(group)/subfolder/inside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), component: SubfolderInsideComponent, }) const routeApi = getRouteApi('/(group)/subfolder/inside') - -function SubfolderInsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx index 59c9e6fa48..62c4af3aa4 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { HeadContent, Link, @@ -10,95 +11,97 @@ import { import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' import NotFoundComponent from '../components/NotFoundComponent.vue' +const RootComponent = defineComponent({ + setup() { + const router = useRouter() + const canGoBack = useCanGoBack() + // test useRouterState doesn't crash client side navigation + const _state = useRouterState() + + return () => ( + <> + +
+ + + Home + + + Posts + + + Layout + + + Only Route Inside Group + + + Inside Group + + + Inside Subfolder Inside Group + + + Inside Group Inside Layout + + + Lazy Inside Group + + + unicode path + + + This Route Does Not Exist + +
+
+ + + + ) + }, +}) + export const Route = createRootRoute({ component: RootComponent, notFoundComponent: NotFoundComponent, }) - -function RootComponent() { - const router = useRouter() - const canGoBack = useCanGoBack() - // test useRouterState doesn't crash client side navigation - const _state = useRouterState() - - return ( - <> - -
- - - Home - - - Posts - - - Layout - - - Only Route Inside Group - - - Inside Group - - - Inside Subfolder Inside Group - - - Inside Group Inside Layout - - - Lazy Inside Group - - - unicode path - - - This Route Does Not Exist - -
-
- - - - ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx index 15d17387c8..54ae789c8e 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx @@ -1,24 +1,27 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import PostErrorComponent from '../components/PostErrorComponent.vue' import { fetchPost } from '../posts' import type { PostType } from '../posts' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

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

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

Post not found

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

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

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

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

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

Post not found

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

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

-
{(post.value as PostType).body}
-
- ) -} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx index ae580dfc02..e0afd27b4c 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx @@ -1,7 +1,38 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' import type { PostType } from '../posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...(posts.value as Array), + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -13,31 +44,3 @@ export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...(posts.value as Array), - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) -} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx index 57963c6b64..22979c93c9 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx @@ -1,23 +1,28 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useParams } from '@tanstack/vue-router' +const PostEditComponent = defineComponent({ + setup() { + const paramsViaApi = api.useParams() + const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) + const paramsViaRouteHook = api.useParams() + + return () => ( +
+
{paramsViaHook.value.postId}
+
+ {paramsViaRouteHook.value.postId} +
+
+ {paramsViaApi.value.postId} +
+
+ ) + }, +}) + export const Route = createFileRoute('/posts_/$postId/edit')({ component: PostEditComponent, }) const api = getRouteApi('/posts_/$postId/edit') - -function PostEditComponent() { - const paramsViaApi = api.useParams() - const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) - const paramsViaRouteHook = api.useParams() - - return ( -
-
{paramsViaHook.value.postId}
-
- {paramsViaRouteHook.value.postId} -
-
{paramsViaApi.value.postId}
-
- ) -} diff --git a/e2e/vue-router/basic-file-based-jsx/src/styles.css b/e2e/vue-router/basic-file-based-jsx/src/styles.css index 6a03b331e8..523c2f2f30 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/styles.css +++ b/e2e/vue-router/basic-file-based-jsx/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @source "./**/*.tsx"; diff --git a/e2e/vue-router/basic-file-based-jsx/src/vite-env.d.ts b/e2e/vue-router/basic-file-based-jsx/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/vue-router/basic-file-based-jsx/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts b/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts index 543746d64d..7380859e7b 100644 --- a/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts +++ b/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-file-based-jsx/vite.config.ts b/e2e/vue-router/basic-file-based-jsx/vite.config.ts index 570e6cff2d..466772973f 100644 --- a/e2e/vue-router/basic-file-based-jsx/vite.config.ts +++ b/e2e/vue-router/basic-file-based-jsx/vite.config.ts @@ -2,10 +2,12 @@ import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'vue', autoCodeSplitting: true, diff --git a/e2e/vue-router/basic-file-based-sfc/.devcontainer/devcontainer.json b/e2e/vue-router/basic-file-based-sfc/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-router/basic-file-based-sfc/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-router/basic-file-based-sfc/package.json b/e2e/vue-router/basic-file-based-sfc/package.json index eedbbd34ad..e6ffa156f9 100644 --- a/e2e/vue-router/basic-file-based-sfc/package.json +++ b/e2e/vue-router/basic-file-based-sfc/package.json @@ -8,27 +8,25 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "@tanstack/zod-adapter": "workspace:^", - "postcss": "^8.5.1", - "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", + "redaxios": "catalog:", + "tailwindcss": "^4.2.2", "vue": "^3.5.16", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^5.2.3", - "@vitejs/plugin-vue-jsx": "^4.1.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^7.1.7", - "vue-tsc": "^3.1.5" + "vite": "^8.0.14", + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basic-file-based-sfc/playwright.config.ts b/e2e/vue-router/basic-file-based-sfc/playwright.config.ts index 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic-file-based-sfc/playwright.config.ts +++ b/e2e/vue-router/basic-file-based-sfc/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-file-based-sfc/postcss.config.mjs b/e2e/vue-router/basic-file-based-sfc/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-router/basic-file-based-sfc/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-router/basic-file-based-sfc/src/posts.ts b/e2e/vue-router/basic-file-based-sfc/src/posts.ts index 1b4c92b41d..f7a1941605 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/posts.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/posts.ts @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts b/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts index ed2e49db39..0bfdddab3d 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts @@ -11,75 +11,43 @@ import { lazyRouteComponent } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' -import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' -import { Route as RemountDepsRouteImport } from './routes/remountDeps' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' -import { Route as EditingBRouteImport } from './routes/editing-b' -import { Route as EditingARouteImport } from './routes/editing-a' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as EditingARouteImport } from './routes/editing-a' +import { Route as EditingBRouteImport } from './routes/editing-b' +import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RemountDepsRouteImport } from './routes/remountDeps' +import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' +import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' +import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' +import { Route as groupInsideRouteImport } from './routes/(group)/inside' +import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' -import { Route as groupInsideRouteImport } from './routes/(group)/inside' -import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' -import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' -import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' +import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -const Char45824Char54620Char48124Char44397Route = - Char45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => rootRouteImport, - } as any).update({ - component: lazyRouteComponent( - () => import('./routes/대한민국.component.vue'), - 'default', - ), - }) -const RemountDepsRoute = RemountDepsRouteImport.update({ - id: '/remountDeps', - path: '/remountDeps', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/remountDeps.component.vue'), + () => import('./routes/index.component.vue'), 'default', ), }) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/posts.component.vue'), - 'default', - ), -}) -const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ - id: '/notRemountDeps', - path: '/notRemountDeps', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/notRemountDeps.component.vue'), - 'default', - ), -}) -const EditingBRoute = EditingBRouteImport.update({ - id: '/editing-b', - path: '/editing-b', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/editing-b.component.vue'), + () => import('./routes/_layout.component.vue'), 'default', ), }) @@ -93,22 +61,110 @@ const EditingARoute = EditingARouteImport.update({ 'default', ), }) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const EditingBRoute = EditingBRouteImport.update({ + id: '/editing-b', + path: '/editing-b', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout.component.vue'), + () => import('./routes/editing-b.component.vue'), 'default', ), }) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ + id: '/notRemountDeps', + path: '/notRemountDeps', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/index.component.vue'), + () => import('./routes/notRemountDeps.component.vue'), + 'default', + ), +}) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/posts.component.vue'), + 'default', + ), +}) +const RemountDepsRoute = RemountDepsRouteImport.update({ + id: '/remountDeps', + path: '/remountDeps', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/remountDeps.component.vue'), + 'default', + ), +}) +const Char45824Char54620Char48124Char44397Route = + Char45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => rootRouteImport, + } as any).update({ + component: lazyRouteComponent( + () => import('./routes/대한민국.component.vue'), + 'default', + ), + }) +const anotherGroupOnlyrouteinsideRoute = anotherGroupOnlyrouteinsideRouteImport + .update({ + id: '/(another-group)/onlyrouteinside', + path: '/onlyrouteinside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(another-group)/onlyrouteinside.component.vue'), + 'default', + ), + }) +const groupLayoutRoute = groupLayoutRouteImport + .update({ + id: '/(group)/_layout', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/_layout.component.vue'), + 'default', + ), + }) +const groupInsideRoute = groupInsideRouteImport + .update({ + id: '/(group)/inside', + path: '/inside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/inside.component.vue'), + 'default', + ), + }) +const groupLazyinsideRoute = groupLazyinsideRouteImport + .update({ + id: '/(group)/lazyinside', + path: '/lazyinside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/lazyinside.component.vue'), + 'default', + ), + }) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/_layout/_layout-2.component.vue'), 'default', ), }) @@ -136,69 +192,37 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ 'default', ), }) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport + .update({ + id: '/insidelayout', + path: '/insidelayout', + getParentRoute: () => groupLayoutRoute, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/_layout.insidelayout.component.vue'), + 'default', + ), + }) +const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport + .update({ + id: '/(group)/subfolder/inside', + path: '/subfolder/inside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/subfolder/inside.component.vue'), + 'default', + ), + }) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout/_layout-2.component.vue'), - 'default', - ), -}) -const groupLazyinsideRoute = groupLazyinsideRouteImport - .update({ - id: '/(group)/lazyinside', - path: '/lazyinside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/lazyinside.component.vue'), - 'default', - ), - }) -const groupInsideRoute = groupInsideRouteImport - .update({ - id: '/(group)/inside', - path: '/inside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/inside.component.vue'), - 'default', - ), - }) -const groupLayoutRoute = groupLayoutRouteImport - .update({ - id: '/(group)/_layout', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/_layout.component.vue'), - 'default', - ), - }) -const anotherGroupOnlyrouteinsideRoute = anotherGroupOnlyrouteinsideRouteImport - .update({ - id: '/(another-group)/onlyrouteinside', - path: '/onlyrouteinside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(another-group)/onlyrouteinside.component.vue'), - 'default', - ), - }) -const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ - id: '/posts_/$postId/edit', - path: '/posts/$postId/edit', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/posts_.$postId.edit.component.vue'), + () => import('./routes/_layout/_layout-2/layout-a.component.vue'), 'default', ), }) @@ -212,40 +236,16 @@ const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ 'default', ), }) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ + id: '/posts_/$postId/edit', + path: '/posts/$postId/edit', + getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout/_layout-2/layout-a.component.vue'), + () => import('./routes/posts_.$postId.edit.component.vue'), 'default', ), }) -const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport - .update({ - id: '/(group)/subfolder/inside', - path: '/subfolder/inside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/subfolder/inside.component.vue'), - 'default', - ), - }) -const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport - .update({ - id: '/insidelayout', - path: '/insidelayout', - getParentRoute: () => groupLayoutRoute, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/_layout.insidelayout.component.vue'), - 'default', - ), - }) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -388,39 +388,18 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/remountDeps': { - id: '/remountDeps' - path: '/remountDeps' - fullPath: '/remountDeps' - preLoaderRoute: typeof RemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/notRemountDeps': { - id: '/notRemountDeps' - path: '/notRemountDeps' - fullPath: '/notRemountDeps' - preLoaderRoute: typeof NotRemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-b': { - id: '/editing-b' - path: '/editing-b' - fullPath: '/editing-b' - preLoaderRoute: typeof EditingBRouteImport + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } '/editing-a': { @@ -430,20 +409,76 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof EditingARouteImport parentRoute: typeof rootRouteImport } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutRouteImport + '/editing-b': { + id: '/editing-b' + path: '/editing-b' + fullPath: '/editing-b' + preLoaderRoute: typeof EditingBRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/notRemountDeps': { + id: '/notRemountDeps' + path: '/notRemountDeps' + fullPath: '/notRemountDeps' + preLoaderRoute: typeof NotRemountDepsRouteImport parentRoute: typeof rootRouteImport } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/remountDeps': { + id: '/remountDeps' + path: '/remountDeps' + fullPath: '/remountDeps' + preLoaderRoute: typeof RemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/대한민국': { + id: '/대한민국' + path: '/대한민국' + fullPath: '/대한민국' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + parentRoute: typeof rootRouteImport + } + '/(another-group)/onlyrouteinside': { + id: '/(another-group)/onlyrouteinside' + path: '/onlyrouteinside' + fullPath: '/onlyrouteinside' + preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/_layout': { + id: '/(group)/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof groupLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/inside': { + id: '/(group)/inside' + path: '/inside' + fullPath: '/inside' + preLoaderRoute: typeof groupInsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/lazyinside': { + id: '/(group)/lazyinside' + path: '/lazyinside' + fullPath: '/lazyinside' + preLoaderRoute: typeof groupLazyinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } '/posts/': { id: '/posts/' path: '/' @@ -458,61 +493,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/(group)/lazyinside': { - id: '/(group)/lazyinside' - path: '/lazyinside' - fullPath: '/lazyinside' - preLoaderRoute: typeof groupLazyinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/inside': { - id: '/(group)/inside' - path: '/inside' - fullPath: '/inside' - preLoaderRoute: typeof groupInsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/_layout': { - id: '/(group)/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof groupLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/(another-group)/onlyrouteinside': { - id: '/(another-group)/onlyrouteinside' - path: '/onlyrouteinside' - fullPath: '/onlyrouteinside' - preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/posts_/$postId/edit': { - id: '/posts_/$postId/edit' - path: '/posts/$postId/edit' - fullPath: '/posts/$postId/edit' - preLoaderRoute: typeof PostsPostIdEditRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/(group)/_layout/insidelayout': { + id: '/(group)/_layout/insidelayout' + path: '/insidelayout' + fullPath: '/insidelayout' + preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport + parentRoute: typeof groupLayoutRoute } '/(group)/subfolder/inside': { id: '/(group)/subfolder/inside' @@ -521,12 +507,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof groupSubfolderInsideRouteImport parentRoute: typeof rootRouteImport } - '/(group)/_layout/insidelayout': { - id: '/(group)/_layout/insidelayout' - path: '/insidelayout' - fullPath: '/insidelayout' - preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport - parentRoute: typeof groupLayoutRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/posts_/$postId/edit': { + id: '/posts_/$postId/edit' + path: '/posts/$postId/edit' + fullPath: '/posts/$postId/edit' + preLoaderRoute: typeof PostsPostIdEditRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/e2e/vue-router/basic-file-based-sfc/src/routes/(another-group)/onlyrouteinside.ts b/e2e/vue-router/basic-file-based-sfc/src/routes/(another-group)/onlyrouteinside.ts index 491bb03649..f427c79321 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/routes/(another-group)/onlyrouteinside.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/routes/(another-group)/onlyrouteinside.ts @@ -1,7 +1,6 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), }) diff --git a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/_layout.insidelayout.ts b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/_layout.insidelayout.ts index 49ef8f7bb9..3b605763af 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/_layout.insidelayout.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/_layout.insidelayout.ts @@ -1,7 +1,6 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/_layout/insidelayout')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), }) diff --git a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/inside.ts b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/inside.ts index f7b06f6a94..456e8fe169 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/inside.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/inside.ts @@ -1,7 +1,6 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/inside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), }) diff --git a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/lazyinside.ts b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/lazyinside.ts index b66d18a729..7fba56aae4 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/lazyinside.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/lazyinside.ts @@ -1,7 +1,6 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/lazyinside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), }) diff --git a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/subfolder/inside.ts b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/subfolder/inside.ts index 50aa8a44ad..21e5d7ba0a 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/subfolder/inside.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/routes/(group)/subfolder/inside.ts @@ -1,7 +1,6 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/subfolder/inside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), }) diff --git a/e2e/vue-router/basic-file-based-sfc/src/styles.css b/e2e/vue-router/basic-file-based-sfc/src/styles.css index 237cc5590d..173bee6195 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/styles.css +++ b/e2e/vue-router/basic-file-based-sfc/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @source "./**/*.vue"; @source "./**/*.ts"; diff --git a/e2e/vue-router/basic-file-based-sfc/src/vite-env.d.ts b/e2e/vue-router/basic-file-based-sfc/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/vue-router/basic-file-based-sfc/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts b/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts index 543746d64d..7380859e7b 100644 --- a/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts +++ b/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-file-based-sfc/vite.config.ts b/e2e/vue-router/basic-file-based-sfc/vite.config.ts index 570e6cff2d..466772973f 100644 --- a/e2e/vue-router/basic-file-based-sfc/vite.config.ts +++ b/e2e/vue-router/basic-file-based-sfc/vite.config.ts @@ -2,10 +2,12 @@ import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'vue', autoCodeSplitting: true, diff --git a/e2e/vue-router/basic-scroll-restoration/.devcontainer/devcontainer.json b/e2e/vue-router/basic-scroll-restoration/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-router/basic-scroll-restoration/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-router/basic-scroll-restoration/package.json b/e2e/vue-router/basic-scroll-restoration/package.json index d00feacb5a..f4616a5651 100644 --- a/e2e/vue-router/basic-scroll-restoration/package.json +++ b/e2e/vue-router/basic-scroll-restoration/package.json @@ -8,25 +8,24 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-virtual": "^3.13.0", - "postcss": "^8.5.1", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.16", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^5.2.3", - "@vitejs/plugin-vue-jsx": "^4.1.2", - "typescript": "~5.8.3", - "vite": "^7.1.7", - "vue-tsc": "^3.1.5" + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "vite": "^8.0.14", + "vue-tsc": "^3.3.8", + "typescript": "~5.9.0" } } diff --git a/e2e/vue-router/basic-scroll-restoration/playwright.config.ts b/e2e/vue-router/basic-scroll-restoration/playwright.config.ts index 0c5cee43e4..6a684ac89e 100644 --- a/e2e/vue-router/basic-scroll-restoration/playwright.config.ts +++ b/e2e/vue-router/basic-scroll-restoration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-scroll-restoration/postcss.config.mjs b/e2e/vue-router/basic-scroll-restoration/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-router/basic-scroll-restoration/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-router/basic-scroll-restoration/src/styles.css b/e2e/vue-router/basic-scroll-restoration/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/e2e/vue-router/basic-scroll-restoration/src/styles.css +++ b/e2e/vue-router/basic-scroll-restoration/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-router/basic-scroll-restoration/src/vite-env.d.ts b/e2e/vue-router/basic-scroll-restoration/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/vue-router/basic-scroll-restoration/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/vue-router/basic-scroll-restoration/vite.config.js b/e2e/vue-router/basic-scroll-restoration/vite.config.js index 33d651a84c..e221c1e0e9 100644 --- a/e2e/vue-router/basic-scroll-restoration/vite.config.js +++ b/e2e/vue-router/basic-scroll-restoration/vite.config.js @@ -1,8 +1,9 @@ import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [vue(), vueJsx()], + plugins: [tailwindcss(), vue(), vueJsx()], }) diff --git a/e2e/vue-router/basic-virtual-file-based/.devcontainer/devcontainer.json b/e2e/vue-router/basic-virtual-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-router/basic-virtual-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-router/basic-virtual-file-based/package.json b/e2e/vue-router/basic-virtual-file-based/package.json index bf094e7d01..3701c2254c 100644 --- a/e2e/vue-router/basic-virtual-file-based/package.json +++ b/e2e/vue-router/basic-virtual-file-based/package.json @@ -8,28 +8,27 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/virtual-file-routes": "workspace:^", "@tanstack/vue-query": "^5.90.0", "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "postcss": "^8.5.1", - "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", + "redaxios": "catalog:", + "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^5.2.3", - "@vitejs/plugin-vue-jsx": "^4.1.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^7.1.7", - "vue-tsc": "^3.1.5" + "vite": "^8.0.14", + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basic-virtual-file-based/playwright.config.ts b/e2e/vue-router/basic-virtual-file-based/playwright.config.ts index 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic-virtual-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-virtual-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-virtual-file-based/postcss.config.mjs b/e2e/vue-router/basic-virtual-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-router/basic-virtual-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-router/basic-virtual-file-based/src/posts.tsx b/e2e/vue-router/basic-virtual-file-based/src/posts.tsx index 8576a3799a..5f5463a668 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts b/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts index 49926e7792..1bae3d69a1 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts +++ b/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts @@ -8,79 +8,77 @@ // You should NOT make any changes in this file as it will be overwritten. // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. -import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/vue-router' - import { Route as rootRouteImport } from './routes/root' -import { Route as postsPostsRouteImport } from './routes/posts/posts' -import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' import { Route as homeRouteImport } from './routes/home' -import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' +import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' +import { Route as postsPostsRouteImport } from './routes/posts/posts' import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' -import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' -import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' -import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' -import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' -import { Route as bRouteImport } from './routes/b' +import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' import { Route as aRouteImport } from './routes/a' +import { Route as bRouteImport } from './routes/b' +import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' +import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' +import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' -const postsPostsRoute = postsPostsRouteImport.update({ - id: '/posts', - path: '/posts', +const homeRoute = homeRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', +const postsPostsRoute = postsPostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => postsPostsRoute, -} as any) const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ id: '/_second', getParentRoute: () => layoutFirstLayoutRoute, } as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => postsPostsRoute, -} as any) const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ id: '/classic/hello', path: '/classic/hello', getParentRoute: () => rootRouteImport, } as any) +const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => postsPostsRoute, +} as any) +const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => postsPostsRoute, +} as any) +const aRoute = aRouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) +const bRoute = bRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) const ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ - id: '/world', - path: '/world', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ id: '/universe', path: '/universe', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const bRoute = bRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => layoutSecondLayoutRoute, -} as any) -const aRoute = aRouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => layoutSecondLayoutRoute, +const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ + id: '/world', + path: '/world', + getParentRoute: () => ClassicHelloRouteRoute, } as any) export interface FileRoutesByFullPath { @@ -168,20 +166,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof postsPostsRouteImport - parentRoute: typeof rootRouteImport - } - '/_first': { - id: '/_first' - path: '' - fullPath: '' - preLoaderRoute: typeof layoutFirstLayoutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -189,27 +173,27 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof homeRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof postsPostsDetailRouteImport - parentRoute: typeof postsPostsRoute + '/_first': { + id: '/_first' + path: '' + fullPath: '/' + preLoaderRoute: typeof layoutFirstLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof postsPostsRouteImport + parentRoute: typeof rootRouteImport } '/_first/_second': { id: '/_first/_second' path: '' - fullPath: '' + fullPath: '/' preLoaderRoute: typeof layoutSecondLayoutRouteImport parentRoute: typeof layoutFirstLayoutRoute } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute - } '/classic/hello': { id: '/classic/hello' path: '/classic/hello' @@ -217,6 +201,34 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloRouteRouteImport parentRoute: typeof rootRouteImport } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof postsPostsHomeRouteImport + parentRoute: typeof postsPostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof postsPostsDetailRouteImport + parentRoute: typeof postsPostsRoute + } + '/_first/_second/layout-a': { + id: '/_first/_second/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof aRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } + '/_first/_second/layout-b': { + id: '/_first/_second/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof bRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -224,13 +236,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/world': { - id: '/classic/hello/world' - path: '/world' - fullPath: '/classic/hello/world' - preLoaderRoute: typeof ClassicHelloWorldRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/universe': { id: '/classic/hello/universe' path: '/universe' @@ -238,132 +243,16 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloUniverseRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second/layout-b': { - id: '/_first/_second/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof bRouteImport - parentRoute: typeof layoutSecondLayoutRoute - } - '/_first/_second/layout-a': { - id: '/_first/_second/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof aRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/world': { + id: '/classic/hello/world' + path: '/world' + fullPath: '/classic/hello/world' + preLoaderRoute: typeof ClassicHelloWorldRouteImport + parentRoute: typeof ClassicHelloRouteRoute } } } -declare module './routes/home' { - const createFileRoute: CreateFileRoute< - '/', - FileRoutesByPath['/']['parentRoute'], - FileRoutesByPath['/']['id'], - FileRoutesByPath['/']['path'], - FileRoutesByPath['/']['fullPath'] - > -} -declare module './routes/layout/first-layout' { - const createFileRoute: CreateFileRoute< - '/_first', - FileRoutesByPath['/_first']['parentRoute'], - FileRoutesByPath['/_first']['id'], - FileRoutesByPath['/_first']['path'], - FileRoutesByPath['/_first']['fullPath'] - > -} -declare module './routes/posts/posts' { - const createFileRoute: CreateFileRoute< - '/posts', - FileRoutesByPath['/posts']['parentRoute'], - FileRoutesByPath['/posts']['id'], - FileRoutesByPath['/posts']['path'], - FileRoutesByPath['/posts']['fullPath'] - > -} -declare module './routes/file-based-subtree/hello/route' { - const createFileRoute: CreateFileRoute< - '/classic/hello', - FileRoutesByPath['/classic/hello']['parentRoute'], - FileRoutesByPath['/classic/hello']['id'], - FileRoutesByPath['/classic/hello']['path'], - FileRoutesByPath['/classic/hello']['fullPath'] - > -} -declare module './routes/posts/posts-home' { - const createFileRoute: CreateFileRoute< - '/posts/', - FileRoutesByPath['/posts/']['parentRoute'], - FileRoutesByPath['/posts/']['id'], - FileRoutesByPath['/posts/']['path'], - FileRoutesByPath['/posts/']['fullPath'] - > -} -declare module './routes/layout/second-layout' { - const createFileRoute: CreateFileRoute< - '/_first/_second', - FileRoutesByPath['/_first/_second']['parentRoute'], - FileRoutesByPath['/_first/_second']['id'], - FileRoutesByPath['/_first/_second']['path'], - FileRoutesByPath['/_first/_second']['fullPath'] - > -} -declare module './routes/posts/posts-detail' { - const createFileRoute: CreateFileRoute< - '/posts/$postId', - FileRoutesByPath['/posts/$postId']['parentRoute'], - FileRoutesByPath['/posts/$postId']['id'], - FileRoutesByPath['/posts/$postId']['path'], - FileRoutesByPath['/posts/$postId']['fullPath'] - > -} -declare module './routes/a' { - const createFileRoute: CreateFileRoute< - '/_first/_second/layout-a', - FileRoutesByPath['/_first/_second/layout-a']['parentRoute'], - FileRoutesByPath['/_first/_second/layout-a']['id'], - FileRoutesByPath['/_first/_second/layout-a']['path'], - FileRoutesByPath['/_first/_second/layout-a']['fullPath'] - > -} -declare module './routes/b' { - const createFileRoute: CreateFileRoute< - '/_first/_second/layout-b', - FileRoutesByPath['/_first/_second/layout-b']['parentRoute'], - FileRoutesByPath['/_first/_second/layout-b']['id'], - FileRoutesByPath['/_first/_second/layout-b']['path'], - FileRoutesByPath['/_first/_second/layout-b']['fullPath'] - > -} -declare module './routes/file-based-subtree/hello/universe' { - const createFileRoute: CreateFileRoute< - '/classic/hello/universe', - FileRoutesByPath['/classic/hello/universe']['parentRoute'], - FileRoutesByPath['/classic/hello/universe']['id'], - FileRoutesByPath['/classic/hello/universe']['path'], - FileRoutesByPath['/classic/hello/universe']['fullPath'] - > -} -declare module './routes/file-based-subtree/hello/world' { - const createFileRoute: CreateFileRoute< - '/classic/hello/world', - FileRoutesByPath['/classic/hello/world']['parentRoute'], - FileRoutesByPath['/classic/hello/world']['id'], - FileRoutesByPath['/classic/hello/world']['path'], - FileRoutesByPath['/classic/hello/world']['fullPath'] - > -} -declare module './routes/file-based-subtree/hello/index' { - const createFileRoute: CreateFileRoute< - '/classic/hello/', - FileRoutesByPath['/classic/hello/']['parentRoute'], - FileRoutesByPath['/classic/hello/']['id'], - FileRoutesByPath['/classic/hello/']['path'], - FileRoutesByPath['/classic/hello/']['fullPath'] - > -} - interface layoutSecondLayoutRouteChildren { aRoute: typeof aRoute bRoute: typeof bRoute diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/a.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/a.tsx index a190b24202..133d40f19e 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/a.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/a.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/_first/_second/layout-a')({ component: LayoutAComponent, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/b.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/b.tsx index 505f8f6fbf..caae6c1ded 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/b.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/b.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/_first/_second/layout-b')({ component: LayoutBComponent, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx index f86335e291..9b0d21d191 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/classic/hello/')({ component: () =>
This is the index
, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx index f07d58fd3e..24c72f2fb9 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet } from '@tanstack/vue-router' +import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/classic/hello')({ component: () => (
Hello! diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx index 20b07c41cc..650dd2ee62 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/classic/hello/universe')({ component: () =>
Hello /classic/hello/universe!
, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx index 4af11357a2..c752e6b5a4 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/classic/hello/world')({ component: () =>
Hello /classic/hello/world!
, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/home.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/home.tsx index 510db79b73..acf99ce567 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/home.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/home.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/')({ component: Home, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/layout/first-layout.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/layout/first-layout.tsx index 9e66c18e33..7b82bcd7c5 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/layout/first-layout.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/layout/first-layout.tsx @@ -1,6 +1,6 @@ -import { Outlet } from '@tanstack/vue-router' +import { Outlet, createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_first')({ component: LayoutComponent, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/layout/second-layout.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/layout/second-layout.tsx index acb6d2c8ae..cc1dafa5a1 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/layout/second-layout.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/layout/second-layout.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet } from '@tanstack/vue-router' +import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_first/_second')({ component: LayoutComponent, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx index 9b416bcf82..aa5387a4d8 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx @@ -1,4 +1,5 @@ -import { ErrorComponent } from '@tanstack/vue-router' +import { defineComponent } from 'vue' +import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,7 +7,20 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } -export const Route = createFileRoute({ +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

{post.value?.title}

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

{post.value?.title}

-
{post.value?.body}
-
- ) -} diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-home.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-home.tsx index 13529228bb..67a4268fae 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-home.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-home.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/posts/')({ component: PostsIndexComponent, }) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx index 5942bac97e..2a4e8deddd 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx @@ -1,39 +1,42 @@ -import { Link, Outlet } from '@tanstack/vue-router' +import { defineComponent } from 'vue' +import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' -export const Route = createFileRoute({ +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) + }, +}) + +export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/e2e/vue-router/basic-virtual-file-based/src/styles.css b/e2e/vue-router/basic-virtual-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/styles.css +++ b/e2e/vue-router/basic-virtual-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-router/basic-virtual-file-based/src/vite-env.d.ts b/e2e/vue-router/basic-virtual-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/vue-router/basic-virtual-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts b/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts index 3e5a69ccaa..fbf093cd51 100644 --- a/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-virtual-file-based/vite.config.ts b/e2e/vue-router/basic-virtual-file-based/vite.config.ts index fba56c6ce5..d9f5956b33 100644 --- a/e2e/vue-router/basic-virtual-file-based/vite.config.ts +++ b/e2e/vue-router/basic-virtual-file-based/vite.config.ts @@ -3,14 +3,15 @@ import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import { tanstackRouter } from '@tanstack/router-plugin/vite' import { routes } from './routes' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'vue', autoCodeSplitting: true, - verboseFileRoutes: false, virtualRouteConfig: routes, }), vue(), diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json b/e2e/vue-router/basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} 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 1bb1009339..d3a69ed573 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/package.json +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/package.json @@ -8,28 +8,27 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/virtual-file-routes": "workspace:^", "@tanstack/vue-query": "^5.90.0", "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "postcss": "^8.5.1", - "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", + "redaxios": "catalog:", + "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^5.2.3", - "@vitejs/plugin-vue-jsx": "^4.1.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^7.1.7", - "vue-tsc": "^3.1.5" + "vite": "^8.0.14", + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts index 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/postcss.config.mjs b/e2e/vue-router/basic-virtual-named-export-config-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx index 8576a3799a..5f5463a668 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/a.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/a.tsx index a190b24202..133d40f19e 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/a.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/a.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/_first/_second/layout-a')({ component: LayoutAComponent, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/b.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/b.tsx index 505f8f6fbf..caae6c1ded 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/b.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/b.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/_first/_second/layout-b')({ component: LayoutBComponent, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/index.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/index.tsx index f86335e291..9b0d21d191 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/index.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/index.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/classic/hello/')({ component: () =>
This is the index
, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/route.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/route.tsx index f07d58fd3e..24c72f2fb9 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/route.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/route.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet } from '@tanstack/vue-router' +import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/classic/hello')({ component: () => (
Hello! diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/universe.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/universe.tsx index 20b07c41cc..650dd2ee62 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/universe.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/universe.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/classic/hello/universe')({ component: () =>
Hello /classic/hello/universe!
, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/world.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/world.tsx index 4af11357a2..c752e6b5a4 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/world.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/file-based-subtree/hello/world.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/classic/hello/world')({ component: () =>
Hello /classic/hello/world!
, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/home.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/home.tsx index 510db79b73..acf99ce567 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/home.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/home.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/')({ component: Home, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/first-layout.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/first-layout.tsx index 9e66c18e33..7b82bcd7c5 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/first-layout.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/first-layout.tsx @@ -1,6 +1,6 @@ -import { Outlet } from '@tanstack/vue-router' +import { Outlet, createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_first')({ component: LayoutComponent, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/second-layout.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/second-layout.tsx index acb6d2c8ae..cc1dafa5a1 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/second-layout.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/layout/second-layout.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet } from '@tanstack/vue-router' +import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_first/_second')({ component: LayoutComponent, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx index 9b416bcf82..aa5387a4d8 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx @@ -1,4 +1,5 @@ -import { ErrorComponent } from '@tanstack/vue-router' +import { defineComponent } from 'vue' +import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,7 +7,20 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } -export const Route = createFileRoute({ +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

{post.value?.title}

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

{post.value?.title}

-
{post.value?.body}
-
- ) -} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-home.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-home.tsx index 13529228bb..67a4268fae 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-home.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-home.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/posts/')({ component: PostsIndexComponent, }) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx index 5942bac97e..2a4e8deddd 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx @@ -1,39 +1,42 @@ -import { Link, Outlet } from '@tanstack/vue-router' +import { defineComponent } from 'vue' +import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' -export const Route = createFileRoute({ +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) + }, +}) + +export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/styles.css b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/styles.css index 4fea791308..0bd1287c82 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/styles.css +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @source './**/*.{js,jsx,ts,tsx}'; diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/vite-env.d.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts index 3e5a69ccaa..fbf093cd51 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/vite.config.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/vite.config.ts index dc5c9283f5..f02a0c0d95 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/vite.config.ts +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/vite.config.ts @@ -2,14 +2,15 @@ import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'vue', autoCodeSplitting: true, - verboseFileRoutes: false, virtualRouteConfig: './routes.ts', }), vue(), diff --git a/e2e/vue-router/basic-vue-query-file-based/.devcontainer/devcontainer.json b/e2e/vue-router/basic-vue-query-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-router/basic-vue-query-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} 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 51c83d23dc..3b4422d8d8 100644 --- a/e2e/vue-router/basic-vue-query-file-based/package.json +++ b/e2e/vue-router/basic-vue-query-file-based/package.json @@ -8,28 +8,27 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-query": "^5.90.0", "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "@tanstack/router-plugin": "workspace:^", - "postcss": "^8.5.1", - "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", + "redaxios": "catalog:", + "tailwindcss": "^4.2.2", "vue": "^3.5.16", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^5.2.3", - "@vitejs/plugin-vue-jsx": "^4.1.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^7.1.7", - "vue-tsc": "^3.1.5" + "vite": "^8.0.14", + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts b/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts index 6e7c123f74..fbda9bd451 100644 --- a/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -17,17 +12,15 @@ export default defineConfig({ workers: 1, reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-vue-query-file-based/postcss.config.mjs b/e2e/vue-router/basic-vue-query-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-router/basic-vue-query-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx b/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx index 1becc2c242..1f6cb8e308 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx @@ -8,11 +8,7 @@ export type PostType = { export class PostNotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts b/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts index ef4bc90b1f..0af0e21dbd 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts +++ b/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts @@ -9,29 +9,33 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const LayoutRoute = LayoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,20 +46,16 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -114,6 +114,20 @@ 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 + } '/posts': { id: '/posts' path: '/posts' @@ -121,19 +135,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/_layout': { - id: '/_layout' + '/_layout/_layout-2': { + id: '/_layout/_layout-2' path: '' - fullPath: '' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute } '/posts/': { id: '/posts/' @@ -149,12 +156,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' @@ -163,13 +170,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route - } } } diff --git a/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx b/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx index 72109fc891..e8b66ddf5d 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { ErrorComponent, useRouter } from '@tanstack/vue-router' import { useQuery } from '@tanstack/vue-query' @@ -5,6 +6,21 @@ import { PostNotFoundError } from '../posts' import { postQueryOptions } from '../postQueryOptions' import type { ErrorComponentProps } from '@tanstack/vue-router' +const PostComponent = defineComponent({ + setup() { + const params = Route.useParams() + useQuery(() => postQueryOptions(params.value.postId)) + const post = Route.useLoaderData() + + return () => ( +
+

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

ParamsNamedFoo

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

ParamsNamedFoo

+

ParamsNamedFooPrefix

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

ParamsNamedFooPrefix

+

ParamsNamedFooSuffix

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

ParamsNamedFooSuffix

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

ParamsWildcardSplat

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

ParamsWildcardSplat

+

ParamsWildcardSplatPrefix

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

ParamsWildcardSplatPrefix

+

ParamsWildcardSplatSuffix

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

ParamsWildcardSplatSuffix

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

{post.value.title}

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

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx b/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx index eaaa35fd5c..518bdc3d70 100644 --- a/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx +++ b/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx @@ -1,39 +1,42 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' +const PostsLayoutComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsLayoutComponent, }) - -function PostsLayoutComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/e2e/vue-router/generator-cli-only/src/styles.css b/e2e/vue-router/generator-cli-only/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/e2e/vue-router/generator-cli-only/src/styles.css +++ b/e2e/vue-router/generator-cli-only/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-router/generator-cli-only/src/vite-env.d.ts b/e2e/vue-router/generator-cli-only/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/vue-router/generator-cli-only/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/vue-router/generator-cli-only/tests/app.spec.ts b/e2e/vue-router/generator-cli-only/tests/app.spec.ts index 5a83a314f2..ced5ac9310 100644 --- a/e2e/vue-router/generator-cli-only/tests/app.spec.ts +++ b/e2e/vue-router/generator-cli-only/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts b/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts b/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/generator-cli-only/vite.config.js b/e2e/vue-router/generator-cli-only/vite.config.js index 33d651a84c..e221c1e0e9 100644 --- a/e2e/vue-router/generator-cli-only/vite.config.js +++ b/e2e/vue-router/generator-cli-only/vite.config.js @@ -1,8 +1,9 @@ import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [vue(), vueJsx()], + plugins: [tailwindcss(), vue(), vueJsx()], }) diff --git a/e2e/vue-router/js-only-file-based/.devcontainer/devcontainer.json b/e2e/vue-router/js-only-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-router/js-only-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-router/js-only-file-based/package.json b/e2e/vue-router/js-only-file-based/package.json index 76fa3dcfce..cda098978c 100644 --- a/e2e/vue-router/js-only-file-based/package.json +++ b/e2e/vue-router/js-only-file-based/package.json @@ -8,25 +8,24 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-query": "^5.90.0", "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "postcss": "^8.5.1", - "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", + "redaxios": "catalog:", + "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^5.2.3", - "@vitejs/plugin-vue-jsx": "^4.1.2", - "vite": "^7.1.7" + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "vite": "^8.0.14" } } diff --git a/e2e/vue-router/js-only-file-based/playwright.config.ts b/e2e/vue-router/js-only-file-based/playwright.config.ts index 4f93bc1413..0925936d55 100644 --- a/e2e/vue-router/js-only-file-based/playwright.config.ts +++ b/e2e/vue-router/js-only-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,18 +13,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/js-only-file-based/postcss.config.mjs b/e2e/vue-router/js-only-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-router/js-only-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-router/js-only-file-based/src/posts.js b/e2e/vue-router/js-only-file-based/src/posts.js index 979e5e381c..36c1c281f6 100644 --- a/e2e/vue-router/js-only-file-based/src/posts.js +++ b/e2e/vue-router/js-only-file-based/src/posts.js @@ -2,11 +2,7 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts b/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts index aabddd8880..decb53754c 100644 --- a/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts +++ b/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts @@ -9,15 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -27,11 +32,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,10 +47,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -53,12 +59,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,10 +117,17 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' - fullPath: '' + fullPath: '/' preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } @@ -131,12 +138,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/posts/': { id: '/posts/' @@ -152,12 +159,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -166,13 +173,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx b/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx index b769e23862..05599a6780 100644 --- a/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx +++ b/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx @@ -1,8 +1,22 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { ErrorComponent } from '@tanstack/vue-router' import { fetchPost } from '../posts' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx index 265faaf650..2a4e8deddd 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx @@ -1,39 +1,42 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/styles.css b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/styles.css index 4fea791308..0bd1287c82 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/styles.css +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @source './**/*.{js,jsx,ts,tsx}'; diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts index 10beff655f..d230263bfe 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json index 23855253ad..ff457aa547 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json @@ -13,6 +13,6 @@ "useDefineForClassFields": true, "allowJs": true }, - "include": ["src", "playwright.config.ts", "tests", "./routes.ts"], + "include": ["src", "tests", "./routes.ts"], "exclude": ["node_modules", "dist"] } diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/.devcontainer/devcontainer.json b/e2e/vue-router/scroll-restoration-sandbox-vite/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-BwsVWHwV.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-BwsVWHwV.js deleted file mode 100644 index 1f78534259..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-BwsVWHwV.js +++ /dev/null @@ -1,18 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/page-with-search-BhJv4yJI.js","assets/scroll-block-BAas_Ct-.js","assets/normal-page-BPOVyYTF.js","assets/virtual-page.lazy-BCqvdivF.js","assets/lazy-with-loader-page.lazy-BzLmn584.js","assets/lazy-page.lazy-BzoMuhUY.js"])))=>i.map(i=>d[i]); -(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();/** -* @vue/shared v3.5.25 -* (c) 2018-present Yuxi (Evan) You and Vue contributors -* @license MIT -**/function Or(e){const t=Object.create(null);for(const s of e.split(","))t[s]=1;return s=>s in t}const me={},_s=[],Xe=()=>{},Eo=()=>!1,In=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),Ar=e=>e.startsWith("onUpdate:"),be=Object.assign,Nr=(e,t)=>{const s=e.indexOf(t);s>-1&&e.splice(s,1)},tc=Object.prototype.hasOwnProperty,le=(e,t)=>tc.call(e,t),X=Array.isArray,bs=e=>Ln(e)==="[object Map]",sc=e=>Ln(e)==="[object Set]",Y=e=>typeof e=="function",xe=e=>typeof e=="string",as=e=>typeof e=="symbol",ge=e=>e!==null&&typeof e=="object",Oo=e=>(ge(e)||Y(e))&&Y(e.then)&&Y(e.catch),nc=Object.prototype.toString,Ln=e=>nc.call(e),rc=e=>Ln(e).slice(8,-1),ic=e=>Ln(e)==="[object Object]",Fr=e=>xe(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,xs=Or(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),Mn=e=>{const t=Object.create(null);return(s=>t[s]||(t[s]=e(s)))},oc=/-\w/g,Pt=Mn(e=>e.replace(oc,t=>t.slice(1).toUpperCase())),ac=/\B([A-Z])/g,Zt=Mn(e=>e.replace(ac,"-$1").toLowerCase()),Ao=Mn(e=>e.charAt(0).toUpperCase()+e.slice(1)),Un=Mn(e=>e?`on${Ao(e)}`:""),xt=(e,t)=>!Object.is(e,t),Hn=(e,...t)=>{for(let s=0;s{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:n,value:s})},cc=e=>{const t=parseFloat(e);return isNaN(t)?e:t},lc=e=>{const t=xe(e)?Number(e):NaN;return isNaN(t)?e:t};let Ri;const En=()=>Ri||(Ri=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function $r(e){if(X(e)){const t={};for(let s=0;s{if(s){const n=s.split(fc);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function Br(e){let t="";if(xe(e))t=e;else if(X(e))for(let s=0;s0&&--this._on===0&&(Ee=this.prevScope,this.prevScope=void 0)}stop(t){if(this._active){this._active=!1;let s,n;for(s=0,n=this.effects.length;s0)return;if(Ss){let t=Ss;for(Ss=void 0;t;){const s=t.next;t.next=void 0,t.flags&=-9,t=s}}let e;for(;ws;){let t=ws;for(ws=void 0;t;){const s=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(n){e||(e=n)}t=s}}if(e)throw e}function jo(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function Do(e){let t,s=e.depsTail,n=s;for(;n;){const r=n.prevDep;n.version===-1?(n===s&&(s=r),Vr(n),yc(n)):t=n,n.dep.activeLink=n.prevActiveLink,n.prevActiveLink=void 0,n=r}e.deps=t,e.depsTail=s}function lr(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(Vo(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function Vo(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===Ms)||(e.globalVersion=Ms,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!lr(e))))return;e.flags|=2;const t=e.dep,s=pe,n=He;pe=e,He=!0;try{jo(e);const r=e.fn(e._value);(t.version===0||xt(r,e._value))&&(e.flags|=128,e._value=r,t.version++)}catch(r){throw t.version++,r}finally{pe=s,He=n,Do(e),e.flags&=-3}}function Vr(e,t=!1){const{dep:s,prevSub:n,nextSub:r}=e;if(n&&(n.nextSub=r,e.prevSub=void 0),r&&(r.prevSub=n,e.nextSub=void 0),s.subs===e&&(s.subs=n,!n&&s.computed)){s.computed.flags&=-5;for(let i=s.computed.deps;i;i=i.nextDep)Vr(i,!0)}!t&&!--s.sc&&s.map&&s.map.delete(s.key)}function yc(e){const{prevDep:t,nextDep:s}=e;t&&(t.nextDep=s,e.prevDep=void 0),s&&(s.prevDep=t,e.nextDep=void 0)}function _c(e,t){e.effect instanceof an&&(e=e.effect.fn);const s=new an(e);t&&be(s,t);try{s.run()}catch(r){throw s.stop(),r}const n=s.run.bind(s);return n.effect=s,n}let He=!0;const Uo=[];function ct(){Uo.push(He),He=!1}function lt(){const e=Uo.pop();He=e===void 0?!0:e}function Ci(e){const{cleanup:t}=e;if(e.cleanup=void 0,t){const s=pe;pe=void 0;try{t()}finally{pe=s}}}let Ms=0,bc=class{constructor(t,s){this.sub=t,this.dep=s,this.version=s.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}};class Ur{constructor(t){this.computed=t,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(t){if(!pe||!He||pe===this.computed)return;let s=this.activeLink;if(s===void 0||s.sub!==pe)s=this.activeLink=new bc(pe,this),pe.deps?(s.prevDep=pe.depsTail,pe.depsTail.nextDep=s,pe.depsTail=s):pe.deps=pe.depsTail=s,Ho(s);else if(s.version===-1&&(s.version=this.version,s.nextDep)){const n=s.nextDep;n.prevDep=s.prevDep,s.prevDep&&(s.prevDep.nextDep=n),s.prevDep=pe.depsTail,s.nextDep=void 0,pe.depsTail.nextDep=s,pe.depsTail=s,pe.deps===s&&(pe.deps=n)}return s}trigger(t){this.version++,Ms++,this.notify(t)}notify(t){jr();try{for(let s=this.subs;s;s=s.prevSub)s.sub.notify()&&s.sub.dep.notify()}finally{Dr()}}}function Ho(e){if(e.dep.sc++,e.sub.flags&4){const t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let n=t.deps;n;n=n.nextDep)Ho(n)}const s=e.dep.subs;s!==e&&(e.prevSub=s,s&&(s.nextSub=e)),e.dep.subs=e}}const ur=new WeakMap,Ft=Symbol(""),fr=Symbol(""),Es=Symbol("");function Se(e,t,s){if(He&&pe){let n=ur.get(e);n||ur.set(e,n=new Map);let r=n.get(s);r||(n.set(s,r=new Ur),r.map=n,r.key=s),r.track()}}function ot(e,t,s,n,r,i){const o=ur.get(e);if(!o){Ms++;return}const a=c=>{c&&c.trigger()};if(jr(),t==="clear")o.forEach(a);else{const c=X(e),u=c&&Fr(s);if(c&&s==="length"){const f=Number(n);o.forEach((l,d)=>{(d==="length"||d===Es||!as(d)&&d>=f)&&a(l)})}else switch((s!==void 0||o.has(void 0))&&a(o.get(s)),u&&a(o.get(Es)),t){case"add":c?u&&a(o.get("length")):(a(o.get(Ft)),bs(e)&&a(o.get(fr)));break;case"delete":c||(a(o.get(Ft)),bs(e)&&a(o.get(fr)));break;case"set":bs(e)&&a(o.get(Ft));break}}Dr()}function zt(e){const t=ae(e);return t===e?t:(Se(t,"iterate",Es),Ze(e)?t:t.map(ut))}function Hr(e){return Se(e=ae(e),"iterate",Es),e}function ht(e,t){return kt(e)?Jt(e)?Os(ut(t)):Os(t):ut(t)}const xc={__proto__:null,[Symbol.iterator](){return Wn(this,Symbol.iterator,e=>ht(this,e))},concat(...e){return zt(this).concat(...e.map(t=>X(t)?zt(t):t))},entries(){return Wn(this,"entries",e=>(e[1]=ht(this,e[1]),e))},every(e,t){return rt(this,"every",e,t,void 0,arguments)},filter(e,t){return rt(this,"filter",e,t,s=>s.map(n=>ht(this,n)),arguments)},find(e,t){return rt(this,"find",e,t,s=>ht(this,s),arguments)},findIndex(e,t){return rt(this,"findIndex",e,t,void 0,arguments)},findLast(e,t){return rt(this,"findLast",e,t,s=>ht(this,s),arguments)},findLastIndex(e,t){return rt(this,"findLastIndex",e,t,void 0,arguments)},forEach(e,t){return rt(this,"forEach",e,t,void 0,arguments)},includes(...e){return zn(this,"includes",e)},indexOf(...e){return zn(this,"indexOf",e)},join(e){return zt(this).join(e)},lastIndexOf(...e){return zn(this,"lastIndexOf",e)},map(e,t){return rt(this,"map",e,t,void 0,arguments)},pop(){return hs(this,"pop")},push(...e){return hs(this,"push",e)},reduce(e,...t){return Pi(this,"reduce",e,t)},reduceRight(e,...t){return Pi(this,"reduceRight",e,t)},shift(){return hs(this,"shift")},some(e,t){return rt(this,"some",e,t,void 0,arguments)},splice(...e){return hs(this,"splice",e)},toReversed(){return zt(this).toReversed()},toSorted(e){return zt(this).toSorted(e)},toSpliced(...e){return zt(this).toSpliced(...e)},unshift(...e){return hs(this,"unshift",e)},values(){return Wn(this,"values",e=>ht(this,e))}};function Wn(e,t,s){const n=Hr(e),r=n[t]();return n!==e&&!Ze(e)&&(r._next=r.next,r.next=()=>{const i=r._next();return i.done||(i.value=s(i.value)),i}),r}const wc=Array.prototype;function rt(e,t,s,n,r,i){const o=Hr(e),a=o!==e&&!Ze(e),c=o[t];if(c!==wc[t]){const l=c.apply(e,i);return a?ut(l):l}let u=s;o!==e&&(a?u=function(l,d){return s.call(this,ht(e,l),d,e)}:s.length>2&&(u=function(l,d){return s.call(this,l,d,e)}));const f=c.call(o,u,n);return a&&r?r(f):f}function Pi(e,t,s,n){const r=Hr(e);let i=s;return r!==e&&(Ze(e)?s.length>3&&(i=function(o,a,c){return s.call(this,o,a,c,e)}):i=function(o,a,c){return s.call(this,o,ht(e,a),c,e)}),r[t](i,...n)}function zn(e,t,s){const n=ae(e);Se(n,"iterate",Es);const r=n[t](...s);return(r===-1||r===!1)&&Kr(s[0])?(s[0]=ae(s[0]),n[t](...s)):r}function hs(e,t,s=[]){ct(),jr();const n=ae(e)[t].apply(e,s);return Dr(),lt(),n}const Sc=Or("__proto__,__v_isRef,__isVue"),Zo=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!=="arguments"&&e!=="caller").map(e=>Symbol[e]).filter(as));function Rc(e){as(e)||(e=String(e));const t=ae(this);return Se(t,"has",e),t.hasOwnProperty(e)}class Wo{constructor(t=!1,s=!1){this._isReadonly=t,this._isShallow=s}get(t,s,n){if(s==="__v_skip")return t.__v_skip;const r=this._isReadonly,i=this._isShallow;if(s==="__v_isReactive")return!r;if(s==="__v_isReadonly")return r;if(s==="__v_isShallow")return i;if(s==="__v_raw")return n===(r?i?Ac:Go:i?qo:Ko).get(t)||Object.getPrototypeOf(t)===Object.getPrototypeOf(n)?t:void 0;const o=X(t);if(!r){let c;if(o&&(c=xc[s]))return c;if(s==="hasOwnProperty")return Rc}const a=Reflect.get(t,s,Re(t)?t:n);if((as(s)?Zo.has(s):Sc(s))||(r||Se(t,"get",s),i))return a;if(Re(a)){const c=o&&Fr(s)?a:a.value;return r&&ge(c)?cn(c):c}return ge(a)?r?cn(a):Wr(a):a}}class zo extends Wo{constructor(t=!1){super(!1,t)}set(t,s,n,r){let i=t[s];const o=X(t)&&Fr(s);if(!this._isShallow){const u=kt(i);if(!Ze(n)&&!kt(n)&&(i=ae(i),n=ae(n)),!o&&Re(i)&&!Re(n))return u||(i.value=n),!0}const a=o?Number(s)e,Gs=e=>Reflect.getPrototypeOf(e);function Ic(e,t,s){return function(...n){const r=this.__v_raw,i=ae(r),o=bs(i),a=e==="entries"||e===Symbol.iterator&&o,c=e==="keys"&&o,u=r[e](...n),f=s?dr:t?Os:ut;return!t&&Se(i,"iterate",c?fr:Ft),{next(){const{value:l,done:d}=u.next();return d?{value:l,done:d}:{value:a?[f(l[0]),f(l[1])]:f(l),done:d}},[Symbol.iterator](){return this}}}}function Js(e){return function(...t){return e==="delete"?!1:e==="clear"?void 0:this}}function Lc(e,t){const s={get(r){const i=this.__v_raw,o=ae(i),a=ae(r);e||(xt(r,a)&&Se(o,"get",r),Se(o,"get",a));const{has:c}=Gs(o),u=t?dr:e?Os:ut;if(c.call(o,r))return u(i.get(r));if(c.call(o,a))return u(i.get(a));i!==o&&i.get(r)},get size(){const r=this.__v_raw;return!e&&Se(ae(r),"iterate",Ft),r.size},has(r){const i=this.__v_raw,o=ae(i),a=ae(r);return e||(xt(r,a)&&Se(o,"has",r),Se(o,"has",a)),r===a?i.has(r):i.has(r)||i.has(a)},forEach(r,i){const o=this,a=o.__v_raw,c=ae(a),u=t?dr:e?Os:ut;return!e&&Se(c,"iterate",Ft),a.forEach((f,l)=>r.call(i,u(f),u(l),o))}};return be(s,e?{add:Js("add"),set:Js("set"),delete:Js("delete"),clear:Js("clear")}:{add(r){!t&&!Ze(r)&&!kt(r)&&(r=ae(r));const i=ae(this);return Gs(i).has.call(i,r)||(i.add(r),ot(i,"add",r,r)),this},set(r,i){!t&&!Ze(i)&&!kt(i)&&(i=ae(i));const o=ae(this),{has:a,get:c}=Gs(o);let u=a.call(o,r);u||(r=ae(r),u=a.call(o,r));const f=c.call(o,r);return o.set(r,i),u?xt(i,f)&&ot(o,"set",r,i):ot(o,"add",r,i),this},delete(r){const i=ae(this),{has:o,get:a}=Gs(i);let c=o.call(i,r);c||(r=ae(r),c=o.call(i,r)),a&&a.call(i,r);const u=i.delete(r);return c&&ot(i,"delete",r,void 0),u},clear(){const r=ae(this),i=r.size!==0,o=r.clear();return i&&ot(r,"clear",void 0,void 0),o}}),["keys","values","entries",Symbol.iterator].forEach(r=>{s[r]=Ic(r,e,t)}),s}function Zr(e,t){const s=Lc(e,t);return(n,r,i)=>r==="__v_isReactive"?!e:r==="__v_isReadonly"?e:r==="__v_raw"?n:Reflect.get(le(s,r)&&r in n?s:n,r,i)}const Mc={get:Zr(!1,!1)},Ec={get:Zr(!1,!0)},Oc={get:Zr(!0,!1)};const Ko=new WeakMap,qo=new WeakMap,Go=new WeakMap,Ac=new WeakMap;function Nc(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function Fc(e){return e.__v_skip||!Object.isExtensible(e)?0:Nc(rc(e))}function Wr(e){return kt(e)?e:zr(e,!1,Pc,Mc,Ko)}function $c(e){return zr(e,!1,Tc,Ec,qo)}function cn(e){return zr(e,!0,kc,Oc,Go)}function zr(e,t,s,n,r){if(!ge(e)||e.__v_raw&&!(t&&e.__v_isReactive))return e;const i=Fc(e);if(i===0)return e;const o=r.get(e);if(o)return o;const a=new Proxy(e,i===2?n:s);return r.set(e,a),a}function Jt(e){return kt(e)?Jt(e.__v_raw):!!(e&&e.__v_isReactive)}function kt(e){return!!(e&&e.__v_isReadonly)}function Ze(e){return!!(e&&e.__v_isShallow)}function Kr(e){return e?!!e.__v_raw:!1}function ae(e){const t=e&&e.__v_raw;return t?ae(t):e}function hr(e){return!le(e,"__v_skip")&&Object.isExtensible(e)&&No(e,"__v_skip",!0),e}const ut=e=>ge(e)?Wr(e):e,Os=e=>ge(e)?cn(e):e;function Re(e){return e?e.__v_isRef===!0:!1}function we(e){return Jo(e,!1)}function Bc(e){return Jo(e,!0)}function Jo(e,t){return Re(e)?e:new jc(e,t)}class jc{constructor(t,s){this.dep=new Ur,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=s?t:ae(t),this._value=s?t:ut(t),this.__v_isShallow=s}get value(){return this.dep.track(),this._value}set value(t){const s=this._rawValue,n=this.__v_isShallow||Ze(t)||kt(t);t=n?t:ae(t),xt(t,s)&&(this._rawValue=t,this._value=n?t:ut(t),this.dep.trigger())}}function Dc(e){return Re(e)?e.value:e}const Vc={get:(e,t,s)=>t==="__v_raw"?e:Dc(Reflect.get(e,t,s)),set:(e,t,s,n)=>{const r=e[t];return Re(r)&&!Re(s)?(r.value=s,!0):Reflect.set(e,t,s,n)}};function Yo(e){return Jt(e)?e:new Proxy(e,Vc)}class Uc{constructor(t,s,n){this.fn=t,this.setter=s,this._value=void 0,this.dep=new Ur(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=Ms-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!s,this.isSSR=n}notify(){if(this.flags|=16,!(this.flags&8)&&pe!==this)return Bo(this,!0),!0}get value(){const t=this.dep.track();return Vo(this),t&&(t.version=this.dep.version),this._value}set value(t){this.setter&&this.setter(t)}}function Hc(e,t,s=!1){let n,r;return Y(e)?n=e:(n=e.get,r=e.set),new Uc(n,r,s)}const Ys={},ln=new WeakMap;let At;function Zc(e,t=!1,s=At){if(s){let n=ln.get(s);n||ln.set(s,n=[]),n.push(e)}}function Wc(e,t,s=me){const{immediate:n,deep:r,once:i,scheduler:o,augmentJob:a,call:c}=s,u=C=>r?C:Ze(C)||r===!1||r===0?vt(C,1):vt(C);let f,l,d,h,g=!1,y=!1;if(Re(e)?(l=()=>e.value,g=Ze(e)):Jt(e)?(l=()=>u(e),g=!0):X(e)?(y=!0,g=e.some(C=>Jt(C)||Ze(C)),l=()=>e.map(C=>{if(Re(C))return C.value;if(Jt(C))return u(C);if(Y(C))return c?c(C,2):C()})):Y(e)?t?l=c?()=>c(e,2):e:l=()=>{if(d){ct();try{d()}finally{lt()}}const C=At;At=f;try{return c?c(e,3,[h]):e(h)}finally{At=C}}:l=Xe,t&&r){const C=l,k=r===!0?1/0:r;l=()=>vt(C(),k)}const x=vc(),b=()=>{f.stop(),x&&x.active&&Nr(x.effects,f)};if(i&&t){const C=t;t=(...k)=>{C(...k),b()}}let L=y?new Array(e.length).fill(Ys):Ys;const $=C=>{if(!(!(f.flags&1)||!f.dirty&&!C))if(t){const k=f.run();if(r||g||(y?k.some((_,D)=>xt(_,L[D])):xt(k,L))){d&&d();const _=At;At=f;try{const D=[k,L===Ys?void 0:y&&L[0]===Ys?[]:L,h];L=k,c?c(t,3,D):t(...D)}finally{At=_}}}else f.run()};return a&&a($),f=new an(l),f.scheduler=o?()=>o($,!1):$,h=C=>Zc(C,!1,f),d=f.onStop=()=>{const C=ln.get(f);if(C){if(c)c(C,4);else for(const k of C)k();ln.delete(f)}},t?n?$(!0):L=f.run():o?o($.bind(null,!0),!0):f.run(),b.pause=f.pause.bind(f),b.resume=f.resume.bind(f),b.stop=b,b}function vt(e,t=1/0,s){if(t<=0||!ge(e)||e.__v_skip||(s=s||new Map,(s.get(e)||0)>=t))return e;if(s.set(e,t),t--,Re(e))vt(e.value,t,s);else if(X(e))for(let n=0;n{vt(n,t,s)});else if(ic(e)){for(const n in e)vt(e[n],t,s);for(const n of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,n)&&vt(e[n],t,s)}return e}/** -* @vue/runtime-core v3.5.25 -* (c) 2018-present Yuxi (Evan) You and Vue contributors -* @license MIT -**/function Zs(e,t,s,n){try{return n?e(...n):e()}catch(r){Ws(r,t,s)}}function tt(e,t,s,n){if(Y(e)){const r=Zs(e,t,s,n);return r&&Oo(r)&&r.catch(i=>{Ws(i,t,s)}),r}if(X(e)){const r=[];for(let i=0;i>>1,r=ke[n],i=As(r);i=As(s)?ke.push(e):ke.splice(Kc(t),0,e),e.flags|=1,Qo()}}function Qo(){un||(un=Xo.then(ta))}function mr(e){X(e)?Yt.push(...e):pt&&e.id===-1?pt.splice(Kt+1,0,e):e.flags&1||(Yt.push(e),e.flags|=1),Qo()}function ki(e,t,s=Je+1){for(;sAs(s)-As(n));if(Yt.length=0,pt){pt.push(...t);return}for(pt=t,Kt=0;Kte.id==null?e.flags&2?-1:1/0:e.id;function ta(e){try{for(Je=0;Je{n._d&&pn(-1);const i=fn(t);let o;try{o=e(...r)}finally{fn(i),n._d&&pn(1)}return o};return n._n=!0,n._c=!0,n._d=!0,n}function Et(e,t,s,n){const r=e.dirs,i=t&&t.dirs;for(let o=0;oe.__isTeleport,Yc=Symbol("_leaveCb");function Gr(e,t){e.shapeFlag&6&&e.component?(e.transition=t,Gr(e.component.subTree,t)):e.shapeFlag&128?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function ve(e,t){return Y(e)?be({name:e.name},t,{setup:e}):e}function na(e){e.ids=[e.ids[0]+e.ids[2]+++"-",0,0]}const dn=new WeakMap;function Rs(e,t,s,n,r=!1){if(X(e)){e.forEach((g,y)=>Rs(g,t&&(X(t)?t[y]:t),s,n,r));return}if(Cs(n)&&!r){n.shapeFlag&512&&n.type.__asyncResolved&&n.component.subTree.component&&Rs(e,t,s,n.component.subTree);return}const i=n.shapeFlag&4?ii(n.component):n.el,o=r?null:i,{i:a,r:c}=e,u=t&&t.r,f=a.refs===me?a.refs={}:a.refs,l=a.setupState,d=ae(l),h=l===me?Eo:g=>le(d,g);if(u!=null&&u!==c){if(Ti(t),xe(u))f[u]=null,h(u)&&(l[u]=null);else if(Re(u)){u.value=null;const g=t;g.k&&(f[g.k]=null)}}if(Y(c))Zs(c,a,12,[o,f]);else{const g=xe(c),y=Re(c);if(g||y){const x=()=>{if(e.f){const b=g?h(c)?l[c]:f[c]:c.value;if(r)X(b)&&Nr(b,i);else if(X(b))b.includes(i)||b.push(i);else if(g)f[c]=[i],h(c)&&(l[c]=f[c]);else{const L=[i];c.value=L,e.k&&(f[e.k]=L)}}else g?(f[c]=o,h(c)&&(l[c]=o)):y&&(c.value=o,e.k&&(f[e.k]=o))};if(o){const b=()=>{x(),dn.delete(e)};b.id=-1,dn.set(e,b),Me(b,s)}else Ti(e),x()}}}function Ti(e){const t=dn.get(e);t&&(t.flags|=8,dn.delete(e))}En().requestIdleCallback;En().cancelIdleCallback;const Cs=e=>!!e.type.__asyncLoader,ra=e=>e.type.__isKeepAlive;function Xc(e,t){ia(e,"a",t)}function Qc(e,t){ia(e,"da",t)}function ia(e,t,s=Te){const n=e.__wdc||(e.__wdc=()=>{let r=s;for(;r;){if(r.isDeactivated)return;r=r.parent}return e()});if(On(t,n,s),s){let r=s.parent;for(;r&&r.parent;)ra(r.parent.vnode)&&el(n,t,s,r),r=r.parent}}function el(e,t,s,n){const r=On(t,e,n,!0);Jr(()=>{Nr(n[t],r)},s)}function On(e,t,s=Te,n=!1){if(s){const r=s[e]||(s[e]=[]),i=t.__weh||(t.__weh=(...o)=>{ct();const a=zs(s),c=tt(t,s,e,o);return a(),lt(),c});return n?r.unshift(i):r.push(i),i}}const dt=e=>(t,s=Te)=>{(!$s||e==="sp")&&On(e,(...n)=>t(...n),s)},tl=dt("bm"),at=dt("m"),sl=dt("bu"),nl=dt("u"),rl=dt("bum"),Jr=dt("um"),il=dt("sp"),ol=dt("rtg"),al=dt("rtc");function oa(e,t=Te){On("ec",e,t)}const cl=Symbol.for("v-ndc"),gr=e=>e?Ca(e)?ii(e):gr(e.parent):null,Ps=be(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>gr(e.parent),$root:e=>gr(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>Yr(e),$forceUpdate:e=>e.f||(e.f=()=>{qr(e.update)}),$nextTick:e=>e.n||(e.n=pr.bind(e.proxy)),$watch:e=>_l.bind(e)}),Kn=(e,t)=>e!==me&&!e.__isScriptSetup&&le(e,t),ll={get({_:e},t){if(t==="__v_skip")return!0;const{ctx:s,setupState:n,data:r,props:i,accessCache:o,type:a,appContext:c}=e;if(t[0]!=="$"){const d=o[t];if(d!==void 0)switch(d){case 1:return n[t];case 2:return r[t];case 4:return s[t];case 3:return i[t]}else{if(Kn(n,t))return o[t]=1,n[t];if(r!==me&&le(r,t))return o[t]=2,r[t];if(le(i,t))return o[t]=3,i[t];if(s!==me&&le(s,t))return o[t]=4,s[t];vr&&(o[t]=0)}}const u=Ps[t];let f,l;if(u)return t==="$attrs"&&Se(e.attrs,"get",""),u(e);if((f=a.__cssModules)&&(f=f[t]))return f;if(s!==me&&le(s,t))return o[t]=4,s[t];if(l=c.config.globalProperties,le(l,t))return l[t]},set({_:e},t,s){const{data:n,setupState:r,ctx:i}=e;return Kn(r,t)?(r[t]=s,!0):n!==me&&le(n,t)?(n[t]=s,!0):le(e.props,t)||t[0]==="$"&&t.slice(1)in e?!1:(i[t]=s,!0)},has({_:{data:e,setupState:t,accessCache:s,ctx:n,appContext:r,props:i,type:o}},a){let c;return!!(s[a]||e!==me&&a[0]!=="$"&&le(e,a)||Kn(t,a)||le(i,a)||le(n,a)||le(Ps,a)||le(r.config.globalProperties,a)||(c=o.__cssModules)&&c[a])},defineProperty(e,t,s){return s.get!=null?e._.accessCache[t]=0:le(s,"value")&&this.set(e,t,s.value,null),Reflect.defineProperty(e,t,s)}};function Ii(e){return X(e)?e.reduce((t,s)=>(t[s]=null,t),{}):e}let vr=!0;function ul(e){const t=Yr(e),s=e.proxy,n=e.ctx;vr=!1,t.beforeCreate&&Li(t.beforeCreate,e,"bc");const{data:r,computed:i,methods:o,watch:a,provide:c,inject:u,created:f,beforeMount:l,mounted:d,beforeUpdate:h,updated:g,activated:y,deactivated:x,beforeDestroy:b,beforeUnmount:L,destroyed:$,unmounted:C,render:k,renderTracked:_,renderTriggered:D,errorCaptured:M,serverPrefetch:B,expose:W,inheritAttrs:J,components:de,directives:P,filters:H}=t;if(u&&fl(u,n,null),o)for(const ie in o){const oe=o[ie];Y(oe)&&(n[ie]=oe.bind(s))}if(r){const ie=r.call(s,s);ge(ie)&&(e.data=Wr(ie))}if(vr=!0,i)for(const ie in i){const oe=i[ie],nt=Y(oe)?oe.bind(s,s):Y(oe.get)?oe.get.bind(s,s):Xe,Ks=!Y(oe)&&Y(oe.set)?oe.set.bind(s):Xe,Mt=fe({get:nt,set:Ks});Object.defineProperty(n,ie,{enumerable:!0,configurable:!0,get:()=>Mt.value,set:We=>Mt.value=We})}if(a)for(const ie in a)aa(a[ie],n,s,ie);if(c){const ie=Y(c)?c.call(s):c;Reflect.ownKeys(ie).forEach(oe=>{An(oe,ie[oe])})}f&&Li(f,e,"c");function Q(ie,oe){X(oe)?oe.forEach(nt=>ie(nt.bind(s))):oe&&ie(oe.bind(s))}if(Q(tl,l),Q(at,d),Q(sl,h),Q(nl,g),Q(Xc,y),Q(Qc,x),Q(oa,M),Q(al,_),Q(ol,D),Q(rl,L),Q(Jr,C),Q(il,B),X(W))if(W.length){const ie=e.exposed||(e.exposed={});W.forEach(oe=>{Object.defineProperty(ie,oe,{get:()=>s[oe],set:nt=>s[oe]=nt,enumerable:!0})})}else e.exposed||(e.exposed={});k&&e.render===Xe&&(e.render=k),J!=null&&(e.inheritAttrs=J),de&&(e.components=de),P&&(e.directives=P),B&&na(e)}function fl(e,t,s=Xe){X(e)&&(e=yr(e));for(const n in e){const r=e[n];let i;ge(r)?"default"in r?i=wt(r.from||n,r.default,!0):i=wt(r.from||n):i=wt(r),Re(i)?Object.defineProperty(t,n,{enumerable:!0,configurable:!0,get:()=>i.value,set:o=>i.value=o}):t[n]=i}}function Li(e,t,s){tt(X(e)?e.map(n=>n.bind(t.proxy)):e.bind(t.proxy),t,s)}function aa(e,t,s,n){let r=n.includes(".")?ua(s,n):()=>s[n];if(xe(e)){const i=t[e];Y(i)&&Qe(r,i)}else if(Y(e))Qe(r,e.bind(s));else if(ge(e))if(X(e))e.forEach(i=>aa(i,t,s,n));else{const i=Y(e.handler)?e.handler.bind(s):t[e.handler];Y(i)&&Qe(r,i,e)}}function Yr(e){const t=e.type,{mixins:s,extends:n}=t,{mixins:r,optionsCache:i,config:{optionMergeStrategies:o}}=e.appContext,a=i.get(t);let c;return a?c=a:!r.length&&!s&&!n?c=t:(c={},r.length&&r.forEach(u=>hn(c,u,o,!0)),hn(c,t,o)),ge(t)&&i.set(t,c),c}function hn(e,t,s,n=!1){const{mixins:r,extends:i}=t;i&&hn(e,i,s,!0),r&&r.forEach(o=>hn(e,o,s,!0));for(const o in t)if(!(n&&o==="expose")){const a=dl[o]||s&&s[o];e[o]=a?a(e[o],t[o]):t[o]}return e}const dl={data:Mi,props:Ei,emits:Ei,methods:gs,computed:gs,beforeCreate:Pe,created:Pe,beforeMount:Pe,mounted:Pe,beforeUpdate:Pe,updated:Pe,beforeDestroy:Pe,beforeUnmount:Pe,destroyed:Pe,unmounted:Pe,activated:Pe,deactivated:Pe,errorCaptured:Pe,serverPrefetch:Pe,components:gs,directives:gs,watch:pl,provide:Mi,inject:hl};function Mi(e,t){return t?e?function(){return be(Y(e)?e.call(this,this):e,Y(t)?t.call(this,this):t)}:t:e}function hl(e,t){return gs(yr(e),yr(t))}function yr(e){if(X(e)){const t={};for(let s=0;s1)return s&&Y(t)?t.call(n&&n.proxy):t}}const vl=Symbol.for("v-scx"),yl=()=>wt(vl);function la(e,t){return Xr(e,null,t)}function Qe(e,t,s){return Xr(e,t,s)}function Xr(e,t,s=me){const{immediate:n,deep:r,flush:i,once:o}=s,a=be({},s),c=t&&n||!t&&i!=="post";let u;if($s){if(i==="sync"){const h=yl();u=h.__watcherHandles||(h.__watcherHandles=[])}else if(!c){const h=()=>{};return h.stop=Xe,h.resume=Xe,h.pause=Xe,h}}const f=Te;a.call=(h,g,y)=>tt(h,f,g,y);let l=!1;i==="post"?a.scheduler=h=>{Me(h,f&&f.suspense)}:i!=="sync"&&(l=!0,a.scheduler=(h,g)=>{g?h():qr(h)}),a.augmentJob=h=>{t&&(h.flags|=4),l&&(h.flags|=2,f&&(h.id=f.uid,h.i=f))};const d=Wc(e,t,a);return $s&&(u?u.push(d):c&&d()),d}function _l(e,t,s){const n=this.proxy,r=xe(e)?e.includes(".")?ua(n,e):()=>n[e]:e.bind(n,n);let i;Y(t)?i=t:(i=t.handler,s=t);const o=zs(this),a=Xr(r,i.bind(n),s);return o(),a}function ua(e,t){const s=t.split(".");return()=>{let n=e;for(let r=0;rt==="modelValue"||t==="model-value"?e.modelModifiers:e[`${t}Modifiers`]||e[`${Pt(t)}Modifiers`]||e[`${Zt(t)}Modifiers`];function xl(e,t,...s){if(e.isUnmounted)return;const n=e.vnode.props||me;let r=s;const i=t.startsWith("update:"),o=i&&bl(n,t.slice(7));o&&(o.trim&&(r=s.map(f=>xe(f)?f.trim():f)),o.number&&(r=s.map(cc)));let a,c=n[a=Un(t)]||n[a=Un(Pt(t))];!c&&i&&(c=n[a=Un(Zt(t))]),c&&tt(c,e,6,r);const u=n[a+"Once"];if(u){if(!e.emitted)e.emitted={};else if(e.emitted[a])return;e.emitted[a]=!0,tt(u,e,6,r)}}const wl=new WeakMap;function fa(e,t,s=!1){const n=s?wl:t.emitsCache,r=n.get(e);if(r!==void 0)return r;const i=e.emits;let o={},a=!1;if(!Y(e)){const c=u=>{const f=fa(u,t,!0);f&&(a=!0,be(o,f))};!s&&t.mixins.length&&t.mixins.forEach(c),e.extends&&c(e.extends),e.mixins&&e.mixins.forEach(c)}return!i&&!a?(ge(e)&&n.set(e,null),null):(X(i)?i.forEach(c=>o[c]=null):be(o,i),ge(e)&&n.set(e,o),o)}function Nn(e,t){return!e||!In(t)?!1:(t=t.slice(2).replace(/Once$/,""),le(e,t[0].toLowerCase()+t.slice(1))||le(e,Zt(t))||le(e,t))}function Oi(e){const{type:t,vnode:s,proxy:n,withProxy:r,propsOptions:[i],slots:o,attrs:a,emit:c,render:u,renderCache:f,props:l,data:d,setupState:h,ctx:g,inheritAttrs:y}=e,x=fn(e);let b,L;try{if(s.shapeFlag&4){const C=r||n,k=C;b=De(u.call(k,C,f,l,h,d,g)),L=a}else{const C=t;b=De(C.length>1?C(l,{attrs:a,slots:o,emit:c}):C(l,null)),L=t.props?a:Rl(a)}}catch(C){ks.length=0,Ws(C,e,1),b=ce(Tt)}let $=b;if(L&&y!==!1){const C=Object.keys(L),{shapeFlag:k}=$;C.length&&k&7&&(i&&C.some(Ar)&&(L=Cl(L,i)),$=es($,L,!1,!0))}return s.dirs&&($=es($,null,!1,!0),$.dirs=$.dirs?$.dirs.concat(s.dirs):s.dirs),s.transition&&Gr($,s.transition),b=$,fn(x),b}function Sl(e,t=!0){let s;for(let n=0;n{let t;for(const s in e)(s==="class"||s==="style"||In(s))&&((t||(t={}))[s]=e[s]);return t},Cl=(e,t)=>{const s={};for(const n in e)(!Ar(n)||!(n.slice(9)in t))&&(s[n]=e[n]);return s};function Pl(e,t,s){const{props:n,children:r,component:i}=e,{props:o,children:a,patchFlag:c}=t,u=i.emitsOptions;if(t.dirs||t.transition)return!0;if(s&&c>=0){if(c&1024)return!0;if(c&16)return n?Ai(n,o,u):!!o;if(c&8){const f=t.dynamicProps;for(let l=0;lObject.create(da),pa=e=>Object.getPrototypeOf(e)===da;function kl(e,t,s,n=!1){const r={},i=ha();e.propsDefaults=Object.create(null),ma(e,t,r,i);for(const o in e.propsOptions[0])o in r||(r[o]=void 0);s?e.props=n?r:$c(r):e.type.props?e.props=r:e.props=i,e.attrs=i}function Tl(e,t,s,n){const{props:r,attrs:i,vnode:{patchFlag:o}}=e,a=ae(r),[c]=e.propsOptions;let u=!1;if((n||o>0)&&!(o&16)){if(o&8){const f=e.vnode.dynamicProps;for(let l=0;l{c=!0;const[d,h]=ga(l,t,!0);be(o,d),h&&a.push(...h)};!s&&t.mixins.length&&t.mixins.forEach(f),e.extends&&f(e.extends),e.mixins&&e.mixins.forEach(f)}if(!i&&!c)return ge(e)&&n.set(e,_s),_s;if(X(i))for(let f=0;fe==="_"||e==="_ctx"||e==="$stable",ti=e=>X(e)?e.map(De):[De(e)],Ll=(e,t,s)=>{if(t._n)return t;const n=qc((...r)=>ti(t(...r)),s);return n._c=!1,n},va=(e,t,s)=>{const n=e._ctx;for(const r in e){if(ei(r))continue;const i=e[r];if(Y(i))t[r]=Ll(r,i,n);else if(i!=null){const o=ti(i);t[r]=()=>o}}},ya=(e,t)=>{const s=ti(t);e.slots.default=()=>s},_a=(e,t,s)=>{for(const n in t)(s||!ei(n))&&(e[n]=t[n])},Ml=(e,t,s)=>{const n=e.slots=ha();if(e.vnode.shapeFlag&32){const r=t._;r?(_a(n,t,s),s&&No(n,"_",r,!0)):va(t,n)}else t&&ya(e,t)},El=(e,t,s)=>{const{vnode:n,slots:r}=e;let i=!0,o=me;if(n.shapeFlag&32){const a=t._;a?s&&a===1?i=!1:_a(r,t,s):(i=!t.$stable,va(t,r)),o=t}else t&&(ya(e,t),o={default:1});if(i)for(const a in r)!ei(a)&&o[a]==null&&delete r[a]},Me=Ul;function Ol(e){return Al(e)}function Al(e,t){const s=En();s.__VUE__=!0;const{insert:n,remove:r,patchProp:i,createElement:o,createText:a,createComment:c,setText:u,setElementText:f,parentNode:l,nextSibling:d,setScopeId:h=Xe,insertStaticContent:g}=e,y=(p,m,v,T=null,w=null,S=null,A=void 0,O=null,E=!!m.dynamicChildren)=>{if(p===m)return;p&&!yt(p,m)&&(T=qs(p),We(p,w,S,!0),p=null),m.patchFlag===-2&&(E=!1,m.dynamicChildren=null);const{type:R,ref:z,shapeFlag:F}=m;switch(R){case Fn:x(p,m,v,T);break;case Tt:b(p,m,v,T);break;case Gn:p==null&&L(m,v,T,A);break;case Fe:de(p,m,v,T,w,S,A,O,E);break;default:F&1?k(p,m,v,T,w,S,A,O,E):F&6?P(p,m,v,T,w,S,A,O,E):(F&64||F&128)&&R.process(p,m,v,T,w,S,A,O,E,fs)}z!=null&&w?Rs(z,p&&p.ref,S,m||p,!m):z==null&&p&&p.ref!=null&&Rs(p.ref,null,S,p,!0)},x=(p,m,v,T)=>{if(p==null)n(m.el=a(m.children),v,T);else{const w=m.el=p.el;m.children!==p.children&&u(w,m.children)}},b=(p,m,v,T)=>{p==null?n(m.el=c(m.children||""),v,T):m.el=p.el},L=(p,m,v,T)=>{[p.el,p.anchor]=g(p.children,m,v,T,p.el,p.anchor)},$=({el:p,anchor:m},v,T)=>{let w;for(;p&&p!==m;)w=d(p),n(p,v,T),p=w;n(m,v,T)},C=({el:p,anchor:m})=>{let v;for(;p&&p!==m;)v=d(p),r(p),p=v;r(m)},k=(p,m,v,T,w,S,A,O,E)=>{if(m.type==="svg"?A="svg":m.type==="math"&&(A="mathml"),p==null)_(m,v,T,w,S,A,O,E);else{const R=p.el&&p.el._isVueCE?p.el:null;try{R&&R._beginPatch(),B(p,m,w,S,A,O,E)}finally{R&&R._endPatch()}}},_=(p,m,v,T,w,S,A,O)=>{let E,R;const{props:z,shapeFlag:F,transition:Z,dirs:K}=p;if(E=p.el=o(p.type,S,z&&z.is,z),F&8?f(E,p.children):F&16&&M(p.children,E,null,T,w,qn(p,S),A,O),K&&Et(p,null,T,"created"),D(E,p,p.scopeId,A,T),z){for(const he in z)he!=="value"&&!xs(he)&&i(E,he,null,z[he],S,T);"value"in z&&i(E,"value",null,z.value,S),(R=z.onVnodeBeforeMount)&&Ge(R,T,p)}K&&Et(p,null,T,"beforeMount");const se=Nl(w,Z);se&&Z.beforeEnter(E),n(E,m,v),((R=z&&z.onVnodeMounted)||se||K)&&Me(()=>{R&&Ge(R,T,p),se&&Z.enter(E),K&&Et(p,null,T,"mounted")},w)},D=(p,m,v,T,w)=>{if(v&&h(p,v),T)for(let S=0;S{for(let R=E;R{const O=m.el=p.el;let{patchFlag:E,dynamicChildren:R,dirs:z}=m;E|=p.patchFlag&16;const F=p.props||me,Z=m.props||me;let K;if(v&&Ot(v,!1),(K=Z.onVnodeBeforeUpdate)&&Ge(K,v,m,p),z&&Et(m,p,v,"beforeUpdate"),v&&Ot(v,!0),(F.innerHTML&&Z.innerHTML==null||F.textContent&&Z.textContent==null)&&f(O,""),R?W(p.dynamicChildren,R,O,v,T,qn(m,w),S):A||oe(p,m,O,null,v,T,qn(m,w),S,!1),E>0){if(E&16)J(O,F,Z,v,w);else if(E&2&&F.class!==Z.class&&i(O,"class",null,Z.class,w),E&4&&i(O,"style",F.style,Z.style,w),E&8){const se=m.dynamicProps;for(let he=0;he{K&&Ge(K,v,m,p),z&&Et(m,p,v,"updated")},T)},W=(p,m,v,T,w,S,A)=>{for(let O=0;O{if(m!==v){if(m!==me)for(const S in m)!xs(S)&&!(S in v)&&i(p,S,m[S],null,w,T);for(const S in v){if(xs(S))continue;const A=v[S],O=m[S];A!==O&&S!=="value"&&i(p,S,O,A,w,T)}"value"in v&&i(p,"value",m.value,v.value,w)}},de=(p,m,v,T,w,S,A,O,E)=>{const R=m.el=p?p.el:a(""),z=m.anchor=p?p.anchor:a("");let{patchFlag:F,dynamicChildren:Z,slotScopeIds:K}=m;K&&(O=O?O.concat(K):K),p==null?(n(R,v,T),n(z,v,T),M(m.children||[],v,z,w,S,A,O,E)):F>0&&F&64&&Z&&p.dynamicChildren?(W(p.dynamicChildren,Z,v,w,S,A,O),(m.key!=null||w&&m===w.subTree)&&ba(p,m,!0)):oe(p,m,v,z,w,S,A,O,E)},P=(p,m,v,T,w,S,A,O,E)=>{m.slotScopeIds=O,p==null?m.shapeFlag&512?w.ctx.activate(m,v,T,A,E):H(m,v,T,w,S,A,E):te(p,m,E)},H=(p,m,v,T,w,S,A)=>{const O=p.component=Yl(p,T,w);if(ra(p)&&(O.ctx.renderer=fs),Ql(O,!1,A),O.asyncDep){if(w&&w.registerDep(O,Q,A),!p.el){const E=O.subTree=ce(Tt);b(null,E,m,v),p.placeholder=E.el}}else Q(O,p,m,v,w,S,A)},te=(p,m,v)=>{const T=m.component=p.component;if(Pl(p,m,v))if(T.asyncDep&&!T.asyncResolved){ie(T,m,v);return}else T.next=m,T.update();else m.el=p.el,T.vnode=m},Q=(p,m,v,T,w,S,A)=>{const O=()=>{if(p.isMounted){let{next:F,bu:Z,u:K,parent:se,vnode:he}=p;{const Ke=xa(p);if(Ke){F&&(F.el=he.el,ie(p,F,A)),Ke.asyncDep.then(()=>{p.isUnmounted||O()});return}}let ue=F,Ie;Ot(p,!1),F?(F.el=he.el,ie(p,F,A)):F=he,Z&&Hn(Z),(Ie=F.props&&F.props.onVnodeBeforeUpdate)&&Ge(Ie,se,F,he),Ot(p,!0);const Le=Oi(p),ze=p.subTree;p.subTree=Le,y(ze,Le,l(ze.el),qs(ze),p,w,S),F.el=Le.el,ue===null&&Qr(p,Le.el),K&&Me(K,w),(Ie=F.props&&F.props.onVnodeUpdated)&&Me(()=>Ge(Ie,se,F,he),w)}else{let F;const{el:Z,props:K}=m,{bm:se,m:he,parent:ue,root:Ie,type:Le}=p,ze=Cs(m);Ot(p,!1),se&&Hn(se),!ze&&(F=K&&K.onVnodeBeforeMount)&&Ge(F,ue,m),Ot(p,!0);{Ie.ce&&Ie.ce._def.shadowRoot!==!1&&Ie.ce._injectChildStyle(Le);const Ke=p.subTree=Oi(p);y(null,Ke,v,T,p,w,S),m.el=Ke.el}if(he&&Me(he,w),!ze&&(F=K&&K.onVnodeMounted)){const Ke=m;Me(()=>Ge(F,ue,Ke),w)}(m.shapeFlag&256||ue&&Cs(ue.vnode)&&ue.vnode.shapeFlag&256)&&p.a&&Me(p.a,w),p.isMounted=!0,m=v=T=null}};p.scope.on();const E=p.effect=new an(O);p.scope.off();const R=p.update=E.run.bind(E),z=p.job=E.runIfDirty.bind(E);z.i=p,z.id=p.uid,E.scheduler=()=>qr(z),Ot(p,!0),R()},ie=(p,m,v)=>{m.component=p;const T=p.vnode.props;p.vnode=m,p.next=null,Tl(p,m.props,T,v),El(p,m.children,v),ct(),ki(p),lt()},oe=(p,m,v,T,w,S,A,O,E=!1)=>{const R=p&&p.children,z=p?p.shapeFlag:0,F=m.children,{patchFlag:Z,shapeFlag:K}=m;if(Z>0){if(Z&128){Ks(R,F,v,T,w,S,A,O,E);return}else if(Z&256){nt(R,F,v,T,w,S,A,O,E);return}}K&8?(z&16&&us(R,w,S),F!==R&&f(v,F)):z&16?K&16?Ks(R,F,v,T,w,S,A,O,E):us(R,w,S,!0):(z&8&&f(v,""),K&16&&M(F,v,T,w,S,A,O,E))},nt=(p,m,v,T,w,S,A,O,E)=>{p=p||_s,m=m||_s;const R=p.length,z=m.length,F=Math.min(R,z);let Z;for(Z=0;Zz?us(p,w,S,!0,!1,F):M(m,v,T,w,S,A,O,E,F)},Ks=(p,m,v,T,w,S,A,O,E)=>{let R=0;const z=m.length;let F=p.length-1,Z=z-1;for(;R<=F&&R<=Z;){const K=p[R],se=m[R]=E?mt(m[R]):De(m[R]);if(yt(K,se))y(K,se,v,null,w,S,A,O,E);else break;R++}for(;R<=F&&R<=Z;){const K=p[F],se=m[Z]=E?mt(m[Z]):De(m[Z]);if(yt(K,se))y(K,se,v,null,w,S,A,O,E);else break;F--,Z--}if(R>F){if(R<=Z){const K=Z+1,se=KZ)for(;R<=F;)We(p[R],w,S,!0),R++;else{const K=R,se=R,he=new Map;for(R=se;R<=Z;R++){const Oe=m[R]=E?mt(m[R]):De(m[R]);Oe.key!=null&&he.set(Oe.key,R)}let ue,Ie=0;const Le=Z-se+1;let ze=!1,Ke=0;const ds=new Array(Le);for(R=0;R=Le){We(Oe,w,S,!0);continue}let qe;if(Oe.key!=null)qe=he.get(Oe.key);else for(ue=se;ue<=Z;ue++)if(ds[ue-se]===0&&yt(Oe,m[ue])){qe=ue;break}qe===void 0?We(Oe,w,S,!0):(ds[qe-se]=R+1,qe>=Ke?Ke=qe:ze=!0,y(Oe,m[qe],v,null,w,S,A,O,E),Ie++)}const xi=ze?Fl(ds):_s;for(ue=xi.length-1,R=Le-1;R>=0;R--){const Oe=se+R,qe=m[Oe],wi=m[Oe+1],Si=Oe+1{const{el:S,type:A,transition:O,children:E,shapeFlag:R}=p;if(R&6){Mt(p.component.subTree,m,v,T);return}if(R&128){p.suspense.move(m,v,T);return}if(R&64){A.move(p,m,v,fs);return}if(A===Fe){n(S,m,v);for(let F=0;FO.enter(S),w);else{const{leave:F,delayLeave:Z,afterLeave:K}=O,se=()=>{p.ctx.isUnmounted?r(S):n(S,m,v)},he=()=>{S._isLeaving&&S[Yc](!0),F(S,()=>{se(),K&&K()})};Z?Z(S,se,he):he()}else n(S,m,v)},We=(p,m,v,T=!1,w=!1)=>{const{type:S,props:A,ref:O,children:E,dynamicChildren:R,shapeFlag:z,patchFlag:F,dirs:Z,cacheIndex:K}=p;if(F===-2&&(w=!1),O!=null&&(ct(),Rs(O,null,v,p,!0),lt()),K!=null&&(m.renderCache[K]=void 0),z&256){m.ctx.deactivate(p);return}const se=z&1&&Z,he=!Cs(p);let ue;if(he&&(ue=A&&A.onVnodeBeforeUnmount)&&Ge(ue,m,p),z&6)ec(p.component,v,T);else{if(z&128){p.suspense.unmount(v,T);return}se&&Et(p,null,m,"beforeUnmount"),z&64?p.type.remove(p,m,v,fs,T):R&&!R.hasOnce&&(S!==Fe||F>0&&F&64)?us(R,m,v,!1,!0):(S===Fe&&F&384||!w&&z&16)&&us(E,m,v),T&&_i(p)}(he&&(ue=A&&A.onVnodeUnmounted)||se)&&Me(()=>{ue&&Ge(ue,m,p),se&&Et(p,null,m,"unmounted")},v)},_i=p=>{const{type:m,el:v,anchor:T,transition:w}=p;if(m===Fe){Qa(v,T);return}if(m===Gn){C(p);return}const S=()=>{r(v),w&&!w.persisted&&w.afterLeave&&w.afterLeave()};if(p.shapeFlag&1&&w&&!w.persisted){const{leave:A,delayLeave:O}=w,E=()=>A(v,S);O?O(p.el,S,E):E()}else S()},Qa=(p,m)=>{let v;for(;p!==m;)v=d(p),r(p),p=v;r(m)},ec=(p,m,v)=>{const{bum:T,scope:w,job:S,subTree:A,um:O,m:E,a:R}=p;Fi(E),Fi(R),T&&Hn(T),w.stop(),S&&(S.flags|=8,We(A,p,m,v)),O&&Me(O,m),Me(()=>{p.isUnmounted=!0},m)},us=(p,m,v,T=!1,w=!1,S=0)=>{for(let A=S;A{if(p.shapeFlag&6)return qs(p.component.subTree);if(p.shapeFlag&128)return p.suspense.next();const m=d(p.anchor||p.el),v=m&&m[Gc];return v?d(v):m};let Vn=!1;const bi=(p,m,v)=>{p==null?m._vnode&&We(m._vnode,null,null,!0):y(m._vnode||null,p,m,null,null,null,v),m._vnode=p,Vn||(Vn=!0,ki(),ea(),Vn=!1)},fs={p:y,um:We,m:Mt,r:_i,mt:H,mc:M,pc:oe,pbc:W,n:qs,o:e};return{render:bi,hydrate:void 0,createApp:gl(bi)}}function qn({type:e,props:t},s){return s==="svg"&&e==="foreignObject"||s==="mathml"&&e==="annotation-xml"&&t&&t.encoding&&t.encoding.includes("html")?void 0:s}function Ot({effect:e,job:t},s){s?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function Nl(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function ba(e,t,s=!1){const n=e.children,r=t.children;if(X(n)&&X(r))for(let i=0;i>1,e[s[a]]0&&(t[n]=s[i-1]),s[i]=n)}}for(i=s.length,o=s[i-1];i-- >0;)s[i]=o,o=t[o];return s}function xa(e){const t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:xa(t)}function Fi(e){if(e)for(let t=0;te.__isSuspense;let br=0;const $l={name:"Suspense",__isSuspense:!0,process(e,t,s,n,r,i,o,a,c,u){if(e==null)Bl(t,s,n,r,i,o,a,c,u);else{if(i&&i.deps>0&&!e.suspense.isInFallback){t.suspense=e.suspense,t.suspense.vnode=t,t.el=e.el;return}jl(e,t,s,n,r,o,a,c,u)}},hydrate:Dl,normalize:Vl},si=$l;function Ns(e,t){const s=e.props&&e.props[t];Y(s)&&s()}function Bl(e,t,s,n,r,i,o,a,c){const{p:u,o:{createElement:f}}=c,l=f("div"),d=e.suspense=Sa(e,r,n,t,l,s,i,o,a,c);u(null,d.pendingBranch=e.ssContent,l,null,n,d,i,o),d.deps>0?(Ns(e,"onPending"),Ns(e,"onFallback"),u(null,e.ssFallback,t,s,n,null,i,o),Qt(d,e.ssFallback)):d.resolve(!1,!0)}function jl(e,t,s,n,r,i,o,a,{p:c,um:u,o:{createElement:f}}){const l=t.suspense=e.suspense;l.vnode=t,t.el=e.el;const d=t.ssContent,h=t.ssFallback,{activeBranch:g,pendingBranch:y,isInFallback:x,isHydrating:b}=l;if(y)l.pendingBranch=d,yt(y,d)?(c(y,d,l.hiddenContainer,null,r,l,i,o,a),l.deps<=0?l.resolve():x&&(b||(c(g,h,s,n,r,null,i,o,a),Qt(l,h)))):(l.pendingId=br++,b?(l.isHydrating=!1,l.activeBranch=y):u(y,r,l),l.deps=0,l.effects.length=0,l.hiddenContainer=f("div"),x?(c(null,d,l.hiddenContainer,null,r,l,i,o,a),l.deps<=0?l.resolve():(c(g,h,s,n,r,null,i,o,a),Qt(l,h))):g&&yt(g,d)?(c(g,d,s,n,r,l,i,o,a),l.resolve(!0)):(c(null,d,l.hiddenContainer,null,r,l,i,o,a),l.deps<=0&&l.resolve()));else if(g&&yt(g,d))c(g,d,s,n,r,l,i,o,a),Qt(l,d);else if(Ns(t,"onPending"),l.pendingBranch=d,d.shapeFlag&512?l.pendingId=d.component.suspenseId:l.pendingId=br++,c(null,d,l.hiddenContainer,null,r,l,i,o,a),l.deps<=0)l.resolve();else{const{timeout:L,pendingId:$}=l;L>0?setTimeout(()=>{l.pendingId===$&&l.fallback(h)},L):L===0&&l.fallback(h)}}function Sa(e,t,s,n,r,i,o,a,c,u,f=!1){const{p:l,m:d,um:h,n:g,o:{parentNode:y,remove:x}}=u;let b;const L=Hl(e);L&&t&&t.pendingBranch&&(b=t.pendingId,t.deps++);const $=e.props?lc(e.props.timeout):void 0,C=i,k={vnode:e,parent:t,parentComponent:s,namespace:o,container:n,hiddenContainer:r,deps:0,pendingId:br++,timeout:typeof $=="number"?$:-1,activeBranch:null,pendingBranch:null,isInFallback:!f,isHydrating:f,isUnmounted:!1,effects:[],resolve(_=!1,D=!1){const{vnode:M,activeBranch:B,pendingBranch:W,pendingId:J,effects:de,parentComponent:P,container:H,isInFallback:te}=k;let Q=!1;k.isHydrating?k.isHydrating=!1:_||(Q=B&&W.transition&&W.transition.mode==="out-in",Q&&(B.transition.afterLeave=()=>{J===k.pendingId&&(d(W,H,i===C?g(B):i,0),mr(de),te&&M.ssFallback&&(M.ssFallback.el=null))}),B&&(y(B.el)===H&&(i=g(B)),h(B,P,k,!0),!Q&&te&&M.ssFallback&&Me(()=>M.ssFallback.el=null,k)),Q||d(W,H,i,0)),Qt(k,W),k.pendingBranch=null,k.isInFallback=!1;let ie=k.parent,oe=!1;for(;ie;){if(ie.pendingBranch){ie.effects.push(...de),oe=!0;break}ie=ie.parent}!oe&&!Q&&mr(de),k.effects=[],L&&t&&t.pendingBranch&&b===t.pendingId&&(t.deps--,t.deps===0&&!D&&t.resolve()),Ns(M,"onResolve")},fallback(_){if(!k.pendingBranch)return;const{vnode:D,activeBranch:M,parentComponent:B,container:W,namespace:J}=k;Ns(D,"onFallback");const de=g(M),P=()=>{k.isInFallback&&(l(null,_,W,de,B,null,J,a,c),Qt(k,_))},H=_.transition&&_.transition.mode==="out-in";H&&(M.transition.afterLeave=P),k.isInFallback=!0,h(M,B,null,!0),H||P()},move(_,D,M){k.activeBranch&&d(k.activeBranch,_,D,M),k.container=_},next(){return k.activeBranch&&g(k.activeBranch)},registerDep(_,D,M){const B=!!k.pendingBranch;B&&k.deps++;const W=_.vnode.el;_.asyncDep.catch(J=>{Ws(J,_,0)}).then(J=>{if(_.isUnmounted||k.isUnmounted||k.pendingId!==_.suspenseId)return;_.asyncResolved=!0;const{vnode:de}=_;Sr(_,J,!1),W&&(de.el=W);const P=!W&&_.subTree.el;D(_,de,y(W||_.subTree.el),W?null:g(_.subTree),k,o,M),P&&(de.placeholder=null,x(P)),Qr(_,de.el),B&&--k.deps===0&&k.resolve()})},unmount(_,D){k.isUnmounted=!0,k.activeBranch&&h(k.activeBranch,s,_,D),k.pendingBranch&&h(k.pendingBranch,s,_,D)}};return k}function Dl(e,t,s,n,r,i,o,a,c){const u=t.suspense=Sa(t,n,s,e.parentNode,document.createElement("div"),null,r,i,o,a,!0),f=c(e,u.pendingBranch=t.ssContent,s,u,i,o);return u.deps===0&&u.resolve(!1,!0),f}function Vl(e){const{shapeFlag:t,children:s}=e,n=t&32;e.ssContent=$i(n?s.default:s),e.ssFallback=n?$i(s.fallback):ce(Tt)}function $i(e){let t;if(Y(e)){const s=$n&&e._c;s&&(e._d=!1,Zl()),e=e(),s&&(e._d=!0,t=Ve,Wl())}return X(e)&&(e=Sl(e)),e=De(e),t&&!e.dynamicChildren&&(e.dynamicChildren=t.filter(s=>s!==e)),e}function Ul(e,t){t&&t.pendingBranch?X(e)?t.effects.push(...e):t.effects.push(e):mr(e)}function Qt(e,t){e.activeBranch=t;const{vnode:s,parentComponent:n}=e;let r=t.el;for(;!r&&t.component;)t=t.component.subTree,r=t.el;s.el=r,n&&n.subTree===s&&(n.vnode.el=r,Qr(n,r))}function Hl(e){const t=e.props&&e.props.suspensible;return t!=null&&t!==!1}const Fe=Symbol.for("v-fgt"),Fn=Symbol.for("v-txt"),Tt=Symbol.for("v-cmt"),Gn=Symbol.for("v-stc"),ks=[];let Ve=null;function Zl(e=!1){ks.push(Ve=e?null:[])}function Wl(){ks.pop(),Ve=ks[ks.length-1]||null}let $n=1;function pn(e,t=!1){$n+=e,e<0&&Ve&&t&&(Ve.hasOnce=!0)}function Fs(e){return e?e.__v_isVNode===!0:!1}function yt(e,t){return e.type===t.type&&e.key===t.key}const Ra=({key:e})=>e??null,sn=({ref:e,ref_key:t,ref_for:s})=>(typeof e=="number"&&(e=""+e),e!=null?xe(e)||Re(e)||Y(e)?{i:Ye,r:e,k:t,f:!!s}:e:null);function zl(e,t=null,s=null,n=0,r=null,i=e===Fe?0:1,o=!1,a=!1){const c={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&Ra(t),ref:t&&sn(t),scopeId:sa,slotScopeIds:null,children:s,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:i,patchFlag:n,dynamicProps:r,dynamicChildren:null,appContext:null,ctx:Ye};return a?(ni(c,s),i&128&&e.normalize(c)):s&&(c.shapeFlag|=xe(s)?8:16),$n>0&&!o&&Ve&&(c.patchFlag>0||i&6)&&c.patchFlag!==32&&Ve.push(c),c}const ce=Kl;function Kl(e,t=null,s=null,n=0,r=null,i=!1){if((!e||e===cl)&&(e=Tt),Fs(e)){const a=es(e,t,!0);return s&&ni(a,s),$n>0&&!i&&Ve&&(a.shapeFlag&6?Ve[Ve.indexOf(e)]=a:Ve.push(a)),a.patchFlag=-2,a}if(nu(e)&&(e=e.__vccOpts),t){t=ql(t);let{class:a,style:c}=t;a&&!xe(a)&&(t.class=Br(a)),ge(c)&&(Kr(c)&&!X(c)&&(c=be({},c)),t.style=$r(c))}const o=xe(e)?1:wa(e)?128:Jc(e)?64:ge(e)?4:Y(e)?2:0;return zl(e,t,s,n,r,o,i,!0)}function ql(e){return e?Kr(e)||pa(e)?be({},e):e:null}function es(e,t,s=!1,n=!1){const{props:r,ref:i,patchFlag:o,children:a,transition:c}=e,u=t?ri(r||{},t):r,f={__v_isVNode:!0,__v_skip:!0,type:e.type,props:u,key:u&&Ra(u),ref:t&&t.ref?s&&i?X(i)?i.concat(sn(t)):[i,sn(t)]:sn(t):i,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:a,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==Fe?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:c,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&es(e.ssContent),ssFallback:e.ssFallback&&es(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce};return c&&n&&Gr(f,c.clone(f)),f}function xr(e=" ",t=0){return ce(Fn,null,e,t)}function De(e){return e==null||typeof e=="boolean"?ce(Tt):X(e)?ce(Fe,null,e.slice()):Fs(e)?mt(e):ce(Fn,null,String(e))}function mt(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:es(e)}function ni(e,t){let s=0;const{shapeFlag:n}=e;if(t==null)t=null;else if(X(t))s=16;else if(typeof t=="object")if(n&65){const r=t.default;r&&(r._c&&(r._d=!1),ni(e,r()),r._c&&(r._d=!0));return}else{s=32;const r=t._;!r&&!pa(t)?t._ctx=Ye:r===3&&Ye&&(Ye.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else Y(t)?(t={default:t,_ctx:Ye},s=32):(t=String(t),n&64?(s=16,t=[xr(t)]):s=8);e.children=t,e.shapeFlag|=s}function ri(...e){const t={};for(let s=0;sTe||Ye;let mn,wr;{const e=En(),t=(s,n)=>{let r;return(r=e[s])||(r=e[s]=[]),r.push(n),i=>{r.length>1?r.forEach(o=>o(i)):r[0](i)}};mn=t("__VUE_INSTANCE_SETTERS__",s=>Te=s),wr=t("__VUE_SSR_SETTERS__",s=>$s=s)}const zs=e=>{const t=Te;return mn(e),e.scope.on(),()=>{e.scope.off(),mn(t)}},Bi=()=>{Te&&Te.scope.off(),mn(null)};function Ca(e){return e.vnode.shapeFlag&4}let $s=!1;function Ql(e,t=!1,s=!1){t&&wr(t);const{props:n,children:r}=e.vnode,i=Ca(e);kl(e,n,i,t),Ml(e,r,s||t);const o=i?eu(e,t):void 0;return t&&wr(!1),o}function eu(e,t){const s=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,ll);const{setup:n}=s;if(n){ct();const r=e.setupContext=n.length>1?su(e):null,i=zs(e),o=Zs(n,e,0,[e.props,r]),a=Oo(o);if(lt(),i(),(a||e.sp)&&!Cs(e)&&na(e),a){if(o.then(Bi,Bi),t)return o.then(c=>{Sr(e,c,t)}).catch(c=>{Ws(c,e,0)});e.asyncDep=o}else Sr(e,o,t)}else Pa(e,t)}function Sr(e,t,s){Y(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:ge(t)&&(e.setupState=Yo(t)),Pa(e,s)}let ji;function Pa(e,t,s){const n=e.type;if(!e.render){if(!t&&ji&&!n.render){const r=n.template||Yr(e).template;if(r){const{isCustomElement:i,compilerOptions:o}=e.appContext.config,{delimiters:a,compilerOptions:c}=n,u=be(be({isCustomElement:i,delimiters:a},o),c);n.render=ji(r,u)}}e.render=n.render||Xe}{const r=zs(e);ct();try{ul(e)}finally{lt(),r()}}}const tu={get(e,t){return Se(e,"get",""),e[t]}};function su(e){const t=s=>{e.exposed=s||{}};return{attrs:new Proxy(e.attrs,tu),slots:e.slots,emit:e.emit,expose:t}}function ii(e){return e.exposed?e.exposeProxy||(e.exposeProxy=new Proxy(Yo(hr(e.exposed)),{get(t,s){if(s in t)return t[s];if(s in Ps)return Ps[s](e)},has(t,s){return s in t||s in Ps}})):e.proxy}function nu(e){return Y(e)&&"__vccOpts"in e}const fe=(e,t)=>Hc(e,t,$s);function j(e,t,s){try{pn(-1);const n=arguments.length;return n===2?ge(t)&&!X(t)?Fs(t)?ce(e,null,[t]):ce(e,t):ce(e,null,t):(n>3?s=Array.prototype.slice.call(arguments,2):n===3&&Fs(s)&&(s=[s]),ce(e,t,s))}finally{pn(1)}}const ru="3.5.25";/** -* @vue/runtime-dom v3.5.25 -* (c) 2018-present Yuxi (Evan) You and Vue contributors -* @license MIT -**/let Rr;const Di=typeof window<"u"&&window.trustedTypes;if(Di)try{Rr=Di.createPolicy("vue",{createHTML:e=>e})}catch{}const ka=Rr?e=>Rr.createHTML(e):e=>e,iu="http://www.w3.org/2000/svg",ou="http://www.w3.org/1998/Math/MathML",it=typeof document<"u"?document:null,Vi=it&&it.createElement("template"),au={insert:(e,t,s)=>{t.insertBefore(e,s||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,s,n)=>{const r=t==="svg"?it.createElementNS(iu,e):t==="mathml"?it.createElementNS(ou,e):s?it.createElement(e,{is:s}):it.createElement(e);return e==="select"&&n&&n.multiple!=null&&r.setAttribute("multiple",n.multiple),r},createText:e=>it.createTextNode(e),createComment:e=>it.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>it.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,s,n,r,i){const o=s?s.previousSibling:t.lastChild;if(r&&(r===i||r.nextSibling))for(;t.insertBefore(r.cloneNode(!0),s),!(r===i||!(r=r.nextSibling)););else{Vi.innerHTML=ka(n==="svg"?`${e}`:n==="mathml"?`${e}`:e);const a=Vi.content;if(n==="svg"||n==="mathml"){const c=a.firstChild;for(;c.firstChild;)a.appendChild(c.firstChild);a.removeChild(c)}t.insertBefore(a,s)}return[o?o.nextSibling:t.firstChild,s?s.previousSibling:t.lastChild]}},cu=Symbol("_vtc");function lu(e,t,s){const n=e[cu];n&&(t=(t?[t,...n]:[...n]).join(" ")),t==null?e.removeAttribute("class"):s?e.setAttribute("class",t):e.className=t}const Ui=Symbol("_vod"),uu=Symbol("_vsh"),fu=Symbol(""),du=/(?:^|;)\s*display\s*:/;function hu(e,t,s){const n=e.style,r=xe(s);let i=!1;if(s&&!r){if(t)if(xe(t))for(const o of t.split(";")){const a=o.slice(0,o.indexOf(":")).trim();s[a]==null&&nn(n,a,"")}else for(const o in t)s[o]==null&&nn(n,o,"");for(const o in s)o==="display"&&(i=!0),nn(n,o,s[o])}else if(r){if(t!==s){const o=n[fu];o&&(s+=";"+o),n.cssText=s,i=du.test(s)}}else t&&e.removeAttribute("style");Ui in e&&(e[Ui]=i?n.display:"",e[uu]&&(n.display="none"))}const Hi=/\s*!important$/;function nn(e,t,s){if(X(s))s.forEach(n=>nn(e,t,n));else if(s==null&&(s=""),t.startsWith("--"))e.setProperty(t,s);else{const n=pu(e,t);Hi.test(s)?e.setProperty(Zt(n),s.replace(Hi,""),"important"):e[n]=s}}const Zi=["Webkit","Moz","ms"],Jn={};function pu(e,t){const s=Jn[t];if(s)return s;let n=Pt(t);if(n!=="filter"&&n in e)return Jn[t]=n;n=Ao(n);for(let r=0;rYn||(_u.then(()=>Yn=0),Yn=Date.now());function xu(e,t){const s=n=>{if(!n._vts)n._vts=Date.now();else if(n._vts<=s.attached)return;tt(wu(n,s.value),t,5,[n])};return s.value=e,s.attached=bu(),s}function wu(e,t){if(X(t)){const s=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{s.call(e),e._stopped=!0},t.map(n=>r=>!r._stopped&&n&&n(r))}else return t}const Ji=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,Su=(e,t,s,n,r,i)=>{const o=r==="svg";t==="class"?lu(e,n,o):t==="style"?hu(e,s,n):In(t)?Ar(t)||vu(e,t,s,n,i):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):Ru(e,t,n,o))?(Ki(e,t,n),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&zi(e,t,n,o,i,t!=="value")):e._isVueCE&&(/[A-Z]/.test(t)||!xe(n))?Ki(e,Pt(t),n,i,t):(t==="true-value"?e._trueValue=n:t==="false-value"&&(e._falseValue=n),zi(e,t,n,o))};function Ru(e,t,s,n){if(n)return!!(t==="innerHTML"||t==="textContent"||t in e&&Ji(t)&&Y(s));if(t==="spellcheck"||t==="draggable"||t==="translate"||t==="autocorrect"||t==="sandbox"&&e.tagName==="IFRAME"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA")return!1;if(t==="width"||t==="height"){const r=e.tagName;if(r==="IMG"||r==="VIDEO"||r==="CANVAS"||r==="SOURCE")return!1}return Ji(t)&&xe(s)?!1:t in e}const Cu=be({patchProp:Su},au);let Yi;function Pu(){return Yi||(Yi=Ol(Cu))}const ku=((...e)=>{const t=Pu().createApp(...e),{mount:s}=t;return t.mount=n=>{const r=Iu(n);if(!r)return;const i=t._component;!Y(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent="");const o=s(r,!1,Tu(r));return r instanceof Element&&(r.removeAttribute("v-cloak"),r.setAttribute("data-v-app","")),o},t});function Tu(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function Iu(e){return xe(e)?document.querySelector(e):e}const Cr=new WeakMap,Lu=new WeakMap,gn={current:[]};let Xn=!1,Ts=0;const vs=new Set,Xs=new Map;function Ta(e){for(const t of e){if(gn.current.includes(t))continue;gn.current.push(t),t.recompute();const s=Lu.get(t);if(s)for(const n of s){const r=Cr.get(n);r?.length&&Ta(r)}}}function Mu(e){const t={prevVal:e.prevState,currentVal:e.state};for(const s of e.listeners)s(t)}function Eu(e){const t={prevVal:e.prevState,currentVal:e.state};for(const s of e.listeners)s(t)}function Ia(e){if(Ts>0&&!Xs.has(e)&&Xs.set(e,e.prevState),vs.add(e),!(Ts>0)&&!Xn)try{for(Xn=!0;vs.size>0;){const t=Array.from(vs);vs.clear();for(const s of t){const n=Xs.get(s)??s.prevState;s.prevState=n,Mu(s)}for(const s of t){const n=Cr.get(s);n&&(gn.current.push(s),Ta(n))}for(const s of t){const n=Cr.get(s);if(n)for(const r of n)Eu(r)}}}finally{Xn=!1,gn.current=[],Xs.clear()}}function Is(e){Ts++;try{e()}finally{if(Ts--,Ts===0){const t=vs.values().next().value;t&&Ia(t)}}}function Ou(e){return typeof e=="function"}class Au{constructor(t,s){this.listeners=new Set,this.subscribe=n=>{var r,i;this.listeners.add(n);const o=(i=(r=this.options)==null?void 0:r.onSubscribe)==null?void 0:i.call(r,n,this);return()=>{this.listeners.delete(n),o?.()}},this.prevState=t,this.state=t,this.options=s}setState(t){var s,n,r;this.prevState=this.state,(s=this.options)!=null&&s.updateFn?this.state=this.options.updateFn(this.prevState)(t):Ou(t)?this.state=t(this.prevState):this.state=t,(r=(n=this.options)==null?void 0:n.onUpdate)==null||r.call(n),Ia(this)}}const St="__TSR_index",Xi="popstate",Qi="beforeunload";function Nu(e){let t=e.getLocation();const s=new Set,n=o=>{t=e.getLocation(),s.forEach(a=>a({location:t,action:o}))},r=o=>{e.notifyOnIndexChange??!0?n(o):t=e.getLocation()},i=async({task:o,navigateOpts:a,...c})=>{if(a?.ignoreBlocker??!1){o();return}const f=e.getBlockers?.()??[],l=c.type==="PUSH"||c.type==="REPLACE";if(typeof document<"u"&&f.length&&l)for(const d of f){const h=Bs(c.path,c.state);if(await d.blockerFn({currentLocation:t,nextLocation:h,action:c.type})){e.onBlocked?.();return}}o()};return{get location(){return t},get length(){return e.getLength()},subscribers:s,subscribe:o=>(s.add(o),()=>{s.delete(o)}),push:(o,a,c)=>{const u=t.state[St];a=eo(u+1,a),i({task:()=>{e.pushState(o,a),n({type:"PUSH"})},navigateOpts:c,type:"PUSH",path:o,state:a})},replace:(o,a,c)=>{const u=t.state[St];a=eo(u,a),i({task:()=>{e.replaceState(o,a),n({type:"REPLACE"})},navigateOpts:c,type:"REPLACE",path:o,state:a})},go:(o,a)=>{i({task:()=>{e.go(o),r({type:"GO",index:o})},navigateOpts:a,type:"GO"})},back:o=>{i({task:()=>{e.back(o?.ignoreBlocker??!1),r({type:"BACK"})},navigateOpts:o,type:"BACK"})},forward:o=>{i({task:()=>{e.forward(o?.ignoreBlocker??!1),r({type:"FORWARD"})},navigateOpts:o,type:"FORWARD"})},canGoBack:()=>t.state[St]!==0,createHref:o=>e.createHref(o),block:o=>{if(!e.setBlockers)return()=>{};const a=e.getBlockers?.()??[];return e.setBlockers([...a,o]),()=>{const c=e.getBlockers?.()??[];e.setBlockers?.(c.filter(u=>u!==o))}},flush:()=>e.flush?.(),destroy:()=>e.destroy?.(),notify:n}}function eo(e,t){t||(t={});const s=oi();return{...t,key:s,__TSR_key:s,[St]:e}}function La(e){const t=e?.window??(typeof document<"u"?window:void 0),s=t.history.pushState,n=t.history.replaceState;let r=[];const i=()=>r,o=M=>r=M,a=e?.createHref??(M=>M),c=e?.parseLocation??(()=>Bs(`${t.location.pathname}${t.location.search}${t.location.hash}`,t.history.state));if(!t.history.state?.__TSR_key&&!t.history.state?.key){const M=oi();t.history.replaceState({[St]:0,key:M,__TSR_key:M},"")}let u=c(),f,l=!1,d=!1,h=!1,g=!1;const y=()=>u;let x,b;const L=()=>{x&&(D._ignoreSubscribers=!0,(x.isPush?t.history.pushState:t.history.replaceState)(x.state,"",x.href),D._ignoreSubscribers=!1,x=void 0,b=void 0,f=void 0)},$=(M,B,W)=>{const J=a(B);b||(f=u),u=Bs(B,W),x={href:J,state:W,isPush:x?.isPush||M==="push"},b||(b=Promise.resolve().then(()=>L()))},C=M=>{u=c(),D.notify({type:M})},k=async()=>{if(d){d=!1;return}const M=c(),B=M.state[St]-u.state[St],W=B===1,J=B===-1,de=!W&&!J||l;l=!1;const P=de?"GO":J?"BACK":"FORWARD",H=de?{type:"GO",index:B}:{type:J?"BACK":"FORWARD"};if(h)h=!1;else{const te=i();if(typeof document<"u"&&te.length){for(const Q of te)if(await Q.blockerFn({currentLocation:u,nextLocation:M,action:P})){d=!0,t.history.go(1),D.notify(H);return}}}u=c(),D.notify(H)},_=M=>{if(g){g=!1;return}let B=!1;const W=i();if(typeof document<"u"&&W.length)for(const J of W){const de=J.enableBeforeUnload??!0;if(de===!0){B=!0;break}if(typeof de=="function"&&de()===!0){B=!0;break}}if(B)return M.preventDefault(),M.returnValue=""},D=Nu({getLocation:y,getLength:()=>t.history.length,pushState:(M,B)=>$("push",M,B),replaceState:(M,B)=>$("replace",M,B),back:M=>(M&&(h=!0),g=!0,t.history.back()),forward:M=>{M&&(h=!0),g=!0,t.history.forward()},go:M=>{l=!0,t.history.go(M)},createHref:M=>a(M),flush:L,destroy:()=>{t.history.pushState=s,t.history.replaceState=n,t.removeEventListener(Qi,_,{capture:!0}),t.removeEventListener(Xi,k)},onBlocked:()=>{f&&u!==f&&(u=f)},getBlockers:i,setBlockers:o,notifyOnIndexChange:!1});return t.addEventListener(Qi,_,{capture:!0}),t.addEventListener(Xi,k),t.history.pushState=function(...M){const B=s.apply(t.history,M);return D._ignoreSubscribers||C("PUSH"),B},t.history.replaceState=function(...M){const B=n.apply(t.history,M);return D._ignoreSubscribers||C("REPLACE"),B},D}function Fu(e){const t=typeof document<"u"?window:void 0;return La({window:t,parseLocation:()=>{const s=t.location.hash.split("#").slice(1),n=s[0]??"/",r=t.location.search,i=s.slice(1),o=i.length===0?"":`#${i.join("#")}`,a=`${n}${r}${o}`;return Bs(a,t.history.state)},createHref:s=>`${t.location.pathname}${t.location.search}#${s}`})}function Bs(e,t){const s=e.indexOf("#"),n=e.indexOf("?"),r=oi();return{href:e,pathname:e.substring(0,s>0?n>0?Math.min(s,n):s:n>0?n:e.length),hash:s>-1?e.substring(s):"",search:n>-1?e.slice(n,s===-1?void 0:s):"",state:t||{[St]:0,key:r,__TSR_key:r}}}function oi(){return(Math.random()+1).toString(36).substring(7)}function vn(e){return e[e.length-1]}function $u(e){return typeof e=="function"}function Gt(e,t){return $u(e)?e(t):e}const Bu=Object.prototype.hasOwnProperty;function je(e,t){if(e===t)return e;const s=t,n=no(e)&&no(s);if(!n&&!(yn(e)&&yn(s)))return s;const r=n?e:to(e);if(!r)return s;const i=n?s:to(s);if(!i)return s;const o=r.length,a=i.length,c=n?new Array(a):{};let u=0;for(let f=0;f"u")return!0;const s=t.prototype;return!(!so(s)||!s.hasOwnProperty("isPrototypeOf"))}function so(e){return Object.prototype.toString.call(e)==="[object Object]"}function no(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function $t(e,t,s){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0,r=e.length;nr||!$t(e[o],t[o],s)))return!1;return r===i}return!1}function ts(e){let t,s;const n=new Promise((r,i)=>{t=r,s=i});return n.status="pending",n.resolve=r=>{n.status="resolved",n.value=r,t(r),e?.(r)},n.reject=r=>{n.status="rejected",s(r)},n}function Rt(e){return!!(e&&typeof e=="object"&&typeof e.then=="function")}function ro(e){try{return decodeURI(e)}catch{return e.replaceAll(/%[0-9A-F]{2}/gi,t=>{try{return decodeURI(t)}catch{return t}})}}function io(e,t){if(!e)return e;const s=/%25|%5C/gi;let n=0,r="",i;for(;(i=s.exec(e))!==null;)r+=ro(e.slice(n,i.index))+i[0],n=s.lastIndex;return r+ro(n?e.slice(n):e)}var ju="Invariant failed";function Dt(e,t){if(!e)throw new Error(ju)}function _n(e){const t=new Map;let s,n;const r=i=>{i.next&&(i.prev?(i.prev.next=i.next,i.next.prev=i.prev,i.next=void 0,n&&(n.next=i,i.prev=n)):(i.next.prev=void 0,s=i.next,i.next=void 0,n&&(i.prev=n,n.next=i)),n=i)};return{get(i){const o=t.get(i);if(o)return r(o),o.value},set(i,o){if(t.size>=e&&s){const c=s;t.delete(c.key),c.next&&(s=c.next,c.next.prev=void 0),c===n&&(n=void 0)}const a=t.get(i);if(a)a.value=o,r(a);else{const c={key:i,value:o,prev:n};n&&(n.next=c),n=c,s||(s=c),t.set(i,c)}},clear(){t.clear(),s=void 0,n=void 0}}}const ss=0,Vt=1,Ut=2,js=3,Du=/^([^{]*)\{\$([a-zA-Z_$][a-zA-Z0-9_$]*)\}([^}]*)$/,Vu=/^([^{]*)\{-\$([a-zA-Z_$][a-zA-Z0-9_$]*)\}([^}]*)$/,Uu=/^([^{]*)\{\$\}([^}]*)$/;function ai(e,t,s=new Uint16Array(6)){const n=e.indexOf("/",t),r=n===-1?e.length:n,i=e.substring(t,r);if(!i||!i.includes("$"))return s[0]=ss,s[1]=t,s[2]=t,s[3]=r,s[4]=r,s[5]=r,s;if(i==="$"){const u=e.length;return s[0]=Ut,s[1]=t,s[2]=t,s[3]=u,s[4]=u,s[5]=u,s}if(i.charCodeAt(0)===36)return s[0]=Vt,s[1]=t,s[2]=t+1,s[3]=r,s[4]=r,s[5]=r,s;const o=i.match(Uu);if(o){const f=o[1].length;return s[0]=Ut,s[1]=t+f,s[2]=t+f+1,s[3]=t+f+2,s[4]=t+f+3,s[5]=e.length,s}const a=i.match(Vu);if(a){const u=a[1],f=a[2],l=a[3],d=u.length;return s[0]=js,s[1]=t+d,s[2]=t+d+3,s[3]=t+d+3+f.length,s[4]=r-l.length,s[5]=r,s}const c=i.match(Du);if(c){const u=c[1],f=c[2],l=c[3],d=u.length;return s[0]=Vt,s[1]=t+d,s[2]=t+d+2,s[3]=t+d+2+f.length,s[4]=r-l.length,s[5]=r,s}return s[0]=ss,s[1]=t,s[2]=t,s[3]=r,s[4]=r,s[5]=r,s}function Bn(e,t,s,n,r,i,o){o?.(s);let a=n;{const c=s.fullPath??s.from,u=c.length,f=s.options?.caseSensitive??e;for(;a_.caseSensitive===L&&_.prefix===$&&_.suffix===C);if(k)d=k;else{const _=er(Vt,s.fullPath??s.from,L,$,C);d=_,_.depth=i,_.parent=r,r.dynamic??=[],r.dynamic.push(_)}break}case js:{const x=c.substring(h,l[1]),b=c.substring(l[4],g),L=f&&!!(x||b),$=x?L?x:x.toLowerCase():void 0,C=b?L?b:b.toLowerCase():void 0,k=r.optional?.find(_=>_.caseSensitive===L&&_.prefix===$&&_.suffix===C);if(k)d=k;else{const _=er(js,s.fullPath??s.from,L,$,C);d=_,_.parent=r,_.depth=i,r.optional??=[],r.optional.push(_)}break}case Ut:{const x=c.substring(h,l[1]),b=c.substring(l[4],g),L=f&&!!(x||b),$=x?L?x:x.toLowerCase():void 0,C=b?L?b:b.toLowerCase():void 0,k=er(Ut,s.fullPath??s.from,L,$,C);d=k,k.parent=r,k.depth=i,r.wildcard??=[],r.wildcard.push(k)}}r=d}if((s.path||!s.children)&&!s.isRoot){const l=c.endsWith("/");l||(r.notFound=s),(!r.route||!r.isIndex&&l)&&(r.route=s,r.fullPath=s.fullPath??s.from),r.isIndex||=l}}if(s.children)for(const c of s.children)Bn(e,t,c,a,r,i,o)}function Qn(e,t){if(e.prefix&&t.prefix&&e.prefix!==t.prefix){if(e.prefix.startsWith(t.prefix))return-1;if(t.prefix.startsWith(e.prefix))return 1}if(e.suffix&&t.suffix&&e.suffix!==t.suffix){if(e.suffix.endsWith(t.suffix))return-1;if(t.suffix.endsWith(e.suffix))return 1}return e.prefix&&!t.prefix?-1:!e.prefix&&t.prefix?1:e.suffix&&!t.suffix?-1:!e.suffix&&t.suffix?1:e.caseSensitive&&!t.caseSensitive?-1:!e.caseSensitive&&t.caseSensitive?1:0}function Nt(e){if(e.static)for(const t of e.static.values())Nt(t);if(e.staticInsensitive)for(const t of e.staticInsensitive.values())Nt(t);if(e.dynamic?.length){e.dynamic.sort(Qn);for(const t of e.dynamic)Nt(t)}if(e.optional?.length){e.optional.sort(Qn);for(const t of e.optional)Nt(t)}if(e.wildcard?.length){e.wildcard.sort(Qn);for(const t of e.wildcard)Nt(t)}}function Ds(e){return{kind:ss,depth:0,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:e,parent:null,isIndex:!1,notFound:null}}function er(e,t,s,n,r){return{kind:e,depth:0,static:null,staticInsensitive:null,dynamic:null,optional:null,wildcard:null,route:null,fullPath:t,parent:null,isIndex:!1,notFound:null,caseSensitive:s,prefix:n,suffix:r}}function Hu(e,t){const s=Ds("/"),n=new Uint16Array(6);for(const r of e)Bn(!1,n,r,1,s,0);Nt(s),t.masksTree=s,t.flatCache=_n(1e3)}function Zu(e,t){e||="/";const s=t.flatCache.get(e);if(s)return s;const n=ci(e,t.masksTree);return t.flatCache.set(e,n),n}function Wu(e,t,s,n,r){e||="/",n||="/";const i=t?`case\0${e}`:e;let o=r.singleCache.get(i);if(!o){o=Ds("/");const a=new Uint16Array(6);Bn(t,a,{from:e},1,o,0),r.singleCache.set(i,o)}return ci(n,o,s)}function zu(e,t,s=!1){const n=s?e:`nofuzz\0${e}`,r=t.matchCache.get(n);if(r!==void 0)return r;e||="/";const i=ci(e,t.segmentTree,s);return i&&(i.branch=Ju(i.route)),t.matchCache.set(n,i),i}function Ku(e){return e==="/"?e:e.replace(/\/{1,}$/,"")}function qu(e,t=!1,s){const n=Ds(e.fullPath),r=new Uint16Array(6),i={},o={};let a=0;return Bn(t,r,e,1,n,0,u=>{if(s?.(u,a),Dt(!(u.id in i),`Duplicate routes found with id: ${String(u.id)}`),i[u.id]=u,a!==0&&u.path){const f=Ku(u.fullPath);(!o[f]||u.fullPath.endsWith("/"))&&(o[f]=u)}a++}),Nt(n),{processedTree:{segmentTree:n,singleCache:_n(1e3),matchCache:_n(1e3),flatCache:null,masksTree:null},routesById:i,routesByPath:o}}function ci(e,t,s=!1){const n=e.split("/"),r=Xu(e,n,t,s);if(!r)return null;const i=Gu(e,n,r),o="**"in r;return o&&(i["**"]=r["**"]),{route:o?r.node.notFound??r.node.route:r.node.route,params:i}}function Gu(e,t,s){const n=Yu(s.node);let r=null;const i={};for(let o=0,a=0,c=0;a=0;M--){const B=d.optional[M];a.push({node:B,index:h,skipped:_,depth:D,statics:x,dynamics:b,optionals:L})}if(!$)for(let M=d.optional.length-1;M>=0;M--){const B=d.optional[M],{prefix:W,suffix:J}=B;if(W||J){const de=B.caseSensitive?C:k??=C.toLowerCase();if(W&&!de.startsWith(W)||J&&!de.endsWith(J))continue}a.push({node:B,index:h+1,skipped:g,depth:D,statics:x,dynamics:b,optionals:L+1})}}if(!$&&d.dynamic&&C)for(let _=d.dynamic.length-1;_>=0;_--){const D=d.dynamic[_],{prefix:M,suffix:B}=D;if(M||B){const W=D.caseSensitive?C:k??=C.toLowerCase();if(M&&!W.startsWith(M)||B&&!W.endsWith(B))continue}a.push({node:D,index:h+1,skipped:g,depth:y+1,statics:x,dynamics:b+1,optionals:L})}if(!$&&d.staticInsensitive){const _=d.staticInsensitive.get(k??=C.toLowerCase());_&&a.push({node:_,index:h+1,skipped:g,depth:y+1,statics:x+1,dynamics:b,optionals:L})}if(!$&&d.static){const _=d.static.get(C);_&&a.push({node:_,index:h+1,skipped:g,depth:y+1,statics:x+1,dynamics:b,optionals:L})}}if(f&&c)return Qs(c,f)?f:c;if(f)return f;if(c)return c;if(n&&u){let l=u.index;for(let h=0;he.statics||t.statics===e.statics&&(t.dynamics>e.dynamics||t.dynamics===e.dynamics&&(t.optionals>e.optionals||t.optionals===e.optionals&&(t.node.isIndex>e.node.isIndex||t.node.isIndex===e.node.isIndex&&t.depth>e.depth))):!0}function rn(e){return li(e.filter(t=>t!==void 0).join("/"))}function li(e){return e.replace(/\/{2,}/g,"/")}function Ma(e){return e==="/"?e:e.replace(/^\/{1,}/,"")}function Bt(e){const t=e.length;return t>1&&e[t-1]==="/"?e.replace(/\/{1,}$/,""):e}function Ea(e){return Bt(Ma(e))}function bn(e,t){return e?.endsWith("/")&&e!=="/"&&e!==`${t}/`?e.slice(0,-1):e}function Qu(e,t,s){return bn(e,s)===bn(t,s)}function ef({base:e,to:t,trailingSlash:s="never",cache:n}){const r=t.startsWith("/"),i=!r&&t===".";let o;if(n){o=r?t:i?e:e+"\0"+t;const l=n.get(o);if(l)return l}let a;if(i)a=e.split("/");else if(r)a=t.split("/");else{for(a=e.split("/");a.length>1&&vn(a)==="";)a.pop();const l=t.split("/");for(let d=0,h=l.length;d1&&(vn(a)===""?s==="never"&&a.pop():s==="always"&&a.push(""));let c,u="";for(let l=0;l0&&(u+="/");const d=a[l];if(!d)continue;c=ai(d,0,c);const h=c[0];if(h===ss){u+=d;continue}const g=c[5],y=d.substring(0,c[1]),x=d.substring(c[4],g),b=d.substring(c[2],c[3]);h===Vt?u+=y||x?`${y}{$${b}}${x}`:`$${b}`:h===Ut?u+=y||x?`${y}{$}${x}`:"$":u+=`${y}{-$${b}}${x}`}u=li(u);const f=u||"/";return o&&n&&n.set(o,f),f}function tr(e,t,s){const n=t[e];return typeof n!="string"?n:e==="_splat"?encodeURI(n):tf(n,s)}function sr({path:e,params:t,decodeCharMap:s}){let n=!1;const r={};if(!e||e==="/")return{interpolatedPath:"/",usedParams:r,isMissingParams:n};if(!e.includes("$"))return{interpolatedPath:e,usedParams:r,isMissingParams:n};const i=e.length;let o=0,a,c="";for(;o{let s;return(...n)=>{s||(s=setTimeout(()=>{e(...n),s=null},t))}};function rf(){const e=sf();if(!e)return null;const t=e.getItem(xn);let s=t?JSON.parse(t):{};return{state:s,set:n=>(s=Gt(n,s)||s,e.setItem(xn,JSON.stringify(s)))}}const en=rf(),Pr=e=>e.state.__TSR_key||e.href;function of(e){const t=[];let s;for(;s=e.parentNode;)t.push(`${e.tagName}:nth-child(${Array.prototype.indexOf.call(s.children,e)+1})`),e=s;return`${t.reverse().join(" > ")}`.toLowerCase()}let wn=!1;function Oa({storageKey:e,key:t,behavior:s,shouldScrollRestoration:n,scrollToTopSelectors:r,location:i}){let o;try{o=JSON.parse(sessionStorage.getItem(e)||"{}")}catch(u){console.error(u);return}const a=t||window.history.state?.__TSR_key,c=o[a];wn=!0;e:{if(n&&c&&Object.keys(c).length>0){for(const l in c){const d=c[l];if(l==="window")window.scrollTo({top:d.scrollY,left:d.scrollX,behavior:s});else if(l){const h=document.querySelector(l);h&&(h.scrollLeft=d.scrollX,h.scrollTop=d.scrollY)}}break e}const u=(i??window.location).hash.split("#",2)[1];if(u){const l=window.history.state?.__hashScrollIntoViewOptions??!0;if(l){const d=document.getElementById(u);d&&d.scrollIntoView(l)}break e}const f={top:0,left:0,behavior:s};if(window.scrollTo(f),r)for(const l of r){if(l==="window")continue;const d=typeof l=="function"?l():document.querySelector(l);d&&d.scrollTo(f)}}wn=!1}function af(e,t){if(!en&&!e.isServer||((e.options.scrollRestoration??!1)&&(e.isScrollRestoring=!0),e.isServer||e.isScrollRestorationSetup||!en))return;e.isScrollRestorationSetup=!0,wn=!1;const n=e.options.getScrollRestorationKey||Pr;window.history.scrollRestoration="manual";const r=i=>{if(wn||!e.isScrollRestoring)return;let o="";if(i.target===document||i.target===window)o="window";else{const c=i.target.getAttribute("data-scroll-restoration-id");c?o=`[data-scroll-restoration-id="${c}"]`:o=of(i.target)}const a=n(e.state.location);en.set(c=>{const u=c[a]||={},f=u[o]||={};if(o==="window")f.scrollX=window.scrollX||0,f.scrollY=window.scrollY||0;else if(o){const l=document.querySelector(o);l&&(f.scrollX=l.scrollLeft||0,f.scrollY=l.scrollTop||0)}return c})};typeof document<"u"&&document.addEventListener("scroll",nf(r,100),!0),e.subscribe("onRendered",i=>{const o=n(i.toLocation);if(!e.resetNextScroll){e.resetNextScroll=!0;return}typeof e.options.scrollRestoration=="function"&&!e.options.scrollRestoration({location:e.latestLocation})||(Oa({storageKey:xn,key:o,behavior:e.options.scrollRestorationBehavior,shouldScrollRestoration:e.isScrollRestoring,scrollToTopSelectors:e.options.scrollToTopSelectors,location:e.history.location}),e.isScrollRestoring&&en.set(a=>(a[o]||={},a)))})}function cf(e){if(typeof document<"u"&&document.querySelector){const t=e.state.location.state.__hashScrollIntoViewOptions??!0;if(t&&e.state.location.hash!==""){const s=document.getElementById(e.state.location.hash);s&&s.scrollIntoView(t)}}}function lf(e,t=String){const s=new URLSearchParams;for(const n in e){const r=e[n];r!==void 0&&s.set(n,t(r))}return s.toString()}function nr(e){return e?e==="false"?!1:e==="true"?!0:+e*0===0&&+e+""===e?+e:e:""}function uf(e){const t=new URLSearchParams(e),s={};for(const[n,r]of t.entries()){const i=s[n];i==null?s[n]=nr(r):Array.isArray(i)?i.push(nr(r)):s[n]=[i,nr(r)]}return s}const ff=hf(JSON.parse),df=pf(JSON.stringify,JSON.parse);function hf(e){return t=>{t[0]==="?"&&(t=t.substring(1));const s=uf(t);for(const n in s){const r=s[n];if(typeof r=="string")try{s[n]=e(r)}catch{}}return s}}function pf(e,t){const s=typeof t=="function";function n(r){if(typeof r=="object"&&r!==null)try{return e(r)}catch{}else if(s&&typeof r=="string")try{return t(r),e(r)}catch{}return r}return r=>{const i=lf(r,n);return i?`?${i}`:""}}const Ne="__root__";function mf(e){if(e.statusCode=e.statusCode||e.code||307,!e.reloadDocument&&typeof e.href=="string")try{new URL(e.href),e.reloadDocument=!0}catch{}const t=new Headers(e.headers);e.href&&t.get("Location")===null&&t.set("Location",e.href);const s=new Response(null,{status:e.statusCode,headers:t});if(s.options=e,e.throw)throw s;return s}function Ue(e){return e instanceof Response&&!!e.options}const on=e=>{if(!e.rendered)return e.rendered=!0,e.onReady?.()},jn=(e,t)=>!!(e.preload&&!e.router.state.matches.some(s=>s.id===t)),ui=(e,t,s=!0)=>{const n={...e.router.options.context??{}},r=s?t:t-1;for(let i=0;i<=r;i++){const o=e.matches[i];if(!o)continue;const a=e.router.getMatch(o.id);a&&Object.assign(n,a.__routeContext,a.__beforeLoadContext)}return n},Aa=(e,t)=>{const s=e.router.routesById[t.routeId??""]??e.router.routeTree;!s.options.notFoundComponent&&e.router.options?.defaultNotFoundComponent&&(s.options.notFoundComponent=e.router.options.defaultNotFoundComponent),Dt(s.options.notFoundComponent);const n=e.matches.find(r=>r.routeId===s.id);Dt(n,"Could not find match for route: "+s.id),e.updateMatch(n.id,r=>({...r,status:"notFound",error:t,isFetching:!1})),t.routerCode==="BEFORE_LOAD"&&s.parentRoute&&(t.routeId=s.parentRoute.id,Aa(e,t))},_t=(e,t,s)=>{if(!(!Ue(s)&&!$e(s))){if(Ue(s)&&s.redirectHandled&&!s.options.reloadDocument)throw s;if(t){t._nonReactive.beforeLoadPromise?.resolve(),t._nonReactive.loaderPromise?.resolve(),t._nonReactive.beforeLoadPromise=void 0,t._nonReactive.loaderPromise=void 0;const n=Ue(s)?"redirected":"notFound";t._nonReactive.error=s,e.updateMatch(t.id,r=>({...r,status:n,isFetching:!1,error:s})),$e(s)&&!s.routeId&&(s.routeId=t.routeId),t._nonReactive.loadPromise?.resolve()}throw Ue(s)?(e.rendered=!0,s.options._fromLocation=e.location,s.redirectHandled=!0,s=e.router.resolveRedirect(s),s):(Aa(e,s),s)}},Na=(e,t)=>{const s=e.router.getMatch(t);return!!(!e.router.isServer&&s._nonReactive.dehydrated||e.router.isServer&&s.ssr===!1)},ps=(e,t,s,n)=>{const{id:r,routeId:i}=e.matches[t],o=e.router.looseRoutesById[i];if(s instanceof Promise)throw s;s.routerCode=n,e.firstBadMatchIndex??=t,_t(e,e.router.getMatch(r),s);try{o.options.onError?.(s)}catch(a){s=a,_t(e,e.router.getMatch(r),s)}e.updateMatch(r,a=>(a._nonReactive.beforeLoadPromise?.resolve(),a._nonReactive.beforeLoadPromise=void 0,a._nonReactive.loadPromise?.resolve(),{...a,error:s,status:"error",isFetching:!1,updatedAt:Date.now(),abortController:new AbortController}))},gf=(e,t,s,n)=>{const r=e.router.getMatch(t),i=e.matches[s-1]?.id,o=i?e.router.getMatch(i):void 0;if(e.router.isShell()){r.ssr=n.id===Ne;return}if(o?.ssr===!1){r.ssr=!1;return}const a=h=>h===!0&&o?.ssr==="data-only"?"data-only":h,c=e.router.options.defaultSsr??!0;if(n.options.ssr===void 0){r.ssr=a(c);return}if(typeof n.options.ssr!="function"){r.ssr=a(n.options.ssr);return}const{search:u,params:f}=r,l={search:tn(u,r.searchError),params:tn(f,r.paramsError),location:e.location,matches:e.matches.map(h=>({index:h.index,pathname:h.pathname,fullPath:h.fullPath,staticData:h.staticData,id:h.id,routeId:h.routeId,search:tn(h.search,h.searchError),params:tn(h.params,h.paramsError),ssr:h.ssr}))},d=n.options.ssr(l);if(Rt(d))return d.then(h=>{r.ssr=a(h??c)});r.ssr=a(d??c)},Fa=(e,t,s,n)=>{if(n._nonReactive.pendingTimeout!==void 0)return;const r=s.options.pendingMs??e.router.options.defaultPendingMs;if(!!(e.onReady&&!e.router.isServer&&!jn(e,t)&&(s.options.loader||s.options.beforeLoad||ja(s))&&typeof r=="number"&&r!==1/0&&(s.options.pendingComponent??e.router.options?.defaultPendingComponent))){const o=setTimeout(()=>{on(e)},r);n._nonReactive.pendingTimeout=o}},vf=(e,t,s)=>{const n=e.router.getMatch(t);if(!n._nonReactive.beforeLoadPromise&&!n._nonReactive.loaderPromise)return;Fa(e,t,s,n);const r=()=>{const i=e.router.getMatch(t);i.preload&&(i.status==="redirected"||i.status==="notFound")&&_t(e,i,i.error)};return n._nonReactive.beforeLoadPromise?n._nonReactive.beforeLoadPromise.then(r):r()},yf=(e,t,s,n)=>{const r=e.router.getMatch(t),i=r._nonReactive.loadPromise;r._nonReactive.loadPromise=ts(()=>{i?.resolve()});const{paramsError:o,searchError:a}=r;o&&ps(e,s,o,"PARSE_PARAMS"),a&&ps(e,s,a,"VALIDATE_SEARCH"),Fa(e,t,n,r);const c=new AbortController,u=e.matches[s-1]?.id;(u?e.router.getMatch(u):void 0)?.context??e.router.options.context;let l=!1;const d=()=>{l||(l=!0,e.updateMatch(t,_=>({..._,isFetching:"beforeLoad",fetchCount:_.fetchCount+1,abortController:c})))},h=()=>{r._nonReactive.beforeLoadPromise?.resolve(),r._nonReactive.beforeLoadPromise=void 0,e.updateMatch(t,_=>({..._,isFetching:!1}))};if(!n.options.beforeLoad){Is(()=>{d(),h()});return}r._nonReactive.beforeLoadPromise=ts();const g={...ui(e,s,!1),...r.__routeContext},{search:y,params:x,cause:b}=r,L=jn(e,t),$={search:y,abortController:c,params:x,preload:L,context:g,location:e.location,navigate:_=>e.router.navigate({..._,_fromLocation:e.location}),buildLocation:e.router.buildLocation,cause:L?"preload":b,matches:e.matches,...e.router.options.additionalContext},C=_=>{if(_===void 0){Is(()=>{d(),h()});return}(Ue(_)||$e(_))&&(d(),ps(e,s,_,"BEFORE_LOAD")),Is(()=>{d(),e.updateMatch(t,D=>({...D,__beforeLoadContext:_})),h()})};let k;try{if(k=n.options.beforeLoad($),Rt(k))return d(),k.catch(_=>{ps(e,s,_,"BEFORE_LOAD")}).then(C)}catch(_){d(),ps(e,s,_,"BEFORE_LOAD")}C(k)},_f=(e,t)=>{const{id:s,routeId:n}=e.matches[t],r=e.router.looseRoutesById[n],i=()=>{if(e.router.isServer){const c=gf(e,s,t,r);if(Rt(c))return c.then(a)}return a()},o=()=>yf(e,s,t,r),a=()=>{if(Na(e,s))return;const c=vf(e,s,r);return Rt(c)?c.then(o):o()};return i()},Ls=(e,t,s)=>{const n=e.router.getMatch(t);if(!n||!s.options.head&&!s.options.scripts&&!s.options.headers)return;const r={matches:e.matches,match:n,params:n.params,loaderData:n.loaderData};return Promise.all([s.options.head?.(r),s.options.scripts?.(r),s.options.headers?.(r)]).then(([i,o,a])=>{const c=i?.meta,u=i?.links,f=i?.scripts,l=i?.styles;return{meta:c,links:u,headScripts:f,headers:a,scripts:o,styles:l}})},$a=(e,t,s,n)=>{const r=e.matchPromises[s-1],{params:i,loaderDeps:o,abortController:a,cause:c}=e.router.getMatch(t),u=ui(e,s),f=jn(e,t);return{params:i,deps:o,preload:!!f,parentMatchPromise:r,abortController:a,context:u,location:e.location,navigate:l=>e.router.navigate({...l,_fromLocation:e.location}),cause:f?"preload":c,route:n,...e.router.options.additionalContext}},oo=async(e,t,s,n)=>{try{const r=e.router.getMatch(t);try{(!e.router.isServer||r.ssr===!0)&&Ba(n);const i=n.options.loader?.($a(e,t,s,n)),o=n.options.loader&&Rt(i);if(!!(o||n._lazyPromise||n._componentsPromise||n.options.head||n.options.scripts||n.options.headers||r._nonReactive.minPendingPromise)&&e.updateMatch(t,l=>({...l,isFetching:"loader"})),n.options.loader){const l=o?await i:i;_t(e,e.router.getMatch(t),l),l!==void 0&&e.updateMatch(t,d=>({...d,loaderData:l}))}n._lazyPromise&&await n._lazyPromise;const c=Ls(e,t,n),u=c?await c:void 0,f=r._nonReactive.minPendingPromise;f&&await f,n._componentsPromise&&await n._componentsPromise,e.updateMatch(t,l=>({...l,error:void 0,status:"success",isFetching:!1,updatedAt:Date.now(),...u}))}catch(i){let o=i;const a=r._nonReactive.minPendingPromise;a&&await a,$e(i)&&await n.options.notFoundComponent?.preload?.(),_t(e,e.router.getMatch(t),i);try{n.options.onError?.(i)}catch(f){o=f,_t(e,e.router.getMatch(t),f)}const c=Ls(e,t,n),u=c?await c:void 0;e.updateMatch(t,f=>({...f,error:o,status:"error",isFetching:!1,...u}))}}catch(r){const i=e.router.getMatch(t);if(i){const o=Ls(e,t,n);if(o){const a=await o;e.updateMatch(t,c=>({...c,...a}))}i._nonReactive.loaderPromise=void 0}_t(e,i,r)}},bf=async(e,t)=>{const{id:s,routeId:n}=e.matches[t];let r=!1,i=!1;const o=e.router.looseRoutesById[n],a=()=>{e.updateMatch(s,f=>({...f,context:ui(e,t)}))};if(Na(e,s)){if(e.router.isServer){const f=Ls(e,s,o);if(f){const l=await f;e.updateMatch(s,d=>({...d,...l}))}return e.router.getMatch(s)}}else{const f=e.router.getMatch(s);if(f._nonReactive.loaderPromise){if(f.status==="success"&&!e.sync&&!f.preload)return f;await f._nonReactive.loaderPromise;const l=e.router.getMatch(s),d=l._nonReactive.error||l.error;d&&_t(e,l,d)}else{const l=Date.now()-f.updatedAt,d=jn(e,s),h=d?o.options.preloadStaleTime??e.router.options.defaultPreloadStaleTime??3e4:o.options.staleTime??e.router.options.defaultStaleTime??0,g=o.options.shouldReload,y=typeof g=="function"?g($a(e,s,t,o)):g,x=!!d&&!e.router.state.matches.some(C=>C.id===s),b=e.router.getMatch(s);b._nonReactive.loaderPromise=ts(),x!==b.preload&&e.updateMatch(s,C=>({...C,preload:x}));const{status:L,invalid:$}=b;if(r=L==="success"&&($||(y??l>h)),!(d&&o.options.preload===!1))if(r&&!e.sync)i=!0,(async()=>{try{await oo(e,s,t,o),a();const C=e.router.getMatch(s);C._nonReactive.loaderPromise?.resolve(),C._nonReactive.loadPromise?.resolve(),C._nonReactive.loaderPromise=void 0}catch(C){Ue(C)&&await e.router.navigate(C.options)}})();else if(L!=="success"||r&&e.sync)await oo(e,s,t,o);else{const C=Ls(e,s,o);if(C){const k=await C;e.updateMatch(s,_=>({..._,...k}))}}}}const c=e.router.getMatch(s);i||(c._nonReactive.loaderPromise?.resolve(),c._nonReactive.loadPromise?.resolve()),clearTimeout(c._nonReactive.pendingTimeout),c._nonReactive.pendingTimeout=void 0,i||(c._nonReactive.loaderPromise=void 0),c._nonReactive.dehydrated=void 0,i||a();const u=i?c.isFetching:!1;return u!==c.isFetching||c.invalid!==!1?(e.updateMatch(s,f=>({...f,isFetching:u,invalid:!1})),e.router.getMatch(s)):c};async function ao(e){const t=Object.assign(e,{matchPromises:[]});!t.router.isServer&&t.router.state.matches.some(s=>s._forcePending)&&on(t);try{for(let r=0;r{const{id:s,...n}=t.options;Object.assign(e.options,n),e._lazyLoaded=!0,e._lazyPromise=void 0}):e._lazyLoaded=!0),!e._componentsLoaded&&e._componentsPromise===void 0){const t=()=>{const s=[];for(const n of Da){const r=e.options[n]?.preload;r&&s.push(r())}if(s.length)return Promise.all(s).then(()=>{e._componentsLoaded=!0,e._componentsPromise=void 0});e._componentsLoaded=!0,e._componentsPromise=void 0};e._componentsPromise=e._lazyPromise?e._lazyPromise.then(t):t()}return e._componentsPromise}function tn(e,t){return t?{status:"error",error:t}:{status:"success",value:e}}function ja(e){for(const t of Da)if(e.options[t]?.preload)return!0;return!1}const Da=["component","errorComponent","pendingComponent","notFoundComponent"];function xf(e){return{input:({url:t})=>{for(const s of e)t=Va(s,t);return t},output:({url:t})=>{for(let s=e.length-1;s>=0;s--)t=Ua(e[s],t);return t}}}function wf(e){const t=Ea(e.basepath),s=`/${t}`,n=`${s}/`,r=e.caseSensitive?s:s.toLowerCase(),i=e.caseSensitive?n:n.toLowerCase();return{input:({url:o})=>{const a=e.caseSensitive?o.pathname:o.pathname.toLowerCase();return a===r?o.pathname="/":a.startsWith(i)&&(o.pathname=o.pathname.slice(s.length)),o},output:({url:o})=>(o.pathname=rn(["/",t,o.pathname]),o)}}function Va(e,t){const s=e?.input?.({url:t});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return t}function Ua(e,t){const s=e?.output?.({url:t});if(s){if(typeof s=="string")return new URL(s);if(s instanceof URL)return s}return t}function jt(e){const t=e.resolvedLocation,s=e.location,n=t?.pathname!==s.pathname,r=t?.href!==s.href,i=t?.hash!==s.hash;return{fromLocation:t,toLocation:s,pathChanged:n,hrefChanged:r,hashChanged:i}}class Sf{constructor(t){this.tempLocationKey=`${Math.round(Math.random()*1e7)}`,this.resetNextScroll=!0,this.shouldViewTransition=void 0,this.isViewTransitionTypesSupported=void 0,this.subscribers=new Set,this.isScrollRestoring=!1,this.isScrollRestorationSetup=!1,this.startTransition=s=>s(),this.update=s=>{s.notFoundRoute&&console.warn("The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/framework/react/guide/not-found-errors#migrating-from-notfoundroute for more info.");const n=this.options,r=this.basepath??n?.basepath??"/",i=this.basepath===void 0,o=n?.rewrite;this.options={...n,...s},this.isServer=this.options.isServer??typeof document>"u",this.pathParamsDecodeCharMap=this.options.pathParamsAllowedCharacters?new Map(this.options.pathParamsAllowedCharacters.map(d=>[encodeURIComponent(d),d])):void 0,(!this.history||this.options.history&&this.options.history!==this.history)&&(this.options.history?this.history=this.options.history:this.isServer||(this.history=La())),this.origin=this.options.origin,this.origin||(!this.isServer&&window?.origin&&window.origin!=="null"?this.origin=window.origin:this.origin="http://localhost"),this.history&&this.updateLatestLocation(),this.options.routeTree!==this.routeTree&&(this.routeTree=this.options.routeTree,this.buildRouteTree()),!this.__store&&this.latestLocation&&(this.__store=new Au(Cf(this.latestLocation),{onUpdate:()=>{this.__store.state={...this.state,cachedMatches:this.state.cachedMatches.filter(d=>!["redirected"].includes(d.status))}}}),af(this));let a=!1;const c=this.options.basepath??"/",u=this.options.rewrite;if(i||r!==c||o!==u){this.basepath=c;const d=[];Ea(c)!==""&&d.push(wf({basepath:c})),u&&d.push(u),this.rewrite=d.length===0?void 0:d.length===1?d[0]:xf(d),this.history&&this.updateLatestLocation(),a=!0}a&&this.__store&&(this.__store.state={...this.state,location:this.latestLocation}),typeof window<"u"&&"CSS"in window&&typeof window.CSS?.supports=="function"&&(this.isViewTransitionTypesSupported=window.CSS.supports("selector(:active-view-transition-type(a)"))},this.updateLatestLocation=()=>{this.latestLocation=this.parseLocation(this.history.location,this.latestLocation)},this.buildRouteTree=()=>{const{routesById:s,routesByPath:n,processedTree:r}=qu(this.routeTree,this.options.caseSensitive,(o,a)=>{o.init({originalIndex:a})});this.options.routeMasks&&Hu(this.options.routeMasks,r),this.routesById=s,this.routesByPath=n,this.processedTree=r;const i=this.options.notFoundRoute;i&&(i.init({originalIndex:99999999999}),this.routesById[i.id]=i)},this.subscribe=(s,n)=>{const r={eventType:s,fn:n};return this.subscribers.add(r),()=>{this.subscribers.delete(r)}},this.emit=s=>{this.subscribers.forEach(n=>{n.eventType===s.type&&n.fn(s)})},this.parseLocation=(s,n)=>{const r=({href:c,state:u})=>{const f=new URL(c,this.origin),l=Va(this.rewrite,f),d=this.options.parseSearch(l.search),h=this.options.stringifySearch(d);return l.search=h,{href:l.href.replace(l.origin,""),publicHref:c,url:l,pathname:io(l.pathname),searchStr:h,search:je(n?.search,d),hash:l.hash.split("#").reverse()[0]??"",state:je(n?.state,u)}},i=r(s),{__tempLocation:o,__tempKey:a}=i.state;if(o&&(!a||a===this.tempLocationKey)){const c=r(o);return c.state.key=i.state.key,c.state.__TSR_key=i.state.__TSR_key,delete c.state.__tempLocation,{...c,maskedLocation:i}}return i},this.resolvePathCache=_n(1e3),this.resolvePathWithBase=(s,n)=>ef({base:s,to:li(n),trailingSlash:this.options.trailingSlash,cache:this.resolvePathCache}),this.matchRoutes=(s,n,r)=>typeof s=="string"?this.matchRoutesInternal({pathname:s,search:n},r):this.matchRoutesInternal(s,n),this.getMatchedRoutes=s=>Pf({pathname:s,routesById:this.routesById,processedTree:this.processedTree}),this.cancelMatch=s=>{const n=this.getMatch(s);n&&(n.abortController.abort(),clearTimeout(n._nonReactive.pendingTimeout),n._nonReactive.pendingTimeout=void 0)},this.cancelMatches=()=>{const s=this.state.matches.filter(i=>i.status==="pending"),n=this.state.matches.filter(i=>i.isFetching==="loader");new Set([...this.state.pendingMatches??[],...s,...n]).forEach(i=>{this.cancelMatch(i.id)})},this.buildLocation=s=>{const n=(i={})=>{const o=i._fromLocation||this.pendingBuiltLocation||this.latestLocation,a=this.matchRoutes(o,{_buildLocation:!0}),c=vn(a);i.from;const u=i.unsafeRelative==="path"?o.pathname:i.from??c.fullPath,f=this.resolvePathWithBase(u,"."),l=c.search,d={...c.params},h=i.to?this.resolvePathWithBase(f,`${i.to}`):this.resolvePathWithBase(f,"."),g=i.params===!1||i.params===null?{}:(i.params??!0)===!0?d:Object.assign(d,Gt(i.params,d)),y=sr({path:h,params:g}).interpolatedPath,x=this.matchRoutes(y,void 0,{_buildLocation:!0}).map(W=>this.looseRoutesById[W.routeId]);if(Object.keys(g).length>0)for(const W of x){const J=W.options.params?.stringify??W.options.stringifyParams;J&&Object.assign(g,J(g))}const b=s.leaveParams?h:io(sr({path:h,params:g,decodeCharMap:this.pathParamsDecodeCharMap}).interpolatedPath);let L=l;if(s._includeValidateSearch&&this.options.search?.strict){const W={};x.forEach(J=>{if(J.options.validateSearch)try{Object.assign(W,kr(J.options.validateSearch,{...W,...L}))}catch{}}),L=W}L=kf({search:L,dest:i,destRoutes:x,_includeValidateSearch:s._includeValidateSearch}),L=je(l,L);const $=this.options.stringifySearch(L),C=i.hash===!0?o.hash:i.hash?Gt(i.hash,o.hash):void 0,k=C?`#${C}`:"";let _=i.state===!0?o.state:i.state?Gt(i.state,o.state):{};_=je(o.state,_);const D=`${b}${$}${k}`,M=new URL(D,this.origin),B=Ua(this.rewrite,M);return{publicHref:B.pathname+B.search+B.hash,href:D,url:B,pathname:b,search:L,searchStr:$,state:_,hash:C??"",unmaskOnReload:i.unmaskOnReload}},r=(i={},o)=>{const a=n(i);let c=o?n(o):void 0;if(!c){const u={};if(this.options.routeMasks){const f=Zu(a.pathname,this.processedTree);if(f){Object.assign(u,f.params);const{from:l,params:d,...h}=f.route,g=d===!1||d===null?{}:(d??!0)===!0?u:Object.assign(u,Gt(d,u));o={from:s.from,...h,params:g},c=n(o)}}}return c&&(a.maskedLocation=c),a};return s.mask?r(s,{from:s.from,...s.mask}):r(s)},this.commitLocation=({viewTransition:s,ignoreBlocker:n,...r})=>{const i=()=>{const c=["key","__TSR_key","__TSR_index","__hashScrollIntoViewOptions"];c.forEach(f=>{r.state[f]=this.latestLocation.state[f]});const u=$t(r.state,this.latestLocation.state);return c.forEach(f=>{delete r.state[f]}),u},o=Bt(this.latestLocation.href)===Bt(r.href),a=this.commitLocationPromise;if(this.commitLocationPromise=ts(()=>{a?.resolve()}),o&&i())this.load();else{let{maskedLocation:c,hashScrollIntoView:u,url:f,...l}=r;c&&(l={...c,state:{...c.state,__tempKey:void 0,__tempLocation:{...l,search:l.searchStr,state:{...l.state,__tempKey:void 0,__tempLocation:void 0,__TSR_key:void 0,key:void 0}}}},(l.unmaskOnReload??this.options.unmaskOnReload??!1)&&(l.state.__tempKey=this.tempLocationKey)),l.state.__hashScrollIntoViewOptions=u??this.options.defaultHashScrollIntoView??!0,this.shouldViewTransition=s,this.history[r.replace?"replace":"push"](l.publicHref,l.state,{ignoreBlocker:n})}return this.resetNextScroll=r.resetScroll??!0,this.history.subscribers.size||this.load(),this.commitLocationPromise},this.buildAndCommitLocation=({replace:s,resetScroll:n,hashScrollIntoView:r,viewTransition:i,ignoreBlocker:o,href:a,...c}={})=>{if(a){const l=this.history.location.state.__TSR_index,d=Bs(a,{__TSR_index:s?l:l+1});c.to=d.pathname,c.search=this.options.parseSearch(d.search),c.hash=d.hash.slice(1)}const u=this.buildLocation({...c,_includeValidateSearch:!0});this.pendingBuiltLocation=u;const f=this.commitLocation({...u,viewTransition:i,replace:s,resetScroll:n,hashScrollIntoView:r,ignoreBlocker:o});return Promise.resolve().then(()=>{this.pendingBuiltLocation===u&&(this.pendingBuiltLocation=void 0)}),f},this.navigate=async({to:s,reloadDocument:n,href:r,...i})=>{if(!n&&r)try{new URL(`${r}`),n=!0}catch{}if(n){if(r||(r=this.buildLocation({to:s,...i}).url.href),!i.ignoreBlocker){const a=this.history.getBlockers?.()??[];for(const c of a)if(c?.blockerFn&&await c.blockerFn({currentLocation:this.latestLocation,nextLocation:this.latestLocation,action:"PUSH"}))return Promise.resolve()}return i.replace?window.location.replace(r):window.location.href=r,Promise.resolve()}return this.buildAndCommitLocation({...i,href:r,to:s,_isNavigate:!0})},this.beforeLoad=()=>{if(this.cancelMatches(),this.updateLatestLocation(),this.isServer){const n=this.buildLocation({to:this.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(this.latestLocation.publicHref!==n.publicHref||n.url.origin!==this.origin){const r=this.getParsedLocationHref(n);throw mf({href:r})}}const s=this.matchRoutes(this.latestLocation);this.__store.setState(n=>({...n,status:"pending",statusCode:200,isLoading:!0,location:this.latestLocation,pendingMatches:s,cachedMatches:n.cachedMatches.filter(r=>!s.some(i=>i.id===r.id))}))},this.load=async s=>{let n,r,i;for(i=new Promise(a=>{this.startTransition(async()=>{try{this.beforeLoad();const c=this.latestLocation,u=this.state.resolvedLocation;this.state.redirect||this.emit({type:"onBeforeNavigate",...jt({resolvedLocation:u,location:c})}),this.emit({type:"onBeforeLoad",...jt({resolvedLocation:u,location:c})}),await ao({router:this,sync:s?.sync,matches:this.state.pendingMatches,location:c,updateMatch:this.updateMatch,onReady:async()=>{this.startTransition(()=>{this.startViewTransition(async()=>{let f=[],l=[],d=[];Is(()=>{this.__store.setState(h=>{const g=h.matches,y=h.pendingMatches||h.matches;return f=g.filter(x=>!y.some(b=>b.id===x.id)),l=y.filter(x=>!g.some(b=>b.id===x.id)),d=y.filter(x=>g.some(b=>b.id===x.id)),{...h,isLoading:!1,loadedAt:Date.now(),matches:y,pendingMatches:void 0,cachedMatches:[...h.cachedMatches,...f.filter(x=>x.status!=="error"&&x.status!=="notFound")]}}),this.clearExpiredCache()}),[[f,"onLeave"],[l,"onEnter"],[d,"onStay"]].forEach(([h,g])=>{h.forEach(y=>{this.looseRoutesById[y.routeId].options[g]?.(y)})})})})}})}catch(c){Ue(c)?(n=c,this.isServer||this.navigate({...n.options,replace:!0,ignoreBlocker:!0})):$e(c)&&(r=c),this.__store.setState(u=>({...u,statusCode:n?n.status:r?404:u.matches.some(f=>f.status==="error")?500:200,redirect:n}))}this.latestLoadPromise===i&&(this.commitLocationPromise?.resolve(),this.latestLoadPromise=void 0,this.commitLocationPromise=void 0),a()})}),this.latestLoadPromise=i,await i;this.latestLoadPromise&&i!==this.latestLoadPromise;)await this.latestLoadPromise;let o;this.hasNotFoundMatch()?o=404:this.__store.state.matches.some(a=>a.status==="error")&&(o=500),o!==void 0&&this.__store.setState(a=>({...a,statusCode:o}))},this.startViewTransition=s=>{const n=this.shouldViewTransition??this.options.defaultViewTransition;if(delete this.shouldViewTransition,n&&typeof document<"u"&&"startViewTransition"in document&&typeof document.startViewTransition=="function"){let r;if(typeof n=="object"&&this.isViewTransitionTypesSupported){const i=this.latestLocation,o=this.state.resolvedLocation,a=typeof n.types=="function"?n.types(jt({resolvedLocation:o,location:i})):n.types;if(a===!1){s();return}r={update:s,types:a}}else r=s;document.startViewTransition(r)}else s()},this.updateMatch=(s,n)=>{this.startTransition(()=>{const r=this.state.pendingMatches?.some(i=>i.id===s)?"pendingMatches":this.state.matches.some(i=>i.id===s)?"matches":this.state.cachedMatches.some(i=>i.id===s)?"cachedMatches":"";r&&this.__store.setState(i=>({...i,[r]:i[r]?.map(o=>o.id===s?n(o):o)}))})},this.getMatch=s=>{const n=r=>r.id===s;return this.state.cachedMatches.find(n)??this.state.pendingMatches?.find(n)??this.state.matches.find(n)},this.invalidate=s=>{const n=r=>s?.filter?.(r)??!0?{...r,invalid:!0,...s?.forcePending||r.status==="error"||r.status==="notFound"?{status:"pending",error:void 0}:void 0}:r;return this.__store.setState(r=>({...r,matches:r.matches.map(n),cachedMatches:r.cachedMatches.map(n),pendingMatches:r.pendingMatches?.map(n)})),this.shouldViewTransition=!1,this.load({sync:s?.sync})},this.getParsedLocationHref=s=>{let n=s.url.href;return this.origin&&s.url.origin===this.origin&&(n=n.replace(this.origin,"")||"/"),n},this.resolveRedirect=s=>{if(!s.options.href){const n=this.buildLocation(s.options),r=this.getParsedLocationHref(n);s.options.href=n.href,s.headers.set("Location",r)}return s.headers.get("Location")||s.headers.set("Location",s.options.href),s},this.clearCache=s=>{const n=s?.filter;n!==void 0?this.__store.setState(r=>({...r,cachedMatches:r.cachedMatches.filter(i=>!n(i))})):this.__store.setState(r=>({...r,cachedMatches:[]}))},this.clearExpiredCache=()=>{const s=n=>{const r=this.looseRoutesById[n.routeId];if(!r.options.loader)return!0;const i=(n.preload?r.options.preloadGcTime??this.options.defaultPreloadGcTime:r.options.gcTime??this.options.defaultGcTime)??300*1e3;return n.status==="error"?!0:Date.now()-n.updatedAt>=i};this.clearCache({filter:s})},this.loadRouteChunk=Ba,this.preloadRoute=async s=>{const n=this.buildLocation(s);let r=this.matchRoutes(n,{throwOnError:!0,preload:!0,dest:s});const i=new Set([...this.state.matches,...this.state.pendingMatches??[]].map(a=>a.id)),o=new Set([...i,...this.state.cachedMatches.map(a=>a.id)]);Is(()=>{r.forEach(a=>{o.has(a.id)||this.__store.setState(c=>({...c,cachedMatches:[...c.cachedMatches,a]}))})});try{return r=await ao({router:this,matches:r,location:n,preload:!0,updateMatch:(a,c)=>{i.has(a)?r=r.map(u=>u.id===a?c(u):u):this.updateMatch(a,c)}}),r}catch(a){if(Ue(a))return a.options.reloadDocument?void 0:await this.preloadRoute({...a.options,_fromLocation:n});$e(a)||console.error(a);return}},this.matchRoute=(s,n)=>{const r={...s,to:s.to?this.resolvePathWithBase(s.from||"",s.to):void 0,params:s.params||{},leaveParams:!0},i=this.buildLocation(r);if(n?.pending&&this.state.status!=="pending")return!1;const a=(n?.pending===void 0?!this.state.isLoading:n.pending)?this.latestLocation:this.state.resolvedLocation||this.state.location,c=Wu(i.pathname,n?.caseSensitive??!1,n?.fuzzy??!1,a.pathname,this.processedTree);return!c||s.params&&!$t(c.params,s.params,{partial:!0})?!1:n?.includeSearch??!0?$t(a.search,i.search,{partial:!0})?c.params:!1:c.params},this.hasNotFoundMatch=()=>this.__store.state.matches.some(s=>s.status==="notFound"||s.globalNotFound),this.update({defaultPreloadDelay:50,defaultPendingMs:1e3,defaultPendingMinMs:500,context:void 0,...t,caseSensitive:t.caseSensitive??!1,notFoundMode:t.notFoundMode??"fuzzy",stringifySearch:t.stringifySearch??df,parseSearch:t.parseSearch??ff}),typeof document<"u"&&(self.__TSR_ROUTER__=this)}isShell(){return!!this.options.isShell}isPrerendering(){return!!this.options.isPrerendering}get state(){return this.__store.state}get looseRoutesById(){return this.routesById}matchRoutesInternal(t,s){const n=this.getMatchedRoutes(t.pathname),{foundRoute:r,routeParams:i}=n;let{matchedRoutes:o}=n,a=!1;(r?r.path!=="/"&&i["**"]:Bt(t.pathname))&&(this.options.notFoundRoute?o=[...o,this.options.notFoundRoute]:a=!0);const c=(()=>{if(a){if(this.options.notFoundMode!=="root")for(let l=o.length-1;l>=0;l--){const d=o[l];if(d.children)return d.id}return Ne}})(),u=[],f=l=>l?.id?l.context??this.options.context??void 0:this.options.context??void 0;return o.forEach((l,d)=>{const h=u[d-1],[g,y,x]=(()=>{const P=h?.search??t.search,H=h?._strictSearch??void 0;try{const te=kr(l.options.validateSearch,{...P})??void 0;return[{...P,...te},{...H,...te},void 0]}catch(te){let Q=te;if(te instanceof Sn||(Q=new Sn(te.message,{cause:te})),s?.throwOnError)throw Q;return[P,{},Q]}})(),b=l.options.loaderDeps?.({search:g})??"",L=b?JSON.stringify(b):"",{interpolatedPath:$,usedParams:C}=sr({path:l.fullPath,params:i,decodeCharMap:this.pathParamsDecodeCharMap}),k=l.id+$+L,_=this.getMatch(k),D=this.state.matches.find(P=>P.routeId===l.id),M=_?._strictParams??C;let B;if(!_){const P=l.options.params?.parse??l.options.parseParams;if(P)try{Object.assign(M,P(M))}catch(H){if($e(H)||Ue(H)?B=H:B=new Rf(H.message,{cause:H}),s?.throwOnError)throw B}}Object.assign(i,M);const W=D?"stay":"enter";let J;if(_)J={..._,cause:W,params:D?je(D.params,i):i,_strictParams:M,search:je(D?D.search:_.search,g),_strictSearch:y};else{const P=l.options.loader||l.options.beforeLoad||l.lazyFn||ja(l)?"pending":"success";J={id:k,ssr:this.isServer?void 0:l.options.ssr,index:d,routeId:l.id,params:D?je(D.params,i):i,_strictParams:M,pathname:$,updatedAt:Date.now(),search:D?je(D.search,g):g,_strictSearch:y,searchError:void 0,status:P,isFetching:!1,error:void 0,paramsError:B,__routeContext:void 0,_nonReactive:{loadPromise:ts()},__beforeLoadContext:void 0,context:{},abortController:new AbortController,fetchCount:0,cause:W,loaderDeps:D?je(D.loaderDeps,b):b,invalid:!1,preload:!1,links:void 0,scripts:void 0,headScripts:void 0,meta:void 0,staticData:l.options.staticData||{},fullPath:l.fullPath}}s?.preload||(J.globalNotFound=c===l.id),J.searchError=x;const de=f(h);J.context={...de,...J.__routeContext,...J.__beforeLoadContext},u.push(J)}),u.forEach((l,d)=>{const h=this.looseRoutesById[l.routeId];if(!this.getMatch(l.id)&&s?._buildLocation!==!0){const y=u[d-1],x=f(y);if(h.options.context){const b={deps:l.loaderDeps,params:l.params,context:x??{},location:t,navigate:L=>this.navigate({...L,_fromLocation:t}),buildLocation:this.buildLocation,cause:l.cause,abortController:l.abortController,preload:!!l.preload,matches:u};l.__routeContext=h.options.context(b)??void 0}l.context={...x,...l.__routeContext,...l.__beforeLoadContext}}}),u}}class Sn extends Error{}class Rf extends Error{}function Cf(e){return{loadedAt:0,isLoading:!1,isTransitioning:!1,status:"idle",resolvedLocation:void 0,location:e,matches:[],pendingMatches:[],cachedMatches:[],statusCode:200}}function kr(e,t){if(e==null)return{};if("~standard"in e){const s=e["~standard"].validate(t);if(s instanceof Promise)throw new Sn("Async validation not supported");if(s.issues)throw new Sn(JSON.stringify(s.issues,void 0,2),{cause:s});return s.value}return"parse"in e?e.parse(t):typeof e=="function"?e(t):{}}function Pf({pathname:e,routesById:t,processedTree:s}){const n={},r=Bt(e);let i;const o=zu(r,s,!0);return o&&(i=o.route,Object.assign(n,o.params)),{matchedRoutes:o?.branch||[t[Ne]],routeParams:n,foundRoute:i}}function kf({search:e,dest:t,destRoutes:s,_includeValidateSearch:n}){const r=s.reduce((a,c)=>{const u=[];if("search"in c.options)c.options.search?.middlewares&&u.push(...c.options.search.middlewares);else if(c.options.preSearchFilters||c.options.postSearchFilters){const f=({search:l,next:d})=>{let h=l;"preSearchFilters"in c.options&&c.options.preSearchFilters&&(h=c.options.preSearchFilters.reduce((y,x)=>x(y),l));const g=d(h);return"postSearchFilters"in c.options&&c.options.postSearchFilters?c.options.postSearchFilters.reduce((y,x)=>x(y),g):g};u.push(f)}if(n&&c.options.validateSearch){const f=({search:l,next:d})=>{const h=d(l);try{return{...h,...kr(c.options.validateSearch,h)??void 0}}catch{return h}};u.push(f)}return a.concat(u)},[])??[],i=({search:a})=>t.search?t.search===!0?a:Gt(t.search,a):{};r.push(i);const o=(a,c)=>{if(a>=r.length)return c;const u=r[a];return u({search:c,next:l=>o(a+1,l)})};return o(0,e)}const Tf="Error preloading route! ☝️";class Ha{constructor(t){if(this.init=s=>{this.originalIndex=s.originalIndex;const n=this.options,r=!n?.path&&!n?.id;this.parentRoute=this.options.getParentRoute?.(),r?this._path=Ne:this.parentRoute||Dt(!1);let i=r?Ne:n?.path;i&&i!=="/"&&(i=Ma(i));const o=n?.id||i;let a=r?Ne:rn([this.parentRoute.id===Ne?"":this.parentRoute.id,o]);i===Ne&&(i="/"),a!==Ne&&(a=rn(["/",a]));const c=a===Ne?"/":rn([this.parentRoute.fullPath,i]);this._path=i,this._id=a,this._fullPath=c,this._to=c},this.addChildren=s=>this._addFileChildren(s),this._addFileChildren=s=>(Array.isArray(s)&&(this.children=s),typeof s=="object"&&s!==null&&(this.children=Object.values(s)),this),this._addFileTypes=()=>this,this.updateLoader=s=>(Object.assign(this.options,s),this),this.update=s=>(Object.assign(this.options,s),this),this.lazy=s=>(this.lazyFn=s,this),this.options=t||{},this.isRoot=!t?.getParentRoute,t?.id&&t?.path)throw new Error("Route cannot have both an 'id' and a 'path' option.")}get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}}class If extends Ha{constructor(t){super(t)}}const Lf=ve({name:"VueErrorBoundary",props:{onError:Function,resetKey:[String,Number]},emits:["catch"],setup(e,{slots:t}){const s=we(null),n=we(null),r=()=>{s.value=null};return Qe(()=>e.resetKey,(i,o)=>{i!==o&&s.value&&r()}),oa(i=>(i instanceof Promise||i&&typeof i.then=="function"||(s.value=i,n.value=r,e.onError&&e.onError(i)),!1)),()=>{if(s.value&&t.fallback){const o=t.fallback({error:s.value,reset:r});return Array.isArray(o)&&o.length===1?o[0]:o}const i=t.default&&t.default();return Array.isArray(i)&&i.length===1?i[0]:i}}}),Mf=ve({name:"CatchBoundary",inheritAttrs:!1,props:["getResetKey","children","errorComponent","onCatch"],setup(e){const t=fe(()=>e.getResetKey());return()=>j(Lf,{resetKey:t.value,onError:e.onCatch},{default:()=>e.children,fallback:({error:s,reset:n})=>e.errorComponent?j(e.errorComponent,{error:s,reset:n}):j(Za,{error:s,reset:n})})}});function fi(e){return j(Mf,e)}const Za=ve({name:"ErrorComponent",props:{error:Object,reset:Function},setup(e){const t=we(!1),s=()=>{t.value=!t.value};return()=>j("div",{style:{padding:".5rem",maxWidth:"100%"}},[j("div",{style:{display:"flex",alignItems:"center",gap:".5rem"}},[j("strong",{style:{fontSize:"1rem"}},"Something went wrong!"),j("button",{style:{appearance:"none",fontSize:".6em",border:"1px solid currentColor",padding:".1rem .2rem",fontWeight:"bold",borderRadius:".25rem"},onClick:s},t.value?"Hide Error":"Show Error")]),j("div",{style:{height:".25rem"}}),t.value?j("div",{},[j("pre",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".3rem",color:"red",overflow:"auto"}},[e.error?.message?j("code",{},e.error.message):null])]):null])}});function Ef(e,t=n=>n,s={}){const n=we(t(e.state)),r=s.equal??Of;return Qe(()=>e,(i,o,a)=>{const c=i.subscribe(()=>{const u=t(i.state);r(ae(n.value),u)||(n.value=u)});a(()=>{c()})},{immediate:!0}),cn(n)}function Of(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const s=Object.keys(e);if(s.length!==Object.keys(t).length)return!1;for(let n=0;n"u"?rr:window.__TSR_ROUTER_CONTEXT__?window.__TSR_ROUTER_CONTEXT__:(window.__TSR_ROUTER_CONTEXT__=rr,rr)}function Af(e){An(Wa(),e)}function Ce(e){const t=wt(Wa(),null);return e?.warn,t}function _e(e){const t=Ce({warn:e?.router===void 0}),s=e?.router||t;return!s||!s.__store?we(void 0):Ef(s.__store,n=>e?.select?e.select(n):n)}const Dn=Symbol("TanStackRouterMatch"),Nf=Symbol("TanStackRouterDummyMatch");function Ff(){return wt(Dn,we(void 0))}function $f(){return wt(Nf,we(void 0))}function st(e){const t=e.from?$f():Ff(),s=we(null),n=_e({select:i=>{const o=i.matches.find(a=>e.from?e.from===a.routeId:a.id===t.value);if(o===void 0){if(i.pendingMatches?.find(c=>e.from?e.from===c.routeId:c.id===t.value)||i.isTransitioning){s.value=null;return}(e.shouldThrow??!0)&&(s.value=new Error(`Invariant failed: Could not find ${e.from?`an active match from "${e.from}"`:"a nearest match!"}`));return}return s.value=null,e.select?e.select(o):o}}),r=fe(()=>{if(s.value)throw s.value;return n.value});if(s.value)throw s.value;return r}function di(e){return st({from:e.from,strict:e.strict,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function hi(e){const{select:t,...s}=e;return st({...s,select:n=>t?t(n.loaderDeps):n.loaderDeps})}function pi(e){return st({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,select:t=>e.select?e.select(t.params):t.params})}function mi(e){return st({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,select:t=>e.select?e.select(t.search):t.search})}function gi(e){const{navigate:t}=Ce();return s=>t({from:e?.from,...s})}let Bf=class extends Ha{constructor(t){super(t),this.useMatch=s=>st({select:s?.select,from:this.id}),this.useRouteContext=s=>st({...s,from:this.id,select:n=>s?.select?s.select(n.context):n.context}),this.useSearch=s=>mi({select:s?.select,from:this.id}),this.useParams=s=>pi({select:s?.select,from:this.id}),this.useLoaderDeps=s=>hi({...s,from:this.id}),this.useLoaderData=s=>di({...s,from:this.id}),this.useNavigate=()=>gi({from:this.fullPath})}};function jf(e){return new Bf(e)}class Df extends If{constructor(t){super(t),this.useMatch=s=>st({select:s?.select,from:this.id}),this.useRouteContext=s=>st({...s,from:this.id,select:n=>s?.select?s.select(n.context):n.context}),this.useSearch=s=>mi({select:s?.select,from:this.id}),this.useParams=s=>pi({select:s?.select,from:this.id}),this.useLoaderDeps=s=>hi({...s,from:this.id}),this.useLoaderData=s=>di({...s,from:this.id}),this.useNavigate=()=>gi({from:this.fullPath})}}function Vf(e){return new Df(e)}function cs(e){return typeof e=="object"?new co(e,{silent:!0}).createRoute(e):new co(e,{silent:!0}).createRoute}class co{constructor(t,s){this.path=t,this.createRoute=n=>{this.silent;const r=jf(n);return r.isRoot=!1,r},this.silent=s?.silent}}class lo{constructor(t){this.useMatch=s=>st({select:s?.select,from:this.options.id}),this.useRouteContext=s=>st({from:this.options.id,select:n=>s?.select?s.select(n.context):n.context}),this.useSearch=s=>mi({select:s?.select,from:this.options.id}),this.useParams=s=>pi({select:s?.select,from:this.options.id}),this.useLoaderDeps=s=>hi({...s,from:this.options.id}),this.useLoaderData=s=>di({...s,from:this.options.id}),this.useNavigate=()=>{const s=Ce();return gi({from:s.routesById[this.options.id].fullPath})},this.options=t}}function mh(e){return typeof e=="object"?new lo(e):t=>new lo({id:e,...t})}function Uf(e){const t=_e({select:n=>`not-found-${n.location.pathname}-${n.status}`});return j(fi,{getResetKey:()=>t.value,onCatch:n=>{if($e(n))e.onCatch&&e.onCatch(n);else throw n},errorComponent:n=>{const r=n.error;if($e(r))return e.fallback?e.fallback(r):j("p",null,"Not Found");throw r},children:e.children})}const Hf=ve({name:"DefaultGlobalNotFound",setup(){return()=>j("p",null,"Not Found")}});function za(e,t,s){return t.options.notFoundComponent?j(t.options.notFoundComponent,s):e.options.defaultNotFoundComponent?j(e.options.defaultNotFoundComponent,s):j(Hf)}const uo=ve({name:"ScriptOnce",props:{children:{type:String,required:!0}},setup(e){const t=Ce();if(t.isServer)return()=>ce("script",{nonce:t.options.ssr?.nonce,class:"$tsr",innerHTML:e.children},null);const s=we(!1);return at(()=>{s.value=!0}),()=>s.value?null:ce("script",{nonce:t.options.ssr?.nonce,class:"$tsr","data-allow-mismatch":!0,innerHTML:""},null)}}),Zf=ve({name:"ScrollRestoration",setup(){const e=Ce(),t=we(!1);return at(()=>{t.value=!0}),()=>{if(t.value||!e.isScrollRestoring||typeof e.options.scrollRestoration=="function"&&!e.options.scrollRestoration({location:e.latestLocation}))return null;const n=(e.options.getScrollRestorationKey||Pr)(e.latestLocation),r=n!==Pr(e.latestLocation)?n:void 0,i={storageKey:xn,shouldScrollRestoration:!0};return r&&(i.key=r),e.isServer?ce(uo,{children:`(${Oa.toString()})(${JSON.stringify(i)})`},null):ce(uo,{children:""},null)}}}),Ka=ve({name:"Match",props:{matchId:{type:String,required:!0}},setup(e){const t=Ce();let s=null;const n=_e({select:f=>{let l=f.matches.find(y=>y.id===e.matchId),d=l?f.matches.findIndex(y=>y.id===e.matchId):-1;if(l?s=l.routeId:s&&(l=f.matches.find(y=>y.routeId===s),d=l?f.matches.findIndex(y=>y.routeId===s):-1),!l)return null;const h=l.routeId,g=d>0?f.matches[d-1]?.routeId:null;return{matchId:l.id,routeId:h,parentRouteId:g,loadedAt:f.loadedAt}}});Dt(n.value,`Could not find routeId for matchId "${e.matchId}". Please file an issue!`);const r=fe(()=>n.value?t.routesById[n.value.routeId]:null),i=fe(()=>r.value?.options?.pendingComponent??t?.options?.defaultPendingComponent),o=fe(()=>r.value?.options?.errorComponent??t?.options?.defaultErrorComponent),a=fe(()=>r.value?.options?.onCatch??t?.options?.defaultOnCatch),c=fe(()=>r.value?.isRoot?r.value?.options?.notFoundComponent??t?.options?.notFoundRoute?.options?.component:r.value?.options?.notFoundComponent),u=we(n.value?.matchId??e.matchId);return Qe([()=>e.matchId,()=>n.value?.matchId],([f,l])=>{u.value=l??f},{immediate:!0}),An(Dn,u),()=>{const f=n.value?.matchId??e.matchId;let l=j(zf,{matchId:f});c.value&&(l=j(Uf,{fallback:g=>{if(!c.value||g.routeId&&g.routeId!==n.value?.routeId||!g.routeId&&r.value&&!r.value.isRoot)throw g;return j(c.value,g)},children:l})),o.value&&(l=fi({getResetKey:()=>n.value?.loadedAt??0,errorComponent:o.value||Za,onCatch:g=>{if($e(g))throw g;a.value?.(g)},children:l})),r.value&&(r.value?.options?.wrapInSuspense??i.value??!1)&&(l=j(si,{fallback:i.value?j(i.value):null},{default:()=>l}));const h=[l,n.value?.parentRouteId===Ne&&t.options.scrollRestoration?j(Fe,null,[j(Wf),j(Zf)]):null].filter(Boolean);return h.length===1?h[0]:j(Fe,null,h)}}}),Wf=ve({name:"OnRendered",setup(){const e=Ce(),t=_e({select:s=>s.resolvedLocation?.state.key});return la(()=>{t.value&&e.emit({type:"onRendered",...jt(e.state)})}),()=>null}}),zf=ve({name:"MatchInner",props:{matchId:{type:String,required:!0}},setup(e){const t=Ce();let s=null;const n=_e({select:a=>{let c=a.matches.find(d=>d.id===e.matchId);if(c)s=c.routeId;else if(s){const d=a.matches.find(h=>h.routeId===s);d&&(c=d)}if(!c)return null;const u=c.routeId,f=t.routesById[u].options.remountDeps??t.options.defaultRemountDeps;let l;if(f){const d=f({routeId:u,loaderDeps:c.loaderDeps,params:c._strictParams,search:c._strictSearch});l=d?JSON.stringify(d):void 0}return{routeId:u,match:{id:c.id,status:c.status,error:c.error},remountKey:l}}}),r=fe(()=>n.value?t.routesById[n.value.routeId]:null),i=fe(()=>n.value?.match),o=fe(()=>n.value?.remountKey);return()=>{if(!n.value||!i.value||!r.value)return null;if(i.value.status==="notFound")return Dt($e(i.value.error)),za(t,r.value,i.value.error);if(i.value.status==="redirected")throw Dt(Ue(i.value.error)),t.getMatch(i.value.id)?._nonReactive.loadPromise;if(i.value.status==="error"){const u=r.value.options.errorComponent??t.options.defaultErrorComponent;if(u)return j(u,{error:i.value.error,reset:()=>{t.invalidate()},info:{componentStack:""}});throw i.value.error}if(i.value.status==="pending"){const u=r.value.options.pendingMinMs??t.options.defaultPendingMinMs,f=t.getMatch(i.value.id);if(u&&f&&!f._nonReactive.minPendingPromise&&!t.isServer){const d=ts();f._nonReactive.minPendingPromise=d,setTimeout(()=>{d.resolve(),f._nonReactive.minPendingPromise=void 0},u)}const l=r.value.options.pendingComponent??t.options.defaultPendingComponent;return l?j(l):null}const a=r.value.options.component??t.options.defaultComponent,c=o.value;return a?j(a,c!==void 0?{key:c}:void 0):j(qa,c!==void 0?{key:c}:void 0)}}}),qa=ve({name:"Outlet",setup(){const e=Ce(),t=wt(Dn),s=fe(()=>t?.value||""),n=_e({select:a=>a.matches.find(c=>c.id===s.value)?.routeId}),r=fe(()=>e.routesById[n.value]),i=_e({select:a=>{const u=a.matches.find(f=>f.id===s.value);return u?u.globalNotFound:!1}}),o=_e({select:a=>{const c=a.matches,u=c.findIndex(l=>l.id===s.value),f=c[u+1];return f?{id:f.id,paramsKey:f.routeId+JSON.stringify(f._strictParams)}:null}});return()=>{if(i.value)return za(e,r.value,void 0);if(!o.value)return null;const a=j(Ka,{matchId:o.value.id,key:o.value.paramsKey});return s.value===Ne?j(si,{fallback:e.options.defaultPendingComponent?j(e.options.defaultPendingComponent):null},{default:()=>a}):a}}});function ir(e){return typeof e?.message!="string"?!1:e.message.startsWith("Failed to fetch dynamically imported module")||e.message.startsWith("error loading dynamically imported module")||e.message.startsWith("Importing a module script failed")}function vi(e,t,s){let n,r=null,i=null,o=!1;const a=()=>(n||(n=e().then(u=>(n=void 0,r=u[t],r)).catch(u=>{if(i=u,n=void 0,ir(i))return null;throw u})),n),c=ve({name:"LazyRouteComponent",setup(u){const f=Bc(r&&hr(r)),l=we(i),d=we(!f.value&&!l.value);if(at(()=>{!f.value&&!l.value&&(d.value=!0,a().then(h=>{f.value=h&&hr(h),d.value=!1}).catch(h=>{l.value=h,d.value=!1}))}),l.value&&ir(l.value)&&!o&&typeof window<"u"&&typeof sessionStorage<"u"){const h=`tanstack_router_reload:${l.value.message}`;if(!sessionStorage.getItem(h))return sessionStorage.setItem(h,"1"),o=!0,window.location.reload(),()=>null}if(l.value&&!ir(l.value))throw l.value;return()=>d.value||!f.value?j("div",null):j(f.value,u)}});return c.preload=a,c}const or=e=>fe((t={current:null,previous:null})=>{const s=e();return t.current!==s&&(t.previous=t.current,t.current=s),t});function Kf(e,t,s={},n={}){const r=typeof IntersectionObserver=="function",i=we(null);return la(o=>{const a=e.value,c=typeof n.disabled=="function"?n.disabled():n.disabled;if(!a||!r||c)return;const u=new IntersectionObserver(([f])=>{t(f)},s);i.value=u,u.observe(a),o(()=>{u.disconnect(),i.value=null})}),i}let ar={router:null,mounted:!1};function qf(){const e=Ce();if(e.isServer)return;const t=_e({select:({isLoading:d})=>d}),s=we(!1),n=_e({select:d=>d.matches.some(h=>h.status==="pending")}),r=or(()=>t.value),i=fe(()=>t.value||s.value||n.value),o=or(()=>i.value),a=fe(()=>t.value||n.value),c=or(()=>a.value);e.startTransition=d=>{s.value=!0;try{e.__store.setState(g=>({...g,isTransitioning:!0}))}catch{}const h=()=>{pr(()=>{try{s.value=!1,e.__store.setState(g=>({...g,isTransitioning:!1}))}catch{}})};d(),h()};const u=e.__tsrOriginalStartViewTransition??e.startViewTransition;e.__tsrOriginalStartViewTransition=u,e.startViewTransition=d=>u?.(async()=>{await d(),await pr()});let f;at(()=>{f=e.history.subscribe(e.load);const d=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});Bt(e.latestLocation.href)!==Bt(d.href)&&e.commitLocation({...d,replace:!0})});const l=we(!1);at(()=>{l.value=!0}),Jr(()=>{l.value=!1,f&&f()}),at(()=>{if(typeof window<"u"&&e.ssr||ar.router===e&&ar.mounted)return;ar={router:e,mounted:!0},(async()=>{try{await e.load()}catch(h){console.error(h)}})()}),Qe(()=>t.value,d=>{if(l.value)try{r.value.previous&&!d&&e.emit({type:"onLoad",...jt(e.state)})}catch{}}),Qe(a,d=>{if(l.value)try{c.value.previous&&!d&&e.emit({type:"onBeforeRouteMount",...jt(e.state)})}catch{}}),Qe(i,d=>{if(l.value)try{if(o.value.previous&&!d){const h=jt(e.state);e.emit({type:"onResolved",...h}),e.__store.setState(g=>({...g,status:"idle",resolvedLocation:g.location})),h.hrefChanged&&cf(e)}}catch{}})}const fo=ve({name:"MatchesContent",setup(){return qf(),()=>j(Yf)}}),Gf=ve({name:"Matches",setup(){const e=Ce();return()=>{const t=e?.options?.defaultPendingComponent?j(e.options.defaultPendingComponent):null,s=e?.isServer||typeof document<"u"&&e?.ssr?j(fo):j(si,{fallback:t},{default:()=>j(fo)});return e?.options?.InnerWrap?j(e.options.InnerWrap,null,{default:()=>s}):s}}}),Jf=e=>j("div",{class:"error"},[j("h1",null,"Error"),j("p",null,e.error.message||String(e.error)),j("button",{onClick:e.reset},"Try Again")]),Yf=ve({name:"MatchesInner",setup(){const e=Ce(),t=_e({select:r=>r.matches[0]?.id}),s=_e({select:r=>r.loadedAt}),n=fe(()=>t.value);return An(Dn,n),()=>{const r=t.value?j(Ka,{matchId:t.value}):j("div");return e.options.disableGlobalCatchBoundary?r:j(fi,{getResetKey:()=>s.value,errorComponent:Jf,onCatch:i=>{i.message||i.toString()},children:r})}}});function Xf(e){return _e({select:t=>{const s=t?.matches||[];return e?.select?e.select(s):s}})}function Qf(e){const t=Ce(),s=we(!1);let n=!1;if(!t)return console.warn("useRouter must be used inside a component!"),{};const r=fe(()=>{try{return new URL(`${e.to}`),"external"}catch{return"internal"}}),i=_e({select:P=>P.location.searchStr}),o=Xf({select:P=>e.from??P[P.length-1]?.fullPath}),a=fe(()=>({...e,from:o.value})),c=fe(()=>(i.value,t.buildLocation(a.value))),u=fe(()=>a.value.reloadDocument?!1:e.preload??t.options.defaultPreload),f=fe(()=>e.preloadDelay??t.options.defaultPreloadDelay??0),l=_e({select:P=>{const H=e.activeOptions;if(H?.exact){if(!Qu(P.location.pathname,c.value.pathname,t.basepath))return!1}else{const te=bn(P.location.pathname,t.basepath).split("/");if(!bn(c.value?.pathname,t.basepath)?.split("/")?.every((oe,nt)=>oe===te[nt]))return!1}return(H?.includeSearch??!0)&&!$t(P.location.search,c.value.search,{partial:!H?.exact,ignoreUndefined:!H?.explicitUndefined})?!1:H?.includeHash?P.location.hash===c.value.hash:!0}}),d=()=>t.preloadRoute(a.value).catch(P=>{console.warn(P),console.warn(Tf)}),h=P=>{P?.isIntersecting&&d()},g=we(null);Kf(g,h,{rootMargin:"100px"},{disabled:()=>!!e.disabled||u.value!=="viewport"}),_c(()=>{n||!e.disabled&&u.value==="render"&&(d(),n=!0)});const y=()=>{const P={};for(const H in e)["activeProps","inactiveProps","activeOptions","to","preload","preloadDelay","hashScrollIntoView","replace","startTransition","resetScroll","viewTransition","children","target","disabled","style","class","onClick","onFocus","onMouseEnter","onMouseLeave","onMouseOver","onMouseOut","onTouchStart","ignoreBlocker","params","search","hash","state","mask","reloadDocument","_asChild","from","additionalProps"].includes(H)||(P[H]=e[H]);return P};if(r.value==="external"){const P={...y(),ref:g,href:e.to,target:e.target,disabled:e.disabled,style:e.style,class:e.class,onClick:e.onClick,onFocus:e.onFocus,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,onMouseOver:e.onMouseOver,onMouseOut:e.onMouseOut,onTouchStart:e.onTouchStart};return Object.keys(P).forEach(H=>{P[H]===void 0&&delete P[H]}),P}const x=P=>{const H=P.currentTarget?.getAttribute("target"),te=e.target!==void 0?e.target:H;if(!e.disabled&&!td(P)&&!P.defaultPrevented&&(!te||te==="_self")&&P.button===0){if(a.value.reloadDocument)return;P.preventDefault(),s.value=!0;const Q=t.subscribe("onResolved",()=>{Q(),s.value=!1});t.navigate({...a.value,replace:e.replace,resetScroll:e.resetScroll,hashScrollIntoView:e.hashScrollIntoView,startTransition:e.startTransition,viewTransition:e.viewTransition,ignoreBlocker:e.ignoreBlocker})}},b=P=>{e.disabled||u.value&&d()},L=P=>{e.disabled||u.value&&d()},$=P=>{if(e.disabled)return;const H=P.currentTarget||P.target||{};if(u.value){if(H.preloadTimeout)return;H.preloadTimeout=setTimeout(()=>{H.preloadTimeout=null,d()},f.value)}},C=P=>{if(e.disabled)return;const H=P.currentTarget||P.target||{};H.preloadTimeout&&(clearTimeout(H.preloadTimeout),H.preloadTimeout=null)};function k(P){return H=>{for(const te of P)te&&te(H)}}const _=fe(()=>{const P=e.activeProps||(()=>({class:"active"}));return(l.value?typeof P=="function"?P():P:{})||{class:void 0,style:void 0}}),D=fe(()=>{const P=e.inactiveProps||(()=>({}));return(l.value?{}:typeof P=="function"?P():P)||{class:void 0,style:void 0}}),M=fe(()=>{const P=[e.class,_.value?.class,D.value?.class].filter(Boolean);return P.length?P.join(" "):void 0}),B=fe(()=>{const P={};return e.style&&Object.assign(P,e.style),_.value?.style&&Object.assign(P,_.value.style),D.value?.style&&Object.assign(P,D.value.style),Object.keys(P).length>0?P:void 0}),W=fe(()=>{if(e.disabled)return;const P=c.value,H=P?.maskedLocation;let te;return H?te=H.url.href:te=P?.url.href,t.origin&&te?.startsWith(t.origin)&&(te=t.history.createHref(te.replace(t.origin,""))),te}),J={onClick:k([e.onClick,x]),onFocus:k([e.onFocus,b]),onMouseenter:k([e.onMouseEnter,$]),onMouseover:k([e.onMouseOver,$]),onMouseleave:k([e.onMouseLeave,C]),onMouseout:k([e.onMouseOut,C]),onTouchstart:k([e.onTouchStart,L])};return fe(()=>{const P={...y(),href:W.value,ref:g,...J,disabled:!!e.disabled,target:e.target};B.value&&(P.style=B.value),M.value&&(P.class=M.value),e.disabled&&(P.role="link",P["aria-disabled"]=!0),l.value&&(P["data-status"]="active",P["aria-current"]="page"),s.value&&(P["data-transitioning"]="transitioning");const H=_.value,te=D.value;for(const Q of Object.keys(H))Q!=="class"&&Q!=="style"&&(P[Q]=H[Q]);for(const Q of Object.keys(te))Q!=="class"&&Q!=="style"&&(P[Q]=te[Q]);return P})}const ed=ve({name:"Link",inheritAttrs:!1,props:["_asChild","to","preload","preloadDelay","activeProps","inactiveProps","activeOptions","from","search","params","hash","state","mask","reloadDocument","disabled","additionalProps","viewTransition","resetScroll","startTransition","hashScrollIntoView","replace","ignoreBlocker","target"],setup(e,{attrs:t,slots:s}){const n={...e,...t},r=Qf(n);return()=>{const i=e._asChild||"a",o=r.value,a=o["data-status"]==="active",c=o["data-transitioning"]==="transitioning",u=s.default?s.default({isActive:a,isTransitioning:c}):[];if(i==="svg"){const f={...o};return delete f.class,j("svg",{},[j("a",f,u)])}return typeof i!="string"?j(i,{...o,children:u},u):j(i,o,u)}}}),ho=ed;function td(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}const ms=e=>e,sd=e=>new nd(e);class nd extends Sf{constructor(t){super(t)}}const rd=ve({name:"RouterContextProvider",props:{router:{type:Object,required:!0}},setup(e,{attrs:t,slots:s}){const n=e.router,r=t;return n.update({...n.options,...r,context:{...n.options.context,...r.context||{}}}),Af(n),()=>{const i=s.default?.();if(n.options.Wrap){const o=n.options.Wrap;return j(o,null,()=>i)}return Array.isArray(i)&&i.length===1?i[0]:i}}}),id=ve({name:"RouterProvider",props:{router:{type:Object,required:!0}},setup(e,{attrs:t}){const s=t;return()=>j(rd,{router:e.router,...s},{default:()=>j(Gf)})}}),od=ve({name:"Title",props:{children:{type:String,default:""}},setup(e){return Ce().isServer||(at(()=>{e.children&&(document.title=e.children)}),Qe(()=>e.children,s=>{s&&(document.title=s)})),()=>j("title",{},e.children)}}),ad=ve({name:"Script",props:{attrs:{type:Object,default:()=>({})},children:{type:String,default:void 0}},setup(e){const t=Ce();return t.isServer||at(()=>{const s=e.attrs,n=e.children;if(s?.src){const r=(()=>{try{const a=document.baseURI||window.location.href;return new URL(s.src,a).href}catch{return s.src}})();if(Array.from(document.querySelectorAll("script[src]")).find(a=>a.src===r))return;const o=document.createElement("script");for(const[a,c]of Object.entries(s))c!==void 0&&c!==!1&&o.setAttribute(a,typeof c=="boolean"?"":String(c));document.head.appendChild(o)}else if(typeof n=="string"){const r=typeof s?.type=="string"?s.type:"text/javascript",i=typeof s?.nonce=="string"?s.nonce:void 0;if(Array.from(document.querySelectorAll("script:not([src])")).find(c=>{if(!(c instanceof HTMLScriptElement))return!1;const u=c.getAttribute("type")??"text/javascript",f=c.getAttribute("nonce")??void 0;return c.textContent===n&&u===r&&f===i}))return;const a=document.createElement("script");if(a.textContent=n,s)for(const[c,u]of Object.entries(s))u!==void 0&&u!==!1&&a.setAttribute(c,typeof u=="boolean"?"":String(u));document.head.appendChild(a)}}),()=>{if(!t.isServer){const{src:s,...n}=e.attrs||{};return j("script",{...n,"data-allow-mismatch":!0,innerHTML:""})}return e.attrs?.src&&typeof e.attrs.src=="string"?j("script",e.attrs):typeof e.children=="string"?j("script",{...e.attrs,innerHTML:e.children}):null}}});function cd({tag:e,attrs:t,children:s}){switch(e){case"title":return j(od,{children:s});case"meta":return ce("meta",t,null);case"link":return ce("link",t,null);case"style":return ce("style",ri(t,{innerHTML:s}),null);case"script":return j(ad,{attrs:t,children:s});default:return null}}const ld=()=>{const e=Ce(),t=_e({select:o=>o.matches.map(a=>a.meta).filter(Boolean)}),s=fe(()=>{const o=[],a={};let c;return[...t.value].reverse().forEach(u=>{[...u].reverse().forEach(f=>{if(f)if(f.title)c||(c={tag:"title",children:f.title});else{const l=f.name??f.property;if(l){if(a[l])return;a[l]=!0}o.push({tag:"meta",attrs:{...f}})}})}),c&&o.push(c),o.reverse(),o}),n=_e({select:o=>o.matches.map(a=>a.links).filter(Boolean).flat(1).map(a=>({tag:"link",attrs:{...a}}))}),r=_e({select:o=>{const a=[];return o.matches.map(c=>e.looseRoutesById[c.routeId]).forEach(c=>e.ssr?.manifest?.routes[c.id]?.preloads?.filter(Boolean).forEach(u=>{a.push({tag:"link",attrs:{rel:"modulepreload",href:u}})})),a}}),i=_e({select:o=>o.matches.map(a=>a.headScripts).flat(1).filter(Boolean).map(({children:a,...c})=>({tag:"script",attrs:{...c},children:a}))});return()=>fd([...s.value,...r.value,...n.value,...i.value],o=>JSON.stringify(o))},ud=ve({name:"HeadContent",setup(){const e=ld();return()=>e().map(t=>j(cd,{...t,key:`tsr-meta-${JSON.stringify(t)}`}))}});function fd(e,t){const s=new Set;return e.filter(n=>{const r=t(n);return s.has(r)?!1:(s.add(r),!0)})}const dd="modulepreload",hd=function(e){return"/"+e},po={},ls=function(t,s,n){let r=Promise.resolve();if(s&&s.length>0){let c=function(u){return Promise.all(u.map(f=>Promise.resolve(f).then(l=>({status:"fulfilled",value:l}),l=>({status:"rejected",reason:l}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=o?.nonce||o?.getAttribute("nonce");r=c(s.map(u=>{if(u=hd(u),u in po)return;po[u]=!0;const f=u.endsWith(".css"),l=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${l}`))return;const d=document.createElement("link");if(d.rel=f?"stylesheet":dd,f||(d.as="script"),d.crossOrigin="",d.href=u,a&&d.setAttribute("nonce",a),document.head.appendChild(d),f)return new Promise((h,g)=>{d.addEventListener("load",h),d.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return r.then(o=>{for(const a of o||[])a.status==="rejected"&&i(a.reason);return t().catch(i)})},pd=ve({name:"NullTanStackRouterDevtools",setup(){return()=>null}}),md=pd,Wt=Vf({component:gd});function gd(){return ce(Fe,null,[ce(ud,null,null),ce(mo,{type:"header"},null),ce("hr",null,null),ce(qa,null,null),ce("hr",null,null),ce(mo,{type:"footer"},null),ce(md,{position:"bottom-right"},null)])}function mo({type:e}){const t=e==="header"?"header":"footer",s=e==="header"?"Head":"Foot";return ce(t,{class:"p-2 flex gap-2 text-lg"},{default:()=>[ce(ho,{to:"/",activeProps:{class:"font-bold"},activeOptions:{exact:!0}},{default:()=>[s,xr("-/")]})," ",[ms({to:"/normal-page"}),ms({to:"/lazy-page"}),ms({to:"/virtual-page"}),ms({to:"/lazy-with-loader-page"}),ms({to:"/page-with-search",search:{where:e}})].map(n=>ce(ho,ri(n,{activeProps:{class:"font-bold"}}),{default:()=>[s,xr("-"),n.to]}))]})}const vd=()=>ls(()=>import("./index-rPfEOKs3.js"),[]),yd=cs("/")({component:vi(vd,"component")});var re;(function(e){e.assertEqual=r=>{};function t(r){}e.assertIs=t;function s(r){throw new Error}e.assertNever=s,e.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},e.getValidEnumValues=r=>{const i=e.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return e.objectValues(o)},e.objectValues=r=>e.objectKeys(r).map(function(i){return r[i]}),e.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},e.find=(r,i)=>{for(const o of r)if(i(o))return o},e.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function n(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}e.joinValues=n,e.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(re||(re={}));var go;(function(e){e.mergeShapes=(t,s)=>({...t,...s})})(go||(go={}));const V=re.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),gt=e=>{switch(typeof e){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(e)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(e)?V.array:e===null?V.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?V.promise:typeof Map<"u"&&e instanceof Map?V.map:typeof Set<"u"&&e instanceof Set?V.set:typeof Date<"u"&&e instanceof Date?V.date:V.object;default:return V.unknown}},I=re.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ft extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const s=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,s):this.__proto__=s,this.name="ZodError",this.issues=t}format(t){const s=t||function(i){return i.message},n={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)n._errors.push(s(o));else{let a=n,c=0;for(;cs.message){const s={},n=[];for(const r of this.issues)r.path.length>0?(s[r.path[0]]=s[r.path[0]]||[],s[r.path[0]].push(t(r))):n.push(t(r));return{formErrors:n,fieldErrors:s}}get formErrors(){return this.flatten()}}ft.create=e=>new ft(e);const Tr=(e,t)=>{let s;switch(e.code){case I.invalid_type:e.received===V.undefined?s="Required":s=`Expected ${e.expected}, received ${e.received}`;break;case I.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,re.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:s=`Unrecognized key(s) in object: ${re.joinValues(e.keys,", ")}`;break;case I.invalid_union:s="Invalid input";break;case I.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${re.joinValues(e.options)}`;break;case I.invalid_enum_value:s=`Invalid enum value. Expected ${re.joinValues(e.options)}, received '${e.received}'`;break;case I.invalid_arguments:s="Invalid function arguments";break;case I.invalid_return_type:s="Invalid function return type";break;case I.invalid_date:s="Invalid date";break;case I.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:re.assertNever(e.validation):e.validation!=="regex"?s=`Invalid ${e.validation}`:s="Invalid";break;case I.too_small:e.type==="array"?s=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?s=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?s=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?s=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:s="Invalid input";break;case I.too_big:e.type==="array"?s=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?s=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?s=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?s=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?s=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:s="Invalid input";break;case I.custom:s="Invalid input";break;case I.invalid_intersection_types:s="Intersection results could not be merged";break;case I.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case I.not_finite:s="Number must be finite";break;default:s=t.defaultError,re.assertNever(e)}return{message:s}};let _d=Tr;function bd(){return _d}const xd=e=>{const{data:t,path:s,errorMaps:n,issueData:r}=e,i=[...s,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let a="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)a=u(o,{data:t,defaultError:a}).message;return{...r,path:i,message:a}};function N(e,t){const s=bd(),n=xd({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===Tr?void 0:Tr].filter(r=>!!r)});e.common.issues.push(n)}class Ae{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,s){const n=[];for(const r of s){if(r.status==="aborted")return q;r.status==="dirty"&&t.dirty(),n.push(r.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,s){const n=[];for(const r of s){const i=await r.key,o=await r.value;n.push({key:i,value:o})}return Ae.mergeObjectSync(t,n)}static mergeObjectSync(t,s){const n={};for(const r of s){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return q;i.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(n[i.value]=o.value)}return{status:t.value,value:n}}}const q=Object.freeze({status:"aborted"}),ys=e=>({status:"dirty",value:e}),Be=e=>({status:"valid",value:e}),vo=e=>e.status==="aborted",yo=e=>e.status==="dirty",ns=e=>e.status==="valid",Rn=e=>typeof Promise<"u"&&e instanceof Promise;var U;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(U||(U={}));class It{constructor(t,s,n,r){this._cachedPath=[],this.parent=t,this.data=s,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const _o=(e,t)=>{if(ns(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const s=new ft(e.common.issues);return this._error=s,this._error}}};function ee(e){if(!e)return{};const{errorMap:t,invalid_type_error:s,required_error:n,description:r}=e;if(t&&(s||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:r}:{errorMap:(o,a)=>{const{message:c}=e;return o.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:c??s??a.defaultError}},description:r}}class ne{get description(){return this._def.description}_getType(t){return gt(t.data)}_getOrReturnCtx(t,s){return s||{common:t.parent.common,data:t.data,parsedType:gt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Ae,ctx:{common:t.parent.common,data:t.data,parsedType:gt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const s=this._parse(t);if(Rn(s))throw new Error("Synchronous parse encountered promise.");return s}_parseAsync(t){const s=this._parse(t);return Promise.resolve(s)}parse(t,s){const n=this.safeParse(t,s);if(n.success)return n.data;throw n.error}safeParse(t,s){const n={common:{issues:[],async:s?.async??!1,contextualErrorMap:s?.errorMap},path:s?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:gt(t)},r=this._parseSync({data:t,path:n.path,parent:n});return _o(n,r)}"~validate"(t){const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:gt(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:s});return ns(n)?{value:n.value}:{issues:s.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(n=>ns(n)?{value:n.value}:{issues:s.common.issues})}async parseAsync(t,s){const n=await this.safeParseAsync(t,s);if(n.success)return n.data;throw n.error}async safeParseAsync(t,s){const n={common:{issues:[],contextualErrorMap:s?.errorMap,async:!0},path:s?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:gt(t)},r=this._parse({data:t,path:n.path,parent:n}),i=await(Rn(r)?r:Promise.resolve(r));return _o(n,i)}refine(t,s){const n=r=>typeof s=="string"||typeof s>"u"?{message:s}:typeof s=="function"?s(r):s;return this._refinement((r,i)=>{const o=t(r),a=()=>i.addIssue({code:I.custom,...n(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(t,s){return this._refinement((n,r)=>t(n)?!0:(r.addIssue(typeof s=="function"?s(n,r):s),!1))}_refinement(t){return new is({schema:this,typeName:G.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s=>this["~validate"](s)}}optional(){return Ct.create(this,this._def)}nullable(){return os.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return et.create(this)}promise(){return Tn.create(this,this._def)}or(t){return Pn.create([this,t],this._def)}and(t){return kn.create(this,t,this._def)}transform(t){return new is({...ee(this._def),schema:this,typeName:G.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const s=typeof t=="function"?t:()=>t;return new Lr({...ee(this._def),innerType:this,defaultValue:s,typeName:G.ZodDefault})}brand(){return new Zd({typeName:G.ZodBranded,type:this,...ee(this._def)})}catch(t){const s=typeof t=="function"?t:()=>t;return new Mr({...ee(this._def),innerType:this,catchValue:s,typeName:G.ZodCatch})}describe(t){const s=this.constructor;return new s({...this._def,description:t})}pipe(t){return yi.create(this,t)}readonly(){return Er.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const wd=/^c[^\s-]{8,}$/i,Sd=/^[0-9a-z]+$/,Rd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Cd=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Pd=/^[a-z0-9_-]{21}$/i,kd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Td=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Id=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ld="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let cr;const Md=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ed=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Od=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ad=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Nd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Fd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ga="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",$d=new RegExp(`^${Ga}$`);function Ja(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const s=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${s}`}function Bd(e){return new RegExp(`^${Ja(e)}$`)}function jd(e){let t=`${Ga}T${Ja(e)}`;const s=[];return s.push(e.local?"Z?":"Z"),e.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,new RegExp(`^${t}$`)}function Dd(e,t){return!!((t==="v4"||!t)&&Md.test(e)||(t==="v6"||!t)&&Od.test(e))}function Vd(e,t){if(!kd.test(e))return!1;try{const[s]=e.split("."),n=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),r=JSON.parse(atob(n));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||t&&r.alg!==t)}catch{return!1}}function Ud(e,t){return!!((t==="v4"||!t)&&Ed.test(e)||(t==="v6"||!t)&&Ad.test(e))}class bt extends ne{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==V.string){const i=this._getOrReturnCtx(t);return N(i,{code:I.invalid_type,expected:V.string,received:i.parsedType}),q}const n=new Ae;let r;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(r=this._getOrReturnCtx(t,r),N(r,{code:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const o=t.data.length>i.value,a=t.data.lengtht.test(r),{validation:s,code:I.invalid_string,...U.errToObj(n)})}_addCheck(t){return new bt({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...U.errToObj(t)})}url(t){return this._addCheck({kind:"url",...U.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...U.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...U.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...U.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...U.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...U.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...U.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...U.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...U.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...U.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...U.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...U.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...U.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...U.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...U.errToObj(t)})}regex(t,s){return this._addCheck({kind:"regex",regex:t,...U.errToObj(s)})}includes(t,s){return this._addCheck({kind:"includes",value:t,position:s?.position,...U.errToObj(s?.message)})}startsWith(t,s){return this._addCheck({kind:"startsWith",value:t,...U.errToObj(s)})}endsWith(t,s){return this._addCheck({kind:"endsWith",value:t,...U.errToObj(s)})}min(t,s){return this._addCheck({kind:"min",value:t,...U.errToObj(s)})}max(t,s){return this._addCheck({kind:"max",value:t,...U.errToObj(s)})}length(t,s){return this._addCheck({kind:"length",value:t,...U.errToObj(s)})}nonempty(t){return this.min(1,U.errToObj(t))}trim(){return new bt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new bt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new bt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxLength(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.valuenew bt({checks:[],typeName:G.ZodString,coerce:e?.coerce??!1,...ee(e)});function Hd(e,t){const s=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,r=s>n?s:n,i=Number.parseInt(e.toFixed(r).replace(".","")),o=Number.parseInt(t.toFixed(r).replace(".",""));return i%o/10**r}class Vs extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==V.number){const i=this._getOrReturnCtx(t);return N(i,{code:I.invalid_type,expected:V.number,received:i.parsedType}),q}let n;const r=new Ae;for(const i of this._def.checks)i.kind==="int"?re.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),N(n,{code:I.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),N(n,{code:I.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Hd(t.data,i.value)!==0&&(n=this._getOrReturnCtx(t,n),N(n,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),N(n,{code:I.not_finite,message:i.message}),r.dirty()):re.assertNever(i);return{status:r.value,value:t.data}}gte(t,s){return this.setLimit("min",t,!0,U.toString(s))}gt(t,s){return this.setLimit("min",t,!1,U.toString(s))}lte(t,s){return this.setLimit("max",t,!0,U.toString(s))}lt(t,s){return this.setLimit("max",t,!1,U.toString(s))}setLimit(t,s,n,r){return new Vs({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:n,message:U.toString(r)}]})}_addCheck(t){return new Vs({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:U.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString(t)})}multipleOf(t,s){return this._addCheck({kind:"multipleOf",value:t,message:U.toString(s)})}finite(t){return this._addCheck({kind:"finite",message:U.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.toString(t)})}get minValue(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxValue(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.valuet.kind==="int"||t.kind==="multipleOf"&&re.isInteger(t.value))}get isFinite(){let t=null,s=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(s===null||n.value>s)&&(s=n.value):n.kind==="max"&&(t===null||n.valuenew Vs({checks:[],typeName:G.ZodNumber,coerce:e?.coerce||!1,...ee(e)});class Us extends ne{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==V.bigint)return this._getInvalidInput(t);let n;const r=new Ae;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),N(n,{code:I.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),N(n,{code:I.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):re.assertNever(i);return{status:r.value,value:t.data}}_getInvalidInput(t){const s=this._getOrReturnCtx(t);return N(s,{code:I.invalid_type,expected:V.bigint,received:s.parsedType}),q}gte(t,s){return this.setLimit("min",t,!0,U.toString(s))}gt(t,s){return this.setLimit("min",t,!1,U.toString(s))}lte(t,s){return this.setLimit("max",t,!0,U.toString(s))}lt(t,s){return this.setLimit("max",t,!1,U.toString(s))}setLimit(t,s,n,r){return new Us({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:n,message:U.toString(r)}]})}_addCheck(t){return new Us({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString(t)})}multipleOf(t,s){return this._addCheck({kind:"multipleOf",value:t,message:U.toString(s)})}get minValue(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t}get maxValue(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.valuenew Us({checks:[],typeName:G.ZodBigInt,coerce:e?.coerce??!1,...ee(e)});class bo extends ne{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==V.boolean){const n=this._getOrReturnCtx(t);return N(n,{code:I.invalid_type,expected:V.boolean,received:n.parsedType}),q}return Be(t.data)}}bo.create=e=>new bo({typeName:G.ZodBoolean,coerce:e?.coerce||!1,...ee(e)});class Cn extends ne{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==V.date){const i=this._getOrReturnCtx(t);return N(i,{code:I.invalid_type,expected:V.date,received:i.parsedType}),q}if(Number.isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return N(i,{code:I.invalid_date}),q}const n=new Ae;let r;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(r=this._getOrReturnCtx(t,r),N(r,{code:I.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):re.assertNever(i);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Cn({...this._def,checks:[...this._def.checks,t]})}min(t,s){return this._addCheck({kind:"min",value:t.getTime(),message:U.toString(s)})}max(t,s){return this._addCheck({kind:"max",value:t.getTime(),message:U.toString(s)})}get minDate(){let t=null;for(const s of this._def.checks)s.kind==="min"&&(t===null||s.value>t)&&(t=s.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const s of this._def.checks)s.kind==="max"&&(t===null||s.valuenew Cn({checks:[],coerce:e?.coerce||!1,typeName:G.ZodDate,...ee(e)});class xo extends ne{_parse(t){if(this._getType(t)!==V.symbol){const n=this._getOrReturnCtx(t);return N(n,{code:I.invalid_type,expected:V.symbol,received:n.parsedType}),q}return Be(t.data)}}xo.create=e=>new xo({typeName:G.ZodSymbol,...ee(e)});class wo extends ne{_parse(t){if(this._getType(t)!==V.undefined){const n=this._getOrReturnCtx(t);return N(n,{code:I.invalid_type,expected:V.undefined,received:n.parsedType}),q}return Be(t.data)}}wo.create=e=>new wo({typeName:G.ZodUndefined,...ee(e)});class So extends ne{_parse(t){if(this._getType(t)!==V.null){const n=this._getOrReturnCtx(t);return N(n,{code:I.invalid_type,expected:V.null,received:n.parsedType}),q}return Be(t.data)}}So.create=e=>new So({typeName:G.ZodNull,...ee(e)});class Ro extends ne{constructor(){super(...arguments),this._any=!0}_parse(t){return Be(t.data)}}Ro.create=e=>new Ro({typeName:G.ZodAny,...ee(e)});class Co extends ne{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Be(t.data)}}Co.create=e=>new Co({typeName:G.ZodUnknown,...ee(e)});class Lt extends ne{_parse(t){const s=this._getOrReturnCtx(t);return N(s,{code:I.invalid_type,expected:V.never,received:s.parsedType}),q}}Lt.create=e=>new Lt({typeName:G.ZodNever,...ee(e)});class Po extends ne{_parse(t){if(this._getType(t)!==V.undefined){const n=this._getOrReturnCtx(t);return N(n,{code:I.invalid_type,expected:V.void,received:n.parsedType}),q}return Be(t.data)}}Po.create=e=>new Po({typeName:G.ZodVoid,...ee(e)});class et extends ne{_parse(t){const{ctx:s,status:n}=this._processInputParams(t),r=this._def;if(s.parsedType!==V.array)return N(s,{code:I.invalid_type,expected:V.array,received:s.parsedType}),q;if(r.exactLength!==null){const o=s.data.length>r.exactLength.value,a=s.data.lengthr.maxLength.value&&(N(s,{code:I.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),s.common.async)return Promise.all([...s.data].map((o,a)=>r.type._parseAsync(new It(s,o,s.path,a)))).then(o=>Ae.mergeArray(n,o));const i=[...s.data].map((o,a)=>r.type._parseSync(new It(s,o,s.path,a)));return Ae.mergeArray(n,i)}get element(){return this._def.type}min(t,s){return new et({...this._def,minLength:{value:t,message:U.toString(s)}})}max(t,s){return new et({...this._def,maxLength:{value:t,message:U.toString(s)}})}length(t,s){return new et({...this._def,exactLength:{value:t,message:U.toString(s)}})}nonempty(t){return this.min(1,t)}}et.create=(e,t)=>new et({type:e,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...ee(t)});function qt(e){if(e instanceof ye){const t={};for(const s in e.shape){const n=e.shape[s];t[s]=Ct.create(qt(n))}return new ye({...e._def,shape:()=>t})}else return e instanceof et?new et({...e._def,type:qt(e.element)}):e instanceof Ct?Ct.create(qt(e.unwrap())):e instanceof os?os.create(qt(e.unwrap())):e instanceof Ht?Ht.create(e.items.map(t=>qt(t))):e}class ye extends ne{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),s=re.objectKeys(t);return this._cached={shape:t,keys:s},this._cached}_parse(t){if(this._getType(t)!==V.object){const u=this._getOrReturnCtx(t);return N(u,{code:I.invalid_type,expected:V.object,received:u.parsedType}),q}const{status:n,ctx:r}=this._processInputParams(t),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Lt&&this._def.unknownKeys==="strip"))for(const u in r.data)o.includes(u)||a.push(u);const c=[];for(const u of o){const f=i[u],l=r.data[u];c.push({key:{status:"valid",value:u},value:f._parse(new It(r,l,r.path,u)),alwaysSet:u in r.data})}if(this._def.catchall instanceof Lt){const u=this._def.unknownKeys;if(u==="passthrough")for(const f of a)c.push({key:{status:"valid",value:f},value:{status:"valid",value:r.data[f]}});else if(u==="strict")a.length>0&&(N(r,{code:I.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const f of a){const l=r.data[f];c.push({key:{status:"valid",value:f},value:u._parse(new It(r,l,r.path,f)),alwaysSet:f in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const u=[];for(const f of c){const l=await f.key,d=await f.value;u.push({key:l,value:d,alwaysSet:f.alwaysSet})}return u}).then(u=>Ae.mergeObjectSync(n,u)):Ae.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return U.errToObj,new ye({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(s,n)=>{const r=this._def.errorMap?.(s,n).message??n.defaultError;return s.code==="unrecognized_keys"?{message:U.errToObj(t).message??r}:{message:r}}}:{}})}strip(){return new ye({...this._def,unknownKeys:"strip"})}passthrough(){return new ye({...this._def,unknownKeys:"passthrough"})}extend(t){return new ye({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new ye({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:G.ZodObject})}setKey(t,s){return this.augment({[t]:s})}catchall(t){return new ye({...this._def,catchall:t})}pick(t){const s={};for(const n of re.objectKeys(t))t[n]&&this.shape[n]&&(s[n]=this.shape[n]);return new ye({...this._def,shape:()=>s})}omit(t){const s={};for(const n of re.objectKeys(this.shape))t[n]||(s[n]=this.shape[n]);return new ye({...this._def,shape:()=>s})}deepPartial(){return qt(this)}partial(t){const s={};for(const n of re.objectKeys(this.shape)){const r=this.shape[n];t&&!t[n]?s[n]=r:s[n]=r.optional()}return new ye({...this._def,shape:()=>s})}required(t){const s={};for(const n of re.objectKeys(this.shape))if(t&&!t[n])s[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Ct;)i=i._def.innerType;s[n]=i}return new ye({...this._def,shape:()=>s})}keyof(){return Ya(re.objectKeys(this.shape))}}ye.create=(e,t)=>new ye({shape:()=>e,unknownKeys:"strip",catchall:Lt.create(),typeName:G.ZodObject,...ee(t)});ye.strictCreate=(e,t)=>new ye({shape:()=>e,unknownKeys:"strict",catchall:Lt.create(),typeName:G.ZodObject,...ee(t)});ye.lazycreate=(e,t)=>new ye({shape:e,unknownKeys:"strip",catchall:Lt.create(),typeName:G.ZodObject,...ee(t)});class Pn extends ne{_parse(t){const{ctx:s}=this._processInputParams(t),n=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return s.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new ft(a.ctx.common.issues));return N(s,{code:I.invalid_union,unionErrors:o}),q}if(s.common.async)return Promise.all(n.map(async i=>{const o={...s,common:{...s.common,issues:[]},parent:null};return{result:await i._parseAsync({data:s.data,path:s.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const c of n){const u={...s,common:{...s.common,issues:[]},parent:null},f=c._parseSync({data:s.data,path:s.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(i)return s.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(c=>new ft(c));return N(s,{code:I.invalid_union,unionErrors:a}),q}}get options(){return this._def.options}}Pn.create=(e,t)=>new Pn({options:e,typeName:G.ZodUnion,...ee(t)});function Ir(e,t){const s=gt(e),n=gt(t);if(e===t)return{valid:!0,data:e};if(s===V.object&&n===V.object){const r=re.objectKeys(t),i=re.objectKeys(e).filter(a=>r.indexOf(a)!==-1),o={...e,...t};for(const a of i){const c=Ir(e[a],t[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(s===V.array&&n===V.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let i=0;i{if(vo(i)||vo(o))return q;const a=Ir(i.value,o.value);return a.valid?((yo(i)||yo(o))&&s.dirty(),{status:s.value,value:a.data}):(N(n,{code:I.invalid_intersection_types}),q)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>r(i,o)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}kn.create=(e,t,s)=>new kn({left:e,right:t,typeName:G.ZodIntersection,...ee(s)});class Ht extends ne{_parse(t){const{status:s,ctx:n}=this._processInputParams(t);if(n.parsedType!==V.array)return N(n,{code:I.invalid_type,expected:V.array,received:n.parsedType}),q;if(n.data.lengththis._def.items.length&&(N(n,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),s.dirty());const i=[...n.data].map((o,a)=>{const c=this._def.items[a]||this._def.rest;return c?c._parse(new It(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>Ae.mergeArray(s,o)):Ae.mergeArray(s,i)}get items(){return this._def.items}rest(t){return new Ht({...this._def,rest:t})}}Ht.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ht({items:e,typeName:G.ZodTuple,rest:null,...ee(t)})};class ko extends ne{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:s,ctx:n}=this._processInputParams(t);if(n.parsedType!==V.map)return N(n,{code:I.invalid_type,expected:V.map,received:n.parsedType}),q;const r=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,c],u)=>({key:r._parse(new It(n,a,n.path,[u,"key"])),value:i._parse(new It(n,c,n.path,[u,"value"]))}));if(n.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const c of o){const u=await c.key,f=await c.value;if(u.status==="aborted"||f.status==="aborted")return q;(u.status==="dirty"||f.status==="dirty")&&s.dirty(),a.set(u.value,f.value)}return{status:s.value,value:a}})}else{const a=new Map;for(const c of o){const u=c.key,f=c.value;if(u.status==="aborted"||f.status==="aborted")return q;(u.status==="dirty"||f.status==="dirty")&&s.dirty(),a.set(u.value,f.value)}return{status:s.value,value:a}}}}ko.create=(e,t,s)=>new ko({valueType:t,keyType:e,typeName:G.ZodMap,...ee(s)});class Hs extends ne{_parse(t){const{status:s,ctx:n}=this._processInputParams(t);if(n.parsedType!==V.set)return N(n,{code:I.invalid_type,expected:V.set,received:n.parsedType}),q;const r=this._def;r.minSize!==null&&n.data.sizer.maxSize.value&&(N(n,{code:I.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),s.dirty());const i=this._def.valueType;function o(c){const u=new Set;for(const f of c){if(f.status==="aborted")return q;f.status==="dirty"&&s.dirty(),u.add(f.value)}return{status:s.value,value:u}}const a=[...n.data.values()].map((c,u)=>i._parse(new It(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(t,s){return new Hs({...this._def,minSize:{value:t,message:U.toString(s)}})}max(t,s){return new Hs({...this._def,maxSize:{value:t,message:U.toString(s)}})}size(t,s){return this.min(t,s).max(t,s)}nonempty(t){return this.min(1,t)}}Hs.create=(e,t)=>new Hs({valueType:e,minSize:null,maxSize:null,typeName:G.ZodSet,...ee(t)});class To extends ne{get schema(){return this._def.getter()}_parse(t){const{ctx:s}=this._processInputParams(t);return this._def.getter()._parse({data:s.data,path:s.path,parent:s})}}To.create=(e,t)=>new To({getter:e,typeName:G.ZodLazy,...ee(t)});class Io extends ne{_parse(t){if(t.data!==this._def.value){const s=this._getOrReturnCtx(t);return N(s,{received:s.data,code:I.invalid_literal,expected:this._def.value}),q}return{status:"valid",value:t.data}}get value(){return this._def.value}}Io.create=(e,t)=>new Io({value:e,typeName:G.ZodLiteral,...ee(t)});function Ya(e,t){return new rs({values:e,typeName:G.ZodEnum,...ee(t)})}class rs extends ne{_parse(t){if(typeof t.data!="string"){const s=this._getOrReturnCtx(t),n=this._def.values;return N(s,{expected:re.joinValues(n),received:s.parsedType,code:I.invalid_type}),q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const s=this._getOrReturnCtx(t),n=this._def.values;return N(s,{received:s.data,code:I.invalid_enum_value,options:n}),q}return Be(t.data)}get options(){return this._def.values}get enum(){const t={};for(const s of this._def.values)t[s]=s;return t}get Values(){const t={};for(const s of this._def.values)t[s]=s;return t}get Enum(){const t={};for(const s of this._def.values)t[s]=s;return t}extract(t,s=this._def){return rs.create(t,{...this._def,...s})}exclude(t,s=this._def){return rs.create(this.options.filter(n=>!t.includes(n)),{...this._def,...s})}}rs.create=Ya;class Lo extends ne{_parse(t){const s=re.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==V.string&&n.parsedType!==V.number){const r=re.objectValues(s);return N(n,{expected:re.joinValues(r),received:n.parsedType,code:I.invalid_type}),q}if(this._cache||(this._cache=new Set(re.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const r=re.objectValues(s);return N(n,{received:n.data,code:I.invalid_enum_value,options:r}),q}return Be(t.data)}get enum(){return this._def.values}}Lo.create=(e,t)=>new Lo({values:e,typeName:G.ZodNativeEnum,...ee(t)});class Tn extends ne{unwrap(){return this._def.type}_parse(t){const{ctx:s}=this._processInputParams(t);if(s.parsedType!==V.promise&&s.common.async===!1)return N(s,{code:I.invalid_type,expected:V.promise,received:s.parsedType}),q;const n=s.parsedType===V.promise?s.data:Promise.resolve(s.data);return Be(n.then(r=>this._def.type.parseAsync(r,{path:s.path,errorMap:s.common.contextualErrorMap})))}}Tn.create=(e,t)=>new Tn({type:e,typeName:G.ZodPromise,...ee(t)});class is extends ne{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:s,ctx:n}=this._processInputParams(t),r=this._def.effect||null,i={addIssue:o=>{N(n,o),o.fatal?s.abort():s.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async a=>{if(s.value==="aborted")return q;const c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?q:c.status==="dirty"||s.value==="dirty"?ys(c.value):c});{if(s.value==="aborted")return q;const a=this._def.schema._parseSync({data:o,path:n.path,parent:n});return a.status==="aborted"?q:a.status==="dirty"||s.value==="dirty"?ys(a.value):a}}if(r.type==="refinement"){const o=a=>{const c=r.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?q:(a.status==="dirty"&&s.dirty(),o(a.value),{status:s.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?q:(a.status==="dirty"&&s.dirty(),o(a.value).then(()=>({status:s.value,value:a.value}))))}if(r.type==="transform")if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ns(o))return q;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:s.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>ns(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:s.value,value:a})):q);re.assertNever(r)}}is.create=(e,t,s)=>new is({schema:e,typeName:G.ZodEffects,effect:t,...ee(s)});is.createWithPreprocess=(e,t,s)=>new is({schema:t,effect:{type:"preprocess",transform:e},typeName:G.ZodEffects,...ee(s)});class Ct extends ne{_parse(t){return this._getType(t)===V.undefined?Be(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ct.create=(e,t)=>new Ct({innerType:e,typeName:G.ZodOptional,...ee(t)});class os extends ne{_parse(t){return this._getType(t)===V.null?Be(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}os.create=(e,t)=>new os({innerType:e,typeName:G.ZodNullable,...ee(t)});class Lr extends ne{_parse(t){const{ctx:s}=this._processInputParams(t);let n=s.data;return s.parsedType===V.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:s.path,parent:s})}removeDefault(){return this._def.innerType}}Lr.create=(e,t)=>new Lr({innerType:e,typeName:G.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ee(t)});class Mr extends ne{_parse(t){const{ctx:s}=this._processInputParams(t),n={...s,common:{...s.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Rn(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ft(n.common.issues)},input:n.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ft(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Mr.create=(e,t)=>new Mr({innerType:e,typeName:G.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ee(t)});class Mo extends ne{_parse(t){if(this._getType(t)!==V.nan){const n=this._getOrReturnCtx(t);return N(n,{code:I.invalid_type,expected:V.nan,received:n.parsedType}),q}return{status:"valid",value:t.data}}}Mo.create=e=>new Mo({typeName:G.ZodNaN,...ee(e)});class Zd extends ne{_parse(t){const{ctx:s}=this._processInputParams(t),n=s.data;return this._def.type._parse({data:n,path:s.path,parent:s})}unwrap(){return this._def.type}}class yi extends ne{_parse(t){const{status:s,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?q:i.status==="dirty"?(s.dirty(),ys(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const r=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return r.status==="aborted"?q:r.status==="dirty"?(s.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:n.path,parent:n})}}static create(t,s){return new yi({in:t,out:s,typeName:G.ZodPipeline})}}class Er extends ne{_parse(t){const s=this._def.innerType._parse(t),n=r=>(ns(r)&&(r.value=Object.freeze(r.value)),r);return Rn(s)?s.then(r=>n(r)):n(s)}unwrap(){return this._def.innerType}}Er.create=(e,t)=>new Er({innerType:e,typeName:G.ZodReadonly,...ee(t)});var G;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(G||(G={}));const Wd=bt.create;Lt.create;et.create;const zd=ye.create;Pn.create;kn.create;Ht.create;rs.create;Tn.create;Ct.create;os.create;const Kd=e=>{const t="input"in e?e.input:"input",s="output"in e?e.output:"output",n="schema"in e?e.schema._input:e._input,r="schema"in e?e.schema._output:e._output;return{types:{input:t==="output"?r:n,output:s==="input"?n:r},parse:i=>"schema"in e?e.schema.parse(i):e.parse(i)}},qd=()=>ls(()=>import("./page-with-search-BhJv4yJI.js"),__vite__mapDeps([0,1])),Gd=cs("/(tests)/page-with-search")({validateSearch:Kd(zd({where:Wd()})),component:vi(qd,"component")}),Jd=()=>ls(()=>import("./normal-page-BPOVyYTF.js"),__vite__mapDeps([2,1])),Yd=cs("/(tests)/normal-page")({component:vi(Jd,"component")});(function e(t){function s(r,i,o){var a,c={};if(Array.isArray(r))return r.concat(i);for(a in r)c[o?a.toLowerCase():a]=r[a];for(a in i){var u=o?a.toLowerCase():a,f=i[a];c[u]=u in c&&typeof f=="object"?s(c[u],f,u=="headers"):f}return c}function n(r,i,o,a,c){var u=typeof r!="string"?(i=r).url:r,f={config:i},l=s(t,i),d={};a=a||l.data,(l.transformRequest||[]).map(function(h){a=h(a,l.headers)||a}),l.auth&&(d.authorization=l.auth),a&&typeof a=="object"&&typeof a.append!="function"&&typeof a.text!="function"&&(a=JSON.stringify(a),d["content-type"]="application/json");try{d[l.xsrfHeaderName]=decodeURIComponent(document.cookie.match(RegExp("(^|; )"+l.xsrfCookieName+"=([^;]*)"))[2])}catch{}return l.baseURL&&(u=u.replace(/^(?!.*\/\/)\/?/,l.baseURL+"/")),l.params&&(u+=(~u.indexOf("?")?"&":"?")+(l.paramsSerializer?l.paramsSerializer(l.params):new URLSearchParams(l.params))),(l.fetch||fetch)(u,{method:(o||l.method||"get").toUpperCase(),body:a,headers:s(l.headers,d,!0),credentials:l.withCredentials?"include":c}).then(function(h){for(var g in h)typeof h[g]!="function"&&(f[g]=h[g]);return l.responseType=="stream"?(f.data=h.body,f):h[l.responseType||"text"]().then(function(y){f.data=y,f.data=JSON.parse(y)}).catch(Object).then(function(){return(l.validateStatus?l.validateStatus(h.status):h.ok)?f:Promise.reject(f)})})}return t=t||{},n.request=n,n.get=function(r,i){return n(r,i,"get")},n.delete=function(r,i){return n(r,i,"delete")},n.head=function(r,i){return n(r,i,"head")},n.options=function(r,i){return n(r,i,"options")},n.post=function(r,i,o){return n(r,o,"post",i)},n.put=function(r,i,o){return n(r,o,"put",i)},n.patch=function(r,i,o){return n(r,o,"patch",i)},n.all=Promise.all.bind(Promise),n.spread=function(r){return r.apply.bind(r,r)},n.CancelToken=typeof AbortController=="function"?AbortController:Object,n.defaults=t,n.create=e,n})();function Xd(e){return new Promise(t=>setTimeout(t,e))}const Qd=cs("/(tests)/lazy-with-loader-page")({loader:async()=>(await Xd(1e3),{foo:"bar"})}),eh=cs("/(tests)/lazy-page")({}),th=cs("/(tests)/virtual-page")(),sh=yd.update({id:"/",path:"/",getParentRoute:()=>Wt}),nh=th.update({id:"/(tests)/virtual-page",path:"/virtual-page",getParentRoute:()=>Wt}).lazy(()=>ls(()=>import("./virtual-page.lazy-BCqvdivF.js"),__vite__mapDeps([3,1])).then(e=>e.Route)),rh=Gd.update({id:"/(tests)/page-with-search",path:"/page-with-search",getParentRoute:()=>Wt}),ih=Yd.update({id:"/(tests)/normal-page",path:"/normal-page",getParentRoute:()=>Wt}),oh=Qd.update({id:"/(tests)/lazy-with-loader-page",path:"/lazy-with-loader-page",getParentRoute:()=>Wt}).lazy(()=>ls(()=>import("./lazy-with-loader-page.lazy-BzLmn584.js"),__vite__mapDeps([4,1])).then(e=>e.Route)),ah=eh.update({id:"/(tests)/lazy-page",path:"/lazy-page",getParentRoute:()=>Wt}).lazy(()=>ls(()=>import("./lazy-page.lazy-BzoMuhUY.js"),__vite__mapDeps([5,1])).then(e=>e.Route)),ch={IndexRoute:sh,testsLazyPageRoute:ah,testsLazyWithLoaderPageRoute:oh,testsNormalPageRoute:ih,testsPageWithSearchRoute:rh,testsVirtualPageLazyRoute:nh},lh=Wt._addFileChildren(ch)._addFileTypes();let Xa;Xa=Fu();const uh=sd({routeTree:lh,history:Xa,scrollRestoration:!0}),fh=document.getElementById("app");fh?.innerHTML||ku({setup(){return()=>ce(id,{router:uh},null)}}).mount("#app");export{Fe as F,ho as L,ce as a,xr as b,mh as c,ms as l,ri as m}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-ElfLiipA.css b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-ElfLiipA.css deleted file mode 100644 index b6e247a9c9..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-ElfLiipA.css +++ /dev/null @@ -1 +0,0 @@ -/*! tailwindcss v4.1.15 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-style:solid;--tw-font-weight:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-gray-50:oklch(98.5% .002 247.839);--color-gray-200:oklch(92.8% .006 264.531);--color-gray-800:oklch(27.8% .033 256.848);--color-gray-900:oklch(21% .034 264.665);--color-gray-950:oklch(13% .028 261.692);--spacing:.25rem;--text-lg:1.125rem;--text-lg--line-height:calc(1.75/1.125);--font-weight-bold:700;--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}*,:after,:before,::backdrop{border-color:var(--color-gray-200,currentcolor)}::file-selector-button{border-color:var(--color-gray-200,currentcolor)}}@layer components;@layer utilities{.flex{display:flex}.grid{display:grid}.gap-2{gap:calc(var(--spacing)*2)}.border{border-style:var(--tw-border-style);border-width:1px}.p-2{padding:calc(var(--spacing)*2)}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}}html{color-scheme:light dark}*{border-color:var(--color-gray-200)}@media (prefers-color-scheme:dark){*{border-color:var(--color-gray-800)}}body{background-color:var(--color-gray-50);color:var(--color-gray-950)}@media (prefers-color-scheme:dark){body{background-color:var(--color-gray-900);color:var(--color-gray-200)}}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-rPfEOKs3.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-rPfEOKs3.js deleted file mode 100644 index 7dff2a5190..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/index-rPfEOKs3.js +++ /dev/null @@ -1 +0,0 @@ -import{a as e,l as t,b as a,L as r,m as s}from"./index-BwsVWHwV.js";function i(){return e("div",{class:"p-2 grid gap-2"},[e("h3",null,[a("Welcome Home!")]),e("p",null,[a("The are the links to be tested when navigating away from the index page. Otherwise known as NOT first-load tests, rather known as navigation tests.")]),[t({to:"/normal-page"}),t({to:"/lazy-page"}),t({to:"/virtual-page"}),t({to:"/lazy-with-loader-page"}),t({to:"/page-with-search",search:{where:"footer"}})].map((o,n)=>e("div",{class:"border p-2"},[e("h4",null,[o.to,a(" tests")]),e("p",null,[e(r,s(o,{hash:"at-the-bottom"}),{default:()=>[o.to,a("#at-the-bottom")]})])]))])}export{i as component}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-page.lazy-BzoMuhUY.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-page.lazy-BzoMuhUY.js deleted file mode 100644 index b2ab5a4389..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-page.lazy-BzoMuhUY.js +++ /dev/null @@ -1 +0,0 @@ -import{c as l,a as e,b as o}from"./index-BwsVWHwV.js";import{S as t}from"./scroll-block-BAas_Ct-.js";const c=l("/(tests)/lazy-page")({component:a});function a(){return e("div",{class:"p-2"},[e("h3",null,[o("lazy-page")]),e("hr",null,null),e(t,null,null)])}export{c as Route}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-with-loader-page.lazy-BzLmn584.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-with-loader-page.lazy-BzLmn584.js deleted file mode 100644 index ab267814ce..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/lazy-with-loader-page.lazy-BzLmn584.js +++ /dev/null @@ -1 +0,0 @@ -import{c as l,a as e,b as o}from"./index-BwsVWHwV.js";import{S as t}from"./scroll-block-BAas_Ct-.js";const c=l("/(tests)/lazy-with-loader-page")({component:a});function a(){return e("div",{class:"p-2"},[e("h3",null,[o("lazy-with-loader-page")]),e("hr",null,null),e(t,null,null)])}export{c as Route}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/normal-page-BPOVyYTF.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/normal-page-BPOVyYTF.js deleted file mode 100644 index ec26f71d98..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/normal-page-BPOVyYTF.js +++ /dev/null @@ -1 +0,0 @@ -import{S as o}from"./scroll-block-BAas_Ct-.js";import{a as l,b as n}from"./index-BwsVWHwV.js";function a(){return l("div",{class:"p-2"},[l("h3",null,[n("normal-page")]),l("hr",null,null),l(o,null,null)])}export{a as component}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/page-with-search-BhJv4yJI.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/page-with-search-BhJv4yJI.js deleted file mode 100644 index 67ce6cd937..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/page-with-search-BhJv4yJI.js +++ /dev/null @@ -1 +0,0 @@ -import{S as o}from"./scroll-block-BAas_Ct-.js";import{a as l,b as e}from"./index-BwsVWHwV.js";function t(){return l("div",{class:"p-2"},[l("h3",null,[e("page-with-search")]),l("hr",null,null),l(o,null,null)])}export{t as component}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/scroll-block-BAas_Ct-.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/scroll-block-BAas_Ct-.js deleted file mode 100644 index 89ed1c6988..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/scroll-block-BAas_Ct-.js +++ /dev/null @@ -1 +0,0 @@ -import{a as t,b as r,F as l}from"./index-BwsVWHwV.js";const o="at-the-top",a="at-the-bottom";function m({number:e=100}){return t(l,null,[t("div",{id:o,"data-testid":o},null),Array.from({length:e}).map((n,d)=>t("div",null,[d])),t("div",{id:a,"data-testid":a},[r("At the bottom")])])}export{m as S}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/virtual-page.lazy-BCqvdivF.js b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/virtual-page.lazy-BCqvdivF.js deleted file mode 100644 index 82d2cac67f..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/assets/virtual-page.lazy-BCqvdivF.js +++ /dev/null @@ -1 +0,0 @@ -import{c as t,a as e,b as l}from"./index-BwsVWHwV.js";import{S as o}from"./scroll-block-BAas_Ct-.js";const u=t("/(tests)/virtual-page")({component:a});function a(){return e("div",{class:"p-2"},[e("h3",null,[l("virtual-page")]),e("hr",null,null),e(o,null,null)])}export{u as Route}; diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/index.html b/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/index.html deleted file mode 100644 index 2a9c6c3574..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/dist-hash/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - -
- - diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/package.json b/e2e/vue-router/scroll-restoration-sandbox-vite/package.json index d4c9776f51..d071ee546a 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/package.json @@ -11,27 +11,35 @@ "start": "vite", "test:e2e:browser": "VITE_APP_HISTORY=browser playwright test --config=playwright.browser.config.ts --project=chromium", "test:e2e:hash": "VITE_APP_HISTORY=hash playwright test --config=playwright.hash.config.ts --project=chromium", - "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "@tanstack/zod-adapter": "workspace:^", - "postcss": "^8.5.1", - "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", + "redaxios": "catalog:", + "tailwindcss": "^4.2.2", "vue": "^3.5.16", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^5.2.3", - "@vitejs/plugin-vue-jsx": "^4.1.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^7.1.7", - "vue-tsc": "^3.1.5" + "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 9d7691f0fd..e2681daea5 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts @@ -1,15 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, - resolveRuntimeSuffix, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - packageJson.name + `-${resolveRuntimeSuffix('browser')}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `VITE_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts index 80a340cef4..445616b9bd 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts @@ -1,15 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, - resolveRuntimeSuffix, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - packageJson.name + `-${resolveRuntimeSuffix('hash')}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/postcss.config.mjs b/e2e/vue-router/scroll-restoration-sandbox-vite/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx b/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx index c6cba486ab..bc56dff904 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -12,11 +12,7 @@ export type PostType = { export class PostNotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts index 69dda324fe..e85be2bf37 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts @@ -12,10 +12,10 @@ import { createFileRoute } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as testsPageWithSearchRouteImport } from './routes/(tests)/page-with-search' -import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' -import { Route as testsLazyWithLoaderPageRouteImport } from './routes/(tests)/lazy-with-loader-page' import { Route as testsLazyPageRouteImport } from './routes/(tests)/lazy-page' +import { Route as testsLazyWithLoaderPageRouteImport } from './routes/(tests)/lazy-with-loader-page' +import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' +import { Route as testsPageWithSearchRouteImport } from './routes/(tests)/page-with-search' const testsVirtualPageLazyRouteImport = createFileRoute( '/(tests)/virtual-page', @@ -26,23 +26,13 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -const testsVirtualPageLazyRoute = testsVirtualPageLazyRouteImport +const testsLazyPageRoute = testsLazyPageRouteImport .update({ - id: '/(tests)/virtual-page', - path: '/virtual-page', + id: '/(tests)/lazy-page', + path: '/lazy-page', getParentRoute: () => rootRouteImport, } as any) - .lazy(() => import('./routes/(tests)/virtual-page.lazy').then((d) => d.Route)) -const testsPageWithSearchRoute = testsPageWithSearchRouteImport.update({ - id: '/(tests)/page-with-search', - path: '/page-with-search', - getParentRoute: () => rootRouteImport, -} as any) -const testsNormalPageRoute = testsNormalPageRouteImport.update({ - id: '/(tests)/normal-page', - path: '/normal-page', - getParentRoute: () => rootRouteImport, -} as any) + .lazy(() => import('./routes/(tests)/lazy-page.lazy').then((d) => d.Route)) const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .update({ id: '/(tests)/lazy-with-loader-page', @@ -52,13 +42,23 @@ const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .lazy(() => import('./routes/(tests)/lazy-with-loader-page.lazy').then((d) => d.Route), ) -const testsLazyPageRoute = testsLazyPageRouteImport +const testsNormalPageRoute = testsNormalPageRouteImport.update({ + id: '/(tests)/normal-page', + path: '/normal-page', + getParentRoute: () => rootRouteImport, +} as any) +const testsPageWithSearchRoute = testsPageWithSearchRouteImport.update({ + id: '/(tests)/page-with-search', + path: '/page-with-search', + getParentRoute: () => rootRouteImport, +} as any) +const testsVirtualPageLazyRoute = testsVirtualPageLazyRouteImport .update({ - id: '/(tests)/lazy-page', - path: '/lazy-page', + id: '/(tests)/virtual-page', + path: '/virtual-page', getParentRoute: () => rootRouteImport, } as any) - .lazy(() => import('./routes/(tests)/lazy-page.lazy').then((d) => d.Route)) + .lazy(() => import('./routes/(tests)/virtual-page.lazy').then((d) => d.Route)) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -130,25 +130,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/virtual-page': { - id: '/(tests)/virtual-page' - path: '/virtual-page' - fullPath: '/virtual-page' - preLoaderRoute: typeof testsVirtualPageLazyRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/page-with-search': { - id: '/(tests)/page-with-search' - path: '/page-with-search' - fullPath: '/page-with-search' - preLoaderRoute: typeof testsPageWithSearchRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/normal-page': { - id: '/(tests)/normal-page' - path: '/normal-page' - fullPath: '/normal-page' - preLoaderRoute: typeof testsNormalPageRouteImport + '/(tests)/lazy-page': { + id: '/(tests)/lazy-page' + path: '/lazy-page' + fullPath: '/lazy-page' + preLoaderRoute: typeof testsLazyPageRouteImport parentRoute: typeof rootRouteImport } '/(tests)/lazy-with-loader-page': { @@ -158,11 +144,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/lazy-page': { - id: '/(tests)/lazy-page' - path: '/lazy-page' - fullPath: '/lazy-page' - preLoaderRoute: typeof testsLazyPageRouteImport + '/(tests)/normal-page': { + id: '/(tests)/normal-page' + path: '/normal-page' + fullPath: '/normal-page' + preLoaderRoute: typeof testsNormalPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/page-with-search': { + id: '/(tests)/page-with-search' + path: '/page-with-search' + fullPath: '/page-with-search' + preLoaderRoute: typeof testsPageWithSearchRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/virtual-page': { + id: '/(tests)/virtual-page' + path: '/virtual-page' + fullPath: '/virtual-page' + preLoaderRoute: typeof testsVirtualPageLazyRouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx b/e2e/vue-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx index 3e1ec1eeba..f608b9e379 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/routes/(tests)/page-with-search.tsx @@ -1,10 +1,9 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' import { ScrollBlock } from '../-components/scroll-block' export const Route = createFileRoute('/(tests)/page-with-search')({ - validateSearch: zodValidator(z.object({ where: z.string() })), + validateSearch: z.object({ where: z.string() }), component: Component, }) diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/styles.css b/e2e/vue-router/scroll-restoration-sandbox-vite/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/styles.css +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts index 5f226c6db3..067f0341c4 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import { toRuntimePath } from '@tanstack/router-e2e-utils' test('Smoke - Renders home', async ({ page }) => { diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json b/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json index 3e5b04987f..b47cca9589 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json @@ -12,5 +12,5 @@ "allowJs": true, "types": ["vite/client", "node"] }, - "exclude": ["node_modules", "dist"] + "exclude": ["node_modules", "dist", "dist-hash"] } diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/vite.config.js b/e2e/vue-router/scroll-restoration-sandbox-vite/vite.config.js index c3ba78d34e..988a2fd1f3 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/vite.config.js +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/vite.config.js @@ -2,10 +2,12 @@ import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'vue', autoCodeSplitting: true }), vue(), vueJsx(), diff --git a/e2e/vue-router/sentry-integration/.devcontainer/devcontainer.json b/e2e/vue-router/sentry-integration/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-router/sentry-integration/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-router/sentry-integration/package.json b/e2e/vue-router/sentry-integration/package.json index 5e8b947dfa..045ddd99be 100644 --- a/e2e/vue-router/sentry-integration/package.json +++ b/e2e/vue-router/sentry-integration/package.json @@ -8,26 +8,25 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@sentry/vue": "^10.32.0", "@sentry/tracing": "^7.120.4", "@sentry/vite-plugin": "^4.6.1", - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "postcss": "^8.5.1", - "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", + "redaxios": "catalog:", + "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue-jsx": "^4.1.2", + "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^7.1.7", - "vue-tsc": "^3.1.5" + "vite": "^8.0.14", + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/sentry-integration/playwright.config.ts b/e2e/vue-router/sentry-integration/playwright.config.ts index 0c5cee43e4..6a684ac89e 100644 --- a/e2e/vue-router/sentry-integration/playwright.config.ts +++ b/e2e/vue-router/sentry-integration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/sentry-integration/postcss.config.mjs b/e2e/vue-router/sentry-integration/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-router/sentry-integration/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-router/sentry-integration/src/styles.css b/e2e/vue-router/sentry-integration/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/e2e/vue-router/sentry-integration/src/styles.css +++ b/e2e/vue-router/sentry-integration/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-router/sentry-integration/src/vite-env.d.ts b/e2e/vue-router/sentry-integration/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/vue-router/sentry-integration/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/vue-router/sentry-integration/vite.config.js b/e2e/vue-router/sentry-integration/vite.config.js index ca9f51ac9c..e095e1900a 100644 --- a/e2e/vue-router/sentry-integration/vite.config.js +++ b/e2e/vue-router/sentry-integration/vite.config.js @@ -1,8 +1,9 @@ import { defineConfig } from 'vite' import { sentryVitePlugin } from '@sentry/vite-plugin' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [vueJsx(), sentryVitePlugin()], + plugins: [tailwindcss(), vueJsx(), sentryVitePlugin()], }) diff --git a/e2e/vue-router/view-transitions/.devcontainer/devcontainer.json b/e2e/vue-router/view-transitions/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-router/view-transitions/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-router/view-transitions/package.json b/e2e/vue-router/view-transitions/package.json index 47d88a7dcf..21a0f1d8a0 100644 --- a/e2e/vue-router/view-transitions/package.json +++ b/e2e/vue-router/view-transitions/package.json @@ -8,27 +8,26 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-query": "^5.90.0", "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "postcss": "^8.5.1", - "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", + "redaxios": "catalog:", + "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", - "@vitejs/plugin-vue": "^5.2.3", - "@vitejs/plugin-vue-jsx": "^4.1.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^7.1.7", - "vue-tsc": "^3.1.5" + "vite": "^8.0.14", + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/view-transitions/playwright.config.ts b/e2e/vue-router/view-transitions/playwright.config.ts index c5de6b5611..4eead86444 100644 --- a/e2e/vue-router/view-transitions/playwright.config.ts +++ b/e2e/vue-router/view-transitions/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -22,13 +17,10 @@ export default defineConfig({ baseURL, }, - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/view-transitions/postcss.config.mjs b/e2e/vue-router/view-transitions/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-router/view-transitions/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-router/view-transitions/src/routeTree.gen.ts b/e2e/vue-router/view-transitions/src/routeTree.gen.ts index 465362a7a2..04708c29a8 100644 --- a/e2e/vue-router/view-transitions/src/routeTree.gen.ts +++ b/e2e/vue-router/view-transitions/src/routeTree.gen.ts @@ -9,16 +9,16 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as HowItWorksRouteImport } from './routes/how-it-works' -import { Route as ExploreRouteImport } from './routes/explore' -import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as IndexRouteImport } from './routes/index' +import { Route as ExploreRouteImport } from './routes/explore' +import { Route as HowItWorksRouteImport } from './routes/how-it-works' +import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const HowItWorksRoute = HowItWorksRouteImport.update({ - id: '/how-it-works', - path: '/how-it-works', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const ExploreRoute = ExploreRouteImport.update({ @@ -26,16 +26,16 @@ const ExploreRoute = ExploreRouteImport.update({ path: '/explore', getParentRoute: () => rootRouteImport, } as any) +const HowItWorksRoute = HowItWorksRouteImport.update({ + id: '/how-it-works', + path: '/how-it-works', + getParentRoute: () => rootRouteImport, +} as any) const PostsRouteRoute = PostsRouteRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -101,11 +101,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/how-it-works': { - id: '/how-it-works' - path: '/how-it-works' - fullPath: '/how-it-works' - preLoaderRoute: typeof HowItWorksRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/explore': { @@ -115,6 +115,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ExploreRouteImport parentRoute: typeof rootRouteImport } + '/how-it-works': { + id: '/how-it-works' + path: '/how-it-works' + fullPath: '/how-it-works' + preLoaderRoute: typeof HowItWorksRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -122,13 +129,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' diff --git a/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx b/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx index e271c139f5..a86ea0762f 100644 --- a/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,6 +7,19 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

{post.value.title}

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

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-router/view-transitions/src/routes/posts.route.tsx b/e2e/vue-router/view-transitions/src/routes/posts.route.tsx index 01d90b7ad6..6802b073f6 100644 --- a/e2e/vue-router/view-transitions/src/routes/posts.route.tsx +++ b/e2e/vue-router/view-transitions/src/routes/posts.route.tsx @@ -1,43 +1,46 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' +const PostsLayoutComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+
+ +
+
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsLayoutComponent, }) - -function PostsLayoutComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
-
- -
-
- ) -} diff --git a/e2e/vue-router/view-transitions/src/styles.css b/e2e/vue-router/view-transitions/src/styles.css index 818667133d..b51e6e1244 100644 --- a/e2e/vue-router/view-transitions/src/styles.css +++ b/e2e/vue-router/view-transitions/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-router/view-transitions/src/vite-env.d.ts b/e2e/vue-router/view-transitions/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/vue-router/view-transitions/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/vue-router/view-transitions/tests/app.spec.ts b/e2e/vue-router/view-transitions/tests/app.spec.ts index 472bd6ed0b..6c1ccf1a6e 100644 --- a/e2e/vue-router/view-transitions/tests/app.spec.ts +++ b/e2e/vue-router/view-transitions/tests/app.spec.ts @@ -1,4 +1,4 @@ -import { test } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/view-transitions/tests/setup/global.setup.ts b/e2e/vue-router/view-transitions/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/view-transitions/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts b/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts index b827bf3e6e..e62662a1d2 100644 --- a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts +++ b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.addInitScript(() => { @@ -31,7 +32,12 @@ test('navigation uses View Transitions API', async ({ page }) => { await page.getByRole('link', { name: 'Next Page ->' }).click() await expect(page).toHaveURL(/\/how-it-works$/) - const calls = await page.evaluate(() => (window as any).__viewTransitionCalls) - expect(Array.isArray(calls)).toBe(true) - expect(calls.length).toBeGreaterThan(0) + await expect + .poll(async () => { + const calls = await page.evaluate( + () => (window as any).__viewTransitionCalls, + ) + return calls.length + }) + .toBeGreaterThan(0) }) diff --git a/e2e/vue-router/view-transitions/vite.config.js b/e2e/vue-router/view-transitions/vite.config.js index c3ba78d34e..988a2fd1f3 100644 --- a/e2e/vue-router/view-transitions/vite.config.js +++ b/e2e/vue-router/view-transitions/vite.config.js @@ -2,10 +2,12 @@ import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'vue', autoCodeSplitting: true }), vue(), vueJsx(), diff --git a/e2e/vue-start/basic-auth/.devcontainer/devcontainer.json b/e2e/vue-start/basic-auth/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/basic-auth/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/basic-auth/package.json b/e2e/vue-start/basic-auth/package.json index 91bac41dd8..7f6fb798da 100644 --- a/e2e/vue-start/basic-auth/package.json +++ b/e2e/vue-start/basic-auth/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", "prisma-generate": "prisma generate", - "test:e2e": "rm -rf port*.txt; mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" + "test:e2e": "mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,24 +19,35 @@ "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "vite": "^7.1.7", + "iron-session": "^9.0.1", + "redaxios": "catalog:", + "tailwind-merge": "^3.6.0", "vue": "^3.5.25" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@tailwindcss/postcss": "^4.1.15", + "@playwright/test": "^1.61.0", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "dotenv": "^17.2.3", - "postcss": "^8.5.1", "prisma": "^7.0.0", - "srvx": "^0.9.8", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "@vitejs/plugin-vue": "^6.0.3", - "@vitejs/plugin-vue-jsx": "^5.1.2", - "vite-tsconfig-paths": "^5.1.4" + "srvx": "^1.0.0", + "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 18b8905468..82678ac00b 100644 --- a/e2e/vue-start/basic-auth/playwright.config.ts +++ b/e2e/vue-start/basic-auth/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-auth/postcss.config.mjs b/e2e/vue-start/basic-auth/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-start/basic-auth/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx index e11970b600..0687372ae0 100644 --- a/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx @@ -1,53 +1,61 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error(error) - - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} +export const DefaultCatchBoundary = defineComponent({ + props: { + error: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + return () => { + console.error(props.error) + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/basic-auth/src/prisma-generated/client.ts b/e2e/vue-start/basic-auth/src/prisma-generated/client.ts index 1b9d548165..2be7866ae3 100644 --- a/e2e/vue-start/basic-auth/src/prisma-generated/client.ts +++ b/e2e/vue-start/basic-auth/src/prisma-generated/client.ts @@ -37,10 +37,10 @@ export * from './enums' export const PrismaClient = $Class.getPrismaClientClass() export type PrismaClient< LogOpts extends Prisma.LogLevel = never, - OmitOpts extends - Prisma.PrismaClientOptions['omit'] = Prisma.PrismaClientOptions['omit'], - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + OmitOpts extends Prisma.PrismaClientOptions['omit'] = + Prisma.PrismaClientOptions['omit'], + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = $Class.PrismaClient export { Prisma } diff --git a/e2e/vue-start/basic-auth/src/prisma-generated/internal/class.ts b/e2e/vue-start/basic-auth/src/prisma-generated/internal/class.ts index 95cb7864ef..594896a020 100644 --- a/e2e/vue-start/basic-auth/src/prisma-generated/internal/class.ts +++ b/e2e/vue-start/basic-auth/src/prisma-generated/internal/class.ts @@ -44,9 +44,8 @@ config.compilerWasm = { await import('@prisma/client/runtime/query_compiler_bg.sqlite.mjs'), getQueryCompilerWasmModule: async () => { - const { wasm } = await import( - '@prisma/client/runtime/query_compiler_bg.sqlite.wasm-base64.mjs' - ) + const { wasm } = + await import('@prisma/client/runtime/query_compiler_bg.sqlite.wasm-base64.mjs') return await decodeBase64AsWasm(wasm) }, } @@ -81,8 +80,8 @@ export interface PrismaClientConstructor { } ? U : Prisma.PrismaClientOptions['omit'], - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, >( options: Prisma.Subset, ): PrismaClient @@ -105,8 +104,8 @@ export interface PrismaClientConstructor { export interface PrismaClient< in LogOpts extends Prisma.LogLevel = never, in out OmitOpts extends Prisma.PrismaClientOptions['omit'] = undefined, - in out ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + in out ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > { [K: symbol]: { types: Prisma.TypeMap['other'] } diff --git a/e2e/vue-start/basic-auth/src/prisma-generated/internal/prismaNamespace.ts b/e2e/vue-start/basic-auth/src/prisma-generated/internal/prismaNamespace.ts index fc96903a35..f420c55329 100644 --- a/e2e/vue-start/basic-auth/src/prisma-generated/internal/prismaNamespace.ts +++ b/e2e/vue-start/basic-auth/src/prisma-generated/internal/prismaNamespace.ts @@ -417,17 +417,17 @@ export const ModelName = { export type ModelName = (typeof ModelName)[keyof typeof ModelName] -export interface TypeMapCb - extends runtime.Types.Utils.Fn< - { extArgs: runtime.Types.Extensions.InternalArgs }, - runtime.Types.Utils.Record - > { +export interface TypeMapCb extends runtime.Types.Utils + .Fn< + { extArgs: runtime.Types.Extensions.InternalArgs }, + runtime.Types.Utils.Record +> { returns: TypeMap } export type TypeMap< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}, > = { globalOmitOptions: { diff --git a/e2e/vue-start/basic-auth/src/prisma-generated/models/User.ts b/e2e/vue-start/basic-auth/src/prisma-generated/models/User.ts index 14c9ca5fb9..4312db9bd9 100644 --- a/e2e/vue-start/basic-auth/src/prisma-generated/models/User.ts +++ b/e2e/vue-start/basic-auth/src/prisma-generated/models/User.ts @@ -57,8 +57,8 @@ export type UserCountAggregateInputType = { } export type UserAggregateArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Filter which User to aggregate. @@ -119,8 +119,8 @@ export type GetUserAggregateType = { } export type UserGroupByArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { where?: Prisma.UserWhereInput orderBy?: @@ -254,8 +254,8 @@ export type StringFieldUpdateOperationsInput = { } export type UserSelect< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetSelect< { email?: boolean @@ -265,8 +265,8 @@ export type UserSelect< > export type UserSelectCreateManyAndReturn< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetSelect< { email?: boolean @@ -276,8 +276,8 @@ export type UserSelectCreateManyAndReturn< > export type UserSelectUpdateManyAndReturn< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetSelect< { email?: boolean @@ -292,16 +292,16 @@ export type UserSelectScalar = { } export type UserOmit< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetOmit< 'email' | 'password', ExtArgs['result']['user'] > export type $UserPayload< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { name: 'User' objects: {} @@ -320,15 +320,15 @@ export type UserGetPayload< > = runtime.Types.Result.GetResult export type UserCountArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = Omit & { select?: UserCountAggregateInputType | true } export interface UserDelegate< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}, > { [K: symbol]: { @@ -854,8 +854,8 @@ export interface UserDelegate< export interface Prisma__UserClient< T, Null = never, - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}, > extends Prisma.PrismaPromise { readonly [Symbol.toStringTag]: 'PrismaPromise' @@ -910,8 +910,8 @@ export interface UserFieldRefs { * User findUnique */ export type UserFindUniqueArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -931,8 +931,8 @@ export type UserFindUniqueArgs< * User findUniqueOrThrow */ export type UserFindUniqueOrThrowArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -952,8 +952,8 @@ export type UserFindUniqueOrThrowArgs< * User findFirst */ export type UserFindFirstArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1005,8 +1005,8 @@ export type UserFindFirstArgs< * User findFirstOrThrow */ export type UserFindFirstOrThrowArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1058,8 +1058,8 @@ export type UserFindFirstOrThrowArgs< * User findMany */ export type UserFindManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1106,8 +1106,8 @@ export type UserFindManyArgs< * User create */ export type UserCreateArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1127,8 +1127,8 @@ export type UserCreateArgs< * User createMany */ export type UserCreateManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * The data used to create many Users. @@ -1140,8 +1140,8 @@ export type UserCreateManyArgs< * User createManyAndReturn */ export type UserCreateManyAndReturnArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1161,8 +1161,8 @@ export type UserCreateManyAndReturnArgs< * User update */ export type UserUpdateArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1186,8 +1186,8 @@ export type UserUpdateArgs< * User updateMany */ export type UserUpdateManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * The data used to update Users. @@ -1210,8 +1210,8 @@ export type UserUpdateManyArgs< * User updateManyAndReturn */ export type UserUpdateManyAndReturnArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1242,8 +1242,8 @@ export type UserUpdateManyAndReturnArgs< * User upsert */ export type UserUpsertArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1271,8 +1271,8 @@ export type UserUpsertArgs< * User delete */ export type UserDeleteArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1292,8 +1292,8 @@ export type UserDeleteArgs< * User deleteMany */ export type UserDeleteManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Filter which Users to delete @@ -1309,8 +1309,8 @@ export type UserDeleteManyArgs< * User without action */ export type UserDefaultArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User diff --git a/e2e/vue-start/basic-auth/src/routeTree.gen.ts b/e2e/vue-start/basic-auth/src/routeTree.gen.ts index 6e06092779..058f8674ac 100644 --- a/e2e/vue-start/basic-auth/src/routeTree.gen.ts +++ b/e2e/vue-start/basic-auth/src/routeTree.gen.ts @@ -9,23 +9,22 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as SignupRouteImport } from './routes/signup' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as SignupRouteImport } from './routes/signup' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -33,13 +32,14 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,18 +120,18 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } '/login': { @@ -141,18 +141,18 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthedRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/e2e/vue-start/basic-auth/src/routes/__root.tsx b/e2e/vue-start/basic-auth/src/routes/__root.tsx index 89802cfd2f..e5b6f6778f 100644 --- a/e2e/vue-start/basic-auth/src/routes/__root.tsx +++ b/e2e/vue-start/basic-auth/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, HeadContent, @@ -15,21 +16,69 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { useAppSession } from '~/utils/session.js' +import { getAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await useAppSession() + const session = await getAppSession() - if (!session.data.userEmail) { + if (!session.userEmail) { return null } return { - email: session.data.userEmail, + email: session.userEmail, } }) +const RootShell = defineComponent({ + setup(_, { slots }) { + const routeContext = Route.useRouteContext() + return () => ( + + + + + +
+ + Home + {' '} + + Posts + +
+ {routeContext.value.user ? ( + <> + {routeContext.value.user.email} + Logout + + ) : ( + Login + )} +
+
+
+ {slots.default?.()} + + + + + ) + }, +}) + export const Route = createRootRoute({ beforeLoad: async () => { const user = await fetchUser() @@ -81,50 +130,3 @@ export const Route = createRootRoute({ notFoundComponent: () => , component: () => , }) - -function RootShell(_: unknown, { slots }: { slots: any }) { - const routeContext = Route.useRouteContext() - - return ( - - - - - -
- - Home - {' '} - - Posts - -
- {routeContext.value.user ? ( - <> - {routeContext.value.user.email} - Logout - - ) : ( - Login - )} -
-
-
- {slots.default?.()} - - - - - ) -} diff --git a/e2e/vue-start/basic-auth/src/routes/_authed.tsx b/e2e/vue-start/basic-auth/src/routes/_authed.tsx index 53e16ebe33..606de3e487 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed.tsx @@ -3,12 +3,12 @@ import { createServerFn } from '@tanstack/vue-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', }) - .inputValidator((payload: { email: string; password: string }) => payload) + .validator((payload: { email: string; password: string }) => payload) .handler(async ({ data }) => { // Find the user const user = await prismaClient.user.findUnique({ @@ -37,12 +37,11 @@ export const loginFn = createServerFn({ } // Create a session - const session = await useAppSession() + const session = await getAppSession() // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + session.userEmail = user.email + await session.save() }) export const Route = createFileRoute('/_authed')({ @@ -52,7 +51,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return } diff --git a/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx b/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx index da0c26f27f..45d6bbab0d 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -8,6 +9,18 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + return () => ( +
+

{post.value.title}

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

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx b/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx index cfac133b51..6b8b54c666 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx @@ -1,36 +1,38 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '~/utils/posts.js' -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) -} +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) + }, +}) export const Route = createFileRoute('/_authed/posts')({ loader: () => fetchPosts(), diff --git a/e2e/vue-start/basic-auth/src/routes/logout.tsx b/e2e/vue-start/basic-auth/src/routes/logout.tsx index f1d7b58e29..8372b33608 100644 --- a/e2e/vue-start/basic-auth/src/routes/logout.tsx +++ b/e2e/vue-start/basic-auth/src/routes/logout.tsx @@ -1,12 +1,12 @@ import { redirect, createFileRoute } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await useAppSession() + const session = await getAppSession() - session.clear() + session.destroy() throw redirect({ href: '/', diff --git a/e2e/vue-start/basic-auth/src/routes/signup.tsx b/e2e/vue-start/basic-auth/src/routes/signup.tsx index 22fd7d4ca5..5f37f109c7 100644 --- a/e2e/vue-start/basic-auth/src/routes/signup.tsx +++ b/e2e/vue-start/basic-auth/src/routes/signup.tsx @@ -5,12 +5,12 @@ import { defineComponent } from 'vue' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST', }) - .inputValidator( + .validator( (data: { email: string; password: string; redirectUrl?: string }) => data, ) .handler(async ({ data: payload }) => { @@ -25,7 +25,7 @@ export const signupFn = createServerFn({ const password = await hashPassword(payload.password) // Create a session - const session = await useAppSession() + const session = await getAppSession() if (found) { if (found.password !== password) { @@ -37,9 +37,8 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - await session.update({ - userEmail: found.email, - }) + session.userEmail = found.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -56,9 +55,8 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + session.userEmail = user.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/e2e/vue-start/basic-auth/src/styles/app.css b/e2e/vue-start/basic-auth/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/e2e/vue-start/basic-auth/src/styles/app.css +++ b/e2e/vue-start/basic-auth/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-start/basic-auth/src/utils/posts.ts b/e2e/vue-start/basic-auth/src/utils/posts.ts index d72d7719a4..04dbccaa11 100644 --- a/e2e/vue-start/basic-auth/src/utils/posts.ts +++ b/e2e/vue-start/basic-auth/src/utils/posts.ts @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) + .validator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/e2e/vue-start/basic-auth/src/utils/session.ts b/e2e/vue-start/basic-auth/src/utils/session.ts index 7cf2a41792..7d078225a0 100644 --- a/e2e/vue-start/basic-auth/src/utils/session.ts +++ b/e2e/vue-start/basic-auth/src/utils/session.ts @@ -1,13 +1,25 @@ -// src/services/session.server.ts -import { useSession } from '@tanstack/vue-start/server' +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/vue-start/server' import type { User } from '~/prisma-generated/client' type SessionUser = { userEmail: User['email'] } -export function useAppSession() { - return useSession({ - password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', - }) +export function getAppSession() { + return getIronSession( + { read: getCookie, write: setCookie }, + { + cookieName: 'test-auth-session', + // This fixture only runs locally with test credentials. + password: 'local-e2e-only-session-password-at-least-32-characters', + ttl: 60 * 60, + cookieOptions: { + httpOnly: true, + secure: false, + sameSite: 'lax', + path: '/', + }, + }, + ) } diff --git a/e2e/vue-start/basic-auth/tsconfig.json b/e2e/vue-start/basic-auth/tsconfig.json index f9f5aab3da..390dad84c0 100644 --- a/e2e/vue-start/basic-auth/tsconfig.json +++ b/e2e/vue-start/basic-auth/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/basic-auth/vite.config.ts b/e2e/vue-start/basic-auth/vite.config.ts index 79edfc05c2..563e212077 100644 --- a/e2e/vue-start/basic-auth/vite.config.ts +++ b/e2e/vue-start/basic-auth/vite.config.ts @@ -1,19 +1,13 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - vue(), - vueJsx(), - ], + plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], }) diff --git a/e2e/vue-start/basic-cloudflare/.devcontainer/devcontainer.json b/e2e/vue-start/basic-cloudflare/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/basic-cloudflare/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/basic-cloudflare/package.json b/e2e/vue-start/basic-cloudflare/package.json index 1a6dd632ad..5ab77db8fc 100644 --- a/e2e/vue-start/basic-cloudflare/package.json +++ b/e2e/vue-start/basic-cloudflare/package.json @@ -9,8 +9,8 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "cf-typegen": "wrangler types", - "postinstall": "npm run cf-typegen", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen", + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -19,18 +19,27 @@ "vue": "^3.5.25" }, "devDependencies": { - "@cloudflare/vite-plugin": "^1.15.1", - "@playwright/test": "^1.50.1", - "@tailwindcss/postcss": "^4.1.15", + "@cloudflare/vite-plugin": "^1.29.0", + "@playwright/test": "^1.61.0", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "@vitejs/plugin-vue": "^6.0.3", - "@vitejs/plugin-vue-jsx": "^5.1.2", - "vite-tsconfig-paths": "^5.1.4", - "wrangler": "^4.49.1" + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "wrangler": "^4.74.0" + }, + "nx": { + "targets": { + "test:e2e": { + "outputs": [ + "...", + "{projectRoot}/.wrangler/deploy" + ] + } + } } } diff --git a/e2e/vue-start/basic-cloudflare/playwright.config.ts b/e2e/vue-start/basic-cloudflare/playwright.config.ts index a545dff891..0925936d55 100644 --- a/e2e/vue-start/basic-cloudflare/playwright.config.ts +++ b/e2e/vue-start/basic-cloudflare/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -14,9 +13,6 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -24,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-cloudflare/postcss.config.mjs b/e2e/vue-start/basic-cloudflare/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-start/basic-cloudflare/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx index e11970b600..0687372ae0 100644 --- a/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx @@ -1,53 +1,61 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error(error) - - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} +export const DefaultCatchBoundary = defineComponent({ + props: { + error: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + return () => { + console.error(props.error) + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/basic-cloudflare/src/routeTree.gen.ts b/e2e/vue-start/basic-cloudflare/src/routeTree.gen.ts index 30451e7ab7..c52a88360b 100644 --- a/e2e/vue-start/basic-cloudflare/src/routeTree.gen.ts +++ b/e2e/vue-start/basic-cloudflare/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as StaticRouteImport } from './routes/static' import { Route as IndexRouteImport } from './routes/index' +import { Route as StaticRouteImport } from './routes/static' -const StaticRoute = StaticRouteImport.update({ - id: '/static', - path: '/static', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const StaticRoute = StaticRouteImport.update({ + id: '/static', + path: '/static', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/static': { - id: '/static' - path: '/static' - fullPath: '/static' - preLoaderRoute: typeof StaticRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/static': { + id: '/static' + path: '/static' + fullPath: '/static' + preLoaderRoute: typeof StaticRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/vue-start/basic-cloudflare/src/routes/index.tsx b/e2e/vue-start/basic-cloudflare/src/routes/index.tsx index 1c708a7ec6..d3a020c7ad 100644 --- a/e2e/vue-start/basic-cloudflare/src/routes/index.tsx +++ b/e2e/vue-start/basic-cloudflare/src/routes/index.tsx @@ -1,7 +1,21 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' import { env } from 'cloudflare:workers' +const Home = defineComponent({ + setup() { + const data = Route.useLoaderData() + return () => ( +
+

Welcome Home!!!

+

{data.value.message}

+

{data.value.myVar}

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

Welcome Home!!!

-

{data.value.message}

-

{data.value.myVar}

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

Static Page

+

The value is {data.value.myVar}

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

Static Page

-

The value is {data.value.myVar}

-
- ) -} diff --git a/e2e/vue-start/basic-cloudflare/src/styles/app.css b/e2e/vue-start/basic-cloudflare/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/e2e/vue-start/basic-cloudflare/src/styles/app.css +++ b/e2e/vue-start/basic-cloudflare/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts b/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts b/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/basic-cloudflare/tsconfig.json b/e2e/vue-start/basic-cloudflare/tsconfig.json index 8bf3d33789..572d840872 100644 --- a/e2e/vue-start/basic-cloudflare/tsconfig.json +++ b/e2e/vue-start/basic-cloudflare/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/basic-cloudflare/vite.config.ts b/e2e/vue-start/basic-cloudflare/vite.config.ts index d1cd20b407..1ee9e68614 100644 --- a/e2e/vue-start/basic-cloudflare/vite.config.ts +++ b/e2e/vue-start/basic-cloudflare/vite.config.ts @@ -1,18 +1,17 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import { cloudflare } from '@cloudflare/vite-plugin' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + resolve: { tsconfigPaths: true }, server: { port: 3000, }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), + tailwindcss(), cloudflare({ viteEnvironment: { name: 'ssr' }, inspectorPort: false }), tanstackStart({ prerender: { diff --git a/e2e/vue-start/basic-cloudflare/worker-configuration.d.ts b/e2e/vue-start/basic-cloudflare/worker-configuration.d.ts index b0b47f3946..f7a8f16397 100644 --- a/e2e/vue-start/basic-cloudflare/worker-configuration.d.ts +++ b/e2e/vue-start/basic-cloudflare/worker-configuration.d.ts @@ -1,6 +1,6 @@ /* eslint-disable */ // Generated by Wrangler by running `wrangler types` (hash: b11df627d8b3c51b1bf3230a546b0f20) -// Runtime types generated with workerd@1.20251118.0 2025-09-24 nodejs_compat +// Runtime types generated with workerd@1.20260317.1 2025-09-24 nodejs_compat declare namespace Cloudflare { interface Env { MY_VAR: "Hello from Cloudflare"; @@ -31,70 +31,70 @@ and limitations under the License. ***************************************************************************** */ /* eslint-disable */ // noinspection JSUnusedGlobalSymbols -declare var onmessage: never +declare var onmessage: never; /** * The **`DOMException`** interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) */ declare class DOMException extends Error { - constructor(message?: string, name?: string) - /** - * The **`message`** read-only property of the a message or description associated with the given error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) - */ - readonly message: string - /** - * The **`name`** read-only property of the one of the strings associated with an error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) - */ - readonly name: string - /** - * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) - */ - readonly code: number - static readonly INDEX_SIZE_ERR: number - static readonly DOMSTRING_SIZE_ERR: number - static readonly HIERARCHY_REQUEST_ERR: number - static readonly WRONG_DOCUMENT_ERR: number - static readonly INVALID_CHARACTER_ERR: number - static readonly NO_DATA_ALLOWED_ERR: number - static readonly NO_MODIFICATION_ALLOWED_ERR: number - static readonly NOT_FOUND_ERR: number - static readonly NOT_SUPPORTED_ERR: number - static readonly INUSE_ATTRIBUTE_ERR: number - static readonly INVALID_STATE_ERR: number - static readonly SYNTAX_ERR: number - static readonly INVALID_MODIFICATION_ERR: number - static readonly NAMESPACE_ERR: number - static readonly INVALID_ACCESS_ERR: number - static readonly VALIDATION_ERR: number - static readonly TYPE_MISMATCH_ERR: number - static readonly SECURITY_ERR: number - static readonly NETWORK_ERR: number - static readonly ABORT_ERR: number - static readonly URL_MISMATCH_ERR: number - static readonly QUOTA_EXCEEDED_ERR: number - static readonly TIMEOUT_ERR: number - static readonly INVALID_NODE_TYPE_ERR: number - static readonly DATA_CLONE_ERR: number - get stack(): any - set stack(value: any) + constructor(message?: string, name?: string); + /** + * The **`message`** read-only property of the a message or description associated with the given error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) + */ + readonly message: string; + /** + * The **`name`** read-only property of the one of the strings associated with an error name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) + */ + readonly name: string; + /** + * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; + get stack(): any; + set stack(value: any); } type WorkerGlobalScopeEventMap = { - fetch: FetchEvent - scheduled: ScheduledEvent - queue: QueueEvent - unhandledrejection: PromiseRejectionEvent - rejectionhandled: PromiseRejectionEvent -} + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; declare abstract class WorkerGlobalScope extends EventTarget { - EventTarget: typeof EventTarget + EventTarget: typeof EventTarget; } /* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). @@ -102,204 +102,186 @@ declare abstract class WorkerGlobalScope extends EventTarget - type Imports = Record - type ExportValue = Function | Global | Memory | Table - type Exports = Record - class Instance { - constructor(module: Module, imports?: Imports) - readonly exports: Exports - } - interface MemoryDescriptor { - initial: number - maximum?: number - shared?: boolean - } - class Memory { - constructor(descriptor: MemoryDescriptor) - readonly buffer: ArrayBuffer - grow(delta: number): number - } - type ImportExportKind = 'function' | 'global' | 'memory' | 'table' - interface ModuleExportDescriptor { - kind: ImportExportKind - name: string - } - interface ModuleImportDescriptor { - kind: ImportExportKind - module: string - name: string - } - abstract class Module { - static customSections(module: Module, sectionName: string): ArrayBuffer[] - static exports(module: Module): ModuleExportDescriptor[] - static imports(module: Module): ModuleImportDescriptor[] - } - type TableKind = 'anyfunc' | 'externref' - interface TableDescriptor { - element: TableKind - initial: number - maximum?: number - } - class Table { - constructor(descriptor: TableDescriptor, value?: any) - readonly length: number - get(index: number): any - grow(delta: number, value?: any): number - set(index: number, value?: any): void - } - function instantiate(module: Module, imports?: Imports): Promise - function validate(bytes: BufferSource): boolean + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; } /** * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. @@ -308,452 +290,311 @@ declare namespace WebAssembly { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) */ interface ServiceWorkerGlobalScope extends WorkerGlobalScope { - DOMException: typeof DOMException - WorkerGlobalScope: typeof WorkerGlobalScope - btoa(data: string): string - atob(data: string): string - setTimeout(callback: (...args: any[]) => void, msDelay?: number): number - setTimeout( - callback: (...args: Args) => void, - msDelay?: number, - ...args: Args - ): number - clearTimeout(timeoutId: number | null): void - setInterval(callback: (...args: any[]) => void, msDelay?: number): number - setInterval( - callback: (...args: Args) => void, - msDelay?: number, - ...args: Args - ): number - clearInterval(timeoutId: number | null): void - queueMicrotask(task: Function): void - structuredClone(value: T, options?: StructuredSerializeOptions): T - reportError(error: any): void - fetch( - input: RequestInfo | URL, - init?: RequestInit, - ): Promise - self: ServiceWorkerGlobalScope - crypto: Crypto - caches: CacheStorage - scheduler: Scheduler - performance: Performance - Cloudflare: Cloudflare - readonly origin: string - Event: typeof Event - ExtendableEvent: typeof ExtendableEvent - CustomEvent: typeof CustomEvent - PromiseRejectionEvent: typeof PromiseRejectionEvent - FetchEvent: typeof FetchEvent - TailEvent: typeof TailEvent - TraceEvent: typeof TailEvent - ScheduledEvent: typeof ScheduledEvent - MessageEvent: typeof MessageEvent - CloseEvent: typeof CloseEvent - ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader - ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader - ReadableStream: typeof ReadableStream - WritableStream: typeof WritableStream - WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter - TransformStream: typeof TransformStream - ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy - CountQueuingStrategy: typeof CountQueuingStrategy - ErrorEvent: typeof ErrorEvent - MessageChannel: typeof MessageChannel - MessagePort: typeof MessagePort - EventSource: typeof EventSource - ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest - ReadableStreamDefaultController: typeof ReadableStreamDefaultController - ReadableByteStreamController: typeof ReadableByteStreamController - WritableStreamDefaultController: typeof WritableStreamDefaultController - TransformStreamDefaultController: typeof TransformStreamDefaultController - CompressionStream: typeof CompressionStream - DecompressionStream: typeof DecompressionStream - TextEncoderStream: typeof TextEncoderStream - TextDecoderStream: typeof TextDecoderStream - Headers: typeof Headers - Body: typeof Body - Request: typeof Request - Response: typeof Response - WebSocket: typeof WebSocket - WebSocketPair: typeof WebSocketPair - WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair - AbortController: typeof AbortController - AbortSignal: typeof AbortSignal - TextDecoder: typeof TextDecoder - TextEncoder: typeof TextEncoder - navigator: Navigator - Navigator: typeof Navigator - URL: typeof URL - URLSearchParams: typeof URLSearchParams - URLPattern: typeof URLPattern - Blob: typeof Blob - File: typeof File - FormData: typeof FormData - Crypto: typeof Crypto - SubtleCrypto: typeof SubtleCrypto - CryptoKey: typeof CryptoKey - CacheStorage: typeof CacheStorage - Cache: typeof Cache - FixedLengthStream: typeof FixedLengthStream - IdentityTransformStream: typeof IdentityTransformStream - HTMLRewriter: typeof HTMLRewriter + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + Cloudflare: Cloudflare; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + MessageChannel: typeof MessageChannel; + MessagePort: typeof MessagePort; + EventSource: typeof EventSource; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + TransformStreamDefaultController: typeof TransformStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; } -declare function addEventListener( - type: Type, - handler: EventListenerOrEventListenerObject, - options?: EventTargetAddEventListenerOptions | boolean, -): void -declare function removeEventListener< - Type extends keyof WorkerGlobalScopeEventMap, ->( - type: Type, - handler: EventListenerOrEventListenerObject, - options?: EventTargetEventListenerOptions | boolean, -): void +declare function addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; +declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; /** * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) */ -declare function dispatchEvent( - event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap], -): boolean +declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ -declare function btoa(data: string): string +declare function btoa(data: string): string; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ -declare function atob(data: string): string +declare function atob(data: string): string; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout( - callback: (...args: any[]) => void, - msDelay?: number, -): number +declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout( - callback: (...args: Args) => void, - msDelay?: number, - ...args: Args -): number +declare function setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ -declare function clearTimeout(timeoutId: number | null): void +declare function clearTimeout(timeoutId: number | null): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval( - callback: (...args: any[]) => void, - msDelay?: number, -): number +declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval( - callback: (...args: Args) => void, - msDelay?: number, - ...args: Args -): number +declare function setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ -declare function clearInterval(timeoutId: number | null): void +declare function clearInterval(timeoutId: number | null): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ -declare function queueMicrotask(task: Function): void +declare function queueMicrotask(task: Function): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ -declare function structuredClone( - value: T, - options?: StructuredSerializeOptions, -): T +declare function structuredClone(value: T, options?: StructuredSerializeOptions): T; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ -declare function reportError(error: any): void +declare function reportError(error: any): void; /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ -declare function fetch( - input: RequestInfo | URL, - init?: RequestInit, -): Promise -declare const self: ServiceWorkerGlobalScope +declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; +declare const self: ServiceWorkerGlobalScope; /** - * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. - * The Workers runtime implements the full surface of this API, but with some differences in - * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) - * compared to those implemented in most browsers. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) - */ -declare const crypto: Crypto +* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. +* The Workers runtime implements the full surface of this API, but with some differences in +* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) +* compared to those implemented in most browsers. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) +*/ +declare const crypto: Crypto; /** - * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) - */ -declare const caches: CacheStorage -declare const scheduler: Scheduler +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ +declare const caches: CacheStorage; +declare const scheduler: Scheduler; /** - * The Workers runtime supports a subset of the Performance API, used to measure timing and performance, - * as well as timing of subrequests and other operations. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) - */ -declare const performance: Performance -declare const Cloudflare: Cloudflare -declare const origin: string -declare const navigator: Navigator -interface TestController {} -interface ExecutionContext { - waitUntil(promise: Promise): void - passThroughOnException(): void - readonly props: Props +* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, +* as well as timing of subrequests and other operations. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) +*/ +declare const performance: Performance; +declare const Cloudflare: Cloudflare; +declare const origin: string; +declare const navigator: Navigator; +interface TestController { } -type ExportedHandlerFetchHandler = ( - request: Request>, - env: Env, - ctx: ExecutionContext, -) => Response | Promise -type ExportedHandlerTailHandler = ( - events: TraceItem[], - env: Env, - ctx: ExecutionContext, -) => void | Promise -type ExportedHandlerTraceHandler = ( - traces: TraceItem[], - env: Env, - ctx: ExecutionContext, -) => void | Promise -type ExportedHandlerTailStreamHandler = ( - event: TailStream.TailEvent, - env: Env, - ctx: ExecutionContext, -) => TailStream.TailEventHandlerType | Promise -type ExportedHandlerScheduledHandler = ( - controller: ScheduledController, - env: Env, - ctx: ExecutionContext, -) => void | Promise -type ExportedHandlerQueueHandler = ( - batch: MessageBatch, - env: Env, - ctx: ExecutionContext, -) => void | Promise -type ExportedHandlerTestHandler = ( - controller: TestController, - env: Env, - ctx: ExecutionContext, -) => void | Promise -interface ExportedHandler< - Env = unknown, - QueueHandlerMessage = unknown, - CfHostMetadata = unknown, -> { - fetch?: ExportedHandlerFetchHandler - tail?: ExportedHandlerTailHandler - trace?: ExportedHandlerTraceHandler - tailStream?: ExportedHandlerTailStreamHandler - scheduled?: ExportedHandlerScheduledHandler - test?: ExportedHandlerTestHandler - email?: EmailExportedHandler - queue?: ExportedHandlerQueueHandler +interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; + readonly props: Props; +} +type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; +type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; +type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; +interface ExportedHandler { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; } interface StructuredSerializeOptions { - transfer?: any[] + transfer?: any[]; } declare abstract class Navigator { - sendBeacon(url: string, body?: BodyInit): boolean - readonly userAgent: string - readonly hardwareConcurrency: number - readonly language: string - readonly languages: string[] + sendBeacon(url: string, body?: BodyInit): boolean; + readonly userAgent: string; + readonly hardwareConcurrency: number; + readonly language: string; + readonly languages: string[]; } interface AlarmInvocationInfo { - readonly isRetry: boolean - readonly retryCount: number + readonly isRetry: boolean; + readonly retryCount: number; } interface Cloudflare { - readonly compatibilityFlags: Record + readonly compatibilityFlags: Record; } interface DurableObject { - fetch(request: Request): Response | Promise - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise - webSocketMessage?( - ws: WebSocket, - message: string | ArrayBuffer, - ): void | Promise - webSocketClose?( - ws: WebSocket, - code: number, - reason: string, - wasClean: boolean, - ): void | Promise - webSocketError?(ws: WebSocket, error: unknown): void | Promise -} -type DurableObjectStub< - T extends Rpc.DurableObjectBranded | undefined = undefined, -> = Fetcher< - T, - 'alarm' | 'webSocketMessage' | 'webSocketClose' | 'webSocketError' -> & { - readonly id: DurableObjectId - readonly name?: string + fetch(request: Request): Response | Promise; + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; + webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; + webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; } +type DurableObjectStub = Fetcher & { + readonly id: DurableObjectId; + readonly name?: string; +}; interface DurableObjectId { - toString(): string - equals(other: DurableObjectId): boolean - readonly name?: string + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; } -declare abstract class DurableObjectNamespace< - T extends Rpc.DurableObjectBranded | undefined = undefined, -> { - newUniqueId( - options?: DurableObjectNamespaceNewUniqueIdOptions, - ): DurableObjectId - idFromName(name: string): DurableObjectId - idFromString(id: string): DurableObjectId - get( - id: DurableObjectId, - options?: DurableObjectNamespaceGetDurableObjectOptions, - ): DurableObjectStub - getByName( - name: string, - options?: DurableObjectNamespaceGetDurableObjectOptions, - ): DurableObjectStub - jurisdiction( - jurisdiction: DurableObjectJurisdiction, - ): DurableObjectNamespace +declare abstract class DurableObjectNamespace { + newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; + getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; } -type DurableObjectJurisdiction = 'eu' | 'fedramp' | 'fedramp-high' +type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; interface DurableObjectNamespaceNewUniqueIdOptions { - jurisdiction?: DurableObjectJurisdiction + jurisdiction?: DurableObjectJurisdiction; } -type DurableObjectLocationHint = - | 'wnam' - | 'enam' - | 'sam' - | 'weur' - | 'eeur' - | 'apac' - | 'oc' - | 'afr' - | 'me' +type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; +type DurableObjectRoutingMode = "primary-only"; interface DurableObjectNamespaceGetDurableObjectOptions { - locationHint?: DurableObjectLocationHint + locationHint?: DurableObjectLocationHint; + routingMode?: DurableObjectRoutingMode; +} +interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { } -interface DurableObjectClass< - _T extends Rpc.DurableObjectBranded | undefined = undefined, -> {} interface DurableObjectState { - waitUntil(promise: Promise): void - readonly props: Props - readonly id: DurableObjectId - readonly storage: DurableObjectStorage - container?: Container - blockConcurrencyWhile(callback: () => Promise): Promise - acceptWebSocket(ws: WebSocket, tags?: string[]): void - getWebSockets(tag?: string): WebSocket[] - setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void - getWebSocketAutoResponse(): WebSocketRequestResponsePair | null - getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null - setHibernatableWebSocketEventTimeout(timeoutMs?: number): void - getHibernatableWebSocketEventTimeout(): number | null - getTags(ws: WebSocket): string[] - abort(reason?: string): void + waitUntil(promise: Promise): void; + readonly props: Props; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + container?: Container; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; + abort(reason?: string): void; } interface DurableObjectTransaction { - get( - key: string, - options?: DurableObjectGetOptions, - ): Promise - get( - keys: string[], - options?: DurableObjectGetOptions, - ): Promise> - list(options?: DurableObjectListOptions): Promise> - put( - key: string, - value: T, - options?: DurableObjectPutOptions, - ): Promise - put( - entries: Record, - options?: DurableObjectPutOptions, - ): Promise - delete(key: string, options?: DurableObjectPutOptions): Promise - delete(keys: string[], options?: DurableObjectPutOptions): Promise - rollback(): void - getAlarm(options?: DurableObjectGetAlarmOptions): Promise - setAlarm( - scheduledTime: number | Date, - options?: DurableObjectSetAlarmOptions, - ): Promise - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; } interface DurableObjectStorage { - get( - key: string, - options?: DurableObjectGetOptions, - ): Promise - get( - keys: string[], - options?: DurableObjectGetOptions, - ): Promise> - list(options?: DurableObjectListOptions): Promise> - put( - key: string, - value: T, - options?: DurableObjectPutOptions, - ): Promise - put( - entries: Record, - options?: DurableObjectPutOptions, - ): Promise - delete(key: string, options?: DurableObjectPutOptions): Promise - delete(keys: string[], options?: DurableObjectPutOptions): Promise - deleteAll(options?: DurableObjectPutOptions): Promise - transaction( - closure: (txn: DurableObjectTransaction) => Promise, - ): Promise - getAlarm(options?: DurableObjectGetAlarmOptions): Promise - setAlarm( - scheduledTime: number | Date, - options?: DurableObjectSetAlarmOptions, - ): Promise - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise - sync(): Promise - sql: SqlStorage - kv: SyncKvStorage - transactionSync(closure: () => T): T - getCurrentBookmark(): Promise - getBookmarkForTime(timestamp: number | Date): Promise - onNextSessionRestoreBookmark(bookmark: string): Promise + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + sql: SqlStorage; + kv: SyncKvStorage; + transactionSync(closure: () => T): T; + getCurrentBookmark(): Promise; + getBookmarkForTime(timestamp: number | Date): Promise; + onNextSessionRestoreBookmark(bookmark: string): Promise; } interface DurableObjectListOptions { - start?: string - startAfter?: string - end?: string - prefix?: string - reverse?: boolean - limit?: number - allowConcurrency?: boolean - noCache?: boolean + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; } interface DurableObjectGetOptions { - allowConcurrency?: boolean - noCache?: boolean + allowConcurrency?: boolean; + noCache?: boolean; } interface DurableObjectGetAlarmOptions { - allowConcurrency?: boolean + allowConcurrency?: boolean; } interface DurableObjectPutOptions { - allowConcurrency?: boolean - allowUnconfirmed?: boolean - noCache?: boolean + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; } interface DurableObjectSetAlarmOptions { - allowConcurrency?: boolean - allowUnconfirmed?: boolean + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; } declare class WebSocketRequestResponsePair { - constructor(request: string, response: string) - get request(): string - get response(): string + constructor(request: string, response: string); + get request(): string; + get response(): string; } interface AnalyticsEngineDataset { - writeDataPoint(event?: AnalyticsEngineDataPoint): void + writeDataPoint(event?: AnalyticsEngineDataPoint): void; } interface AnalyticsEngineDataPoint { - indexes?: ((ArrayBuffer | string) | null)[] - doubles?: number[] - blobs?: ((ArrayBuffer | string) | null)[] + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; } /** * The **`Event`** interface represents an event which takes place on an `EventTarget`. @@ -761,183 +602,171 @@ interface AnalyticsEngineDataPoint { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) */ declare class Event { - constructor(type: string, init?: EventInit) - /** - * The **`type`** read-only property of the Event interface returns a string containing the event's type. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) - */ - get type(): string - /** - * The **`eventPhase`** read-only property of the being evaluated. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) - */ - get eventPhase(): number - /** - * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) - */ - get composed(): boolean - /** - * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) - */ - get bubbles(): boolean - /** - * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) - */ - get cancelable(): boolean - /** - * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) - */ - get defaultPrevented(): boolean - /** - * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) - */ - get returnValue(): boolean - /** - * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) - */ - get currentTarget(): EventTarget | undefined - /** - * The read-only **`target`** property of the dispatched. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) - */ - get target(): EventTarget | undefined - /** - * The deprecated **`Event.srcElement`** is an alias for the Event.target property. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) - */ - get srcElement(): EventTarget | undefined - /** - * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) - */ - get timeStamp(): number - /** - * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) - */ - get isTrusted(): boolean - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - get cancelBubble(): boolean - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - set cancelBubble(value: boolean) - /** - * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) - */ - stopImmediatePropagation(): void - /** - * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) - */ - preventDefault(): void - /** - * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) - */ - stopPropagation(): void - /** - * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) - */ - composedPath(): EventTarget[] - static readonly NONE: number - static readonly CAPTURING_PHASE: number - static readonly AT_TARGET: number - static readonly BUBBLING_PHASE: number + constructor(type: string, init?: EventInit); + /** + * The **`type`** read-only property of the Event interface returns a string containing the event's type. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * The **`eventPhase`** read-only property of the being evaluated. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * The read-only **`target`** property of the dispatched. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) + */ + get target(): EventTarget | undefined; + /** + * The deprecated **`Event.srcElement`** is an alias for the Event.target property. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * The **`cancelBubble`** property of the Event interface is deprecated. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * The **`cancelBubble`** property of the Event interface is deprecated. + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; } interface EventInit { - bubbles?: boolean - cancelable?: boolean - composed?: boolean + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; } -type EventListener = (event: EventType) => void +type EventListener = (event: EventType) => void; interface EventListenerObject { - handleEvent(event: EventType): void + handleEvent(event: EventType): void; } -type EventListenerOrEventListenerObject = - | EventListener - | EventListenerObject +type EventListenerOrEventListenerObject = EventListener | EventListenerObject; /** * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) */ -declare class EventTarget< - EventMap extends Record = Record, -> { - constructor() - /** - * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) - */ - addEventListener( - type: Type, - handler: EventListenerOrEventListenerObject, - options?: EventTargetAddEventListenerOptions | boolean, - ): void - /** - * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) - */ - removeEventListener( - type: Type, - handler: EventListenerOrEventListenerObject, - options?: EventTargetEventListenerOptions | boolean, - ): void - /** - * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) - */ - dispatchEvent(event: EventMap[keyof EventMap]): boolean +declare class EventTarget = Record> { + constructor(); + /** + * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; + /** + * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; + /** + * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; } interface EventTargetEventListenerOptions { - capture?: boolean + capture?: boolean; } interface EventTargetAddEventListenerOptions { - capture?: boolean - passive?: boolean - once?: boolean - signal?: AbortSignal + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; } interface EventTargetHandlerObject { - handleEvent: (event: Event) => any | undefined + handleEvent: (event: Event) => any | undefined; } /** * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. @@ -945,19 +774,19 @@ interface EventTargetHandlerObject { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) */ declare class AbortController { - constructor() - /** - * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) - */ - get signal(): AbortSignal - /** - * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) - */ - abort(reason?: any): void + constructor(); + /** + * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get signal(): AbortSignal; + /** + * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; } /** * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. @@ -965,52 +794,52 @@ declare class AbortController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) */ declare abstract class AbortSignal extends EventTarget { - /** - * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) - */ - static abort(reason?: any): AbortSignal - /** - * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) - */ - static timeout(delay: number): AbortSignal - /** - * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) - */ - static any(signals: AbortSignal[]): AbortSignal - /** - * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) - */ - get aborted(): boolean - /** - * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) - */ - get reason(): any - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - get onabort(): any | null - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - set onabort(value: any | null) - /** - * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) - */ - throwIfAborted(): void + /** + * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) + */ + static abort(reason?: any): AbortSignal; + /** + * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) + */ + static timeout(delay: number): AbortSignal; + /** + * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) + */ + static any(signals: AbortSignal[]): AbortSignal; + /** + * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /** + * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) + */ + get reason(): any; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /** + * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) + */ + throwIfAborted(): void; } interface Scheduler { - wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; } interface SchedulerWaitOptions { - signal?: AbortSignal + signal?: AbortSignal; } /** * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. @@ -1018,12 +847,12 @@ interface SchedulerWaitOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) */ declare abstract class ExtendableEvent extends Event { - /** - * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) - */ - waitUntil(promise: Promise): void + /** + * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) + */ + waitUntil(promise: Promise): void; } /** * The **`CustomEvent`** interface represents events initialized by an application for any purpose. @@ -1031,19 +860,19 @@ declare abstract class ExtendableEvent extends Event { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) */ declare class CustomEvent extends Event { - constructor(type: string, init?: CustomEventCustomEventInit) - /** - * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) - */ - get detail(): T + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; } interface CustomEventCustomEventInit { - bubbles?: boolean - cancelable?: boolean - composed?: boolean - detail?: any + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; } /** * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. @@ -1051,55 +880,52 @@ interface CustomEventCustomEventInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) */ declare class Blob { - constructor( - type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], - options?: BlobOptions, - ) - /** - * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) - */ - get size(): number - /** - * The **`type`** read-only property of the Blob interface returns the MIME type of the file. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) - */ - get type(): string - /** - * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) - */ - slice(start?: number, end?: number, type?: string): Blob - /** - * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) - */ - arrayBuffer(): Promise - /** - * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) - */ - bytes(): Promise - /** - * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) - */ - text(): Promise - /** - * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) - */ - stream(): ReadableStream + constructor(type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); + /** + * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) + */ + get size(): number; + /** + * The **`type`** read-only property of the Blob interface returns the MIME type of the file. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) + */ + get type(): string; + /** + * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) + */ + arrayBuffer(): Promise; + /** + * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) + */ + bytes(): Promise; + /** + * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) + */ + text(): Promise; + /** + * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) + */ + stream(): ReadableStream; } interface BlobOptions { - type?: string + type?: string; } /** * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. @@ -1107,104 +933,84 @@ interface BlobOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) */ declare class File extends Blob { - constructor( - bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, - name: string, - options?: FileOptions, - ) - /** - * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) - */ - get name(): string - /** - * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) - */ - get lastModified(): number + constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions); + /** + * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) + */ + get name(): string; + /** + * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) + */ + get lastModified(): number; } interface FileOptions { - type?: string - lastModified?: number + type?: string; + lastModified?: number; } /** - * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) - */ +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ declare abstract class CacheStorage { - /** - * The **`open()`** method of the the Cache object matching the `cacheName`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) - */ - open(cacheName: string): Promise - readonly default: Cache + /** + * The **`open()`** method of the the Cache object matching the `cacheName`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) + */ + open(cacheName: string): Promise; + readonly default: Cache; } /** - * The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) - */ +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ declare abstract class Cache { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ - delete( - request: RequestInfo | URL, - options?: CacheQueryOptions, - ): Promise - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ - match( - request: RequestInfo | URL, - options?: CacheQueryOptions, - ): Promise - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ - put(request: RequestInfo | URL, response: Response): Promise + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ + delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ + match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ + put(request: RequestInfo | URL, response: Response): Promise; } interface CacheQueryOptions { - ignoreMethod?: boolean + ignoreMethod?: boolean; } /** - * The Web Crypto API provides a set of low-level functions for common cryptographic tasks. - * The Workers runtime implements the full surface of this API, but with some differences in - * the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) - * compared to those implemented in most browsers. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) - */ +* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. +* The Workers runtime implements the full surface of this API, but with some differences in +* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) +* compared to those implemented in most browsers. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) +*/ declare abstract class Crypto { - /** - * The **`Crypto.subtle`** read-only property returns a cryptographic operations. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) - */ - get subtle(): SubtleCrypto - /** - * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) - */ - getRandomValues< - T extends - | Int8Array - | Uint8Array - | Int16Array - | Uint16Array - | Int32Array - | Uint32Array - | BigInt64Array - | BigUint64Array, - >(buffer: T): T - /** - * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) - */ - randomUUID(): string - DigestStream: typeof DigestStream + /** + * The **`Crypto.subtle`** read-only property returns a cryptographic operations. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /** + * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) + */ + getRandomValues(buffer: T): T; + /** + * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; } /** * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. @@ -1213,135 +1019,79 @@ declare abstract class Crypto { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) */ declare abstract class SubtleCrypto { - /** - * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) - */ - encrypt( - algorithm: string | SubtleCryptoEncryptAlgorithm, - key: CryptoKey, - plainText: ArrayBuffer | ArrayBufferView, - ): Promise - /** - * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) - */ - decrypt( - algorithm: string | SubtleCryptoEncryptAlgorithm, - key: CryptoKey, - cipherText: ArrayBuffer | ArrayBufferView, - ): Promise - /** - * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) - */ - sign( - algorithm: string | SubtleCryptoSignAlgorithm, - key: CryptoKey, - data: ArrayBuffer | ArrayBufferView, - ): Promise - /** - * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) - */ - verify( - algorithm: string | SubtleCryptoSignAlgorithm, - key: CryptoKey, - signature: ArrayBuffer | ArrayBufferView, - data: ArrayBuffer | ArrayBufferView, - ): Promise - /** - * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) - */ - digest( - algorithm: string | SubtleCryptoHashAlgorithm, - data: ArrayBuffer | ArrayBufferView, - ): Promise - /** - * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) - */ - generateKey( - algorithm: string | SubtleCryptoGenerateKeyAlgorithm, - extractable: boolean, - keyUsages: string[], - ): Promise - /** - * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) - */ - deriveKey( - algorithm: string | SubtleCryptoDeriveKeyAlgorithm, - baseKey: CryptoKey, - derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, - extractable: boolean, - keyUsages: string[], - ): Promise - /** - * The **`deriveBits()`** method of the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) - */ - deriveBits( - algorithm: string | SubtleCryptoDeriveKeyAlgorithm, - baseKey: CryptoKey, - length?: number | null, - ): Promise - /** - * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) - */ - importKey( - format: string, - keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, - algorithm: string | SubtleCryptoImportKeyAlgorithm, - extractable: boolean, - keyUsages: string[], - ): Promise - /** - * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) - */ - exportKey(format: string, key: CryptoKey): Promise - /** - * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) - */ - wrapKey( - format: string, - key: CryptoKey, - wrappingKey: CryptoKey, - wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, - ): Promise - /** - * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) - */ - unwrapKey( - format: string, - wrappedKey: ArrayBuffer | ArrayBufferView, - unwrappingKey: CryptoKey, - unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, - unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, - extractable: boolean, - keyUsages: string[], - ): Promise - timingSafeEqual( - a: ArrayBuffer | ArrayBufferView, - b: ArrayBuffer | ArrayBufferView, - ): boolean + /** + * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) + */ + encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) + */ + decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) + */ + sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) + */ + verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) + */ + digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; + /** + * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) + */ + generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /** + * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) + */ + deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /** + * The **`deriveBits()`** method of the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) + */ + deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise; + /** + * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) + */ + importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /** + * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) + */ + exportKey(format: string, key: CryptoKey): Promise; + /** + * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) + */ + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise; + /** + * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) + */ + unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; } /** * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey. @@ -1350,141 +1100,133 @@ declare abstract class SubtleCrypto { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) */ declare abstract class CryptoKey { - /** - * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) - */ - readonly type: string - /** - * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) - */ - readonly extractable: boolean - /** - * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) - */ - readonly algorithm: - | CryptoKeyKeyAlgorithm - | CryptoKeyAesKeyAlgorithm - | CryptoKeyHmacKeyAlgorithm - | CryptoKeyRsaKeyAlgorithm - | CryptoKeyEllipticKeyAlgorithm - | CryptoKeyArbitraryKeyAlgorithm - /** - * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) - */ - readonly usages: string[] + /** + * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) + */ + readonly type: string; + /** + * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) + */ + readonly extractable: boolean; + /** + * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) + */ + readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; + /** + * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) + */ + readonly usages: string[]; } interface CryptoKeyPair { - publicKey: CryptoKey - privateKey: CryptoKey + publicKey: CryptoKey; + privateKey: CryptoKey; } interface JsonWebKey { - kty: string - use?: string - key_ops?: string[] - alg?: string - ext?: boolean - crv?: string - x?: string - y?: string - d?: string - n?: string - e?: string - p?: string - q?: string - dp?: string - dq?: string - qi?: string - oth?: RsaOtherPrimesInfo[] - k?: string + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; } interface RsaOtherPrimesInfo { - r?: string - d?: string - t?: string + r?: string; + d?: string; + t?: string; } interface SubtleCryptoDeriveKeyAlgorithm { - name: string - salt?: ArrayBuffer | ArrayBufferView - iterations?: number - hash?: string | SubtleCryptoHashAlgorithm - $public?: CryptoKey - info?: ArrayBuffer | ArrayBufferView + name: string; + salt?: (ArrayBuffer | ArrayBufferView); + iterations?: number; + hash?: (string | SubtleCryptoHashAlgorithm); + $public?: CryptoKey; + info?: (ArrayBuffer | ArrayBufferView); } interface SubtleCryptoEncryptAlgorithm { - name: string - iv?: ArrayBuffer | ArrayBufferView - additionalData?: ArrayBuffer | ArrayBufferView - tagLength?: number - counter?: ArrayBuffer | ArrayBufferView - length?: number - label?: ArrayBuffer | ArrayBufferView + name: string; + iv?: (ArrayBuffer | ArrayBufferView); + additionalData?: (ArrayBuffer | ArrayBufferView); + tagLength?: number; + counter?: (ArrayBuffer | ArrayBufferView); + length?: number; + label?: (ArrayBuffer | ArrayBufferView); } interface SubtleCryptoGenerateKeyAlgorithm { - name: string - hash?: string | SubtleCryptoHashAlgorithm - modulusLength?: number - publicExponent?: ArrayBuffer | ArrayBufferView - length?: number - namedCurve?: string + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + modulusLength?: number; + publicExponent?: (ArrayBuffer | ArrayBufferView); + length?: number; + namedCurve?: string; } interface SubtleCryptoHashAlgorithm { - name: string + name: string; } interface SubtleCryptoImportKeyAlgorithm { - name: string - hash?: string | SubtleCryptoHashAlgorithm - length?: number - namedCurve?: string - compressed?: boolean + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + length?: number; + namedCurve?: string; + compressed?: boolean; } interface SubtleCryptoSignAlgorithm { - name: string - hash?: string | SubtleCryptoHashAlgorithm - dataLength?: number - saltLength?: number + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + dataLength?: number; + saltLength?: number; } interface CryptoKeyKeyAlgorithm { - name: string + name: string; } interface CryptoKeyAesKeyAlgorithm { - name: string - length: number + name: string; + length: number; } interface CryptoKeyHmacKeyAlgorithm { - name: string - hash: CryptoKeyKeyAlgorithm - length: number + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; } interface CryptoKeyRsaKeyAlgorithm { - name: string - modulusLength: number - publicExponent: ArrayBuffer | ArrayBufferView - hash?: CryptoKeyKeyAlgorithm + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | ArrayBufferView; + hash?: CryptoKeyKeyAlgorithm; } interface CryptoKeyEllipticKeyAlgorithm { - name: string - namedCurve: string + name: string; + namedCurve: string; } interface CryptoKeyArbitraryKeyAlgorithm { - name: string - hash?: CryptoKeyKeyAlgorithm - namedCurve?: string - length?: number + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; } -declare class DigestStream extends WritableStream< - ArrayBuffer | ArrayBufferView -> { - constructor(algorithm: string | SubtleCryptoHashAlgorithm) - readonly digest: Promise - get bytesWritten(): number | bigint +declare class DigestStream extends WritableStream { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise; + get bytesWritten(): number | bigint; } /** * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. @@ -1492,19 +1234,16 @@ declare class DigestStream extends WritableStream< * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) */ declare class TextDecoder { - constructor(label?: string, options?: TextDecoderConstructorOptions) - /** - * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) - */ - decode( - input?: ArrayBuffer | ArrayBufferView, - options?: TextDecoderDecodeOptions, - ): string - get encoding(): string - get fatal(): boolean - get ignoreBOM(): boolean + constructor(label?: string, options?: TextDecoderConstructorOptions); + /** + * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; } /** * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. @@ -1512,31 +1251,31 @@ declare class TextDecoder { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) */ declare class TextEncoder { - constructor() - /** - * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) - */ - encode(input?: string): Uint8Array - /** - * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) - */ - encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult - get encoding(): string + constructor(); + /** + * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult; + get encoding(): string; } interface TextDecoderConstructorOptions { - fatal: boolean - ignoreBOM: boolean + fatal: boolean; + ignoreBOM: boolean; } interface TextDecoderDecodeOptions { - stream: boolean + stream: boolean; } interface TextEncoderEncodeIntoResult { - read: number - written: number + read: number; + written: number; } /** * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. @@ -1544,44 +1283,44 @@ interface TextEncoderEncodeIntoResult { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) */ declare class ErrorEvent extends Event { - constructor(type: string, init?: ErrorEventErrorEventInit) - /** - * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) - */ - get filename(): string - /** - * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) - */ - get message(): string - /** - * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) - */ - get lineno(): number - /** - * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) - */ - get colno(): number - /** - * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) - */ - get error(): any + constructor(type: string, init?: ErrorEventErrorEventInit); + /** + * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) + */ + get filename(): string; + /** + * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) + */ + get message(): string; + /** + * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) + */ + get lineno(): number; + /** + * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) + */ + get colno(): number; + /** + * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) + */ + get error(): any; } interface ErrorEventErrorEventInit { - message?: string - filename?: string - lineno?: number - colno?: number - error?: any + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; } /** * The **`MessageEvent`** interface represents a message received by a target object. @@ -1589,40 +1328,40 @@ interface ErrorEventErrorEventInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) */ declare class MessageEvent extends Event { - constructor(type: string, initializer: MessageEventInit) - /** - * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) - */ - readonly data: any - /** - * The **`origin`** read-only property of the origin of the message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) - */ - readonly origin: string | null - /** - * The **`lastEventId`** read-only property of the unique ID for the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) - */ - readonly lastEventId: string - /** - * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) - */ - readonly source: MessagePort | null - /** - * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) - */ - readonly ports: MessagePort[] + constructor(type: string, initializer: MessageEventInit); + /** + * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) + */ + readonly data: any; + /** + * The **`origin`** read-only property of the origin of the message emitter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) + */ + readonly origin: string | null; + /** + * The **`lastEventId`** read-only property of the unique ID for the event. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) + */ + readonly lastEventId: string; + /** + * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) + */ + readonly source: MessagePort | null; + /** + * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) + */ + readonly ports: MessagePort[]; } interface MessageEventInit { - data: ArrayBuffer | string + data: ArrayBuffer | string; } /** * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. @@ -1630,18 +1369,18 @@ interface MessageEventInit { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) */ declare abstract class PromiseRejectionEvent extends Event { - /** - * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) - */ - readonly promise: Promise - /** - * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) - */ - readonly reason: any + /** + * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) + */ + readonly promise: Promise; + /** + * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) + */ + readonly reason: any; } /** * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. @@ -1649,177 +1388,151 @@ declare abstract class PromiseRejectionEvent extends Event { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) */ declare class FormData { - constructor() - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: string): void - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: Blob, filename?: string): void - /** - * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) - */ - delete(name: string): void - /** - * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) - */ - get(name: string): (File | string) | null - /** - * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) - */ - getAll(name: string): (File | string)[] - /** - * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) - */ - has(name: string): boolean - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: string): void - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: Blob, filename?: string): void - /* Returns an array of key, value pairs for every entry in the list. */ - entries(): IterableIterator<[key: string, value: File | string]> - /* Returns a list of keys in the list. */ - keys(): IterableIterator - /* Returns a list of values in the list. */ - values(): IterableIterator - forEach( - callback: ( - this: This, - value: File | string, - key: string, - parent: FormData, - ) => void, - thisArg?: This, - ): void - [Symbol.iterator](): IterableIterator<[key: string, value: File | string]> + constructor(); + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string | Blob): void; + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string): void; + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: Blob, filename?: string): void; + /** + * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) + */ + delete(name: string): void; + /** + * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) + */ + get(name: string): (File | string) | null; + /** + * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) + */ + getAll(name: string): (File | string)[]; + /** + * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) + */ + has(name: string): boolean; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string | Blob): void; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string): void; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: Blob, filename?: string): void; + /* Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[ + key: string, + value: File | string + ]>; + /* Returns a list of keys in the list. */ + keys(): IterableIterator; + /* Returns a list of values in the list. */ + values(): IterableIterator<(File | string)>; + forEach(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: File | string + ]>; } interface ContentOptions { - html?: boolean + html?: boolean; } declare class HTMLRewriter { - constructor() - on( - selector: string, - handlers: HTMLRewriterElementContentHandlers, - ): HTMLRewriter - onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter - transform(response: Response): Response + constructor(); + on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; } interface HTMLRewriterElementContentHandlers { - element?(element: Element): void | Promise - comments?(comment: Comment): void | Promise - text?(element: Text): void | Promise + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; } interface HTMLRewriterDocumentContentHandlers { - doctype?(doctype: Doctype): void | Promise - comments?(comment: Comment): void | Promise - text?(text: Text): void | Promise - end?(end: DocumentEnd): void | Promise + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; } interface Doctype { - readonly name: string | null - readonly publicId: string | null - readonly systemId: string | null + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; } interface Element { - tagName: string - readonly attributes: IterableIterator - readonly removed: boolean - readonly namespaceURI: string - getAttribute(name: string): string | null - hasAttribute(name: string): boolean - setAttribute(name: string, value: string): Element - removeAttribute(name: string): Element - before( - content: string | ReadableStream | Response, - options?: ContentOptions, - ): Element - after( - content: string | ReadableStream | Response, - options?: ContentOptions, - ): Element - prepend( - content: string | ReadableStream | Response, - options?: ContentOptions, - ): Element - append( - content: string | ReadableStream | Response, - options?: ContentOptions, - ): Element - replace( - content: string | ReadableStream | Response, - options?: ContentOptions, - ): Element - remove(): Element - removeAndKeepContent(): Element - setInnerContent( - content: string | ReadableStream | Response, - options?: ContentOptions, - ): Element - onEndTag(handler: (tag: EndTag) => void | Promise): void + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string | ReadableStream | Response, options?: ContentOptions): Element; + after(content: string | ReadableStream | Response, options?: ContentOptions): Element; + prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; + append(content: string | ReadableStream | Response, options?: ContentOptions): Element; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; } interface EndTag { - name: string - before( - content: string | ReadableStream | Response, - options?: ContentOptions, - ): EndTag - after( - content: string | ReadableStream | Response, - options?: ContentOptions, - ): EndTag - remove(): EndTag + name: string; + before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + remove(): EndTag; } interface Comment { - text: string - readonly removed: boolean - before(content: string, options?: ContentOptions): Comment - after(content: string, options?: ContentOptions): Comment - replace(content: string, options?: ContentOptions): Comment - remove(): Comment + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; } interface Text { - readonly text: string - readonly lastInTextNode: boolean - readonly removed: boolean - before( - content: string | ReadableStream | Response, - options?: ContentOptions, - ): Text - after( - content: string | ReadableStream | Response, - options?: ContentOptions, - ): Text - replace( - content: string | ReadableStream | Response, - options?: ContentOptions, - ): Text - remove(): Text + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string | ReadableStream | Response, options?: ContentOptions): Text; + after(content: string | ReadableStream | Response, options?: ContentOptions): Text; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; + remove(): Text; } interface DocumentEnd { - append(content: string, options?: ContentOptions): DocumentEnd + append(content: string, options?: ContentOptions): DocumentEnd; } /** * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. @@ -1827,102 +1540,98 @@ interface DocumentEnd { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) */ declare abstract class FetchEvent extends ExtendableEvent { - /** - * The **`request`** read-only property of the the event handler. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) - */ - readonly request: Request - /** - * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) - */ - respondWith(promise: Response | Promise): void - passThroughOnException(): void + /** + * The **`request`** read-only property of the the event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) + */ + readonly request: Request; + /** + * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) + */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; } -type HeadersInit = Headers | Iterable> | Record +type HeadersInit = Headers | Iterable> | Record; /** * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) */ declare class Headers { - constructor(init?: HeadersInit) - /** - * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) - */ - get(name: string): string | null - getAll(name: string): string[] - /** - * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) - */ - getSetCookie(): string[] - /** - * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) - */ - has(name: string): boolean - /** - * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) - */ - set(name: string, value: string): void - /** - * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) - */ - append(name: string, value: string): void - /** - * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) - */ - delete(name: string): void - forEach( - callback: (this: This, value: string, key: string, parent: Headers) => void, - thisArg?: This, - ): void - /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ - entries(): IterableIterator<[key: string, value: string]> - /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ - keys(): IterableIterator - /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ - values(): IterableIterator - [Symbol.iterator](): IterableIterator<[key: string, value: string]> + constructor(init?: HeadersInit); + /** + * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) + */ + get(name: string): string | null; + getAll(name: string): string[]; + /** + * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) + */ + getSetCookie(): string[]; + /** + * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) + */ + has(name: string): boolean; + /** + * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) + */ + set(name: string, value: string): void; + /** + * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) + */ + append(name: string, value: string): void; + /** + * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) + */ + delete(name: string): void; + forEach(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void; + /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[ + key: string, + value: string + ]>; + /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: string + ]>; } -type BodyInit = - | ReadableStream - | string - | ArrayBuffer - | ArrayBufferView - | Blob - | URLSearchParams - | FormData +type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData; declare abstract class Body { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ - get body(): ReadableStream | null - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ - get bodyUsed(): boolean - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ - arrayBuffer(): Promise - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ - bytes(): Promise - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ - text(): Promise - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ - json(): Promise - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ - formData(): Promise - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ - blob(): Promise + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ + get body(): ReadableStream | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ + get bodyUsed(): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ + arrayBuffer(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ + bytes(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ + text(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ + json(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ + formData(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ + blob(): Promise; } /** * The **`Response`** interface of the Fetch API represents the response to a request. @@ -1930,711 +1639,547 @@ declare abstract class Body { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ declare var Response: { - prototype: Response - new (body?: BodyInit | null, init?: ResponseInit): Response - error(): Response - redirect(url: string, status?: number): Response - json(any: any, maybeInit?: ResponseInit | Response): Response -} + prototype: Response; + new (body?: BodyInit | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; + json(any: any, maybeInit?: (ResponseInit | Response)): Response; +}; /** * The **`Response`** interface of the Fetch API represents the response to a request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) */ interface Response extends Body { - /** - * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) - */ - clone(): Response - /** - * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) - */ - status: number - /** - * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) - */ - statusText: string - /** - * The **`headers`** read-only property of the with the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) - */ - headers: Headers - /** - * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) - */ - ok: boolean - /** - * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) - */ - redirected: boolean - /** - * The **`url`** read-only property of the Response interface contains the URL of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) - */ - url: string - webSocket: WebSocket | null - cf: any | undefined - /** - * The **`type`** read-only property of the Response interface contains the type of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) - */ - type: 'default' | 'error' + /** + * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) + */ + clone(): Response; + /** + * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) + */ + status: number; + /** + * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) + */ + statusText: string; + /** + * The **`headers`** read-only property of the with the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) + */ + headers: Headers; + /** + * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) + */ + ok: boolean; + /** + * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) + */ + redirected: boolean; + /** + * The **`url`** read-only property of the Response interface contains the URL of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) + */ + url: string; + webSocket: WebSocket | null; + cf: any | undefined; + /** + * The **`type`** read-only property of the Response interface contains the type of the response. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) + */ + type: "default" | "error"; } interface ResponseInit { - status?: number - statusText?: string - headers?: HeadersInit - cf?: any - webSocket?: WebSocket | null - encodeBody?: 'automatic' | 'manual' + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: (WebSocket | null); + encodeBody?: "automatic" | "manual"; } -type RequestInfo> = - | Request - | string +type RequestInfo> = Request | string; /** * The **`Request`** interface of the Fetch API represents a resource request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ declare var Request: { - prototype: Request - new >( - input: RequestInfo | URL, - init?: RequestInit, - ): Request -} + prototype: Request; + new >(input: RequestInfo | URL, init?: RequestInit): Request; +}; /** * The **`Request`** interface of the Fetch API represents a resource request. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) */ -interface Request> - extends Body { - /** - * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) - */ - clone(): Request - /** - * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) - */ - method: string - /** - * The **`url`** read-only property of the Request interface contains the URL of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) - */ - url: string - /** - * The **`headers`** read-only property of the with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) - */ - headers: Headers - /** - * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) - */ - redirect: string - fetcher: Fetcher | null - /** - * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) - */ - signal: AbortSignal - cf: Cf | undefined - /** - * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) - */ - integrity: string - /** - * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) - */ - keepalive: boolean - /** - * The **`cache`** read-only property of the Request interface contains the cache mode of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) - */ - cache?: 'no-store' | 'no-cache' +interface Request> extends Body { + /** + * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) + */ + clone(): Request; + /** + * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + method: string; + /** + * The **`url`** read-only property of the Request interface contains the URL of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + url: string; + /** + * The **`headers`** read-only property of the with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + headers: Headers; + /** + * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + redirect: string; + fetcher: Fetcher | null; + /** + * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + signal: AbortSignal; + cf?: Cf; + /** + * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + integrity: string; + /** + * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + keepalive: boolean; + /** + * The **`cache`** read-only property of the Request interface contains the cache mode of the request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) + */ + cache?: "no-store" | "no-cache"; } interface RequestInit { - /* A string to set request's method. */ - method?: string - /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ - headers?: HeadersInit - /* A BodyInit object or null to set request's body. */ - body?: BodyInit | null - /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ - redirect?: string - fetcher?: Fetcher | null - cf?: Cf - /* A string indicating how the request will interact with the browser's cache to set request's cache. */ - cache?: 'no-store' | 'no-cache' - /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ - integrity?: string - /* An AbortSignal to set request's signal. */ - signal?: AbortSignal | null - encodeResponseBody?: 'automatic' | 'manual' -} -type Service< - T extends - | (new (...args: any[]) => Rpc.WorkerEntrypointBranded) - | Rpc.WorkerEntrypointBranded - | ExportedHandler - | undefined = undefined, -> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded - ? Fetcher> - : T extends Rpc.WorkerEntrypointBranded - ? Fetcher - : T extends Exclude - ? never - : Fetcher -type Fetcher< - T extends Rpc.EntrypointBranded | undefined = undefined, - Reserved extends string = never, -> = (T extends Rpc.EntrypointBranded - ? Rpc.Provider - : unknown) & { - fetch(input: RequestInfo | URL, init?: RequestInit): Promise - connect(address: SocketAddress | string, options?: SocketOptions): Socket + /* A string to set request's method. */ + method?: string; + /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /* A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: (Fetcher | null); + cf?: Cf; + /* A string indicating how the request will interact with the browser's cache to set request's cache. */ + cache?: "no-store" | "no-cache"; + /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /* An AbortSignal to set request's signal. */ + signal?: (AbortSignal | null); + encodeResponseBody?: "automatic" | "manual"; } +type Service Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; +type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; interface KVNamespaceListKey { - name: Key - expiration?: number - metadata?: Metadata + name: Key; + expiration?: number; + metadata?: Metadata; } -type KVNamespaceListResult = - | { - list_complete: false - keys: KVNamespaceListKey[] - cursor: string - cacheStatus: string | null - } - | { - list_complete: true - keys: KVNamespaceListKey[] - cacheStatus: string | null - } +type KVNamespaceListResult = { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; +} | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; +}; interface KVNamespace { - get( - key: Key, - options?: Partial>, - ): Promise - get(key: Key, type: 'text'): Promise - get( - key: Key, - type: 'json', - ): Promise - get(key: Key, type: 'arrayBuffer'): Promise - get(key: Key, type: 'stream'): Promise - get(key: Key, options?: KVNamespaceGetOptions<'text'>): Promise - get( - key: Key, - options?: KVNamespaceGetOptions<'json'>, - ): Promise - get( - key: Key, - options?: KVNamespaceGetOptions<'arrayBuffer'>, - ): Promise - get( - key: Key, - options?: KVNamespaceGetOptions<'stream'>, - ): Promise - get(key: Array, type: 'text'): Promise> - get( - key: Array, - type: 'json', - ): Promise> - get( - key: Array, - options?: Partial>, - ): Promise> - get( - key: Array, - options?: KVNamespaceGetOptions<'text'>, - ): Promise> - get( - key: Array, - options?: KVNamespaceGetOptions<'json'>, - ): Promise> - list( - options?: KVNamespaceListOptions, - ): Promise> - put( - key: Key, - value: string | ArrayBuffer | ArrayBufferView | ReadableStream, - options?: KVNamespacePutOptions, - ): Promise - getWithMetadata( - key: Key, - options?: Partial>, - ): Promise> - getWithMetadata( - key: Key, - type: 'text', - ): Promise> - getWithMetadata( - key: Key, - type: 'json', - ): Promise> - getWithMetadata( - key: Key, - type: 'arrayBuffer', - ): Promise> - getWithMetadata( - key: Key, - type: 'stream', - ): Promise> - getWithMetadata( - key: Key, - options: KVNamespaceGetOptions<'text'>, - ): Promise> - getWithMetadata( - key: Key, - options: KVNamespaceGetOptions<'json'>, - ): Promise> - getWithMetadata( - key: Key, - options: KVNamespaceGetOptions<'arrayBuffer'>, - ): Promise> - getWithMetadata( - key: Key, - options: KVNamespaceGetOptions<'stream'>, - ): Promise> - getWithMetadata( - key: Array, - type: 'text', - ): Promise>> - getWithMetadata( - key: Array, - type: 'json', - ): Promise< - Map> - > - getWithMetadata( - key: Array, - options?: Partial>, - ): Promise>> - getWithMetadata( - key: Array, - options?: KVNamespaceGetOptions<'text'>, - ): Promise>> - getWithMetadata( - key: Array, - options?: KVNamespaceGetOptions<'json'>, - ): Promise< - Map> - > - delete(key: Key): Promise + get(key: Key, options?: Partial>): Promise; + get(key: Key, type: "text"): Promise; + get(key: Key, type: "json"): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"json">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; + get(key: Array, type: "text"): Promise>; + get(key: Array, type: "json"): Promise>; + get(key: Array, options?: Partial>): Promise>; + get(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>; + get(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>; + list(options?: KVNamespaceListOptions): Promise>; + put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise; + getWithMetadata(key: Key, options?: Partial>): Promise>; + getWithMetadata(key: Key, type: "text"): Promise>; + getWithMetadata(key: Key, type: "json"): Promise>; + getWithMetadata(key: Key, type: "arrayBuffer"): Promise>; + getWithMetadata(key: Key, type: "stream"): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"text">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"json">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"stream">): Promise>; + getWithMetadata(key: Array, type: "text"): Promise>>; + getWithMetadata(key: Array, type: "json"): Promise>>; + getWithMetadata(key: Array, options?: Partial>): Promise>>; + getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>>; + getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>>; + delete(key: Key): Promise; } interface KVNamespaceListOptions { - limit?: number - prefix?: string | null - cursor?: string | null + limit?: number; + prefix?: (string | null); + cursor?: (string | null); } interface KVNamespaceGetOptions { - type: Type - cacheTtl?: number + type: Type; + cacheTtl?: number; } interface KVNamespacePutOptions { - expiration?: number - expirationTtl?: number - metadata?: any | null + expiration?: number; + expirationTtl?: number; + metadata?: (any | null); } interface KVNamespaceGetWithMetadataResult { - value: Value | null - metadata: Metadata | null - cacheStatus: string | null + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; } -type QueueContentType = 'text' | 'bytes' | 'json' | 'v8' +type QueueContentType = "text" | "bytes" | "json" | "v8"; interface Queue { - send(message: Body, options?: QueueSendOptions): Promise - sendBatch( - messages: Iterable>, - options?: QueueSendBatchOptions, - ): Promise + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; } interface QueueSendOptions { - contentType?: QueueContentType - delaySeconds?: number + contentType?: QueueContentType; + delaySeconds?: number; } interface QueueSendBatchOptions { - delaySeconds?: number + delaySeconds?: number; } interface MessageSendRequest { - body: Body - contentType?: QueueContentType - delaySeconds?: number + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; } interface QueueRetryOptions { - delaySeconds?: number + delaySeconds?: number; } interface Message { - readonly id: string - readonly timestamp: Date - readonly body: Body - readonly attempts: number - retry(options?: QueueRetryOptions): void - ack(): void + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; } interface QueueEvent extends ExtendableEvent { - readonly messages: readonly Message[] - readonly queue: string - retryAll(options?: QueueRetryOptions): void - ackAll(): void + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; } interface MessageBatch { - readonly messages: readonly Message[] - readonly queue: string - retryAll(options?: QueueRetryOptions): void - ackAll(): void + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; } interface R2Error extends Error { - readonly name: string - readonly code: number - readonly message: string - readonly action: string - readonly stack: any + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; } interface R2ListOptions { - limit?: number - prefix?: string - cursor?: string - delimiter?: string - startAfter?: string - include?: ('httpMetadata' | 'customMetadata')[] + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; } declare abstract class R2Bucket { - head(key: string): Promise - get( - key: string, - options: R2GetOptions & { - onlyIf: R2Conditional | Headers - }, - ): Promise - get(key: string, options?: R2GetOptions): Promise - put( - key: string, - value: - | ReadableStream - | ArrayBuffer - | ArrayBufferView - | string - | null - | Blob, - options?: R2PutOptions & { - onlyIf: R2Conditional | Headers - }, - ): Promise - put( - key: string, - value: - | ReadableStream - | ArrayBuffer - | ArrayBufferView - | string - | null - | Blob, - options?: R2PutOptions, - ): Promise - createMultipartUpload( - key: string, - options?: R2MultipartOptions, - ): Promise - resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload - delete(keys: string | string[]): Promise - list(options?: R2ListOptions): Promise + head(key: string): Promise; + get(key: string, options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }): Promise; + get(key: string, options?: R2GetOptions): Promise; + put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }): Promise; + put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise; + createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; } interface R2MultipartUpload { - readonly key: string - readonly uploadId: string - uploadPart( - partNumber: number, - value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, - options?: R2UploadPartOptions, - ): Promise - abort(): Promise - complete(uploadedParts: R2UploadedPart[]): Promise + readonly key: string; + readonly uploadId: string; + uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; } interface R2UploadedPart { - partNumber: number - etag: string + partNumber: number; + etag: string; } declare abstract class R2Object { - readonly key: string - readonly version: string - readonly size: number - readonly etag: string - readonly httpEtag: string - readonly checksums: R2Checksums - readonly uploaded: Date - readonly httpMetadata?: R2HTTPMetadata - readonly customMetadata?: Record - readonly range?: R2Range - readonly storageClass: string - readonly ssecKeyMd5?: string - writeHttpMetadata(headers: Headers): void + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + readonly ssecKeyMd5?: string; + writeHttpMetadata(headers: Headers): void; } interface R2ObjectBody extends R2Object { - get body(): ReadableStream - get bodyUsed(): boolean - arrayBuffer(): Promise - bytes(): Promise - text(): Promise - json(): Promise - blob(): Promise + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + bytes(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; } -type R2Range = - | { - offset: number - length?: number - } - | { - offset?: number - length: number - } - | { - suffix: number - } +type R2Range = { + offset: number; + length?: number; +} | { + offset?: number; + length: number; +} | { + suffix: number; +}; interface R2Conditional { - etagMatches?: string - etagDoesNotMatch?: string - uploadedBefore?: Date - uploadedAfter?: Date - secondsGranularity?: boolean + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; } interface R2GetOptions { - onlyIf?: R2Conditional | Headers - range?: R2Range | Headers - ssecKey?: ArrayBuffer | string + onlyIf?: (R2Conditional | Headers); + range?: (R2Range | Headers); + ssecKey?: (ArrayBuffer | string); } interface R2PutOptions { - onlyIf?: R2Conditional | Headers - httpMetadata?: R2HTTPMetadata | Headers - customMetadata?: Record - md5?: (ArrayBuffer | ArrayBufferView) | string - sha1?: (ArrayBuffer | ArrayBufferView) | string - sha256?: (ArrayBuffer | ArrayBufferView) | string - sha384?: (ArrayBuffer | ArrayBufferView) | string - sha512?: (ArrayBuffer | ArrayBufferView) | string - storageClass?: string - ssecKey?: ArrayBuffer | string + onlyIf?: (R2Conditional | Headers); + httpMetadata?: (R2HTTPMetadata | Headers); + customMetadata?: Record; + md5?: ((ArrayBuffer | ArrayBufferView) | string); + sha1?: ((ArrayBuffer | ArrayBufferView) | string); + sha256?: ((ArrayBuffer | ArrayBufferView) | string); + sha384?: ((ArrayBuffer | ArrayBufferView) | string); + sha512?: ((ArrayBuffer | ArrayBufferView) | string); + storageClass?: string; + ssecKey?: (ArrayBuffer | string); } interface R2MultipartOptions { - httpMetadata?: R2HTTPMetadata | Headers - customMetadata?: Record - storageClass?: string - ssecKey?: ArrayBuffer | string + httpMetadata?: (R2HTTPMetadata | Headers); + customMetadata?: Record; + storageClass?: string; + ssecKey?: (ArrayBuffer | string); } interface R2Checksums { - readonly md5?: ArrayBuffer - readonly sha1?: ArrayBuffer - readonly sha256?: ArrayBuffer - readonly sha384?: ArrayBuffer - readonly sha512?: ArrayBuffer - toJSON(): R2StringChecksums + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; } interface R2StringChecksums { - md5?: string - sha1?: string - sha256?: string - sha384?: string - sha512?: string + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; } interface R2HTTPMetadata { - contentType?: string - contentLanguage?: string - contentDisposition?: string - contentEncoding?: string - cacheControl?: string - cacheExpiry?: Date + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; } type R2Objects = { - objects: R2Object[] - delimitedPrefixes: string[] -} & ( - | { - truncated: true - cursor: string - } - | { - truncated: false - } -) + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ({ + truncated: true; + cursor: string; +} | { + truncated: false; +}); interface R2UploadPartOptions { - ssecKey?: ArrayBuffer | string + ssecKey?: (ArrayBuffer | string); } declare abstract class ScheduledEvent extends ExtendableEvent { - readonly scheduledTime: number - readonly cron: string - noRetry(): void + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; } interface ScheduledController { - readonly scheduledTime: number - readonly cron: string - noRetry(): void + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; } interface QueuingStrategy { - highWaterMark?: number | bigint - size?: (chunk: T) => number | bigint + highWaterMark?: (number | bigint); + size?: (chunk: T) => number | bigint; } interface UnderlyingSink { - type?: string - start?: (controller: WritableStreamDefaultController) => void | Promise - write?: ( - chunk: W, - controller: WritableStreamDefaultController, - ) => void | Promise - abort?: (reason: any) => void | Promise - close?: () => void | Promise + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; } interface UnderlyingByteSource { - type: 'bytes' - autoAllocateChunkSize?: number - start?: (controller: ReadableByteStreamController) => void | Promise - pull?: (controller: ReadableByteStreamController) => void | Promise - cancel?: (reason: any) => void | Promise + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; } interface UnderlyingSource { - type?: '' | undefined - start?: ( - controller: ReadableStreamDefaultController, - ) => void | Promise - pull?: ( - controller: ReadableStreamDefaultController, - ) => void | Promise - cancel?: (reason: any) => void | Promise - expectedLength?: number | bigint + type?: "" | undefined; + start?: (controller: ReadableStreamDefaultController) => void | Promise; + pull?: (controller: ReadableStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: (number | bigint); } interface Transformer { - readableType?: string - writableType?: string - start?: ( - controller: TransformStreamDefaultController, - ) => void | Promise - transform?: ( - chunk: I, - controller: TransformStreamDefaultController, - ) => void | Promise - flush?: ( - controller: TransformStreamDefaultController, - ) => void | Promise - cancel?: (reason: any) => void | Promise - expectedLength?: number + readableType?: string; + writableType?: string; + start?: (controller: TransformStreamDefaultController) => void | Promise; + transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; + flush?: (controller: TransformStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; } interface StreamPipeOptions { - /** - * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * - * Errors and closures of the source and destination streams propagate as follows: - * - * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * - * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * - * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * - * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * - * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. - */ - preventClose?: boolean - preventAbort?: boolean - preventCancel?: boolean - signal?: AbortSignal + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. + * + * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. + * + * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. + * + * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. + * + * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. + */ + preventClose?: boolean; + signal?: AbortSignal; } -type ReadableStreamReadResult = - | { - done: false - value: R - } - | { - done: true - value?: undefined - } +type ReadableStreamReadResult = { + done: false; + value: R; +} | { + done: true; + value?: undefined; +}; /** * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ interface ReadableStream { - /** - * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) - */ - get locked(): boolean - /** - * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) - */ - cancel(reason?: any): Promise - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(): ReadableStreamDefaultReader - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader - /** - * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) - */ - pipeThrough( - transform: ReadableWritablePair, - options?: StreamPipeOptions, - ): ReadableStream - /** - * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) - */ - pipeTo( - destination: WritableStream, - options?: StreamPipeOptions, - ): Promise - /** - * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) - */ - tee(): [ReadableStream, ReadableStream] - values(options?: ReadableStreamValuesOptions): AsyncIterableIterator - [Symbol.asyncIterator]( - options?: ReadableStreamValuesOptions, - ): AsyncIterableIterator + /** + * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) + */ + get locked(): boolean; + /** + * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) + */ + cancel(reason?: any): Promise; + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ + getReader(): ReadableStreamDefaultReader; + /** + * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) + */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /** + * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) + */ + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + /** + * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) + */ + tee(): [ + ReadableStream, + ReadableStream + ]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; } /** * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. @@ -2642,37 +2187,31 @@ interface ReadableStream { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) */ declare const ReadableStream: { - prototype: ReadableStream - new ( - underlyingSource: UnderlyingByteSource, - strategy?: QueuingStrategy, - ): ReadableStream - new ( - underlyingSource?: UnderlyingSource, - strategy?: QueuingStrategy, - ): ReadableStream -} + prototype: ReadableStream; + new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; +}; /** * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request). * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) */ declare class ReadableStreamDefaultReader { - constructor(stream: ReadableStream) - get closed(): Promise - cancel(reason?: any): Promise - /** - * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) - */ - read(): Promise> - /** - * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) - */ - releaseLock(): void + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) + */ + read(): Promise>; + /** + * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) + */ + releaseLock(): void; } /** * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. @@ -2680,36 +2219,33 @@ declare class ReadableStreamDefaultReader { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ declare class ReadableStreamBYOBReader { - constructor(stream: ReadableStream) - get closed(): Promise - cancel(reason?: any): Promise - /** - * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) - */ - read(view: T): Promise> - /** - * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) - */ - releaseLock(): void - readAtLeast( - minElements: number, - view: T, - ): Promise> + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /** + * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) + */ + read(view: T): Promise>; + /** + * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) + */ + releaseLock(): void; + readAtLeast(minElements: number, view: T): Promise>; } interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { - min?: number + min?: number; } interface ReadableStreamGetReaderOptions { - /** - * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. - * - * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. - */ - mode: 'byob' + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; } /** * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a 'pull request' for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues). @@ -2717,25 +2253,25 @@ interface ReadableStreamGetReaderOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ declare abstract class ReadableStreamBYOBRequest { - /** - * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) - */ - get view(): Uint8Array | null - /** - * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) - */ - respond(bytesWritten: number): void - /** - * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) - */ - respondWithNewView(view: ArrayBuffer | ArrayBufferView): void - get atLeast(): number | null + /** + * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) + */ + get view(): Uint8Array | null; + /** + * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) + */ + respond(bytesWritten: number): void; + /** + * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) + */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; } /** * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. @@ -2743,30 +2279,30 @@ declare abstract class ReadableStreamBYOBRequest { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ declare abstract class ReadableStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null - /** - * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) - */ - close(): void - /** - * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) - */ - enqueue(chunk?: R): void - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) - */ - error(reason: any): void + /** + * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) + */ + close(): void; + /** + * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) + */ + enqueue(chunk?: R): void; + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) + */ + error(reason: any): void; } /** * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. @@ -2774,36 +2310,36 @@ declare abstract class ReadableStreamDefaultController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ declare abstract class ReadableByteStreamController { - /** - * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) - */ - get byobRequest(): ReadableStreamBYOBRequest | null - /** - * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) - */ - get desiredSize(): number | null - /** - * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) - */ - close(): void - /** - * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) - */ - enqueue(chunk: ArrayBuffer | ArrayBufferView): void - /** - * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) - */ - error(reason: any): void + /** + * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) + */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** + * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) + */ + close(): void; + /** + * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) + */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /** + * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) + */ + error(reason: any): void; } /** * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. @@ -2811,18 +2347,18 @@ declare abstract class ReadableByteStreamController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) */ declare abstract class WritableStreamDefaultController { - /** - * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) - */ - get signal(): AbortSignal - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) - */ - error(reason?: any): void + /** + * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) + */ + get signal(): AbortSignal; + /** + * The **`error()`** method of the with the associated stream to error. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) + */ + error(reason?: any): void; } /** * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. @@ -2830,39 +2366,39 @@ declare abstract class WritableStreamDefaultController { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ declare abstract class TransformStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null - /** - * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) - */ - enqueue(chunk?: O): void - /** - * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) - */ - error(reason: any): void - /** - * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) - */ - terminate(): void + /** + * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) + */ + enqueue(chunk?: O): void; + /** + * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) + */ + error(reason: any): void; + /** + * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) + */ + terminate(): void; } interface ReadableWritablePair { - /** - * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - */ - writable: WritableStream - readable: ReadableStream + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream; } /** * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. @@ -2870,34 +2406,31 @@ interface ReadableWritablePair { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) */ declare class WritableStream { - constructor( - underlyingSink?: UnderlyingSink, - queuingStrategy?: QueuingStrategy, - ) - /** - * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) - */ - get locked(): boolean - /** - * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) - */ - abort(reason?: any): Promise - /** - * The **`close()`** method of the WritableStream interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) - */ - close(): Promise - /** - * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) - */ - getWriter(): WritableStreamDefaultWriter + constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); + /** + * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) + */ + get locked(): boolean; + /** + * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) + */ + abort(reason?: any): Promise; + /** + * The **`close()`** method of the WritableStream interface closes the associated stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) + */ + close(): Promise; + /** + * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) + */ + getWriter(): WritableStreamDefaultWriter; } /** * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink. @@ -2905,49 +2438,49 @@ declare class WritableStream { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) */ declare class WritableStreamDefaultWriter { - constructor(stream: WritableStream) - /** - * The **`closed`** read-only property of the the stream errors or the writer's lock is released. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) - */ - get closed(): Promise - /** - * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) - */ - get ready(): Promise - /** - * The **`desiredSize`** read-only property of the to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) - */ - get desiredSize(): number | null - /** - * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) - */ - abort(reason?: any): Promise - /** - * The **`close()`** method of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) - */ - close(): Promise - /** - * The **`write()`** method of the operation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) - */ - write(chunk?: W): Promise - /** - * The **`releaseLock()`** method of the corresponding stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) - */ - releaseLock(): void + constructor(stream: WritableStream); + /** + * The **`closed`** read-only property of the the stream errors or the writer's lock is released. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) + */ + get closed(): Promise; + /** + * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) + */ + get ready(): Promise; + /** + * The **`desiredSize`** read-only property of the to fill the stream's internal queue. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) + */ + get desiredSize(): number | null; + /** + * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) + */ + abort(reason?: any): Promise; + /** + * The **`close()`** method of the stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) + */ + close(): Promise; + /** + * The **`write()`** method of the operation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) + */ + write(chunk?: W): Promise; + /** + * The **`releaseLock()`** method of the corresponding stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) + */ + releaseLock(): void; } /** * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. @@ -2955,63 +2488,47 @@ declare class WritableStreamDefaultWriter { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) */ declare class TransformStream { - constructor( - transformer?: Transformer, - writableStrategy?: QueuingStrategy, - readableStrategy?: QueuingStrategy, - ) - /** - * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) - */ - get readable(): ReadableStream - /** - * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) - */ - get writable(): WritableStream + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /** + * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) + */ + get readable(): ReadableStream; + /** + * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) + */ + get writable(): WritableStream; } declare class FixedLengthStream extends IdentityTransformStream { - constructor( - expectedLength: number | bigint, - queuingStrategy?: IdentityTransformStreamQueuingStrategy, - ) + constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); } -declare class IdentityTransformStream extends TransformStream< - ArrayBuffer | ArrayBufferView, - Uint8Array -> { - constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy) +declare class IdentityTransformStream extends TransformStream { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); } interface IdentityTransformStreamQueuingStrategy { - highWaterMark?: number | bigint + highWaterMark?: (number | bigint); } interface ReadableStreamValuesOptions { - preventCancel?: boolean + preventCancel?: boolean; } /** * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ -declare class CompressionStream extends TransformStream< - ArrayBuffer | ArrayBufferView, - Uint8Array -> { - constructor(format: 'gzip' | 'deflate' | 'deflate-raw') +declare class CompressionStream extends TransformStream { + constructor(format: "gzip" | "deflate" | "deflate-raw"); } /** * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */ -declare class DecompressionStream extends TransformStream< - ArrayBuffer | ArrayBufferView, - Uint8Array -> { - constructor(format: 'gzip' | 'deflate' | 'deflate-raw') +declare class DecompressionStream extends TransformStream { + constructor(format: "gzip" | "deflate" | "deflate-raw"); } /** * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. @@ -3019,44 +2536,39 @@ declare class DecompressionStream extends TransformStream< * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) */ declare class TextEncoderStream extends TransformStream { - constructor() - get encoding(): string + constructor(); + get encoding(): string; } /** * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) */ -declare class TextDecoderStream extends TransformStream< - ArrayBuffer | ArrayBufferView, - string -> { - constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit) - get encoding(): string - get fatal(): boolean - get ignoreBOM(): boolean +declare class TextDecoderStream extends TransformStream { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; } interface TextDecoderStreamTextDecoderStreamInit { - fatal?: boolean - ignoreBOM?: boolean + fatal?: boolean; + ignoreBOM?: boolean; } /** * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) */ -declare class ByteLengthQueuingStrategy - implements QueuingStrategy -{ - constructor(init: QueuingStrategyInit) - /** - * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) - */ - get highWaterMark(): number - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ - get size(): (chunk?: any) => number +declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /** + * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) + */ + get highWaterMark(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; } /** * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. @@ -3064,142 +2576,128 @@ declare class ByteLengthQueuingStrategy * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy) */ declare class CountQueuingStrategy implements QueuingStrategy { - constructor(init: QueuingStrategyInit) - /** - * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) - */ - get highWaterMark(): number - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ - get size(): (chunk?: any) => number + constructor(init: QueuingStrategyInit); + /** + * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) + */ + get highWaterMark(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; } interface QueuingStrategyInit { - /** - * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * - * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. - */ - highWaterMark: number + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. + */ + highWaterMark: number; } interface ScriptVersion { - id?: string - tag?: string - message?: string + id?: string; + tag?: string; + message?: string; } declare abstract class TailEvent extends ExtendableEvent { - readonly events: TraceItem[] - readonly traces: TraceItem[] + readonly events: TraceItem[]; + readonly traces: TraceItem[]; } interface TraceItem { - readonly event: - | ( - | TraceItemFetchEventInfo - | TraceItemJsRpcEventInfo - | TraceItemScheduledEventInfo - | TraceItemAlarmEventInfo - | TraceItemQueueEventInfo - | TraceItemEmailEventInfo - | TraceItemTailEventInfo - | TraceItemCustomEventInfo - | TraceItemHibernatableWebSocketEventInfo - ) - | null - readonly eventTimestamp: number | null - readonly logs: TraceLog[] - readonly exceptions: TraceException[] - readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[] - readonly scriptName: string | null - readonly entrypoint?: string - readonly scriptVersion?: ScriptVersion - readonly dispatchNamespace?: string - readonly scriptTags?: string[] - readonly durableObjectId?: string - readonly outcome: string - readonly executionModel: string - readonly truncated: boolean - readonly cpuTime: number - readonly wallTime: number + readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly durableObjectId?: string; + readonly outcome: string; + readonly executionModel: string; + readonly truncated: boolean; + readonly cpuTime: number; + readonly wallTime: number; } interface TraceItemAlarmEventInfo { - readonly scheduledTime: Date + readonly scheduledTime: Date; +} +interface TraceItemCustomEventInfo { } -interface TraceItemCustomEventInfo {} interface TraceItemScheduledEventInfo { - readonly scheduledTime: number - readonly cron: string + readonly scheduledTime: number; + readonly cron: string; } interface TraceItemQueueEventInfo { - readonly queue: string - readonly batchSize: number + readonly queue: string; + readonly batchSize: number; } interface TraceItemEmailEventInfo { - readonly mailFrom: string - readonly rcptTo: string - readonly rawSize: number + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; } interface TraceItemTailEventInfo { - readonly consumedEvents: TraceItemTailEventInfoTailItem[] + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; } interface TraceItemTailEventInfoTailItem { - readonly scriptName: string | null + readonly scriptName: string | null; } interface TraceItemFetchEventInfo { - readonly response?: TraceItemFetchEventInfoResponse - readonly request: TraceItemFetchEventInfoRequest + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; } interface TraceItemFetchEventInfoRequest { - readonly cf?: any - readonly headers: Record - readonly method: string - readonly url: string - getUnredacted(): TraceItemFetchEventInfoRequest + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; } interface TraceItemFetchEventInfoResponse { - readonly status: number + readonly status: number; } interface TraceItemJsRpcEventInfo { - readonly rpcMethod: string + readonly rpcMethod: string; } interface TraceItemHibernatableWebSocketEventInfo { - readonly getWebSocketEvent: - | TraceItemHibernatableWebSocketEventInfoMessage - | TraceItemHibernatableWebSocketEventInfoClose - | TraceItemHibernatableWebSocketEventInfoError + readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; } interface TraceItemHibernatableWebSocketEventInfoMessage { - readonly webSocketEventType: string + readonly webSocketEventType: string; } interface TraceItemHibernatableWebSocketEventInfoClose { - readonly webSocketEventType: string - readonly code: number - readonly wasClean: boolean + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; } interface TraceItemHibernatableWebSocketEventInfoError { - readonly webSocketEventType: string + readonly webSocketEventType: string; } interface TraceLog { - readonly timestamp: number - readonly level: string - readonly message: any + readonly timestamp: number; + readonly level: string; + readonly message: any; } interface TraceException { - readonly timestamp: number - readonly message: string - readonly name: string - readonly stack?: string + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; } interface TraceDiagnosticChannelEvent { - readonly timestamp: number - readonly channel: string - readonly message: any + readonly timestamp: number; + readonly channel: string; + readonly message: any; } interface TraceMetrics { - readonly cpuTime: number - readonly wallTime: number + readonly cpuTime: number; + readonly wallTime: number; } interface UnsafeTraceMetrics { - fromTrace(item: TraceItem): TraceMetrics + fromTrace(item: TraceItem): TraceMetrics; } /** * The **`URL`** interface is used to parse, construct, normalize, and encode URL. @@ -3207,171 +2705,171 @@ interface UnsafeTraceMetrics { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) */ declare class URL { - constructor(url: string | URL, base?: string | URL) - /** - * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) - */ - get origin(): string - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - get href(): string - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - set href(value: string) - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - get protocol(): string - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - set protocol(value: string) - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - get username(): string - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - set username(value: string) - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - get password(): string - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - set password(value: string) - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - get host(): string - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - set host(value: string) - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - get hostname(): string - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - set hostname(value: string) - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - get port(): string - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - set port(value: string) - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - get pathname(): string - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - set pathname(value: string) - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - get search(): string - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - set search(value: string) - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - get hash(): string - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - set hash(value: string) - /** - * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) - */ - get searchParams(): URLSearchParams - /** - * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) - */ - toJSON(): string - /*function toString() { [native code] }*/ - toString(): string - /** - * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) - */ - static canParse(url: string, base?: string): boolean - /** - * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) - */ - static parse(url: string, base?: string): URL | null - /** - * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) - */ - static createObjectURL(object: File | Blob): string - /** - * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) - */ - static revokeObjectURL(object_url: string): void + constructor(url: string | URL, base?: string | URL); + /** + * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) + */ + get origin(): string; + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ + get href(): string; + /** + * The **`href`** property of the URL interface is a string containing the whole URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) + */ + set href(value: string); + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ + get protocol(): string; + /** + * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) + */ + set protocol(value: string); + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ + get username(): string; + /** + * The **`username`** property of the URL interface is a string containing the username component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) + */ + set username(value: string); + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ + get password(): string; + /** + * The **`password`** property of the URL interface is a string containing the password component of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) + */ + set password(value: string); + /** + * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ + get host(): string; + /** + * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) + */ + set host(value: string); + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ + get hostname(): string; + /** + * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) + */ + set hostname(value: string); + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ + get port(): string; + /** + * The **`port`** property of the URL interface is a string containing the port number of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) + */ + set port(value: string); + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ + get pathname(): string; + /** + * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) + */ + set pathname(value: string); + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ + get search(): string; + /** + * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) + */ + set search(value: string); + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ + get hash(): string; + /** + * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) + */ + set hash(value: string); + /** + * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) + */ + get searchParams(): URLSearchParams; + /** + * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) + */ + toJSON(): string; + /*function toString() { [native code] }*/ + toString(): string; + /** + * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) + */ + static canParse(url: string, base?: string): boolean; + /** + * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) + */ + static parse(url: string, base?: string): URL | null; + /** + * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) + */ + static createObjectURL(object: File | Blob): string; + /** + * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) + */ + static revokeObjectURL(object_url: string): void; } /** * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. @@ -3379,125 +2877,114 @@ declare class URL { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) */ declare class URLSearchParams { - constructor( - init?: Iterable> | Record | string, - ) - /** - * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) - */ - get size(): number - /** - * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) - */ - append(name: string, value: string): void - /** - * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) - */ - delete(name: string, value?: string): void - /** - * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) - */ - get(name: string): string | null - /** - * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) - */ - getAll(name: string): string[] - /** - * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) - */ - has(name: string, value?: string): boolean - /** - * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) - */ - set(name: string, value: string): void - /** - * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) - */ - sort(): void - /* Returns an array of key, value pairs for every entry in the search params. */ - entries(): IterableIterator<[key: string, value: string]> - /* Returns a list of keys in the search params. */ - keys(): IterableIterator - /* Returns a list of values in the search params. */ - values(): IterableIterator - forEach( - callback: ( - this: This, - value: string, - key: string, - parent: URLSearchParams, - ) => void, - thisArg?: This, - ): void - /*function toString() { [native code] }*/ - toString(): string - [Symbol.iterator](): IterableIterator<[key: string, value: string]> + constructor(init?: (Iterable> | Record | string)); + /** + * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) + */ + get size(): number; + /** + * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) + */ + append(name: string, value: string): void; + /** + * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) + */ + delete(name: string, value?: string): void; + /** + * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) + */ + get(name: string): string | null; + /** + * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) + */ + getAll(name: string): string[]; + /** + * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) + */ + has(name: string, value?: string): boolean; + /** + * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) + */ + set(name: string, value: string): void; + /** + * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) + */ + sort(): void; + /* Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[ + key: string, + value: string + ]>; + /* Returns a list of keys in the search params. */ + keys(): IterableIterator; + /* Returns a list of values in the search params. */ + values(): IterableIterator; + forEach(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void; + /*function toString() { [native code] }*/ + toString(): string; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: string + ]>; } declare class URLPattern { - constructor( - input?: string | URLPatternInit, - baseURL?: string | URLPatternOptions, - patternOptions?: URLPatternOptions, - ) - get protocol(): string - get username(): string - get password(): string - get hostname(): string - get port(): string - get pathname(): string - get search(): string - get hash(): string - get hasRegExpGroups(): boolean - test(input?: string | URLPatternInit, baseURL?: string): boolean - exec( - input?: string | URLPatternInit, - baseURL?: string, - ): URLPatternResult | null + constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + get hasRegExpGroups(): boolean; + test(input?: (string | URLPatternInit), baseURL?: string): boolean; + exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null; } interface URLPatternInit { - protocol?: string - username?: string - password?: string - hostname?: string - port?: string - pathname?: string - search?: string - hash?: string - baseURL?: string + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; } interface URLPatternComponentResult { - input: string - groups: Record + input: string; + groups: Record; } interface URLPatternResult { - inputs: (string | URLPatternInit)[] - protocol: URLPatternComponentResult - username: URLPatternComponentResult - password: URLPatternComponentResult - hostname: URLPatternComponentResult - port: URLPatternComponentResult - pathname: URLPatternComponentResult - search: URLPatternComponentResult - hash: URLPatternComponentResult + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; } interface URLPatternOptions { - ignoreCase?: boolean + ignoreCase?: boolean; } /** * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. @@ -3505,162 +2992,172 @@ interface URLPatternOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) */ declare class CloseEvent extends Event { - constructor(type: string, initializer?: CloseEventInit) - /** - * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) - */ - readonly code: number - /** - * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) - */ - readonly reason: string - /** - * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) - */ - readonly wasClean: boolean + constructor(type: string, initializer?: CloseEventInit); + /** + * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; } interface CloseEventInit { - code?: number - reason?: string - wasClean?: boolean + code?: number; + reason?: string; + wasClean?: boolean; } type WebSocketEventMap = { - close: CloseEvent - message: MessageEvent - open: Event - error: ErrorEvent -} + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; /** * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ declare var WebSocket: { - prototype: WebSocket - new (url: string, protocols?: string[] | string): WebSocket - readonly READY_STATE_CONNECTING: number - readonly CONNECTING: number - readonly READY_STATE_OPEN: number - readonly OPEN: number - readonly READY_STATE_CLOSING: number - readonly CLOSING: number - readonly READY_STATE_CLOSED: number - readonly CLOSED: number -} + prototype: WebSocket; + new (url: string, protocols?: (string[] | string)): WebSocket; + readonly READY_STATE_CONNECTING: number; + readonly CONNECTING: number; + readonly READY_STATE_OPEN: number; + readonly OPEN: number; + readonly READY_STATE_CLOSING: number; + readonly CLOSING: number; + readonly READY_STATE_CLOSED: number; + readonly CLOSED: number; +}; /** * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ interface WebSocket extends EventTarget { - accept(): void - /** - * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) - */ - send(message: (ArrayBuffer | ArrayBufferView) | string): void - /** - * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) - */ - close(code?: number, reason?: string): void - serializeAttachment(attachment: any): void - deserializeAttachment(): any | null - /** - * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) - */ - readyState: number - /** - * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) - */ - url: string | null - /** - * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) - */ - protocol: string | null - /** - * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) - */ - extensions: string | null + accept(options?: WebSocketAcceptOptions): void; + /** + * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + /** + * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readyState: number; + /** + * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + url: string | null; + /** + * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + protocol: string | null; + /** + * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + extensions: string | null; + /** + * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) + */ + binaryType: "blob" | "arraybuffer"; +} +interface WebSocketAcceptOptions { + /** + * When set to `true`, receiving a server-initiated WebSocket Close frame will not + * automatically send a reciprocal Close frame, leaving the connection in a half-open + * state. This is useful for proxying scenarios where you need to coordinate closing + * both sides independently. Defaults to `false` when the + * `no_web_socket_half_open_by_default` compatibility flag is enabled. + */ + allowHalfOpen?: boolean; } declare const WebSocketPair: { - new (): { - 0: WebSocket - 1: WebSocket - } -} + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; interface SqlStorage { - exec>( - query: string, - ...bindings: any[] - ): SqlStorageCursor - get databaseSize(): number - Cursor: typeof SqlStorageCursor - Statement: typeof SqlStorageStatement + exec>(query: string, ...bindings: any[]): SqlStorageCursor; + get databaseSize(): number; + Cursor: typeof SqlStorageCursor; + Statement: typeof SqlStorageStatement; } -declare abstract class SqlStorageStatement {} -type SqlStorageValue = ArrayBuffer | string | number | null -declare abstract class SqlStorageCursor< - T extends Record, -> { - next(): - | { - done?: false - value: T - } - | { - done: true - value?: never - } - toArray(): T[] - one(): T - raw(): IterableIterator - columnNames: string[] - get rowsRead(): number - get rowsWritten(): number - [Symbol.iterator](): IterableIterator +declare abstract class SqlStorageStatement { +} +type SqlStorageValue = ArrayBuffer | string | number | null; +declare abstract class SqlStorageCursor> { + next(): { + done?: false; + value: T; + } | { + done: true; + value?: never; + }; + toArray(): T[]; + one(): T; + raw(): IterableIterator; + columnNames: string[]; + get rowsRead(): number; + get rowsWritten(): number; + [Symbol.iterator](): IterableIterator; } interface Socket { - get readable(): ReadableStream - get writable(): WritableStream - get closed(): Promise - get opened(): Promise - get upgraded(): boolean - get secureTransport(): 'on' | 'off' | 'starttls' - close(): Promise - startTls(options?: TlsOptions): Socket + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + get upgraded(): boolean; + get secureTransport(): "on" | "off" | "starttls"; + close(): Promise; + startTls(options?: TlsOptions): Socket; } interface SocketOptions { - secureTransport?: string - allowHalfOpen: boolean - highWaterMark?: number | bigint + secureTransport?: string; + allowHalfOpen: boolean; + highWaterMark?: (number | bigint); } interface SocketAddress { - hostname: string - port: number + hostname: string; + port: number; } interface TlsOptions { - expectedServerHostname?: string + expectedServerHostname?: string; } interface SocketInfo { - remoteAddress?: string - localAddress?: string + remoteAddress?: string; + localAddress?: string; } /** * The **`EventSource`** interface is web content's interface to server-sent events. @@ -3668,66 +3165,68 @@ interface SocketInfo { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) */ declare class EventSource extends EventTarget { - constructor(url: string, init?: EventSourceEventSourceInit) - /** - * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - */ - close(): void - /** - * The **`url`** read-only property of the URL of the source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) - */ - get url(): string - /** - * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) - */ - get withCredentials(): boolean - /** - * The **`readyState`** read-only property of the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - */ - get readyState(): number - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen(): any | null - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - set onopen(value: any | null) - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage(): any | null - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - set onmessage(value: any | null) - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror(): any | null - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - set onerror(value: any | null) - static readonly CONNECTING: number - static readonly OPEN: number - static readonly CLOSED: number - static from(stream: ReadableStream): EventSource + constructor(url: string, init?: EventSourceEventSourceInit); + /** + * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void; + /** + * The **`url`** read-only property of the URL of the source. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + get url(): string; + /** + * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials(): boolean; + /** + * The **`readyState`** read-only property of the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null); + static readonly CONNECTING: number; + static readonly OPEN: number; + static readonly CLOSED: number; + static from(stream: ReadableStream): EventSource; } interface EventSourceEventSourceInit { - withCredentials?: boolean - fetcher?: Fetcher + withCredentials?: boolean; + fetcher?: Fetcher; } interface Container { - get running(): boolean - start(options?: ContainerStartupOptions): void - monitor(): Promise - destroy(error?: any): Promise - signal(signo: number): void - getTcpPort(port: number): Fetcher - setInactivityTimeout(durationMs: number | bigint): Promise + get running(): boolean; + start(options?: ContainerStartupOptions): void; + monitor(): Promise; + destroy(error?: any): Promise; + signal(signo: number): void; + getTcpPort(port: number): Fetcher; + setInactivityTimeout(durationMs: number | bigint): Promise; + interceptOutboundHttp(addr: string, binding: Fetcher): Promise; + interceptAllOutboundHttp(binding: Fetcher): Promise; } interface ContainerStartupOptions { - entrypoint?: string[] - enableInternet: boolean - env?: Record - hardTimeout?: number | bigint + entrypoint?: string[]; + enableInternet: boolean; + env?: Record; + hardTimeout?: (number | bigint); } /** * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. @@ -3735,26 +3234,26 @@ interface ContainerStartupOptions { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) */ declare abstract class MessagePort extends EventTarget { - /** - * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) - */ - postMessage(data?: any, options?: any[] | MessagePortPostMessageOptions): void - /** - * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) - */ - close(): void - /** - * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) - */ - start(): void - get onmessage(): any | null - set onmessage(value: any | null) + /** + * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) + */ + postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void; + /** + * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) + */ + close(): void; + /** + * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) + */ + start(): void; + get onmessage(): any | null; + set onmessage(value: any | null); } /** * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. @@ -3762,3988 +3261,5826 @@ declare abstract class MessagePort extends EventTarget { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel) */ declare class MessageChannel { - constructor() - /** - * The **`port1`** read-only property of the the port attached to the context that originated the channel. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) - */ - readonly port1: MessagePort - /** - * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) - */ - readonly port2: MessagePort + constructor(); + /** + * The **`port1`** read-only property of the the port attached to the context that originated the channel. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) + */ + readonly port1: MessagePort; + /** + * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) + */ + readonly port2: MessagePort; } interface MessagePortPostMessageOptions { - transfer?: any[] + transfer?: any[]; } -type LoopbackForExport< - T extends - | (new (...args: any[]) => Rpc.EntrypointBranded) - | ExportedHandler - | undefined = undefined, -> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded - ? LoopbackServiceStub> - : T extends new (...args: any[]) => Rpc.DurableObjectBranded - ? LoopbackDurableObjectClass> - : T extends ExportedHandler - ? LoopbackServiceStub - : undefined -type LoopbackServiceStub< - T extends Rpc.WorkerEntrypointBranded | undefined = undefined, -> = Fetcher & - (T extends CloudflareWorkersModule.WorkerEntrypoint - ? (opts: { props?: Props }) => Fetcher - : (opts: { props?: any }) => Fetcher) -type LoopbackDurableObjectClass< - T extends Rpc.DurableObjectBranded | undefined = undefined, -> = DurableObjectClass & - (T extends CloudflareWorkersModule.DurableObject - ? (opts: { props?: Props }) => DurableObjectClass - : (opts: { props?: any }) => DurableObjectClass) +type LoopbackForExport Rpc.EntrypointBranded) | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass> : T extends ExportedHandler ? LoopbackServiceStub : undefined; +type LoopbackServiceStub = Fetcher & (T extends CloudflareWorkersModule.WorkerEntrypoint ? (opts: { + props?: Props; +}) => Fetcher : (opts: { + props?: any; +}) => Fetcher); +type LoopbackDurableObjectClass = DurableObjectClass & (T extends CloudflareWorkersModule.DurableObject ? (opts: { + props?: Props; +}) => DurableObjectClass : (opts: { + props?: any; +}) => DurableObjectClass); interface SyncKvStorage { - get(key: string): T | undefined - list(options?: SyncKvListOptions): Iterable<[string, T]> - put(key: string, value: T): void - delete(key: string): boolean + get(key: string): T | undefined; + list(options?: SyncKvListOptions): Iterable<[ + string, + T + ]>; + put(key: string, value: T): void; + delete(key: string): boolean; } interface SyncKvListOptions { - start?: string - startAfter?: string - end?: string - prefix?: string - reverse?: boolean - limit?: number + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; } interface WorkerStub { - getEntrypoint( - name?: string, - options?: WorkerStubEntrypointOptions, - ): Fetcher + getEntrypoint(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; } interface WorkerStubEntrypointOptions { - props?: any + props?: any; } interface WorkerLoader { - get( - name: string, - getCode: () => WorkerLoaderWorkerCode | Promise, - ): WorkerStub + get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; + load(code: WorkerLoaderWorkerCode): WorkerStub; } interface WorkerLoaderModule { - js?: string - cjs?: string - text?: string - data?: ArrayBuffer - json?: any - py?: string - wasm?: ArrayBuffer + js?: string; + cjs?: string; + text?: string; + data?: ArrayBuffer; + json?: any; + py?: string; + wasm?: ArrayBuffer; } interface WorkerLoaderWorkerCode { - compatibilityDate: string - compatibilityFlags?: string[] - allowExperimental?: boolean - mainModule: string - modules: Record - env?: any - globalOutbound?: Fetcher | null - tails?: Fetcher[] - streamingTails?: Fetcher[] + compatibilityDate: string; + compatibilityFlags?: string[]; + allowExperimental?: boolean; + mainModule: string; + modules: Record; + env?: any; + globalOutbound?: (Fetcher | null); + tails?: Fetcher[]; + streamingTails?: Fetcher[]; } /** - * The Workers runtime supports a subset of the Performance API, used to measure timing and performance, - * as well as timing of subrequests and other operations. - * - * [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) - */ +* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, +* as well as timing of subrequests and other operations. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) +*/ declare abstract class Performance { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ - get timeOrigin(): number - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ - now(): number + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ + get timeOrigin(): number; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ + now(): number; + /** + * The **`toJSON()`** method of the Performance interface is a Serialization; it returns a JSON representation of the Performance object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON) + */ + toJSON(): object; +} +// AI Search V2 API Error Interfaces +interface AiSearchInternalError extends Error { +} +interface AiSearchNotFoundError extends Error { +} +interface AiSearchNameNotSetError extends Error { +} +// AI Search V2 Request Types +type AiSearchSearchRequest = { + messages: Array<{ + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + }>; + ai_search_options?: { + retrieval?: { + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + /** Maximum number of results (1-50, default 10) */ + max_num_results?: number; + filters?: VectorizeVectorMetadataFilter; + /** Context expansion (0-3, default 0) */ + context_expansion?: number; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + /** Enable reranking (default false) */ + enabled?: boolean; + model?: '@cf/baai/bge-reranker-base' | ''; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + [key: string]: unknown; + }; + [key: string]: unknown; + }; +}; +type AiSearchChatCompletionsRequest = { + messages: Array<{ + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + }>; + model?: string; + stream?: boolean; + ai_search_options?: { + retrieval?: { + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + match_threshold?: number; + max_num_results?: number; + filters?: VectorizeVectorMetadataFilter; + context_expansion?: number; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + enabled?: boolean; + model?: '@cf/baai/bge-reranker-base' | ''; + match_threshold?: number; + [key: string]: unknown; + }; + [key: string]: unknown; + }; + [key: string]: unknown; +}; +// AI Search V2 Response Types +type AiSearchSearchResponse = { + search_query: string; + chunks: Array<{ + id: string; + type: string; + /** Match score (0-1) */ + score: number; + text: string; + item: { + timestamp?: number; + key: string; + metadata?: Record; + }; + scoring_details?: { + /** Keyword match score (0-1) */ + keyword_score?: number; + /** Vector similarity score (0-1) */ + vector_score?: number; + }; + }>; +}; +type AiSearchListResponse = Array<{ + id: string; + internal_id?: string; + account_id?: string; + account_tag?: string; + /** Whether the instance is enabled (default true) */ + enable?: boolean; + type?: 'r2' | 'web-crawler'; + source?: string; + [key: string]: unknown; +}>; +type AiSearchConfig = { + /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ + id: string; + type: 'r2' | 'web-crawler'; + source: string; + source_params?: object; + /** Token ID (UUID format) */ + token_id?: string; + ai_gateway_id?: string; + /** Enable query rewriting (default false) */ + rewrite_query?: boolean; + /** Enable reranking (default false) */ + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; +}; +type AiSearchInstance = { + id: string; + enable?: boolean; + type?: 'r2' | 'web-crawler'; + source?: string; + [key: string]: unknown; +}; +// AI Search Instance Service - Instance-level operations +declare abstract class AiSearchInstanceService { + /** + * Search the AI Search instance for relevant chunks. + * @param params Search request with messages and AI search options + * @returns Search response with matching chunks + */ + search(params: AiSearchSearchRequest): Promise; + /** + * Generate chat completions with AI Search context. + * @param params Chat completions request with optional streaming + * @returns Response object (if streaming) or chat completion result + */ + chatCompletions(params: AiSearchChatCompletionsRequest): Promise; + /** + * Delete this AI Search instance. + */ + delete(): Promise; +} +// AI Search Account Service - Account-level operations +declare abstract class AiSearchAccountService { + /** + * List all AI Search instances in the account. + * @returns Array of AI Search instances + */ + list(): Promise; + /** + * Get an AI Search instance by ID. + * @param name Instance ID + * @returns Instance service for performing operations + */ + get(name: string): AiSearchInstanceService; + /** + * Create a new AI Search instance. + * @param config Instance configuration + * @returns Instance service for performing operations + */ + create(config: AiSearchConfig): Promise; } type AiImageClassificationInput = { - image: number[] -} + image: number[]; +}; type AiImageClassificationOutput = { - score?: number - label?: string -}[] + score?: number; + label?: string; +}[]; declare abstract class BaseAiImageClassification { - inputs: AiImageClassificationInput - postProcessedOutputs: AiImageClassificationOutput + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; } type AiImageToTextInput = { - image: number[] - prompt?: string - max_tokens?: number - temperature?: number - top_p?: number - top_k?: number - seed?: number - repetition_penalty?: number - frequency_penalty?: number - presence_penalty?: number - raw?: boolean - messages?: RoleScopedChatInput[] -} + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; type AiImageToTextOutput = { - description: string -} + description: string; +}; declare abstract class BaseAiImageToText { - inputs: AiImageToTextInput - postProcessedOutputs: AiImageToTextOutput + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; } type AiImageTextToTextInput = { - image: string - prompt?: string - max_tokens?: number - temperature?: number - ignore_eos?: boolean - top_p?: number - top_k?: number - seed?: number - repetition_penalty?: number - frequency_penalty?: number - presence_penalty?: number - raw?: boolean - messages?: RoleScopedChatInput[] -} + image: string; + prompt?: string; + max_tokens?: number; + temperature?: number; + ignore_eos?: boolean; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; type AiImageTextToTextOutput = { - description: string -} + description: string; +}; declare abstract class BaseAiImageTextToText { - inputs: AiImageTextToTextInput - postProcessedOutputs: AiImageTextToTextOutput + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; } type AiMultimodalEmbeddingsInput = { - image: string - text: string[] -} + image: string; + text: string[]; +}; type AiIMultimodalEmbeddingsOutput = { - data: number[][] - shape: number[] -} + data: number[][]; + shape: number[]; +}; declare abstract class BaseAiMultimodalEmbeddings { - inputs: AiImageTextToTextInput - postProcessedOutputs: AiImageTextToTextOutput + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; } type AiObjectDetectionInput = { - image: number[] -} + image: number[]; +}; type AiObjectDetectionOutput = { - score?: number - label?: string -}[] + score?: number; + label?: string; +}[]; declare abstract class BaseAiObjectDetection { - inputs: AiObjectDetectionInput - postProcessedOutputs: AiObjectDetectionOutput + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; } type AiSentenceSimilarityInput = { - source: string - sentences: string[] -} -type AiSentenceSimilarityOutput = number[] + source: string; + sentences: string[]; +}; +type AiSentenceSimilarityOutput = number[]; declare abstract class BaseAiSentenceSimilarity { - inputs: AiSentenceSimilarityInput - postProcessedOutputs: AiSentenceSimilarityOutput + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; } type AiAutomaticSpeechRecognitionInput = { - audio: number[] -} + audio: number[]; +}; type AiAutomaticSpeechRecognitionOutput = { - text?: string - words?: { - word: string - start: number - end: number - }[] - vtt?: string -} + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; declare abstract class BaseAiAutomaticSpeechRecognition { - inputs: AiAutomaticSpeechRecognitionInput - postProcessedOutputs: AiAutomaticSpeechRecognitionOutput + inputs: AiAutomaticSpeechRecognitionInput; + postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; } type AiSummarizationInput = { - input_text: string - max_length?: number -} + input_text: string; + max_length?: number; +}; type AiSummarizationOutput = { - summary: string -} + summary: string; +}; declare abstract class BaseAiSummarization { - inputs: AiSummarizationInput - postProcessedOutputs: AiSummarizationOutput + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; } type AiTextClassificationInput = { - text: string -} + text: string; +}; type AiTextClassificationOutput = { - score?: number - label?: string -}[] + score?: number; + label?: string; +}[]; declare abstract class BaseAiTextClassification { - inputs: AiTextClassificationInput - postProcessedOutputs: AiTextClassificationOutput + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; } type AiTextEmbeddingsInput = { - text: string | string[] -} + text: string | string[]; +}; type AiTextEmbeddingsOutput = { - shape: number[] - data: number[][] -} + shape: number[]; + data: number[][]; +}; declare abstract class BaseAiTextEmbeddings { - inputs: AiTextEmbeddingsInput - postProcessedOutputs: AiTextEmbeddingsOutput + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; } type RoleScopedChatInput = { - role: - | 'user' - | 'assistant' - | 'system' - | 'tool' - | (string & NonNullable) - content: string - name?: string -} + role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); + content: string; + name?: string; +}; type AiTextGenerationToolLegacyInput = { - name: string - description: string - parameters?: { - type: 'object' | (string & NonNullable) - properties: { - [key: string]: { - type: string - description?: string - } - } - required: string[] - } -} -type AiTextGenerationToolInput = { - type: 'function' | (string & NonNullable) - function: { - name: string - description: string + name: string; + description: string; parameters?: { - type: 'object' | (string & NonNullable) - properties: { - [key: string]: { - type: string - description?: string - } - } - required: string[] - } - } -} + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; +}; +type AiTextGenerationToolInput = { + type: "function" | (string & NonNullable); + function: { + name: string; + description: string; + parameters?: { + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; + }; +}; type AiTextGenerationFunctionsInput = { - name: string - code: string -} + name: string; + code: string; +}; type AiTextGenerationResponseFormat = { - type: string - json_schema?: any -} + type: string; + json_schema?: any; +}; type AiTextGenerationInput = { - prompt?: string - raw?: boolean - stream?: boolean - max_tokens?: number - temperature?: number - top_p?: number - top_k?: number - seed?: number - repetition_penalty?: number - frequency_penalty?: number - presence_penalty?: number - messages?: RoleScopedChatInput[] - response_format?: AiTextGenerationResponseFormat - tools?: - | AiTextGenerationToolInput[] - | AiTextGenerationToolLegacyInput[] - | (object & NonNullable) - functions?: AiTextGenerationFunctionsInput[] -} + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + temperature?: number; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + messages?: RoleScopedChatInput[]; + response_format?: AiTextGenerationResponseFormat; + tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable); + functions?: AiTextGenerationFunctionsInput[]; +}; type AiTextGenerationToolLegacyOutput = { - name: string - arguments: unknown -} + name: string; + arguments: unknown; +}; type AiTextGenerationToolOutput = { - id: string - type: 'function' - function: { - name: string - arguments: string - } -} + id: string; + type: "function"; + function: { + name: string; + arguments: string; + }; +}; type UsageTags = { - prompt_tokens: number - completion_tokens: number - total_tokens: number -} + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; +}; type AiTextGenerationOutput = { - response?: string - tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[] - usage?: UsageTags -} + response?: string; + tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; + usage?: UsageTags; +}; declare abstract class BaseAiTextGeneration { - inputs: AiTextGenerationInput - postProcessedOutputs: AiTextGenerationOutput + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; } type AiTextToSpeechInput = { - prompt: string - lang?: string -} -type AiTextToSpeechOutput = - | Uint8Array - | { - audio: string - } + prompt: string; + lang?: string; +}; +type AiTextToSpeechOutput = Uint8Array | { + audio: string; +}; declare abstract class BaseAiTextToSpeech { - inputs: AiTextToSpeechInput - postProcessedOutputs: AiTextToSpeechOutput + inputs: AiTextToSpeechInput; + postProcessedOutputs: AiTextToSpeechOutput; } type AiTextToImageInput = { - prompt: string - negative_prompt?: string - height?: number - width?: number - image?: number[] - image_b64?: string - mask?: number[] - num_steps?: number - strength?: number - guidance?: number - seed?: number -} -type AiTextToImageOutput = ReadableStream + prompt: string; + negative_prompt?: string; + height?: number; + width?: number; + image?: number[]; + image_b64?: string; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; + seed?: number; +}; +type AiTextToImageOutput = ReadableStream; declare abstract class BaseAiTextToImage { - inputs: AiTextToImageInput - postProcessedOutputs: AiTextToImageOutput + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; } type AiTranslationInput = { - text: string - target_lang: string - source_lang?: string -} + text: string; + target_lang: string; + source_lang?: string; +}; type AiTranslationOutput = { - translated_text?: string -} + translated_text?: string; +}; declare abstract class BaseAiTranslation { - inputs: AiTranslationInput - postProcessedOutputs: AiTranslationOutput + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; } -type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = - | { - text: string | string[] - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: 'mean' | 'cls' - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[] +/** + * Workers AI support for OpenAI's Responses API + * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts + * + * It's a stripped down version from its source. + * It currently supports basic function calling, json mode and accepts images as input. + * + * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. + * We plan to add those incrementally as model + platform capabilities evolve. + */ +type ResponsesInput = { + background?: boolean | null; + conversation?: string | ResponseConversationParam | null; + include?: Array | null; + input?: string | ResponseInput; + instructions?: string | null; + max_output_tokens?: number | null; + parallel_tool_calls?: boolean | null; + previous_response_id?: string | null; + prompt_cache_key?: string; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + stream?: boolean | null; + stream_options?: StreamOptions | null; + temperature?: number | null; + text?: ResponseTextConfig; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + truncation?: "auto" | "disabled" | null; +}; +type ResponsesOutput = { + id?: string; + created_at?: number; + output_text?: string; + error?: ResponseError | null; + incomplete_details?: ResponseIncompleteDetails | null; + instructions?: string | Array | null; + object?: "response"; + output?: Array; + parallel_tool_calls?: boolean; + temperature?: number | null; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + max_output_tokens?: number | null; + previous_response_id?: string | null; + prompt?: ResponsePrompt | null; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + status?: ResponseStatus; + text?: ResponseTextConfig; + truncation?: "auto" | "disabled" | null; + usage?: ResponseUsage; +}; +type EasyInputMessage = { + content: string | ResponseInputMessageContentList; + role: "user" | "assistant" | "system" | "developer"; + type?: "message"; +}; +type ResponsesFunctionTool = { + name: string; + parameters: { + [key: string]: unknown; + } | null; + strict: boolean | null; + type: "function"; + description?: string | null; +}; +type ResponseIncompleteDetails = { + reason?: "max_output_tokens" | "content_filter"; +}; +type ResponsePrompt = { + id: string; + variables?: { + [key: string]: string | ResponseInputText | ResponseInputImage; + } | null; + version?: string | null; +}; +type Reasoning = { + effort?: ReasoningEffort | null; + generate_summary?: "auto" | "concise" | "detailed" | null; + summary?: "auto" | "concise" | "detailed" | null; +}; +type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText; +type ResponseContentReasoningText = { + text: string; + type: "reasoning_text"; +}; +type ResponseConversationParam = { + id: string; +}; +type ResponseCreatedEvent = { + response: Response; + sequence_number: number; + type: "response.created"; +}; +type ResponseCustomToolCallOutput = { + call_id: string; + output: string | Array; + type: "custom_tool_call_output"; + id?: string; +}; +type ResponseError = { + code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found"; + message: string; +}; +type ResponseErrorEvent = { + code: string | null; + message: string; + param: string | null; + sequence_number: number; + type: "error"; +}; +type ResponseFailedEvent = { + response: Response; + sequence_number: number; + type: "response.failed"; +}; +type ResponseFormatText = { + type: "text"; +}; +type ResponseFormatJSONObject = { + type: "json_object"; +}; +type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; +type ResponseFormatTextJSONSchemaConfig = { + name: string; + schema: { + [key: string]: unknown; + }; + type: "json_schema"; + description?: string; + strict?: boolean | null; +}; +type ResponseFunctionCallArgumentsDeltaEvent = { + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.delta"; +}; +type ResponseFunctionCallArgumentsDoneEvent = { + arguments: string; + item_id: string; + name: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.done"; +}; +type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; +type ResponseFunctionCallOutputItemList = Array; +type ResponseFunctionToolCall = { + arguments: string; + call_id: string; + name: string; + type: "function_call"; + id?: string; + status?: "in_progress" | "completed" | "incomplete"; +}; +interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { + id: string; +} +type ResponseFunctionToolCallOutputItem = { + id: string; + call_id: string; + output: string | Array; + type: "function_call_output"; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs"; +type ResponseIncompleteEvent = { + response: Response; + sequence_number: number; + type: "response.incomplete"; +}; +type ResponseInput = Array; +type ResponseInputContent = ResponseInputText | ResponseInputImage; +type ResponseInputImage = { + detail: "low" | "high" | "auto"; + type: "input_image"; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputImageContent = { + type: "input_image"; + detail?: "low" | "high" | "auto" | null; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem; +type ResponseInputItemFunctionCallOutput = { + call_id: string; + output: string | ResponseFunctionCallOutputItemList; + type: "function_call_output"; + id?: string | null; + status?: "in_progress" | "completed" | "incomplete" | null; +}; +type ResponseInputItemMessage = { + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputMessageContentList = Array; +type ResponseInputMessageItem = { + id: string; + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputText = { + text: string; + type: "input_text"; +}; +type ResponseInputTextContent = { + text: string; + type: "input_text"; +}; +type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; +type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; +type ResponseOutputItemAddedEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.added"; +}; +type ResponseOutputItemDoneEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.done"; +}; +type ResponseOutputMessage = { + id: string; + content: Array; + role: "assistant"; + status: "in_progress" | "completed" | "incomplete"; + type: "message"; +}; +type ResponseOutputRefusal = { + refusal: string; + type: "refusal"; +}; +type ResponseOutputText = { + text: string; + type: "output_text"; + logprobs?: Array; +}; +type ResponseReasoningItem = { + id: string; + summary: Array; + type: "reasoning"; + content?: Array; + encrypted_content?: string | null; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseReasoningSummaryItem = { + text: string; + type: "summary_text"; +}; +type ResponseReasoningContentItem = { + text: string; + type: "reasoning_text"; +}; +type ResponseReasoningTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.reasoning_text.delta"; +}; +type ResponseReasoningTextDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + sequence_number: number; + text: string; + type: "response.reasoning_text.done"; +}; +type ResponseRefusalDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.refusal.delta"; +}; +type ResponseRefusalDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + refusal: string; + sequence_number: number; + type: "response.refusal.done"; +}; +type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete"; +type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent; +type ResponseCompletedEvent = { + response: Response; + sequence_number: number; + type: "response.completed"; +}; +type ResponseTextConfig = { + format?: ResponseFormatTextConfig; + verbosity?: "low" | "medium" | "high" | null; +}; +type ResponseTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + type: "response.output_text.delta"; +}; +type ResponseTextDoneEvent = { + content_index: number; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + text: string; + type: "response.output_text.done"; +}; +type Logprob = { + token: string; + logprob: number; + top_logprobs?: Array; +}; +type TopLogprob = { + token?: string; + logprob?: number; +}; +type ResponseUsage = { + input_tokens: number; + output_tokens: number; + total_tokens: number; +}; +type Tool = ResponsesFunctionTool; +type ToolChoiceFunction = { + name: string; + type: "function"; +}; +type ToolChoiceOptions = "none"; +type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; +type StreamOptions = { + include_obfuscation?: boolean; +}; +type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; /** * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ - pooling?: 'mean' | 'cls' - }[] - } -type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = - | { - shape?: number[] - /** - * Embeddings of the requested text values - */ - data?: number[][] - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls' - } - | AsyncResponse -interface AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; } declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input - postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output + inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; } -type Ai_Cf_Openai_Whisper_Input = - | string - | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[] - } +type Ai_Cf_Openai_Whisper_Input = string | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; +}; interface Ai_Cf_Openai_Whisper_Output { - /** - * The transcription - */ - text: string - word_count?: number - words?: { - word?: string /** - * The second this word begins in the recording + * The transcription */ - start?: number - /** - * The ending second when the word completes - */ - end?: number - }[] - vtt?: string + text: string; + word_count?: number; + words?: { + word?: string; + /** + * The second this word begins in the recording + */ + start?: number; + /** + * The ending second when the word completes + */ + end?: number; + }[]; + vtt?: string; } declare abstract class Base_Ai_Cf_Openai_Whisper { - inputs: Ai_Cf_Openai_Whisper_Input - postProcessedOutputs: Ai_Cf_Openai_Whisper_Output + inputs: Ai_Cf_Openai_Whisper_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; } -type Ai_Cf_Meta_M2M100_1_2B_Input = - | { - /** - * The text to be translated - */ - text: string - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { +type Ai_Cf_Meta_M2M100_1_2B_Input = { + /** + * The text to be translated + */ + text: string; + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { /** * The text to be translated */ - text: string + text: string; /** * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified */ - source_lang?: string + source_lang?: string; /** * The language code to translate the text into (e.g., 'es' for Spanish) */ - target_lang: string - }[] - } -type Ai_Cf_Meta_M2M100_1_2B_Output = - | { - /** - * The translated text in the target language - */ - translated_text?: string - } - | AsyncResponse + target_lang: string; + }[]; +}; +type Ai_Cf_Meta_M2M100_1_2B_Output = { + /** + * The translated text in the target language + */ + translated_text?: string; +} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; +interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { - inputs: Ai_Cf_Meta_M2M100_1_2B_Input - postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output + inputs: Ai_Cf_Meta_M2M100_1_2B_Input; + postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; } -type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = - | { - text: string | string[] - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: 'mean' | 'cls' - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[] +type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; /** * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ - pooling?: 'mean' | 'cls' - }[] - } -type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = - | { - shape?: number[] - /** - * Embeddings of the requested text values - */ - data?: number[][] - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls' - } - | AsyncResponse + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input - postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output + inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; } -type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = - | { - text: string | string[] - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: 'mean' | 'cls' - } - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[] +type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; /** * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. */ - pooling?: 'mean' | 'cls' - }[] - } -type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = - | { - shape?: number[] - /** - * Embeddings of the requested text values - */ - data?: number[][] - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls' - } - | AsyncResponse + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input - postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output + inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; } -type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = - | string - | { - /** - * The input text prompt for the model to generate a response. - */ - prompt?: string - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number - image: number[] | (string & NonNullable) - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - } -interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { - description?: string -} -declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { - inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input - postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output -} -type Ai_Cf_Openai_Whisper_Tiny_En_Input = - | string - | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[] - } -interface Ai_Cf_Openai_Whisper_Tiny_En_Output { - /** - * The transcription - */ - text: string - word_count?: number - words?: { - word?: string +type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | { /** - * The second this word begins in the recording + * The input text prompt for the model to generate a response. */ - start?: number + prompt?: string; /** - * The ending second when the word completes + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ - end?: number - }[] - vtt?: string -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { - inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input - postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output -} -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { - /** - * Base64 encoded value of the audio data. - */ - audio: string - /** - * Supported tasks are 'translate' or 'transcribe'. - */ - task?: string - /** - * The language of the audio being transcribed or translated. - */ - language?: string - /** - * Preprocess the audio with a voice activity detection model. - */ - vad_filter?: boolean - /** - * A text prompt to help provide context to the model on the contents of the audio. - */ - initial_prompt?: string - /** - * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. - */ - prefix?: string -} -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { - transcription_info?: { + raw?: boolean; /** - * The language of the audio being transcribed or translated. + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. */ - language?: string + top_p?: number; /** - * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. */ - language_probability?: number - /** - * The total duration of the original audio file, in seconds. - */ - duration?: number - /** - * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. - */ - duration_after_vad?: number - } - /** - * The complete transcription of the audio. - */ - text: string - /** - * The total number of words in the transcription. - */ - word_count?: number - segments?: { - /** - * The starting time of the segment within the audio, in seconds. - */ - start?: number - /** - * The ending time of the segment within the audio, in seconds. - */ - end?: number - /** - * The transcription of the segment. - */ - text?: string - /** - * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. - */ - temperature?: number - /** - * The average log probability of the predictions for the words in this segment, indicating overall confidence. - */ - avg_logprob?: number - /** - * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. - */ - compression_ratio?: number - /** - * The probability that the segment contains no speech, represented as a decimal between 0 and 1. - */ - no_speech_prob?: number - words?: { - /** - * The individual word transcribed from the audio. - */ - word?: string - /** - * The starting time of the word within the audio, in seconds. - */ - start?: number - /** - * The ending time of the word within the audio, in seconds. - */ - end?: number - }[] - }[] - /** - * The transcription in WebVTT format, which includes timing and text information for use in subtitles. - */ - vtt?: string -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { - inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input - postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output -} -type Ai_Cf_Baai_Bge_M3_Input = - | BGEM3InputQueryAndContexts - | BGEM3InputEmbedding - | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: (BGEM3InputQueryAndContexts1 | BGEM3InputEmbedding1)[] - } -interface BGEM3InputQueryAndContexts { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string - }[] - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean -} -interface BGEM3InputEmbedding { - text: string | string[] - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean -} -interface BGEM3InputQueryAndContexts1 { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string - }[] - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean -} -interface BGEM3InputEmbedding1 { - text: string | string[] - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean -} -type Ai_Cf_Baai_Bge_M3_Output = - | BGEM3OuputQuery - | BGEM3OutputEmbeddingForContexts - | BGEM3OuputEmbedding - | AsyncResponse -interface BGEM3OuputQuery { - response?: { - /** - * Index of the context in the request - */ - id?: number - /** - * Score of the context under the index. - */ - score?: number - }[] -} -interface BGEM3OutputEmbeddingForContexts { - response?: number[][] - shape?: number[] - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls' -} -interface BGEM3OuputEmbedding { - shape?: number[] - /** - * Embeddings of the requested text values - */ - data?: number[][] - /** - * The pooling method used in the embedding process. - */ - pooling?: 'mean' | 'cls' -} -declare abstract class Base_Ai_Cf_Baai_Bge_M3 { - inputs: Ai_Cf_Baai_Bge_M3_Input - postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string - /** - * The number of diffusion steps; higher values can improve quality but take longer. - */ - steps?: number -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { - /** - * The generated image in Base64 format. - */ - image?: string -} -declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { - inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input - postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Prompt | Messages -interface Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string - image?: number[] | (string & NonNullable) - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string -} -interface Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string - text?: string - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string - } - }[] - | { - /** - * Type of the content provided - */ - type?: string - text?: string - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string - } - } - }[] - image?: number[] | (string & NonNullable) - functions?: { - name: string - code: string - }[] - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string - /** - * A brief description of what the tool does. - */ - description: string - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string - /** - * List of required parameter names. - */ - required?: string[] - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string - /** - * A description of the expected parameter. - */ - description: string - } - } - } - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string - /** - * A brief description of what the function does. - */ - description: string - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string - /** - * List of required parameter names. - */ - required?: string[] - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string - /** - * A description of the expected parameter. - */ - description: string - } - } - } - } - } - )[] - /** - * If true, the response will be streamed back incrementally. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { - /** - * The generated text response from the model - */ - response?: string - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object - /** - * The name of the tool to be called - */ - name?: string - }[] -} -declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { - inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input - postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = - | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt - | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages - | AsyncBatch -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string - response_format?: JSONMode - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number -} -interface JSONMode { - type?: 'json_object' | 'json_schema' - json_schema?: unknown -} -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string - /** - * The content of the message as a string. - */ - content: string - }[] - functions?: { - name: string - code: string - }[] - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { - /** - * The name of the tool. More descriptive the better. - */ - name: string - /** - * A brief description of what the tool does. - */ - description: string - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string - /** - * List of required parameter names. - */ - required?: string[] - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string - /** - * A description of the expected parameter. - */ - description: string - } - } - } - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string - /** - * A brief description of what the function does. - */ - description: string - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string - /** - * List of required parameter names. - */ - required?: string[] - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string - /** - * A description of the expected parameter. - */ - description: string - } - } - } - } - } - )[] - response_format?: JSONMode - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number -} -interface AsyncBatch { - requests?: { - /** - * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. - */ - external_reference?: string - /** - * Prompt for the text generation model - */ - prompt?: string - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number + top_k?: number; /** * Random seed for reproducibility of the generation. */ - seed?: number + seed?: number; /** * Penalty for repeated tokens; higher values discourage repetition. */ - repetition_penalty?: number + repetition_penalty?: number; /** * Decreases the likelihood of the model repeating the same lines verbatim. */ - frequency_penalty?: number + frequency_penalty?: number; /** * Increases the likelihood of the model introducing new topics. */ - presence_penalty?: number - response_format?: JSONMode - }[] + presence_penalty?: number; + image: number[] | (string & NonNullable); + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; +}; +interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { + description?: string; } -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = - | { - /** - * The generated text response from the model - */ - response: string - /** - * Usage statistics for the inference request - */ - usage?: { +declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { + inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; + postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; +} +type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; +}; +interface Ai_Cf_Openai_Whisper_Tiny_En_Output { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; /** - * Total number of tokens in input + * The second this word begins in the recording */ - prompt_tokens?: number + start?: number; /** - * Total number of tokens in output + * The ending second when the word completes */ - completion_tokens?: number + end?: number; + }[]; + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { + inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { + /** + * Base64 encoded value of the audio data. + */ + audio: string; + /** + * Supported tasks are 'translate' or 'transcribe'. + */ + task?: string; + /** + * The language of the audio being transcribed or translated. + */ + language?: string; + /** + * Preprocess the audio with a voice activity detection model. + */ + vad_filter?: boolean; + /** + * A text prompt to help provide context to the model on the contents of the audio. + */ + initial_prompt?: string; + /** + * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. + */ + prefix?: string; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { + transcription_info?: { /** - * Total number of input and output tokens + * The language of the audio being transcribed or translated. */ - total_tokens?: number - } - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { + language?: string; + /** + * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. + */ + language_probability?: number; + /** + * The total duration of the original audio file, in seconds. + */ + duration?: number; + /** + * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. + */ + duration_after_vad?: number; + }; + /** + * The complete transcription of the audio. + */ + text: string; + /** + * The total number of words in the transcription. + */ + word_count?: number; + segments?: { + /** + * The starting time of the segment within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the segment within the audio, in seconds. + */ + end?: number; + /** + * The transcription of the segment. + */ + text?: string; + /** + * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. + */ + temperature?: number; + /** + * The average log probability of the predictions for the words in this segment, indicating overall confidence. + */ + avg_logprob?: number; + /** + * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. + */ + compression_ratio?: number; + /** + * The probability that the segment contains no speech, represented as a decimal between 0 and 1. + */ + no_speech_prob?: number; + words?: { + /** + * The individual word transcribed from the audio. + */ + word?: string; + /** + * The starting time of the word within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the word within the audio, in seconds. + */ + end?: number; + }[]; + }[]; + /** + * The transcription in WebVTT format, which includes timing and text information for use in subtitles. + */ + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { + inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; +} +type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[]; +}; +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_Embedding { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Ouput_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Ouput_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse; +interface Ai_Cf_Baai_Bge_M3_Ouput_Query { + response?: { + /** + * Index of the context in the request + */ + id?: number; + /** + * Score of the context under the index. + */ + score?: number; + }[]; +} +interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { + response?: number[][]; + shape?: number[]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} +interface Ai_Cf_Baai_Bge_M3_Ouput_Embedding { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} +interface Ai_Cf_Baai_Bge_M3_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_M3 { + inputs: Ai_Cf_Baai_Bge_M3_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * The number of diffusion steps; higher values can improve quality but take longer. + */ + steps?: number; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { + /** + * The generated image in Base64 format. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { + inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; +} +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + image?: number[] | (string & NonNullable); + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; +} +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + image?: number[] | (string & NonNullable); + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * If true, the response will be streamed back incrementally. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { + /** + * The generated text response from the model + */ + response?: string; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { /** * The arguments passed to be passed to the tool call request */ - arguments?: object + arguments?: object; /** * The name of the tool to be called */ - name?: string - }[] - } - | string - | AsyncResponse + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { + inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { + requests?: { + /** + * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. + */ + external_reference?: string; + /** + * Prompt for the text generation model + */ + prompt?: string; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; + }[]; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { - inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input - postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output + inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; } interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { - /** - * An array of message objects representing the conversation history. - */ - messages: { /** - * The role of the message sender must alternate between 'user' and 'assistant'. + * An array of message objects representing the conversation history. */ - role: 'user' | 'assistant' + messages: { + /** + * The role of the message sender must alternate between 'user' and 'assistant'. + */ + role: "user" | "assistant"; + /** + * The content of the message as a string. + */ + content: string; + }[]; /** - * The content of the message as a string. + * The maximum number of tokens to generate in the response. */ - content: string - }[] - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Dictate the output format of the generated response. - */ - response_format?: { + max_tokens?: number; /** - * Set to json_object to process and output generated text as JSON. + * Controls the randomness of the output; higher values produce more random results. */ - type?: string - } + temperature?: number; + /** + * Dictate the output format of the generated response. + */ + response_format?: { + /** + * Set to json_object to process and output generated text as JSON. + */ + type?: string; + }; } interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { - response?: - | string - | { + response?: string | { /** * Whether the conversation is safe or not. */ - safe?: boolean + safe?: boolean; /** * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. */ - categories?: string[] - } - /** - * Usage statistics for the inference request - */ - usage?: { + categories?: string[]; + }; /** - * Total number of tokens in input + * Usage statistics for the inference request */ - prompt_tokens?: number - /** - * Total number of tokens in output - */ - completion_tokens?: number - /** - * Total number of input and output tokens - */ - total_tokens?: number - } + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; } declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { - inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input - postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output + inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; } interface Ai_Cf_Baai_Bge_Reranker_Base_Input { - /** - * A query you wish to perform against the provided contexts. - */ - /** - * Number of returned results starting with the best score. - */ - top_k?: number - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { /** - * One of the provided context content + * A query you wish to perform against the provided contexts. */ - text?: string - }[] + /** + * Number of returned results starting with the best score. + */ + top_k?: number; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; } interface Ai_Cf_Baai_Bge_Reranker_Base_Output { - response?: { - /** - * Index of the context in the request - */ - id?: number - /** - * Score of the context under the index. - */ - score?: number - }[] + response?: { + /** + * Index of the context in the request + */ + id?: number; + /** + * Score of the context under the index. + */ + score?: number; + }[]; } declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { - inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input - postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output + inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; } -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = - | Qwen2_5_Coder_32B_Instruct_Prompt - | Qwen2_5_Coder_32B_Instruct_Messages -interface Qwen2_5_Coder_32B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string - response_format?: JSONMode - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } -interface Qwen2_5_Coder_32B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + * An array of message objects representing the conversation history. */ - role: string + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; /** - * The content of the message as a string. + * A list of tools available for the assistant to use. */ - content: string - }[] - functions?: { - name: string - code: string - }[] - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { + tools?: ({ /** * The name of the tool. More descriptive the better. */ - name: string + name: string; /** * A brief description of what the tool does. */ - description: string + description: string; /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string - /** - * List of required parameter names. - */ - required?: string[] - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string - /** - * A description of the expected parameter. - */ - description: string - } - } - } - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string - /** - * A brief description of what the function does. - */ - description: string - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { /** * The type of the parameters object (usually 'object'). */ - type: string + type: string; /** * List of required parameter names. */ - required?: string[] + required?: string[]; /** * Definitions of each parameter. */ properties: { - [k: string]: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { /** - * The data type of the parameter. + * The type of the parameters object (usually 'object'). */ - type: string + type: string; /** - * A description of the expected parameter. + * List of required parameter names. */ - description: string - } - } - } - } - } - )[] - response_format?: JSONMode - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; } type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string - /** - * Usage statistics for the inference request - */ - usage?: { /** - * Total number of tokens in input + * The generated text response from the model */ - prompt_tokens?: number + response: string; /** - * Total number of tokens in output + * Usage statistics for the inference request */ - completion_tokens?: number + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; /** - * Total number of input and output tokens + * An array of tool calls requests made during the response generation */ - total_tokens?: number - } - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object - /** - * The name of the tool to be called - */ - name?: string - }[] -} + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { - inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input - postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output + inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; } -type Ai_Cf_Qwen_Qwq_32B_Input = Qwen_Qwq_32B_Prompt | Qwen_Qwq_32B_Messages -interface Qwen_Qwq_32B_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number +type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; +interface Ai_Cf_Qwen_Qwq_32B_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } -interface Qwen_Qwq_32B_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { +interface Ai_Cf_Qwen_Qwq_32B_Messages { /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + * An array of message objects representing the conversation history. */ - role?: string + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + * A list of tools available for the assistant to use. */ - tool_call_id?: string - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string - text?: string - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string - } - }[] - | { - /** - * Type of the content provided - */ - type?: string - text?: string - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string - } - } - }[] - functions?: { - name: string - code: string - }[] - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { + tools?: ({ /** * The name of the tool. More descriptive the better. */ - name: string + name: string; /** * A brief description of what the tool does. */ - description: string + description: string; /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string - /** - * List of required parameter names. - */ - required?: string[] - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string - /** - * A description of the expected parameter. - */ - description: string - } - } - } - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string - /** - * A brief description of what the function does. - */ - description: string - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { /** * The type of the parameters object (usually 'object'). */ - type: string + type: string; /** * List of required parameter names. */ - required?: string[] + required?: string[]; /** * Definitions of each parameter. */ properties: { - [k: string]: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { /** - * The data type of the parameter. + * The type of the parameters object (usually 'object'). */ - type: string + type: string; /** - * A description of the expected parameter. + * List of required parameter names. */ - description: string - } - } - } - } - } - )[] - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } type Ai_Cf_Qwen_Qwq_32B_Output = { - /** - * The generated text response from the model - */ - response: string - /** - * Usage statistics for the inference request - */ - usage?: { /** - * Total number of tokens in input + * The generated text response from the model */ - prompt_tokens?: number + response: string; /** - * Total number of tokens in output + * Usage statistics for the inference request */ - completion_tokens?: number + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; /** - * Total number of input and output tokens + * An array of tool calls requests made during the response generation */ - total_tokens?: number - } - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object - /** - * The name of the tool to be called - */ - name?: string - }[] -} + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { - inputs: Ai_Cf_Qwen_Qwq_32B_Input - postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output + inputs: Ai_Cf_Qwen_Qwq_32B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; } -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = - | Mistral_Small_3_1_24B_Instruct_Prompt - | Mistral_Small_3_1_24B_Instruct_Messages -interface Mistral_Small_3_1_24B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } -interface Mistral_Small_3_1_24B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + * An array of message objects representing the conversation history. */ - role?: string + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + * A list of tools available for the assistant to use. */ - tool_call_id?: string - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string - text?: string - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string - } - }[] - | { - /** - * Type of the content provided - */ - type?: string - text?: string - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string - } - } - }[] - functions?: { - name: string - code: string - }[] - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { + tools?: ({ /** * The name of the tool. More descriptive the better. */ - name: string + name: string; /** * A brief description of what the tool does. */ - description: string + description: string; /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string - /** - * List of required parameter names. - */ - required?: string[] - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string - /** - * A description of the expected parameter. - */ - description: string - } - } - } - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string - /** - * A brief description of what the function does. - */ - description: string - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { /** * The type of the parameters object (usually 'object'). */ - type: string + type: string; /** * List of required parameter names. */ - required?: string[] + required?: string[]; /** * Definitions of each parameter. */ properties: { - [k: string]: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { /** - * The data type of the parameter. + * The type of the parameters object (usually 'object'). */ - type: string + type: string; /** - * A description of the expected parameter. + * List of required parameter names. */ - description: string - } - } - } - } - } - )[] - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string - /** - * Usage statistics for the inference request - */ - usage?: { /** - * Total number of tokens in input + * The generated text response from the model */ - prompt_tokens?: number + response: string; /** - * Total number of tokens in output + * Usage statistics for the inference request */ - completion_tokens?: number + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; /** - * Total number of input and output tokens + * An array of tool calls requests made during the response generation */ - total_tokens?: number - } - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object - /** - * The name of the tool to be called - */ - name?: string - }[] -} + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { - inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input - postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output + inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; } -type Ai_Cf_Google_Gemma_3_12B_It_Input = - | Google_Gemma_3_12B_It_Prompt - | Google_Gemma_3_12B_It_Messages -interface Google_Gemma_3_12B_It_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number -} -interface Google_Gemma_3_12B_It_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { +type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages; +interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + * The input text prompt for the model to generate a response. */ - role?: string - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string - text?: string - image_url?: { + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Google_Gemma_3_12B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + content?: string | { /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + * Type of the content provided */ - url?: string - } - }[] - | { - /** - * Type of the content provided - */ - type?: string - text?: string - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string - } - } - }[] - functions?: { - name: string - code: string - }[] - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[]; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ /** * The name of the tool. More descriptive the better. */ - name: string + name: string; /** * A brief description of what the tool does. */ - description: string + description: string; /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string - /** - * List of required parameter names. - */ - required?: string[] - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string - /** - * A description of the expected parameter. - */ - description: string - } - } - } - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string - /** - * A brief description of what the function does. - */ - description: string - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { /** * The type of the parameters object (usually 'object'). */ - type: string + type: string; /** * List of required parameter names. */ - required?: string[] + required?: string[]; /** * Definitions of each parameter. */ properties: { - [k: string]: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { /** - * The data type of the parameter. + * The type of the parameters object (usually 'object'). */ - type: string + type: string; /** - * A description of the expected parameter. + * List of required parameter names. */ - description: string - } - } - } - } - } - )[] - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } type Ai_Cf_Google_Gemma_3_12B_It_Output = { - /** - * The generated text response from the model - */ - response: string - /** - * Usage statistics for the inference request - */ - usage?: { /** - * Total number of tokens in input + * The generated text response from the model */ - prompt_tokens?: number + response: string; /** - * Total number of tokens in output + * Usage statistics for the inference request */ - completion_tokens?: number + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; /** - * Total number of input and output tokens + * An array of tool calls requests made during the response generation */ - total_tokens?: number - } - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object - /** - * The name of the tool to be called - */ - name?: string - }[] -} + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { - inputs: Ai_Cf_Google_Gemma_3_12B_It_Input - postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output + inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; + postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; } -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = - | Ai_Cf_Meta_Llama_4_Prompt - | Ai_Cf_Meta_Llama_4_Messages - | Ai_Cf_Meta_Llama_4_Async_Batch -interface Ai_Cf_Meta_Llama_4_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object - response_format?: JSONMode - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + * An array of message objects representing the conversation history. */ - role?: string + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 + * A list of tools available for the assistant to use. */ - tool_call_id?: string - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string - text?: string - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string - } - }[] - | { - /** - * Type of the content provided - */ - type?: string - text?: string - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string - } - } - }[] - functions?: { - name: string - code: string - }[] - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { + tools?: ({ /** * The name of the tool. More descriptive the better. */ - name: string + name: string; /** * A brief description of what the tool does. */ - description: string + description: string; /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string - /** - * List of required parameter names. - */ - required?: string[] - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string - /** - * A description of the expected parameter. - */ - description: string - } - } - } - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string - /** - * A brief description of what the function does. - */ - description: string - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { /** * The type of the parameters object (usually 'object'). */ - type: string + type: string; /** * List of required parameter names. */ - required?: string[] + required?: string[]; /** * Definitions of each parameter. */ properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string - /** - * A description of the expected parameter. - */ - description: string - } - } - } - } - } - )[] - response_format?: JSONMode - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number -} -interface Ai_Cf_Meta_Llama_4_Async_Batch { - requests: ( - | Ai_Cf_Meta_Llama_4_Prompt_Inner - | Ai_Cf_Meta_Llama_4_Messages_Inner - )[] -} -interface Ai_Cf_Meta_Llama_4_Prompt_Inner { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object - response_format?: JSONMode - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number -} -interface Ai_Cf_Meta_Llama_4_Messages_Inner { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string - content?: - | string - | { - /** - * Type of the content provided - */ - type?: string - text?: string - image_url?: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + * The name of the function. */ - url?: string - } - }[] - | { - /** - * Type of the content provided - */ - type?: string - text?: string - image_url?: { + name: string; /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + * A brief description of what the function does. */ - url?: string - } - } - }[] - functions?: { - name: string - code: string - }[] - /** - * A list of tools available for the assistant to use. - */ - tools?: ( - | { + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { + requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[]; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ /** * The name of the tool. More descriptive the better. */ - name: string + name: string; /** * A brief description of what the tool does. */ - description: string + description: string; /** * Schema defining the parameters accepted by the tool. */ parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string - /** - * List of required parameter names. - */ - required?: string[] - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string - /** - * A description of the expected parameter. - */ - description: string - } - } - } - } - | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string - /** - * A brief description of what the function does. - */ - description: string - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { /** * The type of the parameters object (usually 'object'). */ - type: string + type: string; /** * List of required parameter names. */ - required?: string[] + required?: string[]; /** * Definitions of each parameter. */ properties: { - [k: string]: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { /** - * The data type of the parameter. + * The type of the parameters object (usually 'object'). */ - type: string + type: string; /** - * A description of the expected parameter. + * List of required parameter names. */ - description: string - } - } - } - } - } - )[] - response_format?: JSONMode - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number - /** - * Random seed for reproducibility of the generation. - */ - seed?: number - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; } type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string - /** - * Usage statistics for the inference request - */ - usage?: { /** - * Total number of tokens in input + * The generated text response from the model */ - prompt_tokens?: number + response: string; /** - * Total number of tokens in output + * Usage statistics for the inference request */ - completion_tokens?: number + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; /** - * Total number of input and output tokens + * An array of tool calls requests made during the response generation */ - total_tokens?: number - } - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The tool call id. - */ - id?: string - /** - * Specifies the type of tool (e.g., 'function'). - */ - type?: string - /** - * Details of the function tool. - */ - function?: { - /** - * The name of the tool to be called - */ - name?: string - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object - } - }[] -} + tool_calls?: { + /** + * The tool call id. + */ + id?: string; + /** + * Specifies the type of tool (e.g., 'function'). + */ + type?: string; + /** + * Details of the function tool. + */ + function?: { + /** + * The name of the tool to be called + */ + name?: string; + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + }; + }[]; +}; declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { - inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input - postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output + inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { + requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { + inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; } interface Ai_Cf_Deepgram_Nova_3_Input { - audio: { - body: object - contentType: string - } - /** - * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. - */ - custom_topic_mode?: 'extended' | 'strict' - /** - * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 - */ - custom_topic?: string - /** - * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param - */ - custom_intent_mode?: 'extended' | 'strict' - /** - * Custom intents you want the model to detect within your input audio if present - */ - custom_intent?: string - /** - * Identifies and extracts key entities from content in submitted audio - */ - detect_entities?: boolean - /** - * Identifies the dominant language spoken in submitted audio - */ - detect_language?: boolean - /** - * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 - */ - diarize?: boolean - /** - * Identify and extract key entities from content in submitted audio - */ - dictation?: boolean - /** - * Specify the expected encoding of your submitted audio - */ - encoding?: - | 'linear16' - | 'flac' - | 'mulaw' - | 'amr-nb' - | 'amr-wb' - | 'opus' - | 'speex' - | 'g729' - /** - * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing - */ - extra?: string - /** - * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' - */ - filler_words?: boolean - /** - * Key term prompting can boost or suppress specialized terminology and brands. - */ - keyterm?: string - /** - * Keywords can boost or suppress specialized terminology and brands. - */ - keywords?: string - /** - * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. - */ - language?: string - /** - * Spoken measurements will be converted to their corresponding abbreviations. - */ - measurements?: boolean - /** - * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. - */ - mip_opt_out?: boolean - /** - * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio - */ - mode?: 'general' | 'medical' | 'finance' - /** - * Transcribe each audio channel independently. - */ - multichannel?: boolean - /** - * Numerals converts numbers from written format to numerical format. - */ - numerals?: boolean - /** - * Splits audio into paragraphs to improve transcript readability. - */ - paragraphs?: boolean - /** - * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. - */ - profanity_filter?: boolean - /** - * Add punctuation and capitalization to the transcript. - */ - punctuate?: boolean - /** - * Redaction removes sensitive information from your transcripts. - */ - redact?: string - /** - * Search for terms or phrases in submitted audio and replaces them. - */ - replace?: string - /** - * Search for terms or phrases in submitted audio. - */ - search?: string - /** - * Recognizes the sentiment throughout a transcript or text. - */ - sentiment?: boolean - /** - * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. - */ - smart_format?: boolean - /** - * Detect topics throughout a transcript or text. - */ - topics?: boolean - /** - * Segments speech into meaningful semantic units. - */ - utterances?: boolean - /** - * Seconds to wait before detecting a pause between words in submitted audio. - */ - utt_split?: number - /** - * The number of channels in the submitted audio - */ - channels?: number - /** - * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. - */ - interim_results?: boolean - /** - * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing - */ - endpointing?: string - /** - * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. - */ - vad_events?: boolean - /** - * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. - */ - utterance_end_ms?: boolean + audio: { + body: object; + contentType: string; + }; + /** + * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. + */ + custom_topic_mode?: "extended" | "strict"; + /** + * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 + */ + custom_topic?: string; + /** + * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param + */ + custom_intent_mode?: "extended" | "strict"; + /** + * Custom intents you want the model to detect within your input audio if present + */ + custom_intent?: string; + /** + * Identifies and extracts key entities from content in submitted audio + */ + detect_entities?: boolean; + /** + * Identifies the dominant language spoken in submitted audio + */ + detect_language?: boolean; + /** + * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 + */ + diarize?: boolean; + /** + * Identify and extract key entities from content in submitted audio + */ + dictation?: boolean; + /** + * Specify the expected encoding of your submitted audio + */ + encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729"; + /** + * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing + */ + extra?: string; + /** + * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' + */ + filler_words?: boolean; + /** + * Key term prompting can boost or suppress specialized terminology and brands. + */ + keyterm?: string; + /** + * Keywords can boost or suppress specialized terminology and brands. + */ + keywords?: string; + /** + * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. + */ + language?: string; + /** + * Spoken measurements will be converted to their corresponding abbreviations. + */ + measurements?: boolean; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. + */ + mip_opt_out?: boolean; + /** + * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio + */ + mode?: "general" | "medical" | "finance"; + /** + * Transcribe each audio channel independently. + */ + multichannel?: boolean; + /** + * Numerals converts numbers from written format to numerical format. + */ + numerals?: boolean; + /** + * Splits audio into paragraphs to improve transcript readability. + */ + paragraphs?: boolean; + /** + * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. + */ + profanity_filter?: boolean; + /** + * Add punctuation and capitalization to the transcript. + */ + punctuate?: boolean; + /** + * Redaction removes sensitive information from your transcripts. + */ + redact?: string; + /** + * Search for terms or phrases in submitted audio and replaces them. + */ + replace?: string; + /** + * Search for terms or phrases in submitted audio. + */ + search?: string; + /** + * Recognizes the sentiment throughout a transcript or text. + */ + sentiment?: boolean; + /** + * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. + */ + smart_format?: boolean; + /** + * Detect topics throughout a transcript or text. + */ + topics?: boolean; + /** + * Segments speech into meaningful semantic units. + */ + utterances?: boolean; + /** + * Seconds to wait before detecting a pause between words in submitted audio. + */ + utt_split?: number; + /** + * The number of channels in the submitted audio + */ + channels?: number; + /** + * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. + */ + interim_results?: boolean; + /** + * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing + */ + endpointing?: string; + /** + * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. + */ + vad_events?: boolean; + /** + * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. + */ + utterance_end_ms?: boolean; } interface Ai_Cf_Deepgram_Nova_3_Output { - results?: { - channels?: { - alternatives?: { - confidence?: number - transcript?: string - words?: { - confidence?: number - end?: number - start?: number - word?: string - }[] - }[] - }[] - summary?: { - result?: string - short?: string - } - sentiments?: { - segments?: { - text?: string - start_word?: number - end_word?: number - sentiment?: string - sentiment_score?: number - }[] - average?: { - sentiment?: string - sentiment_score?: number - } - } - } + results?: { + channels?: { + alternatives?: { + confidence?: number; + transcript?: string; + words?: { + confidence?: number; + end?: number; + start?: number; + word?: string; + }[]; + }[]; + }[]; + summary?: { + result?: string; + short?: string; + }; + sentiments?: { + segments?: { + text?: string; + start_word?: number; + end_word?: number; + sentiment?: string; + sentiment_score?: number; + }[]; + average?: { + sentiment?: string; + sentiment_score?: number; + }; + }; + }; } declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { - inputs: Ai_Cf_Deepgram_Nova_3_Input - postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output + inputs: Ai_Cf_Deepgram_Nova_3_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; } -type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = - | { - /** - * readable stream with audio data and content-type specified for that data - */ - audio: { - body: object - contentType: string - } - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: 'uint8' | 'float32' | 'float64' - } - | { - /** - * base64 encoded audio data - */ - audio: string - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: 'uint8' | 'float32' | 'float64' - } +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { + queries?: string | string[]; + /** + * Optional instruction for the task + */ + instruction?: string; + documents?: string | string[]; + text?: string | string[]; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { + data?: number[][]; + shape?: number[]; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { + inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; +} +type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = { + /** + * readable stream with audio data and content-type specified for that data + */ + audio: { + body: object; + contentType: string; + }; + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: "uint8" | "float32" | "float64"; +} | { + /** + * base64 encoded audio data + */ + audio: string; + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: "uint8" | "float32" | "float64"; +}; interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { - /** - * if true, end-of-turn was detected - */ - is_complete?: boolean - /** - * probability of the end-of-turn detection - */ - probability?: number + /** + * if true, end-of-turn was detected + */ + is_complete?: boolean; + /** + * probability of the end-of-turn detection + */ + probability?: number; } declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { - inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input - postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output + inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; + postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; } -type Ai_Cf_Openai_Gpt_Oss_120B_Input = - | GPT_OSS_120B_Responses - | GPT_OSS_120B_Responses_Async -interface GPT_OSS_120B_Responses { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[] - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: 'low' | 'medium' | 'high' - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: 'auto' | 'concise' | 'detailed' - } -} -interface GPT_OSS_120B_Responses_Async { - requests: { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[] - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: 'low' | 'medium' | 'high' - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: 'auto' | 'concise' | 'detailed' - } - }[] -} -type Ai_Cf_Openai_Gpt_Oss_120B_Output = {} | (string & NonNullable) declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { - inputs: Ai_Cf_Openai_Gpt_Oss_120B_Input - postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_120B_Output + inputs: ResponsesInput; + postProcessedOutputs: ResponsesOutput; } -type Ai_Cf_Openai_Gpt_Oss_20B_Input = - | GPT_OSS_20B_Responses - | GPT_OSS_20B_Responses_Async -interface GPT_OSS_20B_Responses { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[] - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: 'low' | 'medium' | 'high' - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: 'auto' | 'concise' | 'detailed' - } -} -interface GPT_OSS_20B_Responses_Async { - requests: { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[] - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: 'low' | 'medium' | 'high' - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: 'auto' | 'concise' | 'detailed' - } - }[] -} -type Ai_Cf_Openai_Gpt_Oss_20B_Output = {} | (string & NonNullable) declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { - inputs: Ai_Cf_Openai_Gpt_Oss_20B_Input - postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_20B_Output + inputs: ResponsesInput; + postProcessedOutputs: ResponsesOutput; } interface Ai_Cf_Leonardo_Phoenix_1_0_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number - /** - * Random seed for reproducibility of the image generation - */ - seed?: number - /** - * The height of the generated image in pixels - */ - height?: number - /** - * The width of the generated image in pixels - */ - width?: number - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number - /** - * Specify what to exclude from the generated images - */ - negative_prompt?: string + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number; + /** + * Random seed for reproducibility of the image generation + */ + seed?: number; + /** + * The height of the generated image in pixels + */ + height?: number; + /** + * The width of the generated image in pixels + */ + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * Specify what to exclude from the generated images + */ + negative_prompt?: string; } /** * The generated image in JPEG format */ -type Ai_Cf_Leonardo_Phoenix_1_0_Output = string +type Ai_Cf_Leonardo_Phoenix_1_0_Output = string; declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { - inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input - postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output + inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output; } interface Ai_Cf_Leonardo_Lucid_Origin_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number - /** - * Random seed for reproducibility of the image generation - */ - seed?: number - /** - * The height of the generated image in pixels - */ - height?: number - /** - * The width of the generated image in pixels - */ - width?: number - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - steps?: number + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number; + /** + * Random seed for reproducibility of the image generation + */ + seed?: number; + /** + * The height of the generated image in pixels + */ + height?: number; + /** + * The width of the generated image in pixels + */ + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + steps?: number; } interface Ai_Cf_Leonardo_Lucid_Origin_Output { - /** - * The generated image in Base64 format. - */ - image?: string + /** + * The generated image in Base64 format. + */ + image?: string; } declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { - inputs: Ai_Cf_Leonardo_Lucid_Origin_Input - postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output + inputs: Ai_Cf_Leonardo_Lucid_Origin_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output; } interface Ai_Cf_Deepgram_Aura_1_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: - | 'angus' - | 'asteria' - | 'arcas' - | 'orion' - | 'orpheus' - | 'athena' - | 'luna' - | 'zeus' - | 'perseus' - | 'helios' - | 'hera' - | 'stella' - /** - * Encoding of the output audio. - */ - encoding?: 'linear16' | 'flac' | 'mulaw' | 'alaw' | 'mp3' | 'opus' | 'aac' - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: 'none' | 'wav' | 'ogg' - /** - * The text content to be converted to speech - */ - text: string - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number + /** + * Speaker used to produce the audio. + */ + speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; } /** * The generated audio in MP3 format */ -type Ai_Cf_Deepgram_Aura_1_Output = string +type Ai_Cf_Deepgram_Aura_1_Output = string; declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { - inputs: Ai_Cf_Deepgram_Aura_1_Input - postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output + inputs: Ai_Cf_Deepgram_Aura_1_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; +} +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { + /** + * Input text to translate. Can be a single string or a list of strings. + */ + text: string | string[]; + /** + * Target language to translate to + */ + target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva"; +} +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { + /** + * Translated texts + */ + translations: string[]; +} +declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { + inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; + postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { + requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[]; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { + inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; + postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { + /** + * Input text to embed. Can be a single string or a list of strings. + */ + text: string | string[]; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { + /** + * Embedding vectors, where each vector is a list of floats. + */ + data: number[][]; + /** + * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. + * + * @minItems 2 + * @maxItems 2 + */ + shape: [ + number, + number + ]; +} +declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { + inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; + postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; +} +interface Ai_Cf_Deepgram_Flux_Input { + /** + * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. + */ + encoding: "linear16"; + /** + * Sample rate of the audio stream in Hz. + */ + sample_rate: string; + /** + * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. + */ + eager_eot_threshold?: string; + /** + * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. + */ + eot_threshold?: string; + /** + * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. + */ + eot_timeout_ms?: string; + /** + * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. + */ + keyterm?: string; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip + */ + mip_opt_out?: "true" | "false"; + /** + * Label your requests for the purpose of identification during usage reporting + */ + tag?: string; +} +/** + * Output will be returned as websocket messages. + */ +interface Ai_Cf_Deepgram_Flux_Output { + /** + * The unique identifier of the request (uuid) + */ + request_id?: string; + /** + * Starts at 0 and increments for each message the server sends to the client. + */ + sequence_id?: number; + /** + * The type of event being reported. + */ + event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn"; + /** + * The index of the current turn + */ + turn_index?: number; + /** + * Start time in seconds of the audio range that was transcribed + */ + audio_window_start?: number; + /** + * End time in seconds of the audio range that was transcribed + */ + audio_window_end?: number; + /** + * Text that was said over the course of the current turn + */ + transcript?: string; + /** + * The words in the transcript + */ + words?: { + /** + * The individual punctuated, properly-cased word from the transcript + */ + word: string; + /** + * Confidence that this word was transcribed correctly + */ + confidence: number; + }[]; + /** + * Confidence that no more speech is coming in this turn + */ + end_of_turn_confidence?: number; +} +declare abstract class Base_Ai_Cf_Deepgram_Flux { + inputs: Ai_Cf_Deepgram_Flux_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; +} +interface Ai_Cf_Deepgram_Aura_2_En_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_En_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { + inputs: Ai_Cf_Deepgram_Aura_2_En_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; +} +interface Ai_Cf_Deepgram_Aura_2_Es_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_Es_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { + inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; } interface AiModels { - '@cf/huggingface/distilbert-sst-2-int8': BaseAiTextClassification - '@cf/stabilityai/stable-diffusion-xl-base-1.0': BaseAiTextToImage - '@cf/runwayml/stable-diffusion-v1-5-inpainting': BaseAiTextToImage - '@cf/runwayml/stable-diffusion-v1-5-img2img': BaseAiTextToImage - '@cf/lykon/dreamshaper-8-lcm': BaseAiTextToImage - '@cf/bytedance/stable-diffusion-xl-lightning': BaseAiTextToImage - '@cf/myshell-ai/melotts': BaseAiTextToSpeech - '@cf/google/embeddinggemma-300m': BaseAiTextEmbeddings - '@cf/microsoft/resnet-50': BaseAiImageClassification - '@cf/meta/llama-2-7b-chat-int8': BaseAiTextGeneration - '@cf/mistral/mistral-7b-instruct-v0.1': BaseAiTextGeneration - '@cf/meta/llama-2-7b-chat-fp16': BaseAiTextGeneration - '@hf/thebloke/llama-2-13b-chat-awq': BaseAiTextGeneration - '@hf/thebloke/mistral-7b-instruct-v0.1-awq': BaseAiTextGeneration - '@hf/thebloke/zephyr-7b-beta-awq': BaseAiTextGeneration - '@hf/thebloke/openhermes-2.5-mistral-7b-awq': BaseAiTextGeneration - '@hf/thebloke/neural-chat-7b-v3-1-awq': BaseAiTextGeneration - '@hf/thebloke/llamaguard-7b-awq': BaseAiTextGeneration - '@hf/thebloke/deepseek-coder-6.7b-base-awq': BaseAiTextGeneration - '@hf/thebloke/deepseek-coder-6.7b-instruct-awq': BaseAiTextGeneration - '@cf/deepseek-ai/deepseek-math-7b-instruct': BaseAiTextGeneration - '@cf/defog/sqlcoder-7b-2': BaseAiTextGeneration - '@cf/openchat/openchat-3.5-0106': BaseAiTextGeneration - '@cf/tiiuae/falcon-7b-instruct': BaseAiTextGeneration - '@cf/thebloke/discolm-german-7b-v1-awq': BaseAiTextGeneration - '@cf/qwen/qwen1.5-0.5b-chat': BaseAiTextGeneration - '@cf/qwen/qwen1.5-7b-chat-awq': BaseAiTextGeneration - '@cf/qwen/qwen1.5-14b-chat-awq': BaseAiTextGeneration - '@cf/tinyllama/tinyllama-1.1b-chat-v1.0': BaseAiTextGeneration - '@cf/microsoft/phi-2': BaseAiTextGeneration - '@cf/qwen/qwen1.5-1.8b-chat': BaseAiTextGeneration - '@cf/mistral/mistral-7b-instruct-v0.2-lora': BaseAiTextGeneration - '@hf/nousresearch/hermes-2-pro-mistral-7b': BaseAiTextGeneration - '@hf/nexusflow/starling-lm-7b-beta': BaseAiTextGeneration - '@hf/google/gemma-7b-it': BaseAiTextGeneration - '@cf/meta-llama/llama-2-7b-chat-hf-lora': BaseAiTextGeneration - '@cf/google/gemma-2b-it-lora': BaseAiTextGeneration - '@cf/google/gemma-7b-it-lora': BaseAiTextGeneration - '@hf/mistral/mistral-7b-instruct-v0.2': BaseAiTextGeneration - '@cf/meta/llama-3-8b-instruct': BaseAiTextGeneration - '@cf/fblgit/una-cybertron-7b-v2-bf16': BaseAiTextGeneration - '@cf/meta/llama-3-8b-instruct-awq': BaseAiTextGeneration - '@hf/meta-llama/meta-llama-3-8b-instruct': BaseAiTextGeneration - '@cf/meta/llama-3.1-8b-instruct-fp8': BaseAiTextGeneration - '@cf/meta/llama-3.1-8b-instruct-awq': BaseAiTextGeneration - '@cf/meta/llama-3.2-3b-instruct': BaseAiTextGeneration - '@cf/meta/llama-3.2-1b-instruct': BaseAiTextGeneration - '@cf/deepseek-ai/deepseek-r1-distill-qwen-32b': BaseAiTextGeneration - '@cf/facebook/bart-large-cnn': BaseAiSummarization - '@cf/llava-hf/llava-1.5-7b-hf': BaseAiImageToText - '@cf/baai/bge-base-en-v1.5': Base_Ai_Cf_Baai_Bge_Base_En_V1_5 - '@cf/openai/whisper': Base_Ai_Cf_Openai_Whisper - '@cf/meta/m2m100-1.2b': Base_Ai_Cf_Meta_M2M100_1_2B - '@cf/baai/bge-small-en-v1.5': Base_Ai_Cf_Baai_Bge_Small_En_V1_5 - '@cf/baai/bge-large-en-v1.5': Base_Ai_Cf_Baai_Bge_Large_En_V1_5 - '@cf/unum/uform-gen2-qwen-500m': Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M - '@cf/openai/whisper-tiny-en': Base_Ai_Cf_Openai_Whisper_Tiny_En - '@cf/openai/whisper-large-v3-turbo': Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo - '@cf/baai/bge-m3': Base_Ai_Cf_Baai_Bge_M3 - '@cf/black-forest-labs/flux-1-schnell': Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell - '@cf/meta/llama-3.2-11b-vision-instruct': Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct - '@cf/meta/llama-3.3-70b-instruct-fp8-fast': Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast - '@cf/meta/llama-guard-3-8b': Base_Ai_Cf_Meta_Llama_Guard_3_8B - '@cf/baai/bge-reranker-base': Base_Ai_Cf_Baai_Bge_Reranker_Base - '@cf/qwen/qwen2.5-coder-32b-instruct': Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct - '@cf/qwen/qwq-32b': Base_Ai_Cf_Qwen_Qwq_32B - '@cf/mistralai/mistral-small-3.1-24b-instruct': Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct - '@cf/google/gemma-3-12b-it': Base_Ai_Cf_Google_Gemma_3_12B_It - '@cf/meta/llama-4-scout-17b-16e-instruct': Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct - '@cf/deepgram/nova-3': Base_Ai_Cf_Deepgram_Nova_3 - '@cf/pipecat-ai/smart-turn-v2': Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 - '@cf/openai/gpt-oss-120b': Base_Ai_Cf_Openai_Gpt_Oss_120B - '@cf/openai/gpt-oss-20b': Base_Ai_Cf_Openai_Gpt_Oss_20B - '@cf/leonardo/phoenix-1.0': Base_Ai_Cf_Leonardo_Phoenix_1_0 - '@cf/leonardo/lucid-origin': Base_Ai_Cf_Leonardo_Lucid_Origin - '@cf/deepgram/aura-1': Base_Ai_Cf_Deepgram_Aura_1 + "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; + "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage; + "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage; + "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage; + "@cf/myshell-ai/melotts": BaseAiTextToSpeech; + "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings; + "@cf/microsoft/resnet-50": BaseAiImageClassification; + "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration; + "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration; + "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration; + "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration; + "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration; + "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration; + "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration; + "@hf/thebloke/llamaguard-7b-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration; + "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration; + "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration; + "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration; + "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration; + "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration; + "@cf/microsoft/phi-2": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration; + "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration; + "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration; + "@hf/google/gemma-7b-it": BaseAiTextGeneration; + "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration; + "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration; + "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration; + "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; + "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; + "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; + "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; + "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration; + "@cf/facebook/bart-large-cnn": BaseAiSummarization; + "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; + "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; + "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; + "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B; + "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5; + "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5; + "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; + "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En; + "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; + "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3; + "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; + "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; + "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; + "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; + "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; + "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; + "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B; + "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; + "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; + "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; + "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; + "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; + "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; + "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; + "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; + "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; + "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; + "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; + "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; + "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; + "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; + "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; + "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux; + "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En; + "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es; } type AiOptions = { - /** - * Send requests as an asynchronous batch job, only works for supported models - * https://developers.cloudflare.com/workers-ai/features/batch-api - */ - queueRequest?: boolean - /** - * Establish websocket connections, only works for supported models - */ - websocket?: boolean - gateway?: GatewayOptions - returnRawResponse?: boolean - prefix?: string - extraHeaders?: object -} + /** + * Send requests as an asynchronous batch job, only works for supported models + * https://developers.cloudflare.com/workers-ai/features/batch-api + */ + queueRequest?: boolean; + /** + * Establish websocket connections, only works for supported models + */ + websocket?: boolean; + /** + * Tag your requests to group and view them in Cloudflare dashboard. + * + * Rules: + * Tags must only contain letters, numbers, and the symbols: : - . / @ + * Each tag can have maximum 50 characters. + * Maximum 5 tags are allowed each request. + * Duplicate tags will removed. + */ + tags?: string[]; + gateway?: GatewayOptions; + returnRawResponse?: boolean; + prefix?: string; + extraHeaders?: object; +}; type AiModelsSearchParams = { - author?: string - hide_experimental?: boolean - page?: number - per_page?: number - search?: string - source?: number - task?: string -} + author?: string; + hide_experimental?: boolean; + page?: number; + per_page?: number; + search?: string; + source?: number; + task?: string; +}; type AiModelsSearchObject = { - id: string - source: number - name: string - description: string - task: { - id: string - name: string - description: string - } - tags: string[] - properties: { - property_id: string - value: string - }[] + id: string; + source: number; + name: string; + description: string; + task: { + id: string; + name: string; + description: string; + }; + tags: string[]; + properties: { + property_id: string; + value: string; + }[]; +}; +interface InferenceUpstreamError extends Error { } -interface InferenceUpstreamError extends Error {} -interface AiInternalError extends Error {} -type AiModelListType = Record +interface AiInternalError extends Error { +} +type AiModelListType = Record; declare abstract class Ai { - aiGatewayLogId: string | null - gateway(gatewayId: string): AiGateway - autorag(autoragId: string): AutoRAG - run< - Name extends keyof AiModelList, - Options extends AiOptions, - InputOptions extends AiModelList[Name]['inputs'], - >( - model: Name, - inputs: InputOptions, - options?: Options, - ): Promise< - Options extends - | { - returnRawResponse: true - } - | { - websocket: true - } - ? Response - : InputOptions extends { - stream: true - } - ? ReadableStream - : AiModelList[Name]['postProcessedOutputs'] - > - models(params?: AiModelsSearchParams): Promise - toMarkdown(): ToMarkdownService - toMarkdown( - files: MarkdownDocument[], - options?: ConversionRequestOptions, - ): Promise - toMarkdown( - files: MarkdownDocument, - options?: ConversionRequestOptions, - ): Promise + aiGatewayLogId: string | null; + gateway(gatewayId: string): AiGateway; + /** + * Access the AI Search API for managing AI-powered search instances. + * + * This is the new API that replaces AutoRAG with better namespace separation: + * - Account-level operations: `list()`, `create()` + * - Instance-level operations: `get(id).search()`, `get(id).chatCompletions()`, `get(id).delete()` + * + * @example + * ```typescript + * // List all AI Search instances + * const instances = await env.AI.aiSearch.list(); + * + * // Search an instance + * const results = await env.AI.aiSearch.get('my-search').search({ + * messages: [{ role: 'user', content: 'What is the policy?' }], + * ai_search_options: { + * retrieval: { max_num_results: 10 } + * } + * }); + * + * // Generate chat completions with AI Search context + * const response = await env.AI.aiSearch.get('my-search').chatCompletions({ + * messages: [{ role: 'user', content: 'What is the policy?' }], + * model: '@cf/meta/llama-3.3-70b-instruct-fp8-fast' + * }); + * ``` + */ + aiSearch(): AiSearchAccountService; + /** + * @deprecated AutoRAG has been replaced by AI Search. + * Use `env.AI.aiSearch` instead for better API design and new features. + * + * Migration guide: + * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` + * - `env.AI.autorag('id').search({ query: '...' })` → `env.AI.aiSearch.get('id').search({ messages: [{ role: 'user', content: '...' }] })` + * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` + * + * Note: The old API continues to work for backwards compatibility, but new projects should use AI Search. + * + * @see AiSearchAccountService + * @param autoragId Optional instance ID (omit for account-level operations) + */ + autorag(autoragId: string): AutoRAG; + run(model: Name, inputs: InputOptions, options?: Options): Promise; + models(params?: AiModelsSearchParams): Promise; + toMarkdown(): ToMarkdownService; + toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; + toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; } type GatewayRetries = { - maxAttempts?: 1 | 2 | 3 | 4 | 5 - retryDelayMs?: number - backoff?: 'constant' | 'linear' | 'exponential' -} + maxAttempts?: 1 | 2 | 3 | 4 | 5; + retryDelayMs?: number; + backoff?: 'constant' | 'linear' | 'exponential'; +}; type GatewayOptions = { - id: string - cacheKey?: string - cacheTtl?: number - skipCache?: boolean - metadata?: Record - collectLog?: boolean - eventId?: string - requestTimeoutMs?: number - retries?: GatewayRetries -} + id: string; + cacheKey?: string; + cacheTtl?: number; + skipCache?: boolean; + metadata?: Record; + collectLog?: boolean; + eventId?: string; + requestTimeoutMs?: number; + retries?: GatewayRetries; +}; type UniversalGatewayOptions = Exclude & { - /** - ** @deprecated - */ - id?: string -} + /** + ** @deprecated + */ + id?: string; +}; type AiGatewayPatchLog = { - score?: number | null - feedback?: -1 | 1 | null - metadata?: Record | null -} + score?: number | null; + feedback?: -1 | 1 | null; + metadata?: Record | null; +}; type AiGatewayLog = { - id: string - provider: string - model: string - model_type?: string - path: string - duration: number - request_type?: string - request_content_type?: string - status_code: number - response_content_type?: string - success: boolean - cached: boolean - tokens_in?: number - tokens_out?: number - metadata?: Record - step?: number - cost?: number - custom_cost?: boolean - request_size: number - request_head?: string - request_head_complete: boolean - response_size: number - response_head?: string - response_head_complete: boolean - created_at: Date -} -type AIGatewayProviders = - | 'workers-ai' - | 'anthropic' - | 'aws-bedrock' - | 'azure-openai' - | 'google-vertex-ai' - | 'huggingface' - | 'openai' - | 'perplexity-ai' - | 'replicate' - | 'groq' - | 'cohere' - | 'google-ai-studio' - | 'mistral' - | 'grok' - | 'openrouter' - | 'deepseek' - | 'cerebras' - | 'cartesia' - | 'elevenlabs' - | 'adobe-firefly' + id: string; + provider: string; + model: string; + model_type?: string; + path: string; + duration: number; + request_type?: string; + request_content_type?: string; + status_code: number; + response_content_type?: string; + success: boolean; + cached: boolean; + tokens_in?: number; + tokens_out?: number; + metadata?: Record; + step?: number; + cost?: number; + custom_cost?: boolean; + request_size: number; + request_head?: string; + request_head_complete: boolean; + response_size: number; + response_head?: string; + response_head_complete: boolean; + created_at: Date; +}; +type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly'; type AIGatewayHeaders = { - 'cf-aig-metadata': - | Record - | string - 'cf-aig-custom-cost': - | { - per_token_in?: number - per_token_out?: number - } - | { - total_cost?: number - } - | string - 'cf-aig-cache-ttl': number | string - 'cf-aig-skip-cache': boolean | string - 'cf-aig-cache-key': string - 'cf-aig-event-id': string - 'cf-aig-request-timeout': number | string - 'cf-aig-max-attempts': number | string - 'cf-aig-retry-delay': number | string - 'cf-aig-backoff': string - 'cf-aig-collect-log': boolean | string - Authorization: string - 'Content-Type': string - [key: string]: string | number | boolean | object -} + 'cf-aig-metadata': Record | string; + 'cf-aig-custom-cost': { + per_token_in?: number; + per_token_out?: number; + } | { + total_cost?: number; + } | string; + 'cf-aig-cache-ttl': number | string; + 'cf-aig-skip-cache': boolean | string; + 'cf-aig-cache-key': string; + 'cf-aig-event-id': string; + 'cf-aig-request-timeout': number | string; + 'cf-aig-max-attempts': number | string; + 'cf-aig-retry-delay': number | string; + 'cf-aig-backoff': string; + 'cf-aig-collect-log': boolean | string; + Authorization: string; + 'Content-Type': string; + [key: string]: string | number | boolean | object; +}; type AIGatewayUniversalRequest = { - provider: AIGatewayProviders | string // eslint-disable-line - endpoint: string - headers: Partial - query: unknown + provider: AIGatewayProviders | string; // eslint-disable-line + endpoint: string; + headers: Partial; + query: unknown; +}; +interface AiGatewayInternalError extends Error { +} +interface AiGatewayLogNotFound extends Error { } -interface AiGatewayInternalError extends Error {} -interface AiGatewayLogNotFound extends Error {} declare abstract class AiGateway { - patchLog(logId: string, data: AiGatewayPatchLog): Promise - getLog(logId: string): Promise - run( - data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], - options?: { - gateway?: UniversalGatewayOptions - extraHeaders?: object - }, - ): Promise - getUrl(provider?: AIGatewayProviders | string): Promise // eslint-disable-line + patchLog(logId: string, data: AiGatewayPatchLog): Promise; + getLog(logId: string): Promise; + run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { + gateway?: UniversalGatewayOptions; + extraHeaders?: object; + }): Promise; + getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line +} +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchInternalError instead. + * @see AiSearchInternalError + */ +interface AutoRAGInternalError extends Error { +} +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNotFoundError instead. + * @see AiSearchNotFoundError + */ +interface AutoRAGNotFoundError extends Error { +} +/** + * @deprecated This error type is no longer used in the AI Search API. + */ +interface AutoRAGUnauthorizedError extends Error { +} +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNameNotSetError instead. + * @see AiSearchNameNotSetError + */ +interface AutoRAGNameNotSetError extends Error { } -interface AutoRAGInternalError extends Error {} -interface AutoRAGNotFoundError extends Error {} -interface AutoRAGUnauthorizedError extends Error {} -interface AutoRAGNameNotSetError extends Error {} type ComparisonFilter = { - key: string - type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' - value: string | number | boolean -} + key: string; + type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; + value: string | number | boolean; +}; type CompoundFilter = { - type: 'and' | 'or' - filters: ComparisonFilter[] -} + type: 'and' | 'or'; + filters: ComparisonFilter[]; +}; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchSearchRequest with the new API instead. + * @see AiSearchSearchRequest + */ type AutoRagSearchRequest = { - query: string - filters?: CompoundFilter | ComparisonFilter - max_num_results?: number - ranking_options?: { - ranker?: string - score_threshold?: number - } - reranking?: { - enabled?: boolean - model?: string - } - rewrite_query?: boolean -} + query: string; + filters?: CompoundFilter | ComparisonFilter; + max_num_results?: number; + ranking_options?: { + ranker?: string; + score_threshold?: number; + }; + reranking?: { + enabled?: boolean; + model?: string; + }; + rewrite_query?: boolean; +}; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchChatCompletionsRequest with the new API instead. + * @see AiSearchChatCompletionsRequest + */ type AutoRagAiSearchRequest = AutoRagSearchRequest & { - stream?: boolean - system_prompt?: string -} -type AutoRagAiSearchRequestStreaming = Omit< - AutoRagAiSearchRequest, - 'stream' -> & { - stream: true -} + stream?: boolean; + system_prompt?: string; +}; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchChatCompletionsRequest with stream: true instead. + * @see AiSearchChatCompletionsRequest + */ +type AutoRagAiSearchRequestStreaming = Omit & { + stream: true; +}; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchSearchResponse with the new API instead. + * @see AiSearchSearchResponse + */ type AutoRagSearchResponse = { - object: 'vector_store.search_results.page' - search_query: string - data: { - file_id: string - filename: string - score: number - attributes: Record - content: { - type: 'text' - text: string - }[] - }[] - has_more: boolean - next_page: string | null -} + object: 'vector_store.search_results.page'; + search_query: string; + data: { + file_id: string; + filename: string; + score: number; + attributes: Record; + content: { + type: 'text'; + text: string; + }[]; + }[]; + has_more: boolean; + next_page: string | null; +}; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchListResponse with the new API instead. + * @see AiSearchListResponse + */ type AutoRagListResponse = { - id: string - enable: boolean - type: string - source: string - vectorize_name: string - paused: boolean - status: string -}[] + id: string; + enable: boolean; + type: string; + source: string; + vectorize_name: string; + paused: boolean; + status: string; +}[]; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * The new API returns different response formats for chat completions. + */ type AutoRagAiSearchResponse = AutoRagSearchResponse & { - response: string -} + response: string; +}; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use the new AI Search API instead: `env.AI.aiSearch` + * + * Migration guide: + * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` + * - `env.AI.autorag('id').search(...)` → `env.AI.aiSearch.get('id').search(...)` + * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` + * + * @see AiSearchAccountService + * @see AiSearchInstanceService + */ declare abstract class AutoRAG { - list(): Promise - search(params: AutoRagSearchRequest): Promise - aiSearch(params: AutoRagAiSearchRequestStreaming): Promise - aiSearch(params: AutoRagAiSearchRequest): Promise - aiSearch( - params: AutoRagAiSearchRequest, - ): Promise + /** + * @deprecated Use `env.AI.aiSearch.list()` instead. + * @see AiSearchAccountService.list + */ + list(): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).search(...)` instead. + * Note: The new API uses a messages array instead of a query string. + * @see AiSearchInstanceService.search + */ + search(params: AutoRagSearchRequest): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ + aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ + aiSearch(params: AutoRagAiSearchRequest): Promise; } interface BasicImageTransformations { - /** - * Maximum width in image pixels. The value must be an integer. - */ - width?: number - /** - * Maximum height in image pixels. The value must be an integer. - */ - height?: number - /** - * Resizing mode as a string. It affects interpretation of width and height - * options: - * - scale-down: Similar to contain, but the image is never enlarged. If - * the image is larger than given width or height, it will be resized. - * Otherwise its original size will be kept. - * - contain: Resizes to maximum size that fits within the given width and - * height. If only a single dimension is given (e.g. only width), the - * image will be shrunk or enlarged to exactly match that dimension. - * Aspect ratio is always preserved. - * - cover: Resizes (shrinks or enlarges) to fill the entire area of width - * and height. If the image has an aspect ratio different from the ratio - * of width and height, it will be cropped to fit. - * - crop: The image will be shrunk and cropped to fit within the area - * specified by width and height. The image will not be enlarged. For images - * smaller than the given dimensions it's the same as scale-down. For - * images larger than the given dimensions, it's the same as cover. - * See also trim. - * - pad: Resizes to the maximum size that fits within the given width and - * height, and then fills the remaining area with a background color - * (white by default). Use of this mode is not recommended, as the same - * effect can be more efficiently achieved with the contain mode and the - * CSS object-fit: contain property. - * - squeeze: Stretches and deforms to the width and height given, even if it - * breaks aspect ratio - */ - fit?: 'scale-down' | 'contain' | 'cover' | 'crop' | 'pad' | 'squeeze' - /** - * Image segmentation using artificial intelligence models. Sets pixels not - * within selected segment area to transparent e.g "foreground" sets every - * background pixel as transparent. - */ - segment?: 'foreground' - /** - * When cropping with fit: "cover", this defines the side or point that should - * be left uncropped. The value is either a string - * "left", "right", "top", "bottom", "auto", or "center" (the default), - * or an object {x, y} containing focal point coordinates in the original - * image expressed as fractions ranging from 0.0 (top or left) to 1.0 - * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will - * crop bottom or left and right sides as necessary, but won’t crop anything - * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to - * preserve as much as possible around a point at 20% of the height of the - * source image. - */ - gravity?: - | 'face' - | 'left' - | 'right' - | 'top' - | 'bottom' - | 'center' - | 'auto' - | 'entropy' - | BasicImageTransformationsGravityCoordinates - /** - * Background color to add underneath the image. Applies only to images with - * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), - * hsl(…), etc.) - */ - background?: string - /** - * Number of degrees (90, 180, 270) to rotate the image by. width and height - * options refer to axes after rotation. - */ - rotate?: 0 | 90 | 180 | 270 | 360 + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + * - squeeze: Stretches and deforms to the width and height given, even if it + * breaks aspect ratio + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad" | "squeeze"; + /** + * Image segmentation using artificial intelligence models. Sets pixels not + * within selected segment area to transparent e.g "foreground" sets every + * background pixel as transparent. + */ + segment?: "foreground"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; } interface BasicImageTransformationsGravityCoordinates { - x?: number - y?: number - mode?: 'remainder' | 'box-center' + x?: number; + y?: number; + mode?: 'remainder' | 'box-center'; } /** * In addition to the properties you can set in the RequestInit dict @@ -7755,1027 +9092,755 @@ interface BasicImageTransformationsGravityCoordinates { * playground. */ interface RequestInitCfProperties extends Record { - cacheEverything?: boolean - /** - * A request's cache key is what determines if two requests are - * "the same" for caching purposes. If a request has the same cache key - * as some previous request, then we can serve the same cached response for - * both. (e.g. 'some-key') - * - * Only available for Enterprise customers. - */ - cacheKey?: string - /** - * This allows you to append additional Cache-Tag response headers - * to the origin response without modifications to the origin server. - * This will allow for greater control over the Purge by Cache Tag feature - * utilizing changes only in the Workers process. - * - * Only available for Enterprise customers. - */ - cacheTags?: string[] - /** - * Force response to be cached for a given number of seconds. (e.g. 300) - */ - cacheTtl?: number - /** - * Force response to be cached for a given number of seconds based on the Origin status code. - * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) - */ - cacheTtlByStatus?: Record - scrapeShield?: boolean - apps?: boolean - image?: RequestInitCfPropertiesImage - minify?: RequestInitCfPropertiesImageMinify - mirage?: boolean - polish?: 'lossy' | 'lossless' | 'off' - r2?: RequestInitCfPropertiesR2 - /** - * Redirects the request to an alternate origin server. You can use this, - * for example, to implement load balancing across several origins. - * (e.g.us-east.example.com) - * - * Note - For security reasons, the hostname set in resolveOverride must - * be proxied on the same Cloudflare zone of the incoming request. - * Otherwise, the setting is ignored. CNAME hosts are allowed, so to - * resolve to a host under a different domain or a DNS only domain first - * declare a CNAME record within your own zone’s DNS mapping to the - * external hostname, set proxy on Cloudflare, then set resolveOverride - * to point to that CNAME record. - */ - resolveOverride?: string + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + r2?: RequestInitCfPropertiesR2; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; } interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations { - /** - * Absolute URL of the image file to use for the drawing. It can be any of - * the supported file formats. For drawing of watermarks or non-rectangular - * overlays we recommend using PNG or WebP images. - */ - url: string - /** - * Floating-point number between 0 (transparent) and 1 (opaque). - * For example, opacity: 0.5 makes overlay semitransparent. - */ - opacity?: number - /** - * - If set to true, the overlay image will be tiled to cover the entire - * area. This is useful for stock-photo-like watermarks. - * - If set to "x", the overlay image will be tiled horizontally only - * (form a line). - * - If set to "y", the overlay image will be tiled vertically only - * (form a line). - */ - repeat?: true | 'x' | 'y' - /** - * Position of the overlay image relative to a given edge. Each property is - * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 - * positions left side of the overlay 10 pixels from the left edge of the - * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom - * of the background image. - * - * Setting both left & right, or both top & bottom is an error. - * - * If no position is specified, the image will be centered. - */ - top?: number - left?: number - bottom?: number - right?: number + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; } interface RequestInitCfPropertiesImage extends BasicImageTransformations { - /** - * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it - * easier to specify higher-DPI sizes in . - */ - dpr?: number - /** - * Allows you to trim your image. Takes dpr into account and is performed before - * resizing or rotation. - * - * It can be used as: - * - left, top, right, bottom - it will specify the number of pixels to cut - * off each side - * - width, height - the width/height you'd like to end up with - can be used - * in combination with the properties above - * - border - this will automatically trim the surroundings of an image based on - * it's color. It consists of three properties: - * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) - * - tolerance: difference from color to treat as color - * - keep: the number of pixels of border to keep - */ - trim?: - | 'border' - | { - top?: number - bottom?: number - left?: number - right?: number - width?: number - height?: number - border?: - | boolean - | { - color?: string - tolerance?: number - keep?: number - } - } - /** - * Quality setting from 1-100 (useful values are in 60-90 range). Lower values - * make images look worse, but load faster. The default is 85. It applies only - * to JPEG and WebP images. It doesn’t have any effect on PNG. - */ - quality?: number | 'low' | 'medium-low' | 'medium-high' | 'high' - /** - * Output format to generate. It can be: - * - avif: generate images in AVIF format. - * - webp: generate images in Google WebP format. Set quality to 100 to get - * the WebP-lossless format. - * - json: instead of generating an image, outputs information about the - * image, in JSON format. The JSON object will contain image size - * (before and after resizing), source image’s MIME type, file size, etc. - * - jpeg: generate images in JPEG format. - * - png: generate images in PNG format. - */ - format?: - | 'avif' - | 'webp' - | 'json' - | 'jpeg' - | 'png' - | 'baseline-jpeg' - | 'png-force' - | 'svg' - /** - * Whether to preserve animation frames from input files. Default is true. - * Setting it to false reduces animations to still images. This setting is - * recommended when enlarging images or processing arbitrary user content, - * because large GIF animations can weigh tens or even hundreds of megabytes. - * It is also useful to set anim:false when using format:"json" to get the - * response quicker without the number of frames. - */ - anim?: boolean - /** - * What EXIF data should be preserved in the output image. Note that EXIF - * rotation and embedded color profiles are always applied ("baked in" into - * the image), and aren't affected by this option. Note that if the Polish - * feature is enabled, all metadata may have been removed already and this - * option may have no effect. - * - keep: Preserve most of EXIF metadata, including GPS location if there's - * any. - * - copyright: Only keep the copyright tag, and discard everything else. - * This is the default behavior for JPEG files. - * - none: Discard all invisible EXIF metadata. Currently WebP and PNG - * output formats always discard metadata. - */ - metadata?: 'keep' | 'copyright' | 'none' - /** - * Strength of sharpening filter to apply to the image. Floating-point - * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a - * recommended value for downscaled images. - */ - sharpen?: number - /** - * Radius of a blur filter (approximate gaussian). Maximum supported radius - * is 250. - */ - blur?: number - /** - * Overlays are drawn in the order they appear in the array (last array - * entry is the topmost layer). - */ - draw?: RequestInitCfPropertiesImageDraw[] - /** - * Fetching image from authenticated origin. Setting this property will - * pass authentication headers (Authorization, Cookie, etc.) through to - * the origin. - */ - 'origin-auth'?: 'share-publicly' - /** - * Adds a border around the image. The border is added after resizing. Border - * width takes dpr into account, and can be specified either using a single - * width property, or individually for each side. - */ - border?: - | { - color: string - width: number - } - | { - color: string - top: number - right: number - bottom: number - left: number - } - /** - * Increase brightness by a factor. A value of 1.0 equals no change, a value - * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. - * 0 is ignored. - */ - brightness?: number - /** - * Increase contrast by a factor. A value of 1.0 equals no change, a value of - * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is - * ignored. - */ - contrast?: number - /** - * Increase exposure by a factor. A value of 1.0 equals no change, a value of - * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. - */ - gamma?: number - /** - * Increase contrast by a factor. A value of 1.0 equals no change, a value of - * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is - * ignored. - */ - saturation?: number - /** - * Flips the images horizontally, vertically, or both. Flipping is applied before - * rotation, so if you apply flip=h,rotate=90 then the image will be flipped - * horizontally, then rotated by 90 degrees. - */ - flip?: 'h' | 'v' | 'hv' - /** - * Slightly reduces latency on a cache miss by selecting a - * quickest-to-compress file format, at a cost of increased file size and - * lower image quality. It will usually override the format option and choose - * JPEG over WebP or AVIF. We do not recommend using this option, except in - * unusual circumstances like resizing uncacheable dynamically-generated - * images. - */ - compression?: 'fast' + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * Allows you to trim your image. Takes dpr into account and is performed before + * resizing or rotation. + * + * It can be used as: + * - left, top, right, bottom - it will specify the number of pixels to cut + * off each side + * - width, height - the width/height you'd like to end up with - can be used + * in combination with the properties above + * - border - this will automatically trim the surroundings of an image based on + * it's color. It consists of three properties: + * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) + * - tolerance: difference from color to treat as color + * - keep: the number of pixels of border to keep + */ + trim?: "border" | { + top?: number; + bottom?: number; + left?: number; + right?: number; + width?: number; + height?: number; + border?: boolean | { + color?: string; + tolerance?: number; + keep?: number; + }; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number | "low" | "medium-low" | "medium-high" | "high"; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: { + color: string; + width: number; + } | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + saturation?: number; + /** + * Flips the images horizontally, vertically, or both. Flipping is applied before + * rotation, so if you apply flip=h,rotate=90 then the image will be flipped + * horizontally, then rotated by 90 degrees. + */ + flip?: 'h' | 'v' | 'hv'; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; } interface RequestInitCfPropertiesImageMinify { - javascript?: boolean - css?: boolean - html?: boolean + javascript?: boolean; + css?: boolean; + html?: boolean; } interface RequestInitCfPropertiesR2 { - /** - * Colo id of bucket that an object is stored in - */ - bucketColoId?: number + /** + * Colo id of bucket that an object is stored in + */ + bucketColoId?: number; } /** * Request metadata provided by Cloudflare's edge. */ -type IncomingRequestCfProperties = - IncomingRequestCfPropertiesBase & - IncomingRequestCfPropertiesBotManagementEnterprise & - IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & - IncomingRequestCfPropertiesGeographicInformation & - IncomingRequestCfPropertiesCloudflareAccessOrApiShield +type IncomingRequestCfProperties = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield; interface IncomingRequestCfPropertiesBase extends Record { - /** - * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. - * - * @example 395747 - */ - asn?: number - /** - * The organization which owns the ASN of the incoming request. - * - * @example "Google Cloud" - */ - asOrganization?: string - /** - * The original value of the `Accept-Encoding` header if Cloudflare modified it. - * - * @example "gzip, deflate, br" - */ - clientAcceptEncoding?: string - /** - * The number of milliseconds it took for the request to reach your worker. - * - * @example 22 - */ - clientTcpRtt?: number - /** - * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) - * airport code of the data center that the request hit. - * - * @example "DFW" - */ - colo: string - /** - * Represents the upstream's response to a - * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) - * from cloudflare. - * - * For workers with no upstream, this will always be `1`. - * - * @example 3 - */ - edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus - /** - * The HTTP Protocol the request used. - * - * @example "HTTP/2" - */ - httpProtocol: string - /** - * The browser-requested prioritization information in the request object. - * - * If no information was set, defaults to the empty string `""` - * - * @example "weight=192;exclusive=0;group=3;group-weight=127" - * @default "" - */ - requestPriority: string - /** - * The TLS version of the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "TLSv1.3" - */ - tlsVersion: string - /** - * The cipher for the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "AEAD-AES128-GCM-SHA256" - */ - tlsCipher: string - /** - * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. - * - * If the incoming request was served over plaintext (without TLS) this field is undefined. - */ - tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn?: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization?: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; } interface IncomingRequestCfPropertiesBotManagementBase { - /** - * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, - * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). - * - * @example 54 - */ - score: number - /** - * A boolean value that is true if the request comes from a good bot, like Google or Bing. - * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). - */ - verifiedBot: boolean - /** - * A boolean value that is true if the request originates from a - * Cloudflare-verified proxy service. - */ - corporateProxy: boolean - /** - * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. - */ - staticResource: boolean - /** - * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). - */ - detectionIds: number[] + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; } interface IncomingRequestCfPropertiesBotManagement { - /** - * Results of Cloudflare's Bot Management analysis - */ - botManagement: IncomingRequestCfPropertiesBotManagementBase - /** - * Duplicate of `botManagement.score`. - * - * @deprecated - */ - clientTrustScore: number -} -interface IncomingRequestCfPropertiesBotManagementEnterprise - extends IncomingRequestCfPropertiesBotManagement { - /** - * Results of Cloudflare's Bot Management analysis - */ - botManagement: IncomingRequestCfPropertiesBotManagementBase & { /** - * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients - * across different destination IPs, Ports, and X509 certificates. + * Results of Cloudflare's Bot Management analysis */ - ja3Hash: string - } + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; } interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise { - /** - * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). - * - * This field is only present if you have Cloudflare for SaaS enabled on your account - * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). - */ - hostMetadata?: HostMetadata + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata?: HostMetadata; } interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { - /** - * Information about the client certificate presented to Cloudflare. - * - * This is populated when the incoming request is served over TLS using - * either Cloudflare Access or API Shield (mTLS) - * and the presented SSL certificate has a valid - * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) - * (i.e., not `null` or `""`). - * - * Otherwise, a set of placeholder values are used. - * - * The property `certPresented` will be set to `"1"` when - * the object is populated (i.e. the above conditions were met). - */ - tlsClientAuth: - | IncomingRequestCfPropertiesTLSClientAuth - | IncomingRequestCfPropertiesTLSClientAuthPlaceholder + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; } /** * Metadata about the request's TLS handshake */ interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { - /** - * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - clientHandshake: string - /** - * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - serverHandshake: string - /** - * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - clientFinished: string - /** - * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - serverFinished: string + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; } /** * Geographic data about the request's origin. */ interface IncomingRequestCfPropertiesGeographicInformation { - /** - * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. - * - * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. - * - * If Cloudflare is unable to determine where the request originated this property is omitted. - * - * The country code `"T1"` is used for requests originating on TOR. - * - * @example "GB" - */ - country?: Iso3166Alpha2Code | 'T1' - /** - * If present, this property indicates that the request originated in the EU - * - * @example "1" - */ - isEUCountry?: '1' - /** - * A two-letter code indicating the continent the request originated from. - * - * @example "AN" - */ - continent?: ContinentCode - /** - * The city the request originated from - * - * @example "Austin" - */ - city?: string - /** - * Postal code of the incoming request - * - * @example "78701" - */ - postalCode?: string - /** - * Latitude of the incoming request - * - * @example "30.27130" - */ - latitude?: string - /** - * Longitude of the incoming request - * - * @example "-97.74260" - */ - longitude?: string - /** - * Timezone of the incoming request - * - * @example "America/Chicago" - */ - timezone?: string - /** - * If known, the ISO 3166-2 name for the first level region associated with - * the IP address of the incoming request - * - * @example "Texas" - */ - region?: string - /** - * If known, the ISO 3166-2 code for the first-level region associated with - * the IP address of the incoming request - * - * @example "TX" - */ - regionCode?: string - /** - * Metro code (DMA) of the incoming request - * - * @example "635" - */ - metroCode?: string + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; } /** Data about the incoming request's TLS certificate */ interface IncomingRequestCfPropertiesTLSClientAuth { - /** Always `"1"`, indicating that the certificate was presented */ - certPresented: '1' - /** - * Result of certificate verification. - * - * @example "FAILED:self signed certificate" - */ - certVerified: Exclude - /** The presented certificate's revokation status. - * - * - A value of `"1"` indicates the certificate has been revoked - * - A value of `"0"` indicates the certificate has not been revoked - */ - certRevoked: '1' | '0' - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDN: string - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDN: string - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDNRFC2253: string - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDNRFC2253: string - /** The certificate issuer's distinguished name (legacy policies) */ - certIssuerDNLegacy: string - /** The certificate subject's distinguished name (legacy policies) */ - certSubjectDNLegacy: string - /** - * The certificate's serial number - * - * @example "00936EACBE07F201DF" - */ - certSerial: string - /** - * The certificate issuer's serial number - * - * @example "2489002934BDFEA34" - */ - certIssuerSerial: string - /** - * The certificate's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certSKI: string - /** - * The certificate issuer's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certIssuerSKI: string - /** - * The certificate's SHA-1 fingerprint - * - * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" - */ - certFingerprintSHA1: string - /** - * The certificate's SHA-256 fingerprint - * - * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" - */ - certFingerprintSHA256: string - /** - * The effective starting date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotBefore: string - /** - * The effective expiration date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotAfter: string + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; } /** Placeholder values for TLS Client Authorization */ interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { - certPresented: '0' - certVerified: 'NONE' - certRevoked: '0' - certIssuerDN: '' - certSubjectDN: '' - certIssuerDNRFC2253: '' - certSubjectDNRFC2253: '' - certIssuerDNLegacy: '' - certSubjectDNLegacy: '' - certSerial: '' - certIssuerSerial: '' - certSKI: '' - certIssuerSKI: '' - certFingerprintSHA1: '' - certFingerprintSHA256: '' - certNotBefore: '' - certNotAfter: '' + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; } /** Possible outcomes of TLS verification */ -declare type CertVerificationStatus = - /** Authentication succeeded */ - | 'SUCCESS' - /** No certificate was presented */ - | 'NONE' - /** Failed because the certificate was self-signed */ - | 'FAILED:self signed certificate' - /** Failed because the certificate failed a trust chain check */ - | 'FAILED:unable to verify the first certificate' - /** Failed because the certificate not yet valid */ - | 'FAILED:certificate is not yet valid' - /** Failed because the certificate is expired */ - | 'FAILED:certificate has expired' - /** Failed for another unspecified reason */ - | 'FAILED' +declare type CertVerificationStatus = +/** Authentication succeeded */ +"SUCCESS" +/** No certificate was presented */ + | "NONE" +/** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" +/** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" +/** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" +/** Failed because the certificate is expired */ + | "FAILED:certificate has expired" +/** Failed for another unspecified reason */ + | "FAILED"; /** * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. */ -declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = - | 0 /** Unknown */ - | 1 /** no keepalives (not found) */ - | 2 /** no connection re-use, opening keepalive connection failed */ - | 3 /** no connection re-use, keepalive accepted and saved */ - | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ - | 5 /** connection re-use, accepted by the origin server */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5; /** connection re-use, accepted by the origin server */ /** ISO 3166-1 Alpha-2 codes */ -declare type Iso3166Alpha2Code = - | 'AD' - | 'AE' - | 'AF' - | 'AG' - | 'AI' - | 'AL' - | 'AM' - | 'AO' - | 'AQ' - | 'AR' - | 'AS' - | 'AT' - | 'AU' - | 'AW' - | 'AX' - | 'AZ' - | 'BA' - | 'BB' - | 'BD' - | 'BE' - | 'BF' - | 'BG' - | 'BH' - | 'BI' - | 'BJ' - | 'BL' - | 'BM' - | 'BN' - | 'BO' - | 'BQ' - | 'BR' - | 'BS' - | 'BT' - | 'BV' - | 'BW' - | 'BY' - | 'BZ' - | 'CA' - | 'CC' - | 'CD' - | 'CF' - | 'CG' - | 'CH' - | 'CI' - | 'CK' - | 'CL' - | 'CM' - | 'CN' - | 'CO' - | 'CR' - | 'CU' - | 'CV' - | 'CW' - | 'CX' - | 'CY' - | 'CZ' - | 'DE' - | 'DJ' - | 'DK' - | 'DM' - | 'DO' - | 'DZ' - | 'EC' - | 'EE' - | 'EG' - | 'EH' - | 'ER' - | 'ES' - | 'ET' - | 'FI' - | 'FJ' - | 'FK' - | 'FM' - | 'FO' - | 'FR' - | 'GA' - | 'GB' - | 'GD' - | 'GE' - | 'GF' - | 'GG' - | 'GH' - | 'GI' - | 'GL' - | 'GM' - | 'GN' - | 'GP' - | 'GQ' - | 'GR' - | 'GS' - | 'GT' - | 'GU' - | 'GW' - | 'GY' - | 'HK' - | 'HM' - | 'HN' - | 'HR' - | 'HT' - | 'HU' - | 'ID' - | 'IE' - | 'IL' - | 'IM' - | 'IN' - | 'IO' - | 'IQ' - | 'IR' - | 'IS' - | 'IT' - | 'JE' - | 'JM' - | 'JO' - | 'JP' - | 'KE' - | 'KG' - | 'KH' - | 'KI' - | 'KM' - | 'KN' - | 'KP' - | 'KR' - | 'KW' - | 'KY' - | 'KZ' - | 'LA' - | 'LB' - | 'LC' - | 'LI' - | 'LK' - | 'LR' - | 'LS' - | 'LT' - | 'LU' - | 'LV' - | 'LY' - | 'MA' - | 'MC' - | 'MD' - | 'ME' - | 'MF' - | 'MG' - | 'MH' - | 'MK' - | 'ML' - | 'MM' - | 'MN' - | 'MO' - | 'MP' - | 'MQ' - | 'MR' - | 'MS' - | 'MT' - | 'MU' - | 'MV' - | 'MW' - | 'MX' - | 'MY' - | 'MZ' - | 'NA' - | 'NC' - | 'NE' - | 'NF' - | 'NG' - | 'NI' - | 'NL' - | 'NO' - | 'NP' - | 'NR' - | 'NU' - | 'NZ' - | 'OM' - | 'PA' - | 'PE' - | 'PF' - | 'PG' - | 'PH' - | 'PK' - | 'PL' - | 'PM' - | 'PN' - | 'PR' - | 'PS' - | 'PT' - | 'PW' - | 'PY' - | 'QA' - | 'RE' - | 'RO' - | 'RS' - | 'RU' - | 'RW' - | 'SA' - | 'SB' - | 'SC' - | 'SD' - | 'SE' - | 'SG' - | 'SH' - | 'SI' - | 'SJ' - | 'SK' - | 'SL' - | 'SM' - | 'SN' - | 'SO' - | 'SR' - | 'SS' - | 'ST' - | 'SV' - | 'SX' - | 'SY' - | 'SZ' - | 'TC' - | 'TD' - | 'TF' - | 'TG' - | 'TH' - | 'TJ' - | 'TK' - | 'TL' - | 'TM' - | 'TN' - | 'TO' - | 'TR' - | 'TT' - | 'TV' - | 'TW' - | 'TZ' - | 'UA' - | 'UG' - | 'UM' - | 'US' - | 'UY' - | 'UZ' - | 'VA' - | 'VC' - | 'VE' - | 'VG' - | 'VI' - | 'VN' - | 'VU' - | 'WF' - | 'WS' - | 'YE' - | 'YT' - | 'ZA' - | 'ZM' - | 'ZW' +declare type Iso3166Alpha2Code = "AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" | "AO" | "AQ" | "AR" | "AS" | "AT" | "AU" | "AW" | "AX" | "AZ" | "BA" | "BB" | "BD" | "BE" | "BF" | "BG" | "BH" | "BI" | "BJ" | "BL" | "BM" | "BN" | "BO" | "BQ" | "BR" | "BS" | "BT" | "BV" | "BW" | "BY" | "BZ" | "CA" | "CC" | "CD" | "CF" | "CG" | "CH" | "CI" | "CK" | "CL" | "CM" | "CN" | "CO" | "CR" | "CU" | "CV" | "CW" | "CX" | "CY" | "CZ" | "DE" | "DJ" | "DK" | "DM" | "DO" | "DZ" | "EC" | "EE" | "EG" | "EH" | "ER" | "ES" | "ET" | "FI" | "FJ" | "FK" | "FM" | "FO" | "FR" | "GA" | "GB" | "GD" | "GE" | "GF" | "GG" | "GH" | "GI" | "GL" | "GM" | "GN" | "GP" | "GQ" | "GR" | "GS" | "GT" | "GU" | "GW" | "GY" | "HK" | "HM" | "HN" | "HR" | "HT" | "HU" | "ID" | "IE" | "IL" | "IM" | "IN" | "IO" | "IQ" | "IR" | "IS" | "IT" | "JE" | "JM" | "JO" | "JP" | "KE" | "KG" | "KH" | "KI" | "KM" | "KN" | "KP" | "KR" | "KW" | "KY" | "KZ" | "LA" | "LB" | "LC" | "LI" | "LK" | "LR" | "LS" | "LT" | "LU" | "LV" | "LY" | "MA" | "MC" | "MD" | "ME" | "MF" | "MG" | "MH" | "MK" | "ML" | "MM" | "MN" | "MO" | "MP" | "MQ" | "MR" | "MS" | "MT" | "MU" | "MV" | "MW" | "MX" | "MY" | "MZ" | "NA" | "NC" | "NE" | "NF" | "NG" | "NI" | "NL" | "NO" | "NP" | "NR" | "NU" | "NZ" | "OM" | "PA" | "PE" | "PF" | "PG" | "PH" | "PK" | "PL" | "PM" | "PN" | "PR" | "PS" | "PT" | "PW" | "PY" | "QA" | "RE" | "RO" | "RS" | "RU" | "RW" | "SA" | "SB" | "SC" | "SD" | "SE" | "SG" | "SH" | "SI" | "SJ" | "SK" | "SL" | "SM" | "SN" | "SO" | "SR" | "SS" | "ST" | "SV" | "SX" | "SY" | "SZ" | "TC" | "TD" | "TF" | "TG" | "TH" | "TJ" | "TK" | "TL" | "TM" | "TN" | "TO" | "TR" | "TT" | "TV" | "TW" | "TZ" | "UA" | "UG" | "UM" | "US" | "UY" | "UZ" | "VA" | "VC" | "VE" | "VG" | "VI" | "VN" | "VU" | "WF" | "WS" | "YE" | "YT" | "ZA" | "ZM" | "ZW"; /** The 2-letter continent codes Cloudflare uses */ -declare type ContinentCode = 'AF' | 'AN' | 'AS' | 'EU' | 'NA' | 'OC' | 'SA' -type CfProperties = - | IncomingRequestCfProperties - | RequestInitCfProperties +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +type CfProperties = IncomingRequestCfProperties | RequestInitCfProperties; interface D1Meta { - duration: number - size_after: number - rows_read: number - rows_written: number - last_row_id: number - changed_db: boolean - changes: number - /** - * The region of the database instance that executed the query. - */ - served_by_region?: string - /** - * True if-and-only-if the database instance that executed the query was the primary. - */ - served_by_primary?: boolean - timings?: { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; /** - * The duration of the SQL query execution by the database instance. It doesn't include any network time. + * The region of the database instance that executed the query. */ - sql_duration_ms: number - } - /** - * Number of total attempts to execute the query, due to automatic retries. - * Note: All other fields in the response like `timings` only apply to the last attempt. - */ - total_attempts?: number + served_by_region?: string; + /** + * The three letters airport code of the colo that executed the query. + */ + served_by_colo?: string; + /** + * True if-and-only-if the database instance that executed the query was the primary. + */ + served_by_primary?: boolean; + timings?: { + /** + * The duration of the SQL query execution by the database instance. It doesn't include any network time. + */ + sql_duration_ms: number; + }; + /** + * Number of total attempts to execute the query, due to automatic retries. + * Note: All other fields in the response like `timings` only apply to the last attempt. + */ + total_attempts?: number; } interface D1Response { - success: true - meta: D1Meta & Record - error?: never + success: true; + meta: D1Meta & Record; + error?: never; } type D1Result = D1Response & { - results: T[] -} + results: T[]; +}; interface D1ExecResult { - count: number - duration: number + count: number; + duration: number; } -type D1SessionConstraint = - // Indicates that the first query should go to the primary, and the rest queries - // using the same D1DatabaseSession will go to any replica that is consistent with - // the bookmark maintained by the session (returned by the first query). - | 'first-primary' - // Indicates that the first query can go anywhere (primary or replica), and the rest queries - // using the same D1DatabaseSession will go to any replica that is consistent with - // the bookmark maintained by the session (returned by the first query). - | 'first-unconstrained' -type D1SessionBookmark = string +type D1SessionConstraint = +// Indicates that the first query should go to the primary, and the rest queries +// using the same D1DatabaseSession will go to any replica that is consistent with +// the bookmark maintained by the session (returned by the first query). +'first-primary' +// Indicates that the first query can go anywhere (primary or replica), and the rest queries +// using the same D1DatabaseSession will go to any replica that is consistent with +// the bookmark maintained by the session (returned by the first query). + | 'first-unconstrained'; +type D1SessionBookmark = string; declare abstract class D1Database { - prepare(query: string): D1PreparedStatement - batch(statements: D1PreparedStatement[]): Promise[]> - exec(query: string): Promise - /** - * Creates a new D1 Session anchored at the given constraint or the bookmark. - * All queries executed using the created session will have sequential consistency, - * meaning that all writes done through the session will be visible in subsequent reads. - * - * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. - */ - withSession( - constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint, - ): D1DatabaseSession - /** - * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. - */ - dump(): Promise + prepare(query: string): D1PreparedStatement; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; + /** + * Creates a new D1 Session anchored at the given constraint or the bookmark. + * All queries executed using the created session will have sequential consistency, + * meaning that all writes done through the session will be visible in subsequent reads. + * + * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. + */ + withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession; + /** + * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. + */ + dump(): Promise; } declare abstract class D1DatabaseSession { - prepare(query: string): D1PreparedStatement - batch(statements: D1PreparedStatement[]): Promise[]> - /** - * @returns The latest session bookmark across all executed queries on the session. - * If no query has been executed yet, `null` is returned. - */ - getBookmark(): D1SessionBookmark | null + prepare(query: string): D1PreparedStatement; + batch(statements: D1PreparedStatement[]): Promise[]>; + /** + * @returns The latest session bookmark across all executed queries on the session. + * If no query has been executed yet, `null` is returned. + */ + getBookmark(): D1SessionBookmark | null; } declare abstract class D1PreparedStatement { - bind(...values: unknown[]): D1PreparedStatement - first(colName: string): Promise - first>(): Promise - run>(): Promise> - all>(): Promise> - raw(options: { - columnNames: true - }): Promise<[string[], ...T[]]> - raw(options?: { columnNames?: false }): Promise + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run>(): Promise>; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[ + string[], + ...T[] + ]>; + raw(options?: { + columnNames?: false; + }): Promise; } // `Disposable` was added to TypeScript's standard lib types in version 5.2. // To support older TypeScript versions, define an empty `Disposable` interface. @@ -8783,1138 +9848,1846 @@ declare abstract class D1PreparedStatement { // but this will ensure type checking on older versions still passes. // TypeScript's interface merging will ensure our empty interface is effectively // ignored when `Disposable` is included in the standard lib. -interface Disposable {} +interface Disposable { +} +/** + * The returned data after sending an email + */ +interface EmailSendResult { + /** + * The Email Message ID + */ + messageId: string; +} /** * An email message that can be sent from a Worker. */ interface EmailMessage { - /** - * Envelope From attribute of the email message. - */ - readonly from: string - /** - * Envelope To attribute of the email message. - */ - readonly to: string + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; } /** * An email message that is sent to a consumer Worker and can be rejected/forwarded. */ interface ForwardableEmailMessage extends EmailMessage { - /** - * Stream of the email message content. - */ - readonly raw: ReadableStream - /** - * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - */ - readonly headers: Headers - /** - * Size of the email message content. - */ - readonly rawSize: number - /** - * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. - * @param reason The reject reason. - * @returns void - */ - setReject(reason: string): void - /** - * Forward this email message to a verified destination address of the account. - * @param rcptTo Verified destination address. - * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - * @returns A promise that resolves when the email message is forwarded. - */ - forward(rcptTo: string, headers?: Headers): Promise - /** - * Reply to the sender of this email message with a new EmailMessage object. - * @param message The reply message. - * @returns A promise that resolves when the email message is replied. - */ - reply(message: EmailMessage): Promise + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; + /** + * Reply to the sender of this email message with a new EmailMessage object. + * @param message The reply message. + * @returns A promise that resolves when the email message is replied. + */ + reply(message: EmailMessage): Promise; +} +/** A file attachment for an email message */ +type EmailAttachment = { + disposition: 'inline'; + contentId: string; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; +} | { + disposition: 'attachment'; + contentId?: undefined; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; +}; +/** An Email Address */ +interface EmailAddress { + name: string; + email: string; } /** * A binding that allows a Worker to send email messages. */ interface SendEmail { - send(message: EmailMessage): Promise + send(message: EmailMessage): Promise; + send(builder: { + from: string | EmailAddress; + to: string | string[]; + subject: string; + replyTo?: string | EmailAddress; + cc?: string | string[]; + bcc?: string | string[]; + headers?: Record; + text?: string; + html?: string; + attachments?: EmailAttachment[]; + }): Promise; } declare abstract class EmailEvent extends ExtendableEvent { - readonly message: ForwardableEmailMessage + readonly message: ForwardableEmailMessage; } -declare type EmailExportedHandler = ( - message: ForwardableEmailMessage, - env: Env, - ctx: ExecutionContext, -) => void | Promise -declare module 'cloudflare:email' { - let _EmailMessage: { - prototype: EmailMessage - new (from: string, to: string, raw: ReadableStream | string): EmailMessage - } - export { _EmailMessage as EmailMessage } +declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; } /** * Hello World binding to serve as an explanatory example. DO NOT USE */ interface HelloWorldBinding { - /** - * Retrieve the current stored value - */ - get(): Promise<{ - value: string - ms?: number - }> - /** - * Set a new stored value - */ - set(value: string): Promise + /** + * Retrieve the current stored value + */ + get(): Promise<{ + value: string; + ms?: number; + }>; + /** + * Set a new stored value + */ + set(value: string): Promise; } interface Hyperdrive { - /** - * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. - * - * Calling this method returns an idential socket to if you call - * `connect("host:port")` using the `host` and `port` fields from this object. - * Pick whichever approach works better with your preferred DB client library. - * - * Note that this socket is not yet authenticated -- it's expected that your - * code (or preferably, the client library of your choice) will authenticate - * using the information in this class's readonly fields. - */ - connect(): Socket - /** - * A valid DB connection string that can be passed straight into the typical - * client library/driver/ORM. This will typically be the easiest way to use - * Hyperdrive. - */ - readonly connectionString: string - /* - * A randomly generated hostname that is only valid within the context of the - * currently running Worker which, when passed into `connect()` function from - * the "cloudflare:sockets" module, will connect to the Hyperdrive instance - * for your database. - */ - readonly host: string - /* - * The port that must be paired the the host field when connecting. - */ - readonly port: number - /* - * The username to use when authenticating to your database via Hyperdrive. - * Unlike the host and password, this will be the same every time - */ - readonly user: string - /* - * The randomly generated password to use when authenticating to your - * database via Hyperdrive. Like the host field, this password is only valid - * within the context of the currently running Worker instance from which - * it's read. - */ - readonly password: string - /* - * The name of the database to connect to. - */ - readonly database: string + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an identical socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; } // Copyright (c) 2024 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: // https://opensource.org/licenses/Apache-2.0 -type ImageInfoResponse = - | { - format: 'image/svg+xml' - } - | { - format: string - fileSize: number - width: number - height: number - } +type ImageInfoResponse = { + format: 'image/svg+xml'; +} | { + format: string; + fileSize: number; + width: number; + height: number; +}; type ImageTransform = { - width?: number - height?: number - background?: string - blur?: number - border?: - | { - color?: string - width?: number - } - | { - top?: number - bottom?: number - left?: number - right?: number - } - brightness?: number - contrast?: number - fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop' - flip?: 'h' | 'v' | 'hv' - gamma?: number - segment?: 'foreground' - gravity?: - | 'face' - | 'left' - | 'right' - | 'top' - | 'bottom' - | 'center' - | 'auto' - | 'entropy' - | { - x?: number - y?: number - mode: 'remainder' | 'box-center' - } - rotate?: 0 | 90 | 180 | 270 - saturation?: number - sharpen?: number - trim?: - | 'border' - | { - top?: number - bottom?: number - left?: number - right?: number - width?: number - height?: number - border?: - | boolean - | { - color?: string - tolerance?: number - keep?: number - } - } -} + width?: number; + height?: number; + background?: string; + blur?: number; + border?: { + color?: string; + width?: number; + } | { + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + brightness?: number; + contrast?: number; + fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop'; + flip?: 'h' | 'v' | 'hv'; + gamma?: number; + segment?: 'foreground'; + gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | { + x?: number; + y?: number; + mode: 'remainder' | 'box-center'; + }; + rotate?: 0 | 90 | 180 | 270; + saturation?: number; + sharpen?: number; + trim?: 'border' | { + top?: number; + bottom?: number; + left?: number; + right?: number; + width?: number; + height?: number; + border?: boolean | { + color?: string; + tolerance?: number; + keep?: number; + }; + }; +}; type ImageDrawOptions = { - opacity?: number - repeat?: boolean | string - top?: number - left?: number - bottom?: number - right?: number -} + opacity?: number; + repeat?: boolean | string; + top?: number; + left?: number; + bottom?: number; + right?: number; +}; type ImageInputOptions = { - encoding?: 'base64' -} + encoding?: 'base64'; +}; type ImageOutputOptions = { - format: - | 'image/jpeg' - | 'image/png' - | 'image/gif' - | 'image/webp' - | 'image/avif' - | 'rgb' - | 'rgba' - quality?: number - background?: string - anim?: boolean + format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; + quality?: number; + background?: string; + anim?: boolean; +}; +interface ImageMetadata { + id: string; + filename?: string; + uploaded?: string; + requireSignedURLs: boolean; + meta?: Record; + variants: string[]; + draft?: boolean; + creator?: string; +} +interface ImageUploadOptions { + id?: string; + filename?: string; + requireSignedURLs?: boolean; + metadata?: Record; + creator?: string; + encoding?: 'base64'; +} +interface ImageUpdateOptions { + requireSignedURLs?: boolean; + metadata?: Record; + creator?: string; +} +interface ImageListOptions { + limit?: number; + cursor?: string; + sortOrder?: 'asc' | 'desc'; + creator?: string; +} +interface ImageList { + images: ImageMetadata[]; + cursor?: string; + listComplete: boolean; +} +interface HostedImagesBinding { + /** + * Get detailed metadata for a hosted image + * @param imageId The ID of the image (UUID or custom ID) + * @returns Image metadata, or null if not found + */ + details(imageId: string): Promise; + /** + * Get the raw image data for a hosted image + * @param imageId The ID of the image (UUID or custom ID) + * @returns ReadableStream of image bytes, or null if not found + */ + image(imageId: string): Promise | null>; + /** + * Upload a new hosted image + * @param image The image file to upload + * @param options Upload configuration + * @returns Metadata for the uploaded image + * @throws {@link ImagesError} if upload fails + */ + upload(image: ReadableStream | ArrayBuffer, options?: ImageUploadOptions): Promise; + /** + * Update hosted image metadata + * @param imageId The ID of the image + * @param options Properties to update + * @returns Updated image metadata + * @throws {@link ImagesError} if update fails + */ + update(imageId: string, options: ImageUpdateOptions): Promise; + /** + * Delete a hosted image + * @param imageId The ID of the image + * @returns True if deleted, false if not found + */ + delete(imageId: string): Promise; + /** + * List hosted images with pagination + * @param options List configuration + * @returns List of images with pagination info + * @throws {@link ImagesError} if list fails + */ + list(options?: ImageListOptions): Promise; } interface ImagesBinding { - /** - * Get image metadata (type, width and height) - * @throws {@link ImagesError} with code 9412 if input is not an image - * @param stream The image bytes - */ - info( - stream: ReadableStream, - options?: ImageInputOptions, - ): Promise - /** - * Begin applying a series of transformations to an image - * @param stream The image bytes - * @returns A transform handle - */ - input( - stream: ReadableStream, - options?: ImageInputOptions, - ): ImageTransformer + /** + * Get image metadata (type, width and height) + * @throws {@link ImagesError} with code 9412 if input is not an image + * @param stream The image bytes + */ + info(stream: ReadableStream, options?: ImageInputOptions): Promise; + /** + * Begin applying a series of transformations to an image + * @param stream The image bytes + * @returns A transform handle + */ + input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; + /** + * Access hosted images CRUD operations + */ + readonly hosted: HostedImagesBinding; } interface ImageTransformer { - /** - * Apply transform next, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param transform - */ - transform(transform: ImageTransform): ImageTransformer - /** - * Draw an image on this transformer, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param image The image (or transformer that will give the image) to draw - * @param options The options configuring how to draw the image - */ - draw( - image: ReadableStream | ImageTransformer, - options?: ImageDrawOptions, - ): ImageTransformer - /** - * Retrieve the image that results from applying the transforms to the - * provided input - * @param options Options that apply to the output e.g. output format - */ - output(options: ImageOutputOptions): Promise + /** + * Apply transform next, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param transform + */ + transform(transform: ImageTransform): ImageTransformer; + /** + * Draw an image on this transformer, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param image The image (or transformer that will give the image) to draw + * @param options The options configuring how to draw the image + */ + draw(image: ReadableStream | ImageTransformer, options?: ImageDrawOptions): ImageTransformer; + /** + * Retrieve the image that results from applying the transforms to the + * provided input + * @param options Options that apply to the output e.g. output format + */ + output(options: ImageOutputOptions): Promise; } type ImageTransformationOutputOptions = { - encoding?: 'base64' -} + encoding?: 'base64'; +}; interface ImageTransformationResult { - /** - * The image as a response, ready to store in cache or return to users - */ - response(): Response - /** - * The content type of the returned image - */ - contentType(): string - /** - * The bytes of the response - */ - image(options?: ImageTransformationOutputOptions): ReadableStream + /** + * The image as a response, ready to store in cache or return to users + */ + response(): Response; + /** + * The content type of the returned image + */ + contentType(): string; + /** + * The bytes of the response + */ + image(options?: ImageTransformationOutputOptions): ReadableStream; } interface ImagesError extends Error { - readonly code: number - readonly message: string - readonly stack?: string + readonly code: number; + readonly message: string; + readonly stack?: string; } /** * Media binding for transforming media streams. * Provides the entry point for media transformation operations. */ interface MediaBinding { - /** - * Creates a media transformer from an input stream. - * @param media - The input media bytes - * @returns A MediaTransformer instance for applying transformations - */ - input(media: ReadableStream): MediaTransformer + /** + * Creates a media transformer from an input stream. + * @param media - The input media bytes + * @returns A MediaTransformer instance for applying transformations + */ + input(media: ReadableStream): MediaTransformer; } /** * Media transformer for applying transformation operations to media content. * Handles sizing, fitting, and other input transformation parameters. */ interface MediaTransformer { - /** - * Applies transformation options to the media content. - * @param transform - Configuration for how the media should be transformed - * @returns A generator for producing the transformed media output - */ - transform( - transform: MediaTransformationInputOptions, - ): MediaTransformationGenerator + /** + * Applies transformation options to the media content. + * @param transform - Configuration for how the media should be transformed + * @returns A generator for producing the transformed media output + */ + transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator; + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; } /** * Generator for producing media transformation results. * Configures the output format and parameters for the transformed media. */ interface MediaTransformationGenerator { - /** - * Generates the final media output with specified options. - * @param output - Configuration for the output format and parameters - * @returns The final transformation result containing the transformed media - */ - output(output: MediaTransformationOutputOptions): MediaTransformationResult + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; } /** * Result of a media transformation operation. * Provides multiple ways to access the transformed media content. */ interface MediaTransformationResult { - /** - * Returns the transformed media as a readable stream of bytes. - * @returns A stream containing the transformed media data - */ - media(): ReadableStream - /** - * Returns the transformed media as an HTTP response object. - * @returns The transformed media as a Response, ready to store in cache or return to users - */ - response(): Response - /** - * Returns the MIME type of the transformed media. - * @returns The content type string (e.g., 'image/jpeg', 'video/mp4') - */ - contentType(): string + /** + * Returns the transformed media as a readable stream of bytes. + * @returns A promise containing a readable stream with the transformed media + */ + media(): Promise>; + /** + * Returns the transformed media as an HTTP response object. + * @returns The transformed media as a Promise, ready to store in cache or return to users + */ + response(): Promise; + /** + * Returns the MIME type of the transformed media. + * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4') + */ + contentType(): Promise; } /** * Configuration options for transforming media input. * Controls how the media should be resized and fitted. */ type MediaTransformationInputOptions = { - /** How the media should be resized to fit the specified dimensions */ - fit?: 'contain' | 'cover' | 'scale-down' - /** Target width in pixels */ - width?: number - /** Target height in pixels */ - height?: number -} + /** How the media should be resized to fit the specified dimensions */ + fit?: 'contain' | 'cover' | 'scale-down'; + /** Target width in pixels */ + width?: number; + /** Target height in pixels */ + height?: number; +}; /** * Configuration options for Media Transformations output. * Controls the format, timing, and type of the generated output. */ type MediaTransformationOutputOptions = { - /** - * Output mode determining the type of media to generate - */ - mode?: 'video' | 'spritesheet' | 'frame' | 'audio' - /** Whether to include audio in the output */ - audio?: boolean - /** - * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). - */ - time?: string - /** - * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). - */ - duration?: string - /** - * Number of frames in the spritesheet. - */ - imageCount?: number - /** - * Output format for the generated media. - */ - format?: 'jpg' | 'png' | 'm4a' -} + /** + * Output mode determining the type of media to generate + */ + mode?: 'video' | 'spritesheet' | 'frame' | 'audio'; + /** Whether to include audio in the output */ + audio?: boolean; + /** + * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). + */ + time?: string; + /** + * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). + */ + duration?: string; + /** + * Number of frames in the spritesheet. + */ + imageCount?: number; + /** + * Output format for the generated media. + */ + format?: 'jpg' | 'png' | 'm4a'; +}; /** * Error object for media transformation operations. * Extends the standard Error interface with additional media-specific information. */ interface MediaError extends Error { - readonly code: number - readonly message: string - readonly stack?: string + readonly code: number; + readonly message: string; + readonly stack?: string; } declare module 'cloudflare:node' { - interface NodeStyleServer { - listen(...args: unknown[]): this - address(): { - port?: number | null | undefined + interface NodeStyleServer { + listen(...args: unknown[]): this; + address(): { + port?: number | null | undefined; + }; } - } - export function httpServerHandler(port: number): ExportedHandler - export function httpServerHandler(options: { port: number }): ExportedHandler - export function httpServerHandler(server: NodeStyleServer): ExportedHandler + export function httpServerHandler(port: number): ExportedHandler; + export function httpServerHandler(options: { + port: number; + }): ExportedHandler; + export function httpServerHandler(server: NodeStyleServer): ExportedHandler; } -type Params

= Record +type Params

= Record; type EventContext = { - request: Request> - functionPath: string - waitUntil: (promise: Promise) => void - passThroughOnException: () => void - next: (input?: Request | string, init?: RequestInit) => Promise - env: Env & { - ASSETS: { - fetch: typeof fetch - } - } - params: Params

- data: Data -} -type PagesFunction< - Env = unknown, - Params extends string = any, - Data extends Record = Record, -> = (context: EventContext) => Response | Promise + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +type PagesFunction = Record> = (context: EventContext) => Response | Promise; type EventPluginContext = { - request: Request> - functionPath: string - waitUntil: (promise: Promise) => void - passThroughOnException: () => void - next: (input?: Request | string, init?: RequestInit) => Promise - env: Env & { - ASSETS: { - fetch: typeof fetch - } - } - params: Params

- data: Data - pluginArgs: PluginArgs -} -type PagesPluginFunction< - Env = unknown, - Params extends string = any, - Data extends Record = Record, - PluginArgs = unknown, -> = ( - context: EventPluginContext, -) => Response | Promise -declare module 'assets:*' { - export const onRequest: PagesFunction + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

) => Result> - : Result> - // Type for the callable part of an `Provider` if `T` is callable. - // This is intersected with methods/properties. - type MaybeCallableProvider = T extends (...args: any[]) => any - ? MethodOrProperty - : unknown - // Base type for all other types providing RPC-like interfaces. - // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. - // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. - export type Provider< - T extends object, - Reserved extends string = never, - > = MaybeCallableProvider & { - [K in Exclude< - keyof T, - Reserved | symbol | keyof StubBase - >]: MethodOrProperty - } + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + // prettier-ignore + type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll

) => Result> : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider = MaybeCallableProvider & Pick<{ + [K in keyof T]: MethodOrProperty; + }, Exclude>>; } declare namespace Cloudflare { - // Type of `env`. - // - // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript - // will merge all declarations. - // - // You can use `wrangler types` to generate the `Env` type automatically. - interface Env {} - // Project-specific parameters used to inform types. - // - // This interface is, again, intended to be declared in project-specific files, and then that - // declaration will be merged with this one. - // - // A project should have a declaration like this: - // - // interface GlobalProps { - // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type - // // of `ctx.exports`. - // mainModule: typeof import("my-main-module"); - // - // // Declares which of the main module's exports are configured with durable storage, and - // // thus should behave as Durable Object namsepace bindings. - // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; - // } - // - // You can use `wrangler types` to generate `GlobalProps` automatically. - interface GlobalProps {} - // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not - // present. - type GlobalProp = K extends keyof GlobalProps - ? GlobalProps[K] - : Default - // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the - // `mainModule` property. - type MainModule = GlobalProp<'mainModule', {}> - // The type of ctx.exports, which contains loopback bindings for all top-level exports. - type Exports = { - [K in keyof MainModule]: LoopbackForExport & - // If the export is listed in `durableNamespaces`, then it is also a - // DurableObjectNamespace. - (K extends GlobalProp<'durableNamespaces', never> - ? MainModule[K] extends new (...args: any[]) => infer DoInstance - ? DoInstance extends Rpc.DurableObjectBranded - ? DurableObjectNamespace - : DurableObjectNamespace - : DurableObjectNamespace - : {}) - } + // Type of `env`. + // + // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript + // will merge all declarations. + // + // You can use `wrangler types` to generate the `Env` type automatically. + interface Env { + } + // Project-specific parameters used to inform types. + // + // This interface is, again, intended to be declared in project-specific files, and then that + // declaration will be merged with this one. + // + // A project should have a declaration like this: + // + // interface GlobalProps { + // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type + // // of `ctx.exports`. + // mainModule: typeof import("my-main-module"); + // + // // Declares which of the main module's exports are configured with durable storage, and + // // thus should behave as Durable Object namsepace bindings. + // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; + // } + // + // You can use `wrangler types` to generate `GlobalProps` automatically. + interface GlobalProps { + } + // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not + // present. + type GlobalProp = K extends keyof GlobalProps ? GlobalProps[K] : Default; + // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the + // `mainModule` property. + type MainModule = GlobalProp<"mainModule", {}>; + // The type of ctx.exports, which contains loopback bindings for all top-level exports. + type Exports = { + [K in keyof MainModule]: LoopbackForExport + // If the export is listed in `durableNamespaces`, then it is also a + // DurableObjectNamespace. + & (K extends GlobalProp<"durableNamespaces", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace : DurableObjectNamespace : DurableObjectNamespace : {}); + }; } declare namespace CloudflareWorkersModule { - export type RpcStub = Rpc.Stub - export const RpcStub: { - new (value: T): Rpc.Stub - } - export abstract class RpcTarget implements Rpc.RpcTargetBranded { - [Rpc.__RPC_TARGET_BRAND]: never - } - // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC - export abstract class WorkerEntrypoint - implements Rpc.WorkerEntrypointBranded - { - [Rpc.__WORKER_ENTRYPOINT_BRAND]: never - protected ctx: ExecutionContext - protected env: Env - constructor(ctx: ExecutionContext, env: Env) - email?(message: ForwardableEmailMessage): void | Promise - fetch?(request: Request): Response | Promise - queue?(batch: MessageBatch): void | Promise - scheduled?(controller: ScheduledController): void | Promise - tail?(events: TraceItem[]): void | Promise - tailStream?( - event: TailStream.TailEvent, - ): - | TailStream.TailEventHandlerType - | Promise - test?(controller: TestController): void | Promise - trace?(traces: TraceItem[]): void | Promise - } - export abstract class DurableObject - implements Rpc.DurableObjectBranded - { - [Rpc.__DURABLE_OBJECT_BRAND]: never - protected ctx: DurableObjectState - protected env: Env - constructor(ctx: DurableObjectState, env: Env) - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise - fetch?(request: Request): Response | Promise - webSocketMessage?( - ws: WebSocket, - message: string | ArrayBuffer, - ): void | Promise - webSocketClose?( - ws: WebSocket, - code: number, - reason: string, - wasClean: boolean, - ): void | Promise - webSocketError?(ws: WebSocket, error: unknown): void | Promise - } - export type WorkflowDurationLabel = - | 'second' - | 'minute' - | 'hour' - | 'day' - | 'week' - | 'month' - | 'year' - export type WorkflowSleepDuration = - | `${number} ${WorkflowDurationLabel}${'s' | ''}` - | number - export type WorkflowDelayDuration = WorkflowSleepDuration - export type WorkflowTimeoutDuration = WorkflowSleepDuration - export type WorkflowRetentionDuration = WorkflowSleepDuration - export type WorkflowBackoff = 'constant' | 'linear' | 'exponential' - export type WorkflowStepConfig = { - retries?: { - limit: number - delay: WorkflowDelayDuration | number - backoff?: WorkflowBackoff + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; } - timeout?: WorkflowTimeoutDuration | number - } - export type WorkflowEvent = { - payload: Readonly - timestamp: Date - instanceId: string - } - export type WorkflowStepEvent = { - payload: Readonly - timestamp: Date - type: string - } - export abstract class WorkflowStep { - do>( - name: string, - callback: () => Promise, - ): Promise - do>( - name: string, - config: WorkflowStepConfig, - callback: () => Promise, - ): Promise - sleep: (name: string, duration: WorkflowSleepDuration) => Promise - sleepUntil: (name: string, timestamp: Date | number) => Promise - waitForEvent>( - name: string, - options: { - type: string - timeout?: WorkflowTimeoutDuration | number - }, - ): Promise> - } - export abstract class WorkflowEntrypoint< - Env = unknown, - T extends Rpc.Serializable | unknown = unknown, - > implements Rpc.WorkflowEntrypointBranded - { - [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never - protected ctx: ExecutionContext - protected env: Env - constructor(ctx: ExecutionContext, env: Env) - run(event: Readonly>, step: WorkflowStep): Promise - } - export function waitUntil(promise: Promise): void - export const env: Cloudflare.Env + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint implements Rpc.WorkerEntrypointBranded { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + email?(message: ForwardableEmailMessage): void | Promise; + fetch?(request: Request): Response | Promise; + queue?(batch: MessageBatch): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + tail?(events: TraceItem[]): void | Promise; + tailStream?(event: TailStream.TailEvent): TailStream.TailEventHandlerType | Promise; + test?(controller: TestController): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + } + export abstract class DurableObject implements Rpc.DurableObjectBranded { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; + fetch?(request: Request): Response | Promise; + webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; + webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } + export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; + export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; + export type WorkflowDelayDuration = WorkflowSleepDuration; + export type WorkflowTimeoutDuration = WorkflowSleepDuration; + export type WorkflowRetentionDuration = WorkflowSleepDuration; + export type WorkflowBackoff = 'constant' | 'linear' | 'exponential'; + export type WorkflowStepConfig = { + retries?: { + limit: number; + delay: WorkflowDelayDuration | number; + backoff?: WorkflowBackoff; + }; + timeout?: WorkflowTimeoutDuration | number; + }; + export type WorkflowEvent = { + payload: Readonly; + timestamp: Date; + instanceId: string; + }; + export type WorkflowStepEvent = { + payload: Readonly; + timestamp: Date; + type: string; + }; + export type WorkflowStepContext = { + attempt: number; + }; + export abstract class WorkflowStep { + do>(name: string, callback: (ctx: WorkflowStepContext) => Promise): Promise; + do>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise): Promise; + sleep: (name: string, duration: WorkflowSleepDuration) => Promise; + sleepUntil: (name: string, timestamp: Date | number) => Promise; + waitForEvent>(name: string, options: { + type: string; + timeout?: WorkflowTimeoutDuration | number; + }): Promise>; + } + export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown'; + export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { + [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + run(event: Readonly>, step: WorkflowStep): Promise; + } + export function waitUntil(promise: Promise): void; + export function withEnv(newEnv: unknown, fn: () => unknown): unknown; + export function withExports(newExports: unknown, fn: () => unknown): unknown; + export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown; + export const env: Cloudflare.Env; + export const exports: Cloudflare.Exports; } declare module 'cloudflare:workers' { - export = CloudflareWorkersModule + export = CloudflareWorkersModule; } interface SecretsStoreSecret { - /** - * Get a secret from the Secrets Store, returning a string of the secret value - * if it exists, or throws an error if it does not exist - */ - get(): Promise + /** + * Get a secret from the Secrets Store, returning a string of the secret value + * if it exists, or throws an error if it does not exist + */ + get(): Promise; } -declare module 'cloudflare:sockets' { - function _connect( - address: string | SocketAddress, - options?: SocketOptions, - ): Socket - export { _connect as connect } +declare module "cloudflare:sockets" { + function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; + export { _connect as connect }; +} +/** + * Binding entrypoint for Cloudflare Stream. + * + * Usage: + * - Binding-level operations: + * `await env.STREAM.videos.upload` + * `await env.STREAM.videos.createDirectUpload` + * `await env.STREAM.videos.*` + * `await env.STREAM.watermarks.*` + * - Per-video operations: + * `await env.STREAM.video(id).downloads.*` + * `await env.STREAM.video(id).captions.*` + * + * Example usage: + * ```ts + * await env.STREAM.video(id).downloads.generate(); + * + * const video = env.STREAM.video(id) + * const captions = video.captions.list(); + * const videoDetails = video.details() + * ``` + */ +interface StreamBinding { + /** + * Returns a handle scoped to a single video for per-video operations. + * @param id The unique identifier for the video. + * @returns A handle for per-video operations. + */ + video(id: string): StreamVideoHandle; + /** + * Uploads a new video from a File. + * @param file The video file to upload. + * @returns The uploaded video details. + * @throws {BadRequestError} if the upload parameter is invalid + * @throws {QuotaReachedError} if the account storage capacity is exceeded + * @throws {MaxFileSizeError} if the file size is too large + * @throws {RateLimitedError} if the server received too many requests + * @throws {InternalError} if an unexpected error occurs + */ + upload(file: File): Promise; + /** + * Uploads a new video from a provided URL. + * @param url The URL to upload from. + * @param params Optional upload parameters. + * @returns The uploaded video details. + * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid + * @throws {QuotaReachedError} if the account storage capacity is exceeded + * @throws {MaxFileSizeError} if the file size is too large + * @throws {RateLimitedError} if the server received too many requests + * @throws {AlreadyUploadedError} if a video was already uploaded to this URL + * @throws {InternalError} if an unexpected error occurs + */ + upload(url: string, params?: StreamUrlUploadParams): Promise; + /** + * Creates a direct upload that allows video uploads without an API key. + * @param params Parameters for the direct upload + * @returns The direct upload details. + * @throws {BadRequestError} if the parameters are invalid + * @throws {RateLimitedError} if the server received too many requests + * @throws {InternalError} if an unexpected error occurs + */ + createDirectUpload(params: StreamDirectUploadCreateParams): Promise; + videos: StreamVideos; + watermarks: StreamWatermarks; +} +/** + * Handle for operations scoped to a single Stream video. + */ +interface StreamVideoHandle { + /** + * The unique identifier for the video. + */ + id: string; + /** + * Get a full videos details + * @returns The full video details. + * @throws {NotFoundError} if the video is not found + * @throws {InternalError} if an unexpected error occurs + */ + details(): Promise; + /** + * Update details for a single video. + * @param params The fields to update for the video. + * @returns The updated video details. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the parameters are invalid + * @throws {InternalError} if an unexpected error occurs + */ + update(params: StreamUpdateVideoParams): Promise; + /** + * Deletes a video and its copies from Cloudflare Stream. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(): Promise; + /** + * Creates a signed URL token for a video. + * @returns The signed token that was created. + * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed + */ + generateToken(): Promise; + downloads: StreamScopedDownloads; + captions: StreamScopedCaptions; +} +interface StreamVideo { + /** + * The unique identifier for the video. + */ + id: string; + /** + * A user-defined identifier for the media creator. + */ + creator: string | null; + /** + * The thumbnail URL for the video. + */ + thumbnail: string; + /** + * The thumbnail timestamp percentage. + */ + thumbnailTimestampPct: number; + /** + * Indicates whether the video is ready to stream. + */ + readyToStream: boolean; + /** + * The date and time the video became ready to stream. + */ + readyToStreamAt: string | null; + /** + * Processing status information. + */ + status: StreamVideoStatus; + /** + * A user modifiable key-value store. + */ + meta: Record; + /** + * The date and time the video was created. + */ + created: string; + /** + * The date and time the video was last modified. + */ + modified: string; + /** + * The date and time at which the video will be deleted. + */ + scheduledDeletion: string | null; + /** + * The size of the video in bytes. + */ + size: number; + /** + * The preview URL for the video. + */ + preview?: string; + /** + * Origins allowed to display the video. + */ + allowedOrigins: Array; + /** + * Indicates whether signed URLs are required. + */ + requireSignedURLs: boolean | null; + /** + * The date and time the video was uploaded. + */ + uploaded: string | null; + /** + * The date and time when the upload URL expires. + */ + uploadExpiry: string | null; + /** + * The maximum size in bytes for direct uploads. + */ + maxSizeBytes: number | null; + /** + * The maximum duration in seconds for direct uploads. + */ + maxDurationSeconds: number | null; + /** + * The video duration in seconds. -1 indicates unknown. + */ + duration: number; + /** + * Input metadata for the original upload. + */ + input: StreamVideoInput; + /** + * Playback URLs for the video. + */ + hlsPlaybackUrl: string; + dashPlaybackUrl: string; + /** + * The watermark applied to the video, if any. + */ + watermark: StreamWatermark | null; + /** + * The live input id associated with the video, if any. + */ + liveInputId?: string | null; + /** + * The source video id if this is a clip. + */ + clippedFromId: string | null; + /** + * Public details associated with the video. + */ + publicDetails: StreamPublicDetails | null; +} +type StreamVideoStatus = { + /** + * The current processing state. + */ + state: string; + /** + * The current processing step. + */ + step?: string; + /** + * The percent complete as a string. + */ + pctComplete?: string; + /** + * An error reason code, if applicable. + */ + errorReasonCode: string; + /** + * An error reason text, if applicable. + */ + errorReasonText: string; +}; +type StreamVideoInput = { + /** + * The input width in pixels. + */ + width: number; + /** + * The input height in pixels. + */ + height: number; +}; +type StreamPublicDetails = { + /** + * The public title for the video. + */ + title: string | null; + /** + * The public share link. + */ + share_link: string | null; + /** + * The public channel link. + */ + channel_link: string | null; + /** + * The public logo URL. + */ + logo: string | null; +}; +type StreamDirectUpload = { + /** + * The URL an unauthenticated upload can use for a single multipart request. + */ + uploadURL: string; + /** + * A Cloudflare-generated unique identifier for a media item. + */ + id: string; + /** + * The watermark profile applied to the upload. + */ + watermark: StreamWatermark | null; + /** + * The scheduled deletion time, if any. + */ + scheduledDeletion: string | null; +}; +type StreamDirectUploadCreateParams = { + /** + * The maximum duration in seconds for a video upload. + */ + maxDurationSeconds: number; + /** + * The date and time after upload when videos will not be accepted. + */ + expiry?: string; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * A user modifiable key-value store used to reference other systems of record for + * managing videos. + */ + meta?: Record; + /** + * Lists the origins allowed to display the video. + */ + allowedOrigins?: Array; + /** + * Indicates whether the video can be accessed using the id. When set to `true`, + * a signed token must be generated with a signing key to view the video. + */ + requireSignedURLs?: boolean; + /** + * The thumbnail timestamp percentage. + */ + thumbnailTimestampPct?: number; + /** + * The date and time at which the video will be deleted. Include `null` to remove + * a scheduled deletion. + */ + scheduledDeletion?: string | null; + /** + * The watermark profile to apply. + */ + watermark?: StreamDirectUploadWatermark; +}; +type StreamDirectUploadWatermark = { + /** + * The unique identifier for the watermark profile. + */ + id: string; +}; +type StreamUrlUploadParams = { + /** + * Lists the origins allowed to display the video. Enter allowed origin + * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the + * video to be viewed on any origin. + */ + allowedOrigins?: Array; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * A user modifiable key-value store used to reference other systems of + * record for managing videos. + */ + meta?: Record; + /** + * Indicates whether the video can be a accessed using the id. When + * set to `true`, a signed token must be generated with a signing key to view the + * video. + */ + requireSignedURLs?: boolean; + /** + * Indicates the date and time at which the video will be deleted. Omit + * the field to indicate no change, or include with a `null` value to remove an + * existing scheduled deletion. If specified, must be at least 30 days from upload + * time. + */ + scheduledDeletion?: string | null; + /** + * The timestamp for a thumbnail image calculated as a percentage value + * of the video's duration. To convert from a second-wise timestamp to a + * percentage, divide the desired timestamp by the total duration of the video. If + * this value is not set, the default thumbnail image is taken from 0s of the + * video. + */ + thumbnailTimestampPct?: number; + /** + * The identifier for the watermark profile + */ + watermarkId?: string; +}; +interface StreamScopedCaptions { + /** + * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language. + * One caption or subtitle file per language is allowed. + * @param language The BCP 47 language tag for the caption or subtitle. + * @param file The caption or subtitle file to upload. + * @returns The created caption entry. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the language or file is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {InternalError} if an unexpected error occurs + */ + upload(language: string, file: File): Promise; + /** + * Generate captions or subtitles for the provided language via AI. + * @param language The BCP 47 language tag to generate. + * @returns The generated caption entry. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the language is invalid + * @throws {StreamError} if a generated caption already exists + * @throws {StreamError} if the video duration is too long + * @throws {StreamError} if the video is missing audio + * @throws {StreamError} if the requested language is not supported + * @throws {InternalError} if an unexpected error occurs + */ + generate(language: string): Promise; + /** + * Lists the captions or subtitles. + * Use the language parameter to filter by a specific language. + * @param language The optional BCP 47 language tag to filter by. + * @returns The list of captions or subtitles. + * @throws {NotFoundError} if the video or caption is not found + * @throws {InternalError} if an unexpected error occurs + */ + list(language?: string): Promise; + /** + * Removes the captions or subtitles from a video. + * @param language The BCP 47 language tag to remove. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video or caption is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(language: string): Promise; +} +interface StreamScopedDownloads { + /** + * Generates a download for a video when a video is ready to view. Available + * types are `default` and `audio`. Defaults to `default` when omitted. + * @param downloadType The download type to create. + * @returns The current downloads for the video. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the download type is invalid + * @throws {StreamError} if the video duration is too long to generate a download + * @throws {StreamError} if the video is not ready to stream + * @throws {InternalError} if an unexpected error occurs + */ + generate(downloadType?: StreamDownloadType): Promise; + /** + * Lists the downloads created for a video. + * @returns The current downloads for the video. + * @throws {NotFoundError} if the video or downloads are not found + * @throws {InternalError} if an unexpected error occurs + */ + get(): Promise; + /** + * Delete the downloads for a video. Available types are `default` and `audio`. + * Defaults to `default` when omitted. + * @param downloadType The download type to delete. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video or downloads are not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(downloadType?: StreamDownloadType): Promise; +} +interface StreamVideos { + /** + * Lists all videos in a users account. + * @returns The list of videos. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InternalError} if an unexpected error occurs + */ + list(params?: StreamVideosListParams): Promise; +} +interface StreamWatermarks { + /** + * Generate a new watermark profile + * @param file The image file to upload + * @param params The watermark creation parameters. + * @returns The created watermark profile. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InvalidURLError} if the URL is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached + * @throws {InternalError} if an unexpected error occurs + */ + generate(file: File, params: StreamWatermarkCreateParams): Promise; + /** + * Generate a new watermark profile + * @param url The image url to upload + * @param params The watermark creation parameters. + * @returns The created watermark profile. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InvalidURLError} if the URL is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached + * @throws {InternalError} if an unexpected error occurs + */ + generate(url: string, params: StreamWatermarkCreateParams): Promise; + /** + * Lists all watermark profiles for an account. + * @returns The list of watermark profiles. + * @throws {InternalError} if an unexpected error occurs + */ + list(): Promise; + /** + * Retrieves details for a single watermark profile. + * @param watermarkId The watermark profile identifier. + * @returns The watermark profile details. + * @throws {NotFoundError} if the watermark is not found + * @throws {InternalError} if an unexpected error occurs + */ + get(watermarkId: string): Promise; + /** + * Deletes a watermark profile. + * @param watermarkId The watermark profile identifier. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the watermark is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(watermarkId: string): Promise; +} +type StreamUpdateVideoParams = { + /** + * Lists the origins allowed to display the video. Enter allowed origin + * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the + * video to be viewed on any origin. + */ + allowedOrigins?: Array; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * The maximum duration in seconds for a video upload. Can be set for a + * video that is not yet uploaded to limit its duration. Uploads that exceed the + * specified duration will fail during processing. A value of `-1` means the value + * is unknown. + */ + maxDurationSeconds?: number; + /** + * A user modifiable key-value store used to reference other systems of + * record for managing videos. + */ + meta?: Record; + /** + * Indicates whether the video can be a accessed using the id. When + * set to `true`, a signed token must be generated with a signing key to view the + * video. + */ + requireSignedURLs?: boolean; + /** + * Indicates the date and time at which the video will be deleted. Omit + * the field to indicate no change, or include with a `null` value to remove an + * existing scheduled deletion. If specified, must be at least 30 days from upload + * time. + */ + scheduledDeletion?: string | null; + /** + * The timestamp for a thumbnail image calculated as a percentage value + * of the video's duration. To convert from a second-wise timestamp to a + * percentage, divide the desired timestamp by the total duration of the video. If + * this value is not set, the default thumbnail image is taken from 0s of the + * video. + */ + thumbnailTimestampPct?: number; +}; +type StreamCaption = { + /** + * Whether the caption was generated via AI. + */ + generated?: boolean; + /** + * The language label displayed in the native language to users. + */ + label: string; + /** + * The language tag in BCP 47 format. + */ + language: string; + /** + * The status of a generated caption. + */ + status?: 'ready' | 'inprogress' | 'error'; +}; +type StreamDownloadStatus = 'ready' | 'inprogress' | 'error'; +type StreamDownloadType = 'default' | 'audio'; +type StreamDownload = { + /** + * Indicates the progress as a percentage between 0 and 100. + */ + percentComplete: number; + /** + * The status of a generated download. + */ + status: StreamDownloadStatus; + /** + * The URL to access the generated download. + */ + url?: string; +}; +/** + * An object with download type keys. Each key is optional and only present if that + * download type has been created. + */ +type StreamDownloadGetResponse = { + /** + * The audio-only download. Only present if this download type has been created. + */ + audio?: StreamDownload; + /** + * The default video download. Only present if this download type has been created. + */ + default?: StreamDownload; +}; +type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center'; +type StreamWatermark = { + /** + * The unique identifier for a watermark profile. + */ + id: string; + /** + * The size of the image in bytes. + */ + size: number; + /** + * The height of the image in pixels. + */ + height: number; + /** + * The width of the image in pixels. + */ + width: number; + /** + * The date and a time a watermark profile was created. + */ + created: string; + /** + * The source URL for a downloaded image. If the watermark profile was created via + * direct upload, this field is null. + */ + downloadedFrom: string | null; + /** + * A short description of the watermark profile. + */ + name: string; + /** + * The translucency of the image. A value of `0.0` makes the image completely + * transparent, and `1.0` makes the image completely opaque. Note that if the image + * is already semi-transparent, setting this to `1.0` will not make the image + * completely opaque. + */ + opacity: number; + /** + * The whitespace between the adjacent edges (determined by position) of the video + * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded + * video width or length, as determined by the algorithm. + */ + padding: number; + /** + * The size of the image relative to the overall size of the video. This parameter + * will adapt to horizontal and vertical videos automatically. `0.0` indicates no + * scaling (use the size of the image as-is), and `1.0 `fills the entire video. + */ + scale: number; + /** + * The location of the image. Valid positions are: `upperRight`, `upperLeft`, + * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the + * `padding` parameter. + */ + position: StreamWatermarkPosition; +}; +type StreamWatermarkCreateParams = { + /** + * A short description of the watermark profile. + */ + name?: string; + /** + * The translucency of the image. A value of `0.0` makes the image completely + * transparent, and `1.0` makes the image completely opaque. Note that if the + * image is already semi-transparent, setting this to `1.0` will not make the + * image completely opaque. + */ + opacity?: number; + /** + * The whitespace between the adjacent edges (determined by position) of the + * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully + * padded video width or length, as determined by the algorithm. + */ + padding?: number; + /** + * The size of the image relative to the overall size of the video. This + * parameter will adapt to horizontal and vertical videos automatically. `0.0` + * indicates no scaling (use the size of the image as-is), and `1.0 `fills the + * entire video. + */ + scale?: number; + /** + * The location of the image. + */ + position?: StreamWatermarkPosition; +}; +type StreamVideosListParams = { + /** + * The maximum number of videos to return. + */ + limit?: number; + /** + * Return videos created before this timestamp. + * (RFC3339/RFC3339Nano) + */ + before?: string; + /** + * Comparison operator for the `before` field. + * @default 'lt' + */ + beforeComp?: StreamPaginationComparison; + /** + * Return videos created after this timestamp. + * (RFC3339/RFC3339Nano) + */ + after?: string; + /** + * Comparison operator for the `after` field. + * @default 'gte' + */ + afterComp?: StreamPaginationComparison; +}; +type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte'; +/** + * Error object for Stream binding operations. + */ +interface StreamError extends Error { + readonly code: number; + readonly statusCode: number; + readonly message: string; + readonly stack?: string; +} +interface InternalError extends StreamError { + name: 'InternalError'; +} +interface BadRequestError extends StreamError { + name: 'BadRequestError'; +} +interface NotFoundError extends StreamError { + name: 'NotFoundError'; +} +interface ForbiddenError extends StreamError { + name: 'ForbiddenError'; +} +interface RateLimitedError extends StreamError { + name: 'RateLimitedError'; +} +interface QuotaReachedError extends StreamError { + name: 'QuotaReachedError'; +} +interface MaxFileSizeError extends StreamError { + name: 'MaxFileSizeError'; +} +interface InvalidURLError extends StreamError { + name: 'InvalidURLError'; +} +interface AlreadyUploadedError extends StreamError { + name: 'AlreadyUploadedError'; +} +interface TooManyWatermarksError extends StreamError { + name: 'TooManyWatermarksError'; } type MarkdownDocument = { - name: string - blob: Blob -} -type ConversionResponse = - | { - name: string - mimeType: string - format: 'markdown' - tokens: number - data: string - } - | { - name: string - mimeType: string - format: 'error' - error: string - } + name: string; + blob: Blob; +}; +type ConversionResponse = { + id: string; + name: string; + mimeType: string; + format: 'markdown'; + tokens: number; + data: string; +} | { + id: string; + name: string; + mimeType: string; + format: 'error'; + error: string; +}; type ImageConversionOptions = { - descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de' -} + descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de'; +}; type EmbeddedImageConversionOptions = ImageConversionOptions & { - convert?: boolean - maxConvertedImages?: number -} + convert?: boolean; + maxConvertedImages?: number; +}; type ConversionOptions = { - html?: { - images?: EmbeddedImageConversionOptions & { - convertOGImage?: boolean - } - } - docx?: { - images?: EmbeddedImageConversionOptions - } - image?: ImageConversionOptions - pdf?: { - images?: EmbeddedImageConversionOptions - metadata?: boolean - } -} + html?: { + images?: EmbeddedImageConversionOptions & { + convertOGImage?: boolean; + }; + hostname?: string; + cssSelector?: string; + }; + docx?: { + images?: EmbeddedImageConversionOptions; + }; + image?: ImageConversionOptions; + pdf?: { + images?: EmbeddedImageConversionOptions; + metadata?: boolean; + }; +}; type ConversionRequestOptions = { - gateway?: GatewayOptions - extraHeaders?: object - conversionOptions?: ConversionOptions -} + gateway?: GatewayOptions; + extraHeaders?: object; + conversionOptions?: ConversionOptions; +}; type SupportedFileFormat = { - mimeType: string - extension: string -} + mimeType: string; + extension: string; +}; declare abstract class ToMarkdownService { - transform( - files: MarkdownDocument[], - options?: ConversionRequestOptions, - ): Promise - transform( - files: MarkdownDocument, - options?: ConversionRequestOptions, - ): Promise - supported(): Promise + transform(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; + transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; + supported(): Promise; } declare namespace TailStream { - interface Header { - readonly name: string - readonly value: string - } - interface FetchEventInfo { - readonly type: 'fetch' - readonly method: string - readonly url: string - readonly cfJson?: object - readonly headers: Header[] - } - interface JsRpcEventInfo { - readonly type: 'jsrpc' - } - interface ScheduledEventInfo { - readonly type: 'scheduled' - readonly scheduledTime: Date - readonly cron: string - } - interface AlarmEventInfo { - readonly type: 'alarm' - readonly scheduledTime: Date - } - interface QueueEventInfo { - readonly type: 'queue' - readonly queueName: string - readonly batchSize: number - } - interface EmailEventInfo { - readonly type: 'email' - readonly mailFrom: string - readonly rcptTo: string - readonly rawSize: number - } - interface TraceEventInfo { - readonly type: 'trace' - readonly traces: (string | null)[] - } - interface HibernatableWebSocketEventInfoMessage { - readonly type: 'message' - } - interface HibernatableWebSocketEventInfoError { - readonly type: 'error' - } - interface HibernatableWebSocketEventInfoClose { - readonly type: 'close' - readonly code: number - readonly wasClean: boolean - } - interface HibernatableWebSocketEventInfo { - readonly type: 'hibernatableWebSocket' - readonly info: - | HibernatableWebSocketEventInfoClose - | HibernatableWebSocketEventInfoError - | HibernatableWebSocketEventInfoMessage - } - interface CustomEventInfo { - readonly type: 'custom' - } - interface FetchResponseInfo { - readonly type: 'fetch' - readonly statusCode: number - } - type EventOutcome = - | 'ok' - | 'canceled' - | 'exception' - | 'unknown' - | 'killSwitch' - | 'daemonDown' - | 'exceededCpu' - | 'exceededMemory' - | 'loadShed' - | 'responseStreamDisconnected' - | 'scriptNotFound' - interface ScriptVersion { - readonly id: string - readonly tag?: string - readonly message?: string - } - interface Onset { - readonly type: 'onset' - readonly attributes: Attribute[] - // id for the span being opened by this Onset event. - readonly spanId: string - readonly dispatchNamespace?: string - readonly entrypoint?: string - readonly executionModel: string - readonly scriptName?: string - readonly scriptTags?: string[] - readonly scriptVersion?: ScriptVersion - readonly info: - | FetchEventInfo - | JsRpcEventInfo - | ScheduledEventInfo - | AlarmEventInfo - | QueueEventInfo - | EmailEventInfo - | TraceEventInfo - | HibernatableWebSocketEventInfo - | CustomEventInfo - } - interface Outcome { - readonly type: 'outcome' - readonly outcome: EventOutcome - readonly cpuTime: number - readonly wallTime: number - } - interface SpanOpen { - readonly type: 'spanOpen' - readonly name: string - // id for the span being opened by this SpanOpen event. - readonly spanId: string - readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes - } - interface SpanClose { - readonly type: 'spanClose' - readonly outcome: EventOutcome - } - interface DiagnosticChannelEvent { - readonly type: 'diagnosticChannel' - readonly channel: string - readonly message: any - } - interface Exception { - readonly type: 'exception' - readonly name: string - readonly message: string - readonly stack?: string - } - interface Log { - readonly type: 'log' - readonly level: 'debug' | 'error' | 'info' | 'log' | 'warn' - readonly message: object - } - // This marks the worker handler return information. - // This is separate from Outcome because the worker invocation can live for a long time after - // returning. For example - Websockets that return an http upgrade response but then continue - // streaming information or SSE http connections. - interface Return { - readonly type: 'return' - readonly info?: FetchResponseInfo - } - interface Attribute { - readonly name: string - readonly value: - | string - | string[] - | boolean - | boolean[] - | number - | number[] - | bigint - | bigint[] - } - interface Attributes { - readonly type: 'attributes' - readonly info: Attribute[] - } - type EventType = - | Onset - | Outcome - | SpanOpen - | SpanClose - | DiagnosticChannelEvent - | Exception - | Log - | Return - | Attributes - // Context in which this trace event lives. - interface SpanContext { - // Single id for the entire top-level invocation - // This should be a new traceId for the first worker stage invoked in the eyeball request and then - // same-account service-bindings should reuse the same traceId but cross-account service-bindings - // should use a new traceId. - readonly traceId: string - // spanId in which this event is handled - // for Onset and SpanOpen events this would be the parent span id - // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events - // For Hibernate and Mark this would be the span under which they were emitted. - // spanId is not set ONLY if: - // 1. This is an Onset event - // 2. We are not inherting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) - readonly spanId?: string - } - interface TailEvent { - // invocation id of the currently invoked worker stage. - // invocation id will always be unique to every Onset event and will be the same until the Outcome event. - readonly invocationId: string - // Inherited spanContext for this event. - readonly spanContext: SpanContext - readonly timestamp: Date - readonly sequence: number - readonly event: Event - } - type TailEventHandler = ( - event: TailEvent, - ) => void | Promise - type TailEventHandlerObject = { - outcome?: TailEventHandler - spanOpen?: TailEventHandler - spanClose?: TailEventHandler - diagnosticChannel?: TailEventHandler - exception?: TailEventHandler - log?: TailEventHandler - return?: TailEventHandler - attributes?: TailEventHandler - } - type TailEventHandlerType = TailEventHandler | TailEventHandlerObject + interface Header { + readonly name: string; + readonly value: string; + } + interface FetchEventInfo { + readonly type: "fetch"; + readonly method: string; + readonly url: string; + readonly cfJson?: object; + readonly headers: Header[]; + } + interface JsRpcEventInfo { + readonly type: "jsrpc"; + } + interface ScheduledEventInfo { + readonly type: "scheduled"; + readonly scheduledTime: Date; + readonly cron: string; + } + interface AlarmEventInfo { + readonly type: "alarm"; + readonly scheduledTime: Date; + } + interface QueueEventInfo { + readonly type: "queue"; + readonly queueName: string; + readonly batchSize: number; + } + interface EmailEventInfo { + readonly type: "email"; + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; + } + interface TraceEventInfo { + readonly type: "trace"; + readonly traces: (string | null)[]; + } + interface HibernatableWebSocketEventInfoMessage { + readonly type: "message"; + } + interface HibernatableWebSocketEventInfoError { + readonly type: "error"; + } + interface HibernatableWebSocketEventInfoClose { + readonly type: "close"; + readonly code: number; + readonly wasClean: boolean; + } + interface HibernatableWebSocketEventInfo { + readonly type: "hibernatableWebSocket"; + readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage; + } + interface CustomEventInfo { + readonly type: "custom"; + } + interface FetchResponseInfo { + readonly type: "fetch"; + readonly statusCode: number; + } + type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound"; + interface ScriptVersion { + readonly id: string; + readonly tag?: string; + readonly message?: string; + } + interface Onset { + readonly type: "onset"; + readonly attributes: Attribute[]; + // id for the span being opened by this Onset event. + readonly spanId: string; + readonly dispatchNamespace?: string; + readonly entrypoint?: string; + readonly executionModel: string; + readonly scriptName?: string; + readonly scriptTags?: string[]; + readonly scriptVersion?: ScriptVersion; + readonly info: FetchEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo; + } + interface Outcome { + readonly type: "outcome"; + readonly outcome: EventOutcome; + readonly cpuTime: number; + readonly wallTime: number; + } + interface SpanOpen { + readonly type: "spanOpen"; + readonly name: string; + // id for the span being opened by this SpanOpen event. + readonly spanId: string; + readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes; + } + interface SpanClose { + readonly type: "spanClose"; + readonly outcome: EventOutcome; + } + interface DiagnosticChannelEvent { + readonly type: "diagnosticChannel"; + readonly channel: string; + readonly message: any; + } + interface Exception { + readonly type: "exception"; + readonly name: string; + readonly message: string; + readonly stack?: string; + } + interface Log { + readonly type: "log"; + readonly level: "debug" | "error" | "info" | "log" | "warn"; + readonly message: object; + } + interface DroppedEventsDiagnostic { + readonly diagnosticsType: "droppedEvents"; + readonly count: number; + } + interface StreamDiagnostic { + readonly type: 'streamDiagnostic'; + // To add new diagnostic types, define a new interface and add it to this union type. + readonly diagnostic: DroppedEventsDiagnostic; + } + // This marks the worker handler return information. + // This is separate from Outcome because the worker invocation can live for a long time after + // returning. For example - Websockets that return an http upgrade response but then continue + // streaming information or SSE http connections. + interface Return { + readonly type: "return"; + readonly info?: FetchResponseInfo; + } + interface Attribute { + readonly name: string; + readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[]; + } + interface Attributes { + readonly type: "attributes"; + readonly info: Attribute[]; + } + type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes; + // Context in which this trace event lives. + interface SpanContext { + // Single id for the entire top-level invocation + // This should be a new traceId for the first worker stage invoked in the eyeball request and then + // same-account service-bindings should reuse the same traceId but cross-account service-bindings + // should use a new traceId. + readonly traceId: string; + // spanId in which this event is handled + // for Onset and SpanOpen events this would be the parent span id + // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events + // For Hibernate and Mark this would be the span under which they were emitted. + // spanId is not set ONLY if: + // 1. This is an Onset event + // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) + readonly spanId?: string; + } + interface TailEvent { + // invocation id of the currently invoked worker stage. + // invocation id will always be unique to every Onset event and will be the same until the Outcome event. + readonly invocationId: string; + // Inherited spanContext for this event. + readonly spanContext: SpanContext; + readonly timestamp: Date; + readonly sequence: number; + readonly event: Event; + } + type TailEventHandler = (event: TailEvent) => void | Promise; + type TailEventHandlerObject = { + outcome?: TailEventHandler; + spanOpen?: TailEventHandler; + spanClose?: TailEventHandler; + diagnosticChannel?: TailEventHandler; + exception?: TailEventHandler; + log?: TailEventHandler; + return?: TailEventHandler; + attributes?: TailEventHandler; + }; + type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; } // Copyright (c) 2022-2023 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: @@ -9922,56 +11695,38 @@ declare namespace TailStream { /** * Data types supported for holding vector metadata. */ -type VectorizeVectorMetadataValue = string | number | boolean | string[] +type VectorizeVectorMetadataValue = string | number | boolean | string[]; /** * Additional information to associate with a vector. */ -type VectorizeVectorMetadata = - | VectorizeVectorMetadataValue - | Record -type VectorFloatArray = Float32Array | Float64Array +type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record; +type VectorFloatArray = Float32Array | Float64Array; interface VectorizeError { - code?: number - error: string + code?: number; + error: string; } /** * Comparison logic/operation to use for metadata filtering. * * This list is expected to grow as support for more operations are released. */ -type VectorizeVectorMetadataFilterOp = - | '$eq' - | '$ne' - | '$lt' - | '$lte' - | '$gt' - | '$gte' -type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin' +type VectorizeVectorMetadataFilterOp = '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte'; +type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin'; /** * Filter criteria for vector metadata used to limit the retrieved query result set. */ type VectorizeVectorMetadataFilter = { - [field: string]: - | Exclude - | null - | { - [Op in VectorizeVectorMetadataFilterOp]?: Exclude< - VectorizeVectorMetadataValue, - string[] - > | null - } - | { - [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude< - VectorizeVectorMetadataValue, - string[] - >[] - } -} + [field: string]: Exclude | null | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude | null; + } | { + [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude[]; + }; +}; /** * Supported distance metrics for an index. * Distance metrics determine how other "similar" vectors are determined. */ -type VectorizeDistanceMetric = 'euclidean' | 'cosine' | 'dot-product' +type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; /** * Metadata return levels for a Vectorize query. * @@ -9981,25 +11736,23 @@ type VectorizeDistanceMetric = 'euclidean' | 'cosine' | 'dot-product' * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings). * @property none No indexed metadata will be returned. */ -type VectorizeMetadataRetrievalLevel = 'all' | 'indexed' | 'none' +type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none"; interface VectorizeQueryOptions { - topK?: number - namespace?: string - returnValues?: boolean - returnMetadata?: boolean | VectorizeMetadataRetrievalLevel - filter?: VectorizeVectorMetadataFilter + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; + filter?: VectorizeVectorMetadataFilter; } /** * Information about the configuration of an index. */ -type VectorizeIndexConfig = - | { - dimensions: number - metric: VectorizeDistanceMetric - } - | { - preset: string // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity - } +type VectorizeIndexConfig = { + dimensions: number; + metric: VectorizeDistanceMetric; +} | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity +}; /** * Metadata about an existing index. * @@ -10007,57 +11760,56 @@ type VectorizeIndexConfig = * See {@link VectorizeIndexInfo} for its post-beta equivalent. */ interface VectorizeIndexDetails { - /** The unique ID of the index */ - readonly id: string - /** The name of the index. */ - name: string - /** (optional) A human readable description for the index. */ - description?: string - /** The index configuration, including the dimension size and distance metric. */ - config: VectorizeIndexConfig - /** The number of records containing vectors within the index. */ - vectorsCount: number + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; } /** * Metadata about an existing index. */ interface VectorizeIndexInfo { - /** The number of records containing vectors within the index. */ - vectorCount: number - /** Number of dimensions the index has been configured for. */ - dimensions: number - /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ - processedUpToDatetime: number - /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ - processedUpToMutation: number + /** The number of records containing vectors within the index. */ + vectorCount: number; + /** Number of dimensions the index has been configured for. */ + dimensions: number; + /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ + processedUpToDatetime: number; + /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ + processedUpToMutation: number; } /** * Represents a single vector value set along with its associated metadata. */ interface VectorizeVector { - /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ - id: string - /** The vector values */ - values: VectorFloatArray | number[] - /** The namespace this vector belongs to. */ - namespace?: string - /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ - metadata?: Record + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ + metadata?: Record; } /** * Represents a matched vector for a query along with its score and (if specified) the matching vector information. */ -type VectorizeMatch = Pick, 'values'> & - Omit & { +type VectorizeMatch = Pick, "values"> & Omit & { /** The score or rank for similarity, when returned as a result */ - score: number - } + score: number; +}; /** * A set of matching {@link VectorizeMatch} for a particular query. */ interface VectorizeMatches { - matches: VectorizeMatch[] - count: number + matches: VectorizeMatch[]; + count: number; } /** * Results of an operation that performed a mutation on a set of vectors. @@ -10067,18 +11819,18 @@ interface VectorizeMatches { * See {@link VectorizeAsyncMutation} for its post-beta equivalent. */ interface VectorizeVectorMutation { - /* List of ids of vectors that were successfully processed. */ - ids: string[] - /* Total count of the number of processed vectors. */ - count: number + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; } /** * Result type indicating a mutation on the Vectorize Index. * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation. */ interface VectorizeAsyncMutation { - /** The unique identifier for the async mutation operation containing the changeset. */ - mutationId: string + /** The unique identifier for the async mutation operation containing the changeset. */ + mutationId: string; } /** * A Vectorize Vector Search Index for querying vectors/embeddings. @@ -10087,45 +11839,42 @@ interface VectorizeAsyncMutation { * See {@link Vectorize} for its new implementation. */ declare abstract class VectorizeIndex { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query( - vector: VectorFloatArray | number[], - options?: VectorizeQueryOptions, - ): Promise - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public insert(vectors: VectorizeVector[]): Promise - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public upsert(vectors: VectorizeVector[]): Promise - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). - */ - public deleteByIds(ids: string[]): Promise - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; } /** * A Vectorize Vector Search Index for querying vectors/embeddings. @@ -10133,218 +11882,190 @@ declare abstract class VectorizeIndex { * Mutations in this version are async, returning a mutation id. */ declare abstract class Vectorize { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query( - vector: VectorFloatArray | number[], - options?: VectorizeQueryOptions, - ): Promise - /** - * Use the provided vector-id to perform a similarity search across the index. - * @param vectorId Id for a vector in the index against which the index should be queried. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public queryById( - vectorId: string, - options?: VectorizeQueryOptions, - ): Promise - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. - */ - public insert(vectors: VectorizeVector[]): Promise - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. - */ - public upsert(vectors: VectorizeVector[]): Promise - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. - */ - public deleteByIds(ids: string[]): Promise - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; + /** + * Use the provided vector-id to perform a similarity search across the index. + * @param vectorId Id for a vector in the index against which the index should be queried. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; } /** * The interface for "version_metadata" binding * providing metadata about the Worker Version using this binding. */ type WorkerVersionMetadata = { - /** The ID of the Worker Version using this binding */ - id: string - /** The tag of the Worker Version using this binding */ - tag: string - /** The timestamp of when the Worker Version was uploaded */ - timestamp: string -} + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; + /** The timestamp of when the Worker Version was uploaded */ + timestamp: string; +}; interface DynamicDispatchLimits { - /** - * Limit CPU time in milliseconds. - */ - cpuMs?: number - /** - * Limit number of subrequests. - */ - subRequests?: number + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; } interface DynamicDispatchOptions { - /** - * Limit resources of invoked Worker script. - */ - limits?: DynamicDispatchLimits - /** - * Arguments for outbound Worker script, if configured. - */ - outbound?: { - [key: string]: any - } + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; } interface DispatchNamespace { - /** - * @param name Name of the Worker script. - * @param args Arguments to Worker script. - * @param options Options for Dynamic Dispatch invocation. - * @returns A Fetcher object that allows you to send requests to the Worker script. - * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. - */ - get( - name: string, - args?: { - [key: string]: any - }, - options?: DynamicDispatchOptions, - ): Fetcher + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get(name: string, args?: { + [key: string]: any; + }, options?: DynamicDispatchOptions): Fetcher; } declare module 'cloudflare:workflows' { - /** - * NonRetryableError allows for a user to throw a fatal error - * that makes a Workflow instance fail immediately without triggering a retry - */ - export class NonRetryableError extends Error { - public constructor(message: string, name?: string) - } + /** + * NonRetryableError allows for a user to throw a fatal error + * that makes a Workflow instance fail immediately without triggering a retry + */ + export class NonRetryableError extends Error { + public constructor(message: string, name?: string); + } } declare abstract class Workflow { - /** - * Get a handle to an existing instance of the Workflow. - * @param id Id for the instance of this Workflow - * @returns A promise that resolves with a handle for the Instance - */ - public get(id: string): Promise - /** - * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. - * @param options Options when creating an instance including id and params - * @returns A promise that resolves with a handle for the Instance - */ - public create( - options?: WorkflowInstanceCreateOptions, - ): Promise - /** - * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. - * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. - * @param batch List of Options when creating an instance including name and params - * @returns A promise that resolves with a list of handles for the created instances. - */ - public createBatch( - batch: WorkflowInstanceCreateOptions[], - ): Promise + /** + * Get a handle to an existing instance of the Workflow. + * @param id Id for the instance of this Workflow + * @returns A promise that resolves with a handle for the Instance + */ + public get(id: string): Promise; + /** + * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. + * @param options Options when creating an instance including id and params + * @returns A promise that resolves with a handle for the Instance + */ + public create(options?: WorkflowInstanceCreateOptions): Promise; + /** + * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. + * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. + * @param batch List of Options when creating an instance including name and params + * @returns A promise that resolves with a list of handles for the created instances. + */ + public createBatch(batch: WorkflowInstanceCreateOptions[]): Promise; } -type WorkflowDurationLabel = - | 'second' - | 'minute' - | 'hour' - | 'day' - | 'week' - | 'month' - | 'year' -type WorkflowSleepDuration = - | `${number} ${WorkflowDurationLabel}${'s' | ''}` - | number -type WorkflowRetentionDuration = WorkflowSleepDuration +type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; +type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; +type WorkflowRetentionDuration = WorkflowSleepDuration; interface WorkflowInstanceCreateOptions { - /** - * An id for your Workflow instance. Must be unique within the Workflow. - */ - id?: string - /** - * The event payload the Workflow instance is triggered with - */ - params?: PARAMS - /** - * The retention policy for Workflow instance. - * Defaults to the maximum retention period available for the owner's account. - */ - retention?: { - successRetention?: WorkflowRetentionDuration - errorRetention?: WorkflowRetentionDuration - } + /** + * An id for your Workflow instance. Must be unique within the Workflow. + */ + id?: string; + /** + * The event payload the Workflow instance is triggered with + */ + params?: PARAMS; + /** + * The retention policy for Workflow instance. + * Defaults to the maximum retention period available for the owner's account. + */ + retention?: { + successRetention?: WorkflowRetentionDuration; + errorRetention?: WorkflowRetentionDuration; + }; } type InstanceStatus = { - status: - | 'queued' // means that instance is waiting to be started (see concurrency limits) - | 'running' - | 'paused' - | 'errored' - | 'terminated' // user terminated the instance while it was running - | 'complete' - | 'waiting' // instance is hibernating and waiting for sleep or event to finish - | 'waitingForPause' // instance is finishing the current work to pause - | 'unknown' - error?: string - output?: object -} + status: 'queued' // means that instance is waiting to be started (see concurrency limits) + | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running + | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish + | 'waitingForPause' // instance is finishing the current work to pause + | 'unknown'; + error?: { + name: string; + message: string; + }; + output?: unknown; +}; interface WorkflowError { - code?: number - message: string + code?: number; + message: string; } declare abstract class WorkflowInstance { - public id: string - /** - * Pause the instance. - */ - public pause(): Promise - /** - * Resume the instance. If it is already running, an error will be thrown. - */ - public resume(): Promise - /** - * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. - */ - public terminate(): Promise - /** - * Restart the instance. - */ - public restart(): Promise - /** - * Returns the current status of the instance. - */ - public status(): Promise - /** - * Send an event to this instance. - */ - public sendEvent({ - type, - payload, - }: { - type: string - payload: unknown - }): Promise + public id: string; + /** + * Pause the instance. + */ + public pause(): Promise; + /** + * Resume the instance. If it is already running, an error will be thrown. + */ + public resume(): Promise; + /** + * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. + */ + public terminate(): Promise; + /** + * Restart the instance. + */ + public restart(): Promise; + /** + * Returns the current status of the instance. + */ + public status(): Promise; + /** + * Send an event to this instance. + */ + public sendEvent({ type, payload, }: { + type: string; + payload: unknown; + }): Promise; } diff --git a/e2e/vue-start/basic-tsr-config/.devcontainer/devcontainer.json b/e2e/vue-start/basic-tsr-config/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/basic-tsr-config/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/basic-tsr-config/package.json b/e2e/vue-start/basic-tsr-config/package.json index df5a89b67f..828dce5b2a 100644 --- a/e2e/vue-start/basic-tsr-config/package.json +++ b/e2e/vue-start/basic-tsr-config/package.json @@ -8,22 +8,23 @@ "dev:e2e": "vite dev", "build": "rimraf ./count.txt && vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "vite": "^7.1.7", "vue": "^3.5.25" }, "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "srvx": "^0.9.8", - "typescript": "^5.7.2", - "@vitejs/plugin-vue": "^6.0.3", - "@vitejs/plugin-vue-jsx": "^5.1.2", - "vite-tsconfig-paths": "^5.1.4" + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "vite": "^8.0.14", + "rimraf": "catalog:" } } diff --git a/e2e/vue-start/basic-tsr-config/playwright.config.ts b/e2e/vue-start/basic-tsr-config/playwright.config.ts index f6dd61ba6c..e6b92ce385 100644 --- a/e2e/vue-start/basic-tsr-config/playwright.config.ts +++ b/e2e/vue-start/basic-tsr-config/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx b/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx index feaff21c25..b4b520e8af 100644 --- a/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx +++ b/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import * as fs from 'node:fs' import { createFileRoute, useRouter } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' @@ -12,30 +13,31 @@ const getCount = createServerFn({ }) const updateCount = createServerFn({ method: 'POST' }) - .inputValidator((d: number) => d) + .validator((d: number) => d) .handler(async ({ data }) => { const count = await getCount() await fs.promises.writeFile(filePath, `${count + data}`) }) +const Home = defineComponent({ + setup() { + const router = useRouter() + const state = Route.useLoaderData() + return () => ( + + ) + }, +}) + export const Route = createFileRoute('/')({ component: Home, loader: async () => await getCount(), }) - -function Home() { - const router = useRouter() - const state = Route.useLoaderData() - - return ( - - ) -} diff --git a/e2e/vue-start/basic-tsr-config/tsconfig.json b/e2e/vue-start/basic-tsr-config/tsconfig.json index 010db955bf..e8f3ecf0c9 100644 --- a/e2e/vue-start/basic-tsr-config/tsconfig.json +++ b/e2e/vue-start/basic-tsr-config/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/app/*"] }, diff --git a/e2e/vue-start/basic-tsr-config/vite.config.ts b/e2e/vue-start/basic-tsr-config/vite.config.ts index 9ee2806bfe..3abd7d269c 100644 --- a/e2e/vue-start/basic-tsr-config/vite.config.ts +++ b/e2e/vue-start/basic-tsr-config/vite.config.ts @@ -1,17 +1,14 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' 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 }, server: { port: 3000, }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), tanstackStart({ srcDirectory: './src/app', }), diff --git a/e2e/vue-start/basic-vue-query/.devcontainer/devcontainer.json b/e2e/vue-start/basic-vue-query/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/basic-vue-query/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/basic-vue-query/package.json b/e2e/vue-start/basic-vue-query/package.json index 6bab76cfc3..ab9589376d 100644 --- a/e2e/vue-start/basic-vue-query/package.json +++ b/e2e/vue-start/basic-vue-query/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.92.1", @@ -18,23 +18,22 @@ "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "vite": "^7.1.7", + "redaxios": "catalog:", + "tailwind-merge": "^3.6.0", "vue": "^3.5.25", - "zod": "^4.1.12" + "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@tailwindcss/postcss": "^4.1.15", + "@playwright/test": "^1.61.0", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "postcss": "^8.5.1", - "srvx": "^0.9.8", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "@vitejs/plugin-vue": "^6.0.3", - "@vitejs/plugin-vue-jsx": "^5.1.2", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "srvx": "^1.0.0", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/e2e/vue-start/basic-vue-query/playwright.config.ts b/e2e/vue-start/basic-vue-query/playwright.config.ts index 84636ab0f9..0618b7272a 100644 --- a/e2e/vue-start/basic-vue-query/playwright.config.ts +++ b/e2e/vue-start/basic-vue-query/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` @@ -16,18 +11,18 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', + env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, + }, }, projects: [ diff --git a/e2e/vue-start/basic-vue-query/postcss.config.mjs b/e2e/vue-start/basic-vue-query/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-start/basic-vue-query/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts b/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts index 588ab8b52d..10e8a56450 100644 --- a/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts +++ b/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts @@ -9,37 +9,31 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as UsersRouteImport } from './routes/users' -import { Route as SuspenseTransitionRouteImport } from './routes/suspense-transition' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as SuspenseTransitionRouteImport } from './routes/suspense-transition' +import { Route as UsersRouteImport } from './routes/users' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as TransitionCountQueryRouteImport } from './routes/transition/count/query' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as TransitionCountQueryRouteImport } from './routes/transition/count/query' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ - id: '/suspense-transition', - path: '/suspense-transition', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -47,68 +41,74 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ + id: '/suspense-transition', + path: '/suspense-transition', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const LayoutLayout2Route = LayoutLayout2RouteImport.update({ id: '/_layout-2', getParentRoute: () => LayoutRoute, } as any) -const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ - id: '/transition/count/query', - path: '/transition/count/query', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) +const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ + id: '/transition/count/query', + path: '/transition/count/query', + getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { @@ -231,25 +231,18 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/suspense-transition': { - id: '/suspense-transition' - path: '/suspense-transition' - fullPath: '/suspense-transition' - preLoaderRoute: typeof SuspenseTransitionRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -259,47 +252,33 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/_layout': { - id: '/_layout' + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/suspense-transition': { + id: '/suspense-transition' + path: '/suspense-transition' + fullPath: '/suspense-transition' + preLoaderRoute: typeof SuspenseTransitionRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' path: '' - fullPath: '' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute } '/api/users': { id: '/api/users' @@ -308,33 +287,40 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/transition/count/query': { - id: '/transition/count/query' - path: '/transition/count/query' - fullPath: '/transition/count/query' - preLoaderRoute: typeof TransitionCountQueryRouteImport - parentRoute: typeof rootRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' @@ -343,12 +329,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport + } + '/transition/count/query': { + id: '/transition/count/query' + path: '/transition/count/query' + fullPath: '/transition/count/query' + preLoaderRoute: typeof TransitionCountQueryRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/e2e/vue-start/basic-vue-query/src/routes/api.users.ts b/e2e/vue-start/basic-vue-query/src/routes/api.users.ts index 30be1cc574..f9330a87db 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/api.users.ts +++ b/e2e/vue-start/basic-vue-query/src/routes/api.users.ts @@ -1,13 +1,8 @@ import { createFileRoute } from '@tanstack/vue-router' -import { json } from '@tanstack/vue-start' import axios from 'redaxios' import type { User } from '../utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users')({ server: { @@ -16,7 +11,7 @@ export const Route = createFileRoute('/api/users')({ console.info('Fetching users... @', request.url) const res = await axios.get>(`${queryURL}/users`) const list = res.data.slice(0, 10) - return json( + return Response.json( list.map((u) => ({ id: u.id, name: u.name, email: u.email })), ) }, 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 5f3713e8c8..d138746730 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts +++ b/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts @@ -1,13 +1,8 @@ import { createFileRoute } from '@tanstack/vue-router' -import { json } from '@tanstack/vue-start' import axios from 'redaxios' import type { User } from '../../utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users/$id')({ server: { @@ -16,14 +11,14 @@ export const Route = createFileRoute('/api/users/$id')({ console.info(`Fetching users by id=${params.id}... @`, request.url) try { const res = await axios.get(`${queryURL}/users/` + params.id) - return json({ + return Response.json({ id: res.data.id, name: res.data.name, email: res.data.email, }) } catch (e) { console.error(e) - return json({ error: 'User not found' }, { status: 404 }) + return Response.json({ error: 'User not found' }, { status: 404 }) } }, }, diff --git a/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx b/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx index 5ec224eb2d..fd8deaf291 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx @@ -1,9 +1,10 @@ +import { defineComponent } from 'vue' import { useQuery } from '@tanstack/vue-query' import { ErrorComponent, Link, createFileRoute, - type ErrorComponentProps, + ErrorComponentProps, } from '@tanstack/vue-router' import { postQueryOptions } from '~/utils/posts' @@ -11,27 +12,30 @@ export function PostErrorComponent(props: ErrorComponentProps) { return } -function PostComponent() { - const params = Route.useParams() - const postQuery = useQuery(() => postQueryOptions(params.value.postId)) - - return ( -

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

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

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

{postQuery.data.value?.title}

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

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

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

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

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

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

+
{userQuery.data.value?.email ?? ''}
+
+ ) + }, +}) export const Route = createFileRoute('/users/$userId')({ loader: async ({ context, params: { userId } }) => { diff --git a/e2e/vue-start/basic-vue-query/src/styles/app.css b/e2e/vue-start/basic-vue-query/src/styles/app.css index 3b1c037f8a..7ff6765215 100644 --- a/e2e/vue-start/basic-vue-query/src/styles/app.css +++ b/e2e/vue-start/basic-vue-query/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, 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 7f1f564645..c6b5e70a0b 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/posts.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/posts.tsx @@ -7,6 +7,8 @@ export type PostType = { body: string } +const queryURL = 'https://jsonplaceholder.typicode.com' + export const postsQueryOptions = () => queryOptions({ queryKey: ['posts'], @@ -14,7 +16,7 @@ export const postsQueryOptions = () => console.info('Fetching posts...') await new Promise((r) => setTimeout(r, 500)) return axios - .get>('https://jsonplaceholder.typicode.com/posts') + .get>(`${queryURL}/posts`) .then((r) => r.data.slice(0, 10)) }, }) @@ -27,7 +29,7 @@ export const postQueryOptions = (postId: string) => await new Promise((r) => setTimeout(r, 500)) return axios - .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) + .get(`${queryURL}/posts/${postId}`) .then((r) => r.data) }, }) diff --git a/e2e/vue-start/basic-vue-query/src/utils/users.tsx b/e2e/vue-start/basic-vue-query/src/utils/users.tsx index 29bf08c315..fe7a902fa2 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/users.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/users.tsx @@ -1,4 +1,6 @@ import { queryOptions } from '@tanstack/vue-query' +import { createIsomorphicFn } from '@tanstack/vue-start' +import { getRequestUrl } from '@tanstack/vue-start/server' import axios from 'redaxios' export type User = { @@ -7,17 +9,16 @@ export type User = { email: string } -const PORT = - import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` +const getOrigin = createIsomorphicFn() + .server(() => getRequestUrl().origin) + .client(() => window.location.origin) export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(DEPLOY_URL + '/api/users') + .get>(getOrigin() + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -29,7 +30,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(DEPLOY_URL + '/api/users/' + id) + .get(getOrigin() + '/api/users/' + id) .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch user') diff --git a/e2e/vue-start/basic-vue-query/tests/app.spec.ts b/e2e/vue-start/basic-vue-query/tests/app.spec.ts index ab2469f68d..4ce5c20ef7 100644 --- a/e2e/vue-start/basic-vue-query/tests/app.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test('Navigating to post', async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts b/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts b/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/basic-vue-query/tests/transition.spec.ts b/e2e/vue-start/basic-vue-query/tests/transition.spec.ts index 2c28fc72a2..a0f3bf0964 100644 --- a/e2e/vue-start/basic-vue-query/tests/transition.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/transition.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test('transitions/count/query should keep old values visible during navigation', async ({ page, diff --git a/e2e/vue-start/basic-vue-query/tsconfig.json b/e2e/vue-start/basic-vue-query/tsconfig.json index 8bf3d33789..572d840872 100644 --- a/e2e/vue-start/basic-vue-query/tsconfig.json +++ b/e2e/vue-start/basic-vue-query/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/basic-vue-query/vite.config.ts b/e2e/vue-start/basic-vue-query/vite.config.ts index 79edfc05c2..563e212077 100644 --- a/e2e/vue-start/basic-vue-query/vite.config.ts +++ b/e2e/vue-start/basic-vue-query/vite.config.ts @@ -1,19 +1,13 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - vue(), - vueJsx(), - ], + plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], }) diff --git a/e2e/vue-start/basic/.devcontainer/devcontainer.json b/e2e/vue-start/basic/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/basic/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/basic/.gitignore b/e2e/vue-start/basic/.gitignore index a79d5cf129..b9c2c7e5f6 100644 --- a/e2e/vue-start/basic/.gitignore +++ b/e2e/vue-start/basic/.gitignore @@ -18,3 +18,4 @@ yarn.lock /playwright-report/ /blob-report/ /playwright/.cache/ +/dist-vite-*/ diff --git a/e2e/vue-start/basic/package.json b/e2e/vue-start/basic/package.json index 35b437ca12..2ff8329543 100644 --- a/e2e/vue-start/basic/package.json +++ b/e2e/vue-start/basic/package.json @@ -6,46 +6,73 @@ "scripts": { "dev": "vite dev --port 3000", "dev:e2e": "vite dev", - "build": "vite build && tsc --noEmit", - "build:spa": "MODE=spa vite build && tsc --noEmit", - "build:prerender": "MODE=prerender vite build && tsc --noEmit", + "build": "pnpm build:vite", "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "start:spa": "node server.js", - "test:e2e:startDummyServer": "node -e 'import(\"./tests/setup/global.setup.ts\").then(m => m.default())' &", - "test:e2e:stopDummyServer": "node -e 'import(\"./tests/setup/global.teardown.ts\").then(m => m.default())'", - "test:e2e:spaMode": "rm -rf port*.txt; MODE=spa playwright test --project=chromium", - "test:e2e:ssrMode": "rm -rf port*.txt; playwright test --project=chromium", - "test:e2e:prerender": "rm -rf port*.txt; MODE=prerender playwright test --project=chromium", - "test:e2e:preview": "rm -rf port*.txt; MODE=preview playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:spaMode && pnpm run test:e2e:ssrMode && pnpm run test:e2e:prerender && pnpm run test:e2e:preview" + "start": "node server.js", + "test:e2e:local": "playwright test --project=chromium", + "build:vite": "vite build && tsc --noEmit", + "build:rsbuild": "rsbuild build && tsc --noEmit" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "express": "^5.1.0", + "express": "^5.2.1", "http-proxy-middleware": "^3.0.5", "js-cookie": "^3.0.5", - "redaxios": "^0.5.1", + "redaxios": "catalog:", + "tailwind-merge": "^3.6.0", "vue": "^3.5.16", - "tailwind-merge": "^2.6.0", - "vite": "^7.1.7", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@tailwindcss/postcss": "^4.1.15", + "@playwright/test": "^1.61.0", + "@rsbuild/core": "^2.3.1", + "@rsbuild/plugin-babel": "^1.1.2", + "@rsbuild/plugin-vue": "^1.2.7", + "@rsbuild/plugin-vue-jsx": "^2.0.0", + "@tailwindcss/postcss": "^4.2.2", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/js-cookie": "^3.0.6", "@types/node": "^22.10.2", - "@vitejs/plugin-vue": "^5.2.4", - "@vitejs/plugin-vue-jsx": "^4.1.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "postcss": "^8.5.1", - "srvx": "^0.9.8", - "tailwindcss": "^4.1.15", - "typescript": "^5.7.2", - "vite-tsconfig-paths": "^5.1.4" + "srvx": "^1.0.0", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" + }, + "nx": { + "metadata": { + "playwrightModes": [ + { + "toolchain": "vite", + "mode": "ssr", + "shards": 4 + }, + { + "toolchain": "vite", + "mode": "spa" + }, + { + "toolchain": "vite", + "mode": "prerender", + "env": { + "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" + } + }, + { + "toolchain": "vite", + "mode": "preview" + }, + { + "toolchain": "rsbuild", + "mode": "ssr" + } + ] + } } } diff --git a/e2e/vue-start/basic/playwright.config.ts b/e2e/vue-start/basic/playwright.config.ts index aa29067f46..9322874f3a 100644 --- a/e2e/vue-start/basic/playwright.config.ts +++ b/e2e/vue-start/basic/playwright.config.ts @@ -1,63 +1,37 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import { isSpaMode } from './tests/utils/isSpaMode' -import { isPrerender } from './tests/utils/isPrerender' -import { isPreview } from './tests/utils/isPreview' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - `${packageJson.name}${isSpaMode ? '_spa' : ''}${isPreview ? '_preview' : ''}`, -) -const START_PORT = await getTestServerPort( - `${packageJson.name}${isSpaMode ? '_spa_start' : ''}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const mode = process.env.MODE ?? 'ssr' + +const distDir = process.env.E2E_DIST_DIR ?? 'dist' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` -const spaModeCommand = `pnpm build:spa && pnpm start:spa` -const ssrModeCommand = `pnpm build && pnpm start` -const prerenderModeCommand = `pnpm run test:e2e:startDummyServer && pnpm build:prerender && pnpm run test:e2e:stopDummyServer && pnpm start` -const previewModeCommand = `pnpm build && pnpm preview --port ${PORT}` +const commandByMode = + mode === 'preview' + ? `pnpm preview --host 0.0.0.0 --outDir ${distDir} --port ${PORT}` + : `pnpm start` -const getCommand = () => { - if (isSpaMode) return spaModeCommand - if (isPrerender) return prerenderModeCommand - if (isPreview) return previewModeCommand - return ssrModeCommand -} -console.log('running in spa mode: ', isSpaMode.toString()) -console.log('running in prerender mode: ', isPrerender.toString()) -console.log('running in preview mode: ', isPreview.toString()) -/** - * See https://playwright.dev/docs/test-configuration. - */ export default defineConfig({ testDir: './tests', 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: getCommand(), - url: baseURL, - reuseExistingServer: !process.env.CI, + command: commandByMode, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { - MODE: process.env.MODE || '', - VITE_NODE_ENV: 'test', - VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), - VITE_SERVER_PORT: String(PORT), - START_PORT: String(START_PORT), + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, + MODE: mode, + START_PORT: '0', PORT: String(PORT), + E2E_DIST_DIR: distDir, }, }, diff --git a/e2e/vue-start/basic/rsbuild.config.ts b/e2e/vue-start/basic/rsbuild.config.ts new file mode 100644 index 0000000000..aad3a76e73 --- /dev/null +++ b/e2e/vue-start/basic/rsbuild.config.ts @@ -0,0 +1,29 @@ +import { defineConfig } from '@rsbuild/core' +import { pluginBabel } from '@rsbuild/plugin-babel' +import { pluginVue } from '@rsbuild/plugin-vue' +import { pluginVueJsx } from '@rsbuild/plugin-vue-jsx' +import { tanstackStart } from '@tanstack/vue-start/plugin/rsbuild' +import { isPrerender } from './tests/utils/isPrerender' + +const outDir = process.env.E2E_DIST_DIR ?? 'dist' + +export default defineConfig({ + plugins: [ + pluginBabel({ + include: /\.(?:jsx|tsx)$/, + }), + pluginVue(), + pluginVueJsx(), + tanstackStart(), + ], + source: { + define: { + __TSR_PRERENDER__: JSON.stringify(isPrerender), + }, + }, + output: { + distPath: { + root: outDir, + }, + }, +}) diff --git a/e2e/vue-start/basic/server.js b/e2e/vue-start/basic/server.js index d618ab4bce..3e1ddab400 100644 --- a/e2e/vue-start/basic/server.js +++ b/e2e/vue-start/basic/server.js @@ -1,19 +1,42 @@ -import { toNodeHandler } from 'srvx/node' +import fs from 'node:fs' import path from 'node:path' +import { toNodeHandler } from 'srvx/node' import express from 'express' import { createProxyMiddleware } from 'http-proxy-middleware' -const port = process.env.PORT || 3000 +const port = Number(process.env.PORT ?? 3000) -const startPort = process.env.START_PORT || 3001 +const startPort = Number(process.env.START_PORT ?? 0) + +const isSpaMode = process.env.MODE === 'spa' +const isPrerender = process.env.MODE === 'prerender' +const distDir = process.env.E2E_DIST_DIR || 'dist' +const distClientDir = 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 async function createStartServer() { - const server = (await import('./dist/server/server.js')).default + const distServerEntryPath = resolveDistServerEntryPath() + const server = (await import(distServerEntryPath)).default const nodeHandler = toNodeHandler(server.fetch) const app = express() - app.use(express.static('./dist/client')) + // to keep testing uniform stop express from redirecting /posts to /posts/ + // when serving pre-rendered pages + app.use(express.static(distClientDir, { redirect: !isPrerender })) app.use(async (req, res, next) => { try { @@ -26,13 +49,13 @@ export async function createStartServer() { return { app } } -export async function createSpaServer() { +export async function createSpaServer(backendPort) { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${startPort}/api`, // Replace with your target server's URL + target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -40,28 +63,36 @@ export async function createSpaServer() { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) - app.use(express.static('./dist/client')) + app.use(express.static(distClientDir)) app.get('/{*splat}', (req, res) => { - res.sendFile(path.resolve('./dist/client/index.html')) + res.sendFile('index.html', { root: distClientDir }) }) return { app } } -createSpaServer().then(async ({ app }) => - app.listen(port, () => { - console.info(`Client Server: http://localhost:${port}`) - }), -) - -createStartServer().then(async ({ app }) => - app.listen(startPort, () => { - console.info(`Start Server: http://localhost:${startPort}`) - }), -) +// Bind the backend first so the SPA proxy receives the port actually held by it. +const { app: startApp } = await createStartServer() +const backend = startApp.listen(isSpaMode ? startPort : port, async (error) => { + if (error) { + throw error + } + const backendPort = backend.address().port + if (isSpaMode) { + const { app } = await createSpaServer(backendPort) + const frontend = app.listen(port, (frontendError) => { + if (frontendError) { + throw frontendError + } + console.info(`E2E app: http://localhost:${frontend.address().port}`) + }) + } else { + console.info(`E2E app: http://localhost:${backendPort}`) + } +}) diff --git a/e2e/vue-start/basic/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/basic/src/components/DefaultCatchBoundary.tsx index fe99cf62f3..cd0fa98fc7 100644 --- a/e2e/vue-start/basic/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic/src/components/DefaultCatchBoundary.tsx @@ -1,11 +1,9 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/vue-router' -import type { ErrorComponentProps } from '@tanstack/vue-router' import { defineComponent } from 'vue' export const DefaultCatchBoundary = defineComponent({ @@ -17,9 +15,8 @@ export const DefaultCatchBoundary = defineComponent({ }, setup(props) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error(props.error) diff --git a/e2e/vue-start/basic/src/components/throwRedirect.ts b/e2e/vue-start/basic/src/components/throwRedirect.ts index 187687192b..7d7265e214 100644 --- a/e2e/vue-start/basic/src/components/throwRedirect.ts +++ b/e2e/vue-start/basic/src/components/throwRedirect.ts @@ -2,7 +2,7 @@ import { redirect } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' export const throwRedirect = createServerFn() - .inputValidator( + .validator( (opts: { target: 'internal' | 'external' reloadDocument?: boolean diff --git a/e2e/vue-start/basic/src/raw-stream-fns.ts b/e2e/vue-start/basic/src/raw-stream-fns.ts new file mode 100644 index 0000000000..5b515ea7b8 --- /dev/null +++ b/e2e/vue-start/basic/src/raw-stream-fns.ts @@ -0,0 +1,532 @@ +import { RawStream, createServerFn } from '@tanstack/vue-start' + +// Helper to create a delayed Uint8Array stream +function createDelayedStream( + chunks: Array, + delayMs: number, +): ReadableStream { + return new ReadableStream({ + async start(controller) { + for (const chunk of chunks) { + await new Promise((resolve) => setTimeout(resolve, delayMs)) + controller.enqueue(chunk) + } + controller.close() + }, + }) +} + +// Helper to create a stream with variable delays per chunk +// Each entry is [chunk, delayBeforeMs] - delay happens BEFORE enqueueing the chunk +function createVariableDelayStream( + chunksWithDelays: Array<[Uint8Array, number]>, +): ReadableStream { + return new ReadableStream({ + async start(controller) { + for (const [chunk, delayMs] of chunksWithDelays) { + await new Promise((resolve) => setTimeout(resolve, delayMs)) + controller.enqueue(chunk) + } + controller.close() + }, + }) +} + +// Helper to encode text to Uint8Array +function encode(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +// Export helpers for use in components and SSR routes +export { encode, createDelayedStream, concatBytes } + +// Expected data for hint tests - defined here for both server and client verification +// Test 7: Text hint with pure text +export const TEST7_CHUNKS = [ + encode('Hello, '), + encode('World! '), + encode('This is text.'), +] +export const TEST7_EXPECTED = concatBytes(TEST7_CHUNKS) + +// Test 8: Text hint with pure binary (invalid UTF-8) +export const TEST8_CHUNKS = [ + new Uint8Array([0xff, 0xfe, 0x00, 0x01, 0x80, 0x90]), + new Uint8Array([0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0]), +] +export const TEST8_EXPECTED = concatBytes(TEST8_CHUNKS) + +// Test 9: Text hint with mixed content +export const TEST9_CHUNKS = [ + encode('Valid UTF-8 text'), + new Uint8Array([0xff, 0xfe, 0x80, 0x90]), // Invalid UTF-8 + encode(' More text'), +] +export const TEST9_EXPECTED = concatBytes(TEST9_CHUNKS) + +// Test 10: Binary hint with text data +export const TEST10_CHUNKS = [encode('This is text but using binary hint')] +export const TEST10_EXPECTED = concatBytes(TEST10_CHUNKS) + +// Test 11: Binary hint with pure binary +export const TEST11_CHUNKS = [ + new Uint8Array([0x00, 0x01, 0x02, 0xff, 0xfe, 0xfd]), +] +export const TEST11_EXPECTED = concatBytes(TEST11_CHUNKS) + +// Helper to concatenate byte arrays +function concatBytes(chunks: Array): Uint8Array { + const totalLength = chunks.reduce((acc, c) => acc + c.length, 0) + const result = new Uint8Array(totalLength) + let offset = 0 + for (const chunk of chunks) { + result.set(chunk, offset) + offset += chunk.length + } + return result +} + +// Test 1: Simple single raw stream +export const singleRawStreamFn = createServerFn().handler(async () => { + const stream = createDelayedStream( + [encode('chunk1'), encode('chunk2'), encode('chunk3')], + 50, + ) + return { + message: 'Single stream test', + data: new RawStream(stream), + } +}) + +// Test 2: Multiple raw streams +export const multipleRawStreamsFn = createServerFn().handler(async () => { + const stream1 = createDelayedStream( + [encode('stream1-a'), encode('stream1-b')], + 30, + ) + const stream2 = createDelayedStream( + [encode('stream2-a'), encode('stream2-b')], + 50, + ) + return { + message: 'Multiple streams test', + first: new RawStream(stream1), + second: new RawStream(stream2), + } +}) + +// Test 3: JSON streaming ends before raw stream +export const jsonEndsFirstFn = createServerFn().handler(async () => { + // Slow raw stream (takes 500ms total) + const slowStream = createDelayedStream( + [encode('slow-1'), encode('slow-2'), encode('slow-3'), encode('slow-4')], + 125, + ) + return { + message: 'JSON ends first test', + timestamp: Date.now(), + slowData: new RawStream(slowStream), + } +}) + +// Test 4: Raw stream ends before JSON streaming (fast stream, deferred JSON) +export const rawEndsFirstFn = createServerFn().handler(async () => { + // Fast raw stream (completes quickly) + const fastStream = createDelayedStream([encode('fast-done')], 10) + + // Deferred promise - NOT awaited, so it streams as deferred JSON + const deferredData = new Promise((resolve) => + setTimeout(() => resolve('deferred-json-data'), 200), + ) + + return { + message: 'Raw ends first test', + deferredData, + fastData: new RawStream(fastStream), + } +}) + +// Test 5: Large binary data +export const largeBinaryFn = createServerFn().handler(async () => { + // Create 1KB chunks + const chunk = new Uint8Array(1024) + for (let i = 0; i < chunk.length; i++) { + chunk[i] = i % 256 + } + + const stream = createDelayedStream([chunk, chunk, chunk], 20) + + return { + message: 'Large binary test', + size: 3072, + binary: new RawStream(stream), + } +}) + +// Test 6: Mixed streaming (promise + raw stream) +export const mixedStreamingFn = createServerFn().handler(async () => { + const rawStream = createDelayedStream( + [encode('mixed-raw-1'), encode('mixed-raw-2')], + 50, + ) + + return { + immediate: 'immediate-value', + deferred: new Promise((resolve) => + setTimeout(() => resolve('deferred-value'), 100), + ), + raw: new RawStream(rawStream), + } +}) + +// Test 7: Text hint with pure text data (should use UTF-8 encoding) +export const textHintPureTextFn = createServerFn().handler(async () => { + const stream = createDelayedStream(TEST7_CHUNKS, 30) + return { + message: 'Text hint with pure text', + data: new RawStream(stream, { hint: 'text' }), + } +}) + +// Test 8: Text hint with pure binary data (should fallback to base64) +export const textHintPureBinaryFn = createServerFn().handler(async () => { + const stream = createDelayedStream(TEST8_CHUNKS, 30) + return { + message: 'Text hint with pure binary', + data: new RawStream(stream, { hint: 'text' }), + } +}) + +// Test 9: Text hint with mixed content (some UTF-8, some binary) +export const textHintMixedFn = createServerFn().handler(async () => { + const stream = createDelayedStream(TEST9_CHUNKS, 30) + return { + message: 'Text hint with mixed content', + data: new RawStream(stream, { hint: 'text' }), + } +}) + +// Test 10: Binary hint with text data (should still use base64) +export const binaryHintTextFn = createServerFn().handler(async () => { + const stream = createDelayedStream(TEST10_CHUNKS, 30) + return { + message: 'Binary hint with text data', + data: new RawStream(stream, { hint: 'binary' }), + } +}) + +// Test 11: Binary hint with pure binary data +export const binaryHintBinaryFn = createServerFn().handler(async () => { + const stream = createDelayedStream(TEST11_CHUNKS, 30) + return { + message: 'Binary hint with binary data', + data: new RawStream(stream, { hint: 'binary' }), + } +}) + +// ============================================================================ +// MULTIPLEXING TESTS - Verify correct interleaving of multiple streams +// ============================================================================ + +// Expected data for multiplexing tests +// Test 12: Two streams with interleaved timing +// Stream A: sends at 0ms, 150ms, 200ms (3 chunks with pauses) +// Stream B: sends at 50ms, 100ms, 250ms (3 chunks, different rhythm) +export const TEST12_STREAM_A_CHUNKS: Array<[Uint8Array, number]> = [ + [encode('A1-first'), 0], // immediate + [encode('A2-after-pause'), 150], // 150ms pause + [encode('A3-quick'), 50], // 50ms after A2 +] +export const TEST12_STREAM_B_CHUNKS: Array<[Uint8Array, number]> = [ + [encode('B1-start'), 50], // 50ms after start + [encode('B2-continue'), 50], // 50ms after B1 + [encode('B3-final'), 150], // 150ms pause then final +] +export const TEST12_STREAM_A_EXPECTED = concatBytes( + TEST12_STREAM_A_CHUNKS.map(([chunk]) => chunk), +) +export const TEST12_STREAM_B_EXPECTED = concatBytes( + TEST12_STREAM_B_CHUNKS.map(([chunk]) => chunk), +) + +// Test 13: Burst-pause-burst pattern (single stream) +// 3 chunks quickly, long pause, 3 more chunks quickly +export const TEST13_CHUNKS: Array<[Uint8Array, number]> = [ + [encode('burst1-a'), 10], + [encode('burst1-b'), 10], + [encode('burst1-c'), 10], + [encode('pause-then-burst2-a'), 200], // long pause + [encode('burst2-b'), 10], + [encode('burst2-c'), 10], +] +export const TEST13_EXPECTED = concatBytes( + TEST13_CHUNKS.map(([chunk]) => chunk), +) + +// Test 14: Three concurrent streams with different patterns +// Stream A: fast steady (every 30ms) +// Stream B: slow steady (every 100ms) +// Stream C: burst pattern (quick-pause-quick) +export const TEST14_STREAM_A_CHUNKS: Array<[Uint8Array, number]> = [ + [encode('A1'), 30], + [encode('A2'), 30], + [encode('A3'), 30], + [encode('A4'), 30], +] +export const TEST14_STREAM_B_CHUNKS: Array<[Uint8Array, number]> = [ + [encode('B1-slow'), 100], + [encode('B2-slow'), 100], +] +export const TEST14_STREAM_C_CHUNKS: Array<[Uint8Array, number]> = [ + [encode('C1-burst'), 20], + [encode('C2-burst'), 20], + [encode('C3-after-pause'), 150], +] +export const TEST14_STREAM_A_EXPECTED = concatBytes( + TEST14_STREAM_A_CHUNKS.map(([chunk]) => chunk), +) +export const TEST14_STREAM_B_EXPECTED = concatBytes( + TEST14_STREAM_B_CHUNKS.map(([chunk]) => chunk), +) +export const TEST14_STREAM_C_EXPECTED = concatBytes( + TEST14_STREAM_C_CHUNKS.map(([chunk]) => chunk), +) + +// Test 12: Interleaved multiplexing - two streams with variable delays +export const interleavedStreamsFn = createServerFn().handler(async () => { + const streamA = createVariableDelayStream(TEST12_STREAM_A_CHUNKS) + const streamB = createVariableDelayStream(TEST12_STREAM_B_CHUNKS) + + return { + message: 'Interleaved streams test', + streamA: new RawStream(streamA), + streamB: new RawStream(streamB), + } +}) + +// Test 13: Burst-pause-burst pattern +export const burstPauseBurstFn = createServerFn().handler(async () => { + const stream = createVariableDelayStream(TEST13_CHUNKS) + + return { + message: 'Burst-pause-burst test', + data: new RawStream(stream), + } +}) + +// Test 14: Three concurrent streams +export const threeStreamsFn = createServerFn().handler(async () => { + const streamA = createVariableDelayStream(TEST14_STREAM_A_CHUNKS) + const streamB = createVariableDelayStream(TEST14_STREAM_B_CHUNKS) + const streamC = createVariableDelayStream(TEST14_STREAM_C_CHUNKS) + + return { + message: 'Three concurrent streams test', + fast: new RawStream(streamA), + slow: new RawStream(streamB), + burst: new RawStream(streamC), + } +}) + +// ============================================================================ +// EDGE CASE TESTS +// ============================================================================ + +// Test 15: Empty stream (zero bytes) +export const emptyStreamFn = createServerFn().handler(async () => { + // Stream that immediately closes with no data + const stream = new ReadableStream({ + start(controller) { + controller.close() + }, + }) + + return { + message: 'Empty stream test', + data: new RawStream(stream), + } +}) + +// Test 16: Stream that errors mid-flight +export const errorStreamFn = createServerFn().handler(async () => { + // Stream that sends some data then errors + const stream = new ReadableStream({ + async start(controller) { + controller.enqueue(encode('chunk-before-error')) + await new Promise((resolve) => setTimeout(resolve, 50)) + controller.error(new Error('Intentional stream error')) + }, + }) + + return { + message: 'Error stream test', + data: new RawStream(stream), + } +}) + +// Helpers for consuming streams (exported for use in components) +// Note: RawStream is the marker class used in loaders/server functions, +// but after SSR deserialization it becomes ReadableStream. +// We accept both types to handle the TypeScript mismatch. +function getActualStream( + stream: ReadableStream | RawStream, +): ReadableStream { + return stream instanceof RawStream + ? stream.stream + : (stream as ReadableStream) +} + +const streamTextCache = new WeakMap< + ReadableStream, + Promise +>() +const streamBytesCache = new WeakMap< + ReadableStream, + Promise +>() +const streamByteCountCache = new WeakMap< + ReadableStream, + Promise +>() + +export function createStreamConsumer() { + const decoder = new TextDecoder() + + return async function consumeStream( + stream: ReadableStream | RawStream, + ): Promise { + const actualStream = getActualStream(stream) + const cached = streamTextCache.get(actualStream) + if (cached) { + return cached + } + + const promise = (async () => { + const reader = actualStream.getReader() + const chunks: Array = [] + + try { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (true) { + const { done, value } = await reader.read() + if (done) break + chunks.push(decoder.decode(value, { stream: true })) + } + } finally { + reader.releaseLock() + } + + return chunks.join('') + })() + + streamTextCache.set(actualStream, promise) + return promise + } +} + +export async function consumeBinaryStream( + stream: ReadableStream | RawStream, +): Promise { + const actualStream = getActualStream(stream) + const cached = streamByteCountCache.get(actualStream) + if (cached) { + return cached + } + + const promise = (async () => { + const reader = actualStream.getReader() + let totalBytes = 0 + + try { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (true) { + const { done, value } = await reader.read() + if (done) break + totalBytes += value.length + } + } finally { + reader.releaseLock() + } + + return totalBytes + })() + + streamByteCountCache.set(actualStream, promise) + return promise +} + +// Helper to collect all bytes from a stream +export async function collectBytes( + stream: ReadableStream | RawStream, +): Promise { + const actualStream = getActualStream(stream) + const cached = streamBytesCache.get(actualStream) + if (cached) { + return cached + } + + const promise = (async () => { + const reader = actualStream.getReader() + const chunks: Array = [] + let totalLength = 0 + + try { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (true) { + const { done, value } = await reader.read() + if (done) break + chunks.push(value) + totalLength += value.length + } + } finally { + reader.releaseLock() + } + + const result = new Uint8Array(totalLength) + let pos = 0 + for (const chunk of chunks) { + result.set(chunk, pos) + pos += chunk.length + } + return result + })() + + streamBytesCache.set(actualStream, promise) + return promise +} + +// Compare two Uint8Arrays byte-by-byte +export function compareBytes( + actual: Uint8Array, + expected: Uint8Array, +): { + match: boolean + mismatchIndex: number | null + actualLength: number + expectedLength: number +} { + if (actual.length !== expected.length) { + return { + match: false, + mismatchIndex: -1, // -1 indicates length mismatch + actualLength: actual.length, + expectedLength: expected.length, + } + } + for (let i = 0; i < actual.length; i++) { + if (actual[i] !== expected[i]) { + return { + match: false, + mismatchIndex: i, + actualLength: actual.length, + expectedLength: expected.length, + } + } + } + return { + match: true, + mismatchIndex: null, + actualLength: actual.length, + expectedLength: expected.length, + } +} diff --git a/e2e/vue-start/basic/src/routeTree.gen.ts b/e2e/vue-start/basic/src/routeTree.gen.ts index 7232919c5e..7fbcd192b6 100644 --- a/e2e/vue-start/basic/src/routeTree.gen.ts +++ b/e2e/vue-start/basic/src/routeTree.gen.ts @@ -9,81 +9,71 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' -import { Route as UsersRouteImport } from './routes/users' -import { Route as StreamRouteImport } from './routes/stream' -import { Route as ScriptsRouteImport } from './routes/scripts' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as LinksRouteImport } from './routes/links' -import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as LayoutRouteImport } from './routes/_layout' -import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' -import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' -import { Route as RedirectIndexRouteImport } from './routes/redirect/index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' -import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' -import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' -import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' -import { Route as NotFoundViaHeadRouteImport } from './routes/not-found/via-head' -import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' -import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' +import { Route as LinksRouteImport } from './routes/links' +import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RawStreamRouteImport } from './routes/raw-stream' +import { Route as ScriptsRouteImport } from './routes/scripts' +import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' +import { Route as SpecialCharsRouteRouteImport } from './routes/specialChars/route' +import { Route as StreamRouteImport } from './routes/stream' +import { Route as UsersRouteImport } from './routes/users' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' -import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' -import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' +import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' +import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' +import { Route as NotFoundParentBoundaryRouteRouteImport } from './routes/not-found/parent-boundary/route' +import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' +import { Route as NotFoundViaBeforeLoadTargetRootRouteImport } from './routes/not-found/via-beforeLoad-target-root' +import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as RawStreamIndexRouteImport } from './routes/raw-stream/index' +import { Route as RawStreamClientCallRouteImport } from './routes/raw-stream/client-call' +import { Route as RawStreamSsrBinaryHintRouteImport } from './routes/raw-stream/ssr-binary-hint' +import { Route as RawStreamSsrMixedRouteImport } from './routes/raw-stream/ssr-mixed' +import { Route as RawStreamSsrMultipleRouteImport } from './routes/raw-stream/ssr-multiple' +import { Route as RawStreamSsrSingleRouteImport } from './routes/raw-stream/ssr-single' +import { Route as RawStreamSsrTextHintRouteImport } from './routes/raw-stream/ssr-text-hint' +import { Route as RedirectIndexRouteImport } from './routes/redirect/index' +import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' +import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' +import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' +import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' +import { Route as SpecialCharsParamRouteImport } from './routes/specialChars/$param' +import { Route as SpecialCharsHashRouteImport } from './routes/specialChars/hash' +import { Route as SpecialCharsMalformedRouteRouteImport } from './routes/specialChars/malformed/route' +import { Route as SpecialCharsSearchRouteImport } from './routes/specialChars/search' +import { Route as SpecialCharsChar45824Char54620Char48124Char44397RouteImport } from './routes/specialChars/대한민국' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as NotFoundParentBoundaryViaBeforeLoadRouteImport } from './routes/not-found/parent-boundary/via-beforeLoad' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' +import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' +import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' +import { Route as SpecialCharsMalformedParamRouteImport } from './routes/specialChars/malformed/$param' +import { Route as SpecialCharsMalformedSearchRouteImport } from './routes/specialChars/malformed/search' import { Route as RedirectTargetServerFnIndexRouteImport } from './routes/redirect/$target/serverFn/index' -import { Route as RedirectTargetServerFnViaUseServerFnRouteImport } from './routes/redirect/$target/serverFn/via-useServerFn' -import { Route as RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' import { Route as RedirectTargetServerFnViaBeforeLoadRouteImport } from './routes/redirect/$target/serverFn/via-beforeLoad' +import { Route as RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' +import { Route as RedirectTargetServerFnViaUseServerFnRouteImport } from './routes/redirect/$target/serverFn/via-useServerFn' -const Char45824Char54620Char48124Char44397Route = - Char45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => rootRouteImport, - } as any) -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const StreamRoute = StreamRouteImport.update({ - id: '/stream', - path: '/stream', - getParentRoute: () => rootRouteImport, -} as any) -const ScriptsRoute = ScriptsRouteImport.update({ - id: '/scripts', - path: '/scripts', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const LinksRoute = LinksRouteImport.update({ - id: '/links', - path: '/links', - getParentRoute: () => rootRouteImport, -} as any) -const InlineScriptsRoute = InlineScriptsRouteImport.update({ - id: '/inline-scripts', - path: '/inline-scripts', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -91,13 +81,14 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const InlineScriptsRoute = InlineScriptsRouteImport.update({ + id: '/inline-scripts', + path: '/inline-scripts', getParentRoute: () => rootRouteImport, } as any) -const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ - id: '/search-params', - path: '/search-params', +const LinksRoute = LinksRouteImport.update({ + id: '/links', + path: '/links', getParentRoute: () => rootRouteImport, } as any) const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ @@ -105,35 +96,49 @@ const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ path: '/not-found', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SearchParamsRouteRoute, -} as any) -const RedirectIndexRoute = RedirectIndexRouteImport.update({ - id: '/redirect/', - path: '/redirect/', +const RawStreamRoute = RawStreamRouteImport.update({ + id: '/raw-stream', + path: '/raw-stream', getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, +const ScriptsRoute = ScriptsRouteImport.update({ + id: '/scripts', + path: '/scripts', + getParentRoute: () => rootRouteImport, } as any) -const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NotFoundRouteRoute, +const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ + id: '/search-params', + path: '/search-params', + getParentRoute: () => rootRouteImport, +} as any) +const SpecialCharsRouteRoute = SpecialCharsRouteRouteImport.update({ + id: '/specialChars', + path: '/specialChars', + getParentRoute: () => rootRouteImport, +} as any) +const StreamRoute = StreamRouteImport.update({ + id: '/stream', + path: '/stream', + getParentRoute: () => rootRouteImport, +} as any) +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, } as any) const MultiCookieRedirectIndexRoute = MultiCookieRedirectIndexRouteImport.update({ @@ -141,10 +146,103 @@ const MultiCookieRedirectIndexRoute = path: '/multi-cookie-redirect/', getParentRoute: () => rootRouteImport, } as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, +const MultiCookieRedirectTargetRoute = + MultiCookieRedirectTargetRouteImport.update({ + id: '/multi-cookie-redirect/target', + path: '/multi-cookie-redirect/target', + getParentRoute: () => rootRouteImport, + } as any) +const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NotFoundRouteRoute, +} as any) +const NotFoundParentBoundaryRouteRoute = + NotFoundParentBoundaryRouteRouteImport.update({ + id: '/parent-boundary', + path: '/parent-boundary', + getParentRoute: () => NotFoundRouteRoute, + } as any) +const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', + getParentRoute: () => NotFoundRouteRoute, +} as any) +const NotFoundViaBeforeLoadTargetRootRoute = + NotFoundViaBeforeLoadTargetRootRouteImport.update({ + id: '/via-beforeLoad-target-root', + path: '/via-beforeLoad-target-root', + getParentRoute: () => NotFoundRouteRoute, + } as any) +const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', + getParentRoute: () => NotFoundRouteRoute, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const RawStreamIndexRoute = RawStreamIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamClientCallRoute = RawStreamClientCallRouteImport.update({ + id: '/client-call', + path: '/client-call', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrBinaryHintRoute = RawStreamSsrBinaryHintRouteImport.update({ + id: '/ssr-binary-hint', + path: '/ssr-binary-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMixedRoute = RawStreamSsrMixedRouteImport.update({ + id: '/ssr-mixed', + path: '/ssr-mixed', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMultipleRoute = RawStreamSsrMultipleRouteImport.update({ + id: '/ssr-multiple', + path: '/ssr-multiple', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrSingleRoute = RawStreamSsrSingleRouteImport.update({ + id: '/ssr-single', + path: '/ssr-single', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrTextHintRoute = RawStreamSsrTextHintRouteImport.update({ + id: '/ssr-text-hint', + path: '/ssr-text-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectTargetRoute = RedirectTargetRouteImport.update({ + id: '/redirect/$target', + path: '/redirect/$target', + getParentRoute: () => rootRouteImport, +} as any) +const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SearchParamsRouteRoute, +} as any) +const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ + id: '/default', + path: '/default', + getParentRoute: () => SearchParamsRouteRoute, } as any) const SearchParamsLoaderThrowsRedirectRoute = SearchParamsLoaderThrowsRedirectRouteImport.update({ @@ -152,181 +250,224 @@ const SearchParamsLoaderThrowsRedirectRoute = path: '/loader-throws-redirect', getParentRoute: () => SearchParamsRouteRoute, } as any) -const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ - id: '/default', - path: '/default', - getParentRoute: () => SearchParamsRouteRoute, +const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const RedirectTargetRoute = RedirectTargetRouteImport.update({ - id: '/redirect/$target', - path: '/redirect/$target', - getParentRoute: () => rootRouteImport, +const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ + id: '/hash', + path: '/hash', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', - getParentRoute: () => NotFoundRouteRoute, -} as any) -const NotFoundViaHeadRoute = NotFoundViaHeadRouteImport.update({ - id: '/via-head', - path: '/via-head', - getParentRoute: () => NotFoundRouteRoute, -} as any) -const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', - getParentRoute: () => NotFoundRouteRoute, -} as any) -const MultiCookieRedirectTargetRoute = - MultiCookieRedirectTargetRouteImport.update({ - id: '/multi-cookie-redirect/target', - path: '/multi-cookie-redirect/target', - getParentRoute: () => rootRouteImport, +const SpecialCharsMalformedRouteRoute = + SpecialCharsMalformedRouteRouteImport.update({ + id: '/malformed', + path: '/malformed', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', - getParentRoute: () => rootRouteImport, +const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const SpecialCharsChar45824Char54620Char48124Char44397Route = + SpecialCharsChar45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => SpecialCharsRouteRoute, + } as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const NotFoundParentBoundaryViaBeforeLoadRoute = + NotFoundParentBoundaryViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', + getParentRoute: () => NotFoundParentBoundaryRouteRoute, + } as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, } as any) const RedirectTargetIndexRoute = RedirectTargetIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', - getParentRoute: () => RedirectTargetRoute, -} as any) const RedirectTargetViaBeforeLoadRoute = RedirectTargetViaBeforeLoadRouteImport.update({ id: '/via-beforeLoad', path: '/via-beforeLoad', getParentRoute: () => RedirectTargetRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, -} as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => ApiUsersRoute, -} as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, -} as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', + getParentRoute: () => RedirectTargetRoute, } as any) +const SpecialCharsMalformedParamRoute = + SpecialCharsMalformedParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsMalformedRouteRoute, + } as any) +const SpecialCharsMalformedSearchRoute = + SpecialCharsMalformedSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsMalformedRouteRoute, + } as any) const RedirectTargetServerFnIndexRoute = RedirectTargetServerFnIndexRouteImport.update({ id: '/serverFn/', path: '/serverFn/', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetServerFnViaUseServerFnRoute = - RedirectTargetServerFnViaUseServerFnRouteImport.update({ - id: '/serverFn/via-useServerFn', - path: '/serverFn/via-useServerFn', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetServerFnViaLoaderRoute = - RedirectTargetServerFnViaLoaderRouteImport.update({ - id: '/serverFn/via-loader', - path: '/serverFn/via-loader', - getParentRoute: () => RedirectTargetRoute, - } as any) const RedirectTargetServerFnViaBeforeLoadRoute = RedirectTargetServerFnViaBeforeLoadRouteImport.update({ id: '/serverFn/via-beforeLoad', path: '/serverFn/via-beforeLoad', getParentRoute: () => RedirectTargetRoute, } as any) +const RedirectTargetServerFnViaLoaderRoute = + RedirectTargetServerFnViaLoaderRouteImport.update({ + id: '/serverFn/via-loader', + path: '/serverFn/via-loader', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetServerFnViaUseServerFnRoute = + RedirectTargetServerFnViaUseServerFnRouteImport.update({ + id: '/serverFn/via-useServerFn', + path: '/serverFn/via-useServerFn', + getParentRoute: () => RedirectTargetRoute, + } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute '/not-found': typeof NotFoundRouteRouteWithChildren '/search-params': typeof SearchParamsRouteRouteWithChildren + '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/deferred': typeof DeferredRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute '/posts': typeof PostsRouteWithChildren + '/raw-stream': typeof RawStreamRouteWithChildren '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute '/users': typeof UsersRouteWithChildren - '/대한민국': typeof Char45824Char54620Char48124Char44397Route + '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren + '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute - '/not-found/via-head': typeof NotFoundViaHeadRoute + '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute '/not-found/via-loader': typeof NotFoundViaLoaderRoute '/posts/$postId': typeof PostsPostIdRoute + '/raw-stream/client-call': typeof RawStreamClientCallRoute + '/raw-stream/ssr-binary-hint': typeof RawStreamSsrBinaryHintRoute + '/raw-stream/ssr-mixed': typeof RawStreamSsrMixedRoute + '/raw-stream/ssr-multiple': typeof RawStreamSsrMultipleRoute + '/raw-stream/ssr-single': typeof RawStreamSsrSingleRoute + '/raw-stream/ssr-text-hint': typeof RawStreamSsrTextHintRoute '/redirect/$target': typeof RedirectTargetRouteWithChildren '/search-params/default': typeof SearchParamsDefaultRoute '/search-params/loader-throws-redirect': typeof SearchParamsLoaderThrowsRedirectRoute + '/specialChars/$param': typeof SpecialCharsParamRoute + '/specialChars/hash': typeof SpecialCharsHashRoute + '/specialChars/search': typeof SpecialCharsSearchRoute + '/specialChars/대한민국': typeof SpecialCharsChar45824Char54620Char48124Char44397Route '/users/$userId': typeof UsersUserIdRoute - '/multi-cookie-redirect': typeof MultiCookieRedirectIndexRoute + '/multi-cookie-redirect/': typeof MultiCookieRedirectIndexRoute '/not-found/': typeof NotFoundIndexRoute '/posts/': typeof PostsIndexRoute - '/redirect': typeof RedirectIndexRoute + '/raw-stream/': typeof RawStreamIndexRoute + '/redirect/': typeof RedirectIndexRoute '/search-params/': typeof SearchParamsIndexRoute '/users/': typeof UsersIndexRoute '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$userId': typeof ApiUsersUserIdRoute + '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute '/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute + '/specialChars/malformed/$param': typeof SpecialCharsMalformedParamRoute + '/specialChars/malformed/search': typeof SpecialCharsMalformedSearchRoute '/redirect/$target/': typeof RedirectTargetIndexRoute '/redirect/$target/serverFn/via-beforeLoad': typeof RedirectTargetServerFnViaBeforeLoadRoute '/redirect/$target/serverFn/via-loader': typeof RedirectTargetServerFnViaLoaderRoute '/redirect/$target/serverFn/via-useServerFn': typeof RedirectTargetServerFnViaUseServerFnRoute - '/redirect/$target/serverFn': typeof RedirectTargetServerFnIndexRoute + '/redirect/$target/serverFn/': typeof RedirectTargetServerFnIndexRoute } export interface FileRoutesByTo { '/': typeof IndexRoute + '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/deferred': typeof DeferredRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute - '/대한민국': typeof Char45824Char54620Char48124Char44397Route + '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren + '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute - '/not-found/via-head': typeof NotFoundViaHeadRoute + '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute '/not-found/via-loader': typeof NotFoundViaLoaderRoute '/posts/$postId': typeof PostsPostIdRoute + '/raw-stream/client-call': typeof RawStreamClientCallRoute + '/raw-stream/ssr-binary-hint': typeof RawStreamSsrBinaryHintRoute + '/raw-stream/ssr-mixed': typeof RawStreamSsrMixedRoute + '/raw-stream/ssr-multiple': typeof RawStreamSsrMultipleRoute + '/raw-stream/ssr-single': typeof RawStreamSsrSingleRoute + '/raw-stream/ssr-text-hint': typeof RawStreamSsrTextHintRoute '/search-params/default': typeof SearchParamsDefaultRoute '/search-params/loader-throws-redirect': typeof SearchParamsLoaderThrowsRedirectRoute + '/specialChars/$param': typeof SpecialCharsParamRoute + '/specialChars/hash': typeof SpecialCharsHashRoute + '/specialChars/search': typeof SpecialCharsSearchRoute + '/specialChars/대한민국': typeof SpecialCharsChar45824Char54620Char48124Char44397Route '/users/$userId': typeof UsersUserIdRoute '/multi-cookie-redirect': typeof MultiCookieRedirectIndexRoute '/not-found': typeof NotFoundIndexRoute '/posts': typeof PostsIndexRoute + '/raw-stream': typeof RawStreamIndexRoute '/redirect': typeof RedirectIndexRoute '/search-params': typeof SearchParamsIndexRoute '/users': typeof UsersIndexRoute '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$userId': typeof ApiUsersUserIdRoute + '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute '/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute + '/specialChars/malformed/$param': typeof SpecialCharsMalformedParamRoute + '/specialChars/malformed/search': typeof SpecialCharsMalformedSearchRoute '/redirect/$target': typeof RedirectTargetIndexRoute '/redirect/$target/serverFn/via-beforeLoad': typeof RedirectTargetServerFnViaBeforeLoadRoute '/redirect/$target/serverFn/via-loader': typeof RedirectTargetServerFnViaLoaderRoute @@ -338,38 +479,55 @@ export interface FileRoutesById { '/': typeof IndexRoute '/not-found': typeof NotFoundRouteRouteWithChildren '/search-params': typeof SearchParamsRouteRouteWithChildren + '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/_layout': typeof LayoutRouteWithChildren '/deferred': typeof DeferredRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute '/posts': typeof PostsRouteWithChildren + '/raw-stream': typeof RawStreamRouteWithChildren '/scripts': typeof ScriptsRoute '/stream': typeof StreamRoute '/users': typeof UsersRouteWithChildren - '/대한민국': typeof Char45824Char54620Char48124Char44397Route + '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren + '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute - '/not-found/via-head': typeof NotFoundViaHeadRoute + '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute '/not-found/via-loader': typeof NotFoundViaLoaderRoute '/posts/$postId': typeof PostsPostIdRoute + '/raw-stream/client-call': typeof RawStreamClientCallRoute + '/raw-stream/ssr-binary-hint': typeof RawStreamSsrBinaryHintRoute + '/raw-stream/ssr-mixed': typeof RawStreamSsrMixedRoute + '/raw-stream/ssr-multiple': typeof RawStreamSsrMultipleRoute + '/raw-stream/ssr-single': typeof RawStreamSsrSingleRoute + '/raw-stream/ssr-text-hint': typeof RawStreamSsrTextHintRoute '/redirect/$target': typeof RedirectTargetRouteWithChildren '/search-params/default': typeof SearchParamsDefaultRoute '/search-params/loader-throws-redirect': typeof SearchParamsLoaderThrowsRedirectRoute + '/specialChars/$param': typeof SpecialCharsParamRoute + '/specialChars/hash': typeof SpecialCharsHashRoute + '/specialChars/search': typeof SpecialCharsSearchRoute + '/specialChars/대한민국': typeof SpecialCharsChar45824Char54620Char48124Char44397Route '/users/$userId': typeof UsersUserIdRoute '/multi-cookie-redirect/': typeof MultiCookieRedirectIndexRoute '/not-found/': typeof NotFoundIndexRoute '/posts/': typeof PostsIndexRoute + '/raw-stream/': typeof RawStreamIndexRoute '/redirect/': typeof RedirectIndexRoute '/search-params/': typeof SearchParamsIndexRoute '/users/': typeof UsersIndexRoute '/_layout/_layout-2/layout-a': typeof LayoutLayout2LayoutARoute '/_layout/_layout-2/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$userId': typeof ApiUsersUserIdRoute + '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts_/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute '/redirect/$target/via-loader': typeof RedirectTargetViaLoaderRoute + '/specialChars/malformed/$param': typeof SpecialCharsMalformedParamRoute + '/specialChars/malformed/search': typeof SpecialCharsMalformedSearchRoute '/redirect/$target/': typeof RedirectTargetIndexRoute '/redirect/$target/serverFn/via-beforeLoad': typeof RedirectTargetServerFnViaBeforeLoadRoute '/redirect/$target/serverFn/via-loader': typeof RedirectTargetServerFnViaLoaderRoute @@ -382,71 +540,104 @@ export interface FileRouteTypes { | '/' | '/not-found' | '/search-params' + | '/specialChars' | '/deferred' | '/inline-scripts' | '/links' | '/posts' + | '/raw-stream' | '/scripts' | '/stream' | '/users' - | '/대한민국' + | '/not-found/parent-boundary' + | '/specialChars/malformed' | '/api/users' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' - | '/not-found/via-head' + | '/not-found/via-beforeLoad-target-root' | '/not-found/via-loader' | '/posts/$postId' + | '/raw-stream/client-call' + | '/raw-stream/ssr-binary-hint' + | '/raw-stream/ssr-mixed' + | '/raw-stream/ssr-multiple' + | '/raw-stream/ssr-single' + | '/raw-stream/ssr-text-hint' | '/redirect/$target' | '/search-params/default' | '/search-params/loader-throws-redirect' + | '/specialChars/$param' + | '/specialChars/hash' + | '/specialChars/search' + | '/specialChars/대한민국' | '/users/$userId' - | '/multi-cookie-redirect' + | '/multi-cookie-redirect/' | '/not-found/' | '/posts/' - | '/redirect' + | '/raw-stream/' + | '/redirect/' | '/search-params/' | '/users/' | '/layout-a' | '/layout-b' | '/api/users/$userId' + | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' | '/redirect/$target/via-loader' + | '/specialChars/malformed/$param' + | '/specialChars/malformed/search' | '/redirect/$target/' | '/redirect/$target/serverFn/via-beforeLoad' | '/redirect/$target/serverFn/via-loader' | '/redirect/$target/serverFn/via-useServerFn' - | '/redirect/$target/serverFn' + | '/redirect/$target/serverFn/' fileRoutesByTo: FileRoutesByTo to: | '/' + | '/specialChars' | '/deferred' | '/inline-scripts' | '/links' | '/scripts' | '/stream' - | '/대한민국' + | '/not-found/parent-boundary' + | '/specialChars/malformed' | '/api/users' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' - | '/not-found/via-head' + | '/not-found/via-beforeLoad-target-root' | '/not-found/via-loader' | '/posts/$postId' + | '/raw-stream/client-call' + | '/raw-stream/ssr-binary-hint' + | '/raw-stream/ssr-mixed' + | '/raw-stream/ssr-multiple' + | '/raw-stream/ssr-single' + | '/raw-stream/ssr-text-hint' | '/search-params/default' | '/search-params/loader-throws-redirect' + | '/specialChars/$param' + | '/specialChars/hash' + | '/specialChars/search' + | '/specialChars/대한민국' | '/users/$userId' | '/multi-cookie-redirect' | '/not-found' | '/posts' + | '/raw-stream' | '/redirect' | '/search-params' | '/users' | '/layout-a' | '/layout-b' | '/api/users/$userId' + | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' | '/redirect/$target/via-loader' + | '/specialChars/malformed/$param' + | '/specialChars/malformed/search' | '/redirect/$target' | '/redirect/$target/serverFn/via-beforeLoad' | '/redirect/$target/serverFn/via-loader' @@ -457,38 +648,55 @@ export interface FileRouteTypes { | '/' | '/not-found' | '/search-params' + | '/specialChars' | '/_layout' | '/deferred' | '/inline-scripts' | '/links' | '/posts' + | '/raw-stream' | '/scripts' | '/stream' | '/users' - | '/대한민국' + | '/not-found/parent-boundary' + | '/specialChars/malformed' | '/_layout/_layout-2' | '/api/users' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' - | '/not-found/via-head' + | '/not-found/via-beforeLoad-target-root' | '/not-found/via-loader' | '/posts/$postId' + | '/raw-stream/client-call' + | '/raw-stream/ssr-binary-hint' + | '/raw-stream/ssr-mixed' + | '/raw-stream/ssr-multiple' + | '/raw-stream/ssr-single' + | '/raw-stream/ssr-text-hint' | '/redirect/$target' | '/search-params/default' | '/search-params/loader-throws-redirect' + | '/specialChars/$param' + | '/specialChars/hash' + | '/specialChars/search' + | '/specialChars/대한민국' | '/users/$userId' | '/multi-cookie-redirect/' | '/not-found/' | '/posts/' + | '/raw-stream/' | '/redirect/' | '/search-params/' | '/users/' | '/_layout/_layout-2/layout-a' | '/_layout/_layout-2/layout-b' | '/api/users/$userId' + | '/not-found/parent-boundary/via-beforeLoad' | '/posts_/$postId/deep' | '/redirect/$target/via-beforeLoad' | '/redirect/$target/via-loader' + | '/specialChars/malformed/$param' + | '/specialChars/malformed/search' | '/redirect/$target/' | '/redirect/$target/serverFn/via-beforeLoad' | '/redirect/$target/serverFn/via-loader' @@ -500,15 +708,16 @@ export interface RootRouteChildren { IndexRoute: typeof IndexRoute NotFoundRouteRoute: typeof NotFoundRouteRouteWithChildren SearchParamsRouteRoute: typeof SearchParamsRouteRouteWithChildren + SpecialCharsRouteRoute: typeof SpecialCharsRouteRouteWithChildren LayoutRoute: typeof LayoutRouteWithChildren DeferredRoute: typeof DeferredRoute InlineScriptsRoute: typeof InlineScriptsRoute LinksRoute: typeof LinksRoute PostsRoute: typeof PostsRouteWithChildren + RawStreamRoute: typeof RawStreamRouteWithChildren ScriptsRoute: typeof ScriptsRoute StreamRoute: typeof StreamRoute UsersRoute: typeof UsersRouteWithChildren - Char45824Char54620Char48124Char44397Route: typeof Char45824Char54620Char48124Char44397Route ApiUsersRoute: typeof ApiUsersRouteWithChildren MultiCookieRedirectTargetRoute: typeof MultiCookieRedirectTargetRoute RedirectTargetRoute: typeof RedirectTargetRouteWithChildren @@ -519,53 +728,18 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/stream': { - id: '/stream' - path: '/stream' - fullPath: '/stream' - preLoaderRoute: typeof StreamRouteImport - parentRoute: typeof rootRouteImport - } - '/scripts': { - id: '/scripts' - path: '/scripts' - fullPath: '/scripts' - preLoaderRoute: typeof ScriptsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/links': { - id: '/links' - path: '/links' - fullPath: '/links' - preLoaderRoute: typeof LinksRouteImport - parentRoute: typeof rootRouteImport - } - '/inline-scripts': { - id: '/inline-scripts' - path: '/inline-scripts' - fullPath: '/inline-scripts' - preLoaderRoute: typeof InlineScriptsRouteImport + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -575,18 +749,18 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutRouteImport + '/inline-scripts': { + id: '/inline-scripts' + path: '/inline-scripts' + fullPath: '/inline-scripts' + preLoaderRoute: typeof InlineScriptsRouteImport parentRoute: typeof rootRouteImport } - '/search-params': { - id: '/search-params' - path: '/search-params' - fullPath: '/search-params' - preLoaderRoute: typeof SearchParamsRouteRouteImport + '/links': { + id: '/links' + path: '/links' + fullPath: '/links' + preLoaderRoute: typeof LinksRouteImport parentRoute: typeof rootRouteImport } '/not-found': { @@ -596,40 +770,82 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof NotFoundRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/raw-stream': { + id: '/raw-stream' + path: '/raw-stream' + fullPath: '/raw-stream' + preLoaderRoute: typeof RawStreamRouteImport + parentRoute: typeof rootRouteImport + } + '/scripts': { + id: '/scripts' + path: '/scripts' + fullPath: '/scripts' + preLoaderRoute: typeof ScriptsRouteImport + parentRoute: typeof rootRouteImport + } + '/search-params': { + id: '/search-params' + path: '/search-params' + fullPath: '/search-params' + preLoaderRoute: typeof SearchParamsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/specialChars': { + id: '/specialChars' + path: '/specialChars' + fullPath: '/specialChars' + preLoaderRoute: typeof SpecialCharsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/stream': { + id: '/stream' + path: '/stream' + fullPath: '/stream' + preLoaderRoute: typeof StreamRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/search-params/': { - id: '/search-params/' - path: '/' - fullPath: '/search-params/' - preLoaderRoute: typeof SearchParamsIndexRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectIndexRouteImport + '/multi-cookie-redirect/': { + id: '/multi-cookie-redirect/' + path: '/multi-cookie-redirect' + fullPath: '/multi-cookie-redirect/' + preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute + '/multi-cookie-redirect/target': { + id: '/multi-cookie-redirect/target' + path: '/multi-cookie-redirect/target' + fullPath: '/multi-cookie-redirect/target' + preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport + parentRoute: typeof rootRouteImport } '/not-found/': { id: '/not-found/' @@ -638,60 +854,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof NotFoundIndexRouteImport parentRoute: typeof NotFoundRouteRoute } - '/multi-cookie-redirect/': { - id: '/multi-cookie-redirect/' - path: '/multi-cookie-redirect' - fullPath: '/multi-cookie-redirect' - preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/search-params/loader-throws-redirect': { - id: '/search-params/loader-throws-redirect' - path: '/loader-throws-redirect' - fullPath: '/search-params/loader-throws-redirect' - preLoaderRoute: typeof SearchParamsLoaderThrowsRedirectRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/search-params/default': { - id: '/search-params/default' - path: '/default' - fullPath: '/search-params/default' - preLoaderRoute: typeof SearchParamsDefaultRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/redirect/$target': { - id: '/redirect/$target' - path: '/redirect/$target' - fullPath: '/redirect/$target' - preLoaderRoute: typeof RedirectTargetRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/not-found/via-loader': { - id: '/not-found/via-loader' - path: '/via-loader' - fullPath: '/not-found/via-loader' - preLoaderRoute: typeof NotFoundViaLoaderRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-head': { - id: '/not-found/via-head' - path: '/via-head' - fullPath: '/not-found/via-head' - preLoaderRoute: typeof NotFoundViaHeadRouteImport + '/not-found/parent-boundary': { + id: '/not-found/parent-boundary' + path: '/parent-boundary' + fullPath: '/not-found/parent-boundary' + preLoaderRoute: typeof NotFoundParentBoundaryRouteRouteImport parentRoute: typeof NotFoundRouteRoute } '/not-found/via-beforeLoad': { @@ -701,26 +868,201 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport parentRoute: typeof NotFoundRouteRoute } - '/multi-cookie-redirect/target': { - id: '/multi-cookie-redirect/target' - path: '/multi-cookie-redirect/target' - fullPath: '/multi-cookie-redirect/target' - preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport + '/not-found/via-beforeLoad-target-root': { + id: '/not-found/via-beforeLoad-target-root' + path: '/via-beforeLoad-target-root' + fullPath: '/not-found/via-beforeLoad-target-root' + preLoaderRoute: typeof NotFoundViaBeforeLoadTargetRootRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/not-found/via-loader': { + id: '/not-found/via-loader' + path: '/via-loader' + fullPath: '/not-found/via-loader' + preLoaderRoute: typeof NotFoundViaLoaderRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/raw-stream/': { + id: '/raw-stream/' + path: '/' + fullPath: '/raw-stream/' + preLoaderRoute: typeof RawStreamIndexRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/client-call': { + id: '/raw-stream/client-call' + path: '/client-call' + fullPath: '/raw-stream/client-call' + preLoaderRoute: typeof RawStreamClientCallRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-binary-hint': { + id: '/raw-stream/ssr-binary-hint' + path: '/ssr-binary-hint' + fullPath: '/raw-stream/ssr-binary-hint' + preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-mixed': { + id: '/raw-stream/ssr-mixed' + path: '/ssr-mixed' + fullPath: '/raw-stream/ssr-mixed' + preLoaderRoute: typeof RawStreamSsrMixedRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-multiple': { + id: '/raw-stream/ssr-multiple' + path: '/ssr-multiple' + fullPath: '/raw-stream/ssr-multiple' + preLoaderRoute: typeof RawStreamSsrMultipleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-single': { + id: '/raw-stream/ssr-single' + path: '/ssr-single' + fullPath: '/raw-stream/ssr-single' + preLoaderRoute: typeof RawStreamSsrSingleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-text-hint': { + id: '/raw-stream/ssr-text-hint' + path: '/ssr-text-hint' + fullPath: '/raw-stream/ssr-text-hint' + preLoaderRoute: typeof RawStreamSsrTextHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport parentRoute: typeof rootRouteImport } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/redirect/$target': { + id: '/redirect/$target' + path: '/redirect/$target' + fullPath: '/redirect/$target' + preLoaderRoute: typeof RedirectTargetRouteImport parentRoute: typeof rootRouteImport } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute + '/search-params/': { + id: '/search-params/' + path: '/' + fullPath: '/search-params/' + preLoaderRoute: typeof SearchParamsIndexRouteImport + parentRoute: typeof SearchParamsRouteRoute + } + '/search-params/default': { + id: '/search-params/default' + path: '/default' + fullPath: '/search-params/default' + preLoaderRoute: typeof SearchParamsDefaultRouteImport + parentRoute: typeof SearchParamsRouteRoute + } + '/search-params/loader-throws-redirect': { + id: '/search-params/loader-throws-redirect' + path: '/loader-throws-redirect' + fullPath: '/search-params/loader-throws-redirect' + preLoaderRoute: typeof SearchParamsLoaderThrowsRedirectRouteImport + parentRoute: typeof SearchParamsRouteRoute + } + '/specialChars/$param': { + id: '/specialChars/$param' + path: '/$param' + fullPath: '/specialChars/$param' + preLoaderRoute: typeof SpecialCharsParamRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/hash': { + id: '/specialChars/hash' + path: '/hash' + fullPath: '/specialChars/hash' + preLoaderRoute: typeof SpecialCharsHashRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/malformed': { + id: '/specialChars/malformed' + path: '/malformed' + fullPath: '/specialChars/malformed' + preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/search': { + id: '/specialChars/search' + path: '/search' + fullPath: '/specialChars/search' + preLoaderRoute: typeof SpecialCharsSearchRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/대한민국': { + id: '/specialChars/대한민국' + path: '/대한민국' + fullPath: '/specialChars/대한민국' + preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/not-found/parent-boundary/via-beforeLoad': { + id: '/not-found/parent-boundary/via-beforeLoad' + path: '/via-beforeLoad' + fullPath: '/not-found/parent-boundary/via-beforeLoad' + preLoaderRoute: typeof NotFoundParentBoundaryViaBeforeLoadRouteImport + parentRoute: typeof NotFoundParentBoundaryRouteRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } '/redirect/$target/': { id: '/redirect/$target/' @@ -729,13 +1071,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetIndexRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/via-loader': { - id: '/redirect/$target/via-loader' - path: '/via-loader' - fullPath: '/redirect/$target/via-loader' - preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport - parentRoute: typeof RedirectTargetRoute - } '/redirect/$target/via-beforeLoad': { id: '/redirect/$target/via-beforeLoad' path: '/via-beforeLoad' @@ -743,55 +1078,34 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetViaBeforeLoadRouteImport parentRoute: typeof RedirectTargetRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/redirect/$target/via-loader': { + id: '/redirect/$target/via-loader' + path: '/via-loader' + fullPath: '/redirect/$target/via-loader' + preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport + parentRoute: typeof RedirectTargetRoute } - '/api/users/$userId': { - id: '/api/users/$userId' - path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + '/specialChars/malformed/$param': { + id: '/specialChars/malformed/$param' + path: '/$param' + fullPath: '/specialChars/malformed/$param' + preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/specialChars/malformed/search': { + id: '/specialChars/malformed/search' + path: '/search' + fullPath: '/specialChars/malformed/search' + preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute } '/redirect/$target/serverFn/': { id: '/redirect/$target/serverFn/' path: '/serverFn' - fullPath: '/redirect/$target/serverFn' + fullPath: '/redirect/$target/serverFn/' preLoaderRoute: typeof RedirectTargetServerFnIndexRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/serverFn/via-useServerFn': { - id: '/redirect/$target/serverFn/via-useServerFn' - path: '/serverFn/via-useServerFn' - fullPath: '/redirect/$target/serverFn/via-useServerFn' - preLoaderRoute: typeof RedirectTargetServerFnViaUseServerFnRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/serverFn/via-loader': { - id: '/redirect/$target/serverFn/via-loader' - path: '/serverFn/via-loader' - fullPath: '/redirect/$target/serverFn/via-loader' - preLoaderRoute: typeof RedirectTargetServerFnViaLoaderRouteImport - parentRoute: typeof RedirectTargetRoute - } '/redirect/$target/serverFn/via-beforeLoad': { id: '/redirect/$target/serverFn/via-beforeLoad' path: '/serverFn/via-beforeLoad' @@ -799,19 +1113,51 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport parentRoute: typeof RedirectTargetRoute } + '/redirect/$target/serverFn/via-loader': { + id: '/redirect/$target/serverFn/via-loader' + path: '/serverFn/via-loader' + fullPath: '/redirect/$target/serverFn/via-loader' + preLoaderRoute: typeof RedirectTargetServerFnViaLoaderRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/serverFn/via-useServerFn': { + id: '/redirect/$target/serverFn/via-useServerFn' + path: '/serverFn/via-useServerFn' + fullPath: '/redirect/$target/serverFn/via-useServerFn' + preLoaderRoute: typeof RedirectTargetServerFnViaUseServerFnRouteImport + parentRoute: typeof RedirectTargetRoute + } } } +interface NotFoundParentBoundaryRouteRouteChildren { + NotFoundParentBoundaryViaBeforeLoadRoute: typeof NotFoundParentBoundaryViaBeforeLoadRoute +} + +const NotFoundParentBoundaryRouteRouteChildren: NotFoundParentBoundaryRouteRouteChildren = + { + NotFoundParentBoundaryViaBeforeLoadRoute: + NotFoundParentBoundaryViaBeforeLoadRoute, + } + +const NotFoundParentBoundaryRouteRouteWithChildren = + NotFoundParentBoundaryRouteRoute._addFileChildren( + NotFoundParentBoundaryRouteRouteChildren, + ) + interface NotFoundRouteRouteChildren { + NotFoundParentBoundaryRouteRoute: typeof NotFoundParentBoundaryRouteRouteWithChildren NotFoundViaBeforeLoadRoute: typeof NotFoundViaBeforeLoadRoute - NotFoundViaHeadRoute: typeof NotFoundViaHeadRoute + NotFoundViaBeforeLoadTargetRootRoute: typeof NotFoundViaBeforeLoadTargetRootRoute NotFoundViaLoaderRoute: typeof NotFoundViaLoaderRoute NotFoundIndexRoute: typeof NotFoundIndexRoute } const NotFoundRouteRouteChildren: NotFoundRouteRouteChildren = { + NotFoundParentBoundaryRouteRoute: + NotFoundParentBoundaryRouteRouteWithChildren, NotFoundViaBeforeLoadRoute: NotFoundViaBeforeLoadRoute, - NotFoundViaHeadRoute: NotFoundViaHeadRoute, + NotFoundViaBeforeLoadTargetRootRoute: NotFoundViaBeforeLoadTargetRootRoute, NotFoundViaLoaderRoute: NotFoundViaLoaderRoute, NotFoundIndexRoute: NotFoundIndexRoute, } @@ -835,6 +1181,42 @@ const SearchParamsRouteRouteChildren: SearchParamsRouteRouteChildren = { const SearchParamsRouteRouteWithChildren = SearchParamsRouteRoute._addFileChildren(SearchParamsRouteRouteChildren) +interface SpecialCharsMalformedRouteRouteChildren { + SpecialCharsMalformedParamRoute: typeof SpecialCharsMalformedParamRoute + SpecialCharsMalformedSearchRoute: typeof SpecialCharsMalformedSearchRoute +} + +const SpecialCharsMalformedRouteRouteChildren: SpecialCharsMalformedRouteRouteChildren = + { + SpecialCharsMalformedParamRoute: SpecialCharsMalformedParamRoute, + SpecialCharsMalformedSearchRoute: SpecialCharsMalformedSearchRoute, + } + +const SpecialCharsMalformedRouteRouteWithChildren = + SpecialCharsMalformedRouteRoute._addFileChildren( + SpecialCharsMalformedRouteRouteChildren, + ) + +interface SpecialCharsRouteRouteChildren { + SpecialCharsMalformedRouteRoute: typeof SpecialCharsMalformedRouteRouteWithChildren + SpecialCharsParamRoute: typeof SpecialCharsParamRoute + SpecialCharsHashRoute: typeof SpecialCharsHashRoute + SpecialCharsSearchRoute: typeof SpecialCharsSearchRoute + SpecialCharsChar45824Char54620Char48124Char44397Route: typeof SpecialCharsChar45824Char54620Char48124Char44397Route +} + +const SpecialCharsRouteRouteChildren: SpecialCharsRouteRouteChildren = { + SpecialCharsMalformedRouteRoute: SpecialCharsMalformedRouteRouteWithChildren, + SpecialCharsParamRoute: SpecialCharsParamRoute, + SpecialCharsHashRoute: SpecialCharsHashRoute, + SpecialCharsSearchRoute: SpecialCharsSearchRoute, + SpecialCharsChar45824Char54620Char48124Char44397Route: + SpecialCharsChar45824Char54620Char48124Char44397Route, +} + +const SpecialCharsRouteRouteWithChildren = + SpecialCharsRouteRoute._addFileChildren(SpecialCharsRouteRouteChildren) + interface LayoutLayout2RouteChildren { LayoutLayout2LayoutARoute: typeof LayoutLayout2LayoutARoute LayoutLayout2LayoutBRoute: typeof LayoutLayout2LayoutBRoute @@ -872,6 +1254,30 @@ const PostsRouteChildren: PostsRouteChildren = { const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) +interface RawStreamRouteChildren { + RawStreamClientCallRoute: typeof RawStreamClientCallRoute + RawStreamSsrBinaryHintRoute: typeof RawStreamSsrBinaryHintRoute + RawStreamSsrMixedRoute: typeof RawStreamSsrMixedRoute + RawStreamSsrMultipleRoute: typeof RawStreamSsrMultipleRoute + RawStreamSsrSingleRoute: typeof RawStreamSsrSingleRoute + RawStreamSsrTextHintRoute: typeof RawStreamSsrTextHintRoute + RawStreamIndexRoute: typeof RawStreamIndexRoute +} + +const RawStreamRouteChildren: RawStreamRouteChildren = { + RawStreamClientCallRoute: RawStreamClientCallRoute, + RawStreamSsrBinaryHintRoute: RawStreamSsrBinaryHintRoute, + RawStreamSsrMixedRoute: RawStreamSsrMixedRoute, + RawStreamSsrMultipleRoute: RawStreamSsrMultipleRoute, + RawStreamSsrSingleRoute: RawStreamSsrSingleRoute, + RawStreamSsrTextHintRoute: RawStreamSsrTextHintRoute, + RawStreamIndexRoute: RawStreamIndexRoute, +} + +const RawStreamRouteWithChildren = RawStreamRoute._addFileChildren( + RawStreamRouteChildren, +) + interface UsersRouteChildren { UsersUserIdRoute: typeof UsersUserIdRoute UsersIndexRoute: typeof UsersIndexRoute @@ -926,16 +1332,16 @@ const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, NotFoundRouteRoute: NotFoundRouteRouteWithChildren, SearchParamsRouteRoute: SearchParamsRouteRouteWithChildren, + SpecialCharsRouteRoute: SpecialCharsRouteRouteWithChildren, LayoutRoute: LayoutRouteWithChildren, DeferredRoute: DeferredRoute, InlineScriptsRoute: InlineScriptsRoute, LinksRoute: LinksRoute, PostsRoute: PostsRouteWithChildren, + RawStreamRoute: RawStreamRouteWithChildren, ScriptsRoute: ScriptsRoute, StreamRoute: StreamRoute, UsersRoute: UsersRouteWithChildren, - Char45824Char54620Char48124Char44397Route: - Char45824Char54620Char48124Char44397Route, ApiUsersRoute: ApiUsersRouteWithChildren, MultiCookieRedirectTargetRoute: MultiCookieRedirectTargetRoute, RedirectTargetRoute: RedirectTargetRouteWithChildren, diff --git a/e2e/vue-start/basic/src/routes/__root.tsx b/e2e/vue-start/basic/src/routes/__root.tsx index eddd6cf154..9da2c581fe 100644 --- a/e2e/vue-start/basic/src/routes/__root.tsx +++ b/e2e/vue-start/basic/src/routes/__root.tsx @@ -1,19 +1,135 @@ /// +import { defineComponent } from 'vue' import { Body, + ClientOnly, HeadContent, Html, Link, Outlet, Scripts, createRootRoute, + useRouterState, } from '@tanstack/vue-router' import { TanStackRouterDevtoolsInProd } from '@tanstack/vue-router-devtools' import { NotFound } from '~/components/NotFound' -import appCss from '~/styles/app.css?url' +import '~/styles/app.css' import { seo } from '~/utils/seo' +const RootComponent = defineComponent({ + setup() { + const routerState = useRouterState({ + select: (state) => ({ isLoading: state.isLoading, status: state.status }), + }) + return () => ( + + + + + +
+ + Home + {' '} + + Posts + {' '} + + Users + {' '} + + Layout + {' '} + + Scripts + {' '} + + Inline Scripts + {' '} + + Deferred + {' '} + + redirect + {' '} + + Raw Stream + {' '} + + This Route Does Not Exist + +
+ + + + +
This is an inline styled div
+ + + + + ) + }, +}) + export const Route = createRootRoute({ head: () => ({ meta: [ @@ -28,7 +144,6 @@ export const Route = createRootRoute({ }), ], links: [ - { rel: 'stylesheet', href: appCss }, { rel: 'apple-touch-icon', sizes: '180x180', @@ -61,99 +176,11 @@ export const Route = createRootRoute({ }, ], }), - errorComponent: (props) =>

{props.error.stack}

, + errorComponent: (props) => ( +

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

+ ), notFoundComponent: () => , component: RootComponent, }) - -function RootComponent() { - return ( - - - - - -
- - Home - {' '} - - Posts - {' '} - - Users - {' '} - - Layout - {' '} - - Scripts - {' '} - - Inline Scripts - {' '} - - Deferred - {' '} - - redirect - {' '} - - This Route Does Not Exist - -
- -
This is an inline styled div
- - - - - ) -} diff --git a/e2e/vue-start/basic/src/routes/api/users.$userId.ts b/e2e/vue-start/basic/src/routes/api/users.$userId.ts index 5c55163c7f..24938d51c2 100644 --- a/e2e/vue-start/basic/src/routes/api/users.$userId.ts +++ b/e2e/vue-start/basic/src/routes/api/users.$userId.ts @@ -1,32 +1,27 @@ import { createFileRoute } from '@tanstack/vue-router' -import { json } from '@tanstack/vue-start' import type { User } from '~/utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} - export const Route = createFileRoute('/api/users/$userId')({ server: { handlers: { GET: async ({ params, request }) => { console.info(`Fetching users by id=${params.userId}... @`, request.url) try { - const res = await fetch(`${queryURL}/users/${params.userId}`) + const res = await fetch( + `https://jsonplaceholder.typicode.com/users/${params.userId}`, + ) if (!res.ok) { throw new Error('Failed to fetch user') } const user = (await res.json()) as User - return json({ + return Response.json({ id: user.id, name: user.name, email: user.email, }) } catch (e) { console.error(e) - return json({ error: 'User not found' }, { status: 404 }) + return Response.json({ error: 'User not found' }, { status: 404 }) } }, }, diff --git a/e2e/vue-start/basic/src/routes/api/users.ts b/e2e/vue-start/basic/src/routes/api/users.ts index 5f2ab51270..c6045977b8 100644 --- a/e2e/vue-start/basic/src/routes/api/users.ts +++ b/e2e/vue-start/basic/src/routes/api/users.ts @@ -1,5 +1,5 @@ import { createFileRoute } from '@tanstack/vue-router' -import { createMiddleware, json } from '@tanstack/vue-start' +import { createMiddleware } from '@tanstack/vue-start' import type { User } from '~/utils/users' const userLoggerMiddleware = createMiddleware().server( @@ -38,25 +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(`${queryURL}/users`) + const res = await fetch('https://jsonplaceholder.typicode.com/users') if (!res.ok) { throw new Error('Failed to fetch users') } const data = (await res.json()) as Array const list = data.slice(0, 10) - return json( + return Response.json( list.map((u) => ({ id: u.id, name: u.name, email: u.email })), ) }, diff --git a/e2e/vue-start/basic/src/routes/deferred.tsx b/e2e/vue-start/basic/src/routes/deferred.tsx index 4f8fcd600c..18aae161ab 100644 --- a/e2e/vue-start/basic/src/routes/deferred.tsx +++ b/e2e/vue-start/basic/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/vue-start' import { Suspense, ref, defineComponent } from 'vue' const personServerFn = createServerFn({ method: 'GET' }) - .inputValidator((data: { name: string }) => data) + .validator((data: { name: string }) => data) .handler(({ data }) => { return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .inputValidator((data: { name: string }) => data) + .validator((data: { name: string }) => data) .handler(async ({ data }) => { await new Promise((r) => setTimeout(r, 1000)) return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/e2e/vue-start/basic/src/routes/not-found/index.tsx b/e2e/vue-start/basic/src/routes/not-found/index.tsx index 13cc6ee924..ecd12d1dad 100644 --- a/e2e/vue-start/basic/src/routes/not-found/index.tsx +++ b/e2e/vue-start/basic/src/routes/not-found/index.tsx @@ -1,9 +1,10 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/not-found/')({ - component: () => { +const RouteComponent = defineComponent({ + setup() { const preload = Route.useSearch({ select: (s) => s.preload }) - return ( + return () => (
-
- - via-head - -
) }, }) + +export const Route = createFileRoute('/not-found/')({ + component: RouteComponent, +}) diff --git a/e2e/vue-start/basic/src/routes/not-found/parent-boundary/route.tsx b/e2e/vue-start/basic/src/routes/not-found/parent-boundary/route.tsx new file mode 100644 index 0000000000..26823e5dcc --- /dev/null +++ b/e2e/vue-start/basic/src/routes/not-found/parent-boundary/route.tsx @@ -0,0 +1,31 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const ParentBoundaryNotFoundComponent = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + return () => ( +
+
+ {loaderData.value.parentLoaderData} +
+
+ ) + }, +}) + +export const Route = createFileRoute('/not-found/parent-boundary')({ + loader: () => ({ + parentLoaderData: 'ready', + }), + component: RouteComponent, + notFoundComponent: ParentBoundaryNotFoundComponent, +}) + +function RouteComponent() { + return ( +
+ +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/not-found/parent-boundary/via-beforeLoad.tsx b/e2e/vue-start/basic/src/routes/not-found/parent-boundary/via-beforeLoad.tsx new file mode 100644 index 0000000000..b2c111a5ac --- /dev/null +++ b/e2e/vue-start/basic/src/routes/not-found/parent-boundary/via-beforeLoad.tsx @@ -0,0 +1,19 @@ +import { createFileRoute, notFound } from '@tanstack/vue-router' +import { Route as ParentBoundaryRoute } from './route' + +export const Route = createFileRoute( + '/not-found/parent-boundary/via-beforeLoad', +)({ + beforeLoad: () => { + throw notFound({ routeId: ParentBoundaryRoute.id }) + }, + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+ Hello "/not-found/parent-boundary/via-beforeLoad"! +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/not-found/via-beforeLoad-target-root.tsx b/e2e/vue-start/basic/src/routes/not-found/via-beforeLoad-target-root.tsx new file mode 100644 index 0000000000..1663bdc0af --- /dev/null +++ b/e2e/vue-start/basic/src/routes/not-found/via-beforeLoad-target-root.tsx @@ -0,0 +1,16 @@ +import { createFileRoute, notFound, rootRouteId } from '@tanstack/vue-router' + +export const Route = createFileRoute('/not-found/via-beforeLoad-target-root')({ + beforeLoad: () => { + throw notFound({ routeId: rootRouteId }) + }, + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+ Hello "/not-found/via-beforeLoad-target-root"! +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/not-found/via-head.tsx b/e2e/vue-start/basic/src/routes/not-found/via-head.tsx deleted file mode 100644 index 41966ab429..0000000000 --- a/e2e/vue-start/basic/src/routes/not-found/via-head.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { createFileRoute, notFound } from '@tanstack/vue-router' - -export const Route = createFileRoute('/not-found/via-head')({ - head: () => { - throw notFound() - }, - component: RouteComponent, - notFoundComponent: () => { - return ( -
- Not Found "/not-found/via-head"! -
- ) - }, -}) - -function RouteComponent() { - return ( -
- Hello "/not-found/via-head"! -
- ) -} diff --git a/e2e/vue-start/basic/src/routes/posts.$postId.tsx b/e2e/vue-start/basic/src/routes/posts.$postId.tsx index 4d71080d64..edda7f0017 100644 --- a/e2e/vue-start/basic/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/basic/src/routes/posts.$postId.tsx @@ -1,9 +1,32 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '~/utils/posts' import { NotFound } from '~/components/NotFound' import { PostErrorComponent } from '~/components/PostErrorComponent' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + return () => ( +
+

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-start/basic/src/routes/raw-stream.tsx b/e2e/vue-start/basic/src/routes/raw-stream.tsx new file mode 100644 index 0000000000..ed404f7679 --- /dev/null +++ b/e2e/vue-start/basic/src/routes/raw-stream.tsx @@ -0,0 +1,70 @@ +import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/raw-stream')({ + component: RawStreamLayout, +}) + +function RawStreamLayout() { + return ( +
+

Raw Stream Tests

+ + + +
+ + +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/raw-stream/client-call.tsx b/e2e/vue-start/basic/src/routes/raw-stream/client-call.tsx new file mode 100644 index 0000000000..2aeb738487 --- /dev/null +++ b/e2e/vue-start/basic/src/routes/raw-stream/client-call.tsx @@ -0,0 +1,524 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { defineComponent, ref } from 'vue' +import { + TEST10_EXPECTED, + TEST11_EXPECTED, + TEST12_STREAM_A_EXPECTED, + TEST12_STREAM_B_EXPECTED, + TEST13_EXPECTED, + TEST14_STREAM_A_EXPECTED, + TEST14_STREAM_B_EXPECTED, + TEST14_STREAM_C_EXPECTED, + TEST7_EXPECTED, + TEST8_EXPECTED, + TEST9_EXPECTED, + binaryHintBinaryFn, + binaryHintTextFn, + burstPauseBurstFn, + collectBytes, + compareBytes, + consumeBinaryStream, + createStreamConsumer, + emptyStreamFn, + errorStreamFn, + interleavedStreamsFn, + jsonEndsFirstFn, + largeBinaryFn, + mixedStreamingFn, + multipleRawStreamsFn, + rawEndsFirstFn, + singleRawStreamFn, + textHintMixedFn, + textHintPureBinaryFn, + textHintPureTextFn, + threeStreamsFn, +} from '../../raw-stream-fns' + +const ClientCallTests = defineComponent({ + setup() { + const results = ref>({}) + const loading = ref>({}) + + const consumeStream = createStreamConsumer() + + const runTest = async ( + testName: string, + fn: () => Promise, + processor: (result: any) => Promise, + ) => { + loading.value = { ...loading.value, [testName]: true } + try { + const result = await fn() + const processed = await processor(result) + results.value = { ...results.value, [testName]: processed } + } catch (error) { + results.value = { + ...results.value, + [testName]: { error: String(error) }, + } + } finally { + loading.value = { ...loading.value, [testName]: false } + } + } + + return () => ( +
+

Client-Side Server Function Calls (RPC)

+

+ These tests invoke server functions directly from the client, using + the binary framing protocol for RawStream data. +

+ + {/* Test 1: Single Raw Stream */} +
+

Test 1: Single Raw Stream

+ +
+            {JSON.stringify(results.value.test1)}
+          
+
+ + {/* Test 2: Multiple Raw Streams */} +
+

Test 2: Multiple Raw Streams

+ +
+            {JSON.stringify(results.value.test2)}
+          
+
+ + {/* Test 3: JSON Ends First */} +
+

Test 3: JSON Ends Before Raw Stream

+ +
+            {JSON.stringify(results.value.test3)}
+          
+
+ + {/* Test 4: Raw Ends First */} +
+

Test 4: Raw Stream Ends Before JSON

+ +
+            {JSON.stringify(results.value.test4)}
+          
+
+ + {/* Test 5: Large Binary */} +
+

Test 5: Large Binary Data

+ +
+            {JSON.stringify(results.value.test5)}
+          
+
+ + {/* Test 6: Mixed Streaming */} +
+

Test 6: Mixed Streaming

+ +
+            {JSON.stringify(results.value.test6)}
+          
+
+ + {/* Hint Tests Section */} +

Hint Parameter Tests (RPC)

+

+ These tests verify that hint parameter works correctly for RPC calls. + Note: RPC always uses binary framing regardless of hint. +

+ + {/* Test 7: Text Hint with Pure Text */} +
+

Test 7: Text Hint - Pure Text

+ +
+            {JSON.stringify(results.value.test7)}
+          
+
+ + {/* Test 8: Text Hint with Pure Binary */} +
+

Test 8: Text Hint - Pure Binary

+ +
+            {JSON.stringify(results.value.test8)}
+          
+
+ + {/* Test 9: Text Hint with Mixed Content */} +
+

Test 9: Text Hint - Mixed Content

+ +
+            {JSON.stringify(results.value.test9)}
+          
+
+ + {/* Test 10: Binary Hint with Text Data */} +
+

Test 10: Binary Hint - Text Data

+ +
+            {JSON.stringify(results.value.test10)}
+          
+
+ + {/* Test 11: Binary Hint with Binary Data */} +
+

Test 11: Binary Hint - Binary Data

+ +
+            {JSON.stringify(results.value.test11)}
+          
+
+ + {/* Multiplexing Tests Section */} +

Multiplexing Tests (RPC)

+

+ These tests verify correct interleaving of multiple concurrent + streams. +

+ + {/* Test 12: Interleaved Streams */} +
+

Test 12: Interleaved Streams

+ +
+            {JSON.stringify(results.value.test12)}
+          
+
+ + {/* Test 13: Burst-Pause-Burst */} +
+

Test 13: Burst-Pause-Burst

+ +
+            {JSON.stringify(results.value.test13)}
+          
+
+ + {/* Test 14: Three Concurrent Streams */} +
+

Test 14: Three Concurrent Streams

+ +
+            {JSON.stringify(results.value.test14)}
+          
+
+ + {/* Edge Case Tests Section */} +

Edge Case Tests (RPC)

+

+ These tests verify edge cases like empty streams and error handling. +

+ + {/* Test 15: Empty Stream */} +
+

Test 15: Empty Stream

+ +
+            {JSON.stringify(results.value.test15)}
+          
+
+ + {/* Test 16: Stream Error */} +
+

Test 16: Stream Error

+ +
+            {JSON.stringify(results.value.test16)}
+          
+
+
+ ) + }, +}) + +export const Route = createFileRoute('/raw-stream/client-call')({ + component: ClientCallTests, +}) diff --git a/e2e/vue-start/basic/src/routes/raw-stream/index.tsx b/e2e/vue-start/basic/src/routes/raw-stream/index.tsx new file mode 100644 index 0000000000..76b7233c01 --- /dev/null +++ b/e2e/vue-start/basic/src/routes/raw-stream/index.tsx @@ -0,0 +1,74 @@ +import { Link, createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/raw-stream/')({ + component: RawStreamIndex, +}) + +function RawStreamIndex() { + return ( +
+

Select a test category above to begin testing.

+
    +
  • + + Client Calls + + - Test RawStream via direct server function calls (RPC) +
  • +
  • + + SSR Single + + - Test single RawStream from route loader (SSR) +
  • +
  • + + SSR Multiple + + - Test multiple RawStreams from route loader (SSR) +
  • +
  • + + SSR Mixed + + + {' '} + - Test RawStream mixed with deferred data from loader (SSR) + +
  • +
  • + + SSR Text Hint + + - Test RawStream with hint: 'text' from loader (SSR) +
  • +
  • + + SSR Binary Hint + + - Test RawStream with hint: 'binary' from loader (SSR) +
  • +
+
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/raw-stream/ssr-binary-hint.tsx b/e2e/vue-start/basic/src/routes/raw-stream/ssr-binary-hint.tsx new file mode 100644 index 0000000000..3ded9f67c6 --- /dev/null +++ b/e2e/vue-start/basic/src/routes/raw-stream/ssr-binary-hint.tsx @@ -0,0 +1,204 @@ +import { createFileRoute, useRouter } from '@tanstack/vue-router' +import { RawStream } from '@tanstack/vue-start' +import { defineComponent, onBeforeUnmount, onMounted, ref, watch } from 'vue' +import { + collectBytes, + compareBytes, + concatBytes, + createDelayedStream, + encode, +} from '../../raw-stream-fns' + +// Expected data - defined at module level for client-side verification +const TEXT_CHUNKS = [encode('Binary '), encode('hint '), encode('with text')] +const TEXT_EXPECTED = concatBytes(TEXT_CHUNKS) + +const BINARY_CHUNKS = [ + new Uint8Array([0x00, 0x01, 0x02, 0x03]), + new Uint8Array([0xff, 0xfe, 0xfd, 0xfc]), +] +const BINARY_EXPECTED = concatBytes(BINARY_CHUNKS) + +type TextMatch = { + match: boolean + mismatchIndex: number | null + actualLength: number + expectedLength: number + asText: string +} + +type BinaryMatch = { + match: boolean + mismatchIndex: number | null + actualLength: number + expectedLength: number +} + +const SSRBinaryHintTest = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + const router = useRouter() + const textMatch = ref(null) + const binaryMatch = ref(null) + const isLoading = ref(true) + const error = ref(null) + + let consumeRunId = 0 + const consumeHintStreams = ( + textData: ReadableStream | RawStream | undefined, + binaryData: ReadableStream | RawStream | undefined, + ) => { + if (!textData || !binaryData) { + return Promise.resolve() + } + const currentRun = ++consumeRunId + isLoading.value = true + error.value = null + return Promise.all([collectBytes(textData), collectBytes(binaryData)]) + .then(([textBytes, binaryBytes]) => { + if (currentRun !== consumeRunId) { + return + } + const textComp = compareBytes(textBytes, TEXT_EXPECTED) + const decoder = new TextDecoder() + textMatch.value = { + ...textComp, + actualLength: textBytes.length, + expectedLength: TEXT_EXPECTED.length, + asText: decoder.decode(textBytes), + } + const binaryComp = compareBytes(binaryBytes, BINARY_EXPECTED) + binaryMatch.value = { + ...binaryComp, + actualLength: binaryBytes.length, + expectedLength: BINARY_EXPECTED.length, + } + isLoading.value = false + }) + .catch((err) => { + if (currentRun !== consumeRunId) { + return + } + error.value = String(err) + isLoading.value = false + }) + } + + let stopWatcher: (() => void) | undefined + let lastStreams: + | [ + ReadableStream | RawStream, + ReadableStream | RawStream, + ] + | undefined + let didInvalidate = false + + onMounted(() => { + stopWatcher = watch( + () => [loaderData.value.textData, loaderData.value.binaryData], + ([textData, binaryData]) => { + if (!textData || !binaryData) { + return + } + if ( + lastStreams && + lastStreams[0] === textData && + lastStreams[1] === binaryData + ) { + return + } + lastStreams = [textData, binaryData] + void consumeHintStreams(textData, binaryData) + }, + { immediate: true }, + ) + + if (__TSR_PRERENDER__ && !didInvalidate) { + didInvalidate = true + void router.invalidate({ + filter: (match) => match.routeId === Route.id, + }) + } + }) + + onBeforeUnmount(() => { + stopWatcher?.() + }) + + return () => ( +
+

SSR Binary Hint Test

+

+ This route tests RawStream with hint: 'binary' from loader. Binary + hint always uses base64 encoding (default behavior). +

+ +
+
+ Message: {loaderData.value.message} +
+
+ Text Data: + {error.value + ? `Error: ${error.value}` + : isLoading.value + ? 'Loading...' + : textMatch.value?.asText} +
+
+ Text Bytes Match: + {isLoading.value + ? 'Loading...' + : textMatch.value?.match + ? 'true' + : 'false'} +
+
+ Binary Bytes Match: + {isLoading.value + ? 'Loading...' + : binaryMatch.value?.match + ? 'true' + : 'false'} +
+
+            {JSON.stringify({
+              message: loaderData.value.message,
+              textMatch: textMatch.value,
+              binaryMatch: binaryMatch.value,
+              isLoading: isLoading.value,
+              error: error.value,
+            })}
+          
+
+
+ ) + }, +}) + +export const Route = createFileRoute('/raw-stream/ssr-binary-hint')({ + loader: async () => { + // Text data with binary hint - should still use base64 (default behavior) + const textStream = createDelayedStream( + [encode('Binary '), encode('hint '), encode('with text')], + 30, + ) + + // Pure binary stream with binary hint + const binaryStream = createDelayedStream( + [ + new Uint8Array([0x00, 0x01, 0x02, 0x03]), + new Uint8Array([0xff, 0xfe, 0xfd, 0xfc]), + ], + 30, + ) + + return { + message: 'SSR Binary Hint Test', + textData: new RawStream(textStream, { hint: 'binary' }), + binaryData: new RawStream(binaryStream, { hint: 'binary' }), + } + }, + shouldReload: __TSR_PRERENDER__, + component: SSRBinaryHintTest, +}) diff --git a/e2e/vue-start/basic/src/routes/raw-stream/ssr-mixed.tsx b/e2e/vue-start/basic/src/routes/raw-stream/ssr-mixed.tsx new file mode 100644 index 0000000000..1a311a2015 --- /dev/null +++ b/e2e/vue-start/basic/src/routes/raw-stream/ssr-mixed.tsx @@ -0,0 +1,150 @@ +import { Await, createFileRoute, useRouter } from '@tanstack/vue-router' +import { RawStream } from '@tanstack/vue-start' +import { + Suspense, + defineComponent, + onBeforeUnmount, + onMounted, + ref, + watch, +} from 'vue' +import { + createDelayedStream, + createStreamConsumer, + encode, +} from '../../raw-stream-fns' + +const SSRMixedTest = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + const router = useRouter() + const streamContent = ref('') + const isConsuming = ref(true) + const error = ref(null) + + let consumeRunId = 0 + const consumeRawStream = ( + rawData: ReadableStream | RawStream | undefined, + ) => { + if (!rawData) { + return Promise.resolve() + } + const consumeStream = createStreamConsumer() + const currentRun = ++consumeRunId + isConsuming.value = true + error.value = null + return consumeStream(rawData) + .then((content) => { + if (currentRun !== consumeRunId) { + return + } + streamContent.value = content + isConsuming.value = false + }) + .catch((err) => { + if (currentRun !== consumeRunId) { + return + } + error.value = String(err) + isConsuming.value = false + }) + } + + let stopWatcher: (() => void) | undefined + let lastRawData: ReadableStream | RawStream | undefined + let didInvalidate = false + + onMounted(() => { + stopWatcher = watch( + () => loaderData.value.rawData, + (rawData) => { + if (!rawData || rawData === lastRawData) { + return + } + lastRawData = rawData + void consumeRawStream(rawData) + }, + { immediate: true }, + ) + + if (__TSR_PRERENDER__ && !didInvalidate) { + didInvalidate = true + void router.invalidate({ + filter: (match) => match.routeId === Route.id, + }) + } + }) + + onBeforeUnmount(() => { + stopWatcher?.() + }) + + return () => ( +
+

SSR Mixed Streaming Test

+

+ This route returns a mix of immediate data, deferred promises, and + RawStream from its loader. +

+ +
+
+ Immediate: {loaderData.value.immediate} +
+
+ Deferred: + + {{ + default: () => ( + {value}} + /> + ), + fallback: () => Loading deferred..., + }} + +
+
+ Stream Content: + {error.value + ? `Error: ${error.value}` + : isConsuming.value + ? 'Loading...' + : streamContent.value} +
+
+            {JSON.stringify({
+              immediate: loaderData.value.immediate,
+              streamContent: streamContent.value,
+              isConsuming: isConsuming.value,
+              error: error.value,
+            })}
+          
+
+
+ ) + }, +}) + +export const Route = createFileRoute('/raw-stream/ssr-mixed')({ + loader: () => { + const rawStream = createDelayedStream( + [encode('mixed-ssr-1'), encode('mixed-ssr-2')], + 50, + ) + + // Deferred promise that resolves after a delay + const deferredData = new Promise((resolve) => + setTimeout(() => resolve('deferred-ssr-value'), 100), + ) + + return { + immediate: 'immediate-ssr-value', + deferred: deferredData, + rawData: new RawStream(rawStream), + } + }, + shouldReload: __TSR_PRERENDER__, + component: SSRMixedTest, +}) diff --git a/e2e/vue-start/basic/src/routes/raw-stream/ssr-multiple.tsx b/e2e/vue-start/basic/src/routes/raw-stream/ssr-multiple.tsx new file mode 100644 index 0000000000..5a58e68437 --- /dev/null +++ b/e2e/vue-start/basic/src/routes/raw-stream/ssr-multiple.tsx @@ -0,0 +1,151 @@ +import { createFileRoute, useRouter } from '@tanstack/vue-router' +import { RawStream } from '@tanstack/vue-start' +import { defineComponent, onBeforeUnmount, onMounted, ref, watch } from 'vue' +import { + createDelayedStream, + createStreamConsumer, + encode, +} from '../../raw-stream-fns' + +const SSRMultipleTest = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + const router = useRouter() + const firstContent = ref('') + const secondContent = ref('') + const isConsuming = ref(true) + const error = ref(null) + + let consumeRunId = 0 + const consumeRawStreams = ( + first: ReadableStream | RawStream | undefined, + second: ReadableStream | RawStream | undefined, + ) => { + if (!first || !second) { + return Promise.resolve() + } + const consumeStream = createStreamConsumer() + const currentRun = ++consumeRunId + isConsuming.value = true + error.value = null + return Promise.all([consumeStream(first), consumeStream(second)]) + .then(([content1, content2]) => { + if (currentRun !== consumeRunId) { + return + } + firstContent.value = content1 + secondContent.value = content2 + isConsuming.value = false + }) + .catch((err) => { + if (currentRun !== consumeRunId) { + return + } + error.value = String(err) + isConsuming.value = false + }) + } + + let stopWatcher: (() => void) | undefined + let lastStreams: + | [ + ReadableStream | RawStream, + ReadableStream | RawStream, + ] + | undefined + let didInvalidate = false + + onMounted(() => { + stopWatcher = watch( + () => [loaderData.value.first, loaderData.value.second], + ([first, second]) => { + if (!first || !second) { + return + } + if ( + lastStreams && + lastStreams[0] === first && + lastStreams[1] === second + ) { + return + } + lastStreams = [first, second] + void consumeRawStreams(first, second) + }, + { immediate: true }, + ) + + if (__TSR_PRERENDER__ && !didInvalidate) { + didInvalidate = true + void router.invalidate({ + filter: (match) => match.routeId === Route.id, + }) + } + }) + + onBeforeUnmount(() => { + stopWatcher?.() + }) + + return () => ( +
+

SSR Multiple RawStreams Test

+

+ This route returns multiple RawStreams from its loader. Each stream is + independently serialized during SSR. +

+ +
+
+ Message: {loaderData.value.message} +
+
+ First Stream: + {error.value + ? `Error: ${error.value}` + : isConsuming.value + ? 'Loading...' + : firstContent.value} +
+
+ Second Stream: + {error.value + ? `Error: ${error.value}` + : isConsuming.value + ? 'Loading...' + : secondContent.value} +
+
+            {JSON.stringify({
+              message: loaderData.value.message,
+              firstContent: firstContent.value,
+              secondContent: secondContent.value,
+              isConsuming: isConsuming.value,
+              error: error.value,
+            })}
+          
+
+
+ ) + }, +}) + +export const Route = createFileRoute('/raw-stream/ssr-multiple')({ + loader: async () => { + const stream1 = createDelayedStream( + [encode('multi-1a'), encode('multi-1b')], + 30, + ) + const stream2 = createDelayedStream( + [encode('multi-2a'), encode('multi-2b')], + 50, + ) + return { + message: 'SSR Multiple Streams Test', + first: new RawStream(stream1), + second: new RawStream(stream2), + } + }, + shouldReload: __TSR_PRERENDER__, + component: SSRMultipleTest, +}) diff --git a/e2e/vue-start/basic/src/routes/raw-stream/ssr-single.tsx b/e2e/vue-start/basic/src/routes/raw-stream/ssr-single.tsx new file mode 100644 index 0000000000..ddb47fe179 --- /dev/null +++ b/e2e/vue-start/basic/src/routes/raw-stream/ssr-single.tsx @@ -0,0 +1,133 @@ +import { createFileRoute, useRouter } from '@tanstack/vue-router' +import { RawStream } from '@tanstack/vue-start' +import { defineComponent, onBeforeUnmount, onMounted, ref, watch } from 'vue' +import { + createDelayedStream, + createStreamConsumer, + encode, +} from '../../raw-stream-fns' + +const SSRSingleTest = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + const router = useRouter() + const streamContent = ref('') + const isConsuming = ref(true) + const error = ref(null) + + let consumeRunId = 0 + const consumeRawStream = ( + rawData: ReadableStream | RawStream | undefined, + ) => { + if (!rawData) { + return Promise.resolve() + } + const consumeStream = createStreamConsumer() + const currentRun = ++consumeRunId + isConsuming.value = true + error.value = null + return consumeStream(rawData) + .then((content) => { + if (currentRun !== consumeRunId) { + return + } + streamContent.value = content + isConsuming.value = false + }) + .catch((err) => { + if (currentRun !== consumeRunId) { + return + } + error.value = String(err) + isConsuming.value = false + }) + } + + let stopWatcher: (() => void) | undefined + let lastRawData: ReadableStream | RawStream | undefined + let didInvalidate = false + + onMounted(() => { + stopWatcher = watch( + () => loaderData.value.rawData, + (rawData) => { + if (!rawData || rawData === lastRawData) { + return + } + lastRawData = rawData + void consumeRawStream(rawData) + }, + { immediate: true }, + ) + + if (__TSR_PRERENDER__ && !didInvalidate) { + didInvalidate = true + void router.invalidate({ + filter: (match) => match.routeId === Route.id, + }) + } + }) + + onBeforeUnmount(() => { + stopWatcher?.() + }) + + return () => ( +
+

SSR Single RawStream Test

+

+ This route returns a single RawStream from its loader. The stream is + serialized during SSR using base64 encoding. +

+ +
+
+ Message: {loaderData.value.message} +
+
+ Has Timestamp:{' '} + {typeof loaderData.value.timestamp === 'number' ? 'true' : 'false'} +
+
+ Stream Content: + {error.value + ? `Error: ${error.value}` + : isConsuming.value + ? 'Loading...' + : streamContent.value} +
+
+ RawData Type: {typeof loaderData.value.rawData} | hasStream: + {loaderData.value.rawData && 'getReader' in loaderData.value.rawData + ? 'true' + : 'false'} +
+
+            {JSON.stringify({
+              message: loaderData.value.message,
+              streamContent: streamContent.value,
+              isConsuming: isConsuming.value,
+              error: error.value,
+            })}
+          
+
+
+ ) + }, +}) + +export const Route = createFileRoute('/raw-stream/ssr-single')({ + loader: async () => { + const stream = createDelayedStream( + [encode('ssr-chunk1'), encode('ssr-chunk2'), encode('ssr-chunk3')], + 50, + ) + return { + message: 'SSR Single Stream Test', + timestamp: Date.now(), + rawData: new RawStream(stream), + } + }, + shouldReload: __TSR_PRERENDER__, + component: SSRSingleTest, +}) diff --git a/e2e/vue-start/basic/src/routes/raw-stream/ssr-text-hint.tsx b/e2e/vue-start/basic/src/routes/raw-stream/ssr-text-hint.tsx new file mode 100644 index 0000000000..aad51b2971 --- /dev/null +++ b/e2e/vue-start/basic/src/routes/raw-stream/ssr-text-hint.tsx @@ -0,0 +1,258 @@ +import { createFileRoute, useRouter } from '@tanstack/vue-router' +import { RawStream } from '@tanstack/vue-start' +import { defineComponent, onBeforeUnmount, onMounted, ref, watch } from 'vue' +import { + collectBytes, + compareBytes, + concatBytes, + createDelayedStream, + encode, +} from '../../raw-stream-fns' + +// Expected data - defined at module level for client-side verification +const PURE_TEXT_CHUNKS = [ + encode('Hello '), + encode('World '), + encode('from SSR!'), +] +const PURE_TEXT_EXPECTED = concatBytes(PURE_TEXT_CHUNKS) + +const MIXED_CHUNKS = [ + encode('Valid text'), + new Uint8Array([0xff, 0xfe, 0x80, 0x90]), // Invalid UTF-8 + encode(' more text'), +] +const MIXED_EXPECTED = concatBytes(MIXED_CHUNKS) + +// Pure binary data (invalid UTF-8) - must use base64 fallback +const PURE_BINARY_CHUNKS = [ + new Uint8Array([0xff, 0xfe, 0x00, 0x01, 0x80, 0x90]), + new Uint8Array([0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0]), +] +const PURE_BINARY_EXPECTED = concatBytes(PURE_BINARY_CHUNKS) + +type TextMatch = { + match: boolean + mismatchIndex: number | null + actualLength: number + expectedLength: number + asText: string +} + +type BinaryMatch = { + match: boolean + mismatchIndex: number | null + actualLength: number + expectedLength: number +} + +const SSRTextHintTest = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + const router = useRouter() + const pureTextMatch = ref(null) + const mixedMatch = ref(null) + const pureBinaryMatch = ref(null) + const isLoading = ref(true) + const error = ref(null) + + let consumeRunId = 0 + const consumeHintStreams = ( + pureText: ReadableStream | RawStream | undefined, + mixedContent: ReadableStream | RawStream | undefined, + pureBinary: ReadableStream | RawStream | undefined, + ) => { + if (!pureText || !mixedContent || !pureBinary) { + return Promise.resolve() + } + const currentRun = ++consumeRunId + isLoading.value = true + error.value = null + return Promise.all([ + collectBytes(pureText), + collectBytes(mixedContent), + collectBytes(pureBinary), + ]) + .then(([pureBytes, mixedBytes, pureBinaryBytes]) => { + if (currentRun !== consumeRunId) { + return + } + const pureComp = compareBytes(pureBytes, PURE_TEXT_EXPECTED) + const decoder = new TextDecoder() + pureTextMatch.value = { + ...pureComp, + actualLength: pureBytes.length, + expectedLength: PURE_TEXT_EXPECTED.length, + asText: decoder.decode(pureBytes), + } + const mixedComp = compareBytes(mixedBytes, MIXED_EXPECTED) + mixedMatch.value = { + ...mixedComp, + actualLength: mixedBytes.length, + expectedLength: MIXED_EXPECTED.length, + } + const pureBinaryComp = compareBytes( + pureBinaryBytes, + PURE_BINARY_EXPECTED, + ) + pureBinaryMatch.value = { + ...pureBinaryComp, + actualLength: pureBinaryBytes.length, + expectedLength: PURE_BINARY_EXPECTED.length, + } + isLoading.value = false + }) + .catch((err) => { + if (currentRun !== consumeRunId) { + return + } + error.value = String(err) + isLoading.value = false + }) + } + + let stopWatcher: (() => void) | undefined + let lastStreams: + | [ + ReadableStream | RawStream, + ReadableStream | RawStream, + ReadableStream | RawStream, + ] + | undefined + let didInvalidate = false + + onMounted(() => { + stopWatcher = watch( + () => [ + loaderData.value.pureText, + loaderData.value.mixedContent, + loaderData.value.pureBinary, + ], + ([pureText, mixedContent, pureBinary]) => { + if (!pureText || !mixedContent || !pureBinary) { + return + } + if ( + lastStreams && + lastStreams[0] === pureText && + lastStreams[1] === mixedContent && + lastStreams[2] === pureBinary + ) { + return + } + lastStreams = [pureText, mixedContent, pureBinary] + void consumeHintStreams(pureText, mixedContent, pureBinary) + }, + { immediate: true }, + ) + + if (__TSR_PRERENDER__ && !didInvalidate) { + didInvalidate = true + void router.invalidate({ + filter: (match) => match.routeId === Route.id, + }) + } + }) + + onBeforeUnmount(() => { + stopWatcher?.() + }) + + return () => ( +
+

SSR Text Hint Test

+

+ This route tests RawStream with hint: 'text' from loader. Text hint + optimizes for UTF-8 content but falls back to base64 for invalid + UTF-8. +

+ +
+
+ Message: {loaderData.value.message} +
+
+ Pure Text: + {error.value + ? `Error: ${error.value}` + : isLoading.value + ? 'Loading...' + : pureTextMatch.value?.asText} +
+
+ Pure Text Bytes Match: + {isLoading.value + ? 'Loading...' + : pureTextMatch.value?.match + ? 'true' + : 'false'} +
+
+ Mixed Content Bytes Match: + {isLoading.value + ? 'Loading...' + : mixedMatch.value?.match + ? 'true' + : 'false'} +
+
+ Pure Binary Bytes Match: + {isLoading.value + ? 'Loading...' + : pureBinaryMatch.value?.match + ? 'true' + : 'false'} +
+
+            {JSON.stringify({
+              message: loaderData.value.message,
+              pureTextMatch: pureTextMatch.value,
+              mixedMatch: mixedMatch.value,
+              pureBinaryMatch: pureBinaryMatch.value,
+              isLoading: isLoading.value,
+              error: error.value,
+            })}
+          
+
+
+ ) + }, +}) + +export const Route = createFileRoute('/raw-stream/ssr-text-hint')({ + loader: async () => { + // Pure text stream - should use UTF-8 encoding with text hint + const textStream = createDelayedStream( + [encode('Hello '), encode('World '), encode('from SSR!')], + 30, + ) + + // Mixed content stream - text hint should use UTF-8 for valid text, base64 for binary + const mixedStream = createDelayedStream( + [ + encode('Valid text'), + new Uint8Array([0xff, 0xfe, 0x80, 0x90]), // Invalid UTF-8 + encode(' more text'), + ], + 30, + ) + + // Pure binary stream - text hint must fallback to base64 for all chunks + const pureBinaryStream = createDelayedStream( + [ + new Uint8Array([0xff, 0xfe, 0x00, 0x01, 0x80, 0x90]), + new Uint8Array([0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0]), + ], + 30, + ) + + return { + message: 'SSR Text Hint Test', + pureText: new RawStream(textStream, { hint: 'text' }), + mixedContent: new RawStream(mixedStream, { hint: 'text' }), + pureBinary: new RawStream(pureBinaryStream, { hint: 'text' }), + } + }, + shouldReload: __TSR_PRERENDER__, + component: SSRTextHintTest, +}) diff --git a/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx b/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx index a8c3c75b1f..e39bda5bcf 100644 --- a/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx +++ b/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx @@ -1,9 +1,10 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/redirect/$target/')({ - component: () => { +const RouteComponent = defineComponent({ + setup() { const preload = Route.useSearch({ select: (s) => s.preload }) - return ( + return () => (
{ +const RouteComponent = defineComponent({ + setup() { const params = Route.useParams() - return ( + return () => (

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

SearchParams

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

SearchParams

-
{search.value.step}
-
- ) - }, + component: RouteComponent, }) diff --git a/e2e/vue-start/basic/src/routes/specialChars/$param.tsx b/e2e/vue-start/basic/src/routes/specialChars/$param.tsx new file mode 100644 index 0000000000..ec315ede1f --- /dev/null +++ b/e2e/vue-start/basic/src/routes/specialChars/$param.tsx @@ -0,0 +1,18 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const RouteComponent = defineComponent({ + setup() { + const params = Route.useParams() + return () => ( +
+ Hello "/specialChars/$param":{' '} + {params.value.param} +
+ ) + }, +}) + +export const Route = createFileRoute('/specialChars/$param')({ + component: RouteComponent, +}) diff --git a/e2e/vue-start/basic/src/routes/specialChars/hash.tsx b/e2e/vue-start/basic/src/routes/specialChars/hash.tsx new file mode 100644 index 0000000000..d1cb9041ef --- /dev/null +++ b/e2e/vue-start/basic/src/routes/specialChars/hash.tsx @@ -0,0 +1,39 @@ +import { createFileRoute, useLocation } from '@tanstack/vue-router' +import { defineComponent, ref } from 'vue' + +const RouteComponent = defineComponent({ + setup() { + const l = useLocation() + const toggleHashValue = ref(false) + + const toggle = () => { + toggleHashValue.value = !toggleHashValue.value + } + + return () => ( +
+
Hello "/specialChars/hash"!
+ +
+ {toggleHashValue.value && ( +
+ Hash Value{l.value.hash} +
+ )} +
+
+ ) + }, +}) + +export const Route = createFileRoute('/specialChars/hash')({ + component: RouteComponent, +}) diff --git a/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx b/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx new file mode 100644 index 0000000000..2b19e7e36e --- /dev/null +++ b/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx @@ -0,0 +1,20 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const RouteComponent = defineComponent({ + setup() { + const params = Route.useParams() + return () => ( +
+ Hello "/specialChars/malformed/$param":{' '} + + {params.value.param} + +
+ ) + }, +}) + +export const Route = createFileRoute('/specialChars/malformed/$param')({ + component: RouteComponent, +}) diff --git a/e2e/vue-start/basic/src/routes/specialChars/malformed/route.tsx b/e2e/vue-start/basic/src/routes/specialChars/malformed/route.tsx new file mode 100644 index 0000000000..1121505377 --- /dev/null +++ b/e2e/vue-start/basic/src/routes/specialChars/malformed/route.tsx @@ -0,0 +1,29 @@ +import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/specialChars/malformed')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+
Hello "/specialChars/malformed"!
+ + malformed path param + {' '} + + malformed search param + {' '} +
+ +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx b/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx new file mode 100644 index 0000000000..8d6ad5b1dd --- /dev/null +++ b/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx @@ -0,0 +1,24 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import z from 'zod' + +const RouteComponent = defineComponent({ + setup() { + const search = Route.useSearch() + return () => ( +
+ Hello "/specialChars/malformed/search"! + + {search.value.searchParam} + +
+ ) + }, +}) + +export const Route = createFileRoute('/specialChars/malformed/search')({ + validateSearch: z.object({ + searchParam: z.string(), + }), + component: RouteComponent, +}) diff --git a/e2e/vue-start/basic/src/routes/specialChars/route.tsx b/e2e/vue-start/basic/src/routes/specialChars/route.tsx new file mode 100644 index 0000000000..86dc29d39a --- /dev/null +++ b/e2e/vue-start/basic/src/routes/specialChars/route.tsx @@ -0,0 +1,79 @@ +import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/specialChars')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
+
Hello "/specialChars"!
+ + Unicode + {' '} + + Unicode param + {' '} + + Unicode search param + {' '} + + Unicode Hash + {' '} + + Unicode Hash abc + {' '} + + Malformed paths + {' '} +
+ +
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/specialChars/search.tsx b/e2e/vue-start/basic/src/routes/specialChars/search.tsx new file mode 100644 index 0000000000..b4e022639d --- /dev/null +++ b/e2e/vue-start/basic/src/routes/specialChars/search.tsx @@ -0,0 +1,24 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import z from 'zod' + +const RouteComponent = defineComponent({ + setup() { + const search = Route.useSearch() + return () => ( +
+ Hello "/specialChars/search"! + + {search.value.searchParam} + +
+ ) + }, +}) + +export const Route = createFileRoute('/specialChars/search')({ + validateSearch: z.object({ + searchParam: z.string(), + }), + component: RouteComponent, +}) diff --git a/e2e/vue-start/basic/src/routes/specialChars/대한민국.tsx b/e2e/vue-start/basic/src/routes/specialChars/대한민국.tsx new file mode 100644 index 0000000000..90bd312056 --- /dev/null +++ b/e2e/vue-start/basic/src/routes/specialChars/대한민국.tsx @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/specialChars/대한민국')({ + component: KoreaComponent, +}) + +function KoreaComponent() { + return ( +
+ Test +

+ Hello /specialChars/대한민국 +

+

This is a route with a non-ASCII path.

+
+ ) +} diff --git a/e2e/vue-start/basic/src/routes/users.$userId.tsx b/e2e/vue-start/basic/src/routes/users.$userId.tsx index 420b7e4a50..76340cf9fb 100644 --- a/e2e/vue-start/basic/src/routes/users.$userId.tsx +++ b/e2e/vue-start/basic/src/routes/users.$userId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' @@ -6,6 +7,18 @@ import type { User } from '~/utils/users' import { NotFound } from '~/components/NotFound' import { UserErrorComponent } from '~/components/UserErrorComponent' +const UserComponent = defineComponent({ + setup() { + const user = Route.useLoaderData() + return () => ( +
+

{user.value.name}

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

{user.value.name}

-
{user.value.email}
-
- ) -} diff --git a/e2e/vue-start/basic/src/routes/users.tsx b/e2e/vue-start/basic/src/routes/users.tsx index 1e0b297dd2..3d8ef31598 100644 --- a/e2e/vue-start/basic/src/routes/users.tsx +++ b/e2e/vue-start/basic/src/routes/users.tsx @@ -1,9 +1,41 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { getRouterInstance } from '@tanstack/vue-start' import axios from 'redaxios' import type { User } from '~/utils/users' +const UsersComponent = defineComponent({ + setup() { + const users = Route.useLoaderData() + return () => ( +
+
    + {[ + ...users.value, + { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, + ].map((user) => ( +
  • + +
    {user.name}
    + +
  • + ))} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/users')({ loader: async () => { const router = await getRouterInstance() @@ -16,33 +48,3 @@ export const Route = createFileRoute('/users')({ }, component: UsersComponent, }) - -function UsersComponent() { - const users = Route.useLoaderData() - - return ( -
-
    - {[ - ...users.value, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => ( -
  • - -
    {user.name}
    - -
  • - ))} -
-
- -
- ) -} diff --git a/e2e/vue-start/basic/src/routes/대한민국.tsx b/e2e/vue-start/basic/src/routes/대한민국.tsx deleted file mode 100644 index 16196a6bda..0000000000 --- a/e2e/vue-start/basic/src/routes/대한민국.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/vue-router' - -export const Route = createFileRoute('/대한민국')({ - component: KoreaComponent, -}) - -function KoreaComponent() { - return ( -
-

대한민국

-

This is a route with a non-ASCII path.

-
- ) -} diff --git a/e2e/vue-start/basic/src/styles/app.css b/e2e/vue-start/basic/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/e2e/vue-start/basic/src/styles/app.css +++ b/e2e/vue-start/basic/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-start/basic/src/utils/posts.tsx b/e2e/vue-start/basic/src/utils/posts.tsx index a193bbc7af..d8e2dc7450 100644 --- a/e2e/vue-start/basic/src/utils/posts.tsx +++ b/e2e/vue-start/basic/src/utils/posts.tsx @@ -8,18 +8,12 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} - export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) + .validator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios - .get(`${queryURL}/posts/${postId}`) + .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -36,7 +30,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>(`${queryURL}/posts`) + .get>('https://jsonplaceholder.typicode.com/posts') .then((r) => r.data.slice(0, 10)) }, ) diff --git a/e2e/vue-start/basic/src/utils/users.tsx b/e2e/vue-start/basic/src/utils/users.tsx index 46be4b1580..7ba645b383 100644 --- a/e2e/vue-start/basic/src/utils/users.tsx +++ b/e2e/vue-start/basic/src/utils/users.tsx @@ -3,7 +3,3 @@ export type User = { name: string email: string } - -const PORT = process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/basic/src/vite-env.d.ts b/e2e/vue-start/basic/src/vite-env.d.ts index 4e6e90c846..4da6234c8a 100644 --- a/e2e/vue-start/basic/src/vite-env.d.ts +++ b/e2e/vue-start/basic/src/vite-env.d.ts @@ -2,10 +2,11 @@ interface ImportMetaEnv { readonly VITE_NODE_ENV: string - readonly VITE_EXTERNAL_PORT: string readonly VITE_SERVER_PORT: string } interface ImportMeta { readonly env: ImportMetaEnv } + +declare const __TSR_PRERENDER__: boolean diff --git a/e2e/vue-start/basic/tests/fixture-api.spec.ts b/e2e/vue-start/basic/tests/fixture-api.spec.ts new file mode 100644 index 0000000000..6c9b26dc4c --- /dev/null +++ b/e2e/vue-start/basic/tests/fixture-api.spec.ts @@ -0,0 +1,11 @@ +import { expect, test } from '@playwright/test' + +test('server API receives canned users without a fixture listener', async ({ + request, +}) => { + const response = await request.get('/api/users') + expect(response.ok()).toBe(true) + const users = await response.json() + expect(users).toHaveLength(10) + expect(users[0]).toMatchObject({ id: 1, name: 'Leanne Graham' }) +}) diff --git a/e2e/vue-start/basic/tests/navigation.spec.ts b/e2e/vue-start/basic/tests/navigation.spec.ts index 0a64f58417..ed0b0d3a4d 100644 --- a/e2e/vue-start/basic/tests/navigation.spec.ts +++ b/e2e/vue-start/basic/tests/navigation.spec.ts @@ -3,7 +3,7 @@ import { test } from '@tanstack/router-e2e-utils' test.use({ whitelistErrors: [ - /Failed to load resource: the server responded with a status of 404/, + 'Failed to load resource: the server responded with a status of 404', ], }) test('Navigating to post', async ({ page }) => { diff --git a/e2e/vue-start/basic/tests/not-found.spec.ts b/e2e/vue-start/basic/tests/not-found.spec.ts index 1bed8e991c..cfc60fe5e4 100644 --- a/e2e/vue-start/basic/tests/not-found.spec.ts +++ b/e2e/vue-start/basic/tests/not-found.spec.ts @@ -1,15 +1,14 @@ import { expect } from '@playwright/test' import combinateImport from 'combinate' import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from '../tests/utils/isSpaMode' +import { isSpaMode } from './utils/isSpaMode' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport test.use({ whitelistErrors: [ - /Failed to load resource: the server responded with a status of 404/, - 'NotFound error during hydration for routeId', + 'Failed to load resource: the server responded with a status of 404', ], }) test.describe('not-found', () => { @@ -25,8 +24,7 @@ test.describe('not-found', () => { test.describe('throw notFound()', () => { const navigationTestMatrix = combinate({ - // TODO beforeLoad! - thrower: [/* 'beforeLoad',*/ 'head', 'loader'] as const, + thrower: ['beforeLoad', 'loader'] as const, preload: [false, true] as const, }) @@ -55,9 +53,7 @@ test.describe('not-found', () => { }) }) const directVisitTestMatrix = combinate({ - // TODO beforeLoad! - - thrower: [/* 'beforeLoad',*/ 'head', 'loader'] as const, + thrower: ['beforeLoad', 'loader'] as const, }) directVisitTestMatrix.forEach(({ thrower }) => { @@ -72,5 +68,34 @@ test.describe('not-found', () => { ).not.toBeInViewport() }) }) + + test('direct visit: child beforeLoad notFound renders parent boundary with parent loader data', async ({ + page, + }) => { + await page.goto('/not-found/parent-boundary/via-beforeLoad') + await page.waitForLoadState('networkidle') + + await expect( + page.getByTestId('parent-boundary-notFound-component'), + ).toBeInViewport() + await expect(page.getByTestId('parent-loader-data')).toHaveText('ready') + await expect( + page.getByTestId('parent-boundary-child-route-component'), + ).not.toBeInViewport() + }) + + test('direct visit: beforeLoad notFound with routeId targets root boundary', async ({ + page, + }) => { + await page.goto('/not-found/via-beforeLoad-target-root') + await page.waitForLoadState('networkidle') + + await expect( + page.getByTestId('default-not-found-component'), + ).toBeInViewport() + await expect( + page.getByTestId('via-beforeLoad-target-root-route-component'), + ).not.toBeInViewport() + }) }) }) diff --git a/e2e/vue-start/basic/tests/params.spec.ts b/e2e/vue-start/basic/tests/params.spec.ts deleted file mode 100644 index de8423406b..0000000000 --- a/e2e/vue-start/basic/tests/params.spec.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { expect } from '@playwright/test' - -import { test } from '@tanstack/router-e2e-utils' - -test.beforeEach(async ({ page }) => { - await page.goto('/') -}) - -test.use({ - whitelistErrors: [ - /Failed to load resource: the server responded with a status of 404/, - ], -}) -test.describe('Unicode route rendering', () => { - test('should render non-latin route correctly', async ({ page, baseURL }) => { - await page.goto('/대한민국') - - await expect(page.locator('body')).toContainText('대한민국') - - expect(page.url()).toBe(`${baseURL}/%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD`) - }) -}) diff --git a/e2e/vue-start/basic/tests/prerendering.spec.ts b/e2e/vue-start/basic/tests/prerendering.spec.ts index 7718fe86ef..ddcf720a4c 100644 --- a/e2e/vue-start/basic/tests/prerendering.spec.ts +++ b/e2e/vue-start/basic/tests/prerendering.spec.ts @@ -4,20 +4,26 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' import { isPrerender } from './utils/isPrerender' +const distDir = join( + process.cwd(), + process.env.E2E_DIST_DIR ?? 'dist', + 'client', +) + test.describe('Prerender Static Path Discovery', () => { test.skip(!isPrerender, 'Skipping since not in prerender mode') test.describe('Build Output Verification', () => { test('should automatically discover and prerender static routes', () => { // Check that static routes were automatically discovered and prerendered - const distDir = join(process.cwd(), 'dist', 'client') - // These static routes should be automatically discovered and prerendered expect(existsSync(join(distDir, 'index.html'))).toBe(true) expect(existsSync(join(distDir, 'posts/index.html'))).toBe(true) expect(existsSync(join(distDir, 'deferred/index.html'))).toBe(true) expect(existsSync(join(distDir, 'scripts/index.html'))).toBe(true) expect(existsSync(join(distDir, 'inline-scripts/index.html'))).toBe(true) - expect(existsSync(join(distDir, '대한민국/index.html'))).toBe(true) + expect( + existsSync(join(distDir, 'specialChars/대한민국/index.html')), + ).toBe(true) // Pathless layouts should NOT be prerendered (they start with _) expect(existsSync(join(distDir, '_layout', 'index.html'))).toBe(false) // /_layout @@ -32,7 +38,6 @@ test.describe('Prerender Static Path Discovery', () => { test.describe('Static Files Verification', () => { test('should contain prerendered content in posts.html', () => { - const distDir = join(process.cwd(), 'dist', 'client') expect(existsSync(join(distDir, 'posts/index.html'))).toBe(true) // "Select a post." should be in the prerendered HTML diff --git a/e2e/vue-start/basic/tests/redirect.spec.ts b/e2e/vue-start/basic/tests/redirect.spec.ts index b52ce026af..8e6ceba5b9 100644 --- a/e2e/vue-start/basic/tests/redirect.spec.ts +++ b/e2e/vue-start/basic/tests/redirect.spec.ts @@ -1,22 +1,27 @@ import queryString from 'node:querystring' import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' import combinateImport from 'combinate' -import { - getDummyServerPort, - getTestServerPort, - test, -} from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } -import { isSpaMode } from '../tests/utils/isSpaMode' -import { isPreview } from '../tests/utils/isPreview' +import type { Page } from '@playwright/test' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const PORT = await getTestServerPort( - `${packageJson.name}${isSpaMode ? '_spa' : ''}${isPreview ? '_preview' : ''}`, -) -const EXTERNAL_HOST_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` +const POSTS_URL = `http://localhost:${PORT}/posts` + +async function waitForRouterIdle(page: Page) { + await expect(page.getByTestId('router-isLoading')).toHaveText('false') + await expect(page.getByTestId('router-status')).toHaveText('idle') +} + +async function waitForPostsIndex(page: Page) { + await page.waitForURL(POSTS_URL) + expect(page.url()).toBe(POSTS_URL) + await waitForRouterIdle(page) + await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() +} test.describe('redirects', () => { const internalNavigationTestMatrix = combinate({ @@ -37,7 +42,7 @@ test.describe('redirects', () => { `via-${thrower}${reloadDocument ? '-reloadDocument' : ''}`, ) - await page.waitForLoadState('networkidle') + await waitForRouterIdle(page) let requestHappened = false const requestPromise = new Promise((resolve) => { @@ -65,11 +70,7 @@ test.describe('redirects', () => { await link.click() - const url = `http://localhost:${PORT}/posts` - - await page.waitForURL(url) - expect(page.url()).toBe(url) - await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() + await waitForPostsIndex(page) expect(fullPageLoad).toBe(reloadDocument) }) }, @@ -86,12 +87,7 @@ test.describe('redirects', () => { }) => { await page.goto(`/redirect/internal/via-${thrower}`) - const url = `http://localhost:${PORT}/posts` - - await page.waitForURL(url) - expect(page.url()).toBe(url) - await page.waitForLoadState('networkidle') - await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() + await waitForPostsIndex(page) }) }) @@ -105,12 +101,12 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, }) if (scenario === 'navigate') { await page.goto(`/redirect/external?${q}`) - await page.waitForLoadState('networkidle') + await waitForRouterIdle(page) const link = page.getByTestId(`via-${thrower}`) await link.focus() await link.click() @@ -118,7 +114,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -139,13 +135,13 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, reloadDocument, }) if (scenario === 'navigate') { await page.goto(`/redirect/${target}/serverFn?${q}`) - await page.waitForLoadState('networkidle') + await waitForRouterIdle(page) const link = page.getByTestId( `via-${thrower}${reloadDocument ? '-reloadDocument' : ''}`, ) @@ -158,13 +154,11 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = - target === 'internal' - ? `http://localhost:${PORT}/posts` - : `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal' && scenario === 'navigate') { + await waitForRouterIdle(page) await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() expect(fullPageLoad).toBe(reloadDocument) } @@ -182,13 +176,13 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, reloadDocument, }) await page.goto(`/redirect/${target}/serverFn/via-useServerFn?${q}`) - await page.waitForLoadState('networkidle') + await waitForRouterIdle(page) const button = page.getByTestId('redirect-on-click') @@ -199,13 +193,11 @@ test.describe('redirects', () => { await button.click() - const url = - target === 'internal' - ? `http://localhost:${PORT}/posts` - : `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal') { + await waitForRouterIdle(page) await expect(page.getByTestId('PostsIndexComponent')).toBeInViewport() expect(fullPageLoad).toBe(reloadDocument) } diff --git a/e2e/vue-start/basic/tests/search-params.spec.ts b/e2e/vue-start/basic/tests/search-params.spec.ts index 74c1aa54dc..cdf5a21b4a 100644 --- a/e2e/vue-start/basic/tests/search-params.spec.ts +++ b/e2e/vue-start/basic/tests/search-params.spec.ts @@ -1,6 +1,6 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from 'tests/utils/isSpaMode' +import { isSpaMode } from './utils/isSpaMode' import { isPrerender } from './utils/isPrerender' import type { Response } from '@playwright/test' diff --git a/e2e/vue-start/basic/tests/setup/global.setup.ts b/e2e/vue-start/basic/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/basic/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/basic/tests/setup/global.teardown.ts b/e2e/vue-start/basic/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/basic/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/basic/tests/special-characters.spec.ts b/e2e/vue-start/basic/tests/special-characters.spec.ts new file mode 100644 index 0000000000..284097d72b --- /dev/null +++ b/e2e/vue-start/basic/tests/special-characters.spec.ts @@ -0,0 +1,246 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import { isSpaMode } from './utils/isSpaMode' + +test.use({ + whitelistErrors: [ + /Failed to load resource: the server responded with a status of 404/, + ], +}) +test.describe('Unicode route rendering', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/specialChars') + }) + + test('should render non-latin route correctly with direct navigation', async ({ + page, + baseURL, + }) => { + await page.goto('/specialChars/대한민국') + await page.waitForURL( + `${baseURL}/specialChars/%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD`, + ) + + await expect(page.getByTestId('special-non-latin-heading')).toBeInViewport() + }) + + test('should render non-latin route correctly during router navigation', async ({ + page, + baseURL, + }) => { + const nonLatinLink = page.getByTestId('special-non-latin-link') + + await nonLatinLink.click() + await page.waitForURL( + `${baseURL}/specialChars/%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD`, + ) + + await expect(page.getByTestId('special-non-latin-heading')).toBeInViewport() + }) + + test.describe('Special characters in path params', () => { + test('should render route correctly on direct navigation', async ({ + page, + baseURL, + }) => { + await page.goto('/specialChars/대|') + await page.waitForURL(`${baseURL}/specialChars/%EB%8C%80%7C`) + + const param = await page.getByTestId('special-param').textContent() + + expect(param).toBe('대|') + }) + + test('should render route correctly on router navigation', async ({ + page, + baseURL, + }) => { + const link = page.getByTestId('special-param-link') + + await link.click() + await page.waitForURL(`${baseURL}/specialChars/%EB%8C%80%7C`) + + const param = await page.getByTestId('special-param').textContent() + + expect(param).toBe('대|') + }) + }) + + test.describe('Special characters in search params', () => { + test('should render route correctly on direct navigation', async ({ + page, + baseURL, + }) => { + await page.goto('/specialChars/search?searchParam=대|') + + await page.waitForURL( + `${baseURL}/specialChars/search?searchParam=%EB%8C%80|`, + ) + + const searchParam = await page + .getByTestId('special-search-param') + .textContent() + + expect(searchParam).toBe('대|') + }) + + test('should render route correctly on router navigation', async ({ + page, + baseURL, + }) => { + const link = page.getByTestId('special-searchParam-link') + + await link.click() + await page.waitForURL( + `${baseURL}/specialChars/search?searchParam=%EB%8C%80%7C`, + ) + + const searchParam = await page + .getByTestId('special-search-param') + .textContent() + + expect(searchParam).toBe('대|') + }) + }) + + test.describe('Special characters in url hash', () => { + test('should render route correctly on direct navigation', async ({ + page, + baseURL, + }) => { + await expect(page.getByTestId('special-hash-link-1')).not.toContainClass( + 'font-bold', + ) + await expect(page.getByTestId('special-hash-link-2')).not.toContainClass( + 'font-bold', + ) + + await page.goto('/specialChars/hash#대|') + + await page.waitForURL(`${baseURL}/specialChars/hash#%EB%8C%80|`) + await page.waitForLoadState('load') + + await expect(page.getByTestId('special-hash-heading')).toBeInViewport() + + await expect(page.getByTestId('special-hash-link-1')).toContainClass( + 'font-bold', + ) + + await expect(page.getByTestId('special-hash-link-2')).not.toContainClass( + 'font-bold', + ) + + await page.getByTestId('toggle-hash-button').click() + + const hashValue = await page.getByTestId('special-hash').textContent() + + expect(hashValue).toBe('대|') + }) + + test('should render route correctly on router navigation', async ({ + page, + baseURL, + }) => { + await expect(page.getByTestId('special-hash-link-1')).not.toContainClass( + 'font-bold', + ) + + await expect(page.getByTestId('special-hash-link-2')).not.toContainClass( + 'font-bold', + ) + + const link = page.getByTestId('special-hash-link-1') + + await link.click() + + await page.waitForURL(`${baseURL}/specialChars/hash#%EB%8C%80|`) + await page.waitForLoadState('load') + + await expect(page.getByTestId('special-hash-heading')).toBeInViewport() + + await expect(page.getByTestId('special-hash-link-1')).toContainClass( + 'font-bold', + ) + + await expect(page.getByTestId('special-hash-link-2')).not.toContainClass( + 'font-bold', + ) + + await page.getByTestId('toggle-hash-button').click() + + const hashValue = await page.getByTestId('special-hash').textContent() + + expect(hashValue).toBe('대|') + }) + }) + + test.describe('malformed paths', () => { + const malformedPathnames = [ + '/specialChars/malformed/%E0%A4', + '/specialChars/malformed/%80', + '/specialChars/malformed/%FF', + ] + + test.use({ + whitelistErrors: [ + 'Failed to load resource: the server responded with a status of 404', + 'Failed to load resource: the server responded with a status of 400 (Bad Request)', + ], + }) + + for (const pathname of malformedPathnames) { + test(`un-matched malformed path "${pathname}" should return bad request on direct navigation`, async ({ + page, + }) => { + const res = await page.goto(pathname) + + await page.waitForLoadState(`load`) + + // in spa mode this is caught and handled at server level + if (!isSpaMode) { + expect(res!.status()).toBe(400) + } else { + expect(res!.status()).toBe(400) + } + }) + } + + test('malformed path params should return not found on router link', async ({ + page, + baseURL, + }) => { + await page.goto('/specialChars/malformed') + await page.waitForURL(`${baseURL}/specialChars/malformed`) + + const link = page.getByTestId('special-malformed-path-link') + + await link.click() + await page.waitForLoadState('load') + + await expect( + page.getByTestId('default-not-found-component'), + ).toBeInViewport() + }) + + test('un-matched malformed paths should return not found on direct navigation in search params', async ({ + page, + baseURL, + }) => { + await page.goto('/specialChars/malformed/search?searchParam=%E0%A4') + + await page.waitForURL( + `${baseURL}/specialChars/malformed/search?searchParam=%E0%A4`, + ) + + await expect( + page.getByTestId('special-malformed-search-param'), + ).toBeInViewport() + + const searchParam = await page + .getByTestId('special-malformed-search-param') + .textContent() + + expect(searchParam).toBe('�') + }) + }) +}) diff --git a/e2e/vue-start/basic/tests/utils/getPackageName.ts b/e2e/vue-start/basic/tests/utils/getPackageName.ts new file mode 100644 index 0000000000..6bd2e0499e --- /dev/null +++ b/e2e/vue-start/basic/tests/utils/getPackageName.ts @@ -0,0 +1,16 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' + +let packageName: string | undefined + +export function getPackageName() { + if (!packageName) { + const packageJson = JSON.parse( + readFileSync(join(process.cwd(), 'package.json'), 'utf-8'), + ) as { name: string } + + packageName = packageJson.name + } + + return packageName +} diff --git a/e2e/vue-start/basic/tsconfig.json b/e2e/vue-start/basic/tsconfig.json index 6d933a5b2c..1b2ac7b943 100644 --- a/e2e/vue-start/basic/tsconfig.json +++ b/e2e/vue-start/basic/tsconfig.json @@ -9,12 +9,12 @@ "moduleResolution": "Bundler", "lib": ["DOM", "DOM.Iterable", "ES2022"], "isolatedModules": true, + "allowImportingTsExtensions": true, "resolveJsonModule": true, "skipLibCheck": true, "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/basic/vite.config.ts b/e2e/vue-start/basic/vite.config.ts index 17faf2630f..6fe8d5d194 100644 --- a/e2e/vue-start/basic/vite.config.ts +++ b/e2e/vue-start/basic/vite.config.ts @@ -1,9 +1,9 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' import { isSpaMode } from './tests/utils/isSpaMode' import { isPrerender } from './tests/utils/isPrerender' +import tailwindcss from '@tailwindcss/vite' const spaModeConfiguration = { enabled: true, @@ -19,9 +19,10 @@ const prerenderConfiguration = { '/this-route-does-not-exist', '/redirect', '/i-do-not-exist', - '/not-found/via-beforeLoad', - '/not-found/via-head', - '/not-found/via-loader', + '/not-found', + '/specialChars/search', + '/specialChars/hash', + '/specialChars/malformed', '/search-params', // search-param routes have dynamic content based on query params '/transition', '/users', @@ -29,14 +30,21 @@ const prerenderConfiguration = { maxRedirects: 100, } +const outDir = process.env.E2E_DIST_DIR ?? 'dist' + export default defineConfig({ + resolve: { tsconfigPaths: true }, + build: { + outDir, + }, server: { port: 3000, }, + define: { + __TSR_PRERENDER__: JSON.stringify(isPrerender), + }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), + tailwindcss(), tanstackStart({ spa: isSpaMode ? spaModeConfiguration : undefined, prerender: isPrerender ? prerenderConfiguration : undefined, diff --git a/e2e/vue-start/css-modules/.devcontainer/devcontainer.json b/e2e/vue-start/css-modules/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/css-modules/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/css-modules/.gitignore b/e2e/vue-start/css-modules/.gitignore new file mode 100644 index 0000000000..950326609c --- /dev/null +++ b/e2e/vue-start/css-modules/.gitignore @@ -0,0 +1,7 @@ +node_modules +dist +.routeTree.gen.ts +src/routeTree.gen.ts +test-results +playwright-report +port*.txt diff --git a/e2e/vue-start/css-modules/.prettierignore b/e2e/vue-start/css-modules/.prettierignore new file mode 100644 index 0000000000..083bdb7c4c --- /dev/null +++ b/e2e/vue-start/css-modules/.prettierignore @@ -0,0 +1 @@ +src/routeTree.gen.ts diff --git a/e2e/vue-start/css-modules/package.json b/e2e/vue-start/css-modules/package.json new file mode 100644 index 0000000000..3671774644 --- /dev/null +++ b/e2e/vue-start/css-modules/package.json @@ -0,0 +1,32 @@ +{ + "name": "tanstack-vue-start-e2e-css-modules", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "vite dev --port 3000", + "dev:e2e": "vite dev --port $PORT", + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "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" + }, + "dependencies": { + "@tanstack/vue-router": "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", + "sass": "^1.97.2", + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" + } +} diff --git a/e2e/vue-start/css-modules/playwright.config.ts b/e2e/vue-start/css-modules/playwright.config.ts new file mode 100644 index 0000000000..a50ac5ae63 --- /dev/null +++ b/e2e/vue-start/css-modules/playwright.config.ts @@ -0,0 +1,41 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const mode = process.env.MODE ?? 'prod' +const isDev = mode === 'dev' +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + + globalSetup: './tests/setup/global.setup.ts', + + use: { + baseURL, + }, + + webServer: { + command: isDev + ? `pnpm dev:e2e --port 0` + : `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + env: { + VITE_NODE_ENV: 'test', + PORT: String(PORT), + }, + }, + + projects: [ + { + name: 'chromium', + use: { + ...devices['Desktop Chrome'], + }, + }, + ], +}) diff --git a/e2e/vue-start/css-modules/src/router.tsx b/e2e/vue-start/css-modules/src/router.tsx new file mode 100644 index 0000000000..7394b7042e --- /dev/null +++ b/e2e/vue-start/css-modules/src/router.tsx @@ -0,0 +1,12 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + const router = createRouter({ + routeTree, + scrollRestoration: true, + defaultPreload: false, + }) + + return router +} diff --git a/e2e/vue-start/css-modules/src/routes/__root.tsx b/e2e/vue-start/css-modules/src/routes/__root.tsx new file mode 100644 index 0000000000..9e292654bc --- /dev/null +++ b/e2e/vue-start/css-modules/src/routes/__root.tsx @@ -0,0 +1,69 @@ +import { + Body, + HeadContent, + Html, + Link, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + ], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + +
+ +
+ + + + ) +} diff --git a/e2e/vue-start/css-modules/src/routes/index.tsx b/e2e/vue-start/css-modules/src/routes/index.tsx new file mode 100644 index 0000000000..5c52a6e342 --- /dev/null +++ b/e2e/vue-start/css-modules/src/routes/index.tsx @@ -0,0 +1,25 @@ +import { createFileRoute } from '@tanstack/vue-router' +import '~/styles/global.css' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return ( +
+

CSS Collection Test - Global CSS

+

This page tests that global CSS is collected and served during SSR.

+ +
+
+ Global CSS Applied +
+
+ This container should have a blue background, white text, and rounded + corners even with JavaScript disabled. +
+
+
+ ) +} diff --git a/e2e/vue-start/css-modules/src/routes/modules.tsx b/e2e/vue-start/css-modules/src/routes/modules.tsx new file mode 100644 index 0000000000..4c1a655ed8 --- /dev/null +++ b/e2e/vue-start/css-modules/src/routes/modules.tsx @@ -0,0 +1,28 @@ +/// +import { createFileRoute } from '@tanstack/vue-router' +import styles from '~/styles/card.module.css' + +export const Route = createFileRoute('/modules')({ + component: Modules, +}) + +function Modules() { + return ( +
+

CSS Collection Test - CSS Modules

+

+ This page tests that CSS modules are collected and served during SSR. +

+ +
+
+ CSS Module Applied +
+
+ This card should have a green theme with scoped class names even with + JavaScript disabled. +
+
+
+ ) +} diff --git a/e2e/vue-start/css-modules/src/routes/sass-mixin.tsx b/e2e/vue-start/css-modules/src/routes/sass-mixin.tsx new file mode 100644 index 0000000000..1d0a68d320 --- /dev/null +++ b/e2e/vue-start/css-modules/src/routes/sass-mixin.tsx @@ -0,0 +1,24 @@ +import { createFileRoute } from '@tanstack/vue-router' +import '~/styles/app.scss' + +export const Route = createFileRoute('/sass-mixin')({ + component: SassMixin, +}) + +function SassMixin() { + return ( +
+

CSS Collection Test - Sass Mixin

+

+ This page tests that Sass mixins imported in a parent file are available + to subsequent imports during dev mode SSR. +

+ +
+ + Sass Mixin Applied - Should be centered with purple background + +
+
+ ) +} diff --git a/e2e/vue-start/css-modules/src/styles/app.scss b/e2e/vue-start/css-modules/src/styles/app.scss new file mode 100644 index 0000000000..2c2fde6cb2 --- /dev/null +++ b/e2e/vue-start/css-modules/src/styles/app.scss @@ -0,0 +1,4 @@ +// Import the mixin, which should make them available to future imports +@import './center-mixin.scss'; + +@import './mixin-consumer.scss'; diff --git a/e2e/vue-start/css-modules/src/styles/card.module.css b/e2e/vue-start/css-modules/src/styles/card.module.css new file mode 100644 index 0000000000..fcbcb419aa --- /dev/null +++ b/e2e/vue-start/css-modules/src/styles/card.module.css @@ -0,0 +1,20 @@ +/* CSS Module for testing scoped styles in dev mode */ + +.card { + background-color: #f0fdf4; /* green-50 */ + padding: 16px; + border-radius: 8px; + border: 1px solid #22c55e; /* green-500 */ +} + +.title { + font-size: 18px; + font-weight: 600; + color: #166534; /* green-800 */ + margin-bottom: 8px; +} + +.content { + font-size: 14px; + color: #15803d; /* green-700 */ +} diff --git a/e2e/vue-start/css-modules/src/styles/center-mixin.scss b/e2e/vue-start/css-modules/src/styles/center-mixin.scss new file mode 100644 index 0000000000..7eeb174b6e --- /dev/null +++ b/e2e/vue-start/css-modules/src/styles/center-mixin.scss @@ -0,0 +1,5 @@ +@mixin center-mixin { + display: flex; + justify-content: center; + align-items: center; +} diff --git a/e2e/vue-start/css-modules/src/styles/global.css b/e2e/vue-start/css-modules/src/styles/global.css new file mode 100644 index 0000000000..5bef746780 --- /dev/null +++ b/e2e/vue-start/css-modules/src/styles/global.css @@ -0,0 +1,19 @@ +/* Global styles for testing CSS collection in dev mode */ + +.global-container { + background-color: #3b82f6; /* blue-500 */ + padding: 24px; + border-radius: 12px; + color: white; +} + +.global-title { + font-size: 24px; + font-weight: bold; + margin-bottom: 16px; +} + +.global-description { + font-size: 16px; + opacity: 0.9; +} diff --git a/e2e/vue-start/css-modules/src/styles/mixin-consumer.scss b/e2e/vue-start/css-modules/src/styles/mixin-consumer.scss new file mode 100644 index 0000000000..52715c90b0 --- /dev/null +++ b/e2e/vue-start/css-modules/src/styles/mixin-consumer.scss @@ -0,0 +1,10 @@ +.mixin-container { + // Use the center mixin, which is included in app.scss + // This works for the client build, but not for the dev server styles.css build + @include center-mixin; + background-color: #a855f7; /* purple-500 */ + padding: 24px; + border-radius: 12px; + color: white; + min-height: 100px; +} diff --git a/e2e/vue-start/css-modules/tests/css.spec.ts b/e2e/vue-start/css-modules/tests/css.spec.ts new file mode 100644 index 0000000000..7646eb750e --- /dev/null +++ b/e2e/vue-start/css-modules/tests/css.spec.ts @@ -0,0 +1,209 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' + +// Whitelist errors that can occur in CI: +// - net::ERR_NAME_NOT_RESOLVED: transient network issues +// - 504 (Outdated Optimize Dep): Vite dependency optimization reload +// - net::ERR_INTERNET_DISCONNECTED: transient network issues +const whitelistErrors = [ + 'Failed to load resource: net::ERR_NAME_NOT_RESOLVED', + 'Failed to load resource: net::ERR_INTERNET_DISCONNECTED', + 'Failed to load resource: the server responded with a status of 504', +] + +test.describe('CSS styles in SSR (dev mode)', () => { + test.use({ whitelistErrors }) + + // Helper to build full URL from baseURL and path + // Playwright's goto with absolute paths (like '/modules') ignores baseURL's path portion + // So we need to manually construct the full URL + const buildUrl = (baseURL: string, path: string) => { + return baseURL.replace(/\/$/, '') + path + } + + test.describe('with JavaScript disabled', () => { + test.use({ javaScriptEnabled: false, whitelistErrors }) + + test('global CSS is applied on initial page load', async ({ + page, + baseURL, + }) => { + await page.goto(buildUrl(baseURL!, '/')) + + const element = page.getByTestId('global-styled') + await expect(element).toBeVisible() + + // Verify the CSS is applied by checking computed styles + // #3b82f6 (blue-500) in RGB is rgb(59, 130, 246) + const backgroundColor = await element.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(59, 130, 246)') + + const padding = await element.evaluate( + (el) => getComputedStyle(el).padding, + ) + expect(padding).toBe('24px') + + const borderRadius = await element.evaluate( + (el) => getComputedStyle(el).borderRadius, + ) + expect(borderRadius).toBe('12px') + }) + + test('CSS modules are applied on initial page load', async ({ + page, + baseURL, + }) => { + await page.goto(buildUrl(baseURL!, '/modules')) + + const card = page.getByTestId('module-card') + await expect(card).toBeVisible() + + // Verify class is scoped (hashed) + const className = await card.getAttribute('class') + expect(className).toBeTruthy() + expect(className).not.toBe('card') + // The class should contain some hash characters (CSS modules add a hash) + expect(className!.length).toBeGreaterThan(5) + + // Verify computed styles from card.module.css + // #f0fdf4 (green-50) in RGB is rgb(240, 253, 244) + const backgroundColor = await card.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(240, 253, 244)') + + const padding = await card.evaluate((el) => getComputedStyle(el).padding) + expect(padding).toBe('16px') + + const borderRadius = await card.evaluate( + (el) => getComputedStyle(el).borderRadius, + ) + expect(borderRadius).toBe('8px') + }) + + test('global CSS class names are NOT scoped', async ({ page, baseURL }) => { + await page.goto(buildUrl(baseURL!, '/')) + + const element = page.getByTestId('global-styled') + await expect(element).toBeVisible() + + // Get the class attribute - it should be the plain class name (not hashed) + const className = await element.getAttribute('class') + expect(className).toBe('global-container') + }) + + test('Sass mixin styles are applied on initial page load', async ({ + page, + baseURL, + }) => { + await page.goto(buildUrl(baseURL!, '/sass-mixin')) + + const element = page.getByTestId('mixin-styled') + await expect(element).toBeVisible() + + // Verify the mixin is applied (display: flex from center-mixin) + const display = await element.evaluate( + (el) => getComputedStyle(el).display, + ) + expect(display).toBe('flex') + + const justifyContent = await element.evaluate( + (el) => getComputedStyle(el).justifyContent, + ) + expect(justifyContent).toBe('center') + + const alignItems = await element.evaluate( + (el) => getComputedStyle(el).alignItems, + ) + expect(alignItems).toBe('center') + + // Verify other styles from mixin-consumer.scss + // #a855f7 (purple-500) in RGB is rgb(168, 85, 247) + const backgroundColor = await element.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(168, 85, 247)') + + const padding = await element.evaluate( + (el) => getComputedStyle(el).padding, + ) + expect(padding).toBe('24px') + }) + }) + + test('styles persist after hydration', async ({ page, baseURL }) => { + await page.goto(buildUrl(baseURL!, '/')) + + // Wait for hydration and styles to be applied + const element = page.getByTestId('global-styled') + await expect(element).toBeVisible() + + // Wait for CSS to be applied (background color should not be transparent) + await expect(async () => { + const backgroundColor = await element.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(59, 130, 246)') + }).toPass({ timeout: 5000 }) + }) + + test('CSS modules styles persist after hydration', async ({ + page, + baseURL, + }) => { + await page.goto(buildUrl(baseURL!, '/modules')) + + // Wait for hydration and styles to be applied + const card = page.getByTestId('module-card') + await expect(card).toBeVisible() + + // Wait for CSS to be applied (background color should not be transparent) + await expect(async () => { + const backgroundColor = await card.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(240, 253, 244)') + }).toPass({ timeout: 5000 }) + }) + + test('styles work correctly after client-side navigation', async ({ + page, + baseURL, + }) => { + // Start from home + await page.goto(buildUrl(baseURL!, '/')) + + // Verify initial styles + const globalElement = page.getByTestId('global-styled') + await expect(globalElement).toBeVisible() + let backgroundColor = await globalElement.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(59, 130, 246)') + + // Navigate to modules page + await page.getByTestId('nav-modules').click() + await page.waitForURL('**/modules') + + // Verify CSS modules styles + const card = page.getByTestId('module-card') + await expect(card).toBeVisible() + backgroundColor = await card.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(240, 253, 244)') + + // Navigate back to home + await page.getByTestId('nav-home').click() + await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) + + // Verify global styles still work + await expect(globalElement).toBeVisible() + backgroundColor = await globalElement.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(59, 130, 246)') + }) +}) diff --git a/e2e/vue-start/css-modules/tests/setup/global.setup.ts b/e2e/vue-start/css-modules/tests/setup/global.setup.ts new file mode 100644 index 0000000000..17be637f77 --- /dev/null +++ b/e2e/vue-start/css-modules/tests/setup/global.setup.ts @@ -0,0 +1,39 @@ +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: 'global-styled', + warmup: async (page) => { + await page.goto(`${baseURL}/modules`, { waitUntil: 'domcontentloaded' }) + await page.getByTestId('module-card').waitFor({ state: 'visible' }) + await page.waitForLoadState('networkidle') + + await page.goto(`${baseURL}/sass-mixin`, { + waitUntil: 'domcontentloaded', + }) + await page.getByTestId('mixin-styled').waitFor({ state: 'visible' }) + await page.waitForLoadState('networkidle') + + await page.goto(`${baseURL}/`, { waitUntil: 'domcontentloaded' }) + await page.getByTestId('global-styled').waitFor({ state: 'visible' }) + await page.waitForLoadState('networkidle') + + await page.getByTestId('nav-modules').click() + await page.waitForURL('**/modules') + await page.getByTestId('module-card').waitFor({ state: 'visible' }) + await page.waitForLoadState('networkidle') + + await page.getByTestId('nav-home').click() + await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) + await page.getByTestId('global-styled').waitFor({ state: 'visible' }) + await page.waitForLoadState('networkidle') + }, + }) +} diff --git a/e2e/vue-start/css-modules/tsconfig.json b/e2e/vue-start/css-modules/tsconfig.json new file mode 100644 index 0000000000..572d840872 --- /dev/null +++ b/e2e/vue-start/css-modules/tsconfig.json @@ -0,0 +1,23 @@ +{ + "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, + "types": ["vite/client"] + } +} diff --git a/e2e/vue-start/css-modules/vite.config.ts b/e2e/vue-start/css-modules/vite.config.ts new file mode 100644 index 0000000000..36e10f551e --- /dev/null +++ b/e2e/vue-start/css-modules/vite.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' + +export default defineConfig({ + resolve: { tsconfigPaths: true }, + server: { + port: 3000, + }, + plugins: [tanstackStart(), vueJsx()], +}) diff --git a/e2e/vue-start/custom-basepath/.devcontainer/devcontainer.json b/e2e/vue-start/custom-basepath/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/custom-basepath/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/custom-basepath/express-server.ts b/e2e/vue-start/custom-basepath/express-server.ts index 6fa802e447..b9bf393466 100644 --- a/e2e/vue-start/custom-basepath/express-server.ts +++ b/e2e/vue-start/custom-basepath/express-server.ts @@ -1,5 +1,7 @@ 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' const PORT = Number.parseInt(process.env.PORT || '3000') @@ -17,7 +19,7 @@ if (DEVELOPMENT) { try { const { default: serverEntry } = await viteDevServer.ssrLoadModule('./src/server.ts') - const handler = toNodeHandler(serverEntry.fetch) + const handler = toNodeHandler(serverEntry.fetch) as NodeHttp1Handler await handler(req, res) } catch (error) { if (typeof error === 'object' && error instanceof Error) { @@ -28,7 +30,7 @@ if (DEVELOPMENT) { }) } else { const { default: handler } = await import('./dist/server/server.js') - const nodeHandler = toNodeHandler(handler.fetch) + const nodeHandler = toNodeHandler(handler.fetch) as NodeHttp1Handler app.use('/custom/basepath', express.static('dist/client')) app.use(async (req, res, next) => { try { @@ -39,6 +41,11 @@ if (DEVELOPMENT) { }) } -app.listen(PORT, () => { - console.log(`Server is running on http://localhost:${PORT}`) +const httpServer = app.listen(PORT, (error) => { + if (error) { + throw error + } + console.log( + `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, + ) }) diff --git a/e2e/vue-start/custom-basepath/package.json b/e2e/vue-start/custom-basepath/package.json index b897f78d83..c1032ea88b 100644 --- a/e2e/vue-start/custom-basepath/package.json +++ b/e2e/vue-start/custom-basepath/package.json @@ -8,31 +8,30 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "tsx express-server.ts", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "express": "^4.21.2", - "redaxios": "^0.5.1", + "express": "^5.2.1", + "redaxios": "catalog:", "vue": "^3.5.25" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@tailwindcss/postcss": "^4.1.15", + "@playwright/test": "^1.61.0", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", - "@types/express": "^5.0.3", + "@types/express": "^5.0.6", "@types/node": "^22.10.2", "cross-env": "^10.0.0", - "postcss": "^8.5.1", - "srvx": "^0.9.8", - "tailwindcss": "^4.1.17", + "srvx": "^1.0.0", + "tailwindcss": "^4.2.2", "tsx": "^4.20.3", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "@vitejs/plugin-vue": "^6.0.3", - "@vitejs/plugin-vue-jsx": "^5.1.2", - "vite-tsconfig-paths": "^5.1.4" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5" } } diff --git a/e2e/vue-start/custom-basepath/playwright.config.ts b/e2e/vue-start/custom-basepath/playwright.config.ts index 5095425f47..e113ce64ad 100644 --- a/e2e/vue-start/custom-basepath/playwright.config.ts +++ b/e2e/vue-start/custom-basepath/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}/custom/basepath` /** @@ -18,19 +13,19 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', + env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, + }, }, projects: [ diff --git a/e2e/vue-start/custom-basepath/postcss.config.mjs b/e2e/vue-start/custom-basepath/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-start/custom-basepath/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx index b1f818dd74..77c03c5afa 100644 --- a/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx @@ -1,53 +1,61 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error(error) - - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} +export const DefaultCatchBoundary = defineComponent({ + props: { + error: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + return () => { + console.error(props.error) + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/custom-basepath/src/routeTree.gen.ts b/e2e/vue-start/custom-basepath/src/routeTree.gen.ts index 2aa189fd3c..605193fbec 100644 --- a/e2e/vue-start/custom-basepath/src/routeTree.gen.ts +++ b/e2e/vue-start/custom-basepath/src/routeTree.gen.ts @@ -9,34 +9,24 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as UsersRouteImport } from './routes/users' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as DeferredRouteImport } from './routes/deferred' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as RedirectIndexRouteImport } from './routes/redirect.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as RedirectThrowItRouteImport } from './routes/redirect.throw-it' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as UsersRouteImport } from './routes/users' import { Route as ApiUsersRouteImport } from './routes/api/users' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as RedirectIndexRouteImport } from './routes/redirect.index' +import { Route as RedirectThrowItRouteImport } from './routes/redirect.throw-it' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -44,19 +34,24 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, } as any) -const RedirectIndexRoute = RedirectIndexRouteImport.update({ - id: '/redirect/', - path: '/redirect/', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => rootRouteImport, +} as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ @@ -64,36 +59,41 @@ const PostsIndexRoute = PostsIndexRouteImport.update({ path: '/', getParentRoute: () => PostsRoute, } as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', + getParentRoute: () => rootRouteImport, } as any) const RedirectThrowItRoute = RedirectThrowItRouteImport.update({ id: '/redirect/throw-it', path: '/redirect/throw-it', getParentRoute: () => rootRouteImport, } as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', - getParentRoute: () => rootRouteImport, -} as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, } as any) const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', getParentRoute: () => ApiUsersRoute, } as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -106,7 +106,7 @@ export interface FileRoutesByFullPath { '/redirect/throw-it': typeof RedirectThrowItRoute '/users/$userId': typeof UsersUserIdRoute '/posts/': typeof PostsIndexRoute - '/redirect': typeof RedirectIndexRoute + '/redirect/': typeof RedirectIndexRoute '/users/': typeof UsersIndexRoute '/api/users/$userId': typeof ApiUsersUserIdRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute @@ -155,7 +155,7 @@ export interface FileRouteTypes { | '/redirect/throw-it' | '/users/$userId' | '/posts/' - | '/redirect' + | '/redirect/' | '/users/' | '/api/users/$userId' | '/posts/$postId/deep' @@ -205,25 +205,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -233,25 +219,32 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectIndexRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } '/posts/': { @@ -261,12 +254,19 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsIndexRouteImport parentRoute: typeof PostsRoute } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport } '/redirect/throw-it': { id: '/redirect/throw-it' @@ -275,26 +275,19 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectThrowItRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport - parentRoute: typeof rootRouteImport - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute } '/api/users/$userId': { id: '/api/users/$userId' @@ -303,6 +296,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ApiUsersUserIdRouteImport parentRoute: typeof ApiUsersRoute } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/vue-start/custom-basepath/src/routes/__root.tsx b/e2e/vue-start/custom-basepath/src/routes/__root.tsx index 8bc947b03a..c6d1eb197c 100644 --- a/e2e/vue-start/custom-basepath/src/routes/__root.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/__root.tsx @@ -49,7 +49,11 @@ export const Route = createRootRoute({ { rel: 'icon', href: '/favicon.ico' }, ], }), - errorComponent: (props) =>

{props.error.stack}

, + errorComponent: (props) => ( +

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

+ ), notFoundComponent: () => , component: RootComponent, }) diff --git a/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts b/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts index 5c55163c7f..7e3f528d68 100644 --- a/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts +++ b/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts @@ -1,12 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' -import { json } from '@tanstack/vue-start' import type { User } from '~/utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users/$userId')({ server: { @@ -19,14 +14,14 @@ export const Route = createFileRoute('/api/users/$userId')({ throw new Error('Failed to fetch user') } const user = (await res.json()) as User - return json({ + return Response.json({ id: user.id, name: user.name, email: user.email, }) } catch (e) { console.error(e) - return json({ error: 'User not found' }, { status: 404 }) + return Response.json({ error: 'User not found' }, { status: 404 }) } }, }, 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 5f2ab51270..dfdb5cd844 100644 --- a/e2e/vue-start/custom-basepath/src/routes/api/users.ts +++ b/e2e/vue-start/custom-basepath/src/routes/api/users.ts @@ -1,5 +1,5 @@ import { createFileRoute } from '@tanstack/vue-router' -import { createMiddleware, json } from '@tanstack/vue-start' +import { createMiddleware } from '@tanstack/vue-start' import type { User } from '~/utils/users' const userLoggerMiddleware = createMiddleware().server( @@ -38,11 +38,7 @@ const testMiddleware = createMiddleware() return result }) -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users')({ server: { @@ -56,7 +52,7 @@ export const Route = createFileRoute('/api/users')({ } const data = (await res.json()) as Array const list = data.slice(0, 10) - return json( + return Response.json( list.map((u) => ({ id: u.id, name: u.name, email: u.email })), ) }, diff --git a/e2e/vue-start/custom-basepath/src/routes/deferred.tsx b/e2e/vue-start/custom-basepath/src/routes/deferred.tsx index 7dbd50b030..8db75401e9 100644 --- a/e2e/vue-start/custom-basepath/src/routes/deferred.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/vue-start' import { Suspense, defineComponent, ref } from 'vue' const personServerFn = createServerFn({ method: 'GET' }) - .inputValidator((data: { name: string }) => data) + .validator((data: { name: string }) => data) .handler(({ data }) => { return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .inputValidator((data: { name: string }) => data) + .validator((data: { name: string }) => data) .handler(async ({ data }) => { await new Promise((r) => setTimeout(r, 1000)) return { name: data.name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx b/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx index b4e5a8a6a2..599e0f046e 100644 --- a/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx @@ -1,9 +1,32 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '~/utils/posts' import { NotFound } from '~/components/NotFound' import { PostErrorComponent } from '~/components/PostErrorComponent' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + return () => ( +
+

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{post.value.title}

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

{user.value.name}

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

{user.value.name}

-
{user.value.email}
-
- ) -} diff --git a/e2e/vue-start/custom-basepath/src/routes/users.tsx b/e2e/vue-start/custom-basepath/src/routes/users.tsx index 1432e50451..fe926d0a44 100644 --- a/e2e/vue-start/custom-basepath/src/routes/users.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/users.tsx @@ -1,8 +1,40 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' import type { User } from '~/utils/users' import { basepath } from '~/utils/basepath' +const UsersComponent = defineComponent({ + setup() { + const users = Route.useLoaderData() + return () => ( +
+
    + {[ + ...users.value, + { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, + ].map((user) => ( +
  • + +
    {user.name}
    + +
  • + ))} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/users')({ loader: async () => { return await axios @@ -14,33 +46,3 @@ export const Route = createFileRoute('/users')({ }, component: UsersComponent, }) - -function UsersComponent() { - const users = Route.useLoaderData() - - return ( -
-
    - {[ - ...users.value, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => ( -
  • - -
    {user.name}
    - -
  • - ))} -
-
- -
- ) -} diff --git a/e2e/vue-start/custom-basepath/src/styles/app.css b/e2e/vue-start/custom-basepath/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/e2e/vue-start/custom-basepath/src/styles/app.css +++ b/e2e/vue-start/custom-basepath/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-start/custom-basepath/src/utils/posts.tsx b/e2e/vue-start/custom-basepath/src/utils/posts.tsx index a193bbc7af..11d80d08b5 100644 --- a/e2e/vue-start/custom-basepath/src/utils/posts.tsx +++ b/e2e/vue-start/custom-basepath/src/utils/posts.tsx @@ -8,14 +8,10 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) + .validator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/e2e/vue-start/custom-basepath/src/utils/users.tsx b/e2e/vue-start/custom-basepath/src/utils/users.tsx index 46be4b1580..7ba645b383 100644 --- a/e2e/vue-start/custom-basepath/src/utils/users.tsx +++ b/e2e/vue-start/custom-basepath/src/utils/users.tsx @@ -3,7 +3,3 @@ export type User = { name: string email: string } - -const PORT = process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/custom-basepath/src/vite-env.d.ts b/e2e/vue-start/custom-basepath/src/vite-env.d.ts index 0b2af560d6..d0b512cd80 100644 --- a/e2e/vue-start/custom-basepath/src/vite-env.d.ts +++ b/e2e/vue-start/custom-basepath/src/vite-env.d.ts @@ -1,3 +1,5 @@ +/// + declare module '*?url' { const url: string export default url diff --git a/e2e/vue-start/custom-basepath/tests/navigation.spec.ts b/e2e/vue-start/custom-basepath/tests/navigation.spec.ts index e66f14be9e..3e6a5bd1be 100644 --- a/e2e/vue-start/custom-basepath/tests/navigation.spec.ts +++ b/e2e/vue-start/custom-basepath/tests/navigation.spec.ts @@ -68,7 +68,6 @@ test('server-side redirect', async ({ page, baseURL }) => { const headers = new Headers(res.headers()) expect(headers.get('location')).toBe('/custom/basepath/redirect/throw-it') }) - // now go to the route WITH the base path, this will redirect to the final destination await page.request .get('/custom/basepath/redirect/throw-it', { maxRedirects: 0 }) .then((res) => { diff --git a/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts b/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts b/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/custom-basepath/tsconfig.json b/e2e/vue-start/custom-basepath/tsconfig.json index 6d933a5b2c..6f99c0f49a 100644 --- a/e2e/vue-start/custom-basepath/tsconfig.json +++ b/e2e/vue-start/custom-basepath/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/custom-basepath/vite.config.ts b/e2e/vue-start/custom-basepath/vite.config.ts index 8f0fee2ce7..abfec15781 100644 --- a/e2e/vue-start/custom-basepath/vite.config.ts +++ b/e2e/vue-start/custom-basepath/vite.config.ts @@ -1,20 +1,14 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + resolve: { tsconfigPaths: true }, base: '/custom/basepath', server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - vue(), - vueJsx(), - ], + plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], }) diff --git a/e2e/vue-start/dev-ssr-styles/.gitignore b/e2e/vue-start/dev-ssr-styles/.gitignore new file mode 100644 index 0000000000..950326609c --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/.gitignore @@ -0,0 +1,7 @@ +node_modules +dist +.routeTree.gen.ts +src/routeTree.gen.ts +test-results +playwright-report +port*.txt diff --git a/e2e/vue-start/dev-ssr-styles/package.json b/e2e/vue-start/dev-ssr-styles/package.json new file mode 100644 index 0000000000..0033a0a5cc --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/package.json @@ -0,0 +1,32 @@ +{ + "name": "tanstack-vue-start-e2e-dev-ssr-styles", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "vite dev --port 3000", + "dev:e2e": "vite dev --port 0", + "build": "vite build && tsc --noEmit", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", + "test:e2e:dev": "MODE=dev playwright test --project=chromium", + "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:dev:bundled-dev", + "test:e2e:dev:bundled-dev": "MODE=dev E2E_VITE_BUNDLED_DEV=true playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/vue-router": "workspace:*", + "@tanstack/vue-start": "workspace:*", + "vue": "^3.5.16" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-core": "workspace:*", + "@tanstack/router-e2e-utils": "workspace:*", + "@types/node": "^22.10.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "srvx": "^1.0.0", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "@typescript/native": "npm:typescript@^7.0.2" + } +} diff --git a/e2e/vue-start/dev-ssr-styles/playwright.config.ts b/e2e/vue-start/dev-ssr-styles/playwright.config.ts new file mode 100644 index 0000000000..723cd32789 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/playwright.config.ts @@ -0,0 +1,28 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + use: { baseURL }, + webServer: { + command: 'pnpm dev:e2e', + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + env: { + VITE_NODE_ENV: 'test', + }, + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue b/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue new file mode 100644 index 0000000000..bd92215136 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue @@ -0,0 +1,14 @@ + + + diff --git a/e2e/vue-start/dev-ssr-styles/src/router.tsx b/e2e/vue-start/dev-ssr-styles/src/router.tsx new file mode 100644 index 0000000000..c0d7f2b200 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/router.tsx @@ -0,0 +1,10 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + scrollRestoration: true, + defaultPreload: false, + }) +} diff --git a/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx b/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx new file mode 100644 index 0000000000..0dec479a07 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' +import '~/styles/app.css' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx b/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx new file mode 100644 index 0000000000..733bc1d559 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/vue-router' +import SfcStyledBox from '../components/SfcStyledBox.vue' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return ( +
+

Vue Dev SSR Styles Test

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

{props.error.stack}

+ return ( +

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

+ ) }, notFoundComponent: () => , component: RootComponent, diff --git a/e2e/vue-start/scroll-restoration/src/styles/app.css b/e2e/vue-start/scroll-restoration/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/e2e/vue-start/scroll-restoration/src/styles/app.css +++ b/e2e/vue-start/scroll-restoration/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-start/scroll-restoration/src/utils/posts.tsx b/e2e/vue-start/scroll-restoration/src/utils/posts.tsx index e45ef52969..c4a2d0dcca 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/posts.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/posts.tsx @@ -10,11 +10,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export class PostNotFoundError extends Error {} diff --git a/e2e/vue-start/scroll-restoration/src/utils/users.tsx b/e2e/vue-start/scroll-restoration/src/utils/users.tsx index 46be4b1580..7ba645b383 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/users.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/users.tsx @@ -3,7 +3,3 @@ export type User = { name: string email: string } - -const PORT = process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/scroll-restoration/src/vite-env.d.ts b/e2e/vue-start/scroll-restoration/src/vite-env.d.ts index 0b2af560d6..d0b512cd80 100644 --- a/e2e/vue-start/scroll-restoration/src/vite-env.d.ts +++ b/e2e/vue-start/scroll-restoration/src/vite-env.d.ts @@ -1,3 +1,5 @@ +/// + declare module '*?url' { const url: string export default url diff --git a/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts b/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts new file mode 100644 index 0000000000..df75cba73c --- /dev/null +++ b/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts @@ -0,0 +1,4 @@ +import { test } from '@tanstack/router-e2e-utils' +import { scrollRestorationLifecycleTests } from '../../../scroll-restoration-lifecycle' + +scrollRestorationLifecycleTests(test) diff --git a/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts b/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts b/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/scroll-restoration/tsconfig.json b/e2e/vue-start/scroll-restoration/tsconfig.json index 6d933a5b2c..6f99c0f49a 100644 --- a/e2e/vue-start/scroll-restoration/tsconfig.json +++ b/e2e/vue-start/scroll-restoration/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/scroll-restoration/vite.config.ts b/e2e/vue-start/scroll-restoration/vite.config.ts index 79edfc05c2..563e212077 100644 --- a/e2e/vue-start/scroll-restoration/vite.config.ts +++ b/e2e/vue-start/scroll-restoration/vite.config.ts @@ -1,19 +1,13 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - vue(), - vueJsx(), - ], + plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], }) diff --git a/e2e/vue-start/selective-ssr/.devcontainer/devcontainer.json b/e2e/vue-start/selective-ssr/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/selective-ssr/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/selective-ssr/package.json b/e2e/vue-start/selective-ssr/package.json index 42fb72ac1a..b555a01c26 100644 --- a/e2e/vue-start/selective-ssr/package.json +++ b/e2e/vue-start/selective-ssr/package.json @@ -9,25 +9,24 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-start": "workspace:^", "vue": "^3.5.25", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", - "postcss": "^8.5.1", - "srvx": "^0.9.8", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "@vitejs/plugin-vue": "^6.0.3", - "@vitejs/plugin-vue-jsx": "^5.1.2", - "vite-tsconfig-paths": "^5.1.4", - "vue-tsc": "^3.1.8" + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "srvx": "^1.0.0", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-start/selective-ssr/playwright.config.ts b/e2e/vue-start/selective-ssr/playwright.config.ts index badd6db0eb..630989e41f 100644 --- a/e2e/vue-start/selective-ssr/playwright.config.ts +++ b/e2e/vue-start/selective-ssr/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/selective-ssr/postcss.config.mjs b/e2e/vue-start/selective-ssr/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-start/selective-ssr/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-start/selective-ssr/src/routeTree.gen.ts b/e2e/vue-start/selective-ssr/src/routeTree.gen.ts index 474705b7e7..0d44b648ee 100644 --- a/e2e/vue-start/selective-ssr/src/routeTree.gen.ts +++ b/e2e/vue-start/selective-ssr/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as PostsRouteImport } from './routes/posts' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostsRouteImport } from './routes/posts' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) const PostsPostIdRoute = PostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', @@ -60,13 +60,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -74,6 +67,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } '/posts/$postId': { id: '/posts/$postId' path: '/$postId' diff --git a/e2e/vue-start/selective-ssr/src/routes/__root.tsx b/e2e/vue-start/selective-ssr/src/routes/__root.tsx index a952abd4e0..9319a0982a 100644 --- a/e2e/vue-start/selective-ssr/src/routes/__root.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -14,6 +15,93 @@ import { z } from 'zod' import { ssrSchema } from '~/search' import appCss from '~/styles/app.css?url' +const RootDocument = defineComponent({ + setup(_, { slots }) { + const routerState = useRouterState({ + select: (state) => ({ + isLoading: state.isLoading, + status: state.status, + }), + }) + return () => ( + + + + + +
+

Selective SSR E2E Test

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

root

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

root

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

Selective SSR E2E Test

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

postId

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

postId

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

posts

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

posts

-
- ssr: {JSON.stringify(search.value.posts?.ssr ?? 'undefined')} -
-
- expected data location execution:{' '} - - {search.value.posts?.expected?.data} - -
-
- loader: {loaderData.value.posts} -
-
- context: {context.value.posts} -
-
- -
- ) - }, + component: RouteComponent, }) diff --git a/e2e/vue-start/selective-ssr/src/styles/app.css b/e2e/vue-start/selective-ssr/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/e2e/vue-start/selective-ssr/src/styles/app.css +++ b/e2e/vue-start/selective-ssr/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-start/selective-ssr/tsconfig.json b/e2e/vue-start/selective-ssr/tsconfig.json index f9f5aab3da..390dad84c0 100644 --- a/e2e/vue-start/selective-ssr/tsconfig.json +++ b/e2e/vue-start/selective-ssr/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/selective-ssr/vite.config.ts b/e2e/vue-start/selective-ssr/vite.config.ts index 79edfc05c2..563e212077 100644 --- a/e2e/vue-start/selective-ssr/vite.config.ts +++ b/e2e/vue-start/selective-ssr/vite.config.ts @@ -1,19 +1,13 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - vue(), - vueJsx(), - ], + plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], }) diff --git a/e2e/vue-start/serialization-adapters/.devcontainer/devcontainer.json b/e2e/vue-start/serialization-adapters/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/serialization-adapters/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/serialization-adapters/package.json b/e2e/vue-start/serialization-adapters/package.json index e00b102d9c..a056e21da3 100644 --- a/e2e/vue-start/serialization-adapters/package.json +++ b/e2e/vue-start/serialization-adapters/package.json @@ -9,26 +9,25 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", "vue": "^3.5.25", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", - "postcss": "^8.5.1", - "srvx": "^0.9.8", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "@vitejs/plugin-vue": "^6.0.3", - "@vitejs/plugin-vue-jsx": "^5.1.2", - "vite-tsconfig-paths": "^5.1.4", - "vue-tsc": "^3.1.8" + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "srvx": "^1.0.0", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-start/serialization-adapters/playwright.config.ts b/e2e/vue-start/serialization-adapters/playwright.config.ts index badd6db0eb..630989e41f 100644 --- a/e2e/vue-start/serialization-adapters/playwright.config.ts +++ b/e2e/vue-start/serialization-adapters/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/serialization-adapters/postcss.config.mjs b/e2e/vue-start/serialization-adapters/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-start/serialization-adapters/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts b/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts index 79b17ac82b..c684bbc82c 100644 --- a/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts +++ b/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts @@ -10,43 +10,43 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as SsrStreamRouteImport } from './routes/ssr/stream' -import { Route as SsrNestedRouteImport } from './routes/ssr/nested' -import { Route as SsrDataOnlyRouteImport } from './routes/ssr/data-only' -import { Route as ServerFunctionNestedRouteImport } from './routes/server-function/nested' import { Route as ServerFunctionCustomErrorRouteImport } from './routes/server-function/custom-error' +import { Route as ServerFunctionNestedRouteImport } from './routes/server-function/nested' +import { Route as SsrDataOnlyRouteImport } from './routes/ssr/data-only' +import { Route as SsrNestedRouteImport } from './routes/ssr/nested' +import { Route as SsrStreamRouteImport } from './routes/ssr/stream' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const SsrStreamRoute = SsrStreamRouteImport.update({ - id: '/ssr/stream', - path: '/ssr/stream', - getParentRoute: () => rootRouteImport, -} as any) -const SsrNestedRoute = SsrNestedRouteImport.update({ - id: '/ssr/nested', - path: '/ssr/nested', - getParentRoute: () => rootRouteImport, -} as any) -const SsrDataOnlyRoute = SsrDataOnlyRouteImport.update({ - id: '/ssr/data-only', - path: '/ssr/data-only', - getParentRoute: () => rootRouteImport, -} as any) -const ServerFunctionNestedRoute = ServerFunctionNestedRouteImport.update({ - id: '/server-function/nested', - path: '/server-function/nested', - getParentRoute: () => rootRouteImport, -} as any) const ServerFunctionCustomErrorRoute = ServerFunctionCustomErrorRouteImport.update({ id: '/server-function/custom-error', path: '/server-function/custom-error', getParentRoute: () => rootRouteImport, } as any) +const ServerFunctionNestedRoute = ServerFunctionNestedRouteImport.update({ + id: '/server-function/nested', + path: '/server-function/nested', + getParentRoute: () => rootRouteImport, +} as any) +const SsrDataOnlyRoute = SsrDataOnlyRouteImport.update({ + id: '/ssr/data-only', + path: '/ssr/data-only', + getParentRoute: () => rootRouteImport, +} as any) +const SsrNestedRoute = SsrNestedRouteImport.update({ + id: '/ssr/nested', + path: '/ssr/nested', + getParentRoute: () => rootRouteImport, +} as any) +const SsrStreamRoute = SsrStreamRouteImport.update({ + id: '/ssr/stream', + path: '/ssr/stream', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -118,25 +118,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/ssr/stream': { - id: '/ssr/stream' - path: '/ssr/stream' - fullPath: '/ssr/stream' - preLoaderRoute: typeof SsrStreamRouteImport - parentRoute: typeof rootRouteImport - } - '/ssr/nested': { - id: '/ssr/nested' - path: '/ssr/nested' - fullPath: '/ssr/nested' - preLoaderRoute: typeof SsrNestedRouteImport - parentRoute: typeof rootRouteImport - } - '/ssr/data-only': { - id: '/ssr/data-only' - path: '/ssr/data-only' - fullPath: '/ssr/data-only' - preLoaderRoute: typeof SsrDataOnlyRouteImport + '/server-function/custom-error': { + id: '/server-function/custom-error' + path: '/server-function/custom-error' + fullPath: '/server-function/custom-error' + preLoaderRoute: typeof ServerFunctionCustomErrorRouteImport parentRoute: typeof rootRouteImport } '/server-function/nested': { @@ -146,11 +132,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ServerFunctionNestedRouteImport parentRoute: typeof rootRouteImport } - '/server-function/custom-error': { - id: '/server-function/custom-error' - path: '/server-function/custom-error' - fullPath: '/server-function/custom-error' - preLoaderRoute: typeof ServerFunctionCustomErrorRouteImport + '/ssr/data-only': { + id: '/ssr/data-only' + path: '/ssr/data-only' + fullPath: '/ssr/data-only' + preLoaderRoute: typeof SsrDataOnlyRouteImport + parentRoute: typeof rootRouteImport + } + '/ssr/nested': { + id: '/ssr/nested' + path: '/ssr/nested' + fullPath: '/ssr/nested' + preLoaderRoute: typeof SsrNestedRouteImport + parentRoute: typeof rootRouteImport + } + '/ssr/stream': { + id: '/ssr/stream' + path: '/ssr/stream' + fullPath: '/ssr/stream' + preLoaderRoute: typeof SsrStreamRouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/vue-start/serialization-adapters/src/routes/__root.tsx b/e2e/vue-start/serialization-adapters/src/routes/__root.tsx index 96911d2500..3ea36c7d46 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/__root.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -12,6 +13,51 @@ import { import { TanStackRouterDevtoolsInProd } from '@tanstack/vue-router-devtools' import appCss from '~/styles/app.css?url' +const RootDocument = defineComponent({ + setup(_, { slots }) { + const routerState = useRouterState({ + select: (state) => ({ isLoading: state.isLoading, status: state.status }), + }) + return () => ( + + + + + +
+

Serialization Adapters E2E Test

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

Serialization Adapters E2E Test

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

data-only

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

honk

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

data-only

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

honk

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

Stream

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

Stream

-
{loaderData.value.someString}
- - {{ - default: () => ( - ) => ( - - )} - /> - ), - fallback: () =>
Loading...
, - }} -
-
- ) -} diff --git a/e2e/vue-start/serialization-adapters/src/styles/app.css b/e2e/vue-start/serialization-adapters/src/styles/app.css index fbb4ba08a5..80fe7fc1c2 100644 --- a/e2e/vue-start/serialization-adapters/src/styles/app.css +++ b/e2e/vue-start/serialization-adapters/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); /* The default border color has changed to `currentcolor` in Tailwind CSS v4, diff --git a/e2e/vue-start/serialization-adapters/tests/app.spec.ts b/e2e/vue-start/serialization-adapters/tests/app.spec.ts index 292212a4d1..a74ed1af4f 100644 --- a/e2e/vue-start/serialization-adapters/tests/app.spec.ts +++ b/e2e/vue-start/serialization-adapters/tests/app.spec.ts @@ -41,7 +41,7 @@ async function checkNestedData(page: Page) { } test.use({ whitelistErrors: [ - /Failed to load resource: the server responded with a status of 499/, + 'Failed to load resource: the server responded with a status of 499', ], }) test.describe('SSR serialization adapters', () => { diff --git a/e2e/vue-start/serialization-adapters/tsconfig.json b/e2e/vue-start/serialization-adapters/tsconfig.json index f9f5aab3da..390dad84c0 100644 --- a/e2e/vue-start/serialization-adapters/tsconfig.json +++ b/e2e/vue-start/serialization-adapters/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/serialization-adapters/vite.config.ts b/e2e/vue-start/serialization-adapters/vite.config.ts index 79edfc05c2..563e212077 100644 --- a/e2e/vue-start/serialization-adapters/vite.config.ts +++ b/e2e/vue-start/serialization-adapters/vite.config.ts @@ -1,19 +1,13 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - vue(), - vueJsx(), - ], + plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], }) diff --git a/e2e/vue-start/server-functions/.devcontainer/devcontainer.json b/e2e/vue-start/server-functions/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/server-functions/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/server-functions/package.json b/e2e/vue-start/server-functions/package.json index 27faff7ff2..dd1a7a9c6b 100644 --- a/e2e/vue-start/server-functions/package.json +++ b/e2e/vue-start/server-functions/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.90.9", @@ -18,25 +18,24 @@ "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", "js-cookie": "^3.0.5", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "vite": "^7.1.7", + "redaxios": "catalog:", + "tailwind-merge": "^3.6.0", "vue": "^3.5.25", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@tailwindcss/postcss": "^4.1.15", + "@playwright/test": "^1.61.0", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/js-cookie": "^3.0.6", "@types/node": "^22.10.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "postcss": "^8.5.1", - "srvx": "^0.9.8", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "@vitejs/plugin-vue": "^6.0.3", - "@vitejs/plugin-vue-jsx": "^5.1.2", - "vite-tsconfig-paths": "^5.1.4" + "srvx": "^1.0.0", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/e2e/vue-start/server-functions/playwright.config.ts b/e2e/vue-start/server-functions/playwright.config.ts index cb1da03b94..48e14683f4 100644 --- a/e2e/vue-start/server-functions/playwright.config.ts +++ b/e2e/vue-start/server-functions/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -export const PORT = await getTestServerPort(packageJson.name) +export const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/server-functions/postcss.config.mjs b/e2e/vue-start/server-functions/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-start/server-functions/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx index b1f818dd74..77c03c5afa 100644 --- a/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx @@ -1,53 +1,61 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error(error) - - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} +export const DefaultCatchBoundary = defineComponent({ + props: { + error: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + return () => { + console.error(props.error) + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/server-functions/src/routeTree.gen.ts b/e2e/vue-start/server-functions/src/routeTree.gen.ts index 91633bf3c7..96e5b7ba29 100644 --- a/e2e/vue-start/server-functions/src/routeTree.gen.ts +++ b/e2e/vue-start/server-functions/src/routeTree.gen.ts @@ -9,87 +9,39 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as SubmitPostFormdataRouteImport } from './routes/submit-post-formdata' -import { Route as StatusRouteImport } from './routes/status' -import { Route as SerializeFormDataRouteImport } from './routes/serialize-form-data' -import { Route as ReturnNullRouteImport } from './routes/return-null' -import { Route as RawResponseRouteImport } from './routes/raw-response' -import { Route as MultipartRouteImport } from './routes/multipart' -import { Route as IsomorphicFnsRouteImport } from './routes/isomorphic-fns' -import { Route as HeadersRouteImport } from './routes/headers' -import { Route as EnvOnlyRouteImport } from './routes/env-only' -import { Route as DeadCodePreserveRouteImport } from './routes/dead-code-preserve' -import { Route as ConsistentRouteImport } from './routes/consistent' -import { Route as AbortSignalRouteImport } from './routes/abort-signal' import { Route as IndexRouteImport } from './routes/index' -import { Route as RedirectTestIndexRouteImport } from './routes/redirect-test/index' -import { Route as RedirectTestSsrIndexRouteImport } from './routes/redirect-test-ssr/index' -import { Route as PrimitivesIndexRouteImport } from './routes/primitives/index' -import { Route as MiddlewareIndexRouteImport } from './routes/middleware/index' -import { Route as FormdataRedirectIndexRouteImport } from './routes/formdata-redirect/index' -import { Route as FactoryIndexRouteImport } from './routes/factory/index' +import { Route as AbortSignalRouteImport } from './routes/abort-signal' +import { Route as ConsistentRouteImport } from './routes/consistent' +import { Route as DeadCodePreserveRouteImport } from './routes/dead-code-preserve' +import { Route as EnvOnlyRouteImport } from './routes/env-only' +import { Route as HeadersRouteImport } from './routes/headers' +import { Route as IsomorphicFnsRouteImport } from './routes/isomorphic-fns' +import { Route as MultipartRouteImport } from './routes/multipart' +import { Route as RawResponseRouteImport } from './routes/raw-response' +import { Route as ReturnNullRouteImport } from './routes/return-null' +import { Route as SerializeFormDataRouteImport } from './routes/serialize-form-data' +import { Route as StatusRouteImport } from './routes/status' +import { Route as SubmitPostFormdataRouteImport } from './routes/submit-post-formdata' import { Route as CookiesIndexRouteImport } from './routes/cookies/index' -import { Route as RedirectTestTargetRouteImport } from './routes/redirect-test/target' -import { Route as RedirectTestSsrTargetRouteImport } from './routes/redirect-test-ssr/target' -import { Route as MiddlewareSendServerFnRouteImport } from './routes/middleware/send-serverFn' -import { Route as MiddlewareRequestMiddlewareRouteImport } from './routes/middleware/request-middleware' -import { Route as MiddlewareClientMiddlewareRouterRouteImport } from './routes/middleware/client-middleware-router' import { Route as CookiesSetRouteImport } from './routes/cookies/set' +import { Route as FactoryIndexRouteImport } from './routes/factory/index' +import { Route as FormdataRedirectIndexRouteImport } from './routes/formdata-redirect/index' +import { Route as FunctionMetadataIndexRouteImport } from './routes/function-metadata/index' +import { Route as FunctionMethodIndexRouteImport } from './routes/function-method/index' +import { Route as MiddlewareIndexRouteImport } from './routes/middleware/index' +import { Route as MiddlewareClientMiddlewareRouterRouteImport } from './routes/middleware/client-middleware-router' +import { Route as MiddlewareRequestMiddlewareRouteImport } from './routes/middleware/request-middleware' +import { Route as MiddlewareSendServerFnRouteImport } from './routes/middleware/send-serverFn' +import { Route as PrimitivesIndexRouteImport } from './routes/primitives/index' +import { Route as RedirectTestSsrIndexRouteImport } from './routes/redirect-test-ssr/index' +import { Route as RedirectTestSsrTargetRouteImport } from './routes/redirect-test-ssr/target' +import { Route as RedirectTestIndexRouteImport } from './routes/redirect-test/index' +import { Route as RedirectTestTargetRouteImport } from './routes/redirect-test/target' import { Route as FormdataRedirectTargetNameRouteImport } from './routes/formdata-redirect/target.$name' -const SubmitPostFormdataRoute = SubmitPostFormdataRouteImport.update({ - id: '/submit-post-formdata', - path: '/submit-post-formdata', - getParentRoute: () => rootRouteImport, -} as any) -const StatusRoute = StatusRouteImport.update({ - id: '/status', - path: '/status', - getParentRoute: () => rootRouteImport, -} as any) -const SerializeFormDataRoute = SerializeFormDataRouteImport.update({ - id: '/serialize-form-data', - path: '/serialize-form-data', - getParentRoute: () => rootRouteImport, -} as any) -const ReturnNullRoute = ReturnNullRouteImport.update({ - id: '/return-null', - path: '/return-null', - getParentRoute: () => rootRouteImport, -} as any) -const RawResponseRoute = RawResponseRouteImport.update({ - id: '/raw-response', - path: '/raw-response', - getParentRoute: () => rootRouteImport, -} as any) -const MultipartRoute = MultipartRouteImport.update({ - id: '/multipart', - path: '/multipart', - getParentRoute: () => rootRouteImport, -} as any) -const IsomorphicFnsRoute = IsomorphicFnsRouteImport.update({ - id: '/isomorphic-fns', - path: '/isomorphic-fns', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersRoute = HeadersRouteImport.update({ - id: '/headers', - path: '/headers', - getParentRoute: () => rootRouteImport, -} as any) -const EnvOnlyRoute = EnvOnlyRouteImport.update({ - id: '/env-only', - path: '/env-only', - getParentRoute: () => rootRouteImport, -} as any) -const DeadCodePreserveRoute = DeadCodePreserveRouteImport.update({ - id: '/dead-code-preserve', - path: '/dead-code-preserve', - getParentRoute: () => rootRouteImport, -} as any) -const ConsistentRoute = ConsistentRouteImport.update({ - id: '/consistent', - path: '/consistent', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AbortSignalRoute = AbortSignalRouteImport.update({ @@ -97,39 +49,59 @@ const AbortSignalRoute = AbortSignalRouteImport.update({ path: '/abort-signal', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ConsistentRoute = ConsistentRouteImport.update({ + id: '/consistent', + path: '/consistent', getParentRoute: () => rootRouteImport, } as any) -const RedirectTestIndexRoute = RedirectTestIndexRouteImport.update({ - id: '/redirect-test/', - path: '/redirect-test/', +const DeadCodePreserveRoute = DeadCodePreserveRouteImport.update({ + id: '/dead-code-preserve', + path: '/dead-code-preserve', getParentRoute: () => rootRouteImport, } as any) -const RedirectTestSsrIndexRoute = RedirectTestSsrIndexRouteImport.update({ - id: '/redirect-test-ssr/', - path: '/redirect-test-ssr/', +const EnvOnlyRoute = EnvOnlyRouteImport.update({ + id: '/env-only', + path: '/env-only', getParentRoute: () => rootRouteImport, } as any) -const PrimitivesIndexRoute = PrimitivesIndexRouteImport.update({ - id: '/primitives/', - path: '/primitives/', +const HeadersRoute = HeadersRouteImport.update({ + id: '/headers', + path: '/headers', getParentRoute: () => rootRouteImport, } as any) -const MiddlewareIndexRoute = MiddlewareIndexRouteImport.update({ - id: '/middleware/', - path: '/middleware/', +const IsomorphicFnsRoute = IsomorphicFnsRouteImport.update({ + id: '/isomorphic-fns', + path: '/isomorphic-fns', getParentRoute: () => rootRouteImport, } as any) -const FormdataRedirectIndexRoute = FormdataRedirectIndexRouteImport.update({ - id: '/formdata-redirect/', - path: '/formdata-redirect/', +const MultipartRoute = MultipartRouteImport.update({ + id: '/multipart', + path: '/multipart', getParentRoute: () => rootRouteImport, } as any) -const FactoryIndexRoute = FactoryIndexRouteImport.update({ - id: '/factory/', - path: '/factory/', +const RawResponseRoute = RawResponseRouteImport.update({ + id: '/raw-response', + path: '/raw-response', + getParentRoute: () => rootRouteImport, +} as any) +const ReturnNullRoute = ReturnNullRouteImport.update({ + id: '/return-null', + path: '/return-null', + getParentRoute: () => rootRouteImport, +} as any) +const SerializeFormDataRoute = SerializeFormDataRouteImport.update({ + id: '/serialize-form-data', + path: '/serialize-form-data', + getParentRoute: () => rootRouteImport, +} as any) +const StatusRoute = StatusRouteImport.update({ + id: '/status', + path: '/status', + getParentRoute: () => rootRouteImport, +} as any) +const SubmitPostFormdataRoute = SubmitPostFormdataRouteImport.update({ + id: '/submit-post-formdata', + path: '/submit-post-formdata', getParentRoute: () => rootRouteImport, } as any) const CookiesIndexRoute = CookiesIndexRouteImport.update({ @@ -137,9 +109,61 @@ const CookiesIndexRoute = CookiesIndexRouteImport.update({ path: '/cookies/', getParentRoute: () => rootRouteImport, } as any) -const RedirectTestTargetRoute = RedirectTestTargetRouteImport.update({ - id: '/redirect-test/target', - path: '/redirect-test/target', +const CookiesSetRoute = CookiesSetRouteImport.update({ + id: '/cookies/set', + path: '/cookies/set', + getParentRoute: () => rootRouteImport, +} as any) +const FactoryIndexRoute = FactoryIndexRouteImport.update({ + id: '/factory/', + path: '/factory/', + getParentRoute: () => rootRouteImport, +} as any) +const FormdataRedirectIndexRoute = FormdataRedirectIndexRouteImport.update({ + id: '/formdata-redirect/', + path: '/formdata-redirect/', + getParentRoute: () => rootRouteImport, +} as any) +const FunctionMetadataIndexRoute = FunctionMetadataIndexRouteImport.update({ + id: '/function-metadata/', + path: '/function-metadata/', + getParentRoute: () => rootRouteImport, +} as any) +const FunctionMethodIndexRoute = FunctionMethodIndexRouteImport.update({ + id: '/function-method/', + path: '/function-method/', + getParentRoute: () => rootRouteImport, +} as any) +const MiddlewareIndexRoute = MiddlewareIndexRouteImport.update({ + id: '/middleware/', + path: '/middleware/', + getParentRoute: () => rootRouteImport, +} as any) +const MiddlewareClientMiddlewareRouterRoute = + MiddlewareClientMiddlewareRouterRouteImport.update({ + id: '/middleware/client-middleware-router', + path: '/middleware/client-middleware-router', + getParentRoute: () => rootRouteImport, + } as any) +const MiddlewareRequestMiddlewareRoute = + MiddlewareRequestMiddlewareRouteImport.update({ + id: '/middleware/request-middleware', + path: '/middleware/request-middleware', + getParentRoute: () => rootRouteImport, + } as any) +const MiddlewareSendServerFnRoute = MiddlewareSendServerFnRouteImport.update({ + id: '/middleware/send-serverFn', + path: '/middleware/send-serverFn', + getParentRoute: () => rootRouteImport, +} as any) +const PrimitivesIndexRoute = PrimitivesIndexRouteImport.update({ + id: '/primitives/', + path: '/primitives/', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectTestSsrIndexRoute = RedirectTestSsrIndexRouteImport.update({ + id: '/redirect-test-ssr/', + path: '/redirect-test-ssr/', getParentRoute: () => rootRouteImport, } as any) const RedirectTestSsrTargetRoute = RedirectTestSsrTargetRouteImport.update({ @@ -147,26 +171,14 @@ const RedirectTestSsrTargetRoute = RedirectTestSsrTargetRouteImport.update({ path: '/redirect-test-ssr/target', getParentRoute: () => rootRouteImport, } as any) -const MiddlewareSendServerFnRoute = MiddlewareSendServerFnRouteImport.update({ - id: '/middleware/send-serverFn', - path: '/middleware/send-serverFn', +const RedirectTestIndexRoute = RedirectTestIndexRouteImport.update({ + id: '/redirect-test/', + path: '/redirect-test/', getParentRoute: () => rootRouteImport, } as any) -const MiddlewareRequestMiddlewareRoute = - MiddlewareRequestMiddlewareRouteImport.update({ - id: '/middleware/request-middleware', - path: '/middleware/request-middleware', - getParentRoute: () => rootRouteImport, - } as any) -const MiddlewareClientMiddlewareRouterRoute = - MiddlewareClientMiddlewareRouterRouteImport.update({ - id: '/middleware/client-middleware-router', - path: '/middleware/client-middleware-router', - getParentRoute: () => rootRouteImport, - } as any) -const CookiesSetRoute = CookiesSetRouteImport.update({ - id: '/cookies/set', - path: '/cookies/set', +const RedirectTestTargetRoute = RedirectTestTargetRouteImport.update({ + id: '/redirect-test/target', + path: '/redirect-test/target', getParentRoute: () => rootRouteImport, } as any) const FormdataRedirectTargetNameRoute = @@ -196,13 +208,15 @@ export interface FileRoutesByFullPath { '/middleware/send-serverFn': typeof MiddlewareSendServerFnRoute '/redirect-test-ssr/target': typeof RedirectTestSsrTargetRoute '/redirect-test/target': typeof RedirectTestTargetRoute - '/cookies': typeof CookiesIndexRoute - '/factory': typeof FactoryIndexRoute - '/formdata-redirect': typeof FormdataRedirectIndexRoute - '/middleware': typeof MiddlewareIndexRoute - '/primitives': typeof PrimitivesIndexRoute - '/redirect-test-ssr': typeof RedirectTestSsrIndexRoute - '/redirect-test': typeof RedirectTestIndexRoute + '/cookies/': typeof CookiesIndexRoute + '/factory/': typeof FactoryIndexRoute + '/formdata-redirect/': typeof FormdataRedirectIndexRoute + '/function-metadata/': typeof FunctionMetadataIndexRoute + '/function-method/': typeof FunctionMethodIndexRoute + '/middleware/': typeof MiddlewareIndexRoute + '/primitives/': typeof PrimitivesIndexRoute + '/redirect-test-ssr/': typeof RedirectTestSsrIndexRoute + '/redirect-test/': typeof RedirectTestIndexRoute '/formdata-redirect/target/$name': typeof FormdataRedirectTargetNameRoute } export interface FileRoutesByTo { @@ -228,6 +242,8 @@ export interface FileRoutesByTo { '/cookies': typeof CookiesIndexRoute '/factory': typeof FactoryIndexRoute '/formdata-redirect': typeof FormdataRedirectIndexRoute + '/function-metadata': typeof FunctionMetadataIndexRoute + '/function-method': typeof FunctionMethodIndexRoute '/middleware': typeof MiddlewareIndexRoute '/primitives': typeof PrimitivesIndexRoute '/redirect-test-ssr': typeof RedirectTestSsrIndexRoute @@ -258,6 +274,8 @@ export interface FileRoutesById { '/cookies/': typeof CookiesIndexRoute '/factory/': typeof FactoryIndexRoute '/formdata-redirect/': typeof FormdataRedirectIndexRoute + '/function-metadata/': typeof FunctionMetadataIndexRoute + '/function-method/': typeof FunctionMethodIndexRoute '/middleware/': typeof MiddlewareIndexRoute '/primitives/': typeof PrimitivesIndexRoute '/redirect-test-ssr/': typeof RedirectTestSsrIndexRoute @@ -286,13 +304,15 @@ export interface FileRouteTypes { | '/middleware/send-serverFn' | '/redirect-test-ssr/target' | '/redirect-test/target' - | '/cookies' - | '/factory' - | '/formdata-redirect' - | '/middleware' - | '/primitives' - | '/redirect-test-ssr' - | '/redirect-test' + | '/cookies/' + | '/factory/' + | '/formdata-redirect/' + | '/function-metadata/' + | '/function-method/' + | '/middleware/' + | '/primitives/' + | '/redirect-test-ssr/' + | '/redirect-test/' | '/formdata-redirect/target/$name' fileRoutesByTo: FileRoutesByTo to: @@ -318,6 +338,8 @@ export interface FileRouteTypes { | '/cookies' | '/factory' | '/formdata-redirect' + | '/function-metadata' + | '/function-method' | '/middleware' | '/primitives' | '/redirect-test-ssr' @@ -347,6 +369,8 @@ export interface FileRouteTypes { | '/cookies/' | '/factory/' | '/formdata-redirect/' + | '/function-metadata/' + | '/function-method/' | '/middleware/' | '/primitives/' | '/redirect-test-ssr/' @@ -377,6 +401,8 @@ export interface RootRouteChildren { CookiesIndexRoute: typeof CookiesIndexRoute FactoryIndexRoute: typeof FactoryIndexRoute FormdataRedirectIndexRoute: typeof FormdataRedirectIndexRoute + FunctionMetadataIndexRoute: typeof FunctionMetadataIndexRoute + FunctionMethodIndexRoute: typeof FunctionMethodIndexRoute MiddlewareIndexRoute: typeof MiddlewareIndexRoute PrimitivesIndexRoute: typeof PrimitivesIndexRoute RedirectTestSsrIndexRoute: typeof RedirectTestSsrIndexRoute @@ -386,81 +412,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/submit-post-formdata': { - id: '/submit-post-formdata' - path: '/submit-post-formdata' - fullPath: '/submit-post-formdata' - preLoaderRoute: typeof SubmitPostFormdataRouteImport - parentRoute: typeof rootRouteImport - } - '/status': { - id: '/status' - path: '/status' - fullPath: '/status' - preLoaderRoute: typeof StatusRouteImport - parentRoute: typeof rootRouteImport - } - '/serialize-form-data': { - id: '/serialize-form-data' - path: '/serialize-form-data' - fullPath: '/serialize-form-data' - preLoaderRoute: typeof SerializeFormDataRouteImport - parentRoute: typeof rootRouteImport - } - '/return-null': { - id: '/return-null' - path: '/return-null' - fullPath: '/return-null' - preLoaderRoute: typeof ReturnNullRouteImport - parentRoute: typeof rootRouteImport - } - '/raw-response': { - id: '/raw-response' - path: '/raw-response' - fullPath: '/raw-response' - preLoaderRoute: typeof RawResponseRouteImport - parentRoute: typeof rootRouteImport - } - '/multipart': { - id: '/multipart' - path: '/multipart' - fullPath: '/multipart' - preLoaderRoute: typeof MultipartRouteImport - parentRoute: typeof rootRouteImport - } - '/isomorphic-fns': { - id: '/isomorphic-fns' - path: '/isomorphic-fns' - fullPath: '/isomorphic-fns' - preLoaderRoute: typeof IsomorphicFnsRouteImport - parentRoute: typeof rootRouteImport - } - '/headers': { - id: '/headers' - path: '/headers' - fullPath: '/headers' - preLoaderRoute: typeof HeadersRouteImport - parentRoute: typeof rootRouteImport - } - '/env-only': { - id: '/env-only' - path: '/env-only' - fullPath: '/env-only' - preLoaderRoute: typeof EnvOnlyRouteImport - parentRoute: typeof rootRouteImport - } - '/dead-code-preserve': { - id: '/dead-code-preserve' - path: '/dead-code-preserve' - fullPath: '/dead-code-preserve' - preLoaderRoute: typeof DeadCodePreserveRouteImport - parentRoute: typeof rootRouteImport - } - '/consistent': { - id: '/consistent' - path: '/consistent' - fullPath: '/consistent' - preLoaderRoute: typeof ConsistentRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/abort-signal': { @@ -470,88 +426,130 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof AbortSignalRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/consistent': { + id: '/consistent' + path: '/consistent' + fullPath: '/consistent' + preLoaderRoute: typeof ConsistentRouteImport parentRoute: typeof rootRouteImport } - '/redirect-test/': { - id: '/redirect-test/' - path: '/redirect-test' - fullPath: '/redirect-test' - preLoaderRoute: typeof RedirectTestIndexRouteImport + '/dead-code-preserve': { + id: '/dead-code-preserve' + path: '/dead-code-preserve' + fullPath: '/dead-code-preserve' + preLoaderRoute: typeof DeadCodePreserveRouteImport parentRoute: typeof rootRouteImport } - '/redirect-test-ssr/': { - id: '/redirect-test-ssr/' - path: '/redirect-test-ssr' - fullPath: '/redirect-test-ssr' - preLoaderRoute: typeof RedirectTestSsrIndexRouteImport + '/env-only': { + id: '/env-only' + path: '/env-only' + fullPath: '/env-only' + preLoaderRoute: typeof EnvOnlyRouteImport parentRoute: typeof rootRouteImport } - '/primitives/': { - id: '/primitives/' - path: '/primitives' - fullPath: '/primitives' - preLoaderRoute: typeof PrimitivesIndexRouteImport + '/headers': { + id: '/headers' + path: '/headers' + fullPath: '/headers' + preLoaderRoute: typeof HeadersRouteImport parentRoute: typeof rootRouteImport } - '/middleware/': { - id: '/middleware/' - path: '/middleware' - fullPath: '/middleware' - preLoaderRoute: typeof MiddlewareIndexRouteImport + '/isomorphic-fns': { + id: '/isomorphic-fns' + path: '/isomorphic-fns' + fullPath: '/isomorphic-fns' + preLoaderRoute: typeof IsomorphicFnsRouteImport parentRoute: typeof rootRouteImport } - '/formdata-redirect/': { - id: '/formdata-redirect/' - path: '/formdata-redirect' - fullPath: '/formdata-redirect' - preLoaderRoute: typeof FormdataRedirectIndexRouteImport + '/multipart': { + id: '/multipart' + path: '/multipart' + fullPath: '/multipart' + preLoaderRoute: typeof MultipartRouteImport parentRoute: typeof rootRouteImport } - '/factory/': { - id: '/factory/' - path: '/factory' - fullPath: '/factory' - preLoaderRoute: typeof FactoryIndexRouteImport + '/raw-response': { + id: '/raw-response' + path: '/raw-response' + fullPath: '/raw-response' + preLoaderRoute: typeof RawResponseRouteImport + parentRoute: typeof rootRouteImport + } + '/return-null': { + id: '/return-null' + path: '/return-null' + fullPath: '/return-null' + preLoaderRoute: typeof ReturnNullRouteImport + parentRoute: typeof rootRouteImport + } + '/serialize-form-data': { + id: '/serialize-form-data' + path: '/serialize-form-data' + fullPath: '/serialize-form-data' + preLoaderRoute: typeof SerializeFormDataRouteImport + parentRoute: typeof rootRouteImport + } + '/status': { + id: '/status' + path: '/status' + fullPath: '/status' + preLoaderRoute: typeof StatusRouteImport + parentRoute: typeof rootRouteImport + } + '/submit-post-formdata': { + id: '/submit-post-formdata' + path: '/submit-post-formdata' + fullPath: '/submit-post-formdata' + preLoaderRoute: typeof SubmitPostFormdataRouteImport parentRoute: typeof rootRouteImport } '/cookies/': { id: '/cookies/' path: '/cookies' - fullPath: '/cookies' + fullPath: '/cookies/' preLoaderRoute: typeof CookiesIndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect-test/target': { - id: '/redirect-test/target' - path: '/redirect-test/target' - fullPath: '/redirect-test/target' - preLoaderRoute: typeof RedirectTestTargetRouteImport + '/cookies/set': { + id: '/cookies/set' + path: '/cookies/set' + fullPath: '/cookies/set' + preLoaderRoute: typeof CookiesSetRouteImport parentRoute: typeof rootRouteImport } - '/redirect-test-ssr/target': { - id: '/redirect-test-ssr/target' - path: '/redirect-test-ssr/target' - fullPath: '/redirect-test-ssr/target' - preLoaderRoute: typeof RedirectTestSsrTargetRouteImport + '/factory/': { + id: '/factory/' + path: '/factory' + fullPath: '/factory/' + preLoaderRoute: typeof FactoryIndexRouteImport parentRoute: typeof rootRouteImport } - '/middleware/send-serverFn': { - id: '/middleware/send-serverFn' - path: '/middleware/send-serverFn' - fullPath: '/middleware/send-serverFn' - preLoaderRoute: typeof MiddlewareSendServerFnRouteImport + '/formdata-redirect/': { + id: '/formdata-redirect/' + path: '/formdata-redirect' + fullPath: '/formdata-redirect/' + preLoaderRoute: typeof FormdataRedirectIndexRouteImport parentRoute: typeof rootRouteImport } - '/middleware/request-middleware': { - id: '/middleware/request-middleware' - path: '/middleware/request-middleware' - fullPath: '/middleware/request-middleware' - preLoaderRoute: typeof MiddlewareRequestMiddlewareRouteImport + '/function-metadata/': { + id: '/function-metadata/' + path: '/function-metadata' + fullPath: '/function-metadata/' + preLoaderRoute: typeof FunctionMetadataIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/function-method/': { + id: '/function-method/' + path: '/function-method' + fullPath: '/function-method/' + preLoaderRoute: typeof FunctionMethodIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/middleware/': { + id: '/middleware/' + path: '/middleware' + fullPath: '/middleware/' + preLoaderRoute: typeof MiddlewareIndexRouteImport parentRoute: typeof rootRouteImport } '/middleware/client-middleware-router': { @@ -561,11 +559,53 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof MiddlewareClientMiddlewareRouterRouteImport parentRoute: typeof rootRouteImport } - '/cookies/set': { - id: '/cookies/set' - path: '/cookies/set' - fullPath: '/cookies/set' - preLoaderRoute: typeof CookiesSetRouteImport + '/middleware/request-middleware': { + id: '/middleware/request-middleware' + path: '/middleware/request-middleware' + fullPath: '/middleware/request-middleware' + preLoaderRoute: typeof MiddlewareRequestMiddlewareRouteImport + parentRoute: typeof rootRouteImport + } + '/middleware/send-serverFn': { + id: '/middleware/send-serverFn' + path: '/middleware/send-serverFn' + fullPath: '/middleware/send-serverFn' + preLoaderRoute: typeof MiddlewareSendServerFnRouteImport + parentRoute: typeof rootRouteImport + } + '/primitives/': { + id: '/primitives/' + path: '/primitives' + fullPath: '/primitives/' + preLoaderRoute: typeof PrimitivesIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect-test-ssr/': { + id: '/redirect-test-ssr/' + path: '/redirect-test-ssr' + fullPath: '/redirect-test-ssr/' + preLoaderRoute: typeof RedirectTestSsrIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect-test-ssr/target': { + id: '/redirect-test-ssr/target' + path: '/redirect-test-ssr/target' + fullPath: '/redirect-test-ssr/target' + preLoaderRoute: typeof RedirectTestSsrTargetRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect-test/': { + id: '/redirect-test/' + path: '/redirect-test' + fullPath: '/redirect-test/' + preLoaderRoute: typeof RedirectTestIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect-test/target': { + id: '/redirect-test/target' + path: '/redirect-test/target' + fullPath: '/redirect-test/target' + preLoaderRoute: typeof RedirectTestTargetRouteImport parentRoute: typeof rootRouteImport } '/formdata-redirect/target/$name': { @@ -601,6 +641,8 @@ const rootRouteChildren: RootRouteChildren = { CookiesIndexRoute: CookiesIndexRoute, FactoryIndexRoute: FactoryIndexRoute, FormdataRedirectIndexRoute: FormdataRedirectIndexRoute, + FunctionMetadataIndexRoute: FunctionMetadataIndexRoute, + FunctionMethodIndexRoute: FunctionMethodIndexRoute, MiddlewareIndexRoute: MiddlewareIndexRoute, PrimitivesIndexRoute: PrimitivesIndexRoute, RedirectTestSsrIndexRoute: RedirectTestSsrIndexRoute, diff --git a/e2e/vue-start/server-functions/src/routes/__root.tsx b/e2e/vue-start/server-functions/src/routes/__root.tsx index 342f7a79b3..a52b12deae 100644 --- a/e2e/vue-start/server-functions/src/routes/__root.tsx +++ b/e2e/vue-start/server-functions/src/routes/__root.tsx @@ -25,7 +25,11 @@ export const Route = createRootRoute({ links: [{ rel: 'stylesheet', href: appCss }], }), errorComponent: (props) => { - return

{props.error.stack}

+ return ( +

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

+ ) }, notFoundComponent: () => , component: RootComponent, diff --git a/e2e/vue-start/server-functions/src/routes/abort-signal.tsx b/e2e/vue-start/server-functions/src/routes/abort-signal.tsx index 2a3e08ae59..1fcf89a0b4 100644 --- a/e2e/vue-start/server-functions/src/routes/abort-signal.tsx +++ b/e2e/vue-start/server-functions/src/routes/abort-signal.tsx @@ -1,27 +1,27 @@ import { createFileRoute } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' +import { getRequest } from '@tanstack/vue-start/server' import { defineComponent, ref } from 'vue' -const abortableServerFn = createServerFn().handler( - async ({ context, signal }) => { - console.log('server function started', { context, signal }) - return new Promise((resolve, reject) => { - if (signal.aborted) { - return reject(new Error('Aborted before start')) - } - const timerId = setTimeout(() => { - console.log('server function finished') - resolve('server function result') - }, 1000) - const onAbort = () => { - clearTimeout(timerId) - console.log('server function aborted') - reject(new Error('Aborted')) - } - signal.addEventListener('abort', onAbort, { once: true }) - }) - }, -) +const abortableServerFn = createServerFn().handler(async ({ context }) => { + console.log('server function started', { context }) + const signal = getRequest().signal + return new Promise((resolve, reject) => { + if (signal.aborted) { + return reject(new Error('Aborted before start')) + } + const timerId = setTimeout(() => { + console.log('server function finished') + resolve('server function result') + }, 1000) + const onAbort = () => { + clearTimeout(timerId) + console.log('server function aborted') + reject(new Error('Aborted')) + } + signal.addEventListener('abort', onAbort, { once: true }) + }) +}) const RouteComponent = defineComponent({ setup() { diff --git a/e2e/vue-start/server-functions/src/routes/consistent.tsx b/e2e/vue-start/server-functions/src/routes/consistent.tsx index 5e6b0a7e08..046f15f339 100644 --- a/e2e/vue-start/server-functions/src/routes/consistent.tsx +++ b/e2e/vue-start/server-functions/src/routes/consistent.tsx @@ -11,25 +11,25 @@ import { defineComponent, ref } from 'vue' */ const cons_getFn1 = createServerFn() - .inputValidator((d: { username: string }) => d) + .validator((d: { username: string }) => d) .handler(({ data }) => { return { payload: data } }) const cons_serverGetFn1 = createServerFn() - .inputValidator((d: { username: string }) => d) + .validator((d: { username: string }) => d) .handler(async ({ data }) => { return cons_getFn1({ data }) }) const cons_postFn1 = createServerFn({ method: 'POST' }) - .inputValidator((d: { username: string }) => d) + .validator((d: { username: string }) => d) .handler(({ data }) => { return { payload: data } }) const cons_serverPostFn1 = createServerFn({ method: 'POST' }) - .inputValidator((d: { username: string }) => d) + .validator((d: { username: string }) => d) .handler(({ data }) => { return cons_postFn1({ data }) }) diff --git a/e2e/vue-start/server-functions/src/routes/cookies/index.tsx b/e2e/vue-start/server-functions/src/routes/cookies/index.tsx index c47897c109..90dddad0af 100644 --- a/e2e/vue-start/server-functions/src/routes/cookies/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/cookies/index.tsx @@ -1,24 +1,28 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' const cookieSchema = z - .object({ value: z.string() }) + .object({ value: z.string().default(() => `CLIENT-${Date.now()}`) }) + .prefault({}) .catch(() => ({ value: `CLIENT-${Date.now()}` })) +const RouteComponent = defineComponent({ + setup() { + const search = Route.useSearch() + return () => ( + + got to route that sets the cookies with {JSON.stringify(search.value)} + + ) + }, +}) + export const Route = createFileRoute('/cookies/')({ validateSearch: cookieSchema, component: RouteComponent, }) - -function RouteComponent() { - const search = Route.useSearch() - return ( - - got to route that sets the cookies with {JSON.stringify(search.value)} - - ) -} diff --git a/e2e/vue-start/server-functions/src/routes/cookies/set.tsx b/e2e/vue-start/server-functions/src/routes/cookies/set.tsx index 39fd00b74e..bcdad36ab9 100644 --- a/e2e/vue-start/server-functions/src/routes/cookies/set.tsx +++ b/e2e/vue-start/server-functions/src/routes/cookies/set.tsx @@ -8,14 +8,14 @@ import { defineComponent, ref, watch } from 'vue' const cookieSchema = z.object({ value: z.string() }) export const setCookieServerFn1 = createServerFn() - .inputValidator(cookieSchema) + .validator(cookieSchema) .handler(({ data }) => { setCookie(`cookie-1-${data.value}`, data.value) setCookie(`cookie-2-${data.value}`, data.value) }) export const setCookieServerFn2 = createServerFn() - .inputValidator(cookieSchema) + .validator(cookieSchema) .handler(({ data }) => { setCookie(`cookie-3-${data.value}`, data.value) setCookie(`cookie-4-${data.value}`, data.value) diff --git a/e2e/vue-start/server-functions/src/routes/factory/-functions/createBarServerFn.ts b/e2e/vue-start/server-functions/src/routes/factory/-functions/createBarServerFn.ts index bff6685917..3b25564a0d 100644 --- a/e2e/vue-start/server-functions/src/routes/factory/-functions/createBarServerFn.ts +++ b/e2e/vue-start/server-functions/src/routes/factory/-functions/createBarServerFn.ts @@ -13,10 +13,11 @@ const barMiddleware = createMiddleware({ type: 'function' }).server( export const createBarServerFn = createFooServerFn().middleware([barMiddleware]) export const barFnInsideFactoryFile = createBarServerFn().handler( - ({ context }) => { + ({ context, method }) => { return { name: 'barFnInsideFactoryFile', context, + method, } }, ) diff --git a/e2e/vue-start/server-functions/src/routes/factory/-functions/createFooServerFn.ts b/e2e/vue-start/server-functions/src/routes/factory/-functions/createFooServerFn.ts index d75084b7ff..ed9725f335 100644 --- a/e2e/vue-start/server-functions/src/routes/factory/-functions/createFooServerFn.ts +++ b/e2e/vue-start/server-functions/src/routes/factory/-functions/createFooServerFn.ts @@ -14,11 +14,12 @@ const fooMiddleware = createMiddleware({ type: 'function' }).server( export const createFooServerFn = createServerFn().middleware([fooMiddleware]) export const fooFnInsideFactoryFile = createFooServerFn().handler( - async ({ context }) => { + async ({ context, method }) => { console.log('fooFnInsideFactoryFile handler triggered', context.method) return { name: 'fooFnInsideFactoryFile', context, + method, } }, ) diff --git a/e2e/vue-start/server-functions/src/routes/factory/-functions/functions.ts b/e2e/vue-start/server-functions/src/routes/factory/-functions/functions.ts index 190791a599..e7ec22127d 100644 --- a/e2e/vue-start/server-functions/src/routes/factory/-functions/functions.ts +++ b/e2e/vue-start/server-functions/src/routes/factory/-functions/functions.ts @@ -3,34 +3,38 @@ import { createBarServerFn } from './createBarServerFn' import { createFooServerFn } from './createFooServerFn' import { createFakeFn } from './createFakeFn' -export const fooFn = createFooServerFn().handler(({ context }) => { +export const fooFn = createFooServerFn().handler(({ context, method }) => { return { name: 'fooFn', context, + method, } }) export const fooFnPOST = createFooServerFn({ method: 'POST' }).handler( - ({ context }) => { + ({ context, method }) => { return { name: 'fooFnPOST', context, + method, } }, ) -export const barFn = createBarServerFn().handler(({ context }) => { +export const barFn = createBarServerFn().handler(({ context, method }) => { return { name: 'barFn', context, + method, } }) export const barFnPOST = createBarServerFn({ method: 'POST' }).handler( - ({ context }) => { + ({ context, method }) => { return { name: 'barFnPOST', context, + method, } }, ) @@ -57,19 +61,21 @@ const anotherMiddleware = createMiddleware({ type: 'function' }).server( export const localFn = localFnFactory() .middleware([anotherMiddleware]) - .handler(({ context }) => { + .handler(({ context, method }) => { return { name: 'localFn', context, + method, } }) export const localFnPOST = localFnFactory({ method: 'POST' }) .middleware([anotherMiddleware]) - .handler(({ context }) => { + .handler(({ context, method }) => { return { name: 'localFnPOST', context, + method, } }) @@ -85,9 +91,10 @@ export const composeFactory = createServerFn({ method: 'GET' }).middleware([ ]) export const composedFn = composeFactory() .middleware([anotherMiddleware, localFnFactory]) - .handler(({ context }) => { + .handler(({ context, method }) => { return { name: 'composedFn', context, + method, } }) diff --git a/e2e/vue-start/server-functions/src/routes/factory/index.tsx b/e2e/vue-start/server-functions/src/routes/factory/index.tsx index 8ddf7e6fbc..c02bb1338e 100644 --- a/e2e/vue-start/server-functions/src/routes/factory/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/factory/index.tsx @@ -15,11 +15,14 @@ import { import { computed, defineComponent, ref } from 'vue' import type { PropType } from 'vue' -const fnInsideRoute = createServerFn({ method: 'GET' }).handler(() => { - return { - name: 'fnInsideRoute', - } -}) +const fnInsideRoute = createServerFn({ method: 'GET' }).handler( + ({ method }) => { + return { + name: 'fnInsideRoute', + method, + } + }, +) const functions = { fnInsideRoute: { @@ -27,6 +30,7 @@ const functions = { type: 'serverFn', expected: { name: 'fnInsideRoute', + method: 'GET', }, }, fooFnInsideFactoryFile: { @@ -36,6 +40,7 @@ const functions = { expected: { name: 'fooFnInsideFactoryFile', context: { foo: 'foo', method: 'GET' }, + method: 'GET', }, }, fooFn: { @@ -45,6 +50,7 @@ const functions = { expected: { name: 'fooFn', context: { foo: 'foo', method: 'GET' }, + method: 'GET', }, }, fooFnPOST: { @@ -54,6 +60,7 @@ const functions = { expected: { name: 'fooFnPOST', context: { foo: 'foo', method: 'POST' }, + method: 'POST', }, }, barFn: { @@ -63,6 +70,7 @@ const functions = { expected: { name: 'barFn', context: { foo: 'foo', method: 'GET', bar: 'bar' }, + method: 'GET', }, }, barFnPOST: { @@ -72,6 +80,7 @@ const functions = { expected: { name: 'barFnPOST', context: { foo: 'foo', method: 'POST', bar: 'bar' }, + method: 'POST', }, }, localFn: { @@ -87,6 +96,7 @@ const functions = { local: 'local', another: 'another', }, + method: 'GET', }, }, localFnPOST: { @@ -102,6 +112,7 @@ const functions = { local: 'local', another: 'another', }, + method: 'POST', }, }, composedFn: { @@ -116,6 +127,7 @@ const functions = { another: 'another', local: 'local', }, + method: 'GET', }, }, fakeFn: { diff --git a/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx b/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx index d23eb342b3..8bfcc55ca3 100644 --- a/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx @@ -1,7 +1,51 @@ +import { defineComponent } from 'vue' import { createFileRoute, redirect } from '@tanstack/vue-router' import { createServerFn, useServerFn } from '@tanstack/vue-start' import { z } from 'zod' +const SubmitPostFormDataFn = defineComponent({ + setup() { + const mode = Route.useSearch({ select: (search) => search.mode }) + const greetUserFn = useServerFn(greetUser) + return () => ( +
+

Submit POST FormData Fn Call

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

Submit POST FormData Fn Call

-
- It should return redirect to /formdata-redirect/target/{testValues.name}{' '} - and greet the user with their name: - -
-            {testValues.name}
-          
-
-
-
{ - if (mode.value === 'js') { - evt.preventDefault() - const data = new FormData(evt.currentTarget as HTMLFormElement) - await greetUserFn({ data }) - } - }} - > - - -
-
- ) -} diff --git a/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx b/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx index 958aeaf617..099a8665bf 100644 --- a/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx +++ b/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx @@ -1,18 +1,21 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' +const RouteComponent = defineComponent({ + setup() { + const params = Route.useParams() + return () => ( +
+ Hello{' '} + + {params.value.name} + + ! +
+ ) + }, +}) + export const Route = createFileRoute('/formdata-redirect/target/$name')({ component: RouteComponent, }) - -function RouteComponent() { - const params = Route.useParams() - return ( -
- Hello{' '} - - {params.value.name} - - ! -
- ) -} diff --git a/e2e/vue-start/server-functions/src/routes/function-metadata/-functions/normalServerFn.ts b/e2e/vue-start/server-functions/src/routes/function-metadata/-functions/normalServerFn.ts new file mode 100644 index 0000000000..907ac9df67 --- /dev/null +++ b/e2e/vue-start/server-functions/src/routes/function-metadata/-functions/normalServerFn.ts @@ -0,0 +1,11 @@ +import { createServerFn } from '@tanstack/vue-start' + +export const getServerFn = createServerFn().handler(({ serverFnMeta }) => { + return serverFnMeta +}) + +export const postServerFn = createServerFn({ method: 'POST' }).handler( + ({ serverFnMeta }) => { + return serverFnMeta + }, +) diff --git a/e2e/vue-start/server-functions/src/routes/function-metadata/-functions/serverFnCallingServerFn.ts b/e2e/vue-start/server-functions/src/routes/function-metadata/-functions/serverFnCallingServerFn.ts new file mode 100644 index 0000000000..00f0809834 --- /dev/null +++ b/e2e/vue-start/server-functions/src/routes/function-metadata/-functions/serverFnCallingServerFn.ts @@ -0,0 +1,32 @@ +import { createServerFn } from '@tanstack/vue-start' +import { getServerFn, postServerFn } from './normalServerFn' + +export const getServerFnCallingServerFn = createServerFn().handler( + async ({ serverFnMeta }) => { + const post = await postServerFn() + const get = await getServerFn() + + return { + meta: serverFnMeta, + inner: { + get, + post, + }, + } + }, +) + +export const postServerFnCallingServerFn = createServerFn().handler( + async ({ serverFnMeta }) => { + const post = await postServerFn() + const get = await getServerFn() + + return { + meta: serverFnMeta, + inner: { + get, + post, + }, + } + }, +) diff --git a/e2e/vue-start/server-functions/src/routes/function-metadata/index.tsx b/e2e/vue-start/server-functions/src/routes/function-metadata/index.tsx new file mode 100644 index 0000000000..51e738bc72 --- /dev/null +++ b/e2e/vue-start/server-functions/src/routes/function-metadata/index.tsx @@ -0,0 +1,65 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { defineComponent } from 'vue' +import { getServerFn, postServerFn } from './-functions/normalServerFn' +import { + getServerFnCallingServerFn, + postServerFnCallingServerFn, +} from './-functions/serverFnCallingServerFn' + +const RouteComponent = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + + return () => ( +
+

Server functions metadata E2E tests

+
+
+

Loader Data (SSR)

+

Server Captured Metadata:

+
+ Function Metadata:{' '} + + {JSON.stringify(loaderData.value.normalGet)} + +
+
+ Function Metadata:{' '} + + {JSON.stringify(loaderData.value.normalPost)} + +
+
+ Function Metadata:{' '} + + {JSON.stringify(loaderData.value.nestingGet)} + +
+
+ Function Metadata:{' '} + + {JSON.stringify(loaderData.value.nestingPost)} + +
+
+
+ ) + }, +}) + +export const Route = createFileRoute('/function-metadata/')({ + component: RouteComponent, + loader: async () => { + const normalGet = await getServerFn() + const normalPost = await postServerFn() + const nestingGet = await getServerFnCallingServerFn() + const nestingPost = await postServerFnCallingServerFn() + + return { + normalGet, + normalPost, + nestingGet, + nestingPost, + } + }, +}) diff --git a/e2e/vue-start/server-functions/src/routes/function-method/-functions/serverFnCallingServerFn.ts b/e2e/vue-start/server-functions/src/routes/function-method/-functions/serverFnCallingServerFn.ts new file mode 100644 index 0000000000..419640c59c --- /dev/null +++ b/e2e/vue-start/server-functions/src/routes/function-method/-functions/serverFnCallingServerFn.ts @@ -0,0 +1,39 @@ +import { createServerFn } from '@tanstack/vue-start' + +const postServerFn = createServerFn({ method: 'POST' }).handler( + ({ method }) => { + return { + method, + } + }, +) + +const getServerFn = createServerFn({ method: 'GET' }).handler(({ method }) => { + return { + method, + } +}) + +export const getServerFnCallingPost = createServerFn({ method: 'GET' }).handler( + async ({ method }) => { + const innerFnResult = await postServerFn({}) + + return { + name: 'getServerFnCallingPost', + method, + innerFnResult, + } + }, +) + +export const postServerFnCallingGet = createServerFn({ + method: 'POST', +}).handler(async ({ method }) => { + const innerFnResult = await getServerFn({}) + + return { + name: 'postServerFnCallingGet', + method, + innerFnResult, + } +}) diff --git a/e2e/vue-start/server-functions/src/routes/function-method/index.tsx b/e2e/vue-start/server-functions/src/routes/function-method/index.tsx new file mode 100644 index 0000000000..a4cb3951d5 --- /dev/null +++ b/e2e/vue-start/server-functions/src/routes/function-method/index.tsx @@ -0,0 +1,117 @@ +import { Link, createFileRoute, deepEqual } from '@tanstack/vue-router' +import { computed, defineComponent, ref } from 'vue' +import { + getServerFnCallingPost, + postServerFnCallingGet, +} from './-functions/serverFnCallingServerFn' +import type { PropType } from 'vue' + +const functions = { + getServerFnCallingPost: { + fn: getServerFnCallingPost, + expected: { + name: 'getServerFnCallingPost', + method: 'GET', + innerFnResult: { + method: 'POST', + }, + }, + }, + postServerFnCallingGet: { + fn: postServerFnCallingGet, + expected: { + name: 'postServerFnCallingGet', + method: 'POST', + innerFnResult: { + method: 'GET', + }, + }, + }, +} satisfies Record + +interface TestCase { + fn: () => Promise + expected: any +} +const Test = defineComponent({ + props: { + fn: { + type: Function as PropType<() => Promise>, + required: true, + }, + expected: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const result = ref(null) + const comparison = computed(() => { + if (result.value) { + const isEqual = deepEqual(result.value, props.expected) + return isEqual ? 'equal' : 'not equal' + } + return 'Loading...' + }) + + return () => ( +
+
+ It should return{' '} + +
+              {JSON.stringify(props.expected)}
+            
+
+
+

+ fn returns: +
+ + {result.value ? JSON.stringify(result.value) : 'Loading...'} + {' '} + + {comparison.value} + +

+ +
+ ) + }, +}) + +const RouteComponent = defineComponent({ + setup() { + return () => ( +
+

Server functions methods E2E tests

+
+ +

Go to Factory Functions and request method E2E test

+ +
+ {Object.entries(functions).map(([name, testCase]) => ( + + ))} +
+ ) + }, +}) + +export const Route = createFileRoute('/function-method/')({ + component: RouteComponent, +}) diff --git a/e2e/vue-start/server-functions/src/routes/index.tsx b/e2e/vue-start/server-functions/src/routes/index.tsx index 155fb3dff1..1f9bb4e06b 100644 --- a/e2e/vue-start/server-functions/src/routes/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/index.tsx @@ -72,6 +72,14 @@ function Home() {
  • server function returns raw response
  • +
  • + Server Functions method E2E tests +
  • +
  • + + Server Functions metadata E2E tests + +
  • ) diff --git a/e2e/vue-start/server-functions/src/routes/isomorphic-fns.tsx b/e2e/vue-start/server-functions/src/routes/isomorphic-fns.tsx index 6d0679e34d..8764b558a2 100644 --- a/e2e/vue-start/server-functions/src/routes/isomorphic-fns.tsx +++ b/e2e/vue-start/server-functions/src/routes/isomorphic-fns.tsx @@ -13,7 +13,7 @@ const getEcho = createIsomorphicFn() .client((input) => 'client received ' + input) const getServerEcho = createServerFn() - .inputValidator((input: string) => input) + .validator((input: string) => input) .handler(({ data }) => getEcho(data)) const RouteComponent = defineComponent({ diff --git a/e2e/vue-start/server-functions/src/routes/multipart.tsx b/e2e/vue-start/server-functions/src/routes/multipart.tsx index c41fd8e4e5..2157ed3922 100644 --- a/e2e/vue-start/server-functions/src/routes/multipart.tsx +++ b/e2e/vue-start/server-functions/src/routes/multipart.tsx @@ -3,7 +3,7 @@ import { createServerFn } from '@tanstack/vue-start' import { defineComponent, ref } from 'vue' const multipartFormDataServerFn = createServerFn({ method: 'POST' }) - .inputValidator((x: unknown) => { + .validator((x: unknown) => { if (!(x instanceof FormData)) { throw new Error('Invalid form data') } diff --git a/e2e/vue-start/server-functions/src/routes/primitives/index.tsx b/e2e/vue-start/server-functions/src/routes/primitives/index.tsx index 561f7646eb..2f856bb7f3 100644 --- a/e2e/vue-start/server-functions/src/routes/primitives/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/primitives/index.tsx @@ -9,27 +9,27 @@ function stringify(data: any) { } const $stringPost = createServerFn({ method: 'POST' }) - .inputValidator(z.string()) + .validator(z.string()) .handler((ctx) => ctx.data) const $stringGet = createServerFn({ method: 'GET' }) - .inputValidator(z.string()) + .validator(z.string()) .handler((ctx) => ctx.data) const $undefinedPost = createServerFn({ method: 'POST' }) - .inputValidator(z.undefined()) + .validator(z.undefined()) .handler((ctx) => ctx.data) const $undefinedGet = createServerFn({ method: 'GET' }) - .inputValidator(z.undefined()) + .validator(z.undefined()) .handler((ctx) => ctx.data) const $nullPost = createServerFn({ method: 'POST' }) - .inputValidator(z.null()) + .validator(z.null()) .handler((ctx) => ctx.data) const $nullGet = createServerFn({ method: 'GET' }) - .inputValidator(z.null()) + .validator(z.null()) .handler((ctx) => ctx.data) interface PrimitiveComponentProps { diff --git a/e2e/vue-start/server-functions/src/routes/serialize-form-data.tsx b/e2e/vue-start/server-functions/src/routes/serialize-form-data.tsx index e2b117a9ad..4aaf8eec60 100644 --- a/e2e/vue-start/server-functions/src/routes/serialize-form-data.tsx +++ b/e2e/vue-start/server-functions/src/routes/serialize-form-data.tsx @@ -11,7 +11,7 @@ const testValues = { } export const greetUser = createServerFn({ method: 'POST' }) - .inputValidator((data: FormData) => { + .validator((data: FormData) => { if (!(data instanceof FormData)) { throw new Error('Invalid! FormData is required') } diff --git a/e2e/vue-start/server-functions/src/routes/submit-post-formdata.tsx b/e2e/vue-start/server-functions/src/routes/submit-post-formdata.tsx index 35e083326d..3bbc85a163 100644 --- a/e2e/vue-start/server-functions/src/routes/submit-post-formdata.tsx +++ b/e2e/vue-start/server-functions/src/routes/submit-post-formdata.tsx @@ -10,7 +10,7 @@ const testValues = { } export const greetUser = createServerFn({ method: 'POST' }) - .inputValidator((data: FormData) => { + .validator((data: FormData) => { if (!(data instanceof FormData)) { throw new Error('Invalid! FormData is required') } diff --git a/e2e/vue-start/server-functions/src/styles/app.css b/e2e/vue-start/server-functions/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/e2e/vue-start/server-functions/src/styles/app.css +++ b/e2e/vue-start/server-functions/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-start/server-functions/src/vite-env.d.ts b/e2e/vue-start/server-functions/src/vite-env.d.ts index 0b2af560d6..d0b512cd80 100644 --- a/e2e/vue-start/server-functions/src/vite-env.d.ts +++ b/e2e/vue-start/server-functions/src/vite-env.d.ts @@ -1,3 +1,5 @@ +/// + declare module '*?url' { const url: string export default url diff --git a/e2e/vue-start/server-functions/tests/server-functions.spec.ts b/e2e/vue-start/server-functions/tests/server-functions.spec.ts index 3b32deb5bd..634642240a 100644 --- a/e2e/vue-start/server-functions/tests/server-functions.spec.ts +++ b/e2e/vue-start/server-functions/tests/server-functions.spec.ts @@ -495,3 +495,141 @@ test('redirect in server function called in query during SSR', async ({ await expect(page.getByTestId('redirect-target-ssr')).toBeVisible() expect(page.url()).toContain('/redirect-test-ssr/target') }) + +test('server function is called with correct method option', async ({ + page, +}) => { + await page.goto('/function-method', { waitUntil: 'networkidle' }) + + await expect(page.getByTestId('method-route-component')).toBeInViewport() + + const buttons = await page + .locator('[data-testid^="btn-fn-"]') + .elementHandles() + for (const button of buttons) { + const testId = await button.getAttribute('data-testid') + + if (!testId) { + throw new Error('Button is missing data-testid') + } + + const suffix = testId.replace('btn-fn-', '') + + const expected = + (await page.getByTestId(`expected-fn-result-${suffix}`).textContent()) || + '' + expect(expected).not.toBe('') + + await button.click() + + await expect(page.getByTestId(`fn-result-${suffix}`)).toContainText( + expected, + ) + + await expect(page.getByTestId(`fn-comparison-${suffix}`)).toContainText( + 'equal', + ) + } +}) + +test('server function receives serverFnMeta in options', async ({ page }) => { + // This test verifies that: + // 1. Server functions receive `serverFnMeta` with full { id, name, filename } + // 2. No1 works even when the said server function is called from another server function + + await page.goto('/function-metadata', { waitUntil: 'networkidle' }) + + await expect(page.getByTestId('metadata-route-component')).toBeInViewport() + + // Test for no1 + const loaderNormalGet = await page + .getByTestId('loader-normal-get-function-metadata') + .textContent() + const loaderNormalPost = await page + .getByTestId('loader-normal-post-function-metadata') + .textContent() + + // stringified metadata should not be empty string + expect(loaderNormalGet).toBeTruthy() + // metadata should have `id`, `name`, and `filename` property, with all of them being a non-empty string + const normalGetMetadata = JSON.parse(loaderNormalGet!) + expect(normalGetMetadata).toHaveProperty('id') + expect(normalGetMetadata).toHaveProperty('name') + expect(normalGetMetadata).toHaveProperty('filename') + expect(typeof normalGetMetadata.id).toBe('string') + expect(normalGetMetadata.id.length).toBeGreaterThan(0) + expect(typeof normalGetMetadata.name).toBe('string') + expect(normalGetMetadata.name.length).toBeGreaterThan(0) + expect(typeof normalGetMetadata.filename).toBe('string') + expect(normalGetMetadata.filename.length).toBeGreaterThan(0) + + // stringified metadata should not be empty string + expect(loaderNormalPost).toBeTruthy() + // metadata should have `id`, `name`, and `filename` property, with all of them being a non-empty string + const normalPostMetadata = JSON.parse(loaderNormalPost!) + expect(normalPostMetadata).toHaveProperty('id') + expect(normalPostMetadata).toHaveProperty('name') + expect(normalPostMetadata).toHaveProperty('filename') + expect(typeof normalPostMetadata.id).toBe('string') + expect(normalPostMetadata.id.length).toBeGreaterThan(0) + expect(typeof normalPostMetadata.name).toBe('string') + expect(normalPostMetadata.name.length).toBeGreaterThan(0) + expect(typeof normalPostMetadata.filename).toBe('string') + expect(normalPostMetadata.filename.length).toBeGreaterThan(0) + + // Test for no2 + const loaderNestingGet = await page + .getByTestId('loader-nesting-get-function-metadata') + .textContent() + const loaderNestingPost = await page + .getByTestId('loader-nesting-post-function-metadata') + .textContent() + + // metadata should have `id`, `name`, and `filename` property, with all of them being a non-empty string + const nestingGetMetadata = JSON.parse(loaderNestingGet!) + expect(nestingGetMetadata).toHaveProperty('meta.id') + expect(nestingGetMetadata).toHaveProperty('meta.name') + expect(nestingGetMetadata).toHaveProperty('meta.filename') + expect(typeof nestingGetMetadata.meta.id).toBe('string') + expect(nestingGetMetadata.meta.id.length).toBeGreaterThan(0) + expect(typeof nestingGetMetadata.meta.name).toBe('string') + expect(nestingGetMetadata.meta.name.length).toBeGreaterThan(0) + expect(typeof nestingGetMetadata.meta.filename).toBe('string') + expect(nestingGetMetadata.meta.filename.length).toBeGreaterThan(0) + expect(nestingGetMetadata).toHaveProperty('inner.get.id') + expect(nestingGetMetadata).toHaveProperty('inner.get.name') + expect(nestingGetMetadata).toHaveProperty('inner.get.filename') + expect(nestingGetMetadata.inner.get.id.length).toBeGreaterThan(0) + expect(nestingGetMetadata.inner.get.name.length).toBeGreaterThan(0) + expect(nestingGetMetadata.inner.get.filename.length).toBeGreaterThan(0) + expect(nestingGetMetadata).toHaveProperty('inner.post.id') + expect(nestingGetMetadata).toHaveProperty('inner.post.name') + expect(nestingGetMetadata).toHaveProperty('inner.post.filename') + expect(nestingGetMetadata.inner.post.id.length).toBeGreaterThan(0) + expect(nestingGetMetadata.inner.post.name.length).toBeGreaterThan(0) + expect(nestingGetMetadata.inner.post.filename.length).toBeGreaterThan(0) + + // metadata should have `id`, `name`, and `filename` property, with all of them being a non-empty string + const nestingPostMetadata = JSON.parse(loaderNestingPost!) + expect(nestingPostMetadata).toHaveProperty('meta.id') + expect(nestingPostMetadata).toHaveProperty('meta.name') + expect(nestingPostMetadata).toHaveProperty('meta.filename') + expect(typeof nestingPostMetadata.meta.id).toBe('string') + expect(nestingPostMetadata.meta.id.length).toBeGreaterThan(0) + expect(typeof nestingPostMetadata.meta.name).toBe('string') + expect(nestingPostMetadata.meta.name.length).toBeGreaterThan(0) + expect(typeof nestingPostMetadata.meta.filename).toBe('string') + expect(nestingPostMetadata.meta.filename.length).toBeGreaterThan(0) + expect(nestingPostMetadata).toHaveProperty('inner.get.id') + expect(nestingPostMetadata).toHaveProperty('inner.get.name') + expect(nestingPostMetadata).toHaveProperty('inner.get.filename') + expect(nestingPostMetadata.inner.get.id.length).toBeGreaterThan(0) + expect(nestingPostMetadata.inner.get.name.length).toBeGreaterThan(0) + expect(nestingPostMetadata.inner.get.filename.length).toBeGreaterThan(0) + expect(nestingPostMetadata).toHaveProperty('inner.post.id') + expect(nestingPostMetadata).toHaveProperty('inner.post.name') + expect(nestingPostMetadata).toHaveProperty('inner.post.filename') + expect(nestingPostMetadata.inner.post.id.length).toBeGreaterThan(0) + expect(nestingPostMetadata.inner.post.name.length).toBeGreaterThan(0) + expect(nestingPostMetadata.inner.post.filename.length).toBeGreaterThan(0) +}) diff --git a/e2e/vue-start/server-functions/tsconfig.json b/e2e/vue-start/server-functions/tsconfig.json index a5ae5ae7e4..d5b41741d2 100644 --- a/e2e/vue-start/server-functions/tsconfig.json +++ b/e2e/vue-start/server-functions/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/server-functions/vite.config.ts b/e2e/vue-start/server-functions/vite.config.ts index 4c4af226a3..362cf4e122 100644 --- a/e2e/vue-start/server-functions/vite.config.ts +++ b/e2e/vue-start/server-functions/vite.config.ts @@ -1,8 +1,8 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' const FUNCTIONS_WITH_CONSTANT_ID = [ 'src/routes/submit-post-formdata.tsx/greetUser_createServerFn_handler', @@ -10,13 +10,12 @@ const FUNCTIONS_WITH_CONSTANT_ID = [ ] export default defineConfig({ + resolve: { tsconfigPaths: true }, server: { port: 3000, }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), + tailwindcss(), tanstackStart({ serverFns: { generateFunctionId: (opts) => { diff --git a/e2e/vue-start/server-routes/.devcontainer/devcontainer.json b/e2e/vue-start/server-routes/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/server-routes/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/server-routes/package.json b/e2e/vue-start/server-routes/package.json index 680edbd581..6a8e1babed 100644 --- a/e2e/vue-start/server-routes/package.json +++ b/e2e/vue-start/server-routes/package.json @@ -18,25 +18,24 @@ "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", "js-cookie": "^3.0.5", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "vite": "^7.1.7", + "redaxios": "catalog:", + "tailwind-merge": "^3.6.0", "vue": "^3.5.25", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@tailwindcss/postcss": "^4.1.15", + "@playwright/test": "^1.61.0", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/js-cookie": "^3.0.6", "@types/node": "^22.10.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "postcss": "^8.5.1", - "srvx": "^0.9.8", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "@vitejs/plugin-vue": "^6.0.3", - "@vitejs/plugin-vue-jsx": "^5.1.2", - "vite-tsconfig-paths": "^5.1.4" + "srvx": "^1.0.0", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/e2e/vue-start/server-routes/playwright.config.ts b/e2e/vue-start/server-routes/playwright.config.ts index cb1da03b94..48e14683f4 100644 --- a/e2e/vue-start/server-routes/playwright.config.ts +++ b/e2e/vue-start/server-routes/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -export const PORT = await getTestServerPort(packageJson.name) +export const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/server-routes/postcss.config.mjs b/e2e/vue-start/server-routes/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-start/server-routes/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx index b1f818dd74..77c03c5afa 100644 --- a/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx @@ -1,53 +1,61 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error(error) - - return ( -
    - -
    - - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
    -
    - ) -} +export const DefaultCatchBoundary = defineComponent({ + props: { + error: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + return () => { + console.error(props.error) + return ( +
    + +
    + + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
    +
    + ) + } + }, +}) diff --git a/e2e/vue-start/server-routes/src/routeTree.gen.ts b/e2e/vue-start/server-routes/src/routeTree.gen.ts index 7d9d463772..603560da2a 100644 --- a/e2e/vue-start/server-routes/src/routeTree.gen.ts +++ b/e2e/vue-start/server-routes/src/routeTree.gen.ts @@ -9,16 +9,21 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' import { Route as MergeMiddlewareContextRouteImport } from './routes/merge-middleware-context' import { Route as MethodsRouteRouteImport } from './routes/methods/route' -import { Route as IndexRouteImport } from './routes/index' +import { Route as ApiMiddlewareContextRouteImport } from './routes/api/middleware-context' +import { Route as ApiOnlyAnyRouteImport } from './routes/api/only-any' import { Route as MethodsIndexRouteImport } from './routes/methods/index' import { Route as MethodsOnlyAnyRouteImport } from './routes/methods/only-any' -import { Route as ApiOnlyAnyRouteImport } from './routes/api/only-any' -import { Route as ApiMiddlewareContextRouteImport } from './routes/api/middleware-context' import { Route as ApiParamsFooRouteRouteImport } from './routes/api/params/$foo/route' import { Route as ApiParamsFooBarRouteImport } from './routes/api/params/$foo/$bar' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const MergeMiddlewareContextRoute = MergeMiddlewareContextRouteImport.update({ id: '/merge-middleware-context', path: '/merge-middleware-context', @@ -29,9 +34,14 @@ const MethodsRouteRoute = MethodsRouteRouteImport.update({ path: '/methods', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ApiMiddlewareContextRoute = ApiMiddlewareContextRouteImport.update({ + id: '/api/middleware-context', + path: '/api/middleware-context', + getParentRoute: () => rootRouteImport, +} as any) +const ApiOnlyAnyRoute = ApiOnlyAnyRouteImport.update({ + id: '/api/only-any', + path: '/api/only-any', getParentRoute: () => rootRouteImport, } as any) const MethodsIndexRoute = MethodsIndexRouteImport.update({ @@ -44,16 +54,6 @@ const MethodsOnlyAnyRoute = MethodsOnlyAnyRouteImport.update({ path: '/only-any', getParentRoute: () => MethodsRouteRoute, } as any) -const ApiOnlyAnyRoute = ApiOnlyAnyRouteImport.update({ - id: '/api/only-any', - path: '/api/only-any', - getParentRoute: () => rootRouteImport, -} as any) -const ApiMiddlewareContextRoute = ApiMiddlewareContextRouteImport.update({ - id: '/api/middleware-context', - path: '/api/middleware-context', - getParentRoute: () => rootRouteImport, -} as any) const ApiParamsFooRouteRoute = ApiParamsFooRouteRouteImport.update({ id: '/api/params/$foo', path: '/api/params/$foo', @@ -144,6 +144,13 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/merge-middleware-context': { id: '/merge-middleware-context' path: '/merge-middleware-context' @@ -158,11 +165,18 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof MethodsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/api/middleware-context': { + id: '/api/middleware-context' + path: '/api/middleware-context' + fullPath: '/api/middleware-context' + preLoaderRoute: typeof ApiMiddlewareContextRouteImport + parentRoute: typeof rootRouteImport + } + '/api/only-any': { + id: '/api/only-any' + path: '/api/only-any' + fullPath: '/api/only-any' + preLoaderRoute: typeof ApiOnlyAnyRouteImport parentRoute: typeof rootRouteImport } '/methods/': { @@ -179,20 +193,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof MethodsOnlyAnyRouteImport parentRoute: typeof MethodsRouteRoute } - '/api/only-any': { - id: '/api/only-any' - path: '/api/only-any' - fullPath: '/api/only-any' - preLoaderRoute: typeof ApiOnlyAnyRouteImport - parentRoute: typeof rootRouteImport - } - '/api/middleware-context': { - id: '/api/middleware-context' - path: '/api/middleware-context' - fullPath: '/api/middleware-context' - preLoaderRoute: typeof ApiMiddlewareContextRouteImport - parentRoute: typeof rootRouteImport - } '/api/params/$foo': { id: '/api/params/$foo' path: '/api/params/$foo' diff --git a/e2e/vue-start/server-routes/src/routes/__root.tsx b/e2e/vue-start/server-routes/src/routes/__root.tsx index 999d80fff1..aa4b1f31fa 100644 --- a/e2e/vue-start/server-routes/src/routes/__root.tsx +++ b/e2e/vue-start/server-routes/src/routes/__root.tsx @@ -25,7 +25,11 @@ export const Route = createRootRoute({ links: [{ rel: 'stylesheet', href: appCss }], }), errorComponent: (props) => { - return

    {props.error.stack}

    + return ( +

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

    + ) }, notFoundComponent: () => , component: RootComponent, diff --git a/e2e/vue-start/server-routes/src/routes/api/middleware-context.ts b/e2e/vue-start/server-routes/src/routes/api/middleware-context.ts index d780d2ebb7..c3756d0410 100644 --- a/e2e/vue-start/server-routes/src/routes/api/middleware-context.ts +++ b/e2e/vue-start/server-routes/src/routes/api/middleware-context.ts @@ -1,5 +1,5 @@ import { createFileRoute } from '@tanstack/vue-router' -import { createMiddleware, json } from '@tanstack/vue-start' +import { createMiddleware } from '@tanstack/vue-start' const testParentMiddleware = createMiddleware().server(async ({ next }) => { const result = await next({ context: { testParent: true } }) @@ -18,7 +18,7 @@ export const Route = createFileRoute('/api/middleware-context')({ middleware: [testMiddleware], handlers: { GET: ({ request, context }) => { - return json({ + return Response.json({ url: request.url, context: context, expectedContext: { testParent: true, test: true }, diff --git a/e2e/vue-start/server-routes/src/routes/api/only-any.ts b/e2e/vue-start/server-routes/src/routes/api/only-any.ts index ded160acc1..493688c9c1 100644 --- a/e2e/vue-start/server-routes/src/routes/api/only-any.ts +++ b/e2e/vue-start/server-routes/src/routes/api/only-any.ts @@ -1,11 +1,10 @@ import { createFileRoute } from '@tanstack/vue-router' -import { json } from '@tanstack/vue-start' export const Route = createFileRoute('/api/only-any')({ server: { handlers: { ANY: ({ request }) => { - return json( + return Response.json( { handler: 'ANY', method: request.method, diff --git a/e2e/vue-start/server-routes/src/styles/app.css b/e2e/vue-start/server-routes/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/e2e/vue-start/server-routes/src/styles/app.css +++ b/e2e/vue-start/server-routes/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-start/server-routes/src/vite-env.d.ts b/e2e/vue-start/server-routes/src/vite-env.d.ts index 0b2af560d6..d0b512cd80 100644 --- a/e2e/vue-start/server-routes/src/vite-env.d.ts +++ b/e2e/vue-start/server-routes/src/vite-env.d.ts @@ -1,3 +1,5 @@ +/// + declare module '*?url' { const url: string export default url diff --git a/e2e/vue-start/server-routes/tsconfig.json b/e2e/vue-start/server-routes/tsconfig.json index a5ae5ae7e4..d5b41741d2 100644 --- a/e2e/vue-start/server-routes/tsconfig.json +++ b/e2e/vue-start/server-routes/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/server-routes/vite.config.ts b/e2e/vue-start/server-routes/vite.config.ts index 79edfc05c2..563e212077 100644 --- a/e2e/vue-start/server-routes/vite.config.ts +++ b/e2e/vue-start/server-routes/vite.config.ts @@ -1,19 +1,13 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - vue(), - vueJsx(), - ], + plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], }) diff --git a/e2e/vue-start/spa-mode/.devcontainer/devcontainer.json b/e2e/vue-start/spa-mode/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/spa-mode/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/spa-mode/package.json b/e2e/vue-start/spa-mode/package.json index 94f344a393..c4270cfccd 100644 --- a/e2e/vue-start/spa-mode/package.json +++ b/e2e/vue-start/spa-mode/package.json @@ -9,24 +9,23 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "npx serve dist/client", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", "vue": "^3.5.25", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "@vitejs/plugin-vue": "^6.0.3", - "@vitejs/plugin-vue-jsx": "^5.1.2", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/e2e/vue-start/spa-mode/playwright.config.ts b/e2e/vue-start/spa-mode/playwright.config.ts index badd6db0eb..630989e41f 100644 --- a/e2e/vue-start/spa-mode/playwright.config.ts +++ b/e2e/vue-start/spa-mode/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/spa-mode/postcss.config.mjs b/e2e/vue-start/spa-mode/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-start/spa-mode/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-start/spa-mode/src/routeTree.gen.ts b/e2e/vue-start/spa-mode/src/routeTree.gen.ts index 474705b7e7..0d44b648ee 100644 --- a/e2e/vue-start/spa-mode/src/routeTree.gen.ts +++ b/e2e/vue-start/spa-mode/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as PostsRouteImport } from './routes/posts' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostsRouteImport } from './routes/posts' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) const PostsPostIdRoute = PostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', @@ -60,13 +60,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -74,6 +67,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } '/posts/$postId': { id: '/posts/$postId' path: '/$postId' diff --git a/e2e/vue-start/spa-mode/src/routes/__root.tsx b/e2e/vue-start/spa-mode/src/routes/__root.tsx index 1e38664739..45aee73c06 100644 --- a/e2e/vue-start/spa-mode/src/routes/__root.tsx +++ b/e2e/vue-start/spa-mode/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -13,6 +14,71 @@ import { import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' import appCss from '~/styles/app.css?url' +const RootDocument = defineComponent({ + setup(_, { slots }) { + const routerState = useRouterState({ + select: (state) => ({ isLoading: state.isLoading, status: state.status }), + }) + return () => ( + + + + + +
    +

    SPA Mode E2E Test

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

    root

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

    root

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

    SPA Mode E2E Test

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

    postId

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

    postId

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

    posts

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

    posts

    -
    - loader: {loaderData.value.posts} -
    -
    - context: {context.value.posts} -
    -
    - -
    - ) - }, + component: RouteComponent, pendingComponent: () =>
    posts Loading...
    , }) diff --git a/e2e/vue-start/spa-mode/src/styles/app.css b/e2e/vue-start/spa-mode/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/e2e/vue-start/spa-mode/src/styles/app.css +++ b/e2e/vue-start/spa-mode/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-start/spa-mode/tests/app.spec.ts b/e2e/vue-start/spa-mode/tests/app.spec.ts index c18a0ff65d..ad437c0353 100644 --- a/e2e/vue-start/spa-mode/tests/app.spec.ts +++ b/e2e/vue-start/spa-mode/tests/app.spec.ts @@ -5,9 +5,16 @@ import type { Page } from '@playwright/test' async function runTest( page: Page, expectedData: { - root: 'server' | 'client' - posts: 'server' | 'client' - postId: 'server' | 'client' + loader: { + root: 'server' | 'client' + posts: 'server' | 'client' + postId: 'server' | 'client' + } + context: { + root: 'server' | 'client' + posts: 'server' | 'client' + postId: 'server' | 'client' + } }, ) { // wait for page to be loaded by waiting for the leaf route to be rendered @@ -15,36 +22,64 @@ async function runTest( // check expectations await Promise.all( - Object.entries(expectedData).map(async ([route, expectedData]) => { + Object.entries(expectedData.loader).map(async ([route, expectedLoader]) => { await expect(page.getByTestId(`${route}-loader`)).toContainText( - expectedData, - ) - await expect(page.getByTestId(`${route}-context`)).toContainText( - expectedData, + expectedLoader, ) }), ) + await Promise.all( + Object.entries(expectedData.context).map( + async ([route, expectedContext]) => { + await expect(page.getByTestId(`${route}-context`)).toContainText( + expectedContext, + ) + }, + ), + ) await expect(page.getByTestId('router-isLoading')).toContainText('false') await expect(page.getByTestId('router-status')).toContainText('idle') } test.describe('SPA mode', () => { - test(`directly visiting prerendered /posts/1`, async ({ page }) => { + test(`directly visiting prerendered /posts/1`, async ({ + page, + }: { + page: Page + }) => { await page.goto('/posts/1') await runTest(page, { - root: 'server', - posts: 'server', - postId: 'server', + loader: { + root: 'server', + posts: 'server', + postId: 'server', + }, + context: { + root: 'server', + posts: 'server', + postId: 'server', + }, }) }) - test(`client-side navigation to /posts/1`, async ({ page }) => { + test(`client-side navigation to /posts/1`, async ({ + page, + }: { + page: Page + }) => { await page.goto('/') const testId = 'link-posts-1' await page.getByTestId(testId).click() await runTest(page, { - root: 'client', - posts: 'client', - postId: 'client', + loader: { + root: 'server', + posts: 'client', + postId: 'client', + }, + context: { + root: 'client', + posts: 'client', + postId: 'client', + }, }) }) }) diff --git a/e2e/vue-start/spa-mode/tsconfig.json b/e2e/vue-start/spa-mode/tsconfig.json index f9f5aab3da..390dad84c0 100644 --- a/e2e/vue-start/spa-mode/tsconfig.json +++ b/e2e/vue-start/spa-mode/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/spa-mode/vite.config.ts b/e2e/vue-start/spa-mode/vite.config.ts index ea6f52a24b..b0067bba4b 100644 --- a/e2e/vue-start/spa-mode/vite.config.ts +++ b/e2e/vue-start/spa-mode/vite.config.ts @@ -1,17 +1,16 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + resolve: { tsconfigPaths: true }, server: { port: 3000, }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), + tailwindcss(), tanstackStart({ spa: { enabled: true, diff --git a/e2e/vue-start/start-manifest/package.json b/e2e/vue-start/start-manifest/package.json new file mode 100644 index 0000000000..ae682f7a9d --- /dev/null +++ b/e2e/vue-start/start-manifest/package.json @@ -0,0 +1,34 @@ +{ + "name": "tanstack-vue-start-e2e-start-manifest", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", + "test:e2e": "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-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": { + "test:e2e": { + "parallelism": false + } + } + } +} diff --git a/e2e/vue-start/start-manifest/playwright.config.ts b/e2e/vue-start/start-manifest/playwright.config.ts new file mode 100644 index 0000000000..653e08253f --- /dev/null +++ b/e2e/vue-start/start-manifest/playwright.config.ts @@ -0,0 +1,29 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + + use: { + baseURL, + }, + + webServer: { + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/vue-start/start-manifest/src/components/AppShell.tsx b/e2e/vue-start/start-manifest/src/components/AppShell.tsx new file mode 100644 index 0000000000..0d57b2d0e3 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/components/AppShell.tsx @@ -0,0 +1,38 @@ +/// +import { ClientOnly, Link, Outlet, linkOptions } from '@tanstack/vue-router' +import styles from '~/styles/root-shell.module.css' + +const ROUTES = linkOptions([ + { to: '/', label: 'home' }, + { to: '/a', label: '/a' }, + { to: '/b', label: '/b' }, + { to: '/lazy-css-static', label: '/lazy-css-static' }, + { to: '/lazy-css-lazy', label: '/lazy-css-lazy' }, + { to: '/r1', label: '/r1' }, + { to: '/r2', label: '/r2' }, + { to: '/shared-a', label: '/shared-a' }, +]) + +export function AppShell() { + return ( +
    + + +
    +
    + Start manifest CSS root shell +
    + +
    hydrated
    +
    + +
    +
    + ) +} diff --git a/e2e/vue-start/start-manifest/src/components/SharedCard.tsx b/e2e/vue-start/start-manifest/src/components/SharedCard.tsx new file mode 100644 index 0000000000..c82b2b0ea5 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/components/SharedCard.tsx @@ -0,0 +1,10 @@ +/// +import styles from '~/styles/shared-card.module.css' + +export function SharedCard({ label }: { label: string }) { + return ( +
    + Shared card {label} +
    + ) +} diff --git a/e2e/vue-start/start-manifest/src/components/SharedNestedLayout.tsx b/e2e/vue-start/start-manifest/src/components/SharedNestedLayout.tsx new file mode 100644 index 0000000000..9c1f63f2f9 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/components/SharedNestedLayout.tsx @@ -0,0 +1,34 @@ +/// +import { Link, linkOptions } from '@tanstack/vue-router' +import { defineComponent } from 'vue' +import styles from '~/styles/shared-layout.module.css' + +const ROUTES = linkOptions([ + { to: '/shared-a', label: '/shared-a' }, + { to: '/shared-b', label: '/shared-b' }, + { to: '/shared-c', label: '/shared-c' }, +]) + +export const SharedNestedLayout = defineComponent({ + setup(_, { slots }) { + return () => ( +
    +
    + Shared nested layout CSS +
    + + + +
    + {slots.default?.()} +
    +
    + ) + }, +}) diff --git a/e2e/vue-start/start-manifest/src/components/SharedWidget.tsx b/e2e/vue-start/start-manifest/src/components/SharedWidget.tsx new file mode 100644 index 0000000000..9074d5b2b0 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/components/SharedWidget.tsx @@ -0,0 +1,15 @@ +/// +import styles from '~/styles/shared-widget.module.css' + +export function SharedWidget() { + return ( +
    +
    + Shared widget styles +
    +
    + This widget uses CSS shared by a static route and a lazy route. +
    +
    + ) +} diff --git a/e2e/vue-start/start-manifest/src/components/SharedWidgetLazy.tsx b/e2e/vue-start/start-manifest/src/components/SharedWidgetLazy.tsx new file mode 100644 index 0000000000..5f1f6410a5 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/components/SharedWidgetLazy.tsx @@ -0,0 +1,5 @@ +import { SharedWidget } from './SharedWidget' + +export default function SharedWidgetLazy() { + return +} diff --git a/e2e/vue-start/start-manifest/src/routeTree.gen.ts b/e2e/vue-start/start-manifest/src/routeTree.gen.ts new file mode 100644 index 0000000000..fc42a1e404 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routeTree.gen.ts @@ -0,0 +1,345 @@ +/* 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 ARouteImport } from './routes/a' +import { Route as BRouteImport } from './routes/b' +import { Route as LazyCssLazyRouteImport } from './routes/lazy-css-lazy' +import { Route as LazyCssStaticRouteImport } from './routes/lazy-css-static' +import { Route as R1RouteImport } from './routes/r1' +import { Route as R2RouteImport } from './routes/r2' +import { Route as R3RouteImport } from './routes/r3' +import { Route as R4RouteImport } from './routes/r4' +import { Route as R5RouteImport } from './routes/r5' +import { Route as R6RouteImport } from './routes/r6' +import { Route as SharedARouteImport } from './routes/shared-a' +import { Route as SharedBRouteImport } from './routes/shared-b' +import { Route as SharedCRouteImport } from './routes/shared-c' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ARoute = ARouteImport.update({ + id: '/a', + path: '/a', + getParentRoute: () => rootRouteImport, +} as any) +const BRoute = BRouteImport.update({ + id: '/b', + path: '/b', + getParentRoute: () => rootRouteImport, +} as any) +const LazyCssLazyRoute = LazyCssLazyRouteImport.update({ + id: '/lazy-css-lazy', + path: '/lazy-css-lazy', + getParentRoute: () => rootRouteImport, +} as any) +const LazyCssStaticRoute = LazyCssStaticRouteImport.update({ + id: '/lazy-css-static', + path: '/lazy-css-static', + getParentRoute: () => rootRouteImport, +} as any) +const R1Route = R1RouteImport.update({ + id: '/r1', + path: '/r1', + getParentRoute: () => rootRouteImport, +} as any) +const R2Route = R2RouteImport.update({ + id: '/r2', + path: '/r2', + getParentRoute: () => rootRouteImport, +} as any) +const R3Route = R3RouteImport.update({ + id: '/r3', + path: '/r3', + getParentRoute: () => rootRouteImport, +} as any) +const R4Route = R4RouteImport.update({ + id: '/r4', + path: '/r4', + getParentRoute: () => rootRouteImport, +} as any) +const R5Route = R5RouteImport.update({ + id: '/r5', + path: '/r5', + getParentRoute: () => rootRouteImport, +} as any) +const R6Route = R6RouteImport.update({ + id: '/r6', + path: '/r6', + getParentRoute: () => rootRouteImport, +} as any) +const SharedARoute = SharedARouteImport.update({ + id: '/shared-a', + path: '/shared-a', + getParentRoute: () => rootRouteImport, +} as any) +const SharedBRoute = SharedBRouteImport.update({ + id: '/shared-b', + path: '/shared-b', + getParentRoute: () => rootRouteImport, +} as any) +const SharedCRoute = SharedCRouteImport.update({ + id: '/shared-c', + path: '/shared-c', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/a': typeof ARoute + '/b': typeof BRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute + '/r1': typeof R1Route + '/r2': typeof R2Route + '/r3': typeof R3Route + '/r4': typeof R4Route + '/r5': typeof R5Route + '/r6': typeof R6Route + '/shared-a': typeof SharedARoute + '/shared-b': typeof SharedBRoute + '/shared-c': typeof SharedCRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/a': typeof ARoute + '/b': typeof BRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute + '/r1': typeof R1Route + '/r2': typeof R2Route + '/r3': typeof R3Route + '/r4': typeof R4Route + '/r5': typeof R5Route + '/r6': typeof R6Route + '/shared-a': typeof SharedARoute + '/shared-b': typeof SharedBRoute + '/shared-c': typeof SharedCRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/a': typeof ARoute + '/b': typeof BRoute + '/lazy-css-lazy': typeof LazyCssLazyRoute + '/lazy-css-static': typeof LazyCssStaticRoute + '/r1': typeof R1Route + '/r2': typeof R2Route + '/r3': typeof R3Route + '/r4': typeof R4Route + '/r5': typeof R5Route + '/r6': typeof R6Route + '/shared-a': typeof SharedARoute + '/shared-b': typeof SharedBRoute + '/shared-c': typeof SharedCRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/a' + | '/b' + | '/lazy-css-lazy' + | '/lazy-css-static' + | '/r1' + | '/r2' + | '/r3' + | '/r4' + | '/r5' + | '/r6' + | '/shared-a' + | '/shared-b' + | '/shared-c' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/a' + | '/b' + | '/lazy-css-lazy' + | '/lazy-css-static' + | '/r1' + | '/r2' + | '/r3' + | '/r4' + | '/r5' + | '/r6' + | '/shared-a' + | '/shared-b' + | '/shared-c' + id: + | '__root__' + | '/' + | '/a' + | '/b' + | '/lazy-css-lazy' + | '/lazy-css-static' + | '/r1' + | '/r2' + | '/r3' + | '/r4' + | '/r5' + | '/r6' + | '/shared-a' + | '/shared-b' + | '/shared-c' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ARoute: typeof ARoute + BRoute: typeof BRoute + LazyCssLazyRoute: typeof LazyCssLazyRoute + LazyCssStaticRoute: typeof LazyCssStaticRoute + R1Route: typeof R1Route + R2Route: typeof R2Route + R3Route: typeof R3Route + R4Route: typeof R4Route + R5Route: typeof R5Route + R6Route: typeof R6Route + SharedARoute: typeof SharedARoute + SharedBRoute: typeof SharedBRoute + SharedCRoute: typeof SharedCRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/a': { + id: '/a' + path: '/a' + fullPath: '/a' + preLoaderRoute: typeof ARouteImport + parentRoute: typeof rootRouteImport + } + '/b': { + id: '/b' + path: '/b' + fullPath: '/b' + preLoaderRoute: typeof BRouteImport + parentRoute: typeof rootRouteImport + } + '/lazy-css-lazy': { + id: '/lazy-css-lazy' + path: '/lazy-css-lazy' + fullPath: '/lazy-css-lazy' + preLoaderRoute: typeof LazyCssLazyRouteImport + parentRoute: typeof rootRouteImport + } + '/lazy-css-static': { + id: '/lazy-css-static' + path: '/lazy-css-static' + fullPath: '/lazy-css-static' + preLoaderRoute: typeof LazyCssStaticRouteImport + parentRoute: typeof rootRouteImport + } + '/r1': { + id: '/r1' + path: '/r1' + fullPath: '/r1' + preLoaderRoute: typeof R1RouteImport + parentRoute: typeof rootRouteImport + } + '/r2': { + id: '/r2' + path: '/r2' + fullPath: '/r2' + preLoaderRoute: typeof R2RouteImport + parentRoute: typeof rootRouteImport + } + '/r3': { + id: '/r3' + path: '/r3' + fullPath: '/r3' + preLoaderRoute: typeof R3RouteImport + parentRoute: typeof rootRouteImport + } + '/r4': { + id: '/r4' + path: '/r4' + fullPath: '/r4' + preLoaderRoute: typeof R4RouteImport + parentRoute: typeof rootRouteImport + } + '/r5': { + id: '/r5' + path: '/r5' + fullPath: '/r5' + preLoaderRoute: typeof R5RouteImport + parentRoute: typeof rootRouteImport + } + '/r6': { + id: '/r6' + path: '/r6' + fullPath: '/r6' + preLoaderRoute: typeof R6RouteImport + parentRoute: typeof rootRouteImport + } + '/shared-a': { + id: '/shared-a' + path: '/shared-a' + fullPath: '/shared-a' + preLoaderRoute: typeof SharedARouteImport + parentRoute: typeof rootRouteImport + } + '/shared-b': { + id: '/shared-b' + path: '/shared-b' + fullPath: '/shared-b' + preLoaderRoute: typeof SharedBRouteImport + parentRoute: typeof rootRouteImport + } + '/shared-c': { + id: '/shared-c' + path: '/shared-c' + fullPath: '/shared-c' + preLoaderRoute: typeof SharedCRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ARoute: ARoute, + BRoute: BRoute, + LazyCssLazyRoute: LazyCssLazyRoute, + LazyCssStaticRoute: LazyCssStaticRoute, + R1Route: R1Route, + R2Route: R2Route, + R3Route: R3Route, + R4Route: R4Route, + R5Route: R5Route, + R6Route: R6Route, + SharedARoute: SharedARoute, + SharedBRoute: SharedBRoute, + SharedCRoute: SharedCRoute, +} +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/start-manifest/src/router.tsx b/e2e/vue-start/start-manifest/src/router.tsx new file mode 100644 index 0000000000..d7cd8e8284 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/router.tsx @@ -0,0 +1,18 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export const getRouter = () => { + const router = createRouter({ + routeTree, + scrollRestoration: true, + defaultPreload: 'intent', + }) + + return router +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/e2e/vue-start/start-manifest/src/routes/__root.tsx b/e2e/vue-start/start-manifest/src/routes/__root.tsx new file mode 100644 index 0000000000..b62d37c0f0 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/__root.tsx @@ -0,0 +1,35 @@ +/// +import { + Body, + HeadContent, + Html, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' +import { AppShell } from '~/components/AppShell' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'TanStack Start Manifest Bloat E2E' }, + ], + }), + component: AppShell, + shellComponent: RootDocument, +}) + +function RootDocument(_: unknown, { slots }: { slots: any }) { + return ( + + + + + + {slots.default?.()} + + + + ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/a.tsx b/e2e/vue-start/start-manifest/src/routes/a.tsx new file mode 100644 index 0000000000..e53399273d --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/a.tsx @@ -0,0 +1,18 @@ +/// +import { createFileRoute } from '@tanstack/vue-router' +import { SharedCard } from '~/components/SharedCard' +import styles from '~/styles/page-a.module.css' + +export const Route = createFileRoute('/a')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    +

    Route /a

    +

    Route /a keeps the shared card styled.

    + +
    + ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/b.tsx b/e2e/vue-start/start-manifest/src/routes/b.tsx new file mode 100644 index 0000000000..cb989a257f --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/b.tsx @@ -0,0 +1,18 @@ +/// +import { createFileRoute } from '@tanstack/vue-router' +import { SharedCard } from '~/components/SharedCard' +import styles from '~/styles/page-b.module.css' + +export const Route = createFileRoute('/b')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    +

    Route /b

    +

    Route /b should keep the shared card stylesheet after nav.

    + +
    + ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/index.tsx b/e2e/vue-start/start-manifest/src/routes/index.tsx new file mode 100644 index 0000000000..728cc55e88 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/index.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: HomeRoute, +}) + +function HomeRoute() { + return ( +
    +

    Start manifest fixture

    +

    + Use this page to navigate between CSS module routes. +

    +
    + ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/lazy-css-lazy.tsx b/e2e/vue-start/start-manifest/src/routes/lazy-css-lazy.tsx new file mode 100644 index 0000000000..0db0845425 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/lazy-css-lazy.tsx @@ -0,0 +1,31 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { Suspense, defineAsyncComponent } from 'vue' + +const LazySharedWidget = defineAsyncComponent( + () => import('~/components/SharedWidgetLazy'), +) + +export const Route = createFileRoute('/lazy-css-lazy')({ + component: LazyCssLazyRoute, +}) + +function LazyCssLazyRoute() { + return ( +
    +

    Lazy CSS Repro - Lazy Route

    +

    + This route renders the same widget through a lazy component so the CSS + only exists behind a dynamic import boundary. +

    + + + {{ + default: () => , + fallback: () => ( +
    Loading...
    + ), + }} +
    +
    + ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/lazy-css-static.tsx b/e2e/vue-start/start-manifest/src/routes/lazy-css-static.tsx new file mode 100644 index 0000000000..2a8352e67e --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/lazy-css-static.tsx @@ -0,0 +1,24 @@ +import { ClientOnly, createFileRoute } from '@tanstack/vue-router' +import { SharedWidget } from '~/components/SharedWidget' + +export const Route = createFileRoute('/lazy-css-static')({ + component: LazyCssStaticRoute, +}) + +function LazyCssStaticRoute() { + return ( +
    +

    Lazy CSS Repro - Static Route

    +

    + This route statically imports the shared widget so its CSS is present in + the SSR head. +

    + + +
    hydrated
    +
    + + +
    + ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/r1.tsx b/e2e/vue-start/start-manifest/src/routes/r1.tsx new file mode 100644 index 0000000000..b35bec54e3 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/r1.tsx @@ -0,0 +1,18 @@ +/// +import { createFileRoute } from '@tanstack/vue-router' +import styles from '~/styles/route-one.module.css' + +export const Route = createFileRoute('/r1')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    +

    Route /r1

    +
    + Route /r1 CSS module styling +
    +
    + ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/r2.tsx b/e2e/vue-start/start-manifest/src/routes/r2.tsx new file mode 100644 index 0000000000..eadd952f98 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/r2.tsx @@ -0,0 +1,18 @@ +/// +import { createFileRoute } from '@tanstack/vue-router' +import styles from '~/styles/route-two.module.css' + +export const Route = createFileRoute('/r2')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    +

    Route /r2

    +
    + Route /r2 CSS module styling +
    +
    + ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/r3.tsx b/e2e/vue-start/start-manifest/src/routes/r3.tsx new file mode 100644 index 0000000000..a5a486cfaa --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/r3.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/r3')({ + component: () =>
    Route /r3
    , +}) diff --git a/e2e/vue-start/start-manifest/src/routes/r4.tsx b/e2e/vue-start/start-manifest/src/routes/r4.tsx new file mode 100644 index 0000000000..9739966d02 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/r4.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/r4')({ + component: () =>
    Route /r4
    , +}) diff --git a/e2e/vue-start/start-manifest/src/routes/r5.tsx b/e2e/vue-start/start-manifest/src/routes/r5.tsx new file mode 100644 index 0000000000..7c081e29a6 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/r5.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/r5')({ + component: () =>
    Route /r5
    , +}) diff --git a/e2e/vue-start/start-manifest/src/routes/r6.tsx b/e2e/vue-start/start-manifest/src/routes/r6.tsx new file mode 100644 index 0000000000..c56c2afda3 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/r6.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/r6')({ + component: () =>
    Route /r6
    , +}) diff --git a/e2e/vue-start/start-manifest/src/routes/shared-a.tsx b/e2e/vue-start/start-manifest/src/routes/shared-a.tsx new file mode 100644 index 0000000000..e7253a94ac --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/shared-a.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { SharedNestedLayout } from '~/components/SharedNestedLayout' + +export const Route = createFileRoute('/shared-a')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( + +
    Shared route A
    +
    + ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/shared-b.tsx b/e2e/vue-start/start-manifest/src/routes/shared-b.tsx new file mode 100644 index 0000000000..ed02b3429b --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/shared-b.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { SharedNestedLayout } from '~/components/SharedNestedLayout' + +export const Route = createFileRoute('/shared-b')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( + +
    Shared route B
    +
    + ) +} diff --git a/e2e/vue-start/start-manifest/src/routes/shared-c.tsx b/e2e/vue-start/start-manifest/src/routes/shared-c.tsx new file mode 100644 index 0000000000..e395b33ed5 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/routes/shared-c.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { SharedNestedLayout } from '~/components/SharedNestedLayout' + +export const Route = createFileRoute('/shared-c')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( + +
    Shared route C
    +
    + ) +} diff --git a/e2e/vue-start/start-manifest/src/styles/page-a.module.css b/e2e/vue-start/start-manifest/src/styles/page-a.module.css new file mode 100644 index 0000000000..7ed4301097 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/page-a.module.css @@ -0,0 +1,10 @@ +.page { + padding: 1rem; + min-height: 12rem; + background: rgb(240, 253, 244); + border: 4px solid rgb(22, 163, 74); +} + +.title { + color: rgb(21, 128, 61); +} diff --git a/e2e/vue-start/start-manifest/src/styles/page-b.module.css b/e2e/vue-start/start-manifest/src/styles/page-b.module.css new file mode 100644 index 0000000000..93d1d39a01 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/page-b.module.css @@ -0,0 +1,10 @@ +.page { + padding: 1rem; + min-height: 12rem; + background: rgb(239, 246, 255); + border: 4px solid rgb(37, 99, 235); +} + +.title { + color: rgb(29, 78, 216); +} diff --git a/e2e/vue-start/start-manifest/src/styles/root-shell.module.css b/e2e/vue-start/start-manifest/src/styles/root-shell.module.css new file mode 100644 index 0000000000..e7bece8664 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/root-shell.module.css @@ -0,0 +1,37 @@ +.shell { + font-family: + -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; + min-height: 100vh; + background: rgb(248, 250, 252); + color: rgb(15, 23, 42); +} + +.nav { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + padding: 1rem; + border-bottom: 1px solid rgb(226, 232, 240); + background: white; +} + +.nav a { + color: rgb(37, 99, 235); + text-decoration: none; +} + +.content { + max-width: 760px; + margin: 0 auto; + padding: 1.5rem 1rem 3rem; +} + +.rootBadge { + display: inline-block; + margin-bottom: 1rem; + padding: 0.375rem 0.75rem; + border-radius: 9999px; + background: rgb(220, 252, 231); + color: rgb(22, 101, 52); + font-weight: 700; +} diff --git a/e2e/vue-start/start-manifest/src/styles/route-one.module.css b/e2e/vue-start/start-manifest/src/styles/route-one.module.css new file mode 100644 index 0000000000..623d03e6a3 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/route-one.module.css @@ -0,0 +1,7 @@ +.card { + padding: 1rem; + border-radius: 0.75rem; + background: rgb(239, 246, 255); + color: rgb(30, 64, 175); + border: 2px solid rgb(96, 165, 250); +} diff --git a/e2e/vue-start/start-manifest/src/styles/route-two.module.css b/e2e/vue-start/start-manifest/src/styles/route-two.module.css new file mode 100644 index 0000000000..66ed355711 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/route-two.module.css @@ -0,0 +1,7 @@ +.card { + padding: 1rem; + border-radius: 0.75rem; + background: rgb(250, 245, 255); + color: rgb(126, 34, 206); + border: 2px solid rgb(192, 132, 252); +} diff --git a/e2e/vue-start/start-manifest/src/styles/shared-card.module.css b/e2e/vue-start/start-manifest/src/styles/shared-card.module.css new file mode 100644 index 0000000000..2aa5a6ac17 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/shared-card.module.css @@ -0,0 +1,8 @@ +.card { + margin-top: 1rem; + padding: 1.5rem; + border-radius: 0.75rem; + background: rgb(252, 231, 243); + border: 2px solid rgb(190, 24, 93); + color: rgb(157, 23, 77); +} diff --git a/e2e/vue-start/start-manifest/src/styles/shared-layout.module.css b/e2e/vue-start/start-manifest/src/styles/shared-layout.module.css new file mode 100644 index 0000000000..6025a1da06 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/shared-layout.module.css @@ -0,0 +1,16 @@ +.layout { + padding: 1rem; + border-radius: 0.75rem; + background: rgb(255, 251, 235); + border: 2px solid rgb(245, 158, 11); +} + +.heading { + color: rgb(180, 83, 9); + font-weight: 700; + margin-bottom: 0.5rem; +} + +.body { + color: rgb(146, 64, 14); +} diff --git a/e2e/vue-start/start-manifest/src/styles/shared-widget.module.css b/e2e/vue-start/start-manifest/src/styles/shared-widget.module.css new file mode 100644 index 0000000000..ed197cddb0 --- /dev/null +++ b/e2e/vue-start/start-manifest/src/styles/shared-widget.module.css @@ -0,0 +1,17 @@ +.widget { + margin-top: 1rem; + padding: 1rem; + border-top: 4px solid rgb(249, 115, 22); + border-radius: 0.75rem; + background: rgb(255, 247, 237); +} + +.title { + font-weight: 700; + color: rgb(154, 52, 18); +} + +.content { + margin-top: 0.5rem; + color: rgb(124, 45, 18); +} diff --git a/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts b/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts new file mode 100644 index 0000000000..4d5bea0a33 --- /dev/null +++ b/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts @@ -0,0 +1,449 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import type { Page } from '@playwright/test' +import { readdir } from 'node:fs/promises' +import path from 'node:path' +import { pathToFileURL } from 'node:url' + +const ROOT_SHELL_COLOR = 'rgb(22, 101, 52)' +const ROUTE_ONE_COLOR = 'rgb(30, 64, 175)' +const ROUTE_TWO_COLOR = 'rgb(126, 34, 206)' +const SHARED_CARD_BG = 'rgb(252, 231, 243)' +const SHARED_WIDGET_BG = 'rgb(255, 247, 237)' +const SHARED_WIDGET_BORDER = 'rgb(249, 115, 22)' + +const buildUrl = (baseURL: string, pathname: string) => + baseURL.replace(/\/$/, '') + pathname + +async function getColor(testId: string, page: Page) { + return page + .getByTestId(testId) + .evaluate((element) => getComputedStyle(element).color) +} + +async function getBackgroundColor(testId: string, page: Page) { + return page + .getByTestId(testId) + .evaluate((element) => getComputedStyle(element).backgroundColor) +} + +function getStylesheetHrefsFromHtml(html: string) { + return Array.from( + html.matchAll(/]+rel="stylesheet"[^>]+href="([^"]+)"/g), + (match) => match[1]!, + ) +} + +async function getHeadStylesheetHrefs(page: Page) { + return page.locator('head link[rel="stylesheet"]').evaluateAll((links) => { + return links.map( + (link) => (link as HTMLLinkElement).getAttribute('href') || '', + ) + }) +} + +function hasMatchingStylesheetHref(hrefs: Array, pattern: string) { + return hrefs.some((href) => href.includes(pattern)) +} + +function countMatchingStylesheetHrefs(hrefs: Array, pattern: string) { + return hrefs.filter((href) => href.includes(pattern)).length +} + +async function loadBuiltStartManifest() { + const serverDir = path.resolve(import.meta.dirname, '../dist/server/assets') + const entries = await readdir(serverDir) + const manifestFile = entries.find( + (entry) => + entry.startsWith('_tanstack-start-manifest_v-') && entry.endsWith('.js'), + ) + + expect(manifestFile).toBeTruthy() + + const moduleUrl = `${pathToFileURL(path.join(serverDir, manifestFile!)).href}?t=${Date.now()}` + const manifestModule = await import(moduleUrl) + + return manifestModule.tsrStartManifest() as { + routes: Record }> + } +} + +async function expectDirectEntry({ + page, + request, + baseURL, + pathname, + expectedVisibleTestId, + expectedAbsentTestId, + expectedStylesheetPattern, + unexpectedStylesheetPattern, + expectedColorTestId, + expectedColor, +}: { + page: Page + request: { + get: (url: string) => Promise<{ ok(): boolean; text(): Promise }> + } + baseURL: string + pathname: string + expectedVisibleTestId: string + expectedAbsentTestId: string + expectedStylesheetPattern: string + unexpectedStylesheetPattern: string + expectedColorTestId: string + expectedColor: string +}) { + const url = buildUrl(baseURL, pathname) + const response = await request.get(url) + const ssrHtml = await response.text() + + expect(response.ok()).toBe(true) + expect(ssrHtml).toContain('root-shell-marker') + expect(ssrHtml).toContain(expectedVisibleTestId) + expect(ssrHtml).not.toContain(expectedAbsentTestId) + + const stylesheetLinks = getStylesheetHrefsFromHtml(ssrHtml) + + expect( + countMatchingStylesheetHrefs(stylesheetLinks, expectedStylesheetPattern), + ).toBe(1) + expect( + countMatchingStylesheetHrefs(stylesheetLinks, unexpectedStylesheetPattern), + ).toBe(0) + expect(stylesheetLinks).toHaveLength(2) + + await page.goto(url) + await expect(page.getByTestId(expectedVisibleTestId)).toBeVisible() + await expect(page.getByTestId('hydration-marker')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, expectedStylesheetPattern) + }) + .toBe(1) + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, unexpectedStylesheetPattern) + }) + .toBe(0) + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return hrefs.length + }) + .toBe(2) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) + await expect + .poll(() => getColor(expectedColorTestId, page)) + .toBe(expectedColor) +} + +test('SSR and client navigation keep CSS module styles correct without hydration errors', async ({ + page, + baseURL, + request, +}) => { + const routeOneUrl = buildUrl(baseURL!, '/r1') + const response = await request.get(routeOneUrl) + const ssrHtml = await response.text() + + expect(response.ok()).toBe(true) + expect(ssrHtml).toContain('root-shell-marker') + expect(ssrHtml).toContain('route-r1-card') + expect(ssrHtml).not.toContain('route-r2-card') + + const stylesheetLinks = getStylesheetHrefsFromHtml(ssrHtml) + + expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r1-')).toBe(1) + expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r2-')).toBe(0) + expect(stylesheetLinks).toHaveLength(2) + + await page.goto(routeOneUrl) + + await expect(page.getByTestId('route-r1-card')).toBeVisible() + await expect(page.getByTestId('hydration-marker')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return hasMatchingStylesheetHref(hrefs, 'r1-') + }) + .toBe(true) + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, 'r2-') + }) + .toBe(0) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) + await expect.poll(() => getColor('route-r1-card', page)).toBe(ROUTE_ONE_COLOR) + + await page.getByTestId('nav-/r2').click() + await page.waitForURL('**/r2') + await expect(page.getByTestId('route-r2-card')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return hasMatchingStylesheetHref(hrefs, 'r2-') + }) + .toBe(true) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) + await expect.poll(() => getColor('route-r2-card', page)).toBe(ROUTE_TWO_COLOR) + + await page.getByTestId('nav-/r1').click() + await page.waitForURL('**/r1') + await expect(page.getByTestId('route-r1-card')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return hasMatchingStylesheetHref(hrefs, 'r1-') + }) + .toBe(true) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) + await expect.poll(() => getColor('route-r1-card', page)).toBe(ROUTE_ONE_COLOR) +}) + +test('direct SSR entry on /r2 only includes its stylesheet and hydrates cleanly', async ({ + page, + baseURL, + request, +}) => { + await expectDirectEntry({ + page, + request, + baseURL: baseURL!, + pathname: '/r2', + expectedVisibleTestId: 'route-r2-card', + expectedAbsentTestId: 'route-r1-card', + expectedStylesheetPattern: 'r2-', + unexpectedStylesheetPattern: 'r1-', + expectedColorTestId: 'route-r2-card', + expectedColor: ROUTE_TWO_COLOR, + }) +}) + +test('direct SSR entries on different route-css pages stay isolated', async ({ + page, + baseURL, + request, +}) => { + await expectDirectEntry({ + page, + request, + baseURL: baseURL!, + pathname: '/r2', + expectedVisibleTestId: 'route-r2-card', + expectedAbsentTestId: 'route-r1-card', + expectedStylesheetPattern: 'r2-', + unexpectedStylesheetPattern: 'r1-', + expectedColorTestId: 'route-r2-card', + expectedColor: ROUTE_TWO_COLOR, + }) + + await expectDirectEntry({ + page, + request, + baseURL: baseURL!, + pathname: '/r1', + expectedVisibleTestId: 'route-r1-card', + expectedAbsentTestId: 'route-r2-card', + expectedStylesheetPattern: 'r1-', + unexpectedStylesheetPattern: 'r2-', + expectedColorTestId: 'route-r1-card', + expectedColor: ROUTE_ONE_COLOR, + }) +}) + +test('home route only renders the root stylesheet and no route-specific CSS', async ({ + page, + baseURL, + request, +}) => { + const homeUrl = buildUrl(baseURL!, '/') + const response = await request.get(homeUrl) + const ssrHtml = await response.text() + + expect(response.ok()).toBe(true) + expect(ssrHtml).toContain('root-shell-marker') + expect(ssrHtml).toContain('home-copy') + expect(ssrHtml).not.toContain('route-r1-card') + expect(ssrHtml).not.toContain('route-r2-card') + + const stylesheetLinks = getStylesheetHrefsFromHtml(ssrHtml) + + expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r1-')).toBe(0) + expect(countMatchingStylesheetHrefs(stylesheetLinks, 'r2-')).toBe(0) + expect(stylesheetLinks).toHaveLength(1) + + await page.goto(homeUrl) + await expect(page.getByTestId('home-copy')).toBeVisible() + await expect(page.getByTestId('hydration-marker')).toBeVisible() + + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, 'r1-') + }) + .toBe(0) + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return countMatchingStylesheetHrefs(hrefs, 'r2-') + }) + .toBe(0) + await expect + .poll(async () => { + const hrefs = await getHeadStylesheetHrefs(page) + return hrefs.length + }) + .toBe(1) + + await expect + .poll(() => getColor('root-shell-marker', page)) + .toBe(ROOT_SHELL_COLOR) +}) + +test('built start manifest preserves shared layout asset identity across sibling routes', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/shared-a')) + await expect(page.getByTestId('shared-a-card')).toBeVisible() + + const manifest = await loadBuiltStartManifest() + + const sharedAAsset = manifest.routes['/shared-a']?.css?.[0] + const sharedBAsset = manifest.routes['/shared-b']?.css?.[0] + const sharedCAsset = manifest.routes['/shared-c']?.css?.[0] + + expect(sharedAAsset).toBeTruthy() + expect(sharedAAsset).toBe(sharedBAsset) + expect(sharedBAsset).toBe(sharedCAsset) +}) + +test('shared CSS chunk persists across client-side nav', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/a')) + + await expect(page.getByTestId('page-a')).toBeVisible() + await expect(page.getByTestId('shared-card')).toBeVisible() + await expect + .poll(() => getBackgroundColor('shared-card', page)) + .toBe(SHARED_CARD_BG) + await expect( + page.locator('head link[rel="stylesheet"][href*="SharedCard"]'), + ).toHaveCount(1) + + await page.getByTestId('nav-/b').click() + await page.waitForURL('**/b') + await expect(page.getByTestId('page-b')).toBeVisible() + + await expect( + page.locator('head link[rel="stylesheet"][href*="SharedCard"]'), + ).toHaveCount(1) + await expect + .poll(() => getBackgroundColor('shared-card', page)) + .toBe(SHARED_CARD_BG) +}) + +test('shared widget CSS stays applied when navigating from static to lazy route', async ({ + page, + baseURL, +}) => { + await page.goto(buildUrl(baseURL!, '/lazy-css-static')) + + 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(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) +}) + +test('shared widget CSS stays applied when navigating from lazy to static route', async ({ + page, + baseURL, +}) => { + 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 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() + + await expect(widget).toBeVisible() + await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) +}) + +test('shared widget CSS is applied on direct navigation to lazy route', async ({ + page, + baseURL, +}) => { + 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).toBeVisible() + await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) +}) + +test('shared widget CSS persists after navigating away from lazy and back', async ({ + page, + baseURL, +}) => { + 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 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) +}) diff --git a/e2e/vue-start/start-manifest/tsconfig.json b/e2e/vue-start/start-manifest/tsconfig.json new file mode 100644 index 0000000000..44a68ebf56 --- /dev/null +++ b/e2e/vue-start/start-manifest/tsconfig.json @@ -0,0 +1,23 @@ +{ + "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": "ES2024", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true, + "types": ["vite/client"] + } +} diff --git a/e2e/vue-start/start-manifest/vite.config.ts b/e2e/vue-start/start-manifest/vite.config.ts new file mode 100644 index 0000000000..f1102cffab --- /dev/null +++ b/e2e/vue-start/start-manifest/vite.config.ts @@ -0,0 +1,13 @@ +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, + }, + resolve: { + tsconfigPaths: true, + }, + plugins: [tanstackStart({ srcDirectory: 'src' }), vueJsx()], +}) diff --git a/e2e/vue-start/streaming-ssr/package.json b/e2e/vue-start/streaming-ssr/package.json new file mode 100644 index 0000000000..382120860a --- /dev/null +++ b/e2e/vue-start/streaming-ssr/package.json @@ -0,0 +1,59 @@ +{ + "name": "tanstack-vue-start-e2e-streaming-ssr", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "vite dev --port 3000", + "dev:e2e": "vite dev", + "build": "vite build && tsc --noEmit", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", + "preview": "vite preview", + "test:e2e": "playwright test --project=chromium", + "test:e2e:preview": "MODE=preview playwright test preview-streaming.spec.ts --project=chromium" + }, + "dependencies": { + "@tanstack/vue-query": "^5.90.0", + "@tanstack/vue-router": "workspace:^", + "@tanstack/vue-router-ssr-query": "workspace:^", + "@tanstack/vue-start": "workspace:^", + "vue": "^3.5.16" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/node": "^22.10.2", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" + }, + "nx": { + "targets": { + "build": { + "inputs": [ + "buildProduction", + "^buildProduction", + "dependentTaskOutputs", + "streamingSsrTests" + ] + }, + "test:e2e": { + "inputs": [ + "default", + "^production", + "dependentTaskOutputs", + "streamingSsrTests" + ] + }, + "test:e2e:preview": { + "inputs": [ + "default", + "^production", + "streamingSsrTests" + ] + } + } + } +} diff --git a/e2e/vue-start/streaming-ssr/playwright.config.ts b/e2e/vue-start/streaming-ssr/playwright.config.ts new file mode 100644 index 0000000000..c2f3b67a0c --- /dev/null +++ b/e2e/vue-start/streaming-ssr/playwright.config.ts @@ -0,0 +1,39 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const isPreview = process.env.MODE === 'preview' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` + +const ssrCommand = `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start` +const previewCommand = `VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}` + +/** + * See https://playwright.dev/docs/test-configuration. + */ +export default defineConfig({ + testDir: './tests', + workers: 1, + + reporter: [['line']], + + use: { + /* Base URL to use in actions like `await page.goto('/')`. */ + baseURL, + }, + + webServer: { + command: isPreview ? previewCommand : ssrCommand, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts b/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts new file mode 100644 index 0000000000..ac4c9ab156 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts @@ -0,0 +1,282 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as ConcurrentRouteImport } from './routes/concurrent' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as DeferredRejectionRouteImport } from './routes/deferred-rejection' +import { Route as FastSerialRouteImport } from './routes/fast-serial' +import { Route as ManyPromisesRouteImport } from './routes/many-promises' +import { Route as NestedDeferredRouteImport } from './routes/nested-deferred' +import { Route as QueryHeavyRouteImport } from './routes/query-heavy' +import { Route as SlowRenderRouteImport } from './routes/slow-render' +import { Route as StreamRouteImport } from './routes/stream' +import { Route as SyncOnlyRouteImport } from './routes/sync-only' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ConcurrentRoute = ConcurrentRouteImport.update({ + id: '/concurrent', + path: '/concurrent', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRejectionRoute = DeferredRejectionRouteImport.update({ + id: '/deferred-rejection', + path: '/deferred-rejection', + getParentRoute: () => rootRouteImport, +} as any) +const FastSerialRoute = FastSerialRouteImport.update({ + id: '/fast-serial', + path: '/fast-serial', + getParentRoute: () => rootRouteImport, +} as any) +const ManyPromisesRoute = ManyPromisesRouteImport.update({ + id: '/many-promises', + path: '/many-promises', + getParentRoute: () => rootRouteImport, +} as any) +const NestedDeferredRoute = NestedDeferredRouteImport.update({ + id: '/nested-deferred', + path: '/nested-deferred', + getParentRoute: () => rootRouteImport, +} as any) +const QueryHeavyRoute = QueryHeavyRouteImport.update({ + id: '/query-heavy', + path: '/query-heavy', + getParentRoute: () => rootRouteImport, +} as any) +const SlowRenderRoute = SlowRenderRouteImport.update({ + id: '/slow-render', + path: '/slow-render', + getParentRoute: () => rootRouteImport, +} as any) +const StreamRoute = StreamRouteImport.update({ + id: '/stream', + path: '/stream', + getParentRoute: () => rootRouteImport, +} as any) +const SyncOnlyRoute = SyncOnlyRouteImport.update({ + id: '/sync-only', + path: '/sync-only', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/concurrent': typeof ConcurrentRoute + '/deferred': typeof DeferredRoute + '/deferred-rejection': typeof DeferredRejectionRoute + '/fast-serial': typeof FastSerialRoute + '/many-promises': typeof ManyPromisesRoute + '/nested-deferred': typeof NestedDeferredRoute + '/query-heavy': typeof QueryHeavyRoute + '/slow-render': typeof SlowRenderRoute + '/stream': typeof StreamRoute + '/sync-only': typeof SyncOnlyRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/concurrent': typeof ConcurrentRoute + '/deferred': typeof DeferredRoute + '/deferred-rejection': typeof DeferredRejectionRoute + '/fast-serial': typeof FastSerialRoute + '/many-promises': typeof ManyPromisesRoute + '/nested-deferred': typeof NestedDeferredRoute + '/query-heavy': typeof QueryHeavyRoute + '/slow-render': typeof SlowRenderRoute + '/stream': typeof StreamRoute + '/sync-only': typeof SyncOnlyRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/concurrent': typeof ConcurrentRoute + '/deferred': typeof DeferredRoute + '/deferred-rejection': typeof DeferredRejectionRoute + '/fast-serial': typeof FastSerialRoute + '/many-promises': typeof ManyPromisesRoute + '/nested-deferred': typeof NestedDeferredRoute + '/query-heavy': typeof QueryHeavyRoute + '/slow-render': typeof SlowRenderRoute + '/stream': typeof StreamRoute + '/sync-only': typeof SyncOnlyRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/concurrent' + | '/deferred' + | '/deferred-rejection' + | '/fast-serial' + | '/many-promises' + | '/nested-deferred' + | '/query-heavy' + | '/slow-render' + | '/stream' + | '/sync-only' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/concurrent' + | '/deferred' + | '/deferred-rejection' + | '/fast-serial' + | '/many-promises' + | '/nested-deferred' + | '/query-heavy' + | '/slow-render' + | '/stream' + | '/sync-only' + id: + | '__root__' + | '/' + | '/concurrent' + | '/deferred' + | '/deferred-rejection' + | '/fast-serial' + | '/many-promises' + | '/nested-deferred' + | '/query-heavy' + | '/slow-render' + | '/stream' + | '/sync-only' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ConcurrentRoute: typeof ConcurrentRoute + DeferredRoute: typeof DeferredRoute + DeferredRejectionRoute: typeof DeferredRejectionRoute + FastSerialRoute: typeof FastSerialRoute + ManyPromisesRoute: typeof ManyPromisesRoute + NestedDeferredRoute: typeof NestedDeferredRoute + QueryHeavyRoute: typeof QueryHeavyRoute + SlowRenderRoute: typeof SlowRenderRoute + StreamRoute: typeof StreamRoute + SyncOnlyRoute: typeof SyncOnlyRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/concurrent': { + id: '/concurrent' + path: '/concurrent' + fullPath: '/concurrent' + preLoaderRoute: typeof ConcurrentRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred-rejection': { + id: '/deferred-rejection' + path: '/deferred-rejection' + fullPath: '/deferred-rejection' + preLoaderRoute: typeof DeferredRejectionRouteImport + parentRoute: typeof rootRouteImport + } + '/fast-serial': { + id: '/fast-serial' + path: '/fast-serial' + fullPath: '/fast-serial' + preLoaderRoute: typeof FastSerialRouteImport + parentRoute: typeof rootRouteImport + } + '/many-promises': { + id: '/many-promises' + path: '/many-promises' + fullPath: '/many-promises' + preLoaderRoute: typeof ManyPromisesRouteImport + parentRoute: typeof rootRouteImport + } + '/nested-deferred': { + id: '/nested-deferred' + path: '/nested-deferred' + fullPath: '/nested-deferred' + preLoaderRoute: typeof NestedDeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/query-heavy': { + id: '/query-heavy' + path: '/query-heavy' + fullPath: '/query-heavy' + preLoaderRoute: typeof QueryHeavyRouteImport + parentRoute: typeof rootRouteImport + } + '/slow-render': { + id: '/slow-render' + path: '/slow-render' + fullPath: '/slow-render' + preLoaderRoute: typeof SlowRenderRouteImport + parentRoute: typeof rootRouteImport + } + '/stream': { + id: '/stream' + path: '/stream' + fullPath: '/stream' + preLoaderRoute: typeof StreamRouteImport + parentRoute: typeof rootRouteImport + } + '/sync-only': { + id: '/sync-only' + path: '/sync-only' + fullPath: '/sync-only' + preLoaderRoute: typeof SyncOnlyRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ConcurrentRoute: ConcurrentRoute, + DeferredRoute: DeferredRoute, + DeferredRejectionRoute: DeferredRejectionRoute, + FastSerialRoute: FastSerialRoute, + ManyPromisesRoute: ManyPromisesRoute, + NestedDeferredRoute: NestedDeferredRoute, + QueryHeavyRoute: QueryHeavyRoute, + SlowRenderRoute: SlowRenderRoute, + StreamRoute: StreamRoute, + SyncOnlyRoute: SyncOnlyRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/vue-start' +declare module '@tanstack/vue-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/e2e/vue-start/streaming-ssr/src/router.tsx b/e2e/vue-start/streaming-ssr/src/router.tsx new file mode 100644 index 0000000000..257eb8dac9 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/router.tsx @@ -0,0 +1,18 @@ +import { QueryClient } from '@tanstack/vue-query' +import { createRouter } from '@tanstack/vue-router' +import { setupRouterSsrQueryIntegration } from '@tanstack/vue-router-ssr-query' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + const queryClient = new QueryClient() + const router = createRouter({ + routeTree, + context: { queryClient }, + scrollRestoration: true, + }) + setupRouterSsrQueryIntegration({ + router, + queryClient, + }) + return router +} diff --git a/e2e/vue-start/streaming-ssr/src/routes/__root.tsx b/e2e/vue-start/streaming-ssr/src/routes/__root.tsx new file mode 100644 index 0000000000..d3b3339720 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/__root.tsx @@ -0,0 +1,103 @@ +import { + Body, + HeadContent, + Html, + Link, + Outlet, + Scripts, + createRootRouteWithContext, +} from '@tanstack/vue-router' +import { defineComponent, ref } from 'vue' +import type { QueryClient } from '@tanstack/vue-query' + +export const Route = createRootRouteWithContext<{ + queryClient: QueryClient +}>()({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'Streaming SSR Tests' }, + ], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + + + ) +} + +const HydrationCheck = defineComponent({ + setup() { + const status = ref<'pending' | 'hydrated'>('pending') + + return () => ( +
    + + + {status.value} + +
    + ) + }, +}) diff --git a/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx b/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx new file mode 100644 index 0000000000..5fed8ab517 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx @@ -0,0 +1,54 @@ +import { Await, createFileRoute } from '@tanstack/vue-router' +import { Suspense } from 'vue' +import { createConcurrentLoaderData } from '../../../../streaming-ssr-fixtures' + +export const Route = createFileRoute('/concurrent')({ + loader: async () => createConcurrentLoaderData(), + component: Concurrent, +}) + +function PromiseItem(props: { promise: Promise; testId: string }) { + return ( + + {{ + default: () => ( + ( +
    {value}
    + )} + /> + ), + fallback: () => ( +
    Loading...
    + ), + }} +
    + ) +} + +function Concurrent() { + const data = Route.useLoaderData() + + return ( +
    +

    Concurrent Resolution Test (15 promises in 3 batches)

    +

    Tests multiple promises resolving at the exact same instant.

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

    Deferred Rejection Test

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

    Deferred Data Test

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

    Fast Serialization Test

    +

    This route tests when serialization completes before render.

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

    Streaming SSR Test Scenarios

    +

    This e2e project tests various SSR streaming scenarios:

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

    Many Promises Test (15 deferred)

    +

    Tests streaming with many concurrent deferred promises.

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

    Nested Deferred Test

    +

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

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

    Query Heavy Test (9 useQuery calls)

    +

    Tests multiple useQuery with mixed sync/async queryFn.

    +

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

    + +
    +
    +

    Sync Queries (immediate)

    + + + +
    + +
    +

    Fast Async Queries (50-100ms)

    + + + +
    + +
    +

    Slow Async Queries (200-400ms)

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

    Slow Render Test

    +

    Tests when render takes longer than serialization.

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

    ReadableStream Test

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

    Stream chunks:

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

    Synchronous Serialization Test

    +

    {data.value.message}

    +

    Loaded at: {data.value.timestamp}

    +

    Source: {data.value.source}

    +
      + {data.value.items.map((item: string) => ( +
    • {item}
    • + ))} +
    +
    + ) +} diff --git a/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts b/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts new file mode 100644 index 0000000000..8b9b3a8dcc --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/client-navigation' diff --git a/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts b/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts new file mode 100644 index 0000000000..8625473a58 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/concurrent' diff --git a/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts b/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts new file mode 100644 index 0000000000..355b5019bc --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/deferred-rejection' diff --git a/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts b/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts new file mode 100644 index 0000000000..3145897d7b --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/deferred' diff --git a/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts b/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts new file mode 100644 index 0000000000..95df0555e2 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/fast-serial' diff --git a/e2e/vue-start/streaming-ssr/tests/home.spec.ts b/e2e/vue-start/streaming-ssr/tests/home.spec.ts new file mode 100644 index 0000000000..5d49d34a56 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/home.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/home' diff --git a/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts b/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts new file mode 100644 index 0000000000..b747bd7d0a --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/many-promises' diff --git a/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts b/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts new file mode 100644 index 0000000000..8df20a8a95 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/nested-deferred' diff --git a/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts b/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts new file mode 100644 index 0000000000..34241cfbaa --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/preview-streaming' diff --git a/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts b/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts new file mode 100644 index 0000000000..d15c092f6e --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/query-heavy' diff --git a/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts b/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts new file mode 100644 index 0000000000..0d5a87363f --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/slow-render' diff --git a/e2e/vue-start/streaming-ssr/tests/stream.spec.ts b/e2e/vue-start/streaming-ssr/tests/stream.spec.ts new file mode 100644 index 0000000000..9dfc6820ad --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/stream.spec.ts @@ -0,0 +1,22 @@ +import { expect, testWithHydration } from '../../../streaming-ssr-assertions' +import '../../../streaming-ssr-specs/stream' + +testWithHydration( + 'reads a replacement stream after an active read', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + await page.getByRole('link', { name: 'Stream' }).first().click() + await expect(page.getByTestId('stream-chunk-0')).toHaveText('chunk-0') + await expect(page.getByTestId('stream-complete')).toHaveCount(0) + + await page.getByTestId('refresh-stream').click() + + const streamData = page.getByTestId('stream-data') + await expect(streamData).toHaveAttribute('data-read-count', '2') + await expect(page.getByTestId('stream-complete')).toBeVisible() + await expect( + streamData.locator('[data-testid^="stream-chunk-"]'), + ).toHaveText(['chunk-0', 'chunk-1', 'chunk-2', 'chunk-3', 'chunk-4']) + }, +) diff --git a/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts b/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts new file mode 100644 index 0000000000..b25572f615 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts @@ -0,0 +1,7 @@ +import '../../../streaming-ssr-specs/sync-only' +import { expect, test } from '../../../streaming-ssr-assertions' + +test('Vue renders an unwrapped document root', async ({ request }) => { + const response = await request.get('/sync-only') + expect(await response.text()).toMatch(/^)/) +}) diff --git a/e2e/vue-start/streaming-ssr/tsconfig.json b/e2e/vue-start/streaming-ssr/tsconfig.json new file mode 100644 index 0000000000..390dad84c0 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tsconfig.json @@ -0,0 +1,22 @@ +{ + "include": ["**/*.ts", "**/*.tsx"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2022", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true + } +} diff --git a/e2e/vue-start/streaming-ssr/vite.config.ts b/e2e/vue-start/streaming-ssr/vite.config.ts new file mode 100644 index 0000000000..6519ec54c8 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/vite.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' + +export default defineConfig({ + server: { + port: 3000, + }, + plugins: [tanstackStart(), vueJsx()], +}) diff --git a/e2e/vue-start/virtual-routes/.devcontainer/devcontainer.json b/e2e/vue-start/virtual-routes/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/virtual-routes/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/virtual-routes/package.json b/e2e/vue-start/virtual-routes/package.json index 613082ed37..90f09ce911 100644 --- a/e2e/vue-start/virtual-routes/package.json +++ b/e2e/vue-start/virtual-routes/package.json @@ -9,31 +9,30 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { + "@tanstack/virtual-file-routes": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "@tanstack/virtual-file-routes": "workspace:^", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "vite": "^7.1.7", + "redaxios": "catalog:", + "tailwind-merge": "^3.6.0", "vue": "^3.5.25", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@tailwindcss/postcss": "^4.1.15", + "@playwright/test": "^1.61.0", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "postcss": "^8.5.1", - "srvx": "^0.9.8", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "@vitejs/plugin-vue": "^6.0.3", - "@vitejs/plugin-vue-jsx": "^5.1.2", - "vite-tsconfig-paths": "^5.1.4" + "srvx": "^1.0.0", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/e2e/vue-start/virtual-routes/playwright.config.ts b/e2e/vue-start/virtual-routes/playwright.config.ts index b0c365f8bd..1862174905 100644 --- a/e2e/vue-start/virtual-routes/playwright.config.ts +++ b/e2e/vue-start/virtual-routes/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,19 +13,19 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', + env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, + }, }, projects: [ diff --git a/e2e/vue-start/virtual-routes/postcss.config.mjs b/e2e/vue-start/virtual-routes/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-start/virtual-routes/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-start/virtual-routes/routes.ts b/e2e/vue-start/virtual-routes/routes.ts index ab17b8f58b..37573a0567 100644 --- a/e2e/vue-start/virtual-routes/routes.ts +++ b/e2e/vue-start/virtual-routes/routes.ts @@ -21,4 +21,5 @@ export const routes = rootRoute('root.tsx', [ ]), ]), physical('/classic', 'file-based-subtree'), + route('/special|pipe', 'pipe.tsx'), ]) diff --git a/e2e/vue-start/virtual-routes/src/posts.tsx b/e2e/vue-start/virtual-routes/src/posts.tsx index 1b4c92b41d..f7a1941605 100644 --- a/e2e/vue-start/virtual-routes/src/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-start/virtual-routes/src/routeTree.gen.ts b/e2e/vue-start/virtual-routes/src/routeTree.gen.ts index 1ec4fba15f..1a1bc2d27b 100644 --- a/e2e/vue-start/virtual-routes/src/routeTree.gen.ts +++ b/e2e/vue-start/virtual-routes/src/routeTree.gen.ts @@ -9,81 +9,88 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/root' -import { Route as postsPostsRouteImport } from './routes/posts/posts' -import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' import { Route as homeRouteImport } from './routes/home' -import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' +import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' +import { Route as postsPostsRouteImport } from './routes/posts/posts' +import { Route as pipeRouteImport } from './routes/pipe' import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' -import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' +import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' -import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' -import { Route as bRouteImport } from './routes/b' +import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' import { Route as aRouteImport } from './routes/a' +import { Route as bRouteImport } from './routes/b' -const postsPostsRoute = postsPostsRouteImport.update({ - id: '/posts', - path: '/posts', +const homeRoute = homeRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', +const postsPostsRoute = postsPostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => postsPostsRoute, +const pipeRoute = pipeRouteImport.update({ + id: '/special|pipe', + path: '/special|pipe', + getParentRoute: () => rootRouteImport, } as any) const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ id: '/_second-layout', getParentRoute: () => layoutFirstLayoutRoute, } as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => postsPostsRoute, -} as any) const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ id: '/classic/hello', path: '/classic/hello', getParentRoute: () => rootRouteImport, } as any) +const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => postsPostsRoute, +} as any) +const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => postsPostsRoute, +} as any) const ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ - id: '/world', - path: '/world', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ id: '/universe', path: '/universe', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const bRoute = bRouteImport.update({ - id: '/route-without-file/layout-b', - path: '/route-without-file/layout-b', - getParentRoute: () => layoutSecondLayoutRoute, +const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ + id: '/world', + path: '/world', + getParentRoute: () => ClassicHelloRouteRoute, } as any) const aRoute = aRouteImport.update({ id: '/route-without-file/layout-a', path: '/route-without-file/layout-a', getParentRoute: () => layoutSecondLayoutRoute, } as any) +const bRoute = bRouteImport.update({ + id: '/route-without-file/layout-b', + path: '/route-without-file/layout-b', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof homeRoute '/posts': typeof postsPostsRouteWithChildren + '/special|pipe': typeof pipeRoute '/classic/hello': typeof ClassicHelloRouteRouteWithChildren '/posts/': typeof postsPostsHomeRoute '/posts/$postId': typeof postsPostsDetailRoute @@ -95,6 +102,7 @@ export interface FileRoutesByFullPath { } export interface FileRoutesByTo { '/': typeof homeRoute + '/special|pipe': typeof pipeRoute '/posts': typeof postsPostsHomeRoute '/posts/$postId': typeof postsPostsDetailRoute '/classic/hello/universe': typeof ClassicHelloUniverseRoute @@ -108,6 +116,7 @@ export interface FileRoutesById { '/': typeof homeRoute '/_first': typeof layoutFirstLayoutRouteWithChildren '/posts': typeof postsPostsRouteWithChildren + '/special|pipe': typeof pipeRoute '/classic/hello': typeof ClassicHelloRouteRouteWithChildren '/posts/': typeof postsPostsHomeRoute '/_first/_second-layout': typeof layoutSecondLayoutRouteWithChildren @@ -123,6 +132,7 @@ export interface FileRouteTypes { fullPaths: | '/' | '/posts' + | '/special|pipe' | '/classic/hello' | '/posts/' | '/posts/$postId' @@ -134,6 +144,7 @@ export interface FileRouteTypes { fileRoutesByTo: FileRoutesByTo to: | '/' + | '/special|pipe' | '/posts' | '/posts/$postId' | '/classic/hello/universe' @@ -146,6 +157,7 @@ export interface FileRouteTypes { | '/' | '/_first' | '/posts' + | '/special|pipe' | '/classic/hello' | '/posts/' | '/_first/_second-layout' @@ -161,25 +173,12 @@ export interface RootRouteChildren { homeRoute: typeof homeRoute layoutFirstLayoutRoute: typeof layoutFirstLayoutRouteWithChildren postsPostsRoute: typeof postsPostsRouteWithChildren + pipeRoute: typeof pipeRoute ClassicHelloRouteRoute: typeof ClassicHelloRouteRouteWithChildren } declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof postsPostsRouteImport - parentRoute: typeof rootRouteImport - } - '/_first': { - id: '/_first' - path: '' - fullPath: '' - preLoaderRoute: typeof layoutFirstLayoutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -187,27 +186,34 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof homeRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof postsPostsDetailRouteImport - parentRoute: typeof postsPostsRoute + '/_first': { + id: '/_first' + path: '' + fullPath: '/' + preLoaderRoute: typeof layoutFirstLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof postsPostsRouteImport + parentRoute: typeof rootRouteImport + } + '/special|pipe': { + id: '/special|pipe' + path: '/special|pipe' + fullPath: '/special|pipe' + preLoaderRoute: typeof pipeRouteImport + parentRoute: typeof rootRouteImport } '/_first/_second-layout': { id: '/_first/_second-layout' path: '' - fullPath: '' + fullPath: '/' preLoaderRoute: typeof layoutSecondLayoutRouteImport parentRoute: typeof layoutFirstLayoutRoute } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute - } '/classic/hello': { id: '/classic/hello' path: '/classic/hello' @@ -215,6 +221,20 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloRouteRouteImport parentRoute: typeof rootRouteImport } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof postsPostsHomeRouteImport + parentRoute: typeof postsPostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof postsPostsDetailRouteImport + parentRoute: typeof postsPostsRoute + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -222,13 +242,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/world': { - id: '/classic/hello/world' - path: '/world' - fullPath: '/classic/hello/world' - preLoaderRoute: typeof ClassicHelloWorldRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/universe': { id: '/classic/hello/universe' path: '/universe' @@ -236,12 +249,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloUniverseRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second-layout/route-without-file/layout-b': { - id: '/_first/_second-layout/route-without-file/layout-b' - path: '/route-without-file/layout-b' - fullPath: '/route-without-file/layout-b' - preLoaderRoute: typeof bRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/world': { + id: '/classic/hello/world' + path: '/world' + fullPath: '/classic/hello/world' + preLoaderRoute: typeof ClassicHelloWorldRouteImport + parentRoute: typeof ClassicHelloRouteRoute } '/_first/_second-layout/route-without-file/layout-a': { id: '/_first/_second-layout/route-without-file/layout-a' @@ -250,6 +263,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof aRouteImport parentRoute: typeof layoutSecondLayoutRoute } + '/_first/_second-layout/route-without-file/layout-b': { + id: '/_first/_second-layout/route-without-file/layout-b' + path: '/route-without-file/layout-b' + fullPath: '/route-without-file/layout-b' + preLoaderRoute: typeof bRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } } } @@ -310,6 +330,7 @@ const rootRouteChildren: RootRouteChildren = { homeRoute: homeRoute, layoutFirstLayoutRoute: layoutFirstLayoutRouteWithChildren, postsPostsRoute: postsPostsRouteWithChildren, + pipeRoute: pipeRoute, ClassicHelloRouteRoute: ClassicHelloRouteRouteWithChildren, } export const routeTree = rootRouteImport diff --git a/e2e/vue-start/virtual-routes/src/routes/pipe.tsx b/e2e/vue-start/virtual-routes/src/routes/pipe.tsx new file mode 100644 index 0000000000..bd7dd29a64 --- /dev/null +++ b/e2e/vue-start/virtual-routes/src/routes/pipe.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/special|pipe')({ + component: RouteComponent, +}) + +function RouteComponent() { + return ( +
    Hello "/special|pipe"!
    + ) +} diff --git a/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx b/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx index 5086e3ad88..4bc3824f62 100644 --- a/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx +++ b/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx @@ -1,7 +1,20 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + return () => ( +
    +

    {post.value.title}

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

    {post.value.title}

    -
    {post.value.body}
    -
    - ) -} diff --git a/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx b/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx index f56d6550a6..dd380aa353 100644 --- a/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx @@ -1,37 +1,39 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + return () => ( +
    +
      + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
    • + +
      {post.title.substring(0, 20)}
      + +
    • + ))} +
    +
    + +
    + ) + }, +}) + export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
    -
      - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
    • - -
      {post.title.substring(0, 20)}
      - -
    • - ))} -
    -
    - -
    - ) -} diff --git a/e2e/vue-start/virtual-routes/src/routes/root.tsx b/e2e/vue-start/virtual-routes/src/routes/root.tsx index 2a3a8b98cb..8193fcea71 100644 --- a/e2e/vue-start/virtual-routes/src/routes/root.tsx +++ b/e2e/vue-start/virtual-routes/src/routes/root.tsx @@ -69,6 +69,15 @@ function RootComponent() { > Subtree {' '} + + Pipe + {' '} postId) + .validator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/e2e/vue-start/virtual-routes/src/utils/users.tsx b/e2e/vue-start/virtual-routes/src/utils/users.tsx index 46be4b1580..7ba645b383 100644 --- a/e2e/vue-start/virtual-routes/src/utils/users.tsx +++ b/e2e/vue-start/virtual-routes/src/utils/users.tsx @@ -3,7 +3,3 @@ export type User = { name: string email: string } - -const PORT = process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/virtual-routes/tests/app.spec.ts b/e2e/vue-start/virtual-routes/tests/app.spec.ts index 3182febfa0..e9db98e3f3 100644 --- a/e2e/vue-start/virtual-routes/tests/app.spec.ts +++ b/e2e/vue-start/virtual-routes/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts b/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts b/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/virtual-routes/tests/special-characters.spec.ts b/e2e/vue-start/virtual-routes/tests/special-characters.spec.ts new file mode 100644 index 0000000000..74598fbdac --- /dev/null +++ b/e2e/vue-start/virtual-routes/tests/special-characters.spec.ts @@ -0,0 +1,43 @@ +import { expect } from '@playwright/test' + +import { test } from '@tanstack/router-e2e-utils' + +test.use({ + whitelistErrors: [ + /Failed to load resource: the server responded with a status of 404/, + ], +}) +test.describe('Unicode route rendering', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/') + await page.waitForURL('/') + }) + + test.describe('Special characters in route paths', () => { + test('should render route with pipe character in path on direct navigation', async ({ + page, + baseURL, + }) => { + await page.goto('/special|pipe') + await page.waitForURL(`${baseURL}/special%7Cpipe`) + + await expect( + page.getByTestId('special-pipe-route-heading'), + ).toBeInViewport() + }) + + test('should render route with pipe character in path on router navigation', async ({ + page, + baseURL, + }) => { + const pipeLink = page.getByTestId('special-pipe-link') + + await pipeLink.click() + await page.waitForURL(`${baseURL}/special%7Cpipe`) + + await expect( + page.getByTestId('special-pipe-route-heading'), + ).toBeInViewport() + }) + }) +}) diff --git a/e2e/vue-start/virtual-routes/tsconfig.json b/e2e/vue-start/virtual-routes/tsconfig.json index 6d933a5b2c..6f99c0f49a 100644 --- a/e2e/vue-start/virtual-routes/tsconfig.json +++ b/e2e/vue-start/virtual-routes/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/virtual-routes/vite.config.ts b/e2e/vue-start/virtual-routes/vite.config.ts index a14ed60d41..20df237264 100644 --- a/e2e/vue-start/virtual-routes/vite.config.ts +++ b/e2e/vue-start/virtual-routes/vite.config.ts @@ -1,17 +1,16 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + resolve: { tsconfigPaths: true }, server: { port: 3000, }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), + tailwindcss(), tanstackStart({ router: { virtualRouteConfig: './routes.ts', diff --git a/e2e/vue-start/website/.devcontainer/devcontainer.json b/e2e/vue-start/website/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/e2e/vue-start/website/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/e2e/vue-start/website/package.json b/e2e/vue-start/website/package.json index 000502a037..6c30b1500f 100644 --- a/e2e/vue-start/website/package.json +++ b/e2e/vue-start/website/package.json @@ -9,29 +9,28 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "vite": "^7.1.7", + "redaxios": "catalog:", + "tailwind-merge": "^3.6.0", "vue": "^3.5.25", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@tailwindcss/postcss": "^4.1.15", + "@playwright/test": "^1.61.0", + "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "postcss": "^8.5.1", - "srvx": "^0.9.8", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "@vitejs/plugin-vue": "^6.0.3", - "@vitejs/plugin-vue-jsx": "^5.1.2", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "srvx": "^1.0.0", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/e2e/vue-start/website/playwright.config.ts b/e2e/vue-start/website/playwright.config.ts index f6dd61ba6c..e6b92ce385 100644 --- a/e2e/vue-start/website/playwright.config.ts +++ b/e2e/vue-start/website/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/website/postcss.config.mjs b/e2e/vue-start/website/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/e2e/vue-start/website/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx index b1f818dd74..77c03c5afa 100644 --- a/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx @@ -1,53 +1,61 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error(error) - - return ( -
    - -
    - - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
    -
    - ) -} +export const DefaultCatchBoundary = defineComponent({ + props: { + error: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + return () => { + console.error(props.error) + return ( +
    + +
    + + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
    +
    + ) + } + }, +}) diff --git a/e2e/vue-start/website/src/routeTree.gen.ts b/e2e/vue-start/website/src/routeTree.gen.ts index 6b390c0fcf..0909725a4b 100644 --- a/e2e/vue-start/website/src/routeTree.gen.ts +++ b/e2e/vue-start/website/src/routeTree.gen.ts @@ -10,11 +10,11 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as LibraryRouteImport } from './routes/_library' -import { Route as LibraryIndexRouteImport } from './routes/_library.index' import { Route as ProjectIndexRouteImport } from './routes/$project.index' +import { Route as LibraryIndexRouteImport } from './routes/_library.index' import { Route as LibraryProjectRouteImport } from './routes/_library.$project' -import { Route as LibraryProjectVersionIndexRouteImport } from './routes/_library.$project.$version.index' import { Route as ProjectVersionDocsIndexRouteImport } from './routes/$project.$version.docs.index' +import { Route as LibraryProjectVersionIndexRouteImport } from './routes/_library.$project.$version.index' import { Route as ProjectVersionDocsFrameworkFrameworkRouteImport } from './routes/$project.$version.docs.framework.$framework' import { Route as ProjectVersionDocsFrameworkFrameworkIndexRouteImport } from './routes/$project.$version.docs.framework.$framework.index' import { Route as ProjectVersionDocsFrameworkFrameworkSplatRouteImport } from './routes/$project.$version.docs.framework.$framework.$' @@ -24,32 +24,32 @@ const LibraryRoute = LibraryRouteImport.update({ id: '/_library', getParentRoute: () => rootRouteImport, } as any) -const LibraryIndexRoute = LibraryIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => LibraryRoute, -} as any) const ProjectIndexRoute = ProjectIndexRouteImport.update({ id: '/$project/', path: '/$project/', getParentRoute: () => rootRouteImport, } as any) +const LibraryIndexRoute = LibraryIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => LibraryRoute, +} as any) const LibraryProjectRoute = LibraryProjectRouteImport.update({ id: '/$project', path: '/$project', getParentRoute: () => LibraryRoute, } as any) +const ProjectVersionDocsIndexRoute = ProjectVersionDocsIndexRouteImport.update({ + id: '/$project/$version/docs/', + path: '/$project/$version/docs/', + getParentRoute: () => rootRouteImport, +} as any) const LibraryProjectVersionIndexRoute = LibraryProjectVersionIndexRouteImport.update({ id: '/$version/', path: '/$version/', getParentRoute: () => LibraryProjectRoute, } as any) -const ProjectVersionDocsIndexRoute = ProjectVersionDocsIndexRouteImport.update({ - id: '/$project/$version/docs/', - path: '/$project/$version/docs/', - getParentRoute: () => rootRouteImport, -} as any) const ProjectVersionDocsFrameworkFrameworkRoute = ProjectVersionDocsFrameworkFrameworkRouteImport.update({ id: '/$project/$version/docs/framework/$framework', @@ -76,10 +76,11 @@ const ProjectVersionDocsFrameworkFrameworkExamplesSplatRoute = } as any) export interface FileRoutesByFullPath { - '/$project': typeof ProjectIndexRoute '/': typeof LibraryIndexRoute - '/$project/$version/docs': typeof ProjectVersionDocsIndexRoute - '/$project/$version': typeof LibraryProjectVersionIndexRoute + '/$project': typeof LibraryProjectRouteWithChildren + '/$project/': typeof ProjectIndexRoute + '/$project/$version/docs/': typeof ProjectVersionDocsIndexRoute + '/$project/$version/': typeof LibraryProjectVersionIndexRoute '/$project/$version/docs/framework/$framework': typeof ProjectVersionDocsFrameworkFrameworkRouteWithChildren '/$project/$version/docs/framework/$framework/$': typeof ProjectVersionDocsFrameworkFrameworkSplatRoute '/$project/$version/docs/framework/$framework/': typeof ProjectVersionDocsFrameworkFrameworkIndexRoute @@ -110,10 +111,11 @@ export interface FileRoutesById { export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: - | '/$project' | '/' - | '/$project/$version/docs' - | '/$project/$version' + | '/$project' + | '/$project/' + | '/$project/$version/docs/' + | '/$project/$version/' | '/$project/$version/docs/framework/$framework' | '/$project/$version/docs/framework/$framework/$' | '/$project/$version/docs/framework/$framework/' @@ -153,10 +155,17 @@ declare module '@tanstack/vue-router' { '/_library': { id: '/_library' path: '' - fullPath: '' + fullPath: '/' preLoaderRoute: typeof LibraryRouteImport parentRoute: typeof rootRouteImport } + '/$project/': { + id: '/$project/' + path: '/$project' + fullPath: '/$project/' + preLoaderRoute: typeof ProjectIndexRouteImport + parentRoute: typeof rootRouteImport + } '/_library/': { id: '/_library/' path: '/' @@ -164,13 +173,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LibraryIndexRouteImport parentRoute: typeof LibraryRoute } - '/$project/': { - id: '/$project/' - path: '/$project' - fullPath: '/$project' - preLoaderRoute: typeof ProjectIndexRouteImport - parentRoute: typeof rootRouteImport - } '/_library/$project': { id: '/_library/$project' path: '/$project' @@ -178,20 +180,20 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LibraryProjectRouteImport parentRoute: typeof LibraryRoute } - '/_library/$project/$version/': { - id: '/_library/$project/$version/' - path: '/$version' - fullPath: '/$project/$version' - preLoaderRoute: typeof LibraryProjectVersionIndexRouteImport - parentRoute: typeof LibraryProjectRoute - } '/$project/$version/docs/': { id: '/$project/$version/docs/' path: '/$project/$version/docs' - fullPath: '/$project/$version/docs' + fullPath: '/$project/$version/docs/' preLoaderRoute: typeof ProjectVersionDocsIndexRouteImport parentRoute: typeof rootRouteImport } + '/_library/$project/$version/': { + id: '/_library/$project/$version/' + path: '/$version' + fullPath: '/$project/$version/' + preLoaderRoute: typeof LibraryProjectVersionIndexRouteImport + parentRoute: typeof LibraryProjectRoute + } '/$project/$version/docs/framework/$framework': { id: '/$project/$version/docs/framework/$framework' path: '/$project/$version/docs/framework/$framework' diff --git a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx index f56c911b88..1d9173f200 100644 --- a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx +++ b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx @@ -1,9 +1,27 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' import { NotFound } from '~/components/NotFound' import { getDocument } from '~/server/document' import { capitalize, seo } from '~/utils/seo' +const Page = defineComponent({ + setup() { + const post = Route.useLoaderData() + return () => ( +
    +

    + {post.value.title} +

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

    - {post.value.title} -

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

    + {params.value._splat} example +

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

    - {params.value._splat} example -

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

    + {pathname.value} +

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

    - {pathname.value} -

    - -
    -
    - ) -} diff --git a/e2e/vue-start/website/src/routes/$project.$version.docs.index.tsx b/e2e/vue-start/website/src/routes/$project.$version.docs.index.tsx index b033d53865..8c067c8c86 100644 --- a/e2e/vue-start/website/src/routes/$project.$version.docs.index.tsx +++ b/e2e/vue-start/website/src/routes/$project.$version.docs.index.tsx @@ -3,7 +3,7 @@ import { redirect, createFileRoute } from '@tanstack/vue-router' export const Route = createFileRoute('/$project/$version/docs/')({ beforeLoad: () => { throw redirect({ - from: '/$project/$version/docs', + from: '/$project/$version/docs/', to: '/$project/$version/docs/framework/$framework/$', params: { framework: 'vue', diff --git a/e2e/vue-start/website/src/routes/__root.tsx b/e2e/vue-start/website/src/routes/__root.tsx index 64228c166e..744cac4b11 100644 --- a/e2e/vue-start/website/src/routes/__root.tsx +++ b/e2e/vue-start/website/src/routes/__root.tsx @@ -51,7 +51,11 @@ export const Route = createRootRoute({ ], }), errorComponent: (props) => { - return

    {props.error.stack}

    + return ( +

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

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

    + {params.value.project} landing page +

    +

    + version: {params.value.version} +

    +

    + + Get started with our documentation. + +

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

    - {params.value.project} landing page -

    -

    version: {params.value.version}

    -

    - - Get started with our documentation. - -

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

    + {pathname.value} +

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

    - {pathname.value} -

    - -
    -
    - ) -} diff --git a/e2e/vue-start/website/src/server/document.tsx b/e2e/vue-start/website/src/server/document.tsx index 6623a50a5c..883efbed80 100644 --- a/e2e/vue-start/website/src/server/document.tsx +++ b/e2e/vue-start/website/src/server/document.tsx @@ -41,7 +41,7 @@ export const getDocumentHeads = createServerFn({ method: 'GET' }).handler( ) export const getDocument = createServerFn({ method: 'GET' }) - .inputValidator((id: string) => id) + .validator((id: string) => id) .handler(async ({ data: id }) => { await new Promise((resolve) => setTimeout(resolve, 200)) diff --git a/e2e/vue-start/website/src/server/projects.tsx b/e2e/vue-start/website/src/server/projects.tsx index c97604a199..4ca98c754f 100644 --- a/e2e/vue-start/website/src/server/projects.tsx +++ b/e2e/vue-start/website/src/server/projects.tsx @@ -13,7 +13,7 @@ export const getProjects = createServerFn({ method: 'GET' }).handler( ) export const getProject = createServerFn({ method: 'GET' }) - .inputValidator((project: string) => project) + .validator((project: string) => project) .handler(async (ctx) => { await new Promise((resolve) => setTimeout(resolve, 200)) diff --git a/e2e/vue-start/website/src/styles/app.css b/e2e/vue-start/website/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/e2e/vue-start/website/src/styles/app.css +++ b/e2e/vue-start/website/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/e2e/vue-start/website/tsconfig.json b/e2e/vue-start/website/tsconfig.json index f9f5aab3da..390dad84c0 100644 --- a/e2e/vue-start/website/tsconfig.json +++ b/e2e/vue-start/website/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/e2e/vue-start/website/vite.config.ts b/e2e/vue-start/website/vite.config.ts index 79edfc05c2..563e212077 100644 --- a/e2e/vue-start/website/vite.config.ts +++ b/e2e/vue-start/website/vite.config.ts @@ -1,19 +1,13 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + resolve: { tsconfigPaths: true }, server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - vue(), - vueJsx(), - ], + plugins: [tailwindcss(), tanstackStart(), vue(), vueJsx()], }) diff --git a/eslint.config.js b/eslint.config.js index 90e320da68..f58cc3fd10 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,9 +1,10 @@ // @ts-check -import { tanstackConfig } from '@tanstack/config/eslint' +import { tanstackConfig } from '@tanstack/eslint-config' import unusedImports from 'eslint-plugin-unused-imports' +/** @type {import('eslint').Linter.Config[]} */ export default [ ...tanstackConfig, { diff --git a/examples/AGENTS.md b/examples/AGENTS.md new file mode 100644 index 0000000000..eb47fbd925 --- /dev/null +++ b/examples/AGENTS.md @@ -0,0 +1,4 @@ +# Examples + +- Versioned dependencies on this repository's packages resolve locally through `pnpm-workspace.yaml` overrides. Keep published version ranges in example manifests; do not replace them with `workspace:*` as a linking fix. +- Root `pnpm dev` watches package builds. To run an example app, use its own `dev` script after building its workspace dependencies. diff --git a/examples/react/authenticated-routes-firebase/.devcontainer/devcontainer.json b/examples/react/authenticated-routes-firebase/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/authenticated-routes-firebase/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/authenticated-routes-firebase/package.json b/examples/react/authenticated-routes-firebase/package.json index 8a6bd7dbd3..1efa172047 100644 --- a/examples/react/authenticated-routes-firebase/package.json +++ b/examples/react/authenticated-routes-firebase/package.json @@ -9,24 +9,24 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "firebase": "^11.4.0", - "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", "simple-icons": "^14.9.0", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/authenticated-routes-firebase/postcss.config.mjs b/examples/react/authenticated-routes-firebase/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/authenticated-routes-firebase/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts b/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts index f71d146de9..bcc454ab03 100644 --- a/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts +++ b/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts @@ -9,38 +9,38 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthRouteImport } from './routes/_auth' import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as LoginRouteImport } from './routes/login' import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' +import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => AuthRoute, -} as any) const AuthDashboardRoute = AuthDashboardRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => AuthRoute, } as any) +const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,20 +107,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/_auth': { - id: '/_auth' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -128,12 +114,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/_auth/invoices': { - id: '/_auth/invoices' - path: '/invoices' - fullPath: '/invoices' - preLoaderRoute: typeof AuthInvoicesRouteImport - parentRoute: typeof AuthRoute + '/_auth': { + id: '/_auth' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthRouteImport + parentRoute: typeof rootRouteImport + } + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport } '/_auth/dashboard': { id: '/_auth/dashboard' @@ -142,6 +135,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthDashboardRouteImport parentRoute: typeof AuthRoute } + '/_auth/invoices': { + id: '/_auth/invoices' + path: '/invoices' + fullPath: '/invoices' + preLoaderRoute: typeof AuthInvoicesRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/react/authenticated-routes-firebase/src/styles.css b/examples/react/authenticated-routes-firebase/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/authenticated-routes-firebase/src/styles.css +++ b/examples/react/authenticated-routes-firebase/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/authenticated-routes-firebase/vite.config.js b/examples/react/authenticated-routes-firebase/vite.config.js index 47e327b746..e6a8f48b5f 100644 --- a/examples/react/authenticated-routes-firebase/vite.config.js +++ b/examples/react/authenticated-routes-firebase/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true, diff --git a/examples/react/authenticated-routes/.devcontainer/devcontainer.json b/examples/react/authenticated-routes/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/authenticated-routes/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/authenticated-routes/package.json b/examples/react/authenticated-routes/package.json index e950c43096..6af48f1d34 100644 --- a/examples/react/authenticated-routes/package.json +++ b/examples/react/authenticated-routes/package.json @@ -9,22 +9,22 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/authenticated-routes/postcss.config.mjs b/examples/react/authenticated-routes/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/authenticated-routes/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/authenticated-routes/src/routeTree.gen.ts b/examples/react/authenticated-routes/src/routeTree.gen.ts index f71d146de9..bcc454ab03 100644 --- a/examples/react/authenticated-routes/src/routeTree.gen.ts +++ b/examples/react/authenticated-routes/src/routeTree.gen.ts @@ -9,38 +9,38 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthRouteImport } from './routes/_auth' import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as LoginRouteImport } from './routes/login' import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' +import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => AuthRoute, -} as any) const AuthDashboardRoute = AuthDashboardRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => AuthRoute, } as any) +const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,20 +107,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/_auth': { - id: '/_auth' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -128,12 +114,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/_auth/invoices': { - id: '/_auth/invoices' - path: '/invoices' - fullPath: '/invoices' - preLoaderRoute: typeof AuthInvoicesRouteImport - parentRoute: typeof AuthRoute + '/_auth': { + id: '/_auth' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthRouteImport + parentRoute: typeof rootRouteImport + } + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport } '/_auth/dashboard': { id: '/_auth/dashboard' @@ -142,6 +135,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthDashboardRouteImport parentRoute: typeof AuthRoute } + '/_auth/invoices': { + id: '/_auth/invoices' + path: '/invoices' + fullPath: '/invoices' + preLoaderRoute: typeof AuthInvoicesRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/react/authenticated-routes/src/styles.css b/examples/react/authenticated-routes/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/authenticated-routes/src/styles.css +++ b/examples/react/authenticated-routes/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/authenticated-routes/src/vite-env.d.ts b/examples/react/authenticated-routes/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/authenticated-routes/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/authenticated-routes/vite.config.js b/examples/react/authenticated-routes/vite.config.js index 47e327b746..e6a8f48b5f 100644 --- a/examples/react/authenticated-routes/vite.config.js +++ b/examples/react/authenticated-routes/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true, diff --git a/examples/react/basic-default-search-params/.devcontainer/devcontainer.json b/examples/react/basic-default-search-params/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/basic-default-search-params/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/basic-default-search-params/package.json b/examples/react/basic-default-search-params/package.json index 08fce10b40..96c68fecd4 100644 --- a/examples/react/basic-default-search-params/package.json +++ b/examples/react/basic-default-search-params/package.json @@ -9,22 +9,22 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/basic-default-search-params/postcss.config.mjs b/examples/react/basic-default-search-params/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/basic-default-search-params/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/basic-default-search-params/src/styles.css b/examples/react/basic-default-search-params/src/styles.css index a43da4d776..c346d61a12 100644 --- a/examples/react/basic-default-search-params/src/styles.css +++ b/examples/react/basic-default-search-params/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/basic-default-search-params/src/vite-env.d.ts b/examples/react/basic-default-search-params/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/basic-default-search-params/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/basic-default-search-params/vite.config.js b/examples/react/basic-default-search-params/vite.config.js index 5a33944a9b..2764078e8b 100644 --- a/examples/react/basic-default-search-params/vite.config.js +++ b/examples/react/basic-default-search-params/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [tailwindcss(), react()], }) diff --git a/examples/react/basic-devtools-panel/.devcontainer/devcontainer.json b/examples/react/basic-devtools-panel/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/basic-devtools-panel/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/basic-devtools-panel/package.json b/examples/react/basic-devtools-panel/package.json index 40caf81123..ccae95d73f 100644 --- a/examples/react/basic-devtools-panel/package.json +++ b/examples/react/basic-devtools-panel/package.json @@ -9,21 +9,22 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.67.2", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/basic-devtools-panel/postcss.config.mjs b/examples/react/basic-devtools-panel/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/basic-devtools-panel/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/basic-devtools-panel/src/styles.css b/examples/react/basic-devtools-panel/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/basic-devtools-panel/src/styles.css +++ b/examples/react/basic-devtools-panel/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/basic-devtools-panel/src/vite-env.d.ts b/examples/react/basic-devtools-panel/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/basic-devtools-panel/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/basic-devtools-panel/vite.config.js b/examples/react/basic-devtools-panel/vite.config.js index 5a33944a9b..2764078e8b 100644 --- a/examples/react/basic-devtools-panel/vite.config.js +++ b/examples/react/basic-devtools-panel/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [tailwindcss(), react()], }) diff --git a/examples/react/basic-file-based/.devcontainer/devcontainer.json b/examples/react/basic-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/basic-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/basic-file-based/package.json b/examples/react/basic-file-based/package.json index 89897c9c4c..9c3cacada1 100644 --- a/examples/react/basic-file-based/package.json +++ b/examples/react/basic-file-based/package.json @@ -9,22 +9,22 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/basic-file-based/postcss.config.mjs b/examples/react/basic-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/basic-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/basic-file-based/src/routeTree.gen.ts b/examples/react/basic-file-based/src/routeTree.gen.ts index b8a45d6152..f370ad5d03 100644 --- a/examples/react/basic-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-file-based/src/routeTree.gen.ts @@ -9,35 +9,40 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AnchorRouteImport } from './routes/anchor' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as AnchorRouteImport } from './routes/anchor' +import { Route as PostsRouteRouteImport } from './routes/posts.route' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -const AnchorRoute = AnchorRouteImport.update({ - id: '/anchor', - path: '/anchor', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) +const AnchorRoute = AnchorRouteImport.update({ + id: '/anchor', + path: '/anchor', + getParentRoute: () => rootRouteImport, +} as any) const PostsRouteRoute = PostsRouteRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -48,10 +53,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,12 +65,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -129,20 +129,27 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/anchor': { - id: '/anchor' - path: '/anchor' - fullPath: '/anchor' - preLoaderRoute: typeof AnchorRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' - fullPath: '' + fullPath: '/' preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } + '/anchor': { + id: '/anchor' + path: '/anchor' + fullPath: '/anchor' + preLoaderRoute: typeof AnchorRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -150,12 +157,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/posts/': { id: '/posts/' @@ -171,12 +178,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -185,13 +192,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/examples/react/basic-file-based/src/styles.css b/examples/react/basic-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/basic-file-based/src/styles.css +++ b/examples/react/basic-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/basic-file-based/src/vite-env.d.ts b/examples/react/basic-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/basic-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/basic-file-based/vite.config.js b/examples/react/basic-file-based/vite.config.js index 47e327b746..e6a8f48b5f 100644 --- a/examples/react/basic-file-based/vite.config.js +++ b/examples/react/basic-file-based/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true, diff --git a/examples/react/basic-non-nested-devtools/.devcontainer/devcontainer.json b/examples/react/basic-non-nested-devtools/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/basic-non-nested-devtools/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/basic-non-nested-devtools/package.json b/examples/react/basic-non-nested-devtools/package.json index 7697c5db05..32e856ebcf 100644 --- a/examples/react/basic-non-nested-devtools/package.json +++ b/examples/react/basic-non-nested-devtools/package.json @@ -9,20 +9,20 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/basic-non-nested-devtools/postcss.config.mjs b/examples/react/basic-non-nested-devtools/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/basic-non-nested-devtools/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/basic-non-nested-devtools/src/styles.css b/examples/react/basic-non-nested-devtools/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/basic-non-nested-devtools/src/styles.css +++ b/examples/react/basic-non-nested-devtools/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/basic-non-nested-devtools/src/vite-env.d.ts b/examples/react/basic-non-nested-devtools/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/basic-non-nested-devtools/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/basic-non-nested-devtools/vite.config.js b/examples/react/basic-non-nested-devtools/vite.config.js index 5a33944a9b..2764078e8b 100644 --- a/examples/react/basic-non-nested-devtools/vite.config.js +++ b/examples/react/basic-non-nested-devtools/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [tailwindcss(), react()], }) diff --git a/examples/react/basic-react-query-file-based/.devcontainer/devcontainer.json b/examples/react/basic-react-query-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/basic-react-query-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/basic-react-query-file-based/package.json b/examples/react/basic-react-query-file-based/package.json index 83da4693ec..d01a02872e 100644 --- a/examples/react/basic-react-query-file-based/package.json +++ b/examples/react/basic-react-query-file-based/package.json @@ -9,24 +9,24 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-query": "^5.90.0", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "postcss": "^8.5.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/basic-react-query-file-based/postcss.config.mjs b/examples/react/basic-react-query-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/basic-react-query-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/basic-react-query-file-based/src/routeTree.gen.ts b/examples/react/basic-react-query-file-based/src/routeTree.gen.ts index 03f3dc23c6..9676858c7c 100644 --- a/examples/react/basic-react-query-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-react-query-file-based/src/routeTree.gen.ts @@ -9,15 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -27,11 +32,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,10 +47,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -53,12 +59,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,10 +117,17 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' - fullPath: '' + fullPath: '/' preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } @@ -131,12 +138,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/posts/': { id: '/posts/' @@ -152,12 +159,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -166,13 +173,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/examples/react/basic-react-query-file-based/src/styles.css b/examples/react/basic-react-query-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/basic-react-query-file-based/src/styles.css +++ b/examples/react/basic-react-query-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/basic-react-query-file-based/src/vite-env.d.ts b/examples/react/basic-react-query-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/basic-react-query-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/basic-react-query-file-based/vite.config.js b/examples/react/basic-react-query-file-based/vite.config.js index ab615485ae..ce5fc59483 100644 --- a/examples/react/basic-react-query-file-based/vite.config.js +++ b/examples/react/basic-react-query-file-based/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true }), react(), ], diff --git a/examples/react/basic-react-query/.devcontainer/devcontainer.json b/examples/react/basic-react-query/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/basic-react-query/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/basic-react-query/package.json b/examples/react/basic-react-query/package.json index 6a4cb846e1..edab96afac 100644 --- a/examples/react/basic-react-query/package.json +++ b/examples/react/basic-react-query/package.json @@ -9,22 +9,22 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-query": "^5.90.0", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/basic-react-query/postcss.config.mjs b/examples/react/basic-react-query/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/basic-react-query/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/basic-react-query/src/styles.css b/examples/react/basic-react-query/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/basic-react-query/src/styles.css +++ b/examples/react/basic-react-query/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/basic-react-query/src/vite-env.d.ts b/examples/react/basic-react-query/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/basic-react-query/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/basic-react-query/vite.config.js b/examples/react/basic-react-query/vite.config.js index 5a33944a9b..2764078e8b 100644 --- a/examples/react/basic-react-query/vite.config.js +++ b/examples/react/basic-react-query/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [tailwindcss(), react()], }) diff --git a/examples/react/basic-ssr-file-based/.devcontainer/devcontainer.json b/examples/react/basic-ssr-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/basic-ssr-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/basic-ssr-file-based/package.json b/examples/react/basic-ssr-file-based/package.json index 5466d97030..3222c33e19 100644 --- a/examples/react/basic-ssr-file-based/package.json +++ b/examples/react/basic-ssr-file-based/package.json @@ -11,22 +11,23 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "compression": "^1.8.0", - "express": "^4.21.2", + "express": "^5.2.1", "get-port": "^7.1.0", "node-fetch": "^3.3.2", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.141.8", - "@types/express": "^4.17.23", + "@tanstack/react-router-devtools": "^1.167.3", + "@types/express": "^5.0.6", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", - "@vitejs/plugin-react": "^4.5.2", - "typescript": "^5.8.3", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/basic-ssr-file-based/server.js b/examples/react/basic-ssr-file-based/server.js index 5686edc048..6d060a19f0 100644 --- a/examples/react/basic-ssr-file-based/server.js +++ b/examples/react/basic-ssr-file-based/server.js @@ -51,7 +51,7 @@ export async function createServer( if (isProd) app.use(express.static('./dist/client')) - app.use('*', async (req, res) => { + app.use('/{*splat}', async (req, res) => { try { const url = req.originalUrl @@ -97,7 +97,8 @@ export async function createServer( if (!isTest) { createServer().then(async ({ app }) => - app.listen(await getPort({ port: portNumbers(3000, 3100) }), () => { + app.listen(await getPort({ port: portNumbers(3000, 3100) }), (error) => { + if (error) throw error console.info('Client Server: http://localhost:3000') }), ) diff --git a/examples/react/basic-ssr-file-based/src/routeTree.gen.ts b/examples/react/basic-ssr-file-based/src/routeTree.gen.ts index 4e61620e43..6f9f3f0f5e 100644 --- a/examples/react/basic-ssr-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-ssr-file-based/src/routeTree.gen.ts @@ -9,12 +9,17 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' import { Route as ErrorRouteImport } from './routes/error' import { Route as PostsRouteRouteImport } from './routes/posts/route' -import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts/index' import { Route as PostsPostIdRouteImport } from './routes/posts/$postId' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const ErrorRoute = ErrorRouteImport.update({ id: '/error', path: '/error', @@ -25,11 +30,6 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -78,6 +78,13 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/error': { id: '/error' path: '/error' @@ -92,13 +99,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/react/basic-ssr-file-based/vite.config.ts b/examples/react/basic-ssr-file-based/vite.config.ts index 09cc95baa8..93ff5dea85 100644 --- a/examples/react/basic-ssr-file-based/vite.config.ts +++ b/examples/react/basic-ssr-file-based/vite.config.ts @@ -15,7 +15,7 @@ const ssrBuildConfig: BuildEnvironmentOptions = { ssrEmitAssets: true, copyPublicDir: false, emptyOutDir: true, - rollupOptions: { + rolldownOptions: { input: path.resolve(__dirname, 'src/entry-server.tsx'), output: { entryFileNames: '[name].js', @@ -31,7 +31,7 @@ const clientBuildConfig: BuildEnvironmentOptions = { emitAssets: true, copyPublicDir: true, emptyOutDir: true, - rollupOptions: { + rolldownOptions: { input: path.resolve(__dirname, 'src/entry-client.tsx'), output: { entryFileNames: 'static/[name].js', diff --git a/examples/react/basic-ssr-streaming-file-based/.devcontainer/devcontainer.json b/examples/react/basic-ssr-streaming-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/basic-ssr-streaming-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/basic-ssr-streaming-file-based/package.json b/examples/react/basic-ssr-streaming-file-based/package.json index 21e5eeedf3..c3c87c8d88 100644 --- a/examples/react/basic-ssr-streaming-file-based/package.json +++ b/examples/react/basic-ssr-streaming-file-based/package.json @@ -11,22 +11,23 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "compression": "^1.8.0", - "express": "^4.21.2", + "express": "^5.2.1", "get-port": "^7.1.0", "node-fetch": "^3.3.2", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.141.8", - "@types/express": "^4.17.23", + "@tanstack/react-router-devtools": "^1.167.3", + "@types/express": "^5.0.6", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/basic-ssr-streaming-file-based/server.js b/examples/react/basic-ssr-streaming-file-based/server.js index 5686edc048..6d060a19f0 100644 --- a/examples/react/basic-ssr-streaming-file-based/server.js +++ b/examples/react/basic-ssr-streaming-file-based/server.js @@ -51,7 +51,7 @@ export async function createServer( if (isProd) app.use(express.static('./dist/client')) - app.use('*', async (req, res) => { + app.use('/{*splat}', async (req, res) => { try { const url = req.originalUrl @@ -97,7 +97,8 @@ export async function createServer( if (!isTest) { createServer().then(async ({ app }) => - app.listen(await getPort({ port: portNumbers(3000, 3100) }), () => { + app.listen(await getPort({ port: portNumbers(3000, 3100) }), (error) => { + if (error) throw error console.info('Client Server: http://localhost:3000') }), ) diff --git a/examples/react/basic-ssr-streaming-file-based/src/routeTree.gen.ts b/examples/react/basic-ssr-streaming-file-based/src/routeTree.gen.ts index 4e61620e43..6f9f3f0f5e 100644 --- a/examples/react/basic-ssr-streaming-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-ssr-streaming-file-based/src/routeTree.gen.ts @@ -9,12 +9,17 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' import { Route as ErrorRouteImport } from './routes/error' import { Route as PostsRouteRouteImport } from './routes/posts/route' -import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts/index' import { Route as PostsPostIdRouteImport } from './routes/posts/$postId' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const ErrorRoute = ErrorRouteImport.update({ id: '/error', path: '/error', @@ -25,11 +30,6 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -78,6 +78,13 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/error': { id: '/error' path: '/error' @@ -92,13 +99,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/react/basic-ssr-streaming-file-based/vite.config.ts b/examples/react/basic-ssr-streaming-file-based/vite.config.ts index e6e86d12a0..50f2ef6300 100644 --- a/examples/react/basic-ssr-streaming-file-based/vite.config.ts +++ b/examples/react/basic-ssr-streaming-file-based/vite.config.ts @@ -15,7 +15,7 @@ const ssrBuildConfig: BuildEnvironmentOptions = { ssrEmitAssets: true, copyPublicDir: false, emptyOutDir: true, - rollupOptions: { + rolldownOptions: { input: path.resolve(__dirname, 'src/entry-server.tsx'), output: { entryFileNames: '[name].js', @@ -31,7 +31,7 @@ const clientBuildConfig: BuildEnvironmentOptions = { emitAssets: true, copyPublicDir: true, emptyOutDir: true, - rollupOptions: { + rolldownOptions: { input: path.resolve(__dirname, 'src/entry-client.tsx'), output: { entryFileNames: 'static/[name].js', diff --git a/examples/react/basic-virtual-file-based/.devcontainer/devcontainer.json b/examples/react/basic-virtual-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/basic-virtual-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/basic-virtual-file-based/package.json b/examples/react/basic-virtual-file-based/package.json index 531f86672a..84d326435c 100644 --- a/examples/react/basic-virtual-file-based/package.json +++ b/examples/react/basic-virtual-file-based/package.json @@ -9,23 +9,23 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "@tanstack/virtual-file-routes": "^1.141.0", - "postcss": "^8.5.1", + "@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/virtual-file-routes": "^1.162.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/basic-virtual-file-based/postcss.config.mjs b/examples/react/basic-virtual-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/basic-virtual-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/basic-virtual-file-based/src/routeTree.gen.ts b/examples/react/basic-virtual-file-based/src/routeTree.gen.ts index dc243ae857..6745e373aa 100644 --- a/examples/react/basic-virtual-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-virtual-file-based/src/routeTree.gen.ts @@ -8,80 +8,78 @@ // You should NOT make any changes in this file as it will be overwritten. // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. -import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/react-router' - import { Route as rootRouteImport } from './routes/root' -import { Route as postsPostsRouteImport } from './routes/posts/posts' -import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' import { Route as homeRouteImport } from './routes/home' -import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' +import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' +import { Route as postsPostsRouteImport } from './routes/posts/posts' import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' -import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' +import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' -import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' -import { Route as bRouteImport } from './routes/b' +import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' import { Route as aRouteImport } from './routes/a' +import { Route as bRouteImport } from './routes/b' -const postsPostsRoute = postsPostsRouteImport.update({ - id: '/posts', - path: '/posts', +const homeRoute = homeRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', +const postsPostsRoute = postsPostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => postsPostsRoute, -} as any) const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ id: '/_second-layout', getParentRoute: () => layoutFirstLayoutRoute, } as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => postsPostsRoute, -} as any) const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ id: '/classic/hello', path: '/classic/hello', getParentRoute: () => rootRouteImport, } as any) +const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => postsPostsRoute, +} as any) +const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => postsPostsRoute, +} as any) const ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ - id: '/world', - path: '/world', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ id: '/universe', path: '/universe', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const bRoute = bRouteImport.update({ - id: '/route-without-file/layout-b', - path: '/route-without-file/layout-b', - getParentRoute: () => layoutSecondLayoutRoute, +const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ + id: '/world', + path: '/world', + getParentRoute: () => ClassicHelloRouteRoute, } as any) const aRoute = aRouteImport.update({ id: '/route-without-file/layout-a', path: '/route-without-file/layout-a', getParentRoute: () => layoutSecondLayoutRoute, } as any) +const bRoute = bRouteImport.update({ + id: '/route-without-file/layout-b', + path: '/route-without-file/layout-b', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof homeRoute @@ -168,20 +166,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof postsPostsRouteImport - parentRoute: typeof rootRouteImport - } - '/_first': { - id: '/_first' - path: '' - fullPath: '' - preLoaderRoute: typeof layoutFirstLayoutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -189,27 +173,27 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof homeRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof postsPostsDetailRouteImport - parentRoute: typeof postsPostsRoute + '/_first': { + id: '/_first' + path: '' + fullPath: '/' + preLoaderRoute: typeof layoutFirstLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof postsPostsRouteImport + parentRoute: typeof rootRouteImport } '/_first/_second-layout': { id: '/_first/_second-layout' path: '' - fullPath: '' + fullPath: '/' preLoaderRoute: typeof layoutSecondLayoutRouteImport parentRoute: typeof layoutFirstLayoutRoute } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute - } '/classic/hello': { id: '/classic/hello' path: '/classic/hello' @@ -217,6 +201,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClassicHelloRouteRouteImport parentRoute: typeof rootRouteImport } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof postsPostsHomeRouteImport + parentRoute: typeof postsPostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof postsPostsDetailRouteImport + parentRoute: typeof postsPostsRoute + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -224,13 +222,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/world': { - id: '/classic/hello/world' - path: '/world' - fullPath: '/classic/hello/world' - preLoaderRoute: typeof ClassicHelloWorldRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/universe': { id: '/classic/hello/universe' path: '/universe' @@ -238,12 +229,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClassicHelloUniverseRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second-layout/route-without-file/layout-b': { - id: '/_first/_second-layout/route-without-file/layout-b' - path: '/route-without-file/layout-b' - fullPath: '/route-without-file/layout-b' - preLoaderRoute: typeof bRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/world': { + id: '/classic/hello/world' + path: '/world' + fullPath: '/classic/hello/world' + preLoaderRoute: typeof ClassicHelloWorldRouteImport + parentRoute: typeof ClassicHelloRouteRoute } '/_first/_second-layout/route-without-file/layout-a': { id: '/_first/_second-layout/route-without-file/layout-a' @@ -252,118 +243,16 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof aRouteImport parentRoute: typeof layoutSecondLayoutRoute } + '/_first/_second-layout/route-without-file/layout-b': { + id: '/_first/_second-layout/route-without-file/layout-b' + path: '/route-without-file/layout-b' + fullPath: '/route-without-file/layout-b' + preLoaderRoute: typeof bRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } } } -declare module './routes/home' { - const createFileRoute: CreateFileRoute< - '/', - FileRoutesByPath['/']['parentRoute'], - FileRoutesByPath['/']['id'], - FileRoutesByPath['/']['path'], - FileRoutesByPath['/']['fullPath'] - > -} -declare module './routes/layout/first-layout' { - const createFileRoute: CreateFileRoute< - '/_first', - FileRoutesByPath['/_first']['parentRoute'], - FileRoutesByPath['/_first']['id'], - FileRoutesByPath['/_first']['path'], - FileRoutesByPath['/_first']['fullPath'] - > -} -declare module './routes/posts/posts' { - const createFileRoute: CreateFileRoute< - '/posts', - FileRoutesByPath['/posts']['parentRoute'], - FileRoutesByPath['/posts']['id'], - FileRoutesByPath['/posts']['path'], - FileRoutesByPath['/posts']['fullPath'] - > -} -declare module './routes/file-based-subtree/hello/route' { - const createFileRoute: CreateFileRoute< - '/classic/hello', - FileRoutesByPath['/classic/hello']['parentRoute'], - FileRoutesByPath['/classic/hello']['id'], - FileRoutesByPath['/classic/hello']['path'], - FileRoutesByPath['/classic/hello']['fullPath'] - > -} -declare module './routes/posts/posts-home' { - const createFileRoute: CreateFileRoute< - '/posts/', - FileRoutesByPath['/posts/']['parentRoute'], - FileRoutesByPath['/posts/']['id'], - FileRoutesByPath['/posts/']['path'], - FileRoutesByPath['/posts/']['fullPath'] - > -} -declare module './routes/layout/second-layout' { - const createFileRoute: CreateFileRoute< - '/_first/_second-layout', - FileRoutesByPath['/_first/_second-layout']['parentRoute'], - FileRoutesByPath['/_first/_second-layout']['id'], - FileRoutesByPath['/_first/_second-layout']['path'], - FileRoutesByPath['/_first/_second-layout']['fullPath'] - > -} -declare module './routes/posts/posts-detail' { - const createFileRoute: CreateFileRoute< - '/posts/$postId', - FileRoutesByPath['/posts/$postId']['parentRoute'], - FileRoutesByPath['/posts/$postId']['id'], - FileRoutesByPath['/posts/$postId']['path'], - FileRoutesByPath['/posts/$postId']['fullPath'] - > -} -declare module './routes/file-based-subtree/hello/universe' { - const createFileRoute: CreateFileRoute< - '/classic/hello/universe', - FileRoutesByPath['/classic/hello/universe']['parentRoute'], - FileRoutesByPath['/classic/hello/universe']['id'], - FileRoutesByPath['/classic/hello/universe']['path'], - FileRoutesByPath['/classic/hello/universe']['fullPath'] - > -} -declare module './routes/file-based-subtree/hello/world' { - const createFileRoute: CreateFileRoute< - '/classic/hello/world', - FileRoutesByPath['/classic/hello/world']['parentRoute'], - FileRoutesByPath['/classic/hello/world']['id'], - FileRoutesByPath['/classic/hello/world']['path'], - FileRoutesByPath['/classic/hello/world']['fullPath'] - > -} -declare module './routes/file-based-subtree/hello/index' { - const createFileRoute: CreateFileRoute< - '/classic/hello/', - FileRoutesByPath['/classic/hello/']['parentRoute'], - FileRoutesByPath['/classic/hello/']['id'], - FileRoutesByPath['/classic/hello/']['path'], - FileRoutesByPath['/classic/hello/']['fullPath'] - > -} -declare module './routes/a' { - const createFileRoute: CreateFileRoute< - '/_first/_second-layout/route-without-file/layout-a', - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-a']['parentRoute'], - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-a']['id'], - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-a']['path'], - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-a']['fullPath'] - > -} -declare module './routes/b' { - const createFileRoute: CreateFileRoute< - '/_first/_second-layout/route-without-file/layout-b', - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-b']['parentRoute'], - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-b']['id'], - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-b']['path'], - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-b']['fullPath'] - > -} - interface layoutSecondLayoutRouteChildren { aRoute: typeof aRoute bRoute: typeof bRoute diff --git a/examples/react/basic-virtual-file-based/src/routes/a.tsx b/examples/react/basic-virtual-file-based/src/routes/a.tsx index a190b24202..74d17276d9 100644 --- a/examples/react/basic-virtual-file-based/src/routes/a.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/a.tsx @@ -1,4 +1,7 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute( + '/_first/_second-layout/route-without-file/layout-a', +)({ component: LayoutAComponent, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/b.tsx b/examples/react/basic-virtual-file-based/src/routes/b.tsx index 505f8f6fbf..d9b95f23b4 100644 --- a/examples/react/basic-virtual-file-based/src/routes/b.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/b.tsx @@ -1,4 +1,7 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute( + '/_first/_second-layout/route-without-file/layout-b', +)({ component: LayoutBComponent, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx index f86335e291..0cc76f4a69 100644 --- a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/classic/hello/')({ component: () =>
    This is the index
    , }) diff --git a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx index 620dd2b76b..566efc8777 100644 --- a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet } from '@tanstack/react-router' +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/classic/hello')({ component: () => (
    Hello! diff --git a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx index 20b07c41cc..5aaa7d4fa0 100644 --- a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/classic/hello/universe')({ component: () =>
    Hello /classic/hello/universe!
    , }) diff --git a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx index 4af11357a2..790d33a838 100644 --- a/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/classic/hello/world')({ component: () =>
    Hello /classic/hello/world!
    , }) diff --git a/examples/react/basic-virtual-file-based/src/routes/home.tsx b/examples/react/basic-virtual-file-based/src/routes/home.tsx index b23956ae17..0a5b7572ba 100644 --- a/examples/react/basic-virtual-file-based/src/routes/home.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/home.tsx @@ -1,6 +1,7 @@ +import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' -export const Route = createFileRoute({ +export const Route = createFileRoute('/')({ component: Home, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/layout/first-layout.tsx b/examples/react/basic-virtual-file-based/src/routes/layout/first-layout.tsx index 5c4a461d8d..d39e206f2d 100644 --- a/examples/react/basic-virtual-file-based/src/routes/layout/first-layout.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/layout/first-layout.tsx @@ -1,6 +1,6 @@ -import { Outlet } from '@tanstack/react-router' +import { Outlet, createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_first')({ component: LayoutComponent, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/layout/second-layout.tsx b/examples/react/basic-virtual-file-based/src/routes/layout/second-layout.tsx index 478d9afbec..2f56647492 100644 --- a/examples/react/basic-virtual-file-based/src/routes/layout/second-layout.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/layout/second-layout.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet } from '@tanstack/react-router' +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_first/_second-layout')({ component: LayoutComponent, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/posts/posts-detail.tsx b/examples/react/basic-virtual-file-based/src/routes/posts/posts-detail.tsx index 654f3cfd18..948d52d6d6 100644 --- a/examples/react/basic-virtual-file-based/src/routes/posts/posts-detail.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/posts/posts-detail.tsx @@ -1,9 +1,9 @@ import * as React from 'react' -import { ErrorComponent } from '@tanstack/react-router' +import { ErrorComponent, createFileRoute } from '@tanstack/react-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/react-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent as any, notFoundComponent: () => { diff --git a/examples/react/basic-virtual-file-based/src/routes/posts/posts-home.tsx b/examples/react/basic-virtual-file-based/src/routes/posts/posts-home.tsx index fdbe5865e5..c6b65f1892 100644 --- a/examples/react/basic-virtual-file-based/src/routes/posts/posts-home.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/posts/posts-home.tsx @@ -1,6 +1,7 @@ +import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' -export const Route = createFileRoute({ +export const Route = createFileRoute('/posts/')({ component: PostsIndexComponent, }) diff --git a/examples/react/basic-virtual-file-based/src/routes/posts/posts.tsx b/examples/react/basic-virtual-file-based/src/routes/posts/posts.tsx index f92c37f537..a2ab1ee388 100644 --- a/examples/react/basic-virtual-file-based/src/routes/posts/posts.tsx +++ b/examples/react/basic-virtual-file-based/src/routes/posts/posts.tsx @@ -1,8 +1,8 @@ import * as React from 'react' -import { Link, Outlet } from '@tanstack/react-router' +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' import { fetchPosts } from '../../posts' -export const Route = createFileRoute({ +export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) diff --git a/examples/react/basic-virtual-file-based/src/styles.css b/examples/react/basic-virtual-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/basic-virtual-file-based/src/styles.css +++ b/examples/react/basic-virtual-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/basic-virtual-file-based/src/vite-env.d.ts b/examples/react/basic-virtual-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/basic-virtual-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/basic-virtual-file-based/vite.config.ts b/examples/react/basic-virtual-file-based/vite.config.ts index ea7fb55e88..dd4f00f500 100644 --- a/examples/react/basic-virtual-file-based/vite.config.ts +++ b/examples/react/basic-virtual-file-based/vite.config.ts @@ -1,14 +1,15 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true, - verboseFileRoutes: false, virtualRouteConfig: './routes.ts', }), react(), diff --git a/examples/react/basic-virtual-inside-file-based/.devcontainer/devcontainer.json b/examples/react/basic-virtual-inside-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/basic-virtual-inside-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/basic-virtual-inside-file-based/package.json b/examples/react/basic-virtual-inside-file-based/package.json index dd9805df40..c04cb6012e 100644 --- a/examples/react/basic-virtual-inside-file-based/package.json +++ b/examples/react/basic-virtual-inside-file-based/package.json @@ -9,23 +9,23 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "@tanstack/virtual-file-routes": "^1.141.0", - "postcss": "^8.5.1", + "@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/virtual-file-routes": "^1.162.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/basic-virtual-inside-file-based/postcss.config.mjs b/examples/react/basic-virtual-inside-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/basic-virtual-inside-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/basic-virtual-inside-file-based/src/routeTree.gen.ts b/examples/react/basic-virtual-inside-file-based/src/routeTree.gen.ts index 2d3afb4983..cda1f85f15 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-virtual-inside-file-based/src/routeTree.gen.ts @@ -8,64 +8,62 @@ // You should NOT make any changes in this file as it will be overwritten. // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. -import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/react-router' - import { Route as rootRouteImport } from './routes/__root' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' -import { Route as postsDetailsRouteImport } from './routes/posts/details' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as PostsRouteImport } from './routes/posts' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as postsHomeRouteImport } from './routes/posts/home' -import { Route as postsLetsGoIndexRouteImport } from './routes/posts/lets-go/index' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsHomeRouteImport } from './routes/posts/home' +import { Route as PostsDetailsRouteImport } from './routes/posts/details' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as postsLetsGoDeeperHomeRouteImport } from './routes/posts/lets-go/deeper/home' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsLetsGoIndexRouteImport } from './routes/posts/lets-go/index' +import { Route as PostsLetsGoDeeperHomeRouteImport } from './routes/posts/lets-go/deeper/home' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const LayoutRoute = LayoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const postsDetailsRoute = postsDetailsRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) const LayoutLayout2Route = LayoutLayout2RouteImport.update({ id: '/_layout-2', getParentRoute: () => LayoutRoute, } as any) -const postsHomeRoute = postsHomeRouteImport.update({ +const PostsHomeRoute = PostsHomeRouteImport.update({ id: '/', path: '/', getParentRoute: () => PostsRoute, } as any) -const postsLetsGoIndexRoute = postsLetsGoIndexRouteImport.update({ - id: '/inception/', - path: '/inception/', +const PostsDetailsRoute = PostsDetailsRouteImport.update({ + id: '/$postId', + path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, -} as any) const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ id: '/layout-a', path: '/layout-a', getParentRoute: () => LayoutLayout2Route, } as any) -const postsLetsGoDeeperHomeRoute = postsLetsGoDeeperHomeRouteImport.update({ +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const PostsLetsGoIndexRoute = PostsLetsGoIndexRouteImport.update({ + id: '/inception/', + path: '/inception/', + getParentRoute: () => PostsRoute, +} as any) +const PostsLetsGoDeeperHomeRoute = PostsLetsGoDeeperHomeRouteImport.update({ id: '/inception/deeper/', path: '/inception/deeper/', getParentRoute: () => PostsRoute, @@ -74,34 +72,34 @@ const postsLetsGoDeeperHomeRoute = postsLetsGoDeeperHomeRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren - '/posts/': typeof postsHomeRoute - '/posts/$postId': typeof postsDetailsRoute + '/posts/': typeof PostsHomeRoute + '/posts/$postId': typeof PostsDetailsRoute '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute - '/posts/inception': typeof postsLetsGoIndexRoute - '/posts/inception/deeper': typeof postsLetsGoDeeperHomeRoute + '/posts/inception/': typeof PostsLetsGoIndexRoute + '/posts/inception/deeper/': typeof PostsLetsGoDeeperHomeRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/posts': typeof postsHomeRoute - '/posts/$postId': typeof postsDetailsRoute + '/posts': typeof PostsHomeRoute + '/posts/$postId': typeof PostsDetailsRoute '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute - '/posts/inception': typeof postsLetsGoIndexRoute - '/posts/inception/deeper': typeof postsLetsGoDeeperHomeRoute + '/posts/inception': typeof PostsLetsGoIndexRoute + '/posts/inception/deeper': typeof PostsLetsGoDeeperHomeRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute '/_layout': typeof LayoutRouteWithChildren '/posts': typeof PostsRouteWithChildren - '/posts/': typeof postsHomeRoute + '/posts/': typeof PostsHomeRoute '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren - '/posts/$postId': typeof postsDetailsRoute + '/posts/$postId': typeof PostsDetailsRoute '/_layout/_layout-2/layout-a': typeof LayoutLayout2LayoutARoute '/_layout/_layout-2/layout-b': typeof LayoutLayout2LayoutBRoute - '/posts/inception/': typeof postsLetsGoIndexRoute - '/posts/inception/deeper/': typeof postsLetsGoDeeperHomeRoute + '/posts/inception/': typeof PostsLetsGoIndexRoute + '/posts/inception/deeper/': typeof PostsLetsGoDeeperHomeRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath @@ -112,8 +110,8 @@ export interface FileRouteTypes { | '/posts/$postId' | '/layout-a' | '/layout-b' - | '/posts/inception' - | '/posts/inception/deeper' + | '/posts/inception/' + | '/posts/inception/deeper/' fileRoutesByTo: FileRoutesByTo to: | '/' @@ -145,20 +143,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -166,17 +150,24 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof postsDetailsRouteImport - parentRoute: typeof PostsRoute + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } '/_layout/_layout-2': { id: '/_layout/_layout-2' path: '' - fullPath: '' + fullPath: '/' preLoaderRoute: typeof LayoutLayout2RouteImport parentRoute: typeof LayoutRoute } @@ -184,23 +175,16 @@ declare module '@tanstack/react-router' { id: '/posts/' path: '/' fullPath: '/posts/' - preLoaderRoute: typeof postsHomeRouteImport + preLoaderRoute: typeof PostsHomeRouteImport parentRoute: typeof PostsRoute } - '/posts/inception/': { - id: '/posts/inception/' - path: '/inception' - fullPath: '/posts/inception' - preLoaderRoute: typeof postsLetsGoIndexRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsDetailsRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } '/_layout/_layout-2/layout-a': { id: '/_layout/_layout-2/layout-a' path: '/layout-a' @@ -208,107 +192,30 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutLayout2LayoutARouteImport parentRoute: typeof LayoutLayout2Route } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/posts/inception/': { + id: '/posts/inception/' + path: '/inception' + fullPath: '/posts/inception/' + preLoaderRoute: typeof PostsLetsGoIndexRouteImport + parentRoute: typeof PostsRoute + } '/posts/inception/deeper/': { id: '/posts/inception/deeper/' path: '/inception/deeper' - fullPath: '/posts/inception/deeper' - preLoaderRoute: typeof postsLetsGoDeeperHomeRouteImport + fullPath: '/posts/inception/deeper/' + preLoaderRoute: typeof PostsLetsGoDeeperHomeRouteImport parentRoute: typeof PostsRoute } } } -declare module './routes/index' { - const createFileRoute: CreateFileRoute< - '/', - FileRoutesByPath['/']['parentRoute'], - FileRoutesByPath['/']['id'], - FileRoutesByPath['/']['path'], - FileRoutesByPath['/']['fullPath'] - > -} -declare module './routes/_layout' { - const createFileRoute: CreateFileRoute< - '/_layout', - FileRoutesByPath['/_layout']['parentRoute'], - FileRoutesByPath['/_layout']['id'], - FileRoutesByPath['/_layout']['path'], - FileRoutesByPath['/_layout']['fullPath'] - > -} -declare module './routes/posts' { - const createFileRoute: CreateFileRoute< - '/posts', - FileRoutesByPath['/posts']['parentRoute'], - FileRoutesByPath['/posts']['id'], - FileRoutesByPath['/posts']['path'], - FileRoutesByPath['/posts']['fullPath'] - > -} -declare module './routes/posts/home' { - const createFileRoute: CreateFileRoute< - '/posts/', - FileRoutesByPath['/posts/']['parentRoute'], - FileRoutesByPath['/posts/']['id'], - FileRoutesByPath['/posts/']['path'], - FileRoutesByPath['/posts/']['fullPath'] - > -} -declare module './routes/_layout/_layout-2' { - const createFileRoute: CreateFileRoute< - '/_layout/_layout-2', - FileRoutesByPath['/_layout/_layout-2']['parentRoute'], - FileRoutesByPath['/_layout/_layout-2']['id'], - FileRoutesByPath['/_layout/_layout-2']['path'], - FileRoutesByPath['/_layout/_layout-2']['fullPath'] - > -} -declare module './routes/posts/details' { - const createFileRoute: CreateFileRoute< - '/posts/$postId', - FileRoutesByPath['/posts/$postId']['parentRoute'], - FileRoutesByPath['/posts/$postId']['id'], - FileRoutesByPath['/posts/$postId']['path'], - FileRoutesByPath['/posts/$postId']['fullPath'] - > -} -declare module './routes/_layout/_layout-2/layout-a' { - const createFileRoute: CreateFileRoute< - '/_layout/_layout-2/layout-a', - FileRoutesByPath['/_layout/_layout-2/layout-a']['parentRoute'], - FileRoutesByPath['/_layout/_layout-2/layout-a']['id'], - FileRoutesByPath['/_layout/_layout-2/layout-a']['path'], - FileRoutesByPath['/_layout/_layout-2/layout-a']['fullPath'] - > -} -declare module './routes/_layout/_layout-2/layout-b' { - const createFileRoute: CreateFileRoute< - '/_layout/_layout-2/layout-b', - FileRoutesByPath['/_layout/_layout-2/layout-b']['parentRoute'], - FileRoutesByPath['/_layout/_layout-2/layout-b']['id'], - FileRoutesByPath['/_layout/_layout-2/layout-b']['path'], - FileRoutesByPath['/_layout/_layout-2/layout-b']['fullPath'] - > -} -declare module './routes/posts/lets-go/index' { - const createFileRoute: CreateFileRoute< - '/posts/inception/', - FileRoutesByPath['/posts/inception/']['parentRoute'], - FileRoutesByPath['/posts/inception/']['id'], - FileRoutesByPath['/posts/inception/']['path'], - FileRoutesByPath['/posts/inception/']['fullPath'] - > -} -declare module './routes/posts/lets-go/deeper/home' { - const createFileRoute: CreateFileRoute< - '/posts/inception/deeper/', - FileRoutesByPath['/posts/inception/deeper/']['parentRoute'], - FileRoutesByPath['/posts/inception/deeper/']['id'], - FileRoutesByPath['/posts/inception/deeper/']['path'], - FileRoutesByPath['/posts/inception/deeper/']['fullPath'] - > -} - interface LayoutLayout2RouteChildren { LayoutLayout2LayoutARoute: typeof LayoutLayout2LayoutARoute LayoutLayout2LayoutBRoute: typeof LayoutLayout2LayoutBRoute @@ -335,17 +242,17 @@ const LayoutRouteWithChildren = LayoutRoute._addFileChildren(LayoutRouteChildren) interface PostsRouteChildren { - postsHomeRoute: typeof postsHomeRoute - postsDetailsRoute: typeof postsDetailsRoute - postsLetsGoIndexRoute: typeof postsLetsGoIndexRoute - postsLetsGoDeeperHomeRoute: typeof postsLetsGoDeeperHomeRoute + PostsHomeRoute: typeof PostsHomeRoute + PostsDetailsRoute: typeof PostsDetailsRoute + PostsLetsGoIndexRoute: typeof PostsLetsGoIndexRoute + PostsLetsGoDeeperHomeRoute: typeof PostsLetsGoDeeperHomeRoute } const PostsRouteChildren: PostsRouteChildren = { - postsHomeRoute: postsHomeRoute, - postsDetailsRoute: postsDetailsRoute, - postsLetsGoIndexRoute: postsLetsGoIndexRoute, - postsLetsGoDeeperHomeRoute: postsLetsGoDeeperHomeRoute, + PostsHomeRoute: PostsHomeRoute, + PostsDetailsRoute: PostsDetailsRoute, + PostsLetsGoIndexRoute: PostsLetsGoIndexRoute, + PostsLetsGoDeeperHomeRoute: PostsLetsGoDeeperHomeRoute, } const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/_layout.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/_layout.tsx index 5c4a461d8d..02ddbb1cd9 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/_layout.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/_layout.tsx @@ -1,6 +1,6 @@ -import { Outlet } from '@tanstack/react-router' +import { Outlet, createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_layout')({ component: LayoutComponent, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2.tsx index 483b910862..3b7dbf2903 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet } from '@tanstack/react-router' +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_layout/_layout-2')({ component: LayoutComponent, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-a.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-a.tsx index a190b24202..ed2dea8800 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-a.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-a.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/_layout/_layout-2/layout-a')({ component: LayoutAComponent, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-b.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-b.tsx index 505f8f6fbf..4799d403e9 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-b.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-b.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/_layout/_layout-2/layout-b')({ component: LayoutBComponent, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/index.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/index.tsx index b23956ae17..0a5b7572ba 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/index.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/index.tsx @@ -1,6 +1,7 @@ +import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' -export const Route = createFileRoute({ +export const Route = createFileRoute('/')({ component: Home, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/posts.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/posts.tsx index 4469b2216a..c7a09ed7f8 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/posts.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/posts.tsx @@ -1,8 +1,8 @@ import * as React from 'react' -import { Link, Outlet } from '@tanstack/react-router' +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' import { fetchPosts } from '../posts' -export const Route = createFileRoute({ +export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/posts/details.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/posts/details.tsx index fc10978507..6479bdf803 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/posts/details.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/posts/details.tsx @@ -1,9 +1,9 @@ import * as React from 'react' -import { ErrorComponent } from '@tanstack/react-router' +import { ErrorComponent, createFileRoute } from '@tanstack/react-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/react-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent, notFoundComponent: () => { diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/posts/home.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/posts/home.tsx index fdbe5865e5..c6b65f1892 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/posts/home.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/posts/home.tsx @@ -1,6 +1,7 @@ +import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' -export const Route = createFileRoute({ +export const Route = createFileRoute('/posts/')({ component: PostsIndexComponent, }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/deeper/home.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/deeper/home.tsx index f8bc76644a..d2e95051f6 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/deeper/home.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/deeper/home.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/posts/inception/deeper/')({ component: () =>
    Hello /posts/inception/deeper/!
    , }) diff --git a/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/index.tsx b/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/index.tsx index 1c7ea68931..1a7358f044 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/index.tsx +++ b/examples/react/basic-virtual-inside-file-based/src/routes/posts/lets-go/index.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/posts/inception/')({ component: () =>
    Hello /posts/inception/!
    , }) diff --git a/examples/react/basic-virtual-inside-file-based/src/styles.css b/examples/react/basic-virtual-inside-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/basic-virtual-inside-file-based/src/styles.css +++ b/examples/react/basic-virtual-inside-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/basic-virtual-inside-file-based/src/vite-env.d.ts b/examples/react/basic-virtual-inside-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/basic-virtual-inside-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/basic-virtual-inside-file-based/vite.config.ts b/examples/react/basic-virtual-inside-file-based/vite.config.ts index 3524a957da..e6a8f48b5f 100644 --- a/examples/react/basic-virtual-inside-file-based/vite.config.ts +++ b/examples/react/basic-virtual-inside-file-based/vite.config.ts @@ -1,14 +1,15 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true, - verboseFileRoutes: false, }), react(), ], diff --git a/examples/react/basic/.devcontainer/devcontainer.json b/examples/react/basic/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/basic/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/basic/package.json b/examples/react/basic/package.json index bc1341dda0..2c09a3dfdf 100644 --- a/examples/react/basic/package.json +++ b/examples/react/basic/package.json @@ -9,20 +9,20 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/basic/postcss.config.mjs b/examples/react/basic/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/basic/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/basic/src/styles.css b/examples/react/basic/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/basic/src/styles.css +++ b/examples/react/basic/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/basic/src/vite-env.d.ts b/examples/react/basic/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/basic/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/basic/vite.config.js b/examples/react/basic/vite.config.js index 5a33944a9b..2764078e8b 100644 --- a/examples/react/basic/vite.config.js +++ b/examples/react/basic/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [tailwindcss(), react()], }) diff --git a/examples/react/deferred-data/.devcontainer/devcontainer.json b/examples/react/deferred-data/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/deferred-data/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/deferred-data/package.json b/examples/react/deferred-data/package.json index 3386f1464d..99afb661ee 100644 --- a/examples/react/deferred-data/package.json +++ b/examples/react/deferred-data/package.json @@ -9,21 +9,21 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/deferred-data/postcss.config.mjs b/examples/react/deferred-data/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/deferred-data/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/deferred-data/src/main.tsx b/examples/react/deferred-data/src/main.tsx index ae5ae0f3fb..0a37aa001d 100644 --- a/examples/react/deferred-data/src/main.tsx +++ b/examples/react/deferred-data/src/main.tsx @@ -75,7 +75,7 @@ function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) {
    diff --git a/examples/react/deferred-data/src/styles.css b/examples/react/deferred-data/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/deferred-data/src/styles.css +++ b/examples/react/deferred-data/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/deferred-data/src/vite-env.d.ts b/examples/react/deferred-data/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/deferred-data/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/deferred-data/vite.config.js b/examples/react/deferred-data/vite.config.js index 5a33944a9b..2764078e8b 100644 --- a/examples/react/deferred-data/vite.config.js +++ b/examples/react/deferred-data/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [tailwindcss(), react()], }) diff --git a/examples/react/i18n-paraglide/.devcontainer/devcontainer.json b/examples/react/i18n-paraglide/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/i18n-paraglide/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/i18n-paraglide/README.md b/examples/react/i18n-paraglide/README.md index 4dac51934f..98b25f6d0f 100644 --- a/examples/react/i18n-paraglide/README.md +++ b/examples/react/i18n-paraglide/README.md @@ -1,6 +1,6 @@ # TanStack Router - i18n with Paraglide Example -This example shows how to use Paraglide with TanStack Router. The source code can be found [in the Paraglide monorepo](https://github.com/opral/monorepo/tree/main/inlang/packages/paraglide/paraglide-js/examples/tanstack-router). +This example shows how to use Paraglide with TanStack Router. - [TanStack Router Docs](https://tanstack.com/router) - [Paraglide Documentation](https://inlang.com/m/gerre34r/library-inlang-paraglideJs) diff --git a/examples/react/i18n-paraglide/package.json b/examples/react/i18n-paraglide/package.json index c803d465a7..88140e8911 100644 --- a/examples/react/i18n-paraglide/package.json +++ b/examples/react/i18n-paraglide/package.json @@ -10,20 +10,32 @@ "test": "vitest run" }, "dependencies": { - "@tailwindcss/vite": "^4.1.17", - "@tanstack/react-router": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.1.1", "react-dom": "^19.1.1", - "tailwindcss": "^4.1.13" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/node": "^22.18.6", "@types/react": "^19.1.13", "@types/react-dom": "^19.1.9", - "@vitejs/plugin-react": "^5.0.3", - "typescript": "^5.9.2", - "vite": "^7.1.7", + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "@inlang/paraglide-js": "^2.4.0" + }, + "nx": { + "targets": { + "build": { + "outputs": [ + "...", + "{projectRoot}/src/paraglide", + "{projectRoot}/project.inlang/cache" + ] + } + } } } diff --git a/examples/react/i18n-paraglide/src/routeTree.gen.ts b/examples/react/i18n-paraglide/src/routeTree.gen.ts index 59499d9fbf..12bc916ae4 100644 --- a/examples/react/i18n-paraglide/src/routeTree.gen.ts +++ b/examples/react/i18n-paraglide/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/i18n-paraglide/src/styles.css b/examples/react/i18n-paraglide/src/styles.css index d4b5078586..23fa2415ca 100644 --- a/examples/react/i18n-paraglide/src/styles.css +++ b/examples/react/i18n-paraglide/src/styles.css @@ -1 +1 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); diff --git a/examples/react/i18n-paraglide/src/vite-env.d.ts b/examples/react/i18n-paraglide/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/i18n-paraglide/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/i18n-paraglide/tsconfig.json b/examples/react/i18n-paraglide/tsconfig.json index fded1fca18..c26f8f774e 100644 --- a/examples/react/i18n-paraglide/tsconfig.json +++ b/examples/react/i18n-paraglide/tsconfig.json @@ -21,7 +21,6 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, - "baseUrl": ".", "paths": { "@/*": ["./src/*"] } diff --git a/examples/react/kitchen-sink-file-based/.devcontainer/devcontainer.json b/examples/react/kitchen-sink-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/kitchen-sink-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/kitchen-sink-file-based/package.json b/examples/react/kitchen-sink-file-based/package.json index a5495c70fb..e02defb3ce 100644 --- a/examples/react/kitchen-sink-file-based/package.json +++ b/examples/react/kitchen-sink-file-based/package.json @@ -9,23 +9,23 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "immer": "^10.1.1", - "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/kitchen-sink-file-based/postcss.config.mjs b/examples/react/kitchen-sink-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/kitchen-sink-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/kitchen-sink-file-based/src/components/Spinner.tsx b/examples/react/kitchen-sink-file-based/src/components/Spinner.tsx index 101c31d35f..6b89facdf0 100644 --- a/examples/react/kitchen-sink-file-based/src/components/Spinner.tsx +++ b/examples/react/kitchen-sink-file-based/src/components/Spinner.tsx @@ -11,7 +11,7 @@ export function Spinner({
    diff --git a/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts b/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts index f3accfa48e..03af4e1e58 100644 --- a/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts +++ b/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts @@ -8,132 +8,224 @@ // 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 Routes - -import { Route as rootRoute } from './routes/__root' -import { Route as LoginRouteImport } from './routes/login' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as AuthRouteImport } from './routes/_auth' -import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' -import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' -import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' -import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' -import { Route as AuthProfileRouteImport } from './routes/_auth.profile' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +import { Route as LoginRouteImport } from './routes/login' import { Route as thisFolderIsNotInTheUrlRouteGroupRouteImport } from './routes/(this-folder-is-not-in-the-url)/route-group' -import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as AuthProfileRouteImport } from './routes/_auth.profile' +import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' +import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' -import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' import { Route as DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' - -// Create/Update Routes - -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => rootRoute, -} as any) - -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRoute, -} as any) - -const AuthRoute = AuthRouteImport.update({ - id: '/_auth', - getParentRoute: () => rootRoute, -} as any) - -const DashboardRouteRoute = DashboardRouteRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => rootRoute, -} as any) +import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => rootRoute, + getParentRoute: () => rootRouteImport, } as any) - -const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ - id: '/expensive/', - path: '/expensive/', - getParentRoute: () => rootRoute, +const AuthRoute = AuthRouteImport.update({ + id: '/_auth', + getParentRoute: () => rootRouteImport, } as any) - -const DashboardIndexRoute = DashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardRouteRoute, +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, } as any) - -const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutRoute, +const DashboardRouteRoute = DashboardRouteRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => rootRouteImport, } as any) - -const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutRoute, +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, } as any) - +const thisFolderIsNotInTheUrlRouteGroupRoute = + thisFolderIsNotInTheUrlRouteGroupRouteImport.update({ + id: '/(this-folder-is-not-in-the-url)/route-group', + path: '/route-group', + getParentRoute: () => rootRouteImport, + } as any) const AuthProfileRoute = AuthProfileRouteImport.update({ id: '/profile', path: '/profile', getParentRoute: () => AuthRoute, } as any) - -const thisFolderIsNotInTheUrlRouteGroupRoute = - thisFolderIsNotInTheUrlRouteGroupRouteImport.update({ - id: '/(this-folder-is-not-in-the-url)/route-group', - path: '/route-group', - getParentRoute: () => rootRoute, - } as any) - -const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ - id: '/users', - path: '/users', +const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const DashboardIndexRoute = DashboardIndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => DashboardRouteRoute, } as any) - const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ id: '/invoices', path: '/invoices', getParentRoute: () => DashboardRouteRoute, } as any) - -const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardUsersRouteRoute, +const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => DashboardRouteRoute, +} as any) +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRouteImport, } as any) - const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) - -const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ - id: '/user', - path: '/user', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) - const DashboardInvoicesInvoiceIdRoute = DashboardInvoicesInvoiceIdRouteImport.update({ id: '/$invoiceId', path: '/$invoiceId', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) +const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) +const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ + id: '/user', + path: '/user', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) -// Populate the FileRoutesByPath interface +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/dashboard': typeof DashboardRouteRouteWithChildren + '/login': typeof LoginRoute + '/dashboard/invoices': typeof DashboardInvoicesRouteRouteWithChildren + '/dashboard/users': typeof DashboardUsersRouteRouteWithChildren + '/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute + '/profile': typeof AuthProfileRoute + '/route-a': typeof PathlessLayoutRouteARoute + '/route-b': typeof PathlessLayoutRouteBRoute + '/dashboard/': typeof DashboardIndexRoute + '/expensive/': typeof ExpensiveIndexRoute + '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute + '/dashboard/users/user': typeof DashboardUsersUserRoute + '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute + '/dashboard/users/': typeof DashboardUsersIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/login': typeof LoginRoute + '/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute + '/profile': typeof AuthProfileRoute + '/route-a': typeof PathlessLayoutRouteARoute + '/route-b': typeof PathlessLayoutRouteBRoute + '/dashboard': typeof DashboardIndexRoute + '/expensive': typeof ExpensiveIndexRoute + '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute + '/dashboard/users/user': typeof DashboardUsersUserRoute + '/dashboard/invoices': typeof DashboardInvoicesIndexRoute + '/dashboard/users': typeof DashboardUsersIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/dashboard': typeof DashboardRouteRouteWithChildren + '/_auth': typeof AuthRouteWithChildren + '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren + '/login': typeof LoginRoute + '/dashboard/invoices': typeof DashboardInvoicesRouteRouteWithChildren + '/dashboard/users': typeof DashboardUsersRouteRouteWithChildren + '/(this-folder-is-not-in-the-url)/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute + '/_auth/profile': typeof AuthProfileRoute + '/_pathlessLayout/route-a': typeof PathlessLayoutRouteARoute + '/_pathlessLayout/route-b': typeof PathlessLayoutRouteBRoute + '/dashboard/': typeof DashboardIndexRoute + '/expensive/': typeof ExpensiveIndexRoute + '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute + '/dashboard/users/user': typeof DashboardUsersUserRoute + '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute + '/dashboard/users/': typeof DashboardUsersIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/dashboard' + | '/login' + | '/dashboard/invoices' + | '/dashboard/users' + | '/route-group' + | '/profile' + | '/route-a' + | '/route-b' + | '/dashboard/' + | '/expensive/' + | '/dashboard/invoices/$invoiceId' + | '/dashboard/users/user' + | '/dashboard/invoices/' + | '/dashboard/users/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/login' + | '/route-group' + | '/profile' + | '/route-a' + | '/route-b' + | '/dashboard' + | '/expensive' + | '/dashboard/invoices/$invoiceId' + | '/dashboard/users/user' + | '/dashboard/invoices' + | '/dashboard/users' + id: + | '__root__' + | '/' + | '/dashboard' + | '/_auth' + | '/_pathlessLayout' + | '/login' + | '/dashboard/invoices' + | '/dashboard/users' + | '/(this-folder-is-not-in-the-url)/route-group' + | '/_auth/profile' + | '/_pathlessLayout/route-a' + | '/_pathlessLayout/route-b' + | '/dashboard/' + | '/expensive/' + | '/dashboard/invoices/$invoiceId' + | '/dashboard/users/user' + | '/dashboard/invoices/' + | '/dashboard/users/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DashboardRouteRoute: typeof DashboardRouteRouteWithChildren + AuthRoute: typeof AuthRouteWithChildren + PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren + LoginRoute: typeof LoginRoute + thisFolderIsNotInTheUrlRouteGroupRoute: typeof thisFolderIsNotInTheUrlRouteGroupRoute + ExpensiveIndexRoute: typeof ExpensiveIndexRoute +} declare module '@tanstack/react-router' { interface FileRoutesByPath { @@ -142,125 +234,123 @@ declare module '@tanstack/react-router' { path: '/' fullPath: '/' preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRoute + parentRoute: typeof rootRouteImport + } + '/_auth': { + id: '/_auth' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport } '/dashboard': { id: '/dashboard' path: '/dashboard' fullPath: '/dashboard' preLoaderRoute: typeof DashboardRouteRouteImport - parentRoute: typeof rootRoute - } - '/_auth': { - id: '/_auth' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthRouteImport - parentRoute: typeof rootRoute - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRoute + parentRoute: typeof rootRouteImport } '/login': { id: '/login' path: '/login' fullPath: '/login' preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRoute - } - '/dashboard/invoices': { - id: '/dashboard/invoices' - path: '/invoices' - fullPath: '/dashboard/invoices' - preLoaderRoute: typeof DashboardInvoicesRouteRouteImport - parentRoute: typeof DashboardRouteRouteImport - } - '/dashboard/users': { - id: '/dashboard/users' - path: '/users' - fullPath: '/dashboard/users' - preLoaderRoute: typeof DashboardUsersRouteRouteImport - parentRoute: typeof DashboardRouteRouteImport + parentRoute: typeof rootRouteImport } '/(this-folder-is-not-in-the-url)/route-group': { id: '/(this-folder-is-not-in-the-url)/route-group' path: '/route-group' fullPath: '/route-group' preLoaderRoute: typeof thisFolderIsNotInTheUrlRouteGroupRouteImport - parentRoute: typeof rootRoute + parentRoute: typeof rootRouteImport } '/_auth/profile': { id: '/_auth/profile' path: '/profile' fullPath: '/profile' preLoaderRoute: typeof AuthProfileRouteImport - parentRoute: typeof AuthRouteImport + parentRoute: typeof AuthRoute } '/_pathlessLayout/route-a': { id: '/_pathlessLayout/route-a' path: '/route-a' fullPath: '/route-a' preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/_pathlessLayout/route-b': { id: '/_pathlessLayout/route-b' path: '/route-b' fullPath: '/route-b' preLoaderRoute: typeof PathlessLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/dashboard/': { id: '/dashboard/' path: '/' fullPath: '/dashboard/' preLoaderRoute: typeof DashboardIndexRouteImport - parentRoute: typeof DashboardRouteRouteImport + parentRoute: typeof DashboardRouteRoute + } + '/dashboard/invoices': { + id: '/dashboard/invoices' + path: '/invoices' + fullPath: '/dashboard/invoices' + preLoaderRoute: typeof DashboardInvoicesRouteRouteImport + parentRoute: typeof DashboardRouteRoute + } + '/dashboard/users': { + id: '/dashboard/users' + path: '/users' + fullPath: '/dashboard/users' + preLoaderRoute: typeof DashboardUsersRouteRouteImport + parentRoute: typeof DashboardRouteRoute } '/expensive/': { id: '/expensive/' path: '/expensive' - fullPath: '/expensive' + fullPath: '/expensive/' preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRoute - } - '/dashboard/invoices/$invoiceId': { - id: '/dashboard/invoices/$invoiceId' - path: '/$invoiceId' - fullPath: '/dashboard/invoices/$invoiceId' - preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport - parentRoute: typeof DashboardInvoicesRouteRouteImport - } - '/dashboard/users/user': { - id: '/dashboard/users/user' - path: '/user' - fullPath: '/dashboard/users/user' - preLoaderRoute: typeof DashboardUsersUserRouteImport - parentRoute: typeof DashboardUsersRouteRouteImport + parentRoute: typeof rootRouteImport } '/dashboard/invoices/': { id: '/dashboard/invoices/' path: '/' fullPath: '/dashboard/invoices/' preLoaderRoute: typeof DashboardInvoicesIndexRouteImport - parentRoute: typeof DashboardInvoicesRouteRouteImport + parentRoute: typeof DashboardInvoicesRouteRoute + } + '/dashboard/invoices/$invoiceId': { + id: '/dashboard/invoices/$invoiceId' + path: '/$invoiceId' + fullPath: '/dashboard/invoices/$invoiceId' + preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport + parentRoute: typeof DashboardInvoicesRouteRoute } '/dashboard/users/': { id: '/dashboard/users/' path: '/' fullPath: '/dashboard/users/' preLoaderRoute: typeof DashboardUsersIndexRouteImport - parentRoute: typeof DashboardUsersRouteRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } + '/dashboard/users/user': { + id: '/dashboard/users/user' + path: '/user' + fullPath: '/dashboard/users/user' + preLoaderRoute: typeof DashboardUsersUserRouteImport + parentRoute: typeof DashboardUsersRouteRoute } } } -// Create and export the route tree - interface DashboardInvoicesRouteRouteChildren { DashboardInvoicesInvoiceIdRoute: typeof DashboardInvoicesInvoiceIdRoute DashboardInvoicesIndexRoute: typeof DashboardInvoicesIndexRoute @@ -330,128 +420,6 @@ const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( PathlessLayoutRouteChildren, ) -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/dashboard': typeof DashboardRouteRouteWithChildren - '': typeof PathlessLayoutRouteWithChildren - '/login': typeof LoginRoute - '/dashboard/invoices': typeof DashboardInvoicesRouteRouteWithChildren - '/dashboard/users': typeof DashboardUsersRouteRouteWithChildren - '/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute - '/profile': typeof AuthProfileRoute - '/route-a': typeof PathlessLayoutRouteARoute - '/route-b': typeof PathlessLayoutRouteBRoute - '/dashboard/': typeof DashboardIndexRoute - '/expensive': typeof ExpensiveIndexRoute - '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute - '/dashboard/users/user': typeof DashboardUsersUserRoute - '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute - '/dashboard/users/': typeof DashboardUsersIndexRoute -} - -export interface FileRoutesByTo { - '/': typeof IndexRoute - '': typeof PathlessLayoutRouteWithChildren - '/login': typeof LoginRoute - '/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute - '/profile': typeof AuthProfileRoute - '/route-a': typeof PathlessLayoutRouteARoute - '/route-b': typeof PathlessLayoutRouteBRoute - '/dashboard': typeof DashboardIndexRoute - '/expensive': typeof ExpensiveIndexRoute - '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute - '/dashboard/users/user': typeof DashboardUsersUserRoute - '/dashboard/invoices': typeof DashboardInvoicesIndexRoute - '/dashboard/users': typeof DashboardUsersIndexRoute -} - -export interface FileRoutesById { - __root__: typeof rootRoute - '/': typeof IndexRoute - '/dashboard': typeof DashboardRouteRouteWithChildren - '/_auth': typeof AuthRouteWithChildren - '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren - '/login': typeof LoginRoute - '/dashboard/invoices': typeof DashboardInvoicesRouteRouteWithChildren - '/dashboard/users': typeof DashboardUsersRouteRouteWithChildren - '/(this-folder-is-not-in-the-url)/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute - '/_auth/profile': typeof AuthProfileRoute - '/_pathlessLayout/route-a': typeof PathlessLayoutRouteARoute - '/_pathlessLayout/route-b': typeof PathlessLayoutRouteBRoute - '/dashboard/': typeof DashboardIndexRoute - '/expensive/': typeof ExpensiveIndexRoute - '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute - '/dashboard/users/user': typeof DashboardUsersUserRoute - '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute - '/dashboard/users/': typeof DashboardUsersIndexRoute -} - -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/dashboard' - | '' - | '/login' - | '/dashboard/invoices' - | '/dashboard/users' - | '/route-group' - | '/profile' - | '/route-a' - | '/route-b' - | '/dashboard/' - | '/expensive' - | '/dashboard/invoices/$invoiceId' - | '/dashboard/users/user' - | '/dashboard/invoices/' - | '/dashboard/users/' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '' - | '/login' - | '/route-group' - | '/profile' - | '/route-a' - | '/route-b' - | '/dashboard' - | '/expensive' - | '/dashboard/invoices/$invoiceId' - | '/dashboard/users/user' - | '/dashboard/invoices' - | '/dashboard/users' - id: - | '__root__' - | '/' - | '/dashboard' - | '/_auth' - | '/_pathlessLayout' - | '/login' - | '/dashboard/invoices' - | '/dashboard/users' - | '/(this-folder-is-not-in-the-url)/route-group' - | '/_auth/profile' - | '/_pathlessLayout/route-a' - | '/_pathlessLayout/route-b' - | '/dashboard/' - | '/expensive/' - | '/dashboard/invoices/$invoiceId' - | '/dashboard/users/user' - | '/dashboard/invoices/' - | '/dashboard/users/' - fileRoutesById: FileRoutesById -} - -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - DashboardRouteRoute: typeof DashboardRouteRouteWithChildren - AuthRoute: typeof AuthRouteWithChildren - PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren - LoginRoute: typeof LoginRoute - thisFolderIsNotInTheUrlRouteGroupRoute: typeof thisFolderIsNotInTheUrlRouteGroupRoute - ExpensiveIndexRoute: typeof ExpensiveIndexRoute -} - const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, DashboardRouteRoute: DashboardRouteRouteWithChildren, @@ -462,107 +430,6 @@ const rootRouteChildren: RootRouteChildren = { thisFolderIsNotInTheUrlRouteGroupRoute, ExpensiveIndexRoute: ExpensiveIndexRoute, } - -export const routeTree = rootRoute +export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) ._addFileTypes() - -/* ROUTE_MANIFEST_START -{ - "routes": { - "__root__": { - "filePath": "__root.tsx", - "children": [ - "/", - "/dashboard", - "/_auth", - "/_pathlessLayout", - "/login", - "/(this-folder-is-not-in-the-url)/route-group", - "/expensive/" - ] - }, - "/": { - "filePath": "index.tsx" - }, - "/dashboard": { - "filePath": "dashboard.route.tsx", - "children": [ - "/dashboard/invoices", - "/dashboard/users", - "/dashboard/" - ] - }, - "/_auth": { - "filePath": "_auth.tsx", - "children": [ - "/_auth/profile" - ] - }, - "/_pathlessLayout": { - "filePath": "_pathlessLayout.tsx", - "children": [ - "/_pathlessLayout/route-a", - "/_pathlessLayout/route-b" - ] - }, - "/login": { - "filePath": "login.tsx" - }, - "/dashboard/invoices": { - "filePath": "dashboard.invoices.route.tsx", - "parent": "/dashboard", - "children": [ - "/dashboard/invoices/$invoiceId", - "/dashboard/invoices/" - ] - }, - "/dashboard/users": { - "filePath": "dashboard.users.route.tsx", - "parent": "/dashboard", - "children": [ - "/dashboard/users/user", - "/dashboard/users/" - ] - }, - "/(this-folder-is-not-in-the-url)/route-group": { - "filePath": "(this-folder-is-not-in-the-url)/route-group.tsx" - }, - "/_auth/profile": { - "filePath": "_auth.profile.tsx", - "parent": "/_auth" - }, - "/_pathlessLayout/route-a": { - "filePath": "_pathlessLayout.route-a.tsx", - "parent": "/_pathlessLayout" - }, - "/_pathlessLayout/route-b": { - "filePath": "_pathlessLayout.route-b.tsx", - "parent": "/_pathlessLayout" - }, - "/dashboard/": { - "filePath": "dashboard.index.tsx", - "parent": "/dashboard" - }, - "/expensive/": { - "filePath": "expensive/index.tsx" - }, - "/dashboard/invoices/$invoiceId": { - "filePath": "dashboard.invoices.$invoiceId.tsx", - "parent": "/dashboard/invoices" - }, - "/dashboard/users/user": { - "filePath": "dashboard.users.user.tsx", - "parent": "/dashboard/users" - }, - "/dashboard/invoices/": { - "filePath": "dashboard.invoices.index.tsx", - "parent": "/dashboard/invoices" - }, - "/dashboard/users/": { - "filePath": "dashboard.users.index.tsx", - "parent": "/dashboard/users" - } - } -} -ROUTE_MANIFEST_END */ diff --git a/examples/react/kitchen-sink-file-based/src/styles.css b/examples/react/kitchen-sink-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/kitchen-sink-file-based/src/styles.css +++ b/examples/react/kitchen-sink-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/kitchen-sink-file-based/src/vite-env.d.ts b/examples/react/kitchen-sink-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/kitchen-sink-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/kitchen-sink-file-based/vite.config.js b/examples/react/kitchen-sink-file-based/vite.config.js index ab615485ae..ce5fc59483 100644 --- a/examples/react/kitchen-sink-file-based/vite.config.js +++ b/examples/react/kitchen-sink-file-based/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true }), react(), ], diff --git a/examples/react/kitchen-sink-react-query-file-based/.devcontainer/devcontainer.json b/examples/react/kitchen-sink-react-query-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/kitchen-sink-react-query-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} 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 01d0d42c72..e3dd032ac2 100644 --- a/examples/react/kitchen-sink-react-query-file-based/package.json +++ b/examples/react/kitchen-sink-react-query-file-based/package.json @@ -9,25 +9,25 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-query": "^5.90.0", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "immer": "^10.1.1", - "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/kitchen-sink-react-query-file-based/postcss.config.mjs b/examples/react/kitchen-sink-react-query-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/kitchen-sink-react-query-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/kitchen-sink-react-query-file-based/src/components/Spinner.tsx b/examples/react/kitchen-sink-react-query-file-based/src/components/Spinner.tsx index 101c31d35f..6b89facdf0 100644 --- a/examples/react/kitchen-sink-react-query-file-based/src/components/Spinner.tsx +++ b/examples/react/kitchen-sink-react-query-file-based/src/components/Spinner.tsx @@ -11,7 +11,7 @@ export function Spinner({
    diff --git a/examples/react/kitchen-sink-react-query-file-based/src/routeTree.gen.ts b/examples/react/kitchen-sink-react-query-file-based/src/routeTree.gen.ts index c18ab6eb46..dbce8cf604 100644 --- a/examples/react/kitchen-sink-react-query-file-based/src/routeTree.gen.ts +++ b/examples/react/kitchen-sink-react-query-file-based/src/routeTree.gen.ts @@ -9,80 +9,65 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as LoginRouteImport } from './routes/login' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as AuthRouteImport } from './routes/_auth' -import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' import { Route as IndexRouteImport } from './routes/index' -import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' -import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' -import { Route as FooBarRouteImport } from './routes/foo/bar' -import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' -import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +import { Route as LoginRouteImport } from './routes/login' import { Route as AuthProfileRouteImport } from './routes/_auth.profile' -import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' +import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' -import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' +import { Route as FooBarRouteImport } from './routes/foo/bar' import { Route as DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' +import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, +} as any) const DashboardRouteRoute = DashboardRouteRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ - id: '/expensive/', - path: '/expensive/', - getParentRoute: () => rootRouteImport, -} as any) -const DashboardIndexRoute = DashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardRouteRoute, -} as any) -const FooBarRoute = FooBarRouteImport.update({ - id: '/foo/bar', - path: '/foo/bar', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutRoute, -} as any) -const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutRoute, -} as any) const AuthProfileRoute = AuthProfileRouteImport.update({ id: '/profile', path: '/profile', getParentRoute: () => AuthRoute, } as any) -const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ - id: '/users', - path: '/users', +const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const DashboardIndexRoute = DashboardIndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => DashboardRouteRoute, } as any) const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ @@ -90,27 +75,42 @@ const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ path: '/invoices', getParentRoute: () => DashboardRouteRoute, } as any) -const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardUsersRouteRoute, +const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => DashboardRouteRoute, +} as any) +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRouteImport, +} as any) +const FooBarRoute = FooBarRouteImport.update({ + id: '/foo/bar', + path: '/foo/bar', + getParentRoute: () => rootRouteImport, } as any) const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) -const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ - id: '/user', - path: '/user', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) const DashboardInvoicesInvoiceIdRoute = DashboardInvoicesInvoiceIdRouteImport.update({ id: '/$invoiceId', path: '/$invoiceId', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) +const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) +const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ + id: '/user', + path: '/user', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -123,7 +123,7 @@ export interface FileRoutesByFullPath { '/route-b': typeof PathlessLayoutRouteBRoute '/foo/bar': typeof FooBarRoute '/dashboard/': typeof DashboardIndexRoute - '/expensive': typeof ExpensiveIndexRoute + '/expensive/': typeof ExpensiveIndexRoute '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute '/dashboard/users/user': typeof DashboardUsersUserRoute '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute @@ -176,7 +176,7 @@ export interface FileRouteTypes { | '/route-b' | '/foo/bar' | '/dashboard/' - | '/expensive' + | '/expensive/' | '/dashboard/invoices/$invoiceId' | '/dashboard/users/user' | '/dashboard/invoices/' @@ -228,27 +228,27 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_auth': { id: '/_auth' path: '' - fullPath: '' + fullPath: '/' preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -256,48 +256,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/expensive/': { - id: '/expensive/' - path: '/expensive' - fullPath: '/expensive' - preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/dashboard/': { - id: '/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof DashboardIndexRouteImport - parentRoute: typeof DashboardRouteRoute - } - '/foo/bar': { - id: '/foo/bar' - path: '/foo/bar' - fullPath: '/foo/bar' - preLoaderRoute: typeof FooBarRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/route-b': { - id: '/_pathlessLayout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/_pathlessLayout/route-a': { - id: '/_pathlessLayout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRoute - } '/_auth/profile': { id: '/_auth/profile' path: '/profile' @@ -305,11 +270,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthProfileRouteImport parentRoute: typeof AuthRoute } - '/dashboard/users': { - id: '/dashboard/users' - path: '/users' - fullPath: '/dashboard/users' - preLoaderRoute: typeof DashboardUsersRouteRouteImport + '/_pathlessLayout/route-a': { + id: '/_pathlessLayout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/_pathlessLayout/route-b': { + id: '/_pathlessLayout/route-b' + path: '/route-b' + fullPath: '/route-b' + preLoaderRoute: typeof PathlessLayoutRouteBRouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/dashboard/': { + id: '/dashboard/' + path: '/' + fullPath: '/dashboard/' + preLoaderRoute: typeof DashboardIndexRouteImport parentRoute: typeof DashboardRouteRoute } '/dashboard/invoices': { @@ -319,12 +298,26 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardInvoicesRouteRouteImport parentRoute: typeof DashboardRouteRoute } - '/dashboard/users/': { - id: '/dashboard/users/' - path: '/' - fullPath: '/dashboard/users/' - preLoaderRoute: typeof DashboardUsersIndexRouteImport - parentRoute: typeof DashboardUsersRouteRoute + '/dashboard/users': { + id: '/dashboard/users' + path: '/users' + fullPath: '/dashboard/users' + preLoaderRoute: typeof DashboardUsersRouteRouteImport + parentRoute: typeof DashboardRouteRoute + } + '/expensive/': { + id: '/expensive/' + path: '/expensive' + fullPath: '/expensive/' + preLoaderRoute: typeof ExpensiveIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/foo/bar': { + id: '/foo/bar' + path: '/foo/bar' + fullPath: '/foo/bar' + preLoaderRoute: typeof FooBarRouteImport + parentRoute: typeof rootRouteImport } '/dashboard/invoices/': { id: '/dashboard/invoices/' @@ -333,13 +326,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardInvoicesIndexRouteImport parentRoute: typeof DashboardInvoicesRouteRoute } - '/dashboard/users/user': { - id: '/dashboard/users/user' - path: '/user' - fullPath: '/dashboard/users/user' - preLoaderRoute: typeof DashboardUsersUserRouteImport - parentRoute: typeof DashboardUsersRouteRoute - } '/dashboard/invoices/$invoiceId': { id: '/dashboard/invoices/$invoiceId' path: '/$invoiceId' @@ -347,6 +333,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport parentRoute: typeof DashboardInvoicesRouteRoute } + '/dashboard/users/': { + id: '/dashboard/users/' + path: '/' + fullPath: '/dashboard/users/' + preLoaderRoute: typeof DashboardUsersIndexRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } + '/dashboard/users/user': { + id: '/dashboard/users/user' + path: '/user' + fullPath: '/dashboard/users/user' + preLoaderRoute: typeof DashboardUsersUserRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } } } diff --git a/examples/react/kitchen-sink-react-query-file-based/src/styles.css b/examples/react/kitchen-sink-react-query-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/kitchen-sink-react-query-file-based/src/styles.css +++ b/examples/react/kitchen-sink-react-query-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/kitchen-sink-react-query-file-based/src/vite-env.d.ts b/examples/react/kitchen-sink-react-query-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/kitchen-sink-react-query-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/kitchen-sink-react-query-file-based/vite.config.js b/examples/react/kitchen-sink-react-query-file-based/vite.config.js index ab615485ae..ce5fc59483 100644 --- a/examples/react/kitchen-sink-react-query-file-based/vite.config.js +++ b/examples/react/kitchen-sink-react-query-file-based/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true }), react(), ], diff --git a/examples/react/kitchen-sink-react-query/.devcontainer/devcontainer.json b/examples/react/kitchen-sink-react-query/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/kitchen-sink-react-query/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/kitchen-sink-react-query/package.json b/examples/react/kitchen-sink-react-query/package.json index 4b5f11a034..14d0dc8e86 100644 --- a/examples/react/kitchen-sink-react-query/package.json +++ b/examples/react/kitchen-sink-react-query/package.json @@ -9,24 +9,24 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-query": "^5.90.0", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "immer": "^10.1.1", - "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/kitchen-sink-react-query/postcss.config.mjs b/examples/react/kitchen-sink-react-query/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/kitchen-sink-react-query/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/kitchen-sink-react-query/src/main.tsx b/examples/react/kitchen-sink-react-query/src/main.tsx index be34b9607a..93f885aaca 100644 --- a/examples/react/kitchen-sink-react-query/src/main.tsx +++ b/examples/react/kitchen-sink-react-query/src/main.tsx @@ -1090,7 +1090,7 @@ function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) {
    diff --git a/examples/react/kitchen-sink-react-query/src/styles.css b/examples/react/kitchen-sink-react-query/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/kitchen-sink-react-query/src/styles.css +++ b/examples/react/kitchen-sink-react-query/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/kitchen-sink-react-query/src/vite-env.d.ts b/examples/react/kitchen-sink-react-query/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/kitchen-sink-react-query/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/kitchen-sink-react-query/vite.config.js b/examples/react/kitchen-sink-react-query/vite.config.js index 5a33944a9b..2764078e8b 100644 --- a/examples/react/kitchen-sink-react-query/vite.config.js +++ b/examples/react/kitchen-sink-react-query/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [tailwindcss(), react()], }) diff --git a/examples/react/kitchen-sink/.devcontainer/devcontainer.json b/examples/react/kitchen-sink/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/kitchen-sink/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/kitchen-sink/package.json b/examples/react/kitchen-sink/package.json index 21618cdae2..f738efc37e 100644 --- a/examples/react/kitchen-sink/package.json +++ b/examples/react/kitchen-sink/package.json @@ -9,22 +9,22 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "immer": "^10.1.1", - "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/kitchen-sink/postcss.config.mjs b/examples/react/kitchen-sink/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/kitchen-sink/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/kitchen-sink/src/main.tsx b/examples/react/kitchen-sink/src/main.tsx index ce7687c666..1f6a355302 100644 --- a/examples/react/kitchen-sink/src/main.tsx +++ b/examples/react/kitchen-sink/src/main.tsx @@ -1048,7 +1048,7 @@ function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) {
    diff --git a/examples/react/kitchen-sink/src/styles.css b/examples/react/kitchen-sink/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/kitchen-sink/src/styles.css +++ b/examples/react/kitchen-sink/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/kitchen-sink/src/vite-env.d.ts b/examples/react/kitchen-sink/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/kitchen-sink/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/kitchen-sink/vite.config.js b/examples/react/kitchen-sink/vite.config.js index 5a33944a9b..2764078e8b 100644 --- a/examples/react/kitchen-sink/vite.config.js +++ b/examples/react/kitchen-sink/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [tailwindcss(), react()], }) diff --git a/examples/react/large-file-based/.devcontainer/devcontainer.json b/examples/react/large-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/large-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/large-file-based/package.json b/examples/react/large-file-based/package.json index 15e8243520..23d469d120 100644 --- a/examples/react/large-file-based/package.json +++ b/examples/react/large-file-based/package.json @@ -11,23 +11,23 @@ "test:types": "tsc --extendedDiagnostics" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "postcss": "^8.5.1", + "@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", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/large-file-based/postcss.config.mjs b/examples/react/large-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/large-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/large-file-based/src/routeTree.gen.ts b/examples/react/large-file-based/src/routeTree.gen.ts index 93a5be975c..8494f51d73 100644 --- a/examples/react/large-file-based/src/routeTree.gen.ts +++ b/examples/react/large-file-based/src/routeTree.gen.ts @@ -9,23 +9,18 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as RelativeRouteImport } from './routes/relative' -import { Route as LinkPropsRouteImport } from './routes/linkProps' -import { Route as AbsoluteRouteImport } from './routes/absolute' -import { Route as SearchRouteRouteImport } from './routes/search/route' -import { Route as ParamsRouteRouteImport } from './routes/params/route' import { Route as IndexRouteImport } from './routes/index' -import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' +import { Route as AbsoluteRouteImport } from './routes/absolute' +import { Route as LinkPropsRouteImport } from './routes/linkProps' +import { Route as ParamsRouteRouteImport } from './routes/params/route' +import { Route as RelativeRouteImport } from './routes/relative' +import { Route as SearchRouteRouteImport } from './routes/search/route' import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' +import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' -const RelativeRoute = RelativeRouteImport.update({ - id: '/relative', - path: '/relative', - getParentRoute: () => rootRouteImport, -} as any) -const LinkPropsRoute = LinkPropsRouteImport.update({ - id: '/linkProps', - path: '/linkProps', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AbsoluteRoute = AbsoluteRouteImport.update({ @@ -33,9 +28,9 @@ const AbsoluteRoute = AbsoluteRouteImport.update({ path: '/absolute', getParentRoute: () => rootRouteImport, } as any) -const SearchRouteRoute = SearchRouteRouteImport.update({ - id: '/search', - path: '/search', +const LinkPropsRoute = LinkPropsRouteImport.update({ + id: '/linkProps', + path: '/linkProps', getParentRoute: () => rootRouteImport, } as any) const ParamsRouteRoute = ParamsRouteRouteImport.update({ @@ -43,21 +38,26 @@ const ParamsRouteRoute = ParamsRouteRouteImport.update({ path: '/params', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RelativeRoute = RelativeRouteImport.update({ + id: '/relative', + path: '/relative', getParentRoute: () => rootRouteImport, } as any) -const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ - id: '/searchPlaceholder', - path: '/searchPlaceholder', - getParentRoute: () => SearchRouteRoute, +const SearchRouteRoute = SearchRouteRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, } as any) const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ id: '/$paramsPlaceholder', path: '/$paramsPlaceholder', getParentRoute: () => ParamsRouteRoute, } as any) +const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ + id: '/searchPlaceholder', + path: '/searchPlaceholder', + getParentRoute: () => SearchRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -134,18 +134,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/relative': { - id: '/relative' - path: '/relative' - fullPath: '/relative' - preLoaderRoute: typeof RelativeRouteImport - parentRoute: typeof rootRouteImport - } - '/linkProps': { - id: '/linkProps' - path: '/linkProps' - fullPath: '/linkProps' - preLoaderRoute: typeof LinkPropsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/absolute': { @@ -155,11 +148,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AbsoluteRouteImport parentRoute: typeof rootRouteImport } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteRouteImport + '/linkProps': { + id: '/linkProps' + path: '/linkProps' + fullPath: '/linkProps' + preLoaderRoute: typeof LinkPropsRouteImport parentRoute: typeof rootRouteImport } '/params': { @@ -169,19 +162,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ParamsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/relative': { + id: '/relative' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeRouteImport parentRoute: typeof rootRouteImport } - '/search/searchPlaceholder': { - id: '/search/searchPlaceholder' - path: '/searchPlaceholder' - fullPath: '/search/searchPlaceholder' - preLoaderRoute: typeof SearchSearchPlaceholderRouteImport - parentRoute: typeof SearchRouteRoute + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteRouteImport + parentRoute: typeof rootRouteImport } '/params/$paramsPlaceholder': { id: '/params/$paramsPlaceholder' @@ -190,6 +183,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport parentRoute: typeof ParamsRouteRoute } + '/search/searchPlaceholder': { + id: '/search/searchPlaceholder' + path: '/searchPlaceholder' + fullPath: '/search/searchPlaceholder' + preLoaderRoute: typeof SearchSearchPlaceholderRouteImport + parentRoute: typeof SearchRouteRoute + } } } diff --git a/examples/react/large-file-based/src/styles.css b/examples/react/large-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/large-file-based/src/styles.css +++ b/examples/react/large-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/large-file-based/src/vite-env.d.ts b/examples/react/large-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/large-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/large-file-based/vite.config.js b/examples/react/large-file-based/vite.config.js index ab615485ae..ce5fc59483 100644 --- a/examples/react/large-file-based/vite.config.js +++ b/examples/react/large-file-based/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true }), react(), ], diff --git a/examples/react/location-masking/.devcontainer/devcontainer.json b/examples/react/location-masking/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/location-masking/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/location-masking/package.json b/examples/react/location-masking/package.json index 0466b1e508..fe005c0d2f 100644 --- a/examples/react/location-masking/package.json +++ b/examples/react/location-masking/package.json @@ -10,21 +10,21 @@ }, "dependencies": { "@radix-ui/react-dialog": "^1.1.6", - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/location-masking/postcss.config.mjs b/examples/react/location-masking/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/location-masking/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/location-masking/src/styles.css b/examples/react/location-masking/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/location-masking/src/styles.css +++ b/examples/react/location-masking/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/location-masking/src/vite-env.d.ts b/examples/react/location-masking/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/location-masking/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/location-masking/vite.config.js b/examples/react/location-masking/vite.config.js index 5a33944a9b..2764078e8b 100644 --- a/examples/react/location-masking/vite.config.js +++ b/examples/react/location-masking/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [tailwindcss(), react()], }) diff --git a/examples/react/navigation-blocking/.devcontainer/devcontainer.json b/examples/react/navigation-blocking/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/navigation-blocking/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/navigation-blocking/package.json b/examples/react/navigation-blocking/package.json index a9c6276e75..a7677dfd51 100644 --- a/examples/react/navigation-blocking/package.json +++ b/examples/react/navigation-blocking/package.json @@ -9,21 +9,21 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/navigation-blocking/postcss.config.mjs b/examples/react/navigation-blocking/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/navigation-blocking/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/navigation-blocking/src/styles.css b/examples/react/navigation-blocking/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/navigation-blocking/src/styles.css +++ b/examples/react/navigation-blocking/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/navigation-blocking/src/vite-env.d.ts b/examples/react/navigation-blocking/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/navigation-blocking/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/navigation-blocking/vite.config.js b/examples/react/navigation-blocking/vite.config.js index 5a33944a9b..2764078e8b 100644 --- a/examples/react/navigation-blocking/vite.config.js +++ b/examples/react/navigation-blocking/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [tailwindcss(), react()], }) diff --git a/examples/react/quickstart-esbuild-file-based/.devcontainer/devcontainer.json b/examples/react/quickstart-esbuild-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/quickstart-esbuild-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/quickstart-esbuild-file-based/esbuild.config.js b/examples/react/quickstart-esbuild-file-based/esbuild.config.js index fb7950d1fa..2f83a79984 100644 --- a/examples/react/quickstart-esbuild-file-based/esbuild.config.js +++ b/examples/react/quickstart-esbuild-file-based/esbuild.config.js @@ -7,5 +7,5 @@ export default { bundle: true, format: 'esm', target: ['esnext'], - plugins: [tanstackRouter({ target: 'react', autoCodeSplitting: true })], + plugins: [tanstackRouter({ target: 'react' })], } diff --git a/examples/react/quickstart-esbuild-file-based/package.json b/examples/react/quickstart-esbuild-file-based/package.json index ce458d12d6..d855694fec 100644 --- a/examples/react/quickstart-esbuild-file-based/package.json +++ b/examples/react/quickstart-esbuild-file-based/package.json @@ -9,17 +9,17 @@ "start": "dev" }, "dependencies": { - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "esbuild": "^0.25.0" + "esbuild": "^0.27.4" } } diff --git a/examples/react/quickstart-file-based/.devcontainer/devcontainer.json b/examples/react/quickstart-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/quickstart-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/quickstart-file-based/package.json b/examples/react/quickstart-file-based/package.json index dba04e8a64..976ec838d1 100644 --- a/examples/react/quickstart-file-based/package.json +++ b/examples/react/quickstart-file-based/package.json @@ -9,22 +9,22 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/quickstart-file-based/postcss.config.mjs b/examples/react/quickstart-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/quickstart-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/quickstart-file-based/src/routeTree.gen.ts b/examples/react/quickstart-file-based/src/routeTree.gen.ts index 59499d9fbf..12bc916ae4 100644 --- a/examples/react/quickstart-file-based/src/routeTree.gen.ts +++ b/examples/react/quickstart-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/quickstart-file-based/src/styles.css b/examples/react/quickstart-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/quickstart-file-based/src/styles.css +++ b/examples/react/quickstart-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/quickstart-file-based/src/vite-env.d.ts b/examples/react/quickstart-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/quickstart-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/quickstart-file-based/vite.config.js b/examples/react/quickstart-file-based/vite.config.js index ab615485ae..ce5fc59483 100644 --- a/examples/react/quickstart-file-based/vite.config.js +++ b/examples/react/quickstart-file-based/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true }), react(), ], diff --git a/examples/react/quickstart-rspack-file-based/.devcontainer/devcontainer.json b/examples/react/quickstart-rspack-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/quickstart-rspack-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/quickstart-rspack-file-based/package.json b/examples/react/quickstart-rspack-file-based/package.json index 19fdc77a72..824998f428 100644 --- a/examples/react/quickstart-rspack-file-based/package.json +++ b/examples/react/quickstart-rspack-file-based/package.json @@ -8,20 +8,21 @@ "preview": "rsbuild preview" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", + "@tailwindcss/postcss": "^4.2.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { - "@rsbuild/core": "^1.2.4", - "@rsbuild/plugin-react": "^1.1.0", - "@tanstack/router-plugin": "^1.142.0", + "@rsbuild/core": "^2.3.1", + "@rsbuild/plugin-react": "^2.0.0", + "@tanstack/router-plugin": "^1.169.0", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "typescript": "^5.6.2" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2" } } diff --git a/examples/react/quickstart-rspack-file-based/src/routeTree.gen.ts b/examples/react/quickstart-rspack-file-based/src/routeTree.gen.ts index 59499d9fbf..12bc916ae4 100644 --- a/examples/react/quickstart-rspack-file-based/src/routeTree.gen.ts +++ b/examples/react/quickstart-rspack-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/quickstart-rspack-file-based/src/styles.css b/examples/react/quickstart-rspack-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/quickstart-rspack-file-based/src/styles.css +++ b/examples/react/quickstart-rspack-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/quickstart-rspack-file-based/src/vite-env.d.ts b/examples/react/quickstart-rspack-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/quickstart-rspack-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/quickstart-webpack-file-based/.devcontainer/devcontainer.json b/examples/react/quickstart-webpack-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/quickstart-webpack-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/quickstart-webpack-file-based/package.json b/examples/react/quickstart-webpack-file-based/package.json index 533adaf246..baa14b89dd 100644 --- a/examples/react/quickstart-webpack-file-based/package.json +++ b/examples/react/quickstart-webpack-file-based/package.json @@ -7,21 +7,23 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@swc/core": "^1.10.15", - "@tanstack/router-plugin": "^1.142.0", + "@swc/core": "^1.15.33", + "@tanstack/router-plugin": "^1.169.0", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "html-webpack-plugin": "^5.6.3", + "react-refresh": "^0.18.0", "swc-loader": "^0.2.6", - "typescript": "^5.7.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "webpack": "^5.97.1", "webpack-cli": "^5.1.4", - "webpack-dev-server": "^5.2.0" + "webpack-dev-server": "^5.2.4" } } diff --git a/examples/react/quickstart-webpack-file-based/src/routeTree.gen.ts b/examples/react/quickstart-webpack-file-based/src/routeTree.gen.ts index 59499d9fbf..12bc916ae4 100644 --- a/examples/react/quickstart-webpack-file-based/src/routeTree.gen.ts +++ b/examples/react/quickstart-webpack-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/quickstart-webpack-file-based/webpack.config.js b/examples/react/quickstart-webpack-file-based/webpack.config.js index d83e2bea10..878d2a9735 100644 --- a/examples/react/quickstart-webpack-file-based/webpack.config.js +++ b/examples/react/quickstart-webpack-file-based/webpack.config.js @@ -23,7 +23,11 @@ export default ({ WEBPACK_SERVE }) => ({ template: path.resolve(__dirname, './public/index.html'), filename: 'index.html', }), - tanstackRouter({ target: 'react', autoCodeSplitting: true }), + tanstackRouter({ + target: 'react', + autoCodeSplitting: true, + codeSplittingOptions: { addHmr: Boolean(WEBPACK_SERVE) }, + }), ], module: { rules: [ diff --git a/examples/react/quickstart/.devcontainer/devcontainer.json b/examples/react/quickstart/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/quickstart/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/quickstart/package.json b/examples/react/quickstart/package.json index ab0ec86ad7..b6db476ea8 100644 --- a/examples/react/quickstart/package.json +++ b/examples/react/quickstart/package.json @@ -9,19 +9,19 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/quickstart/postcss.config.mjs b/examples/react/quickstart/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/quickstart/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/quickstart/src/styles.css b/examples/react/quickstart/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/quickstart/src/styles.css +++ b/examples/react/quickstart/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/quickstart/src/vite-env.d.ts b/examples/react/quickstart/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/quickstart/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/quickstart/vite.config.js b/examples/react/quickstart/vite.config.js index 5a33944a9b..2764078e8b 100644 --- a/examples/react/quickstart/vite.config.js +++ b/examples/react/quickstart/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [tailwindcss(), react()], }) diff --git a/examples/react/router-monorepo-react-query/.devcontainer/devcontainer.json b/examples/react/router-monorepo-react-query/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/router-monorepo-react-query/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/router-monorepo-react-query/package.json b/examples/react/router-monorepo-react-query/package.json index 18e87cb406..b158eeda56 100644 --- a/examples/react/router-monorepo-react-query/package.json +++ b/examples/react/router-monorepo-react-query/package.json @@ -10,11 +10,11 @@ "dev": "pnpm post-query build && pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -23,9 +23,10 @@ "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "typescript": "^5.7.2", - "@vitejs/plugin-react": "^4.3.4", - "vite": "^7.1.7", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" }, "keywords": [], 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 2e4630f650..f0994165c2 100644 --- a/examples/react/router-monorepo-react-query/packages/app/package.json +++ b/examples/react/router-monorepo-react-query/packages/app/package.json @@ -9,23 +9,23 @@ "start": "vite" }, "dependencies": { - "@tanstack/react-query": "^5.90.0", "@router-mono-react-query/post-feature": "workspace:*", "@router-mono-react-query/router": "workspace:*", + "@tanstack/react-query": "^5.102.0", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { + "@tanstack/react-router-devtools": "^1.167.3", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "@tanstack/react-router-devtools": "^1.141.8", - "postcss": "^8.5.1", - "autoprefixer": "^10.4.20", - "tailwindcss": "^3.4.17", - "vite": "^7.1.7", - "vite-plugin-dts": "^4.5.4" + "@vitejs/plugin-react": "^6.0.1", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-dts": "^4.5.4", + "@tailwindcss/vite": "^4.2.2" }, "nx": { "targets": { @@ -33,6 +33,12 @@ "dependsOn": [ "^build" ] + }, + "build": { + "inputs": [ + "...", + "{workspaceRoot}/examples/react/router-monorepo-react-query/.gitignore" + ] } } } diff --git a/examples/react/router-monorepo-react-query/packages/app/postcss.config.js b/examples/react/router-monorepo-react-query/packages/app/postcss.config.js deleted file mode 100644 index 61e0dbc36d..0000000000 --- a/examples/react/router-monorepo-react-query/packages/app/postcss.config.js +++ /dev/null @@ -1,8 +0,0 @@ -export default { - plugins: { - tailwindcss: { - config: 'tailwind.config.js', - }, - autoprefixer: {}, - }, -} diff --git a/examples/react/router-monorepo-react-query/packages/app/src/style.css b/examples/react/router-monorepo-react-query/packages/app/src/style.css index 0b8e317099..868812af60 100644 --- a/examples/react/router-monorepo-react-query/packages/app/src/style.css +++ b/examples/react/router-monorepo-react-query/packages/app/src/style.css @@ -1,6 +1,24 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; +@import 'tailwindcss' source('../'); + +@source '../../post-feature/src/**/*.{js,jsx,ts,tsx}'; + +/* + The default border color has changed to `currentcolor` in Tailwind CSS v4, + so we've added these compatibility styles to make sure everything still + looks the same as it did with Tailwind CSS v3. + + If we ever want to remove these styles, we need to add an explicit border + color utility to any element that depends on these defaults. +*/ +@layer base { + *, + ::after, + ::before, + ::backdrop, + ::file-selector-button { + border-color: var(--color-gray-200, currentcolor); + } +} html { color-scheme: light dark; diff --git a/examples/react/router-monorepo-react-query/packages/app/src/vite-env.d.ts b/examples/react/router-monorepo-react-query/packages/app/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/router-monorepo-react-query/packages/app/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/router-monorepo-react-query/packages/app/tailwind.config.js b/examples/react/router-monorepo-react-query/packages/app/tailwind.config.js deleted file mode 100644 index 33c30f731f..0000000000 --- a/examples/react/router-monorepo-react-query/packages/app/tailwind.config.js +++ /dev/null @@ -1,7 +0,0 @@ -/** @type {import('tailwindcss').Config} */ -export default { - content: [ - './src/**/*.{js,jsx,ts,tsx}', - '../post-feature/src/**/*.{js,jsx,ts,tsx}', - ], -} diff --git a/examples/react/router-monorepo-react-query/packages/app/tsconfig.json b/examples/react/router-monorepo-react-query/packages/app/tsconfig.json index ce3a7d2339..196cb055a9 100644 --- a/examples/react/router-monorepo-react-query/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-react-query/packages/app/tsconfig.json @@ -8,5 +8,6 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - } + }, + "exclude": ["node_modules", "dist"] } diff --git a/examples/react/router-monorepo-react-query/packages/app/vite.config.ts b/examples/react/router-monorepo-react-query/packages/app/vite.config.ts index f423196caf..493a44fbca 100644 --- a/examples/react/router-monorepo-react-query/packages/app/vite.config.ts +++ b/examples/react/router-monorepo-react-query/packages/app/vite.config.ts @@ -3,6 +3,7 @@ import dts from 'vite-plugin-dts' import * as path from 'node:path' import { fileURLToPath } from 'node:url' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) @@ -21,6 +22,7 @@ export default defineConfig({ host: 'localhost', }, plugins: [ + tailwindcss(), dts({ entryRoot: 'src', tsconfigPath: path.join(__dirname, 'tsconfig.json'), diff --git a/examples/react/router-monorepo-react-query/packages/post-feature/package.json b/examples/react/router-monorepo-react-query/packages/post-feature/package.json index a412787287..7f5e186ab0 100644 --- a/examples/react/router-monorepo-react-query/packages/post-feature/package.json +++ b/examples/react/router-monorepo-react-query/packages/post-feature/package.json @@ -8,7 +8,7 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@router-mono-react-query/post-query": "workspace:*", "@router-mono-react-query/router": "workspace:*", "react": "^19.0.0", @@ -17,9 +17,10 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-react-query/packages/post-feature/vite.config.ts b/examples/react/router-monorepo-react-query/packages/post-feature/vite.config.ts index ee998ce7c2..02fe64430e 100644 --- a/examples/react/router-monorepo-react-query/packages/post-feature/vite.config.ts +++ b/examples/react/router-monorepo-react-query/packages/post-feature/vite.config.ts @@ -29,7 +29,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: [ 'react', diff --git a/examples/react/router-monorepo-react-query/packages/post-query/package.json b/examples/react/router-monorepo-react-query/packages/post-query/package.json index f8e3398ade..98a06051be 100644 --- a/examples/react/router-monorepo-react-query/packages/post-query/package.json +++ b/examples/react/router-monorepo-react-query/packages/post-query/package.json @@ -8,13 +8,14 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "redaxios": "^0.5.1", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/router-monorepo-react-query/packages/post-query/vite.config.ts b/examples/react/router-monorepo-react-query/packages/post-query/vite.config.ts index cf84936d33..0116b9a9fc 100644 --- a/examples/react/router-monorepo-react-query/packages/post-query/vite.config.ts +++ b/examples/react/router-monorepo-react-query/packages/post-query/vite.config.ts @@ -27,7 +27,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: [ 'react', 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 eb58112d83..1397db14b5 100644 --- a/examples/react/router-monorepo-react-query/packages/router/package.json +++ b/examples/react/router-monorepo-react-query/packages/router/package.json @@ -8,22 +8,23 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.141.0", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", "@router-mono-react-query/post-query": "workspace:*", - "redaxios": "^0.5.1", - "zod": "^3.24.2", + "@tanstack/history": "^1.162.5", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", - "react-dom": "^19.0.0" + "react-dom": "^19.0.0", + "redaxios": "^0.5.1", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-react-query/packages/router/src/routeTree.gen.ts b/examples/react/router-monorepo-react-query/packages/router/src/routeTree.gen.ts index 0820fc5f30..a4ed448d2f 100644 --- a/examples/react/router-monorepo-react-query/packages/router/src/routeTree.gen.ts +++ b/examples/react/router-monorepo-react-query/packages/router/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as PostIdRouteImport } from './routes/$postId' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostIdRouteImport } from './routes/$postId' -const PostIdRoute = PostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostIdRoute = PostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/$postId': { - id: '/$postId' - path: '/$postId' - fullPath: '/$postId' - preLoaderRoute: typeof PostIdRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/$postId': { + id: '/$postId' + path: '/$postId' + fullPath: '/$postId' + preLoaderRoute: typeof PostIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/router-monorepo-react-query/packages/router/tsconfig.json b/examples/react/router-monorepo-react-query/packages/router/tsconfig.json index 0d04c7789d..aeb605df28 100644 --- a/examples/react/router-monorepo-react-query/packages/router/tsconfig.json +++ b/examples/react/router-monorepo-react-query/packages/router/tsconfig.json @@ -7,7 +7,8 @@ "moduleResolution": "Bundler", "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], - "skipLibCheck": true + "skipLibCheck": true, + "rootDir": "src" }, "include": ["src"] } diff --git a/examples/react/router-monorepo-react-query/packages/router/vite.config.ts b/examples/react/router-monorepo-react-query/packages/router/vite.config.ts index b471bd3f58..b5d58d21b5 100644 --- a/examples/react/router-monorepo-react-query/packages/router/vite.config.ts +++ b/examples/react/router-monorepo-react-query/packages/router/vite.config.ts @@ -31,7 +31,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: [ 'react', diff --git a/examples/react/router-monorepo-simple-lazy/.devcontainer/devcontainer.json b/examples/react/router-monorepo-simple-lazy/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/router-monorepo-simple-lazy/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/router-monorepo-simple-lazy/package.json b/examples/react/router-monorepo-simple-lazy/package.json index dd41fbb854..e044d86681 100644 --- a/examples/react/router-monorepo-simple-lazy/package.json +++ b/examples/react/router-monorepo-simple-lazy/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -19,9 +19,10 @@ "@types/node": "^22.7.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" }, "keywords": [], 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 40ca12cc02..cfc7a94942 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/package.json @@ -15,16 +15,16 @@ "react-dom": "^19.0.0" }, "devDependencies": { + "@tanstack/react-router-devtools": "^1.167.3", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "@tanstack/react-router-devtools": "^1.141.8", - "postcss": "^8.5.1", - "autoprefixer": "^10.4.20", - "tailwindcss": "^3.4.17", - "vite": "^7.1.7", - "vite-plugin-dts": "^4.5.4" + "@vitejs/plugin-react": "^6.0.1", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-dts": "^4.5.4", + "@tailwindcss/vite": "^4.2.2" }, "nx": { "targets": { @@ -32,6 +32,12 @@ "dependsOn": [ "^build" ] + }, + "build": { + "inputs": [ + "...", + "{workspaceRoot}/examples/react/router-monorepo-simple-lazy/.gitignore" + ] } } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/postcss.config.js b/examples/react/router-monorepo-simple-lazy/packages/app/postcss.config.js deleted file mode 100644 index 61e0dbc36d..0000000000 --- a/examples/react/router-monorepo-simple-lazy/packages/app/postcss.config.js +++ /dev/null @@ -1,8 +0,0 @@ -export default { - plugins: { - tailwindcss: { - config: 'tailwind.config.js', - }, - autoprefixer: {}, - }, -} diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/src/style.css b/examples/react/router-monorepo-simple-lazy/packages/app/src/style.css index 0b8e317099..868812af60 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/src/style.css +++ b/examples/react/router-monorepo-simple-lazy/packages/app/src/style.css @@ -1,6 +1,24 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; +@import 'tailwindcss' source('../'); + +@source '../../post-feature/src/**/*.{js,jsx,ts,tsx}'; + +/* + The default border color has changed to `currentcolor` in Tailwind CSS v4, + so we've added these compatibility styles to make sure everything still + looks the same as it did with Tailwind CSS v3. + + If we ever want to remove these styles, we need to add an explicit border + color utility to any element that depends on these defaults. +*/ +@layer base { + *, + ::after, + ::before, + ::backdrop, + ::file-selector-button { + border-color: var(--color-gray-200, currentcolor); + } +} html { color-scheme: light dark; diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/src/vite-env.d.ts b/examples/react/router-monorepo-simple-lazy/packages/app/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/router-monorepo-simple-lazy/packages/app/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/tailwind.config.js b/examples/react/router-monorepo-simple-lazy/packages/app/tailwind.config.js deleted file mode 100644 index 33c30f731f..0000000000 --- a/examples/react/router-monorepo-simple-lazy/packages/app/tailwind.config.js +++ /dev/null @@ -1,7 +0,0 @@ -/** @type {import('tailwindcss').Config} */ -export default { - content: [ - './src/**/*.{js,jsx,ts,tsx}', - '../post-feature/src/**/*.{js,jsx,ts,tsx}', - ], -} diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json b/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json index ce3a7d2339..196cb055a9 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json @@ -8,5 +8,6 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - } + }, + "exclude": ["node_modules", "dist"] } diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/vite.config.ts b/examples/react/router-monorepo-simple-lazy/packages/app/vite.config.ts index f423196caf..493a44fbca 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/vite.config.ts +++ b/examples/react/router-monorepo-simple-lazy/packages/app/vite.config.ts @@ -3,6 +3,7 @@ import dts from 'vite-plugin-dts' import * as path from 'node:path' import { fileURLToPath } from 'node:url' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) @@ -21,6 +22,7 @@ export default defineConfig({ host: 'localhost', }, plugins: [ + tailwindcss(), dts({ entryRoot: 'src', tsconfigPath: path.join(__dirname, 'tsconfig.json'), diff --git a/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json b/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json index 396dcc3a8d..65738d6025 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json @@ -16,7 +16,7 @@ } }, "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@router-mono-simple-lazy/router": "workspace:*", "react": "^19.0.0", "react-dom": "^19.0.0" @@ -24,9 +24,10 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/post-feature/vite.config.ts b/examples/react/router-monorepo-simple-lazy/packages/post-feature/vite.config.ts index 79e5b6c46e..b0f8eab682 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/post-feature/vite.config.ts +++ b/examples/react/router-monorepo-simple-lazy/packages/post-feature/vite.config.ts @@ -28,7 +28,7 @@ export default defineConfig({ name: 'post-feature', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: [ 'react', 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 6f5d84739f..afd4702b5d 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/router/package.json @@ -8,20 +8,21 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.141.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "redaxios": "^0.5.1", - "zod": "^3.24.2", + "@tanstack/history": "^1.162.5", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", - "react-dom": "^19.0.0" + "react-dom": "^19.0.0", + "redaxios": "^0.5.1", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts b/examples/react/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts index 0820fc5f30..a4ed448d2f 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts +++ b/examples/react/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as PostIdRouteImport } from './routes/$postId' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostIdRouteImport } from './routes/$postId' -const PostIdRoute = PostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostIdRoute = PostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/$postId': { - id: '/$postId' - path: '/$postId' - fullPath: '/$postId' - preLoaderRoute: typeof PostIdRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/$postId': { + id: '/$postId' + path: '/$postId' + fullPath: '/$postId' + preLoaderRoute: typeof PostIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/tsconfig.json b/examples/react/router-monorepo-simple-lazy/packages/router/tsconfig.json index 0d04c7789d..aeb605df28 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/tsconfig.json +++ b/examples/react/router-monorepo-simple-lazy/packages/router/tsconfig.json @@ -7,7 +7,8 @@ "moduleResolution": "Bundler", "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], - "skipLibCheck": true + "skipLibCheck": true, + "rootDir": "src" }, "include": ["src"] } diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/vite.config.ts b/examples/react/router-monorepo-simple-lazy/packages/router/vite.config.ts index 21aa5e70f4..2a46c98c90 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/vite.config.ts +++ b/examples/react/router-monorepo-simple-lazy/packages/router/vite.config.ts @@ -29,7 +29,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: [ 'react', diff --git a/examples/react/router-monorepo-simple/.devcontainer/devcontainer.json b/examples/react/router-monorepo-simple/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/router-monorepo-simple/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/router-monorepo-simple/package.json b/examples/react/router-monorepo-simple/package.json index 1914130b95..800d948c81 100644 --- a/examples/react/router-monorepo-simple/package.json +++ b/examples/react/router-monorepo-simple/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -19,9 +19,10 @@ "@types/node": "^22.7.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" }, "keywords": [], diff --git a/examples/react/router-monorepo-simple/packages/app/package.json b/examples/react/router-monorepo-simple/packages/app/package.json index 5632cc2226..a06431ef86 100644 --- a/examples/react/router-monorepo-simple/packages/app/package.json +++ b/examples/react/router-monorepo-simple/packages/app/package.json @@ -15,16 +15,16 @@ "react-dom": "^19.0.0" }, "devDependencies": { + "@tanstack/react-router-devtools": "^1.167.3", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "@tanstack/react-router-devtools": "^1.141.8", - "vite": "^7.1.7", - "postcss": "^8.5.1", - "autoprefixer": "^10.4.20", - "tailwindcss": "^3.4.17", - "vite-plugin-dts": "^4.5.4" + "@vitejs/plugin-react": "^6.0.1", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-dts": "^4.5.4", + "@tailwindcss/vite": "^4.2.2" }, "nx": { "targets": { @@ -32,6 +32,12 @@ "dependsOn": [ "^build" ] + }, + "build": { + "inputs": [ + "...", + "{workspaceRoot}/examples/react/router-monorepo-simple/.gitignore" + ] } } } diff --git a/examples/react/router-monorepo-simple/packages/app/postcss.config.js b/examples/react/router-monorepo-simple/packages/app/postcss.config.js deleted file mode 100644 index 61e0dbc36d..0000000000 --- a/examples/react/router-monorepo-simple/packages/app/postcss.config.js +++ /dev/null @@ -1,8 +0,0 @@ -export default { - plugins: { - tailwindcss: { - config: 'tailwind.config.js', - }, - autoprefixer: {}, - }, -} diff --git a/examples/react/router-monorepo-simple/packages/app/src/style.css b/examples/react/router-monorepo-simple/packages/app/src/style.css index 0b8e317099..868812af60 100644 --- a/examples/react/router-monorepo-simple/packages/app/src/style.css +++ b/examples/react/router-monorepo-simple/packages/app/src/style.css @@ -1,6 +1,24 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; +@import 'tailwindcss' source('../'); + +@source '../../post-feature/src/**/*.{js,jsx,ts,tsx}'; + +/* + The default border color has changed to `currentcolor` in Tailwind CSS v4, + so we've added these compatibility styles to make sure everything still + looks the same as it did with Tailwind CSS v3. + + If we ever want to remove these styles, we need to add an explicit border + color utility to any element that depends on these defaults. +*/ +@layer base { + *, + ::after, + ::before, + ::backdrop, + ::file-selector-button { + border-color: var(--color-gray-200, currentcolor); + } +} html { color-scheme: light dark; diff --git a/examples/react/router-monorepo-simple/packages/app/src/vite-env.d.ts b/examples/react/router-monorepo-simple/packages/app/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/router-monorepo-simple/packages/app/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/router-monorepo-simple/packages/app/tailwind.config.js b/examples/react/router-monorepo-simple/packages/app/tailwind.config.js deleted file mode 100644 index 33c30f731f..0000000000 --- a/examples/react/router-monorepo-simple/packages/app/tailwind.config.js +++ /dev/null @@ -1,7 +0,0 @@ -/** @type {import('tailwindcss').Config} */ -export default { - content: [ - './src/**/*.{js,jsx,ts,tsx}', - '../post-feature/src/**/*.{js,jsx,ts,tsx}', - ], -} diff --git a/examples/react/router-monorepo-simple/packages/app/tsconfig.json b/examples/react/router-monorepo-simple/packages/app/tsconfig.json index ce3a7d2339..196cb055a9 100644 --- a/examples/react/router-monorepo-simple/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple/packages/app/tsconfig.json @@ -8,5 +8,6 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - } + }, + "exclude": ["node_modules", "dist"] } diff --git a/examples/react/router-monorepo-simple/packages/app/vite.config.ts b/examples/react/router-monorepo-simple/packages/app/vite.config.ts index f423196caf..493a44fbca 100644 --- a/examples/react/router-monorepo-simple/packages/app/vite.config.ts +++ b/examples/react/router-monorepo-simple/packages/app/vite.config.ts @@ -3,6 +3,7 @@ import dts from 'vite-plugin-dts' import * as path from 'node:path' import { fileURLToPath } from 'node:url' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) @@ -21,6 +22,7 @@ export default defineConfig({ host: 'localhost', }, plugins: [ + tailwindcss(), dts({ entryRoot: 'src', tsconfigPath: path.join(__dirname, 'tsconfig.json'), diff --git a/examples/react/router-monorepo-simple/packages/post-feature/package.json b/examples/react/router-monorepo-simple/packages/post-feature/package.json index fff9f67f84..885aa6bbed 100644 --- a/examples/react/router-monorepo-simple/packages/post-feature/package.json +++ b/examples/react/router-monorepo-simple/packages/post-feature/package.json @@ -15,9 +15,10 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-simple/packages/post-feature/vite.config.ts b/examples/react/router-monorepo-simple/packages/post-feature/vite.config.ts index f07d75fcf3..b9d09b0ced 100644 --- a/examples/react/router-monorepo-simple/packages/post-feature/vite.config.ts +++ b/examples/react/router-monorepo-simple/packages/post-feature/vite.config.ts @@ -29,7 +29,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: [ 'react', diff --git a/examples/react/router-monorepo-simple/packages/router/package.json b/examples/react/router-monorepo-simple/packages/router/package.json index 3d5672e93e..391b72e610 100644 --- a/examples/react/router-monorepo-simple/packages/router/package.json +++ b/examples/react/router-monorepo-simple/packages/router/package.json @@ -8,20 +8,21 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.141.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "redaxios": "^0.5.1", - "zod": "^3.24.2", + "@tanstack/history": "^1.162.5", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", - "react-dom": "^19.0.0" + "react-dom": "^19.0.0", + "redaxios": "^0.5.1", + "zod": "^4.4.3" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/react/router-monorepo-simple/packages/router/src/routeTree.gen.ts b/examples/react/router-monorepo-simple/packages/router/src/routeTree.gen.ts index 0820fc5f30..a4ed448d2f 100644 --- a/examples/react/router-monorepo-simple/packages/router/src/routeTree.gen.ts +++ b/examples/react/router-monorepo-simple/packages/router/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as PostIdRouteImport } from './routes/$postId' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostIdRouteImport } from './routes/$postId' -const PostIdRoute = PostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostIdRoute = PostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/$postId': { - id: '/$postId' - path: '/$postId' - fullPath: '/$postId' - preLoaderRoute: typeof PostIdRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/$postId': { + id: '/$postId' + path: '/$postId' + fullPath: '/$postId' + preLoaderRoute: typeof PostIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/router-monorepo-simple/packages/router/tsconfig.json b/examples/react/router-monorepo-simple/packages/router/tsconfig.json index 0d04c7789d..aeb605df28 100644 --- a/examples/react/router-monorepo-simple/packages/router/tsconfig.json +++ b/examples/react/router-monorepo-simple/packages/router/tsconfig.json @@ -7,7 +7,8 @@ "moduleResolution": "Bundler", "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], - "skipLibCheck": true + "skipLibCheck": true, + "rootDir": "src" }, "include": ["src"] } diff --git a/examples/react/router-monorepo-simple/packages/router/vite.config.ts b/examples/react/router-monorepo-simple/packages/router/vite.config.ts index 21aa5e70f4..2a46c98c90 100644 --- a/examples/react/router-monorepo-simple/packages/router/vite.config.ts +++ b/examples/react/router-monorepo-simple/packages/router/vite.config.ts @@ -29,7 +29,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: [ 'react', diff --git a/examples/react/scroll-restoration/.devcontainer/devcontainer.json b/examples/react/scroll-restoration/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/scroll-restoration/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/scroll-restoration/package.json b/examples/react/scroll-restoration/package.json index 7f719dc0bf..704ff13838 100644 --- a/examples/react/scroll-restoration/package.json +++ b/examples/react/scroll-restoration/package.json @@ -9,20 +9,20 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "@tanstack/react-virtual": "^3.13.0", - "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/scroll-restoration/postcss.config.mjs b/examples/react/scroll-restoration/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/scroll-restoration/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/scroll-restoration/src/styles.css b/examples/react/scroll-restoration/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/scroll-restoration/src/styles.css +++ b/examples/react/scroll-restoration/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/scroll-restoration/src/vite-env.d.ts b/examples/react/scroll-restoration/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/scroll-restoration/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/scroll-restoration/vite.config.js b/examples/react/scroll-restoration/vite.config.js index 5a33944a9b..2764078e8b 100644 --- a/examples/react/scroll-restoration/vite.config.js +++ b/examples/react/scroll-restoration/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react()], + plugins: [tailwindcss(), react()], }) diff --git a/examples/react/search-validator-adapters/.devcontainer/devcontainer.json b/examples/react/search-validator-adapters/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/search-validator-adapters/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/search-validator-adapters/package.json b/examples/react/search-validator-adapters/package.json index bce8710056..35e041e825 100644 --- a/examples/react/search-validator-adapters/package.json +++ b/examples/react/search-validator-adapters/package.json @@ -4,35 +4,37 @@ "type": "module", "scripts": { "dev": "vite --port 3000", - "build": "vite build && tsc --noEmit", + "build": "vite build && NODE_OPTIONS=--max-old-space-size=4096 tsc --noEmit", "preview": "vite preview", "start": "vite", "test:unit": "vitest" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/arktype-adapter": "^1.141.8", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "@tanstack/valibot-adapter": "^1.141.8", - "@tanstack/zod-adapter": "^1.141.8", + "@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/valibot-adapter": "^1.167.0", + "@tanstack/zod-adapter": "^1.167.0", "arktype": "^2.1.7", - "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwindcss": "^4.1.17", + "tailwindcss": "^4.2.2", "valibot": "1.0.0-beta.15", "zod": "^3.24.2" }, "devDependencies": { - "@testing-library/jest-dom": "^6.6.3", + "@testing-library/jest-dom": "^7.0.1", "@testing-library/react": "^16.2.0", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "jsdom": "^27.0.0", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vitest": "^5.0.4" } } diff --git a/examples/react/search-validator-adapters/postcss.config.mjs b/examples/react/search-validator-adapters/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/search-validator-adapters/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/search-validator-adapters/src/routeTree.gen.ts b/examples/react/search-validator-adapters/src/routeTree.gen.ts index 3312abe25e..d58c1ddfa1 100644 --- a/examples/react/search-validator-adapters/src/routeTree.gen.ts +++ b/examples/react/search-validator-adapters/src/routeTree.gen.ts @@ -8,40 +8,38 @@ // You should NOT make any changes in this file as it will be overwritten. // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. -import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/react-router' - import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersZodIndexRouteImport } from './routes/users/zod.index' -import { Route as UsersValibotIndexRouteImport } from './routes/users/valibot.index' import { Route as UsersArktypeIndexRouteImport } from './routes/users/arktype.index' +import { Route as UsersValibotIndexRouteImport } from './routes/users/valibot.index' +import { Route as UsersZodIndexRouteImport } from './routes/users/zod.index' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ - id: '/users/zod/', - path: '/users/zod/', - getParentRoute: () => rootRouteImport, -} as any) -const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ - id: '/users/valibot/', - path: '/users/valibot/', - getParentRoute: () => rootRouteImport, -} as any) const UsersArktypeIndexRoute = UsersArktypeIndexRouteImport.update({ id: '/users/arktype/', path: '/users/arktype/', getParentRoute: () => rootRouteImport, } as any) +const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ + id: '/users/valibot/', + path: '/users/valibot/', + getParentRoute: () => rootRouteImport, +} as any) +const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ + id: '/users/zod/', + path: '/users/zod/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute - '/users/arktype': typeof UsersArktypeIndexRoute - '/users/valibot': typeof UsersValibotIndexRoute - '/users/zod': typeof UsersZodIndexRoute + '/users/arktype/': typeof UsersArktypeIndexRoute + '/users/valibot/': typeof UsersValibotIndexRoute + '/users/zod/': typeof UsersZodIndexRoute } export interface FileRoutesByTo { '/': typeof IndexRoute @@ -58,7 +56,7 @@ export interface FileRoutesById { } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/users/arktype' | '/users/valibot' | '/users/zod' + fullPaths: '/' | '/users/arktype/' | '/users/valibot/' | '/users/zod/' fileRoutesByTo: FileRoutesByTo to: '/' | '/users/arktype' | '/users/valibot' | '/users/zod' id: '__root__' | '/' | '/users/arktype/' | '/users/valibot/' | '/users/zod/' @@ -80,67 +78,30 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/users/zod/': { - id: '/users/zod/' - path: '/users/zod' - fullPath: '/users/zod' - preLoaderRoute: typeof UsersZodIndexRouteImport + '/users/arktype/': { + id: '/users/arktype/' + path: '/users/arktype' + fullPath: '/users/arktype/' + preLoaderRoute: typeof UsersArktypeIndexRouteImport parentRoute: typeof rootRouteImport } '/users/valibot/': { id: '/users/valibot/' path: '/users/valibot' - fullPath: '/users/valibot' + fullPath: '/users/valibot/' preLoaderRoute: typeof UsersValibotIndexRouteImport parentRoute: typeof rootRouteImport } - '/users/arktype/': { - id: '/users/arktype/' - path: '/users/arktype' - fullPath: '/users/arktype' - preLoaderRoute: typeof UsersArktypeIndexRouteImport + '/users/zod/': { + id: '/users/zod/' + path: '/users/zod' + fullPath: '/users/zod/' + preLoaderRoute: typeof UsersZodIndexRouteImport parentRoute: typeof rootRouteImport } } } -declare module './routes/index' { - const createFileRoute: CreateFileRoute< - '/', - FileRoutesByPath['/']['parentRoute'], - FileRoutesByPath['/']['id'], - FileRoutesByPath['/']['path'], - FileRoutesByPath['/']['fullPath'] - > -} -declare module './routes/users/arktype.index' { - const createFileRoute: CreateFileRoute< - '/users/arktype/', - FileRoutesByPath['/users/arktype/']['parentRoute'], - FileRoutesByPath['/users/arktype/']['id'], - FileRoutesByPath['/users/arktype/']['path'], - FileRoutesByPath['/users/arktype/']['fullPath'] - > -} -declare module './routes/users/valibot.index' { - const createFileRoute: CreateFileRoute< - '/users/valibot/', - FileRoutesByPath['/users/valibot/']['parentRoute'], - FileRoutesByPath['/users/valibot/']['id'], - FileRoutesByPath['/users/valibot/']['path'], - FileRoutesByPath['/users/valibot/']['fullPath'] - > -} -declare module './routes/users/zod.index' { - const createFileRoute: CreateFileRoute< - '/users/zod/', - FileRoutesByPath['/users/zod/']['parentRoute'], - FileRoutesByPath['/users/zod/']['id'], - FileRoutesByPath['/users/zod/']['path'], - FileRoutesByPath['/users/zod/']['fullPath'] - > -} - const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, UsersArktypeIndexRoute: UsersArktypeIndexRoute, diff --git a/examples/react/search-validator-adapters/src/routes/index.tsx b/examples/react/search-validator-adapters/src/routes/index.tsx index e279d9c1e0..d0eff7e9f3 100644 --- a/examples/react/search-validator-adapters/src/routes/index.tsx +++ b/examples/react/search-validator-adapters/src/routes/index.tsx @@ -1,3 +1,4 @@ +import { createFileRoute } from '@tanstack/react-router' import * as React from 'react' import { Header } from '../components/Header' @@ -12,6 +13,6 @@ export const Index: React.FunctionComponent = () => { ) } -export const Route = createFileRoute({ +export const Route = createFileRoute('/')({ component: Index, }) diff --git a/examples/react/search-validator-adapters/src/routes/users/arktype.index.tsx b/examples/react/search-validator-adapters/src/routes/users/arktype.index.tsx index 38af594c85..702db7a5d5 100644 --- a/examples/react/search-validator-adapters/src/routes/users/arktype.index.tsx +++ b/examples/react/search-validator-adapters/src/routes/users/arktype.index.tsx @@ -1,5 +1,5 @@ import * as React from 'react' -import { useNavigate } from '@tanstack/react-router' +import { useNavigate, createFileRoute } from '@tanstack/react-router' import { type } from 'arktype' import { Header } from '../../components/Header' import { Users, usersQueryOptions } from '../../components/Users' @@ -32,7 +32,7 @@ const search = type({ search: 'string = ""', }) -export const Route = createFileRoute({ +export const Route = createFileRoute('/users/arktype/')({ validateSearch: search, loaderDeps: (opt) => ({ search: opt.search }), loader: (opt) => { diff --git a/examples/react/search-validator-adapters/src/routes/users/valibot.index.tsx b/examples/react/search-validator-adapters/src/routes/users/valibot.index.tsx index 1a8bc7dd18..8ed997e722 100644 --- a/examples/react/search-validator-adapters/src/routes/users/valibot.index.tsx +++ b/examples/react/search-validator-adapters/src/routes/users/valibot.index.tsx @@ -1,5 +1,5 @@ import * as React from 'react' -import { useNavigate } from '@tanstack/react-router' +import { useNavigate, createFileRoute } from '@tanstack/react-router' import * as v from 'valibot' import { Header } from '../../components/Header' import { Users, usersQueryOptions } from '../../components/Users' @@ -26,7 +26,7 @@ const Valibot = () => { ) } -export const Route = createFileRoute({ +export const Route = createFileRoute('/users/valibot/')({ validateSearch: v.object({ search: v.fallback(v.optional(v.string(), ''), ''), }), diff --git a/examples/react/search-validator-adapters/src/routes/users/zod.index.tsx b/examples/react/search-validator-adapters/src/routes/users/zod.index.tsx index 8f095d156f..526509c8d8 100644 --- a/examples/react/search-validator-adapters/src/routes/users/zod.index.tsx +++ b/examples/react/search-validator-adapters/src/routes/users/zod.index.tsx @@ -1,5 +1,5 @@ import * as React from 'react' -import { useNavigate } from '@tanstack/react-router' +import { useNavigate, createFileRoute } from '@tanstack/react-router' import { fallback, zodValidator } from '@tanstack/zod-adapter' import { z } from 'zod' import { Header } from '../../components/Header' @@ -7,6 +7,11 @@ import { Users, usersQueryOptions } from '../../components/Users' import { Content } from '../../components/Content' import { Search } from '../../components/Search' +const fallbackString = fallback as unknown as ( + schema: z.ZodString, + fallback: string, +) => z.ZodType + const Zod = () => { const search = Route.useSearch({ select: (search) => search.search ?? '', @@ -29,10 +34,10 @@ const Zod = () => { ) } -export const Route = createFileRoute({ +export const Route = createFileRoute('/users/zod/')({ validateSearch: zodValidator( z.object({ - search: fallback(z.string().optional(), undefined), + search: fallbackString(z.string(), '').default(''), }), ), loaderDeps: (opt) => ({ search: opt.search }), diff --git a/examples/react/search-validator-adapters/src/styles.css b/examples/react/search-validator-adapters/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/search-validator-adapters/src/styles.css +++ b/examples/react/search-validator-adapters/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/search-validator-adapters/src/vite-env.d.ts b/examples/react/search-validator-adapters/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/search-validator-adapters/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/search-validator-adapters/tests/arktype.test.tsx b/examples/react/search-validator-adapters/tests/arktype.test.tsx index da70085114..776cc8369e 100644 --- a/examples/react/search-validator-adapters/tests/arktype.test.tsx +++ b/examples/react/search-validator-adapters/tests/arktype.test.tsx @@ -8,7 +8,6 @@ import { createRouter, } from '@tanstack/react-router' -import '@testing-library/jest-dom/vitest' import { type } from 'arktype' test('can navigate to the route', async () => { @@ -26,7 +25,7 @@ test('can navigate to the route', async () => { return (
    {search}
    - + Update
    diff --git a/examples/react/search-validator-adapters/tests/jest-dom.setup.ts b/examples/react/search-validator-adapters/tests/jest-dom.setup.ts new file mode 100644 index 0000000000..8f7cbf15be --- /dev/null +++ b/examples/react/search-validator-adapters/tests/jest-dom.setup.ts @@ -0,0 +1,18 @@ +import * as jestDomMatchers from '@testing-library/jest-dom/matchers' +import { expect } from 'vitest' +import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' + +// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged +// and released, and go back to `import '@testing-library/jest-dom/vitest'`. +// That entry imports `vitest` from its own install location, which can resolve +// a different Vitest copy than the one running these tests, and its types +// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. +// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting +// `@testing-library/jest-dom/vitest` when a setup file path contains it. +expect.extend(jestDomMatchers) + +declare module 'vitest' { + // Type parameter names must match Vitest's declaration for the interfaces to merge. + // eslint-disable-next-line @typescript-eslint/naming-convention + interface Matchers extends TestingLibraryMatchers {} +} diff --git a/examples/react/search-validator-adapters/tests/valibot.test.tsx b/examples/react/search-validator-adapters/tests/valibot.test.tsx index 30dc6da751..d3e18db414 100644 --- a/examples/react/search-validator-adapters/tests/valibot.test.tsx +++ b/examples/react/search-validator-adapters/tests/valibot.test.tsx @@ -8,7 +8,6 @@ import { createRouter, } from '@tanstack/react-router' import * as v from 'valibot' -import '@testing-library/jest-dom/vitest' test('can navigate to the route', async () => { const rootRoute = createRootRoute() @@ -25,7 +24,7 @@ test('can navigate to the route', async () => { return (
    {search}
    - + Update
    diff --git a/examples/react/search-validator-adapters/vite.config.ts b/examples/react/search-validator-adapters/vite.config.ts index a14d94a148..e4b93f5cc3 100644 --- a/examples/react/search-validator-adapters/vite.config.ts +++ b/examples/react/search-validator-adapters/vite.config.ts @@ -2,6 +2,7 @@ import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' import packageJson from './package.json' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ test: { @@ -10,12 +11,13 @@ export default defineConfig({ watch: false, environment: 'jsdom', typecheck: { enabled: true }, + setupFiles: ['./tests/jest-dom.setup.ts'], }, plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true, - verboseFileRoutes: false, }), react(), ], diff --git a/examples/react/start-bare/.devcontainer/devcontainer.json b/examples/react/start-bare/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-bare/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-bare/package.json b/examples/react/start-bare/package.json index 0ff8ad11b5..4ab9aff272 100644 --- a/examples/react/start-bare/package.json +++ b/examples/react/start-bare/package.json @@ -10,20 +10,20 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-bare/src/routeTree.gen.ts b/examples/react/start-bare/src/routeTree.gen.ts index 421daf2790..d89758e684 100644 --- a/examples/react/start-bare/src/routeTree.gen.ts +++ b/examples/react/start-bare/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/start-bare/src/router.tsx b/examples/react/start-bare/src/router.tsx index a464233af9..6f82cbf378 100644 --- a/examples/react/start-bare/src/router.tsx +++ b/examples/react/start-bare/src/router.tsx @@ -5,7 +5,9 @@ export function getRouter() { const router = createRouter({ routeTree, defaultPreload: 'intent', - defaultErrorComponent: (err) =>

    {err.error.stack}

    , + defaultErrorComponent: (err) => ( +

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

    + ), defaultNotFoundComponent: () =>

    not found

    , scrollRestoration: true, }) diff --git a/examples/react/start-bare/tsconfig.json b/examples/react/start-bare/tsconfig.json index b3a2d67dfa..af81492efb 100644 --- a/examples/react/start-bare/tsconfig.json +++ b/examples/react/start-bare/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-bare/vite.config.ts b/examples/react/start-bare/vite.config.ts index f10c86e79f..d0ee8802cf 100644 --- a/examples/react/start-bare/vite.config.ts +++ b/examples/react/start-bare/vite.config.ts @@ -1,17 +1,13 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tanstackStart(), viteReact()], }) diff --git a/examples/react/start-basic-auth/.devcontainer/devcontainer.json b/examples/react/start-basic-auth/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-basic-auth/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-basic-auth/README.md b/examples/react/start-basic-auth/README.md index 4e5ee29b40..7f1b093ba5 100644 --- a/examples/react/start-basic-auth/README.md +++ b/examples/react/start-basic-auth/README.md @@ -39,3 +39,13 @@ This example demonstrates: - Protected routes - Login/logout functionality - Redirect after authentication + +## Session configuration + +This example uses [iron-session](https://github.com/vvo/iron-session) through Start's `getCookie` and `setCookie` helpers. Set `SESSION_PASSWORD` to a random secret of at least 32 characters before starting the app, for example: + +```sh +export SESSION_PASSWORD="$(openssl rand -base64 32)" +``` + +Keep the same secret across instances and deployments that must read the same sessions. The cookie requires HTTPS in production. Each handler reads its own session, then awaits `session.save()` before redirecting or returning. diff --git a/examples/react/start-basic-auth/package.json b/examples/react/start-basic-auth/package.json index 6966bcade5..9ab89bdac9 100644 --- a/examples/react/start-basic-auth/package.json +++ b/examples/react/start-basic-auth/package.json @@ -14,26 +14,26 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.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", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0" + "tailwind-merge": "^3.6.0" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", + "@vitejs/plugin-react": "^6.0.1", "dotenv": "^17.2.3", - "postcss": "^8.5.1", "prisma": "^7.0.0", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-basic-auth/postcss.config.mjs b/examples/react/start-basic-auth/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/start-basic-auth/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx index ef2daa1ea1..405fb5f4a7 100644 --- a/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-basic-auth/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error(error) diff --git a/examples/react/start-basic-auth/src/prisma-generated/client.ts b/examples/react/start-basic-auth/src/prisma-generated/client.ts index 1b9d548165..2be7866ae3 100644 --- a/examples/react/start-basic-auth/src/prisma-generated/client.ts +++ b/examples/react/start-basic-auth/src/prisma-generated/client.ts @@ -37,10 +37,10 @@ export * from './enums' export const PrismaClient = $Class.getPrismaClientClass() export type PrismaClient< LogOpts extends Prisma.LogLevel = never, - OmitOpts extends - Prisma.PrismaClientOptions['omit'] = Prisma.PrismaClientOptions['omit'], - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + OmitOpts extends Prisma.PrismaClientOptions['omit'] = + Prisma.PrismaClientOptions['omit'], + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = $Class.PrismaClient export { Prisma } diff --git a/examples/react/start-basic-auth/src/prisma-generated/internal/class.ts b/examples/react/start-basic-auth/src/prisma-generated/internal/class.ts index 95cb7864ef..594896a020 100644 --- a/examples/react/start-basic-auth/src/prisma-generated/internal/class.ts +++ b/examples/react/start-basic-auth/src/prisma-generated/internal/class.ts @@ -44,9 +44,8 @@ config.compilerWasm = { await import('@prisma/client/runtime/query_compiler_bg.sqlite.mjs'), getQueryCompilerWasmModule: async () => { - const { wasm } = await import( - '@prisma/client/runtime/query_compiler_bg.sqlite.wasm-base64.mjs' - ) + const { wasm } = + await import('@prisma/client/runtime/query_compiler_bg.sqlite.wasm-base64.mjs') return await decodeBase64AsWasm(wasm) }, } @@ -81,8 +80,8 @@ export interface PrismaClientConstructor { } ? U : Prisma.PrismaClientOptions['omit'], - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, >( options: Prisma.Subset, ): PrismaClient @@ -105,8 +104,8 @@ export interface PrismaClientConstructor { export interface PrismaClient< in LogOpts extends Prisma.LogLevel = never, in out OmitOpts extends Prisma.PrismaClientOptions['omit'] = undefined, - in out ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + in out ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > { [K: symbol]: { types: Prisma.TypeMap['other'] } diff --git a/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts b/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts index fc96903a35..f420c55329 100644 --- a/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts +++ b/examples/react/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts @@ -417,17 +417,17 @@ export const ModelName = { export type ModelName = (typeof ModelName)[keyof typeof ModelName] -export interface TypeMapCb - extends runtime.Types.Utils.Fn< - { extArgs: runtime.Types.Extensions.InternalArgs }, - runtime.Types.Utils.Record - > { +export interface TypeMapCb extends runtime.Types.Utils + .Fn< + { extArgs: runtime.Types.Extensions.InternalArgs }, + runtime.Types.Utils.Record +> { returns: TypeMap } export type TypeMap< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}, > = { globalOmitOptions: { diff --git a/examples/react/start-basic-auth/src/prisma-generated/models/User.ts b/examples/react/start-basic-auth/src/prisma-generated/models/User.ts index 14c9ca5fb9..4312db9bd9 100644 --- a/examples/react/start-basic-auth/src/prisma-generated/models/User.ts +++ b/examples/react/start-basic-auth/src/prisma-generated/models/User.ts @@ -57,8 +57,8 @@ export type UserCountAggregateInputType = { } export type UserAggregateArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Filter which User to aggregate. @@ -119,8 +119,8 @@ export type GetUserAggregateType = { } export type UserGroupByArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { where?: Prisma.UserWhereInput orderBy?: @@ -254,8 +254,8 @@ export type StringFieldUpdateOperationsInput = { } export type UserSelect< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetSelect< { email?: boolean @@ -265,8 +265,8 @@ export type UserSelect< > export type UserSelectCreateManyAndReturn< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetSelect< { email?: boolean @@ -276,8 +276,8 @@ export type UserSelectCreateManyAndReturn< > export type UserSelectUpdateManyAndReturn< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetSelect< { email?: boolean @@ -292,16 +292,16 @@ export type UserSelectScalar = { } export type UserOmit< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetOmit< 'email' | 'password', ExtArgs['result']['user'] > export type $UserPayload< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { name: 'User' objects: {} @@ -320,15 +320,15 @@ export type UserGetPayload< > = runtime.Types.Result.GetResult export type UserCountArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = Omit & { select?: UserCountAggregateInputType | true } export interface UserDelegate< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}, > { [K: symbol]: { @@ -854,8 +854,8 @@ export interface UserDelegate< export interface Prisma__UserClient< T, Null = never, - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}, > extends Prisma.PrismaPromise { readonly [Symbol.toStringTag]: 'PrismaPromise' @@ -910,8 +910,8 @@ export interface UserFieldRefs { * User findUnique */ export type UserFindUniqueArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -931,8 +931,8 @@ export type UserFindUniqueArgs< * User findUniqueOrThrow */ export type UserFindUniqueOrThrowArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -952,8 +952,8 @@ export type UserFindUniqueOrThrowArgs< * User findFirst */ export type UserFindFirstArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1005,8 +1005,8 @@ export type UserFindFirstArgs< * User findFirstOrThrow */ export type UserFindFirstOrThrowArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1058,8 +1058,8 @@ export type UserFindFirstOrThrowArgs< * User findMany */ export type UserFindManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1106,8 +1106,8 @@ export type UserFindManyArgs< * User create */ export type UserCreateArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1127,8 +1127,8 @@ export type UserCreateArgs< * User createMany */ export type UserCreateManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * The data used to create many Users. @@ -1140,8 +1140,8 @@ export type UserCreateManyArgs< * User createManyAndReturn */ export type UserCreateManyAndReturnArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1161,8 +1161,8 @@ export type UserCreateManyAndReturnArgs< * User update */ export type UserUpdateArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1186,8 +1186,8 @@ export type UserUpdateArgs< * User updateMany */ export type UserUpdateManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * The data used to update Users. @@ -1210,8 +1210,8 @@ export type UserUpdateManyArgs< * User updateManyAndReturn */ export type UserUpdateManyAndReturnArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1242,8 +1242,8 @@ export type UserUpdateManyAndReturnArgs< * User upsert */ export type UserUpsertArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1271,8 +1271,8 @@ export type UserUpsertArgs< * User delete */ export type UserDeleteArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1292,8 +1292,8 @@ export type UserDeleteArgs< * User deleteMany */ export type UserDeleteManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Filter which Users to delete @@ -1309,8 +1309,8 @@ export type UserDeleteManyArgs< * User without action */ export type UserDefaultArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User diff --git a/examples/react/start-basic-auth/src/routeTree.gen.ts b/examples/react/start-basic-auth/src/routeTree.gen.ts index 6691c8a12f..a74e753aec 100644 --- a/examples/react/start-basic-auth/src/routeTree.gen.ts +++ b/examples/react/start-basic-auth/src/routeTree.gen.ts @@ -9,23 +9,22 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as SignupRouteImport } from './routes/signup' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as SignupRouteImport } from './routes/signup' import { Route as AuthedPostsRouteRouteImport } from './routes/_authed/posts.route' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -33,13 +32,14 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRouteRoute = AuthedPostsRouteRouteImport.update({ @@ -120,18 +120,18 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } '/login': { @@ -141,18 +141,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthedRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/examples/react/start-basic-auth/src/routes/__root.tsx b/examples/react/start-basic-auth/src/routes/__root.tsx index 5728345fcf..3367c62f27 100644 --- a/examples/react/start-basic-auth/src/routes/__root.tsx +++ b/examples/react/start-basic-auth/src/routes/__root.tsx @@ -13,18 +13,18 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { useAppSession } from '~/utils/session.js' +import { getAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await useAppSession() + const session = await getAppSession() - if (!session.data.userEmail) { + if (!session.userEmail) { return null } return { - email: session.data.userEmail, + email: session.userEmail, } }) diff --git a/examples/react/start-basic-auth/src/routes/_authed.tsx b/examples/react/start-basic-auth/src/routes/_authed.tsx index 230be64c62..0b5c6f9047 100644 --- a/examples/react/start-basic-auth/src/routes/_authed.tsx +++ b/examples/react/start-basic-auth/src/routes/_authed.tsx @@ -2,10 +2,10 @@ import { createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST' }) - .inputValidator((d: { email: string; password: string }) => d) + .validator((d: { email: string; password: string }) => d) .handler(async ({ data }) => { // Find the user const user = await prismaClient.user.findUnique({ @@ -33,13 +33,10 @@ export const loginFn = createServerFn({ method: 'POST' }) } } - // Create a session - const session = await useAppSession() - // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + const session = await getAppSession() + session.userEmail = user.email + await session.save() }) export const Route = createFileRoute('/_authed')({ @@ -49,7 +46,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return } diff --git a/examples/react/start-basic-auth/src/routes/logout.tsx b/examples/react/start-basic-auth/src/routes/logout.tsx index 28f3c9f8fe..73cdaf1600 100644 --- a/examples/react/start-basic-auth/src/routes/logout.tsx +++ b/examples/react/start-basic-auth/src/routes/logout.tsx @@ -1,11 +1,10 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' const logoutFn = createServerFn().handler(async () => { - const session = await useAppSession() - - session.clear() + const session = await getAppSession() + session.destroy() throw redirect({ href: '/', diff --git a/examples/react/start-basic-auth/src/routes/signup.tsx b/examples/react/start-basic-auth/src/routes/signup.tsx index 7b64265840..4dc8e350ac 100644 --- a/examples/react/start-basic-auth/src/routes/signup.tsx +++ b/examples/react/start-basic-auth/src/routes/signup.tsx @@ -3,10 +3,10 @@ import { createServerFn, useServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST' }) - .inputValidator( + .validator( (d: { email: string; password: string; redirectUrl?: string }) => d, ) .handler(async ({ data }) => { @@ -20,9 +20,6 @@ export const signupFn = createServerFn({ method: 'POST' }) // Encrypt the password using Sha256 into plaintext const password = await hashPassword(data.password) - // Create a session - const session = await useAppSession() - if (found) { if (found.password !== password) { return { @@ -33,9 +30,9 @@ export const signupFn = createServerFn({ method: 'POST' }) } // Store the user's email in the session - await session.update({ - userEmail: found.email, - }) + const session = await getAppSession() + session.userEmail = found.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -52,9 +49,9 @@ export const signupFn = createServerFn({ method: 'POST' }) }) // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + const session = await getAppSession() + session.userEmail = user.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/examples/react/start-basic-auth/src/styles/app.css b/examples/react/start-basic-auth/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/react/start-basic-auth/src/styles/app.css +++ b/examples/react/start-basic-auth/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/start-basic-auth/src/utils/posts.ts b/examples/react/start-basic-auth/src/utils/posts.ts index fbcc43c34b..a7e0e99cfa 100644 --- a/examples/react/start-basic-auth/src/utils/posts.ts +++ b/examples/react/start-basic-auth/src/utils/posts.ts @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) + .validator((postId: string) => postId) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const post = await axios diff --git a/examples/react/start-basic-auth/src/utils/session.ts b/examples/react/start-basic-auth/src/utils/session.ts index c38bac1e48..7df7bc4da2 100644 --- a/examples/react/start-basic-auth/src/utils/session.ts +++ b/examples/react/start-basic-auth/src/utils/session.ts @@ -1,13 +1,29 @@ -// src/services/session.server.ts -import { useSession } from '@tanstack/react-start/server' +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/react-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function useAppSession() { - return useSession({ - password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', - }) +export function getAppSession() { + const password = process.env.SESSION_PASSWORD + if (!password || password.length < 32) { + throw new Error('Set SESSION_PASSWORD to at least 32 characters') + } + + return getIronSession( + { read: getCookie, write: setCookie }, + { + cookieName: 'app-session', + password, + ttl: 7 * 24 * 60 * 60, + cookieOptions: { + httpOnly: true, + sameSite: 'lax', + secure: process.env.NODE_ENV === 'production', + path: '/', + }, + }, + ) } diff --git a/examples/react/start-basic-auth/tsconfig.json b/examples/react/start-basic-auth/tsconfig.json index 3a9fb7cd71..cef9369516 100644 --- a/examples/react/start-basic-auth/tsconfig.json +++ b/examples/react/start-basic-auth/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-basic-auth/vite.config.ts b/examples/react/start-basic-auth/vite.config.ts index f10c86e79f..ed6799764a 100644 --- a/examples/react/start-basic-auth/vite.config.ts +++ b/examples/react/start-basic-auth/vite.config.ts @@ -1,17 +1,14 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteReact()], }) diff --git a/examples/react/start-basic-authjs/.devcontainer/devcontainer.json b/examples/react/start-basic-authjs/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-basic-authjs/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-basic-authjs/package.json b/examples/react/start-basic-authjs/package.json index a017f682d3..e9fa789ea6 100644 --- a/examples/react/start-basic-authjs/package.json +++ b/examples/react/start-basic-authjs/package.json @@ -11,24 +11,23 @@ }, "dependencies": { "@auth/core": "^0.41.1", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", - "start-authjs": "^1.0.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwind-merge": "^2.6.0" + "start-authjs": "^1.0.0", + "tailwind-merge": "^3.6.0" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "@vitejs/plugin-react": "^4.6.0", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-react": "^6.0.1", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-basic-authjs/postcss.config.mjs b/examples/react/start-basic-authjs/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/start-basic-authjs/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx index 260c2ea41f..4a22649ed4 100644 --- a/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-basic-authjs/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error('DefaultCatchBoundary Error:', error) diff --git a/examples/react/start-basic-authjs/src/routeTree.gen.ts b/examples/react/start-basic-authjs/src/routeTree.gen.ts index 2f59e4ba33..4abcbc8048 100644 --- a/examples/react/start-basic-authjs/src/routeTree.gen.ts +++ b/examples/react/start-basic-authjs/src/routeTree.gen.ts @@ -9,14 +9,14 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as ProtectedRouteImport } from './routes/protected' -import { Route as LoginRouteImport } from './routes/login' import { Route as IndexRouteImport } from './routes/index' +import { Route as LoginRouteImport } from './routes/login' +import { Route as ProtectedRouteImport } from './routes/protected' import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$' -const ProtectedRoute = ProtectedRouteImport.update({ - id: '/protected', - path: '/protected', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -24,9 +24,9 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProtectedRoute = ProtectedRouteImport.update({ + id: '/protected', + path: '/protected', getParentRoute: () => rootRouteImport, } as any) const ApiAuthSplatRoute = ApiAuthSplatRouteImport.update({ @@ -71,11 +71,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/protected': { - id: '/protected' - path: '/protected' - fullPath: '/protected' - preLoaderRoute: typeof ProtectedRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/login': { @@ -85,11 +85,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/protected': { + id: '/protected' + path: '/protected' + fullPath: '/protected' + preLoaderRoute: typeof ProtectedRouteImport parentRoute: typeof rootRouteImport } '/api/auth/$': { diff --git a/examples/react/start-basic-authjs/src/styles/app.css b/examples/react/start-basic-authjs/src/styles/app.css index d4b5078586..23fa2415ca 100644 --- a/examples/react/start-basic-authjs/src/styles/app.css +++ b/examples/react/start-basic-authjs/src/styles/app.css @@ -1 +1 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); diff --git a/examples/react/start-basic-authjs/tsconfig.json b/examples/react/start-basic-authjs/tsconfig.json index 70cbbc5ce3..ff21ac7cfa 100644 --- a/examples/react/start-basic-authjs/tsconfig.json +++ b/examples/react/start-basic-authjs/tsconfig.json @@ -15,7 +15,6 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "allowSyntheticDefaultImports": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] } diff --git a/examples/react/start-basic-authjs/vite.config.ts b/examples/react/start-basic-authjs/vite.config.ts index 75bdbbe66b..90f81aedf7 100644 --- a/examples/react/start-basic-authjs/vite.config.ts +++ b/examples/react/start-basic-authjs/vite.config.ts @@ -1,18 +1,15 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 10000, strictPort: true, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteReact()], }) diff --git a/examples/react/start-basic-cloudflare/.devcontainer/devcontainer.json b/examples/react/start-basic-cloudflare/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-basic-cloudflare/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-basic-cloudflare/package.json b/examples/react/start-basic-cloudflare/package.json index 783a18867c..2108922446 100644 --- a/examples/react/start-basic-cloudflare/package.json +++ b/examples/react/start-basic-cloudflare/package.json @@ -9,27 +9,26 @@ "preview": "vite preview", "deploy": "npm run build && wrangler deploy", "cf-typegen": "wrangler types", - "postinstall": "npm run cf-typegen" + "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen" }, "dependencies": { - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@cloudflare/vite-plugin": "^1.13.7", - "@tailwindcss/postcss": "^4.1.15", + "@cloudflare/vite-plugin": "^1.29.0", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.6.0", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4", - "wrangler": "^4.49.1" + "@vitejs/plugin-react": "^6.0.1", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "wrangler": "^4.74.0" } } diff --git a/examples/react/start-basic-cloudflare/postcss.config.mjs b/examples/react/start-basic-cloudflare/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/start-basic-cloudflare/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx index 260c2ea41f..4a22649ed4 100644 --- a/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error('DefaultCatchBoundary Error:', error) diff --git a/examples/react/start-basic-cloudflare/src/routeTree.gen.ts b/examples/react/start-basic-cloudflare/src/routeTree.gen.ts index 06a64190d7..57b849492d 100644 --- a/examples/react/start-basic-cloudflare/src/routeTree.gen.ts +++ b/examples/react/start-basic-cloudflare/src/routeTree.gen.ts @@ -9,42 +9,31 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ @@ -52,38 +41,24 @@ const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ path: '/customScript.js', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -91,28 +66,53 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => ApiUsersRoute, + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,32 +234,18 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } '/customScript.js': { @@ -269,47 +255,40 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof CustomScriptDotjsRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout': { - id: '/_pathlessLayout' + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/api/users': { id: '/api/users' @@ -318,26 +297,40 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute } - '/api/users/$userId': { - id: '/api/users/$userId' + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -346,12 +339,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/react/start-basic-cloudflare/src/routes/api/users.$userId.ts b/examples/react/start-basic-cloudflare/src/routes/api/users.$userId.ts index 2ae7eb9c04..ee34d7a189 100644 --- a/examples/react/start-basic-cloudflare/src/routes/api/users.$userId.ts +++ b/examples/react/start-basic-cloudflare/src/routes/api/users.$userId.ts @@ -1,5 +1,4 @@ import { createFileRoute } from '@tanstack/react-router' -import { json } from '@tanstack/react-start' import type { User } from '~/utils/users' export const Route = createFileRoute('/api/users/$userId')({ @@ -17,14 +16,14 @@ export const Route = createFileRoute('/api/users/$userId')({ const user = (await res.json()) as User - return json({ + return Response.json({ id: user.id, name: user.name, email: user.email, }) } catch (e) { console.error(e) - return json({ error: 'User not found' }, { status: 404 }) + return Response.json({ error: 'User not found' }, { status: 404 }) } }, }, diff --git a/examples/react/start-basic-cloudflare/src/routes/api/users.ts b/examples/react/start-basic-cloudflare/src/routes/api/users.ts index c1e7473b0c..4cecd01852 100644 --- a/examples/react/start-basic-cloudflare/src/routes/api/users.ts +++ b/examples/react/start-basic-cloudflare/src/routes/api/users.ts @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/react-router' import { getRequestHeaders } from '@tanstack/react-start/server' -import { createMiddleware, json } from '@tanstack/react-start' +import { createMiddleware } from '@tanstack/react-start' import type { User } from '~/utils/users' const userLoggerMiddleware = createMiddleware().server(async ({ next }) => { @@ -54,7 +54,7 @@ export const Route = createFileRoute('/api/users')({ const list = data.slice(0, 10) - return json( + return Response.json( list.map((u) => ({ id: u.id, name: u.name, email: u.email })), ) }, diff --git a/examples/react/start-basic-cloudflare/src/routes/deferred.tsx b/examples/react/start-basic-cloudflare/src/routes/deferred.tsx index c38808243e..f3e09d1d4e 100644 --- a/examples/react/start-basic-cloudflare/src/routes/deferred.tsx +++ b/examples/react/start-basic-cloudflare/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/react-start' import { Suspense, useState } from 'react' const personServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/examples/react/start-basic-cloudflare/src/routes/posts.$postId.tsx b/examples/react/start-basic-cloudflare/src/routes/posts.$postId.tsx index 65905bf8c4..7e111fa20d 100644 --- a/examples/react/start-basic-cloudflare/src/routes/posts.$postId.tsx +++ b/examples/react/start-basic-cloudflare/src/routes/posts.$postId.tsx @@ -1,5 +1,5 @@ import { Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '../utils/posts' +import { fetchPost } from '~/utils/posts' import { NotFound } from '~/components/NotFound' import { PostErrorComponent } from '~/components/PostError' diff --git a/examples/react/start-basic-cloudflare/src/routes/posts.tsx b/examples/react/start-basic-cloudflare/src/routes/posts.tsx index 9b9162be7c..095b2e248f 100644 --- a/examples/react/start-basic-cloudflare/src/routes/posts.tsx +++ b/examples/react/start-basic-cloudflare/src/routes/posts.tsx @@ -1,5 +1,5 @@ import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import { fetchPosts } from '../utils/posts' +import { fetchPosts } from '~/utils/posts' export const Route = createFileRoute('/posts')({ loader: async () => fetchPosts(), diff --git a/examples/react/start-basic-cloudflare/src/routes/posts_.$postId.deep.tsx b/examples/react/start-basic-cloudflare/src/routes/posts_.$postId.deep.tsx index 29e6c39b5a..48d317ec30 100644 --- a/examples/react/start-basic-cloudflare/src/routes/posts_.$postId.deep.tsx +++ b/examples/react/start-basic-cloudflare/src/routes/posts_.$postId.deep.tsx @@ -1,5 +1,5 @@ import { Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '../utils/posts' +import { fetchPost } from '~/utils/posts' import { PostErrorComponent } from '~/components/PostError' export const Route = createFileRoute('/posts_/$postId/deep')({ diff --git a/examples/react/start-basic-cloudflare/src/routes/users.$userId.tsx b/examples/react/start-basic-cloudflare/src/routes/users.$userId.tsx index 1df768344d..fe22eb86c3 100644 --- a/examples/react/start-basic-cloudflare/src/routes/users.$userId.tsx +++ b/examples/react/start-basic-cloudflare/src/routes/users.$userId.tsx @@ -1,7 +1,7 @@ import { createFileRoute } from '@tanstack/react-router' -import { NotFound } from 'src/components/NotFound' -import { UserErrorComponent } from 'src/components/UserError' -import type { User } from '../utils/users' +import { NotFound } from '../components/NotFound' +import { UserErrorComponent } from '../components/UserError' +import type { User } from '~/utils/users' export const Route = createFileRoute('/users/$userId')({ loader: async ({ params: { userId } }) => { diff --git a/examples/react/start-basic-cloudflare/src/routes/users.tsx b/examples/react/start-basic-cloudflare/src/routes/users.tsx index 64ca3ce156..55b22b6e40 100644 --- a/examples/react/start-basic-cloudflare/src/routes/users.tsx +++ b/examples/react/start-basic-cloudflare/src/routes/users.tsx @@ -1,5 +1,5 @@ import { Link, Outlet, createFileRoute } from '@tanstack/react-router' -import type { User } from '../utils/users' +import type { User } from '~/utils/users' export const Route = createFileRoute('/users')({ loader: async () => { diff --git a/examples/react/start-basic-cloudflare/src/styles/app.css b/examples/react/start-basic-cloudflare/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/react/start-basic-cloudflare/src/styles/app.css +++ b/examples/react/start-basic-cloudflare/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/start-basic-cloudflare/src/utils/posts.tsx b/examples/react/start-basic-cloudflare/src/utils/posts.tsx index 098542fd74..ea7dd0a721 100644 --- a/examples/react/start-basic-cloudflare/src/utils/posts.tsx +++ b/examples/react/start-basic-cloudflare/src/utils/posts.tsx @@ -8,7 +8,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'POST' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const res = await fetch( diff --git a/examples/react/start-basic-cloudflare/tsconfig.json b/examples/react/start-basic-cloudflare/tsconfig.json index 3a9fb7cd71..cef9369516 100644 --- a/examples/react/start-basic-cloudflare/tsconfig.json +++ b/examples/react/start-basic-cloudflare/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-basic-cloudflare/vite.config.ts b/examples/react/start-basic-cloudflare/vite.config.ts index 15c066ef0a..ad9418ef35 100644 --- a/examples/react/start-basic-cloudflare/vite.config.ts +++ b/examples/react/start-basic-cloudflare/vite.config.ts @@ -1,17 +1,18 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { cloudflare } from '@cloudflare/vite-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, + resolve: { + tsconfigPaths: true, + }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), + tailwindcss(), cloudflare({ viteEnvironment: { name: 'ssr' } }), tanstackStart(), viteReact(), diff --git a/examples/react/start-basic-cloudflare/worker-configuration.d.ts b/examples/react/start-basic-cloudflare/worker-configuration.d.ts index bdfccc2017..f7a8f16397 100644 --- a/examples/react/start-basic-cloudflare/worker-configuration.d.ts +++ b/examples/react/start-basic-cloudflare/worker-configuration.d.ts @@ -1,6 +1,6 @@ /* eslint-disable */ // Generated by Wrangler by running `wrangler types` (hash: b11df627d8b3c51b1bf3230a546b0f20) -// Runtime types generated with workerd@1.20251118.0 2025-09-24 nodejs_compat +// Runtime types generated with workerd@1.20260317.1 2025-09-24 nodejs_compat declare namespace Cloudflare { interface Env { MY_VAR: "Hello from Cloudflare"; @@ -436,22 +436,22 @@ interface ExecutionContext { passThroughOnException(): void; readonly props: Props; } -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; -type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; +type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; +type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; +type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; +interface ExportedHandler { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; } interface StructuredSerializeOptions { transfer?: any[]; @@ -499,8 +499,10 @@ interface DurableObjectNamespaceNewUniqueIdOptions { jurisdiction?: DurableObjectJurisdiction; } type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; +type DurableObjectRoutingMode = "primary-only"; interface DurableObjectNamespaceGetDurableObjectOptions { locationHint?: DurableObjectLocationHint; + routingMode?: DurableObjectRoutingMode; } interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { } @@ -1387,6 +1389,12 @@ declare abstract class PromiseRejectionEvent extends Event { */ declare class FormData { constructor(); + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string | Blob): void; /** * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. * @@ -1423,6 +1431,12 @@ declare class FormData { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) */ has(name: string): boolean; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string | Blob): void; /** * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. * @@ -1749,7 +1763,7 @@ interface Request> e * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) */ signal: AbortSignal; - cf: Cf | undefined; + cf?: Cf; /** * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. * @@ -2084,6 +2098,8 @@ interface Transformer { expectedLength?: number; } interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; /** * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. * @@ -2102,8 +2118,6 @@ interface StreamPipeOptions { * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. */ preventClose?: boolean; - preventAbort?: boolean; - preventCancel?: boolean; signal?: AbortSignal; } type ReadableStreamReadResult = { @@ -2378,13 +2392,13 @@ declare abstract class TransformStreamDefaultController { terminate(): void; } interface ReadableWritablePair { + readable: ReadableStream; /** * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ writable: WritableStream; - readable: ReadableStream; } /** * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. @@ -3032,7 +3046,7 @@ declare var WebSocket: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ interface WebSocket extends EventTarget { - accept(): void; + accept(options?: WebSocketAcceptOptions): void; /** * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. * @@ -3071,6 +3085,22 @@ interface WebSocket extends EventTarget { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) */ extensions: string | null; + /** + * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) + */ + binaryType: "blob" | "arraybuffer"; +} +interface WebSocketAcceptOptions { + /** + * When set to `true`, receiving a server-initiated WebSocket Close frame will not + * automatically send a reciprocal Close frame, leaving the connection in a half-open + * state. This is useful for proxying scenarios where you need to coordinate closing + * both sides independently. Defaults to `false` when the + * `no_web_socket_half_open_by_default` compatibility flag is enabled. + */ + allowHalfOpen?: boolean; } declare const WebSocketPair: { new (): { @@ -3189,6 +3219,8 @@ interface Container { signal(signo: number): void; getTcpPort(port: number): Fetcher; setInactivityTimeout(durationMs: number | bigint): Promise; + interceptOutboundHttp(addr: string, binding: Fetcher): Promise; + interceptAllOutboundHttp(binding: Fetcher): Promise; } interface ContainerStartupOptions { entrypoint?: string[]; @@ -3281,7 +3313,8 @@ interface WorkerStubEntrypointOptions { props?: any; } interface WorkerLoader { - get(name: string, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; + get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; + load(code: WorkerLoaderWorkerCode): WorkerStub; } interface WorkerLoaderModule { js?: string; @@ -3314,6 +3347,181 @@ declare abstract class Performance { get timeOrigin(): number; /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ now(): number; + /** + * The **`toJSON()`** method of the Performance interface is a Serialization; it returns a JSON representation of the Performance object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON) + */ + toJSON(): object; +} +// AI Search V2 API Error Interfaces +interface AiSearchInternalError extends Error { +} +interface AiSearchNotFoundError extends Error { +} +interface AiSearchNameNotSetError extends Error { +} +// AI Search V2 Request Types +type AiSearchSearchRequest = { + messages: Array<{ + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + }>; + ai_search_options?: { + retrieval?: { + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + /** Maximum number of results (1-50, default 10) */ + max_num_results?: number; + filters?: VectorizeVectorMetadataFilter; + /** Context expansion (0-3, default 0) */ + context_expansion?: number; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + /** Enable reranking (default false) */ + enabled?: boolean; + model?: '@cf/baai/bge-reranker-base' | ''; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + [key: string]: unknown; + }; + [key: string]: unknown; + }; +}; +type AiSearchChatCompletionsRequest = { + messages: Array<{ + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + }>; + model?: string; + stream?: boolean; + ai_search_options?: { + retrieval?: { + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + match_threshold?: number; + max_num_results?: number; + filters?: VectorizeVectorMetadataFilter; + context_expansion?: number; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + enabled?: boolean; + model?: '@cf/baai/bge-reranker-base' | ''; + match_threshold?: number; + [key: string]: unknown; + }; + [key: string]: unknown; + }; + [key: string]: unknown; +}; +// AI Search V2 Response Types +type AiSearchSearchResponse = { + search_query: string; + chunks: Array<{ + id: string; + type: string; + /** Match score (0-1) */ + score: number; + text: string; + item: { + timestamp?: number; + key: string; + metadata?: Record; + }; + scoring_details?: { + /** Keyword match score (0-1) */ + keyword_score?: number; + /** Vector similarity score (0-1) */ + vector_score?: number; + }; + }>; +}; +type AiSearchListResponse = Array<{ + id: string; + internal_id?: string; + account_id?: string; + account_tag?: string; + /** Whether the instance is enabled (default true) */ + enable?: boolean; + type?: 'r2' | 'web-crawler'; + source?: string; + [key: string]: unknown; +}>; +type AiSearchConfig = { + /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ + id: string; + type: 'r2' | 'web-crawler'; + source: string; + source_params?: object; + /** Token ID (UUID format) */ + token_id?: string; + ai_gateway_id?: string; + /** Enable query rewriting (default false) */ + rewrite_query?: boolean; + /** Enable reranking (default false) */ + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; +}; +type AiSearchInstance = { + id: string; + enable?: boolean; + type?: 'r2' | 'web-crawler'; + source?: string; + [key: string]: unknown; +}; +// AI Search Instance Service - Instance-level operations +declare abstract class AiSearchInstanceService { + /** + * Search the AI Search instance for relevant chunks. + * @param params Search request with messages and AI search options + * @returns Search response with matching chunks + */ + search(params: AiSearchSearchRequest): Promise; + /** + * Generate chat completions with AI Search context. + * @param params Chat completions request with optional streaming + * @returns Response object (if streaming) or chat completion result + */ + chatCompletions(params: AiSearchChatCompletionsRequest): Promise; + /** + * Delete this AI Search instance. + */ + delete(): Promise; +} +// AI Search Account Service - Account-level operations +declare abstract class AiSearchAccountService { + /** + * List all AI Search instances in the account. + * @returns Array of AI Search instances + */ + list(): Promise; + /** + * Get an AI Search instance by ID. + * @param name Instance ID + * @returns Instance service for performing operations + */ + get(name: string): AiSearchInstanceService; + /** + * Create a new AI Search instance. + * @param config Instance configuration + * @returns Instance service for performing operations + */ + create(config: AiSearchConfig): Promise; } type AiImageClassificationInput = { image: number[]; @@ -3578,6 +3786,363 @@ declare abstract class BaseAiTranslation { inputs: AiTranslationInput; postProcessedOutputs: AiTranslationOutput; } +/** + * Workers AI support for OpenAI's Responses API + * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts + * + * It's a stripped down version from its source. + * It currently supports basic function calling, json mode and accepts images as input. + * + * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. + * We plan to add those incrementally as model + platform capabilities evolve. + */ +type ResponsesInput = { + background?: boolean | null; + conversation?: string | ResponseConversationParam | null; + include?: Array | null; + input?: string | ResponseInput; + instructions?: string | null; + max_output_tokens?: number | null; + parallel_tool_calls?: boolean | null; + previous_response_id?: string | null; + prompt_cache_key?: string; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + stream?: boolean | null; + stream_options?: StreamOptions | null; + temperature?: number | null; + text?: ResponseTextConfig; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + truncation?: "auto" | "disabled" | null; +}; +type ResponsesOutput = { + id?: string; + created_at?: number; + output_text?: string; + error?: ResponseError | null; + incomplete_details?: ResponseIncompleteDetails | null; + instructions?: string | Array | null; + object?: "response"; + output?: Array; + parallel_tool_calls?: boolean; + temperature?: number | null; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + max_output_tokens?: number | null; + previous_response_id?: string | null; + prompt?: ResponsePrompt | null; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + status?: ResponseStatus; + text?: ResponseTextConfig; + truncation?: "auto" | "disabled" | null; + usage?: ResponseUsage; +}; +type EasyInputMessage = { + content: string | ResponseInputMessageContentList; + role: "user" | "assistant" | "system" | "developer"; + type?: "message"; +}; +type ResponsesFunctionTool = { + name: string; + parameters: { + [key: string]: unknown; + } | null; + strict: boolean | null; + type: "function"; + description?: string | null; +}; +type ResponseIncompleteDetails = { + reason?: "max_output_tokens" | "content_filter"; +}; +type ResponsePrompt = { + id: string; + variables?: { + [key: string]: string | ResponseInputText | ResponseInputImage; + } | null; + version?: string | null; +}; +type Reasoning = { + effort?: ReasoningEffort | null; + generate_summary?: "auto" | "concise" | "detailed" | null; + summary?: "auto" | "concise" | "detailed" | null; +}; +type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText; +type ResponseContentReasoningText = { + text: string; + type: "reasoning_text"; +}; +type ResponseConversationParam = { + id: string; +}; +type ResponseCreatedEvent = { + response: Response; + sequence_number: number; + type: "response.created"; +}; +type ResponseCustomToolCallOutput = { + call_id: string; + output: string | Array; + type: "custom_tool_call_output"; + id?: string; +}; +type ResponseError = { + code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found"; + message: string; +}; +type ResponseErrorEvent = { + code: string | null; + message: string; + param: string | null; + sequence_number: number; + type: "error"; +}; +type ResponseFailedEvent = { + response: Response; + sequence_number: number; + type: "response.failed"; +}; +type ResponseFormatText = { + type: "text"; +}; +type ResponseFormatJSONObject = { + type: "json_object"; +}; +type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; +type ResponseFormatTextJSONSchemaConfig = { + name: string; + schema: { + [key: string]: unknown; + }; + type: "json_schema"; + description?: string; + strict?: boolean | null; +}; +type ResponseFunctionCallArgumentsDeltaEvent = { + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.delta"; +}; +type ResponseFunctionCallArgumentsDoneEvent = { + arguments: string; + item_id: string; + name: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.done"; +}; +type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; +type ResponseFunctionCallOutputItemList = Array; +type ResponseFunctionToolCall = { + arguments: string; + call_id: string; + name: string; + type: "function_call"; + id?: string; + status?: "in_progress" | "completed" | "incomplete"; +}; +interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { + id: string; +} +type ResponseFunctionToolCallOutputItem = { + id: string; + call_id: string; + output: string | Array; + type: "function_call_output"; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs"; +type ResponseIncompleteEvent = { + response: Response; + sequence_number: number; + type: "response.incomplete"; +}; +type ResponseInput = Array; +type ResponseInputContent = ResponseInputText | ResponseInputImage; +type ResponseInputImage = { + detail: "low" | "high" | "auto"; + type: "input_image"; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputImageContent = { + type: "input_image"; + detail?: "low" | "high" | "auto" | null; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem; +type ResponseInputItemFunctionCallOutput = { + call_id: string; + output: string | ResponseFunctionCallOutputItemList; + type: "function_call_output"; + id?: string | null; + status?: "in_progress" | "completed" | "incomplete" | null; +}; +type ResponseInputItemMessage = { + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputMessageContentList = Array; +type ResponseInputMessageItem = { + id: string; + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputText = { + text: string; + type: "input_text"; +}; +type ResponseInputTextContent = { + text: string; + type: "input_text"; +}; +type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; +type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; +type ResponseOutputItemAddedEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.added"; +}; +type ResponseOutputItemDoneEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.done"; +}; +type ResponseOutputMessage = { + id: string; + content: Array; + role: "assistant"; + status: "in_progress" | "completed" | "incomplete"; + type: "message"; +}; +type ResponseOutputRefusal = { + refusal: string; + type: "refusal"; +}; +type ResponseOutputText = { + text: string; + type: "output_text"; + logprobs?: Array; +}; +type ResponseReasoningItem = { + id: string; + summary: Array; + type: "reasoning"; + content?: Array; + encrypted_content?: string | null; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseReasoningSummaryItem = { + text: string; + type: "summary_text"; +}; +type ResponseReasoningContentItem = { + text: string; + type: "reasoning_text"; +}; +type ResponseReasoningTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.reasoning_text.delta"; +}; +type ResponseReasoningTextDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + sequence_number: number; + text: string; + type: "response.reasoning_text.done"; +}; +type ResponseRefusalDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.refusal.delta"; +}; +type ResponseRefusalDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + refusal: string; + sequence_number: number; + type: "response.refusal.done"; +}; +type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete"; +type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent; +type ResponseCompletedEvent = { + response: Response; + sequence_number: number; + type: "response.completed"; +}; +type ResponseTextConfig = { + format?: ResponseFormatTextConfig; + verbosity?: "low" | "medium" | "high" | null; +}; +type ResponseTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + type: "response.output_text.delta"; +}; +type ResponseTextDoneEvent = { + content_index: number; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + text: string; + type: "response.output_text.done"; +}; +type Logprob = { + token: string; + logprob: number; + top_logprobs?: Array; +}; +type TopLogprob = { + token?: string; + logprob?: number; +}; +type ResponseUsage = { + input_tokens: number; + output_tokens: number; + total_tokens: number; +}; +type Tool = ResponsesFunctionTool; +type ToolChoiceFunction = { + name: string; + type: "function"; +}; +type ToolChoiceOptions = "none"; +type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; +type StreamOptions = { + include_obfuscation?: boolean; +}; type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { text: string | string[]; /** @@ -3606,8 +4171,8 @@ type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = { * The pooling method used in the embedding process. */ pooling?: "mean" | "cls"; -} | AsyncResponse; -interface AsyncResponse { +} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { /** * The async request id that can be used to obtain the results. */ @@ -3683,7 +4248,13 @@ type Ai_Cf_Meta_M2M100_1_2B_Output = { * The translated text in the target language */ translated_text?: string; -} | AsyncResponse; +} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; +interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { inputs: Ai_Cf_Meta_M2M100_1_2B_Input; postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; @@ -3716,7 +4287,13 @@ type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = { * The pooling method used in the embedding process. */ pooling?: "mean" | "cls"; -} | AsyncResponse; +} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; @@ -3749,7 +4326,13 @@ type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = { * The pooling method used in the embedding process. */ pooling?: "mean" | "cls"; -} | AsyncResponse; +} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; @@ -3935,13 +4518,13 @@ declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; } -type Ai_Cf_Baai_Bge_M3_Input = BGEM3InputQueryAndContexts | BGEM3InputEmbedding | { +type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | { /** * Batch of the embeddings requests to run using async-queue */ - requests: (BGEM3InputQueryAndContexts1 | BGEM3InputEmbedding1)[]; + requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[]; }; -interface BGEM3InputQueryAndContexts { +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { /** * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts */ @@ -3960,14 +4543,14 @@ interface BGEM3InputQueryAndContexts { */ truncate_inputs?: boolean; } -interface BGEM3InputEmbedding { +interface Ai_Cf_Baai_Bge_M3_Input_Embedding { text: string | string[]; /** * When provided with too long context should the model error out or truncate the context to fit? */ truncate_inputs?: boolean; } -interface BGEM3InputQueryAndContexts1 { +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { /** * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts */ @@ -3986,15 +4569,15 @@ interface BGEM3InputQueryAndContexts1 { */ truncate_inputs?: boolean; } -interface BGEM3InputEmbedding1 { +interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { text: string | string[]; /** * When provided with too long context should the model error out or truncate the context to fit? */ truncate_inputs?: boolean; } -type Ai_Cf_Baai_Bge_M3_Output = BGEM3OuputQuery | BGEM3OutputEmbeddingForContexts | BGEM3OuputEmbedding | AsyncResponse; -interface BGEM3OuputQuery { +type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Ouput_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Ouput_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse; +interface Ai_Cf_Baai_Bge_M3_Ouput_Query { response?: { /** * Index of the context in the request @@ -4006,7 +4589,7 @@ interface BGEM3OuputQuery { score?: number; }[]; } -interface BGEM3OutputEmbeddingForContexts { +interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { response?: number[][]; shape?: number[]; /** @@ -4014,7 +4597,7 @@ interface BGEM3OutputEmbeddingForContexts { */ pooling?: "mean" | "cls"; } -interface BGEM3OuputEmbedding { +interface Ai_Cf_Baai_Bge_M3_Ouput_Embedding { shape?: number[]; /** * Embeddings of the requested text values @@ -4025,6 +4608,12 @@ interface BGEM3OuputEmbedding { */ pooling?: "mean" | "cls"; } +interface Ai_Cf_Baai_Bge_M3_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Baai_Bge_M3 { inputs: Ai_Cf_Baai_Bge_M3_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; @@ -4049,8 +4638,8 @@ declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; } -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Prompt | Messages; -interface Prompt { +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4101,7 +4690,7 @@ interface Prompt { */ lora?: string; } -interface Messages { +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -4292,8 +4881,8 @@ declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; } -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | AsyncBatch; -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4302,7 +4891,7 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4344,11 +4933,11 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { */ presence_penalty?: number; } -interface JSONMode { +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { type?: "json_object" | "json_schema"; json_schema?: unknown; } -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { /** * An array of message objects representing the conversation history. */ @@ -4453,7 +5042,7 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { }; }; })[]; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4495,7 +5084,11 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { */ presence_penalty?: number; } -interface AsyncBatch { +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { requests?: { /** * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. @@ -4537,9 +5130,13 @@ interface AsyncBatch { * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; }[]; } +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { /** * The generated text response from the model @@ -4575,7 +5172,13 @@ type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { */ name?: string; }[]; -} | string | AsyncResponse; +} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; @@ -4679,8 +5282,8 @@ declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; } -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Qwen2_5_Coder_32B_Instruct_Prompt | Qwen2_5_Coder_32B_Instruct_Messages; -interface Qwen2_5_Coder_32B_Instruct_Prompt { +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4689,7 +5292,7 @@ interface Qwen2_5_Coder_32B_Instruct_Prompt { * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string; - response_format?: JSONMode; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4731,7 +5334,11 @@ interface Qwen2_5_Coder_32B_Instruct_Prompt { */ presence_penalty?: number; } -interface Qwen2_5_Coder_32B_Instruct_Messages { +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -4836,7 +5443,7 @@ interface Qwen2_5_Coder_32B_Instruct_Messages { }; }; })[]; - response_format?: JSONMode; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4878,6 +5485,10 @@ interface Qwen2_5_Coder_32B_Instruct_Messages { */ presence_penalty?: number; } +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { /** * The generated text response from the model @@ -4918,8 +5529,8 @@ declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; } -type Ai_Cf_Qwen_Qwq_32B_Input = Qwen_Qwq_32B_Prompt | Qwen_Qwq_32B_Messages; -interface Qwen_Qwq_32B_Prompt { +type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; +interface Ai_Cf_Qwen_Qwq_32B_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4969,7 +5580,7 @@ interface Qwen_Qwq_32B_Prompt { */ presence_penalty?: number; } -interface Qwen_Qwq_32B_Messages { +interface Ai_Cf_Qwen_Qwq_32B_Messages { /** * An array of message objects representing the conversation history. */ @@ -5100,7 +5711,7 @@ interface Qwen_Qwq_32B_Messages { }; })[]; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5184,8 +5795,8 @@ declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { inputs: Ai_Cf_Qwen_Qwq_32B_Input; postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; } -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Mistral_Small_3_1_24B_Instruct_Prompt | Mistral_Small_3_1_24B_Instruct_Messages; -interface Mistral_Small_3_1_24B_Instruct_Prompt { +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -5235,7 +5846,7 @@ interface Mistral_Small_3_1_24B_Instruct_Prompt { */ presence_penalty?: number; } -interface Mistral_Small_3_1_24B_Instruct_Messages { +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -5366,7 +5977,7 @@ interface Mistral_Small_3_1_24B_Instruct_Messages { }; })[]; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5450,14 +6061,14 @@ declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; } -type Ai_Cf_Google_Gemma_3_12B_It_Input = Google_Gemma_3_12B_It_Prompt | Google_Gemma_3_12B_It_Messages; -interface Google_Gemma_3_12B_It_Prompt { +type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages; +interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5501,7 +6112,7 @@ interface Google_Gemma_3_12B_It_Prompt { */ presence_penalty?: number; } -interface Google_Gemma_3_12B_It_Messages { +interface Ai_Cf_Google_Gemma_3_12B_It_Messages { /** * An array of message objects representing the conversation history. */ @@ -5522,19 +6133,7 @@ interface Google_Gemma_3_12B_It_Messages { */ url?: string; }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; + }[]; }[]; functions?: { name: string; @@ -5628,7 +6227,7 @@ interface Google_Gemma_3_12B_It_Messages { }; })[]; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5712,8 +6311,8 @@ declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; } -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Prompt | Ai_Cf_Meta_Llama_4_Messages | Ai_Cf_Meta_Llama_4_Async_Batch; -interface Ai_Cf_Meta_Llama_4_Prompt { +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -5722,7 +6321,7 @@ interface Ai_Cf_Meta_Llama_4_Prompt { * JSON schema that should be fulfilled for the response. */ guided_json?: object; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -5764,7 +6363,11 @@ interface Ai_Cf_Meta_Llama_4_Prompt { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Messages { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -5894,9 +6497,9 @@ interface Ai_Cf_Meta_Llama_4_Messages { }; }; })[]; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5940,10 +6543,10 @@ interface Ai_Cf_Meta_Llama_4_Messages { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Async_Batch { - requests: (Ai_Cf_Meta_Llama_4_Prompt_Inner | Ai_Cf_Meta_Llama_4_Messages_Inner)[]; +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { + requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[]; } -interface Ai_Cf_Meta_Llama_4_Prompt_Inner { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { /** * The input text prompt for the model to generate a response. */ @@ -5952,7 +6555,7 @@ interface Ai_Cf_Meta_Llama_4_Prompt_Inner { * JSON schema that should be fulfilled for the response. */ guided_json?: object; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -5994,7 +6597,7 @@ interface Ai_Cf_Meta_Llama_4_Prompt_Inner { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Messages_Inner { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { /** * An array of message objects representing the conversation history. */ @@ -6124,9 +6727,9 @@ interface Ai_Cf_Meta_Llama_4_Messages_Inner { }; }; })[]; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -6223,6 +6826,597 @@ declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; } +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { + requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { + inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; +} interface Ai_Cf_Deepgram_Nova_3_Input { audio: { body: object; @@ -6406,6 +7600,23 @@ declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { inputs: Ai_Cf_Deepgram_Nova_3_Input; postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; } +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { + queries?: string | string[]; + /** + * Optional instruction for the task + */ + instruction?: string; + documents?: string | string[]; + text?: string | string[]; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { + data?: number[][]; + shape?: number[]; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { + inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; +} type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = { /** * readable stream with audio data and content-type specified for that data @@ -6442,85 +7653,13 @@ declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; } -type Ai_Cf_Openai_Gpt_Oss_120B_Input = GPT_OSS_120B_Responses | GPT_OSS_120B_Responses_Async; -interface GPT_OSS_120B_Responses { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; -} -interface GPT_OSS_120B_Responses_Async { - requests: { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; - }[]; -} -type Ai_Cf_Openai_Gpt_Oss_120B_Output = {} | (string & NonNullable); declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { - inputs: Ai_Cf_Openai_Gpt_Oss_120B_Input; - postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_120B_Output; + inputs: ResponsesInput; + postProcessedOutputs: ResponsesOutput; } -type Ai_Cf_Openai_Gpt_Oss_20B_Input = GPT_OSS_20B_Responses | GPT_OSS_20B_Responses_Async; -interface GPT_OSS_20B_Responses { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; -} -interface GPT_OSS_20B_Responses_Async { - requests: { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; - }[]; -} -type Ai_Cf_Openai_Gpt_Oss_20B_Output = {} | (string & NonNullable); declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { - inputs: Ai_Cf_Openai_Gpt_Oss_20B_Input; - postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_20B_Output; + inputs: ResponsesInput; + postProcessedOutputs: ResponsesOutput; } interface Ai_Cf_Leonardo_Phoenix_1_0_Input { /** @@ -6634,6 +7773,799 @@ declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { inputs: Ai_Cf_Deepgram_Aura_1_Input; postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; } +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { + /** + * Input text to translate. Can be a single string or a list of strings. + */ + text: string | string[]; + /** + * Target language to translate to + */ + target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva"; +} +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { + /** + * Translated texts + */ + translations: string[]; +} +declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { + inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; + postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { + requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[]; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { + inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; + postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { + /** + * Input text to embed. Can be a single string or a list of strings. + */ + text: string | string[]; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { + /** + * Embedding vectors, where each vector is a list of floats. + */ + data: number[][]; + /** + * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. + * + * @minItems 2 + * @maxItems 2 + */ + shape: [ + number, + number + ]; +} +declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { + inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; + postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; +} +interface Ai_Cf_Deepgram_Flux_Input { + /** + * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. + */ + encoding: "linear16"; + /** + * Sample rate of the audio stream in Hz. + */ + sample_rate: string; + /** + * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. + */ + eager_eot_threshold?: string; + /** + * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. + */ + eot_threshold?: string; + /** + * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. + */ + eot_timeout_ms?: string; + /** + * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. + */ + keyterm?: string; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip + */ + mip_opt_out?: "true" | "false"; + /** + * Label your requests for the purpose of identification during usage reporting + */ + tag?: string; +} +/** + * Output will be returned as websocket messages. + */ +interface Ai_Cf_Deepgram_Flux_Output { + /** + * The unique identifier of the request (uuid) + */ + request_id?: string; + /** + * Starts at 0 and increments for each message the server sends to the client. + */ + sequence_id?: number; + /** + * The type of event being reported. + */ + event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn"; + /** + * The index of the current turn + */ + turn_index?: number; + /** + * Start time in seconds of the audio range that was transcribed + */ + audio_window_start?: number; + /** + * End time in seconds of the audio range that was transcribed + */ + audio_window_end?: number; + /** + * Text that was said over the course of the current turn + */ + transcript?: string; + /** + * The words in the transcript + */ + words?: { + /** + * The individual punctuated, properly-cased word from the transcript + */ + word: string; + /** + * Confidence that this word was transcribed correctly + */ + confidence: number; + }[]; + /** + * Confidence that no more speech is coming in this turn + */ + end_of_turn_confidence?: number; +} +declare abstract class Base_Ai_Cf_Deepgram_Flux { + inputs: Ai_Cf_Deepgram_Flux_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; +} +interface Ai_Cf_Deepgram_Aura_2_En_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_En_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { + inputs: Ai_Cf_Deepgram_Aura_2_En_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; +} +interface Ai_Cf_Deepgram_Aura_2_Es_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_Es_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { + inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; +} interface AiModels { "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; @@ -6677,12 +8609,12 @@ interface AiModels { "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; - "@hf/meta-llama/meta-llama-3-8b-instruct": BaseAiTextGeneration; "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; + "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration; "@cf/facebook/bart-large-cnn": BaseAiSummarization; "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; @@ -6704,13 +8636,21 @@ interface AiModels { "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; + "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; + "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; + "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; + "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; + "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; + "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux; + "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En; + "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es; } type AiOptions = { /** @@ -6722,6 +8662,16 @@ type AiOptions = { * Establish websocket connections, only works for supported models */ websocket?: boolean; + /** + * Tag your requests to group and view them in Cloudflare dashboard. + * + * Rules: + * Tags must only contain letters, numbers, and the symbols: : - . / @ + * Each tag can have maximum 50 characters. + * Maximum 5 tags are allowed each request. + * Duplicate tags will removed. + */ + tags?: string[]; gateway?: GatewayOptions; returnRawResponse?: boolean; prefix?: string; @@ -6760,6 +8710,48 @@ type AiModelListType = Record; declare abstract class Ai { aiGatewayLogId: string | null; gateway(gatewayId: string): AiGateway; + /** + * Access the AI Search API for managing AI-powered search instances. + * + * This is the new API that replaces AutoRAG with better namespace separation: + * - Account-level operations: `list()`, `create()` + * - Instance-level operations: `get(id).search()`, `get(id).chatCompletions()`, `get(id).delete()` + * + * @example + * ```typescript + * // List all AI Search instances + * const instances = await env.AI.aiSearch.list(); + * + * // Search an instance + * const results = await env.AI.aiSearch.get('my-search').search({ + * messages: [{ role: 'user', content: 'What is the policy?' }], + * ai_search_options: { + * retrieval: { max_num_results: 10 } + * } + * }); + * + * // Generate chat completions with AI Search context + * const response = await env.AI.aiSearch.get('my-search').chatCompletions({ + * messages: [{ role: 'user', content: 'What is the policy?' }], + * model: '@cf/meta/llama-3.3-70b-instruct-fp8-fast' + * }); + * ``` + */ + aiSearch(): AiSearchAccountService; + /** + * @deprecated AutoRAG has been replaced by AI Search. + * Use `env.AI.aiSearch` instead for better API design and new features. + * + * Migration guide: + * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` + * - `env.AI.autorag('id').search({ query: '...' })` → `env.AI.aiSearch.get('id').search({ messages: [{ role: 'user', content: '...' }] })` + * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` + * + * Note: The old API continues to work for backwards compatibility, but new projects should use AI Search. + * + * @see AiSearchAccountService + * @param autoragId Optional instance ID (omit for account-level operations) + */ autorag(autoragId: string): AutoRAG; run(model: Name, inputs: InputOptions, options?: Options): Promise; getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line } +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchInternalError instead. + * @see AiSearchInternalError + */ interface AutoRAGInternalError extends Error { } +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNotFoundError instead. + * @see AiSearchNotFoundError + */ interface AutoRAGNotFoundError extends Error { } +/** + * @deprecated This error type is no longer used in the AI Search API. + */ interface AutoRAGUnauthorizedError extends Error { } +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNameNotSetError instead. + * @see AiSearchNameNotSetError + */ interface AutoRAGNameNotSetError extends Error { } type ComparisonFilter = { @@ -6885,6 +8892,11 @@ type CompoundFilter = { type: 'and' | 'or'; filters: ComparisonFilter[]; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchSearchRequest with the new API instead. + * @see AiSearchSearchRequest + */ type AutoRagSearchRequest = { query: string; filters?: CompoundFilter | ComparisonFilter; @@ -6899,13 +8911,28 @@ type AutoRagSearchRequest = { }; rewrite_query?: boolean; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchChatCompletionsRequest with the new API instead. + * @see AiSearchChatCompletionsRequest + */ type AutoRagAiSearchRequest = AutoRagSearchRequest & { stream?: boolean; system_prompt?: string; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchChatCompletionsRequest with stream: true instead. + * @see AiSearchChatCompletionsRequest + */ type AutoRagAiSearchRequestStreaming = Omit & { stream: true; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchSearchResponse with the new API instead. + * @see AiSearchSearchResponse + */ type AutoRagSearchResponse = { object: 'vector_store.search_results.page'; search_query: string; @@ -6922,6 +8949,11 @@ type AutoRagSearchResponse = { has_more: boolean; next_page: string | null; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchListResponse with the new API instead. + * @see AiSearchListResponse + */ type AutoRagListResponse = { id: string; enable: boolean; @@ -6931,14 +8963,51 @@ type AutoRagListResponse = { paused: boolean; status: string; }[]; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * The new API returns different response formats for chat completions. + */ type AutoRagAiSearchResponse = AutoRagSearchResponse & { response: string; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use the new AI Search API instead: `env.AI.aiSearch` + * + * Migration guide: + * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` + * - `env.AI.autorag('id').search(...)` → `env.AI.aiSearch.get('id').search(...)` + * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` + * + * @see AiSearchAccountService + * @see AiSearchInstanceService + */ declare abstract class AutoRAG { + /** + * @deprecated Use `env.AI.aiSearch.list()` instead. + * @see AiSearchAccountService.list + */ list(): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).search(...)` instead. + * Note: The new API uses a messages array instead of a query string. + * @see AiSearchInstanceService.search + */ search(params: AutoRagSearchRequest): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ aiSearch(params: AutoRagAiSearchRequest): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ aiSearch(params: AutoRagAiSearchRequest): Promise; } interface BasicImageTransformations { @@ -7689,6 +9758,10 @@ interface D1Meta { * The region of the database instance that executed the query. */ served_by_region?: string; + /** + * The three letters airport code of the colo that executed the query. + */ + served_by_colo?: string; /** * True if-and-only-if the database instance that executed the query was the primary. */ @@ -7777,6 +9850,15 @@ declare abstract class D1PreparedStatement { // ignored when `Disposable` is included in the standard lib. interface Disposable { } +/** + * The returned data after sending an email + */ +interface EmailSendResult { + /** + * The Email Message ID + */ + messageId: string; +} /** * An email message that can be sent from a Worker. */ @@ -7818,24 +9900,55 @@ interface ForwardableEmailMessage extends EmailMessage { * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). * @returns A promise that resolves when the email message is forwarded. */ - forward(rcptTo: string, headers?: Headers): Promise; + forward(rcptTo: string, headers?: Headers): Promise; /** * Reply to the sender of this email message with a new EmailMessage object. * @param message The reply message. * @returns A promise that resolves when the email message is replied. */ - reply(message: EmailMessage): Promise; + reply(message: EmailMessage): Promise; +} +/** A file attachment for an email message */ +type EmailAttachment = { + disposition: 'inline'; + contentId: string; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; +} | { + disposition: 'attachment'; + contentId?: undefined; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; +}; +/** An Email Address */ +interface EmailAddress { + name: string; + email: string; } /** * A binding that allows a Worker to send email messages. */ interface SendEmail { - send(message: EmailMessage): Promise; + send(message: EmailMessage): Promise; + send(builder: { + from: string | EmailAddress; + to: string | string[]; + subject: string; + replyTo?: string | EmailAddress; + cc?: string | string[]; + bcc?: string | string[]; + headers?: Record; + text?: string; + html?: string; + attachments?: EmailAttachment[]; + }): Promise; } declare abstract class EmailEvent extends ExtendableEvent { readonly message: ForwardableEmailMessage; } -declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; +declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; declare module "cloudflare:email" { let _EmailMessage: { prototype: EmailMessage; @@ -7863,7 +9976,7 @@ interface Hyperdrive { /** * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. * - * Calling this method returns an idential socket to if you call + * Calling this method returns an identical socket to if you call * `connect("host:port")` using the `host` and `port` fields from this object. * Pick whichever approach works better with your preferred DB client library. * @@ -7976,6 +10089,83 @@ type ImageOutputOptions = { background?: string; anim?: boolean; }; +interface ImageMetadata { + id: string; + filename?: string; + uploaded?: string; + requireSignedURLs: boolean; + meta?: Record; + variants: string[]; + draft?: boolean; + creator?: string; +} +interface ImageUploadOptions { + id?: string; + filename?: string; + requireSignedURLs?: boolean; + metadata?: Record; + creator?: string; + encoding?: 'base64'; +} +interface ImageUpdateOptions { + requireSignedURLs?: boolean; + metadata?: Record; + creator?: string; +} +interface ImageListOptions { + limit?: number; + cursor?: string; + sortOrder?: 'asc' | 'desc'; + creator?: string; +} +interface ImageList { + images: ImageMetadata[]; + cursor?: string; + listComplete: boolean; +} +interface HostedImagesBinding { + /** + * Get detailed metadata for a hosted image + * @param imageId The ID of the image (UUID or custom ID) + * @returns Image metadata, or null if not found + */ + details(imageId: string): Promise; + /** + * Get the raw image data for a hosted image + * @param imageId The ID of the image (UUID or custom ID) + * @returns ReadableStream of image bytes, or null if not found + */ + image(imageId: string): Promise | null>; + /** + * Upload a new hosted image + * @param image The image file to upload + * @param options Upload configuration + * @returns Metadata for the uploaded image + * @throws {@link ImagesError} if upload fails + */ + upload(image: ReadableStream | ArrayBuffer, options?: ImageUploadOptions): Promise; + /** + * Update hosted image metadata + * @param imageId The ID of the image + * @param options Properties to update + * @returns Updated image metadata + * @throws {@link ImagesError} if update fails + */ + update(imageId: string, options: ImageUpdateOptions): Promise; + /** + * Delete a hosted image + * @param imageId The ID of the image + * @returns True if deleted, false if not found + */ + delete(imageId: string): Promise; + /** + * List hosted images with pagination + * @param options List configuration + * @returns List of images with pagination info + * @throws {@link ImagesError} if list fails + */ + list(options?: ImageListOptions): Promise; +} interface ImagesBinding { /** * Get image metadata (type, width and height) @@ -7989,6 +10179,10 @@ interface ImagesBinding { * @returns A transform handle */ input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; + /** + * Access hosted images CRUD operations + */ + readonly hosted: HostedImagesBinding; } interface ImageTransformer { /** @@ -8055,7 +10249,13 @@ interface MediaTransformer { * @param transform - Configuration for how the media should be transformed * @returns A generator for producing the transformed media output */ - transform(transform: MediaTransformationInputOptions): MediaTransformationGenerator; + transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator; + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; } /** * Generator for producing media transformation results. @@ -8067,7 +10267,7 @@ interface MediaTransformationGenerator { * @param output - Configuration for the output format and parameters * @returns The final transformation result containing the transformed media */ - output(output: MediaTransformationOutputOptions): MediaTransformationResult; + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; } /** * Result of a media transformation operation. @@ -8076,19 +10276,19 @@ interface MediaTransformationGenerator { interface MediaTransformationResult { /** * Returns the transformed media as a readable stream of bytes. - * @returns A stream containing the transformed media data + * @returns A promise containing a readable stream with the transformed media */ - media(): ReadableStream; + media(): Promise>; /** * Returns the transformed media as an HTTP response object. - * @returns The transformed media as a Response, ready to store in cache or return to users + * @returns The transformed media as a Promise, ready to store in cache or return to users */ - response(): Response; + response(): Promise; /** * Returns the MIME type of the transformed media. - * @returns The content type string (e.g., 'image/jpeg', 'video/mp4') + * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4') */ - contentType(): string; + contentType(): Promise; } /** * Configuration options for transforming media input. @@ -8196,7 +10396,7 @@ declare module "cloudflare:pipelines" { protected ctx: ExecutionContext; constructor(ctx: ExecutionContext, env: Env); /** - * run recieves an array of PipelineRecord which can be + * run receives an array of PipelineRecord which can be * transformed and returned to the pipeline * @param records Incoming records from the pipeline to be transformed * @param metadata Information about the specific pipeline calling the transformation entrypoint @@ -8362,9 +10562,9 @@ declare namespace Rpc { // Base type for all other types providing RPC-like interfaces. // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. - export type Provider = MaybeCallableProvider & { - [K in Exclude>]: MethodOrProperty; - }; + export type Provider = MaybeCallableProvider & Pick<{ + [K in keyof T]: MethodOrProperty; + }, Exclude>>; } declare namespace Cloudflare { // Type of `env`. @@ -8467,9 +10667,12 @@ declare namespace CloudflareWorkersModule { timestamp: Date; type: string; }; + export type WorkflowStepContext = { + attempt: number; + }; export abstract class WorkflowStep { - do>(name: string, callback: () => Promise): Promise; - do>(name: string, config: WorkflowStepConfig, callback: () => Promise): Promise; + do>(name: string, callback: (ctx: WorkflowStepContext) => Promise): Promise; + do>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise): Promise; sleep: (name: string, duration: WorkflowSleepDuration) => Promise; sleepUntil: (name: string, timestamp: Date | number) => Promise; waitForEvent>(name: string, options: { @@ -8477,6 +10680,7 @@ declare namespace CloudflareWorkersModule { timeout?: WorkflowTimeoutDuration | number; }): Promise>; } + export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown'; export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; protected ctx: ExecutionContext; @@ -8485,7 +10689,11 @@ declare namespace CloudflareWorkersModule { run(event: Readonly>, step: WorkflowStep): Promise; } export function waitUntil(promise: Promise): void; + export function withEnv(newEnv: unknown, fn: () => unknown): unknown; + export function withExports(newExports: unknown, fn: () => unknown): unknown; + export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown; export const env: Cloudflare.Env; + export const exports: Cloudflare.Exports; } declare module 'cloudflare:workers' { export = CloudflareWorkersModule; @@ -8501,17 +10709,765 @@ declare module "cloudflare:sockets" { function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; export { _connect as connect }; } +/** + * Binding entrypoint for Cloudflare Stream. + * + * Usage: + * - Binding-level operations: + * `await env.STREAM.videos.upload` + * `await env.STREAM.videos.createDirectUpload` + * `await env.STREAM.videos.*` + * `await env.STREAM.watermarks.*` + * - Per-video operations: + * `await env.STREAM.video(id).downloads.*` + * `await env.STREAM.video(id).captions.*` + * + * Example usage: + * ```ts + * await env.STREAM.video(id).downloads.generate(); + * + * const video = env.STREAM.video(id) + * const captions = video.captions.list(); + * const videoDetails = video.details() + * ``` + */ +interface StreamBinding { + /** + * Returns a handle scoped to a single video for per-video operations. + * @param id The unique identifier for the video. + * @returns A handle for per-video operations. + */ + video(id: string): StreamVideoHandle; + /** + * Uploads a new video from a File. + * @param file The video file to upload. + * @returns The uploaded video details. + * @throws {BadRequestError} if the upload parameter is invalid + * @throws {QuotaReachedError} if the account storage capacity is exceeded + * @throws {MaxFileSizeError} if the file size is too large + * @throws {RateLimitedError} if the server received too many requests + * @throws {InternalError} if an unexpected error occurs + */ + upload(file: File): Promise; + /** + * Uploads a new video from a provided URL. + * @param url The URL to upload from. + * @param params Optional upload parameters. + * @returns The uploaded video details. + * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid + * @throws {QuotaReachedError} if the account storage capacity is exceeded + * @throws {MaxFileSizeError} if the file size is too large + * @throws {RateLimitedError} if the server received too many requests + * @throws {AlreadyUploadedError} if a video was already uploaded to this URL + * @throws {InternalError} if an unexpected error occurs + */ + upload(url: string, params?: StreamUrlUploadParams): Promise; + /** + * Creates a direct upload that allows video uploads without an API key. + * @param params Parameters for the direct upload + * @returns The direct upload details. + * @throws {BadRequestError} if the parameters are invalid + * @throws {RateLimitedError} if the server received too many requests + * @throws {InternalError} if an unexpected error occurs + */ + createDirectUpload(params: StreamDirectUploadCreateParams): Promise; + videos: StreamVideos; + watermarks: StreamWatermarks; +} +/** + * Handle for operations scoped to a single Stream video. + */ +interface StreamVideoHandle { + /** + * The unique identifier for the video. + */ + id: string; + /** + * Get a full videos details + * @returns The full video details. + * @throws {NotFoundError} if the video is not found + * @throws {InternalError} if an unexpected error occurs + */ + details(): Promise; + /** + * Update details for a single video. + * @param params The fields to update for the video. + * @returns The updated video details. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the parameters are invalid + * @throws {InternalError} if an unexpected error occurs + */ + update(params: StreamUpdateVideoParams): Promise; + /** + * Deletes a video and its copies from Cloudflare Stream. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(): Promise; + /** + * Creates a signed URL token for a video. + * @returns The signed token that was created. + * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed + */ + generateToken(): Promise; + downloads: StreamScopedDownloads; + captions: StreamScopedCaptions; +} +interface StreamVideo { + /** + * The unique identifier for the video. + */ + id: string; + /** + * A user-defined identifier for the media creator. + */ + creator: string | null; + /** + * The thumbnail URL for the video. + */ + thumbnail: string; + /** + * The thumbnail timestamp percentage. + */ + thumbnailTimestampPct: number; + /** + * Indicates whether the video is ready to stream. + */ + readyToStream: boolean; + /** + * The date and time the video became ready to stream. + */ + readyToStreamAt: string | null; + /** + * Processing status information. + */ + status: StreamVideoStatus; + /** + * A user modifiable key-value store. + */ + meta: Record; + /** + * The date and time the video was created. + */ + created: string; + /** + * The date and time the video was last modified. + */ + modified: string; + /** + * The date and time at which the video will be deleted. + */ + scheduledDeletion: string | null; + /** + * The size of the video in bytes. + */ + size: number; + /** + * The preview URL for the video. + */ + preview?: string; + /** + * Origins allowed to display the video. + */ + allowedOrigins: Array; + /** + * Indicates whether signed URLs are required. + */ + requireSignedURLs: boolean | null; + /** + * The date and time the video was uploaded. + */ + uploaded: string | null; + /** + * The date and time when the upload URL expires. + */ + uploadExpiry: string | null; + /** + * The maximum size in bytes for direct uploads. + */ + maxSizeBytes: number | null; + /** + * The maximum duration in seconds for direct uploads. + */ + maxDurationSeconds: number | null; + /** + * The video duration in seconds. -1 indicates unknown. + */ + duration: number; + /** + * Input metadata for the original upload. + */ + input: StreamVideoInput; + /** + * Playback URLs for the video. + */ + hlsPlaybackUrl: string; + dashPlaybackUrl: string; + /** + * The watermark applied to the video, if any. + */ + watermark: StreamWatermark | null; + /** + * The live input id associated with the video, if any. + */ + liveInputId?: string | null; + /** + * The source video id if this is a clip. + */ + clippedFromId: string | null; + /** + * Public details associated with the video. + */ + publicDetails: StreamPublicDetails | null; +} +type StreamVideoStatus = { + /** + * The current processing state. + */ + state: string; + /** + * The current processing step. + */ + step?: string; + /** + * The percent complete as a string. + */ + pctComplete?: string; + /** + * An error reason code, if applicable. + */ + errorReasonCode: string; + /** + * An error reason text, if applicable. + */ + errorReasonText: string; +}; +type StreamVideoInput = { + /** + * The input width in pixels. + */ + width: number; + /** + * The input height in pixels. + */ + height: number; +}; +type StreamPublicDetails = { + /** + * The public title for the video. + */ + title: string | null; + /** + * The public share link. + */ + share_link: string | null; + /** + * The public channel link. + */ + channel_link: string | null; + /** + * The public logo URL. + */ + logo: string | null; +}; +type StreamDirectUpload = { + /** + * The URL an unauthenticated upload can use for a single multipart request. + */ + uploadURL: string; + /** + * A Cloudflare-generated unique identifier for a media item. + */ + id: string; + /** + * The watermark profile applied to the upload. + */ + watermark: StreamWatermark | null; + /** + * The scheduled deletion time, if any. + */ + scheduledDeletion: string | null; +}; +type StreamDirectUploadCreateParams = { + /** + * The maximum duration in seconds for a video upload. + */ + maxDurationSeconds: number; + /** + * The date and time after upload when videos will not be accepted. + */ + expiry?: string; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * A user modifiable key-value store used to reference other systems of record for + * managing videos. + */ + meta?: Record; + /** + * Lists the origins allowed to display the video. + */ + allowedOrigins?: Array; + /** + * Indicates whether the video can be accessed using the id. When set to `true`, + * a signed token must be generated with a signing key to view the video. + */ + requireSignedURLs?: boolean; + /** + * The thumbnail timestamp percentage. + */ + thumbnailTimestampPct?: number; + /** + * The date and time at which the video will be deleted. Include `null` to remove + * a scheduled deletion. + */ + scheduledDeletion?: string | null; + /** + * The watermark profile to apply. + */ + watermark?: StreamDirectUploadWatermark; +}; +type StreamDirectUploadWatermark = { + /** + * The unique identifier for the watermark profile. + */ + id: string; +}; +type StreamUrlUploadParams = { + /** + * Lists the origins allowed to display the video. Enter allowed origin + * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the + * video to be viewed on any origin. + */ + allowedOrigins?: Array; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * A user modifiable key-value store used to reference other systems of + * record for managing videos. + */ + meta?: Record; + /** + * Indicates whether the video can be a accessed using the id. When + * set to `true`, a signed token must be generated with a signing key to view the + * video. + */ + requireSignedURLs?: boolean; + /** + * Indicates the date and time at which the video will be deleted. Omit + * the field to indicate no change, or include with a `null` value to remove an + * existing scheduled deletion. If specified, must be at least 30 days from upload + * time. + */ + scheduledDeletion?: string | null; + /** + * The timestamp for a thumbnail image calculated as a percentage value + * of the video's duration. To convert from a second-wise timestamp to a + * percentage, divide the desired timestamp by the total duration of the video. If + * this value is not set, the default thumbnail image is taken from 0s of the + * video. + */ + thumbnailTimestampPct?: number; + /** + * The identifier for the watermark profile + */ + watermarkId?: string; +}; +interface StreamScopedCaptions { + /** + * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language. + * One caption or subtitle file per language is allowed. + * @param language The BCP 47 language tag for the caption or subtitle. + * @param file The caption or subtitle file to upload. + * @returns The created caption entry. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the language or file is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {InternalError} if an unexpected error occurs + */ + upload(language: string, file: File): Promise; + /** + * Generate captions or subtitles for the provided language via AI. + * @param language The BCP 47 language tag to generate. + * @returns The generated caption entry. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the language is invalid + * @throws {StreamError} if a generated caption already exists + * @throws {StreamError} if the video duration is too long + * @throws {StreamError} if the video is missing audio + * @throws {StreamError} if the requested language is not supported + * @throws {InternalError} if an unexpected error occurs + */ + generate(language: string): Promise; + /** + * Lists the captions or subtitles. + * Use the language parameter to filter by a specific language. + * @param language The optional BCP 47 language tag to filter by. + * @returns The list of captions or subtitles. + * @throws {NotFoundError} if the video or caption is not found + * @throws {InternalError} if an unexpected error occurs + */ + list(language?: string): Promise; + /** + * Removes the captions or subtitles from a video. + * @param language The BCP 47 language tag to remove. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video or caption is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(language: string): Promise; +} +interface StreamScopedDownloads { + /** + * Generates a download for a video when a video is ready to view. Available + * types are `default` and `audio`. Defaults to `default` when omitted. + * @param downloadType The download type to create. + * @returns The current downloads for the video. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the download type is invalid + * @throws {StreamError} if the video duration is too long to generate a download + * @throws {StreamError} if the video is not ready to stream + * @throws {InternalError} if an unexpected error occurs + */ + generate(downloadType?: StreamDownloadType): Promise; + /** + * Lists the downloads created for a video. + * @returns The current downloads for the video. + * @throws {NotFoundError} if the video or downloads are not found + * @throws {InternalError} if an unexpected error occurs + */ + get(): Promise; + /** + * Delete the downloads for a video. Available types are `default` and `audio`. + * Defaults to `default` when omitted. + * @param downloadType The download type to delete. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video or downloads are not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(downloadType?: StreamDownloadType): Promise; +} +interface StreamVideos { + /** + * Lists all videos in a users account. + * @returns The list of videos. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InternalError} if an unexpected error occurs + */ + list(params?: StreamVideosListParams): Promise; +} +interface StreamWatermarks { + /** + * Generate a new watermark profile + * @param file The image file to upload + * @param params The watermark creation parameters. + * @returns The created watermark profile. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InvalidURLError} if the URL is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached + * @throws {InternalError} if an unexpected error occurs + */ + generate(file: File, params: StreamWatermarkCreateParams): Promise; + /** + * Generate a new watermark profile + * @param url The image url to upload + * @param params The watermark creation parameters. + * @returns The created watermark profile. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InvalidURLError} if the URL is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached + * @throws {InternalError} if an unexpected error occurs + */ + generate(url: string, params: StreamWatermarkCreateParams): Promise; + /** + * Lists all watermark profiles for an account. + * @returns The list of watermark profiles. + * @throws {InternalError} if an unexpected error occurs + */ + list(): Promise; + /** + * Retrieves details for a single watermark profile. + * @param watermarkId The watermark profile identifier. + * @returns The watermark profile details. + * @throws {NotFoundError} if the watermark is not found + * @throws {InternalError} if an unexpected error occurs + */ + get(watermarkId: string): Promise; + /** + * Deletes a watermark profile. + * @param watermarkId The watermark profile identifier. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the watermark is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(watermarkId: string): Promise; +} +type StreamUpdateVideoParams = { + /** + * Lists the origins allowed to display the video. Enter allowed origin + * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the + * video to be viewed on any origin. + */ + allowedOrigins?: Array; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * The maximum duration in seconds for a video upload. Can be set for a + * video that is not yet uploaded to limit its duration. Uploads that exceed the + * specified duration will fail during processing. A value of `-1` means the value + * is unknown. + */ + maxDurationSeconds?: number; + /** + * A user modifiable key-value store used to reference other systems of + * record for managing videos. + */ + meta?: Record; + /** + * Indicates whether the video can be a accessed using the id. When + * set to `true`, a signed token must be generated with a signing key to view the + * video. + */ + requireSignedURLs?: boolean; + /** + * Indicates the date and time at which the video will be deleted. Omit + * the field to indicate no change, or include with a `null` value to remove an + * existing scheduled deletion. If specified, must be at least 30 days from upload + * time. + */ + scheduledDeletion?: string | null; + /** + * The timestamp for a thumbnail image calculated as a percentage value + * of the video's duration. To convert from a second-wise timestamp to a + * percentage, divide the desired timestamp by the total duration of the video. If + * this value is not set, the default thumbnail image is taken from 0s of the + * video. + */ + thumbnailTimestampPct?: number; +}; +type StreamCaption = { + /** + * Whether the caption was generated via AI. + */ + generated?: boolean; + /** + * The language label displayed in the native language to users. + */ + label: string; + /** + * The language tag in BCP 47 format. + */ + language: string; + /** + * The status of a generated caption. + */ + status?: 'ready' | 'inprogress' | 'error'; +}; +type StreamDownloadStatus = 'ready' | 'inprogress' | 'error'; +type StreamDownloadType = 'default' | 'audio'; +type StreamDownload = { + /** + * Indicates the progress as a percentage between 0 and 100. + */ + percentComplete: number; + /** + * The status of a generated download. + */ + status: StreamDownloadStatus; + /** + * The URL to access the generated download. + */ + url?: string; +}; +/** + * An object with download type keys. Each key is optional and only present if that + * download type has been created. + */ +type StreamDownloadGetResponse = { + /** + * The audio-only download. Only present if this download type has been created. + */ + audio?: StreamDownload; + /** + * The default video download. Only present if this download type has been created. + */ + default?: StreamDownload; +}; +type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center'; +type StreamWatermark = { + /** + * The unique identifier for a watermark profile. + */ + id: string; + /** + * The size of the image in bytes. + */ + size: number; + /** + * The height of the image in pixels. + */ + height: number; + /** + * The width of the image in pixels. + */ + width: number; + /** + * The date and a time a watermark profile was created. + */ + created: string; + /** + * The source URL for a downloaded image. If the watermark profile was created via + * direct upload, this field is null. + */ + downloadedFrom: string | null; + /** + * A short description of the watermark profile. + */ + name: string; + /** + * The translucency of the image. A value of `0.0` makes the image completely + * transparent, and `1.0` makes the image completely opaque. Note that if the image + * is already semi-transparent, setting this to `1.0` will not make the image + * completely opaque. + */ + opacity: number; + /** + * The whitespace between the adjacent edges (determined by position) of the video + * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded + * video width or length, as determined by the algorithm. + */ + padding: number; + /** + * The size of the image relative to the overall size of the video. This parameter + * will adapt to horizontal and vertical videos automatically. `0.0` indicates no + * scaling (use the size of the image as-is), and `1.0 `fills the entire video. + */ + scale: number; + /** + * The location of the image. Valid positions are: `upperRight`, `upperLeft`, + * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the + * `padding` parameter. + */ + position: StreamWatermarkPosition; +}; +type StreamWatermarkCreateParams = { + /** + * A short description of the watermark profile. + */ + name?: string; + /** + * The translucency of the image. A value of `0.0` makes the image completely + * transparent, and `1.0` makes the image completely opaque. Note that if the + * image is already semi-transparent, setting this to `1.0` will not make the + * image completely opaque. + */ + opacity?: number; + /** + * The whitespace between the adjacent edges (determined by position) of the + * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully + * padded video width or length, as determined by the algorithm. + */ + padding?: number; + /** + * The size of the image relative to the overall size of the video. This + * parameter will adapt to horizontal and vertical videos automatically. `0.0` + * indicates no scaling (use the size of the image as-is), and `1.0 `fills the + * entire video. + */ + scale?: number; + /** + * The location of the image. + */ + position?: StreamWatermarkPosition; +}; +type StreamVideosListParams = { + /** + * The maximum number of videos to return. + */ + limit?: number; + /** + * Return videos created before this timestamp. + * (RFC3339/RFC3339Nano) + */ + before?: string; + /** + * Comparison operator for the `before` field. + * @default 'lt' + */ + beforeComp?: StreamPaginationComparison; + /** + * Return videos created after this timestamp. + * (RFC3339/RFC3339Nano) + */ + after?: string; + /** + * Comparison operator for the `after` field. + * @default 'gte' + */ + afterComp?: StreamPaginationComparison; +}; +type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte'; +/** + * Error object for Stream binding operations. + */ +interface StreamError extends Error { + readonly code: number; + readonly statusCode: number; + readonly message: string; + readonly stack?: string; +} +interface InternalError extends StreamError { + name: 'InternalError'; +} +interface BadRequestError extends StreamError { + name: 'BadRequestError'; +} +interface NotFoundError extends StreamError { + name: 'NotFoundError'; +} +interface ForbiddenError extends StreamError { + name: 'ForbiddenError'; +} +interface RateLimitedError extends StreamError { + name: 'RateLimitedError'; +} +interface QuotaReachedError extends StreamError { + name: 'QuotaReachedError'; +} +interface MaxFileSizeError extends StreamError { + name: 'MaxFileSizeError'; +} +interface InvalidURLError extends StreamError { + name: 'InvalidURLError'; +} +interface AlreadyUploadedError extends StreamError { + name: 'AlreadyUploadedError'; +} +interface TooManyWatermarksError extends StreamError { + name: 'TooManyWatermarksError'; +} type MarkdownDocument = { name: string; blob: Blob; }; type ConversionResponse = { + id: string; name: string; mimeType: string; format: 'markdown'; tokens: number; data: string; } | { + id: string; name: string; mimeType: string; format: 'error'; @@ -8529,6 +11485,8 @@ type ConversionOptions = { images?: EmbeddedImageConversionOptions & { convertOGImage?: boolean; }; + hostname?: string; + cssSelector?: string; }; docx?: { images?: EmbeddedImageConversionOptions; @@ -8666,6 +11624,15 @@ declare namespace TailStream { readonly level: "debug" | "error" | "info" | "log" | "warn"; readonly message: object; } + interface DroppedEventsDiagnostic { + readonly diagnosticsType: "droppedEvents"; + readonly count: number; + } + interface StreamDiagnostic { + readonly type: 'streamDiagnostic'; + // To add new diagnostic types, define a new interface and add it to this union type. + readonly diagnostic: DroppedEventsDiagnostic; + } // This marks the worker handler return information. // This is separate from Outcome because the worker invocation can live for a long time after // returning. For example - Websockets that return an http upgrade response but then continue @@ -8682,7 +11649,7 @@ declare namespace TailStream { readonly type: "attributes"; readonly info: Attribute[]; } - type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | Return | Attributes; + type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes; // Context in which this trace event lives. interface SpanContext { // Single id for the entire top-level invocation @@ -8696,7 +11663,7 @@ declare namespace TailStream { // For Hibernate and Mark this would be the span under which they were emitted. // spanId is not set ONLY if: // 1. This is an Onset event - // 2. We are not inherting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) + // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) readonly spanId?: string; } interface TailEvent { @@ -9062,8 +12029,11 @@ type InstanceStatus = { | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish | 'waitingForPause' // instance is finishing the current work to pause | 'unknown'; - error?: string; - output?: object; + error?: { + name: string; + message: string; + }; + output?: unknown; }; interface WorkflowError { code?: number; diff --git a/examples/react/start-basic-react-query/.devcontainer/devcontainer.json b/examples/react/start-basic-react-query/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-basic-react-query/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-basic-react-query/README.md b/examples/react/start-basic-react-query/README.md index 77c61c2504..70cc728ae4 100644 --- a/examples/react/start-basic-react-query/README.md +++ b/examples/react/start-basic-react-query/README.md @@ -38,5 +38,18 @@ This example demonstrates how to use TanStack Query with TanStack Start for: - Server-side data fetching - Client-side caching and synchronization -- Optimistic updates -- Automatic refetching +- Confirmed server mutations followed by query invalidation +- Explicit freshness and automatic refetching + +## SSR and mutation checks + +Read the [Start + TanStack Query guide](https://tanstack.com/start/latest/docs/framework/react/guide/tanstack-query). The `/preferences` page stores a harmless display name in a cookie, so its tests need no account or external API. This cookie is not authentication. The other post/user examples use JSONPlaceholder. + +```sh +pnpm exec playwright install chromium +pnpm test:e2e +pnpm build +QUERY_EXAMPLE_PRODUCTION=1 pnpm test:e2e +``` + +The tests check concurrent SSR request isolation, no duplicate hydration read, one refetch after mutation invalidation, and persistence on reload. Query data is fresh for 30 seconds by default in this example; choose a window appropriate for your application. diff --git a/examples/react/start-basic-react-query/package.json b/examples/react/start-basic-react-query/package.json index 8577b59761..9d819d4390 100644 --- a/examples/react/start-basic-react-query/package.json +++ b/examples/react/start-basic-react-query/package.json @@ -7,30 +7,31 @@ "dev": "vite dev", "build": "vite build && tsc --noEmit", "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" + "start": "pnpx srvx --prod -s ../client dist/server/server.js", + "test:e2e": "playwright test" }, "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-router-ssr-query": "^1.141.8", - "@tanstack/react-start": "^1.142.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", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0" + "tailwind-merge": "^3.6.0" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-react": "^6.0.1", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "@playwright/test": "^1.61.0" } } diff --git a/examples/react/start-basic-react-query/playwright.config.ts b/examples/react/start-basic-react-query/playwright.config.ts new file mode 100644 index 0000000000..298a1133e9 --- /dev/null +++ b/examples/react/start-basic-react-query/playwright.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from '@playwright/test' + +export default defineConfig({ + testDir: './tests', + use: { baseURL: 'http://localhost:3110', browserName: 'chromium' }, + webServer: { + command: + process.env.QUERY_EXAMPLE_PRODUCTION === '1' + ? 'PORT=3110 pnpm start' + : 'pnpm dev --port 3110', + url: 'http://localhost:3110/preferences', + timeout: 120_000, + }, +}) diff --git a/examples/react/start-basic-react-query/postcss.config.mjs b/examples/react/start-basic-react-query/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/start-basic-react-query/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx index ef2daa1ea1..405fb5f4a7 100644 --- a/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-basic-react-query/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error(error) diff --git a/examples/react/start-basic-react-query/src/routeTree.gen.ts b/examples/react/start-basic-react-query/src/routeTree.gen.ts index e713afe557..0c7a90d4a1 100644 --- a/examples/react/start-basic-react-query/src/routeTree.gen.ts +++ b/examples/react/start-basic-react-query/src/routeTree.gen.ts @@ -9,26 +9,31 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as UsersRouteRouteImport } from './routes/users.route' -import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteRouteImport } from './routes/posts.route' +import { Route as PreferencesRouteImport } from './routes/preferences' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteRouteImport } from './routes/users.route' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -36,8 +41,19 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const PostsRouteRoute = PostsRouteRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const PreferencesRoute = PreferencesRouteImport.update({ + id: '/preferences', + path: '/preferences', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) const UsersRouteRoute = UsersRouteRouteImport.update({ @@ -45,74 +61,65 @@ const UsersRouteRoute = UsersRouteRouteImport.update({ path: '/users', getParentRoute: () => rootRouteImport, } as any) -const PostsRouteRoute = PostsRouteRouteImport.update({ - id: '/posts', - path: '/posts', +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRouteRoute, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => PostsRouteRoute, } as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRouteRoute, -} as any) const PostsPostIdRoute = PostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', - getParentRoute: () => rootRouteImport, +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRouteRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRouteRoute, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, -} as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute '/posts': typeof PostsRouteRouteWithChildren '/users': typeof UsersRouteRouteWithChildren '/deferred': typeof DeferredRoute + '/preferences': typeof PreferencesRoute '/redirect': typeof RedirectRoute '/api/users': typeof ApiUsersRouteWithChildren '/posts/$postId': typeof PostsPostIdRoute @@ -127,6 +134,7 @@ export interface FileRoutesByFullPath { export interface FileRoutesByTo { '/': typeof IndexRoute '/deferred': typeof DeferredRoute + '/preferences': typeof PreferencesRoute '/redirect': typeof RedirectRoute '/api/users': typeof ApiUsersRouteWithChildren '/posts/$postId': typeof PostsPostIdRoute @@ -145,6 +153,7 @@ export interface FileRoutesById { '/users': typeof UsersRouteRouteWithChildren '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren '/deferred': typeof DeferredRoute + '/preferences': typeof PreferencesRoute '/redirect': typeof RedirectRoute '/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren @@ -164,6 +173,7 @@ export interface FileRouteTypes { | '/posts' | '/users' | '/deferred' + | '/preferences' | '/redirect' | '/api/users' | '/posts/$postId' @@ -178,6 +188,7 @@ export interface FileRouteTypes { to: | '/' | '/deferred' + | '/preferences' | '/redirect' | '/api/users' | '/posts/$postId' @@ -195,6 +206,7 @@ export interface FileRouteTypes { | '/users' | '/_pathlessLayout' | '/deferred' + | '/preferences' | '/redirect' | '/_pathlessLayout/_nested-layout' | '/api/users' @@ -214,6 +226,7 @@ export interface RootRouteChildren { UsersRouteRoute: typeof UsersRouteRouteWithChildren PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren DeferredRoute: typeof DeferredRoute + PreferencesRoute: typeof PreferencesRoute RedirectRoute: typeof RedirectRoute ApiUsersRoute: typeof ApiUsersRouteWithChildren PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute @@ -221,11 +234,18 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -235,11 +255,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/preferences': { + id: '/preferences' + path: '/preferences' + fullPath: '/preferences' + preLoaderRoute: typeof PreferencesRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } '/users': { @@ -249,47 +283,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UsersRouteRouteImport parentRoute: typeof rootRouteImport } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRouteRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRouteRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRouteRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRouteRoute + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/api/users': { id: '/api/users' @@ -298,26 +297,40 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRouteRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRouteRoute } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRouteRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRouteRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -326,12 +339,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } @@ -412,6 +432,7 @@ const rootRouteChildren: RootRouteChildren = { UsersRouteRoute: UsersRouteRouteWithChildren, PathlessLayoutRoute: PathlessLayoutRouteWithChildren, DeferredRoute: DeferredRoute, + PreferencesRoute: PreferencesRoute, RedirectRoute: RedirectRoute, ApiUsersRoute: ApiUsersRouteWithChildren, PostsPostIdDeepRoute: PostsPostIdDeepRoute, @@ -421,10 +442,11 @@ export const routeTree = rootRouteImport ._addFileTypes() import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' +import type { startInstance } from './start.ts' declare module '@tanstack/react-start' { interface Register { ssr: true router: Awaited> + config: Awaited> } } diff --git a/examples/react/start-basic-react-query/src/router.tsx b/examples/react/start-basic-react-query/src/router.tsx index 314b29edd0..345055c116 100644 --- a/examples/react/start-basic-react-query/src/router.tsx +++ b/examples/react/start-basic-react-query/src/router.tsx @@ -6,12 +6,15 @@ import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' import { NotFound } from './components/NotFound' export function getRouter() { - const queryClient = new QueryClient() + const queryClient = new QueryClient({ + defaultOptions: { queries: { staleTime: 30_000 } }, + }) const router = createRouter({ routeTree, context: { queryClient }, defaultPreload: 'intent', + defaultPreloadStaleTime: 0, defaultErrorComponent: DefaultCatchBoundary, defaultNotFoundComponent: () => , }) diff --git a/examples/react/start-basic-react-query/src/routes/__root.tsx b/examples/react/start-basic-react-query/src/routes/__root.tsx index bc278f8036..71c19b2c6f 100644 --- a/examples/react/start-basic-react-query/src/routes/__root.tsx +++ b/examples/react/start-basic-react-query/src/routes/__root.tsx @@ -83,6 +83,7 @@ function RootDocument({ children }: { children: React.ReactNode }) { - ) -} - -function DelayedDateViaSuspense({ state }) { - // a component that will suspend for 1 second and then show the current date - if (state.status === 'pending') { - state.promise = new Promise((resolve) => { - setTimeout(() => { - state.status = 'success' - resolve() - }, 5000) - }) - throw state.promise - } - - return
    {new Date().toISOString().replace('T', ' ').split('.')[0]}
    -} - -// ...fetchPosts -// posts -// ...5000 -// timestamp diff --git a/examples/react/start-basic-rsc/tailwind.config.mjs b/examples/react/start-basic-rsc/tailwind.config.mjs deleted file mode 100644 index e49f4eb776..0000000000 --- a/examples/react/start-basic-rsc/tailwind.config.mjs +++ /dev/null @@ -1,4 +0,0 @@ -/** @type {import('tailwindcss').Config} */ -export default { - content: ['./src/**/*.{js,jsx,ts,tsx}'], -} diff --git a/examples/react/start-basic-rsc/tsconfig.json b/examples/react/start-basic-rsc/tsconfig.json deleted file mode 100644 index 3a9fb7cd71..0000000000 --- a/examples/react/start-basic-rsc/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "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, - "baseUrl": ".", - "paths": { - "~/*": ["./src/*"] - }, - "noEmit": true - } -} diff --git a/examples/react/start-basic-rsc/vite.config.ts b/examples/react/start-basic-rsc/vite.config.ts deleted file mode 100644 index f10c86e79f..0000000000 --- a/examples/react/start-basic-rsc/vite.config.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' -import viteReact from '@vitejs/plugin-react' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], -}) diff --git a/examples/react/start-basic-static/.devcontainer/devcontainer.json b/examples/react/start-basic-static/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-basic-static/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-basic-static/package.json b/examples/react/start-basic-static/package.json index 58549b1531..58d573ca36 100644 --- a/examples/react/start-basic-static/package.json +++ b/examples/react/start-basic-static/package.json @@ -10,25 +10,24 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", - "@tanstack/start-static-server-functions": "^1.142.0", - "@vitejs/plugin-react": "^5.1.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", + "@tanstack/start-static-server-functions": "^1.167.44", + "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0" + "tailwind-merge": "^3.6.0" }, "devDependencies": { + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "autoprefixer": "^10.4.20", - "postcss": "^8.4.49", - "tailwindcss": "^3.4.15", - "typescript": "^5.6.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.3" + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-basic-static/postcss.config.cjs b/examples/react/start-basic-static/postcss.config.cjs deleted file mode 100644 index 8e638a6bcd..0000000000 --- a/examples/react/start-basic-static/postcss.config.cjs +++ /dev/null @@ -1,7 +0,0 @@ -module.exports = { - plugins: [ - require('tailwindcss/nesting'), - require('tailwindcss'), - require('autoprefixer'), - ], -} diff --git a/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx index f750e7bd2b..4a22649ed4 100644 --- a/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-basic-static/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error('DefaultCatchBoundary Error:', error) @@ -24,21 +22,21 @@ export function DefaultCatchBoundary({ error }: ErrorComponentProps) { onClick={() => { router.invalidate() }} - className={`px-2 py-1 bg-gray-600 dark:bg-gray-700 rounded text-white uppercase font-extrabold`} + className={`px-2 py-1 bg-gray-600 dark:bg-gray-700 rounded-sm text-white uppercase font-extrabold`} > Try Again {isRoot ? ( Home ) : ( { e.preventDefault() window.history.back() diff --git a/examples/react/start-basic-static/src/components/NotFound.tsx b/examples/react/start-basic-static/src/components/NotFound.tsx index 7b54fa5680..fd4e75befe 100644 --- a/examples/react/start-basic-static/src/components/NotFound.tsx +++ b/examples/react/start-basic-static/src/components/NotFound.tsx @@ -9,13 +9,13 @@ export function NotFound({ children }: { children?: any }) {

    Start Over diff --git a/examples/react/start-basic-static/src/routeTree.gen.ts b/examples/react/start-basic-static/src/routeTree.gen.ts index bb27e7cefc..d4a8e72343 100644 --- a/examples/react/start-basic-static/src/routeTree.gen.ts +++ b/examples/react/start-basic-static/src/routeTree.gen.ts @@ -9,34 +9,28 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -44,57 +38,63 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = PathlessLayoutNestedLayoutRouteImport.update({ id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -196,25 +196,18 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -224,26 +217,33 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout': { - id: '/_pathlessLayout' + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/posts/': { id: '/posts/' @@ -252,13 +252,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsIndexRouteImport parentRoute: typeof PostsRoute } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } '/posts/$postId': { id: '/posts/$postId' path: '/$postId' @@ -266,19 +259,26 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -287,12 +287,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/react/start-basic-static/src/router.tsx b/examples/react/start-basic-static/src/router.tsx index 1a1d8822d2..5b15fa1059 100644 --- a/examples/react/start-basic-static/src/router.tsx +++ b/examples/react/start-basic-static/src/router.tsx @@ -6,6 +6,7 @@ import { NotFound } from './components/NotFound' export function getRouter() { const router = createRouter({ routeTree, + basepath: '/test/', defaultPreload: 'intent', defaultErrorComponent: DefaultCatchBoundary, defaultNotFoundComponent: () => , diff --git a/examples/react/start-basic-static/src/routes/deferred.tsx b/examples/react/start-basic-static/src/routes/deferred.tsx index f0d832b805..07810ddc39 100644 --- a/examples/react/start-basic-static/src/routes/deferred.tsx +++ b/examples/react/start-basic-static/src/routes/deferred.tsx @@ -5,14 +5,14 @@ import { staticFunctionMiddleware } from '@tanstack/start-static-server-function const personServerFn = createServerFn({ method: 'GET' }) .middleware([staticFunctionMiddleware]) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) .middleware([staticFunctionMiddleware]) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/examples/react/start-basic-static/src/routes/users.$userId.tsx b/examples/react/start-basic-static/src/routes/users.$userId.tsx index 2e163f86ef..2d2d32279d 100644 --- a/examples/react/start-basic-static/src/routes/users.$userId.tsx +++ b/examples/react/start-basic-static/src/routes/users.$userId.tsx @@ -8,7 +8,7 @@ import { staticFunctionMiddleware } from '@tanstack/start-static-server-function const fetchUser = createServerFn({ method: 'GET' }) .middleware([staticFunctionMiddleware]) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data: userId }) => { return axios .get('https://jsonplaceholder.typicode.com/users/' + userId) diff --git a/examples/react/start-basic-static/src/styles/app.css b/examples/react/start-basic-static/src/styles/app.css index d6426ccb72..fa96982706 100644 --- a/examples/react/start-basic-static/src/styles/app.css +++ b/examples/react/start-basic-static/src/styles/app.css @@ -1,6 +1,24 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; +@import 'tailwindcss' source('../'); + +@source '../**/*.{js,jsx,ts,tsx}'; + +/* + The default border color has changed to `currentcolor` in Tailwind CSS v4, + so we've added these compatibility styles to make sure everything still + looks the same as it did with Tailwind CSS v3. + + If we ever want to remove these styles, we need to add an explicit border + color utility to any element that depends on these defaults. +*/ +@layer base { + *, + ::after, + ::before, + ::backdrop, + ::file-selector-button { + border-color: var(--color-gray-200, currentcolor); + } +} @layer base { html, diff --git a/examples/react/start-basic-static/src/utils/posts.tsx b/examples/react/start-basic-static/src/utils/posts.tsx index 5f01de769a..82e568ceef 100644 --- a/examples/react/start-basic-static/src/utils/posts.tsx +++ b/examples/react/start-basic-static/src/utils/posts.tsx @@ -12,7 +12,7 @@ export type PostType = { export const fetchPost = createServerFn({ method: 'GET' }) .middleware([logMiddleware, staticFunctionMiddleware]) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const post = await axios diff --git a/examples/react/start-basic-static/tailwind.config.cjs b/examples/react/start-basic-static/tailwind.config.cjs deleted file mode 100644 index 10c9224f8c..0000000000 --- a/examples/react/start-basic-static/tailwind.config.cjs +++ /dev/null @@ -1,4 +0,0 @@ -/** @type {import('tailwindcss').Config} */ -module.exports = { - content: ['./src/**/*.{js,ts,jsx,tsx}'], -} diff --git a/examples/react/start-basic-static/tsconfig.json b/examples/react/start-basic-static/tsconfig.json index 3a9fb7cd71..cef9369516 100644 --- a/examples/react/start-basic-static/tsconfig.json +++ b/examples/react/start-basic-static/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-basic-static/vite.config.ts b/examples/react/start-basic-static/vite.config.ts index f8f3877767..d7ecaddd27 100644 --- a/examples/react/start-basic-static/vite.config.ts +++ b/examples/react/start-basic-static/vite.config.ts @@ -1,16 +1,18 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ + base: '/test/', server: { port: 3000, }, + resolve: { + tsconfigPaths: true, + }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), + tailwindcss(), tanstackStart({ spa: { enabled: true, diff --git a/examples/react/start-basic/.devcontainer/devcontainer.json b/examples/react/start-basic/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-basic/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-basic/package.json b/examples/react/start-basic/package.json index 0c1a51ea44..46df8e4650 100644 --- a/examples/react/start-basic/package.json +++ b/examples/react/start-basic/package.json @@ -10,24 +10,24 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwind-merge": "^2.6.0", - "zod": "^3.24.2" + "tailwind-merge": "^3.6.0", + "zod": "^4.4.3" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.6.0", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-react": "^6.0.1", + "nitro": "^3.0.260903-beta", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-basic/postcss.config.mjs b/examples/react/start-basic/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/start-basic/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/start-basic/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic/src/components/DefaultCatchBoundary.tsx index 260c2ea41f..4a22649ed4 100644 --- a/examples/react/start-basic/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-basic/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error('DefaultCatchBoundary Error:', error) diff --git a/examples/react/start-basic/src/routeTree.gen.ts b/examples/react/start-basic/src/routeTree.gen.ts index 06a64190d7..57b849492d 100644 --- a/examples/react/start-basic/src/routeTree.gen.ts +++ b/examples/react/start-basic/src/routeTree.gen.ts @@ -9,42 +9,31 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ @@ -52,38 +41,24 @@ const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ path: '/customScript.js', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -91,28 +66,53 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => ApiUsersRoute, + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,32 +234,18 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } '/customScript.js': { @@ -269,47 +255,40 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof CustomScriptDotjsRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout': { - id: '/_pathlessLayout' + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/api/users': { id: '/api/users' @@ -318,26 +297,40 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute } - '/api/users/$userId': { - id: '/api/users/$userId' + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -346,12 +339,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/react/start-basic/src/routes/api/users.$userId.ts b/examples/react/start-basic/src/routes/api/users.$userId.ts index 2ae7eb9c04..ee34d7a189 100644 --- a/examples/react/start-basic/src/routes/api/users.$userId.ts +++ b/examples/react/start-basic/src/routes/api/users.$userId.ts @@ -1,5 +1,4 @@ import { createFileRoute } from '@tanstack/react-router' -import { json } from '@tanstack/react-start' import type { User } from '~/utils/users' export const Route = createFileRoute('/api/users/$userId')({ @@ -17,14 +16,14 @@ export const Route = createFileRoute('/api/users/$userId')({ const user = (await res.json()) as User - return json({ + return Response.json({ id: user.id, name: user.name, email: user.email, }) } catch (e) { console.error(e) - return json({ error: 'User not found' }, { status: 404 }) + return Response.json({ error: 'User not found' }, { status: 404 }) } }, }, diff --git a/examples/react/start-basic/src/routes/api/users.ts b/examples/react/start-basic/src/routes/api/users.ts index c1e7473b0c..4cecd01852 100644 --- a/examples/react/start-basic/src/routes/api/users.ts +++ b/examples/react/start-basic/src/routes/api/users.ts @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/react-router' import { getRequestHeaders } from '@tanstack/react-start/server' -import { createMiddleware, json } from '@tanstack/react-start' +import { createMiddleware } from '@tanstack/react-start' import type { User } from '~/utils/users' const userLoggerMiddleware = createMiddleware().server(async ({ next }) => { @@ -54,7 +54,7 @@ export const Route = createFileRoute('/api/users')({ const list = data.slice(0, 10) - return json( + return Response.json( list.map((u) => ({ id: u.id, name: u.name, email: u.email })), ) }, diff --git a/examples/react/start-basic/src/routes/deferred.tsx b/examples/react/start-basic/src/routes/deferred.tsx index c38808243e..f3e09d1d4e 100644 --- a/examples/react/start-basic/src/routes/deferred.tsx +++ b/examples/react/start-basic/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/react-start' import { Suspense, useState } from 'react' const personServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/examples/react/start-basic/src/routes/users.$userId.tsx b/examples/react/start-basic/src/routes/users.$userId.tsx index 1df768344d..4e4d470075 100644 --- a/examples/react/start-basic/src/routes/users.$userId.tsx +++ b/examples/react/start-basic/src/routes/users.$userId.tsx @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/react-router' -import { NotFound } from 'src/components/NotFound' -import { UserErrorComponent } from 'src/components/UserError' +import { NotFound } from '../components/NotFound' +import { UserErrorComponent } from '../components/UserError' import type { User } from '../utils/users' export const Route = createFileRoute('/users/$userId')({ diff --git a/examples/react/start-basic/src/styles/app.css b/examples/react/start-basic/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/react/start-basic/src/styles/app.css +++ b/examples/react/start-basic/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/start-basic/src/utils/posts.tsx b/examples/react/start-basic/src/utils/posts.tsx index d913ffe3d9..ea7dd0a721 100644 --- a/examples/react/start-basic/src/utils/posts.tsx +++ b/examples/react/start-basic/src/utils/posts.tsx @@ -8,9 +8,8 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'POST' }) - .inputValidator((d: string) => d) - .handler(async ({ data, context }) => { - console.log('Request context:', context) + .validator((d: string) => d) + .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const res = await fetch( `https://jsonplaceholder.typicode.com/posts/${data}`, diff --git a/examples/react/start-basic/tsconfig.json b/examples/react/start-basic/tsconfig.json index 3a9fb7cd71..cc479423a1 100644 --- a/examples/react/start-basic/tsconfig.json +++ b/examples/react/start-basic/tsconfig.json @@ -1,19 +1,18 @@ { - "include": ["**/*.ts", "**/*.tsx"], + "include": ["**/*.ts", "**/*.tsx", "**/*.d.ts"], "compilerOptions": { "strict": true, "esModuleInterop": true, "jsx": "react-jsx", "module": "ESNext", "moduleResolution": "Bundler", - "lib": ["DOM", "DOM.Iterable", "ES2022"], + "lib": ["DOM", "DOM.Iterable", "ES2024"], "isolatedModules": true, "resolveJsonModule": true, "skipLibCheck": true, - "target": "ES2022", + "target": "ES2024", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-basic/vite.config.ts b/examples/react/start-basic/vite.config.ts index c7851284b6..65fa77fd66 100644 --- a/examples/react/start-basic/vite.config.ts +++ b/examples/react/start-basic/vite.config.ts @@ -1,19 +1,22 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' +import { nitro } from 'nitro/vite' export default defineConfig({ server: { port: 3000, }, + resolve: { + tsconfigPaths: true, + }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), + tailwindcss(), tanstackStart({ srcDirectory: 'src', }), viteReact(), + nitro(), ], }) diff --git a/examples/react/start-bun/.devcontainer/devcontainer.json b/examples/react/start-bun/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-bun/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-bun/package.json b/examples/react/start-bun/package.json index 1cedcf8859..24f7113912 100644 --- a/examples/react/start-bun/package.json +++ b/examples/react/start-bun/package.json @@ -13,17 +13,16 @@ "check": "prettier --write . && eslint --fix" }, "dependencies": { - "@tailwindcss/vite": "^4.1.17", + "@tailwindcss/vite": "^4.2.2", "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-router-ssr-query": "^1.141.8", - "@tanstack/react-start": "^1.142.0", - "@tanstack/router-plugin": "^1.142.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", "react": "^19.1.1", "react-dom": "^19.1.1", - "tailwindcss": "^4.1.13", - "vite-tsconfig-paths": "^5.1.4" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@tanstack/eslint-config": "^0.3.2", @@ -33,12 +32,13 @@ "@types/node": "22.10.2", "@types/react": "^19.1.13", "@types/react-dom": "^19.1.9", - "@vitejs/plugin-react": "^5.0.3", + "@vitejs/plugin-react": "^6.0.1", "jsdom": "^27.0.0", "prettier": "^3.6.2", - "typescript": "^5.9.2", - "vite": "^7.1.7", - "vitest": "^3.2.4", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vitest": "^5.0.4", "web-vitals": "^5.1.0" } } diff --git a/examples/react/start-bun/src/routeTree.gen.ts b/examples/react/start-bun/src/routeTree.gen.ts index 18fbc9b60e..77415f9088 100644 --- a/examples/react/start-bun/src/routeTree.gen.ts +++ b/examples/react/start-bun/src/routeTree.gen.ts @@ -11,8 +11,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as ApiDemoNamesRouteImport } from './routes/api.demo-names' -import { Route as DemoStartServerFuncsRouteImport } from './routes/demo.start.server-funcs' import { Route as DemoStartApiRequestRouteImport } from './routes/demo.start.api-request' +import { Route as DemoStartServerFuncsRouteImport } from './routes/demo.start.server-funcs' const IndexRoute = IndexRouteImport.update({ id: '/', @@ -24,16 +24,16 @@ const ApiDemoNamesRoute = ApiDemoNamesRouteImport.update({ path: '/api/demo-names', getParentRoute: () => rootRouteImport, } as any) -const DemoStartServerFuncsRoute = DemoStartServerFuncsRouteImport.update({ - id: '/demo/start/server-funcs', - path: '/demo/start/server-funcs', - getParentRoute: () => rootRouteImport, -} as any) const DemoStartApiRequestRoute = DemoStartApiRequestRouteImport.update({ id: '/demo/start/api-request', path: '/demo/start/api-request', getParentRoute: () => rootRouteImport, } as any) +const DemoStartServerFuncsRoute = DemoStartServerFuncsRouteImport.update({ + id: '/demo/start/server-funcs', + path: '/demo/start/server-funcs', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -98,13 +98,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiDemoNamesRouteImport parentRoute: typeof rootRouteImport } - '/demo/start/server-funcs': { - id: '/demo/start/server-funcs' - path: '/demo/start/server-funcs' - fullPath: '/demo/start/server-funcs' - preLoaderRoute: typeof DemoStartServerFuncsRouteImport - parentRoute: typeof rootRouteImport - } '/demo/start/api-request': { id: '/demo/start/api-request' path: '/demo/start/api-request' @@ -112,6 +105,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DemoStartApiRequestRouteImport parentRoute: typeof rootRouteImport } + '/demo/start/server-funcs': { + id: '/demo/start/server-funcs' + path: '/demo/start/server-funcs' + fullPath: '/demo/start/server-funcs' + preLoaderRoute: typeof DemoStartServerFuncsRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/start-bun/src/routes/demo.start.server-funcs.tsx b/examples/react/start-bun/src/routes/demo.start.server-funcs.tsx index e1a132aa1d..64629c0bdc 100644 --- a/examples/react/start-bun/src/routes/demo.start.server-funcs.tsx +++ b/examples/react/start-bun/src/routes/demo.start.server-funcs.tsx @@ -25,7 +25,7 @@ const getTodos = createServerFn({ }).handler(async () => await readTodos()) const addTodo = createServerFn({ method: 'POST' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data }) => { const todos = await readTodos() todos.push({ id: todos.length + 1, name: data }) diff --git a/examples/react/start-bun/src/styles.css b/examples/react/start-bun/src/styles.css index 06f1bca4b0..f59c071ef6 100644 --- a/examples/react/start-bun/src/styles.css +++ b/examples/react/start-bun/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); body { @apply m-0; diff --git a/examples/react/start-bun/src/vite-env.d.ts b/examples/react/start-bun/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/start-bun/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/start-bun/tsconfig.json b/examples/react/start-bun/tsconfig.json index 2cc3abd5d4..2f09fb43be 100644 --- a/examples/react/start-bun/tsconfig.json +++ b/examples/react/start-bun/tsconfig.json @@ -27,7 +27,6 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, - "baseUrl": ".", "paths": { "@/*": ["./src/*"] } diff --git a/examples/react/start-bun/vite.config.ts b/examples/react/start-bun/vite.config.ts index 206769f502..1e5ca9d8db 100644 --- a/examples/react/start-bun/vite.config.ts +++ b/examples/react/start-bun/vite.config.ts @@ -1,19 +1,13 @@ import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' -import viteTsConfigPaths from 'vite-tsconfig-paths' import tailwindcss from '@tailwindcss/vite' const config = defineConfig({ - plugins: [ - // this is the plugin that enables path aliases - viteTsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tailwindcss(), - tanstackStart(), - viteReact(), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteReact()], }) export default config diff --git a/examples/react/start-clerk-basic/.devcontainer/devcontainer.json b/examples/react/start-clerk-basic/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-clerk-basic/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-clerk-basic/package.json b/examples/react/start-clerk-basic/package.json index 78ff89ec33..022300e159 100644 --- a/examples/react/start-clerk-basic/package.json +++ b/examples/react/start-clerk-basic/package.json @@ -10,26 +10,25 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@clerk/tanstack-react-start": "^0.26.3", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", - "@vitejs/plugin-react": "^4.3.4", + "@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", + "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "srvx": "^0.9.8", - "tailwind-merge": "^2.6.0" + "srvx": "^1.0.0", + "tailwind-merge": "^3.6.0" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-clerk-basic/postcss.config.mjs b/examples/react/start-clerk-basic/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/start-clerk-basic/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx b/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx index ef2daa1ea1..405fb5f4a7 100644 --- a/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-clerk-basic/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error(error) diff --git a/examples/react/start-clerk-basic/src/routeTree.gen.ts b/examples/react/start-clerk-basic/src/routeTree.gen.ts index baaabbc2c0..87269f2faf 100644 --- a/examples/react/start-clerk-basic/src/routeTree.gen.ts +++ b/examples/react/start-clerk-basic/src/routeTree.gen.ts @@ -9,22 +9,22 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' -import { Route as AuthedProfileSplatRouteImport } from './routes/_authed/profile.$' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' +import { Route as AuthedProfileSplatRouteImport } from './routes/_authed/profile.$' -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ id: '/posts', path: '/posts', @@ -35,16 +35,16 @@ const AuthedPostsIndexRoute = AuthedPostsIndexRouteImport.update({ path: '/', getParentRoute: () => AuthedPostsRoute, } as any) -const AuthedProfileSplatRoute = AuthedProfileSplatRouteImport.update({ - id: '/profile/$', - path: '/profile/$', - getParentRoute: () => AuthedRoute, -} as any) const AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => AuthedPostsRoute, } as any) +const AuthedProfileSplatRoute = AuthedProfileSplatRouteImport.update({ + id: '/profile/$', + path: '/profile/$', + getParentRoute: () => AuthedRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -90,13 +90,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/_authed': { - id: '/_authed' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -104,6 +97,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } '/_authed/posts': { id: '/_authed/posts' path: '/posts' @@ -118,13 +118,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedPostsIndexRouteImport parentRoute: typeof AuthedPostsRoute } - '/_authed/profile/$': { - id: '/_authed/profile/$' - path: '/profile/$' - fullPath: '/profile/$' - preLoaderRoute: typeof AuthedProfileSplatRouteImport - parentRoute: typeof AuthedRoute - } '/_authed/posts/$postId': { id: '/_authed/posts/$postId' path: '/$postId' @@ -132,6 +125,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedPostsPostIdRouteImport parentRoute: typeof AuthedPostsRoute } + '/_authed/profile/$': { + id: '/_authed/profile/$' + path: '/profile/$' + fullPath: '/profile/$' + preLoaderRoute: typeof AuthedProfileSplatRouteImport + parentRoute: typeof AuthedRoute + } } } diff --git a/examples/react/start-clerk-basic/src/routes/_authed.tsx b/examples/react/start-clerk-basic/src/routes/_authed.tsx index 1a97917c12..04f8196894 100644 --- a/examples/react/start-clerk-basic/src/routes/_authed.tsx +++ b/examples/react/start-clerk-basic/src/routes/_authed.tsx @@ -8,7 +8,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return (

    diff --git a/examples/react/start-clerk-basic/src/styles/app.css b/examples/react/start-clerk-basic/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/react/start-clerk-basic/src/styles/app.css +++ b/examples/react/start-clerk-basic/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/start-clerk-basic/src/utils/posts.ts b/examples/react/start-clerk-basic/src/utils/posts.ts index fbcc43c34b..a7e0e99cfa 100644 --- a/examples/react/start-clerk-basic/src/utils/posts.ts +++ b/examples/react/start-clerk-basic/src/utils/posts.ts @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) + .validator((postId: string) => postId) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const post = await axios diff --git a/examples/react/start-clerk-basic/tsconfig.json b/examples/react/start-clerk-basic/tsconfig.json index 3a9fb7cd71..cef9369516 100644 --- a/examples/react/start-clerk-basic/tsconfig.json +++ b/examples/react/start-clerk-basic/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-clerk-basic/vite.config.ts b/examples/react/start-clerk-basic/vite.config.ts index f10c86e79f..debc272ace 100644 --- a/examples/react/start-clerk-basic/vite.config.ts +++ b/examples/react/start-clerk-basic/vite.config.ts @@ -1,17 +1,18 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], + plugins: [tailwindcss(), tanstackStart(), viteReact()], + // See https://github.com/TanStack/router/issues/5738 + resolve: { + tsconfigPaths: true, + alias: [ + { find: 'use-sync-external-store/shim/index.js', replacement: 'react' }, + ], + }, }) diff --git a/examples/react/start-convex-trellaux/.devcontainer/devcontainer.json b/examples/react/start-convex-trellaux/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-convex-trellaux/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-convex-trellaux/convex/board.ts b/examples/react/start-convex-trellaux/convex/board.ts index bae241a773..f585a01cd3 100644 --- a/examples/react/start-convex-trellaux/convex/board.ts +++ b/examples/react/start-convex-trellaux/convex/board.ts @@ -1,4 +1,4 @@ -import invariant from 'tiny-invariant' +import { invariant } from './invariant' import { v } from 'convex/values' import { type QueryCtx, diff --git a/examples/react/start-convex-trellaux/convex/invariant.ts b/examples/react/start-convex-trellaux/convex/invariant.ts new file mode 100644 index 0000000000..41fcded35e --- /dev/null +++ b/examples/react/start-convex-trellaux/convex/invariant.ts @@ -0,0 +1,5 @@ +export function invariant(value: unknown, message?: string): asserts value { + if (!value) { + throw new Error(message ?? 'Invariant failed') + } +} diff --git a/examples/react/start-convex-trellaux/package.json b/examples/react/start-convex-trellaux/package.json index af094b329a..3452f910d0 100644 --- a/examples/react/start-convex-trellaux/package.json +++ b/examples/react/start-convex-trellaux/package.json @@ -13,12 +13,12 @@ }, "dependencies": { "@convex-dev/react-query": "0.0.0-alpha.8", - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-router-ssr-query": "^1.141.8", - "@tanstack/react-start": "^1.142.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", "concurrently": "^8.2.2", "convex": "^1.19.0", "ky": "^1.7.4", @@ -27,20 +27,18 @@ "react-dom": "^19.0.0", "react-hot-toast": "^2.5.1", "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "tiny-invariant": "^1.3.3", - "zod": "^3.24.2" + "tailwind-merge": "^3.6.0", + "zod": "^4.4.3" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-react": "^6.0.1", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-convex-trellaux/postcss.config.mjs b/examples/react/start-convex-trellaux/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/start-convex-trellaux/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/start-convex-trellaux/src/components/Board.tsx b/examples/react/start-convex-trellaux/src/components/Board.tsx index 327603e204..ac78c7baae 100644 --- a/examples/react/start-convex-trellaux/src/components/Board.tsx +++ b/examples/react/start-convex-trellaux/src/components/Board.tsx @@ -1,5 +1,5 @@ import { useCallback, useMemo, useRef } from 'react' -import invariant from 'tiny-invariant' +import { invariant } from '../invariant' import { useSuspenseQuery } from '@tanstack/react-query' import { convexQuery } from '@convex-dev/react-query' import { api } from '../../convex/_generated/api.js' diff --git a/examples/react/start-convex-trellaux/src/components/Card.tsx b/examples/react/start-convex-trellaux/src/components/Card.tsx index eacf87d759..23f77ca2b2 100644 --- a/examples/react/start-convex-trellaux/src/components/Card.tsx +++ b/examples/react/start-convex-trellaux/src/components/Card.tsx @@ -1,4 +1,4 @@ -import invariant from 'tiny-invariant' +import { invariant } from '../invariant' import { forwardRef, useState } from 'react' import { CONTENT_TYPES } from '../types' diff --git a/examples/react/start-convex-trellaux/src/components/Column.tsx b/examples/react/start-convex-trellaux/src/components/Column.tsx index dd90e02ee7..fdf2916f6b 100644 --- a/examples/react/start-convex-trellaux/src/components/Column.tsx +++ b/examples/react/start-convex-trellaux/src/components/Column.tsx @@ -1,8 +1,8 @@ import { forwardRef, useCallback, useMemo, useRef, useState } from 'react' -import invariant from 'tiny-invariant' import { twMerge } from 'tailwind-merge' import { flushSync } from 'react-dom' +import { invariant } from '../invariant' import { CONTENT_TYPES } from '../types' import { Icon } from '../icons/icons' import { diff --git a/examples/react/start-convex-trellaux/src/components/DefaultCatchBoundary.tsx b/examples/react/start-convex-trellaux/src/components/DefaultCatchBoundary.tsx index ef2daa1ea1..405fb5f4a7 100644 --- a/examples/react/start-convex-trellaux/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-convex-trellaux/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error(error) diff --git a/examples/react/start-convex-trellaux/src/components/NewCard.tsx b/examples/react/start-convex-trellaux/src/components/NewCard.tsx index 47cadcf5ae..99b0b14839 100644 --- a/examples/react/start-convex-trellaux/src/components/NewCard.tsx +++ b/examples/react/start-convex-trellaux/src/components/NewCard.tsx @@ -1,5 +1,5 @@ import { useRef } from 'react' -import invariant from 'tiny-invariant' +import { invariant } from '../invariant' import { ItemMutationFields } from '../types' import { useCreateItemMutation } from '../queries' diff --git a/examples/react/start-convex-trellaux/src/components/NewColumn.tsx b/examples/react/start-convex-trellaux/src/components/NewColumn.tsx index 50a7d608c5..0cd1f6aa53 100644 --- a/examples/react/start-convex-trellaux/src/components/NewColumn.tsx +++ b/examples/react/start-convex-trellaux/src/components/NewColumn.tsx @@ -1,5 +1,5 @@ import { useRef, useState } from 'react' -import invariant from 'tiny-invariant' +import { invariant } from '../invariant' import { Icon } from '../icons/icons' import { useCreateColumnMutation } from '../queries' diff --git a/examples/react/start-convex-trellaux/src/db/schema.ts b/examples/react/start-convex-trellaux/src/db/schema.ts index 99bd5e220b..74c449e894 100644 --- a/examples/react/start-convex-trellaux/src/db/schema.ts +++ b/examples/react/start-convex-trellaux/src/db/schema.ts @@ -6,9 +6,9 @@ export const itemSchema = z.object({ id: z.string(), title: z.string(), content: z.string().optional(), - order: z.coerce.number(), + order: z.coerce.number(), columnId: z.string().uuid(), - boardId: z.coerce.string(), + boardId: z.coerce.string(), }) export const deleteItemSchema = itemSchema.pick({ id: true, boardId: true }) diff --git a/examples/react/start-convex-trellaux/src/invariant.ts b/examples/react/start-convex-trellaux/src/invariant.ts new file mode 100644 index 0000000000..41fcded35e --- /dev/null +++ b/examples/react/start-convex-trellaux/src/invariant.ts @@ -0,0 +1,5 @@ +export function invariant(value: unknown, message?: string): asserts value { + if (!value) { + throw new Error(message ?? 'Invariant failed') + } +} diff --git a/examples/react/start-convex-trellaux/src/styles/app.css b/examples/react/start-convex-trellaux/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/react/start-convex-trellaux/src/styles/app.css +++ b/examples/react/start-convex-trellaux/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/start-convex-trellaux/src/utils/posts.tsx b/examples/react/start-convex-trellaux/src/utils/posts.tsx index cf602f9827..e87764806d 100644 --- a/examples/react/start-convex-trellaux/src/utils/posts.tsx +++ b/examples/react/start-convex-trellaux/src/utils/posts.tsx @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) + .validator((postId: string) => postId) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const post = await axios diff --git a/examples/react/start-convex-trellaux/tsconfig.json b/examples/react/start-convex-trellaux/tsconfig.json index 3a9fb7cd71..8de1ae61be 100644 --- a/examples/react/start-convex-trellaux/tsconfig.json +++ b/examples/react/start-convex-trellaux/tsconfig.json @@ -13,9 +13,9 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { - "~/*": ["./src/*"] + "~/*": ["./src/*"], + "convex/*": ["./convex/*"] }, "noEmit": true } diff --git a/examples/react/start-convex-trellaux/vite.config.ts b/examples/react/start-convex-trellaux/vite.config.ts index f10c86e79f..ed6799764a 100644 --- a/examples/react/start-convex-trellaux/vite.config.ts +++ b/examples/react/start-convex-trellaux/vite.config.ts @@ -1,17 +1,14 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteReact()], }) diff --git a/examples/react/start-counter/.devcontainer/devcontainer.json b/examples/react/start-counter/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-counter/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-counter/package.json b/examples/react/start-counter/package.json index 259b730ecd..8f4673143e 100644 --- a/examples/react/start-counter/package.json +++ b/examples/react/start-counter/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0" }, @@ -20,8 +20,9 @@ "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-counter/src/routes/index.tsx b/examples/react/start-counter/src/routes/index.tsx index 0faec87836..b95cc76ec8 100644 --- a/examples/react/start-counter/src/routes/index.tsx +++ b/examples/react/start-counter/src/routes/index.tsx @@ -15,7 +15,7 @@ const getCount = createServerFn({ method: 'GET' }).handler(() => { }) const updateCount = createServerFn({ method: 'POST' }) - .inputValidator((addBy: number) => addBy) + .validator((addBy: number) => addBy) .handler(async ({ data }) => { const count = await readCount() await fs.promises.writeFile(filePath, `${count + data}`) diff --git a/examples/react/start-counter/tsconfig.json b/examples/react/start-counter/tsconfig.json index 3a9fb7cd71..cef9369516 100644 --- a/examples/react/start-counter/tsconfig.json +++ b/examples/react/start-counter/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-i18n-paraglide/.devcontainer/devcontainer.json b/examples/react/start-i18n-paraglide/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-i18n-paraglide/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-i18n-paraglide/README.md b/examples/react/start-i18n-paraglide/README.md index f1aa91f518..7c6433440d 100644 --- a/examples/react/start-i18n-paraglide/README.md +++ b/examples/react/start-i18n-paraglide/README.md @@ -1,6 +1,6 @@ # TanStack Start example with Paraglide -This example shows how to use Paraglide with TanStack Start. The source code can be found [in the Paraglide monorepo](https://github.com/opral/monorepo/tree/main/inlang/packages/paraglide/paraglide-js/examples/tanstack-start). +This example shows how to use Paraglide with TanStack Start. - [TanStack Router Docs](https://tanstack.com/router) - [Paraglide Documentation](https://inlang.com/m/gerre34r/library-inlang-paraglideJs) @@ -81,7 +81,7 @@ import { paraglideMiddleware } from './paraglide/server.js' import handler from '@tanstack/react-start/server-entry' export default { fetch(req: Request): Promise { - return paraglideMiddleware(req, ({ request }) => handler.fetch(request)) + return paraglideMiddleware(req, () => handler.fetch(req)) }, } ``` @@ -130,6 +130,7 @@ export const Route = createRootRoute({ If you don't want to miss any translated path, you can create a `createTranslatedPathnames` function and pass it to the vite plugin. ```ts +// i18n/lib.ts import { Locale } from '@/paraglide/runtime' import { FileRoutesByTo } from '../routeTree.gen' @@ -190,6 +191,20 @@ export const translatedPathnames = createTranslatedPathnames({ And import into the Paraglide Vite plugin. +```ts +// vite.config.ts +import { translatedPathnames } from './i18n/lib' + +export default defineConfig({ + plugins: [ + paraglideVitePlugin({ + // ... other options + urlPatterns: translatedPathnames, + }), + ], +}) +``` + ## Prerender routes You can use the `localizeHref` function to map the routes to localized versions and import into the pages option in the TanStack Start plugin. For this to work you will need to compile paraglide before the build with the CLI. diff --git a/examples/react/start-i18n-paraglide/package.json b/examples/react/start-i18n-paraglide/package.json index 183b641983..074f714d5c 100644 --- a/examples/react/start-i18n-paraglide/package.json +++ b/examples/react/start-i18n-paraglide/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.1.1", "react-dom": "^19.1.1" }, @@ -20,12 +20,23 @@ "@types/node": "^22.18.6", "@types/react": "^19.1.13", "@types/react-dom": "^19.1.9", - "@vitejs/plugin-react": "^4.7.0", - "typescript": "^5.9.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4", - "@tailwindcss/vite": "^4.1.17", - "tailwindcss": "^4.1.13", + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "@tailwindcss/vite": "^4.2.2", + "tailwindcss": "^4.2.2", "@inlang/paraglide-js": "^2.4.0" + }, + "nx": { + "targets": { + "build": { + "outputs": [ + "...", + "{projectRoot}/src/paraglide", + "{projectRoot}/project.inlang/cache" + ] + } + } } } diff --git a/examples/react/start-i18n-paraglide/src/routeTree.gen.ts b/examples/react/start-i18n-paraglide/src/routeTree.gen.ts index 421daf2790..d89758e684 100644 --- a/examples/react/start-i18n-paraglide/src/routeTree.gen.ts +++ b/examples/react/start-i18n-paraglide/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/start-i18n-paraglide/src/routes/index.tsx b/examples/react/start-i18n-paraglide/src/routes/index.tsx index 6a9efa6f88..84aa381436 100644 --- a/examples/react/start-i18n-paraglide/src/routes/index.tsx +++ b/examples/react/start-i18n-paraglide/src/routes/index.tsx @@ -4,7 +4,7 @@ import { getLocale } from '@/paraglide/runtime.js' import { createServerFn } from '@tanstack/react-start' const getServerMessage = createServerFn() - .inputValidator((emoji: string) => emoji) + .validator((emoji: string) => emoji) .handler((ctx) => { return m.server_message({ emoji: ctx.data }) }) diff --git a/examples/react/start-i18n-paraglide/src/server.ts b/examples/react/start-i18n-paraglide/src/server.ts index 9542b01d4a..d4dc80a8de 100644 --- a/examples/react/start-i18n-paraglide/src/server.ts +++ b/examples/react/start-i18n-paraglide/src/server.ts @@ -3,6 +3,6 @@ import handler from '@tanstack/react-start/server-entry' export default { fetch(req: Request): Promise { - return paraglideMiddleware(req, ({ request }) => handler.fetch(request)) + return paraglideMiddleware(req, () => handler.fetch(req)) }, } diff --git a/examples/react/start-i18n-paraglide/src/styles.css b/examples/react/start-i18n-paraglide/src/styles.css index d4b5078586..23fa2415ca 100644 --- a/examples/react/start-i18n-paraglide/src/styles.css +++ b/examples/react/start-i18n-paraglide/src/styles.css @@ -1 +1 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); diff --git a/examples/react/start-i18n-paraglide/src/vite-env.d.ts b/examples/react/start-i18n-paraglide/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/start-i18n-paraglide/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/start-i18n-paraglide/tsconfig.json b/examples/react/start-i18n-paraglide/tsconfig.json index 3e42c72626..471d55aed8 100644 --- a/examples/react/start-i18n-paraglide/tsconfig.json +++ b/examples/react/start-i18n-paraglide/tsconfig.json @@ -21,7 +21,6 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, - "baseUrl": ".", "paths": { "@/*": ["./src/*"] } diff --git a/examples/react/start-i18n-paraglide/vite.config.ts b/examples/react/start-i18n-paraglide/vite.config.ts index a0d8a6f77e..f1cb822199 100644 --- a/examples/react/start-i18n-paraglide/vite.config.ts +++ b/examples/react/start-i18n-paraglide/vite.config.ts @@ -2,10 +2,12 @@ import { paraglideVitePlugin } from '@inlang/paraglide-js' import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import viteReact from '@vitejs/plugin-react' -import viteTsConfigPaths from 'vite-tsconfig-paths' import tailwindcss from '@tailwindcss/vite' const config = defineConfig({ + resolve: { + tsconfigPaths: true, + }, plugins: [ paraglideVitePlugin({ project: './project.inlang', @@ -37,7 +39,6 @@ const config = defineConfig({ }, ], }), - viteTsConfigPaths(), tanstackStart(), viteReact(), tailwindcss(), diff --git a/examples/react/start-large/.devcontainer/devcontainer.json b/examples/react/start-large/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-large/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-large/package.json b/examples/react/start-large/package.json index 8c2142073e..f9f86b81d1 100644 --- a/examples/react/start-large/package.json +++ b/examples/react/start-large/package.json @@ -12,27 +12,26 @@ "test:types": "tsc --extendedDiagnostics" }, "dependencies": { - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", + "tailwind-merge": "^3.6.0", "valibot": "^1.0.0-beta.15" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-react": "^6.0.1", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" }, "keywords": [], "author": "", diff --git a/examples/react/start-large/postcss.config.mjs b/examples/react/start-large/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/start-large/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/start-large/src/routeTree.gen.ts b/examples/react/start-large/src/routeTree.gen.ts index 03cc2b9080..4f1551f71d 100644 --- a/examples/react/start-large/src/routeTree.gen.ts +++ b/examples/react/start-large/src/routeTree.gen.ts @@ -9,23 +9,18 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as RelativeRouteImport } from './routes/relative' -import { Route as LinkPropsRouteImport } from './routes/linkProps' -import { Route as AbsoluteRouteImport } from './routes/absolute' -import { Route as SearchRouteRouteImport } from './routes/search/route' -import { Route as ParamsRouteRouteImport } from './routes/params/route' import { Route as IndexRouteImport } from './routes/index' -import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' +import { Route as AbsoluteRouteImport } from './routes/absolute' +import { Route as LinkPropsRouteImport } from './routes/linkProps' +import { Route as ParamsRouteRouteImport } from './routes/params/route' +import { Route as RelativeRouteImport } from './routes/relative' +import { Route as SearchRouteRouteImport } from './routes/search/route' import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' +import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' -const RelativeRoute = RelativeRouteImport.update({ - id: '/relative', - path: '/relative', - getParentRoute: () => rootRouteImport, -} as any) -const LinkPropsRoute = LinkPropsRouteImport.update({ - id: '/linkProps', - path: '/linkProps', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AbsoluteRoute = AbsoluteRouteImport.update({ @@ -33,9 +28,9 @@ const AbsoluteRoute = AbsoluteRouteImport.update({ path: '/absolute', getParentRoute: () => rootRouteImport, } as any) -const SearchRouteRoute = SearchRouteRouteImport.update({ - id: '/search', - path: '/search', +const LinkPropsRoute = LinkPropsRouteImport.update({ + id: '/linkProps', + path: '/linkProps', getParentRoute: () => rootRouteImport, } as any) const ParamsRouteRoute = ParamsRouteRouteImport.update({ @@ -43,21 +38,26 @@ const ParamsRouteRoute = ParamsRouteRouteImport.update({ path: '/params', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RelativeRoute = RelativeRouteImport.update({ + id: '/relative', + path: '/relative', getParentRoute: () => rootRouteImport, } as any) -const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ - id: '/searchPlaceholder', - path: '/searchPlaceholder', - getParentRoute: () => SearchRouteRoute, +const SearchRouteRoute = SearchRouteRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, } as any) const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ id: '/$paramsPlaceholder', path: '/$paramsPlaceholder', getParentRoute: () => ParamsRouteRoute, } as any) +const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ + id: '/searchPlaceholder', + path: '/searchPlaceholder', + getParentRoute: () => SearchRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -134,18 +134,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/relative': { - id: '/relative' - path: '/relative' - fullPath: '/relative' - preLoaderRoute: typeof RelativeRouteImport - parentRoute: typeof rootRouteImport - } - '/linkProps': { - id: '/linkProps' - path: '/linkProps' - fullPath: '/linkProps' - preLoaderRoute: typeof LinkPropsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/absolute': { @@ -155,11 +148,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AbsoluteRouteImport parentRoute: typeof rootRouteImport } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteRouteImport + '/linkProps': { + id: '/linkProps' + path: '/linkProps' + fullPath: '/linkProps' + preLoaderRoute: typeof LinkPropsRouteImport parentRoute: typeof rootRouteImport } '/params': { @@ -169,19 +162,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ParamsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/relative': { + id: '/relative' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeRouteImport parentRoute: typeof rootRouteImport } - '/search/searchPlaceholder': { - id: '/search/searchPlaceholder' - path: '/searchPlaceholder' - fullPath: '/search/searchPlaceholder' - preLoaderRoute: typeof SearchSearchPlaceholderRouteImport - parentRoute: typeof SearchRouteRoute + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteRouteImport + parentRoute: typeof rootRouteImport } '/params/$paramsPlaceholder': { id: '/params/$paramsPlaceholder' @@ -190,6 +183,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport parentRoute: typeof ParamsRouteRoute } + '/search/searchPlaceholder': { + id: '/search/searchPlaceholder' + path: '/searchPlaceholder' + fullPath: '/search/searchPlaceholder' + preLoaderRoute: typeof SearchSearchPlaceholderRouteImport + parentRoute: typeof SearchRouteRoute + } } } diff --git a/examples/react/start-large/src/routes/params/$paramsPlaceholder.tsx b/examples/react/start-large/src/routes/params/$paramsPlaceholder.tsx index 568adb11be..7238dea314 100644 --- a/examples/react/start-large/src/routes/params/$paramsPlaceholder.tsx +++ b/examples/react/start-large/src/routes/params/$paramsPlaceholder.tsx @@ -15,7 +15,7 @@ const loaderResult = v.object({ }) const middleware = createMiddleware({ type: 'function' }) - .inputValidator(params) + .validator(params) .client(({ next }) => { const context = { client: { paramsPlaceholder: 'paramsPlaceholder' } } return next({ diff --git a/examples/react/start-large/src/routes/search/searchPlaceholder.tsx b/examples/react/start-large/src/routes/search/searchPlaceholder.tsx index bcf6bc777f..b8bdfbb453 100644 --- a/examples/react/start-large/src/routes/search/searchPlaceholder.tsx +++ b/examples/react/start-large/src/routes/search/searchPlaceholder.tsx @@ -15,7 +15,7 @@ const loaderResult = v.object({ }) const middleware = createMiddleware({ type: 'function' }) - .inputValidator(search) + .validator(search) .client(({ next }) => { const context = { client: { searchPlaceholder: 'searchPlaceholder' } } return next({ diff --git a/examples/react/start-large/src/styles.css b/examples/react/start-large/src/styles.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/react/start-large/src/styles.css +++ b/examples/react/start-large/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/start-large/tsconfig.json b/examples/react/start-large/tsconfig.json index 3a9fb7cd71..cef9369516 100644 --- a/examples/react/start-large/tsconfig.json +++ b/examples/react/start-large/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-large/vite.config.ts b/examples/react/start-large/vite.config.ts index f10c86e79f..ed6799764a 100644 --- a/examples/react/start-large/vite.config.ts +++ b/examples/react/start-large/vite.config.ts @@ -1,17 +1,14 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteReact()], }) diff --git a/examples/react/start-material-ui/.devcontainer/devcontainer.json b/examples/react/start-material-ui/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-material-ui/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-material-ui/package.json b/examples/react/start-material-ui/package.json index 25c1f3170d..1647e95f20 100644 --- a/examples/react/start-material-ui/package.json +++ b/examples/react/start-material-ui/package.json @@ -15,20 +15,20 @@ "@emotion/styled": "11.14.0", "@fontsource-variable/roboto": "5.2.5", "@mui/material": "6.4.7", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-start": "^1.142.0", - "@tanstack/react-router-devtools": "^1.141.8", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-material-ui/src/routeTree.gen.ts b/examples/react/start-material-ui/src/routeTree.gen.ts index 421daf2790..d89758e684 100644 --- a/examples/react/start-material-ui/src/routeTree.gen.ts +++ b/examples/react/start-material-ui/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/start-material-ui/src/router.tsx b/examples/react/start-material-ui/src/router.tsx index a464233af9..6f82cbf378 100644 --- a/examples/react/start-material-ui/src/router.tsx +++ b/examples/react/start-material-ui/src/router.tsx @@ -5,7 +5,9 @@ export function getRouter() { const router = createRouter({ routeTree, defaultPreload: 'intent', - defaultErrorComponent: (err) =>

    {err.error.stack}

    , + defaultErrorComponent: (err) => ( +

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

    + ), defaultNotFoundComponent: () =>

    not found

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

    {state.error}

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

    Sign in

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

    Article not found

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

    Field notes

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

    {article.title}

    +

    {article.body}

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

    Saved articles

    +

    {session.email}

    +

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

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

    Article not found

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

    Field notes

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

    Sign in

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

    {error}

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

    {article.title}

    +

    {article.body}

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

    Saved articles

    +

    {account.email}

    +

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

    + + +

    {error}

    +
    + ) +} diff --git a/examples/react/start-next-migration/src/routes/sitemap[.]xml.ts b/examples/react/start-next-migration/src/routes/sitemap[.]xml.ts new file mode 100644 index 0000000000..a7dfcaa594 --- /dev/null +++ b/examples/react/start-next-migration/src/routes/sitemap[.]xml.ts @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' +import { articles, siteUrl } from '../content' +export const Route = createFileRoute('/sitemap.xml')({ + server: { + handlers: { + GET: () => + new Response( + `${siteUrl}${articles.map((article) => `${siteUrl}/posts/${article.slug}`).join('')}`, + { headers: { 'Content-Type': 'application/xml' } }, + ), + }, + }, +}) diff --git a/examples/react/start-next-migration/src/server/account.ts b/examples/react/start-next-migration/src/server/account.ts new file mode 100644 index 0000000000..85e921c74b --- /dev/null +++ b/examples/react/start-next-migration/src/server/account.ts @@ -0,0 +1,77 @@ +import { getIronSession } from 'iron-session' +import { createServerFn } from '@tanstack/react-start' +import { + getCookie, + setCookie, + setResponseStatus, + setResponseHeader, +} from '@tanstack/react-start/server' +import { redirect } from '@tanstack/react-router' +async function session() { + setResponseHeader('Cache-Control', 'private, no-store') + const password = process.env.SESSION_PASSWORD + if (!password || password.length < 32) { + throw new Error('Set SESSION_PASSWORD to at least 32 characters') + } + return getIronSession<{ email: string; saved: boolean }>( + { read: getCookie, write: setCookie }, + { + cookieName: 'start-migration-session', + password, + ttl: 7 * 24 * 60 * 60, + cookieOptions: { + httpOnly: true, + secure: process.env.NODE_ENV === 'production', + sameSite: 'lax', + path: '/', + }, + }, + ) +} +export const getAccount = createServerFn({ method: 'GET' }).handler( + async () => { + const current = await session() + return current.email + ? { email: current.email, saved: current.saved ?? false } + : null + }, +) +export const signIn = createServerFn({ method: 'POST' }) + .validator((input: { email: string; password: string }) => { + if (typeof input.email !== 'string' || typeof input.password !== 'string') { + throw new Error('Invalid credentials') + } + return input + }) + .handler(async ({ data }) => { + if (!process.env.DEMO_PASSWORD) { + throw new Error('Set DEMO_PASSWORD before running the example') + } + if ( + data.email !== 'reader@example.com' || + data.password !== process.env.DEMO_PASSWORD + ) { + return { error: 'Invalid credentials' } + } + const current = await session() + current.email = data.email + current.saved = false + await current.save() + return { error: '' } + }) +export const toggleSaved = createServerFn({ method: 'POST' }).handler( + async () => { + const current = await session() + if (!current.email) { + setResponseStatus(401) + throw new Error('Unauthorized') + } + current.saved = !current.saved + await current.save() + }, +) +export const signOut = createServerFn({ method: 'POST' }).handler(async () => { + const current = await session() + current.destroy() + throw redirect({ to: '/login' }) +}) diff --git a/examples/react/start-next-migration/src/start.ts b/examples/react/start-next-migration/src/start.ts new file mode 100644 index 0000000000..5fb1e247fb --- /dev/null +++ b/examples/react/start-next-migration/src/start.ts @@ -0,0 +1,9 @@ +import { createCsrfMiddleware, createStart } from '@tanstack/react-start' + +export const startInstance = createStart(() => ({ + requestMiddleware: [ + createCsrfMiddleware({ + filter: (ctx) => ctx.handlerType === 'serverFn', + }), + ], +})) diff --git a/examples/react/start-next-migration/tests/migration.spec.ts b/examples/react/start-next-migration/tests/migration.spec.ts new file mode 100644 index 0000000000..7009095977 --- /dev/null +++ b/examples/react/start-next-migration/tests/migration.spec.ts @@ -0,0 +1,163 @@ +import { expect, test } from '@playwright/test' + +test('public URLs, server metadata, search, redirects, and missing pages survive migration', async ({ + page, + request, +}) => { + const response = await request.get('/posts/keeping-your-urls') + expect(response.status()).toBe(200) + const html = await response.text() + expect(html).toContain('Keeping your URLs') + expect(html).toMatch( + /]+name="description"[^>]+content="Preserve public URLs when changing frameworks\."/, + ) + expect(html).toMatch( + /]+rel="canonical"[^>]+href="https:\/\/field-notes\.example\/posts\/keeping-your-urls"/, + ) + expect(html).toMatch( + /]+property="og:title"[^>]+content="Keeping your URLs"/, + ) + expect(html).toContain( + 'A framework migration can keep the URLs your readers already use.', + ) + + const old = await request.get('/old-notes', { maxRedirects: 0 }) + expect(old.status()).toBe(308) + expect(new URL(old.headers().location, old.url()).pathname).toBe( + '/posts/keeping-your-urls', + ) + expect((await request.get('/posts/missing')).status()).toBe(404) + const sitemap = await (await request.get('/sitemap.xml')).text() + expect(sitemap).toContain( + 'https://field-notes.example/posts/keeping-your-urls', + ) + expect(sitemap).not.toContain('/saved') + + await page.goto('/?q=metadata') + await expect( + page.getByRole('link', { name: 'Checking your metadata' }), + ).toBeVisible() + await expect( + page.getByRole('link', { name: 'Keeping your URLs' }), + ).toHaveCount(0) + await page.getByRole('link', { name: 'Checking your metadata' }).click() + await expect(page).toHaveURL(/\/posts\/checking-your-metadata$/) + await expect(page).toHaveTitle('Checking your metadata') + await expect(page.locator('link[rel="canonical"]')).toHaveAttribute( + 'href', + 'https://field-notes.example/posts/checking-your-metadata', + ) +}) + +test('sessions and protected mutations survive reload but cannot run after sign-out', async ({ + page, +}, testInfo) => { + await page.goto('/saved') + await expect(page).toHaveURL(/\/login$/) + await page.getByLabel('Email', { exact: true }).fill('reader@example.com') + await page.getByLabel('Password', { exact: true }).fill('wrong-password') + await page.getByRole('button', { name: 'Sign in', exact: true }).click() + await expect(page.getByRole('main').getByRole('alert')).toHaveText( + 'Invalid credentials', + ) + await page.getByLabel('Email', { exact: true }).fill('reader@example.com') + await page + .getByLabel('Password', { exact: true }) + .fill('migration-test-password') + await page.getByRole('button', { name: 'Sign in', exact: true }).click() + await expect(page).toHaveURL(/\/saved$/) + await expect(page.getByTestId('saved-state')).toHaveText('No saved articles') + const mutation = page.waitForRequest((request) => request.method() === 'POST') + await page.getByRole('button', { name: 'Save article', exact: true }).click() + const savedRequest = await mutation + await expect(page.getByTestId('saved-state')).toHaveText( + 'Keeping your URLs is saved', + ) + // Keep the authenticated cookie jar while replaying a cross-site request. + const crossSiteHeaders = await savedRequest.allHeaders() + delete crossSiteHeaders.cookie + delete crossSiteHeaders['content-length'] + crossSiteHeaders.origin = 'https://untrusted.example' + crossSiteHeaders['sec-fetch-site'] = 'cross-site' + const crossSite = await page.request.post(savedRequest.url(), { + headers: crossSiteHeaders, + data: savedRequest.postData() ?? '', + }) + if (testInfo.project.name === 'start') { + expect(crossSite.status()).toBe(403) + } else { + expect(crossSite.status()).toBeGreaterThanOrEqual(400) + } + + const response = await page.reload() + expect(response?.headers()['cache-control']).toMatch( + process.env.MIGRATION_PRODUCTION ? /no-store/ : /no-store|no-cache/, + ) + await expect(page.getByTestId('saved-state')).toHaveText( + 'Keeping your URLs is saved', + ) + await page.getByRole('button', { name: 'Sign out', exact: true }).click() + await expect(page).toHaveURL(/\/login$/) + + // Replay the real mutation with the now-signed-out browser cookie jar. + const headers = await savedRequest.allHeaders() + delete headers.cookie + delete headers['content-length'] + const denied = await page.request.post(savedRequest.url(), { + headers, + data: savedRequest.postData() ?? '', + }) + expect(denied.status()).toBeGreaterThanOrEqual(400) + await page.goto('/saved') + await expect(page).toHaveURL(/\/login$/) +}) + +test('Start serializes saving and signing out so their responses cannot arrive out of order', async ({ + page, +}, testInfo) => { + test.skip(testInfo.project.name !== 'start', 'Start event-handler regression') + await page.goto('/login') + await page.getByLabel('Email', { exact: true }).fill('reader@example.com') + await page + .getByLabel('Password', { exact: true }) + .fill('migration-test-password') + await page.getByRole('button', { name: 'Sign in', exact: true }).click() + await expect(page).toHaveURL(/\/saved$/) + + for (const action of ['Save article', 'Sign out']) { + let release = () => {} + const held = new Promise((resolve) => { + release = resolve + }) + await page.route('**/_serverFn/**', async (route) => { + if (route.request().method() === 'POST') { + await held + } + await route.continue() + }) + await page.getByRole('button', { name: action, exact: true }).click() + try { + await expect( + page.getByRole('button', { name: /^(Save|Remove) article$/ }), + ).toBeDisabled() + await expect( + page.getByRole('button', { name: 'Sign out', exact: true }), + ).toBeDisabled() + } finally { + release() + } + if (action === 'Save article') { + await expect(page.getByTestId('saved-state')).toHaveText( + 'Keeping your URLs is saved', + ) + await expect( + page.getByRole('button', { name: 'Sign out', exact: true }), + ).toBeEnabled() + } else { + await expect(page).toHaveURL(/\/login$/) + } + await page.unrouteAll({ behavior: 'wait' }) + } + await page.goto('/saved') + await expect(page).toHaveURL(/\/login$/) +}) diff --git a/examples/react/start-next-migration/tsconfig.json b/examples/react/start-next-migration/tsconfig.json new file mode 100644 index 0000000000..a41553b9a1 --- /dev/null +++ b/examples/react/start-next-migration/tsconfig.json @@ -0,0 +1,21 @@ +{ + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "vite.config.ts", + "playwright.config.ts", + "tests/**/*.ts" + ], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2024"], + "skipLibCheck": true, + "target": "ES2024", + "noEmit": true, + "types": ["vite/client"] + } +} diff --git a/examples/react/start-next-migration/vite.config.ts b/examples/react/start-next-migration/vite.config.ts new file mode 100644 index 0000000000..26d0e455d5 --- /dev/null +++ b/examples/react/start-next-migration/vite.config.ts @@ -0,0 +1,5 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { nitro } from 'nitro/vite' +export default defineConfig({ plugins: [tanstackStart(), react(), nitro()] }) diff --git a/examples/react/start-rscs/.gitignore b/examples/react/start-rscs/.gitignore new file mode 100644 index 0000000000..6ab0517d9f --- /dev/null +++ b/examples/react/start-rscs/.gitignore @@ -0,0 +1,20 @@ +node_modules +package-lock.json +yarn.lock + +.DS_Store +.cache +.env +.vercel +.output +.nitro +/build/ +/api/ +/server/build +/public/build# Sentry Config File +.env.sentry-build-plugin +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ +.tanstack \ No newline at end of file diff --git a/examples/react/start-rscs/.prettierignore b/examples/react/start-rscs/.prettierignore new file mode 100644 index 0000000000..2be5eaa6ec --- /dev/null +++ b/examples/react/start-rscs/.prettierignore @@ -0,0 +1,4 @@ +**/build +**/public +pnpm-lock.yaml +routeTree.gen.ts \ No newline at end of file diff --git a/examples/react/start-rscs/.vscode/settings.json b/examples/react/start-rscs/.vscode/settings.json new file mode 100644 index 0000000000..00b5278e58 --- /dev/null +++ b/examples/react/start-rscs/.vscode/settings.json @@ -0,0 +1,11 @@ +{ + "files.watcherExclude": { + "**/routeTree.gen.ts": true + }, + "search.exclude": { + "**/routeTree.gen.ts": true + }, + "files.readonlyInclude": { + "**/routeTree.gen.ts": true + } +} diff --git a/examples/react/start-rscs/README.md b/examples/react/start-rscs/README.md new file mode 100644 index 0000000000..e47983c58e --- /dev/null +++ b/examples/react/start-rscs/README.md @@ -0,0 +1,36 @@ +# TanStack Start - Basic Example + +This is the basic TanStack Start example, demonstrating the fundamentals of building applications with TanStack Router and TanStack Start. + +- [TanStack Router Docs](https://tanstack.com/router) + +It's deployed automagically with Netlify! + +- [Netlify](https://netlify.com/) + +## Start a new project based on this example + +To start a new project based on this example, run: + +```sh +npx gitpick TanStack/router/tree/main/examples/react/start-basic start-basic +``` + +## Getting Started + +From your terminal: + +```sh +pnpm install +pnpm dev +``` + +This starts your app in development mode, rebuilding assets on file changes. + +## Build + +To build the app for production: + +```sh +pnpm build +``` diff --git a/examples/react/start-rscs/package.json b/examples/react/start-rscs/package.json new file mode 100644 index 0000000000..00c88681d7 --- /dev/null +++ b/examples/react/start-rscs/package.json @@ -0,0 +1,35 @@ +{ + "name": "tanstack-start-example-rscs", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "vite dev", + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "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", + "dexie": "^4.0.10", + "react": "^19.2.0", + "react-dom": "^19.2.0", + "tailwind-merge": "^3.6.0", + "zod": "^4.4.3", + "zustand": "^5.0.10" + }, + "devDependencies": { + "@tailwindcss/vite": "^4.1.18", + "@types/node": "22.10.2", + "@types/react": "^19.2.2", + "@types/react-dom": "^19.2.2", + "@vitejs/plugin-react": "^6.0.1", + "@vitejs/plugin-rsc": "^0.5.39", + "nitro": "^3.0.260903-beta", + "tailwindcss": "^4.1.18", + "typescript": "^5.7.2", + "vite": "^8.0.14" + } +} diff --git a/examples/react/start-basic-rsc/public/android-chrome-192x192.png b/examples/react/start-rscs/public/android-chrome-192x192.png similarity index 100% rename from examples/react/start-basic-rsc/public/android-chrome-192x192.png rename to examples/react/start-rscs/public/android-chrome-192x192.png diff --git a/examples/react/start-basic-rsc/public/android-chrome-512x512.png b/examples/react/start-rscs/public/android-chrome-512x512.png similarity index 100% rename from examples/react/start-basic-rsc/public/android-chrome-512x512.png rename to examples/react/start-rscs/public/android-chrome-512x512.png diff --git a/examples/react/start-basic-rsc/public/apple-touch-icon.png b/examples/react/start-rscs/public/apple-touch-icon.png similarity index 100% rename from examples/react/start-basic-rsc/public/apple-touch-icon.png rename to examples/react/start-rscs/public/apple-touch-icon.png diff --git a/examples/react/start-rscs/public/example-guitar-flowers.jpg b/examples/react/start-rscs/public/example-guitar-flowers.jpg new file mode 100644 index 0000000000..debe785efe Binary files /dev/null and b/examples/react/start-rscs/public/example-guitar-flowers.jpg differ diff --git a/examples/react/start-rscs/public/example-guitar-motherboard.jpg b/examples/react/start-rscs/public/example-guitar-motherboard.jpg new file mode 100644 index 0000000000..8f1a8d72f8 Binary files /dev/null and b/examples/react/start-rscs/public/example-guitar-motherboard.jpg differ diff --git a/examples/react/start-rscs/public/example-guitar-racing.jpg b/examples/react/start-rscs/public/example-guitar-racing.jpg new file mode 100644 index 0000000000..44555574c4 Binary files /dev/null and b/examples/react/start-rscs/public/example-guitar-racing.jpg differ diff --git a/examples/react/start-rscs/public/example-guitar-steamer-trunk.jpg b/examples/react/start-rscs/public/example-guitar-steamer-trunk.jpg new file mode 100644 index 0000000000..7b93189397 Binary files /dev/null and b/examples/react/start-rscs/public/example-guitar-steamer-trunk.jpg differ diff --git a/examples/react/start-rscs/public/example-guitar-superhero.jpg b/examples/react/start-rscs/public/example-guitar-superhero.jpg new file mode 100644 index 0000000000..3bbea2743d Binary files /dev/null and b/examples/react/start-rscs/public/example-guitar-superhero.jpg differ diff --git a/examples/react/start-rscs/public/example-ukelele-tanstack.jpg b/examples/react/start-rscs/public/example-ukelele-tanstack.jpg new file mode 100644 index 0000000000..1e8a556696 Binary files /dev/null and b/examples/react/start-rscs/public/example-ukelele-tanstack.jpg differ diff --git a/examples/react/start-basic-rsc/public/favicon-16x16.png b/examples/react/start-rscs/public/favicon-16x16.png similarity index 100% rename from examples/react/start-basic-rsc/public/favicon-16x16.png rename to examples/react/start-rscs/public/favicon-16x16.png diff --git a/examples/react/start-basic-rsc/public/favicon-32x32.png b/examples/react/start-rscs/public/favicon-32x32.png similarity index 100% rename from examples/react/start-basic-rsc/public/favicon-32x32.png rename to examples/react/start-rscs/public/favicon-32x32.png diff --git a/examples/react/start-basic-rsc/public/favicon.ico b/examples/react/start-rscs/public/favicon.ico similarity index 100% rename from examples/react/start-basic-rsc/public/favicon.ico rename to examples/react/start-rscs/public/favicon.ico diff --git a/examples/react/start-basic-rsc/public/favicon.png b/examples/react/start-rscs/public/favicon.png similarity index 100% rename from examples/react/start-basic-rsc/public/favicon.png rename to examples/react/start-rscs/public/favicon.png diff --git a/examples/react/start-basic-rsc/public/site.webmanifest b/examples/react/start-rscs/public/site.webmanifest similarity index 100% rename from examples/react/start-basic-rsc/public/site.webmanifest rename to examples/react/start-rscs/public/site.webmanifest diff --git a/examples/react/start-rscs/src/components/Layout.tsx b/examples/react/start-rscs/src/components/Layout.tsx new file mode 100644 index 0000000000..ff0dafa9df --- /dev/null +++ b/examples/react/start-rscs/src/components/Layout.tsx @@ -0,0 +1,139 @@ +import { useState } from 'react' +import { Link, Outlet, useRouterState } from '@tanstack/react-router' + +const navItems = [ + { path: '/', label: 'Home', description: 'Overview of all demos' }, + { + path: '/pokemon-rsc', + label: 'Pokemon RSC', + description: 'Async server components', + }, + { + path: '/e-commerce', + label: 'eCommerce Demo', + description: 'Composite RSC pattern', + }, + { + path: '/low-level-api', + label: 'Low-Level API', + description: 'RSC primitives', + }, +] + +export function Layout() { + const [sidebarOpen, setSidebarOpen] = useState(false) + const routerState = useRouterState() + const currentPath = routerState.location.pathname + + return ( +
    + {/* Top Navigation Bar */} + + +
    + {/* Sidebar Overlay */} + {sidebarOpen && ( +
    setSidebarOpen(false)} + /> + )} + + {/* Sidebar */} + + + {/* Main Content */} +
    + + + {/* Legend Footer */} +
    +
    +
    +
    +
    + + Server Component + +
    +
    +
    + + Client Component + +
    +
    +

    + TanStack Start RSC Examples +

    +
    +
    +
    +
    +
    + ) +} diff --git a/examples/react/start-rscs/src/e-Commerce/components/AddToCartButton.tsx b/examples/react/start-rscs/src/e-Commerce/components/AddToCartButton.tsx new file mode 100644 index 0000000000..79c3a44e61 --- /dev/null +++ b/examples/react/start-rscs/src/e-Commerce/components/AddToCartButton.tsx @@ -0,0 +1,86 @@ +import { useState } from 'react' +import { useCartStore } from '~/e-Commerce/store/cartStore' + +// Product info passed from parent +const product = { + id: 'tanstack-ukulele', + name: 'TanStack Ukulele', + price: 149.99, + image: '/example-ukelele-tanstack.jpg', +} + +export function AddToCartButton() { + const [quantity, setQuantity] = useState(1) + const [added, setAdded] = useState(false) + const [favorite, setFavorite] = useState(false) + const addItem = useCartStore((state) => state.addItem) + + const handleAddToCart = () => { + // Add item(s) to cart + for (let i = 0; i < quantity; i++) { + addItem(product) + } + setAdded(true) + setQuantity(1) // Reset quantity after adding + setTimeout(() => setAdded(false), 2000) + } + + return ( +
    + {/* Quantity Selector */} +
    + Quantity: +
    + + + {quantity} + + +
    +
    + + {/* Action Buttons */} +
    + + + +
    + + {/* Info text */} +

    + Free shipping on orders over $100 +

    +
    + ) +} diff --git a/examples/react/start-rscs/src/e-Commerce/components/AlsoBoughtCarousel.tsx b/examples/react/start-rscs/src/e-Commerce/components/AlsoBoughtCarousel.tsx new file mode 100644 index 0000000000..5b719dfd52 --- /dev/null +++ b/examples/react/start-rscs/src/e-Commerce/components/AlsoBoughtCarousel.tsx @@ -0,0 +1,94 @@ +import { useRef } from 'react' +import type { AlsoBoughtProduct } from '~/e-Commerce/server-functions' + +interface AlsoBoughtCarouselProps { + products: Array +} + +export function AlsoBoughtCarousel({ products }: AlsoBoughtCarouselProps) { + const scrollRef = useRef(null) + + const scroll = (direction: 'left' | 'right') => { + if (scrollRef.current) { + const scrollAmount = 300 + scrollRef.current.scrollBy({ + left: direction === 'left' ? -scrollAmount : scrollAmount, + behavior: 'smooth', + }) + } + } + + return ( +
    +
    + {/* Left scroll button */} + + + {/* Scrollable container */} +
    + {products.map((product) => ( +
    + {product.name} +
    +

    + {product.name} +

    +

    ${product.price}

    +
    +
    + ))} +
    + + {/* Right scroll button */} + +
    +
    + ) +} diff --git a/examples/react/start-rscs/src/e-Commerce/components/Header.tsx b/examples/react/start-rscs/src/e-Commerce/components/Header.tsx new file mode 100644 index 0000000000..35542557fd --- /dev/null +++ b/examples/react/start-rscs/src/e-Commerce/components/Header.tsx @@ -0,0 +1,62 @@ +import { useCartStore } from '~/e-Commerce/store/cartStore' + +export function Header() { + const totalItems = useCartStore((state) => state.totalItems) + const totalPrice = useCartStore((state) => state.totalPrice) + + return ( +
    +
    +
    + 🎸 +

    + TanStack Music Store +

    +
    + +
    +

    + Premium instruments powered by Server Components +

    + + {/* Cart Button */} + +
    +
    + + {/* Cart summary (when items in cart) */} + {totalItems > 0 && ( +
    + + {totalItems} item{totalItems !== 1 ? 's' : ''} in cart + + + Total: ${totalPrice.toFixed(2)} + +
    + )} +
    + ) +} diff --git a/examples/react/start-rscs/src/e-Commerce/components/StreamingComments.tsx b/examples/react/start-rscs/src/e-Commerce/components/StreamingComments.tsx new file mode 100644 index 0000000000..a1c3bf845b --- /dev/null +++ b/examples/react/start-rscs/src/e-Commerce/components/StreamingComments.tsx @@ -0,0 +1,117 @@ +import { useEffect, useRef, useState } from 'react' +import { createFromReadableStream } from '@tanstack/react-start/rsc' +import { streamComments } from '~/e-Commerce/server-functions' + +interface CommentEntry { + id: number + element: React.ReactNode + receivedAt: number +} + +// Helper to convert string payload back to ReadableStream +function payloadToStream(payload: string): ReadableStream { + const encoder = new TextEncoder() + return new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode(payload)) + controller.close() + }, + }) +} + +// Format relative time +function formatRelativeTime(receivedAt: number): string { + const seconds = Math.floor((Date.now() - receivedAt) / 1000) + if (seconds < 1) return 'just now' + if (seconds === 1) return '1 second ago' + return `${seconds} seconds ago` +} + +const MAX_COMMENTS = 10 + +export function StreamingComments() { + const [comments, setComments] = useState>([]) + const [isStreaming, setIsStreaming] = useState(false) + const [, setTick] = useState(0) // Force re-render for relative time updates + const hasStartedRef = useRef(false) + + // Update relative times every second + useEffect(() => { + const interval = setInterval(() => { + setTick((t) => t + 1) + }, 1000) + return () => clearInterval(interval) + }, []) + + // Auto-start streaming on mount + useEffect(() => { + if (hasStartedRef.current) return + hasStartedRef.current = true + + const startStream = async () => { + setIsStreaming(true) + + try { + for await (const { id, payload } of await streamComments()) { + // Decode the RSC payload + const stream = payloadToStream(payload) + const element = await createFromReadableStream(stream) + + const entry: CommentEntry = { + id, + element: element as React.ReactNode, + receivedAt: Date.now(), + } + + // Add to comments, keeping newest at top, capped at MAX_COMMENTS + setComments((prev) => [entry, ...prev].slice(0, MAX_COMMENTS)) + } + } catch (error) { + console.error('Streaming error:', error) + } finally { + setIsStreaming(false) + } + } + + startStream() + }, []) + + return ( +
    + {isStreaming && ( +
    +
    + Streaming live reviews... +
    + )} + +
    + {comments.length === 0 ? ( +
    +
    +
    + Loading reviews... +
    +
    + ) : ( + comments.map((comment) => ( +
    + {/* The RSC element */} + {comment.element} + {/* Client-side relative time */} +
    + received {formatRelativeTime(comment.receivedAt)} +
    +
    + )) + )} +
    + + {comments.length > 0 && ( +
    + Showing {comments.length} of {MAX_COMMENTS} reviews (newest first) +
    + )} +
    + ) +} diff --git a/examples/react/start-rscs/src/e-Commerce/server-functions.tsx b/examples/react/start-rscs/src/e-Commerce/server-functions.tsx new file mode 100644 index 0000000000..3e34aa8d27 --- /dev/null +++ b/examples/react/start-rscs/src/e-Commerce/server-functions.tsx @@ -0,0 +1,257 @@ +import { createServerFn } from '@tanstack/react-start' +import { + createCompositeComponent, + renderToReadableStream, +} from '@tanstack/react-start/rsc' + +// ============================================ +// Product Data & Types +// ============================================ + +export interface Product { + id: string + name: string + price: number + description: string + image: string +} + +export interface AlsoBoughtProduct { + id: string + name: string + price: number + image: string +} + +// Main product +const mainProduct: Product = { + id: 'tanstack-ukulele', + name: 'TanStack Ukulele', + price: 149.99, + description: + 'Hand-crafted koa wood ukulele with mother-of-pearl TanStack inlay. Perfect for beach jams, campfire singalongs, or just strumming at your desk while waiting for builds to finish.', + image: '/example-ukelele-tanstack.jpg', +} + +// Also bought products +const alsoBoughtProducts: Array = [ + { + id: 'guitar-flowers', + name: 'Floral Guitar', + price: 299.99, + image: '/example-guitar-flowers.jpg', + }, + { + id: 'guitar-motherboard', + name: 'Circuit Guitar', + price: 349.99, + image: '/example-guitar-motherboard.jpg', + }, + { + id: 'guitar-racing', + name: 'Racing Guitar', + price: 279.99, + image: '/example-guitar-racing.jpg', + }, + { + id: 'guitar-steamer-trunk', + name: 'Vintage Guitar', + price: 399.99, + image: '/example-guitar-steamer-trunk.jpg', + }, + { + id: 'guitar-superhero', + name: 'Hero Guitar', + price: 329.99, + image: '/example-guitar-superhero.jpg', + }, +] + +// ============================================ +// Product Page Server Function +// ============================================ + +export const getProductPage = createServerFn().handler(async () => { + console.log('[Server] Rendering ProductPage composite') + + const src = await createCompositeComponent( + (props: { + children?: React.ReactNode + renderAlsoBought?: (data: { + products: Array + }) => React.ReactNode + }) => ( +
    + {/* Product Hero Section */} +
    + {/* Product Image */} +
    + {mainProduct.name} +
    + + {/* Product Details */} +
    +

    + {mainProduct.name} +

    +

    {mainProduct.description}

    +

    + ${mainProduct.price} +

    + + {/* CTA Slot (client component) */} +
    {props.children}
    +
    +
    + + {/* Also Bought Section */} +
    +

    + Customers who bought this also bought +

    +
    + {props.renderAlsoBought?.({ products: alsoBoughtProducts })} +
    +
    +
    + ), + ) + + return { src } +}) + +// ============================================ +// Streaming Comments +// ============================================ + +// Sample comments for streaming +const comments = [ + { + author: 'MusicLover42', + text: "Best ukulele I've ever owned! The tone is incredible and the TanStack inlay is gorgeous.", + rating: 5, + }, + { + author: 'BeachVibes', + text: 'Perfect for beach jams. Everyone asks where I got it!', + rating: 5, + }, + { + author: 'UkeNewbie', + text: 'As a beginner, this was the perfect first instrument. Great quality for the price.', + rating: 5, + }, + { + author: 'DevMusician', + text: 'I code with TanStack and play TanStack. Living the dream!', + rating: 5, + }, + { + author: 'IslandDreamer', + text: "The sound is so warm and rich. It's like Hawaii in a box!", + rating: 5, + }, + { + author: 'GuitarConvert', + text: 'Switched from guitar to uke because of this beauty. No regrets!', + rating: 5, + }, + { + author: 'CampfireKing', + text: 'This uke is the star of every campfire. Worth every penny.', + rating: 4, + }, + { + author: 'TechStrummer', + text: 'Finally, an instrument that understands my stack preferences!', + rating: 5, + }, +] + +// Server component for each comment +function CommentCard({ + author, + text, + rating, + timestamp, +}: { + author: string + text: string + rating: number + timestamp: string +}) { + const gradients = [ + 'from-purple-500 to-indigo-600', + 'from-blue-500 to-cyan-500', + 'from-green-500 to-emerald-500', + 'from-amber-500 to-orange-500', + 'from-pink-500 to-rose-500', + ] + const gradient = gradients[Math.floor(Math.random() * gradients.length)] + + return ( +
    +
    +
    {author}
    +
    + {Array.from({ length: rating }).map((_, i) => ( + ⭐ + ))} +
    +
    +

    {text}

    +
    + Posted: {new Date(timestamp).toLocaleTimeString()} +
    +
    + ) +} + +// Helper to convert stream to string +async function streamToString( + stream: ReadableStream, +): Promise { + const reader = stream.getReader() + const chunks: Array = [] + const decoder = new TextDecoder() + + while (true) { + const { done, value } = await reader.read() + if (done) break + chunks.push(decoder.decode(value, { stream: true })) + } + + return chunks.join('') +} + +function sleep(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +// Async generator that streams comment RSCs +export const streamComments = createServerFn().handler(async function* () { + for (let i = 0; i < comments.length; i++) { + await sleep(2000) // Wait 2 seconds between comments + + const comment = comments[i] + console.log(`[Server] Rendering comment from ${comment.author}`) + + const stream = await renderToReadableStream( + , + ) + + const payload = await streamToString(stream) + yield { id: i, payload } + } +}) diff --git a/examples/react/start-rscs/src/e-Commerce/store/cartStore.ts b/examples/react/start-rscs/src/e-Commerce/store/cartStore.ts new file mode 100644 index 0000000000..20c3c53f59 --- /dev/null +++ b/examples/react/start-rscs/src/e-Commerce/store/cartStore.ts @@ -0,0 +1,79 @@ +import { create } from 'zustand' + +interface CartItem { + id: string + name: string + price: number + quantity: number + image: string +} + +interface CartStore { + items: Array + totalItems: number + totalPrice: number + addItem: (item: Omit) => void + removeItem: (id: string) => void + updateQuantity: (id: string, quantity: number) => void + clearCart: () => void +} + +export const useCartStore = create((set, get) => ({ + items: [], + totalItems: 0, + totalPrice: 0, + + addItem: (item) => { + const { items } = get() + const existingItem = items.find((i) => i.id === item.id) + + if (existingItem) { + set({ + items: items.map((i) => + i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i, + ), + totalItems: get().totalItems + 1, + totalPrice: get().totalPrice + item.price, + }) + } else { + set({ + items: [...items, { ...item, quantity: 1 }], + totalItems: get().totalItems + 1, + totalPrice: get().totalPrice + item.price, + }) + } + }, + + removeItem: (id) => { + const { items } = get() + const item = items.find((i) => i.id === id) + if (item) { + set({ + items: items.filter((i) => i.id !== id), + totalItems: get().totalItems - item.quantity, + totalPrice: get().totalPrice - item.price * item.quantity, + }) + } + }, + + updateQuantity: (id, quantity) => { + const { items } = get() + const item = items.find((i) => i.id === id) + if (item) { + const diff = quantity - item.quantity + set({ + items: items.map((i) => (i.id === id ? { ...i, quantity } : i)), + totalItems: get().totalItems + diff, + totalPrice: get().totalPrice + item.price * diff, + }) + } + }, + + clearCart: () => { + set({ + items: [], + totalItems: 0, + totalPrice: 0, + }) + }, +})) diff --git a/examples/react/start-rscs/src/home/server-functions.tsx b/examples/react/start-rscs/src/home/server-functions.tsx new file mode 100644 index 0000000000..123944781c --- /dev/null +++ b/examples/react/start-rscs/src/home/server-functions.tsx @@ -0,0 +1,102 @@ +import { createServerFn } from '@tanstack/react-start' +import { createCompositeComponent } from '@tanstack/react-start/rsc' + +export interface DemoInfo { + title: string + description: string + path: string + features: Array + color: string +} + +const demos: Array = [ + { + title: 'eCommerce Composite Demo', + description: + 'A product page built with composite server components. Shows how to combine server-rendered layouts with client-interactive elements like add-to-cart buttons and carousels.', + path: '/e-commerce', + features: [ + 'Composite RSC pattern', + 'Zustand cart state', + 'Streaming comments', + 'Also bought carousel', + ], + color: 'from-purple-500 to-indigo-600', + }, + { + title: 'Pokemon RSC Demo', + description: + 'Demonstrates async server components that fetch their own data. The Pokemon list is fetched and rendered entirely on the server.', + path: '/pokemon-rsc', + features: [ + 'Async server components', + 'Server-side data fetching', + 'renderServerComponent API', + ], + color: 'from-amber-500 to-orange-500', + }, + { + title: 'Low-Level RSC API Demo', + description: + "Explore TanStack Start's low-level Flight stream APIs including renderToReadableStream, createFromReadableStream, and createFromFetch.", + path: '/low-level-api', + features: [ + 'Direct Flight streams', + 'Parallel streaming', + 'Nested Suspense', + 'IndexedDB caching', + 'HTTP streaming ticker', + ], + color: 'from-cyan-500 to-blue-600', + }, +] + +// Server function to get the home page composite +export const getHomePage = createServerFn().handler(async () => { + console.log('[Server] Rendering HomePage composite') + + const src = await createCompositeComponent( + (props: { + renderDemoCard?: (data: { demo: DemoInfo }) => React.ReactNode + }) => ( +
    +
    + {/* Hero Section */} +
    +

    + React Server Components Examples +

    +

    + Explore different patterns and APIs for building applications with + React Server Components in TanStack Start. +

    +
    + + {/* Demo Cards */} +
    + {demos.map((demo) => ( +
    {props.renderDemoCard?.({ demo })}
    + ))} +
    + + {/* Quick Info */} +
    +

    + About These Examples +

    +

    + These examples demonstrate various React Server Component patterns + available in TanStack Start. Server components are rendered on the + server and sent to the client as a Flight stream. Client + components handle interactivity and state management. The visual + indicators in the footer show which parts are server-rendered + (blue) vs client-interactive (green). +

    +
    +
    +
    + ), + ) + + return { src } +}) diff --git a/examples/react/start-rscs/src/low-level/components/DemoSection.tsx b/examples/react/start-rscs/src/low-level/components/DemoSection.tsx new file mode 100644 index 0000000000..004921dbc4 --- /dev/null +++ b/examples/react/start-rscs/src/low-level/components/DemoSection.tsx @@ -0,0 +1,23 @@ +import type { ReactNode } from 'react' + +interface DemoSectionProps { + title: string + description: string + children: ReactNode +} + +export function DemoSection({ + title, + description, + children, +}: DemoSectionProps) { + return ( +
    +
    +

    {title}

    +

    {description}

    +
    +
    {children}
    +
    + ) +} diff --git a/examples/react/start-rscs/src/low-level/components/dexie-cache/DexieCacheDemo.tsx b/examples/react/start-rscs/src/low-level/components/dexie-cache/DexieCacheDemo.tsx new file mode 100644 index 0000000000..d2278947d9 --- /dev/null +++ b/examples/react/start-rscs/src/low-level/components/dexie-cache/DexieCacheDemo.tsx @@ -0,0 +1,199 @@ +import { useCallback, useEffect, useState } from 'react' +import { createFromReadableStream } from '@tanstack/react-start/rsc' + +import { db } from '../../db' +import { getCounterRscPayload } from './server-functions' + +// Convert string payload back to ReadableStream +function payloadToStream(payload: string): ReadableStream { + const encoder = new TextEncoder() + return new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode(payload)) + controller.close() + }, + }) +} + +export function DexieCacheDemo() { + const [counter, setCounter] = useState(0) + const [result, setResult] = useState(null) + const [loading, setLoading] = useState(false) + const [source, setSource] = useState<'cache' | 'server' | null>(null) + const [cacheStats, setCacheStats] = useState({ count: 0, size: 0 }) + const [loadTime, setLoadTime] = useState(null) + + // Load cache stats on mount and after operations + const updateCacheStats = useCallback(async () => { + const entries = await db.cache.toArray() + const totalSize = entries.reduce((sum, e) => sum + e.payload.length, 0) + setCacheStats({ count: entries.length, size: totalSize }) + }, []) + + const loadRsc = useCallback( + async (count: number) => { + setLoading(true) + setSource(null) + setLoadTime(null) + const startTime = performance.now() + + try { + const cacheKey = `counter-${count}` + + // Check if cached in Dexie + const cached = await db.cache.get(cacheKey) + + if (cached) { + // Load from cache + console.log(`[Client] Cache HIT for counter: ${count}`) + const stream = payloadToStream(cached.payload) + const element = await createFromReadableStream(stream) + setResult(element as React.ReactNode) + setSource('cache') + } else { + // Fetch from server + console.log(`[Client] Cache MISS for counter: ${count}`) + const { payload } = await getCounterRscPayload({ data: { count } }) + + // Store in Dexie + await db.cache.put({ + id: cacheKey, + payload, + createdAt: Date.now(), + }) + + // Decode and render + const stream = payloadToStream(payload) + const element = await createFromReadableStream(stream) + setResult(element as React.ReactNode) + setSource('server') + await updateCacheStats() + } + + setLoadTime(performance.now() - startTime) + } catch (error) { + console.error('Error loading RSC:', error) + } finally { + setLoading(false) + } + }, + [updateCacheStats], + ) + + // Auto-load RSC when counter changes + useEffect(() => { + loadRsc(counter) + }, [counter, loadRsc]) + + // Load cache stats on mount + useEffect(() => { + updateCacheStats() + }, [updateCacheStats]) + + const clearCache = useCallback(async () => { + await db.cache.clear() + await updateCacheStats() + setResult(null) + setSource(null) + setLoadTime(null) + }, [updateCacheStats]) + + return ( +
    + {/* Counter controls */} +
    + +
    + {counter} +
    + + +
    + + {/* Cache stats */} +
    +
    + Cached entries:{' '} + {cacheStats.count} +
    +
    + Cache size:{' '} + + {(cacheStats.size / 1024).toFixed(2)} KB + +
    +
    + + {/* Source indicator */} + {loading ? ( +
    +
    + Loading... +
    + ) : ( + source && ( +
    +
    + + {source === 'cache' + ? 'Loaded from Dexie cache' + : 'Fetched from server'} + + {loadTime !== null && ( + + ({loadTime.toFixed(1)}ms) + + )} +
    + ) + )} + + {/* Result */} + {result && ( +
    +
    + RSC for Counter #{counter}: +
    + {result} +
    + )} + + {/* How it works */} +
    + How it works: When you change the counter, the app + automatically checks Dexie (IndexedDB) for a cached Flight payload. If + found, it decodes the cached string directly. If not found, it fetches + from the server, stores the payload in Dexie, then decodes it. Each + counter value gets its own cache entry with unique server-generated + data. +
    +
    + ) +} diff --git a/examples/react/start-rscs/src/low-level/components/dexie-cache/server-functions.tsx b/examples/react/start-rscs/src/low-level/components/dexie-cache/server-functions.tsx new file mode 100644 index 0000000000..0226aa57e1 --- /dev/null +++ b/examples/react/start-rscs/src/low-level/components/dexie-cache/server-functions.tsx @@ -0,0 +1,76 @@ +import { createServerFn } from '@tanstack/react-start' +import { renderToReadableStream } from '@tanstack/react-start/rsc' + +// Colors for the counter-based RSC +const counterColors = [ + { bg: 'from-red-500 to-orange-500', text: 'text-red-100', name: 'Warm' }, + { bg: 'from-blue-500 to-cyan-500', text: 'text-blue-100', name: 'Cool' }, + { + bg: 'from-green-500 to-emerald-500', + text: 'text-green-100', + name: 'Nature', + }, + { bg: 'from-purple-500 to-pink-500', text: 'text-purple-100', name: 'Royal' }, + { + bg: 'from-amber-500 to-yellow-500', + text: 'text-amber-100', + name: 'Golden', + }, +] + +// Server component for counter-based RSC +function CounterCard({ count }: { count: number }) { + const colorIndex = count % counterColors.length + const color = counterColors[colorIndex] + const timestamp = new Date().toISOString() + const randomValue = Math.floor(Math.random() * 10000) + + console.log(`[Server] Rendering CounterCard for count: ${count}`) + + return ( +
    +
    +
    +

    Counter #{count}

    +

    Theme: {color.name}

    +
    +
    +
    {randomValue}
    +
    Random Value
    +
    +
    +
    + Generated: {timestamp} +
    +
    + ) +} + +// Server function that returns Flight payload as a string for caching +export const getCounterRscPayload = createServerFn() + .validator((data: { count: number }) => data) + .handler(async ({ data }) => { + console.log(`[Server] Creating Flight payload for count: ${data.count}`) + + const stream = await renderToReadableStream( + , + ) + + // Convert stream to string for caching + const reader = stream.getReader() + const chunks: Array = [] + const decoder = new TextDecoder() + + while (true) { + const { done, value } = await reader.read() + if (done) break + chunks.push(decoder.decode(value, { stream: true })) + } + + const payload = chunks.join('') + console.log(`[Server] Flight payload size: ${payload.length} bytes`) + + return { payload, count: data.count } + }) diff --git a/examples/react/start-rscs/src/low-level/components/direct-flight/DirectFlightStreamDemo.tsx b/examples/react/start-rscs/src/low-level/components/direct-flight/DirectFlightStreamDemo.tsx new file mode 100644 index 0000000000..781ddb0bfe --- /dev/null +++ b/examples/react/start-rscs/src/low-level/components/direct-flight/DirectFlightStreamDemo.tsx @@ -0,0 +1,56 @@ +import { useCallback, useState } from 'react' +import { createFromReadableStream } from '@tanstack/react-start/rsc' + +import { getFlightStreamDirect } from './server-functions' + +export function DirectFlightStreamDemo() { + const [result, setResult] = useState(null) + const [loading, setLoading] = useState(false) + const [streamInfo, setStreamInfo] = useState('') + + const loadStream = useCallback(async () => { + setLoading(true) + setStreamInfo('Fetching Flight stream from server function...') + + try { + const stream = await getFlightStreamDirect() + setStreamInfo('Decoding Flight stream with createFromReadableStream...') + + // Use createFromReadableStream to decode the Flight stream + const element = await createFromReadableStream(stream) + setResult(element as React.ReactNode) + setStreamInfo('Stream decoded successfully!') + } catch (error) { + setStreamInfo(`Error: ${error}`) + } finally { + setLoading(false) + } + }, []) + + return ( +
    + + + {streamInfo && ( +
    + {streamInfo} +
    + )} + + {result && ( +
    +
    + Server-Rendered Content: +
    + {result} +
    + )} +
    + ) +} diff --git a/examples/react/start-rscs/src/low-level/components/direct-flight/server-functions.tsx b/examples/react/start-rscs/src/low-level/components/direct-flight/server-functions.tsx new file mode 100644 index 0000000000..c7ba42ffb6 --- /dev/null +++ b/examples/react/start-rscs/src/low-level/components/direct-flight/server-functions.tsx @@ -0,0 +1,34 @@ +import { createServerFn } from '@tanstack/react-start' +import { renderToReadableStream } from '@tanstack/react-start/rsc' + +// Server Component that will be rendered to a Flight stream +function ServerGreeting({ + name, + timestamp, +}: { + name: string + timestamp: string +}) { + console.log('[Server] Rendering ServerGreeting:', name) + return ( +
    +

    Hello, {name}!

    +

    + Rendered on the server at: {timestamp} +

    +
    + ) +} + +// Server function using low-level renderToReadableStream +export const getFlightStreamDirect = createServerFn({ method: 'GET' }).handler( + async () => { + const stream = await renderToReadableStream( + , + ) + return stream + }, +) diff --git a/examples/react/start-rscs/src/low-level/components/fetch-flight/FetchFlightStreamDemo.tsx b/examples/react/start-rscs/src/low-level/components/fetch-flight/FetchFlightStreamDemo.tsx new file mode 100644 index 0000000000..d49d8988db --- /dev/null +++ b/examples/react/start-rscs/src/low-level/components/fetch-flight/FetchFlightStreamDemo.tsx @@ -0,0 +1,41 @@ +import { useCallback, useState } from 'react' +import { createFromFetch } from '@tanstack/react-start/rsc' + +export function FetchFlightStreamDemo() { + const [result, setResult] = useState(null) + const [loading, setLoading] = useState(false) + + const loadFromApi = useCallback(async () => { + setLoading(true) + try { + // Use createFromFetch to decode a Flight stream from a fetch response + const element = await createFromFetch(fetch('/api/rsc')) + setResult(element as React.ReactNode) + } catch (error) { + console.error('Error fetching RSC:', error) + } finally { + setLoading(false) + } + }, []) + + return ( +
    + + + {result && ( +
    +
    + API Route Response: +
    + {result} +
    + )} +
    + ) +} diff --git a/examples/react/start-rscs/src/low-level/components/nested-suspense/NestedSuspenseDemo.tsx b/examples/react/start-rscs/src/low-level/components/nested-suspense/NestedSuspenseDemo.tsx new file mode 100644 index 0000000000..4bc5ab339d --- /dev/null +++ b/examples/react/start-rscs/src/low-level/components/nested-suspense/NestedSuspenseDemo.tsx @@ -0,0 +1,45 @@ +import { Suspense, useCallback, useState } from 'react' +import { createFromReadableStream } from '@tanstack/react-start/rsc' + +import { getNestedServerComponent } from './server-functions' + +export function NestedSuspenseDemo() { + const [result, setResult] = useState(null) + const [loading, setLoading] = useState(false) + + const loadNested = useCallback(async () => { + setLoading(true) + try { + const stream = await getNestedServerComponent() + const element = await createFromReadableStream(stream) + setResult(element as React.ReactNode) + } catch (error) { + console.error('Error:', error) + } finally { + setLoading(false) + } + }, []) + + return ( +
    + + + {result && ( +
    +
    + Nested Server Components with Suspense: +
    + Loading...
    }> + {result} + +
    + )} +
    + ) +} diff --git a/examples/react/start-rscs/src/low-level/components/nested-suspense/server-functions.tsx b/examples/react/start-rscs/src/low-level/components/nested-suspense/server-functions.tsx new file mode 100644 index 0000000000..9b40b68c25 --- /dev/null +++ b/examples/react/start-rscs/src/low-level/components/nested-suspense/server-functions.tsx @@ -0,0 +1,59 @@ +import { Suspense } from 'react' +import { createServerFn } from '@tanstack/react-start' +import { renderToReadableStream } from '@tanstack/react-start/rsc' + +// Server Component with async data +async function ServerDataCard({ delay }: { delay: number }) { + console.log('[Server] Starting ServerDataCard with delay:', delay) + await new Promise((resolve) => setTimeout(resolve, delay)) + const data = { + value: Math.floor(Math.random() * 1000), + computedAt: new Date().toISOString(), + } + console.log('[Server] Finished ServerDataCard:', data) + + return ( +
    +
    {data.value}
    +
    + Computed at: {data.computedAt} +
    +
    Delay: {delay}ms
    +
    + ) +} + +function LoadingSkeleton({ label }: { label: string }) { + return ( +
    +
    +
    +
    {label}
    +
    + ) +} + +// Server function returning a nested server component structure +export const getNestedServerComponent = createServerFn({ + method: 'GET', +}).handler(async () => { + const stream = await renderToReadableStream( +
    +
    +

    Nested Server Component

    +

    + This entire tree is rendered on the server +

    +
    +
    + }> + + + }> + + +
    +
    , + ) + return stream +}) diff --git a/examples/react/start-rscs/src/low-level/components/parallel-streams/ParallelStreamsDemo.tsx b/examples/react/start-rscs/src/low-level/components/parallel-streams/ParallelStreamsDemo.tsx new file mode 100644 index 0000000000..14500905c1 --- /dev/null +++ b/examples/react/start-rscs/src/low-level/components/parallel-streams/ParallelStreamsDemo.tsx @@ -0,0 +1,98 @@ +import { useCallback, useState } from 'react' +import { createFromReadableStream } from '@tanstack/react-start/rsc' + +import { getParallelStreams } from './server-functions' + +export function ParallelStreamsDemo() { + const [streams, setStreams] = useState<{ + card1: React.ReactNode | null + card2: React.ReactNode | null + card3: React.ReactNode | null + }>({ card1: null, card2: null, card3: null }) + const [loading, setLoading] = useState(false) + const [timing, setTiming] = useState>([]) + + const loadParallel = useCallback(async () => { + setLoading(true) + setStreams({ card1: null, card2: null, card3: null }) + setTiming([]) + + const startTime = Date.now() + const addTiming = (label: string) => { + const elapsed = Date.now() - startTime + setTiming((prev) => [...prev, `${label}: ${elapsed}ms`]) + } + + try { + const { stream1, stream2, stream3 } = await getParallelStreams() + addTiming('Streams received') + + // Decode streams in parallel + const [el1, el2, el3] = await Promise.all([ + createFromReadableStream(stream1).then((el) => { + addTiming('Card 1 decoded') + return el + }), + createFromReadableStream(stream2).then((el) => { + addTiming('Card 2 decoded') + return el + }), + createFromReadableStream(stream3).then((el) => { + addTiming('Card 3 decoded') + return el + }), + ]) + + setStreams({ + card1: el1 as React.ReactNode, + card2: el2 as React.ReactNode, + card3: el3 as React.ReactNode, + }) + } catch (error) { + console.error('Error:', error) + } finally { + setLoading(false) + } + }, []) + + return ( +
    + + + {timing.length > 0 && ( +
    + {timing.map((t, i) => ( +
    + {t} +
    + ))} +
    + )} + +
    + {[streams.card1, streams.card2, streams.card3].map((card, i) => ( +
    +
    + Card {i + 1} +
    + {card || ( +
    +
    +
    +
    + )} +
    + ))} +
    +
    + ) +} diff --git a/examples/react/start-rscs/src/low-level/components/parallel-streams/server-functions.tsx b/examples/react/start-rscs/src/low-level/components/parallel-streams/server-functions.tsx new file mode 100644 index 0000000000..3e5e9628b6 --- /dev/null +++ b/examples/react/start-rscs/src/low-level/components/parallel-streams/server-functions.tsx @@ -0,0 +1,37 @@ +import { createServerFn } from '@tanstack/react-start' +import { renderToReadableStream } from '@tanstack/react-start/rsc' + +// Server Component with async data (used for parallel and nested demos) +async function ServerDataCard({ delay }: { delay: number }) { + console.log('[Server] Starting ServerDataCard with delay:', delay) + await new Promise((resolve) => setTimeout(resolve, delay)) + const data = { + value: Math.floor(Math.random() * 1000), + computedAt: new Date().toISOString(), + } + console.log('[Server] Finished ServerDataCard:', data) + + return ( +
    +
    {data.value}
    +
    + Computed at: {data.computedAt} +
    +
    Delay: {delay}ms
    +
    + ) +} + +// Server function that returns multiple streams for parallel loading +export const getParallelStreams = createServerFn({ method: 'GET' }).handler( + async () => { + // Create three independent streams with different delays + const [stream1, stream2, stream3] = await Promise.all([ + renderToReadableStream(), + renderToReadableStream(), + renderToReadableStream(), + ]) + + return { stream1, stream2, stream3 } + }, +) diff --git a/examples/react/start-rscs/src/low-level/components/streaming-ticker/StreamingTicker.tsx b/examples/react/start-rscs/src/low-level/components/streaming-ticker/StreamingTicker.tsx new file mode 100644 index 0000000000..109187ee87 --- /dev/null +++ b/examples/react/start-rscs/src/low-level/components/streaming-ticker/StreamingTicker.tsx @@ -0,0 +1,152 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { createFromReadableStream } from '@tanstack/react-start/rsc' + +import { streamTickerRscs } from './server-functions' + +interface TickerEntry { + id: number + element: React.ReactNode + receivedAt: number +} + +// Helper to convert string payload back to ReadableStream +function payloadToStream(payload: string): ReadableStream { + const encoder = new TextEncoder() + return new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode(payload)) + controller.close() + }, + }) +} + +// Format relative time +function formatRelativeTime(receivedAt: number): string { + const seconds = Math.floor((Date.now() - receivedAt) / 1000) + if (seconds < 1) return 'just now' + if (seconds === 1) return '1 second ago' + return `${seconds} seconds ago` +} + +export function StreamingTicker() { + const [items, setItems] = useState>([]) + const [isStreaming, setIsStreaming] = useState(false) + const [, setTick] = useState(0) // Force re-render for relative time updates + const abortRef = useRef(false) + + // Update relative times every second + useEffect(() => { + const interval = setInterval(() => { + setTick((t) => t + 1) + }, 1000) + return () => clearInterval(interval) + }, []) + + const startStream = useCallback(async () => { + setIsStreaming(true) + abortRef.current = false + setItems([]) + + try { + for await (const { id, payload } of await streamTickerRscs()) { + if (abortRef.current) break + + // Decode the RSC payload + const stream = payloadToStream(payload) + const element = await createFromReadableStream(stream) + + const entry: TickerEntry = { + id, + element: element as React.ReactNode, + receivedAt: Date.now(), + } + + // Add to items, keeping only last 10 + setItems((prev) => [entry, ...prev].slice(0, 10)) + } + } catch (error) { + console.error('Streaming error:', error) + } finally { + setIsStreaming(false) + } + }, []) + + const stopStream = useCallback(() => { + abortRef.current = true + setIsStreaming(false) + }, []) + + const clearItems = useCallback(() => { + abortRef.current = true + setIsStreaming(false) + setItems([]) + }, []) + + return ( +
    +
    + {!isStreaming ? ( + + ) : ( + + )} + +
    + + {isStreaming && ( +
    +
    + Streaming RSCs... +
    + )} + +
    + {items.length === 0 ? ( +
    + Click "Start Stream" to begin receiving RSC payloads +
    + ) : ( + items.map((item) => ( +
    + {/* The RSC element */} + {item.element} + {/* Client-side relative time */} +
    + received {formatRelativeTime(item.receivedAt)} +
    +
    + )) + )} +
    + + {items.length > 0 && ( +
    + Showing {items.length} of last 10 items (newest first) +
    + )} + +
    + How it works: Each ticker item is a React Server + Component rendered on the server with{' '} + renderToReadableStream, streamed as a Flight payload, and + decoded on the client with createFromReadableStream. The + "received X seconds ago" text updates live on the client. +
    +
    + ) +} diff --git a/examples/react/start-rscs/src/low-level/components/streaming-ticker/server-functions.tsx b/examples/react/start-rscs/src/low-level/components/streaming-ticker/server-functions.tsx new file mode 100644 index 0000000000..2525b06f26 --- /dev/null +++ b/examples/react/start-rscs/src/low-level/components/streaming-ticker/server-functions.tsx @@ -0,0 +1,91 @@ +import { createServerFn } from '@tanstack/react-start' +import { renderToReadableStream } from '@tanstack/react-start/rsc' + +function sleep(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +// Helper to convert stream to string +async function streamToString( + stream: ReadableStream, +): Promise { + const reader = stream.getReader() + const chunks: Array = [] + const decoder = new TextDecoder() + + while (true) { + const { done, value } = await reader.read() + if (done) break + chunks.push(decoder.decode(value, { stream: true })) + } + + return chunks.join('') +} + +// Server component for each ticker item +function TickerItemCard({ + id, + timestamp, + variant, +}: { + id: number + timestamp: string + variant: 'info' | 'success' | 'warning' +}) { + const tickerColors = { + info: 'from-blue-500 to-cyan-500', + success: 'from-green-500 to-emerald-500', + warning: 'from-amber-500 to-orange-500', + } + + const formattedTime = new Date(timestamp).toLocaleTimeString() + + return ( +
    +
    +
    Server Update #{id + 1}
    +
    + {variant} +
    +
    +
    + Generated: {formattedTime} +
    +
    + ) +} + +// Server function that streams RSC Flight payloads +export const streamTickerRscs = createServerFn().handler(async function* () { + const variants = ['info', 'success', 'warning'] as const + + for (let i = 0; i < 15; i++) { + await sleep(800) + + console.log(`[Server] Rendering ticker item #${i + 1}`) + + // Render the server component to a Flight stream + const stream = await renderToReadableStream( + , + ) + + // Convert stream to string for yielding + const payload = await streamToString(stream) + + yield { id: i, payload } + } +}) diff --git a/examples/react/start-rscs/src/low-level/db.ts b/examples/react/start-rscs/src/low-level/db.ts new file mode 100644 index 0000000000..1c50f67f82 --- /dev/null +++ b/examples/react/start-rscs/src/low-level/db.ts @@ -0,0 +1,18 @@ +import Dexie from 'dexie' + +import type { EntityTable } from 'dexie' + +// Dexie database for RSC payload caching +export interface RscCacheEntry { + id: string + payload: string + createdAt: number +} + +export const db = new Dexie('RscCache') as Dexie & { + cache: EntityTable +} + +db.version(1).stores({ + cache: 'id, createdAt', +}) diff --git a/examples/react/start-rscs/src/low-level/index.ts b/examples/react/start-rscs/src/low-level/index.ts new file mode 100644 index 0000000000..1f575e2c0b --- /dev/null +++ b/examples/react/start-rscs/src/low-level/index.ts @@ -0,0 +1,29 @@ +// Shared components +export { DemoSection } from './components/DemoSection' + +// Demo 1: Direct Flight Stream +export { DirectFlightStreamDemo } from './components/direct-flight/DirectFlightStreamDemo' +export { getFlightStreamDirect } from './components/direct-flight/server-functions' + +// Demo 2: Fetch Flight Stream (uses /api/rsc route) +export { FetchFlightStreamDemo } from './components/fetch-flight/FetchFlightStreamDemo' + +// Demo 3: Parallel Streams +export { ParallelStreamsDemo } from './components/parallel-streams/ParallelStreamsDemo' +export { getParallelStreams } from './components/parallel-streams/server-functions' + +// Demo 4: Nested Suspense +export { NestedSuspenseDemo } from './components/nested-suspense/NestedSuspenseDemo' +export { getNestedServerComponent } from './components/nested-suspense/server-functions' + +// Demo 5: Dexie Cache +export { DexieCacheDemo } from './components/dexie-cache/DexieCacheDemo' +export { getCounterRscPayload } from './components/dexie-cache/server-functions' + +// Demo 6: Streaming Ticker +export { StreamingTicker } from './components/streaming-ticker/StreamingTicker' +export { streamTickerRscs } from './components/streaming-ticker/server-functions' + +// Dexie database +export { db } from './db' +export type { RscCacheEntry } from './db' diff --git a/examples/react/start-rscs/src/pokemon/Button.tsx b/examples/react/start-rscs/src/pokemon/Button.tsx new file mode 100644 index 0000000000..e458cac948 --- /dev/null +++ b/examples/react/start-rscs/src/pokemon/Button.tsx @@ -0,0 +1,19 @@ +'use client' + +export function Button({ + className, + title, +}: { + className?: string + title?: string +}) { + return ( + + ) +} diff --git a/examples/react/start-rscs/src/pokemon/server-functions.tsx b/examples/react/start-rscs/src/pokemon/server-functions.tsx new file mode 100644 index 0000000000..37aa33a7c2 --- /dev/null +++ b/examples/react/start-rscs/src/pokemon/server-functions.tsx @@ -0,0 +1,139 @@ +import { createServerFn } from '@tanstack/react-start' +import { renderServerComponent } from '@tanstack/react-start/rsc' +import { Button } from './Button' + +// ============================================ +// Pokemon RSC - Async Server Component Example +// ============================================ + +// Types for PokeAPI +export interface PokemonListItem { + name: string + url: string +} + +export interface PokemonDetails { + id: number + name: string + sprites: { front_default: string } + types: Array<{ type: { name: string } }> +} + +// Type color mapping for Pokemon type badges +export const typeColors: Record = { + normal: 'bg-gray-400', + fire: 'bg-red-500', + water: 'bg-blue-500', + electric: 'bg-yellow-400', + grass: 'bg-green-500', + ice: 'bg-cyan-300', + fighting: 'bg-orange-700', + poison: 'bg-purple-500', + ground: 'bg-amber-600', + flying: 'bg-indigo-300', + psychic: 'bg-pink-500', + bug: 'bg-lime-500', + rock: 'bg-stone-500', + ghost: 'bg-purple-700', + dragon: 'bg-indigo-600', + dark: 'bg-gray-700', + steel: 'bg-gray-400', + fairy: 'bg-pink-300', +} + +// Server component for individual Pokemon card +function PokemonCard({ pokemon }: { pokemon: PokemonDetails }) { + return ( +
    + {pokemon.name} +

    {pokemon.name}

    +

    #{pokemon.id}

    +
    + {pokemon.types.map((t) => ( +
    +
    + ) +} + +// Async Server Component - fetches its own data (like Next.js RSC) +async function PokemonList() { + console.log('[Server] Fetching Pokemon data...') + + // Data fetching happens INSIDE the component + const response = await fetch('https://pokeapi.co/api/v2/pokemon?limit=20') + const data = await response.json() + + // Fetch details for each Pokemon to get sprites and types + const pokemonDetails = await Promise.all( + data.results.map(async (pokemon: PokemonListItem) => { + const res = await fetch(pokemon.url) + return res.json() as Promise + }), + ) + + console.log(`[Server] Fetched ${pokemonDetails.length} Pokemon`) + + return ( +
    +

    + Pokemon (Server Component) +

    +

    + This list was fetched and rendered entirely on the server using an async + React component. +

    +
    + {pokemonDetails.map((pokemon) => ( + + ))} +
    +
    + ) +} + +// Server function that renders the async component +export const getPokemonList = createServerFn().handler(async () => { + const Renderable = await renderServerComponent() + return { Renderable } +}) + +// Server function that fetches Pokemon data (traditional SSR - no RSC) +export const fetchPokemonData = createServerFn().handler(async () => { + console.log('[Server] Fetching Pokemon data (traditional loader)...') + + const response = await fetch('https://pokeapi.co/api/v2/pokemon?limit=20') + const data = await response.json() + + const pokemonDetails = await Promise.all( + data.results.map(async (pokemon: PokemonListItem) => { + const res = await fetch(pokemon.url) + const { name, id, sprites, types } = await res.json() + return { + name, + id, + sprites: { + front_default: sprites.front_default, + }, + types: types.map( + (t: { type: { name: string } }): { type: { name: string } } => ({ + type: { name: t.type.name }, + }), + ), + } as unknown as Promise + }), + ) + + console.log(`[Server] Fetched ${pokemonDetails.length} Pokemon (traditional)`) + + return { pokemon: pokemonDetails } +}) diff --git a/examples/react/start-rscs/src/routeTree.gen.ts b/examples/react/start-rscs/src/routeTree.gen.ts new file mode 100644 index 0000000000..d89ab3d3e7 --- /dev/null +++ b/examples/react/start-rscs/src/routeTree.gen.ts @@ -0,0 +1,177 @@ +/* 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 ECommerceRouteImport } from './routes/e-commerce' +import { Route as LowLevelApiRouteImport } from './routes/low-level-api' +import { Route as PokemonRouteImport } from './routes/pokemon' +import { Route as PokemonRscRouteImport } from './routes/pokemon-rsc' +import { Route as ApiRscRouteImport } from './routes/api/rsc' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ECommerceRoute = ECommerceRouteImport.update({ + id: '/e-commerce', + path: '/e-commerce', + getParentRoute: () => rootRouteImport, +} as any) +const LowLevelApiRoute = LowLevelApiRouteImport.update({ + id: '/low-level-api', + path: '/low-level-api', + getParentRoute: () => rootRouteImport, +} as any) +const PokemonRoute = PokemonRouteImport.update({ + id: '/pokemon', + path: '/pokemon', + getParentRoute: () => rootRouteImport, +} as any) +const PokemonRscRoute = PokemonRscRouteImport.update({ + id: '/pokemon-rsc', + path: '/pokemon-rsc', + getParentRoute: () => rootRouteImport, +} as any) +const ApiRscRoute = ApiRscRouteImport.update({ + id: '/api/rsc', + path: '/api/rsc', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/e-commerce': typeof ECommerceRoute + '/low-level-api': typeof LowLevelApiRoute + '/pokemon': typeof PokemonRoute + '/pokemon-rsc': typeof PokemonRscRoute + '/api/rsc': typeof ApiRscRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/e-commerce': typeof ECommerceRoute + '/low-level-api': typeof LowLevelApiRoute + '/pokemon': typeof PokemonRoute + '/pokemon-rsc': typeof PokemonRscRoute + '/api/rsc': typeof ApiRscRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/e-commerce': typeof ECommerceRoute + '/low-level-api': typeof LowLevelApiRoute + '/pokemon': typeof PokemonRoute + '/pokemon-rsc': typeof PokemonRscRoute + '/api/rsc': typeof ApiRscRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/e-commerce' + | '/low-level-api' + | '/pokemon' + | '/pokemon-rsc' + | '/api/rsc' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/e-commerce' + | '/low-level-api' + | '/pokemon' + | '/pokemon-rsc' + | '/api/rsc' + id: + | '__root__' + | '/' + | '/e-commerce' + | '/low-level-api' + | '/pokemon' + | '/pokemon-rsc' + | '/api/rsc' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ECommerceRoute: typeof ECommerceRoute + LowLevelApiRoute: typeof LowLevelApiRoute + PokemonRoute: typeof PokemonRoute + PokemonRscRoute: typeof PokemonRscRoute + ApiRscRoute: typeof ApiRscRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/e-commerce': { + id: '/e-commerce' + path: '/e-commerce' + fullPath: '/e-commerce' + preLoaderRoute: typeof ECommerceRouteImport + parentRoute: typeof rootRouteImport + } + '/low-level-api': { + id: '/low-level-api' + path: '/low-level-api' + fullPath: '/low-level-api' + preLoaderRoute: typeof LowLevelApiRouteImport + parentRoute: typeof rootRouteImport + } + '/pokemon': { + id: '/pokemon' + path: '/pokemon' + fullPath: '/pokemon' + preLoaderRoute: typeof PokemonRouteImport + parentRoute: typeof rootRouteImport + } + '/pokemon-rsc': { + id: '/pokemon-rsc' + path: '/pokemon-rsc' + fullPath: '/pokemon-rsc' + preLoaderRoute: typeof PokemonRscRouteImport + parentRoute: typeof rootRouteImport + } + '/api/rsc': { + id: '/api/rsc' + path: '/api/rsc' + fullPath: '/api/rsc' + preLoaderRoute: typeof ApiRscRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ECommerceRoute: ECommerceRoute, + LowLevelApiRoute: LowLevelApiRoute, + PokemonRoute: PokemonRoute, + PokemonRscRoute: PokemonRscRoute, + ApiRscRoute: ApiRscRoute, +} +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-rscs/src/router.tsx b/examples/react/start-rscs/src/router.tsx new file mode 100644 index 0000000000..335a55600f --- /dev/null +++ b/examples/react/start-rscs/src/router.tsx @@ -0,0 +1,11 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + const router = createRouter({ + routeTree, + defaultPreload: 'intent', + scrollRestoration: true, + }) + return router +} diff --git a/examples/react/start-rscs/src/routes/__root.tsx b/examples/react/start-rscs/src/routes/__root.tsx new file mode 100644 index 0000000000..80891bd2ee --- /dev/null +++ b/examples/react/start-rscs/src/routes/__root.tsx @@ -0,0 +1,44 @@ +/// +import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' +import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' +import * as React from 'react' +import appCss from '~/styles/app.css?url' +import { Layout } from '~/components/Layout' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { + charSet: 'utf-8', + }, + { + name: 'viewport', + content: 'width=device-width, initial-scale=1', + }, + { + title: 'TanStack Start RSC Examples', + }, + ], + links: [ + { rel: 'stylesheet', href: appCss }, + { rel: 'icon', href: '/favicon.ico' }, + ], + }), + shellComponent: RootDocument, + component: Layout, +}) + +function RootDocument({ children }: { children: React.ReactNode }) { + return ( + + + + + + {children} + + + + + ) +} diff --git a/examples/react/start-rscs/src/routes/api/rsc.tsx b/examples/react/start-rscs/src/routes/api/rsc.tsx new file mode 100644 index 0000000000..e2c9aeccd4 --- /dev/null +++ b/examples/react/start-rscs/src/routes/api/rsc.tsx @@ -0,0 +1,43 @@ +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { renderToReadableStream } from '@tanstack/react-start/rsc' + +// Server component to render +function ApiServerComponent() { + const timestamp = new Date().toISOString() + + return ( +
    +

    API Route RSC

    +

    + This component was streamed from /api/rsc +

    +

    + Timestamp: {timestamp} +

    +
    + ) +} + +// Server function to render the RSC +const getFlightStream = createServerFn({ method: 'GET' }).handler(async () => { + console.log('[API] Rendering Flight stream for /api/rsc') + return renderToReadableStream() +}) + +export const Route = createFileRoute('/api/rsc')({ + server: { + handlers: { + GET: async () => { + const stream = await getFlightStream() + + return new Response(stream, { + headers: { + 'Content-Type': 'text/x-component', + 'Cache-Control': 'no-store', + }, + }) + }, + }, + }, +}) diff --git a/examples/react/start-rscs/src/routes/e-commerce.tsx b/examples/react/start-rscs/src/routes/e-commerce.tsx new file mode 100644 index 0000000000..eb215d256c --- /dev/null +++ b/examples/react/start-rscs/src/routes/e-commerce.tsx @@ -0,0 +1,48 @@ +import { createFileRoute } from '@tanstack/react-router' +import { CompositeComponent } from '@tanstack/react-start/rsc' +import { getProductPage } from '~/e-Commerce/server-functions' +import { AddToCartButton } from '~/e-Commerce/components/AddToCartButton' +import { AlsoBoughtCarousel } from '~/e-Commerce/components/AlsoBoughtCarousel' +import { Header } from '~/e-Commerce/components/Header' +import { StreamingComments } from '~/e-Commerce/components/StreamingComments' + +export const Route = createFileRoute('/e-commerce')({ + loader: async () => { + const ProductPage = await getProductPage() + return { ProductPage } + }, + component: ECommercePage, +}) + +function ECommercePage() { + const { ProductPage } = Route.useLoaderData() + + return ( +
    +
    + {/* Page Header with Cart */} +
    + + {/* Main Product Section */} + ( + + )} + > + + + + {/* Customer Reviews Section */} +
    +

    + Customer Reviews +

    +
    + +
    +
    +
    +
    + ) +} diff --git a/examples/react/start-rscs/src/routes/index.tsx b/examples/react/start-rscs/src/routes/index.tsx new file mode 100644 index 0000000000..244bb4ca1d --- /dev/null +++ b/examples/react/start-rscs/src/routes/index.tsx @@ -0,0 +1,71 @@ +import { Link, createFileRoute } from '@tanstack/react-router' +import { CompositeComponent } from '@tanstack/react-start/rsc' +import type { DemoInfo } from '~/home/server-functions' +import { getHomePage } from '~/home/server-functions' + +export const Route = createFileRoute('/')({ + loader: async () => { + const HomePage = await getHomePage() + return { HomePage } + }, + component: Home, +}) + +function DemoCard({ demo }: { demo: DemoInfo }) { + return ( + +
    +
    +
    +

    + {demo.title} +

    +

    {demo.description}

    +
    + {demo.features.map((feature) => ( + + {feature} + + ))} +
    +
    + View Demo + + + +
    +
    +
    + + ) +} + +function Home() { + const { HomePage } = Route.useLoaderData() + + return ( +
    +
    +
    + } + /> +
    +
    +
    + ) +} diff --git a/examples/react/start-rscs/src/routes/low-level-api.tsx b/examples/react/start-rscs/src/routes/low-level-api.tsx new file mode 100644 index 0000000000..58ccf6d1ad --- /dev/null +++ b/examples/react/start-rscs/src/routes/low-level-api.tsx @@ -0,0 +1,82 @@ +import { createFileRoute } from '@tanstack/react-router' + +import { + DemoSection, + DexieCacheDemo, + DirectFlightStreamDemo, + FetchFlightStreamDemo, + NestedSuspenseDemo, + ParallelStreamsDemo, + StreamingTicker, +} from '~/low-level' + +export const Route = createFileRoute('/low-level-api')({ + component: LowLevelApiPage, +}) + +function LowLevelApiPage() { + return ( +
    +
    +
    +

    + Low-Level RSC Primitives +

    +

    + Demonstrating TanStack Start's low-level Flight stream APIs +

    +
    + +
    + {/* Demo 1: Direct Flight Stream */} + + + + + {/* Demo 2: Fetch-based Flight Stream */} + + + + + {/* Demo 3: Parallel Streams */} + + + + + {/* Demo 4: Nested with Suspense */} + + + + + {/* Demo 5: Dexie Cache */} + + + + + {/* Demo 6: HTTP Streaming Ticker */} + + + +
    +
    +
    + ) +} diff --git a/examples/react/start-rscs/src/routes/pokemon-rsc.tsx b/examples/react/start-rscs/src/routes/pokemon-rsc.tsx new file mode 100644 index 0000000000..a654c1f3a5 --- /dev/null +++ b/examples/react/start-rscs/src/routes/pokemon-rsc.tsx @@ -0,0 +1,52 @@ +import { Link, createFileRoute } from '@tanstack/react-router' +import { getPokemonList } from '~/pokemon/server-functions' + +export const Route = createFileRoute('/pokemon-rsc')({ + loader: async () => { + const { Renderable } = await getPokemonList() + return Renderable + }, + component: PokemonPage, +}) + +function PokemonPage() { + const PokemonList = Route.useLoaderData() + + return ( +
    +
    + {/* Comparison Link */} +
    +
    +

    + Compare: See how this RSC version differs from + the traditional SSR approach in structure and payload size. +

    +
    + + View Traditional Version + + + + +
    + + {/* Pokemon List - Server Component */} +
    {PokemonList}
    +
    +
    + ) +} diff --git a/examples/react/start-rscs/src/routes/pokemon.tsx b/examples/react/start-rscs/src/routes/pokemon.tsx new file mode 100644 index 0000000000..e4cffba044 --- /dev/null +++ b/examples/react/start-rscs/src/routes/pokemon.tsx @@ -0,0 +1,105 @@ +import { Link, createFileRoute } from '@tanstack/react-router' +import type { PokemonDetails } from '~/pokemon/server-functions' +import { fetchPokemonData, typeColors } from '~/pokemon/server-functions' + +export const Route = createFileRoute('/pokemon')({ + loader: async () => { + // Traditional loader pattern - fetches data, returns JSON + // This data is serialized to JSON and sent to the client + // The component then renders it on the client + const { pokemon } = await fetchPokemonData() + return { pokemon } + }, + component: PokemonPage, +}) + +function Button({ className, title }: { className?: string; title?: string }) { + return ( + + ) +} + +function PokemonCard({ pokemon }: { pokemon: PokemonDetails }) { + return ( +
    + {pokemon.name} +

    {pokemon.name}

    +

    #{pokemon.id}

    +
    + {pokemon.types.map((t) => ( +
    +
    + ) +} + +function PokemonPage() { + const { pokemon } = Route.useLoaderData() + + return ( +
    +
    +
    +

    + Pokemon (Traditional SSR) +

    +

    + This list was fetched in the loader and rendered as a normal React + component. The data is serialized to JSON and sent to the client, + where the component re-renders with that data. +

    + +
    +

    + Note: Unlike the RSC version, this page sends the + full Pokemon data as JSON in the initial HTML payload. The + component code also ships to the client and re-hydrates. Check the + Network tab to compare payload sizes! +

    +
    + + + + + + View RSC Version + + +
    + {pokemon.map((p) => ( + + ))} +
    +
    +
    +
    + ) +} diff --git a/e2e/react-start/basic-rsc/src/styles/app.css b/examples/react/start-rscs/src/styles/app.css similarity index 100% rename from e2e/react-start/basic-rsc/src/styles/app.css rename to examples/react/start-rscs/src/styles/app.css diff --git a/examples/react/start-rscs/tsconfig.json b/examples/react/start-rscs/tsconfig.json new file mode 100644 index 0000000000..8554925771 --- /dev/null +++ b/examples/react/start-rscs/tsconfig.json @@ -0,0 +1,22 @@ +{ + "include": ["**/*.ts", "**/*.tsx", "**/*.d.ts"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2024"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2024", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "baseUrl": ".", + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true + } +} diff --git a/examples/react/start-rscs/vite.config.ts b/examples/react/start-rscs/vite.config.ts new file mode 100644 index 0000000000..3fffc19f6d --- /dev/null +++ b/examples/react/start-rscs/vite.config.ts @@ -0,0 +1,24 @@ +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' +import { nitro } from 'nitro/vite' +import rsc from '@vitejs/plugin-rsc' + +export default defineConfig({ + resolve: { tsconfigPaths: true }, + server: { + port: 3000, + }, + plugins: [ + tailwindcss(), + tanstackStart({ + rsc: { + enabled: true, + }, + }), + rsc(), + viteReact(), + nitro(), + ], +}) diff --git a/examples/react/start-streaming-data-from-server-functions/.devcontainer/devcontainer.json b/examples/react/start-streaming-data-from-server-functions/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-streaming-data-from-server-functions/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-streaming-data-from-server-functions/package.json b/examples/react/start-streaming-data-from-server-functions/package.json index 25dd9fc2ff..762bbff733 100644 --- a/examples/react/start-streaming-data-from-server-functions/package.json +++ b/examples/react/start-streaming-data-from-server-functions/package.json @@ -10,20 +10,20 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-streaming-data-from-server-functions/src/router.tsx b/examples/react/start-streaming-data-from-server-functions/src/router.tsx index a464233af9..6f82cbf378 100644 --- a/examples/react/start-streaming-data-from-server-functions/src/router.tsx +++ b/examples/react/start-streaming-data-from-server-functions/src/router.tsx @@ -5,7 +5,9 @@ export function getRouter() { const router = createRouter({ routeTree, defaultPreload: 'intent', - defaultErrorComponent: (err) =>

    {err.error.stack}

    , + defaultErrorComponent: (err) => ( +

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

    + ), defaultNotFoundComponent: () =>

    not found

    , scrollRestoration: true, }) diff --git a/examples/react/start-streaming-data-from-server-functions/tsconfig.json b/examples/react/start-streaming-data-from-server-functions/tsconfig.json index b3a2d67dfa..af81492efb 100644 --- a/examples/react/start-streaming-data-from-server-functions/tsconfig.json +++ b/examples/react/start-streaming-data-from-server-functions/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-streaming-data-from-server-functions/vite.config.ts b/examples/react/start-streaming-data-from-server-functions/vite.config.ts index f10c86e79f..d0ee8802cf 100644 --- a/examples/react/start-streaming-data-from-server-functions/vite.config.ts +++ b/examples/react/start-streaming-data-from-server-functions/vite.config.ts @@ -1,17 +1,13 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tanstackStart(), viteReact()], }) diff --git a/examples/react/start-supabase-basic/.devcontainer/devcontainer.json b/examples/react/start-supabase-basic/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-supabase-basic/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-supabase-basic/.gitignore b/examples/react/start-supabase-basic/.gitignore index 8293849e8d..372dc30373 100644 --- a/examples/react/start-supabase-basic/.gitignore +++ b/examples/react/start-supabase-basic/.gitignore @@ -1,12 +1,11 @@ node_modules -# Keep environment variables out of version control -!.env package-lock.json yarn.lock .DS_Store .cache -.env +# The checked-in .env contains public demo values used by the build. +!.env .vercel .output /build/ diff --git a/examples/react/start-supabase-basic/README.md b/examples/react/start-supabase-basic/README.md index adeac26133..8a09b7f154 100644 --- a/examples/react/start-supabase-basic/README.md +++ b/examples/react/start-supabase-basic/README.md @@ -18,8 +18,8 @@ npx gitpick TanStack/router/tree/main/examples/react/start-supabase-basic start- This example requires Supabase configuration. The `.env` file contains the necessary environment variables: ```env -VITE_SUPABASE_URL=your-project-url -VITE_SUPABASE_ANON_KEY=your-anon-key +SUPABASE_URL=your-project-url +SUPABASE_ANON_KEY=your-anon-key ``` You'll need to: diff --git a/examples/react/start-supabase-basic/package.json b/examples/react/start-supabase-basic/package.json index 377a5cb803..0bf4b2c246 100644 --- a/examples/react/start-supabase-basic/package.json +++ b/examples/react/start-supabase-basic/package.json @@ -15,22 +15,21 @@ "dependencies": { "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-react": "^6.0.1", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-supabase-basic/postcss.config.mjs b/examples/react/start-supabase-basic/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/start-supabase-basic/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/start-supabase-basic/src/components/DefaultCatchBoundary.tsx b/examples/react/start-supabase-basic/src/components/DefaultCatchBoundary.tsx index 30e64b85b9..405fb5f4a7 100644 --- a/examples/react/start-supabase-basic/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-supabase-basic/src/components/DefaultCatchBoundary.tsx @@ -1,18 +1,15 @@ -import * as React from 'react' import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error(error) diff --git a/examples/react/start-supabase-basic/src/routeTree.gen.ts b/examples/react/start-supabase-basic/src/routeTree.gen.ts index 9e96fafa6a..998d34a709 100644 --- a/examples/react/start-supabase-basic/src/routeTree.gen.ts +++ b/examples/react/start-supabase-basic/src/routeTree.gen.ts @@ -9,23 +9,22 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as SignupRouteImport } from './routes/signup' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as SignupRouteImport } from './routes/signup' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -33,13 +32,14 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,18 +120,18 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } '/login': { @@ -141,18 +141,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthedRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/examples/react/start-supabase-basic/src/routes/_authed.tsx b/examples/react/start-supabase-basic/src/routes/_authed.tsx index f6edff63c1..697e35e427 100644 --- a/examples/react/start-supabase-basic/src/routes/_authed.tsx +++ b/examples/react/start-supabase-basic/src/routes/_authed.tsx @@ -4,7 +4,7 @@ import { Login } from '../components/Login' import { getSupabaseServerClient } from '../utils/supabase' export const loginFn = createServerFn({ method: 'POST' }) - .inputValidator((d: { email: string; password: string }) => d) + .validator((d: { email: string; password: string }) => d) .handler(async ({ data }) => { const supabase = getSupabaseServerClient() const { error } = await supabase.auth.signInWithPassword({ @@ -27,7 +27,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return } diff --git a/examples/react/start-supabase-basic/src/routes/signup.tsx b/examples/react/start-supabase-basic/src/routes/signup.tsx index 908d8ffcb3..d7c0060084 100644 --- a/examples/react/start-supabase-basic/src/routes/signup.tsx +++ b/examples/react/start-supabase-basic/src/routes/signup.tsx @@ -5,7 +5,7 @@ import { Auth } from '../components/Auth' import { getSupabaseServerClient } from '../utils/supabase' export const signupFn = createServerFn({ method: 'POST' }) - .inputValidator( + .validator( (d: { email: string; password: string; redirectUrl?: string }) => d, ) .handler(async ({ data }) => { diff --git a/examples/react/start-supabase-basic/src/styles/app.css b/examples/react/start-supabase-basic/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/react/start-supabase-basic/src/styles/app.css +++ b/examples/react/start-supabase-basic/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/start-supabase-basic/src/utils/posts.ts b/examples/react/start-supabase-basic/src/utils/posts.ts index 297beefeb7..5512187e92 100644 --- a/examples/react/start-supabase-basic/src/utils/posts.ts +++ b/examples/react/start-supabase-basic/src/utils/posts.ts @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/examples/react/start-supabase-basic/tsconfig.json b/examples/react/start-supabase-basic/tsconfig.json index 3a9fb7cd71..cef9369516 100644 --- a/examples/react/start-supabase-basic/tsconfig.json +++ b/examples/react/start-supabase-basic/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-supabase-basic/vite.config.ts b/examples/react/start-supabase-basic/vite.config.ts index f10c86e79f..ed6799764a 100644 --- a/examples/react/start-supabase-basic/vite.config.ts +++ b/examples/react/start-supabase-basic/vite.config.ts @@ -1,17 +1,14 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteReact()], }) diff --git a/examples/react/start-tailwind-v4/.devcontainer/devcontainer.json b/examples/react/start-tailwind-v4/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-tailwind-v4/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-tailwind-v4/package.json b/examples/react/start-tailwind-v4/package.json index b59c9341e1..b58fbe4ff0 100644 --- a/examples/react/start-tailwind-v4/package.json +++ b/examples/react/start-tailwind-v4/package.json @@ -10,23 +10,23 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", - "tailwind-merge": "^2.6.0", - "zod": "^3.24.2" + "tailwind-merge": "^3.6.0", + "zod": "^4.4.3" }, "devDependencies": { - "@tailwindcss/vite": "^4.1.17", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-react": "^6.0.1", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-tailwind-v4/tsconfig.json b/examples/react/start-tailwind-v4/tsconfig.json index 3a9fb7cd71..cef9369516 100644 --- a/examples/react/start-tailwind-v4/tsconfig.json +++ b/examples/react/start-tailwind-v4/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-tailwind-v4/vite.config.ts b/examples/react/start-tailwind-v4/vite.config.ts index 360b4f7dda..0db3dff8bc 100644 --- a/examples/react/start-tailwind-v4/vite.config.ts +++ b/examples/react/start-tailwind-v4/vite.config.ts @@ -1,6 +1,5 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import tailwindcss from '@tailwindcss/vite' import viteReact from '@vitejs/plugin-react' @@ -8,12 +7,8 @@ export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - tailwindcss(), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tanstackStart(), viteReact(), tailwindcss()], }) diff --git a/examples/react/start-trellaux/.devcontainer/devcontainer.json b/examples/react/start-trellaux/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-trellaux/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-trellaux/package.json b/examples/react/start-trellaux/package.json index e5642842c1..7755d227fc 100644 --- a/examples/react/start-trellaux/package.json +++ b/examples/react/start-trellaux/package.json @@ -10,32 +10,30 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-router-ssr-query": "^1.141.8", - "@tanstack/react-start": "^1.142.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", "ky": "^1.7.4", "msw": "^2.7.0", "react": "^19.0.0", "react-dom": "^19.0.0", "react-hot-toast": "^2.5.1", "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "tiny-invariant": "^1.3.3", - "zod": "^3.24.2" + "tailwind-merge": "^3.6.0", + "zod": "^4.4.3" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.6.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-react": "^6.0.1", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-trellaux/postcss.config.mjs b/examples/react/start-trellaux/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/react/start-trellaux/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/react/start-trellaux/src/components/Board.tsx b/examples/react/start-trellaux/src/components/Board.tsx index 0b43e1d923..0ba9a3c288 100644 --- a/examples/react/start-trellaux/src/components/Board.tsx +++ b/examples/react/start-trellaux/src/components/Board.tsx @@ -1,5 +1,5 @@ import { useCallback, useMemo, useRef } from 'react' -import invariant from 'tiny-invariant' +import { invariant } from '../invariant' import { useSuspenseQuery } from '@tanstack/react-query' import { boardQueries, useUpdateBoardMutation } from '../queries.js' import { NewColumn } from './NewColumn.js' diff --git a/examples/react/start-trellaux/src/components/Card.tsx b/examples/react/start-trellaux/src/components/Card.tsx index 6c73ca079f..729b93d2f8 100644 --- a/examples/react/start-trellaux/src/components/Card.tsx +++ b/examples/react/start-trellaux/src/components/Card.tsx @@ -1,4 +1,4 @@ -import invariant from 'tiny-invariant' +import { invariant } from '../invariant' import { forwardRef, useState } from 'react' import { CONTENT_TYPES } from '../types' diff --git a/examples/react/start-trellaux/src/components/Column.tsx b/examples/react/start-trellaux/src/components/Column.tsx index f9fddaaf5f..a95faedb54 100644 --- a/examples/react/start-trellaux/src/components/Column.tsx +++ b/examples/react/start-trellaux/src/components/Column.tsx @@ -1,8 +1,8 @@ import { forwardRef, useCallback, useMemo, useRef, useState } from 'react' -import invariant from 'tiny-invariant' import { twMerge } from 'tailwind-merge' import { flushSync } from 'react-dom' +import { invariant } from '../invariant' import { CONTENT_TYPES } from '../types' import { Icon } from '../icons/icons' import { diff --git a/examples/react/start-trellaux/src/components/DefaultCatchBoundary.tsx b/examples/react/start-trellaux/src/components/DefaultCatchBoundary.tsx index 260c2ea41f..4a22649ed4 100644 --- a/examples/react/start-trellaux/src/components/DefaultCatchBoundary.tsx +++ b/examples/react/start-trellaux/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/react-router' import type { ErrorComponentProps } from '@tanstack/react-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error('DefaultCatchBoundary Error:', error) diff --git a/examples/react/start-trellaux/src/components/NewCard.tsx b/examples/react/start-trellaux/src/components/NewCard.tsx index 8201083bb3..b46f965c8b 100644 --- a/examples/react/start-trellaux/src/components/NewCard.tsx +++ b/examples/react/start-trellaux/src/components/NewCard.tsx @@ -1,5 +1,5 @@ import { useRef } from 'react' -import invariant from 'tiny-invariant' +import { invariant } from '../invariant' import { ItemMutationFields } from '../types' import { useCreateItemMutation } from '../queries' diff --git a/examples/react/start-trellaux/src/components/NewColumn.tsx b/examples/react/start-trellaux/src/components/NewColumn.tsx index acb6c82cfb..655b380743 100644 --- a/examples/react/start-trellaux/src/components/NewColumn.tsx +++ b/examples/react/start-trellaux/src/components/NewColumn.tsx @@ -1,5 +1,5 @@ import { useRef, useState } from 'react' -import invariant from 'tiny-invariant' +import { invariant } from '../invariant' import { Icon } from '../icons/icons' import { useCreateColumnMutation } from '../queries' diff --git a/examples/react/start-trellaux/src/db/board.ts b/examples/react/start-trellaux/src/db/board.ts index 92f94967e9..91ec369936 100644 --- a/examples/react/start-trellaux/src/db/board.ts +++ b/examples/react/start-trellaux/src/db/board.ts @@ -1,6 +1,6 @@ import crypto from 'node:crypto' import { createServerFn } from '@tanstack/react-start' -import invariant from 'tiny-invariant' +import { invariant } from '../invariant' import * as z from 'zod' import { deleteColumnSchema, @@ -33,7 +33,7 @@ export const getBoards = createServerFn({ method: 'GET' }).handler(async () => { }) export const getBoard = createServerFn({ method: 'GET' }) - .inputValidator(z.string()) + .validator(z.string()) .handler(async ({ data }) => { await delay(DELAY) const board = boards.find((b) => b.id === data) @@ -42,7 +42,7 @@ export const getBoard = createServerFn({ method: 'GET' }) }) export const createColumn = createServerFn() - .inputValidator(newColumnSchema) + .validator(newColumnSchema) .handler(async ({ data }) => { await delay(DELAY) const newColumn = newColumnSchema.parse(data) @@ -62,7 +62,7 @@ export const createColumn = createServerFn() }) export const createItem = createServerFn() - .inputValidator(itemSchema) + .validator(itemSchema) .handler(async ({ data }) => { await delay(DELAY) const item = itemSchema.parse(data) @@ -75,7 +75,7 @@ export const createItem = createServerFn() }) export const deleteItem = createServerFn({ method: 'GET' }) - .inputValidator(deleteItemSchema) + .validator(deleteItemSchema) .handler(async ({ data }) => { await delay(DELAY) const { id } = deleteItemSchema.parse(data) @@ -85,7 +85,7 @@ export const deleteItem = createServerFn({ method: 'GET' }) }) export const updateItem = createServerFn() - .inputValidator(itemSchema) + .validator(itemSchema) .handler(async ({ data }) => { await delay(DELAY) const item = itemSchema.parse(data) @@ -97,7 +97,7 @@ export const updateItem = createServerFn() }) export const updateColumn = createServerFn() - .inputValidator(updateColumnSchema) + .validator(updateColumnSchema) .handler(async ({ data }) => { await delay(DELAY) const column = updateColumnSchema.parse(data) @@ -109,7 +109,7 @@ export const updateColumn = createServerFn() }) export const updateBoard = createServerFn() - .inputValidator(updateBoardSchema) + .validator(updateBoardSchema) .handler(async ({ data }) => { await delay(DELAY) const update = updateBoardSchema.parse(data) @@ -119,7 +119,7 @@ export const updateBoard = createServerFn() }) export const deleteColumn = createServerFn({ method: 'GET' }) - .inputValidator(deleteColumnSchema) + .validator(deleteColumnSchema) .handler(async ({ data }) => { await delay(DELAY) const { id } = deleteColumnSchema.parse(data) diff --git a/examples/react/start-trellaux/src/db/schema.ts b/examples/react/start-trellaux/src/db/schema.ts index 52c3587703..5fe4da32fa 100644 --- a/examples/react/start-trellaux/src/db/schema.ts +++ b/examples/react/start-trellaux/src/db/schema.ts @@ -4,20 +4,20 @@ export const itemSchema = z.object({ id: z.string(), title: z.string(), content: z.string().optional(), - order: z.coerce.number(), + order: z.coerce.number(), columnId: z.string().uuid(), - boardId: z.coerce.string(), + boardId: z.coerce.string(), }) export const columnSchema = z.object({ id: z.string().uuid(), - boardId: z.coerce.string(), + boardId: z.coerce.string(), name: z.string(), order: z.number(), }) export const boardSchema = z.object({ - id: z.coerce.string(), + id: z.coerce.string(), name: z.string(), color: z.string(), columns: z.array(columnSchema), diff --git a/examples/react/start-trellaux/src/invariant.ts b/examples/react/start-trellaux/src/invariant.ts new file mode 100644 index 0000000000..41fcded35e --- /dev/null +++ b/examples/react/start-trellaux/src/invariant.ts @@ -0,0 +1,5 @@ +export function invariant(value: unknown, message?: string): asserts value { + if (!value) { + throw new Error(message ?? 'Invariant failed') + } +} diff --git a/examples/react/start-trellaux/src/styles/app.css b/examples/react/start-trellaux/src/styles/app.css index 333e3db649..0120d98860 100644 --- a/examples/react/start-trellaux/src/styles/app.css +++ b/examples/react/start-trellaux/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/start-trellaux/src/utils/posts.tsx b/examples/react/start-trellaux/src/utils/posts.tsx index cf602f9827..e87764806d 100644 --- a/examples/react/start-trellaux/src/utils/posts.tsx +++ b/examples/react/start-trellaux/src/utils/posts.tsx @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) + .validator((postId: string) => postId) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const post = await axios diff --git a/examples/react/start-trellaux/tsconfig.json b/examples/react/start-trellaux/tsconfig.json index 3a9fb7cd71..cef9369516 100644 --- a/examples/react/start-trellaux/tsconfig.json +++ b/examples/react/start-trellaux/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-trellaux/vite.config.ts b/examples/react/start-trellaux/vite.config.ts index f10c86e79f..ed6799764a 100644 --- a/examples/react/start-trellaux/vite.config.ts +++ b/examples/react/start-trellaux/vite.config.ts @@ -1,17 +1,14 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteReact()], }) diff --git a/examples/react/start-workos/.devcontainer/devcontainer.json b/examples/react/start-workos/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-workos/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-workos/README.md b/examples/react/start-workos/README.md index d6e222c7ba..52dde9410a 100644 --- a/examples/react/start-workos/README.md +++ b/examples/react/start-workos/README.md @@ -30,7 +30,7 @@ You will need a [WorkOS account](https://dashboard.workos.com/signup). WORKOS_CLIENT_ID= WORKOS_API_KEY= WORKOS_COOKIE_PASSWORD= - WORKOS_REDIRECT_URI=http://localhost:3000/callback + WORKOS_REDIRECT_URI=http://localhost:3000/api/auth/callback ``` `WORKOS_COOKIE_PASSWORD` is the private key used to encrypt the session cookie. It has to be at least 32 characters long. You can use the [1Password generator](https://1password.com/password-generator/) or the `openssl` library to generate a strong password via the command line: ```bash diff --git a/examples/react/start-workos/package.json b/examples/react/start-workos/package.json index 4585d9a65c..0ab7e89c2d 100644 --- a/examples/react/start-workos/package.json +++ b/examples/react/start-workos/package.json @@ -13,22 +13,20 @@ "author": "", "license": "MIT", "dependencies": { - "@radix-ui/themes": "^3.2.1", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", - "@workos-inc/node": "^7.45.0", - "iron-session": "^8.0.4", - "jose": "^6.0.10", + "@radix-ui/themes": "^3.3.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", + "@workos/authkit-tanstack-react-start": "^0.5.0", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/react/start-workos/src/app.css b/examples/react/start-workos/src/app.css new file mode 100644 index 0000000000..e544efd1a3 --- /dev/null +++ b/examples/react/start-workos/src/app.css @@ -0,0 +1 @@ +@import '@radix-ui/themes/styles.css'; diff --git a/examples/react/start-workos/src/authkit/serverFunctions.ts b/examples/react/start-workos/src/authkit/serverFunctions.ts deleted file mode 100644 index 07d5909f8b..0000000000 --- a/examples/react/start-workos/src/authkit/serverFunctions.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { createServerFn } from '@tanstack/react-start'; -import { deleteCookie } from '@tanstack/react-start/server'; -import { getConfig } from './ssr/config'; -import { terminateSession, withAuth } from './ssr/session'; -import { getWorkOS } from './ssr/workos'; -import type { GetAuthURLOptions, NoUserInfo, UserInfo } from './ssr/interfaces'; - -export const getAuthorizationUrl = createServerFn({ method: 'GET' }) - .inputValidator((options?: GetAuthURLOptions) => options) - .handler(({ data: options = {} }) => { - const { returnPathname, screenHint, redirectUri } = options; - - return getWorkOS().userManagement.getAuthorizationUrl({ - provider: 'authkit', - clientId: getConfig('clientId'), - redirectUri: redirectUri || getConfig('redirectUri'), - state: returnPathname ? btoa(JSON.stringify({ returnPathname })) : undefined, - screenHint, - }); - }); - -export const getSignInUrl = createServerFn({ method: 'GET' }) - .inputValidator((data?: string) => data) - .handler(async ({ data: returnPathname }) => { - return await getAuthorizationUrl({ data: { returnPathname, screenHint: 'sign-in' } }); - }); - -export const getSignUpUrl = createServerFn({ method: 'GET' }) - .inputValidator((data?: string) => data) - .handler(async ({ data: returnPathname }) => { - return getAuthorizationUrl({ data: { returnPathname, screenHint: 'sign-up' } }); - }); - -export const signOut = createServerFn({ method: 'POST' }) - .inputValidator((data?: string) => data) - .handler(async ({ data: returnTo }) => { - const cookieName = getConfig('cookieName') || 'wos_session'; - deleteCookie(cookieName); - await terminateSession({ returnTo }); - }); - -export const getAuth = createServerFn({ method: 'GET' }).handler(async (): Promise => { - const auth = await withAuth(); - return auth; -}); diff --git a/examples/react/start-workos/src/authkit/ssr/config.ts b/examples/react/start-workos/src/authkit/ssr/config.ts deleted file mode 100644 index e815e54cea..0000000000 --- a/examples/react/start-workos/src/authkit/ssr/config.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { lazy } from './utils.js'; -import type { AuthKitConfig } from './interfaces.js'; - -type ValueSource = Record | ((key: string) => any); - -/** - * Default environment variable source that uses process.env - */ -const defaultSource: ValueSource = (key: string): string | undefined => { - try { - return process.env[key]; - } catch { - return undefined; - } -}; - -/** - * Configuration class for AuthKit. - * This class is used to manage configuration values and provide defaults. - * It also provides a way to get configuration values from environment variables. - * @internal - */ -export class Configuration { - private config: Partial = { - cookieName: 'wos-session', - apiHttps: true, - // Defaults to 400 days, the maximum allowed by Chrome - // It's fine to have a long cookie expiry date as the access/refresh tokens - // act as the actual time-limited aspects of the session. - cookieMaxAge: 60 * 60 * 24 * 400, - apiHostname: 'api.workos.com', - }; - - private valueSource: ValueSource = defaultSource; - - private readonly requiredKeys: Array = ['clientId', 'apiKey', 'redirectUri', 'cookiePassword']; - - /** - * Convert a camelCase string to an uppercase, underscore-separated environment variable name. - * @param str The string to convert - * @returns The environment variable name - */ - protected getEnvironmentVariableName(str: string) { - return `WORKOS_${str.replace(/([a-z])([A-Z])/g, '$1_$2').toUpperCase()}`; - } - - private updateConfig(config: Partial): void { - this.config = { ...this.config, ...config }; - } - - setValueSource(source: ValueSource): void { - this.valueSource = source; - } - - configure(configOrSource: Partial | ValueSource, source?: ValueSource): void { - if (typeof configOrSource === 'function') { - this.setValueSource(configOrSource); - } else if (typeof configOrSource === 'object' && !source) { - this.updateConfig(configOrSource); - } else if (typeof configOrSource === 'object' && source) { - this.updateConfig(configOrSource); - this.setValueSource(source); - } - - // Validate the cookiePassword if provided - if (this.config.cookiePassword && this.config.cookiePassword.length < 32) { - throw new Error('cookiePassword must be at least 32 characters long'); - } - } - - getValue(key: T): AuthKitConfig[T] { - // First check environment variables - const envKey = this.getEnvironmentVariableName(key); - let envValue: AuthKitConfig[T] | undefined = undefined; - - const { valueSource, config } = this; - if (typeof valueSource === 'function') { - envValue = valueSource(envKey); - } else { - envValue = valueSource[envKey]; - } - - // If environment variable exists, use it - if (envValue != null) { - // Convert string values to appropriate types - if (key === 'apiHttps' && typeof envValue === 'string') { - return (envValue === 'true') as AuthKitConfig[T]; - } - - if ((key === 'apiPort' || key === 'cookieMaxAge') && typeof envValue === 'string') { - const num = parseInt(envValue, 10); - return (isNaN(num) ? undefined : num) as AuthKitConfig[T]; - } - - return envValue as AuthKitConfig[T]; - } - - // Then check programmatically provided config - if (key in config && config[key] != undefined) { - return config[key] as AuthKitConfig[T]; - } - - if (this.requiredKeys.includes(key)) { - throw new Error(`Missing required configuration value for ${key} (${envKey}).`); - } - - return undefined as AuthKitConfig[T]; - } -} - -// lazy-instantiate the Configuration instance -const getConfigurationInstance = lazy(() => new Configuration()); - -/** - * Configure AuthKit with a custom value source. - * @param source The source of configuration values - * - * @example - * configure(key => Deno.env.get(key)); - */ -export function configure(source: ValueSource): void; -/** - * Configure AuthKit with custom values. - * @param config The configuration values - * - * @example - * configure({ - * clientId: 'your-client-id', - * redirectUri: 'https://your-app.com/auth/callback', - * apiKey: 'your-api-key', - * cookiePassword: 'your-cookie-password', - * }); - */ -export function configure(config: Partial): void; -/** - * Configure AuthKit with custom values and a custom value source. - * @param config The configuration values - * @param source The source of configuration values - * - * @example - * configure({ - * clientId: 'your-client-id', - * }, env); - */ -export function configure(config: Partial, source: ValueSource): void; -export function configure(configOrSource: Partial | ValueSource, source?: ValueSource): void { - const config = getConfigurationInstance(); - config.configure(configOrSource, source); -} - -/** - * Get a configuration value by key. - * This function will first check environment variables, then programmatically provided config, - * and finally fall back to defaults for optional settings. - * If a required setting is missing, an error will be thrown. - * @param key The configuration key - * @returns The configuration value - */ -export function getConfig(key: T): AuthKitConfig[T] { - const config = getConfigurationInstance(); - return config.getValue(key); -} diff --git a/examples/react/start-workos/src/authkit/ssr/interfaces.ts b/examples/react/start-workos/src/authkit/ssr/interfaces.ts deleted file mode 100644 index bd17a17d56..0000000000 --- a/examples/react/start-workos/src/authkit/ssr/interfaces.ts +++ /dev/null @@ -1,137 +0,0 @@ -import type { Impersonator, User } from '@workos-inc/node'; - -export interface GetAuthURLOptions { - redirectUri?: string; - screenHint?: 'sign-up' | 'sign-in'; - returnPathname?: string; -} - -export interface CookieOptions { - path: '/'; - httpOnly: true; - secure: boolean; - sameSite: 'lax' | 'strict' | 'none'; - maxAge: number; - domain: string | undefined; -} - -export interface UserInfo { - user: User; - sessionId: string; - organizationId?: string; - role?: string; - permissions?: Array; - entitlements?: Array; - impersonator?: Impersonator; - accessToken: string; -} -export interface NoUserInfo { - user: null; - sessionId?: undefined; - organizationId?: undefined; - role?: undefined; - permissions?: undefined; - entitlements?: undefined; - impersonator?: undefined; - accessToken?: undefined; -} - -export interface AuthkitOptions { - debug?: boolean; - redirectUri?: string; - screenHint?: 'sign-up' | 'sign-in'; -} - -export interface AuthkitResponse { - session: UserInfo | NoUserInfo; - headers: Headers; - authorizationUrl?: string; -} - -/** - * AuthKit Session - */ -export interface Session { - /** - * The session access token - */ - accessToken: string; - /** - * The session refresh token - used to refresh the access token - */ - refreshToken: string; - /** - * The logged-in user - */ - user: User; - /** - * The impersonator user, if any - */ - impersonator?: Impersonator; -} - -/** - * AuthKit Configuration Options - */ -export interface AuthKitConfig { - /** - * The WorkOS Client ID - * Equivalent to the WORKOS_CLIENT_ID environment variable - */ - clientId: string; - - /** - * The WorkOS API Key - * Equivalent to the WORKOS_API_KEY environment variable - */ - apiKey: string; - - /** - * The redirect URI for the authentication callback - * Equivalent to the WORKOS_REDIRECT_URI environment variable - */ - redirectUri: string; - - /** - * The password used to encrypt the session cookie - * Equivalent to the WORKOS_COOKIE_PASSWORD environment variable - * Must be at least 32 characters long - */ - cookiePassword: string; - - /** - * The hostname of the API to use - * Equivalent to the WORKOS_API_HOSTNAME environment variable - */ - apiHostname?: string; - - /** - * Whether to use HTTPS for API requests - * Equivalent to the WORKOS_API_HTTPS environment variable - */ - apiHttps: boolean; - - /** - * The port to use for the API - * Equivalent to the WORKOS_API_PORT environment variable - */ - apiPort?: number; - - /** - * The maximum age of the session cookie in seconds - * Equivalent to the WORKOS_COOKIE_MAX_AGE environment variable - */ - cookieMaxAge: number; - - /** - * The name of the session cookie - * Equivalent to the WORKOS_COOKIE_NAME environment variable - * Defaults to "wos-session" - */ - cookieName: string; - - /** - * The domain for the session cookie - */ - cookieDomain?: string; -} diff --git a/examples/react/start-workos/src/authkit/ssr/session.ts b/examples/react/start-workos/src/authkit/ssr/session.ts deleted file mode 100644 index 1c58b6736d..0000000000 --- a/examples/react/start-workos/src/authkit/ssr/session.ts +++ /dev/null @@ -1,268 +0,0 @@ -import { redirect } from '@tanstack/react-router'; -import { getCookie, setCookie } from '@tanstack/react-start/server'; -import { sealData, unsealData } from 'iron-session'; -import { createRemoteJWKSet, decodeJwt, jwtVerify } from 'jose'; -import { getConfig } from './config'; -import { lazy } from './utils'; -import { getWorkOS } from './workos'; -import type { AccessToken, AuthenticationResponse } from '@workos-inc/node'; -import type { AuthkitOptions, AuthkitResponse, CookieOptions, GetAuthURLOptions, Session } from './interfaces'; - -const sessionHeaderName = 'x-workos-session'; -const middlewareHeaderName = 'x-workos-middleware'; - -export function getAuthorizationUrl(options: GetAuthURLOptions = {}) { - const { returnPathname, screenHint, redirectUri } = options; - - return getWorkOS().userManagement.getAuthorizationUrl({ - provider: 'authkit', - clientId: getConfig('clientId'), - redirectUri: redirectUri || getConfig('redirectUri'), - state: returnPathname ? btoa(JSON.stringify({ returnPathname })) : undefined, - screenHint, - }); -} - -export function serializeCookie(name: string, value: string, options: Partial = {}): string { - const { - path = '/', - maxAge = getConfig('cookieMaxAge'), - secure = options.sameSite === 'none' ? true : getConfig('redirectUri').startsWith('https:'), - sameSite = 'lax', - domain = getConfig('cookieDomain'), - } = options; - - let cookie = `${name}=${encodeURIComponent(value)}; Path=${path}; sameSite=${sameSite}; HttpOnly`; - cookie += `; Max-Age=${maxAge}`; - if (!maxAge) cookie += `; Expires=${new Date(0).toUTCString()}`; - if (secure) cookie += '; Secure'; - if (domain) cookie += `; Domain=${domain}`; - - return cookie; -} - -export async function decryptSession(encryptedSession: string): Promise { - const cookiePassword = getConfig('cookiePassword'); - return unsealData(encryptedSession, { - password: cookiePassword, - }); -} - -export async function encryptSession(session: Session) { - return sealData(session, { - password: getConfig('cookiePassword'), - ttl: 0, - }); -} - -export async function withAuth() { - const session = await getSessionFromCookie(); - - if (!session?.user) { - return { user: null }; - } - - const { - sid: sessionId, - org_id: organizationId, - role, - permissions, - entitlements, - } = decodeJwt(session.accessToken); - - return { - sessionId, - user: session.user, - organizationId, - role, - permissions, - entitlements, - impersonator: session.impersonator, - accessToken: session.accessToken, - }; -} - -export async function getSessionFromCookie() { - const cookieName = getConfig('cookieName') || 'wos-session'; - const cookie = getCookie(cookieName); - - if (cookie) { - return decryptSession(cookie); - } -} - -export async function saveSession(sessionOrResponse: Session | AuthenticationResponse): Promise { - const cookieName = getConfig('cookieName') || 'wos-session'; - const encryptedSession = await encryptSession(sessionOrResponse); - setCookie(cookieName, encryptedSession); -} - -// JWKS call only happens once and the result is cached. The lazy function ensures that -// the JWK set is only created when it's needed, and not before. -const JWKS = lazy(() => createRemoteJWKSet(new URL(getWorkOS().userManagement.getJwksUrl(getConfig('clientId'))))); - -async function verifyAccessToken(accessToken: string): Promise { - try { - await jwtVerify(accessToken, JWKS()); - return true; - } catch { - return false; - } -} - -function getReturnPathname(url: string): string { - const newUrl = new URL(url); - - return `${newUrl.pathname}${newUrl.searchParams.size > 0 ? '?' + newUrl.searchParams.toString() : ''}`; -} - -export async function updateSession( - request: Request, - options: AuthkitOptions = { debug: false }, -): Promise { - const session = await getSessionFromCookie(); - - const newRequestHeaders = new Headers(); - - // Record that the request was routed through the middleware so we can check later for DX purposes - newRequestHeaders.set(middlewareHeaderName, 'true'); - - // We store the current request url in a custom header, so we can always have access to it - // This is because on hard navigations we don't have access to `next-url` but need to get the current - // `pathname` to be able to return the users where they came from before sign-in - newRequestHeaders.set('x-url', request.url); - - if (options.redirectUri) { - // Store the redirect URI in a custom header, so we always have access to it and so that subsequent - // calls to `getAuthorizationUrl` will use the same redirect URI - newRequestHeaders.set('x-redirect-uri', options.redirectUri); - } - - newRequestHeaders.delete(sessionHeaderName); - - if (!session) { - if (options.debug) { - console.log('No session found from cookie'); - } - - return { - session: { user: null }, - headers: newRequestHeaders, - authorizationUrl: getAuthorizationUrl({ - returnPathname: getReturnPathname(request.url), - redirectUri: options.redirectUri || getConfig('redirectUri'), - screenHint: options.screenHint, - }), - }; - } - - const hasValidSession = await verifyAccessToken(session.accessToken); - - const cookieName = getConfig('cookieName') || 'wos-session'; - - if (hasValidSession) { - newRequestHeaders.set(sessionHeaderName, getCookie(cookieName)!); - - const { - sid: sessionId, - org_id: organizationId, - role, - permissions, - entitlements, - } = decodeJwt(session.accessToken); - - return { - session: { - sessionId, - user: session.user, - organizationId, - role, - permissions, - entitlements, - impersonator: session.impersonator, - accessToken: session.accessToken, - }, - headers: newRequestHeaders, - }; - } - - try { - if (options.debug) { - // istanbul ignore next - console.log( - `Session invalid. ${session.accessToken ? `Refreshing access token that ends in ${session.accessToken.slice(-10)}` : 'Access token missing.'}`, - ); - } - - const { org_id: organizationIdFromAccessToken } = decodeJwt(session.accessToken); - - const { accessToken, refreshToken, user, impersonator } = - await getWorkOS().userManagement.authenticateWithRefreshToken({ - clientId: getConfig('clientId'), - refreshToken: session.refreshToken, - organizationId: organizationIdFromAccessToken, - }); - - if (options.debug) { - console.log('Session successfully refreshed'); - } - // Encrypt session with new access and refresh tokens - const encryptedSession = await encryptSession({ - accessToken, - refreshToken, - user, - impersonator, - }); - - newRequestHeaders.append('Set-Cookie', serializeCookie(cookieName, encryptedSession)); - newRequestHeaders.set(sessionHeaderName, encryptedSession); - - const { - sid: sessionId, - org_id: organizationId, - role, - permissions, - entitlements, - } = decodeJwt(accessToken); - - return { - session: { - sessionId, - user, - organizationId, - role, - permissions, - entitlements, - impersonator, - accessToken, - }, - headers: newRequestHeaders, - }; - } catch (e) { - if (options.debug) { - console.log('Failed to refresh. Deleting cookie.', e); - } - - // When we need to delete a cookie, return it as a header as you can't delete cookies from edge middleware - const deleteCookie = serializeCookie(cookieName, '', { maxAge: 0 }); - newRequestHeaders.append('Set-Cookie', deleteCookie); - - return { - session: { user: null }, - headers: newRequestHeaders, - authorizationUrl: getAuthorizationUrl({ - returnPathname: getReturnPathname(request.url), - }), - }; - } -} - -export async function terminateSession({ returnTo }: { returnTo?: string } = {}) { - const { sessionId } = await withAuth(); - if (sessionId) { - const href = getWorkOS().userManagement.getLogoutUrl({ sessionId, returnTo }); - return redirect({ href, throw: true, reloadDocument: true }); - } - - return redirect({ to: returnTo ?? '/', throw: true, reloadDocument: true }); -} diff --git a/examples/react/start-workos/src/authkit/ssr/utils.ts b/examples/react/start-workos/src/authkit/ssr/utils.ts deleted file mode 100644 index 73b807cb56..0000000000 --- a/examples/react/start-workos/src/authkit/ssr/utils.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Returns a function that can only be called once. - * Subsequent calls will return the result of the first call. - * This is useful for lazy initialization. - * @param fn - The function to be called once. - * @returns A function that can only be called once. - */ -export function lazy(fn: () => T): () => T { - let called = false; - let result: T; - return () => { - if (!called) { - result = fn(); - called = true; - } - return result; - }; -} diff --git a/examples/react/start-workos/src/authkit/ssr/workos.ts b/examples/react/start-workos/src/authkit/ssr/workos.ts deleted file mode 100644 index b310799210..0000000000 --- a/examples/react/start-workos/src/authkit/ssr/workos.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { WorkOS } from '@workos-inc/node'; -import { getConfig } from './config'; -import { lazy } from './utils'; - -/** - * Create a WorkOS instance with the provided API key and optional settings. - */ -export function createWorkOSInstance() { - // Get required API key from config - const apiKey = getConfig('apiKey'); - - // Get optional settings - const apiHostname = getConfig('apiHostname'); - const apiHttps = getConfig('apiHttps'); - const apiPort = getConfig('apiPort'); - - const options = { - apiHostname, - https: apiHttps, - port: apiPort, - }; - - // Initialize the WorkOS client with config values - const workos = new WorkOS(apiKey, options); - - return workos; -} - -/** - * Create a WorkOS instance with the provided API key and optional settings. - * This function is lazy loaded to avoid loading the WorkOS SDK when it's not needed. - */ -export const getWorkOS = lazy(createWorkOSInstance); diff --git a/examples/react/start-workos/src/components/sign-in-button.tsx b/examples/react/start-workos/src/components/sign-in-button.tsx index 93da26b40c..ba03fa02f0 100644 --- a/examples/react/start-workos/src/components/sign-in-button.tsx +++ b/examples/react/start-workos/src/components/sign-in-button.tsx @@ -1,13 +1,15 @@ import { Button, Flex } from '@radix-ui/themes'; import { Link } from '@tanstack/react-router'; -import type { User } from '@workos-inc/node'; +import type { User } from '@workos/authkit-tanstack-react-start'; export default function SignInButton({ large, user, url }: { large?: boolean; user: User | null; url: string }) { if (user) { return ( ); diff --git a/examples/react/start-workos/src/routeTree.gen.ts b/examples/react/start-workos/src/routeTree.gen.ts index 8e275a0f1b..559db280de 100644 --- a/examples/react/start-workos/src/routeTree.gen.ts +++ b/examples/react/start-workos/src/routeTree.gen.ts @@ -9,24 +9,30 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as AuthenticatedRouteImport } from './routes/_authenticated' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthenticatedRouteImport } from './routes/_authenticated' +import { Route as ClientRouteImport } from './routes/client' +import { Route as LogoutRouteImport } from './routes/logout' import { Route as AuthenticatedAccountRouteImport } from './routes/_authenticated/account' import { Route as ApiAuthCallbackRouteImport } from './routes/api/auth/callback' -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthenticatedRoute = AuthenticatedRouteImport.update({ id: '/_authenticated', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ClientRoute = ClientRouteImport.update({ + id: '/client', + path: '/client', + getParentRoute: () => rootRouteImport, +} as any) +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) const AuthenticatedAccountRoute = AuthenticatedAccountRouteImport.update({ @@ -42,12 +48,14 @@ const ApiAuthCallbackRoute = ApiAuthCallbackRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute + '/client': typeof ClientRoute '/logout': typeof LogoutRoute '/account': typeof AuthenticatedAccountRoute '/api/auth/callback': typeof ApiAuthCallbackRoute } export interface FileRoutesByTo { '/': typeof IndexRoute + '/client': typeof ClientRoute '/logout': typeof LogoutRoute '/account': typeof AuthenticatedAccountRoute '/api/auth/callback': typeof ApiAuthCallbackRoute @@ -56,19 +64,21 @@ export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute '/_authenticated': typeof AuthenticatedRouteWithChildren + '/client': typeof ClientRoute '/logout': typeof LogoutRoute '/_authenticated/account': typeof AuthenticatedAccountRoute '/api/auth/callback': typeof ApiAuthCallbackRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/logout' | '/account' | '/api/auth/callback' + fullPaths: '/' | '/client' | '/logout' | '/account' | '/api/auth/callback' fileRoutesByTo: FileRoutesByTo - to: '/' | '/logout' | '/account' | '/api/auth/callback' + to: '/' | '/client' | '/logout' | '/account' | '/api/auth/callback' id: | '__root__' | '/' | '/_authenticated' + | '/client' | '/logout' | '/_authenticated/account' | '/api/auth/callback' @@ -77,26 +87,13 @@ export interface FileRouteTypes { export interface RootRouteChildren { IndexRoute: typeof IndexRoute AuthenticatedRoute: typeof AuthenticatedRouteWithChildren + ClientRoute: typeof ClientRoute LogoutRoute: typeof LogoutRoute ApiAuthCallbackRoute: typeof ApiAuthCallbackRoute } declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport - parentRoute: typeof rootRouteImport - } - '/_authenticated': { - id: '/_authenticated' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthenticatedRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -104,6 +101,27 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/_authenticated': { + id: '/_authenticated' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthenticatedRouteImport + parentRoute: typeof rootRouteImport + } + '/client': { + id: '/client' + path: '/client' + fullPath: '/client' + preLoaderRoute: typeof ClientRouteImport + parentRoute: typeof rootRouteImport + } + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport + parentRoute: typeof rootRouteImport + } '/_authenticated/account': { id: '/_authenticated/account' path: '/account' @@ -136,6 +154,7 @@ const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren( const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, AuthenticatedRoute: AuthenticatedRouteWithChildren, + ClientRoute: ClientRoute, LogoutRoute: LogoutRoute, ApiAuthCallbackRoute: ApiAuthCallbackRoute, } @@ -144,10 +163,11 @@ export const routeTree = rootRouteImport ._addFileTypes() import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' +import type { startInstance } from './start.ts' declare module '@tanstack/react-start' { interface Register { ssr: true router: Awaited> + config: Awaited> } } diff --git a/examples/react/start-workos/src/routes/__root.tsx b/examples/react/start-workos/src/routes/__root.tsx index 8cdf0bd5bc..1f0c66c9ff 100644 --- a/examples/react/start-workos/src/routes/__root.tsx +++ b/examples/react/start-workos/src/routes/__root.tsx @@ -1,19 +1,15 @@ import { Box, Button, Card, Container, Flex, Theme } from '@radix-ui/themes'; -import '@radix-ui/themes/styles.css'; import { HeadContent, Link, Outlet, Scripts, createRootRoute } from '@tanstack/react-router'; import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'; import { Suspense } from 'react'; -import { getAuth, getSignInUrl } from '../authkit/serverFunctions'; +import { getSignInUrl } from '@workos/authkit-tanstack-react-start'; +import { AuthKitProvider, getAuthAction } from '@workos/authkit-tanstack-react-start/client'; import Footer from '../components/footer'; import SignInButton from '../components/sign-in-button'; +import appCssUrl from '../app.css?url'; import type { ReactNode } from 'react'; export const Route = createRootRoute({ - beforeLoad: async () => { - const { user } = await getAuth(); - - return { user }; - }, head: () => ({ meta: [ { @@ -27,12 +23,15 @@ export const Route = createRootRoute({ title: 'AuthKit Example in TanStack Start', }, ], + links: [{ rel: 'stylesheet', href: appCssUrl }], }), - loader: async ({ context }) => { - const { user } = context; + loader: async () => { + // getAuthAction() returns auth state without accessToken, safe for client + // Pass to AuthKitProvider as initialAuth to avoid loading flicker + const auth = await getAuthAction(); const url = await getSignInUrl(); return { - user, + auth, url, }; }, @@ -41,53 +40,59 @@ export const Route = createRootRoute({ }); function RootComponent() { - const { user, url } = Route.useLoaderData(); + const { auth, url } = Route.useLoaderData(); return ( - - - - - - - -
    - - + + + + + + + + +
    + + - - + - Loading...
    }> - - - + + + + Loading...
    }> + + + + + + +
    + +
    +
    - - -
    - -
    -
    - - - -
    - - - - + + +
    + + + + + ); } function RootDocument({ children }: Readonly<{ children: ReactNode }>) { return ( - + diff --git a/examples/react/start-workos/src/routes/_authenticated.tsx b/examples/react/start-workos/src/routes/_authenticated.tsx index 20be3d7f1b..d5de60b4fe 100644 --- a/examples/react/start-workos/src/routes/_authenticated.tsx +++ b/examples/react/start-workos/src/routes/_authenticated.tsx @@ -1,11 +1,13 @@ -import { redirect, createFileRoute } from '@tanstack/react-router'; -import { getSignInUrl } from '../authkit/serverFunctions'; +import { createFileRoute, redirect } from '@tanstack/react-router'; +import { getAuth, getSignInUrl } from '@workos/authkit-tanstack-react-start'; export const Route = createFileRoute('/_authenticated')({ - beforeLoad: async ({ context, location }) => { - if (!context.user) { + loader: async ({ location }) => { + // Loader runs on server (even during client-side navigation via RPC) + const { user } = await getAuth(); + if (!user) { const path = location.pathname; - const href = await getSignInUrl({ data: path }); + const href = await getSignInUrl({ data: { returnPathname: path } }); throw redirect({ href }); } }, diff --git a/examples/react/start-workos/src/routes/_authenticated/account.tsx b/examples/react/start-workos/src/routes/_authenticated/account.tsx index 5c8b688f92..734daf19da 100644 --- a/examples/react/start-workos/src/routes/_authenticated/account.tsx +++ b/examples/react/start-workos/src/routes/_authenticated/account.tsx @@ -1,27 +1,25 @@ import { createFileRoute } from '@tanstack/react-router'; import { Box, Flex, Heading, Text, TextField } from '@radix-ui/themes'; -import {} from '@tanstack/react-router'; -import { getAuth } from '../../authkit/serverFunctions'; +import { getAuth } from '@workos/authkit-tanstack-react-start'; export const Route = createFileRoute('/_authenticated/account')({ component: RouteComponent, - loader: async ({ context }) => { - const { user } = context; - const { role, permissions } = await getAuth(); + loader: async () => { + const auth = await getAuth(); const userFields: Array<[label: string, value: string | undefined]> = [ - ['First name', user?.firstName ?? ''], - ['Last name', user?.lastName ?? ''], - ['Email', user?.email], - ['Id', user?.id], + ['First name', auth.user?.firstName ?? ''], + ['Last name', auth.user?.lastName ?? ''], + ['Email', auth.user?.email], + ['Id', auth.user?.id], ]; - if (role) { - userFields.push(['Role', role]); + if (auth.user && 'role' in auth && auth.role) { + userFields.push(['Role', auth.role]); } - if (permissions) { - userFields.push(['Permissions', permissions.join(', ')]); + if (auth.user && 'permissions' in auth && auth.permissions) { + userFields.push(['Permissions', auth.permissions.join(', ')]); } return userFields; diff --git a/examples/react/start-workos/src/routes/api/auth/callback.tsx b/examples/react/start-workos/src/routes/api/auth/callback.tsx index 8ba493b7dc..c4cda1ed02 100644 --- a/examples/react/start-workos/src/routes/api/auth/callback.tsx +++ b/examples/react/start-workos/src/routes/api/auth/callback.tsx @@ -1,94 +1,10 @@ import { createFileRoute } from '@tanstack/react-router'; -import { getConfig } from '../../../authkit/ssr/config'; -import { saveSession } from '../../../authkit/ssr/session'; -import { getWorkOS } from '../../../authkit/ssr/workos'; +import { handleCallbackRoute } from '@workos/authkit-tanstack-react-start'; export const Route = createFileRoute('/api/auth/callback')({ server: { handlers: { - GET: async ({ request }) => { - const url = new URL(request.url); - const code = url.searchParams.get('code'); - const state = url.searchParams.get('state'); - let returnPathname = state && state !== 'null' ? JSON.parse(atob(state)).returnPathname : null; - - if (code) { - try { - // Use the code returned to us by AuthKit and authenticate the user with WorkOS - const { accessToken, refreshToken, user, impersonator } = - await getWorkOS().userManagement.authenticateWithCode({ - clientId: getConfig('clientId'), - code, - }); - - // If baseURL is provided, use it instead of request.nextUrl - // This is useful if the app is being run in a container like docker where - // the hostname can be different from the one in the request - const url = new URL(request.url); - - // Cleanup params - url.searchParams.delete('code'); - url.searchParams.delete('state'); - - // Redirect to the requested path and store the session - returnPathname = returnPathname ?? '/'; - - // Extract the search params if they are present - if (returnPathname.includes('?')) { - const newUrl = new URL(returnPathname, 'https://example.com'); - url.pathname = newUrl.pathname; - - for (const [key, value] of newUrl.searchParams) { - url.searchParams.append(key, value); - } - } else { - url.pathname = returnPathname; - } - - const response = redirectWithFallback(url.toString()); - - if (!accessToken || !refreshToken) throw new Error('response is missing tokens'); - - await saveSession({ accessToken, refreshToken, user, impersonator }); - - return response; - } catch (error) { - const errorRes = { - error: error instanceof Error ? error.message : String(error), - }; - - console.error(errorRes); - - return errorResponse(); - } - } - - return errorResponse(); - - function errorResponse() { - return errorResponseWithFallback({ - error: { - message: 'Something went wrong', - description: - "Couldn't sign in. If you are not sure what happened, please contact your organization admin.", - }, - }); - } - }, + GET: handleCallbackRoute(), }, }, }); - -function redirectWithFallback(redirectUri: string, headers?: Headers) { - const newHeaders = headers ? new Headers(headers) : new Headers(); - newHeaders.set('Location', redirectUri); - - return new Response(null, { status: 307, headers: newHeaders }); -} - -function errorResponseWithFallback(errorBody: { error: { message: string; description: string } }) { - return new Response(JSON.stringify(errorBody), { - status: 500, - headers: { 'Content-Type': 'application/json' }, - }); -} diff --git a/examples/react/start-workos/src/routes/client.tsx b/examples/react/start-workos/src/routes/client.tsx new file mode 100644 index 0000000000..9f785915c2 --- /dev/null +++ b/examples/react/start-workos/src/routes/client.tsx @@ -0,0 +1,349 @@ +import { Link, createFileRoute } from '@tanstack/react-router'; +import { Badge, Box, Button, Callout, Code, Flex, Heading, Text, TextField } from '@radix-ui/themes'; +import { useAccessToken, useAuth } from '@workos/authkit-tanstack-react-start/client'; +import { useState } from 'react'; + +export const Route = createFileRoute('/client')({ + component: RouteComponent, +}); + +function RouteComponent() { + const { + user, + loading, + sessionId, + organizationId, + role, + roles, + permissions, + entitlements, + featureFlags, + impersonator, + signOut, + switchToOrganization, + } = useAuth(); + const { accessToken, loading: tokenLoading, error: tokenError, refresh, getAccessToken } = useAccessToken(); + + const handleRefreshToken = async () => { + try { + await refresh(); + } catch (err) { + console.error('Token refresh failed:', err); + } + }; + + const handleGetFreshToken = async () => { + try { + const token = await getAccessToken(); + console.log('Fresh token:', token); + } catch (err) { + console.error('Get fresh token failed:', err); + } + }; + + const handleClientSignOut = async () => { + console.log('🧪 Testing client-side signOut() from useAuth()...'); + try { + await signOut({ returnTo: '/' }); + console.log('✅ signOut() completed'); + } catch (err) { + console.error('❌ signOut() failed:', err); + } + }; + + const [orgIdInput, setOrgIdInput] = useState(''); + const [switchOrgResult, setSwitchOrgResult] = useState(null); + + const handleSwitchOrg = async () => { + if (!orgIdInput.trim()) { + setSwitchOrgResult('Please enter an organization ID'); + return; + } + + console.log(`🔄 Switching to organization: ${orgIdInput}...`); + setSwitchOrgResult(null); + + try { + const result = await switchToOrganization(orgIdInput.trim()); + if (result && 'error' in result) { + console.error('❌ Switch failed:', result.error); + setSwitchOrgResult(`Error: ${result.error}`); + } else { + console.log('✅ Successfully switched organizations'); + setSwitchOrgResult('✅ Success! Check updated claims above.'); + } + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + console.error('❌ Switch error:', message); + setSwitchOrgResult(`Error: ${message}`); + } + }; + + if (loading) { + return ( + + Loading... + + ); + } + + if (!user) { + return ( + + + Client-Side Hooks Demo + + + This page demonstrates the client-side hooks from @workos/authkit-tanstack-start/client + + + ℹ️ Please sign in to see the client-side hooks in action. + + + ); + } + + return ( + + + + Client-Side Hooks Demo + + + Using useAuth() and useAccessToken() + + + + + + ℹ️ This page uses client-side React hooks to access authentication data. Unlike server-side loaders, these + hooks work in client components and automatically update when auth state changes. + + + + + useAuth() Hook + + + + User ID: + + + + + + Email: + + + + + + First Name: + + + + + + Last Name: + + + + + + Session ID: + + + + {organizationId && ( + + + Organization ID: + + + + )} + {role && ( + + + Role: + + + + )} + {roles && roles.length > 0 && ( + + + Roles: + + + {roles.map((r) => ( + {r} + ))} + + + )} + {permissions && permissions.length > 0 && ( + + + Permissions: + + + {permissions.map((p) => ( + + {p} + + ))} + + + )} + {entitlements && entitlements.length > 0 && ( + + + Entitlements: + + + {entitlements.map((e) => ( + + {e} + + ))} + + + )} + {featureFlags && featureFlags.length > 0 && ( + + + Feature Flags: + + + {featureFlags.map((f) => ( + + {f} + + ))} + + + )} + {impersonator && ( + + + Impersonator: + + + + )} + + + + + useAccessToken() Hook + + + + Token Status: + + + {tokenLoading ? 'Loading' : accessToken ? 'Available' : 'None'} + + + {tokenError && ( + + + Error: + + {tokenError.message} + + )} + {accessToken && ( + + + Access Token: + + + + ...{accessToken.slice(-20)} + + + + )} + + + + + + + + + Organization Management + + Switch to a different organization. Requires multi-organization setup in WorkOS. + + + + Setup required: This feature requires your WorkOS user to be a member of multiple + organizations. Create organizations in the WorkOS dashboard and add your user to them. + + + + + + Current Org: + + + {organizationId || 'None'} + + + + + Switch to Org: + + setOrgIdInput(e.target.value)} + style={{ flexGrow: 1 }} + /> + + + {switchOrgResult && ( + + {switchOrgResult} + + )} + + + + + Sign Out Methods + + Test different sign out approaches. Check the browser console for logs. + + + + + + + + Client-Side useAuth: Calls signOut() from the provider context. This tests the + redirect handling logic we just fixed. +
    + Route Loader: Uses the /logout route which calls the server function directly + in a loader. +
    +
    +
    +
    + ); +} diff --git a/examples/react/start-workos/src/routes/index.tsx b/examples/react/start-workos/src/routes/index.tsx index 6f2c64415b..c69922a124 100644 --- a/examples/react/start-workos/src/routes/index.tsx +++ b/examples/react/start-workos/src/routes/index.tsx @@ -1,12 +1,12 @@ import { Button, Flex, Heading, Text } from '@radix-ui/themes'; import { Link, createFileRoute } from '@tanstack/react-router'; -import { getSignInUrl } from '../authkit/serverFunctions'; +import { getAuth, getSignInUrl } from '@workos/authkit-tanstack-react-start'; import SignInButton from '../components/sign-in-button'; export const Route = createFileRoute('/')({ component: Home, - loader: async ({ context }) => { - const { user } = context; + loader: async () => { + const { user } = await getAuth(); const url = await getSignInUrl(); return { user, url }; }, @@ -21,7 +21,7 @@ function Home() { <> Welcome back{user?.firstName && `, ${user?.firstName}`} - You are now authenticated into the application + You are now authenticated into the TanStack Start application
    ) diff --git a/examples/react/with-trpc/src/server/server.ts b/examples/react/with-trpc/src/server/server.ts index b2b3fd2485..0a580d4963 100644 --- a/examples/react/with-trpc/src/server/server.ts +++ b/examples/react/with-trpc/src/server/server.ts @@ -50,7 +50,7 @@ export const createServer = async ( app.use(viteServer.middlewares) // Handle any requests that don't match an API route by serving the React app's index.html - app.get('*', async (req, res, next) => { + app.get('/{*splat}', async (req, res, next) => { try { let html = fs.readFileSync(path.resolve(root, 'index.html'), 'utf-8') @@ -68,7 +68,7 @@ export const createServer = async ( app.use(express.static(path.resolve(__dirname, '../client'))) // Handle any requests that don't match an API route by serving the React app's index.html - app.get('*', (req, res) => { + app.get('/{*splat}', (req, res) => { res.sendFile(path.resolve(__dirname, '../client', 'index.html')) }) } @@ -78,7 +78,8 @@ export const createServer = async ( if (!isTest) { createServer().then(({ app }) => - app.listen(PORT, () => { + app.listen(PORT, (error) => { + if (error) throw error console.info(`Server available at: http://localhost:${PORT}`) }), ) diff --git a/examples/react/with-trpc/src/styles.css b/examples/react/with-trpc/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/react/with-trpc/src/styles.css +++ b/examples/react/with-trpc/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/with-trpc/src/vite-env.d.ts b/examples/react/with-trpc/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/react/with-trpc/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/with-trpc/vite.config.ts b/examples/react/with-trpc/vite.config.ts index 6f66db1139..aa31820950 100644 --- a/examples/react/with-trpc/vite.config.ts +++ b/examples/react/with-trpc/vite.config.ts @@ -4,6 +4,7 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { tanstackRouter } from '@tanstack/router-plugin/vite' import type { BuildEnvironmentOptions } from 'vite' +import tailwindcss from '@tailwindcss/vite' const __filename = url.fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) @@ -22,7 +23,7 @@ const serverBuildConfig: BuildEnvironmentOptions = { outDir: 'dist/server', copyPublicDir: false, emptyOutDir: true, - rollupOptions: { + rolldownOptions: { input: path.resolve(__dirname, 'src/server/server.ts'), output: { entryFileNames: '[name].js', @@ -36,6 +37,7 @@ const serverBuildConfig: BuildEnvironmentOptions = { export default defineConfig((configEnv) => { return { plugins: [ + tailwindcss(), tanstackRouter({ target: 'react', autoCodeSplitting: true, diff --git a/examples/solid/authenticated-routes-firebase/.devcontainer/devcontainer.json b/examples/solid/authenticated-routes-firebase/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/authenticated-routes-firebase/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/authenticated-routes-firebase/README.md b/examples/solid/authenticated-routes-firebase/README.md index 893ae83165..65d381b34b 100644 --- a/examples/solid/authenticated-routes-firebase/README.md +++ b/examples/solid/authenticated-routes-firebase/README.md @@ -24,12 +24,14 @@ Copy the .env.example provided and configure with your firebase credentials -````VITE_FIREBASE_API_KEY= +``` +VITE_FIREBASE_API_KEY= VITE_FIREBASE_AUTH_DOMAIN= VITE_FIREBASE_PROJECT_ID= VITE_FIREBASE_STORAGE_BUCKET= VITE_FIREBASE_MESSAGING_SENDER_ID= -VITE_FIREBASE_APP_ID=``` +VITE_FIREBASE_APP_ID= +``` ## Run the app @@ -37,4 +39,3 @@ To run this example: - `npm install` or `yarn` - `npm start` or `yarn start` -```` diff --git a/examples/solid/authenticated-routes-firebase/package.json b/examples/solid/authenticated-routes-firebase/package.json index eab74fbfb6..110b4d2621 100644 --- a/examples/solid/authenticated-routes-firebase/package.json +++ b/examples/solid/authenticated-routes-firebase/package.json @@ -9,21 +9,21 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "firebase": "^11.4.0", - "postcss": "^8.5.1", - "solid-js": "^1.9.10", "redaxios": "^0.5.1", "simple-icons": "^14.9.0", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "solid-js": "^1.9.10", + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/authenticated-routes-firebase/postcss.config.mjs b/examples/solid/authenticated-routes-firebase/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/authenticated-routes-firebase/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/authenticated-routes-firebase/src/auth.tsx b/examples/solid/authenticated-routes-firebase/src/auth.tsx index 84f1df8c99..97337889b7 100644 --- a/examples/solid/authenticated-routes-firebase/src/auth.tsx +++ b/examples/solid/authenticated-routes-firebase/src/auth.tsx @@ -1,7 +1,6 @@ import * as Solid from 'solid-js' import { onAuthStateChanged, signInWithPopup, signOut } from 'firebase/auth' -import { flushSync } from 'react-dom' import { auth } from './firebase/config' import type { AuthProvider, User } from 'firebase/auth' @@ -22,7 +21,7 @@ export function AuthContextProvider(props: { children: Solid.JSX.Element }) { Solid.createEffect(() => { const unsubscribe = onAuthStateChanged(auth, (user) => { - flushSync(() => { + Solid.batch(() => { setUser(user) setIsInitialLoading(false) }) @@ -39,7 +38,7 @@ export function AuthContextProvider(props: { children: Solid.JSX.Element }) { const login = async (provider: AuthProvider) => { const result = await signInWithPopup(auth, provider) - flushSync(() => { + Solid.batch(() => { setUser(result.user) setIsInitialLoading(false) }) diff --git a/examples/solid/authenticated-routes-firebase/src/routeTree.gen.ts b/examples/solid/authenticated-routes-firebase/src/routeTree.gen.ts index 873a64002d..4b98258aea 100644 --- a/examples/solid/authenticated-routes-firebase/src/routeTree.gen.ts +++ b/examples/solid/authenticated-routes-firebase/src/routeTree.gen.ts @@ -9,38 +9,38 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthRouteImport } from './routes/_auth' import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as LoginRouteImport } from './routes/login' import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' +import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => AuthRoute, -} as any) const AuthDashboardRoute = AuthDashboardRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => AuthRoute, } as any) +const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,20 +107,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/_auth': { - id: '/_auth' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -128,12 +114,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/_auth/invoices': { - id: '/_auth/invoices' - path: '/invoices' - fullPath: '/invoices' - preLoaderRoute: typeof AuthInvoicesRouteImport - parentRoute: typeof AuthRoute + '/_auth': { + id: '/_auth' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthRouteImport + parentRoute: typeof rootRouteImport + } + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport } '/_auth/dashboard': { id: '/_auth/dashboard' @@ -142,6 +135,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthDashboardRouteImport parentRoute: typeof AuthRoute } + '/_auth/invoices': { + id: '/_auth/invoices' + path: '/invoices' + fullPath: '/invoices' + preLoaderRoute: typeof AuthInvoicesRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/solid/authenticated-routes-firebase/src/styles.css b/examples/solid/authenticated-routes-firebase/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/authenticated-routes-firebase/src/styles.css +++ b/examples/solid/authenticated-routes-firebase/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/authenticated-routes-firebase/vite.config.js b/examples/solid/authenticated-routes-firebase/vite.config.js index 74e9ca3db3..79454008ba 100644 --- a/examples/solid/authenticated-routes-firebase/vite.config.js +++ b/examples/solid/authenticated-routes-firebase/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'solid', autoCodeSplitting: true, diff --git a/examples/solid/authenticated-routes/.devcontainer/devcontainer.json b/examples/solid/authenticated-routes/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/authenticated-routes/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/authenticated-routes/package.json b/examples/solid/authenticated-routes/package.json index eafd424254..ea7d05c902 100644 --- a/examples/solid/authenticated-routes/package.json +++ b/examples/solid/authenticated-routes/package.json @@ -9,19 +9,19 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "postcss": "^8.5.1", - "solid-js": "^1.9.10", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "solid-js": "^1.9.10", + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/authenticated-routes/postcss.config.mjs b/examples/solid/authenticated-routes/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/authenticated-routes/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/authenticated-routes/src/routeTree.gen.ts b/examples/solid/authenticated-routes/src/routeTree.gen.ts index 873a64002d..4b98258aea 100644 --- a/examples/solid/authenticated-routes/src/routeTree.gen.ts +++ b/examples/solid/authenticated-routes/src/routeTree.gen.ts @@ -9,38 +9,38 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthRouteImport } from './routes/_auth' import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as LoginRouteImport } from './routes/login' import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' +import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => AuthRoute, -} as any) const AuthDashboardRoute = AuthDashboardRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => AuthRoute, } as any) +const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,20 +107,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/_auth': { - id: '/_auth' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -128,12 +114,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/_auth/invoices': { - id: '/_auth/invoices' - path: '/invoices' - fullPath: '/invoices' - preLoaderRoute: typeof AuthInvoicesRouteImport - parentRoute: typeof AuthRoute + '/_auth': { + id: '/_auth' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthRouteImport + parentRoute: typeof rootRouteImport + } + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport } '/_auth/dashboard': { id: '/_auth/dashboard' @@ -142,6 +135,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthDashboardRouteImport parentRoute: typeof AuthRoute } + '/_auth/invoices': { + id: '/_auth/invoices' + path: '/invoices' + fullPath: '/invoices' + preLoaderRoute: typeof AuthInvoicesRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/solid/authenticated-routes/src/styles.css b/examples/solid/authenticated-routes/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/authenticated-routes/src/styles.css +++ b/examples/solid/authenticated-routes/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/authenticated-routes/src/vite-env.d.ts b/examples/solid/authenticated-routes/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/authenticated-routes/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/authenticated-routes/vite.config.js b/examples/solid/authenticated-routes/vite.config.js index 74e9ca3db3..79454008ba 100644 --- a/examples/solid/authenticated-routes/vite.config.js +++ b/examples/solid/authenticated-routes/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'solid', autoCodeSplitting: true, diff --git a/examples/solid/basic-default-search-params/.devcontainer/devcontainer.json b/examples/solid/basic-default-search-params/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/basic-default-search-params/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/basic-default-search-params/package.json b/examples/solid/basic-default-search-params/package.json index 78d4e62e86..830df7b9cf 100644 --- a/examples/solid/basic-default-search-params/package.json +++ b/examples/solid/basic-default-search-params/package.json @@ -9,19 +9,19 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", - "solid-js": "^1.9.10", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "solid-js": "^1.9.10", + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/basic-default-search-params/postcss.config.mjs b/examples/solid/basic-default-search-params/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/basic-default-search-params/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/basic-default-search-params/src/styles.css b/examples/solid/basic-default-search-params/src/styles.css index a43da4d776..c346d61a12 100644 --- a/examples/solid/basic-default-search-params/src/styles.css +++ b/examples/solid/basic-default-search-params/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/basic-default-search-params/src/vite-env.d.ts b/examples/solid/basic-default-search-params/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/basic-default-search-params/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/basic-default-search-params/vite.config.js b/examples/solid/basic-default-search-params/vite.config.js index 05041cc6d8..fb5faf9236 100644 --- a/examples/solid/basic-default-search-params/vite.config.js +++ b/examples/solid/basic-default-search-params/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [solid()], + plugins: [tailwindcss(), solid()], }) diff --git a/examples/solid/basic-devtools-panel/.devcontainer/devcontainer.json b/examples/solid/basic-devtools-panel/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/basic-devtools-panel/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/basic-devtools-panel/package.json b/examples/solid/basic-devtools-panel/package.json index c6f06d0871..e7d608f5fe 100644 --- a/examples/solid/basic-devtools-panel/package.json +++ b/examples/solid/basic-devtools-panel/package.json @@ -9,17 +9,17 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/basic-devtools-panel/postcss.config.mjs b/examples/solid/basic-devtools-panel/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/basic-devtools-panel/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/basic-devtools-panel/src/styles.css b/examples/solid/basic-devtools-panel/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/basic-devtools-panel/src/styles.css +++ b/examples/solid/basic-devtools-panel/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/basic-devtools-panel/vite.config.js b/examples/solid/basic-devtools-panel/vite.config.js index 05041cc6d8..fb5faf9236 100644 --- a/examples/solid/basic-devtools-panel/vite.config.js +++ b/examples/solid/basic-devtools-panel/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [solid()], + plugins: [tailwindcss(), solid()], }) diff --git a/examples/solid/basic-file-based/.devcontainer/devcontainer.json b/examples/solid/basic-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/basic-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/basic-file-based/package.json b/examples/solid/basic-file-based/package.json index d9a1205af4..867118382e 100644 --- a/examples/solid/basic-file-based/package.json +++ b/examples/solid/basic-file-based/package.json @@ -9,19 +9,19 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.142.0", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10" + "@tanstack/router-plugin": "^1.169.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/basic-file-based/postcss.config.mjs b/examples/solid/basic-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/basic-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/basic-file-based/src/routeTree.gen.ts b/examples/solid/basic-file-based/src/routeTree.gen.ts index 0f36f9678e..5942acc907 100644 --- a/examples/solid/basic-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-file-based/src/routeTree.gen.ts @@ -9,29 +9,34 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,10 +47,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -53,12 +59,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,6 +117,20 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -124,19 +138,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout': { - id: '/_pathlessLayout' + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/posts/': { id: '/posts/' @@ -152,12 +159,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -166,13 +173,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/examples/solid/basic-file-based/src/styles.css b/examples/solid/basic-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/basic-file-based/src/styles.css +++ b/examples/solid/basic-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/basic-file-based/src/vite-env.d.ts b/examples/solid/basic-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/basic-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/basic-file-based/vite.config.js b/examples/solid/basic-file-based/vite.config.js index 74e9ca3db3..79454008ba 100644 --- a/examples/solid/basic-file-based/vite.config.js +++ b/examples/solid/basic-file-based/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'solid', autoCodeSplitting: true, diff --git a/examples/solid/basic-non-nested-devtools/.devcontainer/devcontainer.json b/examples/solid/basic-non-nested-devtools/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/basic-non-nested-devtools/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/basic-non-nested-devtools/package.json b/examples/solid/basic-non-nested-devtools/package.json index ccc4d3582b..c8e00ee43e 100644 --- a/examples/solid/basic-non-nested-devtools/package.json +++ b/examples/solid/basic-non-nested-devtools/package.json @@ -9,19 +9,19 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/basic-non-nested-devtools/postcss.config.mjs b/examples/solid/basic-non-nested-devtools/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/basic-non-nested-devtools/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/basic-non-nested-devtools/src/styles.css b/examples/solid/basic-non-nested-devtools/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/basic-non-nested-devtools/src/styles.css +++ b/examples/solid/basic-non-nested-devtools/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/basic-non-nested-devtools/src/vite-env.d.ts b/examples/solid/basic-non-nested-devtools/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/basic-non-nested-devtools/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/basic-non-nested-devtools/vite.config.js b/examples/solid/basic-non-nested-devtools/vite.config.js index 05041cc6d8..fb5faf9236 100644 --- a/examples/solid/basic-non-nested-devtools/vite.config.js +++ b/examples/solid/basic-non-nested-devtools/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [solid()], + plugins: [tailwindcss(), solid()], }) diff --git a/examples/solid/basic-solid-query-file-based/.devcontainer/devcontainer.json b/examples/solid/basic-solid-query-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/basic-solid-query-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/basic-solid-query-file-based/package.json b/examples/solid/basic-solid-query-file-based/package.json index bfa2050afc..fdb5f05f52 100644 --- a/examples/solid/basic-solid-query-file-based/package.json +++ b/examples/solid/basic-solid-query-file-based/package.json @@ -10,21 +10,21 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.142.0", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10" + "@tanstack/router-plugin": "^1.169.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/basic-solid-query-file-based/postcss.config.mjs b/examples/solid/basic-solid-query-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/basic-solid-query-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/basic-solid-query-file-based/src/routeTree.gen.ts b/examples/solid/basic-solid-query-file-based/src/routeTree.gen.ts index 0f36f9678e..5942acc907 100644 --- a/examples/solid/basic-solid-query-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-solid-query-file-based/src/routeTree.gen.ts @@ -9,29 +9,34 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,10 +47,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -53,12 +59,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,6 +117,20 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -124,19 +138,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout': { - id: '/_pathlessLayout' + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/posts/': { id: '/posts/' @@ -152,12 +159,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -166,13 +173,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/examples/solid/basic-solid-query-file-based/src/styles.css b/examples/solid/basic-solid-query-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/basic-solid-query-file-based/src/styles.css +++ b/examples/solid/basic-solid-query-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/basic-solid-query-file-based/src/vite-env.d.ts b/examples/solid/basic-solid-query-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/basic-solid-query-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/basic-solid-query-file-based/vite.config.js b/examples/solid/basic-solid-query-file-based/vite.config.js index 1660a56c17..95863b470a 100644 --- a/examples/solid/basic-solid-query-file-based/vite.config.js +++ b/examples/solid/basic-solid-query-file-based/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'solid', autoCodeSplitting: true }), solid(), ], diff --git a/examples/solid/basic-solid-query/.devcontainer/devcontainer.json b/examples/solid/basic-solid-query/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/basic-solid-query/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/basic-solid-query/package.json b/examples/solid/basic-solid-query/package.json index bbdd4493f3..7b132b11a1 100644 --- a/examples/solid/basic-solid-query/package.json +++ b/examples/solid/basic-solid-query/package.json @@ -9,20 +9,20 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.142.0", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10" + "@tanstack/router-plugin": "^1.169.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/basic-solid-query/postcss.config.mjs b/examples/solid/basic-solid-query/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/basic-solid-query/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/basic-solid-query/src/styles.css b/examples/solid/basic-solid-query/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/basic-solid-query/src/styles.css +++ b/examples/solid/basic-solid-query/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/basic-solid-query/src/vite-env.d.ts b/examples/solid/basic-solid-query/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/basic-solid-query/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/basic-solid-query/vite.config.js b/examples/solid/basic-solid-query/vite.config.js index 05041cc6d8..fb5faf9236 100644 --- a/examples/solid/basic-solid-query/vite.config.js +++ b/examples/solid/basic-solid-query/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [solid()], + plugins: [tailwindcss(), solid()], }) diff --git a/examples/solid/basic-ssr-file-based/.devcontainer/devcontainer.json b/examples/solid/basic-ssr-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/basic-ssr-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/basic-ssr-file-based/package.json b/examples/solid/basic-ssr-file-based/package.json index 37e4edd889..e3699970a9 100644 --- a/examples/solid/basic-ssr-file-based/package.json +++ b/examples/solid/basic-ssr-file-based/package.json @@ -11,19 +11,20 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/solid-router": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "compression": "^1.8.0", - "express": "^4.21.2", + "express": "^5.2.1", "get-port": "^7.1.0", "node-fetch": "^3.3.2", "solid-js": "^1.9.10" }, "devDependencies": { - "@tanstack/solid-router-devtools": "^1.141.8", - "@types/express": "^4.17.23", - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.8.3", - "vite": "^7.1.7" + "@tanstack/solid-router-devtools": "^1.167.3", + "@types/express": "^5.0.6", + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/solid/basic-ssr-file-based/server.js b/examples/solid/basic-ssr-file-based/server.js index 5686edc048..6d060a19f0 100644 --- a/examples/solid/basic-ssr-file-based/server.js +++ b/examples/solid/basic-ssr-file-based/server.js @@ -51,7 +51,7 @@ export async function createServer( if (isProd) app.use(express.static('./dist/client')) - app.use('*', async (req, res) => { + app.use('/{*splat}', async (req, res) => { try { const url = req.originalUrl @@ -97,7 +97,8 @@ export async function createServer( if (!isTest) { createServer().then(async ({ app }) => - app.listen(await getPort({ port: portNumbers(3000, 3100) }), () => { + app.listen(await getPort({ port: portNumbers(3000, 3100) }), (error) => { + if (error) throw error console.info('Client Server: http://localhost:3000') }), ) diff --git a/examples/solid/basic-ssr-file-based/src/routeTree.gen.ts b/examples/solid/basic-ssr-file-based/src/routeTree.gen.ts index 26eb09e67f..fc6a3e4377 100644 --- a/examples/solid/basic-ssr-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-ssr-file-based/src/routeTree.gen.ts @@ -9,12 +9,17 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' import { Route as ErrorRouteImport } from './routes/error' import { Route as PostsRouteRouteImport } from './routes/posts/route' -import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts/index' import { Route as PostsPostIdRouteImport } from './routes/posts/$postId' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const ErrorRoute = ErrorRouteImport.update({ id: '/error', path: '/error', @@ -25,11 +30,6 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -78,6 +78,13 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/error': { id: '/error' path: '/error' @@ -92,13 +99,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/solid/basic-ssr-file-based/vite.config.ts b/examples/solid/basic-ssr-file-based/vite.config.ts index 295a49b1c1..1d86df82a1 100644 --- a/examples/solid/basic-ssr-file-based/vite.config.ts +++ b/examples/solid/basic-ssr-file-based/vite.config.ts @@ -15,7 +15,7 @@ const ssrBuildConfig: BuildEnvironmentOptions = { ssrEmitAssets: true, copyPublicDir: false, emptyOutDir: true, - rollupOptions: { + rolldownOptions: { input: path.resolve(__dirname, 'src/entry-server.tsx'), output: { entryFileNames: '[name].js', @@ -31,7 +31,7 @@ const clientBuildConfig: BuildEnvironmentOptions = { emitAssets: true, copyPublicDir: true, emptyOutDir: true, - rollupOptions: { + rolldownOptions: { input: path.resolve(__dirname, 'src/entry-client.tsx'), output: { entryFileNames: 'static/[name].js', diff --git a/examples/solid/basic-ssr-streaming-file-based/.devcontainer/devcontainer.json b/examples/solid/basic-ssr-streaming-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/basic-ssr-streaming-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/basic-ssr-streaming-file-based/package.json b/examples/solid/basic-ssr-streaming-file-based/package.json index 8b82bf2fcd..92367442fc 100644 --- a/examples/solid/basic-ssr-streaming-file-based/package.json +++ b/examples/solid/basic-ssr-streaming-file-based/package.json @@ -11,24 +11,24 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "compression": "^1.8.0", - "express": "^4.21.2", + "express": "^5.2.1", "get-port": "^7.1.0", "node-fetch": "^3.3.2", - "postcss": "^8.5.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.142.0", - "@types/express": "^4.17.23", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10" + "@tanstack/router-plugin": "^1.169.0", + "@types/express": "^5.0.6", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/basic-ssr-streaming-file-based/postcss.config.mjs b/examples/solid/basic-ssr-streaming-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/basic-ssr-streaming-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/basic-ssr-streaming-file-based/server.js b/examples/solid/basic-ssr-streaming-file-based/server.js index 1fb56e8ef7..4369c0028b 100644 --- a/examples/solid/basic-ssr-streaming-file-based/server.js +++ b/examples/solid/basic-ssr-streaming-file-based/server.js @@ -51,7 +51,7 @@ export async function createServer( if (isProd) app.use(express.static('./dist/client')) - app.use('*', async (req, res) => { + app.use('/{*splat}', async (req, res) => { try { const url = req.originalUrl @@ -97,7 +97,8 @@ export async function createServer( if (!isTest) { createServer().then(async ({ app }) => - app.listen(await getPort({ port: portNumbers(3000, 3100) }), () => { + app.listen(await getPort({ port: portNumbers(3000, 3100) }), (error) => { + if (error) throw error console.info('Client Server: http://localhost:3000') }), ) diff --git a/examples/solid/basic-ssr-streaming-file-based/src/routeTree.gen.ts b/examples/solid/basic-ssr-streaming-file-based/src/routeTree.gen.ts index be45381f48..0161f550f0 100644 --- a/examples/solid/basic-ssr-streaming-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-ssr-streaming-file-based/src/routeTree.gen.ts @@ -9,19 +9,23 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as CounterRouteImport } from './routes/counter' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CounterRouteImport } from './routes/counter' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const CounterRoute = CounterRouteImport.update({ @@ -29,15 +33,16 @@ const CounterRoute = CounterRouteImport.update({ path: '/counter', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -48,10 +53,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,12 +65,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -129,11 +129,18 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } '/counter': { @@ -143,19 +150,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof CounterRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/posts/': { id: '/posts/' @@ -171,12 +178,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -185,13 +192,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/examples/solid/basic-ssr-streaming-file-based/src/styles.css b/examples/solid/basic-ssr-streaming-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/basic-ssr-streaming-file-based/src/styles.css +++ b/examples/solid/basic-ssr-streaming-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/basic-ssr-streaming-file-based/src/vite-env.d.ts b/examples/solid/basic-ssr-streaming-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/basic-ssr-streaming-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/basic-ssr-streaming-file-based/vite.config.js b/examples/solid/basic-ssr-streaming-file-based/vite.config.js index b87f24abdd..03bd2116e4 100644 --- a/examples/solid/basic-ssr-streaming-file-based/vite.config.js +++ b/examples/solid/basic-ssr-streaming-file-based/vite.config.js @@ -3,6 +3,7 @@ import path from 'node:path' import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' const __filename = url.fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) @@ -14,7 +15,7 @@ const ssrBuildConfig = { ssrEmitAssets: true, copyPublicDir: false, emptyOutDir: true, - rollupOptions: { + rolldownOptions: { input: path.resolve(__dirname, 'src/entry-server.tsx'), output: { entryFileNames: 'static/[name].js', @@ -30,7 +31,7 @@ const clientBuildConfig = { emitAssets: true, copyPublicDir: true, emptyOutDir: true, - rollupOptions: { + rolldownOptions: { input: path.resolve(__dirname, 'src/entry-client.tsx'), output: { entryFileNames: 'static/[name].js', @@ -44,6 +45,7 @@ const clientBuildConfig = { export default defineConfig((configEnv) => { return { plugins: [ + tailwindcss(), tanstackRouter({ target: 'solid', autoCodeSplitting: true }), solid({ ssr: true }), ], diff --git a/examples/solid/basic-virtual-file-based/.devcontainer/devcontainer.json b/examples/solid/basic-virtual-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/basic-virtual-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/basic-virtual-file-based/package.json b/examples/solid/basic-virtual-file-based/package.json index 077ad4c29b..801b452192 100644 --- a/examples/solid/basic-virtual-file-based/package.json +++ b/examples/solid/basic-virtual-file-based/package.json @@ -9,20 +9,20 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "@tanstack/virtual-file-routes": "^1.141.0", - "postcss": "^8.5.1", - "solid-js": "^1.9.10", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/virtual-file-routes": "^1.162.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "solid-js": "^1.9.10", + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/basic-virtual-file-based/postcss.config.mjs b/examples/solid/basic-virtual-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/basic-virtual-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/basic-virtual-file-based/src/routeTree.gen.ts b/examples/solid/basic-virtual-file-based/src/routeTree.gen.ts index b4e2b0d54e..c41eda86bf 100644 --- a/examples/solid/basic-virtual-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-virtual-file-based/src/routeTree.gen.ts @@ -8,80 +8,78 @@ // You should NOT make any changes in this file as it will be overwritten. // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. -import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/solid-router' - import { Route as rootRouteImport } from './routes/root' -import { Route as postsPostsRouteImport } from './routes/posts/posts' -import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' import { Route as homeRouteImport } from './routes/home' -import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' +import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' +import { Route as postsPostsRouteImport } from './routes/posts/posts' import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' -import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' +import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' -import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' -import { Route as bRouteImport } from './routes/b' +import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' import { Route as aRouteImport } from './routes/a' +import { Route as bRouteImport } from './routes/b' -const postsPostsRoute = postsPostsRouteImport.update({ - id: '/posts', - path: '/posts', +const homeRoute = homeRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', +const postsPostsRoute = postsPostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => postsPostsRoute, -} as any) const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ id: '/_second-layout', getParentRoute: () => layoutFirstLayoutRoute, } as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => postsPostsRoute, -} as any) const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ id: '/classic/hello', path: '/classic/hello', getParentRoute: () => rootRouteImport, } as any) +const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => postsPostsRoute, +} as any) +const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => postsPostsRoute, +} as any) const ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ - id: '/world', - path: '/world', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ id: '/universe', path: '/universe', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const bRoute = bRouteImport.update({ - id: '/route-without-file/layout-b', - path: '/route-without-file/layout-b', - getParentRoute: () => layoutSecondLayoutRoute, +const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ + id: '/world', + path: '/world', + getParentRoute: () => ClassicHelloRouteRoute, } as any) const aRoute = aRouteImport.update({ id: '/route-without-file/layout-a', path: '/route-without-file/layout-a', getParentRoute: () => layoutSecondLayoutRoute, } as any) +const bRoute = bRouteImport.update({ + id: '/route-without-file/layout-b', + path: '/route-without-file/layout-b', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof homeRoute @@ -168,20 +166,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof postsPostsRouteImport - parentRoute: typeof rootRouteImport - } - '/_first': { - id: '/_first' - path: '' - fullPath: '' - preLoaderRoute: typeof layoutFirstLayoutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -189,27 +173,27 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof homeRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof postsPostsDetailRouteImport - parentRoute: typeof postsPostsRoute + '/_first': { + id: '/_first' + path: '' + fullPath: '/' + preLoaderRoute: typeof layoutFirstLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof postsPostsRouteImport + parentRoute: typeof rootRouteImport } '/_first/_second-layout': { id: '/_first/_second-layout' path: '' - fullPath: '' + fullPath: '/' preLoaderRoute: typeof layoutSecondLayoutRouteImport parentRoute: typeof layoutFirstLayoutRoute } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute - } '/classic/hello': { id: '/classic/hello' path: '/classic/hello' @@ -217,6 +201,20 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ClassicHelloRouteRouteImport parentRoute: typeof rootRouteImport } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof postsPostsHomeRouteImport + parentRoute: typeof postsPostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof postsPostsDetailRouteImport + parentRoute: typeof postsPostsRoute + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -224,13 +222,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/world': { - id: '/classic/hello/world' - path: '/world' - fullPath: '/classic/hello/world' - preLoaderRoute: typeof ClassicHelloWorldRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/universe': { id: '/classic/hello/universe' path: '/universe' @@ -238,12 +229,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ClassicHelloUniverseRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second-layout/route-without-file/layout-b': { - id: '/_first/_second-layout/route-without-file/layout-b' - path: '/route-without-file/layout-b' - fullPath: '/route-without-file/layout-b' - preLoaderRoute: typeof bRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/world': { + id: '/classic/hello/world' + path: '/world' + fullPath: '/classic/hello/world' + preLoaderRoute: typeof ClassicHelloWorldRouteImport + parentRoute: typeof ClassicHelloRouteRoute } '/_first/_second-layout/route-without-file/layout-a': { id: '/_first/_second-layout/route-without-file/layout-a' @@ -252,118 +243,16 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof aRouteImport parentRoute: typeof layoutSecondLayoutRoute } + '/_first/_second-layout/route-without-file/layout-b': { + id: '/_first/_second-layout/route-without-file/layout-b' + path: '/route-without-file/layout-b' + fullPath: '/route-without-file/layout-b' + preLoaderRoute: typeof bRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } } } -declare module './routes/home' { - const createFileRoute: CreateFileRoute< - '/', - FileRoutesByPath['/']['parentRoute'], - FileRoutesByPath['/']['id'], - FileRoutesByPath['/']['path'], - FileRoutesByPath['/']['fullPath'] - > -} -declare module './routes/layout/first-layout' { - const createFileRoute: CreateFileRoute< - '/_first', - FileRoutesByPath['/_first']['parentRoute'], - FileRoutesByPath['/_first']['id'], - FileRoutesByPath['/_first']['path'], - FileRoutesByPath['/_first']['fullPath'] - > -} -declare module './routes/posts/posts' { - const createFileRoute: CreateFileRoute< - '/posts', - FileRoutesByPath['/posts']['parentRoute'], - FileRoutesByPath['/posts']['id'], - FileRoutesByPath['/posts']['path'], - FileRoutesByPath['/posts']['fullPath'] - > -} -declare module './routes/file-based-subtree/hello/route' { - const createFileRoute: CreateFileRoute< - '/classic/hello', - FileRoutesByPath['/classic/hello']['parentRoute'], - FileRoutesByPath['/classic/hello']['id'], - FileRoutesByPath['/classic/hello']['path'], - FileRoutesByPath['/classic/hello']['fullPath'] - > -} -declare module './routes/posts/posts-home' { - const createFileRoute: CreateFileRoute< - '/posts/', - FileRoutesByPath['/posts/']['parentRoute'], - FileRoutesByPath['/posts/']['id'], - FileRoutesByPath['/posts/']['path'], - FileRoutesByPath['/posts/']['fullPath'] - > -} -declare module './routes/layout/second-layout' { - const createFileRoute: CreateFileRoute< - '/_first/_second-layout', - FileRoutesByPath['/_first/_second-layout']['parentRoute'], - FileRoutesByPath['/_first/_second-layout']['id'], - FileRoutesByPath['/_first/_second-layout']['path'], - FileRoutesByPath['/_first/_second-layout']['fullPath'] - > -} -declare module './routes/posts/posts-detail' { - const createFileRoute: CreateFileRoute< - '/posts/$postId', - FileRoutesByPath['/posts/$postId']['parentRoute'], - FileRoutesByPath['/posts/$postId']['id'], - FileRoutesByPath['/posts/$postId']['path'], - FileRoutesByPath['/posts/$postId']['fullPath'] - > -} -declare module './routes/file-based-subtree/hello/universe' { - const createFileRoute: CreateFileRoute< - '/classic/hello/universe', - FileRoutesByPath['/classic/hello/universe']['parentRoute'], - FileRoutesByPath['/classic/hello/universe']['id'], - FileRoutesByPath['/classic/hello/universe']['path'], - FileRoutesByPath['/classic/hello/universe']['fullPath'] - > -} -declare module './routes/file-based-subtree/hello/world' { - const createFileRoute: CreateFileRoute< - '/classic/hello/world', - FileRoutesByPath['/classic/hello/world']['parentRoute'], - FileRoutesByPath['/classic/hello/world']['id'], - FileRoutesByPath['/classic/hello/world']['path'], - FileRoutesByPath['/classic/hello/world']['fullPath'] - > -} -declare module './routes/file-based-subtree/hello/index' { - const createFileRoute: CreateFileRoute< - '/classic/hello/', - FileRoutesByPath['/classic/hello/']['parentRoute'], - FileRoutesByPath['/classic/hello/']['id'], - FileRoutesByPath['/classic/hello/']['path'], - FileRoutesByPath['/classic/hello/']['fullPath'] - > -} -declare module './routes/a' { - const createFileRoute: CreateFileRoute< - '/_first/_second-layout/route-without-file/layout-a', - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-a']['parentRoute'], - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-a']['id'], - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-a']['path'], - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-a']['fullPath'] - > -} -declare module './routes/b' { - const createFileRoute: CreateFileRoute< - '/_first/_second-layout/route-without-file/layout-b', - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-b']['parentRoute'], - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-b']['id'], - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-b']['path'], - FileRoutesByPath['/_first/_second-layout/route-without-file/layout-b']['fullPath'] - > -} - interface layoutSecondLayoutRouteChildren { aRoute: typeof aRoute bRoute: typeof bRoute diff --git a/examples/solid/basic-virtual-file-based/src/routes/a.tsx b/examples/solid/basic-virtual-file-based/src/routes/a.tsx index a190b24202..5b02ca6dcd 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/a.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/a.tsx @@ -1,4 +1,7 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute( + '/_first/_second-layout/route-without-file/layout-a', +)({ component: LayoutAComponent, }) diff --git a/examples/solid/basic-virtual-file-based/src/routes/b.tsx b/examples/solid/basic-virtual-file-based/src/routes/b.tsx index 505f8f6fbf..014f13c1cc 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/b.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/b.tsx @@ -1,4 +1,7 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute( + '/_first/_second-layout/route-without-file/layout-b', +)({ component: LayoutBComponent, }) diff --git a/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx b/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx index f86335e291..6cc8bb1a6f 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/index.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute('/classic/hello/')({ component: () =>
    This is the index
    , }) diff --git a/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx b/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx index 5b95eea555..f4f30d8425 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/route.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet } from '@tanstack/solid-router' +import { Link, Outlet, createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/classic/hello')({ component: () => (
    Hello! diff --git a/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx b/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx index 20b07c41cc..f250de10c1 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/universe.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute('/classic/hello/universe')({ component: () =>
    Hello /classic/hello/universe!
    , }) diff --git a/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx b/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx index 4af11357a2..d207a49114 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/file-based-subtree/hello/world.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute('/classic/hello/world')({ component: () =>
    Hello /classic/hello/world!
    , }) diff --git a/examples/solid/basic-virtual-file-based/src/routes/home.tsx b/examples/solid/basic-virtual-file-based/src/routes/home.tsx index 510db79b73..3f905db60c 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/home.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/home.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute('/')({ component: Home, }) diff --git a/examples/solid/basic-virtual-file-based/src/routes/layout/first-layout.tsx b/examples/solid/basic-virtual-file-based/src/routes/layout/first-layout.tsx index c549175638..5c77421bb2 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/layout/first-layout.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/layout/first-layout.tsx @@ -1,6 +1,6 @@ -import { Outlet } from '@tanstack/solid-router' +import { Outlet, createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_first')({ component: LayoutComponent, }) diff --git a/examples/solid/basic-virtual-file-based/src/routes/layout/second-layout.tsx b/examples/solid/basic-virtual-file-based/src/routes/layout/second-layout.tsx index b2f544c540..245a25bafc 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/layout/second-layout.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/layout/second-layout.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet } from '@tanstack/solid-router' +import { Link, Outlet, createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_first/_second-layout')({ component: LayoutComponent, }) diff --git a/examples/solid/basic-virtual-file-based/src/routes/posts/posts-detail.tsx b/examples/solid/basic-virtual-file-based/src/routes/posts/posts-detail.tsx index ef413c1be0..990f473ae8 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/posts/posts-detail.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/posts/posts-detail.tsx @@ -1,4 +1,4 @@ -import { ErrorComponent } from '@tanstack/solid-router' +import { ErrorComponent, createFileRoute } from '@tanstack/solid-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/solid-router' @@ -6,7 +6,7 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } -export const Route = createFileRoute({ +export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent as any, notFoundComponent: () => { diff --git a/examples/solid/basic-virtual-file-based/src/routes/posts/posts-home.tsx b/examples/solid/basic-virtual-file-based/src/routes/posts/posts-home.tsx index 13529228bb..812b581e0a 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/posts/posts-home.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/posts/posts-home.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute('/posts/')({ component: PostsIndexComponent, }) diff --git a/examples/solid/basic-virtual-file-based/src/routes/posts/posts.tsx b/examples/solid/basic-virtual-file-based/src/routes/posts/posts.tsx index 46203594d1..9ae6dfc747 100644 --- a/examples/solid/basic-virtual-file-based/src/routes/posts/posts.tsx +++ b/examples/solid/basic-virtual-file-based/src/routes/posts/posts.tsx @@ -1,7 +1,7 @@ -import { Link, Outlet } from '@tanstack/solid-router' +import { Link, Outlet, createFileRoute } from '@tanstack/solid-router' import { fetchPosts } from '../../posts' -export const Route = createFileRoute({ +export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) diff --git a/examples/solid/basic-virtual-file-based/src/styles.css b/examples/solid/basic-virtual-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/basic-virtual-file-based/src/styles.css +++ b/examples/solid/basic-virtual-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/basic-virtual-file-based/src/vite-env.d.ts b/examples/solid/basic-virtual-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/basic-virtual-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/basic-virtual-file-based/vite.config.ts b/examples/solid/basic-virtual-file-based/vite.config.ts index 635aa70940..ec379c254d 100644 --- a/examples/solid/basic-virtual-file-based/vite.config.ts +++ b/examples/solid/basic-virtual-file-based/vite.config.ts @@ -1,14 +1,15 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'solid', autoCodeSplitting: true, - verboseFileRoutes: false, virtualRouteConfig: './routes.ts', }), solid(), diff --git a/examples/solid/basic-virtual-inside-file-based/.devcontainer/devcontainer.json b/examples/solid/basic-virtual-inside-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/basic-virtual-inside-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/basic-virtual-inside-file-based/package.json b/examples/solid/basic-virtual-inside-file-based/package.json index e27710d753..a9cc6360a5 100644 --- a/examples/solid/basic-virtual-inside-file-based/package.json +++ b/examples/solid/basic-virtual-inside-file-based/package.json @@ -9,20 +9,20 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "@tanstack/virtual-file-routes": "^1.141.0", - "postcss": "^8.5.1", - "solid-js": "^1.9.10", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/virtual-file-routes": "^1.162.0", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "solid-js": "^1.9.10", + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/basic-virtual-inside-file-based/postcss.config.mjs b/examples/solid/basic-virtual-inside-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/basic-virtual-inside-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/basic-virtual-inside-file-based/src/routeTree.gen.ts b/examples/solid/basic-virtual-inside-file-based/src/routeTree.gen.ts index e94775b981..6117330aa3 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-virtual-inside-file-based/src/routeTree.gen.ts @@ -8,64 +8,62 @@ // You should NOT make any changes in this file as it will be overwritten. // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. -import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/solid-router' - import { Route as rootRouteImport } from './routes/__root' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' -import { Route as postsDetailsRouteImport } from './routes/posts/details' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as PostsRouteImport } from './routes/posts' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as postsHomeRouteImport } from './routes/posts/home' -import { Route as postsLetsGoIndexRouteImport } from './routes/posts/lets-go/index' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsHomeRouteImport } from './routes/posts/home' +import { Route as PostsDetailsRouteImport } from './routes/posts/details' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as postsLetsGoDeeperHomeRouteImport } from './routes/posts/lets-go/deeper/home' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsLetsGoIndexRouteImport } from './routes/posts/lets-go/index' +import { Route as PostsLetsGoDeeperHomeRouteImport } from './routes/posts/lets-go/deeper/home' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const LayoutRoute = LayoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const postsDetailsRoute = postsDetailsRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) const LayoutLayout2Route = LayoutLayout2RouteImport.update({ id: '/_layout-2', getParentRoute: () => LayoutRoute, } as any) -const postsHomeRoute = postsHomeRouteImport.update({ +const PostsHomeRoute = PostsHomeRouteImport.update({ id: '/', path: '/', getParentRoute: () => PostsRoute, } as any) -const postsLetsGoIndexRoute = postsLetsGoIndexRouteImport.update({ - id: '/inception/', - path: '/inception/', +const PostsDetailsRoute = PostsDetailsRouteImport.update({ + id: '/$postId', + path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, -} as any) const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ id: '/layout-a', path: '/layout-a', getParentRoute: () => LayoutLayout2Route, } as any) -const postsLetsGoDeeperHomeRoute = postsLetsGoDeeperHomeRouteImport.update({ +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const PostsLetsGoIndexRoute = PostsLetsGoIndexRouteImport.update({ + id: '/inception/', + path: '/inception/', + getParentRoute: () => PostsRoute, +} as any) +const PostsLetsGoDeeperHomeRoute = PostsLetsGoDeeperHomeRouteImport.update({ id: '/inception/deeper/', path: '/inception/deeper/', getParentRoute: () => PostsRoute, @@ -74,34 +72,34 @@ const postsLetsGoDeeperHomeRoute = postsLetsGoDeeperHomeRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren - '/posts/': typeof postsHomeRoute - '/posts/$postId': typeof postsDetailsRoute + '/posts/': typeof PostsHomeRoute + '/posts/$postId': typeof PostsDetailsRoute '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute - '/posts/inception': typeof postsLetsGoIndexRoute - '/posts/inception/deeper': typeof postsLetsGoDeeperHomeRoute + '/posts/inception/': typeof PostsLetsGoIndexRoute + '/posts/inception/deeper/': typeof PostsLetsGoDeeperHomeRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/posts': typeof postsHomeRoute - '/posts/$postId': typeof postsDetailsRoute + '/posts': typeof PostsHomeRoute + '/posts/$postId': typeof PostsDetailsRoute '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute - '/posts/inception': typeof postsLetsGoIndexRoute - '/posts/inception/deeper': typeof postsLetsGoDeeperHomeRoute + '/posts/inception': typeof PostsLetsGoIndexRoute + '/posts/inception/deeper': typeof PostsLetsGoDeeperHomeRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute '/_layout': typeof LayoutRouteWithChildren '/posts': typeof PostsRouteWithChildren - '/posts/': typeof postsHomeRoute + '/posts/': typeof PostsHomeRoute '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren - '/posts/$postId': typeof postsDetailsRoute + '/posts/$postId': typeof PostsDetailsRoute '/_layout/_layout-2/layout-a': typeof LayoutLayout2LayoutARoute '/_layout/_layout-2/layout-b': typeof LayoutLayout2LayoutBRoute - '/posts/inception/': typeof postsLetsGoIndexRoute - '/posts/inception/deeper/': typeof postsLetsGoDeeperHomeRoute + '/posts/inception/': typeof PostsLetsGoIndexRoute + '/posts/inception/deeper/': typeof PostsLetsGoDeeperHomeRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath @@ -112,8 +110,8 @@ export interface FileRouteTypes { | '/posts/$postId' | '/layout-a' | '/layout-b' - | '/posts/inception' - | '/posts/inception/deeper' + | '/posts/inception/' + | '/posts/inception/deeper/' fileRoutesByTo: FileRoutesByTo to: | '/' @@ -145,20 +143,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -166,17 +150,24 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof postsDetailsRouteImport - parentRoute: typeof PostsRoute + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } '/_layout/_layout-2': { id: '/_layout/_layout-2' path: '' - fullPath: '' + fullPath: '/' preLoaderRoute: typeof LayoutLayout2RouteImport parentRoute: typeof LayoutRoute } @@ -184,23 +175,16 @@ declare module '@tanstack/solid-router' { id: '/posts/' path: '/' fullPath: '/posts/' - preLoaderRoute: typeof postsHomeRouteImport + preLoaderRoute: typeof PostsHomeRouteImport parentRoute: typeof PostsRoute } - '/posts/inception/': { - id: '/posts/inception/' - path: '/inception' - fullPath: '/posts/inception' - preLoaderRoute: typeof postsLetsGoIndexRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsDetailsRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } '/_layout/_layout-2/layout-a': { id: '/_layout/_layout-2/layout-a' path: '/layout-a' @@ -208,107 +192,30 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LayoutLayout2LayoutARouteImport parentRoute: typeof LayoutLayout2Route } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/posts/inception/': { + id: '/posts/inception/' + path: '/inception' + fullPath: '/posts/inception/' + preLoaderRoute: typeof PostsLetsGoIndexRouteImport + parentRoute: typeof PostsRoute + } '/posts/inception/deeper/': { id: '/posts/inception/deeper/' path: '/inception/deeper' - fullPath: '/posts/inception/deeper' - preLoaderRoute: typeof postsLetsGoDeeperHomeRouteImport + fullPath: '/posts/inception/deeper/' + preLoaderRoute: typeof PostsLetsGoDeeperHomeRouteImport parentRoute: typeof PostsRoute } } } -declare module './routes/index' { - const createFileRoute: CreateFileRoute< - '/', - FileRoutesByPath['/']['parentRoute'], - FileRoutesByPath['/']['id'], - FileRoutesByPath['/']['path'], - FileRoutesByPath['/']['fullPath'] - > -} -declare module './routes/_layout' { - const createFileRoute: CreateFileRoute< - '/_layout', - FileRoutesByPath['/_layout']['parentRoute'], - FileRoutesByPath['/_layout']['id'], - FileRoutesByPath['/_layout']['path'], - FileRoutesByPath['/_layout']['fullPath'] - > -} -declare module './routes/posts' { - const createFileRoute: CreateFileRoute< - '/posts', - FileRoutesByPath['/posts']['parentRoute'], - FileRoutesByPath['/posts']['id'], - FileRoutesByPath['/posts']['path'], - FileRoutesByPath['/posts']['fullPath'] - > -} -declare module './routes/posts/home' { - const createFileRoute: CreateFileRoute< - '/posts/', - FileRoutesByPath['/posts/']['parentRoute'], - FileRoutesByPath['/posts/']['id'], - FileRoutesByPath['/posts/']['path'], - FileRoutesByPath['/posts/']['fullPath'] - > -} -declare module './routes/_layout/_layout-2' { - const createFileRoute: CreateFileRoute< - '/_layout/_layout-2', - FileRoutesByPath['/_layout/_layout-2']['parentRoute'], - FileRoutesByPath['/_layout/_layout-2']['id'], - FileRoutesByPath['/_layout/_layout-2']['path'], - FileRoutesByPath['/_layout/_layout-2']['fullPath'] - > -} -declare module './routes/posts/details' { - const createFileRoute: CreateFileRoute< - '/posts/$postId', - FileRoutesByPath['/posts/$postId']['parentRoute'], - FileRoutesByPath['/posts/$postId']['id'], - FileRoutesByPath['/posts/$postId']['path'], - FileRoutesByPath['/posts/$postId']['fullPath'] - > -} -declare module './routes/_layout/_layout-2/layout-a' { - const createFileRoute: CreateFileRoute< - '/_layout/_layout-2/layout-a', - FileRoutesByPath['/_layout/_layout-2/layout-a']['parentRoute'], - FileRoutesByPath['/_layout/_layout-2/layout-a']['id'], - FileRoutesByPath['/_layout/_layout-2/layout-a']['path'], - FileRoutesByPath['/_layout/_layout-2/layout-a']['fullPath'] - > -} -declare module './routes/_layout/_layout-2/layout-b' { - const createFileRoute: CreateFileRoute< - '/_layout/_layout-2/layout-b', - FileRoutesByPath['/_layout/_layout-2/layout-b']['parentRoute'], - FileRoutesByPath['/_layout/_layout-2/layout-b']['id'], - FileRoutesByPath['/_layout/_layout-2/layout-b']['path'], - FileRoutesByPath['/_layout/_layout-2/layout-b']['fullPath'] - > -} -declare module './routes/posts/lets-go/index' { - const createFileRoute: CreateFileRoute< - '/posts/inception/', - FileRoutesByPath['/posts/inception/']['parentRoute'], - FileRoutesByPath['/posts/inception/']['id'], - FileRoutesByPath['/posts/inception/']['path'], - FileRoutesByPath['/posts/inception/']['fullPath'] - > -} -declare module './routes/posts/lets-go/deeper/home' { - const createFileRoute: CreateFileRoute< - '/posts/inception/deeper/', - FileRoutesByPath['/posts/inception/deeper/']['parentRoute'], - FileRoutesByPath['/posts/inception/deeper/']['id'], - FileRoutesByPath['/posts/inception/deeper/']['path'], - FileRoutesByPath['/posts/inception/deeper/']['fullPath'] - > -} - interface LayoutLayout2RouteChildren { LayoutLayout2LayoutARoute: typeof LayoutLayout2LayoutARoute LayoutLayout2LayoutBRoute: typeof LayoutLayout2LayoutBRoute @@ -335,17 +242,17 @@ const LayoutRouteWithChildren = LayoutRoute._addFileChildren(LayoutRouteChildren) interface PostsRouteChildren { - postsHomeRoute: typeof postsHomeRoute - postsDetailsRoute: typeof postsDetailsRoute - postsLetsGoIndexRoute: typeof postsLetsGoIndexRoute - postsLetsGoDeeperHomeRoute: typeof postsLetsGoDeeperHomeRoute + PostsHomeRoute: typeof PostsHomeRoute + PostsDetailsRoute: typeof PostsDetailsRoute + PostsLetsGoIndexRoute: typeof PostsLetsGoIndexRoute + PostsLetsGoDeeperHomeRoute: typeof PostsLetsGoDeeperHomeRoute } const PostsRouteChildren: PostsRouteChildren = { - postsHomeRoute: postsHomeRoute, - postsDetailsRoute: postsDetailsRoute, - postsLetsGoIndexRoute: postsLetsGoIndexRoute, - postsLetsGoDeeperHomeRoute: postsLetsGoDeeperHomeRoute, + PostsHomeRoute: PostsHomeRoute, + PostsDetailsRoute: PostsDetailsRoute, + PostsLetsGoIndexRoute: PostsLetsGoIndexRoute, + PostsLetsGoDeeperHomeRoute: PostsLetsGoDeeperHomeRoute, } const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) diff --git a/examples/solid/basic-virtual-inside-file-based/src/routes/_layout.tsx b/examples/solid/basic-virtual-inside-file-based/src/routes/_layout.tsx index c549175638..d43b4ef5f5 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/routes/_layout.tsx +++ b/examples/solid/basic-virtual-inside-file-based/src/routes/_layout.tsx @@ -1,6 +1,6 @@ -import { Outlet } from '@tanstack/solid-router' +import { Outlet, createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_layout')({ component: LayoutComponent, }) diff --git a/examples/solid/basic-virtual-inside-file-based/src/routes/_layout/_layout-2.tsx b/examples/solid/basic-virtual-inside-file-based/src/routes/_layout/_layout-2.tsx index efeca5ce86..7a5a3623a0 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/routes/_layout/_layout-2.tsx +++ b/examples/solid/basic-virtual-inside-file-based/src/routes/_layout/_layout-2.tsx @@ -1,6 +1,6 @@ -import { Link, Outlet } from '@tanstack/solid-router' +import { Link, Outlet, createFileRoute } from '@tanstack/solid-router' -export const Route = createFileRoute({ +export const Route = createFileRoute('/_layout/_layout-2')({ component: LayoutComponent, }) diff --git a/examples/solid/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-a.tsx b/examples/solid/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-a.tsx index a190b24202..997e6caf80 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-a.tsx +++ b/examples/solid/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-a.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute('/_layout/_layout-2/layout-a')({ component: LayoutAComponent, }) diff --git a/examples/solid/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-b.tsx b/examples/solid/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-b.tsx index 505f8f6fbf..70135c5809 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-b.tsx +++ b/examples/solid/basic-virtual-inside-file-based/src/routes/_layout/_layout-2/layout-b.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute('/_layout/_layout-2/layout-b')({ component: LayoutBComponent, }) diff --git a/examples/solid/basic-virtual-inside-file-based/src/routes/index.tsx b/examples/solid/basic-virtual-inside-file-based/src/routes/index.tsx index 510db79b73..3f905db60c 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/routes/index.tsx +++ b/examples/solid/basic-virtual-inside-file-based/src/routes/index.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute('/')({ component: Home, }) diff --git a/examples/solid/basic-virtual-inside-file-based/src/routes/posts.tsx b/examples/solid/basic-virtual-inside-file-based/src/routes/posts.tsx index 2e28f9beb3..11a999f50a 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/routes/posts.tsx +++ b/examples/solid/basic-virtual-inside-file-based/src/routes/posts.tsx @@ -1,7 +1,7 @@ -import { Link, Outlet } from '@tanstack/solid-router' +import { Link, Outlet, createFileRoute } from '@tanstack/solid-router' import { fetchPosts } from '../posts' -export const Route = createFileRoute({ +export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) diff --git a/examples/solid/basic-virtual-inside-file-based/src/routes/posts/details.tsx b/examples/solid/basic-virtual-inside-file-based/src/routes/posts/details.tsx index b01702746d..de4cc4ed80 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/routes/posts/details.tsx +++ b/examples/solid/basic-virtual-inside-file-based/src/routes/posts/details.tsx @@ -1,4 +1,4 @@ -import { ErrorComponent } from '@tanstack/solid-router' +import { ErrorComponent, createFileRoute } from '@tanstack/solid-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/solid-router' @@ -6,7 +6,7 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } -export const Route = createFileRoute({ +export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent, notFoundComponent: () => { diff --git a/examples/solid/basic-virtual-inside-file-based/src/routes/posts/home.tsx b/examples/solid/basic-virtual-inside-file-based/src/routes/posts/home.tsx index 13529228bb..812b581e0a 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/routes/posts/home.tsx +++ b/examples/solid/basic-virtual-inside-file-based/src/routes/posts/home.tsx @@ -1,4 +1,5 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute('/posts/')({ component: PostsIndexComponent, }) diff --git a/examples/solid/basic-virtual-inside-file-based/src/routes/posts/lets-go/deeper/home.tsx b/examples/solid/basic-virtual-inside-file-based/src/routes/posts/lets-go/deeper/home.tsx index f8bc76644a..166eda4335 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/routes/posts/lets-go/deeper/home.tsx +++ b/examples/solid/basic-virtual-inside-file-based/src/routes/posts/lets-go/deeper/home.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute('/posts/inception/deeper/')({ component: () =>
    Hello /posts/inception/deeper/!
    , }) diff --git a/examples/solid/basic-virtual-inside-file-based/src/routes/posts/lets-go/index.tsx b/examples/solid/basic-virtual-inside-file-based/src/routes/posts/lets-go/index.tsx index 1c7ea68931..49b88f751d 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/routes/posts/lets-go/index.tsx +++ b/examples/solid/basic-virtual-inside-file-based/src/routes/posts/lets-go/index.tsx @@ -1,3 +1,4 @@ -export const Route = createFileRoute({ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute('/posts/inception/')({ component: () =>
    Hello /posts/inception/!
    , }) diff --git a/examples/solid/basic-virtual-inside-file-based/src/styles.css b/examples/solid/basic-virtual-inside-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/styles.css +++ b/examples/solid/basic-virtual-inside-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/basic-virtual-inside-file-based/src/vite-env.d.ts b/examples/solid/basic-virtual-inside-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/basic-virtual-inside-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/basic-virtual-inside-file-based/vite.config.ts b/examples/solid/basic-virtual-inside-file-based/vite.config.ts index 848503f5b3..79454008ba 100644 --- a/examples/solid/basic-virtual-inside-file-based/vite.config.ts +++ b/examples/solid/basic-virtual-inside-file-based/vite.config.ts @@ -1,14 +1,15 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'solid', autoCodeSplitting: true, - verboseFileRoutes: false, }), solid(), ], diff --git a/examples/solid/basic/.devcontainer/devcontainer.json b/examples/solid/basic/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/basic/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/basic/package.json b/examples/solid/basic/package.json index 1ae8721795..95ec804011 100644 --- a/examples/solid/basic/package.json +++ b/examples/solid/basic/package.json @@ -9,19 +9,19 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/basic/postcss.config.mjs b/examples/solid/basic/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/basic/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/basic/src/styles.css b/examples/solid/basic/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/basic/src/styles.css +++ b/examples/solid/basic/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/basic/src/vite-env.d.ts b/examples/solid/basic/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/basic/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/basic/vite.config.js b/examples/solid/basic/vite.config.js index 05041cc6d8..fb5faf9236 100644 --- a/examples/solid/basic/vite.config.js +++ b/examples/solid/basic/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [solid()], + plugins: [tailwindcss(), solid()], }) diff --git a/examples/solid/deferred-data/.devcontainer/devcontainer.json b/examples/solid/deferred-data/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/deferred-data/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/deferred-data/package.json b/examples/solid/deferred-data/package.json index 0f1045190e..56114afd04 100644 --- a/examples/solid/deferred-data/package.json +++ b/examples/solid/deferred-data/package.json @@ -9,18 +9,18 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", - "solid-js": "^1.9.10", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "solid-js": "^1.9.10", + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/deferred-data/postcss.config.mjs b/examples/solid/deferred-data/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/deferred-data/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/deferred-data/src/main.tsx b/examples/solid/deferred-data/src/main.tsx index f189a2e1c4..4dd43fd97b 100644 --- a/examples/solid/deferred-data/src/main.tsx +++ b/examples/solid/deferred-data/src/main.tsx @@ -75,7 +75,7 @@ function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) {
    diff --git a/examples/solid/deferred-data/src/styles.css b/examples/solid/deferred-data/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/deferred-data/src/styles.css +++ b/examples/solid/deferred-data/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/deferred-data/src/vite-env.d.ts b/examples/solid/deferred-data/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/deferred-data/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/deferred-data/vite.config.js b/examples/solid/deferred-data/vite.config.js index 05041cc6d8..fb5faf9236 100644 --- a/examples/solid/deferred-data/vite.config.js +++ b/examples/solid/deferred-data/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [solid()], + plugins: [tailwindcss(), solid()], }) diff --git a/examples/solid/i18n-paraglide/.devcontainer/devcontainer.json b/examples/solid/i18n-paraglide/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/i18n-paraglide/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/i18n-paraglide/README.md b/examples/solid/i18n-paraglide/README.md index e9dd968ee8..d43951c8f1 100644 --- a/examples/solid/i18n-paraglide/README.md +++ b/examples/solid/i18n-paraglide/README.md @@ -1,6 +1,6 @@ # TanStack Router example -This example shows how to use Paraglide with TanStack Router. The source code can be found [here](https://github.com/opral/monorepo/tree/main/inlang/packages/paraglide/paraglide-js/examples/tanstack-router). +This example shows how to use Paraglide with TanStack Router. ## Getting started diff --git a/examples/solid/i18n-paraglide/package.json b/examples/solid/i18n-paraglide/package.json index bed2a50878..6493a3c7c8 100644 --- a/examples/solid/i18n-paraglide/package.json +++ b/examples/solid/i18n-paraglide/package.json @@ -10,17 +10,29 @@ "test": "vitest run" }, "dependencies": { - "@tailwindcss/vite": "^4.1.17", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.13" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/node": "^22.18.6", - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.9.2", - "vite": "^7.1.7", + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "@inlang/paraglide-js": "^2.4.0" + }, + "nx": { + "targets": { + "build": { + "outputs": [ + "...", + "{projectRoot}/src/paraglide", + "{projectRoot}/project.inlang/cache" + ] + } + } } } diff --git a/examples/solid/i18n-paraglide/src/routeTree.gen.ts b/examples/solid/i18n-paraglide/src/routeTree.gen.ts index 333a815c38..98df1e83d8 100644 --- a/examples/solid/i18n-paraglide/src/routeTree.gen.ts +++ b/examples/solid/i18n-paraglide/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/i18n-paraglide/src/styles.css b/examples/solid/i18n-paraglide/src/styles.css index d4b5078586..23fa2415ca 100644 --- a/examples/solid/i18n-paraglide/src/styles.css +++ b/examples/solid/i18n-paraglide/src/styles.css @@ -1 +1 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); diff --git a/examples/solid/i18n-paraglide/src/vite-env.d.ts b/examples/solid/i18n-paraglide/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/i18n-paraglide/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/i18n-paraglide/tsconfig.json b/examples/solid/i18n-paraglide/tsconfig.json index f3fadb414f..9dcde39a0f 100644 --- a/examples/solid/i18n-paraglide/tsconfig.json +++ b/examples/solid/i18n-paraglide/tsconfig.json @@ -22,7 +22,6 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, - "baseUrl": ".", "paths": { "@/*": ["./src/*"] } diff --git a/examples/solid/kitchen-sink-file-based/.devcontainer/devcontainer.json b/examples/solid/kitchen-sink-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/kitchen-sink-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/kitchen-sink-file-based/package.json b/examples/solid/kitchen-sink-file-based/package.json index 6581f3d1c2..8cd73e38ff 100644 --- a/examples/solid/kitchen-sink-file-based/package.json +++ b/examples/solid/kitchen-sink-file-based/package.json @@ -9,20 +9,20 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "immer": "^10.1.1", - "postcss": "^8.5.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.142.0", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10" + "@tanstack/router-plugin": "^1.169.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/kitchen-sink-file-based/postcss.config.mjs b/examples/solid/kitchen-sink-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/kitchen-sink-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/kitchen-sink-file-based/src/components/Spinner.tsx b/examples/solid/kitchen-sink-file-based/src/components/Spinner.tsx index 2c853ed6ff..b1730754bf 100644 --- a/examples/solid/kitchen-sink-file-based/src/components/Spinner.tsx +++ b/examples/solid/kitchen-sink-file-based/src/components/Spinner.tsx @@ -3,7 +3,7 @@ export function Spinner(props: { show?: boolean; wait?: `delay-${number}` }) {
    diff --git a/examples/solid/kitchen-sink-file-based/src/routeTree.gen.ts b/examples/solid/kitchen-sink-file-based/src/routeTree.gen.ts index f7af0fbf39..76bb314a71 100644 --- a/examples/solid/kitchen-sink-file-based/src/routeTree.gen.ts +++ b/examples/solid/kitchen-sink-file-based/src/routeTree.gen.ts @@ -8,132 +8,224 @@ // 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 Routes - -import { Route as rootRoute } from './routes/__root' -import { Route as LoginRouteImport } from './routes/login' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as AuthRouteImport } from './routes/_auth' -import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' -import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' -import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' -import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' -import { Route as AuthProfileRouteImport } from './routes/_auth.profile' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +import { Route as LoginRouteImport } from './routes/login' import { Route as thisFolderIsNotInTheUrlRouteGroupRouteImport } from './routes/(this-folder-is-not-in-the-url)/route-group' -import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as AuthProfileRouteImport } from './routes/_auth.profile' +import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' +import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' -import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' import { Route as DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' - -// Create/Update Routes - -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => rootRoute, -} as any) - -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRoute, -} as any) - -const AuthRoute = AuthRouteImport.update({ - id: '/_auth', - getParentRoute: () => rootRoute, -} as any) - -const DashboardRouteRoute = DashboardRouteRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => rootRoute, -} as any) +import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => rootRoute, + getParentRoute: () => rootRouteImport, } as any) - -const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ - id: '/expensive/', - path: '/expensive/', - getParentRoute: () => rootRoute, +const AuthRoute = AuthRouteImport.update({ + id: '/_auth', + getParentRoute: () => rootRouteImport, } as any) - -const DashboardIndexRoute = DashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardRouteRoute, +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, } as any) - -const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutRoute, +const DashboardRouteRoute = DashboardRouteRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => rootRouteImport, } as any) - -const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutRoute, +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, } as any) - +const thisFolderIsNotInTheUrlRouteGroupRoute = + thisFolderIsNotInTheUrlRouteGroupRouteImport.update({ + id: '/(this-folder-is-not-in-the-url)/route-group', + path: '/route-group', + getParentRoute: () => rootRouteImport, + } as any) const AuthProfileRoute = AuthProfileRouteImport.update({ id: '/profile', path: '/profile', getParentRoute: () => AuthRoute, } as any) - -const thisFolderIsNotInTheUrlRouteGroupRoute = - thisFolderIsNotInTheUrlRouteGroupRouteImport.update({ - id: '/(this-folder-is-not-in-the-url)/route-group', - path: '/route-group', - getParentRoute: () => rootRoute, - } as any) - -const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ - id: '/users', - path: '/users', +const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const DashboardIndexRoute = DashboardIndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => DashboardRouteRoute, } as any) - const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ id: '/invoices', path: '/invoices', getParentRoute: () => DashboardRouteRoute, } as any) - -const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardUsersRouteRoute, +const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => DashboardRouteRoute, +} as any) +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRouteImport, } as any) - const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) - -const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ - id: '/user', - path: '/user', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) - const DashboardInvoicesInvoiceIdRoute = DashboardInvoicesInvoiceIdRouteImport.update({ id: '/$invoiceId', path: '/$invoiceId', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) +const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) +const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ + id: '/user', + path: '/user', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) -// Populate the FileRoutesByPath interface +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/dashboard': typeof DashboardRouteRouteWithChildren + '/login': typeof LoginRoute + '/dashboard/invoices': typeof DashboardInvoicesRouteRouteWithChildren + '/dashboard/users': typeof DashboardUsersRouteRouteWithChildren + '/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute + '/profile': typeof AuthProfileRoute + '/route-a': typeof PathlessLayoutRouteARoute + '/route-b': typeof PathlessLayoutRouteBRoute + '/dashboard/': typeof DashboardIndexRoute + '/expensive/': typeof ExpensiveIndexRoute + '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute + '/dashboard/users/user': typeof DashboardUsersUserRoute + '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute + '/dashboard/users/': typeof DashboardUsersIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/login': typeof LoginRoute + '/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute + '/profile': typeof AuthProfileRoute + '/route-a': typeof PathlessLayoutRouteARoute + '/route-b': typeof PathlessLayoutRouteBRoute + '/dashboard': typeof DashboardIndexRoute + '/expensive': typeof ExpensiveIndexRoute + '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute + '/dashboard/users/user': typeof DashboardUsersUserRoute + '/dashboard/invoices': typeof DashboardInvoicesIndexRoute + '/dashboard/users': typeof DashboardUsersIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/dashboard': typeof DashboardRouteRouteWithChildren + '/_auth': typeof AuthRouteWithChildren + '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren + '/login': typeof LoginRoute + '/dashboard/invoices': typeof DashboardInvoicesRouteRouteWithChildren + '/dashboard/users': typeof DashboardUsersRouteRouteWithChildren + '/(this-folder-is-not-in-the-url)/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute + '/_auth/profile': typeof AuthProfileRoute + '/_pathlessLayout/route-a': typeof PathlessLayoutRouteARoute + '/_pathlessLayout/route-b': typeof PathlessLayoutRouteBRoute + '/dashboard/': typeof DashboardIndexRoute + '/expensive/': typeof ExpensiveIndexRoute + '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute + '/dashboard/users/user': typeof DashboardUsersUserRoute + '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute + '/dashboard/users/': typeof DashboardUsersIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/dashboard' + | '/login' + | '/dashboard/invoices' + | '/dashboard/users' + | '/route-group' + | '/profile' + | '/route-a' + | '/route-b' + | '/dashboard/' + | '/expensive/' + | '/dashboard/invoices/$invoiceId' + | '/dashboard/users/user' + | '/dashboard/invoices/' + | '/dashboard/users/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/login' + | '/route-group' + | '/profile' + | '/route-a' + | '/route-b' + | '/dashboard' + | '/expensive' + | '/dashboard/invoices/$invoiceId' + | '/dashboard/users/user' + | '/dashboard/invoices' + | '/dashboard/users' + id: + | '__root__' + | '/' + | '/dashboard' + | '/_auth' + | '/_pathlessLayout' + | '/login' + | '/dashboard/invoices' + | '/dashboard/users' + | '/(this-folder-is-not-in-the-url)/route-group' + | '/_auth/profile' + | '/_pathlessLayout/route-a' + | '/_pathlessLayout/route-b' + | '/dashboard/' + | '/expensive/' + | '/dashboard/invoices/$invoiceId' + | '/dashboard/users/user' + | '/dashboard/invoices/' + | '/dashboard/users/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DashboardRouteRoute: typeof DashboardRouteRouteWithChildren + AuthRoute: typeof AuthRouteWithChildren + PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren + LoginRoute: typeof LoginRoute + thisFolderIsNotInTheUrlRouteGroupRoute: typeof thisFolderIsNotInTheUrlRouteGroupRoute + ExpensiveIndexRoute: typeof ExpensiveIndexRoute +} declare module '@tanstack/solid-router' { interface FileRoutesByPath { @@ -142,125 +234,123 @@ declare module '@tanstack/solid-router' { path: '/' fullPath: '/' preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRoute + parentRoute: typeof rootRouteImport + } + '/_auth': { + id: '/_auth' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport } '/dashboard': { id: '/dashboard' path: '/dashboard' fullPath: '/dashboard' preLoaderRoute: typeof DashboardRouteRouteImport - parentRoute: typeof rootRoute - } - '/_auth': { - id: '/_auth' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthRouteImport - parentRoute: typeof rootRoute - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRoute + parentRoute: typeof rootRouteImport } '/login': { id: '/login' path: '/login' fullPath: '/login' preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRoute - } - '/dashboard/invoices': { - id: '/dashboard/invoices' - path: '/invoices' - fullPath: '/dashboard/invoices' - preLoaderRoute: typeof DashboardInvoicesRouteRouteImport - parentRoute: typeof DashboardRouteRouteImport - } - '/dashboard/users': { - id: '/dashboard/users' - path: '/users' - fullPath: '/dashboard/users' - preLoaderRoute: typeof DashboardUsersRouteRouteImport - parentRoute: typeof DashboardRouteRouteImport + parentRoute: typeof rootRouteImport } '/(this-folder-is-not-in-the-url)/route-group': { id: '/(this-folder-is-not-in-the-url)/route-group' path: '/route-group' fullPath: '/route-group' preLoaderRoute: typeof thisFolderIsNotInTheUrlRouteGroupRouteImport - parentRoute: typeof rootRoute + parentRoute: typeof rootRouteImport } '/_auth/profile': { id: '/_auth/profile' path: '/profile' fullPath: '/profile' preLoaderRoute: typeof AuthProfileRouteImport - parentRoute: typeof AuthRouteImport + parentRoute: typeof AuthRoute } '/_pathlessLayout/route-a': { id: '/_pathlessLayout/route-a' path: '/route-a' fullPath: '/route-a' preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/_pathlessLayout/route-b': { id: '/_pathlessLayout/route-b' path: '/route-b' fullPath: '/route-b' preLoaderRoute: typeof PathlessLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/dashboard/': { id: '/dashboard/' path: '/' fullPath: '/dashboard/' preLoaderRoute: typeof DashboardIndexRouteImport - parentRoute: typeof DashboardRouteRouteImport + parentRoute: typeof DashboardRouteRoute + } + '/dashboard/invoices': { + id: '/dashboard/invoices' + path: '/invoices' + fullPath: '/dashboard/invoices' + preLoaderRoute: typeof DashboardInvoicesRouteRouteImport + parentRoute: typeof DashboardRouteRoute + } + '/dashboard/users': { + id: '/dashboard/users' + path: '/users' + fullPath: '/dashboard/users' + preLoaderRoute: typeof DashboardUsersRouteRouteImport + parentRoute: typeof DashboardRouteRoute } '/expensive/': { id: '/expensive/' path: '/expensive' - fullPath: '/expensive' + fullPath: '/expensive/' preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRoute - } - '/dashboard/invoices/$invoiceId': { - id: '/dashboard/invoices/$invoiceId' - path: '/$invoiceId' - fullPath: '/dashboard/invoices/$invoiceId' - preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport - parentRoute: typeof DashboardInvoicesRouteRouteImport - } - '/dashboard/users/user': { - id: '/dashboard/users/user' - path: '/user' - fullPath: '/dashboard/users/user' - preLoaderRoute: typeof DashboardUsersUserRouteImport - parentRoute: typeof DashboardUsersRouteRouteImport + parentRoute: typeof rootRouteImport } '/dashboard/invoices/': { id: '/dashboard/invoices/' path: '/' fullPath: '/dashboard/invoices/' preLoaderRoute: typeof DashboardInvoicesIndexRouteImport - parentRoute: typeof DashboardInvoicesRouteRouteImport + parentRoute: typeof DashboardInvoicesRouteRoute + } + '/dashboard/invoices/$invoiceId': { + id: '/dashboard/invoices/$invoiceId' + path: '/$invoiceId' + fullPath: '/dashboard/invoices/$invoiceId' + preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport + parentRoute: typeof DashboardInvoicesRouteRoute } '/dashboard/users/': { id: '/dashboard/users/' path: '/' fullPath: '/dashboard/users/' preLoaderRoute: typeof DashboardUsersIndexRouteImport - parentRoute: typeof DashboardUsersRouteRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } + '/dashboard/users/user': { + id: '/dashboard/users/user' + path: '/user' + fullPath: '/dashboard/users/user' + preLoaderRoute: typeof DashboardUsersUserRouteImport + parentRoute: typeof DashboardUsersRouteRoute } } } -// Create and export the route tree - interface DashboardInvoicesRouteRouteChildren { DashboardInvoicesInvoiceIdRoute: typeof DashboardInvoicesInvoiceIdRoute DashboardInvoicesIndexRoute: typeof DashboardInvoicesIndexRoute @@ -330,128 +420,6 @@ const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( PathlessLayoutRouteChildren, ) -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/dashboard': typeof DashboardRouteRouteWithChildren - '': typeof PathlessLayoutRouteWithChildren - '/login': typeof LoginRoute - '/dashboard/invoices': typeof DashboardInvoicesRouteRouteWithChildren - '/dashboard/users': typeof DashboardUsersRouteRouteWithChildren - '/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute - '/profile': typeof AuthProfileRoute - '/route-a': typeof PathlessLayoutRouteARoute - '/route-b': typeof PathlessLayoutRouteBRoute - '/dashboard/': typeof DashboardIndexRoute - '/expensive': typeof ExpensiveIndexRoute - '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute - '/dashboard/users/user': typeof DashboardUsersUserRoute - '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute - '/dashboard/users/': typeof DashboardUsersIndexRoute -} - -export interface FileRoutesByTo { - '/': typeof IndexRoute - '': typeof PathlessLayoutRouteWithChildren - '/login': typeof LoginRoute - '/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute - '/profile': typeof AuthProfileRoute - '/route-a': typeof PathlessLayoutRouteARoute - '/route-b': typeof PathlessLayoutRouteBRoute - '/dashboard': typeof DashboardIndexRoute - '/expensive': typeof ExpensiveIndexRoute - '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute - '/dashboard/users/user': typeof DashboardUsersUserRoute - '/dashboard/invoices': typeof DashboardInvoicesIndexRoute - '/dashboard/users': typeof DashboardUsersIndexRoute -} - -export interface FileRoutesById { - __root__: typeof rootRoute - '/': typeof IndexRoute - '/dashboard': typeof DashboardRouteRouteWithChildren - '/_auth': typeof AuthRouteWithChildren - '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren - '/login': typeof LoginRoute - '/dashboard/invoices': typeof DashboardInvoicesRouteRouteWithChildren - '/dashboard/users': typeof DashboardUsersRouteRouteWithChildren - '/(this-folder-is-not-in-the-url)/route-group': typeof thisFolderIsNotInTheUrlRouteGroupRoute - '/_auth/profile': typeof AuthProfileRoute - '/_pathlessLayout/route-a': typeof PathlessLayoutRouteARoute - '/_pathlessLayout/route-b': typeof PathlessLayoutRouteBRoute - '/dashboard/': typeof DashboardIndexRoute - '/expensive/': typeof ExpensiveIndexRoute - '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute - '/dashboard/users/user': typeof DashboardUsersUserRoute - '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute - '/dashboard/users/': typeof DashboardUsersIndexRoute -} - -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/dashboard' - | '' - | '/login' - | '/dashboard/invoices' - | '/dashboard/users' - | '/route-group' - | '/profile' - | '/route-a' - | '/route-b' - | '/dashboard/' - | '/expensive' - | '/dashboard/invoices/$invoiceId' - | '/dashboard/users/user' - | '/dashboard/invoices/' - | '/dashboard/users/' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '' - | '/login' - | '/route-group' - | '/profile' - | '/route-a' - | '/route-b' - | '/dashboard' - | '/expensive' - | '/dashboard/invoices/$invoiceId' - | '/dashboard/users/user' - | '/dashboard/invoices' - | '/dashboard/users' - id: - | '__root__' - | '/' - | '/dashboard' - | '/_auth' - | '/_pathlessLayout' - | '/login' - | '/dashboard/invoices' - | '/dashboard/users' - | '/(this-folder-is-not-in-the-url)/route-group' - | '/_auth/profile' - | '/_pathlessLayout/route-a' - | '/_pathlessLayout/route-b' - | '/dashboard/' - | '/expensive/' - | '/dashboard/invoices/$invoiceId' - | '/dashboard/users/user' - | '/dashboard/invoices/' - | '/dashboard/users/' - fileRoutesById: FileRoutesById -} - -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - DashboardRouteRoute: typeof DashboardRouteRouteWithChildren - AuthRoute: typeof AuthRouteWithChildren - PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren - LoginRoute: typeof LoginRoute - thisFolderIsNotInTheUrlRouteGroupRoute: typeof thisFolderIsNotInTheUrlRouteGroupRoute - ExpensiveIndexRoute: typeof ExpensiveIndexRoute -} - const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, DashboardRouteRoute: DashboardRouteRouteWithChildren, @@ -462,107 +430,6 @@ const rootRouteChildren: RootRouteChildren = { thisFolderIsNotInTheUrlRouteGroupRoute, ExpensiveIndexRoute: ExpensiveIndexRoute, } - -export const routeTree = rootRoute +export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) ._addFileTypes() - -/* ROUTE_MANIFEST_START -{ - "routes": { - "__root__": { - "filePath": "__root.tsx", - "children": [ - "/", - "/dashboard", - "/_auth", - "/_pathlessLayout", - "/login", - "/(this-folder-is-not-in-the-url)/route-group", - "/expensive/" - ] - }, - "/": { - "filePath": "index.tsx" - }, - "/dashboard": { - "filePath": "dashboard.route.tsx", - "children": [ - "/dashboard/invoices", - "/dashboard/users", - "/dashboard/" - ] - }, - "/_auth": { - "filePath": "_auth.tsx", - "children": [ - "/_auth/profile" - ] - }, - "/_pathlessLayout": { - "filePath": "_pathlessLayout.tsx", - "children": [ - "/_pathlessLayout/route-a", - "/_pathlessLayout/route-b" - ] - }, - "/login": { - "filePath": "login.tsx" - }, - "/dashboard/invoices": { - "filePath": "dashboard.invoices.route.tsx", - "parent": "/dashboard", - "children": [ - "/dashboard/invoices/$invoiceId", - "/dashboard/invoices/" - ] - }, - "/dashboard/users": { - "filePath": "dashboard.users.route.tsx", - "parent": "/dashboard", - "children": [ - "/dashboard/users/user", - "/dashboard/users/" - ] - }, - "/(this-folder-is-not-in-the-url)/route-group": { - "filePath": "(this-folder-is-not-in-the-url)/route-group.tsx" - }, - "/_auth/profile": { - "filePath": "_auth.profile.tsx", - "parent": "/_auth" - }, - "/_pathlessLayout/route-a": { - "filePath": "_pathlessLayout.route-a.tsx", - "parent": "/_pathlessLayout" - }, - "/_pathlessLayout/route-b": { - "filePath": "_pathlessLayout.route-b.tsx", - "parent": "/_pathlessLayout" - }, - "/dashboard/": { - "filePath": "dashboard.index.tsx", - "parent": "/dashboard" - }, - "/expensive/": { - "filePath": "expensive/index.tsx" - }, - "/dashboard/invoices/$invoiceId": { - "filePath": "dashboard.invoices.$invoiceId.tsx", - "parent": "/dashboard/invoices" - }, - "/dashboard/users/user": { - "filePath": "dashboard.users.user.tsx", - "parent": "/dashboard/users" - }, - "/dashboard/invoices/": { - "filePath": "dashboard.invoices.index.tsx", - "parent": "/dashboard/invoices" - }, - "/dashboard/users/": { - "filePath": "dashboard.users.index.tsx", - "parent": "/dashboard/users" - } - } -} -ROUTE_MANIFEST_END */ diff --git a/examples/solid/kitchen-sink-file-based/src/styles.css b/examples/solid/kitchen-sink-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/kitchen-sink-file-based/src/styles.css +++ b/examples/solid/kitchen-sink-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/kitchen-sink-file-based/src/vite-env.d.ts b/examples/solid/kitchen-sink-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/kitchen-sink-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/kitchen-sink-file-based/vite.config.js b/examples/solid/kitchen-sink-file-based/vite.config.js index a4b5a71096..ca85ceebb4 100644 --- a/examples/solid/kitchen-sink-file-based/vite.config.js +++ b/examples/solid/kitchen-sink-file-based/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import { tanstackRouter } from '@tanstack/router-plugin/vite' import solidPlugin from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'solid', autoCodeSplitting: true }), solidPlugin(), ], diff --git a/examples/solid/kitchen-sink-solid-query-file-based/.devcontainer/devcontainer.json b/examples/solid/kitchen-sink-solid-query-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/kitchen-sink-solid-query-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/kitchen-sink-solid-query-file-based/package.json b/examples/solid/kitchen-sink-solid-query-file-based/package.json index bcc4f57d0d..25a1c29953 100644 --- a/examples/solid/kitchen-sink-solid-query-file-based/package.json +++ b/examples/solid/kitchen-sink-solid-query-file-based/package.json @@ -9,22 +9,22 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/router-plugin": "^1.142.0", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "immer": "^10.1.1", - "postcss": "^8.5.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^5.7.2", - "vite": "^6.1.0", - "vite-plugin-solid": "^2.11.10" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/kitchen-sink-solid-query-file-based/postcss.config.mjs b/examples/solid/kitchen-sink-solid-query-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/kitchen-sink-solid-query-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/kitchen-sink-solid-query-file-based/src/components/Spinner.tsx b/examples/solid/kitchen-sink-solid-query-file-based/src/components/Spinner.tsx index 15af091123..2f1fa3e523 100644 --- a/examples/solid/kitchen-sink-solid-query-file-based/src/components/Spinner.tsx +++ b/examples/solid/kitchen-sink-solid-query-file-based/src/components/Spinner.tsx @@ -9,7 +9,7 @@ export function Spinner({
    diff --git a/examples/solid/kitchen-sink-solid-query-file-based/src/routeTree.gen.ts b/examples/solid/kitchen-sink-solid-query-file-based/src/routeTree.gen.ts index e366493a81..8235344782 100644 --- a/examples/solid/kitchen-sink-solid-query-file-based/src/routeTree.gen.ts +++ b/examples/solid/kitchen-sink-solid-query-file-based/src/routeTree.gen.ts @@ -9,80 +9,65 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as LoginRouteImport } from './routes/login' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as AuthRouteImport } from './routes/_auth' -import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' import { Route as IndexRouteImport } from './routes/index' -import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' -import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' -import { Route as FooBarRouteImport } from './routes/foo/bar' -import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' -import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +import { Route as LoginRouteImport } from './routes/login' import { Route as AuthProfileRouteImport } from './routes/_auth.profile' -import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' +import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' -import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' +import { Route as FooBarRouteImport } from './routes/foo/bar' import { Route as DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' +import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, +} as any) const DashboardRouteRoute = DashboardRouteRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ - id: '/expensive/', - path: '/expensive/', - getParentRoute: () => rootRouteImport, -} as any) -const DashboardIndexRoute = DashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardRouteRoute, -} as any) -const FooBarRoute = FooBarRouteImport.update({ - id: '/foo/bar', - path: '/foo/bar', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutRoute, -} as any) -const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutRoute, -} as any) const AuthProfileRoute = AuthProfileRouteImport.update({ id: '/profile', path: '/profile', getParentRoute: () => AuthRoute, } as any) -const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ - id: '/users', - path: '/users', +const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const DashboardIndexRoute = DashboardIndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => DashboardRouteRoute, } as any) const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ @@ -90,27 +75,42 @@ const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ path: '/invoices', getParentRoute: () => DashboardRouteRoute, } as any) -const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardUsersRouteRoute, +const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => DashboardRouteRoute, +} as any) +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRouteImport, +} as any) +const FooBarRoute = FooBarRouteImport.update({ + id: '/foo/bar', + path: '/foo/bar', + getParentRoute: () => rootRouteImport, } as any) const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) -const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ - id: '/user', - path: '/user', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) const DashboardInvoicesInvoiceIdRoute = DashboardInvoicesInvoiceIdRouteImport.update({ id: '/$invoiceId', path: '/$invoiceId', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) +const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) +const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ + id: '/user', + path: '/user', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -123,7 +123,7 @@ export interface FileRoutesByFullPath { '/route-b': typeof PathlessLayoutRouteBRoute '/foo/bar': typeof FooBarRoute '/dashboard/': typeof DashboardIndexRoute - '/expensive': typeof ExpensiveIndexRoute + '/expensive/': typeof ExpensiveIndexRoute '/dashboard/invoices/$invoiceId': typeof DashboardInvoicesInvoiceIdRoute '/dashboard/users/user': typeof DashboardUsersUserRoute '/dashboard/invoices/': typeof DashboardInvoicesIndexRoute @@ -176,7 +176,7 @@ export interface FileRouteTypes { | '/route-b' | '/foo/bar' | '/dashboard/' - | '/expensive' + | '/expensive/' | '/dashboard/invoices/$invoiceId' | '/dashboard/users/user' | '/dashboard/invoices/' @@ -228,27 +228,27 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_auth': { id: '/_auth' path: '' - fullPath: '' + fullPath: '/' preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -256,48 +256,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/expensive/': { - id: '/expensive/' - path: '/expensive' - fullPath: '/expensive' - preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/dashboard/': { - id: '/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof DashboardIndexRouteImport - parentRoute: typeof DashboardRouteRoute - } - '/foo/bar': { - id: '/foo/bar' - path: '/foo/bar' - fullPath: '/foo/bar' - preLoaderRoute: typeof FooBarRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/route-b': { - id: '/_pathlessLayout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/_pathlessLayout/route-a': { - id: '/_pathlessLayout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRoute - } '/_auth/profile': { id: '/_auth/profile' path: '/profile' @@ -305,11 +270,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthProfileRouteImport parentRoute: typeof AuthRoute } - '/dashboard/users': { - id: '/dashboard/users' - path: '/users' - fullPath: '/dashboard/users' - preLoaderRoute: typeof DashboardUsersRouteRouteImport + '/_pathlessLayout/route-a': { + id: '/_pathlessLayout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/_pathlessLayout/route-b': { + id: '/_pathlessLayout/route-b' + path: '/route-b' + fullPath: '/route-b' + preLoaderRoute: typeof PathlessLayoutRouteBRouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/dashboard/': { + id: '/dashboard/' + path: '/' + fullPath: '/dashboard/' + preLoaderRoute: typeof DashboardIndexRouteImport parentRoute: typeof DashboardRouteRoute } '/dashboard/invoices': { @@ -319,12 +298,26 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardInvoicesRouteRouteImport parentRoute: typeof DashboardRouteRoute } - '/dashboard/users/': { - id: '/dashboard/users/' - path: '/' - fullPath: '/dashboard/users/' - preLoaderRoute: typeof DashboardUsersIndexRouteImport - parentRoute: typeof DashboardUsersRouteRoute + '/dashboard/users': { + id: '/dashboard/users' + path: '/users' + fullPath: '/dashboard/users' + preLoaderRoute: typeof DashboardUsersRouteRouteImport + parentRoute: typeof DashboardRouteRoute + } + '/expensive/': { + id: '/expensive/' + path: '/expensive' + fullPath: '/expensive/' + preLoaderRoute: typeof ExpensiveIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/foo/bar': { + id: '/foo/bar' + path: '/foo/bar' + fullPath: '/foo/bar' + preLoaderRoute: typeof FooBarRouteImport + parentRoute: typeof rootRouteImport } '/dashboard/invoices/': { id: '/dashboard/invoices/' @@ -333,13 +326,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardInvoicesIndexRouteImport parentRoute: typeof DashboardInvoicesRouteRoute } - '/dashboard/users/user': { - id: '/dashboard/users/user' - path: '/user' - fullPath: '/dashboard/users/user' - preLoaderRoute: typeof DashboardUsersUserRouteImport - parentRoute: typeof DashboardUsersRouteRoute - } '/dashboard/invoices/$invoiceId': { id: '/dashboard/invoices/$invoiceId' path: '/$invoiceId' @@ -347,6 +333,20 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport parentRoute: typeof DashboardInvoicesRouteRoute } + '/dashboard/users/': { + id: '/dashboard/users/' + path: '/' + fullPath: '/dashboard/users/' + preLoaderRoute: typeof DashboardUsersIndexRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } + '/dashboard/users/user': { + id: '/dashboard/users/user' + path: '/user' + fullPath: '/dashboard/users/user' + preLoaderRoute: typeof DashboardUsersUserRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } } } diff --git a/examples/solid/kitchen-sink-solid-query-file-based/src/styles.css b/examples/solid/kitchen-sink-solid-query-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/kitchen-sink-solid-query-file-based/src/styles.css +++ b/examples/solid/kitchen-sink-solid-query-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/kitchen-sink-solid-query-file-based/src/vite-env.d.ts b/examples/solid/kitchen-sink-solid-query-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/kitchen-sink-solid-query-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/kitchen-sink-solid-query-file-based/vite.config.js b/examples/solid/kitchen-sink-solid-query-file-based/vite.config.js index 4af89e7520..378aa5c234 100644 --- a/examples/solid/kitchen-sink-solid-query-file-based/vite.config.js +++ b/examples/solid/kitchen-sink-solid-query-file-based/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { TanStackRouterVite } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), TanStackRouterVite({ target: 'solid', autoCodeSplitting: true }), solid(), ], diff --git a/examples/solid/kitchen-sink-solid-query/.devcontainer/devcontainer.json b/examples/solid/kitchen-sink-solid-query/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/kitchen-sink-solid-query/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/kitchen-sink-solid-query/package.json b/examples/solid/kitchen-sink-solid-query/package.json index cac7db7c48..7a7dc81025 100644 --- a/examples/solid/kitchen-sink-solid-query/package.json +++ b/examples/solid/kitchen-sink-solid-query/package.json @@ -9,21 +9,21 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "immer": "^10.1.1", - "postcss": "^8.5.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^5.7.2", - "vite": "^6.1.0", - "vite-plugin-solid": "^2.11.10" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/kitchen-sink-solid-query/postcss.config.mjs b/examples/solid/kitchen-sink-solid-query/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/kitchen-sink-solid-query/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/kitchen-sink-solid-query/src/main.tsx b/examples/solid/kitchen-sink-solid-query/src/main.tsx index 7c4fe6ea1c..f8790b4a22 100644 --- a/examples/solid/kitchen-sink-solid-query/src/main.tsx +++ b/examples/solid/kitchen-sink-solid-query/src/main.tsx @@ -1088,7 +1088,7 @@ function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) {
    diff --git a/examples/solid/kitchen-sink-solid-query/src/styles.css b/examples/solid/kitchen-sink-solid-query/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/kitchen-sink-solid-query/src/styles.css +++ b/examples/solid/kitchen-sink-solid-query/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/kitchen-sink-solid-query/src/vite-env.d.ts b/examples/solid/kitchen-sink-solid-query/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/kitchen-sink-solid-query/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/kitchen-sink-solid-query/vite.config.js b/examples/solid/kitchen-sink-solid-query/vite.config.js index 05041cc6d8..fb5faf9236 100644 --- a/examples/solid/kitchen-sink-solid-query/vite.config.js +++ b/examples/solid/kitchen-sink-solid-query/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [solid()], + plugins: [tailwindcss(), solid()], }) diff --git a/examples/solid/kitchen-sink/.devcontainer/devcontainer.json b/examples/solid/kitchen-sink/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/kitchen-sink/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/kitchen-sink/package.json b/examples/solid/kitchen-sink/package.json index 57b959ee82..08ad918a60 100644 --- a/examples/solid/kitchen-sink/package.json +++ b/examples/solid/kitchen-sink/package.json @@ -9,19 +9,19 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "immer": "^10.1.1", - "postcss": "^8.5.1", - "solid-js": "^1.9.10", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "solid-js": "^1.9.10", + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/kitchen-sink/postcss.config.mjs b/examples/solid/kitchen-sink/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/kitchen-sink/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/kitchen-sink/src/main.tsx b/examples/solid/kitchen-sink/src/main.tsx index 850e683189..03e8379e40 100644 --- a/examples/solid/kitchen-sink/src/main.tsx +++ b/examples/solid/kitchen-sink/src/main.tsx @@ -1004,7 +1004,7 @@ function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) {
    diff --git a/examples/solid/kitchen-sink/src/styles.css b/examples/solid/kitchen-sink/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/kitchen-sink/src/styles.css +++ b/examples/solid/kitchen-sink/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/kitchen-sink/src/vite-env.d.ts b/examples/solid/kitchen-sink/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/kitchen-sink/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/kitchen-sink/vite.config.js b/examples/solid/kitchen-sink/vite.config.js index 05041cc6d8..fb5faf9236 100644 --- a/examples/solid/kitchen-sink/vite.config.js +++ b/examples/solid/kitchen-sink/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [solid()], + plugins: [tailwindcss(), solid()], }) diff --git a/examples/solid/large-file-based/.devcontainer/devcontainer.json b/examples/solid/large-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/large-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/large-file-based/package.json b/examples/solid/large-file-based/package.json index aa9b34da6b..cd758ab704 100644 --- a/examples/solid/large-file-based/package.json +++ b/examples/solid/large-file-based/package.json @@ -11,20 +11,20 @@ "test:types": "tsc --extendedDiagnostics" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "postcss": "^8.5.1", - "solid-js": "^1.9.10", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "solid-js": "^1.9.10", + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/large-file-based/postcss.config.mjs b/examples/solid/large-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/large-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/large-file-based/src/routeTree.gen.ts b/examples/solid/large-file-based/src/routeTree.gen.ts index d345b69acf..ea7329778c 100644 --- a/examples/solid/large-file-based/src/routeTree.gen.ts +++ b/examples/solid/large-file-based/src/routeTree.gen.ts @@ -9,23 +9,18 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as RelativeRouteImport } from './routes/relative' -import { Route as LinkPropsRouteImport } from './routes/linkProps' -import { Route as AbsoluteRouteImport } from './routes/absolute' -import { Route as SearchRouteRouteImport } from './routes/search/route' -import { Route as ParamsRouteRouteImport } from './routes/params/route' import { Route as IndexRouteImport } from './routes/index' -import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' +import { Route as AbsoluteRouteImport } from './routes/absolute' +import { Route as LinkPropsRouteImport } from './routes/linkProps' +import { Route as ParamsRouteRouteImport } from './routes/params/route' +import { Route as RelativeRouteImport } from './routes/relative' +import { Route as SearchRouteRouteImport } from './routes/search/route' import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' +import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' -const RelativeRoute = RelativeRouteImport.update({ - id: '/relative', - path: '/relative', - getParentRoute: () => rootRouteImport, -} as any) -const LinkPropsRoute = LinkPropsRouteImport.update({ - id: '/linkProps', - path: '/linkProps', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AbsoluteRoute = AbsoluteRouteImport.update({ @@ -33,9 +28,9 @@ const AbsoluteRoute = AbsoluteRouteImport.update({ path: '/absolute', getParentRoute: () => rootRouteImport, } as any) -const SearchRouteRoute = SearchRouteRouteImport.update({ - id: '/search', - path: '/search', +const LinkPropsRoute = LinkPropsRouteImport.update({ + id: '/linkProps', + path: '/linkProps', getParentRoute: () => rootRouteImport, } as any) const ParamsRouteRoute = ParamsRouteRouteImport.update({ @@ -43,21 +38,26 @@ const ParamsRouteRoute = ParamsRouteRouteImport.update({ path: '/params', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RelativeRoute = RelativeRouteImport.update({ + id: '/relative', + path: '/relative', getParentRoute: () => rootRouteImport, } as any) -const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ - id: '/searchPlaceholder', - path: '/searchPlaceholder', - getParentRoute: () => SearchRouteRoute, +const SearchRouteRoute = SearchRouteRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, } as any) const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ id: '/$paramsPlaceholder', path: '/$paramsPlaceholder', getParentRoute: () => ParamsRouteRoute, } as any) +const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ + id: '/searchPlaceholder', + path: '/searchPlaceholder', + getParentRoute: () => SearchRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -134,18 +134,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/relative': { - id: '/relative' - path: '/relative' - fullPath: '/relative' - preLoaderRoute: typeof RelativeRouteImport - parentRoute: typeof rootRouteImport - } - '/linkProps': { - id: '/linkProps' - path: '/linkProps' - fullPath: '/linkProps' - preLoaderRoute: typeof LinkPropsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/absolute': { @@ -155,11 +148,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AbsoluteRouteImport parentRoute: typeof rootRouteImport } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteRouteImport + '/linkProps': { + id: '/linkProps' + path: '/linkProps' + fullPath: '/linkProps' + preLoaderRoute: typeof LinkPropsRouteImport parentRoute: typeof rootRouteImport } '/params': { @@ -169,19 +162,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ParamsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/relative': { + id: '/relative' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeRouteImport parentRoute: typeof rootRouteImport } - '/search/searchPlaceholder': { - id: '/search/searchPlaceholder' - path: '/searchPlaceholder' - fullPath: '/search/searchPlaceholder' - preLoaderRoute: typeof SearchSearchPlaceholderRouteImport - parentRoute: typeof SearchRouteRoute + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteRouteImport + parentRoute: typeof rootRouteImport } '/params/$paramsPlaceholder': { id: '/params/$paramsPlaceholder' @@ -190,6 +183,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport parentRoute: typeof ParamsRouteRoute } + '/search/searchPlaceholder': { + id: '/search/searchPlaceholder' + path: '/searchPlaceholder' + fullPath: '/search/searchPlaceholder' + preLoaderRoute: typeof SearchSearchPlaceholderRouteImport + parentRoute: typeof SearchRouteRoute + } } } diff --git a/examples/solid/large-file-based/src/styles.css b/examples/solid/large-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/large-file-based/src/styles.css +++ b/examples/solid/large-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/large-file-based/src/vite-env.d.ts b/examples/solid/large-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/large-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/large-file-based/vite.config.js b/examples/solid/large-file-based/vite.config.js index 1660a56c17..95863b470a 100644 --- a/examples/solid/large-file-based/vite.config.js +++ b/examples/solid/large-file-based/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'solid', autoCodeSplitting: true }), solid(), ], diff --git a/examples/solid/location-masking/.devcontainer/devcontainer.json b/examples/solid/location-masking/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/location-masking/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/location-masking/package.json b/examples/solid/location-masking/package.json index 17d5e40c65..7d2fbb6756 100644 --- a/examples/solid/location-masking/package.json +++ b/examples/solid/location-masking/package.json @@ -9,18 +9,18 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "solid-js": "^1.9.10", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/solid/location-masking/postcss.config.mjs b/examples/solid/location-masking/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/location-masking/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/location-masking/src/styles.css b/examples/solid/location-masking/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/location-masking/src/styles.css +++ b/examples/solid/location-masking/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/location-masking/src/vite-env.d.ts b/examples/solid/location-masking/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/location-masking/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/location-masking/vite.config.js b/examples/solid/location-masking/vite.config.js index 05041cc6d8..fb5faf9236 100644 --- a/examples/solid/location-masking/vite.config.js +++ b/examples/solid/location-masking/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [solid()], + plugins: [tailwindcss(), solid()], }) diff --git a/examples/solid/navigation-blocking/.devcontainer/devcontainer.json b/examples/solid/navigation-blocking/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/navigation-blocking/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/navigation-blocking/package.json b/examples/solid/navigation-blocking/package.json index d0326eb754..2338d32305 100644 --- a/examples/solid/navigation-blocking/package.json +++ b/examples/solid/navigation-blocking/package.json @@ -9,18 +9,18 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "solid-js": "^1.9.10", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/solid/navigation-blocking/postcss.config.mjs b/examples/solid/navigation-blocking/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/navigation-blocking/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/navigation-blocking/src/styles.css b/examples/solid/navigation-blocking/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/navigation-blocking/src/styles.css +++ b/examples/solid/navigation-blocking/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/navigation-blocking/src/vite-env.d.ts b/examples/solid/navigation-blocking/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/navigation-blocking/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/navigation-blocking/vite.config.js b/examples/solid/navigation-blocking/vite.config.js index 05041cc6d8..fb5faf9236 100644 --- a/examples/solid/navigation-blocking/vite.config.js +++ b/examples/solid/navigation-blocking/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [solid()], + plugins: [tailwindcss(), solid()], }) diff --git a/examples/solid/quickstart-esbuild-file-based/.devcontainer/devcontainer.json b/examples/solid/quickstart-esbuild-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/quickstart-esbuild-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/quickstart-esbuild-file-based/build.js b/examples/solid/quickstart-esbuild-file-based/build.js index f8d31fbbd9..af5e01b4cd 100644 --- a/examples/solid/quickstart-esbuild-file-based/build.js +++ b/examples/solid/quickstart-esbuild-file-based/build.js @@ -14,10 +14,7 @@ const ctx = await esbuild.context({ target: ['esnext'], sourcemap: true, conditions: ['style'], - plugins: [ - solidPlugin(), - tanstackRouter({ target: 'solid', autoCodeSplitting: true }), - ], + plugins: [solidPlugin(), tanstackRouter({ target: 'solid' })], }) if (isDev) { diff --git a/examples/solid/quickstart-esbuild-file-based/package.json b/examples/solid/quickstart-esbuild-file-based/package.json index 621143cafe..9bcc9a08d0 100644 --- a/examples/solid/quickstart-esbuild-file-based/package.json +++ b/examples/solid/quickstart-esbuild-file-based/package.json @@ -9,16 +9,16 @@ "start": "dev" }, "dependencies": { - "@tanstack/router-plugin": "^1.142.0", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "esbuild": "^0.25.0", + "esbuild": "^0.27.4", "esbuild-plugin-solid": "^0.6.0" } } diff --git a/examples/solid/quickstart-esbuild-file-based/src/styles.css b/examples/solid/quickstart-esbuild-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/quickstart-esbuild-file-based/src/styles.css +++ b/examples/solid/quickstart-esbuild-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/quickstart-esbuild-file-based/src/vite-env.d.ts b/examples/solid/quickstart-esbuild-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/quickstart-esbuild-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/quickstart-file-based/.devcontainer/devcontainer.json b/examples/solid/quickstart-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/quickstart-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/quickstart-file-based/package.json b/examples/solid/quickstart-file-based/package.json index 964680999a..920154566d 100644 --- a/examples/solid/quickstart-file-based/package.json +++ b/examples/solid/quickstart-file-based/package.json @@ -9,19 +9,19 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.142.0", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10" + "@tanstack/router-plugin": "^1.169.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/quickstart-file-based/postcss.config.mjs b/examples/solid/quickstart-file-based/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/quickstart-file-based/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/quickstart-file-based/src/routeTree.gen.ts b/examples/solid/quickstart-file-based/src/routeTree.gen.ts index 333a815c38..98df1e83d8 100644 --- a/examples/solid/quickstart-file-based/src/routeTree.gen.ts +++ b/examples/solid/quickstart-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/quickstart-file-based/src/styles.css b/examples/solid/quickstart-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/quickstart-file-based/src/styles.css +++ b/examples/solid/quickstart-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/quickstart-file-based/src/vite-env.d.ts b/examples/solid/quickstart-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/quickstart-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/quickstart-file-based/vite.config.js b/examples/solid/quickstart-file-based/vite.config.js index 74e9ca3db3..79454008ba 100644 --- a/examples/solid/quickstart-file-based/vite.config.js +++ b/examples/solid/quickstart-file-based/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'solid', autoCodeSplitting: true, diff --git a/examples/solid/quickstart-rspack-file-based/.devcontainer/devcontainer.json b/examples/solid/quickstart-rspack-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/quickstart-rspack-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/quickstart-rspack-file-based/package.json b/examples/solid/quickstart-rspack-file-based/package.json index 8b0b2c4004..2d9c886ac3 100644 --- a/examples/solid/quickstart-rspack-file-based/package.json +++ b/examples/solid/quickstart-rspack-file-based/package.json @@ -8,18 +8,19 @@ "preview": "rsbuild preview" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", + "@tailwindcss/postcss": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "postcss": "^8.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { - "@rsbuild/core": "^1.2.4", - "@rsbuild/plugin-babel": "^1.0.6", - "@rsbuild/plugin-solid": "^1.0.6", - "@tanstack/router-plugin": "^1.142.0", - "typescript": "^5.6.2" + "@rsbuild/core": "^2.3.1", + "@rsbuild/plugin-babel": "^1.1.2", + "@rsbuild/plugin-solid": "^1.1.1", + "@tanstack/router-plugin": "^1.169.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2" } } diff --git a/examples/solid/quickstart-rspack-file-based/src/routeTree.gen.ts b/examples/solid/quickstart-rspack-file-based/src/routeTree.gen.ts index 333a815c38..98df1e83d8 100644 --- a/examples/solid/quickstart-rspack-file-based/src/routeTree.gen.ts +++ b/examples/solid/quickstart-rspack-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/quickstart-rspack-file-based/src/styles.css b/examples/solid/quickstart-rspack-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/quickstart-rspack-file-based/src/styles.css +++ b/examples/solid/quickstart-rspack-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/quickstart-rspack-file-based/src/vite-env.d.ts b/examples/solid/quickstart-rspack-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/quickstart-rspack-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/quickstart-webpack-file-based/.devcontainer/devcontainer.json b/examples/solid/quickstart-webpack-file-based/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/quickstart-webpack-file-based/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/quickstart-webpack-file-based/package.json b/examples/solid/quickstart-webpack-file-based/package.json index 16deb9f32b..16167be207 100644 --- a/examples/solid/quickstart-webpack-file-based/package.json +++ b/examples/solid/quickstart-webpack-file-based/package.json @@ -7,16 +7,15 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@babel/core": "^7.28.5", "@babel/preset-typescript": "^7.27.1", - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/router-plugin": "^1.169.0", "babel-loader": "^10.0.0", "babel-preset-solid": "^1.9.10", "css-loader": "^7.1.2", @@ -24,9 +23,10 @@ "postcss": "^8.5.6", "postcss-loader": "^8.2.0", "style-loader": "^4.0.0", - "typescript": "^5.7.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "webpack": "^5.97.1", "webpack-cli": "^5.1.4", - "webpack-dev-server": "^5.2.0" + "webpack-dev-server": "^5.2.4" } } diff --git a/examples/solid/quickstart-webpack-file-based/src/routeTree.gen.ts b/examples/solid/quickstart-webpack-file-based/src/routeTree.gen.ts index 333a815c38..98df1e83d8 100644 --- a/examples/solid/quickstart-webpack-file-based/src/routeTree.gen.ts +++ b/examples/solid/quickstart-webpack-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/quickstart-webpack-file-based/src/styles.css b/examples/solid/quickstart-webpack-file-based/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/quickstart-webpack-file-based/src/styles.css +++ b/examples/solid/quickstart-webpack-file-based/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/quickstart-webpack-file-based/src/vite-env.d.ts b/examples/solid/quickstart-webpack-file-based/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/quickstart-webpack-file-based/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/quickstart/.devcontainer/devcontainer.json b/examples/solid/quickstart/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/quickstart/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/quickstart/package.json b/examples/solid/quickstart/package.json index 780c768ebd..454382e8cc 100644 --- a/examples/solid/quickstart/package.json +++ b/examples/solid/quickstart/package.json @@ -9,16 +9,16 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/solid/quickstart/postcss.config.mjs b/examples/solid/quickstart/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/quickstart/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/quickstart/src/styles.css b/examples/solid/quickstart/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/quickstart/src/styles.css +++ b/examples/solid/quickstart/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/quickstart/src/vite-env.d.ts b/examples/solid/quickstart/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/quickstart/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/quickstart/vite.config.js b/examples/solid/quickstart/vite.config.js index 05041cc6d8..fb5faf9236 100644 --- a/examples/solid/quickstart/vite.config.js +++ b/examples/solid/quickstart/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [solid()], + plugins: [tailwindcss(), solid()], }) diff --git a/examples/solid/router-monorepo-simple-lazy/.devcontainer/devcontainer.json b/examples/solid/router-monorepo-simple-lazy/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/router-monorepo-simple-lazy/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/router-monorepo-simple-lazy/package.json b/examples/solid/router-monorepo-simple-lazy/package.json index da69976949..1d60ab2765 100644 --- a/examples/solid/router-monorepo-simple-lazy/package.json +++ b/examples/solid/router-monorepo-simple-lazy/package.json @@ -8,17 +8,18 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", "redaxios": "^0.5.1" }, "devDependencies": { "@types/node": "^22.7.4", - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" }, "keywords": [], diff --git a/examples/solid/router-monorepo-simple-lazy/packages/app/package.json b/examples/solid/router-monorepo-simple-lazy/packages/app/package.json index 329a1c0033..a2e018fa96 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/app/package.json +++ b/examples/solid/router-monorepo-simple-lazy/packages/app/package.json @@ -17,14 +17,14 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "typescript": "^5.7.2", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", - "autoprefixer": "^10.4.20", - "tailwindcss": "^3.4.17", - "vite": "^7.1.7", - "vite-plugin-dts": "^4.5.4" + "@vitejs/plugin-react": "^6.0.1", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "@tanstack/solid-router-devtools": "^1.167.3", + "tailwindcss": "^4.2.2", + "vite": "^8.0.14", + "vite-plugin-dts": "^4.5.4", + "@tailwindcss/vite": "^4.2.2" }, "nx": { "targets": { diff --git a/examples/solid/router-monorepo-simple-lazy/packages/app/src/style.css b/examples/solid/router-monorepo-simple-lazy/packages/app/src/style.css index 0b8e317099..868812af60 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/app/src/style.css +++ b/examples/solid/router-monorepo-simple-lazy/packages/app/src/style.css @@ -1,6 +1,24 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; +@import 'tailwindcss' source('../'); + +@source '../../post-feature/src/**/*.{js,jsx,ts,tsx}'; + +/* + The default border color has changed to `currentcolor` in Tailwind CSS v4, + so we've added these compatibility styles to make sure everything still + looks the same as it did with Tailwind CSS v3. + + If we ever want to remove these styles, we need to add an explicit border + color utility to any element that depends on these defaults. +*/ +@layer base { + *, + ::after, + ::before, + ::backdrop, + ::file-selector-button { + border-color: var(--color-gray-200, currentcolor); + } +} html { color-scheme: light dark; diff --git a/examples/solid/router-monorepo-simple-lazy/packages/app/vite.config.ts b/examples/solid/router-monorepo-simple-lazy/packages/app/vite.config.ts index 5ee9bc9668..474d3104bd 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/app/vite.config.ts +++ b/examples/solid/router-monorepo-simple-lazy/packages/app/vite.config.ts @@ -3,6 +3,7 @@ import dts from 'vite-plugin-dts' import * as path from 'node:path' import { fileURLToPath } from 'node:url' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) @@ -21,6 +22,7 @@ export default defineConfig({ host: 'localhost', }, plugins: [ + tailwindcss(), dts({ entryRoot: 'src', tsconfigPath: path.join(__dirname, 'tsconfig.json'), diff --git a/examples/solid/router-monorepo-simple-lazy/packages/post-feature/package.json b/examples/solid/router-monorepo-simple-lazy/packages/post-feature/package.json index 2d6e1ef569..849be06ce6 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/post-feature/package.json +++ b/examples/solid/router-monorepo-simple-lazy/packages/post-feature/package.json @@ -21,9 +21,10 @@ "solid-js": "^1.9.10" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/solid/router-monorepo-simple-lazy/packages/post-feature/vite.config.ts b/examples/solid/router-monorepo-simple-lazy/packages/post-feature/vite.config.ts index 167abe6350..e5ab1b29f5 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/post-feature/vite.config.ts +++ b/examples/solid/router-monorepo-simple-lazy/packages/post-feature/vite.config.ts @@ -28,7 +28,7 @@ export default defineConfig({ name: 'post-feature', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: [ 'react', diff --git a/examples/solid/router-monorepo-simple-lazy/packages/router/package.json b/examples/solid/router-monorepo-simple-lazy/packages/router/package.json index aa14cf184f..0672c42931 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/solid/router-monorepo-simple-lazy/packages/router/package.json @@ -8,17 +8,18 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.141.0", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/history": "^1.162.5", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "redaxios": "^0.5.1", - "zod": "^3.24.2", + "zod": "^4.4.3", "solid-js": "^1.9.10" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/solid/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts b/examples/solid/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts index e8f1a5370b..8760312d24 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts +++ b/examples/solid/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as PostIdRouteImport } from './routes/$postId' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostIdRouteImport } from './routes/$postId' -const PostIdRoute = PostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostIdRoute = PostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/$postId': { - id: '/$postId' - path: '/$postId' - fullPath: '/$postId' - preLoaderRoute: typeof PostIdRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/$postId': { + id: '/$postId' + path: '/$postId' + fullPath: '/$postId' + preLoaderRoute: typeof PostIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/router-monorepo-simple-lazy/packages/router/vite.config.ts b/examples/solid/router-monorepo-simple-lazy/packages/router/vite.config.ts index 42ec59324c..018ebfd3d5 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/router/vite.config.ts +++ b/examples/solid/router-monorepo-simple-lazy/packages/router/vite.config.ts @@ -29,7 +29,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: ['solid-js', 'solid-js/web', '@tanstack/solid-router'], }, diff --git a/examples/solid/router-monorepo-simple/.devcontainer/devcontainer.json b/examples/solid/router-monorepo-simple/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/router-monorepo-simple/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/router-monorepo-simple/package.json b/examples/solid/router-monorepo-simple/package.json index c5d67f2a68..3770256692 100644 --- a/examples/solid/router-monorepo-simple/package.json +++ b/examples/solid/router-monorepo-simple/package.json @@ -8,17 +8,18 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", "redaxios": "^0.5.1" }, "devDependencies": { "@types/node": "^22.7.4", - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" }, "keywords": [], diff --git a/examples/solid/router-monorepo-simple/packages/app/package.json b/examples/solid/router-monorepo-simple/packages/app/package.json index 15fa218eae..61234ac455 100644 --- a/examples/solid/router-monorepo-simple/packages/app/package.json +++ b/examples/solid/router-monorepo-simple/packages/app/package.json @@ -14,14 +14,14 @@ "solid-js": "^1.9.10" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "@tanstack/solid-router-devtools": "^1.141.8", - "vite": "^7.1.7", - "postcss": "^8.5.1", - "autoprefixer": "^10.4.20", - "tailwindcss": "^3.4.17", - "vite-plugin-dts": "^4.5.4" + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "@tanstack/solid-router-devtools": "^1.167.3", + "vite": "^8.0.14", + "tailwindcss": "^4.2.2", + "vite-plugin-dts": "^4.5.4", + "@tailwindcss/vite": "^4.2.2" }, "nx": { "targets": { diff --git a/examples/solid/router-monorepo-simple/packages/app/src/style.css b/examples/solid/router-monorepo-simple/packages/app/src/style.css index 0b8e317099..868812af60 100644 --- a/examples/solid/router-monorepo-simple/packages/app/src/style.css +++ b/examples/solid/router-monorepo-simple/packages/app/src/style.css @@ -1,6 +1,24 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; +@import 'tailwindcss' source('../'); + +@source '../../post-feature/src/**/*.{js,jsx,ts,tsx}'; + +/* + The default border color has changed to `currentcolor` in Tailwind CSS v4, + so we've added these compatibility styles to make sure everything still + looks the same as it did with Tailwind CSS v3. + + If we ever want to remove these styles, we need to add an explicit border + color utility to any element that depends on these defaults. +*/ +@layer base { + *, + ::after, + ::before, + ::backdrop, + ::file-selector-button { + border-color: var(--color-gray-200, currentcolor); + } +} html { color-scheme: light dark; diff --git a/examples/solid/router-monorepo-simple/packages/app/vite.config.ts b/examples/solid/router-monorepo-simple/packages/app/vite.config.ts index da736445be..da34410003 100644 --- a/examples/solid/router-monorepo-simple/packages/app/vite.config.ts +++ b/examples/solid/router-monorepo-simple/packages/app/vite.config.ts @@ -3,6 +3,7 @@ import * as path from 'node:path' import { defineConfig } from 'vite' import dts from 'vite-plugin-dts' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) @@ -21,6 +22,7 @@ export default defineConfig({ host: 'localhost', }, plugins: [ + tailwindcss(), dts({ entryRoot: 'src', tsconfigPath: path.join(__dirname, 'tsconfig.json'), diff --git a/examples/solid/router-monorepo-simple/packages/post-feature/package.json b/examples/solid/router-monorepo-simple/packages/post-feature/package.json index 8dbebe9ebd..eb8005b953 100644 --- a/examples/solid/router-monorepo-simple/packages/post-feature/package.json +++ b/examples/solid/router-monorepo-simple/packages/post-feature/package.json @@ -12,9 +12,10 @@ "solid-js": "^1.9.10" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/solid/router-monorepo-simple/packages/post-feature/vite.config.ts b/examples/solid/router-monorepo-simple/packages/post-feature/vite.config.ts index 74360e2dd0..6593e68056 100644 --- a/examples/solid/router-monorepo-simple/packages/post-feature/vite.config.ts +++ b/examples/solid/router-monorepo-simple/packages/post-feature/vite.config.ts @@ -29,7 +29,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: [ 'solid-js', diff --git a/examples/solid/router-monorepo-simple/packages/router/package.json b/examples/solid/router-monorepo-simple/packages/router/package.json index b239742528..ca08511d3e 100644 --- a/examples/solid/router-monorepo-simple/packages/router/package.json +++ b/examples/solid/router-monorepo-simple/packages/router/package.json @@ -8,17 +8,18 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.141.0", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/history": "^1.162.5", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "redaxios": "^0.5.1", - "zod": "^3.24.2", + "zod": "^4.4.3", "solid-js": "^1.9.10" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/solid/router-monorepo-simple/packages/router/src/routeTree.gen.ts b/examples/solid/router-monorepo-simple/packages/router/src/routeTree.gen.ts index e8f1a5370b..8760312d24 100644 --- a/examples/solid/router-monorepo-simple/packages/router/src/routeTree.gen.ts +++ b/examples/solid/router-monorepo-simple/packages/router/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as PostIdRouteImport } from './routes/$postId' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostIdRouteImport } from './routes/$postId' -const PostIdRoute = PostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostIdRoute = PostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/$postId': { - id: '/$postId' - path: '/$postId' - fullPath: '/$postId' - preLoaderRoute: typeof PostIdRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/$postId': { + id: '/$postId' + path: '/$postId' + fullPath: '/$postId' + preLoaderRoute: typeof PostIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/router-monorepo-simple/packages/router/vite.config.ts b/examples/solid/router-monorepo-simple/packages/router/vite.config.ts index 42ec59324c..018ebfd3d5 100644 --- a/examples/solid/router-monorepo-simple/packages/router/vite.config.ts +++ b/examples/solid/router-monorepo-simple/packages/router/vite.config.ts @@ -29,7 +29,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: ['solid-js', 'solid-js/web', '@tanstack/solid-router'], }, diff --git a/examples/solid/router-monorepo-solid-query/.devcontainer/devcontainer.json b/examples/solid/router-monorepo-solid-query/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/router-monorepo-solid-query/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/router-monorepo-solid-query/package.json b/examples/solid/router-monorepo-solid-query/package.json index bb023f0d0e..3d9fd2e2d0 100644 --- a/examples/solid/router-monorepo-solid-query/package.json +++ b/examples/solid/router-monorepo-solid-query/package.json @@ -12,17 +12,18 @@ "dependencies": { "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", "redaxios": "^0.5.1" }, "devDependencies": { "@types/node": "^22.10.2", - "typescript": "^5.7.2", - "vite-plugin-solid": "^2.11.10", - "vite": "^7.1.7", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite-plugin-solid": "^2.11.11", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" }, "keywords": [], diff --git a/examples/solid/router-monorepo-solid-query/packages/app/package.json b/examples/solid/router-monorepo-solid-query/packages/app/package.json index 461c99b917..76bb059de5 100644 --- a/examples/solid/router-monorepo-solid-query/packages/app/package.json +++ b/examples/solid/router-monorepo-solid-query/packages/app/package.json @@ -15,14 +15,14 @@ "solid-js": "^1.9.10" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", - "autoprefixer": "^10.4.20", - "tailwindcss": "^3.4.17", - "vite": "^7.1.7", - "vite-plugin-dts": "^4.5.4" + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "@tanstack/solid-router-devtools": "^1.167.3", + "tailwindcss": "^4.2.2", + "vite": "^8.0.14", + "vite-plugin-dts": "^4.5.4", + "@tailwindcss/vite": "^4.2.2" }, "nx": { "targets": { diff --git a/examples/solid/router-monorepo-solid-query/packages/app/src/style.css b/examples/solid/router-monorepo-solid-query/packages/app/src/style.css index 0b8e317099..868812af60 100644 --- a/examples/solid/router-monorepo-solid-query/packages/app/src/style.css +++ b/examples/solid/router-monorepo-solid-query/packages/app/src/style.css @@ -1,6 +1,24 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; +@import 'tailwindcss' source('../'); + +@source '../../post-feature/src/**/*.{js,jsx,ts,tsx}'; + +/* + The default border color has changed to `currentcolor` in Tailwind CSS v4, + so we've added these compatibility styles to make sure everything still + looks the same as it did with Tailwind CSS v3. + + If we ever want to remove these styles, we need to add an explicit border + color utility to any element that depends on these defaults. +*/ +@layer base { + *, + ::after, + ::before, + ::backdrop, + ::file-selector-button { + border-color: var(--color-gray-200, currentcolor); + } +} html { color-scheme: light dark; diff --git a/examples/solid/router-monorepo-solid-query/packages/app/vite.config.ts b/examples/solid/router-monorepo-solid-query/packages/app/vite.config.ts index da736445be..da34410003 100644 --- a/examples/solid/router-monorepo-solid-query/packages/app/vite.config.ts +++ b/examples/solid/router-monorepo-solid-query/packages/app/vite.config.ts @@ -3,6 +3,7 @@ import * as path from 'node:path' import { defineConfig } from 'vite' import dts from 'vite-plugin-dts' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) @@ -21,6 +22,7 @@ export default defineConfig({ host: 'localhost', }, plugins: [ + tailwindcss(), dts({ entryRoot: 'src', tsconfigPath: path.join(__dirname, 'tsconfig.json'), diff --git a/examples/solid/router-monorepo-solid-query/packages/post-feature/package.json b/examples/solid/router-monorepo-solid-query/packages/post-feature/package.json index c693e3d0a4..39b57c7dfa 100644 --- a/examples/solid/router-monorepo-solid-query/packages/post-feature/package.json +++ b/examples/solid/router-monorepo-solid-query/packages/post-feature/package.json @@ -14,9 +14,10 @@ "solid-js": "^1.9.10" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/solid/router-monorepo-solid-query/packages/post-feature/vite.config.ts b/examples/solid/router-monorepo-solid-query/packages/post-feature/vite.config.ts index a195b2687d..28a231eb39 100644 --- a/examples/solid/router-monorepo-solid-query/packages/post-feature/vite.config.ts +++ b/examples/solid/router-monorepo-solid-query/packages/post-feature/vite.config.ts @@ -29,7 +29,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: [ 'solid-js', diff --git a/examples/solid/router-monorepo-solid-query/packages/post-query/package.json b/examples/solid/router-monorepo-solid-query/packages/post-query/package.json index dd18b955bc..8e3a4b0e71 100644 --- a/examples/solid/router-monorepo-solid-query/packages/post-query/package.json +++ b/examples/solid/router-monorepo-solid-query/packages/post-query/package.json @@ -10,11 +10,12 @@ "dependencies": { "@tanstack/solid-query": "^5.90.9", "redaxios": "^0.5.1", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/solid/router-monorepo-solid-query/packages/post-query/vite.config.ts b/examples/solid/router-monorepo-solid-query/packages/post-query/vite.config.ts index ca7192f9e9..0176645332 100644 --- a/examples/solid/router-monorepo-solid-query/packages/post-query/vite.config.ts +++ b/examples/solid/router-monorepo-solid-query/packages/post-query/vite.config.ts @@ -27,7 +27,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: [ 'solid-js', diff --git a/examples/solid/router-monorepo-solid-query/packages/router/package.json b/examples/solid/router-monorepo-solid-query/packages/router/package.json index af333238f0..93943a1df8 100644 --- a/examples/solid/router-monorepo-solid-query/packages/router/package.json +++ b/examples/solid/router-monorepo-solid-query/packages/router/package.json @@ -8,19 +8,20 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.141.0", + "@tanstack/history": "^1.162.5", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "@router-solid-mono-solid-query/post-query": "workspace:*", "redaxios": "^0.5.1", - "zod": "^3.24.2", + "zod": "^4.4.3", "solid-js": "^1.9.10" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7", + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } } diff --git a/examples/solid/router-monorepo-solid-query/packages/router/src/routeTree.gen.ts b/examples/solid/router-monorepo-solid-query/packages/router/src/routeTree.gen.ts index e8f1a5370b..8760312d24 100644 --- a/examples/solid/router-monorepo-solid-query/packages/router/src/routeTree.gen.ts +++ b/examples/solid/router-monorepo-solid-query/packages/router/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as PostIdRouteImport } from './routes/$postId' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostIdRouteImport } from './routes/$postId' -const PostIdRoute = PostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostIdRoute = PostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/$postId': { - id: '/$postId' - path: '/$postId' - fullPath: '/$postId' - preLoaderRoute: typeof PostIdRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/$postId': { + id: '/$postId' + path: '/$postId' + fullPath: '/$postId' + preLoaderRoute: typeof PostIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/router-monorepo-solid-query/packages/router/src/router.tsx b/examples/solid/router-monorepo-solid-query/packages/router/src/router.tsx index 6153a54a8b..99874f49e5 100644 --- a/examples/solid/router-monorepo-solid-query/packages/router/src/router.tsx +++ b/examples/solid/router-monorepo-solid-query/packages/router/src/router.tsx @@ -1,4 +1,3 @@ -import React from 'react' import { createRouter } from '@tanstack/solid-router' // Import the generated route tree diff --git a/examples/solid/router-monorepo-solid-query/packages/router/vite.config.ts b/examples/solid/router-monorepo-solid-query/packages/router/vite.config.ts index 438ad4b27f..7d65f1b5f5 100644 --- a/examples/solid/router-monorepo-solid-query/packages/router/vite.config.ts +++ b/examples/solid/router-monorepo-solid-query/packages/router/vite.config.ts @@ -31,7 +31,7 @@ export default defineConfig({ fileName: 'index', formats: ['es'], }, - rollupOptions: { + rolldownOptions: { // External packages that should not be bundled into your library. external: [ 'solid-js', diff --git a/examples/solid/scroll-restoration/.devcontainer/devcontainer.json b/examples/solid/scroll-restoration/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/scroll-restoration/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/scroll-restoration/package.json b/examples/solid/scroll-restoration/package.json index 0ccd27604d..eaa5a5aaea 100644 --- a/examples/solid/scroll-restoration/package.json +++ b/examples/solid/scroll-restoration/package.json @@ -9,17 +9,17 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "@tanstack/solid-virtual": "^3.13.0", - "postcss": "^8.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17" + "tailwindcss": "^4.2.2" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" } } diff --git a/examples/solid/scroll-restoration/postcss.config.mjs b/examples/solid/scroll-restoration/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/scroll-restoration/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/scroll-restoration/src/styles.css b/examples/solid/scroll-restoration/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/scroll-restoration/src/styles.css +++ b/examples/solid/scroll-restoration/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/scroll-restoration/src/vite-env.d.ts b/examples/solid/scroll-restoration/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/scroll-restoration/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/scroll-restoration/vite.config.js b/examples/solid/scroll-restoration/vite.config.js index 05041cc6d8..fb5faf9236 100644 --- a/examples/solid/scroll-restoration/vite.config.js +++ b/examples/solid/scroll-restoration/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [solid()], + plugins: [tailwindcss(), solid()], }) diff --git a/examples/solid/search-validator-adapters/.devcontainer/devcontainer.json b/examples/solid/search-validator-adapters/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/search-validator-adapters/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/search-validator-adapters/package.json b/examples/solid/search-validator-adapters/package.json index 26ee464f68..59991edb36 100644 --- a/examples/solid/search-validator-adapters/package.json +++ b/examples/solid/search-validator-adapters/package.json @@ -4,32 +4,34 @@ "type": "module", "scripts": { "dev": "vite --port 3000", - "build": "vite build && tsc --noEmit", + "build": "vite build && NODE_OPTIONS=--max-old-space-size=4096 tsc --noEmit", "preview": "vite preview", "start": "vite", "test:unit": "vitest" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/arktype-adapter": "^1.141.8", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/arktype-adapter": "^1.167.0", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "@tanstack/valibot-adapter": "^1.141.8", - "@tanstack/zod-adapter": "^1.141.8", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/valibot-adapter": "^1.167.0", + "@tanstack/zod-adapter": "^1.167.0", "arktype": "^2.1.7", - "postcss": "^8.5.1", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.17", + "tailwindcss": "^4.2.2", "valibot": "1.0.0-beta.15", "zod": "^3.24.2" }, "devDependencies": { - "@testing-library/jest-dom": "^6.6.3", + "@testing-library/jest-dom": "^7.0.1", "@solidjs/testing-library": "^0.8.10", - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "jsdom": "^27.0.0", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vitest": "^5.0.4" } } diff --git a/examples/solid/search-validator-adapters/postcss.config.mjs b/examples/solid/search-validator-adapters/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/search-validator-adapters/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/search-validator-adapters/src/routeTree.gen.ts b/examples/solid/search-validator-adapters/src/routeTree.gen.ts index 3226feeab2..4cb97b08e9 100644 --- a/examples/solid/search-validator-adapters/src/routeTree.gen.ts +++ b/examples/solid/search-validator-adapters/src/routeTree.gen.ts @@ -8,40 +8,38 @@ // You should NOT make any changes in this file as it will be overwritten. // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. -import type { CreateFileRoute, FileRoutesByPath } from '@tanstack/solid-router' - import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersZodIndexRouteImport } from './routes/users/zod.index' -import { Route as UsersValibotIndexRouteImport } from './routes/users/valibot.index' import { Route as UsersArktypeIndexRouteImport } from './routes/users/arktype.index' +import { Route as UsersValibotIndexRouteImport } from './routes/users/valibot.index' +import { Route as UsersZodIndexRouteImport } from './routes/users/zod.index' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ - id: '/users/zod/', - path: '/users/zod/', - getParentRoute: () => rootRouteImport, -} as any) -const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ - id: '/users/valibot/', - path: '/users/valibot/', - getParentRoute: () => rootRouteImport, -} as any) const UsersArktypeIndexRoute = UsersArktypeIndexRouteImport.update({ id: '/users/arktype/', path: '/users/arktype/', getParentRoute: () => rootRouteImport, } as any) +const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ + id: '/users/valibot/', + path: '/users/valibot/', + getParentRoute: () => rootRouteImport, +} as any) +const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ + id: '/users/zod/', + path: '/users/zod/', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute - '/users/arktype': typeof UsersArktypeIndexRoute - '/users/valibot': typeof UsersValibotIndexRoute - '/users/zod': typeof UsersZodIndexRoute + '/users/arktype/': typeof UsersArktypeIndexRoute + '/users/valibot/': typeof UsersValibotIndexRoute + '/users/zod/': typeof UsersZodIndexRoute } export interface FileRoutesByTo { '/': typeof IndexRoute @@ -58,7 +56,7 @@ export interface FileRoutesById { } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/users/arktype' | '/users/valibot' | '/users/zod' + fullPaths: '/' | '/users/arktype/' | '/users/valibot/' | '/users/zod/' fileRoutesByTo: FileRoutesByTo to: '/' | '/users/arktype' | '/users/valibot' | '/users/zod' id: '__root__' | '/' | '/users/arktype/' | '/users/valibot/' | '/users/zod/' @@ -80,67 +78,30 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/users/zod/': { - id: '/users/zod/' - path: '/users/zod' - fullPath: '/users/zod' - preLoaderRoute: typeof UsersZodIndexRouteImport + '/users/arktype/': { + id: '/users/arktype/' + path: '/users/arktype' + fullPath: '/users/arktype/' + preLoaderRoute: typeof UsersArktypeIndexRouteImport parentRoute: typeof rootRouteImport } '/users/valibot/': { id: '/users/valibot/' path: '/users/valibot' - fullPath: '/users/valibot' + fullPath: '/users/valibot/' preLoaderRoute: typeof UsersValibotIndexRouteImport parentRoute: typeof rootRouteImport } - '/users/arktype/': { - id: '/users/arktype/' - path: '/users/arktype' - fullPath: '/users/arktype' - preLoaderRoute: typeof UsersArktypeIndexRouteImport + '/users/zod/': { + id: '/users/zod/' + path: '/users/zod' + fullPath: '/users/zod/' + preLoaderRoute: typeof UsersZodIndexRouteImport parentRoute: typeof rootRouteImport } } } -declare module './routes/index' { - const createFileRoute: CreateFileRoute< - '/', - FileRoutesByPath['/']['parentRoute'], - FileRoutesByPath['/']['id'], - FileRoutesByPath['/']['path'], - FileRoutesByPath['/']['fullPath'] - > -} -declare module './routes/users/arktype.index' { - const createFileRoute: CreateFileRoute< - '/users/arktype/', - FileRoutesByPath['/users/arktype/']['parentRoute'], - FileRoutesByPath['/users/arktype/']['id'], - FileRoutesByPath['/users/arktype/']['path'], - FileRoutesByPath['/users/arktype/']['fullPath'] - > -} -declare module './routes/users/valibot.index' { - const createFileRoute: CreateFileRoute< - '/users/valibot/', - FileRoutesByPath['/users/valibot/']['parentRoute'], - FileRoutesByPath['/users/valibot/']['id'], - FileRoutesByPath['/users/valibot/']['path'], - FileRoutesByPath['/users/valibot/']['fullPath'] - > -} -declare module './routes/users/zod.index' { - const createFileRoute: CreateFileRoute< - '/users/zod/', - FileRoutesByPath['/users/zod/']['parentRoute'], - FileRoutesByPath['/users/zod/']['id'], - FileRoutesByPath['/users/zod/']['path'], - FileRoutesByPath['/users/zod/']['fullPath'] - > -} - const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, UsersArktypeIndexRoute: UsersArktypeIndexRoute, diff --git a/examples/solid/search-validator-adapters/src/routes/index.tsx b/examples/solid/search-validator-adapters/src/routes/index.tsx index 9a47bda715..33041cecaf 100644 --- a/examples/solid/search-validator-adapters/src/routes/index.tsx +++ b/examples/solid/search-validator-adapters/src/routes/index.tsx @@ -1,3 +1,4 @@ +import { createFileRoute } from '@tanstack/solid-router' import { Header } from '../components/Header' import { Content } from '../components/Content' @@ -10,6 +11,6 @@ export const Index = () => { ) } -export const Route = createFileRoute({ +export const Route = createFileRoute('/')({ component: Index, }) diff --git a/examples/solid/search-validator-adapters/src/routes/users/arktype.index.tsx b/examples/solid/search-validator-adapters/src/routes/users/arktype.index.tsx index cd31ae9955..560354627c 100644 --- a/examples/solid/search-validator-adapters/src/routes/users/arktype.index.tsx +++ b/examples/solid/search-validator-adapters/src/routes/users/arktype.index.tsx @@ -1,4 +1,4 @@ -import { useNavigate } from '@tanstack/solid-router' +import { useNavigate, createFileRoute } from '@tanstack/solid-router' import { type } from 'arktype' import { Suspense } from 'solid-js' import { Header } from '../../components/Header' @@ -30,7 +30,7 @@ const search = type({ search: 'string = ""', }) -export const Route = createFileRoute({ +export const Route = createFileRoute('/users/arktype/')({ validateSearch: search, loaderDeps: (opt) => ({ search: opt.search }), loader: (opt) => { diff --git a/examples/solid/search-validator-adapters/src/routes/users/valibot.index.tsx b/examples/solid/search-validator-adapters/src/routes/users/valibot.index.tsx index 8358cdb89f..f9041c6126 100644 --- a/examples/solid/search-validator-adapters/src/routes/users/valibot.index.tsx +++ b/examples/solid/search-validator-adapters/src/routes/users/valibot.index.tsx @@ -1,4 +1,4 @@ -import { useNavigate } from '@tanstack/solid-router' +import { useNavigate, createFileRoute } from '@tanstack/solid-router' import * as v from 'valibot' import { Suspense } from 'solid-js' import { Header } from '../../components/Header' @@ -26,7 +26,7 @@ const Valibot = () => { ) } -export const Route = createFileRoute({ +export const Route = createFileRoute('/users/valibot/')({ validateSearch: v.object({ search: v.fallback(v.optional(v.string(), ''), ''), }), diff --git a/examples/solid/search-validator-adapters/src/routes/users/zod.index.tsx b/examples/solid/search-validator-adapters/src/routes/users/zod.index.tsx index 6c8654f291..8568476756 100644 --- a/examples/solid/search-validator-adapters/src/routes/users/zod.index.tsx +++ b/examples/solid/search-validator-adapters/src/routes/users/zod.index.tsx @@ -1,4 +1,4 @@ -import { useNavigate } from '@tanstack/solid-router' +import { useNavigate, createFileRoute } from '@tanstack/solid-router' import { fallback, zodValidator } from '@tanstack/zod-adapter' import { z } from 'zod' import { Suspense } from 'solid-js' @@ -7,6 +7,11 @@ import { Users, usersQueryOptions } from '../../components/Users' import { Content } from '../../components/Content' import { Search } from '../../components/Search' +const fallbackString = fallback as unknown as ( + schema: z.ZodString, + fallback: string, +) => z.ZodType + const Zod = () => { const search = Route.useSearch({ select: (search) => search.search ?? '', @@ -29,10 +34,10 @@ const Zod = () => { ) } -export const Route = createFileRoute({ +export const Route = createFileRoute('/users/zod/')({ validateSearch: zodValidator( z.object({ - search: fallback(z.string().optional(), undefined), + search: fallbackString(z.string(), '').default(''), }), ), loaderDeps: (opt) => ({ search: opt.search }), diff --git a/examples/solid/search-validator-adapters/src/styles.css b/examples/solid/search-validator-adapters/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/search-validator-adapters/src/styles.css +++ b/examples/solid/search-validator-adapters/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/search-validator-adapters/src/vite-env.d.ts b/examples/solid/search-validator-adapters/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/search-validator-adapters/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/search-validator-adapters/tests/arktype.test.tsx b/examples/solid/search-validator-adapters/tests/arktype.test.tsx index 7e130132bd..f22a359995 100644 --- a/examples/solid/search-validator-adapters/tests/arktype.test.tsx +++ b/examples/solid/search-validator-adapters/tests/arktype.test.tsx @@ -8,7 +8,6 @@ import { createRouter, } from '@tanstack/solid-router' -import '@testing-library/jest-dom/vitest' import { type } from 'arktype' test('can navigate to the route', async () => { @@ -26,7 +25,7 @@ test('can navigate to the route', async () => { return (
    {search().search}
    - + Update
    diff --git a/examples/solid/search-validator-adapters/tests/jest-dom.setup.ts b/examples/solid/search-validator-adapters/tests/jest-dom.setup.ts new file mode 100644 index 0000000000..8f7cbf15be --- /dev/null +++ b/examples/solid/search-validator-adapters/tests/jest-dom.setup.ts @@ -0,0 +1,18 @@ +import * as jestDomMatchers from '@testing-library/jest-dom/matchers' +import { expect } from 'vitest' +import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' + +// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged +// and released, and go back to `import '@testing-library/jest-dom/vitest'`. +// That entry imports `vitest` from its own install location, which can resolve +// a different Vitest copy than the one running these tests, and its types +// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. +// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting +// `@testing-library/jest-dom/vitest` when a setup file path contains it. +expect.extend(jestDomMatchers) + +declare module 'vitest' { + // Type parameter names must match Vitest's declaration for the interfaces to merge. + // eslint-disable-next-line @typescript-eslint/naming-convention + interface Matchers extends TestingLibraryMatchers {} +} diff --git a/examples/solid/search-validator-adapters/tests/valibot.test.tsx b/examples/solid/search-validator-adapters/tests/valibot.test.tsx index 882a73d574..8594c1cb29 100644 --- a/examples/solid/search-validator-adapters/tests/valibot.test.tsx +++ b/examples/solid/search-validator-adapters/tests/valibot.test.tsx @@ -8,7 +8,6 @@ import { createRouter, } from '@tanstack/solid-router' import * as v from 'valibot' -import '@testing-library/jest-dom/vitest' test('can navigate to the route', async () => { const rootRoute = createRootRoute() @@ -25,7 +24,7 @@ test('can navigate to the route', async () => { return (
    {search().search}
    - + Update
    diff --git a/examples/solid/search-validator-adapters/vite.config.ts b/examples/solid/search-validator-adapters/vite.config.ts index 0384779545..4e05d81e75 100644 --- a/examples/solid/search-validator-adapters/vite.config.ts +++ b/examples/solid/search-validator-adapters/vite.config.ts @@ -2,6 +2,7 @@ import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' import packageJson from './package.json' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ test: { @@ -10,12 +11,18 @@ export default defineConfig({ watch: false, environment: 'jsdom', typecheck: { enabled: true }, + setupFiles: ['./tests/jest-dom.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, }, plugins: [ + tailwindcss(), tanstackRouter({ target: 'solid', autoCodeSplitting: true, - verboseFileRoutes: false, }), solid(), ], diff --git a/examples/solid/start-basic-auth/.devcontainer/devcontainer.json b/examples/solid/start-basic-auth/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-basic-auth/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-basic-auth/README.md b/examples/solid/start-basic-auth/README.md index 90cba4aac1..313c930051 100644 --- a/examples/solid/start-basic-auth/README.md +++ b/examples/solid/start-basic-auth/README.md @@ -70,3 +70,13 @@ pnpm dev > [!WARNING] > You will need to update the `docs/config.json` file (in the project's repo) if you add a new doc page! + +## Session configuration + +This example uses [iron-session](https://github.com/vvo/iron-session) through Start's `getCookie` and `setCookie` helpers. Set `SESSION_PASSWORD` to a random secret of at least 32 characters before starting the app, for example: + +```sh +export SESSION_PASSWORD="$(openssl rand -base64 32)" +``` + +Keep the same secret across instances and deployments that must read the same sessions. The cookie requires HTTPS in production. Each handler reads its own session, then awaits `session.save()` before redirecting or returning. diff --git a/examples/solid/start-basic-auth/package.json b/examples/solid/start-basic-auth/package.json index d92adb48af..d686fdf616 100644 --- a/examples/solid/start-basic-auth/package.json +++ b/examples/solid/start-basic-auth/package.json @@ -14,23 +14,23 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.0", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", + "iron-session": "^9.0.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwind-merge": "^2.6.0" + "tailwind-merge": "^3.6.0" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "dotenv": "^17.2.3", - "postcss": "^8.5.1", "prisma": "^7.0.0", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10", - "vite-tsconfig-paths": "^5.1.4" + "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" } } diff --git a/examples/solid/start-basic-auth/postcss.config.mjs b/examples/solid/start-basic-auth/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/start-basic-auth/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/start-basic-auth/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic-auth/src/components/DefaultCatchBoundary.tsx index 2c0d464a06..f44db955a0 100644 --- a/examples/solid/start-basic-auth/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-auth/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error(error) diff --git a/examples/solid/start-basic-auth/src/prisma-generated/client.ts b/examples/solid/start-basic-auth/src/prisma-generated/client.ts index 1b9d548165..2be7866ae3 100644 --- a/examples/solid/start-basic-auth/src/prisma-generated/client.ts +++ b/examples/solid/start-basic-auth/src/prisma-generated/client.ts @@ -37,10 +37,10 @@ export * from './enums' export const PrismaClient = $Class.getPrismaClientClass() export type PrismaClient< LogOpts extends Prisma.LogLevel = never, - OmitOpts extends - Prisma.PrismaClientOptions['omit'] = Prisma.PrismaClientOptions['omit'], - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + OmitOpts extends Prisma.PrismaClientOptions['omit'] = + Prisma.PrismaClientOptions['omit'], + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = $Class.PrismaClient export { Prisma } diff --git a/examples/solid/start-basic-auth/src/prisma-generated/internal/class.ts b/examples/solid/start-basic-auth/src/prisma-generated/internal/class.ts index 95cb7864ef..594896a020 100644 --- a/examples/solid/start-basic-auth/src/prisma-generated/internal/class.ts +++ b/examples/solid/start-basic-auth/src/prisma-generated/internal/class.ts @@ -44,9 +44,8 @@ config.compilerWasm = { await import('@prisma/client/runtime/query_compiler_bg.sqlite.mjs'), getQueryCompilerWasmModule: async () => { - const { wasm } = await import( - '@prisma/client/runtime/query_compiler_bg.sqlite.wasm-base64.mjs' - ) + const { wasm } = + await import('@prisma/client/runtime/query_compiler_bg.sqlite.wasm-base64.mjs') return await decodeBase64AsWasm(wasm) }, } @@ -81,8 +80,8 @@ export interface PrismaClientConstructor { } ? U : Prisma.PrismaClientOptions['omit'], - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, >( options: Prisma.Subset, ): PrismaClient @@ -105,8 +104,8 @@ export interface PrismaClientConstructor { export interface PrismaClient< in LogOpts extends Prisma.LogLevel = never, in out OmitOpts extends Prisma.PrismaClientOptions['omit'] = undefined, - in out ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + in out ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > { [K: symbol]: { types: Prisma.TypeMap['other'] } diff --git a/examples/solid/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts b/examples/solid/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts index fc96903a35..f420c55329 100644 --- a/examples/solid/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts +++ b/examples/solid/start-basic-auth/src/prisma-generated/internal/prismaNamespace.ts @@ -417,17 +417,17 @@ export const ModelName = { export type ModelName = (typeof ModelName)[keyof typeof ModelName] -export interface TypeMapCb - extends runtime.Types.Utils.Fn< - { extArgs: runtime.Types.Extensions.InternalArgs }, - runtime.Types.Utils.Record - > { +export interface TypeMapCb extends runtime.Types.Utils + .Fn< + { extArgs: runtime.Types.Extensions.InternalArgs }, + runtime.Types.Utils.Record +> { returns: TypeMap } export type TypeMap< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}, > = { globalOmitOptions: { diff --git a/examples/solid/start-basic-auth/src/prisma-generated/models/User.ts b/examples/solid/start-basic-auth/src/prisma-generated/models/User.ts index 14c9ca5fb9..4312db9bd9 100644 --- a/examples/solid/start-basic-auth/src/prisma-generated/models/User.ts +++ b/examples/solid/start-basic-auth/src/prisma-generated/models/User.ts @@ -57,8 +57,8 @@ export type UserCountAggregateInputType = { } export type UserAggregateArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Filter which User to aggregate. @@ -119,8 +119,8 @@ export type GetUserAggregateType = { } export type UserGroupByArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { where?: Prisma.UserWhereInput orderBy?: @@ -254,8 +254,8 @@ export type StringFieldUpdateOperationsInput = { } export type UserSelect< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetSelect< { email?: boolean @@ -265,8 +265,8 @@ export type UserSelect< > export type UserSelectCreateManyAndReturn< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetSelect< { email?: boolean @@ -276,8 +276,8 @@ export type UserSelectCreateManyAndReturn< > export type UserSelectUpdateManyAndReturn< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetSelect< { email?: boolean @@ -292,16 +292,16 @@ export type UserSelectScalar = { } export type UserOmit< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = runtime.Types.Extensions.GetOmit< 'email' | 'password', ExtArgs['result']['user'] > export type $UserPayload< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { name: 'User' objects: {} @@ -320,15 +320,15 @@ export type UserGetPayload< > = runtime.Types.Result.GetResult export type UserCountArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = Omit & { select?: UserCountAggregateInputType | true } export interface UserDelegate< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}, > { [K: symbol]: { @@ -854,8 +854,8 @@ export interface UserDelegate< export interface Prisma__UserClient< T, Null = never, - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, GlobalOmitOptions = {}, > extends Prisma.PrismaPromise { readonly [Symbol.toStringTag]: 'PrismaPromise' @@ -910,8 +910,8 @@ export interface UserFieldRefs { * User findUnique */ export type UserFindUniqueArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -931,8 +931,8 @@ export type UserFindUniqueArgs< * User findUniqueOrThrow */ export type UserFindUniqueOrThrowArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -952,8 +952,8 @@ export type UserFindUniqueOrThrowArgs< * User findFirst */ export type UserFindFirstArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1005,8 +1005,8 @@ export type UserFindFirstArgs< * User findFirstOrThrow */ export type UserFindFirstOrThrowArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1058,8 +1058,8 @@ export type UserFindFirstOrThrowArgs< * User findMany */ export type UserFindManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1106,8 +1106,8 @@ export type UserFindManyArgs< * User create */ export type UserCreateArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1127,8 +1127,8 @@ export type UserCreateArgs< * User createMany */ export type UserCreateManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * The data used to create many Users. @@ -1140,8 +1140,8 @@ export type UserCreateManyArgs< * User createManyAndReturn */ export type UserCreateManyAndReturnArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1161,8 +1161,8 @@ export type UserCreateManyAndReturnArgs< * User update */ export type UserUpdateArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1186,8 +1186,8 @@ export type UserUpdateArgs< * User updateMany */ export type UserUpdateManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * The data used to update Users. @@ -1210,8 +1210,8 @@ export type UserUpdateManyArgs< * User updateManyAndReturn */ export type UserUpdateManyAndReturnArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1242,8 +1242,8 @@ export type UserUpdateManyAndReturnArgs< * User upsert */ export type UserUpsertArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1271,8 +1271,8 @@ export type UserUpsertArgs< * User delete */ export type UserDeleteArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User @@ -1292,8 +1292,8 @@ export type UserDeleteArgs< * User deleteMany */ export type UserDeleteManyArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Filter which Users to delete @@ -1309,8 +1309,8 @@ export type UserDeleteManyArgs< * User without action */ export type UserDefaultArgs< - ExtArgs extends - runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs, + ExtArgs extends runtime.Types.Extensions.InternalArgs = + runtime.Types.Extensions.DefaultArgs, > = { /** * Select specific fields to fetch from the User diff --git a/examples/solid/start-basic-auth/src/routeTree.gen.ts b/examples/solid/start-basic-auth/src/routeTree.gen.ts index 3b5f50dde1..07924d102a 100644 --- a/examples/solid/start-basic-auth/src/routeTree.gen.ts +++ b/examples/solid/start-basic-auth/src/routeTree.gen.ts @@ -9,23 +9,22 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as SignupRouteImport } from './routes/signup' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as SignupRouteImport } from './routes/signup' import { Route as AuthedPostsRouteRouteImport } from './routes/_authed/posts.route' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -33,13 +32,14 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRouteRoute = AuthedPostsRouteRouteImport.update({ @@ -120,18 +120,18 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } '/login': { @@ -141,18 +141,18 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthedRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/examples/solid/start-basic-auth/src/routes/__root.tsx b/examples/solid/start-basic-auth/src/routes/__root.tsx index 3aa0bfa18b..05ad0d298a 100644 --- a/examples/solid/start-basic-auth/src/routes/__root.tsx +++ b/examples/solid/start-basic-auth/src/routes/__root.tsx @@ -14,18 +14,18 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { useAppSession } from '~/utils/session.js' +import { getAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await useAppSession() + const session = await getAppSession() - if (!session.data.userEmail) { + if (!session.userEmail) { return null } return { - email: session.data.userEmail, + email: session.userEmail, } }) diff --git a/examples/solid/start-basic-auth/src/routes/_authed.tsx b/examples/solid/start-basic-auth/src/routes/_authed.tsx index 3caa846b22..cded7ca880 100644 --- a/examples/solid/start-basic-auth/src/routes/_authed.tsx +++ b/examples/solid/start-basic-auth/src/routes/_authed.tsx @@ -2,10 +2,10 @@ import { createFileRoute } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST' }) - .inputValidator((d: { email: string; password: string }) => d) + .validator((d: { email: string; password: string }) => d) .handler(async ({ data }) => { // Find the user const user = await prismaClient.user.findUnique({ @@ -33,13 +33,10 @@ export const loginFn = createServerFn({ method: 'POST' }) } } - // Create a session - const session = await useAppSession() - // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + const session = await getAppSession() + session.userEmail = user.email + await session.save() }) export const Route = createFileRoute('/_authed')({ diff --git a/examples/solid/start-basic-auth/src/routes/logout.tsx b/examples/solid/start-basic-auth/src/routes/logout.tsx index f7d624ff15..56cd70cbc2 100644 --- a/examples/solid/start-basic-auth/src/routes/logout.tsx +++ b/examples/solid/start-basic-auth/src/routes/logout.tsx @@ -1,11 +1,10 @@ import { createFileRoute, redirect } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' const logoutFn = createServerFn().handler(async () => { - const session = await useAppSession() - - session.clear() + const session = await getAppSession() + session.destroy() throw redirect({ href: '/', diff --git a/examples/solid/start-basic-auth/src/routes/signup.tsx b/examples/solid/start-basic-auth/src/routes/signup.tsx index 020e07c029..b8d6bf89fa 100644 --- a/examples/solid/start-basic-auth/src/routes/signup.tsx +++ b/examples/solid/start-basic-auth/src/routes/signup.tsx @@ -3,10 +3,10 @@ import { createServerFn, useServerFn } from '@tanstack/solid-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST' }) - .inputValidator( + .validator( (d: { email: string; password: string; redirectUrl?: string }) => d, ) .handler(async ({ data }) => { @@ -20,9 +20,6 @@ export const signupFn = createServerFn({ method: 'POST' }) // Encrypt the password using Sha256 into plaintext const password = await hashPassword(data.password) - // Create a session - const session = await useAppSession() - if (found) { if (found.password !== password) { return { @@ -33,9 +30,9 @@ export const signupFn = createServerFn({ method: 'POST' }) } // Store the user's email in the session - await session.update({ - userEmail: found.email, - }) + const session = await getAppSession() + session.userEmail = found.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -52,9 +49,9 @@ export const signupFn = createServerFn({ method: 'POST' }) }) // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + const session = await getAppSession() + session.userEmail = user.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/examples/solid/start-basic-auth/src/styles/app.css b/examples/solid/start-basic-auth/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/solid/start-basic-auth/src/styles/app.css +++ b/examples/solid/start-basic-auth/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/start-basic-auth/src/utils/posts.ts b/examples/solid/start-basic-auth/src/utils/posts.ts index 5c2e34c98d..f62670517f 100644 --- a/examples/solid/start-basic-auth/src/utils/posts.ts +++ b/examples/solid/start-basic-auth/src/utils/posts.ts @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) + .validator((postId: string) => postId) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const post = await axios diff --git a/examples/solid/start-basic-auth/src/utils/session.ts b/examples/solid/start-basic-auth/src/utils/session.ts index 120a410b60..4577764d28 100644 --- a/examples/solid/start-basic-auth/src/utils/session.ts +++ b/examples/solid/start-basic-auth/src/utils/session.ts @@ -1,13 +1,29 @@ -// src/services/session.server.ts -import { useSession } from '@tanstack/solid-start/server' +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/solid-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function useAppSession() { - return useSession({ - password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', - }) +export function getAppSession() { + const password = process.env.SESSION_PASSWORD + if (!password || password.length < 32) { + throw new Error('Set SESSION_PASSWORD to at least 32 characters') + } + + return getIronSession( + { read: getCookie, write: setCookie }, + { + cookieName: 'app-session', + password, + ttl: 7 * 24 * 60 * 60, + cookieOptions: { + httpOnly: true, + sameSite: 'lax', + secure: process.env.NODE_ENV === 'production', + path: '/', + }, + }, + ) } diff --git a/examples/solid/start-basic-auth/tsconfig.json b/examples/solid/start-basic-auth/tsconfig.json index a40235b863..ff0556e7a8 100644 --- a/examples/solid/start-basic-auth/tsconfig.json +++ b/examples/solid/start-basic-auth/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-basic-auth/vite.config.ts b/examples/solid/start-basic-auth/vite.config.ts index 27a27a7b5a..3c406c8001 100644 --- a/examples/solid/start-basic-auth/vite.config.ts +++ b/examples/solid/start-basic-auth/vite.config.ts @@ -1,17 +1,14 @@ import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteSolid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteSolid({ ssr: true }), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteSolid({ ssr: true })], }) diff --git a/examples/solid/start-basic-authjs/.devcontainer/devcontainer.json b/examples/solid/start-basic-authjs/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-basic-authjs/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-basic-authjs/package.json b/examples/solid/start-basic-authjs/package.json index 43b7c2444f..2c910663bd 100644 --- a/examples/solid/start-basic-authjs/package.json +++ b/examples/solid/start-basic-authjs/package.json @@ -11,21 +11,20 @@ }, "dependencies": { "@auth/core": "^0.41.1", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", - "start-authjs": "^1.0.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10", - "tailwind-merge": "^2.6.0" + "start-authjs": "^1.0.0", + "tailwind-merge": "^3.6.0" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10", - "vite-tsconfig-paths": "^5.1.4" + "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" } } diff --git a/examples/solid/start-basic-authjs/postcss.config.mjs b/examples/solid/start-basic-authjs/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/start-basic-authjs/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/start-basic-authjs/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic-authjs/src/components/DefaultCatchBoundary.tsx index 1ae7a0cf94..beff7bc210 100644 --- a/examples/solid/start-basic-authjs/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-authjs/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error('DefaultCatchBoundary Error:', error) diff --git a/examples/solid/start-basic-authjs/src/routeTree.gen.ts b/examples/solid/start-basic-authjs/src/routeTree.gen.ts index e772ba9c3e..7cc6d28cf7 100644 --- a/examples/solid/start-basic-authjs/src/routeTree.gen.ts +++ b/examples/solid/start-basic-authjs/src/routeTree.gen.ts @@ -9,14 +9,14 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as ProtectedRouteImport } from './routes/protected' -import { Route as LoginRouteImport } from './routes/login' import { Route as IndexRouteImport } from './routes/index' +import { Route as LoginRouteImport } from './routes/login' +import { Route as ProtectedRouteImport } from './routes/protected' import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$' -const ProtectedRoute = ProtectedRouteImport.update({ - id: '/protected', - path: '/protected', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -24,9 +24,9 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProtectedRoute = ProtectedRouteImport.update({ + id: '/protected', + path: '/protected', getParentRoute: () => rootRouteImport, } as any) const ApiAuthSplatRoute = ApiAuthSplatRouteImport.update({ @@ -71,11 +71,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/protected': { - id: '/protected' - path: '/protected' - fullPath: '/protected' - preLoaderRoute: typeof ProtectedRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/login': { @@ -85,11 +85,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/protected': { + id: '/protected' + path: '/protected' + fullPath: '/protected' + preLoaderRoute: typeof ProtectedRouteImport parentRoute: typeof rootRouteImport } '/api/auth/$': { diff --git a/examples/solid/start-basic-authjs/src/styles/app.css b/examples/solid/start-basic-authjs/src/styles/app.css index d4b5078586..23fa2415ca 100644 --- a/examples/solid/start-basic-authjs/src/styles/app.css +++ b/examples/solid/start-basic-authjs/src/styles/app.css @@ -1 +1 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); diff --git a/examples/solid/start-basic-authjs/tsconfig.json b/examples/solid/start-basic-authjs/tsconfig.json index 608d3ba5f3..726f20245f 100644 --- a/examples/solid/start-basic-authjs/tsconfig.json +++ b/examples/solid/start-basic-authjs/tsconfig.json @@ -16,7 +16,6 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "allowSyntheticDefaultImports": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] } diff --git a/examples/solid/start-basic-authjs/vite.config.ts b/examples/solid/start-basic-authjs/vite.config.ts index c917cc531d..a18dcb874b 100644 --- a/examples/solid/start-basic-authjs/vite.config.ts +++ b/examples/solid/start-basic-authjs/vite.config.ts @@ -1,18 +1,15 @@ import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteSolid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 10000, strictPort: true, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteSolid({ ssr: true }), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteSolid({ ssr: true })], }) diff --git a/examples/solid/start-basic-cloudflare/.devcontainer/devcontainer.json b/examples/solid/start-basic-cloudflare/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-basic-cloudflare/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-basic-cloudflare/package.json b/examples/solid/start-basic-cloudflare/package.json index 59e77d31fc..7ece143f61 100644 --- a/examples/solid/start-basic-cloudflare/package.json +++ b/examples/solid/start-basic-cloudflare/package.json @@ -9,24 +9,23 @@ "preview": "vite preview", "deploy": "npm run build && wrangler deploy", "cf-typegen": "wrangler types", - "postinstall": "npm run cf-typegen" + "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen" }, "dependencies": { - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10" }, "devDependencies": { - "@cloudflare/vite-plugin": "^1.13.7", - "@tailwindcss/postcss": "^4.1.15", + "@cloudflare/vite-plugin": "^1.29.0", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10", - "vite-tsconfig-paths": "^5.1.4", - "wrangler": "^4.49.1" + "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", + "wrangler": "^4.74.0" } } diff --git a/examples/solid/start-basic-cloudflare/postcss.config.mjs b/examples/solid/start-basic-cloudflare/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/start-basic-cloudflare/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx index 1ae7a0cf94..beff7bc210 100644 --- a/examples/solid/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-cloudflare/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error('DefaultCatchBoundary Error:', error) diff --git a/examples/solid/start-basic-cloudflare/src/routeTree.gen.ts b/examples/solid/start-basic-cloudflare/src/routeTree.gen.ts index 194a2a0705..7cba7e8958 100644 --- a/examples/solid/start-basic-cloudflare/src/routeTree.gen.ts +++ b/examples/solid/start-basic-cloudflare/src/routeTree.gen.ts @@ -9,42 +9,31 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ @@ -52,38 +41,24 @@ const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ path: '/customScript.js', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -91,28 +66,53 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => ApiUsersRoute, + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,32 +234,18 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } '/customScript.js': { @@ -269,47 +255,40 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof CustomScriptDotjsRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout': { - id: '/_pathlessLayout' + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/api/users': { id: '/api/users' @@ -318,26 +297,40 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute } - '/api/users/$userId': { - id: '/api/users/$userId' + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -346,12 +339,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/solid/start-basic-cloudflare/src/routes/api/users.$userId.ts b/examples/solid/start-basic-cloudflare/src/routes/api/users.$userId.ts index 8f31b7a890..b65c0396c4 100644 --- a/examples/solid/start-basic-cloudflare/src/routes/api/users.$userId.ts +++ b/examples/solid/start-basic-cloudflare/src/routes/api/users.$userId.ts @@ -1,5 +1,4 @@ import { createFileRoute } from '@tanstack/solid-router' -import { json } from '@tanstack/solid-start' import type { User } from '~/utils/users' export const Route = createFileRoute('/api/users/$userId')({ @@ -18,14 +17,14 @@ export const Route = createFileRoute('/api/users/$userId')({ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const user = (await res.json()) as User - return json({ + return Response.json({ id: user.id, name: user.name, email: user.email, }) } catch (e) { console.error(e) - return json({ error: 'User not found' }, { status: 404 }) + return Response.json({ error: 'User not found' }, { status: 404 }) } }, }, diff --git a/examples/solid/start-basic-cloudflare/src/routes/api/users.ts b/examples/solid/start-basic-cloudflare/src/routes/api/users.ts index a9d6505508..a6542d11bd 100644 --- a/examples/solid/start-basic-cloudflare/src/routes/api/users.ts +++ b/examples/solid/start-basic-cloudflare/src/routes/api/users.ts @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/solid-router' import { getRequestHeaders } from '@tanstack/solid-start/server' -import { createMiddleware, json } from '@tanstack/solid-start' +import { createMiddleware } from '@tanstack/solid-start' import type { User } from '~/utils/users' const userLoggerMiddleware = createMiddleware().server(async ({ next }) => { @@ -55,7 +55,7 @@ export const Route = createFileRoute('/api/users')({ const list = data.slice(0, 10) - return json( + return Response.json( list.map((u) => ({ id: u.id, name: u.name, email: u.email })), ) }, diff --git a/examples/solid/start-basic-cloudflare/src/routes/deferred.tsx b/examples/solid/start-basic-cloudflare/src/routes/deferred.tsx index 97c018ab03..1633369b20 100644 --- a/examples/solid/start-basic-cloudflare/src/routes/deferred.tsx +++ b/examples/solid/start-basic-cloudflare/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/solid-start' import { Suspense, createSignal } from 'solid-js' const personServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/examples/solid/start-basic-cloudflare/src/routes/users.$userId.tsx b/examples/solid/start-basic-cloudflare/src/routes/users.$userId.tsx index ffd624dcce..d2aeeb448c 100644 --- a/examples/solid/start-basic-cloudflare/src/routes/users.$userId.tsx +++ b/examples/solid/start-basic-cloudflare/src/routes/users.$userId.tsx @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/solid-router' -import { NotFound } from 'src/components/NotFound' -import { UserErrorComponent } from 'src/components/UserError' +import { NotFound } from '../components/NotFound' +import { UserErrorComponent } from '../components/UserError' import type { User } from '../utils/users' export const Route = createFileRoute('/users/$userId')({ diff --git a/examples/solid/start-basic-cloudflare/src/styles/app.css b/examples/solid/start-basic-cloudflare/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/solid/start-basic-cloudflare/src/styles/app.css +++ b/examples/solid/start-basic-cloudflare/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/start-basic-cloudflare/src/utils/posts.tsx b/examples/solid/start-basic-cloudflare/src/utils/posts.tsx index 609b78965e..d94aa88ece 100644 --- a/examples/solid/start-basic-cloudflare/src/utils/posts.tsx +++ b/examples/solid/start-basic-cloudflare/src/utils/posts.tsx @@ -8,7 +8,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'POST' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const res = await fetch( diff --git a/examples/solid/start-basic-cloudflare/tsconfig.json b/examples/solid/start-basic-cloudflare/tsconfig.json index a40235b863..ff0556e7a8 100644 --- a/examples/solid/start-basic-cloudflare/tsconfig.json +++ b/examples/solid/start-basic-cloudflare/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-basic-cloudflare/vite.config.ts b/examples/solid/start-basic-cloudflare/vite.config.ts index 806aecf99e..b9deb59030 100644 --- a/examples/solid/start-basic-cloudflare/vite.config.ts +++ b/examples/solid/start-basic-cloudflare/vite.config.ts @@ -1,17 +1,18 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { cloudflare } from '@cloudflare/vite-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import viteSolid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, + resolve: { + tsconfigPaths: true, + }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), + tailwindcss(), cloudflare({ viteEnvironment: { name: 'ssr' } }), tanstackStart(), viteSolid({ ssr: true }), diff --git a/examples/solid/start-basic-cloudflare/worker-configuration.d.ts b/examples/solid/start-basic-cloudflare/worker-configuration.d.ts index bdfccc2017..f7a8f16397 100644 --- a/examples/solid/start-basic-cloudflare/worker-configuration.d.ts +++ b/examples/solid/start-basic-cloudflare/worker-configuration.d.ts @@ -1,6 +1,6 @@ /* eslint-disable */ // Generated by Wrangler by running `wrangler types` (hash: b11df627d8b3c51b1bf3230a546b0f20) -// Runtime types generated with workerd@1.20251118.0 2025-09-24 nodejs_compat +// Runtime types generated with workerd@1.20260317.1 2025-09-24 nodejs_compat declare namespace Cloudflare { interface Env { MY_VAR: "Hello from Cloudflare"; @@ -436,22 +436,22 @@ interface ExecutionContext { passThroughOnException(): void; readonly props: Props; } -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; -type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; +type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; +type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; +type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; +interface ExportedHandler { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; } interface StructuredSerializeOptions { transfer?: any[]; @@ -499,8 +499,10 @@ interface DurableObjectNamespaceNewUniqueIdOptions { jurisdiction?: DurableObjectJurisdiction; } type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; +type DurableObjectRoutingMode = "primary-only"; interface DurableObjectNamespaceGetDurableObjectOptions { locationHint?: DurableObjectLocationHint; + routingMode?: DurableObjectRoutingMode; } interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { } @@ -1387,6 +1389,12 @@ declare abstract class PromiseRejectionEvent extends Event { */ declare class FormData { constructor(); + /** + * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) + */ + append(name: string, value: string | Blob): void; /** * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. * @@ -1423,6 +1431,12 @@ declare class FormData { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) */ has(name: string): boolean; + /** + * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) + */ + set(name: string, value: string | Blob): void; /** * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. * @@ -1749,7 +1763,7 @@ interface Request> e * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) */ signal: AbortSignal; - cf: Cf | undefined; + cf?: Cf; /** * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. * @@ -2084,6 +2098,8 @@ interface Transformer { expectedLength?: number; } interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; /** * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. * @@ -2102,8 +2118,6 @@ interface StreamPipeOptions { * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. */ preventClose?: boolean; - preventAbort?: boolean; - preventCancel?: boolean; signal?: AbortSignal; } type ReadableStreamReadResult = { @@ -2378,13 +2392,13 @@ declare abstract class TransformStreamDefaultController { terminate(): void; } interface ReadableWritablePair { + readable: ReadableStream; /** * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ writable: WritableStream; - readable: ReadableStream; } /** * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. @@ -3032,7 +3046,7 @@ declare var WebSocket: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) */ interface WebSocket extends EventTarget { - accept(): void; + accept(options?: WebSocketAcceptOptions): void; /** * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. * @@ -3071,6 +3085,22 @@ interface WebSocket extends EventTarget { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) */ extensions: string | null; + /** + * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) + */ + binaryType: "blob" | "arraybuffer"; +} +interface WebSocketAcceptOptions { + /** + * When set to `true`, receiving a server-initiated WebSocket Close frame will not + * automatically send a reciprocal Close frame, leaving the connection in a half-open + * state. This is useful for proxying scenarios where you need to coordinate closing + * both sides independently. Defaults to `false` when the + * `no_web_socket_half_open_by_default` compatibility flag is enabled. + */ + allowHalfOpen?: boolean; } declare const WebSocketPair: { new (): { @@ -3189,6 +3219,8 @@ interface Container { signal(signo: number): void; getTcpPort(port: number): Fetcher; setInactivityTimeout(durationMs: number | bigint): Promise; + interceptOutboundHttp(addr: string, binding: Fetcher): Promise; + interceptAllOutboundHttp(binding: Fetcher): Promise; } interface ContainerStartupOptions { entrypoint?: string[]; @@ -3281,7 +3313,8 @@ interface WorkerStubEntrypointOptions { props?: any; } interface WorkerLoader { - get(name: string, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; + get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; + load(code: WorkerLoaderWorkerCode): WorkerStub; } interface WorkerLoaderModule { js?: string; @@ -3314,6 +3347,181 @@ declare abstract class Performance { get timeOrigin(): number; /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ now(): number; + /** + * The **`toJSON()`** method of the Performance interface is a Serialization; it returns a JSON representation of the Performance object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON) + */ + toJSON(): object; +} +// AI Search V2 API Error Interfaces +interface AiSearchInternalError extends Error { +} +interface AiSearchNotFoundError extends Error { +} +interface AiSearchNameNotSetError extends Error { +} +// AI Search V2 Request Types +type AiSearchSearchRequest = { + messages: Array<{ + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + }>; + ai_search_options?: { + retrieval?: { + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + /** Maximum number of results (1-50, default 10) */ + max_num_results?: number; + filters?: VectorizeVectorMetadataFilter; + /** Context expansion (0-3, default 0) */ + context_expansion?: number; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + /** Enable reranking (default false) */ + enabled?: boolean; + model?: '@cf/baai/bge-reranker-base' | ''; + /** Match threshold (0-1, default 0.4) */ + match_threshold?: number; + [key: string]: unknown; + }; + [key: string]: unknown; + }; +}; +type AiSearchChatCompletionsRequest = { + messages: Array<{ + role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; + content: string | null; + }>; + model?: string; + stream?: boolean; + ai_search_options?: { + retrieval?: { + retrieval_type?: 'vector' | 'keyword' | 'hybrid'; + match_threshold?: number; + max_num_results?: number; + filters?: VectorizeVectorMetadataFilter; + context_expansion?: number; + [key: string]: unknown; + }; + query_rewrite?: { + enabled?: boolean; + model?: string; + rewrite_prompt?: string; + [key: string]: unknown; + }; + reranking?: { + enabled?: boolean; + model?: '@cf/baai/bge-reranker-base' | ''; + match_threshold?: number; + [key: string]: unknown; + }; + [key: string]: unknown; + }; + [key: string]: unknown; +}; +// AI Search V2 Response Types +type AiSearchSearchResponse = { + search_query: string; + chunks: Array<{ + id: string; + type: string; + /** Match score (0-1) */ + score: number; + text: string; + item: { + timestamp?: number; + key: string; + metadata?: Record; + }; + scoring_details?: { + /** Keyword match score (0-1) */ + keyword_score?: number; + /** Vector similarity score (0-1) */ + vector_score?: number; + }; + }>; +}; +type AiSearchListResponse = Array<{ + id: string; + internal_id?: string; + account_id?: string; + account_tag?: string; + /** Whether the instance is enabled (default true) */ + enable?: boolean; + type?: 'r2' | 'web-crawler'; + source?: string; + [key: string]: unknown; +}>; +type AiSearchConfig = { + /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ + id: string; + type: 'r2' | 'web-crawler'; + source: string; + source_params?: object; + /** Token ID (UUID format) */ + token_id?: string; + ai_gateway_id?: string; + /** Enable query rewriting (default false) */ + rewrite_query?: boolean; + /** Enable reranking (default false) */ + reranking?: boolean; + embedding_model?: string; + ai_search_model?: string; +}; +type AiSearchInstance = { + id: string; + enable?: boolean; + type?: 'r2' | 'web-crawler'; + source?: string; + [key: string]: unknown; +}; +// AI Search Instance Service - Instance-level operations +declare abstract class AiSearchInstanceService { + /** + * Search the AI Search instance for relevant chunks. + * @param params Search request with messages and AI search options + * @returns Search response with matching chunks + */ + search(params: AiSearchSearchRequest): Promise; + /** + * Generate chat completions with AI Search context. + * @param params Chat completions request with optional streaming + * @returns Response object (if streaming) or chat completion result + */ + chatCompletions(params: AiSearchChatCompletionsRequest): Promise; + /** + * Delete this AI Search instance. + */ + delete(): Promise; +} +// AI Search Account Service - Account-level operations +declare abstract class AiSearchAccountService { + /** + * List all AI Search instances in the account. + * @returns Array of AI Search instances + */ + list(): Promise; + /** + * Get an AI Search instance by ID. + * @param name Instance ID + * @returns Instance service for performing operations + */ + get(name: string): AiSearchInstanceService; + /** + * Create a new AI Search instance. + * @param config Instance configuration + * @returns Instance service for performing operations + */ + create(config: AiSearchConfig): Promise; } type AiImageClassificationInput = { image: number[]; @@ -3578,6 +3786,363 @@ declare abstract class BaseAiTranslation { inputs: AiTranslationInput; postProcessedOutputs: AiTranslationOutput; } +/** + * Workers AI support for OpenAI's Responses API + * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts + * + * It's a stripped down version from its source. + * It currently supports basic function calling, json mode and accepts images as input. + * + * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. + * We plan to add those incrementally as model + platform capabilities evolve. + */ +type ResponsesInput = { + background?: boolean | null; + conversation?: string | ResponseConversationParam | null; + include?: Array | null; + input?: string | ResponseInput; + instructions?: string | null; + max_output_tokens?: number | null; + parallel_tool_calls?: boolean | null; + previous_response_id?: string | null; + prompt_cache_key?: string; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + stream?: boolean | null; + stream_options?: StreamOptions | null; + temperature?: number | null; + text?: ResponseTextConfig; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + truncation?: "auto" | "disabled" | null; +}; +type ResponsesOutput = { + id?: string; + created_at?: number; + output_text?: string; + error?: ResponseError | null; + incomplete_details?: ResponseIncompleteDetails | null; + instructions?: string | Array | null; + object?: "response"; + output?: Array; + parallel_tool_calls?: boolean; + temperature?: number | null; + tool_choice?: ToolChoiceOptions | ToolChoiceFunction; + tools?: Array; + top_p?: number | null; + max_output_tokens?: number | null; + previous_response_id?: string | null; + prompt?: ResponsePrompt | null; + reasoning?: Reasoning | null; + safety_identifier?: string; + service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; + status?: ResponseStatus; + text?: ResponseTextConfig; + truncation?: "auto" | "disabled" | null; + usage?: ResponseUsage; +}; +type EasyInputMessage = { + content: string | ResponseInputMessageContentList; + role: "user" | "assistant" | "system" | "developer"; + type?: "message"; +}; +type ResponsesFunctionTool = { + name: string; + parameters: { + [key: string]: unknown; + } | null; + strict: boolean | null; + type: "function"; + description?: string | null; +}; +type ResponseIncompleteDetails = { + reason?: "max_output_tokens" | "content_filter"; +}; +type ResponsePrompt = { + id: string; + variables?: { + [key: string]: string | ResponseInputText | ResponseInputImage; + } | null; + version?: string | null; +}; +type Reasoning = { + effort?: ReasoningEffort | null; + generate_summary?: "auto" | "concise" | "detailed" | null; + summary?: "auto" | "concise" | "detailed" | null; +}; +type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText; +type ResponseContentReasoningText = { + text: string; + type: "reasoning_text"; +}; +type ResponseConversationParam = { + id: string; +}; +type ResponseCreatedEvent = { + response: Response; + sequence_number: number; + type: "response.created"; +}; +type ResponseCustomToolCallOutput = { + call_id: string; + output: string | Array; + type: "custom_tool_call_output"; + id?: string; +}; +type ResponseError = { + code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found"; + message: string; +}; +type ResponseErrorEvent = { + code: string | null; + message: string; + param: string | null; + sequence_number: number; + type: "error"; +}; +type ResponseFailedEvent = { + response: Response; + sequence_number: number; + type: "response.failed"; +}; +type ResponseFormatText = { + type: "text"; +}; +type ResponseFormatJSONObject = { + type: "json_object"; +}; +type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; +type ResponseFormatTextJSONSchemaConfig = { + name: string; + schema: { + [key: string]: unknown; + }; + type: "json_schema"; + description?: string; + strict?: boolean | null; +}; +type ResponseFunctionCallArgumentsDeltaEvent = { + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.delta"; +}; +type ResponseFunctionCallArgumentsDoneEvent = { + arguments: string; + item_id: string; + name: string; + output_index: number; + sequence_number: number; + type: "response.function_call_arguments.done"; +}; +type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; +type ResponseFunctionCallOutputItemList = Array; +type ResponseFunctionToolCall = { + arguments: string; + call_id: string; + name: string; + type: "function_call"; + id?: string; + status?: "in_progress" | "completed" | "incomplete"; +}; +interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { + id: string; +} +type ResponseFunctionToolCallOutputItem = { + id: string; + call_id: string; + output: string | Array; + type: "function_call_output"; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs"; +type ResponseIncompleteEvent = { + response: Response; + sequence_number: number; + type: "response.incomplete"; +}; +type ResponseInput = Array; +type ResponseInputContent = ResponseInputText | ResponseInputImage; +type ResponseInputImage = { + detail: "low" | "high" | "auto"; + type: "input_image"; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputImageContent = { + type: "input_image"; + detail?: "low" | "high" | "auto" | null; + /** + * Base64 encoded image + */ + image_url?: string | null; +}; +type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem; +type ResponseInputItemFunctionCallOutput = { + call_id: string; + output: string | ResponseFunctionCallOutputItemList; + type: "function_call_output"; + id?: string | null; + status?: "in_progress" | "completed" | "incomplete" | null; +}; +type ResponseInputItemMessage = { + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputMessageContentList = Array; +type ResponseInputMessageItem = { + id: string; + content: ResponseInputMessageContentList; + role: "user" | "system" | "developer"; + status?: "in_progress" | "completed" | "incomplete"; + type?: "message"; +}; +type ResponseInputText = { + text: string; + type: "input_text"; +}; +type ResponseInputTextContent = { + text: string; + type: "input_text"; +}; +type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; +type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; +type ResponseOutputItemAddedEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.added"; +}; +type ResponseOutputItemDoneEvent = { + item: ResponseOutputItem; + output_index: number; + sequence_number: number; + type: "response.output_item.done"; +}; +type ResponseOutputMessage = { + id: string; + content: Array; + role: "assistant"; + status: "in_progress" | "completed" | "incomplete"; + type: "message"; +}; +type ResponseOutputRefusal = { + refusal: string; + type: "refusal"; +}; +type ResponseOutputText = { + text: string; + type: "output_text"; + logprobs?: Array; +}; +type ResponseReasoningItem = { + id: string; + summary: Array; + type: "reasoning"; + content?: Array; + encrypted_content?: string | null; + status?: "in_progress" | "completed" | "incomplete"; +}; +type ResponseReasoningSummaryItem = { + text: string; + type: "summary_text"; +}; +type ResponseReasoningContentItem = { + text: string; + type: "reasoning_text"; +}; +type ResponseReasoningTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.reasoning_text.delta"; +}; +type ResponseReasoningTextDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + sequence_number: number; + text: string; + type: "response.reasoning_text.done"; +}; +type ResponseRefusalDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + output_index: number; + sequence_number: number; + type: "response.refusal.delta"; +}; +type ResponseRefusalDoneEvent = { + content_index: number; + item_id: string; + output_index: number; + refusal: string; + sequence_number: number; + type: "response.refusal.done"; +}; +type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete"; +type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent; +type ResponseCompletedEvent = { + response: Response; + sequence_number: number; + type: "response.completed"; +}; +type ResponseTextConfig = { + format?: ResponseFormatTextConfig; + verbosity?: "low" | "medium" | "high" | null; +}; +type ResponseTextDeltaEvent = { + content_index: number; + delta: string; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + type: "response.output_text.delta"; +}; +type ResponseTextDoneEvent = { + content_index: number; + item_id: string; + logprobs: Array; + output_index: number; + sequence_number: number; + text: string; + type: "response.output_text.done"; +}; +type Logprob = { + token: string; + logprob: number; + top_logprobs?: Array; +}; +type TopLogprob = { + token?: string; + logprob?: number; +}; +type ResponseUsage = { + input_tokens: number; + output_tokens: number; + total_tokens: number; +}; +type Tool = ResponsesFunctionTool; +type ToolChoiceFunction = { + name: string; + type: "function"; +}; +type ToolChoiceOptions = "none"; +type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; +type StreamOptions = { + include_obfuscation?: boolean; +}; type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { text: string | string[]; /** @@ -3606,8 +4171,8 @@ type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = { * The pooling method used in the embedding process. */ pooling?: "mean" | "cls"; -} | AsyncResponse; -interface AsyncResponse { +} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { /** * The async request id that can be used to obtain the results. */ @@ -3683,7 +4248,13 @@ type Ai_Cf_Meta_M2M100_1_2B_Output = { * The translated text in the target language */ translated_text?: string; -} | AsyncResponse; +} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; +interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { inputs: Ai_Cf_Meta_M2M100_1_2B_Input; postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; @@ -3716,7 +4287,13 @@ type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = { * The pooling method used in the embedding process. */ pooling?: "mean" | "cls"; -} | AsyncResponse; +} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; @@ -3749,7 +4326,13 @@ type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = { * The pooling method used in the embedding process. */ pooling?: "mean" | "cls"; -} | AsyncResponse; +} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; +interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; @@ -3935,13 +4518,13 @@ declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; } -type Ai_Cf_Baai_Bge_M3_Input = BGEM3InputQueryAndContexts | BGEM3InputEmbedding | { +type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | { /** * Batch of the embeddings requests to run using async-queue */ - requests: (BGEM3InputQueryAndContexts1 | BGEM3InputEmbedding1)[]; + requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[]; }; -interface BGEM3InputQueryAndContexts { +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { /** * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts */ @@ -3960,14 +4543,14 @@ interface BGEM3InputQueryAndContexts { */ truncate_inputs?: boolean; } -interface BGEM3InputEmbedding { +interface Ai_Cf_Baai_Bge_M3_Input_Embedding { text: string | string[]; /** * When provided with too long context should the model error out or truncate the context to fit? */ truncate_inputs?: boolean; } -interface BGEM3InputQueryAndContexts1 { +interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { /** * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts */ @@ -3986,15 +4569,15 @@ interface BGEM3InputQueryAndContexts1 { */ truncate_inputs?: boolean; } -interface BGEM3InputEmbedding1 { +interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { text: string | string[]; /** * When provided with too long context should the model error out or truncate the context to fit? */ truncate_inputs?: boolean; } -type Ai_Cf_Baai_Bge_M3_Output = BGEM3OuputQuery | BGEM3OutputEmbeddingForContexts | BGEM3OuputEmbedding | AsyncResponse; -interface BGEM3OuputQuery { +type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Ouput_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Ouput_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse; +interface Ai_Cf_Baai_Bge_M3_Ouput_Query { response?: { /** * Index of the context in the request @@ -4006,7 +4589,7 @@ interface BGEM3OuputQuery { score?: number; }[]; } -interface BGEM3OutputEmbeddingForContexts { +interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { response?: number[][]; shape?: number[]; /** @@ -4014,7 +4597,7 @@ interface BGEM3OutputEmbeddingForContexts { */ pooling?: "mean" | "cls"; } -interface BGEM3OuputEmbedding { +interface Ai_Cf_Baai_Bge_M3_Ouput_Embedding { shape?: number[]; /** * Embeddings of the requested text values @@ -4025,6 +4608,12 @@ interface BGEM3OuputEmbedding { */ pooling?: "mean" | "cls"; } +interface Ai_Cf_Baai_Bge_M3_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Baai_Bge_M3 { inputs: Ai_Cf_Baai_Bge_M3_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; @@ -4049,8 +4638,8 @@ declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; } -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Prompt | Messages; -interface Prompt { +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4101,7 +4690,7 @@ interface Prompt { */ lora?: string; } -interface Messages { +interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -4292,8 +4881,8 @@ declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; } -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | AsyncBatch; -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4302,7 +4891,7 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4344,11 +4933,11 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { */ presence_penalty?: number; } -interface JSONMode { +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { type?: "json_object" | "json_schema"; json_schema?: unknown; } -interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { /** * An array of message objects representing the conversation history. */ @@ -4453,7 +5042,7 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { }; }; })[]; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4495,7 +5084,11 @@ interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { */ presence_penalty?: number; } -interface AsyncBatch { +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { requests?: { /** * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. @@ -4537,9 +5130,13 @@ interface AsyncBatch { * Increases the likelihood of the model introducing new topics. */ presence_penalty?: number; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; }[]; } +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { /** * The generated text response from the model @@ -4575,7 +5172,13 @@ type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { */ name?: string; }[]; -} | string | AsyncResponse; +} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; +interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; @@ -4679,8 +5282,8 @@ declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; } -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Qwen2_5_Coder_32B_Instruct_Prompt | Qwen2_5_Coder_32B_Instruct_Messages; -interface Qwen2_5_Coder_32B_Instruct_Prompt { +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4689,7 +5292,7 @@ interface Qwen2_5_Coder_32B_Instruct_Prompt { * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. */ lora?: string; - response_format?: JSONMode; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4731,7 +5334,11 @@ interface Qwen2_5_Coder_32B_Instruct_Prompt { */ presence_penalty?: number; } -interface Qwen2_5_Coder_32B_Instruct_Messages { +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -4836,7 +5443,7 @@ interface Qwen2_5_Coder_32B_Instruct_Messages { }; }; })[]; - response_format?: JSONMode; + response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -4878,6 +5485,10 @@ interface Qwen2_5_Coder_32B_Instruct_Messages { */ presence_penalty?: number; } +interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { /** * The generated text response from the model @@ -4918,8 +5529,8 @@ declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; } -type Ai_Cf_Qwen_Qwq_32B_Input = Qwen_Qwq_32B_Prompt | Qwen_Qwq_32B_Messages; -interface Qwen_Qwq_32B_Prompt { +type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; +interface Ai_Cf_Qwen_Qwq_32B_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -4969,7 +5580,7 @@ interface Qwen_Qwq_32B_Prompt { */ presence_penalty?: number; } -interface Qwen_Qwq_32B_Messages { +interface Ai_Cf_Qwen_Qwq_32B_Messages { /** * An array of message objects representing the conversation history. */ @@ -5100,7 +5711,7 @@ interface Qwen_Qwq_32B_Messages { }; })[]; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5184,8 +5795,8 @@ declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { inputs: Ai_Cf_Qwen_Qwq_32B_Input; postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; } -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Mistral_Small_3_1_24B_Instruct_Prompt | Mistral_Small_3_1_24B_Instruct_Messages; -interface Mistral_Small_3_1_24B_Instruct_Prompt { +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -5235,7 +5846,7 @@ interface Mistral_Small_3_1_24B_Instruct_Prompt { */ presence_penalty?: number; } -interface Mistral_Small_3_1_24B_Instruct_Messages { +interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -5366,7 +5977,7 @@ interface Mistral_Small_3_1_24B_Instruct_Messages { }; })[]; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5450,14 +6061,14 @@ declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; } -type Ai_Cf_Google_Gemma_3_12B_It_Input = Google_Gemma_3_12B_It_Prompt | Google_Gemma_3_12B_It_Messages; -interface Google_Gemma_3_12B_It_Prompt { +type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages; +interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { /** * The input text prompt for the model to generate a response. */ prompt: string; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5501,7 +6112,7 @@ interface Google_Gemma_3_12B_It_Prompt { */ presence_penalty?: number; } -interface Google_Gemma_3_12B_It_Messages { +interface Ai_Cf_Google_Gemma_3_12B_It_Messages { /** * An array of message objects representing the conversation history. */ @@ -5522,19 +6133,7 @@ interface Google_Gemma_3_12B_It_Messages { */ url?: string; }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; + }[]; }[]; functions?: { name: string; @@ -5628,7 +6227,7 @@ interface Google_Gemma_3_12B_It_Messages { }; })[]; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5712,8 +6311,8 @@ declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; } -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Prompt | Ai_Cf_Meta_Llama_4_Messages | Ai_Cf_Meta_Llama_4_Async_Batch; -interface Ai_Cf_Meta_Llama_4_Prompt { +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { /** * The input text prompt for the model to generate a response. */ @@ -5722,7 +6321,7 @@ interface Ai_Cf_Meta_Llama_4_Prompt { * JSON schema that should be fulfilled for the response. */ guided_json?: object; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -5764,7 +6363,11 @@ interface Ai_Cf_Meta_Llama_4_Prompt { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Messages { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { /** * An array of message objects representing the conversation history. */ @@ -5894,9 +6497,9 @@ interface Ai_Cf_Meta_Llama_4_Messages { }; }; })[]; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -5940,10 +6543,10 @@ interface Ai_Cf_Meta_Llama_4_Messages { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Async_Batch { - requests: (Ai_Cf_Meta_Llama_4_Prompt_Inner | Ai_Cf_Meta_Llama_4_Messages_Inner)[]; +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { + requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[]; } -interface Ai_Cf_Meta_Llama_4_Prompt_Inner { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { /** * The input text prompt for the model to generate a response. */ @@ -5952,7 +6555,7 @@ interface Ai_Cf_Meta_Llama_4_Prompt_Inner { * JSON schema that should be fulfilled for the response. */ guided_json?: object; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. */ @@ -5994,7 +6597,7 @@ interface Ai_Cf_Meta_Llama_4_Prompt_Inner { */ presence_penalty?: number; } -interface Ai_Cf_Meta_Llama_4_Messages_Inner { +interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { /** * An array of message objects representing the conversation history. */ @@ -6124,9 +6727,9 @@ interface Ai_Cf_Meta_Llama_4_Messages_Inner { }; }; })[]; - response_format?: JSONMode; + response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; /** - * JSON schema that should be fufilled for the response. + * JSON schema that should be fulfilled for the response. */ guided_json?: object; /** @@ -6223,6 +6826,597 @@ declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; } +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { + requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { + inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; +} interface Ai_Cf_Deepgram_Nova_3_Input { audio: { body: object; @@ -6406,6 +7600,23 @@ declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { inputs: Ai_Cf_Deepgram_Nova_3_Input; postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; } +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { + queries?: string | string[]; + /** + * Optional instruction for the task + */ + instruction?: string; + documents?: string | string[]; + text?: string | string[]; +} +interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { + data?: number[][]; + shape?: number[]; +} +declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { + inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; +} type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = { /** * readable stream with audio data and content-type specified for that data @@ -6442,85 +7653,13 @@ declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; } -type Ai_Cf_Openai_Gpt_Oss_120B_Input = GPT_OSS_120B_Responses | GPT_OSS_120B_Responses_Async; -interface GPT_OSS_120B_Responses { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; -} -interface GPT_OSS_120B_Responses_Async { - requests: { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; - }[]; -} -type Ai_Cf_Openai_Gpt_Oss_120B_Output = {} | (string & NonNullable); declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { - inputs: Ai_Cf_Openai_Gpt_Oss_120B_Input; - postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_120B_Output; + inputs: ResponsesInput; + postProcessedOutputs: ResponsesOutput; } -type Ai_Cf_Openai_Gpt_Oss_20B_Input = GPT_OSS_20B_Responses | GPT_OSS_20B_Responses_Async; -interface GPT_OSS_20B_Responses { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; -} -interface GPT_OSS_20B_Responses_Async { - requests: { - /** - * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types - */ - input: string | unknown[]; - reasoning?: { - /** - * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - */ - effort?: "low" | "medium" | "high"; - /** - * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. - */ - summary?: "auto" | "concise" | "detailed"; - }; - }[]; -} -type Ai_Cf_Openai_Gpt_Oss_20B_Output = {} | (string & NonNullable); declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { - inputs: Ai_Cf_Openai_Gpt_Oss_20B_Input; - postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_20B_Output; + inputs: ResponsesInput; + postProcessedOutputs: ResponsesOutput; } interface Ai_Cf_Leonardo_Phoenix_1_0_Input { /** @@ -6634,6 +7773,799 @@ declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { inputs: Ai_Cf_Deepgram_Aura_1_Input; postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; } +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { + /** + * Input text to translate. Can be a single string or a list of strings. + */ + text: string | string[]; + /** + * Target language to translate to + */ + target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva"; +} +interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { + /** + * Translated texts + */ + translations: string[]; +} +declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { + inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; + postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { + requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[]; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "chat.completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index?: number; + /** + * The message generated by the model + */ + message?: { + /** + * Role of the message author + */ + role: string; + /** + * The content of the message + */ + content: string; + /** + * Internal reasoning content (if available) + */ + reasoning_content?: string; + /** + * Tool calls made by the assistant + */ + tool_calls?: { + /** + * Unique identifier for the tool call + */ + id: string; + /** + * Type of tool call + */ + type: "function"; + function: { + /** + * Name of the function to call + */ + name: string; + /** + * JSON string of arguments for the function + */ + arguments: string; + }; + }[]; + }; + /** + * Reason why the model stopped generating + */ + finish_reason?: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { + /** + * Unique identifier for the completion + */ + id?: string; + /** + * Object type identifier + */ + object?: "text_completion"; + /** + * Unix timestamp of when the completion was created + */ + created?: number; + /** + * Model used for the completion + */ + model?: string; + /** + * List of completion choices + */ + choices?: { + /** + * Index of the choice in the list + */ + index: number; + /** + * The generated text completion + */ + text: string; + /** + * Reason why the model stopped generating + */ + finish_reason: string; + /** + * Stop reason (may be null) + */ + stop_reason?: string | null; + /** + * Log probabilities (if requested) + */ + logprobs?: {} | null; + /** + * Log probabilities for the prompt (if requested) + */ + prompt_logprobs?: {} | null; + }[]; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { + inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; + postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { + /** + * Input text to embed. Can be a single string or a list of strings. + */ + text: string | string[]; +} +interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { + /** + * Embedding vectors, where each vector is a list of floats. + */ + data: number[][]; + /** + * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. + * + * @minItems 2 + * @maxItems 2 + */ + shape: [ + number, + number + ]; +} +declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { + inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; + postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; +} +interface Ai_Cf_Deepgram_Flux_Input { + /** + * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. + */ + encoding: "linear16"; + /** + * Sample rate of the audio stream in Hz. + */ + sample_rate: string; + /** + * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. + */ + eager_eot_threshold?: string; + /** + * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. + */ + eot_threshold?: string; + /** + * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. + */ + eot_timeout_ms?: string; + /** + * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. + */ + keyterm?: string; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip + */ + mip_opt_out?: "true" | "false"; + /** + * Label your requests for the purpose of identification during usage reporting + */ + tag?: string; +} +/** + * Output will be returned as websocket messages. + */ +interface Ai_Cf_Deepgram_Flux_Output { + /** + * The unique identifier of the request (uuid) + */ + request_id?: string; + /** + * Starts at 0 and increments for each message the server sends to the client. + */ + sequence_id?: number; + /** + * The type of event being reported. + */ + event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn"; + /** + * The index of the current turn + */ + turn_index?: number; + /** + * Start time in seconds of the audio range that was transcribed + */ + audio_window_start?: number; + /** + * End time in seconds of the audio range that was transcribed + */ + audio_window_end?: number; + /** + * Text that was said over the course of the current turn + */ + transcript?: string; + /** + * The words in the transcript + */ + words?: { + /** + * The individual punctuated, properly-cased word from the transcript + */ + word: string; + /** + * Confidence that this word was transcribed correctly + */ + confidence: number; + }[]; + /** + * Confidence that no more speech is coming in this turn + */ + end_of_turn_confidence?: number; +} +declare abstract class Base_Ai_Cf_Deepgram_Flux { + inputs: Ai_Cf_Deepgram_Flux_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; +} +interface Ai_Cf_Deepgram_Aura_2_En_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_En_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { + inputs: Ai_Cf_Deepgram_Aura_2_En_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; +} +interface Ai_Cf_Deepgram_Aura_2_Es_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_2_Es_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { + inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; +} interface AiModels { "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; @@ -6677,12 +8609,12 @@ interface AiModels { "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; - "@hf/meta-llama/meta-llama-3-8b-instruct": BaseAiTextGeneration; "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; + "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration; "@cf/facebook/bart-large-cnn": BaseAiSummarization; "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; @@ -6704,13 +8636,21 @@ interface AiModels { "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; + "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; + "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; + "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; + "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; + "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; + "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux; + "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En; + "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es; } type AiOptions = { /** @@ -6722,6 +8662,16 @@ type AiOptions = { * Establish websocket connections, only works for supported models */ websocket?: boolean; + /** + * Tag your requests to group and view them in Cloudflare dashboard. + * + * Rules: + * Tags must only contain letters, numbers, and the symbols: : - . / @ + * Each tag can have maximum 50 characters. + * Maximum 5 tags are allowed each request. + * Duplicate tags will removed. + */ + tags?: string[]; gateway?: GatewayOptions; returnRawResponse?: boolean; prefix?: string; @@ -6760,6 +8710,48 @@ type AiModelListType = Record; declare abstract class Ai { aiGatewayLogId: string | null; gateway(gatewayId: string): AiGateway; + /** + * Access the AI Search API for managing AI-powered search instances. + * + * This is the new API that replaces AutoRAG with better namespace separation: + * - Account-level operations: `list()`, `create()` + * - Instance-level operations: `get(id).search()`, `get(id).chatCompletions()`, `get(id).delete()` + * + * @example + * ```typescript + * // List all AI Search instances + * const instances = await env.AI.aiSearch.list(); + * + * // Search an instance + * const results = await env.AI.aiSearch.get('my-search').search({ + * messages: [{ role: 'user', content: 'What is the policy?' }], + * ai_search_options: { + * retrieval: { max_num_results: 10 } + * } + * }); + * + * // Generate chat completions with AI Search context + * const response = await env.AI.aiSearch.get('my-search').chatCompletions({ + * messages: [{ role: 'user', content: 'What is the policy?' }], + * model: '@cf/meta/llama-3.3-70b-instruct-fp8-fast' + * }); + * ``` + */ + aiSearch(): AiSearchAccountService; + /** + * @deprecated AutoRAG has been replaced by AI Search. + * Use `env.AI.aiSearch` instead for better API design and new features. + * + * Migration guide: + * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` + * - `env.AI.autorag('id').search({ query: '...' })` → `env.AI.aiSearch.get('id').search({ messages: [{ role: 'user', content: '...' }] })` + * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` + * + * Note: The old API continues to work for backwards compatibility, but new projects should use AI Search. + * + * @see AiSearchAccountService + * @param autoragId Optional instance ID (omit for account-level operations) + */ autorag(autoragId: string): AutoRAG; run(model: Name, inputs: InputOptions, options?: Options): Promise; getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line } +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchInternalError instead. + * @see AiSearchInternalError + */ interface AutoRAGInternalError extends Error { } +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNotFoundError instead. + * @see AiSearchNotFoundError + */ interface AutoRAGNotFoundError extends Error { } +/** + * @deprecated This error type is no longer used in the AI Search API. + */ interface AutoRAGUnauthorizedError extends Error { } +/** + * @deprecated AutoRAG has been replaced by AI Search. Use AiSearchNameNotSetError instead. + * @see AiSearchNameNotSetError + */ interface AutoRAGNameNotSetError extends Error { } type ComparisonFilter = { @@ -6885,6 +8892,11 @@ type CompoundFilter = { type: 'and' | 'or'; filters: ComparisonFilter[]; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchSearchRequest with the new API instead. + * @see AiSearchSearchRequest + */ type AutoRagSearchRequest = { query: string; filters?: CompoundFilter | ComparisonFilter; @@ -6899,13 +8911,28 @@ type AutoRagSearchRequest = { }; rewrite_query?: boolean; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchChatCompletionsRequest with the new API instead. + * @see AiSearchChatCompletionsRequest + */ type AutoRagAiSearchRequest = AutoRagSearchRequest & { stream?: boolean; system_prompt?: string; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchChatCompletionsRequest with stream: true instead. + * @see AiSearchChatCompletionsRequest + */ type AutoRagAiSearchRequestStreaming = Omit & { stream: true; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchSearchResponse with the new API instead. + * @see AiSearchSearchResponse + */ type AutoRagSearchResponse = { object: 'vector_store.search_results.page'; search_query: string; @@ -6922,6 +8949,11 @@ type AutoRagSearchResponse = { has_more: boolean; next_page: string | null; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use AiSearchListResponse with the new API instead. + * @see AiSearchListResponse + */ type AutoRagListResponse = { id: string; enable: boolean; @@ -6931,14 +8963,51 @@ type AutoRagListResponse = { paused: boolean; status: string; }[]; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * The new API returns different response formats for chat completions. + */ type AutoRagAiSearchResponse = AutoRagSearchResponse & { response: string; }; +/** + * @deprecated AutoRAG has been replaced by AI Search. + * Use the new AI Search API instead: `env.AI.aiSearch` + * + * Migration guide: + * - `env.AI.autorag().list()` → `env.AI.aiSearch.list()` + * - `env.AI.autorag('id').search(...)` → `env.AI.aiSearch.get('id').search(...)` + * - `env.AI.autorag('id').aiSearch(...)` → `env.AI.aiSearch.get('id').chatCompletions(...)` + * + * @see AiSearchAccountService + * @see AiSearchInstanceService + */ declare abstract class AutoRAG { + /** + * @deprecated Use `env.AI.aiSearch.list()` instead. + * @see AiSearchAccountService.list + */ list(): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).search(...)` instead. + * Note: The new API uses a messages array instead of a query string. + * @see AiSearchInstanceService.search + */ search(params: AutoRagSearchRequest): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ aiSearch(params: AutoRagAiSearchRequest): Promise; + /** + * @deprecated Use `env.AI.aiSearch.get(id).chatCompletions(...)` instead. + * @see AiSearchInstanceService.chatCompletions + */ aiSearch(params: AutoRagAiSearchRequest): Promise; } interface BasicImageTransformations { @@ -7689,6 +9758,10 @@ interface D1Meta { * The region of the database instance that executed the query. */ served_by_region?: string; + /** + * The three letters airport code of the colo that executed the query. + */ + served_by_colo?: string; /** * True if-and-only-if the database instance that executed the query was the primary. */ @@ -7777,6 +9850,15 @@ declare abstract class D1PreparedStatement { // ignored when `Disposable` is included in the standard lib. interface Disposable { } +/** + * The returned data after sending an email + */ +interface EmailSendResult { + /** + * The Email Message ID + */ + messageId: string; +} /** * An email message that can be sent from a Worker. */ @@ -7818,24 +9900,55 @@ interface ForwardableEmailMessage extends EmailMessage { * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). * @returns A promise that resolves when the email message is forwarded. */ - forward(rcptTo: string, headers?: Headers): Promise; + forward(rcptTo: string, headers?: Headers): Promise; /** * Reply to the sender of this email message with a new EmailMessage object. * @param message The reply message. * @returns A promise that resolves when the email message is replied. */ - reply(message: EmailMessage): Promise; + reply(message: EmailMessage): Promise; +} +/** A file attachment for an email message */ +type EmailAttachment = { + disposition: 'inline'; + contentId: string; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; +} | { + disposition: 'attachment'; + contentId?: undefined; + filename: string; + type: string; + content: string | ArrayBuffer | ArrayBufferView; +}; +/** An Email Address */ +interface EmailAddress { + name: string; + email: string; } /** * A binding that allows a Worker to send email messages. */ interface SendEmail { - send(message: EmailMessage): Promise; + send(message: EmailMessage): Promise; + send(builder: { + from: string | EmailAddress; + to: string | string[]; + subject: string; + replyTo?: string | EmailAddress; + cc?: string | string[]; + bcc?: string | string[]; + headers?: Record; + text?: string; + html?: string; + attachments?: EmailAttachment[]; + }): Promise; } declare abstract class EmailEvent extends ExtendableEvent { readonly message: ForwardableEmailMessage; } -declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; +declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; declare module "cloudflare:email" { let _EmailMessage: { prototype: EmailMessage; @@ -7863,7 +9976,7 @@ interface Hyperdrive { /** * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. * - * Calling this method returns an idential socket to if you call + * Calling this method returns an identical socket to if you call * `connect("host:port")` using the `host` and `port` fields from this object. * Pick whichever approach works better with your preferred DB client library. * @@ -7976,6 +10089,83 @@ type ImageOutputOptions = { background?: string; anim?: boolean; }; +interface ImageMetadata { + id: string; + filename?: string; + uploaded?: string; + requireSignedURLs: boolean; + meta?: Record; + variants: string[]; + draft?: boolean; + creator?: string; +} +interface ImageUploadOptions { + id?: string; + filename?: string; + requireSignedURLs?: boolean; + metadata?: Record; + creator?: string; + encoding?: 'base64'; +} +interface ImageUpdateOptions { + requireSignedURLs?: boolean; + metadata?: Record; + creator?: string; +} +interface ImageListOptions { + limit?: number; + cursor?: string; + sortOrder?: 'asc' | 'desc'; + creator?: string; +} +interface ImageList { + images: ImageMetadata[]; + cursor?: string; + listComplete: boolean; +} +interface HostedImagesBinding { + /** + * Get detailed metadata for a hosted image + * @param imageId The ID of the image (UUID or custom ID) + * @returns Image metadata, or null if not found + */ + details(imageId: string): Promise; + /** + * Get the raw image data for a hosted image + * @param imageId The ID of the image (UUID or custom ID) + * @returns ReadableStream of image bytes, or null if not found + */ + image(imageId: string): Promise | null>; + /** + * Upload a new hosted image + * @param image The image file to upload + * @param options Upload configuration + * @returns Metadata for the uploaded image + * @throws {@link ImagesError} if upload fails + */ + upload(image: ReadableStream | ArrayBuffer, options?: ImageUploadOptions): Promise; + /** + * Update hosted image metadata + * @param imageId The ID of the image + * @param options Properties to update + * @returns Updated image metadata + * @throws {@link ImagesError} if update fails + */ + update(imageId: string, options: ImageUpdateOptions): Promise; + /** + * Delete a hosted image + * @param imageId The ID of the image + * @returns True if deleted, false if not found + */ + delete(imageId: string): Promise; + /** + * List hosted images with pagination + * @param options List configuration + * @returns List of images with pagination info + * @throws {@link ImagesError} if list fails + */ + list(options?: ImageListOptions): Promise; +} interface ImagesBinding { /** * Get image metadata (type, width and height) @@ -7989,6 +10179,10 @@ interface ImagesBinding { * @returns A transform handle */ input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; + /** + * Access hosted images CRUD operations + */ + readonly hosted: HostedImagesBinding; } interface ImageTransformer { /** @@ -8055,7 +10249,13 @@ interface MediaTransformer { * @param transform - Configuration for how the media should be transformed * @returns A generator for producing the transformed media output */ - transform(transform: MediaTransformationInputOptions): MediaTransformationGenerator; + transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator; + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; } /** * Generator for producing media transformation results. @@ -8067,7 +10267,7 @@ interface MediaTransformationGenerator { * @param output - Configuration for the output format and parameters * @returns The final transformation result containing the transformed media */ - output(output: MediaTransformationOutputOptions): MediaTransformationResult; + output(output?: MediaTransformationOutputOptions): MediaTransformationResult; } /** * Result of a media transformation operation. @@ -8076,19 +10276,19 @@ interface MediaTransformationGenerator { interface MediaTransformationResult { /** * Returns the transformed media as a readable stream of bytes. - * @returns A stream containing the transformed media data + * @returns A promise containing a readable stream with the transformed media */ - media(): ReadableStream; + media(): Promise>; /** * Returns the transformed media as an HTTP response object. - * @returns The transformed media as a Response, ready to store in cache or return to users + * @returns The transformed media as a Promise, ready to store in cache or return to users */ - response(): Response; + response(): Promise; /** * Returns the MIME type of the transformed media. - * @returns The content type string (e.g., 'image/jpeg', 'video/mp4') + * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4') */ - contentType(): string; + contentType(): Promise; } /** * Configuration options for transforming media input. @@ -8196,7 +10396,7 @@ declare module "cloudflare:pipelines" { protected ctx: ExecutionContext; constructor(ctx: ExecutionContext, env: Env); /** - * run recieves an array of PipelineRecord which can be + * run receives an array of PipelineRecord which can be * transformed and returned to the pipeline * @param records Incoming records from the pipeline to be transformed * @param metadata Information about the specific pipeline calling the transformation entrypoint @@ -8362,9 +10562,9 @@ declare namespace Rpc { // Base type for all other types providing RPC-like interfaces. // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. - export type Provider = MaybeCallableProvider & { - [K in Exclude>]: MethodOrProperty; - }; + export type Provider = MaybeCallableProvider & Pick<{ + [K in keyof T]: MethodOrProperty; + }, Exclude>>; } declare namespace Cloudflare { // Type of `env`. @@ -8467,9 +10667,12 @@ declare namespace CloudflareWorkersModule { timestamp: Date; type: string; }; + export type WorkflowStepContext = { + attempt: number; + }; export abstract class WorkflowStep { - do>(name: string, callback: () => Promise): Promise; - do>(name: string, config: WorkflowStepConfig, callback: () => Promise): Promise; + do>(name: string, callback: (ctx: WorkflowStepContext) => Promise): Promise; + do>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise): Promise; sleep: (name: string, duration: WorkflowSleepDuration) => Promise; sleepUntil: (name: string, timestamp: Date | number) => Promise; waitForEvent>(name: string, options: { @@ -8477,6 +10680,7 @@ declare namespace CloudflareWorkersModule { timeout?: WorkflowTimeoutDuration | number; }): Promise>; } + export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown'; export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; protected ctx: ExecutionContext; @@ -8485,7 +10689,11 @@ declare namespace CloudflareWorkersModule { run(event: Readonly>, step: WorkflowStep): Promise; } export function waitUntil(promise: Promise): void; + export function withEnv(newEnv: unknown, fn: () => unknown): unknown; + export function withExports(newExports: unknown, fn: () => unknown): unknown; + export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown; export const env: Cloudflare.Env; + export const exports: Cloudflare.Exports; } declare module 'cloudflare:workers' { export = CloudflareWorkersModule; @@ -8501,17 +10709,765 @@ declare module "cloudflare:sockets" { function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; export { _connect as connect }; } +/** + * Binding entrypoint for Cloudflare Stream. + * + * Usage: + * - Binding-level operations: + * `await env.STREAM.videos.upload` + * `await env.STREAM.videos.createDirectUpload` + * `await env.STREAM.videos.*` + * `await env.STREAM.watermarks.*` + * - Per-video operations: + * `await env.STREAM.video(id).downloads.*` + * `await env.STREAM.video(id).captions.*` + * + * Example usage: + * ```ts + * await env.STREAM.video(id).downloads.generate(); + * + * const video = env.STREAM.video(id) + * const captions = video.captions.list(); + * const videoDetails = video.details() + * ``` + */ +interface StreamBinding { + /** + * Returns a handle scoped to a single video for per-video operations. + * @param id The unique identifier for the video. + * @returns A handle for per-video operations. + */ + video(id: string): StreamVideoHandle; + /** + * Uploads a new video from a File. + * @param file The video file to upload. + * @returns The uploaded video details. + * @throws {BadRequestError} if the upload parameter is invalid + * @throws {QuotaReachedError} if the account storage capacity is exceeded + * @throws {MaxFileSizeError} if the file size is too large + * @throws {RateLimitedError} if the server received too many requests + * @throws {InternalError} if an unexpected error occurs + */ + upload(file: File): Promise; + /** + * Uploads a new video from a provided URL. + * @param url The URL to upload from. + * @param params Optional upload parameters. + * @returns The uploaded video details. + * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid + * @throws {QuotaReachedError} if the account storage capacity is exceeded + * @throws {MaxFileSizeError} if the file size is too large + * @throws {RateLimitedError} if the server received too many requests + * @throws {AlreadyUploadedError} if a video was already uploaded to this URL + * @throws {InternalError} if an unexpected error occurs + */ + upload(url: string, params?: StreamUrlUploadParams): Promise; + /** + * Creates a direct upload that allows video uploads without an API key. + * @param params Parameters for the direct upload + * @returns The direct upload details. + * @throws {BadRequestError} if the parameters are invalid + * @throws {RateLimitedError} if the server received too many requests + * @throws {InternalError} if an unexpected error occurs + */ + createDirectUpload(params: StreamDirectUploadCreateParams): Promise; + videos: StreamVideos; + watermarks: StreamWatermarks; +} +/** + * Handle for operations scoped to a single Stream video. + */ +interface StreamVideoHandle { + /** + * The unique identifier for the video. + */ + id: string; + /** + * Get a full videos details + * @returns The full video details. + * @throws {NotFoundError} if the video is not found + * @throws {InternalError} if an unexpected error occurs + */ + details(): Promise; + /** + * Update details for a single video. + * @param params The fields to update for the video. + * @returns The updated video details. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the parameters are invalid + * @throws {InternalError} if an unexpected error occurs + */ + update(params: StreamUpdateVideoParams): Promise; + /** + * Deletes a video and its copies from Cloudflare Stream. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(): Promise; + /** + * Creates a signed URL token for a video. + * @returns The signed token that was created. + * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed + */ + generateToken(): Promise; + downloads: StreamScopedDownloads; + captions: StreamScopedCaptions; +} +interface StreamVideo { + /** + * The unique identifier for the video. + */ + id: string; + /** + * A user-defined identifier for the media creator. + */ + creator: string | null; + /** + * The thumbnail URL for the video. + */ + thumbnail: string; + /** + * The thumbnail timestamp percentage. + */ + thumbnailTimestampPct: number; + /** + * Indicates whether the video is ready to stream. + */ + readyToStream: boolean; + /** + * The date and time the video became ready to stream. + */ + readyToStreamAt: string | null; + /** + * Processing status information. + */ + status: StreamVideoStatus; + /** + * A user modifiable key-value store. + */ + meta: Record; + /** + * The date and time the video was created. + */ + created: string; + /** + * The date and time the video was last modified. + */ + modified: string; + /** + * The date and time at which the video will be deleted. + */ + scheduledDeletion: string | null; + /** + * The size of the video in bytes. + */ + size: number; + /** + * The preview URL for the video. + */ + preview?: string; + /** + * Origins allowed to display the video. + */ + allowedOrigins: Array; + /** + * Indicates whether signed URLs are required. + */ + requireSignedURLs: boolean | null; + /** + * The date and time the video was uploaded. + */ + uploaded: string | null; + /** + * The date and time when the upload URL expires. + */ + uploadExpiry: string | null; + /** + * The maximum size in bytes for direct uploads. + */ + maxSizeBytes: number | null; + /** + * The maximum duration in seconds for direct uploads. + */ + maxDurationSeconds: number | null; + /** + * The video duration in seconds. -1 indicates unknown. + */ + duration: number; + /** + * Input metadata for the original upload. + */ + input: StreamVideoInput; + /** + * Playback URLs for the video. + */ + hlsPlaybackUrl: string; + dashPlaybackUrl: string; + /** + * The watermark applied to the video, if any. + */ + watermark: StreamWatermark | null; + /** + * The live input id associated with the video, if any. + */ + liveInputId?: string | null; + /** + * The source video id if this is a clip. + */ + clippedFromId: string | null; + /** + * Public details associated with the video. + */ + publicDetails: StreamPublicDetails | null; +} +type StreamVideoStatus = { + /** + * The current processing state. + */ + state: string; + /** + * The current processing step. + */ + step?: string; + /** + * The percent complete as a string. + */ + pctComplete?: string; + /** + * An error reason code, if applicable. + */ + errorReasonCode: string; + /** + * An error reason text, if applicable. + */ + errorReasonText: string; +}; +type StreamVideoInput = { + /** + * The input width in pixels. + */ + width: number; + /** + * The input height in pixels. + */ + height: number; +}; +type StreamPublicDetails = { + /** + * The public title for the video. + */ + title: string | null; + /** + * The public share link. + */ + share_link: string | null; + /** + * The public channel link. + */ + channel_link: string | null; + /** + * The public logo URL. + */ + logo: string | null; +}; +type StreamDirectUpload = { + /** + * The URL an unauthenticated upload can use for a single multipart request. + */ + uploadURL: string; + /** + * A Cloudflare-generated unique identifier for a media item. + */ + id: string; + /** + * The watermark profile applied to the upload. + */ + watermark: StreamWatermark | null; + /** + * The scheduled deletion time, if any. + */ + scheduledDeletion: string | null; +}; +type StreamDirectUploadCreateParams = { + /** + * The maximum duration in seconds for a video upload. + */ + maxDurationSeconds: number; + /** + * The date and time after upload when videos will not be accepted. + */ + expiry?: string; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * A user modifiable key-value store used to reference other systems of record for + * managing videos. + */ + meta?: Record; + /** + * Lists the origins allowed to display the video. + */ + allowedOrigins?: Array; + /** + * Indicates whether the video can be accessed using the id. When set to `true`, + * a signed token must be generated with a signing key to view the video. + */ + requireSignedURLs?: boolean; + /** + * The thumbnail timestamp percentage. + */ + thumbnailTimestampPct?: number; + /** + * The date and time at which the video will be deleted. Include `null` to remove + * a scheduled deletion. + */ + scheduledDeletion?: string | null; + /** + * The watermark profile to apply. + */ + watermark?: StreamDirectUploadWatermark; +}; +type StreamDirectUploadWatermark = { + /** + * The unique identifier for the watermark profile. + */ + id: string; +}; +type StreamUrlUploadParams = { + /** + * Lists the origins allowed to display the video. Enter allowed origin + * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the + * video to be viewed on any origin. + */ + allowedOrigins?: Array; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * A user modifiable key-value store used to reference other systems of + * record for managing videos. + */ + meta?: Record; + /** + * Indicates whether the video can be a accessed using the id. When + * set to `true`, a signed token must be generated with a signing key to view the + * video. + */ + requireSignedURLs?: boolean; + /** + * Indicates the date and time at which the video will be deleted. Omit + * the field to indicate no change, or include with a `null` value to remove an + * existing scheduled deletion. If specified, must be at least 30 days from upload + * time. + */ + scheduledDeletion?: string | null; + /** + * The timestamp for a thumbnail image calculated as a percentage value + * of the video's duration. To convert from a second-wise timestamp to a + * percentage, divide the desired timestamp by the total duration of the video. If + * this value is not set, the default thumbnail image is taken from 0s of the + * video. + */ + thumbnailTimestampPct?: number; + /** + * The identifier for the watermark profile + */ + watermarkId?: string; +}; +interface StreamScopedCaptions { + /** + * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language. + * One caption or subtitle file per language is allowed. + * @param language The BCP 47 language tag for the caption or subtitle. + * @param file The caption or subtitle file to upload. + * @returns The created caption entry. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the language or file is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {InternalError} if an unexpected error occurs + */ + upload(language: string, file: File): Promise; + /** + * Generate captions or subtitles for the provided language via AI. + * @param language The BCP 47 language tag to generate. + * @returns The generated caption entry. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the language is invalid + * @throws {StreamError} if a generated caption already exists + * @throws {StreamError} if the video duration is too long + * @throws {StreamError} if the video is missing audio + * @throws {StreamError} if the requested language is not supported + * @throws {InternalError} if an unexpected error occurs + */ + generate(language: string): Promise; + /** + * Lists the captions or subtitles. + * Use the language parameter to filter by a specific language. + * @param language The optional BCP 47 language tag to filter by. + * @returns The list of captions or subtitles. + * @throws {NotFoundError} if the video or caption is not found + * @throws {InternalError} if an unexpected error occurs + */ + list(language?: string): Promise; + /** + * Removes the captions or subtitles from a video. + * @param language The BCP 47 language tag to remove. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video or caption is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(language: string): Promise; +} +interface StreamScopedDownloads { + /** + * Generates a download for a video when a video is ready to view. Available + * types are `default` and `audio`. Defaults to `default` when omitted. + * @param downloadType The download type to create. + * @returns The current downloads for the video. + * @throws {NotFoundError} if the video is not found + * @throws {BadRequestError} if the download type is invalid + * @throws {StreamError} if the video duration is too long to generate a download + * @throws {StreamError} if the video is not ready to stream + * @throws {InternalError} if an unexpected error occurs + */ + generate(downloadType?: StreamDownloadType): Promise; + /** + * Lists the downloads created for a video. + * @returns The current downloads for the video. + * @throws {NotFoundError} if the video or downloads are not found + * @throws {InternalError} if an unexpected error occurs + */ + get(): Promise; + /** + * Delete the downloads for a video. Available types are `default` and `audio`. + * Defaults to `default` when omitted. + * @param downloadType The download type to delete. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the video or downloads are not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(downloadType?: StreamDownloadType): Promise; +} +interface StreamVideos { + /** + * Lists all videos in a users account. + * @returns The list of videos. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InternalError} if an unexpected error occurs + */ + list(params?: StreamVideosListParams): Promise; +} +interface StreamWatermarks { + /** + * Generate a new watermark profile + * @param file The image file to upload + * @param params The watermark creation parameters. + * @returns The created watermark profile. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InvalidURLError} if the URL is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached + * @throws {InternalError} if an unexpected error occurs + */ + generate(file: File, params: StreamWatermarkCreateParams): Promise; + /** + * Generate a new watermark profile + * @param url The image url to upload + * @param params The watermark creation parameters. + * @returns The created watermark profile. + * @throws {BadRequestError} if the parameters are invalid + * @throws {InvalidURLError} if the URL is invalid + * @throws {MaxFileSizeError} if the file size is too large + * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached + * @throws {InternalError} if an unexpected error occurs + */ + generate(url: string, params: StreamWatermarkCreateParams): Promise; + /** + * Lists all watermark profiles for an account. + * @returns The list of watermark profiles. + * @throws {InternalError} if an unexpected error occurs + */ + list(): Promise; + /** + * Retrieves details for a single watermark profile. + * @param watermarkId The watermark profile identifier. + * @returns The watermark profile details. + * @throws {NotFoundError} if the watermark is not found + * @throws {InternalError} if an unexpected error occurs + */ + get(watermarkId: string): Promise; + /** + * Deletes a watermark profile. + * @param watermarkId The watermark profile identifier. + * @returns A promise that resolves when deletion completes. + * @throws {NotFoundError} if the watermark is not found + * @throws {InternalError} if an unexpected error occurs + */ + delete(watermarkId: string): Promise; +} +type StreamUpdateVideoParams = { + /** + * Lists the origins allowed to display the video. Enter allowed origin + * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the + * video to be viewed on any origin. + */ + allowedOrigins?: Array; + /** + * A user-defined identifier for the media creator. + */ + creator?: string; + /** + * The maximum duration in seconds for a video upload. Can be set for a + * video that is not yet uploaded to limit its duration. Uploads that exceed the + * specified duration will fail during processing. A value of `-1` means the value + * is unknown. + */ + maxDurationSeconds?: number; + /** + * A user modifiable key-value store used to reference other systems of + * record for managing videos. + */ + meta?: Record; + /** + * Indicates whether the video can be a accessed using the id. When + * set to `true`, a signed token must be generated with a signing key to view the + * video. + */ + requireSignedURLs?: boolean; + /** + * Indicates the date and time at which the video will be deleted. Omit + * the field to indicate no change, or include with a `null` value to remove an + * existing scheduled deletion. If specified, must be at least 30 days from upload + * time. + */ + scheduledDeletion?: string | null; + /** + * The timestamp for a thumbnail image calculated as a percentage value + * of the video's duration. To convert from a second-wise timestamp to a + * percentage, divide the desired timestamp by the total duration of the video. If + * this value is not set, the default thumbnail image is taken from 0s of the + * video. + */ + thumbnailTimestampPct?: number; +}; +type StreamCaption = { + /** + * Whether the caption was generated via AI. + */ + generated?: boolean; + /** + * The language label displayed in the native language to users. + */ + label: string; + /** + * The language tag in BCP 47 format. + */ + language: string; + /** + * The status of a generated caption. + */ + status?: 'ready' | 'inprogress' | 'error'; +}; +type StreamDownloadStatus = 'ready' | 'inprogress' | 'error'; +type StreamDownloadType = 'default' | 'audio'; +type StreamDownload = { + /** + * Indicates the progress as a percentage between 0 and 100. + */ + percentComplete: number; + /** + * The status of a generated download. + */ + status: StreamDownloadStatus; + /** + * The URL to access the generated download. + */ + url?: string; +}; +/** + * An object with download type keys. Each key is optional and only present if that + * download type has been created. + */ +type StreamDownloadGetResponse = { + /** + * The audio-only download. Only present if this download type has been created. + */ + audio?: StreamDownload; + /** + * The default video download. Only present if this download type has been created. + */ + default?: StreamDownload; +}; +type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center'; +type StreamWatermark = { + /** + * The unique identifier for a watermark profile. + */ + id: string; + /** + * The size of the image in bytes. + */ + size: number; + /** + * The height of the image in pixels. + */ + height: number; + /** + * The width of the image in pixels. + */ + width: number; + /** + * The date and a time a watermark profile was created. + */ + created: string; + /** + * The source URL for a downloaded image. If the watermark profile was created via + * direct upload, this field is null. + */ + downloadedFrom: string | null; + /** + * A short description of the watermark profile. + */ + name: string; + /** + * The translucency of the image. A value of `0.0` makes the image completely + * transparent, and `1.0` makes the image completely opaque. Note that if the image + * is already semi-transparent, setting this to `1.0` will not make the image + * completely opaque. + */ + opacity: number; + /** + * The whitespace between the adjacent edges (determined by position) of the video + * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded + * video width or length, as determined by the algorithm. + */ + padding: number; + /** + * The size of the image relative to the overall size of the video. This parameter + * will adapt to horizontal and vertical videos automatically. `0.0` indicates no + * scaling (use the size of the image as-is), and `1.0 `fills the entire video. + */ + scale: number; + /** + * The location of the image. Valid positions are: `upperRight`, `upperLeft`, + * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the + * `padding` parameter. + */ + position: StreamWatermarkPosition; +}; +type StreamWatermarkCreateParams = { + /** + * A short description of the watermark profile. + */ + name?: string; + /** + * The translucency of the image. A value of `0.0` makes the image completely + * transparent, and `1.0` makes the image completely opaque. Note that if the + * image is already semi-transparent, setting this to `1.0` will not make the + * image completely opaque. + */ + opacity?: number; + /** + * The whitespace between the adjacent edges (determined by position) of the + * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully + * padded video width or length, as determined by the algorithm. + */ + padding?: number; + /** + * The size of the image relative to the overall size of the video. This + * parameter will adapt to horizontal and vertical videos automatically. `0.0` + * indicates no scaling (use the size of the image as-is), and `1.0 `fills the + * entire video. + */ + scale?: number; + /** + * The location of the image. + */ + position?: StreamWatermarkPosition; +}; +type StreamVideosListParams = { + /** + * The maximum number of videos to return. + */ + limit?: number; + /** + * Return videos created before this timestamp. + * (RFC3339/RFC3339Nano) + */ + before?: string; + /** + * Comparison operator for the `before` field. + * @default 'lt' + */ + beforeComp?: StreamPaginationComparison; + /** + * Return videos created after this timestamp. + * (RFC3339/RFC3339Nano) + */ + after?: string; + /** + * Comparison operator for the `after` field. + * @default 'gte' + */ + afterComp?: StreamPaginationComparison; +}; +type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte'; +/** + * Error object for Stream binding operations. + */ +interface StreamError extends Error { + readonly code: number; + readonly statusCode: number; + readonly message: string; + readonly stack?: string; +} +interface InternalError extends StreamError { + name: 'InternalError'; +} +interface BadRequestError extends StreamError { + name: 'BadRequestError'; +} +interface NotFoundError extends StreamError { + name: 'NotFoundError'; +} +interface ForbiddenError extends StreamError { + name: 'ForbiddenError'; +} +interface RateLimitedError extends StreamError { + name: 'RateLimitedError'; +} +interface QuotaReachedError extends StreamError { + name: 'QuotaReachedError'; +} +interface MaxFileSizeError extends StreamError { + name: 'MaxFileSizeError'; +} +interface InvalidURLError extends StreamError { + name: 'InvalidURLError'; +} +interface AlreadyUploadedError extends StreamError { + name: 'AlreadyUploadedError'; +} +interface TooManyWatermarksError extends StreamError { + name: 'TooManyWatermarksError'; +} type MarkdownDocument = { name: string; blob: Blob; }; type ConversionResponse = { + id: string; name: string; mimeType: string; format: 'markdown'; tokens: number; data: string; } | { + id: string; name: string; mimeType: string; format: 'error'; @@ -8529,6 +11485,8 @@ type ConversionOptions = { images?: EmbeddedImageConversionOptions & { convertOGImage?: boolean; }; + hostname?: string; + cssSelector?: string; }; docx?: { images?: EmbeddedImageConversionOptions; @@ -8666,6 +11624,15 @@ declare namespace TailStream { readonly level: "debug" | "error" | "info" | "log" | "warn"; readonly message: object; } + interface DroppedEventsDiagnostic { + readonly diagnosticsType: "droppedEvents"; + readonly count: number; + } + interface StreamDiagnostic { + readonly type: 'streamDiagnostic'; + // To add new diagnostic types, define a new interface and add it to this union type. + readonly diagnostic: DroppedEventsDiagnostic; + } // This marks the worker handler return information. // This is separate from Outcome because the worker invocation can live for a long time after // returning. For example - Websockets that return an http upgrade response but then continue @@ -8682,7 +11649,7 @@ declare namespace TailStream { readonly type: "attributes"; readonly info: Attribute[]; } - type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | Return | Attributes; + type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes; // Context in which this trace event lives. interface SpanContext { // Single id for the entire top-level invocation @@ -8696,7 +11663,7 @@ declare namespace TailStream { // For Hibernate and Mark this would be the span under which they were emitted. // spanId is not set ONLY if: // 1. This is an Onset event - // 2. We are not inherting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) + // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) readonly spanId?: string; } interface TailEvent { @@ -9062,8 +12029,11 @@ type InstanceStatus = { | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish | 'waitingForPause' // instance is finishing the current work to pause | 'unknown'; - error?: string; - output?: object; + error?: { + name: string; + message: string; + }; + output?: unknown; }; interface WorkflowError { code?: number; diff --git a/examples/solid/start-basic-netlify/.devcontainer/devcontainer.json b/examples/solid/start-basic-netlify/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-basic-netlify/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-basic-netlify/package.json b/examples/solid/start-basic-netlify/package.json index d0dc1de0bc..69299cdb79 100644 --- a/examples/solid/start-basic-netlify/package.json +++ b/examples/solid/start-basic-netlify/package.json @@ -9,20 +9,19 @@ "preview": "vite preview" }, "dependencies": { - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10" }, "devDependencies": { - "@netlify/vite-plugin-tanstack-start": "^1.1.4", - "@tailwindcss/postcss": "^4.1.15", + "@netlify/vite-plugin-tanstack-start": "^1.3.19", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10", - "vite-tsconfig-paths": "^5.1.4" + "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" } } diff --git a/examples/solid/start-basic-netlify/postcss.config.mjs b/examples/solid/start-basic-netlify/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/start-basic-netlify/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/start-basic-netlify/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic-netlify/src/components/DefaultCatchBoundary.tsx index 1ae7a0cf94..beff7bc210 100644 --- a/examples/solid/start-basic-netlify/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-netlify/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error('DefaultCatchBoundary Error:', error) diff --git a/examples/solid/start-basic-netlify/src/routeTree.gen.ts b/examples/solid/start-basic-netlify/src/routeTree.gen.ts index 194a2a0705..7cba7e8958 100644 --- a/examples/solid/start-basic-netlify/src/routeTree.gen.ts +++ b/examples/solid/start-basic-netlify/src/routeTree.gen.ts @@ -9,42 +9,31 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ @@ -52,38 +41,24 @@ const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ path: '/customScript.js', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -91,28 +66,53 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => ApiUsersRoute, + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,32 +234,18 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } '/customScript.js': { @@ -269,47 +255,40 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof CustomScriptDotjsRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout': { - id: '/_pathlessLayout' + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/api/users': { id: '/api/users' @@ -318,26 +297,40 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute } - '/api/users/$userId': { - id: '/api/users/$userId' + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -346,12 +339,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/solid/start-basic-netlify/src/routes/api/users.$userId.ts b/examples/solid/start-basic-netlify/src/routes/api/users.$userId.ts index 8f31b7a890..b65c0396c4 100644 --- a/examples/solid/start-basic-netlify/src/routes/api/users.$userId.ts +++ b/examples/solid/start-basic-netlify/src/routes/api/users.$userId.ts @@ -1,5 +1,4 @@ import { createFileRoute } from '@tanstack/solid-router' -import { json } from '@tanstack/solid-start' import type { User } from '~/utils/users' export const Route = createFileRoute('/api/users/$userId')({ @@ -18,14 +17,14 @@ export const Route = createFileRoute('/api/users/$userId')({ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const user = (await res.json()) as User - return json({ + return Response.json({ id: user.id, name: user.name, email: user.email, }) } catch (e) { console.error(e) - return json({ error: 'User not found' }, { status: 404 }) + return Response.json({ error: 'User not found' }, { status: 404 }) } }, }, diff --git a/examples/solid/start-basic-netlify/src/routes/api/users.ts b/examples/solid/start-basic-netlify/src/routes/api/users.ts index a9d6505508..a6542d11bd 100644 --- a/examples/solid/start-basic-netlify/src/routes/api/users.ts +++ b/examples/solid/start-basic-netlify/src/routes/api/users.ts @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/solid-router' import { getRequestHeaders } from '@tanstack/solid-start/server' -import { createMiddleware, json } from '@tanstack/solid-start' +import { createMiddleware } from '@tanstack/solid-start' import type { User } from '~/utils/users' const userLoggerMiddleware = createMiddleware().server(async ({ next }) => { @@ -55,7 +55,7 @@ export const Route = createFileRoute('/api/users')({ const list = data.slice(0, 10) - return json( + return Response.json( list.map((u) => ({ id: u.id, name: u.name, email: u.email })), ) }, diff --git a/examples/solid/start-basic-netlify/src/routes/deferred.tsx b/examples/solid/start-basic-netlify/src/routes/deferred.tsx index 97c018ab03..1633369b20 100644 --- a/examples/solid/start-basic-netlify/src/routes/deferred.tsx +++ b/examples/solid/start-basic-netlify/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/solid-start' import { Suspense, createSignal } from 'solid-js' const personServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/examples/solid/start-basic-netlify/src/routes/users.$userId.tsx b/examples/solid/start-basic-netlify/src/routes/users.$userId.tsx index ffd624dcce..d2aeeb448c 100644 --- a/examples/solid/start-basic-netlify/src/routes/users.$userId.tsx +++ b/examples/solid/start-basic-netlify/src/routes/users.$userId.tsx @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/solid-router' -import { NotFound } from 'src/components/NotFound' -import { UserErrorComponent } from 'src/components/UserError' +import { NotFound } from '../components/NotFound' +import { UserErrorComponent } from '../components/UserError' import type { User } from '../utils/users' export const Route = createFileRoute('/users/$userId')({ diff --git a/examples/solid/start-basic-netlify/src/styles/app.css b/examples/solid/start-basic-netlify/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/solid/start-basic-netlify/src/styles/app.css +++ b/examples/solid/start-basic-netlify/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/start-basic-netlify/src/utils/posts.tsx b/examples/solid/start-basic-netlify/src/utils/posts.tsx index 609b78965e..d94aa88ece 100644 --- a/examples/solid/start-basic-netlify/src/utils/posts.tsx +++ b/examples/solid/start-basic-netlify/src/utils/posts.tsx @@ -8,7 +8,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'POST' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const res = await fetch( diff --git a/examples/solid/start-basic-netlify/tsconfig.json b/examples/solid/start-basic-netlify/tsconfig.json index a40235b863..ff0556e7a8 100644 --- a/examples/solid/start-basic-netlify/tsconfig.json +++ b/examples/solid/start-basic-netlify/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-basic-netlify/vite.config.ts b/examples/solid/start-basic-netlify/vite.config.ts index 3b26635823..7324d8f585 100644 --- a/examples/solid/start-basic-netlify/vite.config.ts +++ b/examples/solid/start-basic-netlify/vite.config.ts @@ -1,17 +1,18 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import netlify from '@netlify/vite-plugin-tanstack-start' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import viteSolid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, + resolve: { + tsconfigPaths: true, + }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), + tailwindcss(), netlify(), tanstackStart(), viteSolid({ ssr: true }), diff --git a/examples/solid/start-basic-nitro/.devcontainer/devcontainer.json b/examples/solid/start-basic-nitro/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-basic-nitro/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-basic-nitro/package.json b/examples/solid/start-basic-nitro/package.json index 83e1ae385f..2c0dc7dad6 100644 --- a/examples/solid/start-basic-nitro/package.json +++ b/examples/solid/start-basic-nitro/package.json @@ -9,20 +9,19 @@ "preview": "vite preview" }, "dependencies": { - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "nitro": "^3.0.1-alpha.0", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10", - "vite-tsconfig-paths": "^5.1.4" + "nitro": "^3.0.260903-beta", + "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" } } diff --git a/examples/solid/start-basic-nitro/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic-nitro/src/components/DefaultCatchBoundary.tsx index 1ae7a0cf94..beff7bc210 100644 --- a/examples/solid/start-basic-nitro/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-nitro/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error('DefaultCatchBoundary Error:', error) diff --git a/examples/solid/start-basic-nitro/src/routeTree.gen.ts b/examples/solid/start-basic-nitro/src/routeTree.gen.ts index 194a2a0705..7cba7e8958 100644 --- a/examples/solid/start-basic-nitro/src/routeTree.gen.ts +++ b/examples/solid/start-basic-nitro/src/routeTree.gen.ts @@ -9,42 +9,31 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ @@ -52,38 +41,24 @@ const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ path: '/customScript.js', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -91,28 +66,53 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => ApiUsersRoute, + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,32 +234,18 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } '/customScript.js': { @@ -269,47 +255,40 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof CustomScriptDotjsRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout': { - id: '/_pathlessLayout' + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/api/users': { id: '/api/users' @@ -318,26 +297,40 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute } - '/api/users/$userId': { - id: '/api/users/$userId' + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -346,12 +339,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/solid/start-basic-nitro/src/routes/api/users.$userId.ts b/examples/solid/start-basic-nitro/src/routes/api/users.$userId.ts index 8f31b7a890..b65c0396c4 100644 --- a/examples/solid/start-basic-nitro/src/routes/api/users.$userId.ts +++ b/examples/solid/start-basic-nitro/src/routes/api/users.$userId.ts @@ -1,5 +1,4 @@ import { createFileRoute } from '@tanstack/solid-router' -import { json } from '@tanstack/solid-start' import type { User } from '~/utils/users' export const Route = createFileRoute('/api/users/$userId')({ @@ -18,14 +17,14 @@ export const Route = createFileRoute('/api/users/$userId')({ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const user = (await res.json()) as User - return json({ + return Response.json({ id: user.id, name: user.name, email: user.email, }) } catch (e) { console.error(e) - return json({ error: 'User not found' }, { status: 404 }) + return Response.json({ error: 'User not found' }, { status: 404 }) } }, }, diff --git a/examples/solid/start-basic-nitro/src/routes/api/users.ts b/examples/solid/start-basic-nitro/src/routes/api/users.ts index a9d6505508..a6542d11bd 100644 --- a/examples/solid/start-basic-nitro/src/routes/api/users.ts +++ b/examples/solid/start-basic-nitro/src/routes/api/users.ts @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/solid-router' import { getRequestHeaders } from '@tanstack/solid-start/server' -import { createMiddleware, json } from '@tanstack/solid-start' +import { createMiddleware } from '@tanstack/solid-start' import type { User } from '~/utils/users' const userLoggerMiddleware = createMiddleware().server(async ({ next }) => { @@ -55,7 +55,7 @@ export const Route = createFileRoute('/api/users')({ const list = data.slice(0, 10) - return json( + return Response.json( list.map((u) => ({ id: u.id, name: u.name, email: u.email })), ) }, diff --git a/examples/solid/start-basic-nitro/src/routes/deferred.tsx b/examples/solid/start-basic-nitro/src/routes/deferred.tsx index 97c018ab03..1633369b20 100644 --- a/examples/solid/start-basic-nitro/src/routes/deferred.tsx +++ b/examples/solid/start-basic-nitro/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/solid-start' import { Suspense, createSignal } from 'solid-js' const personServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/examples/solid/start-basic-nitro/src/routes/users.$userId.tsx b/examples/solid/start-basic-nitro/src/routes/users.$userId.tsx index ffd624dcce..d2aeeb448c 100644 --- a/examples/solid/start-basic-nitro/src/routes/users.$userId.tsx +++ b/examples/solid/start-basic-nitro/src/routes/users.$userId.tsx @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/solid-router' -import { NotFound } from 'src/components/NotFound' -import { UserErrorComponent } from 'src/components/UserError' +import { NotFound } from '../components/NotFound' +import { UserErrorComponent } from '../components/UserError' import type { User } from '../utils/users' export const Route = createFileRoute('/users/$userId')({ diff --git a/examples/solid/start-basic-nitro/src/styles/app.css b/examples/solid/start-basic-nitro/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/solid/start-basic-nitro/src/styles/app.css +++ b/examples/solid/start-basic-nitro/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/start-basic-nitro/src/utils/posts.tsx b/examples/solid/start-basic-nitro/src/utils/posts.tsx index 609b78965e..d94aa88ece 100644 --- a/examples/solid/start-basic-nitro/src/utils/posts.tsx +++ b/examples/solid/start-basic-nitro/src/utils/posts.tsx @@ -8,7 +8,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'POST' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const res = await fetch( diff --git a/examples/solid/start-basic-nitro/tsconfig.json b/examples/solid/start-basic-nitro/tsconfig.json index a40235b863..ff0556e7a8 100644 --- a/examples/solid/start-basic-nitro/tsconfig.json +++ b/examples/solid/start-basic-nitro/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-basic-nitro/vite.config.ts b/examples/solid/start-basic-nitro/vite.config.ts index e622a3a5c1..db70391ee1 100644 --- a/examples/solid/start-basic-nitro/vite.config.ts +++ b/examples/solid/start-basic-nitro/vite.config.ts @@ -1,19 +1,30 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { nitro } from 'nitro/vite' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import viteSolid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, + resolve: { + tsconfigPaths: true, + }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], + tailwindcss(), + nitro({ preset: 'node-server' }), + tanstackStart({ + sitemap: { enabled: false }, + prerender: { + enabled: true, + filter: ({ path }) => + !path.startsWith('/users') && + !path.startsWith('/this-route-does-not-exist') && + !path.startsWith('/posts/i-do-not-exist') && + !path.startsWith('/deferred'), + }, }), - nitro({ config: { preset: 'node-server' } }), - tanstackStart(), viteSolid({ ssr: true }), ], }) diff --git a/examples/solid/start-basic-solid-query/.devcontainer/devcontainer.json b/examples/solid/start-basic-solid-query/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-basic-solid-query/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-basic-solid-query/package.json b/examples/solid/start-basic-solid-query/package.json index b190d9ee23..ddbb7d8764 100644 --- a/examples/solid/start-basic-solid-query/package.json +++ b/examples/solid/start-basic-solid-query/package.json @@ -12,22 +12,21 @@ "dependencies": { "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-router-ssr-query": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router-ssr-query": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwind-merge": "^2.6.0" + "tailwind-merge": "^3.6.0" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10", - "vite-tsconfig-paths": "^5.1.4" + "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" } } diff --git a/examples/solid/start-basic-solid-query/postcss.config.mjs b/examples/solid/start-basic-solid-query/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/start-basic-solid-query/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/start-basic-solid-query/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic-solid-query/src/components/DefaultCatchBoundary.tsx index 2c0d464a06..f44db955a0 100644 --- a/examples/solid/start-basic-solid-query/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-solid-query/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error(error) diff --git a/examples/solid/start-basic-solid-query/src/routeTree.gen.ts b/examples/solid/start-basic-solid-query/src/routeTree.gen.ts index 5f21fd643a..4a1747ae36 100644 --- a/examples/solid/start-basic-solid-query/src/routeTree.gen.ts +++ b/examples/solid/start-basic-solid-query/src/routeTree.gen.ts @@ -9,26 +9,30 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as UsersRouteRouteImport } from './routes/users.route' -import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteRouteImport } from './routes/posts.route' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteRouteImport } from './routes/users.route' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -36,8 +40,14 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const PostsRouteRoute = PostsRouteRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) const UsersRouteRoute = UsersRouteRouteImport.update({ @@ -45,68 +55,58 @@ const UsersRouteRoute = UsersRouteRouteImport.update({ path: '/users', getParentRoute: () => rootRouteImport, } as any) -const PostsRouteRoute = PostsRouteRouteImport.update({ - id: '/posts', - path: '/posts', +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRouteRoute, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => PostsRouteRoute, } as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRouteRoute, -} as any) const PostsPostIdRoute = PostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', - getParentRoute: () => rootRouteImport, +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRouteRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRouteRoute, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, -} as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -221,11 +221,18 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -235,11 +242,18 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } '/users': { @@ -249,47 +263,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof UsersRouteRouteImport parentRoute: typeof rootRouteImport } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRouteRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRouteRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRouteRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRouteRoute + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/api/users': { id: '/api/users' @@ -298,26 +277,40 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRouteRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRouteRoute } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRouteRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRouteRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -326,12 +319,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/solid/start-basic-solid-query/src/routes/api/users.$id.ts b/examples/solid/start-basic-solid-query/src/routes/api/users.$id.ts index ef13c22ab2..47d0b2e7a4 100644 --- a/examples/solid/start-basic-solid-query/src/routes/api/users.$id.ts +++ b/examples/solid/start-basic-solid-query/src/routes/api/users.$id.ts @@ -1,5 +1,4 @@ import { createFileRoute } from '@tanstack/solid-router' -import { json } from '@tanstack/solid-start' import axios from 'redaxios' import type { User } from '../../utils/users' @@ -12,14 +11,14 @@ export const Route = createFileRoute('/api/users/$id')({ const res = await axios.get( 'https://jsonplaceholder.typicode.com/users/' + params.id, ) - return json({ + return Response.json({ id: res.data.id, name: res.data.name, email: res.data.email, }) } catch (e) { console.error(e) - return json({ error: 'User not found' }, { status: 404 }) + return Response.json({ error: 'User not found' }, { status: 404 }) } }, }, diff --git a/examples/solid/start-basic-solid-query/src/routes/api/users.ts b/examples/solid/start-basic-solid-query/src/routes/api/users.ts index f0f272a8c4..9a6a3d65ae 100644 --- a/examples/solid/start-basic-solid-query/src/routes/api/users.ts +++ b/examples/solid/start-basic-solid-query/src/routes/api/users.ts @@ -1,5 +1,4 @@ import { createFileRoute } from '@tanstack/solid-router' -import { json } from '@tanstack/solid-start' import axios from 'redaxios' import type { User } from '../../utils/users' @@ -12,7 +11,7 @@ export const Route = createFileRoute('/api/users')({ 'https://jsonplaceholder.typicode.com/users', ) const list = res.data.slice(0, 10) - return json( + return Response.json( list.map((u) => ({ id: u.id, name: u.name, email: u.email })), ) }, diff --git a/examples/solid/start-basic-solid-query/src/styles/app.css b/examples/solid/start-basic-solid-query/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/solid/start-basic-solid-query/src/styles/app.css +++ b/examples/solid/start-basic-solid-query/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/start-basic-solid-query/src/utils/posts.tsx b/examples/solid/start-basic-solid-query/src/utils/posts.tsx index 528dd449d7..84091f451a 100644 --- a/examples/solid/start-basic-solid-query/src/utils/posts.tsx +++ b/examples/solid/start-basic-solid-query/src/utils/posts.tsx @@ -25,7 +25,7 @@ export const postsQueryOptions = () => }) export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const post = await axios diff --git a/examples/solid/start-basic-solid-query/tsconfig.json b/examples/solid/start-basic-solid-query/tsconfig.json index a40235b863..ff0556e7a8 100644 --- a/examples/solid/start-basic-solid-query/tsconfig.json +++ b/examples/solid/start-basic-solid-query/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-basic-solid-query/vite.config.ts b/examples/solid/start-basic-solid-query/vite.config.ts index 27a27a7b5a..3c406c8001 100644 --- a/examples/solid/start-basic-solid-query/vite.config.ts +++ b/examples/solid/start-basic-solid-query/vite.config.ts @@ -1,17 +1,14 @@ import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteSolid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteSolid({ ssr: true }), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteSolid({ ssr: true })], }) diff --git a/examples/solid/start-basic-static/.devcontainer/devcontainer.json b/examples/solid/start-basic-static/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-basic-static/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-basic-static/package.json b/examples/solid/start-basic-static/package.json index 956611714f..8b639da68a 100644 --- a/examples/solid/start-basic-static/package.json +++ b/examples/solid/start-basic-static/package.json @@ -10,22 +10,21 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", - "@tanstack/start-static-server-functions": "^1.142.0", - "solid-js": "^1.9.10", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", + "@tanstack/start-static-server-functions": "^1.167.44", "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0" + "solid-js": "^1.9.10", + "tailwind-merge": "^3.6.0" }, "devDependencies": { + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "autoprefixer": "^10.4.20", - "postcss": "^8.4.49", - "tailwindcss": "^3.4.15", - "typescript": "^5.6.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.3", - "vite-plugin-solid": "^2.11.10" + "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" } } diff --git a/examples/solid/start-basic-static/postcss.config.cjs b/examples/solid/start-basic-static/postcss.config.cjs deleted file mode 100644 index 8e638a6bcd..0000000000 --- a/examples/solid/start-basic-static/postcss.config.cjs +++ /dev/null @@ -1,7 +0,0 @@ -module.exports = { - plugins: [ - require('tailwindcss/nesting'), - require('tailwindcss'), - require('autoprefixer'), - ], -} diff --git a/examples/solid/start-basic-static/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic-static/src/components/DefaultCatchBoundary.tsx index 0dff3919fd..db574e0f90 100644 --- a/examples/solid/start-basic-static/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic-static/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error('DefaultCatchBoundary Error:', error) diff --git a/examples/solid/start-basic-static/src/routeTree.gen.ts b/examples/solid/start-basic-static/src/routeTree.gen.ts index 71da6e9ae8..a94e0fcf2e 100644 --- a/examples/solid/start-basic-static/src/routeTree.gen.ts +++ b/examples/solid/start-basic-static/src/routeTree.gen.ts @@ -9,34 +9,28 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -44,57 +38,63 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = PathlessLayoutNestedLayoutRouteImport.update({ id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -196,25 +196,18 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -224,26 +217,33 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout': { - id: '/_pathlessLayout' + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/posts/': { id: '/posts/' @@ -252,13 +252,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsIndexRouteImport parentRoute: typeof PostsRoute } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } '/posts/$postId': { id: '/posts/$postId' path: '/$postId' @@ -266,19 +259,26 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -287,12 +287,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/solid/start-basic-static/src/routes/deferred.tsx b/examples/solid/start-basic-static/src/routes/deferred.tsx index 11a5c62f8c..17ea8b7400 100644 --- a/examples/solid/start-basic-static/src/routes/deferred.tsx +++ b/examples/solid/start-basic-static/src/routes/deferred.tsx @@ -5,14 +5,14 @@ import { staticFunctionMiddleware } from '@tanstack/start-static-server-function const personServerFn = createServerFn({ method: 'GET' }) .middleware([staticFunctionMiddleware]) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) .middleware([staticFunctionMiddleware]) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/examples/solid/start-basic-static/src/routes/users.$userId.tsx b/examples/solid/start-basic-static/src/routes/users.$userId.tsx index 1b0a2e84b8..2c667b8ceb 100644 --- a/examples/solid/start-basic-static/src/routes/users.$userId.tsx +++ b/examples/solid/start-basic-static/src/routes/users.$userId.tsx @@ -8,7 +8,7 @@ import { staticFunctionMiddleware } from '@tanstack/start-static-server-function const fetchUser = createServerFn({ method: 'GET' }) .middleware([staticFunctionMiddleware]) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data: userId }) => { return axios .get('https://jsonplaceholder.typicode.com/users/' + userId) diff --git a/examples/solid/start-basic-static/src/styles/app.css b/examples/solid/start-basic-static/src/styles/app.css index d6426ccb72..6ab3f34a82 100644 --- a/examples/solid/start-basic-static/src/styles/app.css +++ b/examples/solid/start-basic-static/src/styles/app.css @@ -1,6 +1,24 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; +@import 'tailwindcss' source('../'); + +@source '../**/*.{js,ts,jsx,tsx}'; + +/* + The default border color has changed to `currentcolor` in Tailwind CSS v4, + so we've added these compatibility styles to make sure everything still + looks the same as it did with Tailwind CSS v3. + + If we ever want to remove these styles, we need to add an explicit border + color utility to any element that depends on these defaults. +*/ +@layer base { + *, + ::after, + ::before, + ::backdrop, + ::file-selector-button { + border-color: var(--color-gray-200, currentcolor); + } +} @layer base { html, diff --git a/examples/solid/start-basic-static/src/utils/posts.tsx b/examples/solid/start-basic-static/src/utils/posts.tsx index 166c1787c8..01a6673569 100644 --- a/examples/solid/start-basic-static/src/utils/posts.tsx +++ b/examples/solid/start-basic-static/src/utils/posts.tsx @@ -12,7 +12,7 @@ export type PostType = { export const fetchPost = createServerFn({ method: 'GET' }) .middleware([logMiddleware, staticFunctionMiddleware]) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const post = await axios diff --git a/examples/solid/start-basic-static/tailwind.config.cjs b/examples/solid/start-basic-static/tailwind.config.cjs deleted file mode 100644 index 10c9224f8c..0000000000 --- a/examples/solid/start-basic-static/tailwind.config.cjs +++ /dev/null @@ -1,4 +0,0 @@ -/** @type {import('tailwindcss').Config} */ -module.exports = { - content: ['./src/**/*.{js,ts,jsx,tsx}'], -} diff --git a/examples/solid/start-basic-static/tsconfig.json b/examples/solid/start-basic-static/tsconfig.json index a40235b863..ff0556e7a8 100644 --- a/examples/solid/start-basic-static/tsconfig.json +++ b/examples/solid/start-basic-static/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-basic-static/vite.config.ts b/examples/solid/start-basic-static/vite.config.ts index 97fcbafb57..9d2f632fa3 100644 --- a/examples/solid/start-basic-static/vite.config.ts +++ b/examples/solid/start-basic-static/vite.config.ts @@ -1,16 +1,17 @@ import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteSolid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, + resolve: { + tsconfigPaths: true, + }, plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), + tailwindcss(), tanstackStart({ spa: { enabled: true, diff --git a/examples/solid/start-basic/.devcontainer/devcontainer.json b/examples/solid/start-basic/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-basic/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-basic/package.json b/examples/solid/start-basic/package.json index a386d09792..758815b669 100644 --- a/examples/solid/start-basic/package.json +++ b/examples/solid/start-basic/package.json @@ -7,24 +7,24 @@ "dev": "vite dev", "build": "vite build && tsc --noEmit", "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" + "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwind-merge": "^2.6.0" + "tailwind-merge": "^3.6.0" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10", - "vite-tsconfig-paths": "^5.1.4" + "nitro": "^3.0.260903-beta", + "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" } } diff --git a/examples/solid/start-basic/postcss.config.mjs b/examples/solid/start-basic/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/start-basic/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/start-basic/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-basic/src/components/DefaultCatchBoundary.tsx index 1ae7a0cf94..beff7bc210 100644 --- a/examples/solid/start-basic/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-basic/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error('DefaultCatchBoundary Error:', error) diff --git a/examples/solid/start-basic/src/routeTree.gen.ts b/examples/solid/start-basic/src/routeTree.gen.ts index 7ee820f3c9..8d6c8ffc2b 100644 --- a/examples/solid/start-basic/src/routeTree.gen.ts +++ b/examples/solid/start-basic/src/routeTree.gen.ts @@ -9,36 +9,30 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -46,38 +40,19 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -85,28 +60,53 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => ApiUsersRoute, + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -221,25 +221,18 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -249,47 +242,33 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout': { - id: '/_pathlessLayout' + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/api/users': { id: '/api/users' @@ -298,26 +277,40 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute } - '/api/users/$userId': { - id: '/api/users/$userId' + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -326,12 +319,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/solid/start-basic/src/routes/api/users.$userId.ts b/examples/solid/start-basic/src/routes/api/users.$userId.ts index 65e5da00fc..32a658cb4b 100644 --- a/examples/solid/start-basic/src/routes/api/users.$userId.ts +++ b/examples/solid/start-basic/src/routes/api/users.$userId.ts @@ -1,5 +1,4 @@ import { createFileRoute } from '@tanstack/solid-router' -import { json } from '@tanstack/solid-start' import type { User } from '~/utils/users' export const Route = createFileRoute('/api/users/$userId')({ @@ -15,14 +14,14 @@ export const Route = createFileRoute('/api/users/$userId')({ throw new Error('Failed to fetch user') } const user = (await res.json()) as User - return json({ + return Response.json({ id: user.id, name: user.name, email: user.email, }) } catch (e) { console.error(e) - return json({ error: 'User not found' }, { status: 404 }) + return Response.json({ error: 'User not found' }, { status: 404 }) } }, }, diff --git a/examples/solid/start-basic/src/routes/api/users.ts b/examples/solid/start-basic/src/routes/api/users.ts index 755805280b..f2fa98359a 100644 --- a/examples/solid/start-basic/src/routes/api/users.ts +++ b/examples/solid/start-basic/src/routes/api/users.ts @@ -1,5 +1,5 @@ import { createFileRoute } from '@tanstack/solid-router' -import { createMiddleware, json } from '@tanstack/solid-start' +import { createMiddleware } from '@tanstack/solid-start' import type { User } from '~/utils/users' const userLoggerMiddleware = createMiddleware().server( @@ -50,7 +50,7 @@ export const Route = createFileRoute('/api/users')({ } const data = (await res.json()) as Array const list = data.slice(0, 10) - return json( + return Response.json( list.map((u) => ({ id: u.id, name: u.name, email: u.email })), ) }, diff --git a/examples/solid/start-basic/src/routes/deferred.tsx b/examples/solid/start-basic/src/routes/deferred.tsx index 97c018ab03..1633369b20 100644 --- a/examples/solid/start-basic/src/routes/deferred.tsx +++ b/examples/solid/start-basic/src/routes/deferred.tsx @@ -3,13 +3,13 @@ import { createServerFn } from '@tanstack/solid-start' import { Suspense, createSignal } from 'solid-js' const personServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(({ data: name }) => { return { name, randomNumber: Math.floor(Math.random() * 100) } }) const slowServerFn = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data: name }) => { await new Promise((r) => setTimeout(r, 1000)) return { name, randomNumber: Math.floor(Math.random() * 100) } diff --git a/examples/solid/start-basic/src/routes/users.$userId.tsx b/examples/solid/start-basic/src/routes/users.$userId.tsx index 74279aa20e..489abd1d3d 100644 --- a/examples/solid/start-basic/src/routes/users.$userId.tsx +++ b/examples/solid/start-basic/src/routes/users.$userId.tsx @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/solid-router' -import { NotFound } from 'src/components/NotFound' -import { UserErrorComponent } from 'src/components/UserError' +import { NotFound } from '../components/NotFound' +import { UserErrorComponent } from '../components/UserError' export const Route = createFileRoute('/users/$userId')({ loader: async ({ params: { userId } }) => { diff --git a/examples/solid/start-basic/src/styles/app.css b/examples/solid/start-basic/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/solid/start-basic/src/styles/app.css +++ b/examples/solid/start-basic/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/start-basic/src/utils/posts.tsx b/examples/solid/start-basic/src/utils/posts.tsx index 78c7f7d44a..22db5ebb5f 100644 --- a/examples/solid/start-basic/src/utils/posts.tsx +++ b/examples/solid/start-basic/src/utils/posts.tsx @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const post = await axios diff --git a/examples/solid/start-basic/tsconfig.json b/examples/solid/start-basic/tsconfig.json index a40235b863..ff0556e7a8 100644 --- a/examples/solid/start-basic/tsconfig.json +++ b/examples/solid/start-basic/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-basic/vite.config.ts b/examples/solid/start-basic/vite.config.ts index 1a2219f443..21afe15e79 100644 --- a/examples/solid/start-basic/vite.config.ts +++ b/examples/solid/start-basic/vite.config.ts @@ -1,17 +1,15 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import viteSolid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' +import { nitro } from 'nitro/vite' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteSolid({ ssr: true }), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteSolid({ ssr: true }), nitro()], }) diff --git a/examples/solid/start-bun/.devcontainer/devcontainer.json b/examples/solid/start-bun/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-bun/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-bun/package.json b/examples/solid/start-bun/package.json index 15aaa22ccb..d1ad9a9563 100644 --- a/examples/solid/start-bun/package.json +++ b/examples/solid/start-bun/package.json @@ -13,16 +13,15 @@ "check": "prettier --write . && eslint --fix" }, "dependencies": { - "@tailwindcss/vite": "^4.1.17", + "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-devtools": "^0.7.0", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-router-ssr-query": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", - "@tanstack/router-plugin": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router-ssr-query": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", - "tailwindcss": "^4.1.13", - "vite-tsconfig-paths": "^5.1.4" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@tanstack/eslint-config": "^0.3.2", @@ -30,12 +29,13 @@ "@solidjs/testing-library": "^0.8.10", "@types/bun": "^1.2.22", "@types/node": "22.10.2", - "vite-plugin-solid": "^2.11.10", + "vite-plugin-solid": "^2.11.11", "jsdom": "^27.0.0", "prettier": "^3.6.2", - "typescript": "^5.9.2", - "vite": "^7.1.7", - "vitest": "^3.2.4", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vitest": "^5.0.4", "web-vitals": "^5.1.0" } } diff --git a/examples/solid/start-bun/src/routeTree.gen.ts b/examples/solid/start-bun/src/routeTree.gen.ts index 19009b2f5b..353db2cd02 100644 --- a/examples/solid/start-bun/src/routeTree.gen.ts +++ b/examples/solid/start-bun/src/routeTree.gen.ts @@ -11,8 +11,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as ApiDemoNamesRouteImport } from './routes/api.demo-names' -import { Route as DemoStartServerFuncsRouteImport } from './routes/demo.start.server-funcs' import { Route as DemoStartApiRequestRouteImport } from './routes/demo.start.api-request' +import { Route as DemoStartServerFuncsRouteImport } from './routes/demo.start.server-funcs' const IndexRoute = IndexRouteImport.update({ id: '/', @@ -24,16 +24,16 @@ const ApiDemoNamesRoute = ApiDemoNamesRouteImport.update({ path: '/api/demo-names', getParentRoute: () => rootRouteImport, } as any) -const DemoStartServerFuncsRoute = DemoStartServerFuncsRouteImport.update({ - id: '/demo/start/server-funcs', - path: '/demo/start/server-funcs', - getParentRoute: () => rootRouteImport, -} as any) const DemoStartApiRequestRoute = DemoStartApiRequestRouteImport.update({ id: '/demo/start/api-request', path: '/demo/start/api-request', getParentRoute: () => rootRouteImport, } as any) +const DemoStartServerFuncsRoute = DemoStartServerFuncsRouteImport.update({ + id: '/demo/start/server-funcs', + path: '/demo/start/server-funcs', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -98,13 +98,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ApiDemoNamesRouteImport parentRoute: typeof rootRouteImport } - '/demo/start/server-funcs': { - id: '/demo/start/server-funcs' - path: '/demo/start/server-funcs' - fullPath: '/demo/start/server-funcs' - preLoaderRoute: typeof DemoStartServerFuncsRouteImport - parentRoute: typeof rootRouteImport - } '/demo/start/api-request': { id: '/demo/start/api-request' path: '/demo/start/api-request' @@ -112,6 +105,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DemoStartApiRequestRouteImport parentRoute: typeof rootRouteImport } + '/demo/start/server-funcs': { + id: '/demo/start/server-funcs' + path: '/demo/start/server-funcs' + fullPath: '/demo/start/server-funcs' + preLoaderRoute: typeof DemoStartServerFuncsRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/start-bun/src/routes/demo.start.server-funcs.tsx b/examples/solid/start-bun/src/routes/demo.start.server-funcs.tsx index 65bc7aa96f..eb9e575747 100644 --- a/examples/solid/start-bun/src/routes/demo.start.server-funcs.tsx +++ b/examples/solid/start-bun/src/routes/demo.start.server-funcs.tsx @@ -25,7 +25,7 @@ const getTodos = createServerFn({ }).handler(async () => await readTodos()) const addTodo = createServerFn({ method: 'POST' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data }) => { const todos = await readTodos() todos.push({ id: todos.length + 1, name: data }) diff --git a/examples/solid/start-bun/src/styles.css b/examples/solid/start-bun/src/styles.css index 06f1bca4b0..f59c071ef6 100644 --- a/examples/solid/start-bun/src/styles.css +++ b/examples/solid/start-bun/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); body { @apply m-0; diff --git a/examples/solid/start-bun/src/vite-env.d.ts b/examples/solid/start-bun/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/start-bun/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/start-bun/tsconfig.json b/examples/solid/start-bun/tsconfig.json index 70c9888dea..7d5e1c1aaf 100644 --- a/examples/solid/start-bun/tsconfig.json +++ b/examples/solid/start-bun/tsconfig.json @@ -28,7 +28,6 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, - "baseUrl": ".", "paths": { "@/*": ["./src/*"] } diff --git a/examples/solid/start-bun/vite.config.ts b/examples/solid/start-bun/vite.config.ts index 0a49792ba5..660dc8ed50 100644 --- a/examples/solid/start-bun/vite.config.ts +++ b/examples/solid/start-bun/vite.config.ts @@ -1,19 +1,13 @@ import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import viteSolid from 'vite-plugin-solid' -import viteTsConfigPaths from 'vite-tsconfig-paths' import tailwindcss from '@tailwindcss/vite' const config = defineConfig({ - plugins: [ - // this is the plugin that enables path aliases - viteTsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tailwindcss(), - tanstackStart(), - viteSolid({ ssr: true }), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteSolid({ ssr: true })], }) export default config diff --git a/examples/solid/start-convex-better-auth/.devcontainer/devcontainer.json b/examples/solid/start-convex-better-auth/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-convex-better-auth/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-convex-better-auth/convex/auth.ts b/examples/solid/start-convex-better-auth/convex/auth.ts index e9c2cdb499..7509818aac 100644 --- a/examples/solid/start-convex-better-auth/convex/auth.ts +++ b/examples/solid/start-convex-better-auth/convex/auth.ts @@ -4,6 +4,7 @@ import { betterAuth } from 'better-auth' import { components } from './_generated/api' import { query } from './_generated/server' import type { GenericCtx } from '@convex-dev/better-auth' +import type { BetterAuthOptions } from 'better-auth' import type { DataModel } from './_generated/dataModel' const siteUrl = process.env.SITE_URL! @@ -16,7 +17,7 @@ export const createAuth = ( ctx: GenericCtx, { optionsOnly } = { optionsOnly: false }, ) => { - return betterAuth({ + return betterAuth({ // disable logging when createAuth is called just to generate options. // this is not required, but there's a lot of noise in logs without it. logger: { diff --git a/examples/solid/start-convex-better-auth/package.json b/examples/solid/start-convex-better-auth/package.json index 024209863f..ea13a1c1e3 100644 --- a/examples/solid/start-convex-better-auth/package.json +++ b/examples/solid/start-convex-better-auth/package.json @@ -12,26 +12,26 @@ }, "dependencies": { "@convex-dev/better-auth": "^0.9.7", - "@tailwindcss/vite": "^4.1.17", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", - "better-auth": "^1.3.27", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", + "better-auth": "^1.6.19", "clsx": "^2.1.1", "convex": "^1.28.2", "convex-solidjs": "^0.0.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", - "tailwind-merge": "^2.6.0", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwind-merge": "^3.6.0", + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { "@types/node": "^22.10.2", "combinate": "^1.1.11", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10", - "vite-tsconfig-paths": "^5.1.4" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/start-convex-better-auth/src/library/convex-client.ts b/examples/solid/start-convex-better-auth/src/library/convex-client.ts index 4f60bbdbfd..90dfd5ee28 100644 --- a/examples/solid/start-convex-better-auth/src/library/convex-client.ts +++ b/examples/solid/start-convex-better-auth/src/library/convex-client.ts @@ -3,7 +3,7 @@ import { fetchAuth } from '~/library/server' const CONVEX_URL = import.meta.env.VITE_CONVEX_URL if (!CONVEX_URL) { - console.error('missing envar CONVEX_URL') + throw new Error('missing envar CONVEX_URL') } // Set up Convex client with auth diff --git a/examples/solid/start-convex-better-auth/src/routeTree.gen.ts b/examples/solid/start-convex-better-auth/src/routeTree.gen.ts index e0a4f396fc..d2307d1277 100644 --- a/examples/solid/start-convex-better-auth/src/routeTree.gen.ts +++ b/examples/solid/start-convex-better-auth/src/routeTree.gen.ts @@ -9,24 +9,24 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as AboutRouteImport } from './routes/about' import { Route as AuthedDashboardRouteImport } from './routes/_authed/dashboard' import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthedRoute = AuthedRouteImport.update({ id: '/_authed', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', getParentRoute: () => rootRouteImport, } as any) const AuthedDashboardRoute = AuthedDashboardRouteImport.update({ @@ -83,20 +83,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -104,6 +90,20 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } '/_authed/dashboard': { id: '/_authed/dashboard' path: '/dashboard' diff --git a/examples/solid/start-convex-better-auth/src/styles/app.css b/examples/solid/start-convex-better-auth/src/styles/app.css index 43d97fa7a7..967a7a1e87 100644 --- a/examples/solid/start-convex-better-auth/src/styles/app.css +++ b/examples/solid/start-convex-better-auth/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); body { font-family: diff --git a/examples/solid/start-convex-better-auth/tsconfig.json b/examples/solid/start-convex-better-auth/tsconfig.json index 57ea27b286..4b77b70bcf 100644 --- a/examples/solid/start-convex-better-auth/tsconfig.json +++ b/examples/solid/start-convex-better-auth/tsconfig.json @@ -14,9 +14,9 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { - "~/*": ["./src/*"] + "~/*": ["./src/*"], + "convex/*": ["./convex/*"] }, "noEmit": true } diff --git a/examples/solid/start-convex-better-auth/vite.config.ts b/examples/solid/start-convex-better-auth/vite.config.ts index a74c0fe0d4..659538b94f 100644 --- a/examples/solid/start-convex-better-auth/vite.config.ts +++ b/examples/solid/start-convex-better-auth/vite.config.ts @@ -1,5 +1,4 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import viteSolid from 'vite-plugin-solid' import tailwindcss from '@tailwindcss/vite' @@ -8,12 +7,8 @@ export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tailwindcss(), - tanstackStart(), - viteSolid({ ssr: true }), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteSolid({ ssr: true })], }) diff --git a/examples/solid/start-counter/.devcontainer/devcontainer.json b/examples/solid/start-counter/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-counter/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-counter/package.json b/examples/solid/start-counter/package.json index 9ba31b874a..8b49c516bd 100644 --- a/examples/solid/start-counter/package.json +++ b/examples/solid/start-counter/package.json @@ -10,20 +10,20 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", - "solid-js": "^1.9.10", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", - "zod": "^3.24.2" + "solid-js": "^1.9.10", + "tailwind-merge": "^3.6.0", + "zod": "^4.4.3" }, "devDependencies": { "@types/node": "^22.10.2", - "vite-plugin-solid": "^2.11.10", "combinate": "^1.1.11", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/start-counter/src/routeTree.gen.ts b/examples/solid/start-counter/src/routeTree.gen.ts index 3cc45c071e..7495244535 100644 --- a/examples/solid/start-counter/src/routeTree.gen.ts +++ b/examples/solid/start-counter/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/start-counter/tsconfig.json b/examples/solid/start-counter/tsconfig.json index 57ea27b286..508ace2e17 100644 --- a/examples/solid/start-counter/tsconfig.json +++ b/examples/solid/start-counter/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-counter/vite.config.ts b/examples/solid/start-counter/vite.config.ts index 1a2219f443..e60181d9f2 100644 --- a/examples/solid/start-counter/vite.config.ts +++ b/examples/solid/start-counter/vite.config.ts @@ -1,5 +1,4 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import viteSolid from 'vite-plugin-solid' @@ -7,11 +6,8 @@ export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteSolid({ ssr: true }), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tanstackStart(), viteSolid({ ssr: true })], }) diff --git a/examples/solid/start-i18n-paraglide/.devcontainer/devcontainer.json b/examples/solid/start-i18n-paraglide/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-i18n-paraglide/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-i18n-paraglide/README.md b/examples/solid/start-i18n-paraglide/README.md index eee202e3a1..395c59fb95 100644 --- a/examples/solid/start-i18n-paraglide/README.md +++ b/examples/solid/start-i18n-paraglide/README.md @@ -1,6 +1,6 @@ # TanStack Start example -This example shows how to use Paraglide with TanStack Start. The source code can be found [here](https://github.com/opral/monorepo/tree/main/inlang/packages/paraglide/paraglide-js/examples/tanstack-start). +This example shows how to use Paraglide with TanStack Start. ## Getting started @@ -71,7 +71,7 @@ import handler from '@tanstack/solid-start/server-entry' export default { fetch(req: Request): Promise { - return paraglideMiddleware(req, ({ request }) => handler.fetch(request)) + return paraglideMiddleware(req, () => handler.fetch(req)) }, } ``` diff --git a/examples/solid/start-i18n-paraglide/package.json b/examples/solid/start-i18n-paraglide/package.json index 298e78dfd3..076c9b41dc 100644 --- a/examples/solid/start-i18n-paraglide/package.json +++ b/examples/solid/start-i18n-paraglide/package.json @@ -10,19 +10,30 @@ }, "dependencies": { "@tanstack/solid-devtools": "^0.7.0", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10" }, "devDependencies": { "@types/node": "^22.18.6", - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.9.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4", - "@tailwindcss/vite": "^4.1.17", - "tailwindcss": "^4.1.13", + "vite-plugin-solid": "^2.11.11", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "@tailwindcss/vite": "^4.2.2", + "tailwindcss": "^4.2.2", "@inlang/paraglide-js": "^2.4.0" + }, + "nx": { + "targets": { + "build": { + "outputs": [ + "...", + "{projectRoot}/src/paraglide", + "{projectRoot}/project.inlang/cache" + ] + } + } } } diff --git a/examples/solid/start-i18n-paraglide/src/routeTree.gen.ts b/examples/solid/start-i18n-paraglide/src/routeTree.gen.ts index 3cc45c071e..7495244535 100644 --- a/examples/solid/start-i18n-paraglide/src/routeTree.gen.ts +++ b/examples/solid/start-i18n-paraglide/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/start-i18n-paraglide/src/routes/index.tsx b/examples/solid/start-i18n-paraglide/src/routes/index.tsx index 48f092c754..e08d2ed0f8 100644 --- a/examples/solid/start-i18n-paraglide/src/routes/index.tsx +++ b/examples/solid/start-i18n-paraglide/src/routes/index.tsx @@ -4,7 +4,7 @@ import { m } from '@/paraglide/messages.js' // import { getLocale } from '@/paraglide/runtime.js' const getServerMessage = createServerFn() - .inputValidator((emoji: string) => emoji) + .validator((emoji: string) => emoji) .handler((ctx) => { return m.server_message({ emoji: ctx.data }) }) diff --git a/examples/solid/start-i18n-paraglide/src/server.ts b/examples/solid/start-i18n-paraglide/src/server.ts index fffdaf3ca1..8a521898f2 100644 --- a/examples/solid/start-i18n-paraglide/src/server.ts +++ b/examples/solid/start-i18n-paraglide/src/server.ts @@ -3,6 +3,6 @@ import handler from '@tanstack/solid-start/server-entry' export default { fetch(req: Request): Promise { - return paraglideMiddleware(req, ({ request }) => handler.fetch(request)) + return paraglideMiddleware(req, () => handler.fetch(req)) }, } diff --git a/examples/solid/start-i18n-paraglide/src/styles.css b/examples/solid/start-i18n-paraglide/src/styles.css index d4b5078586..23fa2415ca 100644 --- a/examples/solid/start-i18n-paraglide/src/styles.css +++ b/examples/solid/start-i18n-paraglide/src/styles.css @@ -1 +1 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); diff --git a/examples/solid/start-i18n-paraglide/src/vite-env.d.ts b/examples/solid/start-i18n-paraglide/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/start-i18n-paraglide/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/start-i18n-paraglide/tsconfig.json b/examples/solid/start-i18n-paraglide/tsconfig.json index 522b26852d..8d23f745d0 100644 --- a/examples/solid/start-i18n-paraglide/tsconfig.json +++ b/examples/solid/start-i18n-paraglide/tsconfig.json @@ -22,7 +22,6 @@ "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, - "baseUrl": ".", "paths": { "@/*": ["./src/*"] } diff --git a/examples/solid/start-i18n-paraglide/vite.config.ts b/examples/solid/start-i18n-paraglide/vite.config.ts index 77d18ac832..709f9596f3 100644 --- a/examples/solid/start-i18n-paraglide/vite.config.ts +++ b/examples/solid/start-i18n-paraglide/vite.config.ts @@ -2,10 +2,12 @@ import { paraglideVitePlugin } from '@inlang/paraglide-js' import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import viteSolid from 'vite-plugin-solid' -import viteTsConfigPaths from 'vite-tsconfig-paths' import tailwindcss from '@tailwindcss/vite' const config = defineConfig({ + resolve: { + tsconfigPaths: true, + }, plugins: [ paraglideVitePlugin({ project: './project.inlang', @@ -37,7 +39,6 @@ const config = defineConfig({ }, ], }), - viteTsConfigPaths(), tanstackStart(), viteSolid({ ssr: true }), tailwindcss(), diff --git a/examples/solid/start-large/.devcontainer/devcontainer.json b/examples/solid/start-large/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-large/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-large/package.json b/examples/solid/start-large/package.json index 0b894757ea..83f3589cc2 100644 --- a/examples/solid/start-large/package.json +++ b/examples/solid/start-large/package.json @@ -13,23 +13,22 @@ }, "dependencies": { "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", - "solid-js": "^1.9.10", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0", + "solid-js": "^1.9.10", + "tailwind-merge": "^3.6.0", "valibot": "^1.0.0-beta.15" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "vite-plugin-solid": "^2.11.10", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "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" }, "keywords": [], "author": "", diff --git a/examples/solid/start-large/postcss.config.mjs b/examples/solid/start-large/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/start-large/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/start-large/src/routeTree.gen.ts b/examples/solid/start-large/src/routeTree.gen.ts index 3fb99e1aca..1febe90621 100644 --- a/examples/solid/start-large/src/routeTree.gen.ts +++ b/examples/solid/start-large/src/routeTree.gen.ts @@ -9,23 +9,18 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as RelativeRouteImport } from './routes/relative' -import { Route as LinkPropsRouteImport } from './routes/linkProps' -import { Route as AbsoluteRouteImport } from './routes/absolute' -import { Route as SearchRouteRouteImport } from './routes/search/route' -import { Route as ParamsRouteRouteImport } from './routes/params/route' import { Route as IndexRouteImport } from './routes/index' -import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' +import { Route as AbsoluteRouteImport } from './routes/absolute' +import { Route as LinkPropsRouteImport } from './routes/linkProps' +import { Route as ParamsRouteRouteImport } from './routes/params/route' +import { Route as RelativeRouteImport } from './routes/relative' +import { Route as SearchRouteRouteImport } from './routes/search/route' import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' +import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' -const RelativeRoute = RelativeRouteImport.update({ - id: '/relative', - path: '/relative', - getParentRoute: () => rootRouteImport, -} as any) -const LinkPropsRoute = LinkPropsRouteImport.update({ - id: '/linkProps', - path: '/linkProps', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AbsoluteRoute = AbsoluteRouteImport.update({ @@ -33,9 +28,9 @@ const AbsoluteRoute = AbsoluteRouteImport.update({ path: '/absolute', getParentRoute: () => rootRouteImport, } as any) -const SearchRouteRoute = SearchRouteRouteImport.update({ - id: '/search', - path: '/search', +const LinkPropsRoute = LinkPropsRouteImport.update({ + id: '/linkProps', + path: '/linkProps', getParentRoute: () => rootRouteImport, } as any) const ParamsRouteRoute = ParamsRouteRouteImport.update({ @@ -43,21 +38,26 @@ const ParamsRouteRoute = ParamsRouteRouteImport.update({ path: '/params', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RelativeRoute = RelativeRouteImport.update({ + id: '/relative', + path: '/relative', getParentRoute: () => rootRouteImport, } as any) -const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ - id: '/searchPlaceholder', - path: '/searchPlaceholder', - getParentRoute: () => SearchRouteRoute, +const SearchRouteRoute = SearchRouteRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, } as any) const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ id: '/$paramsPlaceholder', path: '/$paramsPlaceholder', getParentRoute: () => ParamsRouteRoute, } as any) +const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ + id: '/searchPlaceholder', + path: '/searchPlaceholder', + getParentRoute: () => SearchRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -134,18 +134,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/relative': { - id: '/relative' - path: '/relative' - fullPath: '/relative' - preLoaderRoute: typeof RelativeRouteImport - parentRoute: typeof rootRouteImport - } - '/linkProps': { - id: '/linkProps' - path: '/linkProps' - fullPath: '/linkProps' - preLoaderRoute: typeof LinkPropsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/absolute': { @@ -155,11 +148,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AbsoluteRouteImport parentRoute: typeof rootRouteImport } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteRouteImport + '/linkProps': { + id: '/linkProps' + path: '/linkProps' + fullPath: '/linkProps' + preLoaderRoute: typeof LinkPropsRouteImport parentRoute: typeof rootRouteImport } '/params': { @@ -169,19 +162,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ParamsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/relative': { + id: '/relative' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeRouteImport parentRoute: typeof rootRouteImport } - '/search/searchPlaceholder': { - id: '/search/searchPlaceholder' - path: '/searchPlaceholder' - fullPath: '/search/searchPlaceholder' - preLoaderRoute: typeof SearchSearchPlaceholderRouteImport - parentRoute: typeof SearchRouteRoute + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteRouteImport + parentRoute: typeof rootRouteImport } '/params/$paramsPlaceholder': { id: '/params/$paramsPlaceholder' @@ -190,6 +183,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport parentRoute: typeof ParamsRouteRoute } + '/search/searchPlaceholder': { + id: '/search/searchPlaceholder' + path: '/searchPlaceholder' + fullPath: '/search/searchPlaceholder' + preLoaderRoute: typeof SearchSearchPlaceholderRouteImport + parentRoute: typeof SearchRouteRoute + } } } diff --git a/examples/solid/start-large/src/routes/params/$paramsPlaceholder.tsx b/examples/solid/start-large/src/routes/params/$paramsPlaceholder.tsx index d7a62860e5..5c4638851f 100644 --- a/examples/solid/start-large/src/routes/params/$paramsPlaceholder.tsx +++ b/examples/solid/start-large/src/routes/params/$paramsPlaceholder.tsx @@ -14,7 +14,7 @@ const loaderResult = v.object({ }) const middleware = createMiddleware({ type: 'function' }) - .inputValidator(params) + .validator(params) .client(({ next }) => { const context = { client: { paramsPlaceholder: 'paramsPlaceholder' } } return next({ diff --git a/examples/solid/start-large/src/routes/search/searchPlaceholder.tsx b/examples/solid/start-large/src/routes/search/searchPlaceholder.tsx index 0fa857d29c..d61e34357e 100644 --- a/examples/solid/start-large/src/routes/search/searchPlaceholder.tsx +++ b/examples/solid/start-large/src/routes/search/searchPlaceholder.tsx @@ -15,7 +15,7 @@ const loaderResult = v.object({ }) const middleware = createMiddleware({ type: 'function' }) - .inputValidator(search) + .validator(search) .client(({ next }) => { const context = { client: { searchPlaceholder: 'searchPlaceholder' } } return next({ diff --git a/examples/solid/start-large/src/styles.css b/examples/solid/start-large/src/styles.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/solid/start-large/src/styles.css +++ b/examples/solid/start-large/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/start-large/tsconfig.json b/examples/solid/start-large/tsconfig.json index a40235b863..ff0556e7a8 100644 --- a/examples/solid/start-large/tsconfig.json +++ b/examples/solid/start-large/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-large/vite.config.ts b/examples/solid/start-large/vite.config.ts index 27a27a7b5a..3c406c8001 100644 --- a/examples/solid/start-large/vite.config.ts +++ b/examples/solid/start-large/vite.config.ts @@ -1,17 +1,14 @@ import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteSolid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteSolid({ ssr: true }), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteSolid({ ssr: true })], }) diff --git a/examples/solid/start-streaming-data-from-server-functions/.devcontainer/devcontainer.json b/examples/solid/start-streaming-data-from-server-functions/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-streaming-data-from-server-functions/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-streaming-data-from-server-functions/package.json b/examples/solid/start-streaming-data-from-server-functions/package.json index a2efb660dc..83e0719b39 100644 --- a/examples/solid/start-streaming-data-from-server-functions/package.json +++ b/examples/solid/start-streaming-data-from-server-functions/package.json @@ -10,17 +10,17 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { "@types/node": "^22.5.4", - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/start-streaming-data-from-server-functions/tsconfig.json b/examples/solid/start-streaming-data-from-server-functions/tsconfig.json index 57ea27b286..508ace2e17 100644 --- a/examples/solid/start-streaming-data-from-server-functions/tsconfig.json +++ b/examples/solid/start-streaming-data-from-server-functions/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-streaming-data-from-server-functions/vite.config.ts b/examples/solid/start-streaming-data-from-server-functions/vite.config.ts index 27a27a7b5a..7a6ce913f8 100644 --- a/examples/solid/start-streaming-data-from-server-functions/vite.config.ts +++ b/examples/solid/start-streaming-data-from-server-functions/vite.config.ts @@ -1,17 +1,13 @@ import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteSolid from 'vite-plugin-solid' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteSolid({ ssr: true }), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tanstackStart(), viteSolid({ ssr: true })], }) diff --git a/examples/solid/start-supabase-basic/.devcontainer/devcontainer.json b/examples/solid/start-supabase-basic/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-supabase-basic/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-supabase-basic/package.json b/examples/solid/start-supabase-basic/package.json index 8d722ff213..81ab5cd63c 100644 --- a/examples/solid/start-supabase-basic/package.json +++ b/examples/solid/start-supabase-basic/package.json @@ -14,19 +14,19 @@ "dependencies": { "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.9", "redaxios": "^0.5.1" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10", - "vite-tsconfig-paths": "^5.1.4" + "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" } } diff --git a/examples/solid/start-supabase-basic/postcss.config.mjs b/examples/solid/start-supabase-basic/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/start-supabase-basic/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/start-supabase-basic/src/components/DefaultCatchBoundary.tsx b/examples/solid/start-supabase-basic/src/components/DefaultCatchBoundary.tsx index 32aed20e67..6de1f0b377 100644 --- a/examples/solid/start-supabase-basic/src/components/DefaultCatchBoundary.tsx +++ b/examples/solid/start-supabase-basic/src/components/DefaultCatchBoundary.tsx @@ -1,17 +1,15 @@ import { ErrorComponent, Link, - rootRouteId, - useMatch, + useLocation, useRouter, } from '@tanstack/solid-router' import type { ErrorComponentProps } from '@tanstack/solid-router' export function DefaultCatchBoundary({ error }: ErrorComponentProps) { const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, + const isRoot = useLocation({ + select: (location) => location.pathname === '/', }) console.error(error) diff --git a/examples/solid/start-supabase-basic/src/routeTree.gen.ts b/examples/solid/start-supabase-basic/src/routeTree.gen.ts index 86521aa789..bbebb19df3 100644 --- a/examples/solid/start-supabase-basic/src/routeTree.gen.ts +++ b/examples/solid/start-supabase-basic/src/routeTree.gen.ts @@ -9,23 +9,22 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as SignupRouteImport } from './routes/signup' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as SignupRouteImport } from './routes/signup' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -33,13 +32,14 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,18 +120,18 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } '/login': { @@ -141,18 +141,18 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/_authed': { - id: '/_authed' - path: '' - fullPath: '' - preLoaderRoute: typeof AuthedRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/examples/solid/start-supabase-basic/src/routes/_authed.tsx b/examples/solid/start-supabase-basic/src/routes/_authed.tsx index 72e354a3fe..72e7052f56 100644 --- a/examples/solid/start-supabase-basic/src/routes/_authed.tsx +++ b/examples/solid/start-supabase-basic/src/routes/_authed.tsx @@ -4,7 +4,7 @@ import { Login } from '../components/Login' import { getSupabaseServerClient } from '../utils/supabase' export const loginFn = createServerFn({ method: 'POST' }) - .inputValidator((d: { email: string; password: string }) => d) + .validator((d: { email: string; password: string }) => d) .handler(async ({ data }) => { const supabase = getSupabaseServerClient() const { error } = await supabase.auth.signInWithPassword({ diff --git a/examples/solid/start-supabase-basic/src/routes/signup.tsx b/examples/solid/start-supabase-basic/src/routes/signup.tsx index 129a638c94..ab499b5ec0 100644 --- a/examples/solid/start-supabase-basic/src/routes/signup.tsx +++ b/examples/solid/start-supabase-basic/src/routes/signup.tsx @@ -5,7 +5,7 @@ import { Auth } from '../components/Auth' import { getSupabaseServerClient } from '../utils/supabase' export const signupFn = createServerFn({ method: 'POST' }) - .inputValidator( + .validator( (d: { email: string; password: string; redirectUrl?: string }) => d, ) .handler(async ({ data }) => { diff --git a/examples/solid/start-supabase-basic/src/styles/app.css b/examples/solid/start-supabase-basic/src/styles/app.css index 857e5045e3..dcca122a5c 100644 --- a/examples/solid/start-supabase-basic/src/styles/app.css +++ b/examples/solid/start-supabase-basic/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { html { diff --git a/examples/solid/start-supabase-basic/src/utils/posts.ts b/examples/solid/start-supabase-basic/src/utils/posts.ts index 290917db65..f7cc78fec3 100644 --- a/examples/solid/start-supabase-basic/src/utils/posts.ts +++ b/examples/solid/start-supabase-basic/src/utils/posts.ts @@ -9,7 +9,7 @@ export type PostType = { } export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios diff --git a/examples/solid/start-supabase-basic/tsconfig.json b/examples/solid/start-supabase-basic/tsconfig.json index a40235b863..ff0556e7a8 100644 --- a/examples/solid/start-supabase-basic/tsconfig.json +++ b/examples/solid/start-supabase-basic/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-supabase-basic/vite.config.ts b/examples/solid/start-supabase-basic/vite.config.ts index 1a2219f443..659538b94f 100644 --- a/examples/solid/start-supabase-basic/vite.config.ts +++ b/examples/solid/start-supabase-basic/vite.config.ts @@ -1,17 +1,14 @@ import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import viteSolid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteSolid({ ssr: true }), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteSolid({ ssr: true })], }) diff --git a/examples/solid/start-tailwind-v4/.devcontainer/devcontainer.json b/examples/solid/start-tailwind-v4/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/start-tailwind-v4/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/start-tailwind-v4/package.json b/examples/solid/start-tailwind-v4/package.json index 0873afba37..94db6ac790 100644 --- a/examples/solid/start-tailwind-v4/package.json +++ b/examples/solid/start-tailwind-v4/package.json @@ -10,21 +10,20 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/solid-start": "^1.142.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10", - "tailwind-merge": "^2.6.0", - "zod": "^3.24.2" + "tailwind-merge": "^3.6.0", + "zod": "^4.4.3" }, "devDependencies": { - "@tailwindcss/postcss": "^4.1.15", + "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "postcss": "^8.5.1", - "tailwindcss": "^4.1.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10", - "vite-tsconfig-paths": "^5.1.4" + "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" } } diff --git a/examples/solid/start-tailwind-v4/postcss.config.mjs b/examples/solid/start-tailwind-v4/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/start-tailwind-v4/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/start-tailwind-v4/src/routes/__root.tsx b/examples/solid/start-tailwind-v4/src/routes/__root.tsx index 8347bb3b5a..489680b739 100644 --- a/examples/solid/start-tailwind-v4/src/routes/__root.tsx +++ b/examples/solid/start-tailwind-v4/src/routes/__root.tsx @@ -7,7 +7,6 @@ import { createRootRoute, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' -import * as React from 'react' import { HydrationScript } from 'solid-js/web' import type { JSX } from 'solid-js' import appCss from '~/styles/app.css?url' diff --git a/examples/solid/start-tailwind-v4/src/styles/app.css b/examples/solid/start-tailwind-v4/src/styles/app.css index 857e5045e3..dcca122a5c 100644 --- a/examples/solid/start-tailwind-v4/src/styles/app.css +++ b/examples/solid/start-tailwind-v4/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { html { diff --git a/examples/solid/start-tailwind-v4/tsconfig.json b/examples/solid/start-tailwind-v4/tsconfig.json index a40235b863..ff0556e7a8 100644 --- a/examples/solid/start-tailwind-v4/tsconfig.json +++ b/examples/solid/start-tailwind-v4/tsconfig.json @@ -14,7 +14,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/solid/start-tailwind-v4/vite.config.ts b/examples/solid/start-tailwind-v4/vite.config.ts index 27a27a7b5a..3c406c8001 100644 --- a/examples/solid/start-tailwind-v4/vite.config.ts +++ b/examples/solid/start-tailwind-v4/vite.config.ts @@ -1,17 +1,14 @@ import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteSolid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteSolid({ ssr: true }), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteSolid({ ssr: true })], }) diff --git a/examples/solid/view-transitions/.devcontainer/devcontainer.json b/examples/solid/view-transitions/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/view-transitions/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/view-transitions/package.json b/examples/solid/view-transitions/package.json index 5d715be81d..2acb2432bf 100644 --- a/examples/solid/view-transitions/package.json +++ b/examples/solid/view-transitions/package.json @@ -9,19 +9,19 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", - "postcss": "^8.5.1", - "solid-js": "^1.9.10", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "solid-js": "^1.9.10", + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "vite-plugin-solid": "^2.11.10", - "typescript": "^5.7.2", - "vite": "^7.1.7" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/view-transitions/postcss.config.mjs b/examples/solid/view-transitions/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/view-transitions/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/view-transitions/src/routeTree.gen.ts b/examples/solid/view-transitions/src/routeTree.gen.ts index 114e34ed9d..01843027dc 100644 --- a/examples/solid/view-transitions/src/routeTree.gen.ts +++ b/examples/solid/view-transitions/src/routeTree.gen.ts @@ -9,16 +9,16 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as HowItWorksRouteImport } from './routes/how-it-works' -import { Route as ExploreRouteImport } from './routes/explore' -import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as IndexRouteImport } from './routes/index' +import { Route as ExploreRouteImport } from './routes/explore' +import { Route as HowItWorksRouteImport } from './routes/how-it-works' +import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const HowItWorksRoute = HowItWorksRouteImport.update({ - id: '/how-it-works', - path: '/how-it-works', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const ExploreRoute = ExploreRouteImport.update({ @@ -26,16 +26,16 @@ const ExploreRoute = ExploreRouteImport.update({ path: '/explore', getParentRoute: () => rootRouteImport, } as any) +const HowItWorksRoute = HowItWorksRouteImport.update({ + id: '/how-it-works', + path: '/how-it-works', + getParentRoute: () => rootRouteImport, +} as any) const PostsRouteRoute = PostsRouteRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -101,11 +101,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/how-it-works': { - id: '/how-it-works' - path: '/how-it-works' - fullPath: '/how-it-works' - preLoaderRoute: typeof HowItWorksRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/explore': { @@ -115,6 +115,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ExploreRouteImport parentRoute: typeof rootRouteImport } + '/how-it-works': { + id: '/how-it-works' + path: '/how-it-works' + fullPath: '/how-it-works' + preLoaderRoute: typeof HowItWorksRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -122,13 +129,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/solid/view-transitions/src/styles.css b/examples/solid/view-transitions/src/styles.css index 818667133d..b51e6e1244 100644 --- a/examples/solid/view-transitions/src/styles.css +++ b/examples/solid/view-transitions/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/view-transitions/src/vite-env.d.ts b/examples/solid/view-transitions/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/view-transitions/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/view-transitions/vite.config.js b/examples/solid/view-transitions/vite.config.js index 74e9ca3db3..79454008ba 100644 --- a/examples/solid/view-transitions/vite.config.js +++ b/examples/solid/view-transitions/vite.config.js @@ -1,10 +1,12 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'solid', autoCodeSplitting: true, diff --git a/examples/solid/with-framer-motion/.devcontainer/devcontainer.json b/examples/solid/with-framer-motion/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/with-framer-motion/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/with-framer-motion/package.json b/examples/solid/with-framer-motion/package.json index 96fc569e20..449d8a3927 100644 --- a/examples/solid/with-framer-motion/package.json +++ b/examples/solid/with-framer-motion/package.json @@ -9,19 +9,19 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "solid-motionone": "^1.0.4", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/with-framer-motion/postcss.config.mjs b/examples/solid/with-framer-motion/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/with-framer-motion/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/with-framer-motion/src/styles.css b/examples/solid/with-framer-motion/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/with-framer-motion/src/styles.css +++ b/examples/solid/with-framer-motion/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/with-framer-motion/src/vite-env.d.ts b/examples/solid/with-framer-motion/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/with-framer-motion/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/with-framer-motion/vite.config.js b/examples/solid/with-framer-motion/vite.config.js index 05041cc6d8..fb5faf9236 100644 --- a/examples/solid/with-framer-motion/vite.config.js +++ b/examples/solid/with-framer-motion/vite.config.js @@ -1,7 +1,8 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [solid()], + plugins: [tailwindcss(), solid()], }) diff --git a/examples/solid/with-trpc/.devcontainer/devcontainer.json b/examples/solid/with-trpc/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/solid/with-trpc/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/solid/with-trpc/package.json b/examples/solid/with-trpc/package.json index 217665accc..46d33436db 100644 --- a/examples/solid/with-trpc/package.json +++ b/examples/solid/with-trpc/package.json @@ -10,23 +10,22 @@ "start": "NODE_ENV=production node dist/server/server.js" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/solid-router": "^1.141.8", - "@tanstack/solid-router-devtools": "^1.141.8", - "@tanstack/router-plugin": "^1.142.0", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", - "express": "^4.21.2", - "postcss": "^8.5.1", - "solid-js": "^1.9.10", + "express": "^5.2.1", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", - "zod": "^3.24.2" + "solid-js": "^1.9.10", + "tailwindcss": "^4.2.2", + "zod": "^4.4.3" }, "devDependencies": { - "@types/express": "^4.17.23", - "vite-plugin-solid": "^2.11.10", + "@types/express": "^5.0.6", "tsx": "^4.20.3", - "vite": "^7.1.7" + "vite": "^8.0.14", + "vite-plugin-solid": "^2.11.11" } } diff --git a/examples/solid/with-trpc/postcss.config.mjs b/examples/solid/with-trpc/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/solid/with-trpc/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/solid/with-trpc/src/routeTree.gen.ts b/examples/solid/with-trpc/src/routeTree.gen.ts index fd93507694..aa08570aca 100644 --- a/examples/solid/with-trpc/src/routeTree.gen.ts +++ b/examples/solid/with-trpc/src/routeTree.gen.ts @@ -9,23 +9,23 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as DashboardRouteImport } from './routes/dashboard' import { Route as IndexRouteImport } from './routes/index' +import { Route as DashboardRouteImport } from './routes/dashboard' import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' import { Route as DashboardPostsRouteImport } from './routes/dashboard.posts' import { Route as DashboardPostsIndexRouteImport } from './routes/dashboard.posts.index' import { Route as DashboardPostsPostIdRouteImport } from './routes/dashboard.posts.$postId' -const DashboardRoute = DashboardRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const DashboardRoute = DashboardRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => rootRouteImport, +} as any) const DashboardIndexRoute = DashboardIndexRouteImport.update({ id: '/', path: '/', @@ -98,13 +98,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/dashboard': { - id: '/dashboard' - path: '/dashboard' - fullPath: '/dashboard' - preLoaderRoute: typeof DashboardRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -112,6 +105,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/dashboard': { + id: '/dashboard' + path: '/dashboard' + fullPath: '/dashboard' + preLoaderRoute: typeof DashboardRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard/': { id: '/dashboard/' path: '/' diff --git a/examples/solid/with-trpc/src/server/server.ts b/examples/solid/with-trpc/src/server/server.ts index b2b3fd2485..0a580d4963 100644 --- a/examples/solid/with-trpc/src/server/server.ts +++ b/examples/solid/with-trpc/src/server/server.ts @@ -50,7 +50,7 @@ export const createServer = async ( app.use(viteServer.middlewares) // Handle any requests that don't match an API route by serving the React app's index.html - app.get('*', async (req, res, next) => { + app.get('/{*splat}', async (req, res, next) => { try { let html = fs.readFileSync(path.resolve(root, 'index.html'), 'utf-8') @@ -68,7 +68,7 @@ export const createServer = async ( app.use(express.static(path.resolve(__dirname, '../client'))) // Handle any requests that don't match an API route by serving the React app's index.html - app.get('*', (req, res) => { + app.get('/{*splat}', (req, res) => { res.sendFile(path.resolve(__dirname, '../client', 'index.html')) }) } @@ -78,7 +78,8 @@ export const createServer = async ( if (!isTest) { createServer().then(({ app }) => - app.listen(PORT, () => { + app.listen(PORT, (error) => { + if (error) throw error console.info(`Server available at: http://localhost:${PORT}`) }), ) diff --git a/examples/solid/with-trpc/src/styles.css b/examples/solid/with-trpc/src/styles.css index 37a1064738..ce24a390c7 100644 --- a/examples/solid/with-trpc/src/styles.css +++ b/examples/solid/with-trpc/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/solid/with-trpc/src/vite-env.d.ts b/examples/solid/with-trpc/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/solid/with-trpc/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solid/with-trpc/vite.config.ts b/examples/solid/with-trpc/vite.config.ts index 38953f0a2c..553d3030d1 100644 --- a/examples/solid/with-trpc/vite.config.ts +++ b/examples/solid/with-trpc/vite.config.ts @@ -4,6 +4,7 @@ import { defineConfig } from 'vite' import solid from 'vite-plugin-solid' import { tanstackRouter } from '@tanstack/router-plugin/vite' import type { BuildEnvironmentOptions } from 'vite' +import tailwindcss from '@tailwindcss/vite' const __filename = url.fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) @@ -22,7 +23,7 @@ const serverBuildConfig: BuildEnvironmentOptions = { outDir: 'dist/server', copyPublicDir: false, emptyOutDir: true, - rollupOptions: { + rolldownOptions: { input: path.resolve(__dirname, 'src/server/server.ts'), output: { entryFileNames: '[name].js', @@ -36,6 +37,7 @@ const serverBuildConfig: BuildEnvironmentOptions = { export default defineConfig((configEnv) => { return { plugins: [ + tailwindcss(), tanstackRouter({ target: 'solid', autoCodeSplitting: true, diff --git a/examples/vue/basic-file-based-jsx/.devcontainer/devcontainer.json b/examples/vue/basic-file-based-jsx/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/vue/basic-file-based-jsx/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/vue/basic-file-based-jsx/package.json b/examples/vue/basic-file-based-jsx/package.json index 000dd06cdb..9cc36a6991 100644 --- a/examples/vue/basic-file-based-jsx/package.json +++ b/examples/vue/basic-file-based-jsx/package.json @@ -9,27 +9,25 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/router-plugin": "^1.142.0", - "@tanstack/vue-router": "^1.141.8", - "@tanstack/vue-router-devtools": "^1.141.8", - "@tanstack/zod-adapter": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/vue-router": "^1.170.42", + "@tanstack/vue-router-devtools": "^1.167.3", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", + "tailwindcss": "^4.2.2", "vue": "^3.5.16", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { "@eslint/js": "^9.36.0", "@typescript-eslint/eslint-plugin": "^8.44.1", "@typescript-eslint/parser": "^8.44.1", - "@vitejs/plugin-vue": "^5.2.3", - "@vitejs/plugin-vue-jsx": "^4.1.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "eslint-plugin-vue": "^9.33.0", "typescript": "~5.8.3", - "vite": "^7.1.7", + "vite": "^8.0.14", "vue-eslint-parser": "^9.4.3", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/examples/vue/basic-file-based-jsx/postcss.config.mjs b/examples/vue/basic-file-based-jsx/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/vue/basic-file-based-jsx/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/vue/basic-file-based-jsx/src/posts.tsx b/examples/vue/basic-file-based-jsx/src/posts.tsx index 1b4c92b41d..f7a1941605 100644 --- a/examples/vue/basic-file-based-jsx/src/posts.tsx +++ b/examples/vue/basic-file-based-jsx/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts b/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts index 01bb4b0d05..5922c5f7b1 100644 --- a/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts +++ b/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts @@ -11,34 +11,62 @@ import { lazyRouteComponent } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' -import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' -import { Route as SfcComponentRouteImport } from './routes/sfcComponent' -import { Route as RemountDepsRouteImport } from './routes/remountDeps' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' -import { Route as EditingBRouteImport } from './routes/editing-b' -import { Route as EditingARouteImport } from './routes/editing-a' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as EditingARouteImport } from './routes/editing-a' +import { Route as EditingBRouteImport } from './routes/editing-b' +import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RemountDepsRouteImport } from './routes/remountDeps' +import { Route as SfcComponentRouteImport } from './routes/sfcComponent' +import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' +import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' +import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' +import { Route as groupInsideRouteImport } from './routes/(group)/inside' +import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' -import { Route as groupInsideRouteImport } from './routes/(group)/inside' -import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' -import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' -import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' +import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -const Char45824Char54620Char48124Char44397Route = - Char45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => rootRouteImport, - } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const EditingARoute = EditingARouteImport.update({ + id: '/editing-a', + path: '/editing-a', + getParentRoute: () => rootRouteImport, +} as any) +const EditingBRoute = EditingBRouteImport.update({ + id: '/editing-b', + path: '/editing-b', + getParentRoute: () => rootRouteImport, +} as any) +const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ + id: '/notRemountDeps', + path: '/notRemountDeps', + getParentRoute: () => rootRouteImport, +} as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const RemountDepsRoute = RemountDepsRouteImport.update({ + id: '/remountDeps', + path: '/remountDeps', + getParentRoute: () => rootRouteImport, +} as any) const SfcComponentRoute = SfcComponentRouteImport.update({ id: '/sfcComponent', path: '/sfcComponent', @@ -49,39 +77,35 @@ const SfcComponentRoute = SfcComponentRouteImport.update({ 'default', ), }) -const RemountDepsRoute = RemountDepsRouteImport.update({ - id: '/remountDeps', - path: '/remountDeps', +const Char45824Char54620Char48124Char44397Route = + Char45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => rootRouteImport, + } as any) +const anotherGroupOnlyrouteinsideRoute = + anotherGroupOnlyrouteinsideRouteImport.update({ + id: '/(another-group)/onlyrouteinside', + path: '/onlyrouteinside', + getParentRoute: () => rootRouteImport, + } as any) +const groupLayoutRoute = groupLayoutRouteImport.update({ + id: '/(group)/_layout', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const groupInsideRoute = groupInsideRouteImport.update({ + id: '/(group)/inside', + path: '/inside', getParentRoute: () => rootRouteImport, } as any) -const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ - id: '/notRemountDeps', - path: '/notRemountDeps', +const groupLazyinsideRoute = groupLazyinsideRouteImport.update({ + id: '/(group)/lazyinside', + path: '/lazyinside', getParentRoute: () => rootRouteImport, } as any) -const EditingBRoute = EditingBRouteImport.update({ - id: '/editing-b', - path: '/editing-b', - getParentRoute: () => rootRouteImport, -} as any) -const EditingARoute = EditingARouteImport.update({ - id: '/editing-a', - path: '/editing-a', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', @@ -93,54 +117,30 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, -} as any) -const groupLazyinsideRoute = groupLazyinsideRouteImport.update({ - id: '/(group)/lazyinside', - path: '/lazyinside', - getParentRoute: () => rootRouteImport, -} as any) -const groupInsideRoute = groupInsideRouteImport.update({ - id: '/(group)/inside', - path: '/inside', - getParentRoute: () => rootRouteImport, -} as any) -const groupLayoutRoute = groupLayoutRouteImport.update({ - id: '/(group)/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const anotherGroupOnlyrouteinsideRoute = - anotherGroupOnlyrouteinsideRouteImport.update({ - id: '/(another-group)/onlyrouteinside', - path: '/onlyrouteinside', - getParentRoute: () => rootRouteImport, - } as any) -const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ - id: '/posts_/$postId/edit', - path: '/posts/$postId/edit', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, -} as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ + id: '/insidelayout', + path: '/insidelayout', + getParentRoute: () => groupLayoutRoute, } as any) const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport.update({ id: '/(group)/subfolder/inside', path: '/subfolder/inside', getParentRoute: () => rootRouteImport, } as any) -const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ - id: '/insidelayout', - path: '/insidelayout', - getParentRoute: () => groupLayoutRoute, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ + id: '/posts_/$postId/edit', + path: '/posts/$postId/edit', + getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { @@ -291,46 +291,18 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/sfcComponent': { - id: '/sfcComponent' - path: '/sfcComponent' - fullPath: '/sfcComponent' - preLoaderRoute: typeof SfcComponentRouteImport - parentRoute: typeof rootRouteImport - } - '/remountDeps': { - id: '/remountDeps' - path: '/remountDeps' - fullPath: '/remountDeps' - preLoaderRoute: typeof RemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/notRemountDeps': { - id: '/notRemountDeps' - path: '/notRemountDeps' - fullPath: '/notRemountDeps' - preLoaderRoute: typeof NotRemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-b': { - id: '/editing-b' - path: '/editing-b' - fullPath: '/editing-b' - preLoaderRoute: typeof EditingBRouteImport + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } '/editing-a': { @@ -340,20 +312,83 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof EditingARouteImport parentRoute: typeof rootRouteImport } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutRouteImport + '/editing-b': { + id: '/editing-b' + path: '/editing-b' + fullPath: '/editing-b' + preLoaderRoute: typeof EditingBRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/notRemountDeps': { + id: '/notRemountDeps' + path: '/notRemountDeps' + fullPath: '/notRemountDeps' + preLoaderRoute: typeof NotRemountDepsRouteImport parentRoute: typeof rootRouteImport } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/remountDeps': { + id: '/remountDeps' + path: '/remountDeps' + fullPath: '/remountDeps' + preLoaderRoute: typeof RemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/sfcComponent': { + id: '/sfcComponent' + path: '/sfcComponent' + fullPath: '/sfcComponent' + preLoaderRoute: typeof SfcComponentRouteImport + parentRoute: typeof rootRouteImport + } + '/대한민국': { + id: '/대한민국' + path: '/대한민국' + fullPath: '/대한민국' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + parentRoute: typeof rootRouteImport + } + '/(another-group)/onlyrouteinside': { + id: '/(another-group)/onlyrouteinside' + path: '/onlyrouteinside' + fullPath: '/onlyrouteinside' + preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/_layout': { + id: '/(group)/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof groupLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/inside': { + id: '/(group)/inside' + path: '/inside' + fullPath: '/inside' + preLoaderRoute: typeof groupInsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/lazyinside': { + id: '/(group)/lazyinside' + path: '/lazyinside' + fullPath: '/lazyinside' + preLoaderRoute: typeof groupLazyinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } '/posts/': { id: '/posts/' path: '/' @@ -368,61 +403,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/(group)/lazyinside': { - id: '/(group)/lazyinside' - path: '/lazyinside' - fullPath: '/lazyinside' - preLoaderRoute: typeof groupLazyinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/inside': { - id: '/(group)/inside' - path: '/inside' - fullPath: '/inside' - preLoaderRoute: typeof groupInsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/_layout': { - id: '/(group)/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof groupLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/(another-group)/onlyrouteinside': { - id: '/(another-group)/onlyrouteinside' - path: '/onlyrouteinside' - fullPath: '/onlyrouteinside' - preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/posts_/$postId/edit': { - id: '/posts_/$postId/edit' - path: '/posts/$postId/edit' - fullPath: '/posts/$postId/edit' - preLoaderRoute: typeof PostsPostIdEditRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/(group)/_layout/insidelayout': { + id: '/(group)/_layout/insidelayout' + path: '/insidelayout' + fullPath: '/insidelayout' + preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport + parentRoute: typeof groupLayoutRoute } '/(group)/subfolder/inside': { id: '/(group)/subfolder/inside' @@ -431,12 +417,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof groupSubfolderInsideRouteImport parentRoute: typeof rootRouteImport } - '/(group)/_layout/insidelayout': { - id: '/(group)/_layout/insidelayout' - path: '/insidelayout' - fullPath: '/insidelayout' - preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport - parentRoute: typeof groupLayoutRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/posts_/$postId/edit': { + id: '/posts_/$postId/edit' + path: '/posts/$postId/edit' + fullPath: '/posts/$postId/edit' + preLoaderRoute: typeof PostsPostIdEditRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/vue/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx b/examples/vue/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx index 83036509ba..e475111e40 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx @@ -1,28 +1,32 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' + +const OnlyRouteInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ + from: '/(another-group)/onlyrouteinside', + }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
    +
    {searchViaHook.value.hello}
    +
    + {searchViaRouteHook.value.hello} +
    +
    + {searchViaRouteApi.value.hello} +
    +
    + ) + }, +}) export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), component: OnlyRouteInsideComponent, }) const routeApi = getRouteApi('/(another-group)/onlyrouteinside') - -function OnlyRouteInsideComponent() { - const searchViaHook = useSearch({ from: '/(another-group)/onlyrouteinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
    -
    {searchViaHook.value.hello}
    -
    - {searchViaRouteHook.value.hello} -
    -
    - {searchViaRouteApi.value.hello} -
    -
    - ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx b/examples/vue/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx index 557503a0c2..869e536811 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx @@ -1,28 +1,30 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' + +const InsideLayoutComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
    +
    {searchViaHook.value.hello}
    +
    + {searchViaRouteHook.value.hello} +
    +
    + {searchViaRouteApi.value.hello} +
    +
    + ) + }, +}) export const Route = createFileRoute('/(group)/_layout/insidelayout')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), component: InsideLayoutComponent, }) const routeApi = getRouteApi('/(group)/_layout/insidelayout') - -function InsideLayoutComponent() { - const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
    -
    {searchViaHook.value.hello}
    -
    - {searchViaRouteHook.value.hello} -
    -
    - {searchViaRouteApi.value.hello} -
    -
    - ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/(group)/inside.tsx b/examples/vue/basic-file-based-jsx/src/routes/(group)/inside.tsx index bec12d8de2..4a0caa8f8d 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(group)/inside.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(group)/inside.tsx @@ -1,28 +1,30 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' + +const InsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
    +
    {searchViaHook.value.hello}
    +
    + {searchViaRouteHook.value.hello} +
    +
    + {searchViaRouteApi.value.hello} +
    +
    + ) + }, +}) export const Route = createFileRoute('/(group)/inside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), component: InsideComponent, }) const routeApi = getRouteApi('/(group)/inside') - -function InsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
    -
    {searchViaHook.value.hello}
    -
    - {searchViaRouteHook.value.hello} -
    -
    - {searchViaRouteApi.value.hello} -
    -
    - ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx b/examples/vue/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx index 56d8d6cae8..fdae632aee 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx @@ -1,28 +1,30 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' + +const LazyInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
    +
    {searchViaHook.value.hello}
    +
    + {searchViaRouteHook.value.hello} +
    +
    + {searchViaRouteApi.value.hello} +
    +
    + ) + }, +}) export const Route = createFileRoute('/(group)/lazyinside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), component: LazyInsideComponent, }) const routeApi = getRouteApi('/(group)/lazyinside') - -function LazyInsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
    -
    {searchViaHook.value.hello}
    -
    - {searchViaRouteHook.value.hello} -
    -
    - {searchViaRouteApi.value.hello} -
    -
    - ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx b/examples/vue/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx index b4487d163d..8c7222ee70 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx @@ -1,28 +1,30 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' + +const SubfolderInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
    +
    {searchViaHook.value.hello}
    +
    + {searchViaRouteHook.value.hello} +
    +
    + {searchViaRouteApi.value.hello} +
    +
    + ) + }, +}) export const Route = createFileRoute('/(group)/subfolder/inside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), component: SubfolderInsideComponent, }) const routeApi = getRouteApi('/(group)/subfolder/inside') - -function SubfolderInsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
    -
    {searchViaHook.value.hello}
    -
    - {searchViaRouteHook.value.hello} -
    -
    - {searchViaRouteApi.value.hello} -
    -
    - ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/__root.tsx b/examples/vue/basic-file-based-jsx/src/routes/__root.tsx index 59c9e6fa48..adcc3acbd7 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/__root.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/__root.tsx @@ -8,97 +8,100 @@ import { useRouterState, } from '@tanstack/vue-router' import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' +import { defineComponent } from 'vue' import NotFoundComponent from '../components/NotFoundComponent.vue' +const RootComponent = defineComponent({ + setup() { + const router = useRouter() + const canGoBack = useCanGoBack() + // test useRouterState doesn't crash client side navigation + const _state = useRouterState() + + return () => ( + <> + +
    + + + Home + + + Posts + + + Layout + + + Only Route Inside Group + + + Inside Group + + + Inside Subfolder Inside Group + + + Inside Group Inside Layout + + + Lazy Inside Group + + + unicode path + + + This Route Does Not Exist + +
    +
    + + + + ) + }, +}) + export const Route = createRootRoute({ component: RootComponent, notFoundComponent: NotFoundComponent, }) - -function RootComponent() { - const router = useRouter() - const canGoBack = useCanGoBack() - // test useRouterState doesn't crash client side navigation - const _state = useRouterState() - - return ( - <> - -
    - - - Home - - - Posts - - - Layout - - - Only Route Inside Group - - - Inside Group - - - Inside Subfolder Inside Group - - - Inside Group Inside Layout - - - Lazy Inside Group - - - unicode path - - - This Route Does Not Exist - -
    -
    - - - - ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/posts.$postId.tsx b/examples/vue/basic-file-based-jsx/src/routes/posts.$postId.tsx index 15d17387c8..bc1dbfbbd0 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/posts.$postId.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/posts.$postId.tsx @@ -1,24 +1,27 @@ import { createFileRoute } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import PostErrorComponent from '../components/PostErrorComponent.vue' import { fetchPost } from '../posts' import type { PostType } from '../posts' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
    +

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

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

    Post not found

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

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

    -
    {(post.value as PostType).body}
    -
    - ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/posts.tsx b/examples/vue/basic-file-based-jsx/src/routes/posts.tsx index ae580dfc02..522988e52b 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/posts.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/posts.tsx @@ -1,7 +1,38 @@ import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import { fetchPosts } from '../posts' import type { PostType } from '../posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
    +
      + {[ + ...(posts.value as Array), + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
    • + +
      {post.title.substring(0, 20)}
      + +
    • + ))} +
    +
    + +
    + ) + }, +}) + export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -13,31 +44,3 @@ export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
    -
      - {[ - ...(posts.value as Array), - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
    • - -
      {post.title.substring(0, 20)}
      - -
    • - ))} -
    -
    - -
    - ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx b/examples/vue/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx index 57963c6b64..ad20bcdf97 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx @@ -1,23 +1,28 @@ import { createFileRoute, getRouteApi, useParams } from '@tanstack/vue-router' +import { defineComponent } from 'vue' + +const PostEditComponent = defineComponent({ + setup() { + const paramsViaApi = api.useParams() + const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) + const paramsViaRouteHook = api.useParams() + + return () => ( +
    +
    {paramsViaHook.value.postId}
    +
    + {paramsViaRouteHook.value.postId} +
    +
    + {paramsViaApi.value.postId} +
    +
    + ) + }, +}) export const Route = createFileRoute('/posts_/$postId/edit')({ component: PostEditComponent, }) const api = getRouteApi('/posts_/$postId/edit') - -function PostEditComponent() { - const paramsViaApi = api.useParams() - const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) - const paramsViaRouteHook = api.useParams() - - return ( -
    -
    {paramsViaHook.value.postId}
    -
    - {paramsViaRouteHook.value.postId} -
    -
    {paramsViaApi.value.postId}
    -
    - ) -} diff --git a/examples/vue/basic-file-based-jsx/src/styles.css b/examples/vue/basic-file-based-jsx/src/styles.css index 6a03b331e8..4bc1c65d67 100644 --- a/examples/vue/basic-file-based-jsx/src/styles.css +++ b/examples/vue/basic-file-based-jsx/src/styles.css @@ -1,6 +1,6 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); -@source "./**/*.tsx"; +@source './**/*.{ts,tsx,vue}'; @layer base { *, diff --git a/examples/vue/basic-file-based-jsx/src/vite-env.d.ts b/examples/vue/basic-file-based-jsx/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/vue/basic-file-based-jsx/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/vue/basic-file-based-jsx/vite.config.ts b/examples/vue/basic-file-based-jsx/vite.config.ts index 570e6cff2d..466772973f 100644 --- a/examples/vue/basic-file-based-jsx/vite.config.ts +++ b/examples/vue/basic-file-based-jsx/vite.config.ts @@ -2,10 +2,12 @@ import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'vue', autoCodeSplitting: true, diff --git a/examples/vue/basic-file-based-sfc/.devcontainer/devcontainer.json b/examples/vue/basic-file-based-sfc/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/vue/basic-file-based-sfc/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/vue/basic-file-based-sfc/package.json b/examples/vue/basic-file-based-sfc/package.json index 4473b9b7c9..87ab2c332b 100644 --- a/examples/vue/basic-file-based-sfc/package.json +++ b/examples/vue/basic-file-based-sfc/package.json @@ -9,22 +9,20 @@ "start": "vite" }, "dependencies": { - "@tailwindcss/postcss": "^4.1.15", - "@tanstack/router-plugin": "^1.142.0", - "@tanstack/vue-router": "^1.141.8", - "@tanstack/vue-router-devtools": "^1.141.8", - "@tanstack/zod-adapter": "^1.141.8", - "postcss": "^8.5.1", + "@tailwindcss/vite": "^4.2.2", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/vue-router": "^1.170.42", + "@tanstack/vue-router-devtools": "^1.167.3", "redaxios": "^0.5.1", - "tailwindcss": "^4.1.17", + "tailwindcss": "^4.2.2", "vue": "^3.5.16", - "zod": "^3.24.2" + "zod": "^4.4.3" }, "devDependencies": { - "@vitejs/plugin-vue": "^5.2.3", - "@vitejs/plugin-vue-jsx": "^4.1.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", - "vite": "^7.1.7", - "vue-tsc": "^3.1.5" + "vite": "^8.0.14", + "vue-tsc": "^3.3.8" } } diff --git a/examples/vue/basic-file-based-sfc/postcss.config.mjs b/examples/vue/basic-file-based-sfc/postcss.config.mjs deleted file mode 100644 index a7f73a2d1d..0000000000 --- a/examples/vue/basic-file-based-sfc/postcss.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} diff --git a/examples/vue/basic-file-based-sfc/src/posts.ts b/examples/vue/basic-file-based-sfc/src/posts.ts index 1b4c92b41d..f7a1941605 100644 --- a/examples/vue/basic-file-based-sfc/src/posts.ts +++ b/examples/vue/basic-file-based-sfc/src/posts.ts @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts b/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts index ed2e49db39..0bfdddab3d 100644 --- a/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts +++ b/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts @@ -11,75 +11,43 @@ import { lazyRouteComponent } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' -import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' -import { Route as RemountDepsRouteImport } from './routes/remountDeps' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' -import { Route as EditingBRouteImport } from './routes/editing-b' -import { Route as EditingARouteImport } from './routes/editing-a' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as EditingARouteImport } from './routes/editing-a' +import { Route as EditingBRouteImport } from './routes/editing-b' +import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RemountDepsRouteImport } from './routes/remountDeps' +import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' +import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' +import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' +import { Route as groupInsideRouteImport } from './routes/(group)/inside' +import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' -import { Route as groupInsideRouteImport } from './routes/(group)/inside' -import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' -import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' -import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' +import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -const Char45824Char54620Char48124Char44397Route = - Char45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => rootRouteImport, - } as any).update({ - component: lazyRouteComponent( - () => import('./routes/대한민국.component.vue'), - 'default', - ), - }) -const RemountDepsRoute = RemountDepsRouteImport.update({ - id: '/remountDeps', - path: '/remountDeps', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/remountDeps.component.vue'), + () => import('./routes/index.component.vue'), 'default', ), }) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/posts.component.vue'), - 'default', - ), -}) -const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ - id: '/notRemountDeps', - path: '/notRemountDeps', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/notRemountDeps.component.vue'), - 'default', - ), -}) -const EditingBRoute = EditingBRouteImport.update({ - id: '/editing-b', - path: '/editing-b', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/editing-b.component.vue'), + () => import('./routes/_layout.component.vue'), 'default', ), }) @@ -93,22 +61,110 @@ const EditingARoute = EditingARouteImport.update({ 'default', ), }) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const EditingBRoute = EditingBRouteImport.update({ + id: '/editing-b', + path: '/editing-b', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout.component.vue'), + () => import('./routes/editing-b.component.vue'), 'default', ), }) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ + id: '/notRemountDeps', + path: '/notRemountDeps', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/index.component.vue'), + () => import('./routes/notRemountDeps.component.vue'), + 'default', + ), +}) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/posts.component.vue'), + 'default', + ), +}) +const RemountDepsRoute = RemountDepsRouteImport.update({ + id: '/remountDeps', + path: '/remountDeps', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/remountDeps.component.vue'), + 'default', + ), +}) +const Char45824Char54620Char48124Char44397Route = + Char45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => rootRouteImport, + } as any).update({ + component: lazyRouteComponent( + () => import('./routes/대한민국.component.vue'), + 'default', + ), + }) +const anotherGroupOnlyrouteinsideRoute = anotherGroupOnlyrouteinsideRouteImport + .update({ + id: '/(another-group)/onlyrouteinside', + path: '/onlyrouteinside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(another-group)/onlyrouteinside.component.vue'), + 'default', + ), + }) +const groupLayoutRoute = groupLayoutRouteImport + .update({ + id: '/(group)/_layout', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/_layout.component.vue'), + 'default', + ), + }) +const groupInsideRoute = groupInsideRouteImport + .update({ + id: '/(group)/inside', + path: '/inside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/inside.component.vue'), + 'default', + ), + }) +const groupLazyinsideRoute = groupLazyinsideRouteImport + .update({ + id: '/(group)/lazyinside', + path: '/lazyinside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/lazyinside.component.vue'), + 'default', + ), + }) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/_layout/_layout-2.component.vue'), 'default', ), }) @@ -136,69 +192,37 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ 'default', ), }) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport + .update({ + id: '/insidelayout', + path: '/insidelayout', + getParentRoute: () => groupLayoutRoute, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/_layout.insidelayout.component.vue'), + 'default', + ), + }) +const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport + .update({ + id: '/(group)/subfolder/inside', + path: '/subfolder/inside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/subfolder/inside.component.vue'), + 'default', + ), + }) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout/_layout-2.component.vue'), - 'default', - ), -}) -const groupLazyinsideRoute = groupLazyinsideRouteImport - .update({ - id: '/(group)/lazyinside', - path: '/lazyinside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/lazyinside.component.vue'), - 'default', - ), - }) -const groupInsideRoute = groupInsideRouteImport - .update({ - id: '/(group)/inside', - path: '/inside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/inside.component.vue'), - 'default', - ), - }) -const groupLayoutRoute = groupLayoutRouteImport - .update({ - id: '/(group)/_layout', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/_layout.component.vue'), - 'default', - ), - }) -const anotherGroupOnlyrouteinsideRoute = anotherGroupOnlyrouteinsideRouteImport - .update({ - id: '/(another-group)/onlyrouteinside', - path: '/onlyrouteinside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(another-group)/onlyrouteinside.component.vue'), - 'default', - ), - }) -const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ - id: '/posts_/$postId/edit', - path: '/posts/$postId/edit', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/posts_.$postId.edit.component.vue'), + () => import('./routes/_layout/_layout-2/layout-a.component.vue'), 'default', ), }) @@ -212,40 +236,16 @@ const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ 'default', ), }) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ + id: '/posts_/$postId/edit', + path: '/posts/$postId/edit', + getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout/_layout-2/layout-a.component.vue'), + () => import('./routes/posts_.$postId.edit.component.vue'), 'default', ), }) -const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport - .update({ - id: '/(group)/subfolder/inside', - path: '/subfolder/inside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/subfolder/inside.component.vue'), - 'default', - ), - }) -const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport - .update({ - id: '/insidelayout', - path: '/insidelayout', - getParentRoute: () => groupLayoutRoute, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/_layout.insidelayout.component.vue'), - 'default', - ), - }) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -388,39 +388,18 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/remountDeps': { - id: '/remountDeps' - path: '/remountDeps' - fullPath: '/remountDeps' - preLoaderRoute: typeof RemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/notRemountDeps': { - id: '/notRemountDeps' - path: '/notRemountDeps' - fullPath: '/notRemountDeps' - preLoaderRoute: typeof NotRemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-b': { - id: '/editing-b' - path: '/editing-b' - fullPath: '/editing-b' - preLoaderRoute: typeof EditingBRouteImport + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } '/editing-a': { @@ -430,20 +409,76 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof EditingARouteImport parentRoute: typeof rootRouteImport } - '/_layout': { - id: '/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutRouteImport + '/editing-b': { + id: '/editing-b' + path: '/editing-b' + fullPath: '/editing-b' + preLoaderRoute: typeof EditingBRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/notRemountDeps': { + id: '/notRemountDeps' + path: '/notRemountDeps' + fullPath: '/notRemountDeps' + preLoaderRoute: typeof NotRemountDepsRouteImport parentRoute: typeof rootRouteImport } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/remountDeps': { + id: '/remountDeps' + path: '/remountDeps' + fullPath: '/remountDeps' + preLoaderRoute: typeof RemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/대한민국': { + id: '/대한민국' + path: '/대한민국' + fullPath: '/대한민국' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + parentRoute: typeof rootRouteImport + } + '/(another-group)/onlyrouteinside': { + id: '/(another-group)/onlyrouteinside' + path: '/onlyrouteinside' + fullPath: '/onlyrouteinside' + preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/_layout': { + id: '/(group)/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof groupLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/inside': { + id: '/(group)/inside' + path: '/inside' + fullPath: '/inside' + preLoaderRoute: typeof groupInsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/lazyinside': { + id: '/(group)/lazyinside' + path: '/lazyinside' + fullPath: '/lazyinside' + preLoaderRoute: typeof groupLazyinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } '/posts/': { id: '/posts/' path: '/' @@ -458,61 +493,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/(group)/lazyinside': { - id: '/(group)/lazyinside' - path: '/lazyinside' - fullPath: '/lazyinside' - preLoaderRoute: typeof groupLazyinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/inside': { - id: '/(group)/inside' - path: '/inside' - fullPath: '/inside' - preLoaderRoute: typeof groupInsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/_layout': { - id: '/(group)/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof groupLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/(another-group)/onlyrouteinside': { - id: '/(another-group)/onlyrouteinside' - path: '/onlyrouteinside' - fullPath: '/onlyrouteinside' - preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/posts_/$postId/edit': { - id: '/posts_/$postId/edit' - path: '/posts/$postId/edit' - fullPath: '/posts/$postId/edit' - preLoaderRoute: typeof PostsPostIdEditRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/(group)/_layout/insidelayout': { + id: '/(group)/_layout/insidelayout' + path: '/insidelayout' + fullPath: '/insidelayout' + preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport + parentRoute: typeof groupLayoutRoute } '/(group)/subfolder/inside': { id: '/(group)/subfolder/inside' @@ -521,12 +507,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof groupSubfolderInsideRouteImport parentRoute: typeof rootRouteImport } - '/(group)/_layout/insidelayout': { - id: '/(group)/_layout/insidelayout' - path: '/insidelayout' - fullPath: '/insidelayout' - preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport - parentRoute: typeof groupLayoutRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/posts_/$postId/edit': { + id: '/posts_/$postId/edit' + path: '/posts/$postId/edit' + fullPath: '/posts/$postId/edit' + preLoaderRoute: typeof PostsPostIdEditRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/vue/basic-file-based-sfc/src/routes/(another-group)/onlyrouteinside.ts b/examples/vue/basic-file-based-sfc/src/routes/(another-group)/onlyrouteinside.ts index 491bb03649..f427c79321 100644 --- a/examples/vue/basic-file-based-sfc/src/routes/(another-group)/onlyrouteinside.ts +++ b/examples/vue/basic-file-based-sfc/src/routes/(another-group)/onlyrouteinside.ts @@ -1,7 +1,6 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), }) diff --git a/examples/vue/basic-file-based-sfc/src/routes/(group)/_layout.insidelayout.ts b/examples/vue/basic-file-based-sfc/src/routes/(group)/_layout.insidelayout.ts index 49ef8f7bb9..3b605763af 100644 --- a/examples/vue/basic-file-based-sfc/src/routes/(group)/_layout.insidelayout.ts +++ b/examples/vue/basic-file-based-sfc/src/routes/(group)/_layout.insidelayout.ts @@ -1,7 +1,6 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/_layout/insidelayout')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), }) diff --git a/examples/vue/basic-file-based-sfc/src/routes/(group)/inside.ts b/examples/vue/basic-file-based-sfc/src/routes/(group)/inside.ts index f7b06f6a94..456e8fe169 100644 --- a/examples/vue/basic-file-based-sfc/src/routes/(group)/inside.ts +++ b/examples/vue/basic-file-based-sfc/src/routes/(group)/inside.ts @@ -1,7 +1,6 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/inside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), }) diff --git a/examples/vue/basic-file-based-sfc/src/routes/(group)/lazyinside.ts b/examples/vue/basic-file-based-sfc/src/routes/(group)/lazyinside.ts index b66d18a729..7fba56aae4 100644 --- a/examples/vue/basic-file-based-sfc/src/routes/(group)/lazyinside.ts +++ b/examples/vue/basic-file-based-sfc/src/routes/(group)/lazyinside.ts @@ -1,7 +1,6 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/lazyinside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), }) diff --git a/examples/vue/basic-file-based-sfc/src/routes/(group)/subfolder/inside.ts b/examples/vue/basic-file-based-sfc/src/routes/(group)/subfolder/inside.ts index 50aa8a44ad..21e5d7ba0a 100644 --- a/examples/vue/basic-file-based-sfc/src/routes/(group)/subfolder/inside.ts +++ b/examples/vue/basic-file-based-sfc/src/routes/(group)/subfolder/inside.ts @@ -1,7 +1,6 @@ import { createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' -import { zodValidator } from '@tanstack/zod-adapter' export const Route = createFileRoute('/(group)/subfolder/inside')({ - validateSearch: zodValidator(z.object({ hello: z.string().optional() })), + validateSearch: z.object({ hello: z.string().optional() }), }) diff --git a/examples/vue/basic-file-based-sfc/src/styles.css b/examples/vue/basic-file-based-sfc/src/styles.css index 237cc5590d..173bee6195 100644 --- a/examples/vue/basic-file-based-sfc/src/styles.css +++ b/examples/vue/basic-file-based-sfc/src/styles.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @source "./**/*.vue"; @source "./**/*.ts"; diff --git a/examples/vue/basic-file-based-sfc/src/vite-env.d.ts b/examples/vue/basic-file-based-sfc/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/vue/basic-file-based-sfc/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/vue/basic-file-based-sfc/vite.config.ts b/examples/vue/basic-file-based-sfc/vite.config.ts index 570e6cff2d..466772973f 100644 --- a/examples/vue/basic-file-based-sfc/vite.config.ts +++ b/examples/vue/basic-file-based-sfc/vite.config.ts @@ -2,10 +2,12 @@ import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ + tailwindcss(), tanstackRouter({ target: 'vue', autoCodeSplitting: true, diff --git a/examples/vue/basic/.devcontainer/devcontainer.json b/examples/vue/basic/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/vue/basic/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/vue/basic/package.json b/examples/vue/basic/package.json index 99d1d08879..af74afff3a 100644 --- a/examples/vue/basic/package.json +++ b/examples/vue/basic/package.json @@ -9,19 +9,19 @@ "start": "vite" }, "dependencies": { - "@tanstack/vue-router": "^1.141.8", - "@tanstack/vue-router-devtools": "^1.141.8", + "@tanstack/vue-router": "^1.170.42", + "@tanstack/vue-router-devtools": "^1.167.3", "redaxios": "^0.5.1", - "postcss": "^8.5.1", "vue": "^3.5.13", - "autoprefixer": "^10.4.20", - "tailwindcss": "^3.4.17" + "tailwindcss": "4.1.18" }, "devDependencies": { - "typescript": "^5.7.2", - "vite": "^6.1.0", - "vue-tsc": "^3.1.5", - "@vitejs/plugin-vue": "^5.2.3", - "@vitejs/plugin-vue-jsx": "^4.1.2" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vue-tsc": "^3.3.8", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "@tailwindcss/vite": "^4.2.2" } } diff --git a/examples/vue/basic/postcss.config.mjs b/examples/vue/basic/postcss.config.mjs deleted file mode 100644 index 2e7af2b7f1..0000000000 --- a/examples/vue/basic/postcss.config.mjs +++ /dev/null @@ -1,6 +0,0 @@ -export default { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -} diff --git a/examples/vue/basic/src/main.tsx b/examples/vue/basic/src/main.tsx index dc12871db0..09878913a8 100644 --- a/examples/vue/basic/src/main.tsx +++ b/examples/vue/basic/src/main.tsx @@ -1,4 +1,4 @@ -import { createApp } from 'vue' +import { createApp, defineComponent } from 'vue' import { ErrorComponent, Link, @@ -102,6 +102,20 @@ function PostsIndexComponent() { return
    Select a post.
    } +const PostComponent = defineComponent({ + setup() { + const post = postRoute.useLoaderData() + + return () => ( +
    +

    {post.value.title}

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

    {post.value.title}

    -
    -
    {post.value.body}
    -
    - ) -} - const pathlessLayoutRoute = createRoute({ getParentRoute: () => rootRoute, id: '_pathlessLayout', diff --git a/examples/vue/basic/src/posts.lazy.tsx b/examples/vue/basic/src/posts.lazy.tsx index 1fd64723e5..8602de045f 100644 --- a/examples/vue/basic/src/posts.lazy.tsx +++ b/examples/vue/basic/src/posts.lazy.tsx @@ -1,36 +1,39 @@ import { Link, Outlet, createLazyRoute } from '@tanstack/vue-router' +import { defineComponent } from 'vue' + +const PostsLayoutComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
    +
      + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
    • + +
      {post.title.substring(0, 20)}
      + +
    • + ) + })} +
    + +
    + ) + }, +}) export const Route = createLazyRoute('/posts')({ component: PostsLayoutComponent, }) - -function PostsLayoutComponent() { - const posts = Route.useLoaderData() - - return ( -
    -
      - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
    • - -
      {post.title.substring(0, 20)}
      - -
    • - ) - })} -
    - -
    - ) -} diff --git a/examples/vue/basic/src/styles.css b/examples/vue/basic/src/styles.css index 0b8e317099..f62e2e6782 100644 --- a/examples/vue/basic/src/styles.css +++ b/examples/vue/basic/src/styles.css @@ -1,6 +1,24 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; +@import 'tailwindcss' source('../'); + +@source './**/*.{ts,tsx,vue}'; + +/* + The default border color has changed to `currentcolor` in Tailwind CSS v4, + so we've added these compatibility styles to make sure everything still + looks the same as it did with Tailwind CSS v3. + + If we ever want to remove these styles, we need to add an explicit border + color utility to any element that depends on these defaults. +*/ +@layer base { + *, + ::after, + ::before, + ::backdrop, + ::file-selector-button { + border-color: var(--color-gray-200, currentcolor); + } +} html { color-scheme: light dark; diff --git a/examples/vue/basic/src/vite-env.d.ts b/examples/vue/basic/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/examples/vue/basic/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/vue/basic/tailwind.config.mjs b/examples/vue/basic/tailwind.config.mjs deleted file mode 100644 index 4986094b9d..0000000000 --- a/examples/vue/basic/tailwind.config.mjs +++ /dev/null @@ -1,4 +0,0 @@ -/** @type {import('tailwindcss').Config} */ -export default { - content: ['./src/**/*.{js,jsx,ts,tsx}', './index.html'], -} diff --git a/examples/vue/basic/vite.config.js b/examples/vue/basic/vite.config.js index 33d651a84c..e221c1e0e9 100644 --- a/examples/vue/basic/vite.config.js +++ b/examples/vue/basic/vite.config.js @@ -1,8 +1,9 @@ import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import tailwindcss from '@tailwindcss/vite' // https://vitejs.dev/config/ export default defineConfig({ - plugins: [vue(), vueJsx()], + plugins: [tailwindcss(), vue(), vueJsx()], }) diff --git a/labeler-config.yml b/labeler-config.yml index d09a536709..9da92bf7ff 100644 --- a/labeler-config.yml +++ b/labeler-config.yml @@ -1,18 +1,15 @@ 'package: arktype-adapter': - changed-files: - any-glob-to-any-file: 'packages/arktype-adapter/**/*' -'package: directive-functions-plugin': - - changed-files: - - any-glob-to-any-file: 'packages/directive-functions-plugin/**/*' 'package: eslint-plugin-router': - changed-files: - any-glob-to-any-file: 'packages/eslint-plugin-router/**/*' +'package: eslint-plugin-start': + - changed-files: + - any-glob-to-any-file: 'packages/eslint-plugin-start/**/*' 'package: history': - changed-files: - any-glob-to-any-file: 'packages/history/**/*' -'package: nitro-v2-vite-plugin': - - changed-files: - - any-glob-to-any-file: 'packages/nitro-v2-vite-plugin/**/*' 'package: react-router': - changed-files: - any-glob-to-any-file: 'packages/react-router/**/*' @@ -28,6 +25,9 @@ 'package: react-start-client': - changed-files: - any-glob-to-any-file: 'packages/react-start-client/**/*' +'package: react-start-rsc': + - changed-files: + - any-glob-to-any-file: 'packages/react-start-rsc/**/*' 'package: react-start-server': - changed-files: - any-glob-to-any-file: 'packages/react-start-server/**/*' @@ -58,9 +58,6 @@ 'package: router-vite-plugin': - changed-files: - any-glob-to-any-file: 'packages/router-vite-plugin/**/*' -'package: server-functions-plugin': - - changed-files: - - any-glob-to-any-file: 'packages/server-functions-plugin/**/*' 'package: solid-router': - changed-files: - any-glob-to-any-file: 'packages/solid-router/**/*' @@ -82,6 +79,9 @@ 'package: start-client-core': - changed-files: - any-glob-to-any-file: 'packages/start-client-core/**/*' +'package: start-fn-stubs': + - changed-files: + - any-glob-to-any-file: 'packages/start-fn-stubs/**/*' 'package: start-plugin-core': - changed-files: - any-glob-to-any-file: 'packages/start-plugin-core/**/*' diff --git a/media/header_router.png b/media/header_router.png deleted file mode 100644 index 5f2d58134d..0000000000 Binary files a/media/header_router.png and /dev/null differ diff --git a/media/header_start.png b/media/header_start.png deleted file mode 100644 index 8622986ee1..0000000000 Binary files a/media/header_start.png and /dev/null differ diff --git a/nx.json b/nx.json index 4f8c811d34..b7df8b2c09 100644 --- a/nx.json +++ b/nx.json @@ -1,6 +1,7 @@ { "$schema": "./node_modules/nx/schemas/nx-schema.json", "defaultBase": "main", + "bust": "nx24-exclusive-e2e-16-medium-baseline-2026-10-25-05", "nxCloudId": "6442f7de8226a6291646a813", "useInferencePlugins": false, "parallel": 5, @@ -9,10 +10,26 @@ }, "namedInputs": { "sharedGlobals": [ + "{workspaceRoot}/.npmrc", + "{workspaceRoot}/nx.json", + "{workspaceRoot}/.github/workflows/pr.yml", + "{workspaceRoot}/.nx/ci-config.yaml", + "{workspaceRoot}/.nx/workflows/ultracache-config.yaml", "{workspaceRoot}/.nvmrc", "{workspaceRoot}/package.json", "{workspaceRoot}/tsconfig.json" ], + "dependentTaskOutputs": [ + { + "dependentTasksOutputFiles": "**/*", + "transitive": true + } + ], + "streamingSsrTests": [ + "{workspaceRoot}/e2e/streaming-ssr-assertions.ts", + "{workspaceRoot}/e2e/streaming-ssr-fixtures/**/*", + "{workspaceRoot}/e2e/streaming-ssr-specs/**/*" + ], "default": [ "sharedGlobals", "{projectRoot}/**/*", @@ -22,44 +39,126 @@ "default", "!{projectRoot}/tests/**/*", "!{projectRoot}/eslint.config.js" - ] + ], + "buildProduction": ["sharedGlobals", "{projectRoot}/**/*"] }, "targetDefaults": { "test:docs": { "cache": true, - "inputs": ["{workspaceRoot}/docs/**/*"] + "inputs": ["sharedGlobals", "{workspaceRoot}/docs/**/*"] }, "test:eslint": { "cache": true, - "dependsOn": ["^build"], - "inputs": ["default", "^production", "{workspaceRoot}/eslint.config.js"] + "dependsOn": ["^build", "build"], + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "dependentTaskOutputs" + ] }, "test:unit": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"], + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "dependentTaskOutputs" + ], "outputs": ["{projectRoot}/coverage"] }, "test:e2e": { + "cache": true, + "dependsOn": ["^build", "test:e2e--*"], + "inputs": ["buildProduction", "^production", "dependentTaskOutputs"], + "outputs": ["{projectRoot}/dist", "{projectRoot}/test-results"], + "parallelism": false + }, + "test:e2e:nitro": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"] + "inputs": ["default", "^production"], + "parallelism": false + }, + "test:e2e:basepath": { + "cache": true, + "dependsOn": ["^build"], + "inputs": ["default", "^production"], + "parallelism": false + }, + "test:e2e:preview": { + "cache": true, + "dependsOn": ["^build"], + "inputs": ["default", "^production"], + "parallelism": false }, "test:types": { "cache": true, - "dependsOn": ["^build"], - "inputs": ["default", "^production"] + "dependsOn": ["^build", "build"], + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "dependentTaskOutputs" + ] + }, + "test:types:client": { + "cache": true, + "inputs": [ + "default", + "^production", + "{workspaceRoot}/benchmarks/client-nav/*.{ts,json}", + "{workspaceRoot}/benchmarks/client-nav/scenarios/*.ts", + "{workspaceRoot}/benchmarks/client-nav/scenarios/*/*.ts", + "{workspaceRoot}/benchmarks/memory/*.ts", + "{workspaceRoot}/benchmarks/memory/client/*.{ts,json}", + "{workspaceRoot}/benchmarks/memory/client/scenarios/*/*.ts", + "{workspaceRoot}/benchmarks/cpu-simulation.ts", + "dependentTaskOutputs" + ] + }, + "test:types:ssr": { + "cache": true, + "dependsOn": ["^build", "build"], + "inputs": [ + "default", + "^production", + "{workspaceRoot}/benchmarks/ssr/bench-utils.ts", + "{workspaceRoot}/benchmarks/cpu-simulation.ts", + "{workspaceRoot}/benchmarks/ssr/scenarios/*/*.ts", + "{workspaceRoot}/benchmarks/memory/*.ts", + "{workspaceRoot}/benchmarks/memory/server/*.ts", + "{workspaceRoot}/benchmarks/memory/server/scenarios/*/*.ts", + "dependentTaskOutputs" + ] }, "build": { "cache": true, "dependsOn": ["^build"], - "inputs": ["production", "^production"], - "outputs": ["{projectRoot}/build", "{projectRoot}/dist"] + "inputs": ["buildProduction", "^buildProduction", "dependentTaskOutputs"], + "outputs": [ + "{projectRoot}/.netlify", + "{projectRoot}/.wrangler", + "{projectRoot}/.output", + "{projectRoot}/build", + "{projectRoot}/dist" + ] }, "test:build": { "cache": true, "dependsOn": ["build"], - "inputs": ["production"] + "inputs": ["buildProduction", "dependentTaskOutputs"] + }, + "test:e2e*": { + "parallelism": false } - } + }, + "plugins": [ + { + "name": "Playwright Sharding Plugin", + "plugin": "./scripts/nx/playwright-plugin.ts" + } + ], + "analytics": true } diff --git a/package.json b/package.json index 8d7d840dc8..3ef11b1969 100644 --- a/package.json +++ b/package.json @@ -5,31 +5,57 @@ "type": "git", "url": "git+https://github.com/TanStack/router.git" }, - "packageManager": "pnpm@10.24.0", + "packageManager": "pnpm@12.18.0", + "engines": { + "pnpm": ">=12.18.0" + }, "type": "module", "scripts": { "cleanNodeModules": "pnpm -r exec rm -rf node_modules", "clean": "pnpm --filter \"./packages/**\" run clean", "test": "pnpm run test:ci", - "test:pr": "nx affected --targets=test:eslint,test:unit,test:e2e,test:types,test:build,build", - "test:ci": "nx run-many --targets=test:eslint,test:unit,test:e2e,test:types,test:build,build", + "test:pr": "nx affected --targets=test:eslint,test:unit,test:integration,test:e2e,test:types,test:build,build", + "test:ci": "nx run-many --targets=test:eslint,test:unit,test:integration,test:e2e,test:types,test:build,build", "test:eslint": "nx affected --target=test:eslint --exclude=examples/**,e2e/**", "test:unit": "nx affected --target=test:unit --exclude=examples/**,e2e/**", "test:unit:dev": "pnpm run test:unit && nx watch --all -- pnpm run test:unit", "test:build": "nx affected --target=test:build --exclude=examples/**", "test:types": "nx affected --target=test:types --exclude=examples/**", "test:e2e": "nx run-many --target=test:e2e", + "benchmark:bundle-size": "node scripts/benchmarks/bundle-size/build.mjs", + "benchmark:bundle-size:run": "node scripts/benchmarks/bundle-size/run.mjs", + "benchmark:bundle-size:query": "node scripts/benchmarks/bundle-size/query.mjs", + "benchmark:bundle-size:diff": "node scripts/benchmarks/bundle-size/diff.mjs", + "benchmark:bundle-size:history": "node scripts/benchmarks/bundle-size/history.mjs", + "benchmark:bundle-size:analyze": "node scripts/benchmarks/bundle-size/analyze.mjs", + "benchmark:client-nav": "nx run @benchmarks/client-nav:test:perf", + "benchmark:ssr": "nx run @benchmarks/ssr:test:perf", + "benchmark:memory:client:flame": "nx run @benchmarks/memory-client:test:flame:react --parallel=1", + "benchmark:memory:client:flame:react": "nx run @benchmarks/memory-client:test:flame:react --parallel=1", + "benchmark:memory:client:flame:solid": "nx run @benchmarks/memory-client:test:flame:solid --parallel=1", + "benchmark:memory:client:flame:vue": "nx run @benchmarks/memory-client:test:flame:vue --parallel=1", + "benchmark:memory:server:flame": "nx run @benchmarks/memory-server:test:flame:react --parallel=1", + "benchmark:memory:server:flame:react": "nx run @benchmarks/memory-server:test:flame:react --parallel=1", + "benchmark:memory:server:flame:solid": "nx run @benchmarks/memory-server:test:flame:solid --parallel=1", + "benchmark:memory:server:flame:vue": "nx run @benchmarks/memory-server:test:flame:vue --parallel=1", "build": "nx affected --target=build --exclude=e2e/** --exclude=examples/**", "build:all": "nx run-many --target=build --exclude=examples/** --exclude=e2e/**", "watch": "pnpm run build:all && nx watch --all -- pnpm run build:all", "dev": "pnpm run watch", "format": "prettier --experimental-cli --ignore-unknown '**/*' --write", - "cipublish": "node scripts/publish.js", + "changeset": "changeset", + "changeset:publish": "changeset publish", + "changeset:version": "changeset version && pnpm run update:example-deps && pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile && pnpm format", + "update:example-deps": "node scripts/update-example-deps.mjs", "gpt-generate": "node gpt/generate.js", "set-ts-version": "node scripts/set-ts-version.js", "labeler-generate": "node scripts/generate-labeler-config.ts", "cleanup-empty-packages": "node scripts/cleanup-empty-packages.mjs", - "test:docs": "node scripts/verify-links.ts" + "test:docs": "node scripts/verify-links.ts", + "ts:symbol-references": "node scripts/ts-symbol-references.mjs", + "vite-ecosystem-ci:build": "nx run-many --targets=build --projects=@tanstack/router-plugin,@tanstack/start-plugin-core,@tanstack/react-start,@tanstack/react-start-client,@tanstack/react-start-server --skipRemoteCache", + "vite-ecosystem-ci:before-test": "pnpm exec playwright install chromium", + "vite-ecosystem-ci:test": "nx run-many --targets=test:unit --projects=@tanstack/router-plugin,@tanstack/start-plugin-core,@tanstack/react-start-client --skipRemoteCache && nx run-many --target=test:e2e --projects=tanstack-router-e2e-react-basic-file-based,tanstack-router-e2e-react-basic-file-based-code-splitting,tanstack-react-start-e2e-basic,tanstack-vue-start-e2e-basic,tanstack-solid-start-e2e-basic --skipRemoteCache" }, "nx": { "includedScripts": [ @@ -37,93 +63,25 @@ ] }, "devDependencies": { - "@arethetypeswrong/cli": "^0.18.2", - "@eslint-react/eslint-plugin": "^1.26.2", - "@playwright/test": "^1.56.1", - "@tanstack/config": "0.22.0", - "@tanstack/react-query": "^5.90.7", - "@tanstack/query-core": "^5.90.7", - "@types/node": "22.10.2", - "@types/react": "^19.2.2", - "@types/react-dom": "^19.2.2", - "@vitest/browser": "^3.0.6", - "@vitest/ui": "^3.0.6", - "eslint": "^9.22.0", - "eslint-plugin-react-hooks": "^5.1.0", + "@changesets/changelog-github": "^0.7.0", + "@changesets/cli": "^2.30.0", + "@nx/devkit": "24.0.0", + "@playwright/test": "catalog:", + "@swc-node/register": "^1.11.1", + "@tanstack/eslint-config": "0.4.0", + "@types/node": "catalog:", + "eslint": "catalog:", "eslint-plugin-unused-imports": "^4.1.4", - "jsdom": "^25.0.1", - "markdown-link-extractor": "^4.0.2", - "nx": "22.1.3", - "prettier": "^3.6.2", - "publint": "^0.3.15", - "react": "^19.2.0", - "react-dom": "^19.2.0", - "redaxios": "^0.5.1", - "rimraf": "^6.0.1", + "markdown-link-extractor": "^4.0.3", + "nx": "24.0.0", + "prettier": "^3.8.0", "tinyglobby": "^0.2.15", - "typescript": "^5.9.0", - "typescript54": "npm:typescript@5.4", - "typescript55": "npm:typescript@5.5", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "catalog:", + "@typescript/native": "npm:typescript@^7.0.2", "typescript56": "npm:typescript@5.6", "typescript57": "npm:typescript@5.7", "typescript58": "npm:typescript@5.8", - "vite": "^7.1.7", - "vitest": "^3.2.4" - }, - "pnpm": { - "overrides": { - "vite-plugin-dts": "4.0.3", - "solid-js": "1.9.10", - "react": "$react", - "react-dom": "$react-dom", - "@types/react": "$@types/react", - "@types/react-dom": "$@types/react-dom", - "eslint": "$eslint", - "vite": "$vite", - "@types/node": "$@types/node", - "@playwright/test": "$@playwright/test", - "@tanstack/react-query": "$@tanstack/react-query", - "@tanstack/query-core": "$@tanstack/query-core", - "@tanstack/history": "workspace:*", - "@tanstack/router-core": "workspace:*", - "@tanstack/react-router": "workspace:*", - "@tanstack/router-cli": "workspace:*", - "@tanstack/router-devtools": "workspace:*", - "@tanstack/router-devtools-core": "workspace:^", - "@tanstack/react-router-devtools": "workspace:^", - "@tanstack/solid-router-devtools": "workspace:^", - "@tanstack/router-generator": "workspace:*", - "@tanstack/virtual-file-routes": "workspace:*", - "@tanstack/router-plugin": "workspace:*", - "@tanstack/router-vite-plugin": "workspace:*", - "@tanstack/router-ssr-query-core": "workspace:*", - "@tanstack/react-router-ssr-query": "workspace:*", - "@tanstack/solid-router-ssr-query": "workspace:*", - "@tanstack/vue-router-ssr-query": "workspace:*", - "@tanstack/zod-adapter": "workspace:*", - "@tanstack/valibot-adapter": "workspace:*", - "@tanstack/arktype-adapter": "workspace:*", - "@tanstack/react-start": "workspace:*", - "@tanstack/react-start-client": "workspace:*", - "@tanstack/react-start-server": "workspace:*", - "@tanstack/solid-start": "workspace:*", - "@tanstack/solid-start-client": "workspace:*", - "@tanstack/solid-start-server": "workspace:*", - "@tanstack/vue-start": "workspace:*", - "@tanstack/vue-start-client": "workspace:*", - "@tanstack/vue-start-server": "workspace:*", - "@tanstack/start-plugin-core": "workspace:*", - "@tanstack/start-client-core": "workspace:*", - "@tanstack/start-server-core": "workspace:*", - "@tanstack/start-storage-context": "workspace:*", - "@tanstack/vue-router": "workspace:*", - "@tanstack/vue-router-devtools": "workspace:*", - "@tanstack/eslint-plugin-router": "workspace:*", - "@tanstack/server-functions-plugin": "workspace:*", - "@tanstack/directive-functions-plugin": "workspace:*", - "@tanstack/router-utils": "workspace:*", - "@tanstack/start-static-server-functions": "workspace:*", - "@tanstack/nitro-v2-vite-plugin": "workspace:*" - } + "typescript59": "npm:typescript@5.9" } } diff --git a/packages/AGENTS.md b/packages/AGENTS.md new file mode 100644 index 0000000000..0c63c3a15c --- /dev/null +++ b/packages/AGENTS.md @@ -0,0 +1,16 @@ +# Packages + +- Route generation/code splitting live in `router-generator`/`router-plugin`; Start build transforms live in `start-plugin-core`. + +## Router bindings + +- Navigation/render identity is more than href or route membership: same-href navigations can have different history keys, and suspended renders must acknowledge only their own match publication. Preserve those identity checks when optimizing stores or render notifications. +- In navigation params/search, an explicit `undefined` can clear an inherited value; an absent key can inherit it. Preserve that distinction when comparing or memoizing options; React's `useValueStable` uses `deepEqual` with `ignoreUndefined: false`. + +## Tests + +- Inspect test commands: several `test:unit` scripts immediately exit or only echo a message. For these packages, validate behavior in the shared core or consuming e2e app; a successful placeholder target provides no unit coverage. +- For `*-router-ssr-query` changes, run `router-ssr-query-core` unit tests and the affected framework's `e2e/-start/query-integration` tests. The framework wrapper unit targets currently exit without running tests. +- For single-command Vitest targets, append filters after `--`, e.g. `-- tests/link.test.tsx -t "preloading"`. +- `solid-router` and `router-generator` chain two Vitest commands in `test:unit`. Trailing file/name/update arguments reach only the final command. Run the full target for verification: Solid needs browser and server suites; the generator needs fixture generation followed by typechecking. +- For public type changes, add `*.test-d.*` inference regressions and run both unit and type targets. React/Solid Router's TypeScript compiler matrix checks `src`; Vitest runs their inference tests. For changes to inference cost, follow the [type-safety performance guidance](../docs/router/guide/type-safety.md#performance-recommendations); `test:perf` measures runtime, not compiler cost. diff --git a/packages/arktype-adapter/CHANGELOG.md b/packages/arktype-adapter/CHANGELOG.md new file mode 100644 index 0000000000..9e41a6b247 --- /dev/null +++ b/packages/arktype-adapter/CHANGELOG.md @@ -0,0 +1,19 @@ +# @tanstack/arktype-adapter + +## 1.167.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +## 1.166.9 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +## 1.166.8 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) diff --git a/packages/arktype-adapter/package.json b/packages/arktype-adapter/package.json index 525f106204..ceca3fad73 100644 --- a/packages/arktype-adapter/package.json +++ b/packages/arktype-adapter/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/arktype-adapter", - "version": "1.141.8", + "version": "1.167.0", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -27,12 +27,12 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch --typecheck", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", @@ -61,15 +61,24 @@ "src" ], "engines": { - "node": ">=12" + "node": ">=20.19" }, "devDependencies": { "@tanstack/react-router": "workspace:*", "arktype": "^2.1.7", - "@testing-library/jest-dom": "^6.6.3", - "@testing-library/react": "^16.2.0", - "react": "^19.0.0", - "react-dom": "^19.0.0" + "@testing-library/jest-dom": "catalog:", + "@testing-library/react": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "arktype": ">=2.0.0-rc <3", diff --git a/packages/arktype-adapter/tests/index.test.tsx b/packages/arktype-adapter/tests/index.test.tsx index a99ecda9c4..ce6eb74756 100644 --- a/packages/arktype-adapter/tests/index.test.tsx +++ b/packages/arktype-adapter/tests/index.test.tsx @@ -9,7 +9,6 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, expect, test, vi } from 'vitest' import { type } from 'arktype' import { arkTypeValidator } from '../src' -import '@testing-library/jest-dom/vitest' afterEach(() => { vi.resetAllMocks() diff --git a/packages/arktype-adapter/tests/jest-dom.setup.ts b/packages/arktype-adapter/tests/jest-dom.setup.ts new file mode 100644 index 0000000000..8f7cbf15be --- /dev/null +++ b/packages/arktype-adapter/tests/jest-dom.setup.ts @@ -0,0 +1,18 @@ +import * as jestDomMatchers from '@testing-library/jest-dom/matchers' +import { expect } from 'vitest' +import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' + +// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged +// and released, and go back to `import '@testing-library/jest-dom/vitest'`. +// That entry imports `vitest` from its own install location, which can resolve +// a different Vitest copy than the one running these tests, and its types +// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. +// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting +// `@testing-library/jest-dom/vitest` when a setup file path contains it. +expect.extend(jestDomMatchers) + +declare module 'vitest' { + // Type parameter names must match Vitest's declaration for the interfaces to merge. + // eslint-disable-next-line @typescript-eslint/naming-convention + interface Matchers extends TestingLibraryMatchers {} +} diff --git a/packages/arktype-adapter/tsconfig.build.json b/packages/arktype-adapter/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/arktype-adapter/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/arktype-adapter/vite.config.ts b/packages/arktype-adapter/vite.config.ts index 5edc0264cb..8d553e0a59 100644 --- a/packages/arktype-adapter/vite.config.ts +++ b/packages/arktype-adapter/vite.config.ts @@ -1,5 +1,5 @@ import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' import packageJson from './package.json' const config = defineConfig({ @@ -9,12 +9,14 @@ const config = defineConfig({ watch: false, environment: 'jsdom', typecheck: { enabled: true }, + setupFiles: ['./tests/jest-dom.setup.ts'], }, }) export default mergeConfig( config, tanstackViteConfig({ + tsconfigPath: './tsconfig.build.json', entry: './src/index.ts', srcDir: './src', }), diff --git a/packages/directive-functions-plugin/README.md b/packages/directive-functions-plugin/README.md deleted file mode 100644 index 687695557c..0000000000 --- a/packages/directive-functions-plugin/README.md +++ /dev/null @@ -1,5 +0,0 @@ - - -# TanStack Directive Functions Plugin - -See https://tanstack.com/router/latest/docs/framework/react/routing/file-based-routing diff --git a/packages/directive-functions-plugin/package.json b/packages/directive-functions-plugin/package.json deleted file mode 100644 index 33469983d5..0000000000 --- a/packages/directive-functions-plugin/package.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "name": "@tanstack/directive-functions-plugin", - "version": "1.141.0", - "description": "Modern and scalable routing for React applications", - "author": "Tanner Linsley", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/TanStack/router.git", - "directory": "packages/directive-functions-plugin" - }, - "homepage": "https://tanstack.com/start", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/tannerlinsley" - }, - "keywords": [ - "react", - "location", - "router", - "routing", - "async", - "async router", - "typescript" - ], - "scripts": { - "clean": "rimraf ./dist && rimraf ./coverage", - "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit", - "test:unit": "vitest", - "test:unit:dev": "vitest --watch", - "test:eslint": "eslint ./src", - "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", - "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", - "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", - "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", - "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", - "build": "vite build" - }, - "type": "module", - "types": "dist/esm/index.d.ts", - "main": "dist/cjs/index.cjs", - "module": "dist/esm/index.js", - "exports": { - ".": { - "import": { - "types": "./dist/esm/index.d.ts", - "default": "./dist/esm/index.js" - }, - "require": { - "types": "./dist/cjs/index.d.cts", - "default": "./dist/cjs/index.cjs" - } - }, - "./package.json": "./package.json" - }, - "sideEffects": false, - "files": [ - "dist", - "src" - ], - "engines": { - "node": ">=12" - }, - "dependencies": { - "@babel/code-frame": "7.27.1", - "@babel/core": "^7.27.7", - "@babel/traverse": "^7.27.7", - "@babel/types": "^7.27.7", - "@tanstack/router-utils": "workspace:*", - "babel-dead-code-elimination": "^1.0.10", - "pathe": "^2.0.3", - "tiny-invariant": "^1.3.3" - }, - "devDependencies": { - "@types/babel__code-frame": "^7.0.6", - "@types/babel__core": "^7.20.5", - "@types/babel__traverse": "^7.20.7", - "dedent": "^1.6.0", - "vite": "^7.1.7" - }, - "peerDependencies": { - "vite": ">=6.0.0 || >=7.0.0" - } -} diff --git a/packages/directive-functions-plugin/src/compilers.ts b/packages/directive-functions-plugin/src/compilers.ts deleted file mode 100644 index de71df6eaa..0000000000 --- a/packages/directive-functions-plugin/src/compilers.ts +++ /dev/null @@ -1,588 +0,0 @@ -import * as babel from '@babel/core' -import { isIdentifier, isVariableDeclarator } from '@babel/types' -import { codeFrameColumns } from '@babel/code-frame' -import { - deadCodeElimination, - findReferencedIdentifiers, -} from 'babel-dead-code-elimination' -import path from 'pathe' -import { generateFromAst, parseAst } from '@tanstack/router-utils' -import type { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils' - -export interface DirectiveFn { - nodePath: SupportedFunctionPath - functionName: string - functionId: string - extractedFilename: string - filename: string - chunkName: string -} - -export type SupportedFunctionPath = - | babel.NodePath - | babel.NodePath - | babel.NodePath - -export type GenerateFunctionIdFn = (opts: { - filename: string - functionName: string - extractedFilename: string -}) => string - -export type ReplacerFn = (opts: { - fn: string - extractedFilename: string - filename: string - functionId: string - isSourceFn: boolean -}) => string - -// const debug = process.env.TSR_VITE_DEBUG === 'true' - -export type CompileDirectivesOpts = ParseAstOptions & { - directive: string - getRuntimeCode?: (opts: { - directiveFnsById: Record - }) => string - generateFunctionId: GenerateFunctionIdFn - replacer: ReplacerFn - filename: string - root: string - isDirectiveSplitParam: boolean - directiveSplitParam: string -} - -export function compileDirectives(opts: CompileDirectivesOpts): { - compiledResult: GeneratorResult - directiveFnsById: Record -} { - const ast = parseAst(opts) - const refIdents = findReferencedIdentifiers(ast) - const directiveFnsById = findDirectives(ast, { - ...opts, - directiveSplitParam: opts.directiveSplitParam, - isDirectiveSplitParam: opts.isDirectiveSplitParam, - }) - - // Add runtime code if there are directives - if (Object.keys(directiveFnsById).length > 0) { - if (opts.getRuntimeCode) { - const runtimeImport = babel.template.statement( - opts.getRuntimeCode({ directiveFnsById }), - )() - ast.program.body.unshift(runtimeImport) - } - } - - // If we are in the source file, we need to remove all exports - // then make sure that all of our functions are exported under their - // directive name - if (opts.isDirectiveSplitParam) { - safeRemoveExports(ast) - - // Export a single object with all of the functions - // e.g. export { directiveFn1, directiveFn2 } - ast.program.body.push( - babel.types.exportNamedDeclaration( - undefined, - Object.values(directiveFnsById).map((fn) => - babel.types.exportSpecifier( - babel.types.identifier(fn.functionName), - babel.types.identifier(fn.functionName), - ), - ), - ), - ) - } - - deadCodeElimination(ast, refIdents) - - const compiledResult = generateFromAst(ast, { - sourceMaps: true, - sourceFileName: opts.filename, - filename: opts.filename, - }) - - return { - compiledResult, - directiveFnsById, - } -} - -function findNearestVariableName( - path: babel.NodePath, - directive: string, -): string { - let currentPath: babel.NodePath | null = path - const nameParts: Array = [] - - while (currentPath) { - const name = (() => { - // Check for named function expression - if ( - babel.types.isFunctionExpression(currentPath.node) && - currentPath.node.id - ) { - return currentPath.node.id.name - } - - // Handle method chains - if (babel.types.isCallExpression(currentPath.node)) { - const current = currentPath.node.callee - const chainParts: Array = [] - - // Get the nearest method name (if it's a method call) - if (babel.types.isMemberExpression(current)) { - if (babel.types.isIdentifier(current.property)) { - chainParts.unshift(current.property.name) - } - - // Get the base callee - let base = current.object - while (!babel.types.isIdentifier(base)) { - if (babel.types.isCallExpression(base)) { - base = base.callee as babel.types.Expression - } else if (babel.types.isMemberExpression(base)) { - base = base.object - } else { - break - } - } - if (babel.types.isIdentifier(base)) { - chainParts.unshift(base.name) - } - } else if (babel.types.isIdentifier(current)) { - chainParts.unshift(current.name) - } - - if (chainParts.length > 0) { - return chainParts.join('_') - } - } - - // Rest of the existing checks... - if (babel.types.isFunctionDeclaration(currentPath.node)) { - return currentPath.node.id?.name - } - - if (babel.types.isIdentifier(currentPath.node)) { - return currentPath.node.name - } - - if ( - isVariableDeclarator(currentPath.node) && - isIdentifier(currentPath.node.id) - ) { - return currentPath.node.id.name - } - - if ( - babel.types.isClassMethod(currentPath.node) || - babel.types.isObjectMethod(currentPath.node) - ) { - throw new Error( - `"${directive}" in ClassMethod or ObjectMethod not supported`, - ) - } - - return '' - })() - - if (name) { - nameParts.unshift(name) - } - - currentPath = currentPath.parentPath - } - - return nameParts.length > 0 ? nameParts.join('_') : 'anonymous' -} - -function makeIdentifierSafe(identifier: string): string { - return identifier - .replace(/[^a-zA-Z0-9_$]/g, '_') // Replace unsafe chars with underscore - .replace(/^[0-9]/, '_$&') // Prefix leading number with underscore - .replace(/^\$/, '_$') // Prefix leading $ with underscore - .replace(/_{2,}/g, '_') // Collapse multiple underscores - .replace(/^_|_$/g, '') // Trim leading/trailing underscores -} - -export function findDirectives( - ast: babel.types.File, - opts: ParseAstOptions & { - directive: string - replacer?: ReplacerFn - generateFunctionId: GenerateFunctionIdFn - directiveSplitParam: string - filename: string - root: string - isDirectiveSplitParam: boolean - }, -): Record { - const directiveFnsById: Record = {} - const functionNameSet: Set = new Set() - - let programPath: babel.NodePath - - babel.traverse(ast, { - Program(path) { - programPath = path - }, - }) - - // Does the file have the directive in the program body? - const hasFileDirective = ast.program.directives.some( - (directive) => directive.value.value === opts.directive, - ) - const compileDirectiveOpts = { - isDirectiveSplitParam: opts.isDirectiveSplitParam, - } - - // If the entire file has a directive, we need to compile all of the functions that are - // exported by the file. - if (hasFileDirective) { - // Find all of the exported functions - // They must be either function declarations or const function/anonymous function declarations - babel.traverse(ast, { - ExportDefaultDeclaration(path) { - if (babel.types.isFunctionDeclaration(path.node.declaration)) { - compileDirective( - path.get('declaration') as SupportedFunctionPath, - compileDirectiveOpts, - ) - } - }, - ExportNamedDeclaration(path) { - if (babel.types.isFunctionDeclaration(path.node.declaration)) { - compileDirective( - path.get('declaration') as SupportedFunctionPath, - compileDirectiveOpts, - ) - } - }, - ExportDeclaration(path) { - if ( - babel.types.isExportNamedDeclaration(path.node) && - babel.types.isVariableDeclaration(path.node.declaration) && - (babel.types.isFunctionExpression( - path.node.declaration.declarations[0]?.init, - ) || - babel.types.isArrowFunctionExpression( - path.node.declaration.declarations[0]?.init, - )) - ) { - compileDirective( - path.get( - 'declaration.declarations.0.init', - ) as SupportedFunctionPath, - compileDirectiveOpts, - ) - } - }, - }) - } else { - // Find all directives - babel.traverse(ast, { - DirectiveLiteral(nodePath) { - if (nodePath.node.value === opts.directive) { - const directiveFn = nodePath.findParent((p) => p.isFunction()) - - if (!directiveFn) return - - // Handle class and object methods which are not supported - const isClassMethod = directiveFn.isClassMethod() - const isObjectMethod = directiveFn.isObjectMethod() - - if (isClassMethod || isObjectMethod) { - throw codeFrameError( - opts.code, - directiveFn.node.loc, - `"${opts.directive}" in ${isClassMethod ? 'class' : isObjectMethod ? 'object method' : ''} not supported`, - ) - } - - // If the function is inside another block that isn't the program, - // Error out. This is not supported. - const nearestBlock = directiveFn.findParent( - (p) => (p.isBlockStatement() || p.isScopable()) && !p.isProgram(), - ) - - if (nearestBlock) { - throw codeFrameError( - opts.code, - nearestBlock.node.loc, - `"${opts.directive}" cannot be nested in other blocks or functions`, - ) - } - - if ( - !directiveFn.isFunctionDeclaration() && - !directiveFn.isFunctionExpression() && - !( - directiveFn.isArrowFunctionExpression() && - babel.types.isBlockStatement(directiveFn.node.body) - ) - ) { - throw codeFrameError( - opts.code, - directiveFn.node.loc, - `"${opts.directive}" must be function declarations or function expressions`, - ) - } - - compileDirective(directiveFn, compileDirectiveOpts) - } - }, - }) - } - - return directiveFnsById - - function compileDirective( - directiveFn: SupportedFunctionPath, - compileDirectiveOpts: { isDirectiveSplitParam: boolean }, - ) { - // Move the function to program level while preserving its position - // in the program body - const programBody = programPath.node.body - - // Remove the directive directive from the function body - if ( - babel.types.isFunction(directiveFn.node) && - babel.types.isBlockStatement(directiveFn.node.body) - ) { - directiveFn.node.body.directives = - directiveFn.node.body.directives.filter( - (directive) => directive.value.value !== opts.directive, - ) - } - - // if the directive function is a top-level function, we need to create a const declaration - // using the same name as the function and replace the function with the variable declaration - // that points to the function - if (directiveFn.parentPath.isProgram()) { - if (!babel.types.isFunctionDeclaration(directiveFn.node)) { - throw new Error('Top level functions must be function declarations') - } - - const index = programBody.indexOf(directiveFn.node) - - // First get the name of the function - const originalFunctionName = directiveFn.node.id!.name - - // Now turn the function into an anonymous function - directiveFn.node.id = null - - const variableDeclaration = babel.types.variableDeclaration('const', [ - babel.types.variableDeclarator( - babel.types.identifier(originalFunctionName), - babel.types.toExpression(directiveFn.node as any), - ), - ]) - - directiveFn.replaceWith(variableDeclaration) - - directiveFn = programPath.get( - `body.${index}.declarations.0.init`, - ) as SupportedFunctionPath - } - - // Find the nearest variable name - let functionName = findNearestVariableName(directiveFn, opts.directive) - - const incrementFunctionNameVersion = (functionName: string) => { - const [realReferenceName, count] = functionName.split(/_(\d+)$/) - const resolvedCount = Number(count || '0') - const suffix = `_${resolvedCount + 1}` - return makeIdentifierSafe(realReferenceName!) + suffix - } - - while (functionNameSet.has(functionName)) { - functionName = incrementFunctionNameVersion(functionName) - } - - functionNameSet.add(functionName) - - while (programPath.scope.hasBinding(functionName)) { - functionName = incrementFunctionNameVersion(functionName) - programPath.scope.crawl() - } - - functionNameSet.add(functionName) - - const topParent = - directiveFn.findParent((p) => !!p.parentPath?.isProgram()) || directiveFn - - const topParentIndex = programBody.indexOf(topParent.node as any) - - // If the function has a parent that isn't the program, - // we need to replace it with an identifier and - // hoist the function to the top level as a const declaration - if (directiveFn.parentPath.isProgram()) { - throw new Error( - 'Top level functions should have already been compiled to variable declarations by this point', - ) - } - // Then place the function at the top level - programBody.splice( - topParentIndex, - 0, - babel.types.variableDeclaration('const', [ - babel.types.variableDeclarator( - babel.types.identifier(functionName), - babel.types.toExpression(directiveFn.node as any), - ), - ]), - ) - - // If it's an exported named function, we need to swap it with an - // export const originalFunctionName = functionName - if ( - (babel.types.isExportNamedDeclaration(directiveFn.parentPath.node) || - (compileDirectiveOpts.isDirectiveSplitParam && - babel.types.isExportDefaultDeclaration( - directiveFn.parentPath.node, - ))) && - (babel.types.isFunctionDeclaration(directiveFn.node) || - babel.types.isFunctionExpression(directiveFn.node)) && - babel.types.isIdentifier(directiveFn.node.id) - ) { - const originalFunctionName = directiveFn.node.id.name - programBody.splice( - topParentIndex + 1, - 0, - babel.types.exportNamedDeclaration( - babel.types.variableDeclaration('const', [ - babel.types.variableDeclarator( - babel.types.identifier(originalFunctionName), - babel.types.identifier(functionName), - ), - ]), - ), - ) - - directiveFn.remove() - } else { - directiveFn.replaceWith(babel.types.identifier(functionName)) - } - - directiveFn = programPath.get( - `body.${topParentIndex}.declarations.0.init`, - ) as SupportedFunctionPath - - const [baseFilename, ..._searchParams] = opts.filename.split('?') as [ - string, - ...Array, - ] - const searchParams = new URLSearchParams(_searchParams.join('&')) - searchParams.set(opts.directiveSplitParam, '') - - const extractedFilename = `${baseFilename}?${searchParams.toString()}` - - // Relative to have constant functionId regardless of the machine - // that we are executing - const relativeFilename = path.relative(opts.root, baseFilename) - const functionId = opts.generateFunctionId({ - filename: relativeFilename, - functionName, - extractedFilename, - }) - // If a replacer is provided, replace the function with the replacer - if (opts.replacer) { - const replacer = opts.replacer({ - fn: '$$fn$$', - extractedFilename, - filename: opts.filename, - functionId, - isSourceFn: !!opts.directiveSplitParam, - }) - - const replacement = babel.template.expression(replacer, { - placeholderPattern: false, - placeholderWhitelist: new Set(['$$fn$$']), - })({ - ...(replacer.includes('$$fn$$') - ? { $$fn$$: babel.types.toExpression(directiveFn.node) } - : {}), - }) - - directiveFn.replaceWith(replacement) - } - - // Finally register the directive to - // our map of directives - directiveFnsById[functionId] = { - nodePath: directiveFn, - functionName, - functionId, - extractedFilename, - filename: opts.filename, - chunkName: fileNameToChunkName(opts.root, extractedFilename), - } - } -} - -function codeFrameError( - code: string, - loc: - | { - start: { line: number; column: number } - end: { line: number; column: number } - } - | undefined - | null, - message: string, -) { - if (!loc) { - return new Error(`${message} at unknown location`) - } - - const frame = codeFrameColumns( - code, - { - start: loc.start, - end: loc.end, - }, - { - highlightCode: true, - message, - }, - ) - - return new Error(frame) -} - -const safeRemoveExports = (ast: babel.types.File) => { - ast.program.body = ast.program.body.flatMap((node) => { - if ( - babel.types.isExportNamedDeclaration(node) || - babel.types.isExportDefaultDeclaration(node) - ) { - if ( - babel.types.isFunctionDeclaration(node.declaration) || - babel.types.isClassDeclaration(node.declaration) || - babel.types.isVariableDeclaration(node.declaration) - ) { - // do not remove export if it is an anonymous function / class, otherwise this would produce a syntax error - if ( - babel.types.isFunctionDeclaration(node.declaration) || - babel.types.isClassDeclaration(node.declaration) - ) { - if (!node.declaration.id) { - return node - } - } - return node.declaration - } else if (node.declaration === null) { - // remove e.g. `export { RouteComponent as component }` - return [] - } - } - return node - }) -} - -function fileNameToChunkName(root: string, fileName: string) { - // Replace anything that can't go into an import statement - return fileName.replace(root, '').replace(/[^a-zA-Z0-9_]/g, '_') -} diff --git a/packages/directive-functions-plugin/src/index.ts b/packages/directive-functions-plugin/src/index.ts deleted file mode 100644 index d34a7e7196..0000000000 --- a/packages/directive-functions-plugin/src/index.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { fileURLToPath, pathToFileURL } from 'node:url' - -import { logDiff } from '@tanstack/router-utils' -import { compileDirectives } from './compilers' -import type { - CompileDirectivesOpts, - DirectiveFn, - GenerateFunctionIdFn, -} from './compilers' -import type { Plugin } from 'vite' - -const debug = - process.env.TSR_VITE_DEBUG && - ['true', 'directives-functions-plugin'].includes(process.env.TSR_VITE_DEBUG) - -export type { - DirectiveFn, - CompileDirectivesOpts, - ReplacerFn, - GenerateFunctionIdFn, -} from './compilers' - -export type DirectiveFunctionsViteEnvOptions = Pick< - CompileDirectivesOpts, - 'getRuntimeCode' | 'replacer' -> -export type DirectiveFunctionsViteOptions = DirectiveFunctionsViteEnvOptions & { - directive: string - onDirectiveFnsById?: (directiveFnsById: Record) => void - generateFunctionId: GenerateFunctionIdFn -} - -const createDirectiveRx = (directive: string) => - new RegExp(`"${directive}"|'${directive}'`, 'gm') - -export type DirectiveFunctionsVitePluginEnvOptions = { - directive: string - callers: Array - provider: DirectiveFunctionsViteEnvOptions & { envName: string } - onDirectiveFnsById?: (directiveFnsById: Record) => void - generateFunctionId: GenerateFunctionIdFn -} - -function buildDirectiveSplitParam(directive: string) { - return `tsr-directive-${directive.replace(/[^a-zA-Z0-9]/g, '-')}` -} - -export function TanStackDirectiveFunctionsPluginEnv( - opts: DirectiveFunctionsVitePluginEnvOptions, -): Plugin { - let root: string = process.cwd() - - const directiveRx = createDirectiveRx(opts.directive) - - const appliedEnvironments = new Set([ - ...opts.callers.map((c) => c.envName), - opts.provider.envName, - ]) - - const directiveSplitParam = buildDirectiveSplitParam(opts.directive) - - return { - name: 'tanstack-start-directive-vite-plugin', - enforce: 'pre', - buildStart() { - root = this.environment.config.root - }, - applyToEnvironment(env) { - return appliedEnvironments.has(env.name) - }, - transform: { - filter: { - code: directiveRx, - }, - handler(code, id) { - const url = pathToFileURL(id) - url.searchParams.delete('v') - id = fileURLToPath(url).replace(/\\/g, '/') - - const isDirectiveSplitParam = id.includes(directiveSplitParam) - - let envOptions: DirectiveFunctionsViteEnvOptions & { envName: string } - if (isDirectiveSplitParam) { - envOptions = opts.provider - if (debug) - console.info( - `Compiling Directives for provider in environment ${envOptions.envName}: `, - id, - ) - } else { - envOptions = opts.callers.find( - (e) => e.envName === this.environment.name, - )! - if (debug) - console.info( - `Compiling Directives for caller in environment ${envOptions.envName}: `, - id, - ) - } - const { compiledResult, directiveFnsById } = compileDirectives({ - directive: opts.directive, - getRuntimeCode: envOptions.getRuntimeCode, - generateFunctionId: opts.generateFunctionId, - replacer: envOptions.replacer, - code, - root, - filename: id, - directiveSplitParam, - isDirectiveSplitParam, - }) - // when we process a file with a directive split param, we have already encountered the directives in that file - // (otherwise we wouldn't have gotten here) - if (!isDirectiveSplitParam) { - opts.onDirectiveFnsById?.(directiveFnsById) - } - - if (debug) { - logDiff(code, compiledResult.code) - console.log('Output:\n', compiledResult.code + '\n\n') - } - - return compiledResult - }, - }, - } -} diff --git a/packages/directive-functions-plugin/tests/compiler.test.ts b/packages/directive-functions-plugin/tests/compiler.test.ts deleted file mode 100644 index e6d993c999..0000000000 --- a/packages/directive-functions-plugin/tests/compiler.test.ts +++ /dev/null @@ -1,978 +0,0 @@ -import { describe, expect, test } from 'vitest' - -import { compileDirectives } from '../src/compilers' -import type { CompileDirectivesOpts } from '../src/compilers' - -function makeFunctionIdUrlSafe(location: string): string { - return location - .replace(/[^a-zA-Z0-9-_]/g, '_') // Replace unsafe chars with underscore - .replace(/_{2,}/g, '_') // Collapse multiple underscores - .replace(/^_|_$/g, '') // Trim leading/trailing underscores - .replace(/_--/g, '--') // Clean up the joiner -} - -const generateFunctionId: CompileDirectivesOpts['generateFunctionId'] = ( - opts, -) => { - return makeFunctionIdUrlSafe(`${opts.filename}--${opts.functionName}`) -} - -const clientConfig: Omit = { - directive: 'use server', - root: './test-files', - filename: './test-files/test.ts', - getRuntimeCode: () => 'import { createClientRpc } from "my-rpc-lib-client"', - generateFunctionId, - replacer: (opts) => `createClientRpc(${JSON.stringify(opts.functionId)})`, - directiveSplitParam: 'tsr-directive-use-server', - isDirectiveSplitParam: false, -} - -const ssrConfig: Omit = { - directive: 'use server', - root: './test-files', - filename: './test-files/test.ts', - getRuntimeCode: () => 'import { createSsrRpc } from "my-rpc-lib-server"', - generateFunctionId, - replacer: (opts) => `createSsrRpc(${JSON.stringify(opts.functionId)})`, - directiveSplitParam: 'tsr-directive-use-server', - isDirectiveSplitParam: false, -} - -const serverConfig: Omit = { - directive: 'use server', - root: './test-files', - filename: './test-files/test.ts', - getRuntimeCode: () => 'import { createServerRpc } from "my-rpc-lib-server"', - generateFunctionId, - replacer: (opts) => - // On the server build, we need different code for the split function - // vs any other server functions the split function may reference - - // For the split function itself, we use the original function. - // For any other server functions the split function may reference, - // we use the splitImportFn which is a dynamic import of the split file. - `createServerRpc(${JSON.stringify(opts.functionId)}, ${opts.fn})`, - directiveSplitParam: 'tsr-directive-use-server', - isDirectiveSplitParam: true, -} - -describe('server function compilation', () => { - test('basic function declaration nested in other variable', () => { - const code = ` - export const namedFunction = createServerFn(function namedFunction() { - 'use server' - return 'hello' - }) - - export const namedGeneratorFunction = createServerFn(function* namedGeneratorFunction () { - 'use server' - yield 'hello' - return 'hello world' - }) - - export const arrowFunction = createServerFn(() => { - 'use server' - return 'hello' - }) - - export const anonymousFunction = createServerFn(function () { - 'use server' - return 'hello' - }) - - export const anonymousGeneratorFunction = createServerFn(function* () { - 'use server' - yield 'hello' - return 'hello world' - }) - - export const multipleDirectives = function multipleDirectives() { - 'use server' - 'use strict' - return 'hello' - } - - export const iife = (function () { - 'use server' - return 'hello' - })() - - export default function defaultExportFn() { - 'use server' - return 'hello' - } - - export function namedExportFn() { - 'use server' - return 'hello' - } - - export const exportedArrowFunction = wrapper(() => { - 'use server' - return 'hello' - }) - - export const namedExportConst = () => { - 'use server' - return usedFn() - } - - export const namedExportConstGenerator = function* () { - 'use server' - yield 'hello' - return usedFn() - } - - function usedFn() { - return 'hello' - } - - function unusedFn() { - return 'hello' - } - - const namedDefaultExport = 'namedDefaultExport' - export default namedDefaultExport - - const usedButNotExported = 'usedButNotExported' - - const namedExport = 'namedExport' - - export { - namedExport - } - ` - const client = compileDirectives({ - ...clientConfig, - code, - }) - const ssr = compileDirectives({ ...ssrConfig, code }) - - const server = compileDirectives({ - ...serverConfig, - code, - filename: `${ssr.directiveFnsById[Object.keys(ssr.directiveFnsById)[0]!]!.extractedFilename}`, - }) - - expect(client.compiledResult.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib-client"; - const namedFunction_createServerFn_namedFunction = createClientRpc("test_ts--namedFunction_createServerFn_namedFunction"); - export const namedFunction = createServerFn(namedFunction_createServerFn_namedFunction); - const namedGeneratorFunction_createServerFn_namedGeneratorFunction = createClientRpc("test_ts--namedGeneratorFunction_createServerFn_namedGeneratorFunction"); - export const namedGeneratorFunction = createServerFn(namedGeneratorFunction_createServerFn_namedGeneratorFunction); - const arrowFunction_createServerFn = createClientRpc("test_ts--arrowFunction_createServerFn"); - export const arrowFunction = createServerFn(arrowFunction_createServerFn); - const anonymousFunction_createServerFn = createClientRpc("test_ts--anonymousFunction_createServerFn"); - export const anonymousFunction = createServerFn(anonymousFunction_createServerFn); - const anonymousGeneratorFunction_createServerFn = createClientRpc("test_ts--anonymousGeneratorFunction_createServerFn"); - export const anonymousGeneratorFunction = createServerFn(anonymousGeneratorFunction_createServerFn); - const multipleDirectives_multipleDirectives = createClientRpc("test_ts--multipleDirectives_multipleDirectives"); - export const multipleDirectives = multipleDirectives_multipleDirectives; - const iife_1 = createClientRpc("test_ts--iife_1"); - export const iife = iife_1(); - const defaultExportFn_1 = createClientRpc("test_ts--defaultExportFn_1"); - export default defaultExportFn_1; - const namedExportFn_1 = createClientRpc("test_ts--namedExportFn_1"); - export const namedExportFn = namedExportFn_1; - const exportedArrowFunction_wrapper = createClientRpc("test_ts--exportedArrowFunction_wrapper"); - export const exportedArrowFunction = wrapper(exportedArrowFunction_wrapper); - const namedExportConst_1 = createClientRpc("test_ts--namedExportConst_1"); - export const namedExportConst = namedExportConst_1; - const namedExportConstGenerator_1 = createClientRpc("test_ts--namedExportConstGenerator_1"); - export const namedExportConstGenerator = namedExportConstGenerator_1; - function unusedFn() { - return 'hello'; - } - const namedDefaultExport = 'namedDefaultExport'; - export default namedDefaultExport; - const usedButNotExported = 'usedButNotExported'; - const namedExport = 'namedExport'; - export { namedExport };" - `) - - expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createSsrRpc } from "my-rpc-lib-server"; - const namedFunction_createServerFn_namedFunction = createSsrRpc("test_ts--namedFunction_createServerFn_namedFunction"); - export const namedFunction = createServerFn(namedFunction_createServerFn_namedFunction); - const namedGeneratorFunction_createServerFn_namedGeneratorFunction = createSsrRpc("test_ts--namedGeneratorFunction_createServerFn_namedGeneratorFunction"); - export const namedGeneratorFunction = createServerFn(namedGeneratorFunction_createServerFn_namedGeneratorFunction); - const arrowFunction_createServerFn = createSsrRpc("test_ts--arrowFunction_createServerFn"); - export const arrowFunction = createServerFn(arrowFunction_createServerFn); - const anonymousFunction_createServerFn = createSsrRpc("test_ts--anonymousFunction_createServerFn"); - export const anonymousFunction = createServerFn(anonymousFunction_createServerFn); - const anonymousGeneratorFunction_createServerFn = createSsrRpc("test_ts--anonymousGeneratorFunction_createServerFn"); - export const anonymousGeneratorFunction = createServerFn(anonymousGeneratorFunction_createServerFn); - const multipleDirectives_multipleDirectives = createSsrRpc("test_ts--multipleDirectives_multipleDirectives"); - export const multipleDirectives = multipleDirectives_multipleDirectives; - const iife_1 = createSsrRpc("test_ts--iife_1"); - export const iife = iife_1(); - const defaultExportFn_1 = createSsrRpc("test_ts--defaultExportFn_1"); - export default defaultExportFn_1; - const namedExportFn_1 = createSsrRpc("test_ts--namedExportFn_1"); - export const namedExportFn = namedExportFn_1; - const exportedArrowFunction_wrapper = createSsrRpc("test_ts--exportedArrowFunction_wrapper"); - export const exportedArrowFunction = wrapper(exportedArrowFunction_wrapper); - const namedExportConst_1 = createSsrRpc("test_ts--namedExportConst_1"); - export const namedExportConst = namedExportConst_1; - const namedExportConstGenerator_1 = createSsrRpc("test_ts--namedExportConstGenerator_1"); - export const namedExportConstGenerator = namedExportConstGenerator_1; - function unusedFn() { - return 'hello'; - } - const namedDefaultExport = 'namedDefaultExport'; - export default namedDefaultExport; - const usedButNotExported = 'usedButNotExported'; - const namedExport = 'namedExport'; - export { namedExport };" - `) - - expect(server.compiledResult.code).toMatchInlineSnapshot( - ` - "import { createServerRpc } from "my-rpc-lib-server"; - const namedFunction_createServerFn_namedFunction = createServerRpc("test_ts--namedFunction_createServerFn_namedFunction", function namedFunction() { - return 'hello'; - }); - const namedGeneratorFunction_createServerFn_namedGeneratorFunction = createServerRpc("test_ts--namedGeneratorFunction_createServerFn_namedGeneratorFunction", function* namedGeneratorFunction() { - yield 'hello'; - return 'hello world'; - }); - const arrowFunction_createServerFn = createServerRpc("test_ts--arrowFunction_createServerFn", () => { - return 'hello'; - }); - const anonymousFunction_createServerFn = createServerRpc("test_ts--anonymousFunction_createServerFn", function () { - return 'hello'; - }); - const anonymousGeneratorFunction_createServerFn = createServerRpc("test_ts--anonymousGeneratorFunction_createServerFn", function* () { - yield 'hello'; - return 'hello world'; - }); - const multipleDirectives_multipleDirectives = createServerRpc("test_ts--multipleDirectives_multipleDirectives", function multipleDirectives() { - 'use strict'; - - return 'hello'; - }); - const iife_1 = createServerRpc("test_ts--iife_1", function () { - return 'hello'; - }); - const defaultExportFn_1 = createServerRpc("test_ts--defaultExportFn_1", function defaultExportFn() { - return 'hello'; - }); - const defaultExportFn = defaultExportFn_1; - const namedExportFn_1 = createServerRpc("test_ts--namedExportFn_1", function namedExportFn() { - return 'hello'; - }); - const namedExportFn = namedExportFn_1; - const exportedArrowFunction_wrapper = createServerRpc("test_ts--exportedArrowFunction_wrapper", () => { - return 'hello'; - }); - const namedExportConst_1 = createServerRpc("test_ts--namedExportConst_1", () => { - return usedFn(); - }); - const namedExportConstGenerator_1 = createServerRpc("test_ts--namedExportConstGenerator_1", function* () { - yield 'hello'; - return usedFn(); - }); - function usedFn() { - return 'hello'; - } - function unusedFn() { - return 'hello'; - } - const namedDefaultExport = 'namedDefaultExport'; - export default namedDefaultExport; - const usedButNotExported = 'usedButNotExported'; - export { namedFunction_createServerFn_namedFunction, namedGeneratorFunction_createServerFn_namedGeneratorFunction, arrowFunction_createServerFn, anonymousFunction_createServerFn, anonymousGeneratorFunction_createServerFn, multipleDirectives_multipleDirectives, iife_1, defaultExportFn_1, namedExportFn_1, exportedArrowFunction_wrapper, namedExportConst_1, namedExportConstGenerator_1 };" - `, - ) - }) - - test('Does not support function declarations nested in other blocks', () => { - const code = ` - outer(() => { - function useServer() { - 'use server' - return 'hello' - } - }) - ` - - expect(() => compileDirectives({ ...clientConfig, code })).toThrow() - expect(() => compileDirectives({ ...serverConfig, code })).toThrow() - expect(() => - compileDirectives({ - ...serverConfig, - code, - filename: serverConfig.filename + `?tsr-serverfn-split=temp`, - }), - ).toThrow() - }) - - test('does not support class methods', () => { - const code = ` - class TestClass { - method() { - 'use server' - return 'hello' - } - - static staticMethod() { - 'use server' - return 'hello' - } - } - ` - - expect(() => compileDirectives({ ...clientConfig, code })).toThrow() - expect(() => compileDirectives({ ...serverConfig, code })).toThrow() - expect(() => - compileDirectives({ - ...serverConfig, - code, - filename: serverConfig.filename + `?tsr-serverfn-split=temp`, - }), - ).toThrow() - }) - - test('does not support object methods', () => { - const code = ` - const obj = { - method() { - 'use server' - return 'hello' - }, - } - ` - - expect(() => compileDirectives({ ...clientConfig, code })).toThrow() - expect(() => compileDirectives({ ...serverConfig, code })).toThrow() - expect(() => - compileDirectives({ - ...serverConfig, - code, - filename: serverConfig.filename + `?tsr-serverfn-split=temp`, - }), - ).toThrow() - }) - - test('multiple directiveFnsById', () => { - const code = ` - function multiDirective() { - 'use strict' - 'use server' - return 'hello' - } - - multiDirective() - ` - - const client = compileDirectives({ ...clientConfig, code }) - const ssr = compileDirectives({ ...ssrConfig, code }) - - const server = compileDirectives({ - ...serverConfig, - code, - filename: - ssr.directiveFnsById[Object.keys(ssr.directiveFnsById)[0]!]! - .extractedFilename, - }) - - expect(client.compiledResult.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib-client"; - const multiDirective_1 = createClientRpc("test_ts--multiDirective_1"); - const multiDirective = multiDirective_1; - multiDirective();" - `) - expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createSsrRpc } from "my-rpc-lib-server"; - const multiDirective_1 = createSsrRpc("test_ts--multiDirective_1"); - const multiDirective = multiDirective_1; - multiDirective();" - `) - expect(server.compiledResult.code).toMatchInlineSnapshot(` - "import { createServerRpc } from "my-rpc-lib-server"; - const multiDirective_1 = createServerRpc("test_ts--multiDirective_1", function () { - 'use strict'; - - return 'hello'; - }); - const multiDirective = multiDirective_1; - multiDirective(); - export { multiDirective_1 };" - `) - }) - - test('IIFE', () => { - const code = ` - export const iife = (function () { - 'use server' - return 'hello' - })() - ` - - const client = compileDirectives({ ...clientConfig, code }) - const ssr = compileDirectives({ ...ssrConfig, code }) - - const server = compileDirectives({ - ...serverConfig, - code, - filename: - ssr.directiveFnsById[Object.keys(ssr.directiveFnsById)[0]!]! - .extractedFilename, - }) - - expect(client.compiledResult.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib-client"; - const iife_1 = createClientRpc("test_ts--iife_1"); - export const iife = iife_1();" - `) - - expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createSsrRpc } from "my-rpc-lib-server"; - const iife_1 = createSsrRpc("test_ts--iife_1"); - export const iife = iife_1();" - `) - - expect(server.compiledResult.code).toMatchInlineSnapshot(` - "import { createServerRpc } from "my-rpc-lib-server"; - const iife_1 = createServerRpc("test_ts--iife_1", function () { - return 'hello'; - }); - export { iife_1 };" - `) - }) - - test('functions that might have the same functionId', () => { - const code = ` - outer(function useServer() { - 'use server' - return 'hello' - }) - - outer(function useServer() { - 'use server' - return 'hello' - }) - ` - - const client = compileDirectives({ ...clientConfig, code }) - const ssr = compileDirectives({ ...ssrConfig, code }) - - const server = compileDirectives({ - ...serverConfig, - code, - filename: - ssr.directiveFnsById[Object.keys(ssr.directiveFnsById)[0]!]! - .extractedFilename, - }) - - expect(client.compiledResult.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib-client"; - const outer_useServer = createClientRpc("test_ts--outer_useServer"); - outer(outer_useServer); - const outer_useServer_1 = createClientRpc("test_ts--outer_useServer_1"); - outer(outer_useServer_1);" - `) - - expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createSsrRpc } from "my-rpc-lib-server"; - const outer_useServer = createSsrRpc("test_ts--outer_useServer"); - outer(outer_useServer); - const outer_useServer_1 = createSsrRpc("test_ts--outer_useServer_1"); - outer(outer_useServer_1);" - `) - - expect(server.compiledResult.code).toMatchInlineSnapshot(` - "import { createServerRpc } from "my-rpc-lib-server"; - const outer_useServer = createServerRpc("test_ts--outer_useServer", function useServer() { - return 'hello'; - }); - outer(outer_useServer); - const outer_useServer_1 = createServerRpc("test_ts--outer_useServer_1", function useServer() { - return 'hello'; - }); - outer(outer_useServer_1); - export { outer_useServer, outer_useServer_1 };" - `) - }) - - test('use server directive in program body', () => { - const code = ` - 'use server' - - export function useServer() { - return usedInUseServer() - } - - function notExported() { - return 'hello' - } - - function usedInUseServer() { - return 'hello' - } - - export default function defaultExport() { - return 'hello' - } - ` - - const client = compileDirectives({ ...clientConfig, code }) - const ssr = compileDirectives({ ...ssrConfig, code }) - const server = compileDirectives({ - ...serverConfig, - code, - filename: - ssr.directiveFnsById[Object.keys(ssr.directiveFnsById)[0]!]! - .extractedFilename, - }) - - expect(client.compiledResult.code).toMatchInlineSnapshot(` - "'use server'; - - import { createClientRpc } from "my-rpc-lib-client"; - const useServer_1 = createClientRpc("test_ts--useServer_1"); - export const useServer = useServer_1; - function notExported() { - return 'hello'; - } - const defaultExport_1 = createClientRpc("test_ts--defaultExport_1"); - export default defaultExport_1;" - `) - expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "'use server'; - - import { createSsrRpc } from "my-rpc-lib-server"; - const useServer_1 = createSsrRpc("test_ts--useServer_1"); - export const useServer = useServer_1; - function notExported() { - return 'hello'; - } - const defaultExport_1 = createSsrRpc("test_ts--defaultExport_1"); - export default defaultExport_1;" - `) - expect(server.compiledResult.code).toMatchInlineSnapshot(` - "'use server'; - - import { createServerRpc } from "my-rpc-lib-server"; - const useServer_1 = createServerRpc("test_ts--useServer_1", function useServer() { - return usedInUseServer(); - }); - const useServer = useServer_1; - function notExported() { - return 'hello'; - } - function usedInUseServer() { - return 'hello'; - } - const defaultExport_1 = createServerRpc("test_ts--defaultExport_1", function defaultExport() { - return 'hello'; - }); - const defaultExport = defaultExport_1; - export { useServer_1, defaultExport_1 };" - `) - }) - - test('createServerFn with identifier', () => { - // The following code is the client output of the tanstack-start-plugin - // that compiles `createServerFn` calls to automatically add the `use server` - // directive in the right places. - const clientOrSsrCode = `import { createServerFn } from '@tanstack/react-start'; - export const myServerFn = createServerFn().handler(opts => { - "use server"; - - return myServerFn.__executeServer(opts); - }); - - export const myServerFn2 = createServerFn().handler(opts => { - "use server"; - - return myServerFn2.__executeServer(opts); - });` - - // The following code is the server output of the tanstack-start-plugin - // that compiles `createServerFn` calls to automatically add the `use server` - // directive in the right places. - const serverCode = `import { createServerFn } from '@tanstack/react-start'; - const myFunc = () => { - return 'hello from the server' - }; - export const myServerFn = createServerFn().handler(opts => { - "use server"; - - return myServerFn.__executeServer(opts); - }, myFunc); - - const myFunc2 = () => { - return myServerFn({ data: 'hello 2 from the server' }); - }; - export const myServerFn2 = createServerFn().handler(opts => { - "use server"; - - return myServerFn2.__executeServer(opts); - }, myFunc2);` - - const client = compileDirectives({ ...clientConfig, code: clientOrSsrCode }) - const ssr = compileDirectives({ ...ssrConfig, code: clientOrSsrCode }) - const server = compileDirectives({ - ...serverConfig, - code: serverCode, - filename: - ssr.directiveFnsById[Object.keys(ssr.directiveFnsById)[0]!]! - .extractedFilename, - }) - - expect(client.compiledResult.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib-client"; - import { createServerFn } from '@tanstack/react-start'; - const myServerFn_createServerFn_handler = createClientRpc("test_ts--myServerFn_createServerFn_handler"); - export const myServerFn = createServerFn().handler(myServerFn_createServerFn_handler); - const myServerFn2_createServerFn_handler = createClientRpc("test_ts--myServerFn2_createServerFn_handler"); - export const myServerFn2 = createServerFn().handler(myServerFn2_createServerFn_handler);" - `) - - expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createSsrRpc } from "my-rpc-lib-server"; - import { createServerFn } from '@tanstack/react-start'; - const myServerFn_createServerFn_handler = createSsrRpc("test_ts--myServerFn_createServerFn_handler"); - export const myServerFn = createServerFn().handler(myServerFn_createServerFn_handler); - const myServerFn2_createServerFn_handler = createSsrRpc("test_ts--myServerFn2_createServerFn_handler"); - export const myServerFn2 = createServerFn().handler(myServerFn2_createServerFn_handler);" - `) - - expect(server.compiledResult.code).toMatchInlineSnapshot(` - "import { createServerRpc } from "my-rpc-lib-server"; - import { createServerFn } from '@tanstack/react-start'; - const myFunc = () => { - return 'hello from the server'; - }; - const myServerFn_createServerFn_handler = createServerRpc("test_ts--myServerFn_createServerFn_handler", opts => { - return myServerFn.__executeServer(opts); - }); - const myServerFn = createServerFn().handler(myServerFn_createServerFn_handler, myFunc); - const myFunc2 = () => { - return myServerFn({ - data: 'hello 2 from the server' - }); - }; - const myServerFn2_createServerFn_handler = createServerRpc("test_ts--myServerFn2_createServerFn_handler", opts => { - return myServerFn2.__executeServer(opts); - }); - const myServerFn2 = createServerFn().handler(myServerFn2_createServerFn_handler, myFunc2); - export { myServerFn_createServerFn_handler, myServerFn2_createServerFn_handler };" - `) - }) - - test('async function with directive', () => { - const code = ` - async function bytesSignupServerFn({ email }: { email: string }) { - 'use server' - - return 'test' - } - - bytesSignupServerFn() - - ` - - const client = compileDirectives({ ...clientConfig, code }) - const ssr = compileDirectives({ ...ssrConfig, code }) - const server = compileDirectives({ - ...serverConfig, - code, - filename: - ssr.directiveFnsById[Object.keys(ssr.directiveFnsById)[0]!]! - .extractedFilename, - }) - - expect(client.compiledResult.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib-client"; - const bytesSignupServerFn_1 = createClientRpc("test_ts--bytesSignupServerFn_1"); - const bytesSignupServerFn = bytesSignupServerFn_1; - bytesSignupServerFn();" - `) - expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createSsrRpc } from "my-rpc-lib-server"; - const bytesSignupServerFn_1 = createSsrRpc("test_ts--bytesSignupServerFn_1"); - const bytesSignupServerFn = bytesSignupServerFn_1; - bytesSignupServerFn();" - `) - expect(server.compiledResult.code).toMatchInlineSnapshot(` - "import { createServerRpc } from "my-rpc-lib-server"; - const bytesSignupServerFn_1 = createServerRpc("test_ts--bytesSignupServerFn_1", async function ({ - email - }: { - email: string; - }) { - return 'test'; - }); - const bytesSignupServerFn = bytesSignupServerFn_1; - bytesSignupServerFn(); - export { bytesSignupServerFn_1 };" - `) - }) - - test('file-wide use server directive', () => { - const code = ` - 'use server' - - import { imported } from 'imported' - - export const serverFnConstWithImport = async () => { - return imported - } - - export function serverFnNamedWithImport () { - return imported - } - ` - - const client = compileDirectives({ ...clientConfig, code }) - const ssr = compileDirectives({ ...ssrConfig, code }) - const server = compileDirectives({ - ...serverConfig, - code, - filename: - ssr.directiveFnsById[Object.keys(ssr.directiveFnsById)[0]!]! - .extractedFilename, - }) - - expect(client.compiledResult.code).toMatchInlineSnapshot(` - "'use server'; - - import { createClientRpc } from "my-rpc-lib-client"; - const serverFnConstWithImport_1 = createClientRpc("test_ts--serverFnConstWithImport_1"); - export const serverFnConstWithImport = serverFnConstWithImport_1; - const serverFnNamedWithImport_1 = createClientRpc("test_ts--serverFnNamedWithImport_1"); - export const serverFnNamedWithImport = serverFnNamedWithImport_1;" - `) - - expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "'use server'; - - import { createSsrRpc } from "my-rpc-lib-server"; - const serverFnConstWithImport_1 = createSsrRpc("test_ts--serverFnConstWithImport_1"); - export const serverFnConstWithImport = serverFnConstWithImport_1; - const serverFnNamedWithImport_1 = createSsrRpc("test_ts--serverFnNamedWithImport_1"); - export const serverFnNamedWithImport = serverFnNamedWithImport_1;" - `) - - expect(server.compiledResult.code).toMatchInlineSnapshot(` - "'use server'; - - import { createServerRpc } from "my-rpc-lib-server"; - import { imported } from 'imported'; - const serverFnConstWithImport_1 = createServerRpc("test_ts--serverFnConstWithImport_1", async () => { - return imported; - }); - const serverFnNamedWithImport_1 = createServerRpc("test_ts--serverFnNamedWithImport_1", function serverFnNamedWithImport() { - return imported; - }); - const serverFnNamedWithImport = serverFnNamedWithImport_1; - export { serverFnConstWithImport_1, serverFnNamedWithImport_1 };" - `) - }) - test('async function with anonymous default export', () => { - const code = ` - async function bytesSignupServerFn({ email }: { email: string }) { - 'use server' - return 'test' - } - export default function () { - return null; - } - ` - - const client = compileDirectives({ ...clientConfig, code }) - const ssr = compileDirectives({ ...ssrConfig, code }) - const server = compileDirectives({ - ...serverConfig, - code, - filename: - ssr.directiveFnsById[Object.keys(ssr.directiveFnsById)[0]!]! - .extractedFilename, - }) - - expect(client.compiledResult.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib-client"; - const bytesSignupServerFn_1 = createClientRpc("test_ts--bytesSignupServerFn_1"); - const bytesSignupServerFn = bytesSignupServerFn_1; - export default function () { - return null; - }" - `) - expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createSsrRpc } from "my-rpc-lib-server"; - const bytesSignupServerFn_1 = createSsrRpc("test_ts--bytesSignupServerFn_1"); - const bytesSignupServerFn = bytesSignupServerFn_1; - export default function () { - return null; - }" - `) - expect(server.compiledResult.code).toMatchInlineSnapshot(` - "import { createServerRpc } from "my-rpc-lib-server"; - const bytesSignupServerFn_1 = createServerRpc("test_ts--bytesSignupServerFn_1", async function ({ - email - }: { - email: string; - }) { - return 'test'; - }); - const bytesSignupServerFn = bytesSignupServerFn_1; - export default function () { - return null; - } - export { bytesSignupServerFn_1 };" - `) - }) - - test('generator function', () => { - const code = ` - function* generator() { - 'use server' - yield 'hello' - return 'hello world' - } - ` - const client = compileDirectives({ - ...clientConfig, - code, - }) - const ssr = compileDirectives({ ...ssrConfig, code }) - - const server = compileDirectives({ - ...serverConfig, - code, - filename: `${ssr.directiveFnsById[Object.keys(ssr.directiveFnsById)[0]!]!.extractedFilename}`, - }) - - expect(client.compiledResult.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib-client"; - const generator_1 = createClientRpc("test_ts--generator_1"); - const generator = generator_1;" - `) - - expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createSsrRpc } from "my-rpc-lib-server"; - const generator_1 = createSsrRpc("test_ts--generator_1"); - const generator = generator_1;" - `) - - expect(server.compiledResult.code).toMatchInlineSnapshot(` - "import { createServerRpc } from "my-rpc-lib-server"; - const generator_1 = createServerRpc("test_ts--generator_1", function* () { - yield 'hello'; - return 'hello world'; - }); - const generator = generator_1; - export { generator_1 };" - `) - }) - test('async generator function', () => { - const code = ` - async function* asyncGenerator() { - 'use server' - yield 'hello' - return 'hello world' - } - ` - const client = compileDirectives({ - ...clientConfig, - code, - }) - const ssr = compileDirectives({ ...ssrConfig, code }) - - const server = compileDirectives({ - ...serverConfig, - code, - filename: `${ssr.directiveFnsById[Object.keys(ssr.directiveFnsById)[0]!]!.extractedFilename}`, - }) - - expect(client.compiledResult.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib-client"; - const asyncGenerator_1 = createClientRpc("test_ts--asyncGenerator_1"); - const asyncGenerator = asyncGenerator_1;" - `) - - expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createSsrRpc } from "my-rpc-lib-server"; - const asyncGenerator_1 = createSsrRpc("test_ts--asyncGenerator_1"); - const asyncGenerator = asyncGenerator_1;" - `) - - expect(server.compiledResult.code).toMatchInlineSnapshot(` - "import { createServerRpc } from "my-rpc-lib-server"; - const asyncGenerator_1 = createServerRpc("test_ts--asyncGenerator_1", async function* () { - yield 'hello'; - return 'hello world'; - }); - const asyncGenerator = asyncGenerator_1; - export { asyncGenerator_1 };" - `) - }) - - test('server function references exported value', () => { - const code = ` - - import z from "zod"; - - export const zExampleSchema = z.object({ - name: z.string(), - age: z.number(), - }); - - export const namedFunction = createServerFn(() => { - 'use server' - zExampleSchema.safeParse({ name: 'test', age: 123 }) - return 'hello' - }) - ` - - const client = compileDirectives({ ...clientConfig, code }) - const ssr = compileDirectives({ ...ssrConfig, code }) - const server = compileDirectives({ - ...serverConfig, - code, - filename: - ssr.directiveFnsById[Object.keys(ssr.directiveFnsById)[0]!]! - .extractedFilename, - }) - - expect(client.compiledResult.code).toMatchInlineSnapshot(` - "import { createClientRpc } from "my-rpc-lib-client"; - import z from "zod"; - export const zExampleSchema = z.object({ - name: z.string(), - age: z.number() - }); - const namedFunction_createServerFn = createClientRpc("test_ts--namedFunction_createServerFn"); - export const namedFunction = createServerFn(namedFunction_createServerFn);" - `) - expect(ssr.compiledResult.code).toMatchInlineSnapshot(` - "import { createSsrRpc } from "my-rpc-lib-server"; - import z from "zod"; - export const zExampleSchema = z.object({ - name: z.string(), - age: z.number() - }); - const namedFunction_createServerFn = createSsrRpc("test_ts--namedFunction_createServerFn"); - export const namedFunction = createServerFn(namedFunction_createServerFn);" - `) - expect(server.compiledResult.code).toMatchInlineSnapshot(` - "import { createServerRpc } from "my-rpc-lib-server"; - import z from "zod"; - const zExampleSchema = z.object({ - name: z.string(), - age: z.number() - }); - const namedFunction_createServerFn = createServerRpc("test_ts--namedFunction_createServerFn", () => { - zExampleSchema.safeParse({ - name: 'test', - age: 123 - }); - return 'hello'; - }); - export { namedFunction_createServerFn };" - `) - }) -}) diff --git a/packages/directive-functions-plugin/tsconfig.json b/packages/directive-functions-plugin/tsconfig.json deleted file mode 100644 index 37d21ef6ca..0000000000 --- a/packages/directive-functions-plugin/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "include": ["src", "vite.config.ts", "tests"], - "exclude": ["tests/**/test-files/**", "tests/**/snapshots/**"], - "compilerOptions": { - "jsx": "react-jsx" - } -} diff --git a/packages/directive-functions-plugin/vite.config.ts b/packages/directive-functions-plugin/vite.config.ts deleted file mode 100644 index 5389f0f739..0000000000 --- a/packages/directive-functions-plugin/vite.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' -import packageJson from './package.json' - -const config = defineConfig({ - test: { - name: packageJson.name, - dir: './tests', - watch: false, - typecheck: { enabled: true }, - }, -}) - -export default mergeConfig( - config, - tanstackViteConfig({ - entry: './src/index.ts', - srcDir: './src', - }), -) diff --git a/packages/eslint-plugin-router/CHANGELOG.md b/packages/eslint-plugin-router/CHANGELOG.md new file mode 100644 index 0000000000..f58a2ecd63 --- /dev/null +++ b/packages/eslint-plugin-router/CHANGELOG.md @@ -0,0 +1,19 @@ +# @tanstack/eslint-plugin-router + +## 1.162.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +## 1.161.6 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +## 1.161.5 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) diff --git a/packages/eslint-plugin-router/package.json b/packages/eslint-plugin-router/package.json index e6d19fd359..9be54c220e 100644 --- a/packages/eslint-plugin-router/package.json +++ b/packages/eslint-plugin-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/eslint-plugin-router", - "version": "1.141.0", + "version": "1.162.0", "description": "ESLint plugin for TanStack Router", "author": "Manuel Schiller", "license": "MIT", @@ -18,12 +18,12 @@ "clean": "rimraf ./dist ./coverage", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch --typecheck", "test:build": "publint --strict && attw --pack .", @@ -56,10 +56,26 @@ }, "devDependencies": { "@typescript-eslint/rule-tester": "^8.23.0", - "combinate": "^1.1.11", - "eslint": "^9.22.0" + "combinate": "catalog:", + "eslint": "^9.22.0", + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0" + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0" + }, + "nx": { + "targets": { + "build": { + "inputs": [ + "...", + "{workspaceRoot}/eslint.config.js" + ] + } + } } } diff --git a/packages/eslint-plugin-router/src/__tests__/route-param-names.rule.test.ts b/packages/eslint-plugin-router/src/__tests__/route-param-names.rule.test.ts new file mode 100644 index 0000000000..e66847e363 --- /dev/null +++ b/packages/eslint-plugin-router/src/__tests__/route-param-names.rule.test.ts @@ -0,0 +1,271 @@ +import { RuleTester } from '@typescript-eslint/rule-tester' + +import { name, rule } from '../rules/route-param-names/route-param-names.rule' + +const ruleTester = new RuleTester() + +ruleTester.run(name, rule, { + valid: [ + // Valid param names - simple $param format + { + name: 'valid simple param: $userId', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/users/$userId')({}) + `, + }, + { + name: 'valid simple param: $id', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/posts/$id')({}) + `, + }, + { + name: 'valid simple param: $_id (underscore prefix)', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/items/$_id')({}) + `, + }, + { + name: 'valid simple param: $$var (dollar prefix)', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/data/$$var')({}) + `, + }, + { + name: 'valid param with numbers: $user123', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/users/$user123')({}) + `, + }, + + // Valid param names - braces format {$param} + { + name: 'valid braces param: {$userName}', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/users/{$userName}')({}) + `, + }, + { + name: 'valid braces param with prefix/suffix: prefix{$id}suffix', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/items/item-{$id}-details')({}) + `, + }, + + // Valid optional params - {-$param} + { + name: 'valid optional param: {-$optional}', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/search/{-$query}')({}) + `, + }, + { + name: 'valid optional param with prefix/suffix: prefix{-$opt}suffix', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/filter/by-{-$category}-items')({}) + `, + }, + + // Wildcards - should be skipped (no validation) + { + name: 'wildcard: $ alone', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/files/$')({}) + `, + }, + { + name: 'wildcard: {$}', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/catch/{$}')({}) + `, + }, + + // Multiple valid params + { + name: 'multiple valid params in path', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/users/$userId/posts/$postId')({}) + `, + }, + + // createRoute with path property + { + name: 'createRoute with valid param in path property', + code: ` + import { createRoute } from '@tanstack/react-router' + const Route = createRoute({ path: '/users/$userId' }) + `, + }, + + // createLazyFileRoute + { + name: 'createLazyFileRoute with valid param', + code: ` + import { createLazyFileRoute } from '@tanstack/react-router' + const Route = createLazyFileRoute('/users/$userId')({}) + `, + }, + + // createLazyRoute + { + name: 'createLazyRoute with valid param', + code: ` + import { createLazyRoute } from '@tanstack/react-router' + const Route = createLazyRoute('/users/$userId')({}) + `, + }, + + // No params - should pass + { + name: 'no params in path', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/users/list')({}) + `, + }, + + // Not from tanstack router - should be ignored + { + name: 'non-tanstack import should be ignored', + code: ` + import { createFileRoute } from 'other-router' + const Route = createFileRoute('/users/$123invalid')({}) + `, + }, + ], + + invalid: [ + // Invalid param names - starts with number + { + name: 'invalid param starting with number: $123', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/users/$123')({}) + `, + errors: [{ messageId: 'invalidParamName', data: { paramName: '123' } }], + }, + { + name: 'invalid param starting with number: $1user', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/users/$1user')({}) + `, + errors: [{ messageId: 'invalidParamName', data: { paramName: '1user' } }], + }, + + // Invalid param names - contains hyphen + { + name: 'invalid param with hyphen: $user-name', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/users/$user-name')({}) + `, + errors: [ + { messageId: 'invalidParamName', data: { paramName: 'user-name' } }, + ], + }, + + // Invalid param names - contains dot + { + name: 'invalid param with dot: {$my.param}', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/users/{$my.param}')({}) + `, + errors: [ + { messageId: 'invalidParamName', data: { paramName: 'my.param' } }, + ], + }, + + // Invalid param names - contains space + { + name: 'invalid param with space: {$param name}', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/users/{$param name}')({}) + `, + errors: [ + { messageId: 'invalidParamName', data: { paramName: 'param name' } }, + ], + }, + + // Invalid optional param + { + name: 'invalid optional param: {-$123invalid}', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/search/{-$123invalid}')({}) + `, + errors: [ + { messageId: 'invalidParamName', data: { paramName: '123invalid' } }, + ], + }, + + // Multiple invalid params + { + name: 'multiple invalid params in path', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/users/$1id/posts/$post-id')({}) + `, + errors: [ + { messageId: 'invalidParamName', data: { paramName: '1id' } }, + { messageId: 'invalidParamName', data: { paramName: 'post-id' } }, + ], + }, + + // createRoute with invalid path property + { + name: 'createRoute with invalid param in path property', + code: ` + import { createRoute } from '@tanstack/react-router' + const Route = createRoute({ path: '/users/$123' }) + `, + errors: [{ messageId: 'invalidParamName', data: { paramName: '123' } }], + }, + + // createLazyFileRoute with invalid param + { + name: 'createLazyFileRoute with invalid param', + code: ` + import { createLazyFileRoute } from '@tanstack/react-router' + const Route = createLazyFileRoute('/users/$user-id')({}) + `, + errors: [ + { messageId: 'invalidParamName', data: { paramName: 'user-id' } }, + ], + }, + + // createLazyRoute with invalid param + { + name: 'createLazyRoute with invalid param', + code: ` + import { createLazyRoute } from '@tanstack/react-router' + const Route = createLazyRoute('/users/$1abc')({}) + `, + errors: [{ messageId: 'invalidParamName', data: { paramName: '1abc' } }], + }, + + // Invalid braces param with prefix/suffix + { + name: 'invalid braces param with prefix/suffix', + code: ` + import { createFileRoute } from '@tanstack/react-router' + const Route = createFileRoute('/items/item-{$123}-details')({}) + `, + errors: [{ messageId: 'invalidParamName', data: { paramName: '123' } }], + }, + ], +}) diff --git a/packages/eslint-plugin-router/src/__tests__/route-param-names.utils.test.ts b/packages/eslint-plugin-router/src/__tests__/route-param-names.utils.test.ts new file mode 100644 index 0000000000..67d0488b99 --- /dev/null +++ b/packages/eslint-plugin-router/src/__tests__/route-param-names.utils.test.ts @@ -0,0 +1,174 @@ +import { describe, expect, it } from 'vitest' +import { + extractParamsFromPath, + extractParamsFromSegment, + getInvalidParams, + isValidParamName, +} from '../rules/route-param-names/route-param-names.utils' + +describe('isValidParamName', () => { + it('should return true for valid param names', () => { + expect(isValidParamName('userId')).toBe(true) + expect(isValidParamName('id')).toBe(true) + expect(isValidParamName('_id')).toBe(true) + expect(isValidParamName('$var')).toBe(true) + expect(isValidParamName('user123')).toBe(true) + expect(isValidParamName('_')).toBe(true) + expect(isValidParamName('$')).toBe(true) + expect(isValidParamName('ABC')).toBe(true) + expect(isValidParamName('camelCase')).toBe(true) + expect(isValidParamName('PascalCase')).toBe(true) + expect(isValidParamName('snake_case')).toBe(true) + expect(isValidParamName('$$double')).toBe(true) + expect(isValidParamName('__double')).toBe(true) + }) + + it('should return false for invalid param names', () => { + expect(isValidParamName('123')).toBe(false) + expect(isValidParamName('1user')).toBe(false) + expect(isValidParamName('user-name')).toBe(false) + expect(isValidParamName('user.name')).toBe(false) + expect(isValidParamName('user name')).toBe(false) + expect(isValidParamName('')).toBe(false) + expect(isValidParamName('user@name')).toBe(false) + expect(isValidParamName('user#name')).toBe(false) + expect(isValidParamName('-user')).toBe(false) + }) +}) + +describe('extractParamsFromSegment', () => { + it('should return empty array for segments without $', () => { + expect(extractParamsFromSegment('')).toEqual([]) + expect(extractParamsFromSegment('users')).toEqual([]) + expect(extractParamsFromSegment('static-segment')).toEqual([]) + }) + + it('should skip wildcard segments', () => { + expect(extractParamsFromSegment('$')).toEqual([]) + expect(extractParamsFromSegment('{$}')).toEqual([]) + }) + + it('should extract simple $param format', () => { + const result = extractParamsFromSegment('$userId') + expect(result).toHaveLength(1) + expect(result[0]).toEqual({ + fullParam: '$userId', + paramName: 'userId', + isOptional: false, + isValid: true, + }) + }) + + it('should extract braces {$param} format', () => { + const result = extractParamsFromSegment('{$userId}') + expect(result).toHaveLength(1) + expect(result[0]).toEqual({ + fullParam: '$userId', + paramName: 'userId', + isOptional: false, + isValid: true, + }) + }) + + it('should extract braces with prefix/suffix', () => { + const result = extractParamsFromSegment('prefix{$id}suffix') + expect(result).toHaveLength(1) + expect(result[0]).toEqual({ + fullParam: '$id', + paramName: 'id', + isOptional: false, + isValid: true, + }) + }) + + it('should extract optional {-$param} format', () => { + const result = extractParamsFromSegment('{-$optional}') + expect(result).toHaveLength(1) + expect(result[0]).toEqual({ + fullParam: '-$optional', + paramName: 'optional', + isOptional: true, + isValid: true, + }) + }) + + it('should extract optional with prefix/suffix', () => { + const result = extractParamsFromSegment('pre{-$opt}post') + expect(result).toHaveLength(1) + expect(result[0]).toEqual({ + fullParam: '-$opt', + paramName: 'opt', + isOptional: true, + isValid: true, + }) + }) + + it('should mark invalid param names', () => { + const result = extractParamsFromSegment('$123invalid') + expect(result).toHaveLength(1) + expect(result[0]?.isValid).toBe(false) + expect(result[0]?.paramName).toBe('123invalid') + }) + + it('should mark hyphenated param names as invalid', () => { + const result = extractParamsFromSegment('$user-name') + expect(result).toHaveLength(1) + expect(result[0]?.isValid).toBe(false) + expect(result[0]?.paramName).toBe('user-name') + }) +}) + +describe('extractParamsFromPath', () => { + it('should return empty array for paths without params', () => { + expect(extractParamsFromPath('')).toEqual([]) + expect(extractParamsFromPath('/')).toEqual([]) + expect(extractParamsFromPath('/users/list')).toEqual([]) + }) + + it('should extract single param from path', () => { + const result = extractParamsFromPath('/users/$userId') + expect(result).toHaveLength(1) + expect(result[0]?.paramName).toBe('userId') + }) + + it('should extract multiple params from path', () => { + const result = extractParamsFromPath('/users/$userId/posts/$postId') + expect(result).toHaveLength(2) + expect(result[0]?.paramName).toBe('userId') + expect(result[1]?.paramName).toBe('postId') + }) + + it('should extract params with various formats', () => { + const result = extractParamsFromPath( + '/a/$simple/b/{$braces}/c/{-$optional}', + ) + expect(result).toHaveLength(3) + expect(result[0]?.paramName).toBe('simple') + expect(result[0]?.isOptional).toBe(false) + expect(result[1]?.paramName).toBe('braces') + expect(result[1]?.isOptional).toBe(false) + expect(result[2]?.paramName).toBe('optional') + expect(result[2]?.isOptional).toBe(true) + }) +}) + +describe('getInvalidParams', () => { + it('should return empty array for valid params', () => { + expect(getInvalidParams('/users/$userId')).toEqual([]) + expect(getInvalidParams('/users/$_id')).toEqual([]) + expect(getInvalidParams('/users/$$var')).toEqual([]) + }) + + it('should return invalid params only', () => { + const result = getInvalidParams('/users/$123/posts/$validId') + expect(result).toHaveLength(1) + expect(result[0]?.paramName).toBe('123') + }) + + it('should return all invalid params', () => { + const result = getInvalidParams('/users/$1id/posts/$post-id') + expect(result).toHaveLength(2) + expect(result[0]?.paramName).toBe('1id') + expect(result[1]?.paramName).toBe('post-id') + }) +}) diff --git a/packages/eslint-plugin-router/src/index.ts b/packages/eslint-plugin-router/src/index.ts index f02ea5a000..7b8855cdf2 100644 --- a/packages/eslint-plugin-router/src/index.ts +++ b/packages/eslint-plugin-router/src/index.ts @@ -26,6 +26,7 @@ Object.assign(plugin.configs, { plugins: ['@tanstack/eslint-plugin-router'], rules: { '@tanstack/router/create-route-property-order': 'warn', + '@tanstack/router/route-param-names': 'error', }, }, 'flat/recommended': [ @@ -35,6 +36,7 @@ Object.assign(plugin.configs, { }, rules: { '@tanstack/router/create-route-property-order': 'warn', + '@tanstack/router/route-param-names': 'error', }, }, ], diff --git a/packages/eslint-plugin-router/src/rules.ts b/packages/eslint-plugin-router/src/rules.ts index 73219d401e..1042929a45 100644 --- a/packages/eslint-plugin-router/src/rules.ts +++ b/packages/eslint-plugin-router/src/rules.ts @@ -1,4 +1,5 @@ import * as createRoutePropertyOrder from './rules/create-route-property-order/create-route-property-order.rule' +import * as routeParamNames from './rules/route-param-names/route-param-names.rule' import type { ESLintUtils } from '@typescript-eslint/utils' import type { ExtraRuleDocs } from './types' @@ -12,4 +13,5 @@ export const rules: Record< > > = { [createRoutePropertyOrder.name]: createRoutePropertyOrder.rule, + [routeParamNames.name]: routeParamNames.rule, } diff --git a/packages/eslint-plugin-router/src/rules/route-param-names/constants.ts b/packages/eslint-plugin-router/src/rules/route-param-names/constants.ts new file mode 100644 index 0000000000..541374da06 --- /dev/null +++ b/packages/eslint-plugin-router/src/rules/route-param-names/constants.ts @@ -0,0 +1,36 @@ +/** + * Functions where the path is passed as the first argument (string literal) + * e.g., createFileRoute('/path/$param')(...) + */ +export const pathAsFirstArgFunctions = [ + 'createFileRoute', + 'createLazyFileRoute', + 'createLazyRoute', +] as const + +export type PathAsFirstArgFunction = (typeof pathAsFirstArgFunctions)[number] + +/** + * Functions where the path is a property in the options object + * e.g., createRoute({ path: '/path/$param' }) + */ +export const pathAsPropertyFunctions = ['createRoute'] as const + +export type PathAsPropertyFunction = (typeof pathAsPropertyFunctions)[number] + +/** + * All route functions that need param name validation + */ +export const allRouteFunctions = [ + ...pathAsFirstArgFunctions, + ...pathAsPropertyFunctions, +] as const + +export type RouteFunction = (typeof allRouteFunctions)[number] + +/** + * Regex for valid JavaScript identifier (param name) + * Must start with letter, underscore, or dollar sign + * Can contain letters, numbers, underscores, or dollar signs + */ +export const VALID_PARAM_NAME_REGEX = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/ diff --git a/packages/eslint-plugin-router/src/rules/route-param-names/route-param-names.rule.ts b/packages/eslint-plugin-router/src/rules/route-param-names/route-param-names.rule.ts new file mode 100644 index 0000000000..ae63ab98c4 --- /dev/null +++ b/packages/eslint-plugin-router/src/rules/route-param-names/route-param-names.rule.ts @@ -0,0 +1,127 @@ +import { AST_NODE_TYPES, ESLintUtils } from '@typescript-eslint/utils' + +import { getDocsUrl } from '../../utils/get-docs-url' +import { detectTanstackRouterImports } from '../../utils/detect-router-imports' +import { getInvalidParams } from './route-param-names.utils' +import { pathAsFirstArgFunctions, pathAsPropertyFunctions } from './constants' +import type { TSESTree } from '@typescript-eslint/utils' +import type { ExtraRuleDocs } from '../../types' + +const createRule = ESLintUtils.RuleCreator(getDocsUrl) + +const pathAsFirstArgSet = new Set(pathAsFirstArgFunctions) +const pathAsPropertySet = new Set(pathAsPropertyFunctions) + +export const name = 'route-param-names' + +export const rule = createRule({ + name, + meta: { + type: 'problem', + docs: { + description: 'Ensure route param names are valid JavaScript identifiers', + recommended: 'error', + }, + messages: { + invalidParamName: + 'Invalid param name "{{paramName}}" in route path. Param names must be valid JavaScript identifiers (match /[a-zA-Z_$][a-zA-Z0-9_$]*/).', + }, + schema: [], + }, + defaultOptions: [], + + create: detectTanstackRouterImports((context, _, helpers) => { + function reportInvalidParams(node: TSESTree.Node, path: string) { + const invalidParams = getInvalidParams(path) + + for (const param of invalidParams) { + context.report({ + node, + messageId: 'invalidParamName', + data: { paramName: param.paramName }, + }) + } + } + + function getStringLiteralValue(node: TSESTree.Node): string | null { + if ( + node.type === AST_NODE_TYPES.Literal && + typeof node.value === 'string' + ) { + return node.value + } + if ( + node.type === AST_NODE_TYPES.TemplateLiteral && + node.quasis.length === 1 + ) { + const cooked = node.quasis[0]?.value.cooked + if (cooked != null) { + return cooked + } + } + return null + } + + return { + CallExpression(node) { + // Handle direct function call: createRoute({ path: '...' }) + if (node.callee.type === AST_NODE_TYPES.Identifier) { + const funcName = node.callee.name + + // Skip if not imported from TanStack Router + if (!helpers.isTanstackRouterImport(node.callee)) { + return + } + + // Case: createRoute({ path: '/path/$param' }) or createRoute({ 'path': '/path/$param' }) + if (pathAsPropertySet.has(funcName)) { + const arg = node.arguments[0] + if (arg?.type === AST_NODE_TYPES.ObjectExpression) { + for (const prop of arg.properties) { + if (prop.type === AST_NODE_TYPES.Property) { + const isPathKey = + (prop.key.type === AST_NODE_TYPES.Identifier && + prop.key.name === 'path') || + (prop.key.type === AST_NODE_TYPES.Literal && + prop.key.value === 'path') + if (isPathKey) { + const pathValue = getStringLiteralValue(prop.value) + if (pathValue) { + reportInvalidParams(prop.value, pathValue) + } + } + } + } + } + return + } + } + + // Handle curried function call: createFileRoute('/path')({ ... }) + if (node.callee.type === AST_NODE_TYPES.CallExpression) { + const innerCall = node.callee + + if (innerCall.callee.type === AST_NODE_TYPES.Identifier) { + const funcName = innerCall.callee.name + + // Skip if not imported from TanStack Router + if (!helpers.isTanstackRouterImport(innerCall.callee)) { + return + } + + // Case: createFileRoute('/path/$param')(...) or similar + if (pathAsFirstArgSet.has(funcName)) { + const pathArg = innerCall.arguments[0] + if (pathArg) { + const pathValue = getStringLiteralValue(pathArg) + if (pathValue) { + reportInvalidParams(pathArg, pathValue) + } + } + } + } + } + }, + } + }), +}) diff --git a/packages/eslint-plugin-router/src/rules/route-param-names/route-param-names.utils.ts b/packages/eslint-plugin-router/src/rules/route-param-names/route-param-names.utils.ts new file mode 100644 index 0000000000..825c9eed96 --- /dev/null +++ b/packages/eslint-plugin-router/src/rules/route-param-names/route-param-names.utils.ts @@ -0,0 +1,122 @@ +import { VALID_PARAM_NAME_REGEX } from './constants' + +export interface ExtractedParam { + /** The full param string including $ prefix (e.g., "$userId", "-$optional") */ + fullParam: string + /** The param name without $ prefix (e.g., "userId", "optional") */ + paramName: string + /** Whether this is an optional param (prefixed with -$) */ + isOptional: boolean + /** Whether this param name is valid */ + isValid: boolean +} + +/** + * Extracts param names from a route path segment. + * + * Handles these patterns: + * - $paramName -> extract "paramName" + * - {$paramName} -> extract "paramName" + * - prefix{$paramName}suffix -> extract "paramName" + * - {-$paramName} -> extract "paramName" (optional) + * - prefix{-$paramName}suffix -> extract "paramName" (optional) + * - $ or {$} -> wildcard, skip validation + */ +export function extractParamsFromSegment( + segment: string, +): Array { + const params: Array = [] + + // Skip empty segments + if (!segment || !segment.includes('$')) { + return params + } + + // Check for wildcard ($ alone or {$}) + if (segment === '$' || segment === '{$}') { + return params // Wildcard, no param name to validate + } + + // Pattern 1: Simple $paramName (entire segment starts with $) + if (segment.startsWith('$') && !segment.includes('{')) { + const paramName = segment.slice(1) + if (paramName) { + params.push({ + fullParam: segment, + paramName, + isOptional: false, + isValid: VALID_PARAM_NAME_REGEX.test(paramName), + }) + } + return params + } + + // Pattern 2: Braces pattern {$paramName} or {-$paramName} with optional prefix/suffix + // Match patterns like: prefix{$param}suffix, {$param}, {-$param} + const bracePattern = /\{(-?\$)([^}]*)\}/g + let match + + while ((match = bracePattern.exec(segment)) !== null) { + const prefix = match[1] // "$" or "-$" + const paramName = match[2] // The param name after $ or -$ + + if (!paramName) { + // This is a wildcard {$} or {-$}, skip + continue + } + + const isOptional = prefix === '-$' + + params.push({ + fullParam: `${prefix}${paramName}`, + paramName, + isOptional, + isValid: VALID_PARAM_NAME_REGEX.test(paramName), + }) + } + + return params +} + +/** + * Extracts all params from a route path. + * + * @param path - The route path (e.g., "/users/$userId/posts/$postId") + * @returns Array of extracted params with validation info + */ +export function extractParamsFromPath(path: string): Array { + if (!path || !path.includes('$')) { + return [] + } + + const segments = path.split('/') + const allParams: Array = [] + + for (const segment of segments) { + const params = extractParamsFromSegment(segment) + allParams.push(...params) + } + + return allParams +} + +/** + * Validates a single param name. + * + * @param paramName - The param name to validate (without $ prefix) + * @returns Whether the param name is valid + */ +export function isValidParamName(paramName: string): boolean { + return VALID_PARAM_NAME_REGEX.test(paramName) +} + +/** + * Gets all invalid params from a route path. + * + * @param path - The route path + * @returns Array of invalid param info + */ +export function getInvalidParams(path: string): Array { + const params = extractParamsFromPath(path) + return params.filter((p) => !p.isValid) +} diff --git a/packages/eslint-plugin-router/src/utils/detect-router-imports.ts b/packages/eslint-plugin-router/src/utils/detect-router-imports.ts index 1e9e047dac..00ba0f05ae 100644 --- a/packages/eslint-plugin-router/src/utils/detect-router-imports.ts +++ b/packages/eslint-plugin-router/src/utils/detect-router-imports.ts @@ -55,7 +55,8 @@ export function detectTanstackRouterImports(create: EnhancedCreate): Create { ImportDeclaration(node) { if ( node.specifiers.length > 0 && - node.importKind === 'value' && + // `importKind` is parser-dependent and can be undefined (eg. Espree) + node.importKind !== 'type' && node.source.value.startsWith('@tanstack/') && node.source.value.endsWith('-router') ) { diff --git a/packages/eslint-plugin-router/tsconfig.build.json b/packages/eslint-plugin-router/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/eslint-plugin-router/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/eslint-plugin-router/vite.config.ts b/packages/eslint-plugin-router/vite.config.ts index e0de55875e..77ecb53a97 100644 --- a/packages/eslint-plugin-router/vite.config.ts +++ b/packages/eslint-plugin-router/vite.config.ts @@ -1,5 +1,5 @@ import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' import packageJson from './package.json' const config = defineConfig({ @@ -16,6 +16,7 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ + tsconfigPath: './tsconfig.build.json', entry: './src/index.ts', srcDir: './src', exclude: ['./src/__tests__'], diff --git a/packages/eslint-plugin-start/.attw.json b/packages/eslint-plugin-start/.attw.json new file mode 100644 index 0000000000..329bfe8343 --- /dev/null +++ b/packages/eslint-plugin-start/.attw.json @@ -0,0 +1,3 @@ +{ + "ignoreRules": ["false-export-default"] +} diff --git a/packages/eslint-plugin-start/CHANGELOG.md b/packages/eslint-plugin-start/CHANGELOG.md new file mode 100644 index 0000000000..45cec4b95a --- /dev/null +++ b/packages/eslint-plugin-start/CHANGELOG.md @@ -0,0 +1,13 @@ +# @tanstack/eslint-plugin-start + +## 0.1.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +## 0.0.1 + +### Patch Changes + +- Bump the initial release line for `@tanstack/react-start-rsc` and `@tanstack/eslint-plugin-start` to `0.0.1` after the manual `0.0.0` publish. ([#7144](https://github.com/TanStack/router/pull/7144)) diff --git a/packages/directive-functions-plugin/eslint.config.js b/packages/eslint-plugin-start/eslint.config.js similarity index 100% rename from packages/directive-functions-plugin/eslint.config.js rename to packages/eslint-plugin-start/eslint.config.js diff --git a/packages/eslint-plugin-start/lint-improvements.md b/packages/eslint-plugin-start/lint-improvements.md new file mode 100644 index 0000000000..ff46b57353 --- /dev/null +++ b/packages/eslint-plugin-start/lint-improvements.md @@ -0,0 +1,693 @@ +# ESLint Plugin Performance Improvements Plan + +## Problem Statement + +The `no-async-client-component` rule currently builds a **full render graph** of the entire TypeScript program on every lint run. This involves: + +1. Iterating through ALL source files in the program +2. Indexing ALL component definitions +3. Building ALL render edges (JSX references) +4. Only then checking a small subset for violations + +For a codebase with **thousands of files** and **only a few route files**, this is extremely wasteful: + +``` +Current: Scan 5000 files → Build graph of ~2000 components → Use ~50 of them +Optimal: Find 10 route files → Analyze only ~50 referenced components +``` + +## Solution: Lazy Entry-Point Analysis + +Instead of building a complete program graph upfront, we analyze **on-demand** starting from entry points: + +1. When linting file X, quick check: Does X have `createServerComponent` or route options? +2. If no: Skip entirely (zero analysis cost) +3. If yes: Analyze only components reachable from X's entry points + +This mirrors how `no-client-code-in-server-component` already works with its on-demand `CallExpression` trigger + `transitive-analyzer.ts` reachability walk. + +--- + +## Implementation Phases + +### Phase 1: Extract Shared Utilities (Safe, Low-Risk) + +**Goal:** Create shared infrastructure that both rules can use. + +#### 1.1 Create shared folder structure + +``` +packages/eslint-plugin-start/src/ +├── rules/ +│ ├── no-async-client-component/ +│ └── no-client-code-in-server-component/ +└── shared/ # NEW + ├── use-client-resolver.ts # Moved from no-client-code-in-server-component + ├── component-resolver.ts # NEW: Resolve component symbols + ├── transitive-walker.ts # NEW: Unified transitive analysis + └── types.ts # NEW: Shared type definitions +``` + +#### 1.2 Extract use-client-resolver + +Move `rules/no-client-code-in-server-component/use-client-resolver.ts` to `shared/use-client-resolver.ts`. + +No logic changes needed - just re-export from both rules. + +```typescript +// shared/use-client-resolver.ts +export interface UseClientResolver { + hasUseClientDirective(fileName: string): boolean +} + +export function createUseClientResolver( + program: ts.Program, +): UseClientResolver { + const cache = new Map() + + return { + hasUseClientDirective(fileName: string): boolean { + if (cache.has(fileName)) return cache.get(fileName)! + + const sourceFile = program.getSourceFile(fileName) + if (!sourceFile) { + cache.set(fileName, false) + return false + } + + const result = checkFirstStatement(sourceFile) + cache.set(fileName, result) + return result + }, + } +} +``` + +#### 1.3 Create component-resolver + +New utility to resolve component symbols from various patterns: + +```typescript +// shared/component-resolver.ts +export interface ComponentInfo { + name: string + fileName: string + symbol: ts.Symbol + declaration: ts.Declaration + isAsync: boolean +} + +export interface ComponentResolver { + /** + * Resolve a component from an identifier (e.g., JSX tag name or route option value) + */ + resolveComponent(node: ts.Identifier): ComponentInfo | undefined + + /** + * Check if a function-like node is async + */ + isAsyncFunction(node: ts.Node): boolean +} + +export function createComponentResolver( + ts: typeof import('typescript'), + checker: ts.TypeChecker, +): ComponentResolver { + // Implementation... +} +``` + +#### 1.4 Create shared types + +```typescript +// shared/types.ts +export interface EntryPoint { + type: 'server-component' | 'route-option' + node: ts.Node + fileName: string + /** For route-option, the specific option name (component, pendingComponent, etc.) */ + optionName?: string +} + +export interface AnalysisContext { + program: ts.Program + checker: ts.TypeChecker + useClientResolver: UseClientResolver + componentResolver: ComponentResolver +} +``` + +--- + +### Phase 2: Refactor no-async-client-component to On-Demand + +**Goal:** Avoid full-program graph build; analyze only when a file contains route options / entry points. + +#### 2.1 New architecture + +``` +Before: +┌─────────────────────────────────────────────────────────────┐ +│ Program() visitor │ +│ └── For each file in program: │ +│ └── Index all components, edges, roots │ +│ └── analyzeContext() on complete graph │ +│ └── Report violations │ +└─────────────────────────────────────────────────────────────┘ + +After: +┌─────────────────────────────────────────────────────────────┐ +│ CallExpression visitor (only triggers on specific calls) │ +│ └── Is this createFileRoute/createRootRoute/etc? │ +│ └── YES: Extract component references from options │ +│ └── For each component: analyzeTransitively│ +│ └── Is this createServerComponent? │ +│ └── YES: Mark referenced components as server context│ +└─────────────────────────────────────────────────────────────┘ +``` + +#### 2.2 Stop building full-program render graph + +Replace full-program graph build with per-entry-point analysis. Actual file deletion can come later after parity is proven. + +#### 2.3 Stop precomputing global context + +Context propagation becomes implicit in a focused traversal (starting from route-option components and respecting server boundaries). + +#### 2.4 New rule structure + +```typescript +// no-async-client-component.rule.ts (simplified) +export const rule = ESLintUtils.RuleCreator(getDocsUrl)({ + // ...meta... + + create(context) { + const services = ESLintUtils.getParserServices(context) + const program = services.program + const checker = program.getTypeChecker() + + // Shared utilities + const useClientResolver = createUseClientResolver(program) + const componentResolver = createComponentResolver(ts, checker) + + // Track what we've already analyzed to avoid duplicates + const analyzedComponents = new Set() + const reportedViolations = new Set() + + return { + CallExpression(node) { + const tsNode = services.esTreeNodeToTSNodeMap.get(node) + + // Check for route options: createFileRoute('/')({ component: X }) + const routeComponents = extractRouteOptionComponents(tsNode) + if (routeComponents.length > 0) { + for (const { component, optionNode } of routeComponents) { + analyzeAsClientRoot(component, optionNode, node) + } + return + } + + // Check for server component: createServerComponent(() => ) + const serverComponents = extractServerComponentChildren(tsNode) + if (serverComponents.length > 0) { + // These are in server context - async is ALLOWED here + // Mark them so we don't report if encountered via route options + for (const comp of serverComponents) { + markAsServerContext(comp) + } + } + }, + } + + function analyzeAsClientRoot( + componentSymbol: ts.Symbol, + usageNode: ts.Node, + eslintNode: TSESTree.CallExpression, + ) { + // Walk transitively, checking for async components + // Stop at 'use client' boundaries + // Report violations at usageNode location + } + }, +}) +``` + +#### 2.5 Transitive async analysis + +```typescript +interface AsyncAnalysisResult { + /** Components that are async and in client context */ + asyncViolations: Array<{ + componentName: string + componentFile: string + isAsync: boolean + chain: Array<{ file: string; component: string }> + }> + /** Whether we hit a 'use client' boundary (stops propagation) */ + hitClientBoundary: boolean +} + +function analyzeComponentTransitively( + entrySymbol: ts.Symbol, + context: AnalysisContext, + visited: Set, +): AsyncAnalysisResult { + const key = symbolKey(entrySymbol) + if (visited.has(key)) return { asyncViolations: [], hitClientBoundary: false } + visited.add(key) + + const decl = entrySymbol.getDeclarations()?.[0] + if (!decl) return { asyncViolations: [], hitClientBoundary: false } + + const fileName = decl.getSourceFile().fileName + + // Check for 'use client' boundary + if (context.useClientResolver.hasUseClientDirective(fileName)) { + return { asyncViolations: [], hitClientBoundary: true } + } + + const violations: AsyncAnalysisResult['asyncViolations'] = [] + + // Check if this component is async + const componentInfo = context.componentResolver.resolveFromDeclaration(decl) + if (componentInfo?.isAsync) { + violations.push({ + componentName: componentInfo.name, + componentFile: fileName, + isAsync: true, + chain: [], + }) + } + + // Find JSX children and recurse + const childRefs = findJsxComponentReferences(decl) + for (const childRef of childRefs) { + const childSymbol = context.checker.getSymbolAtLocation(childRef) + if (!childSymbol) continue + + const childResult = analyzeComponentTransitively( + resolveAlias(childSymbol), + context, + visited, + ) + + if (childResult.hitClientBoundary) continue // Stop at boundary + + // Add chain info to child violations + for (const v of childResult.asyncViolations) { + violations.push({ + ...v, + chain: [ + { file: fileName, component: componentInfo?.name ?? 'unknown' }, + ...v.chain, + ], + }) + } + } + + return { asyncViolations: violations, hitClientBoundary: false } +} +``` + +--- + +### Phase 3: Unify Transitive Analysis + +**Goal:** Both rules share the same transitive walking infrastructure. + +#### 3.1 Create unified transitive-walker + +```typescript +// shared/transitive-walker.ts + +export interface WalkOptions { + /** Whether to detect client-only code violations (hooks, onClick, etc.) */ + detectClientViolations?: boolean + /** Whether to detect async component violations */ + detectAsyncViolations?: boolean + /** Allowed hooks for client violation detection */ + allowedHooks?: Set +} + +export interface WalkResult { + /** Client-only code violations (if detectClientViolations) */ + clientViolations: Array + /** Async components found (if detectAsyncViolations) */ + asyncComponents: Array + /** Whether a 'use client' boundary was hit */ + hitClientBoundary: boolean + /** Import chain to reach this point */ + chain: Array +} + +export interface TransitiveWalker { + /** + * Walk from an entry symbol, collecting violations based on options. + * Stops at 'use client' boundaries. + */ + walk(entrySymbol: ts.Symbol, options: WalkOptions): WalkResult + + /** + * Clear caches (call between unrelated analyses) + */ + clearCaches(): void +} + +export function createTransitiveWalker( + ts: typeof import('typescript'), + context: AnalysisContext, +): TransitiveWalker { + // Per-symbol cache for walk results + const walkCache = new Map() + + // Per-file violation cache (reusable across symbols in same file) + const fileViolationCache = new Map>() + + return { + walk(entrySymbol, options) { + const cacheKey = `${symbolKey(entrySymbol)}:${JSON.stringify(options)}` + if (walkCache.has(cacheKey)) return walkCache.get(cacheKey)! + + const result = walkInternal(entrySymbol, options, new Set(), []) + walkCache.set(cacheKey, result) + return result + }, + + clearCaches() { + walkCache.clear() + fileViolationCache.clear() + }, + } + + function walkInternal( + symbol: ts.Symbol, + options: WalkOptions, + visited: Set, + chain: Array, + ): WalkResult { + // Implementation combines logic from: + // - transitive-analyzer.ts (following symbols) + // - violation-detector.ts (detecting client violations) + // - render-graph-builder.ts (detecting async) + } +} +``` + +#### 3.2 Update no-client-code-in-server-component to use shared walker + +```typescript +// no-client-code-in-server-component.rule.ts +import { createTransitiveWalker } from '../../shared/transitive-walker' + +export const rule = ESLintUtils.RuleCreator(getDocsUrl)({ + create(context) { + const walker = createTransitiveWalker(ts, analysisContext) + + return { + CallExpression(node) { + if (!isCreateServerComponentCall(node)) return + + const componentRefs = findComponentReferences(callback) + for (const ref of componentRefs) { + const result = walker.walk(resolvedSymbol, { + detectClientViolations: true, + detectAsyncViolations: false, // Other rule handles this + allowedHooks, + }) + + if (result.hitClientBoundary) continue + + for (const violation of result.clientViolations) { + reportViolation(violation, result.chain, ref.text, eslintNode) + } + } + }, + } + }, +}) +``` + +#### 3.3 Update no-async-client-component to use shared walker + +```typescript +// no-async-client-component.rule.ts +import { createTransitiveWalker } from '../../shared/transitive-walker' + +export const rule = ESLintUtils.RuleCreator(getDocsUrl)({ + create(context) { + const walker = createTransitiveWalker(ts, analysisContext) + + return { + CallExpression(node) { + const routeComponents = extractRouteOptionComponents(tsNode) + + for (const { componentSymbol, optionNode } of routeComponents) { + const result = walker.walk(componentSymbol, { + detectClientViolations: false, // Other rule handles this + detectAsyncViolations: true, + }) + + if (result.hitClientBoundary) continue + + for (const asyncComp of result.asyncComponents) { + reportAsyncViolation(asyncComp, optionNode, eslintNode) + } + } + }, + } + }, +}) +``` + +--- + +### Phase 4: Enhanced Caching (Future) + +**Goal:** Further optimize repeat analyses with persistent caches. + +> **Note:** This phase is documented for future implementation. Do not implement yet. + +#### 4.1 File-level violation cache + +Cache violations detected in each source file, keyed by file path and content hash. + +```typescript +interface FileViolationCache { + /** Content hash when cached */ + contentHash: string + /** Cached client violations */ + clientViolations: Array + /** Cached component metadata */ + components: Array<{ + name: string + isAsync: boolean + line: number + }> +} + +const fileCache = new Map() + +function getFileViolations(sourceFile: ts.SourceFile): Array { + const hash = computeHash(sourceFile.text) + const cached = fileCache.get(sourceFile.fileName) + + if (cached?.contentHash === hash) { + return cached.clientViolations + } + + // Recompute and cache + const violations = detectViolationsInFile(sourceFile) + fileCache.set(sourceFile.fileName, { + contentHash: hash, + clientViolations: violations, + components: extractComponentMetadata(sourceFile), + }) + + return violations +} +``` + +#### 4.2 Import graph cache + +Cache which symbols each file imports, enabling quick dependency lookups. + +```typescript +interface ImportGraphCache { + /** Content hash when cached */ + contentHash: string + /** Imported symbols: Map */ + imports: Map + /** Exported symbols */ + exports: Set +} +``` + +#### 4.3 Cross-file dependency tracking + +Track which files depend on which, for incremental invalidation. + +```typescript +interface DependencyGraph { + /** Files that import this file */ + importedBy: Map> + /** Files this file imports */ + imports: Map> +} + +function invalidateFile(fileName: string, graph: DependencyGraph) { + // Clear cache for this file + fileCache.delete(fileName) + + // Clear cache for files that import this file + const dependents = graph.importedBy.get(fileName) ?? new Set() + for (const dep of dependents) { + fileCache.delete(dep) + } +} +``` + +#### 4.4 LRU eviction for memory management + +```typescript +import { LRUCache } from 'lru-cache' + +const fileCache = new LRUCache({ + max: 1000, // Max 1000 files + ttl: 1000 * 60 * 5, // 5 minute TTL +}) +``` + +--- + +## File Changes Summary + +### New Files + +| File | Description | +| ----------------------------------- | ------------------------------------------------------ | +| `src/shared/use-client-resolver.ts` | Moved from `rules/no-client-code-in-server-component/` | +| `src/shared/component-resolver.ts` | New: Resolve component symbols | +| `src/shared/transitive-walker.ts` | New: Unified transitive analysis | +| `src/shared/types.ts` | New: Shared type definitions | + +### Modified Files + +| File | Changes | +| ----------------------------------------------------------------------------------------- | ----------------------------- | +| `src/rules/no-async-client-component/no-async-client-component.rule.ts` | Complete rewrite to on-demand | +| `src/rules/no-client-code-in-server-component/no-client-code-in-server-component.rule.ts` | Use shared utilities | + +### Deleted / Retired Files + +| File | Reason | +| --------------------------------------------------------------------- | ------------------------------------------ | +| `src/rules/no-async-client-component/render-graph-builder.ts` | Eventually retired after on-demand parity | +| `src/rules/no-async-client-component/context-analyzer.ts` | Eventually retired after on-demand parity | +| `src/rules/no-client-code-in-server-component/use-client-resolver.ts` | Moved to shared | +| `src/rules/no-client-code-in-server-component/transitive-analyzer.ts` | (Optional) later replaced by shared walker | + +--- + +## Performance Expectations + +### Before Optimization + +| Metric | Value | +| --------------- | ---------------------------------- | +| Files scanned | All files in program | +| Time complexity | O(files × avg components per file) | +| Memory | Full component graph in memory | + +### After Optimization + +| Metric | Value | +| --------------- | --------------------------------------------- | +| Files scanned | Only entry point files + reachable components | +| Time complexity | O(entry points × avg reachable depth) | +| Memory | Only active analysis path | + +### Example: 5000 files, 10 routes, 50 components per route + +| Metric | Before | After | Improvement | +| ------------------ | ----------------- | --------------- | ----------- | +| File visits | ~5000 | ~500 | 10x | +| Components indexed | ~2000 | ~500 | 4x | +| Memory usage | High (full graph) | Low (path only) | ~10x | + +--- + +## Testing Strategy + +### Unit Tests + +1. **Shared utilities:** + - `use-client-resolver.ts`: Test directive detection + - `component-resolver.ts`: Test symbol resolution + - `transitive-walker.ts`: Test walk behavior, caching, boundary detection + +2. **Rule behavior:** + - Existing tests should continue to pass + - Add tests for edge cases in on-demand analysis + +### E2E Tests + +Use `e2e/eslint-plugin-start/` project to verify: + +1. Cross-file analysis still works +2. No false positives from lazy analysis +3. Performance improvement on large fixture sets + +### Performance Benchmarks + +Create benchmark script: + +```typescript +// scripts/benchmark-eslint-rules.ts +import { ESLint } from 'eslint' +import { performance } from 'perf_hooks' + +async function benchmark(name: string, fn: () => Promise) { + const start = performance.now() + await fn() + const end = performance.now() + console.log(`${name}: ${(end - start).toFixed(2)}ms`) +} + +// Run on large fixture set +await benchmark('no-async-client-component', async () => { + const eslint = new ESLint({ + /* config */ + }) + await eslint.lintFiles(['fixtures/large-project/**/*.tsx']) +}) +``` + +--- + +## Migration Notes + +### Breaking Changes + +None expected. The rules produce the same errors, just faster. + +### Deprecation + +- Internal APIs (`RenderGraph`, `ContextAnalysisResult`) are removed +- These were never part of public API + +### Rollback Plan + +If issues arise, revert to commit before Phase 2 changes. + +--- + +## Timeline Estimate + +| Phase | Effort | Dependencies | +| ------------------------------------------- | --------- | ------------ | +| Phase 1: Extract shared utilities | 2-3 hours | None | +| Phase 2: Refactor no-async-client-component | 4-6 hours | Phase 1 | +| Phase 3: Unify transitive analysis | 3-4 hours | Phase 2 | +| Phase 4: Enhanced caching | Future | Phase 3 | + +**Total: ~10-13 hours for Phases 1-3** diff --git a/packages/eslint-plugin-start/no-async-client-component.md b/packages/eslint-plugin-start/no-async-client-component.md new file mode 100644 index 0000000000..4e312fd9f6 --- /dev/null +++ b/packages/eslint-plugin-start/no-async-client-component.md @@ -0,0 +1,346 @@ +# Rule: `no-async-client-component` + +## Overview + +Disallow async components in client context. Async components are only valid inside `createServerComponent()`. + +## Problem + +In React Server Components: + +- Async components can only be awaited on the server +- Client components cannot be async (React throws at runtime) +- Components become "client" when: + 1. Referenced by `createFileRoute()` or `createRootRoute()` options (`component`, `pendingComponent`, etc.) + 2. Inside a `'use client'` file + 3. Rendered by another client component (transitively) + +## Detection Algorithm + +### Phase 1: Build Render Graph (whole-program) + +Using TypeScript program from ESLint parser services: + +``` +For each file in program: + 1. Index component definitions + - PascalCase exported function or const assigned to function/arrow + - async-ness from TS node flags + 2. Find JSX usages () + 3. Build edges: callerComponent -> calleeComponent + 4. Mark "server roots": + - the createServerComponent() callback itself + - components referenced from within that callback's JSX tree + 5. Mark "client roots": + - createFileRoute()({ component, pendingComponent, errorComponent, notFoundComponent, ... }) + - createRootRoute()({ component, pendingComponent, errorComponent, notFoundComponent, ... }) + - Files with 'use client' directive + +Notes: +- `createRootRoute`/`createFileRoute` refer to `@tanstack/react-router` APIs. +- `createLazyFileRoute` is intentionally out of scope. +- Prefer TS symbol resolution (e.g. aliases/re-exports via `checker.getAliasedSymbol`). +``` + +### Phase 2: Propagate Context + +``` +1. Mark all server roots as "server context" +2. Walk render graph from server roots; mark descendants as "server context" + - STOP at a 'use client' boundary (descendants become client) +3. Mark all client roots as "client context" +4. Walk render graph from client roots; mark descendants as "client context" +5. Any component reachable from BOTH contexts is "tainted" (client wins) +6. Any component not reachable from server context is "client context" + +Note: if the program has no server roots (no createServerComponent usage), +then all components end up in client context and async components are always invalid. +``` + +### Phase 3: Report Violations + +``` +For each async component: + If component is in client context: + Report error at: + 1. The async component definition (primary) + 2. Each JSX usage site where the *caller component* is in client context (secondary) +``` + +## Error Messages + +**At definition site:** + +``` +Async component "MyComponent" cannot be used in client context. Async components +are only valid inside createServerComponent(). Either remove 'async' or ensure +this component is only rendered within server components. +``` + +**At usage site:** + +``` +Async component "MyComponent" is rendered in client context here. Async components +are only valid inside createServerComponent(). Move this to a server component or +use a non-async version. +``` + +## Implementation Structure + +``` +src/rules/no-async-client-component/ + no-async-client-component.rule.ts -- Main ESLint rule + render-graph-builder.ts -- Build component render graph + context-analyzer.ts -- Propagate server/client context + async-component-detector.ts -- Find async function components + constants.ts -- Route option names, etc. +``` + +## Key Types + +```typescript +interface ComponentInfo { + name: string + fileName: string + node: ts.Node + isAsync: boolean + line: number +} + +interface RenderEdge { + fromFile: string + fromComponent: string + toFile: string + toComponent: string + jsxNode: ts.Node // For reporting at usage site +} + +interface ComponentContext { + component: ComponentInfo + isServerContext: boolean + isClientContext: boolean + // If client, why? + clientReason?: + | { type: 'use-client' } + | { type: 'route-option'; routeFile: string; option: string } + | { type: 'rendered-by-client'; parentComponent: string } +} + +type RenderGraph = { + components: Map // key: "file:ComponentName" + edges: Array + serverRoots: Set // Components inside createServerComponent + clientRoots: Set // Components in route options or 'use client' +} +``` + +## Route Options to Track + +From `createFileRoute()` and `createRootRoute()` (component-ish keys only): + +```typescript +const ROUTE_COMPONENT_OPTION_NAMES = [ + 'component', + 'pendingComponent', + 'errorComponent', + 'notFoundComponent', +] +``` + +Only analyze these keys, and only when the value resolves to a function/component reference (identifier, inline function, etc.). + +## Edge Cases + +### 1. Component used in both server and client + +```tsx +// ServerPage.tsx +createServerComponent(() => ) // Server usage + +// ClientPage.tsx +createFileRoute('/')({ component: () => }) // Client usage +``` + +**Result**: Error - SharedComponent is tainted (used in client context) + +### 2. Conditional rendering + +```tsx +createServerComponent(() => { + if (condition) return // Valid + return +}) +``` + +**Result**: AsyncComponent is in server context, valid + +### 3. Dynamic imports + +```tsx +const LazyComponent = lazy(() => import('./AsyncComponent')) +``` + +**Result**: Out of scope initially (non-trivial to resolve statically). + +### 4. Component passed as prop + +```tsx +createServerComponent(({ ActionButton }) => { + return ( +
    + +
    + ) // ActionButton comes from client +}) +``` + +**Result**: ActionButton is a slot from client, tracked separately + +### 5. Re-exports + +```tsx +// components/index.ts +export { MyComponent } from './MyComponent' +``` + +**Result**: Follow re-exports via TS symbol resolution (alias symbols). + +## Performance Considerations + +1. **Use TypeScript program** from parser services (already built) +2. **Cache render graph** per program instance +3. **Incremental updates** if possible (watch mode) +4. **Early termination** - once a component is proven client, stop analyzing + +## Rule Options + +```typescript +interface RuleOptions { + /** + * Additional file patterns to treat as client entry points + * @default [] + */ + additionalClientPatterns?: string[] + + /** + * File patterns to ignore + * @default [] + */ + ignorePatterns?: string[] +} +``` + +## Test Cases + +### Valid (should NOT report) + +```tsx +// Async inside createServerComponent +createServerComponent(async () => { + const data = await fetch() + return
    {data}
    +}) + +// Async component rendered by server component +// AsyncData.tsx +export async function AsyncData() { + return
    {await getData()}
    +} +// ServerPage.tsx +createServerComponent(() => ) + +// Sync component in client context (OK) +createFileRoute('/')({ component: SyncComponent }) +``` + +### Invalid (should report) + +```tsx +// Async component as route component +export async function Page() { + return
    +} +createFileRoute('/')({ component: Page }) // Error at both locations + +// Async component rendered by client +// AsyncWidget.tsx +export async function AsyncWidget() { + return
    +} +// ClientPage.tsx +createFileRoute('/')({ + component: () => , // Error: AsyncWidget is async +}) + +// Async in 'use client' file +;('use client') +export async function ClientComponent() { + return
    +} // Error + +// Async component rendered by 'use client' file +// Widget.tsx +export async function Widget() { + return
    +} +// ClientWrapper.tsx +;('use client') +import { Widget } from './Widget' +export function Wrapper() { + return +} // Error at usage +// Widget.tsx also gets error at definition + +// Transitive client context +// AsyncDeep.tsx +export async function AsyncDeep() { + return
    +} +// Middle.tsx +export function Middle() { + return +} +// ClientPage.tsx +createFileRoute('/')({ component: () => }) +// Error: AsyncDeep rendered transitively in client context +``` + +## Implementation Steps + +1. **Create async-component-detector.ts** + - Find all async function components in a file + - Detect: `export async function Foo()`, `export const Foo = async () => {}` + - Component heuristic: PascalCase name (avoid deep return/CFG analysis initially) + +2. **Create render-graph-builder.ts** + - Walk all files in TypeScript program + - Build component -> component edges from JSX + - Identify server roots (createServerComponent callbacks) + - Identify client roots (route options, 'use client') + +3. **Create context-analyzer.ts** + - Propagate server context from server roots + - Propagate client context from client roots + - Handle 'use client' boundaries + - Determine final context for each component + +4. **Create no-async-client-component.rule.ts** + - Build/cache render graph on Program node + - For each file, find async components + - Check context, report violations + - Report at both definition and usage sites + +5. **Add tests** + - Valid cases (async in server context) + - Invalid cases (async in client context) + - Edge cases (mixed, transitive, re-exports) + +6. **Update plugin exports** + - Add to rules.ts + - Add to index.ts + +## Dependencies + +- Reuses `use-client-resolver.ts` from existing rule +- Uses TypeScript program from ESLint parser services +- No new external dependencies diff --git a/packages/eslint-plugin-start/no-client-code-in-server-component.md b/packages/eslint-plugin-start/no-client-code-in-server-component.md new file mode 100644 index 0000000000..11450f2bd6 --- /dev/null +++ b/packages/eslint-plugin-start/no-client-code-in-server-component.md @@ -0,0 +1,163 @@ +# Rule: `no-client-code-in-server-component` + +## Overview + +Disallow client-only code inside `createServerComponent()`. + +This rule is meant to catch common "RSC boundary" mistakes in TanStack Start: + +- calling React client hooks in server components +- referencing browser-only globals (eg `window`, `document`) +- using React event handlers (`onClick`, etc.) +- passing functions as props (non-serializable) +- using class components + +## What counts as a "server component" here? + +This rule treats the callback passed to `createServerComponent(...)` as server-only, and also treats any components rendered from within that callback as server-only unless they cross a `'use client'` boundary. + +Supported call patterns: + +- `createServerComponent(() =>
    )` +- `createServerComponent(async () =>
    )` +- `createServerComponent(MyComponent)` (direct reference) + +## What counts as "client code"? + +### React hooks + +The rule flags common React hooks that require a client runtime (eg `useState`, `useEffect`). + +Allowed hooks: + +- `useId` is allowed by default. +- You can allow additional hooks via the `allowedServerHooks` option. + +### Browser-only globals + +Any global that exists in `globals.browser` but not `globals.node` is treated as browser-only and disallowed. + +Examples: + +- `window` +- `document` +- `navigator` + +### Event handlers + +JSX props that look like React event handlers (eg `onClick`, `onChange`, etc.) are disallowed in server components. + +### Function props + +Passing a function through props is disallowed because server-to-client serialization can’t serialize functions. + +### Class components + +Class components are disallowed because they rely on client-side lifecycle. + +## Reporting location + +- For direct violations inside a `createServerComponent` callback, the error is reported at the violating node. +- For transitive violations (server component → imports another file → reaches client code), the rule reports at: + - the specific violating node (where possible) and + - includes a "Triggered by rendering \"X\"" hint naming the entry component. + +## Options + +```ts +type Options = [ + { + allowedServerHooks?: string[] + }, +] +``` + +### `allowedServerHooks` + +Add additional hook names that should be allowed in server components. + +Example: + +```js +{ + rules: { + '@tanstack/start/no-client-code-in-server-component': [ + 'error', + { + allowedServerHooks: ['useMyServerSafeHook'], + }, + ], + }, +} +``` + +## Examples + +### Invalid: client hook in server component + +```tsx +import { createServerComponent } from '@tanstack/react-start/rsc' +import { useState } from 'react' + +export const Server = createServerComponent(() => { + const [count, setCount] = useState(0) + return +}) +``` + +### Invalid: browser global access + +```tsx +import { createServerComponent } from '@tanstack/react-start/rsc' + +export const Server = createServerComponent(() => { + return
    {window.location.href}
    +}) +``` + +### Invalid: transitive client import + +```tsx +// server.tsx +import { createServerComponent } from '@tanstack/react-start/rsc' +import { Middle } from './middle' + +export const Server = createServerComponent(() => ) + +// middle.tsx +import { ClientThing } from './client-thing' +export function Middle() { + return +} + +// client-thing.tsx +export function ClientThing() { + return +} +``` + +### Valid: slot/prop boundary (pattern suggestion) + +```tsx +import { createServerComponent } from '@tanstack/react-start/rsc' + +export const Server = createServerComponent(({ ActionButton }) => { + return ( +
    + +
    + ) +}) +``` + +## Implementation structure + +```txt +src/rules/no-client-code-in-server-component/ + no-client-code-in-server-component.rule.ts + transitive-analyzer.ts + violation-detector.ts + constants.ts +src/shared/ + use-client-resolver.ts +``` diff --git a/packages/eslint-plugin-start/package.json b/packages/eslint-plugin-start/package.json new file mode 100644 index 0000000000..803264ed10 --- /dev/null +++ b/packages/eslint-plugin-start/package.json @@ -0,0 +1,82 @@ +{ + "name": "@tanstack/eslint-plugin-start", + "version": "0.1.0", + "description": "ESLint plugin for TanStack Start", + "author": "TanStack", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/TanStack/router.git", + "directory": "packages/eslint-plugin-start" + }, + "homepage": "https://tanstack.com/start", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "scripts": { + "clean": "rimraf ./dist ./coverage", + "test:eslint": "eslint ./src", + "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", + "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", + "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", + "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", + "test:unit": "vitest", + "test:unit:dev": "pnpm run test:unit --watch --typecheck", + "test:build": "publint --strict && attw --pack .", + "build": "vite build && tsc --noEmit" + }, + "type": "module", + "types": "dist/esm/index.d.ts", + "main": "dist/cjs/index.cjs", + "module": "dist/esm/index.js", + "exports": { + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + } + }, + "./package.json": "./package.json" + }, + "sideEffects": false, + "files": [ + "dist", + "src" + ], + "dependencies": { + "@typescript-eslint/utils": "^8.44.1", + "globals": "^16.2.0" + }, + "devDependencies": { + "@typescript-eslint/rule-tester": "^8.44.1", + "eslint": "^9.22.0", + "typescript": "^5.8.2", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.7.0" + }, + "nx": { + "targets": { + "build": { + "inputs": [ + "...", + "{workspaceRoot}/eslint.config.js" + ] + } + } + } +} diff --git a/packages/eslint-plugin-start/src/__tests__/no-async-client-component.rule.test.ts b/packages/eslint-plugin-start/src/__tests__/no-async-client-component.rule.test.ts new file mode 100644 index 0000000000..53c8ed7705 --- /dev/null +++ b/packages/eslint-plugin-start/src/__tests__/no-async-client-component.rule.test.ts @@ -0,0 +1,287 @@ +import * as path from 'node:path' +import { RuleTester } from '@typescript-eslint/rule-tester' +import * as vitest from 'vitest' + +import { + name, + rule, +} from '../rules/no-async-client-component/no-async-client-component.rule' + +RuleTester.afterAll = vitest.afterAll +RuleTester.it = ((name, fn) => + vitest.it(name, { timeout: 15000 }, fn)) as typeof RuleTester.it +RuleTester.itOnly = vitest.it.only +RuleTester.describe = vitest.describe + +const ruleTester = new RuleTester({ + languageOptions: { + parserOptions: { + ecmaFeatures: { + jsx: true, + }, + projectService: { + allowDefaultProject: ['*.tsx'], + maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING: 50, + }, + tsconfigRootDir: path.join(__dirname), + }, + }, +}) + +ruleTester.run(name, rule as any, { + valid: [ + // Sync component in route is fine + { + filename: 'SyncRoute.tsx', + code: ` + import { createFileRoute } from '@tanstack/react-router' + + function SyncComponent() { + return
    Hello
    + } + + export const Route = createFileRoute('/')({ + component: SyncComponent, + }) + `, + }, + // Async inside createCompositeComponent is fine + { + filename: 'ServerComponent.tsx', + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(async () => { + const data = await fetch('/api') + return
    {data}
    + }) + `, + }, + // Sync component with 'use client' is fine (not async) + { + filename: 'ClientFile.tsx', + code: ` + 'use client' + + function ClientComponent() { + return + } + `, + }, + // Inline sync component in route is fine + { + filename: 'InlineRoute.tsx', + code: ` + import { createFileRoute } from '@tanstack/react-router' + + export const Route = createFileRoute('/')({ + component: () =>
    Hello
    , + }) + `, + }, + // Sync pendingComponent is fine + { + filename: 'SyncPending.tsx', + code: ` + import { createFileRoute } from '@tanstack/react-router' + + function Loading() { + return
    Loading...
    + } + + export const Route = createFileRoute('/')({ + component: () =>
    Hello
    , + pendingComponent: Loading, + }) + `, + }, + // createRootRoute with sync component is fine + { + filename: 'RootSync.tsx', + code: ` + import { createRootRoute } from '@tanstack/react-router' + + function RootLayout() { + return
    Layout
    + } + + export const Route = createRootRoute()({ + component: RootLayout, + }) + `, + }, + ], + invalid: [ + // Async component directly in route option + { + filename: 'AsyncRoute.tsx', + code: ` + import { createFileRoute } from '@tanstack/react-router' + + async function AsyncPage() { + const data = await fetch('/api') + return
    {data}
    + } + + export const Route = createFileRoute('/')({ + component: AsyncPage, + }) + `, + errors: [ + { + messageId: 'asyncClientComponentDefinition', + }, + ], + }, + // Async component in 'use client' file + { + filename: 'AsyncClient.tsx', + code: ` + 'use client' + + export async function AsyncClientComponent() { + return
    Async
    + } + `, + errors: [ + { + messageId: 'asyncClientComponentDefinition', + }, + ], + }, + // Async arrow component in route + { + filename: 'AsyncArrowRoute.tsx', + code: ` + import { createFileRoute } from '@tanstack/react-router' + + const AsyncPage = async () => { + return
    Async
    + } + + export const Route = createFileRoute('/')({ + component: AsyncPage, + }) + `, + errors: [ + { + messageId: 'asyncClientComponentDefinition', + }, + ], + }, + // Async pendingComponent + { + filename: 'AsyncPending.tsx', + code: ` + import { createFileRoute } from '@tanstack/react-router' + + async function AsyncPending() { + return
    Loading...
    + } + + export const Route = createFileRoute('/')({ + component: () =>
    Hello
    , + pendingComponent: AsyncPending, + }) + `, + errors: [ + { + messageId: 'asyncClientComponentDefinition', + }, + ], + }, + // Async errorComponent + { + filename: 'AsyncError.tsx', + code: ` + import { createFileRoute } from '@tanstack/react-router' + + async function AsyncError() { + return
    Error
    + } + + export const Route = createFileRoute('/')({ + component: () =>
    Hello
    , + errorComponent: AsyncError, + }) + `, + errors: [ + { + messageId: 'asyncClientComponentDefinition', + }, + ], + }, + // Async in createRootRoute + { + filename: 'AsyncRoot.tsx', + code: ` + import { createRootRoute } from '@tanstack/react-router' + + async function AsyncRoot() { + return
    Root
    + } + + export const Route = createRootRoute()({ + component: AsyncRoot, + }) + `, + errors: [ + { + messageId: 'asyncClientComponentDefinition', + }, + ], + }, + // Async in createRootRouteWithContext + { + filename: 'AsyncRootWithContext.tsx', + code: ` + import { createRootRouteWithContext, Outlet } from '@tanstack/react-router' + + interface MyRouterContext { + foo: string + } + + async function AsyncRoot() { + return
    Root
    + } + + const rootRoute = createRootRouteWithContext()({ + component: AsyncRoot, + }) + `, + errors: [ + { + messageId: 'asyncClientComponentDefinition', + }, + ], + }, + // Multiple async components in same file + { + filename: 'AsyncMultiple.tsx', + code: ` + import { createFileRoute } from '@tanstack/react-router' + + async function AsyncOne() { + return
    One
    + } + + async function AsyncTwo() { + return
    Two
    + } + + export const Route = createFileRoute('/')({ + component: AsyncOne, + pendingComponent: AsyncTwo, + }) + `, + errors: [ + { + messageId: 'asyncClientComponentDefinition', + }, + { + messageId: 'asyncClientComponentDefinition', + }, + ], + }, + ], +}) diff --git a/packages/eslint-plugin-start/src/__tests__/no-client-code-in-server-component.rule.test.ts b/packages/eslint-plugin-start/src/__tests__/no-client-code-in-server-component.rule.test.ts new file mode 100644 index 0000000000..39c780417f --- /dev/null +++ b/packages/eslint-plugin-start/src/__tests__/no-client-code-in-server-component.rule.test.ts @@ -0,0 +1,289 @@ +import * as path from 'node:path' +import { RuleTester } from '@typescript-eslint/rule-tester' +import * as vitest from 'vitest' + +import { + name, + rule, +} from '../rules/no-client-code-in-server-component/no-client-code-in-server-component.rule' + +RuleTester.afterAll = vitest.afterAll +RuleTester.it = ((name, fn) => + vitest.it(name, { timeout: 15000 }, fn)) as typeof RuleTester.it +RuleTester.itOnly = vitest.it.only +RuleTester.describe = vitest.describe + +const ruleTester = new RuleTester({ + languageOptions: { + parserOptions: { + ecmaFeatures: { + jsx: true, + }, + projectService: { + allowDefaultProject: ['*.tsx'], + }, + tsconfigRootDir: path.join(__dirname), + }, + }, +}) + +ruleTester.run(name, rule as any, { + valid: [ + // useId is allowed in server components + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + const id = useId() + return
    Content
    + }) + `, + }, + // File with 'use client' is skipped entirely + { + code: ` + 'use client' + + import { useState } from 'react' + + function ClientComponent() { + const [state] = useState(0) + return + } + `, + }, + // Async server component is fine + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(async () => { + const data = await fetch('/api/data') + return
    {data}
    + }) + `, + }, + // Regular function outside createCompositeComponent is fine + { + code: ` + function RegularComponent() { + const [state] = useState(0) + return + } + `, + }, + // Component passed as prop (slot) is allowed + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(({ ActionButton }) => { + return
    + }) + `, + }, + // Component from destructured props is allowed + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent((props) => { + const { ActionButton } = props + return
    + }) + `, + }, + // Non-JSX attribute function is allowed (not an event handler) + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + return
    Content
    + }) + `, + }, + // Static strings and primitives are fine + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + const name = "John" + return
    {name}
    + }) + `, + }, + // Custom hook allowed via options + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + const data = useServerData() + return
    {data}
    + }) + `, + options: [{ allowedServerHooks: ['useServerData'] }], + }, + ], + invalid: [ + // Hook in inline server component + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + const [state] = useState(0) + return
    {state}
    + }) + `, + errors: [{ messageId: 'hookInServerComponent' }], + }, + // Browser API in server component + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + const width = window.innerWidth + return
    {width}
    + }) + `, + errors: [{ messageId: 'browserGlobalInServerComponent' }], + }, + // Event handler in server component + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + return + }) + `, + errors: [{ messageId: 'eventHandlerInServerComponent' }], + }, + // Event handler on intrinsic element (div) is also not allowed + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + return
    {}}>Click
    + }) + `, + errors: [{ messageId: 'eventHandlerInServerComponent' }], + }, + // Multiple violations + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + const [state] = useState(0) + const width = window.innerWidth + return + }) + `, + errors: [ + { messageId: 'hookInServerComponent' }, + { messageId: 'browserGlobalInServerComponent' }, + { messageId: 'eventHandlerInServerComponent' }, + ], + }, + // localStorage browser API + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + const val = localStorage.getItem('key') + return
    {val}
    + }) + `, + errors: [{ messageId: 'browserGlobalInServerComponent' }], + }, + // document browser API + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + const el = document.getElementById('foo') + return
    {el}
    + }) + `, + errors: [{ messageId: 'browserGlobalInServerComponent' }], + }, + // useEffect hook + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + useEffect(() => {}, []) + return
    Content
    + }) + `, + errors: [{ messageId: 'hookInServerComponent' }], + }, + // useRef hook + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + const ref = useRef(null) + return
    Content
    + }) + `, + errors: [{ messageId: 'hookInServerComponent' }], + }, + // useContext hook + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + const ctx = useContext(MyContext) + return
    {ctx}
    + }) + `, + errors: [{ messageId: 'hookInServerComponent' }], + }, + // onSubmit event handler + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + return
    {}}>Submit
    + }) + `, + errors: [{ messageId: 'eventHandlerInServerComponent' }], + }, + // onChange event handler + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + return {}} /> + }) + `, + errors: [{ messageId: 'eventHandlerInServerComponent' }], + }, + // onMouseEnter event handler + { + code: ` + import { createCompositeComponent } from '@tanstack/react-start/rsc' + + createCompositeComponent(() => { + return
    {}}>Hover
    + }) + `, + errors: [{ messageId: 'eventHandlerInServerComponent' }], + }, + ], +}) diff --git a/packages/eslint-plugin-start/src/__tests__/tsconfig.json b/packages/eslint-plugin-start/src/__tests__/tsconfig.json new file mode 100644 index 0000000000..1f4ecae36f --- /dev/null +++ b/packages/eslint-plugin-start/src/__tests__/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "jsx": "react-jsx", + "esModuleInterop": true, + "skipLibCheck": true, + "noEmit": true + }, + "include": ["./**/*"] +} diff --git a/packages/eslint-plugin-start/src/index.ts b/packages/eslint-plugin-start/src/index.ts new file mode 100644 index 0000000000..a6815a6328 --- /dev/null +++ b/packages/eslint-plugin-start/src/index.ts @@ -0,0 +1,45 @@ +import { rules } from './rules' +import type { ESLint, Linter } from 'eslint' +import type { RuleModule } from '@typescript-eslint/utils/ts-eslint' + +type RuleKey = keyof typeof rules + +interface Plugin extends Omit { + rules: Record> + configs: { + recommended: ESLint.ConfigData + 'flat/recommended': Array + } +} + +const plugin: Plugin = { + meta: { + name: '@tanstack/eslint-plugin-start', + }, + configs: {} as Plugin['configs'], + rules, +} + +// Assign configs here so we can reference `plugin` +Object.assign(plugin.configs, { + recommended: { + plugins: ['@tanstack/eslint-plugin-start'], + rules: { + '@tanstack/start/no-client-code-in-server-component': 'error', + '@tanstack/start/no-async-client-component': 'error', + }, + }, + 'flat/recommended': [ + { + plugins: { + '@tanstack/start': plugin, + }, + rules: { + '@tanstack/start/no-client-code-in-server-component': 'error', + '@tanstack/start/no-async-client-component': 'error', + }, + }, + ], +}) + +export default plugin diff --git a/packages/eslint-plugin-start/src/rules.ts b/packages/eslint-plugin-start/src/rules.ts new file mode 100644 index 0000000000..01df0f0239 --- /dev/null +++ b/packages/eslint-plugin-start/src/rules.ts @@ -0,0 +1,17 @@ +import * as noClientCodeInServerComponent from './rules/no-client-code-in-server-component/no-client-code-in-server-component.rule' +import * as noAsyncClientComponent from './rules/no-async-client-component/no-async-client-component.rule' +import type { ESLintUtils } from '@typescript-eslint/utils' +import type { ExtraRuleDocs } from './types' + +export const rules: Record< + string, + ESLintUtils.RuleModule< + string, + ReadonlyArray, + ExtraRuleDocs, + ESLintUtils.RuleListener + > +> = { + [noClientCodeInServerComponent.name]: noClientCodeInServerComponent.rule, + [noAsyncClientComponent.name]: noAsyncClientComponent.rule, +} diff --git a/packages/eslint-plugin-start/src/rules/no-async-client-component/async-component-detector.ts b/packages/eslint-plugin-start/src/rules/no-async-client-component/async-component-detector.ts new file mode 100644 index 0000000000..cf377ac6c4 --- /dev/null +++ b/packages/eslint-plugin-start/src/rules/no-async-client-component/async-component-detector.ts @@ -0,0 +1,121 @@ +import type ts from 'typescript' + +export interface AsyncComponentInfo { + name: string + fileName: string + node: ts.FunctionDeclaration | ts.VariableDeclaration + line: number +} + +/** + * Detects async function components in a TypeScript source file. + * A component is identified by: + * - PascalCase name (starts with uppercase) + * - async function declaration or const assigned to async arrow/function + */ +export function createAsyncComponentDetector(tsLib: typeof ts) { + return { + /** + * Find all async components in a source file + */ + detectAsyncComponents( + sourceFile: ts.SourceFile, + ): Array { + const asyncComponents: Array = [] + + function visit(node: ts.Node): void { + // async function MyComponent() { ... } + if ( + tsLib.isFunctionDeclaration(node) && + node.name && + isPascalCase(node.name.text) && + hasAsyncModifier(node) + ) { + asyncComponents.push({ + name: node.name.text, + fileName: sourceFile.fileName, + node, + line: + sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + + 1, + }) + } + + // const MyComponent = async () => { ... } + // const MyComponent = async function() { ... } + if (tsLib.isVariableStatement(node)) { + for (const decl of node.declarationList.declarations) { + if ( + tsLib.isIdentifier(decl.name) && + isPascalCase(decl.name.text) && + decl.initializer && + isAsyncFunctionLike(decl.initializer) + ) { + asyncComponents.push({ + name: decl.name.text, + fileName: sourceFile.fileName, + node: decl, + line: + sourceFile.getLineAndCharacterOfPosition(decl.getStart()) + .line + 1, + }) + } + } + } + + tsLib.forEachChild(node, visit) + } + + visit(sourceFile) + return asyncComponents + }, + + /** + * Check if a specific function node is async + */ + isAsyncFunction(node: ts.Node): boolean { + if ( + tsLib.isFunctionDeclaration(node) || + tsLib.isFunctionExpression(node) + ) { + return hasAsyncModifier(node) + } + if (tsLib.isArrowFunction(node)) { + return hasAsyncModifier(node) + } + return false + }, + } + + function isPascalCase(name: string): boolean { + return /^[A-Z]/.test(name) + } + + function hasAsyncModifier( + node: + | ts.FunctionDeclaration + | ts.FunctionExpression + | ts.ArrowFunction + | ts.MethodDeclaration, + ): boolean { + return ( + node.modifiers?.some( + (mod) => mod.kind === tsLib.SyntaxKind.AsyncKeyword, + ) ?? false + ) + } + + function isAsyncFunctionLike(node: ts.Node): boolean { + if (tsLib.isArrowFunction(node)) { + return hasAsyncModifier(node) + } + if (tsLib.isFunctionExpression(node)) { + return hasAsyncModifier(node) + } + return false + } +} + +export type AsyncComponentDetector = ReturnType< + typeof createAsyncComponentDetector +> diff --git a/packages/eslint-plugin-start/src/rules/no-async-client-component/constants.ts b/packages/eslint-plugin-start/src/rules/no-async-client-component/constants.ts new file mode 100644 index 0000000000..ffc2809518 --- /dev/null +++ b/packages/eslint-plugin-start/src/rules/no-async-client-component/constants.ts @@ -0,0 +1,27 @@ +/** + * Route option names that accept component references. + * These make the referenced component a "client root". + */ +export const ROUTE_COMPONENT_OPTION_NAMES = [ + 'component', + 'pendingComponent', + 'errorComponent', + 'notFoundComponent', +] as const + +/** + * Function names that create routes (client entry points). + */ +export const ROUTE_CREATOR_NAMES = [ + 'createFileRoute', + 'createRootRoute', + 'createRootRouteWithContext', +] as const + +/** + * Function names that create server-component roots. + */ +export const SERVER_COMPONENT_ROOTS = [ + 'renderServerComponent', + 'createCompositeComponent', +] as const diff --git a/packages/eslint-plugin-start/src/rules/no-async-client-component/context-analyzer.ts b/packages/eslint-plugin-start/src/rules/no-async-client-component/context-analyzer.ts new file mode 100644 index 0000000000..126019e93f --- /dev/null +++ b/packages/eslint-plugin-start/src/rules/no-async-client-component/context-analyzer.ts @@ -0,0 +1,203 @@ +import type { + ComponentInfo, + RenderEdge, + RenderGraph, +} from './render-graph-builder' + +export type ClientReason = + | { type: 'use-client'; fileName: string } + | { + type: 'route-option' + fileName: string + usageFile?: string + usageNode?: unknown + usageLine?: number + } + | { type: 'rendered-by-client'; parentComponent: string; parentFile: string } + +export interface ComponentContext { + key: string + component: ComponentInfo + isServerContext: boolean + isClientContext: boolean + clientReason?: ClientReason +} + +export interface ContextAnalysisResult { + /** Map of component key -> context info */ + contexts: Map + /** Edges where caller is in client context (for usage-site reporting) */ + clientEdges: Array +} + +/** + * Analyzes the render graph to propagate server/client context. + * + * Algorithm: + * 1. Mark server roots as server context, propagate to descendants + * 2. Stop propagation at 'use client' boundaries + * 3. Mark client roots as client context, propagate to descendants + * 4. Components reachable from both => client wins (tainted) + + */ +export function analyzeContext(graph: RenderGraph): ContextAnalysisResult { + const contexts = new Map() + + // Initialize all components with unknown context + for (const [key, component] of graph.components) { + contexts.set(key, { + key, + component, + isServerContext: false, + isClientContext: false, + }) + } + + // Build adjacency list for efficient traversal + const adjacency = buildAdjacencyList(graph.edges) + + // Phase 1: Propagate server context from server roots + const serverVisited = new Set() + for (const serverRoot of graph.serverRoots) { + propagateServerContext( + serverRoot, + serverVisited, + graph, + contexts, + adjacency, + ) + } + + // Phase 2: Propagate client context from client roots + const clientVisited = new Set() + for (const clientRoot of graph.clientRoots) { + const ctx = contexts.get(clientRoot) + if (!ctx) continue + + let reason: ClientReason + if (graph.useClientFiles.has(ctx.component.fileName)) { + reason = { type: 'use-client', fileName: ctx.component.fileName } + } else { + const routeUsage = graph.routeOptionUsages.get(clientRoot) + reason = { + type: 'route-option', + fileName: ctx.component.fileName, + usageFile: routeUsage?.fileName, + usageNode: routeUsage?.usageNode, + usageLine: routeUsage?.usageLine, + } + } + + propagateClientContext( + clientRoot, + clientVisited, + contexts, + adjacency, + reason, + ) + } + + // Phase 3: Components in 'use client' files are always client + for (const [_key, ctx] of contexts) { + if ( + graph.useClientFiles.has(ctx.component.fileName) && + !ctx.isClientContext + ) { + ctx.isClientContext = true + ctx.clientReason = { + type: 'use-client', + fileName: ctx.component.fileName, + } + } + } + + // Collect edges where caller is in client context + const clientEdges: Array = [] + for (const edge of graph.edges) { + const fromKey = `${edge.fromFile}:${edge.fromComponent}` + const fromCtx = contexts.get(fromKey) + if (fromCtx?.isClientContext) { + clientEdges.push(edge) + } + } + + return { contexts, clientEdges } +} + +function buildAdjacencyList( + edges: Array, +): Map> { + const adj = new Map>() + for (const edge of edges) { + const fromKey = `${edge.fromFile}:${edge.fromComponent}` + if (!adj.has(fromKey)) { + adj.set(fromKey, []) + } + adj.get(fromKey)!.push(edge) + } + return adj +} + +function propagateServerContext( + key: string, + visited: Set, + graph: RenderGraph, + contexts: Map, + adjacency: Map>, +): void { + if (visited.has(key)) return + visited.add(key) + + const ctx = contexts.get(key) + if (!ctx) return + + // Stop at 'use client' boundary + if (graph.useClientFiles.has(ctx.component.fileName)) { + ctx.isClientContext = true + ctx.clientReason = { type: 'use-client', fileName: ctx.component.fileName } + return + } + + ctx.isServerContext = true + + // Propagate to children + const edges = adjacency.get(key) ?? [] + for (const edge of edges) { + propagateServerContext( + edge.toComponentKey, + visited, + graph, + contexts, + adjacency, + ) + } +} + +function propagateClientContext( + key: string, + visited: Set, + contexts: Map, + adjacency: Map>, + reason: ClientReason, +): void { + if (visited.has(key)) return + visited.add(key) + + const ctx = contexts.get(key) + if (!ctx) return + + ctx.isClientContext = true + if (!ctx.clientReason) { + ctx.clientReason = reason + } + + // Propagate to children + const edges = adjacency.get(key) ?? [] + for (const edge of edges) { + propagateClientContext(edge.toComponentKey, visited, contexts, adjacency, { + type: 'rendered-by-client', + parentComponent: ctx.component.name, + parentFile: ctx.component.fileName, + }) + } +} diff --git a/packages/eslint-plugin-start/src/rules/no-async-client-component/no-async-client-component.rule.ts b/packages/eslint-plugin-start/src/rules/no-async-client-component/no-async-client-component.rule.ts new file mode 100644 index 0000000000..54a69a6fb8 --- /dev/null +++ b/packages/eslint-plugin-start/src/rules/no-async-client-component/no-async-client-component.rule.ts @@ -0,0 +1,430 @@ +import path from 'node:path' +import { ESLintUtils } from '@typescript-eslint/utils' +import * as ts from 'typescript' +import { getDocsUrl } from '../../utils/get-docs-url' +import { createRenderGraphBuilder } from './render-graph-builder' +import { analyzeContext } from './context-analyzer' +import type { ClientReason, ContextAnalysisResult } from './context-analyzer' +import type { ExtraRuleDocs } from '../../types' + +export const name = 'no-async-client-component' + +// Cache full graph per program (built rarely due to gating). +const perProgramCache = new WeakMap< + ts.Program, + { + builder: ReturnType + graphBuilt: boolean + } +>() + +// Cache for on-demand subgraph analysis per entry file +const onDemandCache = new WeakMap< + ts.Program, + Map< + string, + { + graph: ReturnType['getGraph']> + analysis: ContextAnalysisResult + } + > +>() + +// Cache adjacency per program to avoid O(allEdges) scans while slicing +const adjacencyCache = new WeakMap>>() + +export const rule = ESLintUtils.RuleCreator(getDocsUrl)({ + name, + meta: { + type: 'problem', + docs: { + description: + 'Disallow async components in client context. Async components are only valid inside server components.', + + recommended: 'error', + }, + schema: [ + { + type: 'object', + properties: { + ignorePatterns: { + type: 'array', + items: { type: 'string' }, + description: 'File patterns to ignore', + }, + }, + additionalProperties: false, + }, + ], + messages: { + asyncClientComponentDefinition: + 'Async component "{{name}}" cannot be used in client context. ' + + 'Async components are only valid inside server components. ' + + 'Either remove "async" or ensure this component is only rendered within server components. ' + + '{{reason}}', + asyncClientComponentUsage: + 'Async component "{{name}}" is rendered in client context here. ' + + 'Async components are only valid inside server components. ' + + 'Move this to a server component or use a non-async version.', + }, + }, + defaultOptions: [{ ignorePatterns: [] }] as const, + create(context, [options]) { + const services = ESLintUtils.getParserServices(context) + const program = services.program + const checker = program.getTypeChecker() + // Normalize the current file path to absolute + const currentFile = path.isAbsolute(context.filename) + ? context.filename + : path.resolve(context.cwd, context.filename) + + // Check if file should be ignored + const ignorePatterns = [...options.ignorePatterns] + if (shouldIgnore(currentFile, ignorePatterns)) { + return {} + } + + // Build full graph once (still gated per-file above). + let cached = perProgramCache.get(program) + if (!cached) { + const builder = createRenderGraphBuilder(ts, program, checker) + cached = { builder, graphBuilt: false } + perProgramCache.set(program, cached) + } + + // Track reported to avoid duplicates + const reported = new Set() + + return { + Program() { + // Fast path: if current file can’t introduce client roots, skip. + // This avoids full-program graph build for most files. + const sourceFile = program.getSourceFile(currentFile) + if ( + !sourceFile || + (!fileContainsRouteOptions(sourceFile) && + !fileContainsServerComponentRoots(sourceFile) && + !fileHasUseClientDirective(sourceFile)) + ) { + return + } + + // Ensure route-option cases are always analyzed (e2e runs ESLint per-file). + // On-demand caching is still used for perf; this just avoids missing route roots. + if (fileContainsRouteOptions(sourceFile)) { + // no-op: gate ensures analysis runs + } + + // On-demand: build only the subgraph reachable from this file's entry points, + // then analyze contexts within that subgraph. + const analysis = getOnDemandAnalysis(currentFile) + + // Report async components in client context + for (const [key, ctx] of analysis.contexts) { + if (!ctx.component.isAsync || !ctx.isClientContext) { + continue + } + + const reportKey = `def:${key}` + if (reported.has(reportKey)) continue + + // For route-option cases, ONLY report at usage site (in the route file) + if (ctx.clientReason?.type === 'route-option') { + const usageFile = ctx.clientReason.usageFile + if (usageFile && usageFile === currentFile) { + const usageTsNode = ctx.clientReason.usageNode as ts.Node + const usageEslintNode = + services.tsNodeToESTreeNodeMap.get(usageTsNode) + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Map.get() can return undefined + if (usageEslintNode) { + reported.add(reportKey) + context.report({ + node: usageEslintNode, + messageId: 'asyncClientComponentDefinition', + data: { + name: ctx.component.name, + reason: formatReason(ctx.clientReason, context.cwd), + }, + }) + } + } + continue + } + + reported.add(reportKey) + + // For other cases (use-client, rendered-by-client): report at definition site + const tsNode = ctx.component.node + const eslintNode = services.tsNodeToESTreeNodeMap.get(tsNode) + + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Map.get() can return undefined + if (eslintNode) { + context.report({ + node: eslintNode, + messageId: 'asyncClientComponentDefinition', + data: { + name: ctx.component.name, + reason: ctx.clientReason + ? formatReason(ctx.clientReason, context.cwd) + : '', + }, + }) + } + } + + // Report usage sites where async component is rendered in client context + for (const edge of analysis.clientEdges) { + const targetCtx = analysis.contexts.get(edge.toComponentKey) + if (!targetCtx?.component.isAsync) continue + + if (edge.fromFile !== currentFile) continue + + const reportKey = `usage:${edge.fromFile}:${edge.jsxLine}:${edge.toComponent}` + if (reported.has(reportKey)) continue + reported.add(reportKey) + + const eslintNode = services.tsNodeToESTreeNodeMap.get(edge.jsxNode) + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Map.get() can return undefined + if (eslintNode) { + context.report({ + node: eslintNode, + messageId: 'asyncClientComponentUsage', + data: { + name: edge.toComponent, + }, + }) + } + } + }, + } + + function shouldIgnore(filePath: string, patterns: Array): boolean { + for (const pattern of patterns) { + if (filePath.includes(pattern)) { + return true + } + } + return false + } + + function formatReason(reason: ClientReason, cwd: string): string { + switch (reason.type) { + case 'use-client': + return `File has "use client" directive.` + case 'route-option': + return `Component is referenced by a route option (createFileRoute/createRootRoute).` + case 'rendered-by-client': + return `Rendered by client component "${reason.parentComponent}" in ${path.relative(cwd, reason.parentFile)}.` + } + } + + function getOnDemandAnalysis(entryFile: string): ContextAnalysisResult { + let programCache = onDemandCache.get(program) + if (!programCache) { + programCache = new Map() + onDemandCache.set(program, programCache) + } + + const cachedResult = programCache.get(entryFile) + if (cachedResult) return cachedResult.analysis + + // Build a complete graph once (still gated), then slice it to + // only what’s reachable from entry points in `entryFile`. + if (!cached!.graphBuilt) { + cached!.builder.build() + cached!.graphBuilt = true + } + const full = cached!.builder.getGraph() + + const subgraph = sliceGraphForEntryFile(full, entryFile) + + const entrySourceFile = program.getSourceFile(entryFile) + const shouldFallbackToFull = + !!entrySourceFile && + fileContainsRouteOptions(entrySourceFile) && + subgraph.clientRoots.size === 0 && + subgraph.serverRoots.size === 0 + + // Fallback: if slicing yields nothing but file has route options, analyze full graph. + const analysis = shouldFallbackToFull + ? analyzeContext(full) + : analyzeContext(subgraph) + + programCache.set(entryFile, { graph: subgraph, analysis }) + return analysis + } + + function sliceGraphForEntryFile( + full: ReturnType< + typeof createRenderGraphBuilder + >['getGraph'] extends () => infer G + ? G + : never, + entryFile: string, + ) { + const components = full.components + const edges = full.edges + const serverRoots = full.serverRoots + const clientRoots = full.clientRoots + const useClientFiles = full.useClientFiles + const routeOptionUsages = full.routeOptionUsages + + // Determine entry roots from this file. + const entryClientRoots = new Set() + const entryServerRoots = new Set() + + // Use the indexed routeOptionRootsByFile for O(roots-in-file) lookup + const routeRootsInFile = + routeOptionUsages.size > 0 + ? full.routeOptionRootsByFile.get(entryFile) + : undefined + if (routeRootsInFile) { + for (const key of routeRootsInFile) { + if (clientRoots.has(key)) { + entryClientRoots.add(key) + } + } + } + + for (const key of serverRoots) { + const component = components.get(key) + if (component?.fileName === entryFile) { + entryServerRoots.add(key) + } + } + + // If it’s a use-client file, also treat local components as client roots. + if (useClientFiles.has(entryFile)) { + for (const [key, component] of components) { + if (component.fileName === entryFile) { + entryClientRoots.add(key) + } + } + } + + const reachable = new Set() + const queue: Array = [] + for (const r of entryClientRoots) queue.push(r) + for (const r of entryServerRoots) queue.push(r) + + const adjacency = getAdjacency(full) + + while (queue.length) { + const key = queue.pop()! + if (reachable.has(key)) continue + reachable.add(key) + + const children = adjacency.get(key) + if (!children) continue + for (const toKey of children) { + if (!reachable.has(toKey)) { + queue.push(toKey) + } + } + } + + const subComponents = new Map() + for (const key of reachable) { + const comp = components.get(key) + if (comp) subComponents.set(key, comp) + } + + const subEdges = edges.filter((edge) => { + const fromKey = `${edge.fromFile}:${edge.fromComponent}` + return reachable.has(fromKey) && reachable.has(edge.toComponentKey) + }) + + const subServerRoots = new Set( + [...entryServerRoots].filter((k) => reachable.has(k)), + ) + const subClientRoots = new Set( + [...entryClientRoots].filter((k) => reachable.has(k)), + ) + + // Keep only routeUsage for roots we kept. + const subRouteOptionUsages = new Map() + const subRouteOptionRootsByFile = new Map>() + for (const key of subClientRoots) { + const usage = routeOptionUsages.get(key) + if (usage) { + subRouteOptionUsages.set(key, usage) + let set = subRouteOptionRootsByFile.get(usage.fileName) + if (!set) { + set = new Set() + subRouteOptionRootsByFile.set(usage.fileName, set) + } + set.add(key) + } + } + + return { + components: subComponents, + edges: subEdges, + serverRoots: subServerRoots, + clientRoots: subClientRoots, + useClientFiles, + routeOptionUsages: subRouteOptionUsages, + routeOptionRootsByFile: subRouteOptionRootsByFile, + } + } + + function getAdjacency(full: { edges: Array }) { + let cachedAdjacency = adjacencyCache.get(program) + if (cachedAdjacency) return cachedAdjacency + + cachedAdjacency = new Map() + for (const edge of full.edges) { + const fromKey = `${edge.fromFile}:${edge.fromComponent}` + let set = cachedAdjacency.get(fromKey) + if (!set) { + set = new Set() + cachedAdjacency.set(fromKey, set) + } + set.add(edge.toComponentKey) + } + + adjacencyCache.set(program, cachedAdjacency) + return cachedAdjacency + } + + function fileHasUseClientDirective(sourceFile: ts.SourceFile): boolean { + const firstStmt = sourceFile.statements[0] + if (!firstStmt) return false + return ( + ts.isExpressionStatement(firstStmt) && + ts.isStringLiteral(firstStmt.expression) && + firstStmt.expression.text === 'use client' + ) + } + + function fileContainsServerComponentRoots( + sourceFile: ts.SourceFile, + ): boolean { + // Cheaper than full AST traversal; ok since this is only a gate. + const text = sourceFile.text + return ( + text.includes('renderServerComponent') || + text.includes('createCompositeComponent') + ) + } + + function fileContainsRouteOptions(sourceFile: ts.SourceFile): boolean { + // Cheaper than full AST traversal; ok since this is only a gate. + const text = sourceFile.text + if ( + !text.includes('createFileRoute') && + !text.includes('createRootRoute') && + !text.includes('createRootRouteWithContext') + ) { + return false + } + + return ( + text.includes('component') || + text.includes('pendingComponent') || + text.includes('errorComponent') || + text.includes('notFoundComponent') + ) + } + }, +}) diff --git a/packages/eslint-plugin-start/src/rules/no-async-client-component/render-graph-builder.ts b/packages/eslint-plugin-start/src/rules/no-async-client-component/render-graph-builder.ts new file mode 100644 index 0000000000..3b736da2d9 --- /dev/null +++ b/packages/eslint-plugin-start/src/rules/no-async-client-component/render-graph-builder.ts @@ -0,0 +1,551 @@ +import { + ROUTE_COMPONENT_OPTION_NAMES, + ROUTE_CREATOR_NAMES, + SERVER_COMPONENT_ROOTS, +} from './constants' +import type ts from 'typescript' + +export interface ComponentInfo { + name: string + fileName: string + node: ts.Node + isAsync: boolean + line: number +} + +export interface RenderEdge { + fromFile: string + fromComponent: string + toFile: string + toComponent: string + toComponentKey: string + jsxNode: ts.Node + jsxLine: number +} + +export interface RouteOptionUsage { + componentKey: string + usageNode: ts.Node + usageLine: number + fileName: string +} + +export interface RenderGraph { + /** Map of "fileName:ComponentName" -> ComponentInfo */ + components: Map + /** All render edges (component -> component via JSX) */ + edges: Array + /** Components under server-component roots */ + serverRoots: Set + /** Components referenced by route options or in 'use client' files */ + clientRoots: Set + /** Files with 'use client' directive */ + useClientFiles: Set + /** Route option usage info for better error locations */ + routeOptionUsages: Map + /** Index: file name -> component keys referenced by route options in that file */ + routeOptionRootsByFile: Map> +} + +/** + * Builds a render graph from the TypeScript program. + * Indexes components, JSX edges, server roots, and client roots. + */ +export function createRenderGraphBuilder( + tsLib: typeof ts, + program: ts.Program, + checker: ts.TypeChecker, +) { + const graph: RenderGraph = { + components: new Map(), + edges: [], + serverRoots: new Set(), + clientRoots: new Set(), + useClientFiles: new Set(), + routeOptionUsages: new Map(), + routeOptionRootsByFile: new Map(), + } + + return { + build(): RenderGraph { + for (const sourceFile of program.getSourceFiles()) { + if (sourceFile.isDeclarationFile) continue + if (sourceFile.fileName.includes('node_modules')) continue + + // Pre-filter: skip files that can't contribute to the render graph + if (!fileCanContribute(sourceFile)) continue + + processSourceFile(sourceFile) + } + return graph + }, + + getGraph(): RenderGraph { + return graph + }, + } + + /** + * Quick text-based check to skip files that can't contribute edges or roots. + * A file can contribute if it might have: + * - JSX (components, edges) + * - 'use client' directive (client roots) + * - createFileRoute/createRootRoute (route-option roots) + * - renderServerComponent/createCompositeComponent (server roots) + + */ + function fileCanContribute(sourceFile: ts.SourceFile): boolean { + const text = sourceFile.text + + // Quick check: has JSX-like syntax or relevant keywords + // Must handle both and + const hasJsx = + text.includes('<') && (text.includes('/>') || text.includes(' + text.includes(name), + ) + + return hasJsx || hasUseClient || hasRouteCreator || hasServerComponentRoot + } + + function processSourceFile(sourceFile: ts.SourceFile): void { + // Check for 'use client' directive + if (hasUseClientDirective(sourceFile)) { + graph.useClientFiles.add(sourceFile.fileName) + } + + // Walk AST + visitNode(sourceFile, sourceFile, null) + } + + function hasUseClientDirective(sourceFile: ts.SourceFile): boolean { + const firstStatement = sourceFile.statements[0] + if (!firstStatement) return false + + if ( + tsLib.isExpressionStatement(firstStatement) && + tsLib.isStringLiteral(firstStatement.expression) && + firstStatement.expression.text === 'use client' + ) { + return true + } + return false + } + + function visitNode( + node: ts.Node, + sourceFile: ts.SourceFile, + currentComponent: string | null, + ): void { + // Index component definitions + if (tsLib.isFunctionDeclaration(node) && node.name) { + if (isPascalCase(node.name.text)) { + const key = makeKey(sourceFile.fileName, node.name.text) + graph.components.set(key, { + name: node.name.text, + fileName: sourceFile.fileName, + node, + isAsync: hasAsyncModifier(node), + line: getLine(sourceFile, node), + }) + + // If file has 'use client', mark as client root + if (graph.useClientFiles.has(sourceFile.fileName)) { + graph.clientRoots.add(key) + } + + // Visit body with this component as context + if (node.body) { + tsLib.forEachChild(node.body, (child) => + visitNode(child, sourceFile, key), + ) + } + return + } + } + + // const MyComponent = () => { ... } or const MyComponent = function() { ... } + if (tsLib.isVariableStatement(node)) { + for (const decl of node.declarationList.declarations) { + if ( + tsLib.isIdentifier(decl.name) && + isPascalCase(decl.name.text) && + decl.initializer && + isFunctionLike(decl.initializer) + ) { + const key = makeKey(sourceFile.fileName, decl.name.text) + graph.components.set(key, { + name: decl.name.text, + fileName: sourceFile.fileName, + node: decl, + isAsync: isAsyncFunctionLike(decl.initializer), + line: getLine(sourceFile, decl), + }) + + if (graph.useClientFiles.has(sourceFile.fileName)) { + graph.clientRoots.add(key) + } + + // Visit body with this component as context + const funcNode = decl.initializer as + | ts.ArrowFunction + | ts.FunctionExpression + tsLib.forEachChild(funcNode.body, (child) => + visitNode(child, sourceFile, key), + ) + } else if (decl.initializer) { + // For non-component variable declarations (like route definitions), + // visit the initializer to detect route creator calls + visitNode(decl.initializer, sourceFile, currentComponent) + } + } + return + } + + // Detect server-component roots + // - createCompositeComponent((props) => <...>) + // - renderServerComponent(<...>) + if (tsLib.isCallExpression(node)) { + const serverRootKind = getServerRootKind(node, checker) + if (serverRootKind === 'createCompositeComponent') { + const callback = node.arguments[0] + if (callback && isFunctionLike(callback)) { + collectJsxComponentRefs(callback, sourceFile, currentComponent, true) + } + return + } + + if (serverRootKind === 'renderServerComponent') { + const element = node.arguments[0] + if (element) { + collectJsxComponentRefs(element, sourceFile, currentComponent, true) + } + return + } + } + + // Detect createFileRoute/createRootRoute/createRootRouteWithContext()({ component: X }) + if (tsLib.isCallExpression(node)) { + const routeOptions = getRouteOptionsObject(node) + if (routeOptions) { + for (const prop of routeOptions.properties) { + if ( + tsLib.isPropertyAssignment(prop) && + tsLib.isIdentifier(prop.name) && + ROUTE_COMPONENT_OPTION_NAMES.includes( + prop.name.text as (typeof ROUTE_COMPONENT_OPTION_NAMES)[number], + ) + ) { + markAsClientRoot( + prop.initializer, + sourceFile, + currentComponent, + prop, + ) + } + } + } + } + + // Detect JSX usage: + if ( + tsLib.isJsxOpeningElement(node) || + tsLib.isJsxSelfClosingElement(node) + ) { + const tagName = node.tagName + if (tsLib.isIdentifier(tagName) && isPascalCase(tagName.text)) { + // Try to resolve the component + const symbol = checker.getSymbolAtLocation(tagName) + if (symbol) { + const resolved = resolveSymbol(symbol) + if (resolved) { + const decls = resolved.getDeclarations() + if (decls && decls.length > 0) { + const declFile = decls[0]!.getSourceFile().fileName + const toKey = makeKey(declFile, tagName.text) + + if (currentComponent) { + graph.edges.push({ + fromFile: sourceFile.fileName, + fromComponent: currentComponent.split(':')[1]!, + toFile: declFile, + toComponent: tagName.text, + toComponentKey: toKey, + jsxNode: node, + jsxLine: getLine(sourceFile, node), + }) + } + } + } + } + } + } + + tsLib.forEachChild(node, (child) => + visitNode(child, sourceFile, currentComponent), + ) + return + } + + function getServerRootKind( + node: ts.CallExpression, + _checker: ts.TypeChecker, + ): (typeof SERVER_COMPONENT_ROOTS)[number] | null { + if (tsLib.isIdentifier(node.expression)) { + const name = node.expression.text + return SERVER_COMPONENT_ROOTS.includes( + name as (typeof SERVER_COMPONENT_ROOTS)[number], + ) + ? (name as (typeof SERVER_COMPONENT_ROOTS)[number]) + : null + } + + if ( + tsLib.isPropertyAccessExpression(node.expression) && + tsLib.isIdentifier(node.expression.name) + ) { + const name = node.expression.name.text + return SERVER_COMPONENT_ROOTS.includes( + name as (typeof SERVER_COMPONENT_ROOTS)[number], + ) + ? (name as (typeof SERVER_COMPONENT_ROOTS)[number]) + : null + } + + return null + } + + function getRouteOptionsObject( + node: ts.CallExpression, + ): ts.ObjectLiteralExpression | undefined { + // Matches route options call patterns: + // - createFileRoute('/x')({ ... }) + // - createRootRoute()({ ... }) + // - createRootRouteWithContext()({ ... }) + // - plus common chaining/currying where the creator call is nested + + // We only care about the call expression that receives the options object. + const optionsArg = node.arguments[0] + if (!optionsArg || !tsLib.isObjectLiteralExpression(optionsArg)) { + return + } + + // Accept any call where the callee ultimately originates from a route creator. + // Examples: + // createFileRoute('/x')({}) + // createFileRoute('/x').update({})(...) + // (createFileRoute('/x'))({}) + const routeCreator = findRouteCreatorFromCallee(node.expression) + if (!routeCreator) return + + const routeCreatorName = tsLib.isIdentifier(routeCreator) + ? routeCreator.text + : routeCreator.name.text + + if ( + ROUTE_CREATOR_NAMES.includes( + routeCreatorName as (typeof ROUTE_CREATOR_NAMES)[number], + ) + ) { + return optionsArg + } + + return + } + + function findRouteCreatorFromCallee( + expr: ts.Expression, + ): ts.Identifier | ts.PropertyAccessExpression | undefined { + // OUTER call has callee like: CallExpression or PropertyAccessExpression, etc. + // Walk back through call/property/paren nodes to find the originating identifier. + + if (tsLib.isParenthesizedExpression(expr)) { + return findRouteCreatorFromCallee(expr.expression) + } + + if (tsLib.isCallExpression(expr)) { + return findRouteCreatorFromCallee(expr.expression) + } + + if (tsLib.isPropertyAccessExpression(expr)) { + // foo.bar -> keep walking left side, but allow final `.createFileRoute` access. + if (tsLib.isIdentifier(expr.name)) { + if ( + ROUTE_CREATOR_NAMES.includes( + expr.name.text as (typeof ROUTE_CREATOR_NAMES)[number], + ) + ) { + return expr + } + } + return findRouteCreatorFromCallee(expr.expression) + } + + if (tsLib.isIdentifier(expr)) { + return expr + } + + return + } + + function markAsClientRoot( + node: ts.Node, + sourceFile: ts.SourceFile, + _currentComponent: string | null, + usageNode?: ts.Node, + ): void { + // Direct identifier reference: component: MyComponent + if (tsLib.isIdentifier(node)) { + const componentName = node.text + + // First, try to find by symbol resolution + const symbol = checker.getSymbolAtLocation(node) + if (symbol) { + const resolved = resolveSymbol(symbol) + if (resolved) { + const decls = resolved.getDeclarations() + if (decls && decls.length > 0) { + const declFile = decls[0]!.getSourceFile().fileName + const key = makeKey(declFile, componentName) + graph.clientRoots.add(key) + if (usageNode) { + graph.routeOptionUsages.set(key, { + componentKey: key, + usageNode, + usageLine: getLine(sourceFile, usageNode), + fileName: sourceFile.fileName, + }) + addToRouteOptionRootsByFile(sourceFile.fileName, key) + } + return + } + } + } + + // Fallback: assume it's in the same file + const fallbackKey = makeKey(sourceFile.fileName, componentName) + graph.clientRoots.add(fallbackKey) + if (usageNode) { + graph.routeOptionUsages.set(fallbackKey, { + componentKey: fallbackKey, + usageNode, + usageLine: getLine(sourceFile, usageNode), + fileName: sourceFile.fileName, + }) + addToRouteOptionRootsByFile(sourceFile.fileName, fallbackKey) + } + return + } + + // Inline function: component: () => + // Find JSX refs within and mark them as client roots + if (isFunctionLike(node)) { + collectJsxComponentRefs(node, sourceFile, null, false, usageNode) + } + } + + function collectJsxComponentRefs( + node: ts.Node, + sourceFile: ts.SourceFile, + _currentComponent: string | null, + isServerContext: boolean, + usageNode?: ts.Node, + ): void { + function walk(n: ts.Node): void { + if (tsLib.isJsxOpeningElement(n) || tsLib.isJsxSelfClosingElement(n)) { + const tagName = n.tagName + if (tsLib.isIdentifier(tagName) && isPascalCase(tagName.text)) { + const symbol = checker.getSymbolAtLocation(tagName) + if (symbol) { + const resolved = resolveSymbol(symbol) + if (resolved) { + const decls = resolved.getDeclarations() + if (decls && decls.length > 0) { + const declFile = decls[0]!.getSourceFile().fileName + const key = makeKey(declFile, tagName.text) + + if (isServerContext) { + graph.serverRoots.add(key) + } else { + graph.clientRoots.add(key) + // For inline route options like component: () => , + // use the JSX node as the usage location + const effectiveUsageNode = usageNode ?? n + graph.routeOptionUsages.set(key, { + componentKey: key, + usageNode: effectiveUsageNode, + usageLine: getLine(sourceFile, effectiveUsageNode), + fileName: sourceFile.fileName, + }) + addToRouteOptionRootsByFile(sourceFile.fileName, key) + } + } + } + } + } + } + tsLib.forEachChild(n, walk) + } + walk(node) + } + + function resolveSymbol(symbol: ts.Symbol): ts.Symbol | undefined { + if (symbol.flags & tsLib.SymbolFlags.Alias) { + return checker.getAliasedSymbol(symbol) + } + return symbol + } + + function isPascalCase(name: string): boolean { + return /^[A-Z]/.test(name) + } + + function hasAsyncModifier( + node: ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction, + ): boolean { + return ( + node.modifiers?.some( + (mod) => mod.kind === tsLib.SyntaxKind.AsyncKeyword, + ) ?? false + ) + } + + function isFunctionLike(node: ts.Node): boolean { + return ( + tsLib.isArrowFunction(node) || + tsLib.isFunctionExpression(node) || + tsLib.isFunctionDeclaration(node) + ) + } + + function isAsyncFunctionLike(node: ts.Node): boolean { + if (tsLib.isArrowFunction(node) || tsLib.isFunctionExpression(node)) { + return hasAsyncModifier(node) + } + return false + } + + function makeKey(fileName: string, componentName: string): string { + return `${fileName}:${componentName}` + } + + function getLine(sourceFile: ts.SourceFile, node: ts.Node): number { + return sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1 + } + + function addToRouteOptionRootsByFile(fileName: string, key: string): void { + let set = graph.routeOptionRootsByFile.get(fileName) + if (!set) { + set = new Set() + graph.routeOptionRootsByFile.set(fileName, set) + } + set.add(key) + } +} + +export type RenderGraphBuilder = ReturnType diff --git a/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/constants.ts b/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/constants.ts new file mode 100644 index 0000000000..87fb9a8a3e --- /dev/null +++ b/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/constants.ts @@ -0,0 +1,266 @@ +import globals from 'globals' + +/** + * Hooks allowed in server components + */ +export const DEFAULT_ALLOWED_HOOKS = new Set(['useId']) + +/** + * React hooks to detect (common ones that are NOT allowed in server components) + */ +export const REACT_HOOKS = new Set([ + 'useState', + 'useEffect', + 'useLayoutEffect', + 'useReducer', + 'useCallback', + 'useMemo', + 'useRef', + 'useContext', + 'useImperativeHandle', + 'useDebugValue', + 'useDeferredValue', + 'useTransition', + 'useSyncExternalStore', + 'useInsertionEffect', + 'useOptimistic', + 'useFormStatus', + 'useActionState', +]) + +/** + * Browser-only globals not available in server context + * Dynamically computed from globals package: browser globals that are NOT in node + */ +export const BROWSER_ONLY_GLOBALS: Set = (() => { + const browserGlobals = Object.keys(globals.browser as Record) + const nodeGlobals = new Set( + Object.keys(globals.node as Record), + ) + + const browserOnly = new Set() + for (const name of browserGlobals) { + if (!nodeGlobals.has(name)) { + browserOnly.add(name) + } + } + return browserOnly +})() + +/** + * React event handler props - comprehensive list from React types + */ +export const REACT_EVENT_HANDLERS = new Set([ + // Clipboard Events + 'onCopy', + 'onCopyCapture', + 'onCut', + 'onCutCapture', + 'onPaste', + 'onPasteCapture', + + // Composition Events + 'onCompositionEnd', + 'onCompositionEndCapture', + 'onCompositionStart', + 'onCompositionStartCapture', + 'onCompositionUpdate', + 'onCompositionUpdateCapture', + + // Focus Events + 'onFocus', + 'onFocusCapture', + 'onBlur', + 'onBlurCapture', + + // Form Events + 'onChange', + 'onChangeCapture', + 'onBeforeInput', + 'onBeforeInputCapture', + 'onInput', + 'onInputCapture', + 'onReset', + 'onResetCapture', + 'onSubmit', + 'onSubmitCapture', + 'onInvalid', + 'onInvalidCapture', + + // Image Events + 'onLoad', + 'onLoadCapture', + 'onError', + 'onErrorCapture', + + // Keyboard Events + 'onKeyDown', + 'onKeyDownCapture', + 'onKeyPress', + 'onKeyPressCapture', + 'onKeyUp', + 'onKeyUpCapture', + + // Media Events + 'onAbort', + 'onAbortCapture', + 'onCanPlay', + 'onCanPlayCapture', + 'onCanPlayThrough', + 'onCanPlayThroughCapture', + 'onDurationChange', + 'onDurationChangeCapture', + 'onEmptied', + 'onEmptiedCapture', + 'onEncrypted', + 'onEncryptedCapture', + 'onEnded', + 'onEndedCapture', + 'onLoadedData', + 'onLoadedDataCapture', + 'onLoadedMetadata', + 'onLoadedMetadataCapture', + 'onLoadStart', + 'onLoadStartCapture', + 'onPause', + 'onPauseCapture', + 'onPlay', + 'onPlayCapture', + 'onPlaying', + 'onPlayingCapture', + 'onProgress', + 'onProgressCapture', + 'onRateChange', + 'onRateChangeCapture', + 'onResize', + 'onResizeCapture', + 'onSeeked', + 'onSeekedCapture', + 'onSeeking', + 'onSeekingCapture', + 'onStalled', + 'onStalledCapture', + 'onSuspend', + 'onSuspendCapture', + 'onTimeUpdate', + 'onTimeUpdateCapture', + 'onVolumeChange', + 'onVolumeChangeCapture', + 'onWaiting', + 'onWaitingCapture', + + // Mouse Events + 'onAuxClick', + 'onAuxClickCapture', + 'onClick', + 'onClickCapture', + 'onContextMenu', + 'onContextMenuCapture', + 'onDoubleClick', + 'onDoubleClickCapture', + 'onDrag', + 'onDragCapture', + 'onDragEnd', + 'onDragEndCapture', + 'onDragEnter', + 'onDragEnterCapture', + 'onDragExit', + 'onDragExitCapture', + 'onDragLeave', + 'onDragLeaveCapture', + 'onDragOver', + 'onDragOverCapture', + 'onDragStart', + 'onDragStartCapture', + 'onDrop', + 'onDropCapture', + 'onMouseDown', + 'onMouseDownCapture', + 'onMouseEnter', + 'onMouseLeave', + 'onMouseMove', + 'onMouseMoveCapture', + 'onMouseOut', + 'onMouseOutCapture', + 'onMouseOver', + 'onMouseOverCapture', + 'onMouseUp', + 'onMouseUpCapture', + + // Selection Events + 'onSelect', + 'onSelectCapture', + + // Touch Events + 'onTouchCancel', + 'onTouchCancelCapture', + 'onTouchEnd', + 'onTouchEndCapture', + 'onTouchMove', + 'onTouchMoveCapture', + 'onTouchStart', + 'onTouchStartCapture', + + // Pointer Events + 'onPointerDown', + 'onPointerDownCapture', + 'onPointerMove', + 'onPointerMoveCapture', + 'onPointerUp', + 'onPointerUpCapture', + 'onPointerCancel', + 'onPointerCancelCapture', + 'onPointerEnter', + 'onPointerEnterCapture', + 'onPointerLeave', + 'onPointerLeaveCapture', + 'onPointerOver', + 'onPointerOverCapture', + 'onPointerOut', + 'onPointerOutCapture', + 'onGotPointerCapture', + 'onGotPointerCaptureCapture', + 'onLostPointerCapture', + 'onLostPointerCaptureCapture', + + // UI Events + 'onScroll', + 'onScrollCapture', + + // Wheel Events + 'onWheel', + 'onWheelCapture', + + // Animation Events + 'onAnimationStart', + 'onAnimationStartCapture', + 'onAnimationEnd', + 'onAnimationEndCapture', + 'onAnimationIteration', + 'onAnimationIterationCapture', + + // Transition Events + 'onTransitionEnd', + 'onTransitionEndCapture', +]) + +/** + * Check if a prop name is a React event handler + */ +export function isReactEventHandler(name: string): boolean { + return REACT_EVENT_HANDLERS.has(name) +} + +/** + * Check if a hook name is client-only (not allowed in server components) + */ +export function isClientOnlyHook( + name: string, + allowedHooks: Set = DEFAULT_ALLOWED_HOOKS, +): boolean { + // Must match use[A-Z] pattern + if (!/^use[A-Z]/.test(name)) return false + // Check if explicitly allowed + if (allowedHooks.has(name)) return false + return true +} diff --git a/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/no-client-code-in-server-component.rule.ts b/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/no-client-code-in-server-component.rule.ts new file mode 100644 index 0000000000..57d314ee9c --- /dev/null +++ b/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/no-client-code-in-server-component.rule.ts @@ -0,0 +1,472 @@ +import path from 'node:path' +import { ESLintUtils } from '@typescript-eslint/utils' +import * as ts from 'typescript' +import { getDocsUrl } from '../../utils/get-docs-url' +import { createUseClientResolver } from '../../shared/use-client-resolver' +import { createViolationDetector } from './violation-detector' +import { createTransitiveAnalyzer } from './transitive-analyzer' +import { DEFAULT_ALLOWED_HOOKS } from './constants' +import type { Violation, ViolationType } from './violation-detector' +import type { ImportEdge } from './transitive-analyzer' +import type { ExtraRuleDocs } from '../../types' +import type { TSESTree } from '@typescript-eslint/utils' + +export const name = 'no-client-code-in-server-component' + +type MessageIds = + | 'hookInServerComponent' + | 'browserGlobalInServerComponent' + | 'eventHandlerInServerComponent' + | 'functionPropInServerComponent' + | 'classComponentInServerComponent' + +type _Options = [ + { + allowedServerHooks?: Array + }, +] + +const SLOT_HINT = + 'To use client functionality, either: (1) pass the client component as a prop/slot to the server component, or (2) move this code to a separate file and add "use client" directive.' + +const TRIGGER_HINT = 'Triggered by rendering "{{entry}}".' + +export const rule = ESLintUtils.RuleCreator(getDocsUrl)({ + name, + meta: { + type: 'problem', + docs: { + description: 'Disallow client-only code inside server components', + recommended: 'error', + }, + schema: [ + { + type: 'object', + properties: { + allowedServerHooks: { + type: 'array', + items: { type: 'string' }, + description: + 'Additional hooks that are allowed in server components (e.g., custom server-safe hooks)', + }, + }, + additionalProperties: false, + }, + ], + messages: { + hookInServerComponent: + '"{{name}}" hook {{location}} cannot be used in server components. ' + + TRIGGER_HINT + + ' ' + + SLOT_HINT, + browserGlobalInServerComponent: + '"{{name}}" browser API {{location}} is not available in server components. ' + + TRIGGER_HINT + + ' ' + + SLOT_HINT, + eventHandlerInServerComponent: + '"{{name}}" event handler {{location}} cannot be used in server components. ' + + TRIGGER_HINT + + ' ' + + SLOT_HINT, + functionPropInServerComponent: + '"{{name}}" function prop {{location}} cannot be passed in server components. ' + + 'Functions cannot be serialized from server to client. ' + + TRIGGER_HINT + + ' ' + + SLOT_HINT, + classComponentInServerComponent: + '"{{name}}" class component {{location}} cannot be used in server components. ' + + 'Class components require client-side lifecycle methods. ' + + TRIGGER_HINT + + ' ' + + SLOT_HINT, + }, + }, + defaultOptions: [{ allowedServerHooks: [] }] as const, + create(context, [options]) { + // Get TypeScript services + const services = ESLintUtils.getParserServices(context) + const program = services.program + const checker = program.getTypeChecker() + + // Build allowed hooks set from options + const allowedHooks = new Set([ + ...DEFAULT_ALLOWED_HOOKS, + ...options.allowedServerHooks, + ]) + + // Initialize analyzers + const useClientResolver = createUseClientResolver(program) + const violationDetector = createViolationDetector(ts, { + allowedHooks, + checker, + }) + const transitiveAnalyzer = createTransitiveAnalyzer( + ts, + program, + checker, + useClientResolver, + violationDetector, + ) + + return { + // Find server-component roots + CallExpression(node) { + // Skip client files + const sourceFile = services.esTreeNodeToTSNodeMap + .get(node) + .getSourceFile() + if (useClientResolver.hasUseClientDirective(sourceFile.fileName)) return + + const rootKind = getServerRootKind(node) + if (!rootKind) return + + if (rootKind === 'createCompositeComponent') { + const callback = node.arguments[0] + if (!callback) return + + const tsNode = services.esTreeNodeToTSNodeMap.get(callback) + + if (ts.isFunctionLike(tsNode)) { + analyzeServerComponentCallback( + tsNode as ts.FunctionLikeDeclaration, + node, + rootKind, + ) + } else if (ts.isIdentifier(tsNode)) { + analyzeDirectComponentReference(tsNode, node, rootKind) + } + + return + } + + const element = node.arguments[0] + if (!element) return + + const tsNode = services.esTreeNodeToTSNodeMap.get(element) + analyzeServerComponentNode(tsNode, node, rootKind) + return + }, + } + + function getServerRootKind( + node: TSESTree.CallExpression, + ): 'createCompositeComponent' | 'renderServerComponent' | null { + if (node.callee.type === 'Identifier') { + if (node.callee.name === 'createCompositeComponent') { + return 'createCompositeComponent' + } + if (node.callee.name === 'renderServerComponent') { + return 'renderServerComponent' + } + } + if ( + node.callee.type === 'MemberExpression' && + node.callee.property.type === 'Identifier' + ) { + if (node.callee.property.name === 'createCompositeComponent') { + return 'createCompositeComponent' + } + if (node.callee.property.name === 'renderServerComponent') { + return 'renderServerComponent' + } + } + return null + } + + function analyzeServerComponentNode( + node: ts.Node, + eslintNode: TSESTree.CallExpression, + rootKind: 'createCompositeComponent' | 'renderServerComponent', + ) { + // Track reported violations to avoid duplicates + const reportedViolations = new Set() + + const sourceFile = node.getSourceFile() + + // Detect violations in the whole arg node + const directViolations = violationDetector.detectViolations(sourceFile) + const start = node.getStart() + const end = node.getEnd() + + for (const violation of directViolations) { + const violationPos = violation.node.getStart() + if (violationPos >= start && violationPos <= end) { + const key = `${violation.fileName}:${violation.line}:${violation.name}` + if (!reportedViolations.has(key)) { + reportedViolations.add(key) + reportViolation(violation, [], rootKind, eslintNode) + } + } + } + + // Find all JSX component references in the node + const componentRefs = findComponentReferences(node) + + for (const ref of componentRefs) { + const symbol = checker.getSymbolAtLocation(ref) + if (!symbol) continue + + const resolvedSymbol = + ts.SymbolFlags.Alias & symbol.flags + ? checker.getAliasedSymbol(symbol) + : symbol + + const result = transitiveAnalyzer.analyzeEntrySymbol(resolvedSymbol) + + if (result.isClientBoundary) continue + + for (const violation of result.violations) { + const key = `${violation.fileName}:${violation.line}:${violation.name}` + if (!reportedViolations.has(key)) { + reportedViolations.add(key) + reportViolation(violation, violation.chain, rootKind, eslintNode) + } + } + } + } + + function analyzeServerComponentCallback( + callback: ts.FunctionLikeDeclaration, + eslintNode: TSESTree.CallExpression, + rootKind: 'createCompositeComponent' | 'renderServerComponent', + ) { + // Track reported violations to avoid duplicates + const reportedViolations = new Set() + + // Collect parameter names - these are "slots" passed from client, skip them + const parameterNames = new Set() + for (const param of callback.parameters) { + collectParameterBindings(param.name, parameterNames) + } + + // First, detect violations directly in the callback body + const body = callback.body + if (body) { + const sourceFile = callback.getSourceFile() + + // Check for violations in the callback itself + const directViolations = violationDetector.detectViolations(sourceFile) + + // Filter to only violations within the callback body + const callbackStart = body.getStart() + const callbackEnd = body.getEnd() + + for (const violation of directViolations) { + const violationPos = violation.node.getStart() + if (violationPos >= callbackStart && violationPos <= callbackEnd) { + const key = `${violation.fileName}:${violation.line}:${violation.name}` + if (!reportedViolations.has(key)) { + reportedViolations.add(key) + reportViolation(violation, [], rootKind, eslintNode) + } + } + } + } + + // Find all JSX component references in the callback + const componentRefs = findComponentReferences(callback) + + for (const ref of componentRefs) { + // Skip if this component name comes from a parameter (it's a client slot) + if (parameterNames.has(ref.text)) { + continue + } + + const symbol = checker.getSymbolAtLocation(ref) + if (!symbol) continue + + // Check if the symbol is declared in the callback parameters + // This handles destructured props like { ActionButton } + const declarations = symbol.getDeclarations() + if (declarations?.some((d) => isWithinParameters(d, callback))) { + continue // Skip - it's a prop/slot + } + + // Resolve alias if it's an import + const resolvedSymbol = + ts.SymbolFlags.Alias & symbol.flags + ? checker.getAliasedSymbol(symbol) + : symbol + + const result = transitiveAnalyzer.analyzeEntrySymbol(resolvedSymbol) + + if (result.isClientBoundary) continue // Has 'use client', skip + + // Report violations (deduplicated) + for (const violation of result.violations) { + const key = `${violation.fileName}:${violation.line}:${violation.name}` + if (!reportedViolations.has(key)) { + reportedViolations.add(key) + reportViolation(violation, violation.chain, rootKind, eslintNode) + } + } + } + } + + /** + * Analyze a component passed directly to createCompositeComponent(Component) + */ + + function analyzeDirectComponentReference( + ref: ts.Identifier, + eslintNode: TSESTree.CallExpression, + rootKind: + | 'createCompositeComponent' + | 'renderServerComponent' = 'createCompositeComponent', + ) { + const symbol = checker.getSymbolAtLocation(ref) + if (!symbol) return + + // Resolve alias if it's an import + const resolvedSymbol = + ts.SymbolFlags.Alias & symbol.flags + ? checker.getAliasedSymbol(symbol) + : symbol + + const result = transitiveAnalyzer.analyzeEntrySymbol(resolvedSymbol) + + if (result.isClientBoundary) return // Has 'use client', skip + + // Track reported violations to avoid duplicates + const reportedViolations = new Set() + + // Report violations (deduplicated) + for (const violation of result.violations) { + const key = `${violation.fileName}:${violation.line}:${violation.name}` + if (!reportedViolations.has(key)) { + reportedViolations.add(key) + reportViolation(violation, violation.chain, rootKind, eslintNode) + } + } + } + + /** + * Collect all binding names from a parameter (handles destructuring) + */ + function collectParameterBindings( + bindingName: ts.BindingName, + names: Set, + ): void { + function collectFromBinding(node: ts.BindingName): void { + if (ts.isIdentifier(node)) { + names.add(node.text) + } else if (ts.isObjectBindingPattern(node)) { + for (const element of node.elements) { + collectFromBinding(element.name) + } + } else if (ts.isArrayBindingPattern(node)) { + for (const element of node.elements) { + if (ts.isBindingElement(element)) { + collectFromBinding(element.name) + } + } + } + } + collectFromBinding(bindingName) + } + + /** + * Check if a declaration is within the parameters of the callback + */ + function isWithinParameters( + decl: ts.Declaration, + callback: ts.FunctionLikeDeclaration, + ): boolean { + // Walk up the parent chain to see if this declaration is within a parameter + let current: ts.Node | undefined = decl + while (current) { + if (ts.isParameter(current)) { + // Check if this parameter belongs to our callback + const paramParent = current.parent + if (ts.isFunctionLike(paramParent) && paramParent === callback) { + return true + } + } + current = current.parent as ts.Node | undefined + } + return false + } + + function findComponentReferences(node: ts.Node): Array { + const refs: Array = [] + + function visit(n: ts.Node) { + // JSX element: + if (ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n)) { + const tagName = n.tagName + // Only components (uppercase) not intrinsic elements (lowercase) + if (ts.isIdentifier(tagName) && /^[A-Z]/.test(tagName.text)) { + refs.push(tagName) + } + } + // Also check function calls that might return JSX + if (ts.isCallExpression(n)) { + const callee = n.expression + if (ts.isIdentifier(callee) && /^[A-Z]/.test(callee.text)) { + refs.push(callee) + } + } + ts.forEachChild(n, visit) + } + + ts.forEachChild(node, visit) + return refs + } + + function reportViolation( + violation: Violation, + chain: Array, + entryComponentName: string, + eslintNode: TSESTree.CallExpression, + ) { + const location = formatLocation(violation, chain) + const messageId = getMessageId(violation.type) + + context.report({ + node: eslintNode, + messageId, + data: { + name: violation.name, + location, + entry: entryComponentName, + fileName: getRelativePath(violation.fileName), + }, + }) + } + + function getMessageId(type: ViolationType): MessageIds { + switch (type) { + case 'hook': + return 'hookInServerComponent' + case 'browser-global': + return 'browserGlobalInServerComponent' + case 'event-handler': + return 'eventHandlerInServerComponent' + case 'function-prop': + return 'functionPropInServerComponent' + case 'class-component': + return 'classComponentInServerComponent' + } + } + + function formatLocation( + violation: Violation, + chain: Array, + ): string { + if (chain.length > 0) { + const chainStr = chain + .map((e) => getRelativePath(e.toFile)) + .join(' -> ') + return `(via ${chainStr}) at ${getRelativePath(violation.fileName)}:${violation.line}` + } + return `at ${getRelativePath(violation.fileName)}:${violation.line}` + } + + function getRelativePath(fileName: string): string { + const cwd = context.cwd + return path.relative(cwd, fileName) + } + }, +}) diff --git a/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/transitive-analyzer.ts b/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/transitive-analyzer.ts new file mode 100644 index 0000000000..7a349be6cd --- /dev/null +++ b/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/transitive-analyzer.ts @@ -0,0 +1,245 @@ +import type ts from 'typescript' +import type { UseClientResolver } from '../../shared/use-client-resolver' +import type { Violation, ViolationDetector } from './violation-detector' + +export interface ImportEdge { + fromFile: string + toFile: string + viaSymbol: string +} + +export interface TransitiveResult { + isClientBoundary: boolean + violations: Array }> +} + +export interface TransitiveAnalyzer { + /** + * Analyze an entry symbol and all reachable symbols for violations. + * Stops at 'use client' boundaries. + */ + analyzeEntrySymbol: (entrySymbol: ts.Symbol) => TransitiveResult +} + +/** + * Creates an analyzer that follows reachable symbol references + * to find transitive violations, stopping at 'use client' boundaries. + */ +export function createTransitiveAnalyzer( + tsLib: typeof ts, + program: ts.Program, + checker: ts.TypeChecker, + useClientResolver: UseClientResolver, + violationDetector: ViolationDetector, +): TransitiveAnalyzer { + const visitedSymbols = new Set() + const analysisCache = new Map() + + function symbolKey(symbol: ts.Symbol): string { + const decl = symbol.getDeclarations()?.[0] + return `${decl?.getSourceFile().fileName ?? 'unknown'}::${symbol.getName()}` + } + + function analyzeEntrySymbol(entrySymbol: ts.Symbol): TransitiveResult { + visitedSymbols.clear() + + const cached = analysisCache.get(symbolKey(entrySymbol)) + if (cached) return cached + + const violations: Array }> = [] + + function visitSymbol(symbol: ts.Symbol, chain: Array): boolean { + const key = symbolKey(symbol) + if (visitedSymbols.has(key)) return false + visitedSymbols.add(key) + + const decl = symbol.getDeclarations()?.[0] + if (!decl) return false + + const sourceFile = decl.getSourceFile() + const fileName = sourceFile.fileName + + // Skip node_modules and declaration files + if (fileName.includes('/node_modules/') || fileName.endsWith('.d.ts')) { + return false + } + + // Check for 'use client' boundary + if (useClientResolver.hasUseClientDirective(fileName)) { + return true // client boundary - stop here + } + + // Find the traversal root for this symbol + const traversalRoots = getTraversalRoots(decl) + + // Detect violations ONLY within the symbol's traversal roots, not the entire file + for (const root of traversalRoots) { + const rootViolations = violationDetector.detectViolationsInNode( + root, + sourceFile, + ) + for (const v of rootViolations) { + violations.push({ ...v, chain: [...chain] }) + } + } + + // Collect reachable identifiers from traversal roots + for (const root of traversalRoots) { + const identifiers = collectReachableIdentifiers(root, decl) + + for (const ident of identifiers) { + const refSym = checker.getSymbolAtLocation(ident) + if (!refSym) continue + + // Resolve alias if needed + const aliased = + tsLib.SymbolFlags.Alias & refSym.flags + ? checker.getAliasedSymbol(refSym) + : refSym + + const refDecl = aliased.getDeclarations()?.[0] + const refFile = refDecl?.getSourceFile().fileName + if (!refFile) continue + + // Skip libs / node_modules + if (refFile.includes('/node_modules/') || refFile.endsWith('.d.ts')) { + continue + } + + const edge: ImportEdge = { + fromFile: fileName, + toFile: refFile, + viaSymbol: aliased.getName(), + } + + visitSymbol(aliased, [...chain, edge]) + } + } + + return false + } + + /** + * Get traversal roots based on declaration kind + */ + function getTraversalRoots(decl: ts.Declaration): Array { + // FunctionDeclaration / FunctionExpression / ArrowFunction: its body + if (tsLib.isFunctionDeclaration(decl) && decl.body) { + return [decl.body] + } + if (tsLib.isFunctionExpression(decl)) { + return [decl.body] + } + if (tsLib.isArrowFunction(decl)) { + return [decl.body] + } + + // VariableDeclaration: check initializer + if (tsLib.isVariableDeclaration(decl) && decl.initializer) { + if ( + tsLib.isFunctionExpression(decl.initializer) || + tsLib.isArrowFunction(decl.initializer) + ) { + return [decl.initializer.body] + } + return [decl.initializer] + } + + // ClassDeclaration / ClassExpression: traverse methods + property initializers + if (tsLib.isClassDeclaration(decl) || tsLib.isClassExpression(decl)) { + const roots: Array = [] + for (const member of decl.members) { + if (tsLib.isMethodDeclaration(member) && member.body) { + roots.push(member.body) + } + if (tsLib.isPropertyDeclaration(member) && member.initializer) { + roots.push(member.initializer) + } + } + return roots + } + + // ExportSpecifier / ImportSpecifier: resolve aliased symbol handled by caller + // Fallback: traverse the declaration node itself + return [decl] + } + + /** + * Collect identifier nodes from a traversal root, skipping: + * - The defining identifier for the symbol (avoid self-loop) + * - Type-only positions + * - Property names when not computed + */ + function collectReachableIdentifiers( + root: ts.Node, + originalDecl: ts.Declaration, + ): Array { + const identifiers: Array = [] + + // Get the name of the original declaration to avoid self-reference + let declName: string | undefined + if ('name' in originalDecl && originalDecl.name) { + const nameNode = originalDecl.name as ts.Node + if (tsLib.isIdentifier(nameNode)) { + declName = nameNode.text + } + } + + function visit(node: ts.Node) { + // Skip type-only positions + if ( + tsLib.isTypeReferenceNode(node) || + tsLib.isInterfaceDeclaration(node) || + tsLib.isTypeAliasDeclaration(node) || + tsLib.isTypeQueryNode(node) || + tsLib.isTypeParameterDeclaration(node) + ) { + return // Don't descend into type nodes + } + + if (tsLib.isIdentifier(node)) { + const name = node.text + + // Skip the defining identifier + if (name === declName) return + + // Skip property names in property access (obj.prop -> prop is not a symbol ref) + const parent = node.parent + if ( + tsLib.isPropertyAccessExpression(parent) && + parent.name === node + ) { + return + } + + // Skip property names in object literals + if (tsLib.isPropertyAssignment(parent) && parent.name === node) { + return + } + + // Skip parameter names and variable declaration names + if ( + (tsLib.isParameter(parent) && parent.name === node) || + (tsLib.isVariableDeclaration(parent) && parent.name === node) + ) { + return + } + + identifiers.push(node) + } + + tsLib.forEachChild(node, visit) + } + + visit(root) + return identifiers + } + + const isClientBoundary = visitSymbol(entrySymbol, []) + const result: TransitiveResult = { isClientBoundary, violations } + analysisCache.set(symbolKey(entrySymbol), result) + return result + } + + return { analyzeEntrySymbol } +} diff --git a/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/violation-detector.ts b/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/violation-detector.ts new file mode 100644 index 0000000000..3457b7d3c1 --- /dev/null +++ b/packages/eslint-plugin-start/src/rules/no-client-code-in-server-component/violation-detector.ts @@ -0,0 +1,316 @@ +import { + BROWSER_ONLY_GLOBALS, + DEFAULT_ALLOWED_HOOKS, + isClientOnlyHook, + isReactEventHandler, +} from './constants' +import type ts from 'typescript' + +export type ViolationType = + | 'hook' + | 'browser-global' + | 'event-handler' + | 'function-prop' + | 'class-component' + +export interface Violation { + type: ViolationType + name: string + node: ts.Node + fileName: string + line: number + column: number +} + +export interface ViolationDetectorOptions { + allowedHooks?: Set + checker?: ts.TypeChecker +} + +export interface ViolationDetector { + /** + * Detect client-only code violations in a source file + */ + detectViolations: (sourceFile: ts.SourceFile) => Array + + /** + * Detect client-only code violations within a specific node subtree + */ + detectViolationsInNode: ( + node: ts.Node, + sourceFile: ts.SourceFile, + ) => Array +} + +/** + * Get line and column position for a node + */ +function getPosition( + node: ts.Node, + sourceFile: ts.SourceFile, +): { line: number; column: number } { + const { line, character } = sourceFile.getLineAndCharacterOfPosition( + node.getStart(), + ) + return { line: line + 1, column: character + 1 } +} + +/** + * Creates a detector that finds client-only code violations in TypeScript AST + */ +export function createViolationDetector( + tsLib: typeof ts, + options: ViolationDetectorOptions = {}, +): ViolationDetector { + const allowedHooks = options.allowedHooks ?? DEFAULT_ALLOWED_HOOKS + const checker = options.checker + + /** + * Check if a class declaration extends React.Component or React.PureComponent + */ + function isReactClassComponent(node: ts.ClassDeclaration): boolean { + if (!node.heritageClauses) return false + + for (const clause of node.heritageClauses) { + if (clause.token !== tsLib.SyntaxKind.ExtendsKeyword) continue + + for (const type of clause.types) { + const expr = type.expression + + // Check for React.Component or React.PureComponent + if (tsLib.isPropertyAccessExpression(expr)) { + const propName = expr.name.text + if (propName === 'Component' || propName === 'PureComponent') { + // Check if it's React.Component + if (tsLib.isIdentifier(expr.expression)) { + const objName = expr.expression.text + if (objName === 'React') { + return true + } + } + } + } + + // Check for direct Component or PureComponent import + if (tsLib.isIdentifier(expr)) { + const name = expr.text + if (name === 'Component' || name === 'PureComponent') { + return true + } + } + } + } + + return false + } + + /** + * Shared visitor logic that collects violations into the provided array + */ + function visitNode( + node: ts.Node, + sourceFile: ts.SourceFile, + violations: Array, + ) { + // 1. Detect React class components + if (tsLib.isClassDeclaration(node) && isReactClassComponent(node)) { + const name = node.name?.text ?? 'ClassComponent' + violations.push({ + type: 'class-component', + name, + node, + fileName: sourceFile.fileName, + ...getPosition(node, sourceFile), + }) + } + + // 2. Detect hook calls: useXxx() + if (tsLib.isCallExpression(node)) { + const callee = node.expression + let name = '' + + if (tsLib.isIdentifier(callee)) { + name = callee.text + } else if (tsLib.isPropertyAccessExpression(callee)) { + // React.useState() etc + name = callee.name.text + } + + if (name && isClientOnlyHook(name, allowedHooks)) { + violations.push({ + type: 'hook', + name, + node, + fileName: sourceFile.fileName, + ...getPosition(node, sourceFile), + }) + } + } + + // 3. Detect browser globals: window, document, etc. + if (tsLib.isIdentifier(node)) { + const name = node.text + if (BROWSER_ONLY_GLOBALS.has(name)) { + const parent = node.parent + + // Skip if this is the property name in a property access (obj.window is fine) + if (tsLib.isPropertyAccessExpression(parent) && parent.name === node) { + // This is a property access like obj.window - skip + } + // Skip if this is a property assignment key + else if (tsLib.isPropertyAssignment(parent) && parent.name === node) { + // This is { window: value } - skip + } + // Skip type-only positions + else if ( + tsLib.isTypeReferenceNode(parent) || + tsLib.isInterfaceDeclaration(parent) || + tsLib.isTypeAliasDeclaration(parent) + ) { + // Type position - skip + } + // Skip if this is a parameter name or variable declaration name + else if ( + (tsLib.isParameter(parent) && parent.name === node) || + (tsLib.isVariableDeclaration(parent) && parent.name === node) + ) { + // Declaration name - skip + } + // Skip if imported (the import itself is fine, usage is caught elsewhere) + else if ( + tsLib.isImportSpecifier(parent) || + tsLib.isImportClause(parent) + ) { + // Import - skip + } + // If we have a type checker, verify this is truly a global reference (no local binding) + else if (checker) { + const symbol = checker.getSymbolAtLocation(node) + if (symbol) { + const declarations = symbol.getDeclarations() + if (declarations?.length) { + // Check if ALL declarations are from lib files (global types) + // If any declaration is from a user file, it's a local variable + const isLocalDeclaration = declarations.some((decl) => { + const fileName = decl.getSourceFile().fileName + // User declarations are not from node_modules or lib files + return ( + !fileName.includes('/node_modules/') && + !fileName.includes('/typescript/lib/') + ) + }) + + if (isLocalDeclaration) { + // Has a local declaration - skip + } else { + // All declarations are from lib files - it's a global reference + violations.push({ + type: 'browser-global', + name, + node, + fileName: sourceFile.fileName, + ...getPosition(node, sourceFile), + }) + } + } else { + // No declarations found - treat as global + violations.push({ + type: 'browser-global', + name, + node, + fileName: sourceFile.fileName, + ...getPosition(node, sourceFile), + }) + } + } else { + // No symbol - assume global (conservative) + violations.push({ + type: 'browser-global', + name, + node, + fileName: sourceFile.fileName, + ...getPosition(node, sourceFile), + }) + } + } + // No type checker, fallback to AST-only check (may have false positives) + else { + violations.push({ + type: 'browser-global', + name, + node, + fileName: sourceFile.fileName, + ...getPosition(node, sourceFile), + }) + } + } + } + + // 4. Detect JSX attributes: event handlers AND function props + if (tsLib.isJsxAttribute(node)) { + const attrName = node.name + if (tsLib.isIdentifier(attrName)) { + const name = attrName.text + const value = node.initializer + + // Check if it's a React event handler (onClick, onChange, etc.) + if (isReactEventHandler(name)) { + violations.push({ + type: 'event-handler', + name, + node, + fileName: sourceFile.fileName, + ...getPosition(node, sourceFile), + }) + } + // Check if it's a function prop (not an event handler, not style/className) + // Skip common non-function props that might have complex expressions + else if ( + name !== 'style' && + name !== 'className' && + name !== 'key' && + name !== 'ref' && + name !== 'dangerouslySetInnerHTML' && + value && + tsLib.isJsxExpression(value) && + value.expression + ) { + const expr = value.expression + // Only flag actual function expressions, not objects or other values + if (tsLib.isArrowFunction(expr) || tsLib.isFunctionExpression(expr)) { + violations.push({ + type: 'function-prop', + name, + node, + fileName: sourceFile.fileName, + ...getPosition(node, sourceFile), + }) + } + } + } + } + + tsLib.forEachChild(node, (child) => + visitNode(child, sourceFile, violations), + ) + } + + function detectViolations(sourceFile: ts.SourceFile): Array { + const violations: Array = [] + tsLib.forEachChild(sourceFile, (child) => + visitNode(child, sourceFile, violations), + ) + return violations + } + + function detectViolationsInNode( + node: ts.Node, + sourceFile: ts.SourceFile, + ): Array { + const violations: Array = [] + visitNode(node, sourceFile, violations) + return violations + } + + return { detectViolations, detectViolationsInNode } +} diff --git a/packages/eslint-plugin-start/src/shared/use-client-resolver.ts b/packages/eslint-plugin-start/src/shared/use-client-resolver.ts new file mode 100644 index 0000000000..a80f9a0c77 --- /dev/null +++ b/packages/eslint-plugin-start/src/shared/use-client-resolver.ts @@ -0,0 +1,34 @@ +import * as ts from 'typescript' + +export interface UseClientResolver { + /** + * Check if a file has 'use client' directive at the top + */ + hasUseClientDirective: (fileName: string) => boolean +} + +/** + * Creates a resolver that checks for 'use client' directive in source files + */ +export function createUseClientResolver( + program: ts.Program, +): UseClientResolver { + function hasUseClientDirective(fileName: string): boolean { + const sourceFile = program.getSourceFile(fileName) + if (!sourceFile) return false + + const firstStmt = sourceFile.statements[0] + if (!firstStmt) return false + + if ( + ts.isExpressionStatement(firstStmt) && + ts.isStringLiteral(firstStmt.expression) + ) { + return firstStmt.expression.text === 'use client' + } + + return false + } + + return { hasUseClientDirective } +} diff --git a/packages/eslint-plugin-start/src/types.ts b/packages/eslint-plugin-start/src/types.ts new file mode 100644 index 0000000000..74c3053188 --- /dev/null +++ b/packages/eslint-plugin-start/src/types.ts @@ -0,0 +1,3 @@ +export type ExtraRuleDocs = { + recommended: 'strict' | 'error' | 'warn' +} diff --git a/packages/eslint-plugin-start/src/utils/get-docs-url.ts b/packages/eslint-plugin-start/src/utils/get-docs-url.ts new file mode 100644 index 0000000000..04579e47c8 --- /dev/null +++ b/packages/eslint-plugin-start/src/utils/get-docs-url.ts @@ -0,0 +1,2 @@ +export const getDocsUrl = (ruleName: string): string => + `https://tanstack.com/start/latest/docs/eslint/${ruleName}` diff --git a/packages/eslint-plugin-start/tsconfig.json b/packages/eslint-plugin-start/tsconfig.json new file mode 100644 index 0000000000..1715152a91 --- /dev/null +++ b/packages/eslint-plugin-start/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "moduleResolution": "Bundler", + "types": ["node"] + }, + "include": ["src", "eslint.config.js", "vite.config.ts"] +} diff --git a/packages/eslint-plugin-start/vite.config.ts b/packages/eslint-plugin-start/vite.config.ts new file mode 100644 index 0000000000..8769e2779e --- /dev/null +++ b/packages/eslint-plugin-start/vite.config.ts @@ -0,0 +1,23 @@ +import { defineConfig, mergeConfig } from 'vitest/config' +import { tanstackViteConfig } from '@tanstack/vite-config' +import packageJson from './package.json' + +const config = defineConfig({ + test: { + name: packageJson.name, + dir: './src', + watch: false, + globals: true, + typecheck: { enabled: true }, + restoreMocks: true, + }, +}) + +export default mergeConfig( + config, + tanstackViteConfig({ + entry: './src/index.ts', + srcDir: './src', + exclude: ['./src/__tests__'], + }), +) diff --git a/packages/history/AGENTS.md b/packages/history/AGENTS.md new file mode 100644 index 0000000000..509da6a4ec --- /dev/null +++ b/packages/history/AGENTS.md @@ -0,0 +1,3 @@ +# History + +Accepted browser push/replace operations update the in-memory location immediately and batch native writes into a microtask. Preserve coalescing: the latest href/state wins, but any queued push wins over replaces. Use `history.flush()` when native browser state must be current; verify subsequent updates still flush afterward in `tests/createBrowserHistory.test.ts`. diff --git a/packages/history/CHANGELOG.md b/packages/history/CHANGELOG.md new file mode 100644 index 0000000000..ca3341088c --- /dev/null +++ b/packages/history/CHANGELOG.md @@ -0,0 +1,77 @@ +# @tanstack/history + +## 1.162.5 + +### Patch Changes + +- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Drop a duplicated current-location flag and a redundant `createHref` wrapper. + +- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Avoid temporary arrays when reading hash-history locations. + +- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Keep a leading query or fragment out of the parsed pathname, so hash-history URLs like `/#?x=1` no longer repeat the query in the router location. + +- [#8602](https://github.com/TanStack/router/pull/8602) [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb) - Fixed Link destinations that resolve to a route mask are now reused across navigations instead of being rebuilt every time. A mounted Link now follows changes to its `href` and `reloadDocument` props, and React Links no longer each subscribe to a hydration flag. + +- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Use `slice` instead of `substring` where the bounds are always ordered and non-negative. + +## 1.162.4 + +### Patch Changes + +- [#8359](https://github.com/TanStack/router/pull/8359) [`8fff7fa`](https://github.com/TanStack/router/commit/8fff7fa1f2e6f061916b0bf5e0ec486b2e732f94) - Normalize memory history hrefs consistently with browser and server history, including protocol-relative paths and control characters. + +- [#8352](https://github.com/TanStack/router/pull/8352) [`f021f6d`](https://github.com/TanStack/router/commit/f021f6d1c6dce6c9b54d70766f1d636d8fd9e184) - Avoid temporary arrays when replacing forward memory-history entries. + +- [#8349](https://github.com/TanStack/router/pull/8349) [`ae68535`](https://github.com/TanStack/router/commit/ae68535929043607d4ee9438f8ae401f3a064862) - Avoid generating unused history keys for locations with existing state. + +- [#8354](https://github.com/TanStack/router/pull/8354) [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244) - Use lightweight request history for SSR and make server navigation a no-op. Use redirect() to issue HTTP redirects. Server hrefs use the same normalization as browser history to handle protocol-relative URLs and control characters. + +## 1.162.3 + +### Patch Changes + +- [#8308](https://github.com/TanStack/router/pull/8308) [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8) - Validate navigation and redirect destinations, keep ambiguous relative URLs on the current origin, and constrain prerender requests and output paths. Prevent redirect headers from appearing in serialized server function response bodies. + + Preserve native form HTTP redirects, route error handling and masks for document redirects, and per-navigation destinations for shared loader redirects. Avoid redundant origin parsing and reduce link styling and server-rendering work. Configured origins must already be normalized. + + Keep blocked-link inactive props consistent during React hydration, honor explicit redirect Location headers before checking route options, and refresh Vue link state when destinations become internal. Reuse the protocol-relative URL check while parsing redirect schemes once. + + Reduce React link bundle size by sharing pathname comparisons, state-prop selection, and element creation. + + Share normalized pathname comparisons in Solid and Vue links to reduce bundle size. + +- [#8287](https://github.com/TanStack/router/pull/8287) [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9) - Use full-document navigation when an output rewrite produces a cross-origin destination, including the public URL of a route mask. + + Respect registered history blockers during document navigation, passing history locations and the requested push or replace action. + +## 1.162.2 + +### Patch Changes + +- [#8264](https://github.com/TanStack/router/pull/8264) [`9035abc`](https://github.com/TanStack/router/commit/9035abc41163d83409ef582f7743a3c7be57dd93) - Respect `ignoreBlocker` during `go()` navigation, including document unload warnings. Preserve beforeunload warnings during back and forward navigation unless `ignoreBlocker` is requested, and clear the bypass after same-document traversal so later document navigation still warns about unsaved changes. + + Restore the original browser history entry when forward or multi-entry navigation is blocked. + +## 1.162.1 + +### Patch Changes + +- [#7985](https://github.com/TanStack/router/pull/7985) [`9cac62a`](https://github.com/TanStack/router/commit/9cac62a5c7f99ef070991ea6f1fa7e42c746d46b) - perf: compact private bundle boundaries- [#7975](https://github.com/TanStack/router/issues/7975) + +## 1.162.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +## 1.161.6 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +## 1.161.5 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) diff --git a/packages/history/package.json b/packages/history/package.json index 63d62a783c..d09c710d2f 100644 --- a/packages/history/package.json +++ b/packages/history/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/history", - "version": "1.141.0", + "version": "1.162.5", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -22,12 +22,12 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch", @@ -56,6 +56,15 @@ "src" ], "engines": { - "node": ">=12" + "node": ">=20.19" + }, + "devDependencies": { + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" } } diff --git a/packages/history/src/index.ts b/packages/history/src/index.ts index 5efa47ea38..d2f80581b9 100644 --- a/packages/history/src/index.ts +++ b/packages/history/src/index.ts @@ -36,7 +36,9 @@ export interface RouterHistory { flush: () => void destroy: () => void notify: (action: SubscriberHistoryAction) => void + _getBlockers: () => Array _ignoreSubscribers?: boolean + _ignoreNextBeforeUnload?: (href: string) => void } export interface HistoryLocation extends ParsedPath { @@ -96,12 +98,40 @@ const stateIndexKey = '__TSR_index' const popStateEvent = 'popstate' const beforeUnloadEvent = 'beforeunload' +/** + * Turn protocol-relative inputs such as "//evil.example" into paths + * such as "/evil.example", keeping navigation on the current origin. + * + * For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces, + * removes tabs/newlines, and treats backslashes as slashes, so inputs like + * "/\evil.example" also need normalization. This only allocates when those + * rules would make the input protocol-relative. + */ +// eslint-disable-next-line no-control-regex +const protocolRelativePrefix = /^[\x00-\x20]*(?:[\\/][\t\n\r]*){2,}/ + +export function normalizeProtocolRelative(url: string): string { + const match = protocolRelativePrefix.exec(url) + return match ? '/' + url.slice(match[0].length) : url +} + +function normalizeHref(href: string): string { + // eslint-disable-next-line no-control-regex + if (/[\x00-\x1f\x7f]/.test(href)) { + // eslint-disable-next-line no-control-regex + href = href.replace(/[\x00-\x1f\x7f]/g, (character) => + '\t\n\r'.includes(character) ? '' : encodeURIComponent(character), + ) + } + return normalizeProtocolRelative(href) +} + export function createHistory(opts: { getLocation: () => HistoryLocation getLength: () => number pushState: (path: string, state: any) => void replaceState: (path: string, state: any) => void - go: (n: number) => void + go: (n: number, ignoreBlocker: boolean) => void back: (ignoreBlocker: boolean) => void forward: (ignoreBlocker: boolean) => void createHref: (path: string) => string @@ -126,27 +156,21 @@ export function createHistory(opts: { else location = opts.getLocation() } - const tryNavigation = async ({ - task, - navigateOpts, - ...actionInfo - }: TryNavigateArgs) => { - const ignoreBlocker = navigateOpts?.ignoreBlocker ?? false - if (ignoreBlocker) { - task() - return - } - - const blockers = opts.getBlockers?.() ?? [] - const isPushOrReplace = - actionInfo.type === 'PUSH' || actionInfo.type === 'REPLACE' - if (typeof document !== 'undefined' && blockers.length && isPushOrReplace) { + const tryNavigation = async (args: TryNavigateArgs) => { + const blockers = args.navigateOpts?.ignoreBlocker + ? undefined + : opts.getBlockers?.() + if ( + typeof document !== 'undefined' && + blockers?.length && + (args.type === 'PUSH' || args.type === 'REPLACE') + ) { for (const blocker of blockers) { - const nextLocation = parseHref(actionInfo.path, actionInfo.state) + const nextLocation = parseHref(args.path, args.state) const isBlocked = await blocker.blockerFn({ currentLocation: location, nextLocation, - action: actionInfo.type, + action: args.type, }) if (isBlocked) { opts.onBlocked?.() @@ -155,7 +179,7 @@ export function createHistory(opts: { } } - task() + args.task() } return { @@ -204,7 +228,7 @@ export function createHistory(opts: { go: (index, navigateOpts) => { tryNavigation({ task: () => { - opts.go(index) + opts.go(index, navigateOpts?.ignoreBlocker ?? false) handleIndexChange({ type: 'GO', index }) }, navigateOpts, @@ -246,13 +270,11 @@ export function createHistory(opts: { flush: () => opts.flush?.(), destroy: () => opts.destroy?.(), notify, + _getBlockers: () => opts.getBlockers?.() ?? [], } } function assignKeyAndIndex(index: number, state: HistoryState | undefined) { - if (!state) { - state = {} as HistoryState - } const key = createRandomKey() return { ...state, @@ -295,7 +317,8 @@ export function createBrowserHistory(opts?: { const _setBlockers = (newBlockers: Array) => (blockers = newBlockers) - const createHref = opts?.createHref ?? ((path) => path) + const createHref = (path: string) => + normalizeHref(opts?.createHref ? opts.createHref(path) : path) const parseLocation = opts?.parseLocation ?? (() => @@ -322,6 +345,9 @@ export function createBrowserHistory(opts?: { let nextPopIsGo = false let ignoreNextPop = false + // TODO: An ignored traversal past a history boundary emits neither popstate + // nor beforeunload, leaving these bypasses active for a later navigation. + // The History API provides no completion signal for such no-op traversals. let skipBlockerNextPop = false let ignoreNextBeforeUnload = false @@ -329,18 +355,14 @@ export function createBrowserHistory(opts?: { let next: | undefined - | { - // This is the latest location that we were attempting to push/replace - href: string - // This is the latest state that we were attempting to push/replace - state: any - // This is the latest type that we were attempting to push/replace - isPush: boolean - } - - // We need to track the current scheduled update to prevent - // multiple updates from being scheduled at the same time. - let scheduled: Promise | undefined + | [ + // The latest location that we were attempting to push/replace + href: string, + // The latest state that we were attempting to push/replace + state: any, + // Whether any queued update needs to push rather than replace + isPush: boolean, + ] // This function flushes the next update to the browser history const flush = () => { @@ -352,46 +374,48 @@ export function createBrowserHistory(opts?: { history._ignoreSubscribers = true // Update the browser history - ;(next.isPush ? win.history.pushState : win.history.replaceState)( - next.state, + ;(next[2 /* is push */] ? win.history.pushState : win.history.replaceState)( + next[1 /* state */], '', - next.href, + next[0 /* href */], ) // Stop ignoring subscriber updates history._ignoreSubscribers = false - // Reset the nextIsPush flag and clear the scheduled update + // Clear the queued action after it reaches browser history. next = undefined - scheduled = undefined rollbackLocation = undefined } // This function queues up a call to update the browser history const queueHistoryAction = ( - type: 'push' | 'replace', + isPush: boolean, destHref: string, state: any, ) => { - const href = createHref(destHref) + // A formatter changes the URL space and must receive the original input. + // Otherwise parseHref below already produces the browser destination. + const href = opts?.createHref ? createHref(destHref) : undefined + const hasPendingAction = !!next - if (!scheduled) { + if (!hasPendingAction) { rollbackLocation = currentLocation } - // Update the location in memory + // Keep the optimistic location in the router's logical URL space. currentLocation = parseHref(destHref, state) // Keep track of the next location we need to flush to the URL - next = { - href, + next = [ + href ?? currentLocation.href, state, - isPush: next?.isPush || type === 'push', - } + next?.[2 /* is push */] || isPush, + ] - if (!scheduled) { + if (!hasPendingAction) { // Schedule an update to the browser history - scheduled = Promise.resolve().then(() => flush()) + queueMicrotask(() => flush()) } } @@ -402,6 +426,10 @@ export function createBrowserHistory(opts?: { } const onPushPopEvent = async () => { + // Same-document traversals do not fire beforeunload, so consume their + // exemption here instead of carrying it into a later document navigation. + ignoreNextBeforeUnload = false + if (ignoreNextPop) { ignoreNextPop = false return @@ -438,7 +466,7 @@ export function createBrowserHistory(opts?: { }) if (isBlocked) { ignoreNextPop = true - win.history.go(1) + win.history.go(-delta) history.notify(notify) return } @@ -488,23 +516,31 @@ export function createBrowserHistory(opts?: { const history = createHistory({ getLocation, getLength: () => win.history.length, - pushState: (href, state) => queueHistoryAction('push', href, state), - replaceState: (href, state) => queueHistoryAction('replace', href, state), + pushState: (href, state) => queueHistoryAction(true, href, state), + replaceState: (href, state) => queueHistoryAction(false, href, state), back: (ignoreBlocker) => { - if (ignoreBlocker) skipBlockerNextPop = true - ignoreNextBeforeUnload = true + if (ignoreBlocker) { + skipBlockerNextPop = true + ignoreNextBeforeUnload = true + } return win.history.back() }, forward: (ignoreBlocker) => { - if (ignoreBlocker) skipBlockerNextPop = true - ignoreNextBeforeUnload = true + if (ignoreBlocker) { + skipBlockerNextPop = true + ignoreNextBeforeUnload = true + } win.history.forward() }, - go: (n) => { + go: (n, ignoreBlocker) => { nextPopIsGo = true + if (ignoreBlocker) { + skipBlockerNextPop = true + ignoreNextBeforeUnload = true + } win.history.go(n) }, - createHref: (href) => createHref(href), + createHref, flush, destroy: () => { win.history.pushState = originalPushState @@ -526,6 +562,21 @@ export function createBrowserHistory(opts?: { notifyOnIndexChange: false, }) + history._ignoreNextBeforeUnload = (href) => { + ignoreNextBeforeUnload = false + try { + href = new URL(href, win.document.baseURI).href + // External handlers and same-document fragments may emit neither + // beforeunload nor popstate, leaving an exemption for a later departure. + ignoreNextBeforeUnload = + /^https?:/.test(href) && + (!href.includes('#') || + href.split('#')[0] !== win.location.href.split('#')[0]) + } catch { + // Invalid URLs cannot unload the document. + } + } + win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true }) win.addEventListener(popStateEvent, onPushPopEvent) @@ -556,14 +607,17 @@ export function createHashHistory(opts?: { window?: any }): RouterHistory { return createBrowserHistory({ window: win, parseLocation: () => { - const hashSplit = win.location.hash.split('#').slice(1) - const pathPart = hashSplit[0] ?? '/' - const searchPart = win.location.search - const hashEntries = hashSplit.slice(1) - const hashPart = - hashEntries.length === 0 ? '' : `#${hashEntries.join('#')}` - const hashHref = `${pathPart}${searchPart}${hashPart}` - return parseHref(hashHref, win.history.state) + // `#/path?query#fragment`: the router's own fragment starts at the + // second '#'. A non-empty `location.hash` always starts with '#'. + const hash = win.location.hash + let hashIndex = hash.indexOf('#', 1) + if (hashIndex < 0) { + hashIndex = hash.length + } + return parseHref( + `${hash ? hash.slice(1, hashIndex) : '/'}${win.location.search}${hash.slice(hashIndex)}`, + win.history.state, + ) }, createHref: (href) => `${win.location.pathname}${win.location.search}#${href}`, @@ -593,18 +647,23 @@ export function createMemoryHistory( const getLocation = () => parseHref(entries[index]!, states[index]) + let blockers: Array = [] + const _getBlockers = () => blockers + const _setBlockers = (newBlockers: Array) => + (blockers = newBlockers) + return createHistory({ getLocation, getLength: () => entries.length, pushState: (path, state) => { // Removes all subsequent entries after the current index to start a new branch + index = index < entries.length - 1 ? index + 1 : entries.length + states[index] = state + entries[index] = path if (index < entries.length - 1) { - entries.splice(index + 1) - states.splice(index + 1) + entries.length = index + 1 + states.length = index + 1 } - states.push(state) - entries.push(path) - index = Math.max(entries.length - 1, 0) }, replaceState: (path, state) => { states[index] = state @@ -619,41 +678,101 @@ export function createMemoryHistory( go: (n) => { index = Math.min(Math.max(index + n, 0), entries.length - 1) }, - createHref: (path) => path, + createHref: normalizeHref, + getBlockers: _getBlockers, + setBlockers: _setBlockers, }) } +const noop = () => {} + +class ServerHistory implements RouterHistory { + declare private _subscribers?: RouterHistory['subscribers'] + + constructor(public location: HistoryLocation) {} + + get length() { + return 1 + } + + // Preserve the history interface without allocating a Set for each request. + get subscribers() { + return (this._subscribers ??= new Set()) + } + + subscribe() { + return noop + } + + push() {} + replace() {} + go() {} + back() {} + forward() {} + + canGoBack() { + return false + } + + createHref(href: string) { + return normalizeHref(href) + } + + block() { + return noop + } + + flush() {} + destroy() {} + notify() {} + + _getBlockers(): Array { + return [] + } +} + +/** A fixed request location; server navigation is a no-op. */ +export function createServerHistory(href: string): RouterHistory { + return new ServerHistory(parseHref(href, undefined)) +} + export function parseHref( href: string, state: ParsedHistoryState | undefined, ): HistoryLocation { - const hashIndex = href.indexOf('#') - const searchIndex = href.indexOf('?') - - const addedKey = createRandomKey() + const sanitizedHref = normalizeHref(href) + const hashIndex = sanitizedHref.indexOf('#') + const searchIndex = sanitizedHref.indexOf('?') + if (!state) { + const key = createRandomKey() + state = { [stateIndexKey]: 0, key, __TSR_key: key } + } return { - href, - pathname: href.substring( + href: sanitizedHref, + pathname: sanitizedHref.slice( 0, - hashIndex > 0 - ? searchIndex > 0 + hashIndex > -1 + ? searchIndex > -1 ? Math.min(hashIndex, searchIndex) : hashIndex - : searchIndex > 0 + : searchIndex > -1 ? searchIndex - : href.length, + : sanitizedHref.length, ), - hash: hashIndex > -1 ? href.substring(hashIndex) : '', + hash: hashIndex > -1 ? sanitizedHref.slice(hashIndex) : '', search: searchIndex > -1 - ? href.slice(searchIndex, hashIndex === -1 ? undefined : hashIndex) + ? sanitizedHref.slice( + searchIndex, + hashIndex === -1 ? undefined : hashIndex, + ) : '', - state: state || { [stateIndexKey]: 0, key: addedKey, __TSR_key: addedKey }, + state, } } // Thanks co-pilot! function createRandomKey() { - return (Math.random() + 1).toString(36).substring(7) + return (Math.random() + 1).toString(36).slice(7) } diff --git a/packages/history/tests/createBrowserHistory.test.ts b/packages/history/tests/createBrowserHistory.test.ts new file mode 100644 index 0000000000..5b24744fb5 --- /dev/null +++ b/packages/history/tests/createBrowserHistory.test.ts @@ -0,0 +1,307 @@ +import { describe, expect, test, vi } from 'vitest' +import { createBrowserHistory } from '../src' + +function createBrowserHistoryHarness(createHref?: (path: string) => string) { + const listeners = new Map any>() + const location = { + pathname: '/', + search: '', + hash: '', + } + const pushState = vi.fn() + const replaceState = vi.fn() + const nativeHistory = { + state: { __TSR_index: 0, __TSR_key: 'initial' }, + length: 1, + pushState, + replaceState, + back: vi.fn(), + forward: vi.fn(), + go: vi.fn(), + } + const window = { + location, + history: nativeHistory, + addEventListener: vi.fn((type: string, listener: (event: any) => any) => { + listeners.set(type, listener) + }), + removeEventListener: vi.fn((type: string) => { + listeners.delete(type) + }), + dispatchEvent: (event: { type: string }) => + listeners.get(event.type)?.(event), + } + const history = createBrowserHistory({ window, createHref }) + + return { + history, + pushState, + replaceState, + window, + } +} + +describe('createBrowserHistory', () => { + test('passes the original destination to a custom formatter', () => { + const { history, pushState } = createBrowserHistoryHarness( + (href) => '/mapped?value=' + encodeURIComponent(href), + ) + history.push('/a\tb') + history.flush() + expect(pushState).toHaveBeenCalledWith( + expect.anything(), + '', + '/mapped?value=%2Fa%09b', + ) + expect(history.location.href).toBe('/ab') + history.destroy() + }) + + test.each(['/a\x00b?q=a\x01b#/\\section\x7f', '/a\tb?q=a\nb#/\\section\r'])( + 'preserves the browser interpretation of %j', + (href) => { + const originalHref = window.location.href + const expected = new URL(href, originalHref) + const history = createBrowserHistory() + try { + expect(new URL(history.createHref(href), originalHref).href).toBe( + expected.href, + ) + history.push(href) + history.flush() + expect(window.location.href).toBe(expected.href) + expect(new URL(history.location.href, originalHref).href).toBe( + expected.href, + ) + } finally { + history.destroy() + window.history.replaceState(null, '', originalHref) + } + }, + ) + + test('coalesces consecutive replaces into the latest replace', async () => { + const { history, pushState, replaceState } = createBrowserHistoryHarness() + + history.replace('/first', { value: 1 }) + history.replace('/second', { value: 2 }) + await Promise.resolve() + + expect(pushState).not.toHaveBeenCalled() + expect(replaceState).toHaveBeenCalledTimes(1) + expect(replaceState).toHaveBeenCalledWith( + expect.objectContaining({ value: 2 }), + '', + '/second', + ) + history.destroy() + }) + + test('promotes a queued replace to a push', async () => { + const { history, pushState, replaceState } = createBrowserHistoryHarness() + + history.replace('/first', { value: 1 }) + history.push('/second', { value: 2 }) + await Promise.resolve() + + expect(replaceState).not.toHaveBeenCalled() + expect(pushState).toHaveBeenCalledTimes(1) + expect(pushState).toHaveBeenCalledWith( + expect.objectContaining({ value: 2 }), + '', + '/second', + ) + history.destroy() + }) + + test('keeps a queued push when followed by a replace', async () => { + const { history, pushState, replaceState } = createBrowserHistoryHarness() + + history.push('/first', { value: 1 }) + history.replace('/second', { value: 2 }) + await Promise.resolve() + + expect(replaceState).not.toHaveBeenCalled() + expect(pushState).toHaveBeenCalledTimes(1) + expect(pushState).toHaveBeenCalledWith( + expect.objectContaining({ value: 2 }), + '', + '/second', + ) + history.destroy() + }) + + test('flushes a later action after an explicit flush', async () => { + const { history, pushState, replaceState } = createBrowserHistoryHarness() + + history.replace('/first', { value: 1 }) + history.flush() + await Promise.resolve() + history.replace('/second', { value: 2 }) + await Promise.resolve() + + expect(pushState).not.toHaveBeenCalled() + expect(replaceState).toHaveBeenCalledTimes(2) + expect(replaceState).toHaveBeenLastCalledWith( + expect.objectContaining({ value: 2 }), + '', + '/second', + ) + history.destroy() + }) + + test.each([ + '//evil.com/path', + '///evil.com/path', + '/\\evil.com/path', + '/\\\\evil.com/path', + '/\\/evil.com/path', + '\\/evil.com/path', + '\\\\evil.com/path', + ' /\\evil.com/path', + '\x01//evil.com/path', + '/\t/evil.com/path', + ])('sanitizes %j before calling the native History API', async (href) => { + const { history, pushState } = createBrowserHistoryHarness() + + history.push(href) + await Promise.resolve() + + expect(pushState).toHaveBeenCalledOnce() + const pushedHref = pushState.mock.calls[0]![2] + const serializedUrl = new URL(pushedHref, 'https://victim.example') + expect(serializedUrl.origin).toBe('https://victim.example') + expect(serializedUrl.pathname).toBe( + href === '\x01//evil.com/path' ? '/%01//evil.com/path' : '/evil.com/path', + ) + expect( + new URL(history.location.href, 'https://victim.example').origin, + ).toBe('https://victim.example') + history.destroy() + }) + + test('does not exempt a normal traversal from beforeunload blockers', () => { + const { history, window } = createBrowserHistoryHarness() + history.block({ blockerFn: vi.fn(), enableBeforeUnload: true }) + + history.back() + const event = { + type: 'beforeunload', + preventDefault: vi.fn(), + returnValue: undefined, + } + window.dispatchEvent(event) + + expect(event.preventDefault).toHaveBeenCalledOnce() + expect(event.returnValue).toBe('') + history.destroy() + }) + + test('exempts an ignored document traversal from beforeunload blockers', () => { + const { history, window } = createBrowserHistoryHarness() + history.block({ blockerFn: vi.fn(), enableBeforeUnload: true }) + + history.back({ ignoreBlocker: true }) + const event = { + type: 'beforeunload', + preventDefault: vi.fn(), + returnValue: undefined, + } + window.dispatchEvent(event) + + expect(event.preventDefault).not.toHaveBeenCalled() + expect(event.returnValue).toBeUndefined() + history.destroy() + }) + + test('passes the logical requested destination to blockers', async () => { + const { history } = createBrowserHistoryHarness( + () => '/mapped/../browser-destination', + ) + const blockerFn = vi.fn(() => true) + history.block({ blockerFn, enableBeforeUnload: false }) + + history.push('/logical/../destination?query=value#hash') + await Promise.resolve() + + expect(blockerFn).toHaveBeenCalledWith( + expect.objectContaining({ + action: 'PUSH', + nextLocation: expect.objectContaining({ + href: '/logical/../destination?query=value#hash', + pathname: '/logical/../destination', + search: '?query=value', + hash: '#hash', + }), + }), + ) + history.destroy() + }) + + test('normalizes the final result of a custom createHref', async () => { + const { history, pushState, replaceState } = createBrowserHistoryHarness( + () => ' \t/\\evil.example/path', + ) + + expect(history.createHref('/safe')).toBe('/evil.example/path') + + history.push('/safe') + await Promise.resolve() + history.replace('/safe') + await Promise.resolve() + + expect(pushState).toHaveBeenCalledWith( + expect.anything(), + '', + '/evil.example/path', + ) + expect(replaceState).toHaveBeenCalledWith( + expect.anything(), + '', + '/evil.example/path', + ) + expect(history.location.href).toBe('/safe') + history.destroy() + }) + + test('keeps the optimistic location in the logical URL space', async () => { + const { history, pushState } = createBrowserHistoryHarness( + () => '/mapped/../browser-destination', + ) + + history.push('/logical/../destination?query=value#hash') + await Promise.resolve() + + expect(history.location).toMatchObject({ + href: '/logical/../destination?query=value#hash', + pathname: '/logical/../destination', + search: '?query=value', + hash: '#hash', + }) + expect(pushState).toHaveBeenCalledWith( + expect.anything(), + '', + '/mapped/../browser-destination', + ) + history.destroy() + }) + + test('does not retain a beforeunload exemption after a same-document traversal', async () => { + const { history, window } = createBrowserHistoryHarness() + history.block({ blockerFn: vi.fn(), enableBeforeUnload: true }) + + history.back({ ignoreBlocker: true }) + await window.dispatchEvent({ type: 'popstate' }) + + const event = { + type: 'beforeunload', + preventDefault: vi.fn(), + returnValue: undefined, + } + window.dispatchEvent(event) + + expect(event.preventDefault).toHaveBeenCalledOnce() + expect(event.returnValue).toBe('') + history.destroy() + }) +}) diff --git a/packages/history/tests/createHashHistory.test.ts b/packages/history/tests/createHashHistory.test.ts index 4d68238249..e54b1a1ae1 100644 --- a/packages/history/tests/createHashHistory.test.ts +++ b/packages/history/tests/createHashHistory.test.ts @@ -1,8 +1,162 @@ -import { describe, expect, test } from 'vitest' +import { describe, expect, test, vi } from 'vitest' import { createHashHistory } from '../src' describe('createHashHistory', () => { + test.each(['\x00/route', '/route\x01', '/route?q=a\x1fb#c\x7fd'])( + 'keeps logical control data stable after reading the browser URL again: %j', + (href) => { + const originalHref = window.location.href + window.history.replaceState(null, '', '/shell') + const history = createHashHistory() + let reloaded: ReturnType | undefined + try { + history.push(href) + history.flush() + const location = history.location + history.destroy() + reloaded = createHashHistory() + expect(reloaded.location).toEqual(location) + } finally { + history.destroy() + reloaded?.destroy() + window.history.replaceState(null, '', originalHref) + } + }, + ) + + test('reads a hash route that starts with a query without leaking it into the pathname', () => { + const window = { + location: { pathname: '/', search: '', hash: '#?x=1' }, + history: { + state: { __TSR_index: 0, __TSR_key: 'initial' }, + length: 1, + pushState: vi.fn(), + replaceState: vi.fn(), + back: vi.fn(), + forward: vi.fn(), + go: vi.fn(), + }, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + } + const history = createHashHistory({ window }) + + expect(history.location).toMatchObject({ + href: '?x=1', + pathname: '', + search: '?x=1', + hash: '', + }) + history.destroy() + }) + + test('normalizes the final browser href without changing the logical hash location', async () => { + const pushState = vi.fn() + const window = { + location: { + pathname: '//nested/path', + search: '', + hash: '', + }, + history: { + state: { __TSR_index: 0, __TSR_key: 'initial' }, + length: 1, + pushState, + replaceState: vi.fn(), + back: vi.fn(), + forward: vi.fn(), + go: vi.fn(), + }, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + } + const history = createHashHistory({ window }) + + history.push('/logical') + await Promise.resolve() + + expect(pushState).toHaveBeenCalledWith( + expect.anything(), + '', + '/nested/path#/logical', + ) + expect(history.location.href).toBe('/logical') + history.destroy() + }) + + test.each([ + [ + '/?shell=1#/hello#section#tail', + { + href: '/hello?shell=1#section#tail', + pathname: '/hello', + search: '?shell=1', + hash: '#section#tail', + }, + ], + [ + '/?shell=1#/hello?route=2#section', + { + href: '/hello?route=2?shell=1#section', + pathname: '/hello', + search: '?route=2?shell=1', + hash: '#section', + }, + ], + [ + '/#/hello##tail#', + { + href: '/hello##tail#', + pathname: '/hello', + search: '', + hash: '##tail#', + }, + ], + [ + '/#/hello%23nested?value=%23#anchor%23tail', + { + href: '/hello%23nested?value=%23#anchor%23tail', + pathname: '/hello%23nested', + search: '?value=%23', + hash: '#anchor%23tail', + }, + ], + [ + '/?shell=1#//evil.example/path#fragment', + { + href: '/evil.example/path?shell=1#fragment', + pathname: '/evil.example/path', + search: '?shell=1', + hash: '#fragment', + }, + ], + [ + '/?shell=1#', + { + href: '/?shell=1', + pathname: '/', + search: '?shell=1', + hash: '', + }, + ], + ])('preserves the logical URL when reading %s', (href, expected) => { + const originalHref = window.location.href + const originalState = window.history.state + window.history.replaceState(null, '', href) + const history = createHashHistory() + + try { + expect(history.location).toMatchObject(expected) + window.history.replaceState(window.history.state, '', '/shell') + window.history.pushState(window.history.state, '', href) + expect(history.location).toMatchObject(expected) + } finally { + history.destroy() + window.history.replaceState(originalState, '', originalHref) + } + }) + describe('parseLocation', () => { describe.each([ ['/', { pathname: '/', search: '' }, 'neither search params nor hash'], diff --git a/packages/history/tests/createMemoryHistory.test.ts b/packages/history/tests/createMemoryHistory.test.ts index caddb96ac0..c0f565115e 100644 --- a/packages/history/tests/createMemoryHistory.test.ts +++ b/packages/history/tests/createMemoryHistory.test.ts @@ -1,7 +1,54 @@ -import { describe, expect, test } from 'vitest' +import { describe, expect, test, vi } from 'vitest' import { createMemoryHistory } from '../src' describe('createMemoryHistory', () => { + test.each([ + ['//example.com/path', '/example.com/path'], + ['/\\example.com/path', '/example.com/path'], + ['\\/example.com/path', '/example.com/path'], + ['\\\\example.com/path', '/example.com/path'], + [' \t/\r\\example.com/path', '/example.com/path'], + ['/\t/example.com/path', '/example.com/path'], + ['/a\tb?q=a\nb#section\r', '/ab?q=ab#section'], + ['/a\u0000b?q=a\u0001b#section\u007f', '/a%00b?q=a%01b#section%7F'], + ['/', '/'], + ['/posts/123?sort=new#comments', '/posts/123?sort=new#comments'], + ['/caf%C3%A9?q=%2F#//section', '/caf%C3%A9?q=%2F#//section'], + ['/a//b?q=//value#\\/section', '/a//b?q=//value#\\/section'], + ['/%2Fexample.com/path', '/%2Fexample.com/path'], + ])('creates href %j consistent with navigation', (href, expected) => { + const history = createMemoryHistory() + const location = history.location + const createdHref = history.createHref(href) + + expect(createdHref).toBe(expected) + expect(history.location).toBe(location) + expect(new URL(createdHref, 'https://app.example').origin).toBe( + 'https://app.example', + ) + + history.push(href) + expect(history.location.href).toBe(createdHref) + }) + + test('exposes the current blocker registry after registration and removal', () => { + const history = createMemoryHistory() + const first = { blockerFn: vi.fn(() => true) } + const second = { blockerFn: vi.fn(() => false) } + + expect(history._getBlockers()).toEqual([]) + + const removeFirst = history.block(first) + const removeSecond = history.block(second) + expect(history._getBlockers()).toEqual([first, second]) + + removeFirst() + expect(history._getBlockers()).toEqual([second]) + + removeSecond() + expect(history._getBlockers()).toEqual([]) + }) + test('back', () => { const initialEntry = '/initial' const history = createMemoryHistory({ initialEntries: [initialEntry] }) @@ -52,6 +99,38 @@ describe('createMemoryHistory', () => { expect(history.location.pathname).toBe('/b') }) + test('discards forward entries and their state when pushing a new branch', () => { + const initialEntries = ['/'] + const history = createMemoryHistory({ initialEntries }) + history.push('/kept', { marker: 'kept' }) + const keptState = history.location.state + history.push('/discarded-first', { marker: 'discarded-first' }) + history.push('/discarded-last', { marker: 'discarded-last' }) + history.go(-2) + history.push('/new', { marker: 'new' }) + + expect(initialEntries).toEqual(['/', '/kept', '/new']) + expect(history.length).toBe(3) + expect(history.location.pathname).toBe('/new') + expect(history.location.state).toMatchObject({ + __TSR_index: 2, + marker: 'new', + }) + const newState = history.location.state + + history.forward() + expect(history.location.pathname).toBe('/new') + expect(history.location.state).toBe(newState) + + history.back() + expect(history.location.pathname).toBe('/kept') + expect(history.location.state).toBe(keptState) + + history.forward() + expect(history.location.pathname).toBe('/new') + expect(history.location.state).toBe(newState) + }) + test('length', () => { const history = createMemoryHistory() expect(history.length).toBe(1) @@ -76,4 +155,59 @@ describe('createMemoryHistory', () => { history.push('/c', { i: 3 }) expect((history.location.state as any).i).toBe(3) }) + + test('block prevents navigation', async () => { + const history = createMemoryHistory({ initialEntries: ['/'] }) + const blockerFn = vi.fn(() => true) // Always block + + const unblock = history.block({ + blockerFn, + enableBeforeUnload: false, + }) + + await history.push('/a') + + // Navigation should be blocked + expect(history.location.pathname).toBe('/') + expect(blockerFn).toHaveBeenCalled() + + unblock() + }) + + test('block allows navigation when blockerFn returns false', async () => { + const history = createMemoryHistory({ initialEntries: ['/'] }) + const blockerFn = vi.fn(() => false) // Never block + + const unblock = history.block({ + blockerFn, + enableBeforeUnload: false, + }) + + await history.push('/a') + + // Navigation should proceed + expect(history.location.pathname).toBe('/a') + expect(blockerFn).toHaveBeenCalled() + + unblock() + }) + + test('unblock removes blocker', async () => { + const history = createMemoryHistory({ initialEntries: ['/'] }) + const blockerFn = vi.fn(() => true) // Always block + + const unblock = history.block({ + blockerFn, + enableBeforeUnload: false, + }) + + // Unblock immediately + unblock() + + await history.push('/a') + + // Navigation should proceed since blocker was removed + expect(history.location.pathname).toBe('/a') + expect(blockerFn).not.toHaveBeenCalled() + }) }) diff --git a/packages/history/tests/createServerHistory.test.ts b/packages/history/tests/createServerHistory.test.ts new file mode 100644 index 0000000000..c036cea185 --- /dev/null +++ b/packages/history/tests/createServerHistory.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, test, vi } from 'vitest' +import { + createBrowserHistory, + createMemoryHistory, + createServerHistory, +} from '../src' + +describe('server history', () => { + test.each([ + '/', + '/posts/123?sort=new#comments', + '/caf%C3%A9?q=%2F#//section', + '//example.com/path', + '/\\example.com/path', + '/path\nname?value=\u0000', + ])('parses and sanitizes %j like memory history', (href) => { + const history = createServerHistory(href) + const memory = createMemoryHistory({ initialEntries: [href] }) + expect(history.location).toEqual({ + ...memory.location, + state: { + key: expect.any(String), + __TSR_key: expect.any(String), + __TSR_index: 0, + }, + }) + expect(history.location.state.key).toBe(history.location.state.__TSR_key) + }) + + test.each([ + '//evil.example/path', + '/\\evil.example/path', + '\\/evil.example/path', + '\\\\evil.example/path', + ' \t/\r\\evil.example/path', + '/\t/evil.example/path', + '/a\tb?q=a\nb#section\r', + '/a\u0000b?q=a\u0001b#section\u007f', + '/', + '/posts/123?sort=new#comments', + '/caf%C3%A9?q=%2F#//section', + '/a//b?q=//value#\\/section', + '/%2Fevil.example/path', + ])('normalizes href %j like browser history', (href) => { + const history = createServerHistory('/request') + const browser = createBrowserHistory() + try { + expect(history.createHref(href)).toBe(browser.createHref(href)) + expect(history.location.href).toBe('/request') + } finally { + browser.destroy() + } + }) + + test('ignores navigation, subscriptions, and blockers', () => { + const history = createServerHistory('/request?q=1') + const location = history.location + const subscriber = vi.fn() + const blockerFn = vi.fn(() => true) + const unsubscribe = history.subscribe(subscriber) + const unblock = history.block({ blockerFn }) + + history.push('/pushed', { value: 1 }) + history.replace('/replaced', { value: 2 }) + history.go(-1) + history.back() + history.forward() + history.notify({ type: 'PUSH' }) + history.flush() + history.destroy() + unsubscribe() + unblock() + + expect(history.location).toBe(location) + expect(history.length).toBe(1) + expect(history.canGoBack()).toBe(false) + expect(history.subscribers.size).toBe(0) + expect(history._getBlockers()).toEqual([]) + expect(subscriber).not.toHaveBeenCalled() + expect(blockerFn).not.toHaveBeenCalled() + }) + + test('isolates state and exposed collections between requests', () => { + const first = createServerHistory('/first') + const second = createServerHistory('/second') + first.location.state.__TSR_index = 10 + first.subscribers.add(vi.fn()) + first._getBlockers().push({ blockerFn: () => true }) + + expect(second.location.pathname).toBe('/second') + expect(second.location.state.__TSR_index).toBe(0) + expect(second.subscribers.size).toBe(0) + expect(second._getBlockers()).toEqual([]) + }) +}) diff --git a/packages/history/tests/parseHref.test.ts b/packages/history/tests/parseHref.test.ts index 93388f411c..aa6882e6fc 100644 --- a/packages/history/tests/parseHref.test.ts +++ b/packages/history/tests/parseHref.test.ts @@ -1,11 +1,184 @@ import { describe, expect, test } from 'vitest' import { parseHref } from '../src' +const baseUrl = new URL('https://victim.example/base') + describe('parseHref', () => { + test.each(['\x00', '\x01', '\x1f', '\x7f', '\t', '\n', '\r'])( + 'preserves browser path, query, and fragment interpretation for %j', + (character) => { + const href = `/a${character}b?q=a${character}b#a${character}b` + expect(new URL(parseHref(href, undefined).href, baseUrl).href).toBe( + new URL(href, baseUrl).href, + ) + }, + ) + test('works', () => { - const parsed = parseHref('/foo?bar=baz#qux', {}) + const parsed = parseHref('/foo?bar=baz#qux', {} as any) expect(parsed.pathname).toEqual('/foo') expect(parsed.search).toEqual('?bar=baz') expect(parsed.hash).toEqual('#qux') }) + + test.each([ + ['?x=1', { pathname: '', search: '?x=1', hash: '' }], + ['#top', { pathname: '', search: '', hash: '#top' }], + ['?x=1#top', { pathname: '', search: '?x=1', hash: '#top' }], + ['#top?x=1', { pathname: '', search: '', hash: '#top?x=1' }], + ])( + 'keeps a leading query or fragment out of the pathname: %j', + (href, expected) => { + expect(parseHref(href, undefined)).toMatchObject({ href, ...expected }) + }, + ) + + test.each([ + { __TSR_index: 2 }, + { __TSR_index: 2, key: 'legacy-key', __TSR_key: 'current-key' }, + ])('preserves supplied state %j', (state) => { + Object.freeze(state) + expect(parseHref('/foo', state).state).toBe(state) + }) + + test('creates independent initial states with matching history keys', () => { + const first = parseHref('/foo', undefined) + const second = parseHref('/bar', undefined) + + for (const location of [first, second]) { + expect(location.state).toEqual({ + __TSR_index: 0, + key: expect.any(String), + __TSR_key: location.state.key, + }) + } + + first.state.__TSR_index = 1 + expect(second.state.__TSR_index).toBe(0) + }) + + describe('open redirect prevention', () => { + test('strips CR characters to prevent open redirect', () => { + // If \r (CR) is in the href, it should be stripped + const parsed = parseHref('/\r/google.com/', undefined) + expect(parsed.href).toBe('/google.com/') + expect(parsed.pathname).toBe('/google.com/') + expect(parsed.href).not.toMatch(/^\/\//) + }) + + test('strips LF characters to prevent open redirect', () => { + const parsed = parseHref('/\n/evil.com/', undefined) + expect(parsed.href).toBe('/evil.com/') + expect(parsed.pathname).toBe('/evil.com/') + expect(parsed.href).not.toMatch(/^\/\//) + }) + + test('strips CRLF characters to prevent open redirect', () => { + const parsed = parseHref('/\r\n/evil.com/', undefined) + expect(parsed.href).toBe('/evil.com/') + expect(parsed.pathname).toBe('/evil.com/') + expect(parsed.href).not.toMatch(/^\/\//) + }) + + test('collapses leading double slashes to prevent protocol-relative URLs', () => { + const parsed = parseHref('//evil.com/path', undefined) + expect(parsed.href).toBe('/evil.com/path') + expect(parsed.pathname).toBe('/evil.com/path') + }) + + test('sanitized href resolves safely to same origin', () => { + const parsed = parseHref('/\r/evil.com/', undefined) + const url = new URL(parsed.href, 'http://localhost:3000') + expect(url.origin).toBe('http://localhost:3000') + expect(url.pathname).toBe('/evil.com/') + }) + + test.each([ + '//evil.com/path', + '///evil.com/path', + '/\\evil.com/path', + '/\\\\evil.com/path', + '/\\/evil.com/path', + '\\/evil.com/path', + '\\\\evil.com/path', + ' /\\evil.com/path', + '\x01//evil.com/path', + '/\t/evil.com/path', + ])('keeps protocol-relative input %j on the current origin', (href) => { + const parsed = parseHref(href, undefined) + const url = new URL(parsed.href, 'https://victim.example') + + expect(url.origin).toBe('https://victim.example') + }) + + test.each([ + 'h\x00ttps://evil.example', + 'java\x00script:alert(1)', + '/\x00/evil.example', + '\x7f//evil.example', + '/%5c/evil.example', + '/%2f/evil.example', + '?next=//evil.example', + '#//evil.example', + '//evil.example', + '', + ' ', + '\x00', + '\x00\t\n', + ])('does not make same-origin input %j cross-origin', (href) => { + expect(new URL(href, baseUrl).origin).toBe(baseUrl.origin) + + const parsed = parseHref(href, undefined) + + expect(new URL(parsed.href, baseUrl).origin).toBe(baseUrl.origin) + }) + + test('matches WHATWG parsing of protocol-relative prefixes', () => { + const alphabet = [ + '/', + '\\', + '\t', + '\n', + '\r', + '\x00', + '\x0b', + ' ', + '\x7f', + ] + + for (let length = 0; length <= 4; length++) { + const count = alphabet.length ** length + for (let value = 0; value < count; value++) { + let input = '' + let cursor = value + for (let index = 0; index < length; index++) { + input += alphabet[cursor % alphabet.length] + cursor = Math.floor(cursor / alphabet.length) + } + input += 'evil.example/path' + + try { + new URL(input, baseUrl) + } catch { + continue + } + + const parsed = parseHref(input, undefined) + + expect( + new URL(parsed.href, baseUrl).origin, + JSON.stringify(input), + ).toBe(baseUrl.origin) + } + } + }) + + test('normal paths remain unchanged', () => { + const parsed = parseHref('/users/profile?id=1#section', undefined) + expect(parsed.href).toBe('/users/profile?id=1#section') + expect(parsed.pathname).toBe('/users/profile') + expect(parsed.search).toBe('?id=1') + expect(parsed.hash).toBe('#section') + }) + }) }) diff --git a/packages/history/tsconfig.build.json b/packages/history/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/history/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/history/vite.config.ts b/packages/history/vite.config.ts index 5edc0264cb..5eef55c1d9 100644 --- a/packages/history/vite.config.ts +++ b/packages/history/vite.config.ts @@ -1,5 +1,5 @@ import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' import packageJson from './package.json' const config = defineConfig({ @@ -17,5 +17,6 @@ export default mergeConfig( tanstackViteConfig({ entry: './src/index.ts', srcDir: './src', + tsconfigPath: './tsconfig.build.json', }), ) diff --git a/packages/nitro-v2-vite-plugin/README.md b/packages/nitro-v2-vite-plugin/README.md deleted file mode 100644 index 5882e61120..0000000000 --- a/packages/nitro-v2-vite-plugin/README.md +++ /dev/null @@ -1 +0,0 @@ -# Experimental Nitro v2 Vite Plugin diff --git a/packages/nitro-v2-vite-plugin/eslint.config.js b/packages/nitro-v2-vite-plugin/eslint.config.js deleted file mode 100644 index 8ce6ad05fc..0000000000 --- a/packages/nitro-v2-vite-plugin/eslint.config.js +++ /dev/null @@ -1,5 +0,0 @@ -// @ts-check - -import rootConfig from '../../eslint.config.js' - -export default [...rootConfig] diff --git a/packages/nitro-v2-vite-plugin/package.json b/packages/nitro-v2-vite-plugin/package.json deleted file mode 100644 index 1a88c8733e..0000000000 --- a/packages/nitro-v2-vite-plugin/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "name": "@tanstack/nitro-v2-vite-plugin", - "version": "1.141.0", - "description": "Modern and scalable routing for React applications", - "author": "Tanner Linsley", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/TanStack/router.git", - "directory": "packages/nitro-v2-vite-plugin" - }, - "homepage": "https://tanstack.com/router", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/tannerlinsley" - }, - "keywords": [ - "react", - "location", - "router", - "routing", - "async", - "async router", - "typescript" - ], - "scripts": { - "clean": "rimraf ./dist && rimraf ./coverage", - "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit", - "test:unit": "echo 'No unit tests are needed here since we do them in @tanstack/router-plugin!'", - "test:eslint": "eslint ./src", - "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", - "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", - "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", - "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", - "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", - "build": "vite build" - }, - "type": "module", - "types": "dist/esm/index.d.ts", - "main": "dist/cjs/index.cjs", - "module": "dist/esm/index.js", - "exports": { - ".": { - "import": { - "types": "./dist/esm/index.d.ts", - "default": "./dist/esm/index.js" - } - }, - "./package.json": "./package.json" - }, - "sideEffects": false, - "files": [ - "dist", - "src" - ], - "engines": { - "node": ">=22.12" - }, - "dependencies": { - "nitropack": "^2.12.6", - "pathe": "^2.0.3" - }, - "peerDependencies": { - "vite": ">=7.0.0" - } -} diff --git a/packages/nitro-v2-vite-plugin/src/index.ts b/packages/nitro-v2-vite-plugin/src/index.ts deleted file mode 100644 index d8ae5009de..0000000000 --- a/packages/nitro-v2-vite-plugin/src/index.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { build, copyPublicAssets, createNitro, prepare } from 'nitropack' -import { dirname, resolve } from 'pathe' - -import type { PluginOption, ResolvedConfig, Rollup } from 'vite' -import type { NitroConfig } from 'nitropack' - -let ssrBundle: Rollup.OutputBundle -let ssrEntryFile: string - -function isFullUrl(str: string): boolean { - try { - new URL(str) - return true - } catch { - return false - } -} - -export function nitroV2Plugin(nitroConfig?: NitroConfig): Array { - let resolvedConfig: ResolvedConfig - return [ - { - name: 'tanstack-nitro-v2-vite-plugin', - - generateBundle: { - handler(_options, bundle) { - if (this.environment.name !== 'ssr') { - return - } - - // find entry point of ssr bundle - let entryFile: string | undefined - for (const [_name, file] of Object.entries(bundle)) { - if (file.type === 'chunk') { - if (file.isEntry) { - if (entryFile !== undefined) { - this.error( - `Multiple entry points found for service "${this.environment.name}". Only one entry point is allowed.`, - ) - } - entryFile = file.fileName - } - } - } - if (entryFile === undefined) { - this.error( - `No entry point found for service "${this.environment.name}".`, - ) - } - ssrEntryFile = entryFile! - ssrBundle = bundle - }, - }, - - configResolved(config) { - resolvedConfig = config - }, - config(_, env) { - if (env.command !== 'build') { - return - } - - return { - environments: { - ssr: { - consumer: 'server', - build: { - ssr: true, - // we don't write to the file system as the below 'capture-output' plugin will - // capture the output and write it to the virtual file system - write: false, - copyPublicDir: false, - commonjsOptions: { - include: [/node_modules/], - }, - }, - }, - }, - builder: { - sharedPlugins: true, - async buildApp(builder) { - const client = builder.environments.client - const server = builder.environments.ssr - - if (!client) { - throw new Error('Client environment not found') - } - - if (!server) { - throw new Error('SSR environment not found') - } - - await builder.build(client) - await builder.build(server) - - const virtualEntry = '#tanstack/start/entry' - const baseURL = !isFullUrl(resolvedConfig.base) - ? resolvedConfig.base - : undefined - const config: NitroConfig = { - baseURL, - publicAssets: [ - { - dir: client.config.build.outDir, - maxAge: 31536000, // 1 year - baseURL: '/', - }, - ], - ...nitroConfig, - esbuild: { - options: { - target: server.config.build.target || undefined, - ...nitroConfig?.esbuild?.options, - }, - }, - renderer: virtualEntry, - rollupConfig: { - ...nitroConfig?.rollupConfig, - plugins: [virtualBundlePlugin(ssrBundle) as any], - }, - virtual: { - ...nitroConfig?.virtual, - [virtualEntry]: `import { fromWebHandler } from 'h3' - import handler from '${ssrEntryFile}' - export default fromWebHandler(handler.fetch)`, - }, - } - - const nitro = await createNitro(config) - - await prepare(nitro) - await copyPublicAssets(nitro) - await build(nitro) - - await nitro.close() - }, - }, - } - }, - }, - ] -} - -function virtualBundlePlugin(bundle: Rollup.OutputBundle): Rollup.Plugin { - type VirtualModule = { code: string; map: string | null } - let _modules: Map | null = null - - // lazy initialize _modules since at the time of plugin creation, the bundles are not available yet - const getModules = () => { - if (_modules) { - return _modules - } - _modules = new Map() - // group chunks and source maps - for (const [fileName, content] of Object.entries(bundle)) { - if (content.type === 'chunk') { - const virtualModule: VirtualModule = { - code: content.code, - map: null, - } - const maybeMap = bundle[`${fileName}.map`] - if (maybeMap && maybeMap.type === 'asset') { - virtualModule.map = maybeMap.source as string - } - _modules.set(fileName, virtualModule) - _modules.set(resolve(fileName), virtualModule) - } - } - return _modules - } - - return { - name: 'virtual-bundle', - resolveId(id, importer) { - const modules = getModules() - if (modules.has(id)) { - return resolve(id) - } - - if (importer) { - const resolved = resolve(dirname(importer), id) - if (modules.has(resolved)) { - return resolved - } - } - return null - }, - load(id) { - const modules = getModules() - const m = modules.get(id) - if (!m) { - return null - } - return m - }, - } -} diff --git a/packages/nitro-v2-vite-plugin/tsconfig.json b/packages/nitro-v2-vite-plugin/tsconfig.json deleted file mode 100644 index bd398a8728..0000000000 --- a/packages/nitro-v2-vite-plugin/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "include": ["src", "vite.config.ts", "tests"], - "exclude": ["tests/test-files/**", "tests/snapshots/**"], - "compilerOptions": { - "jsx": "react-jsx" - } -} diff --git a/packages/nitro-v2-vite-plugin/vite.config.ts b/packages/nitro-v2-vite-plugin/vite.config.ts deleted file mode 100644 index 75bb759998..0000000000 --- a/packages/nitro-v2-vite-plugin/vite.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' - -const config = defineConfig({}) - -export default mergeConfig( - config, - tanstackViteConfig({ - entry: './src/index.ts', - srcDir: './src', - exclude: ['./src/tests/'], - }), -) diff --git a/packages/react-router-devtools/CHANGELOG.md b/packages/react-router-devtools/CHANGELOG.md new file mode 100644 index 0000000000..f74de5f187 --- /dev/null +++ b/packages/react-router-devtools/CHANGELOG.md @@ -0,0 +1,97 @@ +# @tanstack/react-router-devtools + +## 1.167.3 + +### Patch Changes + +- Updated dependencies [[`bbf9b75`](https://github.com/TanStack/router/commit/bbf9b75808d8eee497a6dd1663f0cf08426512e0)]: + - @tanstack/router-devtools-core@1.168.3 + +## 1.167.2 + +### Patch Changes + +- Updated dependencies [[`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776), [`6cfb1e8`](https://github.com/TanStack/router/commit/6cfb1e8b564be282584765352250bf61747895ed), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8), [`873c830`](https://github.com/TanStack/router/commit/873c830ccb2610a864ee697250e10fcc99772ffa), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`f151ab0`](https://github.com/TanStack/router/commit/f151ab018eede64ae849b77e68f3cdf31cb95cc5), [`bc57fa3`](https://github.com/TanStack/router/commit/bc57fa3f12450cf34c731450947c7c8f1ea05e58), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9448caa`](https://github.com/TanStack/router/commit/9448caa03a89076b9770631c356c0cc502802c09), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef)]: + - @tanstack/router-core@1.171.30 + - @tanstack/react-router@1.170.36 + - @tanstack/router-devtools-core@1.168.2 + +## 1.167.1 + +### Patch Changes + +- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: + - @tanstack/router-core@1.171.16 + - @tanstack/react-router@1.170.19 + - @tanstack/router-devtools-core@1.168.1 + +## 1.167.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +### Patch Changes + +- Updated dependencies [[`b1c061a`](https://github.com/TanStack/router/commit/b1c061aff9185cdf5fdc08c0136382a9dce0302f), [`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14)]: + - @tanstack/router-core@1.170.0 + - @tanstack/react-router@1.170.0 + - @tanstack/router-devtools-core@1.168.0 + +## 1.166.13 + +### Patch Changes + +- Updated dependencies [[`6355bb7`](https://github.com/TanStack/router/commit/6355bb75f7637ba77f06a923c18fdaf37720bb48)]: + - @tanstack/router-devtools-core@1.167.3 + - @tanstack/react-router@1.168.15 + - @tanstack/router-core@1.168.11 + +## 1.166.12 + +### Patch Changes + +- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: + - @tanstack/router-devtools-core@1.167.2 + - @tanstack/react-router@1.168.14 + - @tanstack/router-core@1.168.10 + +## 1.166.11 + +### Patch Changes + +- Updated dependencies [[`c9e1855`](https://github.com/TanStack/router/commit/c9e18555f3a5531e96de8f574cfca9edcdb18e5c)]: + - @tanstack/router-devtools-core@1.167.1 + - @tanstack/react-router@1.168.2 + - @tanstack/router-core@1.168.2 + +## 1.166.10 + +### Patch Changes + +- Updated dependencies [[`0545239`](https://github.com/TanStack/router/commit/054523900b2ee19308e5a88417dadfc6923afe30)]: + - @tanstack/router-devtools-core@1.167.0 + - @tanstack/react-router@1.168.0 + - @tanstack/router-core@1.168.0 + +## 1.166.9 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +- Updated dependencies [[`838b0eb`](https://github.com/TanStack/router/commit/838b0eb9a8bbbb987a0a6972c1446e01423bbd7b)]: + - @tanstack/router-devtools-core@1.166.9 + - @tanstack/react-router@1.167.2 + - @tanstack/router-core@1.167.2 + +## 1.166.8 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) + +- Updated dependencies [[`ef9b241`](https://github.com/TanStack/router/commit/ef9b241f3cfe95cee40daa96da669f0ffd4a971a)]: + - @tanstack/router-devtools-core@1.166.8 + - @tanstack/react-router@1.167.1 + - @tanstack/router-core@1.167.1 diff --git a/packages/react-router-devtools/README.md b/packages/react-router-devtools/README.md index 7be76f46c2..0079d7c065 100644 --- a/packages/react-router-devtools/README.md +++ b/packages/react-router-devtools/README.md @@ -1,5 +1,22 @@ +
    + + + + TanStack React Router + +
    # TanStack React Router Devtools See https://tanstack.com/router/latest/docs/framework/react/devtools diff --git a/packages/react-router-devtools/package.json b/packages/react-router-devtools/package.json index e0dffa7df1..969371a6a6 100644 --- a/packages/react-router-devtools/package.json +++ b/packages/react-router-devtools/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router-devtools", - "version": "1.141.8", + "version": "1.167.3", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -27,12 +27,12 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -59,16 +59,27 @@ "src" ], "engines": { - "node": ">=12" + "node": ">=20.19" }, "dependencies": { "@tanstack/router-devtools-core": "workspace:*" }, "devDependencies": { - "@vitejs/plugin-react": "^4.3.4", - "react": ">=19", - "react-dom": ">=19", - "vite": "^7.1.7" + "@vitejs/plugin-react": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", + "vite": "*", + "@types/node": ">=20", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@eslint-react/eslint-plugin": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "@tanstack/react-router": "workspace:^", diff --git a/packages/react-router-devtools/src/TanStackRouterDevtools.tsx b/packages/react-router-devtools/src/TanStackRouterDevtools.tsx index 925e7687e9..2248d27ef6 100644 --- a/packages/react-router-devtools/src/TanStackRouterDevtools.tsx +++ b/packages/react-router-devtools/src/TanStackRouterDevtools.tsx @@ -1,3 +1,5 @@ +'use client' + import { TanStackRouterDevtoolsCore } from '@tanstack/router-devtools-core' import { Fragment, useEffect, useRef, useState } from 'react' import { useRouter, useRouterState } from '@tanstack/react-router' diff --git a/packages/react-router-devtools/src/TanStackRouterDevtoolsPanel.tsx b/packages/react-router-devtools/src/TanStackRouterDevtoolsPanel.tsx index 46118bf2e6..ee7fba313b 100644 --- a/packages/react-router-devtools/src/TanStackRouterDevtoolsPanel.tsx +++ b/packages/react-router-devtools/src/TanStackRouterDevtoolsPanel.tsx @@ -1,3 +1,5 @@ +'use client' + import { useRouter, useRouterState } from '@tanstack/react-router' import { TanStackRouterDevtoolsPanelCore } from '@tanstack/router-devtools-core' import React, { useEffect, useRef, useState } from 'react' diff --git a/packages/react-router-devtools/src/index.ts b/packages/react-router-devtools/src/index.ts index 3db31a9b73..e711869ce8 100644 --- a/packages/react-router-devtools/src/index.ts +++ b/packages/react-router-devtools/src/index.ts @@ -1,3 +1,5 @@ +'use client' + import * as Devtools from './TanStackRouterDevtools' import * as DevtoolsPanel from './TanStackRouterDevtoolsPanel' diff --git a/packages/react-router-devtools/tsconfig.build.json b/packages/react-router-devtools/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/react-router-devtools/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/react-router-devtools/tsconfig.json b/packages/react-router-devtools/tsconfig.json index 1599b212c0..fc0a511b1a 100644 --- a/packages/react-router-devtools/tsconfig.json +++ b/packages/react-router-devtools/tsconfig.json @@ -2,7 +2,8 @@ "extends": "../../tsconfig.json", "compilerOptions": { "jsx": "react-jsx", - "jsxImportSource": "react" + "jsxImportSource": "react", + "types": ["node"] }, "include": ["src", "tests", "vite.config.ts"] } diff --git a/packages/react-router-devtools/vite.config.ts b/packages/react-router-devtools/vite.config.ts index 410777b826..0f6d3b9227 100644 --- a/packages/react-router-devtools/vite.config.ts +++ b/packages/react-router-devtools/vite.config.ts @@ -1,11 +1,10 @@ import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' import react from '@vitejs/plugin-react' import packageJson from './package.json' -import type { UserConfig } from 'vitest/config' const config = defineConfig({ - plugins: [react()] as UserConfig['plugins'], + plugins: [react()], test: { name: packageJson.name, dir: './tests', @@ -18,6 +17,7 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ + tsconfigPath: './tsconfig.build.json', entry: './src/index.ts', srcDir: './src', }), diff --git a/packages/react-router-ssr-query/CHANGELOG.md b/packages/react-router-ssr-query/CHANGELOG.md new file mode 100644 index 0000000000..d0fc73ff50 --- /dev/null +++ b/packages/react-router-ssr-query/CHANGELOG.md @@ -0,0 +1,92 @@ +# @tanstack/react-router-ssr-query + +## 1.167.3 + +### Patch Changes + +- [#8204](https://github.com/TanStack/router/pull/8204) [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26) - Stream large deferred SSR hydration payloads through a backpressure-aware router transport, fail known setup errors before response creation, and close cancelled or expired transforms safely. + + Start now cancels discarded middleware and HEAD response bodies, including plain streams and derived branches. + + Server-function raw streams share one ordered response. Arbitrary or sequential consumption can require potentially unbounded buffering of unread data on the client. Cancelling one raw stream discards it locally, while aborting the whole call cancels the response and server work. Consume streams concurrently, cancel unused streams promptly, or use separate calls when independent backpressure is required. A raw stream that exceeds its unread-byte limit now fails alone; sibling streams and the JSON result keep flowing. + + The JSON wire shape of a `RawStream` server-function argument changed. Clients and servers must run matching versions for requests that pass a `RawStream`. + + The frame-protocol constants (`FRAME_TYPE_*`, `MAX_FRAME_PAYLOAD_SIZE`, `MAX_FRAMED_STREAMS`) moved from the `@tanstack/start-client-core` root to the `@tanstack/start-client-core/client-rpc` subpath. + + Router requests whose `Accept` header allows neither `text/html` nor `*/*` now receive `406 Not Acceptable` instead of `500`. + + Framework adapters share the body `` composition (`getSsrBodyScriptParts`, `composeSsrBodyScripts`) and the eager HTML response wrapper (`renderSsrHtmlResponse`) from `@tanstack/router-core`. + + Solid SSR now emits one document type and renders late lazy errors through route boundaries. A Solid `` without a `fallback` no longer holds the streamed shell; it renders inside the nearest `` boundary like React and Vue, and now renders falsy resolved values. + + Static server functions decode cached `RawStream` values with the client deserializer plugins. + + SSR Query integrations now keep request cleanup and stream ownership aligned with the router lifecycle. + +- Updated dependencies [[`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26)]: + - @tanstack/router-ssr-query-core@1.169.3 + +## 1.167.2 + +### Patch Changes + +- Updated dependencies [[`79e3533`](https://github.com/TanStack/router/commit/79e35335b4bb1c3b5e2275a8df5181aa05036628)]: + - @tanstack/router-ssr-query-core@1.169.2 + +## 1.167.1 + +### Patch Changes + +- Updated dependencies [[`d1997b6`](https://github.com/TanStack/router/commit/d1997b66d7c24c1d64772bb8bab5caf9c6d9cc48)]: + - @tanstack/router-ssr-query-core@1.169.1 + +## 1.167.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +### Patch Changes + +- Updated dependencies [[`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14)]: + - @tanstack/router-ssr-query-core@1.169.0 + +## 1.166.12 + +### Patch Changes + +- Updated dependencies [[`b12f57b`](https://github.com/TanStack/router/commit/b12f57bbb44e47d5452d46e9e67ea4d63cdb5b55)]: + - @tanstack/router-ssr-query-core@1.168.0 + +## 1.166.11 + +### Patch Changes + +- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: + - @tanstack/router-ssr-query-core@1.167.1 + +## 1.166.10 + +### Patch Changes + +- Updated dependencies [[`0545239`](https://github.com/TanStack/router/commit/054523900b2ee19308e5a88417dadfc6923afe30)]: + - @tanstack/router-ssr-query-core@1.167.0 + +## 1.166.9 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +- Updated dependencies [[`838b0eb`](https://github.com/TanStack/router/commit/838b0eb9a8bbbb987a0a6972c1446e01423bbd7b)]: + - @tanstack/router-ssr-query-core@1.166.9 + +## 1.166.8 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) + +- Updated dependencies [[`ef9b241`](https://github.com/TanStack/router/commit/ef9b241f3cfe95cee40daa96da669f0ffd4a971a)]: + - @tanstack/router-ssr-query-core@1.166.8 diff --git a/packages/react-router-ssr-query/README.md b/packages/react-router-ssr-query/README.md index 1cc3471e0a..c3a60d1008 100644 --- a/packages/react-router-ssr-query/README.md +++ b/packages/react-router-ssr-query/README.md @@ -2,7 +2,21 @@ # TanStack React Router -![TanStack Router Header](https://github.com/tanstack/router/raw/main/media/header_router.png) + + + + TanStack React Router + 🤖 Type-safe router w/ built-in caching & URL state management for React! @@ -16,9 +30,9 @@ semantic-release - + Join the discussion on Github -Best of JS +Best of JS @@ -26,6 +40,6 @@ -Enjoy this library? Try the entire [TanStack](https://tanstack.com)! [React Query](https://github.com/tannerlinsley/react-query), [React Table](https://github.com/tanstack/react-table), [React Charts](https://github.com/tannerlinsley/react-charts), [React Virtual](https://github.com/tannerlinsley/react-virtual) +Enjoy this library? Try the entire [TanStack](https://tanstack.com)! [React Query](https://github.com/TanStack/query), [React Table](https://github.com/TanStack/table), [React Charts](https://github.com/TanStack/react-charts), [React Virtual](https://github.com/TanStack/virtual) ## Visit [tanstack.com/router](https://tanstack.com/router) for docs, guides, API and more! diff --git a/packages/react-router-ssr-query/package.json b/packages/react-router-ssr-query/package.json index 6d48c00e5c..7333146047 100644 --- a/packages/react-router-ssr-query/package.json +++ b/packages/react-router-ssr-query/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router-ssr-query", - "version": "1.141.8", + "version": "1.167.3", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -27,12 +27,12 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:unit": "exit 0; vitest", "test:unit:dev": "pnpm run test:unit --watch", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", @@ -61,23 +61,34 @@ "src" ], "engines": { - "node": ">=12" + "node": ">=20.19" }, "dependencies": { "@tanstack/router-ssr-query-core": "workspace:*" }, "devDependencies": { - "@vitejs/plugin-react": "^4.3.4", - "react": ">=19", - "react-dom": ">=19", + "@vitejs/plugin-react": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", "@tanstack/react-router": "workspace:*", - "@tanstack/react-query": ">=5.90.0" + "@tanstack/react-query": ">=5.102.0", + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@eslint-react/eslint-plugin": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", - "@tanstack/query-core": ">=5.90.0", - "@tanstack/react-router": ">=1.127.0", - "@tanstack/react-query": ">=5.90.0" + "@tanstack/query-core": ">=5.102.0", + "@tanstack/react-router": ">=1.170.33", + "@tanstack/react-query": ">=5.102.0" } } diff --git a/packages/react-router-ssr-query/tsconfig.build.json b/packages/react-router-ssr-query/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/react-router-ssr-query/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/react-router-ssr-query/vite.config.ts b/packages/react-router-ssr-query/vite.config.ts index 212232f411..ffe4359c13 100644 --- a/packages/react-router-ssr-query/vite.config.ts +++ b/packages/react-router-ssr-query/vite.config.ts @@ -1,11 +1,10 @@ import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' import react from '@vitejs/plugin-react' import packageJson from './package.json' -import type { UserConfig } from 'vitest/config' const config = defineConfig({ - plugins: [react()] as UserConfig['plugins'], + plugins: [react()], test: { name: packageJson.name, dir: './tests', @@ -18,6 +17,7 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ + tsconfigPath: './tsconfig.build.json', entry: './src/index.tsx', srcDir: './src', }), diff --git a/packages/react-router/CHANGELOG.md b/packages/react-router/CHANGELOG.md new file mode 100644 index 0000000000..7e1e2f1a62 --- /dev/null +++ b/packages/react-router/CHANGELOG.md @@ -0,0 +1,808 @@ +# @tanstack/react-router + +## 1.170.46 + +### Patch Changes + +- [#8670](https://github.com/TanStack/router/pull/8670) [`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c) - Reference agent skills in other packages by their `intent load` identifier (`@tanstack/#`) instead of relative file links that break once packages are installed. + +- [#8671](https://github.com/TanStack/router/pull/8671) [`689a7c5`](https://github.com/TanStack/router/commit/689a7c5419de68bce0aaaef72b9a36f115ea1398) - Publish the `@tanstack/react-router` agent skills (`react-router`, `compositions/router-query`, `lifecycle/migrate-from-react-router`), which were missing from the package's `files` list. + +- Updated dependencies [[`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c)]: + - @tanstack/router-core@1.171.39 + +## 1.170.45 + +### Patch Changes + +- Updated dependencies [[`18154b1`](https://github.com/TanStack/router/commit/18154b1c45454a70aa77e9d6d27c8a6e0733d031)]: + - @tanstack/router-core@1.171.38 + +## 1.170.44 + +### Patch Changes + +- Updated dependencies [[`d6ba115`](https://github.com/TanStack/router/commit/d6ba115d5751c75e20943f0062577cf17b446d82)]: + - @tanstack/router-core@1.171.37 + +## 1.170.43 + +### Patch Changes + +- Updated dependencies [[`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5)]: + - @tanstack/router-core@1.171.36 + +## 1.170.42 + +### Patch Changes + +- [#8594](https://github.com/TanStack/router/pull/8594) [`2413cc0`](https://github.com/TanStack/router/commit/2413cc009826fba4f97b166a35a8a50a4a8fe4bb) - reduce component nesting per route match + +- [#8602](https://github.com/TanStack/router/pull/8602) [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb) - Links of a route that the pending navigation leaves skip deriving the destination location, and clicks and preloads follow the href a Link displays. `buildLocation` now builds `mask` and `routeMasks` locations from the same `_fromLocation` as the destination. + +- [#8602](https://github.com/TanStack/router/pull/8602) [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb) - Fixed Link destinations that resolve to a route mask are now reused across navigations instead of being rebuilt every time. A mounted Link now follows changes to its `href` and `reloadDocument` props, and React Links no longer each subscribe to a hydration flag. + +- [#8579](https://github.com/TanStack/router/pull/8579) [`d35aab4`](https://github.com/TanStack/router/commit/d35aab425b07b46e222a507c0f0239644669757b) - Cancel pending link preload timers when starting navigation to avoid redundant preloading while the destination is loading. + +- Updated dependencies [[`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`663282b`](https://github.com/TanStack/router/commit/663282b0ebbc494aee3595ed95867ee29d01938e)]: + - @tanstack/history@1.162.5 + - @tanstack/router-core@1.171.35 + +## 1.170.41 + +### Patch Changes + +- [#8529](https://github.com/TanStack/router/pull/8529) [`60b8ad1`](https://github.com/TanStack/router/commit/60b8ad1ad00812bf966a8eeee6be238c37ddad74) - Compose only enabled route boundaries instead of rendering inactive wrapper components. + +- [#8568](https://github.com/TanStack/router/pull/8568) [`614bc27`](https://github.com/TanStack/router/commit/614bc27034c8ec98747bf305ed41d4a619640949) - Update TanStack Store to 0.11.2 to prevent unrelated atom reads inside subscription observers from triggering extra notifications. + +- [#8530](https://github.com/TanStack/router/pull/8530) [`ff66a03`](https://github.com/TanStack/router/commit/ff66a03df4816f44a48a4a37189fc4021b1c8480) - Consolidate the root match context provider while preserving match context in the root shell. + +- [#8522](https://github.com/TanStack/router/pull/8522) [`863c8a7`](https://github.com/TanStack/router/commit/863c8a736b96746c56278a16c50554356f5523d1) - Reuse Link href classification and active/inactive results across location updates while preserving live history href formatting. + +- Updated dependencies [[`d521abd`](https://github.com/TanStack/router/commit/d521abd71c69f1ff010bb3def4d417cb5fa058cb)]: + - @tanstack/router-core@1.171.34 + +## 1.170.40 + +### Patch Changes + +- [#8436](https://github.com/TanStack/router/pull/8436) [`f5ffd38`](https://github.com/TanStack/router/commit/f5ffd3884ba26778a2a8ce53b379a5bded231676) - Skip unused Link preload cleanup when preloading is disabled and ignore queued viewport notifications after their effect has been cleaned up. + +- Updated dependencies [[`488d046`](https://github.com/TanStack/router/commit/488d046a907d330429e2c807ef95326dad87480f), [`0c1b5e3`](https://github.com/TanStack/router/commit/0c1b5e38de71b7e81bbf1fd81c73ee0cd68ffe47), [`3cdd1af`](https://github.com/TanStack/router/commit/3cdd1af04b3e2d6f777797ee7bddf285318dd9d2)]: + - @tanstack/router-core@1.171.33 + +## 1.170.39 + +### Patch Changes + +- [#8435](https://github.com/TanStack/router/pull/8435) [`73bfc15`](https://github.com/TanStack/router/commit/73bfc153eef460e9b670556215a5adb2b5cbf542) - Avoid hydration-triggered rerenders for links that do not compare URL hashes while preserving hash-sensitive active state and ClientOnly behavior. + +## 1.170.38 + +### Patch Changes + +- Updated dependencies [[`cecae54`](https://github.com/TanStack/router/commit/cecae5440b8edaea77c5448fe3d74bbd20fe10a4), [`0103578`](https://github.com/TanStack/router/commit/01035782e53af9b929c784b94ddd64b95efb89c7), [`ce10dcd`](https://github.com/TanStack/router/commit/ce10dcd4d9d3d23738744e453205aad5c6dbd716), [`84936cc`](https://github.com/TanStack/router/commit/84936cc04530bba11059c57b293a794922bbc5aa), [`bbd2336`](https://github.com/TanStack/router/commit/bbd2336b8446de3f7dd85070895e7cf43980183e)]: + - @tanstack/router-core@1.171.32 + +## 1.170.37 + +### Patch Changes + +- [#8418](https://github.com/TanStack/router/pull/8418) [`e561fa1`](https://github.com/TanStack/router/commit/e561fa1d7118e3d29267cc3b6ce1130d6581f387) - `deepEqual` now takes its flags as positional arguments — `deepEqual(a, b, partial?, explicitUndefined?)` — instead of an options object. The router's hot callers (Link option stabilization and active-state checks, `matchRoute`) no longer allocate an options object per comparison, and the comparator reads two booleans instead of a polymorphic object. `explicitUndefined` replaces `ignoreUndefined: false`. `deepEqual` is an internal helper; it stays exported for compatibility of two-argument calls. + +- [#8419](https://github.com/TanStack/router/pull/8419) [`a1c8d1a`](https://github.com/TanStack/router/commit/a1c8d1aa759c227eae9601a030321ac4c53c24bd) - `resolvePath` (internal helper) now takes positional arguments — `resolvePath(base, to, trailingSlash?, cache?)` — so `buildLocation` and `matchRoute` no longer allocate an options object per path resolution. + +- [#8204](https://github.com/TanStack/router/pull/8204) [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26) - Stream large deferred SSR hydration payloads through a backpressure-aware router transport, fail known setup errors before response creation, and close cancelled or expired transforms safely. + + Start now cancels discarded middleware and HEAD response bodies, including plain streams and derived branches. + + Server-function raw streams share one ordered response. Arbitrary or sequential consumption can require potentially unbounded buffering of unread data on the client. Cancelling one raw stream discards it locally, while aborting the whole call cancels the response and server work. Consume streams concurrently, cancel unused streams promptly, or use separate calls when independent backpressure is required. A raw stream that exceeds its unread-byte limit now fails alone; sibling streams and the JSON result keep flowing. + + The JSON wire shape of a `RawStream` server-function argument changed. Clients and servers must run matching versions for requests that pass a `RawStream`. + + The frame-protocol constants (`FRAME_TYPE_*`, `MAX_FRAME_PAYLOAD_SIZE`, `MAX_FRAMED_STREAMS`) moved from the `@tanstack/start-client-core` root to the `@tanstack/start-client-core/client-rpc` subpath. + + Router requests whose `Accept` header allows neither `text/html` nor `*/*` now receive `406 Not Acceptable` instead of `500`. + + Framework adapters share the body `` composition (`getSsrBodyScriptParts`, `composeSsrBodyScripts`) and the eager HTML response wrapper (`renderSsrHtmlResponse`) from `@tanstack/router-core`. + + Solid SSR now emits one document type and renders late lazy errors through route boundaries. A Solid `` without a `fallback` no longer holds the streamed shell; it renders inside the nearest `` boundary like React and Vue, and now renders falsy resolved values. + + Static server functions decode cached `RawStream` values with the client deserializer plugins. + + SSR Query integrations now keep request cleanup and stream ownership aligned with the router lifecycle. + +- [#8420](https://github.com/TanStack/router/pull/8420) [`8e164d2`](https://github.com/TanStack/router/commit/8e164d28f9e9eb1a7301109230d7ece9817492a8) - `useLinkProps` no longer calls through an internal wrapper. The host element `Link` renders on is an `@internal` overload parameter that is stripped from the published declarations, so the public `useLinkProps(options, forwardedRef?)` signature is unchanged. + +- Updated dependencies [[`bc80866`](https://github.com/TanStack/router/commit/bc80866f6d6eb3e6f152ee3682eb783c96403e83), [`e561fa1`](https://github.com/TanStack/router/commit/e561fa1d7118e3d29267cc3b6ce1130d6581f387), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a1c8d1a`](https://github.com/TanStack/router/commit/a1c8d1aa759c227eae9601a030321ac4c53c24bd), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a0b2ad9`](https://github.com/TanStack/router/commit/a0b2ad99aee64af08d16b0e4ff26b3ba42a99f0a), [`1ca361b`](https://github.com/TanStack/router/commit/1ca361ba52a627d2f76ab33323bd83d1d0aa65a3)]: + - @tanstack/router-core@1.171.31 + +## 1.170.36 + +### Patch Changes + +- [#8390](https://github.com/TanStack/router/pull/8390) [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776) - Keep the Link location cache out of server bundles: `buildLocation` only creates, reads and writes it when `isServer` is false. Render React Links on the server without the extra prop copies and the forwarded-ref hook. Link SSR rendering is 20-40% faster in the Link benchmarks and the React Start SSR request loop about 7% faster. + + React `activeProps` and `inactiveProps` now follow one precedence rule on every link, including links whose destination is blocked for using a disallowed scheme: state props override element props, `ref` and event handlers, while `href`, `disabled` and `target` stay controlled by the router. Previously a blocked link ignored a `ref` or handler from its inactive props. + + React `Link` and `useLinkProps` split router options from element props with one key set on the client and the server. Element props pass through as given: external links forward them verbatim, falsy values included, and `useLinkProps` now returns `children` for router-controlled links as it already did for external ones. + +- [#8324](https://github.com/TanStack/router/pull/8324) [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2) - Reuse hydration snapshot getters to avoid unnecessary store-instance effect updates when Links and other hydration-aware components rerender. + +- [#8318](https://github.com/TanStack/router/pull/8318) [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8) - Allow active and inactive Link props to override base element props in React and Solid while preserving class/style merging. Keep React's `href`, `target`, and `disabled` values controlled by routing options. Preserve Vue object and nested-array class bindings, including reactive updates and server rendering, without mutating cached bindings during VNode normalization. + +- [#8327](https://github.com/TanStack/router/pull/8327) [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef) - Make `pathParamsAllowedCharacters` initialization-only. Configure it when creating the router; changing allowed characters requires a new router instance. Remove decoder-update bookkeeping and decoder-change checks from route-owned path caches. + +- [#8370](https://github.com/TanStack/router/pull/8370) [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5) - Stop exporting the internal `isPlainObject` and `isPlainArray` helpers. + +- [#8324](https://github.com/TanStack/router/pull/8324) [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2) - Avoid a redundant prop copy when rendering native Links while preserving custom-component props and the public hook result. + +- [#8252](https://github.com/TanStack/router/pull/8252) [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734) - Reduce the bundle cost of shared Link pathname interpolation while preserving its rendering performance. Reuse one interpolation pass for pathname and optional metadata, keep the bounded cache on the router, and simplify React Link active-state and prop merging. + +- [#8370](https://github.com/TanStack/router/pull/8370) [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5) - Reuse built locations for Links whose destination does not depend on the current location. `buildLocation` keeps the result per options object when the build never read the current location, and the React `Link` passes one stable options object per instance, so navigations resolve unchanged Links with a lookup instead of a full build. The per-route pathname interpolation cache this replaces is removed. Link `params`, `search` and `activeOptions` are compared by value on render, so inline object literals with unchanged contents keep reusing the Link's location. Pass a new object to change a destination; like any other React prop, an object mutated in place is not re-read. + +- Updated dependencies [[`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776), [`6cfb1e8`](https://github.com/TanStack/router/commit/6cfb1e8b564be282584765352250bf61747895ed), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`8fff7fa`](https://github.com/TanStack/router/commit/8fff7fa1f2e6f061916b0bf5e0ec486b2e732f94), [`f021f6d`](https://github.com/TanStack/router/commit/f021f6d1c6dce6c9b54d70766f1d636d8fd9e184), [`ae68535`](https://github.com/TanStack/router/commit/ae68535929043607d4ee9438f8ae401f3a064862), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`873c830`](https://github.com/TanStack/router/commit/873c830ccb2610a864ee697250e10fcc99772ffa), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`f151ab0`](https://github.com/TanStack/router/commit/f151ab018eede64ae849b77e68f3cdf31cb95cc5), [`bc57fa3`](https://github.com/TanStack/router/commit/bc57fa3f12450cf34c731450947c7c8f1ea05e58), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9448caa`](https://github.com/TanStack/router/commit/9448caa03a89076b9770631c356c0cc502802c09), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef)]: + - @tanstack/router-core@1.171.30 + - @tanstack/history@1.162.4 + +## 1.170.35 + +### Patch Changes + +- [#7824](https://github.com/TanStack/router/pull/7824) [`8c43c71`](https://github.com/TanStack/router/commit/8c43c712523fc63dc3a814f3a19617e270ce8ed1) - Upgrade TanStack Store to 0.11 and migrate router subscriptions to useSelector, preserving selector comparisons and Vue subscription cleanup. + +## 1.170.34 + +### Patch Changes + +- [#8279](https://github.com/TanStack/router/pull/8279) [`aee42c6`](https://github.com/TanStack/router/commit/aee42c6b641d8e919bfed9e0f04bb1b72092f3a6) - Avoid allocating event-handler arrays and wrapper functions for links without user-supplied event handlers. + +- [#8308](https://github.com/TanStack/router/pull/8308) [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8) - Validate navigation and redirect destinations, keep ambiguous relative URLs on the current origin, and constrain prerender requests and output paths. Prevent redirect headers from appearing in serialized server function response bodies. + + Preserve native form HTTP redirects, route error handling and masks for document redirects, and per-navigation destinations for shared loader redirects. Avoid redundant origin parsing and reduce link styling and server-rendering work. Configured origins must already be normalized. + + Keep blocked-link inactive props consistent during React hydration, honor explicit redirect Location headers before checking route options, and refresh Vue link state when destinations become internal. Reuse the protocol-relative URL check while parsing redirect schemes once. + + Reduce React link bundle size by sharing pathname comparisons, state-prop selection, and element creation. + + Share normalized pathname comparisons in Solid and Vue links to reduce bundle size. + +- [#8311](https://github.com/TanStack/router/pull/8311) [`9aec5a7`](https://github.com/TanStack/router/commit/9aec5a7012c47e83ec23bb4763494b72a5e68bfc) - React Links resolve state props without temporary class-name arrays or unnecessary style copies. + +- Updated dependencies [[`f9836f1`](https://github.com/TanStack/router/commit/f9836f16f0e25b0a8495f5e01e3f303b1cbc8725), [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8), [`9871c06`](https://github.com/TanStack/router/commit/9871c0625806001d6bf373524821a00303438a91), [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9)]: + - @tanstack/router-core@1.171.29 + - @tanstack/history@1.162.3 + +## 1.170.33 + +### Patch Changes + +- [#8165](https://github.com/TanStack/router/pull/8165) [`2f20c00`](https://github.com/TanStack/router/commit/2f20c00224c5ba63467551914e0c37012588c4c2) - Exclude structural descendants below error and not-found boundaries from route lifecycle callbacks. Preserve lifecycle membership through invalidation, hydration, background reloads, and superseded navigation publication. + +- [#8209](https://github.com/TanStack/router/pull/8209) [`28a5e45`](https://github.com/TanStack/router/commit/28a5e4504e4ea5cb1480667a4bea2588a53e110f) - Preserve falsy thrown values in React and Vue error boundaries. Type React and Vue boundary error components and `onCatch` callbacks as `unknown`. Solid boundary errors remain typed as `Error`; SSR now wraps non-`Error` loader errors to match Solid’s native boundary behavior, preserving the original value in `cause`. Router state and loader `onError` values are unchanged. + + When upgrading React or Vue, narrow boundary errors (for example, with `error instanceof Error`) before reading `message` or `stack`. `ErrorComponentProps` remains available for values narrowed to a specific error type. Route `onError` types are unchanged. + +- [#8161](https://github.com/TanStack/router/pull/8161) [`f0b5eda`](https://github.com/TanStack/router/commit/f0b5eda544606686a8a8d675a686ca1366428b96) - Retain successful not-found matches as terminal shared boundaries during client navigation, preserving route context while the destination loads. + +- [#8251](https://github.com/TanStack/router/pull/8251) [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b) - Use URL.canParse for absolute URL checks in links, navigation, redirects, and build configuration. Preserve a URL constructor fallback for older browsers. + +- [#8169](https://github.com/TanStack/router/pull/8169) [`0caf6b9`](https://github.com/TanStack/router/commit/0caf6b9a2b7e14b0b146c74cc27cb05c19d700a5) - Fix route-scoped `useMatch`, `useSearch`, and `useParams` APIs to forward the `shouldThrow` option and preserve optional return types when `shouldThrow: false`. + +- [#8257](https://github.com/TanStack/router/pull/8257) [`cf166d1`](https://github.com/TanStack/router/commit/cf166d160e6397007a979bfc7065b45ff69ea543) - Fix repeated `innerHTML` writes for unchanged styles and data scripts during React re-renders. This prevents unnecessary CSS parsing and Trusted Types errors during client navigation. + +- Updated dependencies [[`edf0e16`](https://github.com/TanStack/router/commit/edf0e16ebfe82ec6e8f68f403a1fda8de9e28889), [`2f20c00`](https://github.com/TanStack/router/commit/2f20c00224c5ba63467551914e0c37012588c4c2), [`28a5e45`](https://github.com/TanStack/router/commit/28a5e4504e4ea5cb1480667a4bea2588a53e110f), [`08eff50`](https://github.com/TanStack/router/commit/08eff50c447a154a3373909009e9e4375cea17ce), [`216c0c4`](https://github.com/TanStack/router/commit/216c0c48036fd1a33163b70dcabfed2b893808b0), [`2f91503`](https://github.com/TanStack/router/commit/2f9150309bc472f4a75cbe98adcdb50c76b12c7a), [`f0b5eda`](https://github.com/TanStack/router/commit/f0b5eda544606686a8a8d675a686ca1366428b96), [`50eafca`](https://github.com/TanStack/router/commit/50eafcaebbbedb6fde3b2816de7a0ace8cde4832), [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b), [`ee28348`](https://github.com/TanStack/router/commit/ee283480dfa51150a2e0b096a6eff94a89ff8b3f), [`9035abc`](https://github.com/TanStack/router/commit/9035abc41163d83409ef582f7743a3c7be57dd93), [`c18e690`](https://github.com/TanStack/router/commit/c18e69081475a7c98f9d40bd0fe6da78ccb84598)]: + - @tanstack/router-core@1.171.28 + - @tanstack/history@1.162.2 + +## 1.170.32 + +### Patch Changes + +- [#8130](https://github.com/TanStack/router/pull/8130) [`cb281d7`](https://github.com/TanStack/router/commit/cb281d70c1f5fe780f9d07bc500ea3a284a4e04b) - preserve context during reloads + +- Updated dependencies [[`fa65287`](https://github.com/TanStack/router/commit/fa652872812c9433ba8b9d9a285e51b535e7367c), [`cb281d7`](https://github.com/TanStack/router/commit/cb281d70c1f5fe780f9d07bc500ea3a284a4e04b)]: + - @tanstack/router-core@1.171.27 + +## 1.170.31 + +### Patch Changes + +- Updated dependencies [[`3e016ac`](https://github.com/TanStack/router/commit/3e016ac84ffec8119f0c25cfdd1fb17e5292bd34)]: + - @tanstack/router-core@1.171.26 + +## 1.170.30 + +### Patch Changes + +- [#8084](https://github.com/TanStack/router/pull/8084) [`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175) - preserve pending UI across retained routes + +- [#8068](https://github.com/TanStack/router/pull/8068) [`f75cada`](https://github.com/TanStack/router/commit/f75cada01707e51fb9650dd301bc04f8b2265a2a) - direct export of CatchBoundary class component, remove function wrapper + +- Updated dependencies [[`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175), [`63d2cc9`](https://github.com/TanStack/router/commit/63d2cc9155ff5374112f7d067d0b278bafeb8486)]: + - @tanstack/router-core@1.171.25 + +## 1.170.29 + +### Patch Changes + +- [#8073](https://github.com/TanStack/router/pull/8073) [`0fdf9ff`](https://github.com/TanStack/router/commit/0fdf9ff16fc532de9fc131d18df167ebd8038720) - inline isCtrlKey inside Link component for byte shaving + +- Updated dependencies [[`4c89b15`](https://github.com/TanStack/router/commit/4c89b15dd2b46491ee5e57985559bae8e31d62c2), [`cf6ab17`](https://github.com/TanStack/router/commit/cf6ab178b39e7628bf784759f384e0f4230e6d9e), [`bdaf73a`](https://github.com/TanStack/router/commit/bdaf73a4063ee2b02e3c9cc105ad10ce82a5a0ff)]: + - @tanstack/router-core@1.171.24 + +## 1.170.28 + +### Patch Changes + +- [#8055](https://github.com/TanStack/router/pull/8055) [`0c25a7b`](https://github.com/TanStack/router/commit/0c25a7b43b5331ee6ebf94d50e9793002783adab) - Avoid wrapping root components that may render the HTML document in a Suspense boundary during SSR and hydration. + +- [#8054](https://github.com/TanStack/router/pull/8054) [`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90) - Reuse resolved lazy route components when revisiting code-split routes, preventing unnecessary pending UI. + +- Updated dependencies [[`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90)]: + - @tanstack/router-core@1.171.23 + +## 1.170.27 + +### Patch Changes + +- [#8047](https://github.com/TanStack/router/pull/8047) [`b0817f5`](https://github.com/TanStack/router/commit/b0817f50cc639ae50b6c30cd11c5adbf7eed028c) - useMatchRoute w/ React Compiler + +## 1.170.26 + +### Patch Changes + +- [#8045](https://github.com/TanStack/router/pull/8045) [`f500760`](https://github.com/TanStack/router/commit/f5007607d62e932b8df19de866cdc6bddcff8db3) - Warn when an Outlet is rendered inside a pending, error, or not-found component. + +- [#8043](https://github.com/TanStack/router/pull/8043) [`1aafca9`](https://github.com/TanStack/router/commit/1aafca9b45d24f8f0dba78e716fc9582346c6ca1) - remove the undocumented Link `isTransitioning` state and `data-transitioning` attribute + +- [#8044](https://github.com/TanStack/router/pull/8044) [`aa10b65`](https://github.com/TanStack/router/commit/aa10b6589eeda215f5a60ea0af95a3101d8c414e) - Apply `preloadDelay` to viewport link preloading and cancel pending preloads when links leave the viewport. + +- Updated dependencies [[`7e93431`](https://github.com/TanStack/router/commit/7e93431ae9ff58c91c3c5ca10ffcb8414c1d0b13)]: + - @tanstack/router-core@1.171.22 + +## 1.170.25 + +### Patch Changes + +- Updated dependencies [[`51138a8`](https://github.com/TanStack/router/commit/51138a824cea053738f125c4c95073bd6286ff05)]: + - @tanstack/router-core@1.171.21 + +## 1.170.24 + +### Patch Changes + +- Updated dependencies [[`44a8c3e`](https://github.com/TanStack/router/commit/44a8c3e1d2af305064b2363d97fc7847c6f1a246), [`5253e70`](https://github.com/TanStack/router/commit/5253e70db2083d68a788fb7c9a043bb0c5518f2a)]: + - @tanstack/router-core@1.171.20 + +## 1.170.23 + +### Patch Changes + +- [#7952](https://github.com/TanStack/router/pull/7952) [`95dec51`](https://github.com/TanStack/router/commit/95dec51018d01483949c6f1fe3094b019ccf3b4f) - bail out of `Link` re-renders when the resolved href and active state are unchanged + +## 1.170.22 + +### Patch Changes + +- [#7992](https://github.com/TanStack/router/pull/7992) [`ea3a665`](https://github.com/TanStack/router/commit/ea3a665d81cbb5074c2d77ec953255ab534e7db9) - retain mounted UI during revalidation + +- Updated dependencies [[`ea3a665`](https://github.com/TanStack/router/commit/ea3a665d81cbb5074c2d77ec953255ab534e7db9)]: + - @tanstack/router-core@1.171.19 + +## 1.170.21 + +### Patch Changes + +- [#7961](https://github.com/TanStack/router/pull/7961) [`697ebb6`](https://github.com/TanStack/router/commit/697ebb6ddbd433d052b6b4707938a5c595865d58) - Prevent a blank frame before zero-delay initial pending UI by using a + component-scoped React transition for match publication. Pending timing, + boundary selection, and rendered matches continue to come from the router + core. + +- [#7970](https://github.com/TanStack/router/pull/7970) [`2435885`](https://github.com/TanStack/router/commit/2435885fa8b5e31c8c4b74d93920919f27316ebf) - createFileRoute does not rely on FileRoute class + +- [#7971](https://github.com/TanStack/router/pull/7971) [`86bf510`](https://github.com/TanStack/router/commit/86bf510c2923afb76804223bd04afc2a809b33e7) - clean intersection observer options in link component + +- [#7967](https://github.com/TanStack/router/pull/7967) [`6aefb33`](https://github.com/TanStack/router/commit/6aefb3392595a07a93f89301d7b5e3558ff9190c) - Preserve path params in their raw string form while matching routes so structured values returned by `params.parse` produce stable match IDs and do not reuse stale loader data. + + `RouterCore.getMatchedRoutes()` now returns `[matchedRoutes, rawParams, foundRoute]` instead of an object. + +- Updated dependencies [[`84db4a8`](https://github.com/TanStack/router/commit/84db4a842311df3f7e58073f6f12aaf371aeb5c7), [`9cac62a`](https://github.com/TanStack/router/commit/9cac62a5c7f99ef070991ea6f1fa7e42c746d46b), [`6aefb33`](https://github.com/TanStack/router/commit/6aefb3392595a07a93f89301d7b5e3558ff9190c)]: + - @tanstack/router-core@1.171.18 + - @tanstack/history@1.162.1 + +## 1.170.20 + +### Patch Changes + +- Updated dependencies [[`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5)]: + - @tanstack/router-core@1.171.17 + +## 1.170.19 + +### Patch Changes + +- [#7805](https://github.com/TanStack/router/pull/7805) [`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd) - Rewrite match loading around a lane-based scheduler that tracks each navigation, preload, and background reload as an ordered unit of work. This fixes pending/redirect/retry state leaking between overlapping navigations, restores correct SSR status codes for redirects, errors, and not-found responses, and closes hydration gaps where the client re-ran work the server had already completed. + - Invalidation now retires matching active preloads so older speculative loader results cannot become fresh cache data after invalidation. + - Route `headers()` now only runs on the server, matching the documented behavior — it is no longer invoked during client-side asset projection. + - The documented default `gcTime` and `preloadGcTime` now match the existing runtime default of 5 minutes (`300_000`). + + **Removed / changed exported internals** + - `RouterState` no longer includes `loadedAt`, `isTransitioning`, `statusCode`, or `redirect`. Use `match.updatedAt` in place of `loadedAt`; subscribe to `router.state.status` / `router.state.isLoading` in place of `isTransitioning`; server response status and redirect handling are now internal to the server loader and are no longer exposed on `router.state`. + - `RouteMatch.fetchCount` has been removed, with no replacement — it was purely informational. + - `RouteMatch.status` no longer includes `'redirected'` (it remains `'pending' | 'success' | 'error' | 'notFound'`) — redirected matches are dropped from the match list instead of being rendered. + - `RouteMatch.globalNotFound` has been renamed and privatized to the internal `_notFound` field. Use `match.status === 'notFound'` instead. + - The exported React, Solid, and Vue `Match` components now accept `routeId` instead of `matchId`. + - The exported `RouterStores` adapter contract now uses route-keyed presentation stores: `matchesId` is replaced by `ids`, `matchStores` by `byRoute`, and `getRouteMatchStore()` by `getMatchStore()`. The separate `loadedAt`, `isLoading`, `isTransitioning`, `statusCode`, and `redirect` stores have been removed, along with the pending/cache stores and their setters. `StoreConfig.init` has also been removed. Read application-facing state from `router.state`; preload and cache coordination are now internal. + - Removed `RouterCore` members `getMatch()`, `updateMatch()`, `cancelMatch()`, and `cancelMatches()` — read matches from `router.state.matches` (e.g. `router.state.matches.find((m) => m.id === id)`); there is no replacement for mutating or cancelling an individual in-flight match from outside the router. + - Removed `RouterCore.hasNotFoundMatch()` — use `router.state.matches.some((m) => m.status === 'notFound')`. + - Removed `RouterCore.looseRoutesById` — use `routesById`. + - Removed `RouterCore.isPrerendering()`, `RouterCore.isViewTransitionTypesSupported`, and `RouterCore.viewTransitionPromise`, with no replacement. + - Removed `RouterCore.getParsedLocationHref()` and `RouterCore.clearExpiredCache()`, with no replacement — expired cache entries are now reconciled automatically as part of match commit. + - Removed `RouterCore.latestLoadPromise` and `RouterCore.beforeLoad()`, with no replacement. + - `RouterCore.commitLocationPromise` and `RouterCore.pendingBuiltLocation` have been replaced by the internal `_commitPromise` and `_pendingLocation` fields. + - Removed the exported `GetMatchFn` and `UpdateMatchFn` types, along with the methods they typed. + - Removed the standalone `getMatchedRoutes()` export from `@tanstack/router-core` — use the `router.getMatchedRoutes()` instance method instead. + - `RouterCore.loadRouteChunk()` no longer accepts an array of component types as its second argument. One-argument usage is unchanged; the optional second argument is now `'errorComponent'`, `'notFoundComponent'`, or `false` for internal boundary loading. + - Removed `Redirect.redirectHandled`, which was internal redirect bookkeeping. + - `MatchRoutesOpts.preload` and `MatchRoutesOpts.dest` have been removed. + - `StartTransitionFn` is now `(fn, expected) => Promise` (previously `(fn) => void`). This only affects custom framework adapters that implement `startTransition`. + +- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: + - @tanstack/router-core@1.171.16 + +## 1.170.18 + +### Patch Changes + +- Updated dependencies [[`e2dd204`](https://github.com/TanStack/router/commit/e2dd2049cb42eb219d3b447b8605066d19d9c1fa)]: + - @tanstack/router-core@1.171.15 + +## 1.170.17 + +### Patch Changes + +- Updated dependencies [[`9809a06`](https://github.com/TanStack/router/commit/9809a0619d4ed3fe8c2a393af5b9eca4b6c7695b)]: + - @tanstack/router-core@1.171.14 + +## 1.170.16 + +### Patch Changes + +- [#7595](https://github.com/TanStack/router/pull/7595) [`52db703`](https://github.com/TanStack/router/commit/52db7034fd83b17cc45da9ba775ec253f2a9a149) - Perf improvement of useMatch and derived hooks when navigating away from previous match + +- [#7575](https://github.com/TanStack/router/pull/7575) [`4a93cff`](https://github.com/TanStack/router/commit/4a93cffffca34702e419bc47db827f964fd0cb65) - useMatches can skip useRef for structural sharing during SSR + +- [#7600](https://github.com/TanStack/router/pull/7600) [`f046b06`](https://github.com/TanStack/router/commit/f046b064d32222cad0b7ea061311ca9a474f5990) - Reduce Match rerenders during navigations (PR [#7596](https://github.com/TanStack/router/issues/7596)) + +- [#7577](https://github.com/TanStack/router/pull/7577) [`689d88e`](https://github.com/TanStack/router/commit/689d88e04c48ec76a18453ab8b82d8d58f2668b6) - Reduce bundle size by sharing structuralSharing selector logic + +- [#7627](https://github.com/TanStack/router/pull/7627) [`689c5ab`](https://github.com/TanStack/router/commit/689c5ab32e9bb18d90a5a94c33237b0e418df3e3) - Silence AbortError in renderRouterToStream, this is normal operation + +## 1.170.15 + +### Patch Changes + +- Updated dependencies [[`776d8ef`](https://github.com/TanStack/router/commit/776d8ef283e5bd9ffe97d43bc3a7f58064cd7e03)]: + - @tanstack/router-core@1.171.13 + +## 1.170.14 + +### Patch Changes + +- Updated dependencies [[`df1076c`](https://github.com/TanStack/router/commit/df1076c03ae5a51ab384bebd4d6afda20fb6f107)]: + - @tanstack/router-core@1.171.12 + +## 1.170.13 + +### Patch Changes + +- [#7555](https://github.com/TanStack/router/pull/7555) [`ac10815`](https://github.com/TanStack/router/commit/ac10815f387d25b15163ff711b4049e8f8482d01) - Fix search middleware composition so `retainSearchParams` does not restore search params that a downstream `stripSearchParams` removed. + +- Updated dependencies [[`ac10815`](https://github.com/TanStack/router/commit/ac10815f387d25b15163ff711b4049e8f8482d01)]: + - @tanstack/router-core@1.171.11 + +## 1.170.12 + +### Patch Changes + +- Updated dependencies [[`2cca73c`](https://github.com/TanStack/router/commit/2cca73c92262ffd96dac4e283c9f69fb37f4b43a), [`7a83e67`](https://github.com/TanStack/router/commit/7a83e67e6596fbef21cb0a88a7127f5935bed2ba), [`76b3d3b`](https://github.com/TanStack/router/commit/76b3d3b24522bd3d1d216674c441252c9b8f184c)]: + - @tanstack/router-core@1.171.10 + +## 1.170.11 + +### Patch Changes + +- Updated dependencies [[`b4cd5af`](https://github.com/TanStack/router/commit/b4cd5af8d0f9d4aaa2d29095e6a261b9181bc778)]: + - @tanstack/router-core@1.171.9 + +## 1.170.10 + +### Patch Changes + +- [#7505](https://github.com/TanStack/router/pull/7505) [`2f53749`](https://github.com/TanStack/router/commit/2f5374945e2138559a51464f45a5152eae67e1dd) - Preserve primitive values thrown from beforeLoad error handling. + +- Updated dependencies [[`2f53749`](https://github.com/TanStack/router/commit/2f5374945e2138559a51464f45a5152eae67e1dd)]: + - @tanstack/router-core@1.171.8 + +## 1.170.9 + +### Patch Changes + +- [#7497](https://github.com/TanStack/router/pull/7497) [`d1997b6`](https://github.com/TanStack/router/commit/d1997b66d7c24c1d64772bb8bab5caf9c6d9cc48) - fix streaming + +- Updated dependencies [[`d1997b6`](https://github.com/TanStack/router/commit/d1997b66d7c24c1d64772bb8bab5caf9c6d9cc48)]: + - @tanstack/router-core@1.171.7 + +## 1.170.8 + +### Patch Changes + +- Add support for Rsbuild client output formats, including module output by default and IIFE output for classic script environments. ([#7477](https://github.com/TanStack/router/pull/7477)) + + Client entry scripts and preloads are now represented as root route manifest assets, script preloads follow the manifest script format, and script asset cross-origin configuration uses the `script` key. The `transformAssets` script callback context now exposes only `kind: 'script'` and `url`, keeping script format handling internal to manifest rendering. + +- Updated dependencies [[`51a97a1`](https://github.com/TanStack/router/commit/51a97a167fb3ef1b8ca70fbb63db635158f43509)]: + - @tanstack/router-core@1.171.6 + +## 1.170.7 + +### Patch Changes + +- Updated dependencies [[`5268ba4`](https://github.com/TanStack/router/commit/5268ba4566233ea58880df85f167ad0401a93a46)]: + - @tanstack/router-core@1.171.5 + +## 1.170.6 + +### Patch Changes + +- Fix hash navigation being overridden by stale scroll restoration entries. ([#7447](https://github.com/TanStack/router/pull/7447)) + +- Updated dependencies [[`0300f87`](https://github.com/TanStack/router/commit/0300f87ec5a7f878ffbe0b181acf84cba9139960), [`0300f87`](https://github.com/TanStack/router/commit/0300f87ec5a7f878ffbe0b181acf84cba9139960)]: + - @tanstack/router-core@1.171.4 + +## 1.170.5 + +### Patch Changes + +- Updated dependencies [[`5fa9e55`](https://github.com/TanStack/router/commit/5fa9e555f3a2edb5e45586623e6bcbfa7f7c7a6b)]: + - @tanstack/router-core@1.171.3 + +## 1.170.4 + +### Patch Changes + +- Updated dependencies [[`b60eb36`](https://github.com/TanStack/router/commit/b60eb36e59e8a468ee0742cbcf7f47aca1ff1c67)]: + - @tanstack/router-core@1.171.2 + +## 1.170.3 + +### Patch Changes + +- Updated dependencies [[`d9cf933`](https://github.com/TanStack/router/commit/d9cf9331b83fcbd2abfee75d839d862f9bb18e6b)]: + - @tanstack/router-core@1.171.1 + +## 1.170.2 + +### Patch Changes + +- Updated dependencies [[`d533f87`](https://github.com/TanStack/router/commit/d533f87976704098a40b48f160b37c28c8182806)]: + - @tanstack/router-core@1.171.0 + +## 1.170.1 + +### Patch Changes + +- Updated dependencies [[`2387a2e`](https://github.com/TanStack/router/commit/2387a2eea0683004cc400b9f71bed5944eb60110)]: + - @tanstack/router-core@1.170.1 + +## 1.170.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +### Patch Changes + +- Updated dependencies [[`b1c061a`](https://github.com/TanStack/router/commit/b1c061aff9185cdf5fdc08c0136382a9dce0302f), [`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14)]: + - @tanstack/router-core@1.170.0 + - @tanstack/history@1.162.0 + +## 1.169.2 + +### Patch Changes + +- Updated dependencies [[`35e88f0`](https://github.com/TanStack/router/commit/35e88f04996d71019a1868b7b06ecb4ddbc9df9e)]: + - @tanstack/router-core@1.169.2 + +## 1.169.1 + +### Patch Changes + +- Updated dependencies [[`4a1e63f`](https://github.com/TanStack/router/commit/4a1e63f1d1230b1ed8234609acad4639d8982c13)]: + - @tanstack/router-core@1.169.1 + +## 1.169.0 + +### Minor Changes + +- Allow `params.parse` to experimentally return `false` to skip an incoming route candidate during path matching. Thrown parse errors still surface on the selected match instead of falling through, and outgoing typed route-template links continue to use exact route lookup followed by `params.stringify` for URL generation. ([#7263](https://github.com/TanStack/router/pull/7263)) + +### Patch Changes + +- Updated dependencies [[`c992495`](https://github.com/TanStack/router/commit/c992495bf4010ff4c3597bb1f3b1ba02594e857e)]: + - @tanstack/router-core@1.169.0 + +## 1.168.26 + +### Patch Changes + +- Updated dependencies [[`b5c4183`](https://github.com/TanStack/router/commit/b5c4183ab8b44be8a75647b7f7b588ad7c146ece)]: + - @tanstack/router-core@1.168.18 + +## 1.168.25 + +### Patch Changes + +- Updated dependencies [[`493148b`](https://github.com/TanStack/router/commit/493148bc5378b7f9de1544d87f6aaa425c12eb34)]: + - @tanstack/router-core@1.168.17 + +## 1.168.24 + +### Patch Changes + +- Add TanStack Start inline CSS manifest support for SSR so route styles can be embedded in the HTML response and hydrated without duplicate stylesheet links. ([#7253](https://github.com/TanStack/router/pull/7253)) + +- Updated dependencies [[`4d864ee`](https://github.com/TanStack/router/commit/4d864eebbd184265eabb563d326ab409c93feb17)]: + - @tanstack/router-core@1.168.16 + +## 1.168.23 + +### Patch Changes + +- fix(react-router): prevent webpack static analysis of `React.use` with let binding ([#7182](https://github.com/TanStack/router/pull/7182)) + +## 1.168.22 + +### Patch Changes + +- Preserve shared route stylesheet links across client navigation by rendering route CSS assets with React stylesheet precedence. ([#7186](https://github.com/TanStack/router/pull/7186)) + +## 1.168.21 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + +## 1.168.20 + +### Patch Changes + +- Fix React Server Component imports from `@tanstack/react-router` by adding a `react-server` root export that preserves the normal API surface while resolving `notFound` and `redirect` from a server-safe entry. ([#7183](https://github.com/TanStack/router/pull/7183)) + + This fixes RSC routes that throw `notFound()` or `redirect()` from server functions so they behave correctly during SSR and client navigation. + +## 1.168.19 + +### Patch Changes + +- Fix route file transforms to preserve route ID quoting, handle more exported `Route` patterns, and avoid incorrect import rewrites in edge cases. ([#7167](https://github.com/TanStack/router/pull/7167)) + + Improve transform robustness with clearer route-call detection, safer import removal, and expanded test coverage for quote preservation, constructor swaps, and unsupported route definitions. + +## 1.168.18 + +### Patch Changes + +- Updated dependencies [[`0e2c900`](https://github.com/TanStack/router/commit/0e2c9003c18ae07c09969189c028f277ea562a7a)]: + - @tanstack/router-core@1.168.14 + +## 1.168.17 + +### Patch Changes + +- Updated dependencies [[`812792f`](https://github.com/TanStack/router/commit/812792fbda3caf97b300770855cf5641252f413b)]: + - @tanstack/router-core@1.168.13 + +## 1.168.16 + +### Patch Changes + +- Updated dependencies [[`8ec9ca9`](https://github.com/TanStack/router/commit/8ec9ca97b472779de878c2a6510f21deb24d386c)]: + - @tanstack/router-core@1.168.12 + +## 1.168.15 + +### Patch Changes + +- shorten internal non-minifiable store names for byte shaving ([#7152](https://github.com/TanStack/router/pull/7152)) + +- Updated dependencies [[`6355bb7`](https://github.com/TanStack/router/commit/6355bb75f7637ba77f06a923c18fdaf37720bb48)]: + - @tanstack/router-core@1.168.11 + +## 1.168.14 + +### Patch Changes + +- migrate createStore > createAtom for simpler API ([#7150](https://github.com/TanStack/router/pull/7150)) + +- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: + - @tanstack/router-core@1.168.10 + +## 1.168.13 + +### Patch Changes + +- Fix `MatchRoute` child callback param inference to resolve params from the target `to` route instead of the route path key across React, Solid, and Vue adapters. ([#7139](https://github.com/TanStack/router/pull/7139)) + +- Fix a stale route error boundary state issue that could briefly render the next route's `errorComponent` after navigating away from a failed route. ([#7136](https://github.com/TanStack/router/pull/7136)) + +## 1.168.12 + +### Patch Changes + +- Fix redirected pending route transitions so lazy target routes can finish loading without stale redirected matches causing render errors. ([#7137](https://github.com/TanStack/router/pull/7137)) + +## 1.168.11 + +### Patch Changes + +- Fix `Link` to keep internal routing props like `preloadIntentProximity`, `from`, and `unsafeRelative` from leaking to rendered DOM elements across React, Solid, and Vue. ([#7138](https://github.com/TanStack/router/pull/7138)) + +## 1.168.10 + +### Patch Changes + +- Preserve component-thrown `notFound()` errors through framework error boundaries so route `notFoundComponent` handlers render without requiring an explicit `routeId`. ([#7077](https://github.com/TanStack/router/pull/7077)) + +- Updated dependencies [[`796406d`](https://github.com/TanStack/router/commit/796406da66cfb12b518bb3ca326c9d541368fb06)]: + - @tanstack/router-core@1.168.9 + +## 1.168.9 + +### Patch Changes + +- Updated dependencies [[`2d1ec86`](https://github.com/TanStack/router/commit/2d1ec865a446926f7db6e29dbbde82d265de6d36)]: + - @tanstack/router-core@1.168.8 + +## 1.168.8 + +### Patch Changes + +- Updated dependencies [[`6ee0e79`](https://github.com/TanStack/router/commit/6ee0e795b085651beb2f1ac6503cdbd7eaffedd1)]: + - @tanstack/router-core@1.168.7 + +## 1.168.7 + +### Patch Changes + +- Updated dependencies [[`42c3f3b`](https://github.com/TanStack/router/commit/42c3f3b3a3a478fd6d6894310ef94b2d23794b8e)]: + - @tanstack/router-core@1.168.6 + +## 1.168.6 + +### Patch Changes + +- Remove the extra SSR sentinel tag used for `onRendered` in React Router while ([#7054](https://github.com/TanStack/router/pull/7054)) + preserving the client-side render timing needed for scroll restoration and + `onRendered` subscribers. + +## 1.168.5 + +### Patch Changes + +- fix: scroll restoration without throttling ([#7042](https://github.com/TanStack/router/pull/7042)) + +- Updated dependencies [[`cf5f554`](https://github.com/TanStack/router/commit/cf5f5542476137a81515099ad740747e84512f9a)]: + - @tanstack/router-core@1.168.5 + +## 1.168.4 + +### Patch Changes + +- tanstack/store 0.9.3 ([#7041](https://github.com/TanStack/router/pull/7041)) + +- Updated dependencies [[`71a8b68`](https://github.com/TanStack/router/commit/71a8b684c87c37fd4a033d99f5ba4a05c7a179f5)]: + - @tanstack/router-core@1.168.4 + +## 1.168.3 + +### Patch Changes + +- feat: transformAssets ([#7023](https://github.com/TanStack/router/pull/7023)) + +- Updated dependencies [[`d81d21a`](https://github.com/TanStack/router/commit/d81d21ad05c9401bf54b24acd29401e1e4fd624c)]: + - @tanstack/router-core@1.168.3 + +## 1.168.2 + +### Patch Changes + +- Replace tiny-invariant and tiny-warning with in-house solution for bundle-size ([#7007](https://github.com/TanStack/router/pull/7007)) + +- Updated dependencies [[`c9e1855`](https://github.com/TanStack/router/commit/c9e18555f3a5531e96de8f574cfca9edcdb18e5c)]: + - @tanstack/router-core@1.168.2 + +## 1.168.1 + +### Patch Changes + +- Update store to 0.9.2 ([#6993](https://github.com/TanStack/router/pull/6993)) + +- Updated dependencies [[`91cc628`](https://github.com/TanStack/router/commit/91cc62899b75ca920fe83c5ee7f3dbb5c71a523f)]: + - @tanstack/router-core@1.168.1 + +## 1.168.0 + +### Minor Changes + +- remove pendingMatches, cachedMatches ([#6704](https://github.com/TanStack/router/pull/6704)) + move to signal-based reactivity + solid uses its own native signals + +### Patch Changes + +- Updated dependencies [[`0545239`](https://github.com/TanStack/router/commit/054523900b2ee19308e5a88417dadfc6923afe30)]: + - @tanstack/router-core@1.168.0 + +## 1.167.5 + +### Patch Changes + +- Updated dependencies [[`5ff4f0b`](https://github.com/TanStack/router/commit/5ff4f0b8dce1fac2bb0b0bfe2684fc677a8ee505)]: + - @tanstack/router-core@1.167.5 + +## 1.167.4 + +### Patch Changes + +- Add @tanstack/intent AI agent skills and CLI entry points for Router and Start packages ([#6866](https://github.com/TanStack/router/pull/6866)) + +- Updated dependencies [[`940151c`](https://github.com/TanStack/router/commit/940151cbed0c76c92a5cf196c0905b17a956ca7e)]: + - @tanstack/router-core@1.167.4 + +## 1.167.3 + +### Patch Changes + +- Updated dependencies [[`32fcba7`](https://github.com/TanStack/router/commit/32fcba7b044b03f5901308b870f70b0b4910c220)]: + - @tanstack/router-core@1.167.3 + +## 1.167.2 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +- Updated dependencies [[`838b0eb`](https://github.com/TanStack/router/commit/838b0eb9a8bbbb987a0a6972c1446e01423bbd7b)]: + - @tanstack/history@1.161.6 + - @tanstack/router-core@1.167.2 + +## 1.167.1 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) + +- Updated dependencies [[`ef9b241`](https://github.com/TanStack/router/commit/ef9b241f3cfe95cee40daa96da669f0ffd4a971a)]: + - @tanstack/router-core@1.167.1 + - @tanstack/history@1.161.5 + +## 1.167.0 + +### Minor Changes + +- feat: add staleReloadMode ([#6921](https://github.com/TanStack/router/pull/6921)) + +### Patch Changes + +- Updated dependencies [[`6f297a2`](https://github.com/TanStack/router/commit/6f297a249424c0fd1c1a56aa4fc12c8217be7b6a)]: + - @tanstack/router-core@1.167.0 + +## 1.166.8 + +### Patch Changes + +- fix: hoist inline component definitions for proper React HMR#6919 ([#6919](https://github.com/TanStack/router/pull/6919)) diff --git a/packages/react-router/README.md b/packages/react-router/README.md index 1cc3471e0a..c3a60d1008 100644 --- a/packages/react-router/README.md +++ b/packages/react-router/README.md @@ -2,7 +2,21 @@ # TanStack React Router -![TanStack Router Header](https://github.com/tanstack/router/raw/main/media/header_router.png) + + + + TanStack React Router + 🤖 Type-safe router w/ built-in caching & URL state management for React! @@ -16,9 +30,9 @@ semantic-release - + Join the discussion on Github -Best of JS +Best of JS @@ -26,6 +40,6 @@ -Enjoy this library? Try the entire [TanStack](https://tanstack.com)! [React Query](https://github.com/tannerlinsley/react-query), [React Table](https://github.com/tanstack/react-table), [React Charts](https://github.com/tannerlinsley/react-charts), [React Virtual](https://github.com/tannerlinsley/react-virtual) +Enjoy this library? Try the entire [TanStack](https://tanstack.com)! [React Query](https://github.com/TanStack/query), [React Table](https://github.com/TanStack/table), [React Charts](https://github.com/TanStack/react-charts), [React Virtual](https://github.com/TanStack/virtual) ## Visit [tanstack.com/router](https://tanstack.com/router) for docs, guides, API and more! diff --git a/packages/react-router/eslint.config.ts b/packages/react-router/eslint.config.ts index 5d879181f7..e5f4ab4120 100644 --- a/packages/react-router/eslint.config.ts +++ b/packages/react-router/eslint.config.ts @@ -2,9 +2,13 @@ import pluginReact from '@eslint-react/eslint-plugin' // @ts-expect-error import pluginReactHooks from 'eslint-plugin-react-hooks' import rootConfig from '../../eslint.config.js' +import type { Linter } from 'eslint' export default [ ...rootConfig, + { + ignores: ['bin/**'], + }, { files: ['src/**/*.{ts,tsx}', 'tests/**/*.{ts,tsx}'], }, @@ -22,4 +26,4 @@ export default [ '@typescript-eslint/no-unnecessary-condition': 'off', }, }, -] +] as Array diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 9abcfae246..9a61d5af25 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router", - "version": "1.141.8", + "version": "1.170.46", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -27,20 +27,18 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js -p tsconfig.legacy.json", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js -p tsconfig.legacy.json", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js -p tsconfig.legacy.json", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js -p tsconfig.legacy.json", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js -p tsconfig.legacy.json", - "test:types:ts59": "tsc -p tsconfig.legacy.json", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js -p tsconfig.legacy.json", + "test:types:ts60": "tsc6 -p tsconfig.legacy.json", + "test:types:ts70": "tsc -p tsconfig.legacy.json", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch --hideSkippedTests", "test:perf": "vitest bench", "test:perf:dev": "pnpm run test:perf --watch --hideSkippedTests", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", - "build": "pnpm run build:lib && pnpm run build:llm", - "build:lib": "vite build", - "build:llm": "node ../../scripts/llms-generate.mjs react-router && tsc -p ./llms/tsconfig.json" + "build": "vite build" }, "type": "module", "types": "dist/esm/index.d.ts", @@ -48,12 +46,18 @@ "module": "dist/esm/index.js", "exports": { ".": { + "react-server": { + "types": "./dist/esm/index.rsc.d.ts", + "default": "./dist/esm/index.rsc.js" + }, "import": { "types": "./dist/esm/index.d.ts", + "development": "./dist/esm/index.dev.js", "default": "./dist/esm/index.js" }, "require": { "types": "./dist/cjs/index.d.cts", + "development": "./dist/cjs/index.dev.cjs", "default": "./dist/cjs/index.cjs" } }, @@ -77,39 +81,45 @@ "default": "./dist/cjs/ssr/client.cjs" } }, - "./package.json": "./package.json", - "./llms": { - "import": { - "types": "./dist/llms/index.d.ts", - "default": "./dist/llms/index.js" - } - } + "./package.json": "./package.json" }, "sideEffects": false, "files": [ "dist", - "src" + "src", + "skills", + "!skills/_artifacts" ], "engines": { - "node": ">=12" + "node": ">=20.19" }, "dependencies": { "@tanstack/history": "workspace:*", - "@tanstack/react-store": "^0.8.0", + "@tanstack/react-store": "^0.11.2", "@tanstack/router-core": "workspace:*", - "isbot": "^5.1.22", - "tiny-invariant": "^1.3.3", - "tiny-warning": "^1.0.3" + "isbot": "catalog:" }, "devDependencies": { - "@testing-library/jest-dom": "^6.6.3", - "@testing-library/react": "^16.2.0", - "@vitejs/plugin-react": "^4.3.4", - "combinate": "^1.1.11", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "vibe-rules": "^0.2.57", - "zod": "^3.24.2" + "@testing-library/jest-dom": "catalog:", + "@testing-library/react": "catalog:", + "@tanstack/react-query": "catalog:", + "@types/node": ">=20", + "@vitejs/plugin-react": "catalog:", + "combinate": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", + "vite": "*", + "zod": "catalog:", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@eslint-react/eslint-plugin": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", diff --git a/packages/react-router/skills/compositions/router-query/SKILL.md b/packages/react-router/skills/compositions/router-query/SKILL.md new file mode 100644 index 0000000000..4fdd74fc30 --- /dev/null +++ b/packages/react-router/skills/compositions/router-query/SKILL.md @@ -0,0 +1,441 @@ +--- +name: router-query +description: >- + Integrating TanStack Router with TanStack Query: queryClient + in router context, static queries and fire-and-forget queries in loaders, + useSuspenseQuery in components, defaultPreloadStaleTime: 0, + setupRouterSsrQueryIntegration for SSR dehydration/hydration + and streaming, per-request QueryClient isolation. +metadata: + type: composition + library: tanstack-router + library_version: '1.166.2' +requires: + - router-core + - router-core/data-loading + - react-router +sources: + - TanStack/router:docs/router/guide/external-data-loading.md + - TanStack/router:docs/router/integrations/query.md +--- + +# TanStack Router + TanStack Query Integration + +This skill requires familiarity with both TanStack Router and TanStack Query. Read `@tanstack/router-core#router-core` and [react-router](../../react-router/SKILL.md) first. + +This skill covers coordinating TanStack Query as an external data cache with TanStack Router's loader system. The router acts as a **coordinator** — it triggers data fetching during navigation, while Query manages caching, background refetching, and data lifecycle. + +> **CRITICAL**: Set `defaultPreloadStaleTime: 0` when using TanStack Query. Without this, Router's built-in preload cache (30s default) prevents Query from controlling data freshness. + +> **CRITICAL**: For SSR, create `QueryClient` inside the `createRouter` factory function. A module-level singleton leaks data between server requests. + +## Setup: QueryClient in Router Context + +### Basic (Client-Only) + +```tsx +// src/main.tsx +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { + RouterProvider, + createRouter, + createRootRouteWithContext, +} from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +// Root route declares that router context includes queryClient +// (root route file creates it with createRootRouteWithContext — see below) + +const queryClient = new QueryClient() + +const router = createRouter({ + routeTree, + defaultPreloadStaleTime: 0, // Let Query manage caching + context: { queryClient }, + Wrap: ({ children }) => ( + {children} + ), +}) + +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +function App() { + return +} +``` + +### Root Route with Context + +```tsx +// src/routes/__root.tsx +import { createRootRouteWithContext, Outlet } from '@tanstack/react-router' +import type { QueryClient } from '@tanstack/react-query' + +// Double parentheses: factory pattern +export const Route = createRootRouteWithContext<{ + queryClient: QueryClient +}>()({ + component: () => , +}) +``` + +### SSR-Safe Setup + +```tsx +// src/router.tsx +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function createAppRouter() { + // Fresh QueryClient per request — prevents data leaking between SSR requests + const queryClient = new QueryClient() + + return createRouter({ + routeTree, + defaultPreloadStaleTime: 0, + context: { queryClient }, + Wrap: ({ children }) => ( + {children} + ), + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} +``` + +### SSR with `setupRouterSsrQueryIntegration` + +For automatic SSR dehydration/hydration and streaming: + +```bash +npm install @tanstack/react-router-ssr-query +``` + +```tsx +// src/router.tsx +import { QueryClient } from '@tanstack/react-query' +import { createRouter } from '@tanstack/react-router' +import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query' +import { routeTree } from './routeTree.gen' + +export function createAppRouter() { + const queryClient = new QueryClient() + + const router = createRouter({ + routeTree, + defaultPreloadStaleTime: 0, + context: { queryClient }, + }) + + setupRouterSsrQueryIntegration({ + router, + queryClient, + // wrapQueryClient: true (default — wraps with QueryClientProvider) + // handleRedirects: true (default — handles redirect() from queries) + }) + + return router +} +``` + +The integration: + +- Dehydrates query state on the server and hydrates on the client automatically +- Streams queries that resolve during server render to the client +- Handles `redirect()` thrown from queries/mutations + +### Manual SSR Dehydration/Hydration (Without SSR Query Package) + +```tsx +// src/router.tsx +import { QueryClient, dehydrate, hydrate } from '@tanstack/react-query' +import { QueryClientProvider } from '@tanstack/react-query' +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function createAppRouter() { + const queryClient = new QueryClient() + + return createRouter({ + routeTree, + defaultPreloadStaleTime: 0, + context: { queryClient }, + dehydrate: () => ({ + queryClientState: dehydrate(queryClient), + }), + hydrate: (dehydrated) => { + hydrate(queryClient, dehydrated.queryClientState) + }, + Wrap: ({ children }) => ( + {children} + ), + }) +} +``` + +## Core Pattern: Static `query` in Loader + `useSuspenseQuery` in Component + +This is the recommended pattern. The loader queries data before render (no loading flash), using `staleTime: 'static'` to reuse cached data without a stale refetch. The component subscribes to the cache for updates. + +```tsx +// src/routes/posts.tsx +import { queryOptions, useSuspenseQuery } from '@tanstack/react-query' +import { createFileRoute } from '@tanstack/react-router' + +interface Post { + id: string + title: string +} + +const postsQueryOptions = queryOptions({ + queryKey: ['posts'], + queryFn: (): Promise> => + fetch('/api/posts').then((r) => r.json()), +}) + +export const Route = createFileRoute('/posts')({ + loader: ({ context }) => { + // query returns cached data when available and fetches when it is missing + // Keep this query static so a stale refetch does not block navigation + return context.queryClient.query({ + ...postsQueryOptions, + staleTime: 'static', + }) + }, + component: PostsPage, +}) + +function PostsPage() { + // useSuspenseQuery subscribes to cache — gets background updates + const { data: posts } = useSuspenseQuery(postsQueryOptions) + + return ( +
      + {posts.map((post) => ( +
    • {post.title}
    • + ))} +
    + ) +} +``` + +### With Dynamic Params + +```tsx +// src/routes/posts/$postId.tsx +import { queryOptions, useSuspenseQuery } from '@tanstack/react-query' +import { createFileRoute } from '@tanstack/react-router' + +interface Post { + id: string + title: string + content: string +} + +const postQueryOptions = (postId: string) => + queryOptions({ + queryKey: ['posts', postId], + queryFn: () => fetch(`/api/posts/${postId}`).then((r) => r.json()), + }) + +export const Route = createFileRoute('/posts/$postId')({ + loader: ({ context, params }) => { + return context.queryClient.query({ + ...postQueryOptions(params.postId), + staleTime: 'static', + }) + }, + component: PostPage, +}) + +function PostPage() { + const { postId } = Route.useParams() + const { data: post } = useSuspenseQuery(postQueryOptions(postId)) + + return
    {post.title}
    +} +``` + +## Streaming Pattern: Fire-and-Forget `query` (Not Awaited) + +For non-critical data, start a query without blocking navigation. Handle its rejection with `noop` so a background failure does not become an unhandled rejection: + +```tsx +import { noop, useQuery, useSuspenseQuery } from '@tanstack/react-query' + +export const Route = createFileRoute('/dashboard')({ + loader: ({ context }) => { + // Await critical data + const user = context.queryClient.query({ + ...userQueryOptions, + staleTime: 'static', + }) + + // Start non-critical query without awaiting — streams during SSR + void context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) + + return user + }, + component: Dashboard, +}) + +function Dashboard() { + // Critical: suspense (data ready immediately) + const { data: user } = useSuspenseQuery(userQueryOptions) + + // Non-critical: regular query (shows loading state) + const { data: analytics, isLoading } = useQuery(analyticsQueryOptions) + + return ( +
    +

    Welcome {user.name}

    + {isLoading ? : } +
    + ) +} +``` + +## Error Handling with `useQueryErrorResetBoundary` + +```tsx +import { useEffect } from 'react' +import { useQueryErrorResetBoundary } from '@tanstack/react-query' +import { useRouter } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts')({ + loader: ({ context }) => + context.queryClient.query({ + ...postsQueryOptions, + staleTime: 'static', + }), + errorComponent: PostsErrorComponent, + component: PostsPage, +}) + +function PostsErrorComponent({ + error, + reset, +}: { + error: unknown + reset: () => void +}) { + const router = useRouter() + const queryErrorResetBoundary = useQueryErrorResetBoundary() + + useEffect(() => { + queryErrorResetBoundary.reset() + }, [queryErrorResetBoundary]) + + return ( +
    +

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

    + +
    + ) +} +``` + +## Common Mistakes + +### 1. HIGH: Not setting `defaultPreloadStaleTime` to 0 + +Router has a built-in preload cache (default `staleTime` for preloads is 30s). This prevents Query from controlling data freshness during preloading. + +```tsx +// WRONG — Router's preload cache serves stale data, Query never refetches +const router = createRouter({ routeTree }) + +// CORRECT — disable Router's preload cache, let Query manage freshness +const router = createRouter({ + routeTree, + defaultPreloadStaleTime: 0, +}) +``` + +### 2. HIGH: Creating QueryClient outside `createRouter` for SSR + +A module-level singleton `QueryClient` is shared across all server requests, leaking user data between requests. + +```tsx +// WRONG — shared across SSR requests +const queryClient = new QueryClient() +export function createAppRouter() { + return createRouter({ + routeTree, + context: { queryClient }, + }) +} + +// CORRECT — new QueryClient per createAppRouter call +export function createAppRouter() { + const queryClient = new QueryClient() + return createRouter({ + routeTree, + context: { queryClient }, + }) +} +``` + +### 3. MEDIUM: Awaiting a fire-and-forget query in a loader blocks rendering + +A query used for streaming should start in the background and handle errors with `catch(noop)`. Awaiting it blocks the navigation transition until the data resolves, defeating the purpose of streaming. + +```tsx +import { noop } from '@tanstack/react-query' + +// WRONG — blocks navigation, no streaming benefit +loader: async ({ context }) => { + await context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) +} + +// CORRECT — fire and forget for streaming, with handled rejection +loader: ({ context }) => { + void context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) +} + +// If you need to block (critical data), use a static query instead: +loader: ({ context }) => { + return context.queryClient.query({ + ...criticalQueryOptions, + staleTime: 'static', + }) +} +``` + +### 4. HIGH: Missing double parentheses on `createRootRouteWithContext` + +`createRootRouteWithContext()` is a factory — it returns a function. The second call passes route options. + +```tsx +// WRONG — passing options to the factory, not the returned function +const rootRoute = createRootRouteWithContext<{ queryClient: QueryClient }>({ + component: RootComponent, +}) + +// CORRECT — double call: factory()({options}) +const rootRoute = createRootRouteWithContext<{ queryClient: QueryClient }>()({ + component: RootComponent, +}) +``` + +## Tension: Built-In SWR Cache vs External Cache + +TanStack Router has its own SWR cache (`staleTime`, `gcTime`, `defaultPreloadStaleTime`). When using Query as an external cache: + +- Set `defaultPreloadStaleTime: 0` to prevent Router's cache from short-circuiting Query's freshness logic +- Router's `staleTime`/`gcTime` still apply to the loader return value. For pure Query patterns, return nothing from the loader (just a static `query` for the side effect) and read data exclusively from `useSuspenseQuery` +- `router.invalidate()` re-runs loaders (which call `query` with `staleTime: 'static'`), so the cached Query data remains the freshness authority + +## Cross-References + +- `@tanstack/router-core#router-core/data-loading` — built-in loader caching fundamentals +- `@tanstack/router-core#router-core/ssr` — SSR setup for dehydration/hydration diff --git a/packages/react-router/skills/lifecycle/migrate-from-react-router/SKILL.md b/packages/react-router/skills/lifecycle/migrate-from-react-router/SKILL.md new file mode 100644 index 0000000000..fdc4f4c4e5 --- /dev/null +++ b/packages/react-router/skills/lifecycle/migrate-from-react-router/SKILL.md @@ -0,0 +1,489 @@ +--- +name: migrate-from-react-router +description: >- + Step-by-step migration from React Router v7 to TanStack Router: + route definition conversion, Link/useNavigate API differences, + useSearchParams to validateSearch + useSearch, useParams with from, + Outlet replacement, loader conversion, code splitting differences. +metadata: + type: lifecycle + library: tanstack-router + library_version: '1.166.2' +requires: + - router-core + - react-router +sources: + - TanStack/router:docs/router/how-to/migrate-from-react-router.md + - TanStack/router:docs/router/installation/migrate-from-react-router.md +--- + +# Migrate from React Router v7 to TanStack Router + +This is a step-by-step migration checklist. Each check covers one conversion task. Complete them in order. + +> **CRITICAL**: If your UI is blank after migration, open the console. Errors like "cannot use useNavigate outside of context" mean React Router imports remain alongside TanStack Router imports. Uninstall `react-router` (and `react-router-dom` if present) to surface them as TypeScript errors. +> +> **CRITICAL**: TanStack Router uses `to` + `params` for navigation, NOT template literal paths. Never interpolate params into the `to` string. +> +> **NOTE**: React Router v7 recommends importing from `react-router` (not `react-router-dom`). The `react-router-dom` package still exists but just re-exports from `react-router`. Check for imports from both. + +## Pre-Migration + +- [ ] **Create a migration branch** + +```bash +git checkout -b migrate-to-tanstack-router +``` + +- [ ] **Install TanStack Router alongside React Router temporarily** + +```bash +npm install @tanstack/react-router @tanstack/react-router-devtools +npm install -D @tanstack/router-plugin +``` + +- [ ] **Configure bundler plugin (Vite example)** + +```ts +// vite.config.ts +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ target: 'react', autoCodeSplitting: true }), + react(), + ], +}) +``` + +- [ ] **Create routes directory** + +```bash +mkdir src/routes +``` + +## Route Definitions + +- [ ] **Create root route** + +React Router: `` or `createBrowserRouter([{ element: , children: [...] }])` + +TanStack Router: `src/routes/__root.tsx` + +```tsx +// src/routes/__root.tsx +import { createRootRoute, Link, Outlet } from '@tanstack/react-router' +import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' + +export const Route = createRootRoute({ + component: () => ( + <> + + + + + ), +}) +``` + +- [ ] **Create router instance with type registration** + +```tsx +// src/main.tsx +import { StrictMode } from 'react' +import ReactDOM from 'react-dom/client' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ routeTree }) + +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +const rootElement = document.getElementById('root')! +if (!rootElement.innerHTML) { + ReactDOM.createRoot(rootElement).render( + + + , + ) +} +``` + +- [ ] **Convert each route file to `createFileRoute`** + +React Router: + +```tsx +// Defined in route config array +{ path: '/posts', element: , loader: postsLoader } +``` + +TanStack Router: + +```tsx +// src/routes/posts.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts')({ + loader: async () => { + const posts = await fetchPosts() + return { posts } + }, + component: PostsPage, +}) + +function PostsPage() { + const { posts } = Route.useLoaderData() + return ( +
      + {posts.map((p) => ( +
    • {p.title}
    • + ))} +
    + ) +} +``` + +- [ ] **Convert dynamic routes** + +React Router: `/posts/:postId` (colon syntax) + +TanStack Router: `/posts/$postId` (dollar syntax) + +```tsx +// src/routes/posts/$postId.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params }) => { + const post = await fetchPost(params.postId) + return { post } + }, + component: PostPage, +}) + +function PostPage() { + const { post } = Route.useLoaderData() + return
    {post.title}
    +} +``` + +## Navigation + +- [ ] **Convert all `` components** + +React Router: + +```tsx +import { Link } from 'react-router' +;View Post +``` + +TanStack Router: + +```tsx +import { Link } from '@tanstack/react-router' +; + View Post + +``` + +Key differences: + +- `to` is a route path pattern, NOT an interpolated string +- `params` is a separate prop with typed values +- Active styling: use `activeProps={{ className: 'font-bold' }}` or `data-status="active"` attribute for CSS + +- [ ] **Convert all `useNavigate` calls** + +React Router: + +```tsx +import { useNavigate } from 'react-router' +const navigate = useNavigate() +navigate(`/posts/${postId}`) +``` + +TanStack Router: + +```tsx +import { useNavigate } from '@tanstack/react-router' +const navigate = useNavigate() +navigate({ to: '/posts/$postId', params: { postId } }) +``` + +## Search Params + +- [ ] **Replace `useSearchParams` with `validateSearch` + `useSearch`** + +React Router: + +```tsx +import { useSearchParams } from 'react-router' + +function Posts() { + const [searchParams, setSearchParams] = useSearchParams() + const page = Number(searchParams.get('page')) || 1 + + const goToPage = (p: number) => setSearchParams({ page: String(p) }) +} +``` + +TanStack Router: + +```tsx +// In the route definition: +import { createFileRoute } from '@tanstack/react-router' +import { z } from 'zod' + +export const Route = createFileRoute('/posts')({ + validateSearch: z.object({ + page: z.number().default(1).catch(1), + }), + component: Posts, +}) + +// In the component: +import { useNavigate } from '@tanstack/react-router' + +function Posts() { + const { page } = Route.useSearch() + const navigate = useNavigate({ from: '/posts' }) + + const goToPage = (p: number) => { + navigate({ search: (prev) => ({ ...prev, page: p }) }) + } +} +``` + +Key differences: + +- Search params are validated and typed at the route level +- `useSearch()` returns typed objects, not `URLSearchParams` +- Update with function form to preserve other params + +## Path Params + +- [ ] **Update `useParams` with `from` property** + +React Router: + +```tsx +import { useParams } from 'react-router' +const { postId } = useParams() +``` + +TanStack Router: + +```tsx +import { useParams } from '@tanstack/react-router' +const { postId } = useParams({ from: '/posts/$postId' }) +``` + +Or from within the route component: + +```tsx +const { postId } = Route.useParams() +``` + +## `useLocation` — Common Pitfall + +- [ ] **Replace `useLocation` with specific hooks** + +React Router's `useLocation` is heavily used, and TanStack Router has a hook with the same name — but they are NOT equivalent. TanStack Router's `useLocation()` returns the router's current location, which during pending navigations may differ from what's currently rendered. Most React Router `useLocation` usage should be replaced with more specific hooks. See [#3110](https://github.com/TanStack/router/issues/3110). + +Replace based on what you actually need: + +```tsx +// React Router +import { useLocation } from 'react-router' +const location = useLocation() + +// ❌ DON'T just swap to TanStack Router's useLocation — it's the "live" URL +import { useLocation } from '@tanstack/react-router' + +// ✅ DO use the specific hook for what you need: +import { + useMatch, + useMatches, + useParams, + useSearch, +} from '@tanstack/react-router' + +// Current route match (replaces most useLocation().pathname usage) +const match = useMatch({ from: '/posts/$postId' }) + +// All active matches (replaces useLocation for breadcrumbs/analytics) +const matches = useMatches() + +// Path params (replaces useLocation + manual parsing) +const { postId } = useParams({ from: '/posts/$postId' }) + +// Search params (replaces useLocation().search parsing) +const { page } = useSearch({ from: '/posts' }) +``` + +## Outlet + +- [ ] **Replace React Router `Outlet` with TanStack Router `Outlet`** + +The API is identical — just change the import: + +```tsx +// Before +import { Outlet } from 'react-router' + +// After +import { Outlet } from '@tanstack/react-router' +``` + +## Loaders + +- [ ] **Convert React Router loaders** + +React Router (v7): + +```tsx +export async function loader({ params }) { + const post = await fetchPost(params.postId) + return { post } +} + +export default function Post() { + const { post } = useLoaderData() + return
    {post.title}
    +} +``` + +TanStack Router: + +```tsx +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params }) => { + const post = await fetchPost(params.postId) + return { post } + }, + component: Post, +}) + +function Post() { + const { post } = Route.useLoaderData() + return
    {post.title}
    +} +``` + +Key differences: + +- Loader is a route option, not a separate export +- `useLoaderData()` is called via `Route.useLoaderData()` (or `useLoaderData({ from })`) +- TanStack Router loaders run on the CLIENT by default (not server-only) +- No `json()` wrapper needed — return plain objects + +## Code Splitting + +- [ ] **Convert lazy route imports** — with `autoCodeSplitting: true` in the plugin config, this is automatic. For manual splitting, use `.lazy.tsx` files: + +```tsx +// src/routes/lazy-page.lazy.tsx +import { createLazyFileRoute } from '@tanstack/react-router' + +export const Route = createLazyFileRoute('/lazy-page')({ + component: () =>
    Lazy loaded
    , +}) +``` + +## Cleanup + +- [ ] **Remove React Router and verify** + +```bash +npm uninstall react-router react-router-dom +grep -r "from 'react-router" src/ # find stale imports +npx tsc --noEmit # verify clean build +``` + +- [ ] **Test all routes** — verify rendering, navigation (incl. back/forward), search params, dynamic params, and loaders + +## Common Mistakes + +### 1. HIGH: Leaving React Router imports alongside TanStack Router + +Both libraries export `Link`, `useNavigate`, `Outlet`, etc. Leftover React Router imports cause "cannot use useNavigate outside of context" errors because the wrong context provider is used. + +```tsx +// WRONG — mixed imports +import { Link } from '@tanstack/react-router' +import { useNavigate } from 'react-router' // <- still React Router! + +// CORRECT — all from TanStack Router +import { Link, useNavigate } from '@tanstack/react-router' +``` + +**Fix**: Uninstall `react-router`/`react-router-dom` completely. TypeScript will flag every stale import. + +### 2. HIGH: Using React Router `useSearchParams` pattern + +```tsx +// WRONG — React Router pattern, returns URLSearchParams +const [searchParams, setSearchParams] = useSearchParams() +const page = Number(searchParams.get('page')) + +// CORRECT — TanStack Router pattern, returns typed object +// Route definition: +validateSearch: + z.object({ + page: z.number().default(1).catch(1), + }), + +// Component: +const { page } = Route.useSearch() +// page is already typed as number — no casting needed +``` + +### 3. HIGH: Interpolating params into `to` string + +```tsx +// WRONG — React Router habit +Post + +// CORRECT — TanStack Router: path pattern + params prop +Post +``` + +### 4. MEDIUM: Using `:param` syntax instead of `$param` + +```text +React Router: /posts/:postId +TanStack Router: /posts/$postId +``` + +File naming also uses `$`: `src/routes/posts/$postId.tsx` + +## Quick Reference: API Mapping + +| React Router v7 | TanStack Router | +| ---------------------------- | ---------------------------------------------------- | +| `` | `` | +| `` / `` | File-based: `src/routes/*.tsx` | +| `` | `` | +| `` | `` | +| `useNavigate()('/path')` | `navigate({ to: '/path' })` | +| `useParams()` | `useParams({ from: '/route/$param' })` | +| `useSearchParams()` | `validateSearch` + `useSearch({ from })` | +| `useLoaderData()` | `Route.useLoaderData()` | +| `useLocation()` | `useMatch`, `useMatches`, `useParams`, `useSearch` | +| `` | `` | +| `loader({ params })` | `loader: ({ params }) => ...` (route option) | +| `action({ request })` | Use mutations / form libraries | +| `lazy(() => import(...))` | `autoCodeSplitting` or `.lazy.tsx` files | +| `:paramName` | `$paramName` | +| `*` (splat) | `$` (splat, accessed via `_splat`) | diff --git a/packages/react-router/skills/react-router/SKILL.md b/packages/react-router/skills/react-router/SKILL.md new file mode 100644 index 0000000000..f8df76df02 --- /dev/null +++ b/packages/react-router/skills/react-router/SKILL.md @@ -0,0 +1,498 @@ +--- +name: react-router +description: >- + React bindings for TanStack Router: RouterProvider, useRouter, + useRouterState, useMatch, useMatches, useLocation, useSearch, + useParams, useNavigate, useLoaderData, useLoaderDeps, + useRouteContext, useBlocker, useCanGoBack, Link, Navigate, + Outlet, CatchBoundary, ErrorComponent. React-specific patterns + for hooks, providers, SSR hydration, and createLink with + forwardRef. +metadata: + type: framework + library: tanstack-router + library_version: '1.166.2' + framework: react +requires: + - router-core +sources: + - TanStack/router:packages/react-router/src + - TanStack/router:docs/router/guide/creating-a-router.md + - TanStack/router:docs/router/installation/manual.md +--- + +# React Router (`@tanstack/react-router`) + +This skill builds on router-core. Read `@tanstack/router-core#router-core` first for foundational concepts. + +> **CRITICAL**: TanStack Router types are FULLY INFERRED. Never cast, never annotate inferred values. +> **CRITICAL**: TanStack Router is CLIENT-FIRST. Loaders run on the client by default, not on the server. +> **CRITICAL**: Do not confuse `@tanstack/react-router` with `react-router-dom`/`react-router`. They are completely different libraries with different APIs. + +## Full Setup: File-Based Routing with Vite + +### 1. Install Dependencies + +```bash +npm install @tanstack/react-router +npm install -D @tanstack/router-plugin @tanstack/react-router-devtools +``` + +### 2. Configure Vite Plugin + +```ts +// vite.config.ts +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + // MUST come before react() + tanstackRouter({ + target: 'react', + autoCodeSplitting: true, + }), + react(), + ], +}) +``` + +### 3. Create Root Route + +```tsx +// src/routes/__root.tsx +import { createRootRoute, Link, Outlet } from '@tanstack/react-router' +import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' + +export const Route = createRootRoute({ + component: RootLayout, +}) + +function RootLayout() { + return ( + <> + +
    + + + + ) +} +``` + +### 4. Create Route Files + +```tsx +// src/routes/index.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return

    Welcome Home

    +} +``` + +```tsx +// src/routes/about.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/about')({ + component: AboutPage, +}) + +function AboutPage() { + return

    About

    +} +``` + +### 5. Create Router Instance and Register Types + +```tsx +// src/main.tsx +import { StrictMode } from 'react' +import ReactDOM from 'react-dom/client' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ routeTree }) + +// REQUIRED — without this, Link/useNavigate/useSearch have no type safety +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +const rootElement = document.getElementById('root')! +if (!rootElement.innerHTML) { + const root = ReactDOM.createRoot(rootElement) + root.render( + + + , + ) +} +``` + +## Hooks Reference + +All hooks are imported from `@tanstack/react-router`. + +### `useRouter()` + +Access the router instance directly: + +```tsx +import { useRouter } from '@tanstack/react-router' + +function InvalidateButton() { + const router = useRouter() + return +} +``` + +### `useRouterState()` + +Subscribe to router state changes. Exposes the entire state and thus incurs +a performance cost. For matches or location favor `useMatches` and `useLocation`. + +```tsx +import { useRouterState } from '@tanstack/react-router' + +function LoadingIndicator() { + const isLoading = useRouterState({ select: (s) => s.isLoading }) + return isLoading ?
    Loading...
    : null +} +``` + +### `useNavigate()` + +Programmatic navigation (prefer `` for user-clickable elements): + +```tsx +import { useNavigate } from '@tanstack/react-router' + +function AfterSubmit() { + const navigate = useNavigate() + + const handleSubmit = async () => { + await saveData() + navigate({ to: '/posts/$postId', params: { postId: '123' } }) + } + + return +} +``` + +### `useSearch({ from })` + +Read validated search params: + +```tsx +import { useSearch } from '@tanstack/react-router' + +function Pagination() { + const { page } = useSearch({ from: '/products' }) + return Page {page} +} +``` + +### `useParams({ from })` + +Read path params: + +```tsx +import { useParams } from '@tanstack/react-router' + +function PostHeader() { + const { postId } = useParams({ from: '/posts/$postId' }) + return

    Post {postId}

    +} +``` + +### `useLoaderData({ from })` + +Read data returned from the route loader: + +```tsx +import { useLoaderData } from '@tanstack/react-router' + +function PostContent() { + const { post } = useLoaderData({ from: '/posts/$postId' }) + return
    {post.content}
    +} +``` + +### `useMatch({ from })` + +Access the full route match (params, search, loader data, context): + +```tsx +import { useMatch } from '@tanstack/react-router' + +function PostDetails() { + const match = useMatch({ from: '/posts/$postId' }) + return
    {match.loaderData.post.title}
    +} +``` + +### Other Hooks + +All imported from `@tanstack/react-router`: + +- **`useMatches()`** — array of all active route matches (useful for breadcrumbs) +- **`useRouteContext({ from })`** — read context from `beforeLoad` or parent routes +- **`useBlocker({ shouldBlockFn })`** — block navigation for unsaved changes +- **`useCanGoBack()`** — returns `boolean`, check if history has entries to go back to +- **`useLocation()`** — current parsed location (`pathname`, `search`, `hash`) +- **`useLinkProps({ to, params?, search? })`** — get `` props for custom link elements +- **`useMatchRoute()`** — returns a function: `matchRoute({ to }) => match | false` + +## Components Reference + +### `RouterProvider` + +Mount the router at the top of your React tree: + +```tsx + +``` + +### `Link` + +Type-safe navigation link with `` semantics: + +```tsx + + View Post + +``` + +### `Outlet` + +Renders the matched child route component: + +```tsx +function Layout() { + return ( +
    + +
    + +
    +
    + ) +} +``` + +### `Navigate` + +Declarative redirect component: + +```tsx +import { Navigate } from '@tanstack/react-router' + +function OldPage() { + return +} +``` + +### `Await` + +Renders deferred data from unawaited loader promises with Suspense: + +```tsx +import { Await } from '@tanstack/react-router' +import { Suspense } from 'react' + +function PostWithComments() { + const { deferredComments } = Route.useLoaderData() + return ( +
    +

    Post

    + Loading comments...
    }> + + {(comments) => ( +
      + {comments.map((c) => ( +
    • {c.text}
    • + ))} +
    + )} +
    +
    +
    + ) +} +``` + +### `CatchBoundary` + +Error boundary for component-level error handling (route-level errors use `errorComponent` route option): + +```tsx +import { CatchBoundary } from '@tanstack/react-router' +; 'widget'} + onCatch={(error) => console.error(error)} + errorComponent={({ error }) =>
    {String(error)}
    } +> + +
    +``` + +## React-Specific Patterns + +### Custom Link Component with `createLink` + +Wrap `Link` in a custom component while preserving type safety: + +```tsx +import { createLink } from '@tanstack/react-router' +import { forwardRef, type ComponentPropsWithoutRef } from 'react' + +const StyledLinkComponent = forwardRef< + HTMLAnchorElement, + ComponentPropsWithoutRef<'a'> +>((props, ref) => ( +
    +)) + +const StyledLink = createLink(StyledLinkComponent) + +// Usage — same type-safe props as Link +function Nav() { + return ( + + Post + + ) +} +``` + +### Reusable Components with Router Hooks + +To create a component that uses router hooks across multiple routes, pass a union of route paths as the `from` prop: + +```tsx +function PostIdDisplay({ from }: { from: '/posts/$id' | '/drafts/$id' }) { + const { id } = useParams({ from }) + return ID: {id} +} + +// Usage in different route components + + +``` + +This pattern avoids `strict: false` (which returns an imprecise union) while keeping the component reusable across specific known routes. + +### Auth Provider Must Wrap RouterProvider + +If routes use auth context (via `createRootRouteWithContext`), the auth provider must be an ancestor of `RouterProvider`: + +```tsx +// CORRECT — AuthProvider wraps RouterProvider +function App() { + return ( + + + + ) +} + +// WRONG — RouterProvider outside auth provider +function App() { + return ( + + {/* ... */} + + ) +} +``` + +Or use the `Wrap` router option to provide context without wrapping externally: + +```tsx +const router = createRouter({ + routeTree, + Wrap: ({ children }) => ( + {children} + ), +}) +``` + +## Common Mistakes + +### 1. HIGH: Using React hooks in `beforeLoad` or `loader` + +`beforeLoad` and `loader` are NOT React components — they are plain async functions. React hooks cannot be called in them. Pass auth state via router context instead. + +```tsx +// WRONG — useAuth is a React hook, cannot be called here +beforeLoad: () => { + const auth = useAuth() + if (!auth.user) throw redirect({ to: '/login' }) +} + +// CORRECT — read auth from router context +beforeLoad: ({ context }) => { + if (!context.auth.isAuthenticated) { + throw redirect({ to: '/login' }) + } +} +``` + +### 2. HIGH: Wrapping RouterProvider inside an auth provider incorrectly + +Create the router once with an `undefined!` placeholder, then inject live auth via `RouterProvider`'s `context` prop. Do NOT recreate the router on auth changes — this resets caches and rebuilds the tree. + +```tsx +// CORRECT — create router once, inject live auth via context prop +const router = createRouter({ + routeTree, + context: { auth: undefined! }, // placeholder, filled by RouterProvider +}) + +function InnerApp() { + const auth = useAuth() + return +} + +function App() { + return ( + + + + ) +} +``` + +### 3. MEDIUM: Missing Suspense boundary for `Await`/deferred data + +`Await` requires a `` ancestor. Without it, the deferred promise has no fallback UI and throws. + +```tsx +// WRONG — no Suspense boundary +{(data) =>
    {data}
    }
    + +// CORRECT — wrap in Suspense +Loading...
    }> + {(data) =>
    {data}
    }
    + +``` + +## Cross-References + +- `@tanstack/router-core#router-core` — all sub-skills for domain-specific patterns (search params, data loading, navigation, auth, SSR, etc.) diff --git a/packages/react-router/src/Asset.tsx b/packages/react-router/src/Asset.tsx index ce1a9699e4..04cbac9064 100644 --- a/packages/react-router/src/Asset.tsx +++ b/packages/react-router/src/Asset.tsx @@ -1,20 +1,54 @@ +'use client' + import * as React from 'react' +import { isServer } from '@tanstack/router-core/isServer' import { useRouter } from './useRouter' +import { useHydrated } from './ClientOnly' import type { RouterManagedTag } from '@tanstack/router-core' +const INLINE_CSS_HYDRATION_ATTR = 'data-tsr-inline-css' + interface ScriptAttrs { [key: string]: string | boolean | undefined src?: string suppressHydrationWarning?: boolean } -export function Asset({ - tag, - attrs, - children, - nonce, -}: RouterManagedTag & { nonce?: string }): React.ReactElement | null { - switch (tag) { +const noopScriptHandler = () => {} + +function setScriptAttrs( + script: HTMLScriptElement, + attrs: ScriptAttrs | undefined, +) { + if (!attrs) { + return + } + + for (const [key, value] of Object.entries(attrs)) { + if ( + key !== 'suppressHydrationWarning' && + value !== undefined && + value !== false + ) { + script.setAttribute(key, typeof value === 'boolean' ? '' : String(value)) + } + } +} + +export function Asset( + asset: RouterManagedTag & { + nonce?: string + preventScriptHoist?: boolean + }, +): React.ReactElement | null { + const { attrs, children, nonce, preventScriptHoist } = asset + // React 19 compares this object by reference before assigning innerHTML. + const innerHTML = React.useMemo( + () => (children === undefined ? undefined : { __html: children }), + [children], + ) + + switch (asset.tag) { case 'title': return ( @@ -24,71 +58,136 @@ export function Asset({ case 'meta': return <meta {...attrs} suppressHydrationWarning /> case 'link': - return <link {...attrs} nonce={nonce} suppressHydrationWarning /> - case 'style': return ( - <style + <link {...attrs} - dangerouslySetInnerHTML={{ __html: children as string }} + precedence={ + attrs?.precedence ?? + (attrs?.rel === 'stylesheet' ? 'default' : undefined) + } nonce={nonce} + suppressHydrationWarning /> ) + case 'style': + if ( + asset.inlineCss && + (process.env.TSS_INLINE_CSS_ENABLED === 'true' || + (process.env.TSS_INLINE_CSS_ENABLED === undefined && isServer)) + ) { + return ( + <InlineCssStyle attrs={attrs} nonce={nonce}> + {children} + </InlineCssStyle> + ) + } + + return ( + <style {...attrs} dangerouslySetInnerHTML={innerHTML} nonce={nonce} /> + ) case 'script': - return <Script attrs={attrs}>{children}</Script> + return ( + <Script attrs={attrs} preventScriptHoist={preventScriptHoist}> + {children} + </Script> + ) default: return null } } +function InlineCssStyle({ + attrs, + children, + nonce, +}: { + attrs?: Record<string, any> + children?: RouterManagedTag['children'] + nonce?: string +}) { + const isInlineCssPlaceholder = children === undefined + const [hydratedInlineCss] = React.useState(() => { + if (!isInlineCssPlaceholder || typeof document === 'undefined') { + return undefined + } + + return ( + document.querySelector<HTMLStyleElement>( + `style[${INLINE_CSS_HYDRATION_ATTR}]`, + )?.textContent ?? undefined + ) + }) + const html = isInlineCssPlaceholder + ? (hydratedInlineCss ?? '') + : (children ?? '') + const innerHTML = React.useMemo(() => ({ __html: html }), [html]) + + return ( + <style + {...attrs} + {...{ [INLINE_CSS_HYDRATION_ATTR]: '' }} + dangerouslySetInnerHTML={innerHTML} + nonce={nonce} + suppressHydrationWarning + /> + ) +} + function Script({ attrs, children, + preventScriptHoist, }: { attrs?: ScriptAttrs children?: string + preventScriptHoist?: boolean }) { const router = useRouter() + const hydrated = useHydrated() + const innerHTML = React.useMemo( + () => (children === undefined ? undefined : { __html: children }), + [children], + ) + const dataScript = + typeof attrs?.type === 'string' && + attrs.type !== '' && + attrs.type !== 'text/javascript' && + attrs.type !== 'module' + + if ( + process.env.NODE_ENV !== 'production' && + attrs?.src && + typeof children === 'string' && + children.trim().length + ) { + console.warn( + '[TanStack Router] <Script> received both `src` and `children`. The `children` content will be ignored. Remove `children` or remove `src`.', + ) + } React.useEffect(() => { - if (attrs?.src) { - const normSrc = (() => { - try { - const base = document.baseURI || window.location.href - return new URL(attrs.src, base).href - } catch { - return attrs.src - } - })() - const existingScript = Array.from( - document.querySelectorAll('script[src]'), - ).find((el) => (el as HTMLScriptElement).src === normSrc) + if (dataScript) { + return + } - if (existingScript) { - return + if (attrs?.src) { + // Anchors resolve relative URLs and preserve invalid URLs without throwing. + const link = document.createElement('a') + link.href = attrs.src + const normSrc = link.href + for (const el of document.scripts) { + if (el.src === normSrc) { + return + } } const script = document.createElement('script') - for (const [key, value] of Object.entries(attrs)) { - if ( - key !== 'suppressHydrationWarning' && - value !== undefined && - value !== false - ) { - script.setAttribute( - key, - typeof value === 'boolean' ? '' : String(value), - ) - } - } + setScriptAttrs(script, attrs) document.head.appendChild(script) - return () => { - if (script.parentNode) { - script.parentNode.removeChild(script) - } - } + return () => script.remove() } if (typeof children === 'string') { @@ -96,78 +195,98 @@ function Script({ typeof attrs?.type === 'string' ? attrs.type : 'text/javascript' const nonceAttr = typeof attrs?.nonce === 'string' ? attrs.nonce : undefined - const existingScript = Array.from( - document.querySelectorAll('script:not([src])'), - ).find((el) => { - if (!(el instanceof HTMLScriptElement)) return false + for (const el of document.scripts) { + if (el.hasAttribute('src')) { + continue + } + const sType = el.getAttribute('type') ?? 'text/javascript' const sNonce = el.getAttribute('nonce') ?? undefined - return ( + if ( el.textContent === children && sType === typeAttr && sNonce === nonceAttr - ) - }) - - if (existingScript) { - return + ) { + return + } } const script = document.createElement('script') script.textContent = children - - if (attrs) { - for (const [key, value] of Object.entries(attrs)) { - if ( - key !== 'suppressHydrationWarning' && - value !== undefined && - value !== false - ) { - script.setAttribute( - key, - typeof value === 'boolean' ? '' : String(value), - ) - } - } - } + setScriptAttrs(script, attrs) document.head.appendChild(script) - return () => { - if (script.parentNode) { - script.parentNode.removeChild(script) - } - } + return () => script.remove() } return undefined - }, [attrs, children]) + }, [attrs, children, dataScript]) - if (!router.isServer) { - const { src, ...rest } = attrs || {} - // render an empty script on the client just to avoid hydration errors - return ( - <script - suppressHydrationWarning - dangerouslySetInnerHTML={{ __html: '' }} - {...rest} - ></script> - ) + // --- Server rendering --- + if (isServer ?? router.isServer) { + if (attrs?.src) { + if (!preventScriptHoist) { + return <script {...attrs} suppressHydrationWarning /> + } + + return ( + <script + {...attrs} + // React hoists async src scripts into <head> during SSR unless they + // have an event handler. Start's client entry must stay after router + // dehydration. + onLoad={noopScriptHandler} + suppressHydrationWarning + /> + ) + } + + if (typeof children === 'string') { + return ( + <script + {...attrs} + dangerouslySetInnerHTML={innerHTML} + suppressHydrationWarning + /> + ) + } + + return null } - if (attrs?.src && typeof attrs.src === 'string') { - return <script {...attrs} suppressHydrationWarning /> - } + // --- Client rendering --- - if (typeof children === 'string') { + // Data scripts (e.g. application/ld+json) are rendered in the tree; + // the useEffect intentionally skips them. + if (dataScript && typeof children === 'string') { return ( <script {...attrs} - dangerouslySetInnerHTML={{ __html: children }} suppressHydrationWarning + dangerouslySetInnerHTML={innerHTML} /> ) } + // During hydration (before useEffect has fired), render the script element + // to match the server-rendered HTML and avoid structural hydration mismatches. + // After hydration, return null — the useEffect handles imperative injection. + if (!hydrated) { + if (attrs?.src) { + return <script {...attrs} suppressHydrationWarning /> + } + + if (typeof children === 'string') { + return ( + <script + {...attrs} + dangerouslySetInnerHTML={innerHTML} + suppressHydrationWarning + /> + ) + } + } + return null } diff --git a/packages/react-router/src/CatchBoundary.tsx b/packages/react-router/src/CatchBoundary.tsx index 68197b2eb6..1015a9e116 100644 --- a/packages/react-router/src/CatchBoundary.tsx +++ b/packages/react-router/src/CatchBoundary.tsx @@ -1,83 +1,61 @@ +'use client' + import * as React from 'react' +import { wrapInNonRouteComponentContext } from './nonRouteComponentContext' import type { ErrorRouteComponent } from './route' import type { ErrorInfo } from 'react' -export function CatchBoundary(props: { - getResetKey: () => number | string +export class CatchBoundary extends React.Component<{ + getResetKey: () => unknown children: React.ReactNode errorComponent?: ErrorRouteComponent - onCatch?: (error: Error, errorInfo: ErrorInfo) => void -}) { - const errorComponent = props.errorComponent ?? ErrorComponent - - return ( - <CatchBoundaryImpl - getResetKey={props.getResetKey} - onCatch={props.onCatch} - children={({ error, reset }) => { - if (error) { - return React.createElement(errorComponent, { - error, - reset, - }) - } - - return props.children - }} - /> - ) -} - -class CatchBoundaryImpl extends React.Component<{ - getResetKey: () => number | string - children: (props: { - error: Error | null - reset: () => void - }) => React.ReactNode - onCatch?: (error: Error, errorInfo: ErrorInfo) => void + onCatch?: (error: unknown, errorInfo: ErrorInfo) => void }> { - state = { error: null } as { error: Error | null; resetKey: string } - static getDerivedStateFromProps(props: any) { - return { resetKey: props.getResetKey() } - } - static getDerivedStateFromError(error: Error) { - return { error } - } - reset() { - this.setState({ error: null }) - } - componentDidUpdate( - prevProps: Readonly<{ - getResetKey: () => string - children: (props: { error: any; reset: () => void }) => any - onCatch?: ((error: any, info: any) => void) | undefined - }>, - prevState: any, - ): void { - if (prevState.error && prevState.resetKey !== this.state.resetKey) { - this.reset() + // Wrapping caught values keeps every possible thrown value truthy. + state = { error: 0 } as { error: [unknown] | 0; resetKey?: unknown } + + static getDerivedStateFromProps( + props: { getResetKey: () => unknown }, + state: { resetKey?: unknown; error: [unknown] | 0 }, + ) { + const resetKey = props.getResetKey() + + if (state.error && state.resetKey !== resetKey) { + return { resetKey, error: 0 } } + + return { resetKey } } - componentDidCatch(error: Error, errorInfo: ErrorInfo) { - if (this.props.onCatch) { - this.props.onCatch(error, errorInfo) - } + static getDerivedStateFromError(error: unknown) { + return { error: [error] } + } + reset = () => { + this.setState({ error: 0 }) + } + componentDidCatch(error: unknown, errorInfo: ErrorInfo) { + this.props.onCatch?.(error, errorInfo) } render() { - // If the resetKey has changed, don't render the error - return this.props.children({ - error: - this.state.resetKey !== this.props.getResetKey() - ? null - : this.state.error, - reset: () => { - this.reset() - }, - }) + const error = this.state.error + if (error) { + const element = React.createElement( + this.props.errorComponent ?? ErrorComponent, + { + error: error[0], + reset: this.reset, + }, + ) + + return process.env.NODE_ENV !== 'production' + ? wrapInNonRouteComponentContext(element, 'errorComponent') + : element + } + + return this.props.children } } -export function ErrorComponent({ error }: { error: any }) { +export function ErrorComponent({ error }: { error: unknown }) { const [show, setShow] = React.useState(process.env.NODE_ENV !== 'production') return ( @@ -111,7 +89,9 @@ export function ErrorComponent({ error }: { error: any }) { overflow: 'auto', }} > - {error.message ? <code>{error.message}</code> : null} + {(error as { message?: string } | null)?.message ? ( + <code>{(error as { message: string }).message}</code> + ) : null} </pre> </div> ) : null} diff --git a/packages/react-router/src/ClientOnly.tsx b/packages/react-router/src/ClientOnly.tsx index 931804b259..010a6d3117 100644 --- a/packages/react-router/src/ClientOnly.tsx +++ b/packages/react-router/src/ClientOnly.tsx @@ -1,5 +1,10 @@ +'use client' + import React from 'react' +const getSnapshot = () => true +const getServerSnapshot = () => false + export interface ClientOnlyProps { /** * The children to render when the JS is loaded. @@ -29,11 +34,7 @@ export interface ClientOnlyProps { * ``` */ export function ClientOnly({ children, fallback = null }: ClientOnlyProps) { - return useHydrated() ? ( - <React.Fragment>{children}</React.Fragment> - ) : ( - <React.Fragment>{fallback}</React.Fragment> - ) + return <React.Fragment>{useHydrated() ? children : fallback}</React.Fragment> } /** @@ -55,14 +56,24 @@ export function ClientOnly({ children, fallback = null }: ClientOnlyProps) { * ``` * @returns True if the JS has been hydrated already, false otherwise. */ -export function useHydrated(): boolean { +export function useHydrated(): boolean +/** + * @internal + * callers whose output does not depend on hydration can keep the + * same snapshot on both sides, avoiding an unnecessary post-hydration render. + */ +export function useHydrated(enabled: boolean): boolean +/** @internal */ +export function useHydrated(enabled = true): boolean { return React.useSyncExternalStore( subscribe, - () => true, - () => false, + getSnapshot, + enabled ? getServerSnapshot : getSnapshot, ) } function subscribe() { - return () => {} + return () => { + // noop + } } diff --git a/packages/react-router/src/HeadContent.dev.tsx b/packages/react-router/src/HeadContent.dev.tsx new file mode 100644 index 0000000000..776f334318 --- /dev/null +++ b/packages/react-router/src/HeadContent.dev.tsx @@ -0,0 +1,50 @@ +'use client' + +import * as React from 'react' +import { DEV_STYLES_ATTR } from '@tanstack/router-core' +import { Asset } from './Asset' +import { useRouter } from './useRouter' +import { useHydrated } from './ClientOnly' +import { useTags } from './headContentUtils' +import type { HeadContentProps } from './HeadContent' + +/** + * Render route-managed head tags (title, meta, links, styles, head scripts). + * Place inside the document head of your app shell. + * + * Development version: filters out dev styles link after hydration and + * includes a fallback cleanup effect for hydration mismatch cases. + * + * @link https://tanstack.com/router/latest/docs/framework/react/guide/document-head-management + */ +export function HeadContent(props: HeadContentProps) { + const tags = useTags(props.assetCrossOrigin) + const router = useRouter() + const nonce = router.options.ssr?.nonce + const hydrated = useHydrated() + + // Fallback cleanup for hydration mismatch cases + // Runs when hydration completes to remove any orphaned dev styles links from DOM + React.useEffect(() => { + if (hydrated) { + document + .querySelectorAll(`link[${DEV_STYLES_ATTR}]`) + .forEach((el) => el.remove()) + } + }, [hydrated]) + + // Filter out dev styles after hydration + const filteredTags = hydrated + ? tags.filter( + (tag) => tag.tag !== 'link' || tag.attrs?.[DEV_STYLES_ATTR] !== true, + ) + : tags + + return ( + <> + {filteredTags.map((tag) => ( + <Asset {...tag} key={`tsr-meta-${JSON.stringify(tag)}`} nonce={nonce} /> + ))} + </> + ) +} diff --git a/packages/react-router/src/HeadContent.tsx b/packages/react-router/src/HeadContent.tsx index b86d706cd0..6a0c8188bc 100644 --- a/packages/react-router/src/HeadContent.tsx +++ b/packages/react-router/src/HeadContent.tsx @@ -1,190 +1,13 @@ +'use client' + import * as React from 'react' import { Asset } from './Asset' import { useRouter } from './useRouter' -import { useRouterState } from './useRouterState' -import type { RouterManagedTag } from '@tanstack/router-core' +import { useTags } from './headContentUtils' +import type { AssetCrossOriginConfig } from '@tanstack/router-core' -/** - * Build the list of head/link/meta/script tags to render for active matches. - * Used internally by `HeadContent`. - */ -export const useTags = () => { - const router = useRouter() - const nonce = router.options.ssr?.nonce - const routeMeta = useRouterState({ - select: (state) => { - return state.matches.map((match) => match.meta!).filter(Boolean) - }, - }) - - const meta: Array<RouterManagedTag> = React.useMemo(() => { - const resultMeta: Array<RouterManagedTag> = [] - const metaByAttribute: Record<string, true> = {} - let title: RouterManagedTag | undefined - for (let i = routeMeta.length - 1; i >= 0; i--) { - const metas = routeMeta[i]! - for (let j = metas.length - 1; j >= 0; j--) { - const m = metas[j] - if (!m) continue - - if (m.title) { - if (!title) { - title = { - tag: 'title', - children: m.title, - } - } - } else { - const attribute = m.name ?? m.property - if (attribute) { - if (metaByAttribute[attribute]) { - continue - } else { - metaByAttribute[attribute] = true - } - } - - resultMeta.push({ - tag: 'meta', - attrs: { - ...m, - nonce, - }, - }) - } - } - } - - if (title) { - resultMeta.push(title) - } - - if (nonce) { - resultMeta.push({ - tag: 'meta', - attrs: { - property: 'csp-nonce', - content: nonce, - }, - }) - } - resultMeta.reverse() - - return resultMeta - }, [routeMeta, nonce]) - - const links = useRouterState({ - select: (state) => { - const constructed = state.matches - .map((match) => match.links!) - .filter(Boolean) - .flat(1) - .map((link) => ({ - tag: 'link', - attrs: { - ...link, - nonce, - }, - })) satisfies Array<RouterManagedTag> - - const manifest = router.ssr?.manifest - - // These are the assets extracted from the ViteManifest - // using the `startManifestPlugin` - const assets = state.matches - .map((match) => manifest?.routes[match.routeId]?.assets ?? []) - .filter(Boolean) - .flat(1) - .filter((asset) => asset.tag === 'link') - .map( - (asset) => - ({ - tag: 'link', - attrs: { - ...asset.attrs, - suppressHydrationWarning: true, - nonce, - }, - }) satisfies RouterManagedTag, - ) - - return [...constructed, ...assets] - }, - structuralSharing: true as any, - }) - - const preloadLinks = useRouterState({ - select: (state) => { - const preloadLinks: Array<RouterManagedTag> = [] - - state.matches - .map((match) => router.looseRoutesById[match.routeId]!) - .forEach((route) => - router.ssr?.manifest?.routes[route.id]?.preloads - ?.filter(Boolean) - .forEach((preload) => { - preloadLinks.push({ - tag: 'link', - attrs: { - rel: 'modulepreload', - href: preload, - nonce, - }, - }) - }), - ) - - return preloadLinks - }, - structuralSharing: true as any, - }) - - const styles = useRouterState({ - select: (state) => - ( - state.matches - .map((match) => match.styles!) - .flat(1) - .filter(Boolean) as Array<RouterManagedTag> - ).map(({ children, ...attrs }) => ({ - tag: 'style', - attrs, - children, - nonce, - })), - structuralSharing: true as any, - }) - - const headScripts: Array<RouterManagedTag> = useRouterState({ - select: (state) => - ( - state.matches - .map((match) => match.headScripts!) - .flat(1) - .filter(Boolean) as Array<RouterManagedTag> - ).map(({ children, ...script }) => ({ - tag: 'script', - attrs: { - ...script, - nonce, - }, - children, - })), - structuralSharing: true as any, - }) - - return uniqBy( - [ - ...meta, - ...preloadLinks, - ...links, - ...styles, - ...headScripts, - ] as Array<RouterManagedTag>, - (d) => { - return JSON.stringify(d) - }, - ) +export interface HeadContentProps { + assetCrossOrigin?: AssetCrossOriginConfig } /** @@ -192,23 +15,15 @@ export const useTags = () => { * Place inside the document head of your app shell. * @link https://tanstack.com/router/latest/docs/framework/react/guide/document-head-management */ -export function HeadContent() { - const tags = useTags() +export function HeadContent(props: HeadContentProps) { + const tags = useTags(props.assetCrossOrigin) const router = useRouter() const nonce = router.options.ssr?.nonce - return tags.map((tag) => ( - <Asset {...tag} key={`tsr-meta-${JSON.stringify(tag)}`} nonce={nonce} /> - )) -} - -function uniqBy<T>(arr: Array<T>, fn: (item: T) => string) { - const seen = new Set<string>() - return arr.filter((item) => { - const key = fn(item) - if (seen.has(key)) { - return false - } - seen.add(key) - return true - }) + return ( + <> + {tags.map((tag) => ( + <Asset {...tag} key={`tsr-meta-${JSON.stringify(tag)}`} nonce={nonce} /> + ))} + </> + ) } diff --git a/packages/react-router/src/Match.tsx b/packages/react-router/src/Match.tsx index 6c16c330b5..db1d341ec4 100644 --- a/packages/react-router/src/Match.tsx +++ b/packages/react-router/src/Match.tsx @@ -1,56 +1,86 @@ +'use client' + import * as React from 'react' -import invariant from 'tiny-invariant' -import warning from 'tiny-warning' -import { - createControlledPromise, - getLocationChangeInfo, - isNotFound, - isRedirect, - rootRouteId, -} from '@tanstack/router-core' +import { useSelector } from '@tanstack/react-store' +import { isNotFound, rootRouteId } from '@tanstack/router-core' +import { isServer } from '@tanstack/router-core/isServer' import { CatchBoundary, ErrorComponent } from './CatchBoundary' -import { useRouterState } from './useRouterState' import { useRouter } from './useRouter' import { CatchNotFound } from './not-found' import { matchContext } from './matchContext' -import { SafeFragment } from './SafeFragment' import { renderRouteNotFound } from './renderRouteNotFound' import { ScrollRestoration } from './scroll-restoration' import { ClientOnly } from './ClientOnly' +import { + nonRouteComponentContext, + wrapInNonRouteComponentContext, +} from './nonRouteComponentContext' import type { AnyRoute, - ParsedLocation, + AnyRouteMatch, RootRouteOptions, } from '@tanstack/router-core' +export function renderPending( + router: ReturnType<typeof useRouter>, + route?: AnyRoute, +) { + const PendingComponent = + route?.options.pendingComponent ?? router.options.defaultPendingComponent + if (!PendingComponent) { + return null + } + + const pendingElement = <PendingComponent /> + return process.env.NODE_ENV !== 'production' + ? wrapInNonRouteComponentContext(pendingElement, 'pendingComponent') + : pendingElement +} + +type OutletMatchSelection = [ + parentGlobalNotFound: boolean, + parentNotFoundError: unknown, +] + +const outletMatchSelectionEqual = ( + a: OutletMatchSelection, + b: OutletMatchSelection, +) => a[0] === b[0] && a[1] === b[1] + +const canWrapInSuspense = ( + router: ReturnType<typeof useRouter>, + route: AnyRoute, + ssr: AnyRouteMatch['ssr'], +) => + !route.isRoot || + (route.options as RootRouteOptions).shellComponent || + route.options.wrapInSuspense || + ssr === false || + ssr === 'data-only' || + !((isServer ?? router.isServer) || router.ssr) + export const Match = React.memo(function MatchImpl({ - matchId, + routeId, }: { - matchId: string + routeId: string }) { const router = useRouter() - const matchState = useRouterState({ - select: (s) => { - const match = s.matches.find((d) => d.id === matchId) - invariant( - match, - `Could not find match for matchId "${matchId}". Please file an issue!`, - ) - return { - routeId: match.routeId, - ssr: match.ssr, - _displayPending: match._displayPending, - } - }, - structuralSharing: true as any, - }) - const route: AnyRoute = router.routesById[matchState.routeId] + if (isServer ?? router.isServer) { + const match = router.stores.byRoute.get(routeId)!.get()! + return matchView(router, match) + } - const PendingComponent = - route.options.pendingComponent ?? router.options.defaultPendingComponent + const matchStore = router.stores.getMatchStore(routeId) + // eslint-disable-next-line react-hooks/rules-of-hooks + const match = useSelector(matchStore)! + return matchView(router, match) +}) - const pendingElement = PendingComponent ? <PendingComponent /> : null +function matchView(router: ReturnType<typeof useRouter>, match: AnyRouteMatch) { + const route: AnyRoute = router.routesById[match.routeId] + + const pendingElement = renderPending(router, route) const routeErrorComponent = route.options.errorComponent ?? router.options.defaultErrorComponent @@ -58,248 +88,167 @@ export const Match = React.memo(function MatchImpl({ const routeOnCatch = route.options.onCatch ?? router.options.defaultOnCatch const routeNotFoundComponent = route.isRoot - ? // If it's the root route, use the globalNotFound option, with fallback to the notFoundRoute's component + ? // If it's the root route, use the _notFound option, with fallback to the notFoundRoute's component (route.options.notFoundComponent ?? router.options.notFoundRoute?.options.component) : route.options.notFoundComponent - const resolvedNoSsr = - matchState.ssr === false || matchState.ssr === 'data-only' - const ResolvedSuspenseBoundary = - // If we're on the root route, allow forcefully wrapping in suspense - (!route.isRoot || route.options.wrapInSuspense || resolvedNoSsr) && + const resolvedNoSsr = match.ssr === false || match.ssr === 'data-only' + // A root component may render the document itself. Only place its Suspense + // boundary in pure CSR, inside an explicit shell, or when explicitly opted in. + const wrapInSuspense = + canWrapInSuspense(router, route, match.ssr) && (route.options.wrapInSuspense ?? - PendingComponent ?? + pendingElement ?? ((route.options.errorComponent as any)?.preload || resolvedNoSsr)) - ? React.Suspense - : SafeFragment - const ResolvedCatchBoundary = routeErrorComponent - ? CatchBoundary - : SafeFragment + let content = <MatchInner match={match} /> + if (resolvedNoSsr) { + content = <ClientOnly fallback={pendingElement}>{content}</ClientOnly> + } + if (routeNotFoundComponent) { + content = ( + <CatchNotFound + fallback={(error) => { + error.routeId ??= match.routeId + if (error.routeId !== match.routeId) { + throw error + } + const notFoundElement = React.createElement( + routeNotFoundComponent, + error as any, + ) + return process.env.NODE_ENV !== 'production' + ? wrapInNonRouteComponentContext( + notFoundElement, + 'notFoundComponent', + ) + : notFoundElement + }} + > + {content} + </CatchNotFound> + ) + } + if (routeErrorComponent) { + content = ( + <CatchBoundary + getResetKey={() => match} + errorComponent={routeErrorComponent as any} + onCatch={(error, errorInfo) => { + // Not-found errors belong to the enclosing not-found boundary. + if (isNotFound(error)) { + error.routeId ??= match.routeId + throw error + } + if (process.env.NODE_ENV !== 'production') { + console.warn(`Warning: Error in route match: ${match.id}`) + } + routeOnCatch?.(error, errorInfo) + }} + > + {content} + </CatchBoundary> + ) + } + if (wrapInSuspense) { + content = ( + <React.Suspense fallback={pendingElement}>{content}</React.Suspense> + ) + } - const ResolvedNotFoundBoundary = routeNotFoundComponent - ? CatchNotFound - : SafeFragment + const scrollRestoration = + (isServer ?? router.isServer) && + route.parentRoute?.id === rootRouteId && + router.options.scrollRestoration ? ( + <ScrollRestoration /> + ) : null - const resetKey = useRouterState({ - select: (s) => s.loadedAt, - }) + const ShellComponent = + route.isRoot && (route.options as RootRouteOptions).shellComponent - const parentRouteId = useRouterState({ - select: (s) => { - const index = s.matches.findIndex((d) => d.id === matchId) - return s.matches[index - 1]?.routeId as string - }, - }) - - const ShellComponent = route.isRoot - ? ((route.options as RootRouteOptions).shellComponent ?? SafeFragment) - : SafeFragment - return ( - <ShellComponent> - <matchContext.Provider value={matchId}> - <ResolvedSuspenseBoundary fallback={pendingElement}> - <ResolvedCatchBoundary - getResetKey={() => resetKey} - errorComponent={routeErrorComponent || ErrorComponent} - onCatch={(error, errorInfo) => { - // Forward not found errors (we don't want to show the error component for these) - if (isNotFound(error)) throw error - warning(false, `Error in route match: ${matchId}`) - routeOnCatch?.(error, errorInfo) - }} - > - <ResolvedNotFoundBoundary - fallback={(error) => { - // If the current not found handler doesn't exist or it has a - // route ID which doesn't match the current route, rethrow the error - if ( - !routeNotFoundComponent || - (error.routeId && error.routeId !== matchState.routeId) || - (!error.routeId && !route.isRoot) - ) - throw error - - return React.createElement(routeNotFoundComponent, error as any) - }} - > - {resolvedNoSsr || matchState._displayPending ? ( - <ClientOnly fallback={pendingElement}> - <MatchInner matchId={matchId} /> - </ClientOnly> - ) : ( - <MatchInner matchId={matchId} /> - )} - </ResolvedNotFoundBoundary> - </ResolvedCatchBoundary> - </ResolvedSuspenseBoundary> - </matchContext.Provider> - {parentRouteId === rootRouteId && router.options.scrollRestoration ? ( - <> - <OnRendered /> - <ScrollRestoration /> - </> - ) : null} - </ShellComponent> - ) -}) - -// On Rendered can't happen above the root layout because it actually -// renders a dummy dom element to track the rendered state of the app. -// We render a script tag with a key that changes based on the current -// location state.__TSR_key. Also, because it's below the root layout, it -// allows us to fire onRendered events even after a hydration mismatch -// error that occurred above the root layout (like bad head/link tags, -// which is common). -function OnRendered() { - const router = useRouter() - - const prevLocationRef = React.useRef<undefined | ParsedLocation<{}>>( - undefined, - ) - - return ( - <script - key={router.latestLocation.state.__TSR_key} - suppressHydrationWarning - ref={(el) => { - if ( - el && - (prevLocationRef.current === undefined || - prevLocationRef.current.href !== router.latestLocation.href) - ) { - router.emit({ - type: 'onRendered', - ...getLocationChangeInfo(router.state), - }) - prevLocationRef.current = router.latestLocation - } - }} - /> + return ShellComponent ? ( + // The shell and route boundaries must share this match's context. + <matchContext.Provider value={match.routeId}> + <ShellComponent> + {content} + {scrollRestoration} + </ShellComponent> + </matchContext.Provider> + ) : ( + <matchContext.Provider value={match.routeId}> + {content} + {scrollRestoration} + </matchContext.Provider> ) } export const MatchInner = React.memo(function MatchInnerImpl({ - matchId, + match, }: { - matchId: string + match: AnyRouteMatch }): any { const router = useRouter() - - const { match, key, routeId } = useRouterState({ - select: (s) => { - const match = s.matches.find((d) => d.id === matchId)! - const routeId = match.routeId as string - - const remountFn = - (router.routesById[routeId] as AnyRoute).options.remountDeps ?? - router.options.defaultRemountDeps - const remountDeps = remountFn?.({ - routeId, - loaderDeps: match.loaderDeps, - params: match._strictParams, - search: match._strictSearch, - }) - const key = remountDeps ? JSON.stringify(remountDeps) : undefined - - return { - key, - routeId, - match: { - id: match.id, - status: match.status, - error: match.error, - _forcePending: match._forcePending, - _displayPending: match._displayPending, - }, - } - }, - structuralSharing: true as any, - }) - + const routeId = match.routeId const route = router.routesById[routeId] as AnyRoute - + const key = React.useMemo(() => { + const remountFn = + route.options.remountDeps ?? router.options.defaultRemountDeps + const remountDeps = remountFn?.({ + routeId, + loaderDeps: match.loaderDeps, + params: match._strictParams, + search: match._strictSearch, + }) + return remountDeps ? JSON.stringify(remountDeps) : undefined + }, [ + routeId, + match.loaderDeps, + match._strictParams, + match._strictSearch, + route.options.remountDeps, + router.options.defaultRemountDeps, + ]) const out = React.useMemo(() => { const Comp = route.options.component ?? router.options.defaultComponent - if (Comp) { - return <Comp key={key} /> - } - return <Outlet /> + return Comp ? <Comp key={key} /> : <Outlet /> }, [key, route.options.component, router.options.defaultComponent]) - if (match._displayPending) { - throw router.getMatch(match.id)?._nonReactive.displayPendingPromise - } - - if (match._forcePending) { - throw router.getMatch(match.id)?._nonReactive.minPendingPromise - } - - // see also hydrate() in packages/router-core/src/ssr/ssr-client.ts if (match.status === 'pending') { - // We're pending, and if we have a minPendingMs, we need to wait for it - const pendingMinMs = - route.options.pendingMinMs ?? router.options.defaultPendingMinMs - if (pendingMinMs) { - const routerMatch = router.getMatch(match.id) - if (routerMatch && !routerMatch._nonReactive.minPendingPromise) { - // Create a promise that will resolve after the minPendingMs - if (!router.isServer) { - const minPendingPromise = createControlledPromise<void>() - - routerMatch._nonReactive.minPendingPromise = minPendingPromise - - setTimeout(() => { - minPendingPromise.resolve() - // We've handled the minPendingPromise, so we can delete it - routerMatch._nonReactive.minPendingPromise = undefined - }, pendingMinMs) - } - } + if (router.ssr && !canWrapInSuspense(router, route, match.ssr)) { + // Replacing an SSR document root with pending UI would remove <html>. + // Hydrated matches retain their prior data, so keep rendering it. + return out } - throw router.getMatch(match.id)?._nonReactive.loadPromise + if (router._tx) { + throw router._tx[5] + } + return renderPending(router, route) } if (match.status === 'notFound') { - invariant(isNotFound(match.error), 'Expected a notFound error') return renderRouteNotFound(router, route, match.error) } - if (match.status === 'redirected') { - // Redirects should be handled by the router transition. If we happen to - // encounter a redirect here, it's a bug. Let's warn, but render nothing. - invariant(isRedirect(match.error), 'Expected a redirect error') - - // warning( - // false, - // 'Tried to render a redirected route match! This is a weird circumstance, please file an issue!', - // ) - throw router.getMatch(match.id)?._nonReactive.loadPromise - } - if (match.status === 'error') { - // If we're on the server, we need to use React's new and super - // wonky api for throwing errors from a server side render inside - // of a suspense boundary. This is the only way to get - // renderToPipeableStream to not hang indefinitely. - // We'll serialize the error and rethrow it on the client. - if (router.isServer) { + if (isServer ?? router.isServer) { const RouteErrorComponent = (route.options.errorComponent ?? router.options.defaultErrorComponent) || ErrorComponent - return ( + const errorElement = ( <RouteErrorComponent - error={match.error as any} + error={match.error} reset={undefined as any} info={{ componentStack: '', }} /> ) + return process.env.NODE_ENV !== 'production' + ? wrapInNonRouteComponentContext(errorElement, 'errorComponent') + : errorElement } - throw match.error } @@ -313,51 +262,65 @@ export const MatchInner = React.memo(function MatchInnerImpl({ * @link https://tanstack.com/router/latest/docs/framework/react/api/router/outletComponent */ export const Outlet = React.memo(function OutletImpl() { - const router = useRouter() - const matchId = React.useContext(matchContext) - const routeId = useRouterState({ - select: (s) => s.matches.find((d) => d.id === matchId)?.routeId as string, - }) - - const route = router.routesById[routeId]! - - const parentGlobalNotFound = useRouterState({ - select: (s) => { - const matches = s.matches - const parentMatch = matches.find((d) => d.id === matchId) - invariant( - parentMatch, - `Could not find parent match for matchId "${matchId}"`, + if (process.env.NODE_ENV !== 'production') { + // eslint-disable-next-line react-hooks/rules-of-hooks + const nonRouteComponent = React.useContext(nonRouteComponentContext!) + if (nonRouteComponent) { + console.warn( + `Warning: An <Outlet /> was rendered inside a ${nonRouteComponent}. <Outlet /> should only be rendered inside a route component.`, ) - return parentMatch.globalNotFound - }, - }) - - const childMatchId = useRouterState({ - select: (s) => { - const matches = s.matches - const index = matches.findIndex((d) => d.id === matchId) - return matches[index + 1]?.id - }, - }) - - const pendingElement = router.options.defaultPendingComponent ? ( - <router.options.defaultPendingComponent /> - ) : null - - if (parentGlobalNotFound) { - return renderRouteNotFound(router, route, undefined) + } } - if (!childMatchId) { + const router = useRouter() + const routeId = React.useContext(matchContext)! + + let parentGlobalNotFound: boolean + let parentNotFoundError: unknown + let childRouteId: string | undefined + + if (isServer ?? router.isServer) { + const matches = router.stores.matches.get() + const parentIndex = matches.findIndex((match) => match.routeId === routeId) + const parentMatch = matches[parentIndex]! + parentGlobalNotFound = !!parentMatch._notFound + parentNotFoundError = parentMatch.error + childRouteId = matches[parentIndex + 1]?.routeId + } else { + const parentMatchStore = router.stores.getMatchStore(routeId) + + // eslint-disable-next-line react-hooks/rules-of-hooks + ;[parentGlobalNotFound, parentNotFoundError] = useSelector( + parentMatchStore, + (match): OutletMatchSelection => [!!match!._notFound, match!.error], + { compare: outletMatchSelectionEqual }, + ) + + // eslint-disable-next-line react-hooks/rules-of-hooks + childRouteId = useSelector(router.stores.ids, (ids) => { + return ids[ids.indexOf(routeId) + 1] + }) + } + + if (parentGlobalNotFound) { + return renderRouteNotFound( + router, + router.routesById[routeId], + parentNotFoundError, + ) + } + + if (!childRouteId) { return null } - const nextMatch = <Match matchId={childMatchId} /> + const nextMatch = <Match routeId={childRouteId} /> if (routeId === rootRouteId) { return ( - <React.Suspense fallback={pendingElement}>{nextMatch}</React.Suspense> + <React.Suspense fallback={renderPending(router)}> + {nextMatch} + </React.Suspense> ) } diff --git a/packages/react-router/src/Matches.tsx b/packages/react-router/src/Matches.tsx index 0d64831d94..a20c862b23 100644 --- a/packages/react-router/src/Matches.tsx +++ b/packages/react-router/src/Matches.tsx @@ -1,13 +1,16 @@ +'use client' + import * as React from 'react' -import warning from 'tiny-warning' +import { useSelector } from '@tanstack/react-store' import { rootRouteId } from '@tanstack/router-core' -import { CatchBoundary, ErrorComponent } from './CatchBoundary' -import { useRouterState } from './useRouterState' +import { isServer } from '@tanstack/router-core/isServer' +import { CatchBoundary } from './CatchBoundary' import { useRouter } from './useRouter' -import { Transitioner } from './Transitioner' +import { useStructuralSharing } from './useMatch' +import { useLayoutEffect } from './utils' +import { Transitioner, settleOwner } from './Transitioner' import { matchContext } from './matchContext' -import { Match } from './Match' -import { SafeFragment } from './SafeFragment' +import { Match, renderPending } from './Match' import type { StructuralSharingOption, ValidateSelected, @@ -22,12 +25,8 @@ import type { MakeRouteMatchUnion, MaskOptions, MatchRouteOptions, - NoInfer, RegisteredRouter, - ResolveRelativePath, ResolveRoute, - RouteByPath, - RouterState, ToSubOptionsProps, } from '@tanstack/router-core' @@ -49,22 +48,28 @@ export function Matches() { const router = useRouter() const rootRoute: AnyRoute = router.routesById[rootRouteId] - const PendingComponent = - rootRoute.options.pendingComponent ?? router.options.defaultPendingComponent - - const pendingElement = PendingComponent ? <PendingComponent /> : null - - // Do not render a root Suspense during SSR or hydrating from SSR - const ResolvedSuspense = - router.isServer || (typeof document !== 'undefined' && router.ssr) - ? SafeFragment - : React.Suspense + const pendingElement = renderPending(router, rootRoute) const inner = ( - <ResolvedSuspense fallback={pendingElement}> - {!router.isServer && <Transitioner />} - <MatchesInner /> - </ResolvedSuspense> + <> + {!(isServer ?? router.isServer) && ( + <Transitioner + // The initial load publishes matches before MatchesInner's store + // subscription is active. Storing the router here forces Matches to render + // that first publication before paint. Later publications store the same + // router object, so React skips the update. + // eslint-disable-next-line react-hooks/rules-of-hooks -- server only, condition is static + t={React.useState<AnyRouter>()[1]} + /> + )} + {(isServer ?? router.isServer) || router.ssr ? ( + <MatchesInner /> + ) : ( + <React.Suspense fallback={pendingElement}> + <MatchesInner /> + </React.Suspense> + )} + </> ) return router.options.InnerWrap ? ( @@ -76,38 +81,44 @@ export function Matches() { function MatchesInner() { const router = useRouter() - const matchId = useRouterState({ - select: (s) => { - return s.matches[0]?.id - }, - }) + const acknowledgement = router._rendered! + const matches = + (isServer ?? router.isServer) + ? router.stores.matches.get() + : // eslint-disable-next-line react-hooks/rules-of-hooks + useSelector( + router.stores.matches, + (value) => acknowledgement[0 /* offered */] ?? value, + ) + const match = matches[0] + const routeId = match?.routeId - const resetKey = useRouterState({ - select: (s) => s.loadedAt, - }) + useLayoutEffect(() => { + if (acknowledgement[0 /* offered */] === matches) { + settleOwner(acknowledgement, true) + } + }, [acknowledgement, matches]) - const matchComponent = matchId ? <Match matchId={matchId} /> : null + const matchComponent = routeId ? <Match routeId={routeId} /> : null - return ( - <matchContext.Provider value={matchId}> - {router.options.disableGlobalCatchBoundary ? ( - matchComponent - ) : ( - <CatchBoundary - getResetKey={() => resetKey} - errorComponent={ErrorComponent} - onCatch={(error) => { - warning( - false, - `The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`, - ) - warning(false, error.message || error.toString()) - }} - > - {matchComponent} - </CatchBoundary> - )} - </matchContext.Provider> + return router.options.disableGlobalCatchBoundary ? ( + matchComponent + ) : ( + <CatchBoundary + getResetKey={() => match} + onCatch={ + process.env.NODE_ENV !== 'production' + ? (error) => { + console.warn( + `Warning: The following error wasn't caught by any route! At the very least, consider setting an 'errorComponent' in your RootRoute!`, + ) + console.warn('Warning:', error) + } + : undefined + } + > + {matchComponent} + </CatchBoundary> ) } @@ -130,30 +141,40 @@ export type UseMatchRouteOptions< * `search`, etc.) and returns either `false` (no match) or the matched params * object when the route matches the current or pending location. * - * Useful for conditional rendering and active UI states. + * Useful for conditional rendering and active UI states because it subscribes + * the component to the router state used for matching. The returned function's + * identity changes when that state changes. For imperative checks in event + * handlers, get the router with `useRouter` and call `router.matchRoute(...)` + * to avoid that subscription. * * @returns A `matchRoute(options)` function that returns `false` or params. * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchRouteHook */ -export function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>() { +export function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>(): < + const TFrom extends string = string, + const TTo extends string | undefined = undefined, + const TMaskFrom extends string = TFrom, + const TMaskTo extends string = '', +>( + opts: UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>, +) => false | Expand<ResolveRoute<TRouter, TFrom, TTo>['types']['allParams']> { const router = useRouter() + if (isServer ?? router.isServer) { + return (opts) => { + const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts - useRouterState({ - select: (s) => [s.location.href, s.resolvedLocation?.href, s.status], - structuralSharing: true as any, - }) + return router.matchRoute(rest as any, { + pending, + caseSensitive, + fuzzy, + includeSearch, + }) + } + } + // eslint-disable-next-line react-hooks/rules-of-hooks return React.useCallback( - < - const TFrom extends string = string, - const TTo extends string | undefined = undefined, - const TMaskFrom extends string = TFrom, - const TMaskTo extends string = '', - >( - opts: UseMatchRouteOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>, - ): - | false - | Expand<ResolveRoute<TRouter, TFrom, TTo>['types']['allParams']> => { + (opts) => { const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts return router.matchRoute(rest as any, { @@ -163,7 +184,15 @@ export function useMatchRoute<TRouter extends AnyRouter = RegisteredRouter>() { includeSearch, }) }, - [router], + [ + router, + // eslint-disable-next-line react-hooks/rules-of-hooks, react-hooks/exhaustive-deps + useSelector(router.stores.location, (location) => location.href), + // eslint-disable-next-line react-hooks/rules-of-hooks, react-hooks/exhaustive-deps + useSelector(router.stores.resolvedLocation, (location) => location?.href), + // eslint-disable-next-line react-hooks/rules-of-hooks, react-hooks/exhaustive-deps + useSelector(router.stores.status), + ], ) } @@ -177,10 +206,9 @@ export type MakeMatchRouteOptions< // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns children?: | (( - params?: RouteByPath< - TRouter['routeTree'], - ResolveRelativePath<TFrom, NoInfer<TTo>> - >['types']['allParams'], + params?: Expand< + ResolveRoute<TRouter, TFrom, TTo>['types']['allParams'] + >, ) => React.ReactNode) | React.ReactNode } @@ -232,32 +260,29 @@ export function useMatches< opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, ): UseMatchesResult<TRouter, TSelected> { - return useRouterState({ - select: (state: RouterState<TRouter['routeTree']>) => { - const matches = state.matches - return opts?.select - ? opts.select(matches as Array<MakeRouteMatchUnion<TRouter>>) - : matches - }, - structuralSharing: opts?.structuralSharing, - } as any) as UseMatchesResult<TRouter, TSelected> + const router = useRouter<TRouter>() + + if (isServer ?? router.isServer) { + const matches = router.stores.matches.get() as Array< + MakeRouteMatchUnion<TRouter> + > + return (opts?.select ? opts.select(matches) : matches) as UseMatchesResult< + TRouter, + TSelected + > + } + + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + return useSelector( + router.stores.matches, + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + useStructuralSharing(opts, router), + ) as UseMatchesResult<TRouter, TSelected> } /** - * Read the full array of active route matches or select a derived subset. - * - * Useful for debugging, breadcrumbs, or aggregating metadata across matches. - * - * @returns The array of matches (or the selected value). - * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook - */ - -/** - * Read the full array of active route matches or select a derived subset. - * - * Useful for debugging, breadcrumbs, or aggregating metadata across matches. - * - * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook + * Read the presented route matches above the current match, or select a + * derived value from them. */ export function useParentMatches< TRouter extends AnyRouter = RegisteredRouter, @@ -267,13 +292,13 @@ export function useParentMatches< opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, ): UseMatchesResult<TRouter, TSelected> { - const contextMatchId = React.useContext(matchContext) + const contextRouteId = React.useContext(matchContext) return useMatches({ select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => { matches = matches.slice( 0, - matches.findIndex((d) => d.id === contextMatchId), + matches.findIndex((d) => d.routeId === contextRouteId), ) return opts?.select ? opts.select(matches) : matches }, @@ -282,8 +307,8 @@ export function useParentMatches< } /** - * Read the array of active route matches that are children of the current - * match (or selected parent) in the match tree. + * Read the presented route matches below the current match, or select a + * derived value from them. */ export function useChildMatches< TRouter extends AnyRouter = RegisteredRouter, @@ -293,12 +318,12 @@ export function useChildMatches< opts?: UseMatchesBaseOptions<TRouter, TSelected, TStructuralSharing> & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, ): UseMatchesResult<TRouter, TSelected> { - const contextMatchId = React.useContext(matchContext) + const contextRouteId = React.useContext(matchContext) return useMatches({ select: (matches: Array<MakeRouteMatchUnion<TRouter>>) => { matches = matches.slice( - matches.findIndex((d) => d.id === contextMatchId) + 1, + matches.findIndex((d) => d.routeId === contextRouteId) + 1, ) return opts?.select ? opts.select(matches) : matches }, diff --git a/packages/react-router/src/RouterProvider.tsx b/packages/react-router/src/RouterProvider.tsx index fd2aeb1eef..e61cdf1b8a 100644 --- a/packages/react-router/src/RouterProvider.tsx +++ b/packages/react-router/src/RouterProvider.tsx @@ -1,6 +1,9 @@ +'use client' + import * as React from 'react' +import { hasKeys } from '@tanstack/router-core' import { Matches } from './Matches' -import { getRouterContext } from './routerContext' +import { routerContext } from './routerContext' import type { AnyRouter, RegisteredRouter, @@ -21,7 +24,7 @@ export function RouterContextProvider< }: RouterProps<TRouter, TDehydrated> & { children: React.ReactNode }) { - if (Object.keys(rest).length > 0) { + if (hasKeys(rest)) { // Allow the router to update options on the router instance router.update({ ...router.options, @@ -30,11 +33,9 @@ export function RouterContextProvider< ...router.options.context, ...rest.context, }, - } as any) + }) } - const routerContext = getRouterContext() - const provider = ( <routerContext.Provider value={router as AnyRouter}> {children} @@ -49,11 +50,11 @@ export function RouterContextProvider< } /** - * Top-level component that renders the active route matches and provides the - * router to the React tree via context. + * Renders the current match presentation and provides the router to the React + * tree via context. * - * Accepts the same options as `createRouter` via props to update the router - * instance after creation. + * Accepts mutable router options via props. Configure initialization-only + * options with `createRouter`. * * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouterFunction */ @@ -79,7 +80,7 @@ export type RouterProps< TRouter['history'], TDehydrated >, - 'context' + 'context' | 'pathParamsAllowedCharacters' > & { router: TRouter context?: Partial< diff --git a/packages/react-router/src/SafeFragment.tsx b/packages/react-router/src/SafeFragment.tsx deleted file mode 100644 index 72a95bac01..0000000000 --- a/packages/react-router/src/SafeFragment.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import * as React from 'react' - -export function SafeFragment(props: any) { - return <>{props.children}</> -} diff --git a/packages/react-router/src/ScriptOnce.tsx b/packages/react-router/src/ScriptOnce.tsx index 97609c6fc7..f552becb9f 100644 --- a/packages/react-router/src/ScriptOnce.tsx +++ b/packages/react-router/src/ScriptOnce.tsx @@ -1,3 +1,4 @@ +import { isServer } from '@tanstack/router-core/isServer' import { useRouter } from './useRouter' /** @@ -5,7 +6,7 @@ import { useRouter } from './useRouter' */ export function ScriptOnce({ children }: { children: string }) { const router = useRouter() - if (!router.isServer) { + if (!(isServer ?? router.isServer)) { return null } diff --git a/packages/react-router/src/Scripts.tsx b/packages/react-router/src/Scripts.tsx index e7fced4d72..56afe0a443 100644 --- a/packages/react-router/src/Scripts.tsx +++ b/packages/react-router/src/Scripts.tsx @@ -1,78 +1,71 @@ +import { useSelector } from '@tanstack/react-store' +import { + composeSsrBodyScripts, + deepEqual, + getSsrBodyScriptParts, +} from '@tanstack/router-core' +import { isServer } from '@tanstack/router-core/isServer' import { Asset } from './Asset' -import { useRouterState } from './useRouterState' import { useRouter } from './useRouter' import type { RouterManagedTag } from '@tanstack/router-core' +type ScriptRenderAsset = RouterManagedTag & { + preventScriptHoist?: boolean +} + +const routeScriptAttrs = { suppressHydrationWarning: true } + /** * Render body script tags collected from route matches and SSR manifests. - * Should be placed near the end of the document body. + * During streaming SSR, `<Scripts>` marks where late hydration scripts may + * begin to be inserted. */ export const Scripts = () => { const router = useRouter() const nonce = router.options.ssr?.nonce - const assetScripts = useRouterState({ - select: (state) => { - const assetScripts: Array<RouterManagedTag> = [] - const manifest = router.ssr?.manifest - if (!manifest) { - return [] + const getParts = (matches: Array<any>) => { + const parts = getSsrBodyScriptParts( + matches, + router.ssr?.manifest, + nonce, + routeScriptAttrs, + ) + for (const script of parts[1]) { + if (typeof script.attrs?.src === 'string') { + const scriptWithHoist = script as ScriptRenderAsset + scriptWithHoist.preventScriptHoist = true } - - state.matches - .map((match) => router.looseRoutesById[match.routeId]!) - .forEach((route) => - manifest.routes[route.id]?.assets - ?.filter((d) => d.tag === 'script') - .forEach((asset) => { - assetScripts.push({ - tag: 'script', - attrs: { ...asset.attrs, nonce }, - children: asset.children, - } as any) - }), - ) - - return assetScripts - }, - structuralSharing: true as any, - }) - - const { scripts } = useRouterState({ - select: (state) => ({ - scripts: ( - state.matches - .map((match) => match.scripts!) - .flat(1) - .filter(Boolean) as Array<RouterManagedTag> - ).map(({ children, ...script }) => ({ - tag: 'script', - attrs: { - ...script, - suppressHydrationWarning: true, - nonce, - }, - children, - })), - }), - structuralSharing: true as any, - }) - - let serverBufferedScript: RouterManagedTag | undefined = undefined - - if (router.serverSsr) { - serverBufferedScript = router.serverSsr.takeBufferedScripts() + } + return parts } - const allScripts = [...scripts, ...assetScripts] as Array<RouterManagedTag> - - if (serverBufferedScript) { - allScripts.unshift(serverBufferedScript) + const getScripts = (matches: Array<any>) => { + return composeSsrBodyScripts(getParts(matches)) } + if (isServer ?? router.isServer) { + const activeMatches = router.stores.matches.get() + return renderScripts( + composeSsrBodyScripts( + getParts(activeMatches), + router.serverSsr?.takeInitialHydrationScriptTags(), + ), + ) + } + + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + const scripts = useSelector(router.stores.matches, getScripts, { + compare: deepEqual, + }) + + return renderScripts(scripts) +} + +function renderScripts(scripts: Array<ScriptRenderAsset>) { return ( <> - {allScripts.map((asset, i) => ( + {scripts.map((asset, i) => ( <Asset {...asset} key={`tsr-scripts-${asset.tag}-${i}`} /> ))} </> diff --git a/packages/react-router/src/ScrollRestoration.tsx b/packages/react-router/src/ScrollRestoration.tsx index 55591c92ce..d36210db41 100644 --- a/packages/react-router/src/ScrollRestoration.tsx +++ b/packages/react-router/src/ScrollRestoration.tsx @@ -1,7 +1,5 @@ import { - defaultGetScrollRestorationKey, - getCssSelector, - scrollRestorationCache, + getElementScrollRestorationEntry, setupScrollRestoration, } from '@tanstack/router-core' import { useRouter } from './useRouter' @@ -47,23 +45,5 @@ export function useElementScrollRestoration( ): ScrollRestorationEntry | undefined { useScrollRestoration() - const router = useRouter() - const getKey = options.getKey || defaultGetScrollRestorationKey - - let elementSelector = '' - - if (options.id) { - elementSelector = `[data-scroll-restoration-id="${options.id}"]` - } else { - const element = options.getElement?.() - if (!element) { - return - } - elementSelector = - element instanceof Window ? 'window' : getCssSelector(element) - } - - const restoreKey = getKey(router.latestLocation) - const byKey = scrollRestorationCache?.state[restoreKey] - return byKey?.[elementSelector] + return getElementScrollRestorationEntry(useRouter(), options) } diff --git a/packages/react-router/src/Transitioner.tsx b/packages/react-router/src/Transitioner.tsx index f547cdd5f5..ddf8afea2e 100644 --- a/packages/react-router/src/Transitioner.tsx +++ b/packages/react-router/src/Transitioner.tsx @@ -1,50 +1,56 @@ +'use client' + import * as React from 'react' -import { - getLocationChangeInfo, - handleHashScroll, - trimPathRight, -} from '@tanstack/router-core' -import { useLayoutEffect, usePrevious } from './utils' +import { getLocationChangeInfo, trimPathRight } from '@tanstack/router-core' +import { useLayoutEffect } from './utils' import { useRouter } from './useRouter' -import { useRouterState } from './useRouterState' +import type { AnyRouter } from '@tanstack/router-core' -export function Transitioner() { +export function settleOwner( + owner: NonNullable<AnyRouter['_rendered']>, + rendered: boolean, +) { + const settle = owner[1 /* settle */] + owner.length = 0 + settle?.(rendered) +} + +export function Transitioner({ + t, +}: { + t: React.Dispatch<React.SetStateAction<AnyRouter | undefined>> +}) { const router = useRouter() - const mountLoadForRouter = React.useRef({ router, mounted: false }) + const acknowledgement = (router._rendered ??= []) + const mounted = + process.env.NODE_ENV !== 'production' + ? // eslint-disable-next-line react-hooks/rules-of-hooks + React.useRef(false) + : undefined - const [isTransitioning, setIsTransitioning] = React.useState(false) - // Track pending state changes - const { hasPendingMatches, isLoading } = useRouterState({ - select: (s) => ({ - isLoading: s.isLoading, - hasPendingMatches: s.matches.some((d) => d.status === 'pending'), - }), - structuralSharing: true, - }) - - const previousIsLoading = usePrevious(isLoading) - - const isAnyPending = isLoading || isTransitioning || hasPendingMatches - const previousIsAnyPending = usePrevious(isAnyPending) - - const isPagePending = isLoading || hasPendingMatches - const previousIsPagePending = usePrevious(isPagePending) - - router.startTransition = (fn: () => void) => { - setIsTransitioning(true) - React.startTransition(() => { - fn() - setIsTransitioning(false) + router.startTransition = (fn, expected) => + new Promise((resolve) => { + settleOwner(acknowledgement, false) + acknowledgement.push(expected, resolve) + t(router) + React.startTransition(fn) }) - } - // Subscribe to location changes - // and try to load the new location - React.useEffect(() => { + // Subscribe before canonicalizing so the initial URL has exactly one load. + useLayoutEffect(() => { const unsub = router.history.subscribe(router.load) + if (mounted?.current) { + return unsub + } + if (mounted) { + mounted.current = true + } + + router.updateLatestLocation() + const location = router.latestLocation const nextLocation = router.buildLocation({ - to: router.latestLocation.pathname, + to: location.pathname, search: true, params: true, hash: true, @@ -52,80 +58,42 @@ export function Transitioner() { _includeValidateSearch: true, }) + // Check if the current URL matches the canonical form. + // Compare publicHref (browser-facing URL) consistently with server + // canonicalization. if ( - trimPathRight(router.latestLocation.href) !== - trimPathRight(nextLocation.href) + trimPathRight(location.publicHref) !== + trimPathRight(nextLocation.publicHref) ) { - router.commitLocation({ ...nextLocation, replace: true }) + router.commitLocation({ + ...nextLocation, + replace: true, + ignoreBlocker: true, + }) + return unsub } - return () => { - unsub() + const resolvedLocation = router.stores.resolvedLocation.get() + if ( + resolvedLocation?.href === location.href && + resolvedLocation.state.__TSR_key === location.state.__TSR_key + ) { + acknowledgement.push(router.stores.matches.get(), (rendered) => { + if (rendered) { + router.emit({ + type: 'onRendered', + ...getLocationChangeInfo(resolvedLocation, resolvedLocation), + }) + } + }) + } else if (!router._tx) { + router.load({ sync: true }).catch(console.error) } + + return unsub + // `mounted` exists only in development and is a stable ref when present. + // eslint-disable-next-line react-hooks/exhaustive-deps }, [router, router.history]) - // Try to load the initial location - useLayoutEffect(() => { - if ( - // if we are hydrating from SSR, loading is triggered in ssr-client - (typeof window !== 'undefined' && router.ssr) || - (mountLoadForRouter.current.router === router && - mountLoadForRouter.current.mounted) - ) { - return - } - mountLoadForRouter.current = { router, mounted: true } - - const tryLoad = async () => { - try { - await router.load() - } catch (err) { - console.error(err) - } - } - - tryLoad() - }, [router]) - - useLayoutEffect(() => { - // The router was loading and now it's not - if (previousIsLoading && !isLoading) { - router.emit({ - type: 'onLoad', // When the new URL has committed, when the new matches have been loaded into state.matches - ...getLocationChangeInfo(router.state), - }) - } - }, [previousIsLoading, router, isLoading]) - - useLayoutEffect(() => { - // emit onBeforeRouteMount - if (previousIsPagePending && !isPagePending) { - router.emit({ - type: 'onBeforeRouteMount', - ...getLocationChangeInfo(router.state), - }) - } - }, [isPagePending, previousIsPagePending, router]) - - useLayoutEffect(() => { - if (previousIsAnyPending && !isAnyPending) { - const changeInfo = getLocationChangeInfo(router.state) - router.emit({ - type: 'onResolved', - ...changeInfo, - }) - - router.__store.setState((s: typeof router.state) => ({ - ...s, - status: 'idle', - resolvedLocation: s.location, - })) - - if (changeInfo.hrefChanged) { - handleHashScroll(router) - } - } - }, [isAnyPending, previousIsAnyPending, router]) - return null } diff --git a/packages/react-router/src/awaited.tsx b/packages/react-router/src/awaited.tsx index 75ff49b8a8..c3397bd433 100644 --- a/packages/react-router/src/awaited.tsx +++ b/packages/react-router/src/awaited.tsx @@ -1,16 +1,18 @@ import * as React from 'react' import { TSR_DEFERRED_PROMISE, defer } from '@tanstack/router-core' -import type { DeferredPromise } from '@tanstack/router-core' +import { reactUse } from './utils' export type AwaitOptions<T> = { promise: Promise<T> } /** Suspend until a deferred promise resolves or rejects and return its data. */ -export function useAwaited<T>({ - promise: _promise, -}: AwaitOptions<T>): [T, DeferredPromise<T>] { +export function useAwaited<T>({ promise: _promise }: AwaitOptions<T>): T { + if (reactUse) { + const data = reactUse(_promise) + return data + } const promise = defer(_promise) if (promise[TSR_DEFERRED_PROMISE].status === 'pending') { @@ -21,7 +23,7 @@ export function useAwaited<T>({ throw promise[TSR_DEFERRED_PROMISE].error } - return [promise[TSR_DEFERRED_PROMISE].data, promise] + return promise[TSR_DEFERRED_PROMISE].data } /** @@ -47,7 +49,7 @@ function AwaitInner<T>( children: (result: T) => React.ReactNode }, ): React.JSX.Element { - const [data] = useAwaited(props) + const data = useAwaited(props) return props.children(data) as React.JSX.Element } diff --git a/packages/react-router/src/fileRoute.ts b/packages/react-router/src/fileRoute.ts index 7af8877d1a..f4d8c9b967 100644 --- a/packages/react-router/src/fileRoute.ts +++ b/packages/react-router/src/fileRoute.ts @@ -1,4 +1,3 @@ -import warning from 'tiny-warning' import { createRoute } from './route' import { useMatch } from './useMatch' @@ -8,6 +7,7 @@ import { useSearch } from './useSearch' import { useParams } from './useParams' import { useNavigate } from './useNavigate' import { useRouter } from './useRouter' +import { useRouteContext } from './useRouteContext' import type { UseParamsRoute } from './useParams' import type { UseMatchRoute } from './useMatch' import type { UseSearchRoute } from './useSearch' @@ -27,7 +27,7 @@ import type { RouteById, RouteConstraints, RouteIds, - RouteLoaderFn, + RouteLoaderEntry, UpdatableRouteOptions, UseNavigateResult, } from '@tanstack/router-core' @@ -51,19 +51,17 @@ export function createFileRoute< TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'], TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'], TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'], - TFullPath extends - RouteConstraints['TFullPath'] = FileRoutesByPath[TFilePath]['fullPath'], + TFullPath extends RouteConstraints['TFullPath'] = + FileRoutesByPath[TFilePath]['fullPath'], >( + // eslint-disable-next-line unused-imports/no-unused-vars path?: TFilePath, ): FileRoute<TFilePath, TParentRoute, TId, TPath, TFullPath>['createRoute'] { - if (typeof path === 'object') { - return new FileRoute<TFilePath, TParentRoute, TId, TPath, TFullPath>(path, { - silent: true, - }).createRoute(path) as any + return (options) => { + const route = createRoute(options as any) + ;(route as any).isRoot = false + return route as any } - return new FileRoute<TFilePath, TParentRoute, TId, TPath, TFullPath>(path, { - silent: true, - }).createRoute } /** @@ -75,8 +73,8 @@ export class FileRoute< TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'], TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'], TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'], - TFullPath extends - RouteConstraints['TFullPath'] = FileRoutesByPath[TFilePath]['fullPath'], + TFullPath extends RouteConstraints['TFullPath'] = + FileRoutesByPath[TFilePath]['fullPath'], > { silent?: boolean @@ -149,10 +147,13 @@ export class FileRoute< TMiddlewares, THandlers > => { - warning( - this.silent, - 'FileRoute is deprecated and will be removed in the next major version. Use the createFileRoute(path)(options) function instead.', - ) + if (process.env.NODE_ENV !== 'production') { + if (!this.silent) { + console.warn( + 'Warning: FileRoute is deprecated and will be removed in the next major version. Use the createFileRoute(path)(options) function instead.', + ) + } + } const route = createRoute(options as any) ;(route as any).isRoot = false return route as any @@ -171,7 +172,7 @@ export function FileRouteLoader< ): <TLoaderFn>( loaderFn: Constrain< TLoaderFn, - RouteLoaderFn< + RouteLoaderEntry< Register, TRoute['parentRoute'], TRoute['types']['id'], @@ -183,10 +184,11 @@ export function FileRouteLoader< > >, ) => TLoaderFn { - warning( - false, - `FileRouteLoader is deprecated and will be removed in the next major version. Please place the loader function in the the main route file, inside the \`createFileRoute('/path/to/file')(options)\` options`, - ) + if (process.env.NODE_ENV !== 'production') { + console.warn( + `Warning: FileRouteLoader is deprecated and will be removed in the next major version. Please place the loader function in the main route file, inside the \`createFileRoute('/path/to/file')(options)\` options`, + ) + } return (loaderFn) => loaderFn as any } @@ -213,40 +215,22 @@ export class LazyRoute<TRoute extends AnyRoute> { } & LazyRouteOptions, ) { this.options = opts - ;(this as any).$$typeof = Symbol.for('react.memo') } useMatch: UseMatchRoute<TRoute['id']> = (opts) => { - return useMatch({ - select: opts?.select, - from: this.options.id, - structuralSharing: opts?.structuralSharing, - } as any) as any + return useMatch({ ...opts, from: this.options.id } as any) as any } useRouteContext: UseRouteContextRoute<TRoute['id']> = (opts) => { - return useMatch({ - from: this.options.id, - select: (d: any) => (opts?.select ? opts.select(d.context) : d.context), - }) as any + return useRouteContext({ ...(opts as any), from: this.options.id }) } useSearch: UseSearchRoute<TRoute['id']> = (opts) => { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion - return useSearch({ - select: opts?.select, - structuralSharing: opts?.structuralSharing, - from: this.options.id, - } as any) as any + return useSearch({ ...opts, from: this.options.id } as any) } useParams: UseParamsRoute<TRoute['id']> = (opts) => { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion - return useParams({ - select: opts?.select, - structuralSharing: opts?.structuralSharing, - from: this.options.id, - } as any) as any + return useParams({ ...opts, from: this.options.id } as any) } useLoaderDeps: UseLoaderDepsRoute<TRoute['id']> = (opts) => { diff --git a/packages/react-router/src/headContentUtils.tsx b/packages/react-router/src/headContentUtils.tsx new file mode 100644 index 0000000000..d517e0e453 --- /dev/null +++ b/packages/react-router/src/headContentUtils.tsx @@ -0,0 +1,216 @@ +import * as React from 'react' +import { useSelector } from '@tanstack/react-store' +import { + _getAssetMatches, + appendUniqueUserTags, + deepEqual, + escapeHtml, + getAssetCrossOrigin, + getScriptPreloadAttrs, + resolveManifestCssLink, +} from '@tanstack/router-core' +import { isServer } from '@tanstack/router-core/isServer' +import { useRouter } from './useRouter' +import type { + AnyRouteMatch, + AssetCrossOriginConfig, + RouterManagedTag, +} from '@tanstack/router-core' + +function buildTagsFromMatches( + router: ReturnType<typeof useRouter>, + nonce: string | undefined, + matches: Array<AnyRouteMatch>, + assetCrossOrigin?: AssetCrossOriginConfig, +): Array<RouterManagedTag> { + matches = _getAssetMatches(matches) + const routeMeta = matches + .map((match) => match.meta) + .filter((meta) => meta !== undefined) + + const resultMeta: Array<RouterManagedTag> = [] + const metaByAttribute: Record<string, true> = {} + let title: RouterManagedTag | undefined + for (let i = routeMeta.length - 1; i >= 0; i--) { + const metas = routeMeta[i]! + for (let j = metas.length - 1; j >= 0; j--) { + const m = metas[j] + if (!m) continue + + if (m.title) { + if (!title) { + title = { + tag: 'title', + children: m.title, + } + } + } else if ('script:ld+json' in m) { + try { + const json = JSON.stringify(m['script:ld+json']) + resultMeta.push({ + tag: 'script', + attrs: { + type: 'application/ld+json', + }, + children: escapeHtml(json), + }) + } catch { + // Skip invalid JSON-LD objects + } + } else { + const attribute = m.name ?? m.property + if (attribute) { + if (metaByAttribute[attribute]) { + continue + } else { + metaByAttribute[attribute] = true + } + } + + resultMeta.push({ + tag: 'meta', + attrs: { + ...m, + nonce, + }, + }) + } + } + } + + if (title) { + resultMeta.push(title) + } + + if (nonce) { + resultMeta.push({ + tag: 'meta', + attrs: { + property: 'csp-nonce', + content: nonce, + }, + }) + } + resultMeta.reverse() + + const constructedLinks = matches + .flatMap((match) => match.links ?? []) + .filter((link) => link !== undefined) + .map((link) => ({ + tag: 'link', + attrs: { + ...link, + nonce, + }, + })) satisfies Array<RouterManagedTag> + + const manifest = router.ssr?.manifest + const manifestCssTags: Array<RouterManagedTag> = [] + if (manifest) { + matches.forEach((match) => { + const css = manifest.routes[match.routeId]?.css + css?.forEach((link) => { + const resolvedLink = resolveManifestCssLink(link) + manifestCssTags.push({ + tag: 'link', + attrs: { + rel: 'stylesheet', + ...resolvedLink, + crossOrigin: + getAssetCrossOrigin(assetCrossOrigin, 'stylesheet') ?? + resolvedLink.crossOrigin, + suppressHydrationWarning: true, + nonce, + }, + }) + }) + }) + + if (manifest.inlineStyle) { + manifestCssTags.push({ + tag: 'style', + attrs: { + ...manifest.inlineStyle.attrs, + nonce, + }, + children: manifest.inlineStyle.children, + inlineCss: true, + }) + } + } + + const preloadLinks: Array<RouterManagedTag> = [] + if (manifest) { + matches.forEach((match) => { + manifest.routes[match.routeId]?.preloads?.forEach((preload) => { + preloadLinks.push({ + tag: 'link', + attrs: { + ...getScriptPreloadAttrs(manifest, preload, assetCrossOrigin), + nonce, + }, + }) + }) + }) + } + + const styles = matches + .flatMap((match) => match.styles ?? []) + .filter((style) => style !== undefined) + .map(({ children, ...attrs }) => ({ + tag: 'style', + attrs: { + ...attrs, + nonce, + }, + children: children as string | undefined, + })) satisfies Array<RouterManagedTag> + + const headScripts = matches + .flatMap((match) => match.headScripts ?? []) + .filter((script) => script !== undefined) + .map(({ children, ...script }) => ({ + tag: 'script', + attrs: { + ...script, + nonce, + }, + children: children as string | undefined, + })) satisfies Array<RouterManagedTag> + + const tags: Array<RouterManagedTag> = [] + appendUniqueUserTags(tags, resultMeta) + tags.push(...preloadLinks) + appendUniqueUserTags(tags, constructedLinks) + tags.push(...manifestCssTags) + appendUniqueUserTags(tags, styles) + appendUniqueUserTags(tags, headScripts) + return tags +} + +/** + * Build the head/link/meta/script tags from the renderable presented prefix. + * Used internally by `HeadContent`. + */ +export const useTags = (assetCrossOrigin?: AssetCrossOriginConfig) => { + const router = useRouter() + const nonce = router.options.ssr?.nonce + + if (isServer ?? router.isServer) { + return buildTagsFromMatches( + router, + nonce, + router.stores.matches.get(), + assetCrossOrigin, + ) + } + + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + const selectTags = React.useCallback( + (matches: Array<AnyRouteMatch>) => + buildTagsFromMatches(router, nonce, matches, assetCrossOrigin), + [assetCrossOrigin, nonce, router], + ) + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + return useSelector(router.stores.matches, selectTags, { compare: deepEqual }) +} diff --git a/packages/react-router/src/index.dev.tsx b/packages/react-router/src/index.dev.tsx new file mode 100644 index 0000000000..dde6fd2eea --- /dev/null +++ b/packages/react-router/src/index.dev.tsx @@ -0,0 +1,8 @@ +'use client' + +// Development entry point - re-exports everything from index.tsx +// but overrides HeadContent with the dev version that handles +// dev styles cleanup after hydration + +export * from './index' +export { HeadContent } from './HeadContent.dev' diff --git a/packages/react-router/src/index.rsc.ts b/packages/react-router/src/index.rsc.ts new file mode 100644 index 0000000000..d5baf7e952 --- /dev/null +++ b/packages/react-router/src/index.rsc.ts @@ -0,0 +1,11 @@ +export * from './index' + +export { + notFound, + isNotFound, + redirect, + isRedirect, + rootRouteId, +} from '@tanstack/router-core' + +export type { NotFoundError } from '@tanstack/router-core' diff --git a/packages/react-router/src/index.tsx b/packages/react-router/src/index.tsx index 9779e391b3..23ebf57938 100644 --- a/packages/react-router/src/index.tsx +++ b/packages/react-router/src/index.tsx @@ -1,6 +1,7 @@ +'use client' + export { defer, - TSR_DEFERRED_PROMISE, isMatch, joinPaths, cleanPath, @@ -10,15 +11,12 @@ export { resolvePath, interpolatePath, rootRouteId, - defaultSerializeError, defaultParseSearch, defaultStringifySearch, parseSearchWith, stringifySearchWith, functionalUpdate, replaceEqualDeep, - isPlainObject, - isPlainArray, deepEqual, createControlledPromise, retainSearchParams, @@ -73,6 +71,7 @@ export type { ResolveRouteContext, SearchSerializer, SearchParser, + SearchMiddleware, TrailingSlashOption, Manifest, RouterManagedTag, @@ -105,6 +104,7 @@ export type { CreateFileRoute, SerializationAdapter, AnySerializationAdapter, + SerializableExtensions, } from '@tanstack/router-core' export { @@ -127,6 +127,7 @@ export type { AwaitOptions } from './awaited' export { CatchBoundary, ErrorComponent } from './CatchBoundary' export { ClientOnly, useHydrated } from './ClientOnly' +export { reactUse, useLayoutEffect } from './utils' export { FileRoute, @@ -201,7 +202,6 @@ export type { RegisteredRouter, RouterContextOptions, ControllablePromise, - InjectedHtmlEntry, RouterOptions, RouterState, ListenerFn, @@ -235,14 +235,18 @@ export { export type { UseMatchRouteOptions, MakeMatchRouteOptions } from './Matches' -export { matchContext } from './matchContext' export { Match, Outlet } from './Match' export { useMatch } from './useMatch' export { useLoaderDeps } from './useLoaderDeps' export { useLoaderData } from './useLoaderData' -export { redirect, isRedirect, createRouterConfig } from '@tanstack/router-core' +export { + redirect, + isRedirect, + createRouterConfig, + DEFAULT_PROTOCOL_ALLOWLIST, +} from '@tanstack/router-core' export { RouteApi, @@ -268,13 +272,7 @@ export type { export { createRouter, Router } from './router' -export { - componentTypes, - lazyFn, - SearchParamError, - PathParamError, - getInitialRouterState, -} from '@tanstack/router-core' +export { lazyFn, SearchParamError } from '@tanstack/router-core' export { RouterProvider, RouterContextProvider } from './RouterProvider' export type { RouterProps } from './RouterProvider' @@ -292,21 +290,12 @@ export { useNavigate, Navigate } from './useNavigate' export { useParams } from './useParams' export { useSearch } from './useSearch' -export { - getRouterContext, // SSR -} from './routerContext' - export { useRouteContext } from './useRouteContext' export { useRouter } from './useRouter' export { useRouterState } from './useRouterState' export { useLocation } from './useLocation' export { useCanGoBack } from './useCanGoBack' -export { - useLayoutEffect, // SSR - useStableCallback, -} from './utils' - export { CatchNotFound, DefaultGlobalNotFound } from './not-found' export { notFound, isNotFound } from '@tanstack/router-core' export type { NotFoundError } from '@tanstack/router-core' @@ -338,11 +327,15 @@ export type { InferSelected, ValidateUseSearchResult, ValidateUseParamsResult, + SerializerExtensions, + RegisteredSerializableInput, + Serializable, } from '@tanstack/router-core' export { ScriptOnce } from './ScriptOnce' export { Asset } from './Asset' export { HeadContent } from './HeadContent' +export { useTags } from './headContentUtils' export { Scripts } from './Scripts' export type * from './ssr/serializer' export { composeRewrites } from '@tanstack/router-core' diff --git a/packages/react-router/src/lazyRouteComponent.tsx b/packages/react-router/src/lazyRouteComponent.tsx index c679625298..a7b58c4499 100644 --- a/packages/react-router/src/lazyRouteComponent.tsx +++ b/packages/react-router/src/lazyRouteComponent.tsx @@ -1,5 +1,7 @@ import * as React from 'react' import { isModuleNotFoundError } from '@tanstack/router-core' +import { isServer } from '@tanstack/router-core/isServer' +import { reactUse } from './utils' import type { AsyncRouteComponent } from './route' /** @@ -23,63 +25,57 @@ export function lazyRouteComponent< let loadPromise: Promise<any> | undefined let comp: T[TKey] | T['default'] let error: any - let reload: boolean const load = () => { if (!loadPromise) { + error = undefined loadPromise = importer() .then((res) => { - loadPromise = undefined + // Resolved clients have no preload work; SSR can reuse the import. + if (!(isServer ?? typeof window === 'undefined')) { + loadPromise = undefined + ;(lazyComp as any).preload = undefined + } comp = res[exportName ?? 'default'] }) .catch((err) => { + loadPromise = undefined // We don't want an error thrown from preload in this case, because // there's nothing we want to do about module not found during preload. // Record the error, the rest is handled during the render path. error = err - // If the load fails due to module not found, it may mean a new version of - // the build was deployed and the user's browser is still using an old version. - // If this happens, the old version in the user's browser would have an outdated - // URL to the lazy module. - // In that case, we want to attempt one window refresh to get the latest. - if (isModuleNotFoundError(error)) { - if ( - error instanceof Error && - typeof window !== 'undefined' && - typeof sessionStorage !== 'undefined' - ) { - // Again, we want to reload one time on module not found error and not enter - // a reload loop if there is some other issue besides an old deploy. - // That's why we store our reload attempt in sessionStorage. - // Use error.message as key because it contains the module path that failed. - const storageKey = `tanstack_router_reload:${error.message}` - if (!sessionStorage.getItem(storageKey)) { - sessionStorage.setItem(storageKey, '1') - reload = true - } - } - } }) } return loadPromise } - const lazyComp = function Lazy(props: any) { - // Now that we're out of preload and into actual render path, - if (reload) { - // If it was a module loading error, - // throw eternal suspense while we wait for window to reload - window.location.reload() - throw new Promise(() => {}) - } if (error) { - // Otherwise, just throw the error + // A missing module can mean that a newer deployment replaced the URL. + // Reload only for the error that is still current at render time, so a + // successful retry cannot leave a stale reload request armed. + if ( + isModuleNotFoundError(error) && + !(isServer ?? typeof window === 'undefined') && + typeof sessionStorage !== 'undefined' + ) { + const storageKey = `tanstack_router_reload:${error.message}` + if (!sessionStorage.getItem(storageKey)) { + sessionStorage.setItem(storageKey, '1') + window.location.reload() + // Suspend forever while the document reloads. + throw new Promise(() => {}) + } + } throw error } if (!comp) { - throw load() + if (reactUse) { + reactUse(load()) + } else { + throw load() + } } return React.createElement(comp, props) diff --git a/packages/react-router/src/link.tsx b/packages/react-router/src/link.tsx index 365464bf01..ce6a7ed9d1 100644 --- a/packages/react-router/src/link.tsx +++ b/packages/react-router/src/link.tsx @@ -1,21 +1,24 @@ +'use client' + import * as React from 'react' -import { flushSync } from 'react-dom' import { deepEqual, - exactPathTest, functionalUpdate, + getUrlScheme, + isDangerousProtocol, preloadWarning, removeTrailingSlash, } from '@tanstack/router-core' -import { useRouterState } from './useRouterState' +import { isServer } from '@tanstack/router-core/isServer' import { useRouter } from './useRouter' - -import { useForwardedRef, useIntersectionObserver } from './utils' +import { createLinkScope, matchContext } from './matchContext' import type { + ActiveOptions, AnyRouter, Constrain, LinkOptions, + ParsedLocation, RegisteredRouter, RoutePaths, } from '@tanstack/router-core' @@ -25,6 +28,97 @@ import type { ValidateLinkOptionsArray, } from './typePrimitives' +// Undefined active state marks an external or blocked link. +// Keep that classification with the href instead of parsing it again on render. +type LinkState = [href: string | undefined, isActive?: boolean] + +// Keep referentially stable values while their contents are equal. Links +// routinely pass inline `params` / `search` object literals, which would +// otherwise change `dest` identity on every parent render, rebuild the +// link state snapshot, and discard its memoized state. One ref holds all of +// them; each entry is replaced only when its own contents change. +// +// The router reuses a built location for as long as it sees the same options +// object, so the references returned here are its invalidation signal: pass a +// new object to change a destination. Like every other React prop, an object +// mutated in place is not re-read. `deepEqual` short-circuits on reference +// equality, so an unchanged reference costs nothing. +// +// `explicitUndefined` is required: an explicit `undefined` clears an +// inherited param or search key, so `{}` and `{ category: undefined }` build +// different locations and must not be treated as equal here. +function useStableValues<T extends ReadonlyArray<unknown>>(...values: T): T { + const ref = React.useRef<ReadonlyArray<unknown>>(values) + const stable = ref.current as Array<unknown> + values.forEach((value, index) => { + if (!deepEqual(stable[index], value, false, true)) { + stable[index] = value + } + }) + return ref.current as T +} + +function preloadLink(router: AnyRouter, options: unknown) { + router.preloadRoute(options as any).catch((err) => { + console.warn(err) + console.warn(preloadWarning) + }) +} + +function resolveExternalLink( + to: string | undefined, + protocolAllowlist: AnyRouter['protocolAllowlist'], +): string | null | undefined { + const scheme = typeof to === 'string' && getUrlScheme(to) + if (!scheme) { + return undefined + } + if (!protocolAllowlist.has(scheme)) { + if (process.env.NODE_ENV !== 'production') { + console.warn(`Blocked Link with dangerous protocol: ${to}`) + } + return null + } + return to +} + +function resolveIsActive( + location: ParsedLocation, + next: ParsedLocation, + activeOptions: ActiveOptions | undefined, + basepath: string, +): boolean { + const currentPath = removeTrailingSlash(location.pathname, basepath) + const nextPath = removeTrailingSlash(next.pathname, basepath) + + // Both modes compare normalized paths; fuzzy matches need a segment boundary. + if ( + activeOptions?.exact + ? currentPath !== nextPath + : !( + currentPath.startsWith(nextPath) && + (currentPath.length === nextPath.length || + currentPath[nextPath.length] === '/') + ) + ) { + return false + } + + if (activeOptions?.includeSearch ?? true) { + const searchTest = deepEqual( + location.search, + next.search, + !activeOptions?.exact, + activeOptions?.explicitUndefined, + ) + if (!searchTest) { + return false + } + } + + return !activeOptions?.includeHash || location.hash === next.hash +} + /** * Build anchor-like props for declarative navigation and preloading. * @@ -46,367 +140,554 @@ export function useLinkProps< >( options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>, forwardedRef?: React.ForwardedRef<Element>, +): React.ComponentPropsWithRef<'a'> +/** + * `host` is what the props are rendered on: `'a'` for `Link` or the component + * given to `createLink`. `Link` never renders `type` and an anchor never + * receives `disabled`, so those are left out here rather than copied away + * from the result in the component. Stripped from the public declarations. + * + * @internal + */ +export function useLinkProps< + TRouter extends AnyRouter = RegisteredRouter, + const TFrom extends string = string, + const TTo extends string | undefined = undefined, + const TMaskFrom extends string = TFrom, + const TMaskTo extends string = '', +>( + options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>, + forwardedRef: React.ForwardedRef<Element> | undefined, + host: 'a' | React.ElementType, +): React.ComponentPropsWithRef<'a'> +export function useLinkProps< + TRouter extends AnyRouter = RegisteredRouter, + const TFrom extends string = string, + const TTo extends string | undefined = undefined, + const TMaskFrom extends string = TFrom, + const TMaskTo extends string = '', +>( + options: UseLinkPropsOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>, + forwardedRef?: React.ForwardedRef<Element>, + host?: 'a' | React.ElementType, ): React.ComponentPropsWithRef<'a'> { const router = useRouter() - const [isTransitioning, setIsTransitioning] = React.useState(false) - const hasRenderFetched = React.useRef(false) - const innerRef = useForwardedRef(forwardedRef) + + // ========================================================================== + // SERVER EARLY RETURN + // On the server, we return static props without any event handlers, + // effects, or client-side interactivity. + // + // For SSR parity (to avoid hydration errors), we still compute the link's + // active status on the server, but we avoid creating any router-state + // subscriptions by reading from the location store directly. + // + // Note: `location.hash` is not available on the server. + // ========================================================================== + // The expression must stay inlined in the `if` so bundlers fold the + // browser-build constant `isServer = false` and drop this server block, + // together with `getServerLinkProps` and the key sets only it references. + if (isServer ?? router.isServer) { + return getServerLinkProps(router, options, forwardedRef, host) + } + + // ========================================================================== + // CLIENT-ONLY CODE + // Everything below this point only runs on the client. The `isServer` check + // above is a compile-time constant that bundlers use for dead code elimination, + // so this entire section is removed from server bundles. + // + // We disable the rules-of-hooks lint rule because these hooks appear after + // an early return. This is safe because: + // 1. `isServer` is a compile-time constant from conditional exports + // 2. In server bundles, this code is completely eliminated by the bundler + // 3. In client bundles, `isServer` is `false`, so the early return never executes + // ========================================================================== + + // The link's own ref: the element for the viewport observer and the holder + // of a pending intent timer. A forwarded ref is filled alongside it by one + // callback, memoized on the forwarded ref so React re-attaches it (and + // notifies the consumer) only when their ref changes, not on every render. + // A cleanup returned by a consumer callback is passed through to React. + // eslint-disable-next-line react-hooks/rules-of-hooks + const innerRef: LinkRef = React.useRef<Element>(null) + // eslint-disable-next-line react-hooks/rules-of-hooks + const mergedRef = React.useCallback( + (element: Element | null) => { + innerRef.current = element + if (typeof forwardedRef === 'function') { + return forwardedRef(element) + } + if (forwardedRef) { + forwardedRef.current = element + } + return undefined + }, + [forwardedRef], + ) const { - // custom props - activeProps, - inactiveProps, activeOptions, to, preload: userPreload, preloadDelay: userPreloadDelay, - hashScrollIntoView, - replace, - startTransition, - resetScroll, - viewTransition, - // element props - children, - target, disabled, - style, - className, + target, onClick, + onBlur, onFocus, onMouseEnter, onMouseLeave, onTouchStart, - ignoreBlocker, - // prevent these from being returned - params: _params, - search: _search, - hash: _hash, - state: _state, - mask: _mask, - reloadDocument: _reloadDocument, - unsafeRelative: _unsafeRelative, - from: _from, - _fromLocation, - ...propsSafeToSpread - } = options + } = options as typeof options & { to?: string } - // subscribe to search params to re-build location if it changes - const currentSearch = useRouterState({ - select: (s) => s.location.search, - structuralSharing: true as any, - }) - - const from = options.from - - const _options = React.useMemo( - () => { - return { ...options, from } - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [ - router, - currentSearch, - from, - options._fromLocation, - options.hash, - options.to, - options.search, - options.params, - options.state, - options.mask, - options.unsafeRelative, - ], + // eslint-disable-next-line react-hooks/rules-of-hooks + const [stableSearch, stableParams, stableActiveOptions] = useStableValues( + options.search, + options.params, + activeOptions, ) + // The links of a route share its location source. Links outside every + // match share one that never departs. + // eslint-disable-next-line react-hooks/rules-of-hooks + const routeId = React.useContext(matchContext) + const scope = ((router.stores._linkScopes ??= {})[routeId!] ??= + createLinkScope(router, routeId)) - const next = React.useMemo( - () => router.buildLocation({ ..._options } as any), - [router, _options], - ) - - const hrefOption = React.useMemo(() => { - if (disabled) { - return undefined + // `dest` is the link's own copy of the options from the render that last + // changed the link: one stable object per link lets the router reuse + // location-independent results. It also carries the location the link + // displays, so clicks and preloads go where its href points. + // The snapshot depends only on the scope's location: it derives once per + // location so React can bail out on an unchanged state, and derives eagerly + // inside the scope's notification. + // eslint-disable-next-line react-hooks/rules-of-hooks + const [dest, getLinkState, getHydrationState] = React.useMemo(() => { + // Direct destinations and the router's allowlist are stable for this snapshot. + const directExternalLink = resolveExternalLink(to, router.protocolAllowlist) + if (directExternalLink !== undefined) { + const state: LinkState = [directExternalLink ?? undefined] + return [options, () => state] as const } - let href = next.maskedLocation - ? next.maskedLocation.url.href - : next.url.href - let external = false - if (router.origin) { - if (href.startsWith(router.origin)) { - href = router.history.createHref(href.replace(router.origin, '')) || '/' - } else { - external = true + const dest = { ...options } as any + let source: ParsedLocation | undefined + let state: LinkState + let hydrationState: LinkState | undefined + + const getLinkState = (): LinkState => { + // Read the location once and record it only after deriving: a + // derivation that throws is retried instead of caching its state. + const location = scope[0 /* getSource */]() + if (location !== source) { + dest._fromLocation = location + const next = router.buildLocation(dest) + + // History formatters can depend on the current browser URL (hash history). + const href = getHrefOption(next, router, disabled) + // Internal and disabled links can be active; external and blocked + // links have no active state. + const isActive = + disabled || (href && !getUrlScheme(href)) + ? resolveIsActive( + location, + next, + stableActiveOptions, + router.basepath, + ) + : undefined + // Keep the state while it is equal so React can bail out. + if ( + !state || + state[0 /* href */] !== href || + state[1 /* isActive */] !== isActive + ) { + state = [href, isActive] + } + source = location } + return state } - return { href, external } - }, [disabled, next.maskedLocation, next.url, router.origin, router.history]) - const externalLink = React.useMemo(() => { - if (hrefOption?.external) { - return hrefOption.href - } - try { - new URL(to as any) - return to - } catch {} - return undefined - }, [to, hrefOption]) + return [ + dest, + getLinkState, + // Hydration renders the server's markup, which has no hash, so an active + // hash-sensitive link hydrates inactive and React rerenders it after. + stableActiveOptions?.includeHash && + ((): LinkState => { + const state = getLinkState() + return state[1 /* isActive */] + ? (hydrationState ??= [state[0 /* href */], false]) + : state + }), + ] as const + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ + router, + scope, + options.from, + options.hash, + options.href, + to, + stableSearch, + stableParams, + options.state, + options.mask, + options.unsafeRelative, + stableActiveOptions, + disabled, + ]) + + // eslint-disable-next-line react-hooks/rules-of-hooks + const [href, isActive] = React.useSyncExternalStore( + scope[1 /* subscribe */], + getLinkState, + getHydrationState || getLinkState, + ) + const externalLink = isActive === undefined && href + const linkDisabled = disabled || href === undefined + + // eslint-disable-next-line react-hooks/rules-of-hooks + const hasRenderFetched = React.useRef(false) const preload = - options.reloadDocument || externalLink + options.reloadDocument || externalLink || linkDisabled ? false : (userPreload ?? router.options.defaultPreload) const preloadDelay = userPreloadDelay ?? router.options.defaultPreloadDelay ?? 0 - const isActive = useRouterState({ - select: (s) => { - if (externalLink) return false - if (activeOptions?.exact) { - const testExact = exactPathTest( - s.location.pathname, - next.pathname, - router.basepath, - ) - if (!testExact) { - return false - } - } else { - const currentPathSplit = removeTrailingSlash( - s.location.pathname, - router.basepath, - ) - const nextPathSplit = removeTrailingSlash( - next.pathname, - router.basepath, - ) - - const pathIsFuzzyEqual = - currentPathSplit.startsWith(nextPathSplit) && - (currentPathSplit.length === nextPathSplit.length || - currentPathSplit[nextPathSplit.length] === '/') - - if (!pathIsFuzzyEqual) { - return false + // `preloadRoute` builds the location itself and only reads the options, so + // `dest` goes through as-is. + // eslint-disable-next-line react-hooks/rules-of-hooks + const enqueuePreload = React.useCallback( + (e?: React.MouseEvent | React.FocusEvent | IntersectionObserverEntry) => { + const isIntersecting = (e as IntersectionObserverEntry | undefined) + ?.isIntersecting + if (!(isIntersecting ?? preload === 'intent')) { + if (isIntersecting === false) { + cancelPreload(innerRef) } + return } - if (activeOptions?.includeSearch ?? true) { - const searchTest = deepEqual(s.location.search, next.search, { - partial: !activeOptions?.exact, - ignoreUndefined: !activeOptions?.explicitUndefined, - }) - if (!searchTest) { - return false - } + if (!preloadDelay) { + preloadLink(router, dest) + return } - if (activeOptions?.includeHash) { - return s.location.hash === next.hash - } - return true + innerRef.t ??= setTimeout(() => { + innerRef.t = undefined + preloadLink(router, dest) + }, preloadDelay) }, - }) - - const doPreload = React.useCallback(() => { - router.preloadRoute({ ..._options } as any).catch((err) => { - console.warn(err) - console.warn(preloadWarning) - }) - }, [router, _options]) - - const preloadViewportIoCallback = React.useCallback( - (entry: IntersectionObserverEntry | undefined) => { - if (entry?.isIntersecting) { - doPreload() - } - }, - [doPreload], - ) - - useIntersectionObserver( - innerRef, - preloadViewportIoCallback, - intersectionObserverOptions, - { disabled: !!disabled || !(preload === 'viewport') }, + [router, dest, innerRef, preload, preloadDelay], ) + // Preload side effects: `render` preloads once per link, `viewport` watches + // the element. The cleanup also cancels a pending intent timer. + // eslint-disable-next-line react-hooks/rules-of-hooks React.useEffect(() => { - if (hasRenderFetched.current) { + // Disabled preloading creates neither an observer nor an intent timer. + if (!preload) { return } - if (!disabled && preload === 'render') { - doPreload() + if (preload === 'render' && !hasRenderFetched.current) { hasRenderFetched.current = true + preloadLink(router, dest) } - }, [disabled, doPreload, preload]) + let active = true + let observer: IntersectionObserver | undefined + if ( + preload === 'viewport' && + innerRef.current && + typeof IntersectionObserver === 'function' + ) { + observer = new IntersectionObserver( + (entries) => { + // A queued observer notification can arrive after disconnect(). + if (active) { + enqueuePreload(entries.pop()) + } + }, + { rootMargin: '100px' }, + ) + observer.observe(innerRef.current) + } + return () => { + active = false + observer?.disconnect() + cancelPreload(innerRef) + } + }, [router, dest, preload, enqueuePreload, innerRef]) + + const props = collectElementProps(options, host) + props.ref = forwardedRef ? mergedRef : innerRef + // External links get no router behavior: element props pass through as given. + if (externalLink) { + props.href = externalLink + return props + } // The click handler const handleClick = (e: React.MouseEvent) => { - // Check actual element's target attribute as fallback - const elementTarget = ( - e.currentTarget as HTMLAnchorElement | SVGAElement - ).getAttribute('target') - const effectiveTarget = target !== undefined ? target : elementTarget + // The element's own target attribute is the fallback. + const effectiveTarget = + target ?? + (e.currentTarget as HTMLAnchorElement | SVGAElement).getAttribute( + 'target', + ) if ( - !disabled && - !isCtrlEvent(e) && + !linkDisabled && + !(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) && !e.defaultPrevented && (!effectiveTarget || effectiveTarget === '_self') && e.button === 0 ) { e.preventDefault() + cancelPreload(innerRef) - flushSync(() => { - setIsTransitioning(true) - }) - - const unsub = router.subscribe('onResolved', () => { - unsub() - setIsTransitioning(false) - }) - - // All is well? Navigate! - // N.B. we don't call `router.commitLocation(next) here because we want to run `validateSearch` before committing - router.navigate({ - ..._options, - replace, - resetScroll, - hashScrollIntoView, - startTransition, - viewTransition, - ignoreBlocker, - }) + // The current options carry the navigation controls; `dest` only + // contributes the location the link displays. Navigation builds again + // to run `validateSearch` before committing. + router.navigate({ ...options, _fromLocation: dest._fromLocation }) } } - if (externalLink) { - return { - ...propsSafeToSpread, - ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'], - href: externalLink, - ...(children && { children }), - ...(target && { target }), - ...(disabled && { disabled }), - ...(style && { style }), - ...(className && { className }), - ...(onClick && { onClick }), - ...(onFocus && { onFocus }), - ...(onMouseEnter && { onMouseEnter }), - ...(onMouseLeave && { onMouseLeave }), - ...(onTouchStart && { onTouchStart }), + const handleTouchStart = () => { + if (preload === 'intent') { + preloadLink(router, dest) } } - // The click handler - const handleFocus = (_: React.MouseEvent) => { - if (disabled) return - if (preload) { - doPreload() + const handleLeave = () => { + if (preload === 'intent') { + cancelPreload(innerRef) } } - const handleTouchStart = handleFocus - - const handleEnter = (e: React.MouseEvent) => { - if (disabled || !preload) return - - if (!preloadDelay) { - doPreload() - } else { - const eventTarget = e.target - if (timeoutMap.has(eventTarget)) { - return - } - const id = setTimeout(() => { - timeoutMap.delete(eventTarget) - doPreload() - }, preloadDelay) - timeoutMap.set(eventTarget, id) - } - } - - const handleLeave = (e: React.MouseEvent) => { - if (disabled || !preload || !preloadDelay) return - const eventTarget = e.target - const id = timeoutMap.get(eventTarget) - if (id) { - clearTimeout(id) - timeoutMap.delete(eventTarget) - } - } - - // Get the active props - const resolvedActiveProps: React.HTMLAttributes<HTMLAnchorElement> = isActive - ? (functionalUpdate(activeProps as any, {}) ?? STATIC_ACTIVE_OBJECT) - : STATIC_EMPTY_OBJECT - - // Get the inactive props - const resolvedInactiveProps: React.HTMLAttributes<HTMLAnchorElement> = - isActive - ? STATIC_EMPTY_OBJECT - : (functionalUpdate(inactiveProps, {}) ?? STATIC_EMPTY_OBJECT) - - const resolvedClassName = [ - className, - resolvedActiveProps.className, - resolvedInactiveProps.className, - ] - .filter(Boolean) - .join(' ') - - const resolvedStyle = (style || - resolvedActiveProps.style || - resolvedInactiveProps.style) && { - ...style, - ...resolvedActiveProps.style, - ...resolvedInactiveProps.style, - } - - return { - ...propsSafeToSpread, - ...resolvedActiveProps, - ...resolvedInactiveProps, - href: hrefOption?.href, - ref: innerRef as React.ComponentPropsWithRef<'a'>['ref'], - onClick: composeHandlers([onClick, handleClick]), - onFocus: composeHandlers([onFocus, handleFocus]), - onMouseEnter: composeHandlers([onMouseEnter, handleEnter]), - onMouseLeave: composeHandlers([onMouseLeave, handleLeave]), - onTouchStart: composeHandlers([onTouchStart, handleTouchStart]), - disabled: !!disabled, - target, - ...(resolvedStyle && { style: resolvedStyle }), - ...(resolvedClassName && { className: resolvedClassName }), - ...(disabled && STATIC_DISABLED_PROPS), - ...(isActive && STATIC_ACTIVE_PROPS), - ...(isTransitioning && STATIC_TRANSITIONING_PROPS), - } + props.onClick = composeHandlers(onClick, handleClick) + props.onBlur = composeHandlers(onBlur, handleLeave) + props.onFocus = composeHandlers(onFocus, enqueuePreload) + props.onMouseEnter = composeHandlers(onMouseEnter, enqueuePreload) + props.onMouseLeave = composeHandlers(onMouseLeave, handleLeave) + props.onTouchStart = composeHandlers(onTouchStart, handleTouchStart) + return applyLinkState(props, options, isActive, href, linkDisabled, host) } const STATIC_EMPTY_OBJECT = {} const STATIC_ACTIVE_OBJECT = { className: 'active' } -const STATIC_DISABLED_PROPS = { role: 'link', 'aria-disabled': true } -const STATIC_ACTIVE_PROPS = { 'data-status': 'active', 'aria-current': 'page' } -const STATIC_TRANSITIONING_PROPS = { 'data-transitioning': 'transitioning' } +// Options the router consumes; they never reach the element. Every other +// option is an element prop and passes through. +const ROUTER_OPTION_KEYS = /* @__PURE__ */ new Set([ + 'to', + 'params', + 'search', + 'hash', + 'state', + 'mask', + 'from', + 'unsafeRelative', + 'reloadDocument', + 'preload', + 'preloadDelay', + 'preloadIntentProximity', + 'hashScrollIntoView', + 'replace', + 'startTransition', + 'resetScroll', + 'viewTransition', + 'ignoreBlocker', + 'activeProps', + 'inactiveProps', + 'activeOptions', + '_asChild', +]) -const timeoutMap = new WeakMap<EventTarget, ReturnType<typeof setTimeout>>() - -const intersectionObserverOptions: IntersectionObserverInit = { - rootMargin: '100px', +// Copies the element props. An object rest would test every key against the +// whole exclusion list; the key set is much cheaper. `Link` hosts never render +// `type`, and an anchor has no `disabled` attribute. +function collectElementProps( + options: object, + host: 'a' | React.ElementType | undefined, +): Record<string, unknown> { + const props: Record<string, unknown> = {} + for (const key in options) { + if ( + ROUTER_OPTION_KEYS.has(key) || + (key === 'type' && host !== undefined) || + (key === 'disabled' && host === 'a') + ) { + continue + } + props[key] = (options as Record<string, unknown>)[key] + } + return props } -const composeHandlers = - (handlers: Array<undefined | React.EventHandler<any>>) => - (e: React.SyntheticEvent) => { - for (const handler of handlers) { - if (!handler) continue - if (e.defaultPrevented) return - handler(e) - } +// Finishes a router-controlled link: the selected state props, then the +// routing attributes. This is the one place that defines precedence: state +// props override element props, `ref` and handlers; `href`, `disabled`, +// `target` and the merged class and style always win. +function applyLinkState( + props: Record<string, unknown>, + options: { + activeProps?: unknown + inactiveProps?: unknown + className?: string + style?: React.CSSProperties + target?: string + }, + isActive: boolean | undefined, + href: string | undefined, + linkDisabled: boolean, + host: 'a' | React.ElementType | undefined, +): React.ComponentPropsWithRef<'a'> { + const { activeProps, inactiveProps, className, style, target } = options + const stateProps: React.HTMLAttributes<HTMLAnchorElement> = + functionalUpdate((isActive ? activeProps : inactiveProps) as any, {}) ?? + (isActive ? STATIC_ACTIVE_OBJECT : STATIC_EMPTY_OBJECT) + Object.assign(props, stateProps) + props.href = href + if (host !== 'a') { + props.disabled = linkDisabled } + props.target = target + // Merge class and style with the state's. Links without either keep their + // props as given and carry no `undefined` keys. + const stateStyle = stateProps.style + if (style || stateStyle) { + props.style = + style && stateStyle ? { ...style, ...stateStyle } : style || stateStyle + } + const stateClassName = stateProps.className + if (className || stateClassName) { + props.className = className + ? stateClassName + ? `${className} ${stateClassName}` + : className + : stateClassName + } + if (linkDisabled) { + props.role = 'link' + props['aria-disabled'] = true + } + if (isActive) { + props['data-status'] = 'active' + props['aria-current'] = 'page' + } + return props +} + +// Server render of a Link: static props only, no hooks. Only server bundles +// keep this function; the `isServer` check that calls it folds away on the client. +function getServerLinkProps( + router: AnyRouter, + options: any, + forwardedRef: React.ForwardedRef<Element> | undefined, + host: 'a' | React.ElementType | undefined, +): React.ComponentPropsWithRef<'a'> { + const { to, disabled, activeOptions } = options as { + to: string | undefined + disabled: boolean | undefined + activeOptions: ActiveOptions | undefined + } + + const directExternalLink = resolveExternalLink(to, router.protocolAllowlist) + + // Direct-scheme links need no route resolution. Blocked links still use + // the shared inactive-prop merge so their server and client markup agree. + const next = + directExternalLink === undefined ? router.buildLocation(options) : undefined + + const hrefOption = next + ? getHrefOption(next, router, disabled) + : (directExternalLink ?? undefined) + const linkDisabled = disabled || !hrefOption + + const externalLink = + directExternalLink ?? + (hrefOption && getUrlScheme(hrefOption) ? hrefOption : undefined) + + const props = collectElementProps(options, host) + props.ref = forwardedRef + if (externalLink) { + props.href = externalLink + return props + } + + const blockedLink = !disabled && !hrefOption + // Hash is not available on the server: hash-sensitive links are inactive. + const isActive = + !!next && + !blockedLink && + !activeOptions?.includeHash && + resolveIsActive( + router.stores.location.get(), + next, + activeOptions, + router.basepath, + ) + return applyLinkState( + props, + options, + isActive, + hrefOption, + linkDisabled, + host, + ) +} + +// A Link's own ref also holds its pending intent preload timer. +type LinkRef = React.RefObject<Element | null> & { + t?: ReturnType<typeof setTimeout> +} +const cancelPreload = (ref: LinkRef) => { + clearTimeout(ref.t) + ref.t = undefined +} + +export const composeHandlers = ( + first: React.EventHandler<any> | undefined, + second: React.EventHandler<any>, +) => { + if (!first) { + return second + } + + // The first guard skips user handlers for already-prevented events; the second + // lets user handlers prevent the internal handler from running. + return (event: React.SyntheticEvent) => + event.defaultPrevented || + (first(event), event.defaultPrevented || second(event)) +} + +function getHrefOption( + next: ParsedLocation, + router: AnyRouter, + disabled: boolean | undefined, +) { + if (disabled) { + return undefined + } + const location = next.maskedLocation ?? next + // A rewritten external URL must bypass history's relative-path formatting. + const href = location.external + ? location.publicHref + : router.history.createHref(location.publicHref) || '/' + if ( + (location.external || href !== location.publicHref) && + isDangerousProtocol(href, router.protocolAllowlist) + ) { + if (process.env.NODE_ENV !== 'production') { + console.warn(`Blocked Link with dangerous protocol: ${href}`) + } + return undefined + } + return href +} type UseLinkReactProps<TComp> = TComp extends keyof React.JSX.IntrinsicElements ? React.JSX.IntrinsicElements[TComp] @@ -467,10 +748,7 @@ export interface LinkPropsChildren { // If a function is passed as a child, it will be given the `isActive` boolean to aid in further styling on the element it returns children?: | React.ReactNode - | ((state: { - isActive: boolean - isTransitioning: boolean - }) => React.ReactNode) + | ((state: { isActive: boolean }) => React.ReactNode) } type LinkComponentReactProps<TComp> = Omit< @@ -513,7 +791,7 @@ export type LinkComponent< export interface LinkComponentRoute< in out TDefaultFrom extends string = string, > { - defaultFrom: TDefaultFrom + defaultFrom: TDefaultFrom; < TRouter extends AnyRouter = RegisteredRouter, const TTo extends string | undefined = undefined, @@ -557,7 +835,7 @@ export function createLink<const TComp>( * * Props: * - `preload`: Controls route preloading (eg. 'intent', 'render', 'viewport', true/false) - * - `preloadDelay`: Delay in ms before preloading on hover + * - `preloadDelay`: Delay in ms before preloading on focus, hover, or viewport entry * - `activeProps`/`inactiveProps`: Additional props merged when link is active/inactive * - `resetScroll`/`hashScrollIntoView`: Control scroll behavior on navigation * - `viewTransition`/`startTransition`: Use View Transitions/React transitions for navigation @@ -566,41 +844,50 @@ export function createLink<const TComp>( * @returns An anchor-like element that navigates without full page reloads. * @link https://tanstack.com/router/latest/docs/framework/react/api/router/linkComponent */ -export const Link: LinkComponent<'a'> = React.forwardRef<Element, any>( - (props, ref) => { - const { _asChild, ...rest } = props - const { - type: _type, - ref: innerRef, - ...linkProps - } = useLinkProps(rest as any, ref) +export const Link: LinkComponent<'a'> = React.memo( + React.forwardRef<Element, any>((props, ref) => { + const host = props._asChild || 'a' + const linkProps = useLinkProps(props as any, ref, host) const children = - typeof rest.children === 'function' - ? rest.children({ + typeof props.children === 'function' + ? props.children({ isActive: (linkProps as any)['data-status'] === 'active', }) - : rest.children + : props.children - if (_asChild === undefined) { - // the ReturnType of useLinkProps returns the correct type for a <a> element, not a general component that has a disabled prop - // @ts-expect-error - delete linkProps.disabled - } - - return React.createElement( - _asChild ? _asChild : 'a', - { - ...linkProps, - ref: innerRef, - }, - children, - ) - }, + return React.createElement(host, linkProps, children) + }), + areLinkPropsEqual, ) as any -function isCtrlEvent(e: React.MouseEvent) { - return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) +// A Link's output depends only on its props, the router context and its +// route's location source, which React tracks for memoized components, so a parent +// re-render with equal props can skip it. Router options are compared by +// value: destinations are usually inline object literals. Element props +// (`children`, handlers, `style`, ...) are compared by reference only, since +// they may hold arbitrary (even cyclic) data. +function areLinkPropsEqual( + prev: Record<string, unknown>, + next: Record<string, unknown>, +): boolean { + let extraKeys = 0 + for (const key in next) { + extraKeys++ + if (prev[key] === next[key]) { + continue + } + if ( + !ROUTER_OPTION_KEYS.has(key) || + !deepEqual(prev[key], next[key], false, true) + ) { + return false + } + } + for (const _key in prev) { + extraKeys-- + } + return extraKeys === 0 } export type LinkOptionsFnOptions< diff --git a/packages/react-router/src/matchContext.tsx b/packages/react-router/src/matchContext.tsx index ce182bd994..12db4dbada 100644 --- a/packages/react-router/src/matchContext.tsx +++ b/packages/react-router/src/matchContext.tsx @@ -1,4 +1,70 @@ +'use client' + import * as React from 'react' +import { _isRouteDeparting } from '@tanstack/router-core' +import type { AnyRoute, AnyRouter, ParsedLocation } from '@tanstack/router-core' + +declare module '@tanstack/router-core' { + // Declaration merging requires the original type parameters. + // eslint-disable-next-line unused-imports/no-unused-vars + interface RouterStores<in out TRouteTree extends AnyRoute> { + /** + * The link scope of each route id that rendered links, keyed `undefined` + * for links outside every match (route ids start with `/` or are the + * root id). A scope without links holds no location. + */ + _linkScopes?: Record<string, LinkScope> + } +} + +/** + * The location source shared by the links of one route. It holds one location + * subscription for all of them while any is subscribed, and skips a + * publication whose navigation removes the route: those links keep the + * location their route still presents until it unmounts or a newer + * publication keeps it. Without subscribers it holds nothing and reads the + * live location. + */ +export type LinkScope = [ + getSource: () => ParsedLocation, + subscribe: (listener: () => void) => () => void, +] + +export function createLinkScope( + router: AnyRouter, + routeId?: string, +): LinkScope { + // Stores are created once per router. + const store = router.stores.location + const listeners = new Set<() => void>() + let source: ParsedLocation | undefined + let unsubscribe: () => void + // Defined outside `subscribe` so the store's subscription does not share a + // closure with, and retain, the first listener after it unsubscribes. + const update = (location: ParsedLocation) => { + if (!_isRouteDeparting(router, routeId, location)) { + source = location + listeners.forEach((listener) => listener()) + } + } + return [ + () => source ?? store.get(), + (listener) => { + if (!listeners.size) { + source = store.get() + unsubscribe = store.subscribe(update).unsubscribe + } + listeners.add(listener) + return () => { + listeners.delete(listener) + if (!listeners.size) { + unsubscribe() + source = undefined + } + } + }, + ] +} export const matchContext = React.createContext<string | undefined>(undefined) diff --git a/packages/react-router/src/nonRouteComponentContext.tsx b/packages/react-router/src/nonRouteComponentContext.tsx new file mode 100644 index 0000000000..252ab7fd10 --- /dev/null +++ b/packages/react-router/src/nonRouteComponentContext.tsx @@ -0,0 +1,21 @@ +'use client' + +import * as React from 'react' + +export type NonRouteComponent = + | 'pendingComponent' + | 'errorComponent' + | 'notFoundComponent' + +export const nonRouteComponentContext = + process.env.NODE_ENV !== 'production' + ? React.createContext<NonRouteComponent | undefined>(undefined) + : undefined + +export function wrapInNonRouteComponentContext( + element: React.ReactElement, + component: NonRouteComponent, +): React.ReactElement { + const Context = nonRouteComponentContext! + return <Context.Provider value={component}>{element}</Context.Provider> +} diff --git a/packages/react-router/src/not-found.tsx b/packages/react-router/src/not-found.tsx index db64e6d745..3c5287cb2e 100644 --- a/packages/react-router/src/not-found.tsx +++ b/packages/react-router/src/not-found.tsx @@ -1,19 +1,56 @@ import * as React from 'react' import { isNotFound } from '@tanstack/router-core' +import { isServer } from '@tanstack/router-core/isServer' +import { useSelector } from '@tanstack/react-store' import { CatchBoundary } from './CatchBoundary' -import { useRouterState } from './useRouterState' +import { useRouter } from './useRouter' import type { ErrorInfo } from 'react' import type { NotFoundError } from '@tanstack/router-core' export function CatchNotFound(props: { fallback?: (error: NotFoundError) => React.ReactElement - onCatch?: (error: Error, errorInfo: ErrorInfo) => void + onCatch?: (error: NotFoundError, errorInfo: ErrorInfo) => void children: React.ReactNode }) { + const router = useRouter() + + if (isServer ?? router.isServer) { + const pathname = router.stores.location.get().pathname + const status = router.stores.status.get() + const resetKey = `not-found-${pathname}-${status}` + + return ( + <CatchBoundary + getResetKey={() => resetKey} + onCatch={(error, errorInfo) => { + if (isNotFound(error)) { + props.onCatch?.(error, errorInfo) + } else { + throw error + } + }} + errorComponent={({ error }) => { + if (isNotFound(error)) { + return props.fallback?.(error) + } else { + throw error + } + }} + > + {props.children} + </CatchBoundary> + ) + } + // TODO: Some way for the user to programmatically reset the not-found boundary? - const resetKey = useRouterState({ - select: (s) => `not-found-${s.location.pathname}-${s.status}`, - }) + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + const pathname = useSelector( + router.stores.location, + (location) => location.pathname, + ) + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + const status = useSelector(router.stores.status) + const resetKey = `not-found-${pathname}-${status}` return ( <CatchBoundary diff --git a/packages/react-router/src/renderRouteNotFound.tsx b/packages/react-router/src/renderRouteNotFound.tsx index 225a013bea..9e363da7f4 100644 --- a/packages/react-router/src/renderRouteNotFound.tsx +++ b/packages/react-router/src/renderRouteNotFound.tsx @@ -1,6 +1,6 @@ import * as React from 'react' -import warning from 'tiny-warning' import { DefaultGlobalNotFound } from './not-found' +import { wrapInNonRouteComponentContext } from './nonRouteComponentContext' import type { AnyRoute, AnyRouter } from '@tanstack/router-core' /** @@ -18,18 +18,27 @@ export function renderRouteNotFound( ) { if (!route.options.notFoundComponent) { if (router.options.defaultNotFoundComponent) { - return <router.options.defaultNotFoundComponent {...data} /> + const notFoundElement = ( + <router.options.defaultNotFoundComponent {...data} /> + ) + return process.env.NODE_ENV !== 'production' + ? wrapInNonRouteComponentContext(notFoundElement, 'notFoundComponent') + : notFoundElement } - if (process.env.NODE_ENV === 'development') { - warning( - route.options.notFoundComponent, - `A notFoundError was encountered on the route with ID "${route.id}", but a notFoundComponent option was not configured, nor was a router level defaultNotFoundComponent configured. Consider configuring at least one of these to avoid TanStack Router's overly generic defaultNotFoundComponent (<p>Not Found</p>)`, - ) + if (process.env.NODE_ENV !== 'production') { + if (!route.options.notFoundComponent) { + console.warn( + `Warning: A notFoundError was encountered on the route with ID "${route.id}", but a notFoundComponent option was not configured, nor was a router level defaultNotFoundComponent configured. Consider configuring at least one of these to avoid TanStack Router's overly generic defaultNotFoundComponent (<p>Not Found</p>)`, + ) + } } return <DefaultGlobalNotFound /> } - return <route.options.notFoundComponent {...data} /> + const notFoundElement = <route.options.notFoundComponent {...data} /> + return process.env.NODE_ENV !== 'production' + ? wrapInNonRouteComponentContext(notFoundElement, 'notFoundComponent') + : notFoundElement } diff --git a/packages/react-router/src/route.tsx b/packages/react-router/src/route.tsx index 3fb7716e7a..57dca9ef02 100644 --- a/packages/react-router/src/route.tsx +++ b/packages/react-router/src/route.tsx @@ -11,6 +11,7 @@ import { useParams } from './useParams' import { useSearch } from './useSearch' import { useNavigate } from './useNavigate' import { useMatch } from './useMatch' +import { useRouteContext } from './useRouteContext' import { useRouter } from './useRouter' import { Link } from './link' import type { @@ -106,36 +107,19 @@ export class RouteApi< } useMatch: UseMatchRoute<TId> = (opts) => { - return useMatch({ - select: opts?.select, - from: this.id, - structuralSharing: opts?.structuralSharing, - } as any) as any + return useMatch({ ...opts, from: this.id } as any) as any } useRouteContext: UseRouteContextRoute<TId> = (opts) => { - return useMatch({ - from: this.id as any, - select: (d) => (opts?.select ? opts.select(d.context) : d.context), - }) as any + return useRouteContext({ ...(opts as any), from: this.id }) } useSearch: UseSearchRoute<TId> = (opts) => { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion - return useSearch({ - select: opts?.select, - structuralSharing: opts?.structuralSharing, - from: this.id, - } as any) as any + return useSearch({ ...opts, from: this.id } as any) } useParams: UseParamsRoute<TId> = (opts) => { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion - return useParams({ - select: opts?.select, - structuralSharing: opts?.structuralSharing, - from: this.id, - } as any) as any + return useParams({ ...opts, from: this.id } as any) } useLoaderDeps: UseLoaderDepsRoute<TId> = (opts) => { @@ -168,32 +152,32 @@ export class RouteApi< } export class Route< - in out TRegister = unknown, - in out TParentRoute extends RouteConstraints['TParentRoute'] = AnyRoute, - in out TPath extends RouteConstraints['TPath'] = '/', - in out TFullPath extends RouteConstraints['TFullPath'] = ResolveFullPath< - TParentRoute, - TPath - >, - in out TCustomId extends RouteConstraints['TCustomId'] = string, - in out TId extends RouteConstraints['TId'] = ResolveId< - TParentRoute, - TCustomId, - TPath - >, - in out TSearchValidator = undefined, - in out TParams = ResolveParams<TPath>, - in out TRouterContext = AnyContext, - in out TRouteContextFn = AnyContext, - in out TBeforeLoadFn = AnyContext, - in out TLoaderDeps extends Record<string, any> = {}, - in out TLoaderFn = undefined, - in out TChildren = unknown, - in out TFileRouteTypes = unknown, - in out TSSR = unknown, - in out TServerMiddlewares = unknown, - in out THandlers = undefined, - > + in out TRegister = unknown, + in out TParentRoute extends RouteConstraints['TParentRoute'] = AnyRoute, + in out TPath extends RouteConstraints['TPath'] = '/', + in out TFullPath extends RouteConstraints['TFullPath'] = ResolveFullPath< + TParentRoute, + TPath + >, + in out TCustomId extends RouteConstraints['TCustomId'] = string, + in out TId extends RouteConstraints['TId'] = ResolveId< + TParentRoute, + TCustomId, + TPath + >, + in out TSearchValidator = undefined, + in out TParams = ResolveParams<TPath>, + in out TRouterContext = AnyContext, + in out TRouteContextFn = AnyContext, + in out TBeforeLoadFn = AnyContext, + in out TLoaderDeps extends Record<string, any> = {}, + in out TLoaderFn = undefined, + in out TChildren = unknown, + in out TFileRouteTypes = unknown, + in out TSSR = unknown, + in out TServerMiddlewares = unknown, + in out THandlers = undefined, +> extends BaseRoute< TRegister, TParentRoute, @@ -260,41 +244,22 @@ export class Route< >, ) { super(options) - ;(this as any).$$typeof = Symbol.for('react.memo') } useMatch: UseMatchRoute<TId> = (opts) => { - return useMatch({ - select: opts?.select, - from: this.id, - structuralSharing: opts?.structuralSharing, - } as any) as any + return useMatch({ ...opts, from: this.id } as any) as any } useRouteContext: UseRouteContextRoute<TId> = (opts?) => { - return useMatch({ - ...opts, - from: this.id, - select: (d) => (opts?.select ? opts.select(d.context) : d.context), - }) as any + return useRouteContext({ ...(opts as any), from: this.id }) } useSearch: UseSearchRoute<TId> = (opts) => { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion - return useSearch({ - select: opts?.select, - structuralSharing: opts?.structuralSharing, - from: this.id, - } as any) as any + return useSearch({ ...opts, from: this.id } as any) } useParams: UseParamsRoute<TId> = (opts) => { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion - return useParams({ - select: opts?.select, - structuralSharing: opts?.structuralSharing, - from: this.id, - } as any) as any + return useParams({ ...opts, from: this.id } as any) } useLoaderDeps: UseLoaderDepsRoute<TId> = (opts) => { @@ -465,7 +430,7 @@ export function createRootRouteWithContext<TRouterContext extends {}>() { TLoaderFn, TSSR, TServerMiddlewares - >(options as any) + >(options) } } @@ -475,19 +440,19 @@ export function createRootRouteWithContext<TRouterContext extends {}>() { export const rootRouteWithContext = createRootRouteWithContext export class RootRoute< - in out TRegister = unknown, - in out TSearchValidator = undefined, - in out TRouterContext = {}, - in out TRouteContextFn = AnyContext, - in out TBeforeLoadFn = AnyContext, - in out TLoaderDeps extends Record<string, any> = {}, - in out TLoaderFn = undefined, - in out TChildren = unknown, - in out TFileRouteTypes = unknown, - in out TSSR = unknown, - in out TServerMiddlewares = unknown, - in out THandlers = undefined, - > + in out TRegister = unknown, + in out TSearchValidator = undefined, + in out TRouterContext = {}, + in out TRouteContextFn = AnyContext, + in out TBeforeLoadFn = AnyContext, + in out TLoaderDeps extends Record<string, any> = {}, + in out TLoaderFn = undefined, + in out TChildren = unknown, + in out TFileRouteTypes = unknown, + in out TSSR = unknown, + in out TServerMiddlewares = unknown, + in out THandlers = undefined, +> extends BaseRootRoute< TRegister, TSearchValidator, @@ -536,41 +501,22 @@ export class RootRoute< >, ) { super(options) - ;(this as any).$$typeof = Symbol.for('react.memo') } useMatch: UseMatchRoute<RootRouteId> = (opts) => { - return useMatch({ - select: opts?.select, - from: this.id, - structuralSharing: opts?.structuralSharing, - } as any) as any + return useMatch({ ...opts, from: this.id } as any) as any } useRouteContext: UseRouteContextRoute<RootRouteId> = (opts) => { - return useMatch({ - ...opts, - from: this.id, - select: (d) => (opts?.select ? opts.select(d.context) : d.context), - }) as any + return useRouteContext({ ...(opts as any), from: this.id }) } useSearch: UseSearchRoute<RootRouteId> = (opts) => { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion - return useSearch({ - select: opts?.select, - structuralSharing: opts?.structuralSharing, - from: this.id, - } as any) as any + return useSearch({ ...opts, from: this.id } as any) } useParams: UseParamsRoute<RootRouteId> = (opts) => { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion - return useParams({ - select: opts?.select, - structuralSharing: opts?.structuralSharing, - from: this.id, - } as any) as any + return useParams({ ...opts, from: this.id } as any) } useLoaderDeps: UseLoaderDepsRoute<RootRouteId> = (opts) => { @@ -676,7 +622,7 @@ export interface DefaultRouteTypes<TProps> { export interface RouteTypes<TProps> extends DefaultRouteTypes<TProps> {} export type AsyncRouteComponent<TProps> = RouteTypes<TProps>['component'] & { - preload?: () => Promise<void> + preload?: () => Promise<void> | undefined } export type RouteComponent = AsyncRouteComponent<{}> diff --git a/packages/react-router/src/router.ts b/packages/react-router/src/router.ts index b3a20910f8..de5e89a9fb 100644 --- a/packages/react-router/src/router.ts +++ b/packages/react-router/src/router.ts @@ -1,5 +1,5 @@ import { RouterCore } from '@tanstack/router-core' -import { createFileRoute, createLazyFileRoute } from './fileRoute' +import { getStoreFactory } from './routerStores' import type { RouterHistory } from '@tanstack/history' import type { AnyRoute, @@ -73,7 +73,7 @@ declare module '@tanstack/router-core' { * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultoncatch-property) * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#handling-errors-with-routeoptionsoncatch) */ - defaultOnCatch?: (error: Error, errorInfo: React.ErrorInfo) => void + defaultOnCatch?: (error: unknown, errorInfo: React.ErrorInfo) => void } } @@ -114,14 +114,6 @@ export class Router< TDehydrated >, ) { - super(options) + super(options, getStoreFactory) } } - -if (typeof globalThis !== 'undefined') { - ;(globalThis as any).createFileRoute = createFileRoute - ;(globalThis as any).createLazyFileRoute = createLazyFileRoute -} else if (typeof window !== 'undefined') { - ;(window as any).createFileRoute = createFileRoute - ;(window as any).createLazyFileRoute = createLazyFileRoute -} diff --git a/packages/react-router/src/routerContext.tsx b/packages/react-router/src/routerContext.tsx index a08855ee44..30b442c6c4 100644 --- a/packages/react-router/src/routerContext.tsx +++ b/packages/react-router/src/routerContext.tsx @@ -1,24 +1,6 @@ +'use client' + import * as React from 'react' import type { AnyRouter } from '@tanstack/router-core' -declare global { - interface Window { - __TSR_ROUTER_CONTEXT__?: React.Context<AnyRouter> - } -} - -const routerContext = React.createContext<AnyRouter>(null!) - -export function getRouterContext() { - if (typeof document === 'undefined') { - return routerContext - } - - if (window.__TSR_ROUTER_CONTEXT__) { - return window.__TSR_ROUTER_CONTEXT__ - } - - window.__TSR_ROUTER_CONTEXT__ = routerContext as any - - return routerContext -} +export const routerContext = React.createContext<AnyRouter>(null!) diff --git a/packages/react-router/src/routerStores.ts b/packages/react-router/src/routerStores.ts new file mode 100644 index 0000000000..3197f54681 --- /dev/null +++ b/packages/react-router/src/routerStores.ts @@ -0,0 +1,26 @@ +import { batch, createAtom } from '@tanstack/react-store' +import { + createNonReactiveMutableStore, + createNonReactiveReadonlyStore, +} from '@tanstack/router-core' +import { isServer } from '@tanstack/router-core/isServer' +import type { Readable } from '@tanstack/react-store' +import type { GetStoreConfig } from '@tanstack/router-core' + +declare module '@tanstack/router-core' { + export interface RouterReadableStore<TValue> extends Readable<TValue> {} +} +export const getStoreFactory: GetStoreConfig = (opts) => { + if (isServer ?? opts.isServer) { + return { + createMutableStore: createNonReactiveMutableStore, + createReadonlyStore: createNonReactiveReadonlyStore, + batch: (fn) => fn(), + } + } + return { + createMutableStore: createAtom, + createReadonlyStore: createAtom, + batch: batch, + } +} diff --git a/packages/react-router/src/scroll-restoration.tsx b/packages/react-router/src/scroll-restoration.tsx index 3527a2db37..5c49425e77 100644 --- a/packages/react-router/src/scroll-restoration.tsx +++ b/packages/react-router/src/scroll-restoration.tsx @@ -1,43 +1,14 @@ -import { - defaultGetScrollRestorationKey, - restoreScroll, - storageKey, -} from '@tanstack/router-core' +import { getScrollRestorationScriptForRouter } from '@tanstack/router-core/scroll-restoration-script' import { useRouter } from './useRouter' import { ScriptOnce } from './ScriptOnce' export function ScrollRestoration() { const router = useRouter() - if (!router.isScrollRestoring || !router.isServer) { + const script = getScrollRestorationScriptForRouter(router) + + if (!script) { return null } - if (typeof router.options.scrollRestoration === 'function') { - const shouldRestore = router.options.scrollRestoration({ - location: router.latestLocation, - }) - if (!shouldRestore) { - return null - } - } - const getKey = - router.options.getScrollRestorationKey || defaultGetScrollRestorationKey - const userKey = getKey(router.latestLocation) - const resolvedKey = - userKey !== defaultGetScrollRestorationKey(router.latestLocation) - ? userKey - : undefined - const restoreScrollOptions: Parameters<typeof restoreScroll>[0] = { - storageKey, - shouldScrollRestoration: true, - } - if (resolvedKey) { - restoreScrollOptions.key = resolvedKey - } - - return ( - <ScriptOnce - children={`(${restoreScroll.toString()})(${JSON.stringify(restoreScrollOptions)})`} - /> - ) + return <ScriptOnce children={script} /> } diff --git a/packages/react-router/src/ssr/RouterClient.tsx b/packages/react-router/src/ssr/RouterClient.tsx index 3af3fa89ac..69abc97f0b 100644 --- a/packages/react-router/src/ssr/RouterClient.tsx +++ b/packages/react-router/src/ssr/RouterClient.tsx @@ -3,16 +3,11 @@ import { Await } from '../awaited' import { RouterProvider } from '../RouterProvider' import type { AnyRouter } from '@tanstack/router-core' -let hydrationPromise: Promise<void | Array<Array<void>>> | undefined +let hydrationPromise: Promise<void> | undefined export function RouterClient(props: { router: AnyRouter }) { - if (!hydrationPromise) { - if (!props.router.state.matches.length) { - hydrationPromise = hydrate(props.router) - } else { - hydrationPromise = Promise.resolve() - } - } + hydrationPromise ??= hydrate(props.router).finally(() => window.$_TSR!.h()) + return ( <Await promise={hydrationPromise} diff --git a/packages/react-router/src/ssr/renderRouterToStream.tsx b/packages/react-router/src/ssr/renderRouterToStream.tsx index 147a13a9a9..b55fc35405 100644 --- a/packages/react-router/src/ssr/renderRouterToStream.tsx +++ b/packages/react-router/src/ssr/renderRouterToStream.tsx @@ -1,12 +1,13 @@ -import { PassThrough } from 'node:stream' +import { PassThrough, Readable } from 'node:stream' import ReactDOMServer from 'react-dom/server' import { isbot } from 'isbot' import { - transformPipeableStreamWithRouter, + createSsrStreamResponse, + getSsrStatus, transformReadableStreamWithRouter, + waitForRequest, } from '@tanstack/router-core/ssr/server' import type { AnyRouter } from '@tanstack/router-core' -import type { ReadableStream } from 'node:stream/web' import type { ReactNode } from 'react' export const renderRouterToStream = async ({ @@ -20,71 +21,116 @@ export const renderRouterToStream = async ({ responseHeaders: Headers children: ReactNode }) => { - if (typeof ReactDOMServer.renderToReadableStream === 'function') { - const stream = await ReactDOMServer.renderToReadableStream(children, { - signal: request.signal, - nonce: router.options.ssr?.nonce, - progressiveChunkSize: Number.POSITIVE_INFINITY, - }) - - if (isbot(request.headers.get('User-Agent'))) { - await stream.allReady + const signal = request.signal + if (signal.aborted) { + router.serverSsr?.cleanup() + throw signal.reason + } + let rendererTeardown = false + const bot = isbot(request.headers.get('User-Agent')) + const onError = + ( + renderer: string, + ): ReactDOMServer.RenderToPipeableStreamOptions['onError'] => + (error, info) => { + if (!rendererTeardown && !signal.aborted) { + console.error(`Error in ${renderer}:`, error, info) + } } - const responseStream = transformReadableStreamWithRouter( - router, - stream as unknown as ReadableStream, - ) - return new Response(responseStream as any, { - status: router.state.statusCode, - headers: responseHeaders, - }) - } - - if (typeof ReactDOMServer.renderToPipeableStream === 'function') { - const reactAppPassthrough = new PassThrough() - - try { - const pipeable = ReactDOMServer.renderToPipeableStream(children, { + try { + if (typeof ReactDOMServer.renderToReadableStream === 'function') { + const stream = await ReactDOMServer.renderToReadableStream(children, { + signal, nonce: router.options.ssr?.nonce, progressiveChunkSize: Number.POSITIVE_INFINITY, - ...(isbot(request.headers.get('User-Agent')) - ? { - onAllReady() { - pipeable.pipe(reactAppPassthrough) - }, - } - : { - onShellReady() { - pipeable.pipe(reactAppPassthrough) - }, - }), - onError: (error, info) => { - console.error('Error in renderToPipeableStream:', error, info) - // Destroy the passthrough stream on error - if (!reactAppPassthrough.destroyed) { - reactAppPassthrough.destroy( - error instanceof Error ? error : new Error(String(error)), - ) - } + onError: onError('renderToReadableStream'), + }) + // The transform owns the reader and bounds bot readiness by its lifetime. + const rendererAbort = bot ? new AbortController() : undefined + const responseStream = transformReadableStreamWithRouter(router, stream, { + rendererSafePoint: 'script-close', + signal, + onAbort: (reason) => { + rendererTeardown = true + rendererAbort?.abort(reason) }, }) - } catch (e) { - console.error('Error in renderToPipeableStream:', e) - reactAppPassthrough.destroy(e instanceof Error ? e : new Error(String(e))) + if (rendererAbort) { + await waitForRequest(stream.allReady, rendererAbort.signal) + } + return createSsrStreamResponse( + router, + new Response(responseStream, { + status: getSsrStatus(router), + headers: responseHeaders, + }), + ) } - const responseStream = transformPipeableStreamWithRouter( - router, - reactAppPassthrough, - ) - return new Response(responseStream as any, { - status: router.state.statusCode, - headers: responseHeaders, - }) - } + if (typeof ReactDOMServer.renderToPipeableStream === 'function') { + const reactAppPassthrough = new PassThrough() + let pipeable: + | ReturnType<typeof ReactDOMServer.renderToPipeableStream> + | undefined + let resolveReady!: () => void + const ready = new Promise<void>((resolve) => { + resolveReady = resolve + }) + const rendererAbort = new AbortController() + const abortPipeable = (reason?: unknown) => { + if (rendererTeardown) { + return + } + rendererTeardown = true + rendererAbort.abort(reason) + try { + pipeable?.abort(reason) + } catch { + // ignore — React may throw if already aborted/finished + } + } + try { + pipeable = ReactDOMServer.renderToPipeableStream(children, { + nonce: router.options.ssr?.nonce, + progressiveChunkSize: Number.POSITIVE_INFINITY, + ...(bot + ? { onAllReady: resolveReady } + : { onShellReady: resolveReady }), + onError: onError('renderToPipeableStream'), + onShellError: (error) => rendererAbort.abort(error), + }) + const responseStream = transformReadableStreamWithRouter( + router, + Readable.toWeb(reactAppPassthrough), + { + rendererSafePoint: 'script-close', + signal, + onAbort: abortPipeable, + }, + ) - throw new Error( - 'No renderToReadableStream or renderToPipeableStream found in react-dom/server. Ensure you are using a version of react-dom that supports streaming.', - ) + await waitForRequest(ready, rendererAbort.signal) + pipeable.pipe(reactAppPassthrough) + + return createSsrStreamResponse( + router, + new Response(responseStream, { + status: getSsrStatus(router), + headers: responseHeaders, + }), + ) + } catch (error) { + abortPipeable(error) + throw error + } + } + + throw new Error( + 'No renderToReadableStream or renderToPipeableStream found in react-dom/server. Ensure you are using a version of react-dom that supports streaming.', + ) + } catch (error) { + router.serverSsr?.cleanup() + throw error + } } diff --git a/packages/react-router/src/ssr/renderRouterToString.tsx b/packages/react-router/src/ssr/renderRouterToString.tsx index e13527b584..4b2faa2409 100644 --- a/packages/react-router/src/ssr/renderRouterToString.tsx +++ b/packages/react-router/src/ssr/renderRouterToString.tsx @@ -1,4 +1,5 @@ import ReactDOMServer from 'react-dom/server' +import { renderSsrHtmlResponse } from '@tanstack/router-core/ssr/server' import type { ReactNode } from 'react' import type { AnyRouter } from '@tanstack/router-core' @@ -11,24 +12,9 @@ export const renderRouterToString = async ({ responseHeaders: Headers children: ReactNode }) => { - try { - let html = ReactDOMServer.renderToString(children) - router.serverSsr!.setRenderFinished() - const injectedHtml = await Promise.all(router.serverSsr!.injectedHtml).then( - (htmls) => htmls.join(''), - ) - html = html.replace(`</body>`, () => `${injectedHtml}</body>`) - return new Response(`<!DOCTYPE html>${html}`, { - status: router.state.statusCode, - headers: responseHeaders, - }) - } catch (error) { - console.error('Render to string error:', error) - return new Response('Internal Server Error', { - status: 500, - headers: responseHeaders, - }) - } finally { - router.serverSsr?.cleanup() - } + return renderSsrHtmlResponse({ + router, + responseHeaders, + render: () => ReactDOMServer.renderToString(children), + }) } diff --git a/packages/react-router/src/useBlocker.tsx b/packages/react-router/src/useBlocker.tsx index 209af19501..65636510c9 100644 --- a/packages/react-router/src/useBlocker.tsx +++ b/packages/react-router/src/useBlocker.tsx @@ -1,3 +1,5 @@ +'use client' + import * as React from 'react' import { useRouter } from './useRouter' import type { @@ -12,12 +14,12 @@ import type { RegisteredRouter, } from '@tanstack/router-core' -interface ShouldBlockFnLocation< +type ShouldBlockFnLocation< out TRouteId, out TFullPath, out TAllParams, out TFullSearchSchema, -> { +> = { routeId: TRouteId fullPath: TFullPath pathname: string @@ -177,22 +179,24 @@ export function useBlocker( location: HistoryLocation, ): AnyShouldBlockFnLocation { const parsedLocation = router.parseLocation(location) - const matchedRoutes = router.getMatchedRoutes(parsedLocation.pathname) - if (matchedRoutes.foundRoute === undefined) { + const [, rawParams, foundRoute] = router.getMatchedRoutes( + parsedLocation.pathname, + ) + if (foundRoute === undefined) { return { routeId: '__notFound__', fullPath: parsedLocation.pathname, pathname: parsedLocation.pathname, - params: matchedRoutes.routeParams, + params: rawParams, search: router.options.parseSearch(location.search), } } return { - routeId: matchedRoutes.foundRoute.id, - fullPath: matchedRoutes.foundRoute.fullPath, + routeId: foundRoute.id, + fullPath: foundRoute.fullPath, pathname: parsedLocation.pathname, - params: matchedRoutes.routeParams, + params: rawParams, search: router.options.parseSearch(location.search), } } diff --git a/packages/react-router/src/useCanGoBack.ts b/packages/react-router/src/useCanGoBack.ts index 9476a9d51f..2a8ce612b1 100644 --- a/packages/react-router/src/useCanGoBack.ts +++ b/packages/react-router/src/useCanGoBack.ts @@ -1,5 +1,17 @@ -import { useRouterState } from './useRouterState' +import { useSelector } from '@tanstack/react-store' +import { isServer } from '@tanstack/router-core/isServer' +import { useRouter } from './useRouter' export function useCanGoBack() { - return useRouterState({ select: (s) => s.location.state.__TSR_index !== 0 }) + const router = useRouter() + + if (isServer ?? router.isServer) { + return router.stores.location.get().state.__TSR_index !== 0 + } + + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + return useSelector( + router.stores.location, + (location) => location.state.__TSR_index !== 0, + ) } diff --git a/packages/react-router/src/useLoaderData.tsx b/packages/react-router/src/useLoaderData.tsx index eb82a40461..755a39616e 100644 --- a/packages/react-router/src/useLoaderData.tsx +++ b/packages/react-router/src/useLoaderData.tsx @@ -84,8 +84,8 @@ export function useLoaderData< from: opts.from!, strict: opts.strict, structuralSharing: opts.structuralSharing, - select: (s: any) => { - return opts.select ? opts.select(s.loaderData) : s.loaderData + select: (match) => { + return opts.select ? opts.select(match.loaderData) : match.loaderData }, - } as any) as UseLoaderDataResult<TRouter, TFrom, TStrict, TSelected> + }) as UseLoaderDataResult<TRouter, TFrom, TStrict, TSelected> } diff --git a/packages/react-router/src/useLoaderDeps.tsx b/packages/react-router/src/useLoaderDeps.tsx index bab8cbdf36..21e7267d4e 100644 --- a/packages/react-router/src/useLoaderDeps.tsx +++ b/packages/react-router/src/useLoaderDeps.tsx @@ -37,7 +37,7 @@ export type UseLoaderDepsRoute<out TId> = < TStructuralSharing extends boolean = boolean, >( opts?: UseLoaderDepsBaseOptions<TRouter, TId, TSelected, TStructuralSharing> & - StructuralSharingOption<TRouter, TSelected, false>, + StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, ) => UseLoaderDepsResult<TRouter, TId, TSelected> /** @@ -62,8 +62,8 @@ export function useLoaderDeps< const { select, ...rest } = opts return useMatch({ ...rest, - select: (s) => { - return select ? select(s.loaderDeps) : s.loaderDeps + select: (match) => { + return select ? select(match.loaderDeps) : match.loaderDeps }, }) as UseLoaderDepsResult<TRouter, TFrom, TSelected> } diff --git a/packages/react-router/src/useLocation.tsx b/packages/react-router/src/useLocation.tsx index f0bcc8fffc..5fa39fa92e 100644 --- a/packages/react-router/src/useLocation.tsx +++ b/packages/react-router/src/useLocation.tsx @@ -1,4 +1,9 @@ -import { useRouterState } from './useRouterState' +'use client' + +import { useSelector } from '@tanstack/react-store' +import { isServer } from '@tanstack/router-core/isServer' +import { useRouter } from './useRouter' +import { useStructuralSharing } from './useMatch' import type { StructuralSharingOption, ValidateSelected, @@ -45,8 +50,19 @@ export function useLocation< opts?: UseLocationBaseOptions<TRouter, TSelected, TStructuralSharing> & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, ): UseLocationResult<TRouter, TSelected> { - return useRouterState({ - select: (state: any) => - opts?.select ? opts.select(state.location) : state.location, - } as any) as UseLocationResult<TRouter, TSelected> + const router = useRouter<TRouter>() + + if (isServer ?? router.isServer) { + const location = router.stores.location.get() + return ( + opts?.select ? opts.select(location as any) : location + ) as UseLocationResult<TRouter, TSelected> + } + + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + return useSelector( + router.stores.location, + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + useStructuralSharing(opts, router), + ) as UseLocationResult<TRouter, TSelected> } diff --git a/packages/react-router/src/useMatch.tsx b/packages/react-router/src/useMatch.tsx index 0f362a2c5b..95a4aaa286 100644 --- a/packages/react-router/src/useMatch.tsx +++ b/packages/react-router/src/useMatch.tsx @@ -1,7 +1,11 @@ +'use client' + import * as React from 'react' -import invariant from 'tiny-invariant' -import { useRouterState } from './useRouterState' +import { useSelector } from '@tanstack/react-store' +import { invariant, replaceEqualDeep } from '@tanstack/router-core' +import { isServer } from '@tanstack/router-core/isServer' import { dummyMatchContext, matchContext } from './matchContext' +import { useRouter } from './useRouter' import type { StructuralSharingOption, ValidateSelected, @@ -16,6 +20,47 @@ import type { ThrowOrOptional, } from '@tanstack/router-core' +const dummyMatch = {} + +export function useStructuralSharing< + TRouter extends AnyRouter, + TSelected, + TStructuralSharing extends boolean, + TStoreSlice, + TSelectSlice = TStoreSlice, +>( + opts: + | { + select?: ( + slice: TSelectSlice, + ) => ValidateSelected<TRouter, TSelected, TStructuralSharing> + structuralSharing?: boolean + } + | undefined, + router: TRouter, +): ( + slice: TStoreSlice, +) => ValidateSelected<TRouter, TSelected, TStructuralSharing> { + const previousResult = + // @ts-expect-error -- init to undefined, but without writing `undefined` to shave bytes + React.useRef<ValidateSelected<TRouter, TSelected, TStructuralSharing>>() + + return (slice) => { + const selected = opts?.select + ? opts.select(slice as unknown as TSelectSlice) + : (slice as ValidateSelected<TRouter, TSelected, TStructuralSharing>) + + if (opts?.structuralSharing ?? router.options.defaultStructuralSharing) { + return (previousResult.current = replaceEqualDeep( + previousResult.current, + selected, + )) + } + + return selected + } +} + export interface UseMatchBaseOptions< TRouter extends AnyRouter, TFrom, @@ -34,17 +79,18 @@ export type UseMatchRoute<out TFrom> = < TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, TStructuralSharing extends boolean = boolean, + TThrow extends boolean = true, >( opts?: UseMatchBaseOptions< TRouter, TFrom, true, - true, + TThrow, TSelected, TStructuralSharing > & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, -) => UseMatchResult<TRouter, TFrom, true, TSelected> +) => ThrowOrOptional<UseMatchResult<TRouter, TFrom, true, TSelected>, TThrow> export type UseMatchOptions< TRouter extends AnyRouter, @@ -96,28 +142,55 @@ export function useMatch< TStructuralSharing >, ): ThrowOrOptional<UseMatchResult<TRouter, TFrom, TStrict, TSelected>, TThrow> { - const nearestMatchId = React.useContext( + const router = useRouter<TRouter>() + const nearestRouteId = React.useContext( opts.from ? dummyMatchContext : matchContext, ) - const matchSelection = useRouterState({ - select: (state: any) => { - const match = state.matches.find((d: any) => - opts.from ? opts.from === d.routeId : d.id === nearestMatchId, - ) - invariant( - !((opts.shouldThrow ?? true) && !match), - `Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`, - ) + const routeId = opts.from ?? nearestRouteId + const matchStore = router.stores.getMatchStore(routeId!) - if (match === undefined) { - return undefined + if (isServer ?? router.isServer) { + const match = matchStore.get() + if (!match) { + if (opts.shouldThrow ?? true) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + `Invariant failed: Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`, + ) + } + + invariant() } - return opts.select ? opts.select(match) : match - }, - structuralSharing: opts.structuralSharing, - } as any) + return undefined as any + } - return matchSelection as any + return (opts.select ? opts.select(match as any) : match) as any + } + + const selector = + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + useStructuralSharing(opts, router) + + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + const matchSelection = useSelector(matchStore, (match) => + match ? selector(match as any) : dummyMatch, + ) + + if (matchSelection !== dummyMatch) { + return matchSelection as any + } + + if (opts.shouldThrow ?? true) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + `Invariant failed: Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`, + ) + } + + invariant() + } + + return undefined as any } diff --git a/packages/react-router/src/useNavigate.tsx b/packages/react-router/src/useNavigate.tsx index f697d0fbdd..ce95e5b4c1 100644 --- a/packages/react-router/src/useNavigate.tsx +++ b/packages/react-router/src/useNavigate.tsx @@ -1,3 +1,5 @@ +'use client' + import * as React from 'react' import { useLayoutEffect } from './utils' import { useRouter } from './useRouter' diff --git a/packages/react-router/src/useParams.tsx b/packages/react-router/src/useParams.tsx index 444eee7a41..44a6e47f9d 100644 --- a/packages/react-router/src/useParams.tsx +++ b/packages/react-router/src/useParams.tsx @@ -49,17 +49,18 @@ export type UseParamsRoute<out TFrom> = < TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, TStructuralSharing extends boolean = boolean, + TThrow extends boolean = true, >( opts?: UseParamsBaseOptions< TRouter, TFrom, /* TStrict */ true, - /* TThrow */ true, + TThrow, TSelected, TStructuralSharing > & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, -) => UseParamsResult<TRouter, TFrom, true, TSelected> +) => ThrowOrOptional<UseParamsResult<TRouter, TFrom, true, TSelected>, TThrow> /** * Access the current route's path parameters with type-safety. diff --git a/packages/react-router/src/useRouter.tsx b/packages/react-router/src/useRouter.tsx index abfefecaa3..6708274c11 100644 --- a/packages/react-router/src/useRouter.tsx +++ b/packages/react-router/src/useRouter.tsx @@ -1,6 +1,7 @@ +'use client' + import * as React from 'react' -import warning from 'tiny-warning' -import { getRouterContext } from './routerContext' +import { routerContext } from './routerContext' import type { AnyRouter, RegisteredRouter } from '@tanstack/router-core' /** @@ -16,10 +17,19 @@ import type { AnyRouter, RegisteredRouter } from '@tanstack/router-core' export function useRouter<TRouter extends AnyRouter = RegisteredRouter>(opts?: { warn?: boolean }): TRouter { - const value = React.useContext(getRouterContext()) - warning( - !((opts?.warn ?? true) && !value), - 'useRouter must be used inside a <RouterProvider> component!', - ) + const value = React.useContext(routerContext) + if (!value) { + warnMissingRouter(opts) + } return value as any } + +// Kept out of the hook body: this dev-only branch runs for every Link and +// route hook, and on the server each `process.env` read is a native call. +function warnMissingRouter(opts?: { warn?: boolean }) { + if (process.env.NODE_ENV !== 'production' && (opts?.warn ?? true)) { + console.warn( + 'Warning: useRouter must be used inside a <RouterProvider> component!', + ) + } +} diff --git a/packages/react-router/src/useRouterState.tsx b/packages/react-router/src/useRouterState.tsx index 08a7c7b9b8..fa17ee9f59 100644 --- a/packages/react-router/src/useRouterState.tsx +++ b/packages/react-router/src/useRouterState.tsx @@ -1,7 +1,9 @@ -import { useStore } from '@tanstack/react-store' -import { useRef } from 'react' -import { replaceEqualDeep } from '@tanstack/router-core' +'use client' + +import { useSelector } from '@tanstack/react-store' +import { isServer } from '@tanstack/router-core/isServer' import { useRouter } from './useRouter' +import { useStructuralSharing } from './useMatch' import type { AnyRouter, RegisteredRouter, @@ -51,21 +53,25 @@ export function useRouterState< warn: opts?.router === undefined, }) const router = opts?.router || contextRouter - const previousResult = - useRef<ValidateSelected<TRouter, TSelected, TStructuralSharing>>(undefined) - return useStore(router.__store, (state) => { - if (opts?.select) { - if (opts.structuralSharing ?? router.options.defaultStructuralSharing) { - const newSlice = replaceEqualDeep( - previousResult.current, - opts.select(state), - ) - previousResult.current = newSlice - return newSlice - } - return opts.select(state) - } - return state - }) as UseRouterStateResult<TRouter, TSelected> + // During SSR we render exactly once and do not need reactivity. + // Avoid subscribing to the store (and any structural sharing work) on the server. + // The expression must stay inlined in the `if` so bundlers fold the + // browser-build constant `isServer = false` and drop this server block. + if (isServer ?? router.isServer) { + const state = router.stores.__store.get() as RouterState< + TRouter['routeTree'] + > + return (opts?.select ? opts.select(state) : state) as UseRouterStateResult< + TRouter, + TSelected + > + } + + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + return useSelector( + router.stores.__store, + // eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static + useStructuralSharing(opts, router), + ) as UseRouterStateResult<TRouter, TSelected> } diff --git a/packages/react-router/src/useSearch.tsx b/packages/react-router/src/useSearch.tsx index 46b6e51642..3979967d76 100644 --- a/packages/react-router/src/useSearch.tsx +++ b/packages/react-router/src/useSearch.tsx @@ -49,17 +49,18 @@ export type UseSearchRoute<out TFrom> = < TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, TStructuralSharing extends boolean = boolean, + TThrow extends boolean = true, >( opts?: UseSearchBaseOptions< TRouter, TFrom, /* TStrict */ true, - /* TThrow */ true, + TThrow, TSelected, TStructuralSharing > & StructuralSharingOption<TRouter, TSelected, TStructuralSharing>, -) => UseSearchResult<TRouter, TFrom, true, TSelected> +) => ThrowOrOptional<UseSearchResult<TRouter, TFrom, true, TSelected>, TThrow> /** * Read and select the current route's search parameters with type-safety. @@ -98,7 +99,7 @@ export function useSearch< strict: opts.strict, shouldThrow: opts.shouldThrow, structuralSharing: opts.structuralSharing, - select: (match: any) => { + select: (match) => { return opts.select ? opts.select(match.search) : match.search }, }) as any diff --git a/packages/react-router/src/utils.ts b/packages/react-router/src/utils.ts index 23443dc58e..7887761993 100644 --- a/packages/react-router/src/utils.ts +++ b/packages/react-router/src/utils.ts @@ -1,4 +1,21 @@ +'use client' import * as React from 'react' +import { isServer } from '@tanstack/router-core/isServer' + +// Safe version of React.use() that will not cause compilation errors against +// React 18 with Webpack, which statically analyzes imports and fails when it +// sees React.use referenced (since 'use' is not exported from React 18). +// This uses a dynamic string lookup to avoid the static analysis. +// eslint-disable-next-line prefer-const -- Must be `let` to prevent bundler constant-folding +let REACT_USE = 'use' + +/** + * React.use if available (React 19+), undefined otherwise. + * Use dynamic lookup to avoid Webpack compilation errors with React 18. + */ +export const reactUse: + | (<T>(usable: Promise<T> | React.Context<T>) => T) + | undefined = (React as any)[REACT_USE] export function useStableCallback<T extends (...args: Array<any>) => any>( fn: T, @@ -11,7 +28,9 @@ export function useStableCallback<T extends (...args: Array<any>) => any>( } export const useLayoutEffect = - typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect + (isServer ?? typeof window === 'undefined') + ? React.useEffect + : React.useLayoutEffect /** * Taken from https://www.developerway.com/posts/implementing-advanced-use-previous-hook#part3 @@ -38,74 +57,3 @@ export function usePrevious<T>(value: T): T | null { // return the previous value only return ref.current.prev } - -/** - * React hook to wrap `IntersectionObserver`. - * - * This hook will create an `IntersectionObserver` and observe the ref passed to it. - * - * When the intersection changes, the callback will be called with the `IntersectionObserverEntry`. - * - * @param ref - The ref to observe - * @param intersectionObserverOptions - The options to pass to the IntersectionObserver - * @param options - The options to pass to the hook - * @param callback - The callback to call when the intersection changes - * @returns The IntersectionObserver instance - * @example - * ```tsx - * const MyComponent = () => { - * const ref = React.useRef<HTMLDivElement>(null) - * useIntersectionObserver( - * ref, - * (entry) => { doSomething(entry) }, - * { rootMargin: '10px' }, - * { disabled: false } - * ) - * return <div ref={ref} /> - * ``` - */ -export function useIntersectionObserver<T extends Element>( - ref: React.RefObject<T | null>, - callback: (entry: IntersectionObserverEntry | undefined) => void, - intersectionObserverOptions: IntersectionObserverInit = {}, - options: { disabled?: boolean } = {}, -) { - React.useEffect(() => { - if ( - !ref.current || - options.disabled || - typeof IntersectionObserver !== 'function' - ) { - return - } - - const observer = new IntersectionObserver(([entry]) => { - callback(entry) - }, intersectionObserverOptions) - - observer.observe(ref.current) - - return () => { - observer.disconnect() - } - }, [callback, intersectionObserverOptions, options.disabled, ref]) -} - -/** - * React hook to take a `React.ForwardedRef` and returns a `ref` that can be used on a DOM element. - * - * @param ref - The forwarded ref - * @returns The inner ref returned by `useRef` - * @example - * ```tsx - * const MyComponent = React.forwardRef((props, ref) => { - * const innerRef = useForwardedRef(ref) - * return <div ref={innerRef} /> - * }) - * ``` - */ -export function useForwardedRef<T>(ref?: React.ForwardedRef<T>) { - const innerRef = React.useRef<T>(null) - React.useImperativeHandle(ref, () => innerRef.current!, []) - return innerRef -} diff --git a/packages/react-router/tests/Asset.test.tsx b/packages/react-router/tests/Asset.test.tsx new file mode 100644 index 0000000000..11978db209 --- /dev/null +++ b/packages/react-router/tests/Asset.test.tsx @@ -0,0 +1,166 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, render } from '@testing-library/react' +import { + Asset, + RouterContextProvider, + createMemoryHistory, + createRootRoute, + createRouter, +} from '../src' +import type { RouterManagedTag } from '@tanstack/router-core' + +afterEach(() => { + cleanup() + vi.unstubAllEnvs() +}) + +test.each([ + ['style', { tag: 'style' }], + ['inline CSS', { tag: 'style', inlineCss: true }], + ['JSON-LD script', { tag: 'script', attrs: { type: 'application/ld+json' } }], + ['JSON script', { tag: 'script', attrs: { type: 'application/json' } }], +] satisfies Array<[string, RouterManagedTag]>)( + '%s only replaces content when it changes', + (_name, asset: Extract<RouterManagedTag, { tag: 'style' | 'script' }>) => { + vi.stubEnv('TSS_INLINE_CSS_ENABLED', 'true') + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory(), + }) + const initial = + asset.tag === 'style' ? '.asset{color:red}' : '{"value":"initial"}' + const updated = + asset.tag === 'style' ? '.asset{color:blue}' : '{"value":"updated"}' + const renderAsset = (children: string, version: string) => ( + <RouterContextProvider router={router}> + <Asset + {...asset} + attrs={{ + ...asset.attrs, + 'data-testid': 'asset', + 'data-version': version, + }} + > + {children} + </Asset> + </RouterContextProvider> + ) + const { getByTestId, rerender } = render(renderAsset(initial, 'initial')) + const element = getByTestId('asset') + const text = element.firstChild + expect(element.textContent).toBe(initial) + expect(text).not.toBeNull() + + rerender(renderAsset(initial, 'rerender')) + expect(getByTestId('asset')).toBe(element) + expect(element).toHaveAttribute('data-version', 'rerender') + expect(element.firstChild).toBe(text) + + rerender(renderAsset(updated, 'updated')) + expect(getByTestId('asset')).toBe(element) + expect(element.textContent).toBe(updated) + expect(element.firstChild).not.toBe(text) + + rerender(renderAsset('', 'empty')) + expect(element.textContent).toBe('') + }, +) + +test.each([undefined, '/asset.js'])( + 'injects and cleans up executable scripts with src=%s', + (src) => { + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory(), + }) + const { unmount } = render( + <RouterContextProvider router={router}> + <Asset + tag="script" + attrs={{ + id: 'injected-asset', + src, + async: true, + defer: false, + nonce: 'asset-nonce', + 'data-empty': '', + 'data-omitted': undefined, + suppressHydrationWarning: true, + }} + > + {src ? undefined : 'void 0'} + </Asset> + </RouterContextProvider>, + ) + const script = + document.head.querySelector<HTMLScriptElement>('#injected-asset') + expect(script).toHaveAttribute('async', '') + expect(script).not.toHaveAttribute('defer') + expect(script).toHaveAttribute('data-empty', '') + expect(script).not.toHaveAttribute('data-omitted') + expect(script).not.toHaveAttribute('suppresshydrationwarning') + expect(script?.nonce).toBe('asset-nonce') + expect(script?.textContent).toBe(src ? '' : 'void 0') + expect(script?.getAttribute('src')).toBe(src ?? null) + + unmount() + expect(script).not.toBeInTheDocument() + }, +) + +test.each(['/asset.js', '//cdn.example.com/asset.js', 'http://['])( + 'reuses existing executable scripts with src=%s', + (src) => { + const existing = document.createElement('script') + existing.src = src + document.head.appendChild(existing) + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory(), + }) + + try { + const { unmount } = render( + <RouterContextProvider router={router}> + <Asset tag="script" attrs={{ src }} /> + </RouterContextProvider>, + ) + expect(Array.from(document.scripts)).toEqual([existing]) + + unmount() + expect(existing).toBeInTheDocument() + } finally { + existing.remove() + } + }, +) + +test.each([undefined, '', '/asset.js'])( + 'only deduplicates inline content against scripts without src (src=%s)', + (src) => { + const existing = document.createElement('script') + existing.textContent = 'void 0' + if (src !== undefined) { + existing.setAttribute('src', src) + } + document.head.appendChild(existing) + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory(), + }) + + try { + const { unmount } = render( + <RouterContextProvider router={router}> + <Asset tag="script">void 0</Asset> + </RouterContextProvider>, + ) + expect(document.scripts).toHaveLength(src === undefined ? 1 : 2) + + unmount() + expect(Array.from(document.scripts)).toEqual([existing]) + } finally { + existing.remove() + } + }, +) diff --git a/packages/react-router/tests/Matches.test-d.tsx b/packages/react-router/tests/Matches.test-d.tsx index 2116e78416..89e1088454 100644 --- a/packages/react-router/tests/Matches.test-d.tsx +++ b/packages/react-router/tests/Matches.test-d.tsx @@ -8,7 +8,8 @@ import { useMatchRoute, useMatches, } from '../src' -import type { AnyRouteMatch, RouteMatch } from '../src' +import type * as React from 'react' +import type { AnyRouteMatch, MakeMatchRouteOptions, RouteMatch } from '../src' const rootRoute = createRootRoute() @@ -233,3 +234,19 @@ test('when filtering useMatches by loaderData with an array', () => { matches.filter((match) => isMatch(match, 'loaderData.0.comment')), ).toEqualTypeOf<Array<CommentsMatch>>() }) + +test('MatchRoute children are typed from resolved params under pathless layouts', () => { + type CommentsMatchRouteChildren = MakeMatchRouteOptions< + DefaultRouter, + string, + '/comments/$id' + >['children'] + type CommentsMatchRouteRenderFn = Extract< + CommentsMatchRouteChildren, + (...args: Array<any>) => any + > + + expectTypeOf<CommentsMatchRouteRenderFn>().toEqualTypeOf< + (params?: { id: string } | undefined) => React.ReactNode + >() +}) diff --git a/packages/react-router/tests/Matches.test.tsx b/packages/react-router/tests/Matches.test.tsx index dd3ca3dfa6..93dca8b9c0 100644 --- a/packages/react-router/tests/Matches.test.tsx +++ b/packages/react-router/tests/Matches.test.tsx @@ -1,9 +1,19 @@ import { afterEach, describe, expect, test } from 'vitest' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { + act, + cleanup, + fireEvent, + render, + renderHook, + screen, + waitFor, +} from '@testing-library/react' import { createMemoryHistory } from '@tanstack/history' +import { createControlledPromise } from '@tanstack/router-core' import { Link, Outlet, + RouterContextProvider, RouterProvider, createRootRoute, createRoute, @@ -126,11 +136,11 @@ test('when filtering useMatches by loaderData', async () => { test('should show pendingComponent of root route', async () => { const root = createRootRoute({ - pendingComponent: () => <div data-testId="root-pending" />, + pendingComponent: () => <div data-testid="root-pending" />, loader: async () => { await new Promise((r) => setTimeout(r, 50)) }, - component: () => <div data-testId="root-content" />, + component: () => <div data-testid="root-content" />, }) const router = createRouter({ @@ -145,6 +155,187 @@ test('should show pendingComponent of root route', async () => { expect(await rendered.findByTestId('root-content')).toBeInTheDocument() }) +test('useMatchRoute follows superseding pending locations', async () => { + const aGate = createControlledPromise<void>() + const bGate = createControlledPromise<void>() + + function Layout() { + const matchRoute = useMatchRoute() + return ( + <div> + <span data-testid="pending-a"> + {String(Boolean(matchRoute({ to: '/a', pending: true })))} + </span> + <span data-testid="pending-b"> + {String(Boolean(matchRoute({ to: '/b', pending: true })))} + </span> + <span data-testid="resolved-b"> + {String(Boolean(matchRoute({ to: '/b', pending: false })))} + </span> + <Outlet /> + </div> + ) + } + + const root = createRootRoute({ component: Layout }) + const index = createRoute({ + getParentRoute: () => root, + path: '/', + }) + const a = createRoute({ + getParentRoute: () => root, + path: '/a', + loader: () => aGate, + }) + const b = createRoute({ + getParentRoute: () => root, + path: '/b', + loader: () => bGate, + }) + const router = createRouter({ + routeTree: root.addChildren([index, a, b]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + render(<RouterProvider router={router} />) + + await waitFor(() => { + expect(screen.getByTestId('pending-a')).toHaveTextContent('false') + expect(router.stores.status.get()).toBe('idle') + expect(router.stores.resolvedLocation.get()?.pathname).toBe('/') + }) + + let navigationA!: Promise<void> + act(() => { + navigationA = router.navigate({ to: '/a' }) + }) + await waitFor(() => { + expect(screen.getByTestId('pending-a')).toHaveTextContent('true') + expect(screen.getByTestId('resolved-b')).toHaveTextContent('false') + }) + + let navigationB!: Promise<void> + act(() => { + navigationB = router.navigate({ to: '/b' }) + }) + await waitFor(() => { + expect(screen.getByTestId('pending-a')).toHaveTextContent('false') + expect(screen.getByTestId('pending-b')).toHaveTextContent('true') + expect(screen.getByTestId('resolved-b')).toHaveTextContent('false') + }) + + await act(async () => { + aGate.resolve() + bGate.resolve() + await Promise.allSettled([navigationA, navigationB]) + }) + await waitFor(() => { + expect(screen.getByTestId('pending-b')).toHaveTextContent('false') + expect(screen.getByTestId('resolved-b')).toHaveTextContent('true') + }) +}) + +test('useMatchRoute callback identity tracks route matching state', async () => { + const root = createRootRoute() + const a = createRoute({ + getParentRoute: () => root, + path: '/a', + }) + const b = createRoute({ + getParentRoute: () => root, + path: '/b', + }) + const router = createRouter({ + routeTree: root.addChildren([a, b]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const aLocation = router.buildLocation({ to: '/a' }) + const bLocation = router.buildLocation({ to: '/b' }) + + const { result, rerender } = renderHook(() => useMatchRoute(), { + wrapper: ({ children }) => ( + <RouterContextProvider router={router}>{children}</RouterContextProvider> + ), + }) + + let previous = result.current + rerender() + expect(result.current).toBe(previous) + + async function expectCallbackInvalidated(update: () => void) { + previous = result.current + act(update) + await waitFor(() => expect(result.current).not.toBe(previous)) + } + + await expectCallbackInvalidated(() => { + router.stores.location.set(aLocation) + }) + await expectCallbackInvalidated(() => { + router.stores.resolvedLocation.set(bLocation) + }) + await expectCallbackInvalidated(() => { + router.stores.status.set('pending') + }) + + previous = result.current + act(() => { + router.stores.location.set({ ...aLocation }) + router.stores.resolvedLocation.set({ ...bLocation }) + router.stores.status.set('pending') + }) + rerender() + expect(result.current).toBe(previous) +}) + +test('legacy notFoundRoute drops a stale parent layout after navigation', async () => { + let legacyLoads = 0 + const root = createRootRoute({ component: Outlet }) + const parent = createRoute({ + getParentRoute: () => root, + path: '/parent', + component: () => ( + <div> + Parent layout + <Outlet /> + </div> + ), + }) + const known = createRoute({ + getParentRoute: () => parent, + path: '/known', + }) + const legacyNotFound = createRoute({ + getParentRoute: () => root, + path: '/404', + loader: () => { + legacyLoads++ + return 'not found' + }, + component: () => <div>Legacy not found</div>, + staleTime: Infinity, + gcTime: Infinity, + }) + const router = createRouter({ + routeTree: root.addChildren([parent.addChildren([known])]), + history: createMemoryHistory({ initialEntries: ['/parent/missing'] }), + notFoundRoute: legacyNotFound, + }) + + const rendered = render(<RouterProvider router={router} />) + expect(await rendered.findByText('Parent layout')).toBeInTheDocument() + expect(await rendered.findByText('Legacy not found')).toBeInTheDocument() + expect(legacyLoads).toBe(1) + + await act(async () => { + await router.navigate({ to: '/missing' } as any) + }) + + expect(rendered.queryByText('Parent layout')).not.toBeInTheDocument() + expect(await rendered.findByText('Legacy not found')).toBeInTheDocument() + expect(legacyLoads).toBe(1) + rendered.unmount() +}) + describe('matching on different param types', () => { const testCases = [ { diff --git a/packages/react-router/tests/Outlet.test.tsx b/packages/react-router/tests/Outlet.test.tsx new file mode 100644 index 0000000000..e8dc5447cb --- /dev/null +++ b/packages/react-router/tests/Outlet.test.tsx @@ -0,0 +1,146 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, render, screen } from '@testing-library/react' +import { createMemoryHistory } from '@tanstack/history' +import { createControlledPromise, notFound } from '@tanstack/router-core' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +const outletWarning = ( + component: 'pendingComponent' | 'errorComponent' | 'notFoundComponent', +) => + `Warning: An <Outlet /> was rendered inside a ${component}. <Outlet /> should only be rendered inside a route component.` + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +test('does not warn when Outlet is rendered inside a route component', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const rootRoute = createRootRoute({ + component: () => ( + <> + <span>Root route</span> + <Outlet /> + </> + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => <span>Index route</span>, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(<RouterProvider router={router} />) + + expect(await screen.findByText('Index route')).toBeInTheDocument() + expect(warn).not.toHaveBeenCalled() +}) + +test('warns when Outlet is rendered inside a pendingComponent', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const pending = createControlledPromise<void>() + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => <span>Index route</span>, + }) + const pendingRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/pending', + loader: () => pending, + pendingMs: 0, + pendingComponent: () => ( + <> + <span>Pending route</span> + <Outlet /> + </> + ), + component: () => <span>Resolved route</span>, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pendingRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(<RouterProvider router={router} />) + await screen.findByText('Index route') + + const navigation = router.navigate({ to: '/pending' }) + expect(await screen.findByText('Pending route')).toBeInTheDocument() + pending.resolve() + await navigation + + expect(warn).toHaveBeenCalledWith(outletWarning('pendingComponent')) +}) + +test('warns when Outlet is rendered inside an errorComponent', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: () => { + throw new Error('Loader failed') + }, + errorComponent: () => ( + <> + <span>Error route</span> + <Outlet /> + </> + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(<RouterProvider router={router} />) + + expect(await screen.findByText('Error route')).toBeInTheDocument() + expect(warn).toHaveBeenCalledWith(outletWarning('errorComponent')) +}) + +test('warns when Outlet is rendered inside a notFoundComponent', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => <span>Index route</span>, + }) + const notFoundRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/not-found', + component: () => { + throw notFound() + }, + notFoundComponent: () => ( + <> + <span>Not found route</span> + <Outlet /> + </> + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, notFoundRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(<RouterProvider router={router} />) + await screen.findByText('Index route') + await router.navigate({ to: '/not-found' }) + + expect(await screen.findByText('Not found route')).toBeInTheDocument() + expect(warn).toHaveBeenCalledWith(outletWarning('notFoundComponent')) +}) diff --git a/packages/react-router/tests/Scripts.test.tsx b/packages/react-router/tests/Scripts.test.tsx index 315b3e528e..976410cba5 100644 --- a/packages/react-router/tests/Scripts.test.tsx +++ b/packages/react-router/tests/Scripts.test.tsx @@ -1,17 +1,67 @@ -import { describe, expect, test } from 'vitest' -import { act, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { createPortal } from 'react-dom' import ReactDOMServer from 'react-dom/server' +import { hydrate } from '@tanstack/router-core/ssr/client' +import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id' import { HeadContent, + Link, Outlet, + RouterContextProvider, RouterProvider, + createBrowserHistory, createMemoryHistory, createRootRoute, createRoute, createRouter, } from '../src' import { Scripts } from '../src/Scripts' +import type { Manifest } from '@tanstack/router-core' + +// React 19 keeps stylesheet resources keyed by href alive for the lifetime of +// the test module, so these tests use explicit asset URLs to avoid collisions +// between cases even though Testing Library cleanup runs after each test. +const createTestManifest = ( + routeId: string, + options?: { + stylesheetHref?: string + preloadHref?: string + scriptFormat?: Manifest['scriptFormat'] + }, +) => + ({ + ...(options?.scriptFormat ? { scriptFormat: options.scriptFormat } : {}), + routes: { + [routeId]: { + preloads: [options?.preloadHref ?? '/main.js'], + css: [options?.stylesheetHref ?? '/main.css'], + }, + }, + }) satisfies Manifest + +const browserHistories: Array<ReturnType<typeof createBrowserHistory>> = [] + +const createTestBrowserHistory = () => { + const history = createBrowserHistory() + browserHistories.push(history) + return history +} + +afterEach(() => { + cleanup() + browserHistories.splice(0).forEach((history) => history.destroy()) + window.history.replaceState(null, 'root', '/') + delete window.$_TSR +}) describe('ssr scripts', () => { test('it works', async () => { @@ -112,19 +162,295 @@ describe('ssr scripts', () => { { src: 'script3.js' }, ]) - const { container } = await act(() => - render(<RouterProvider router={router} />), + const html = ReactDOMServer.renderToString( + <RouterProvider router={router} />, ) - expect(await screen.findByTestId('root')).toBeInTheDocument() - expect(await screen.findByTestId('index')).toBeInTheDocument() + expect(html).toContain('<script src="script.js"></script>') + expect(html).toContain('<script src="script3.js"></script>') + expect(html).not.toContain('script2.js') + }) +}) - expect(container.innerHTML).toEqual( - `<div><div data-testid="root">root</div><div data-testid="index">index</div><script src="script.js"></script><script src="script3.js"></script></div>`, +describe('scripts with async/defer attributes', () => { + test('server renders scripts with async/defer attributes in output', async () => { + const rootRoute = createRootRoute({ + scripts: () => [ + { + src: 'script.js', + async: true, + }, + { + src: 'script2.js', + defer: true, + }, + ], + component: () => { + return ( + <div> + <div data-testid="server-root">root</div> + <Outlet /> + <Scripts /> + </div> + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + component: () => { + return <div data-testid="server-index">index</div> + }, + }) + + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree: rootRoute.addChildren([indexRoute]), + isServer: true, + }) + + await router.load() + + // Use ReactDOMServer.renderToString to test actual server output + const html = ReactDOMServer.renderToString( + <RouterProvider router={router} />, ) + + expect(html).toMatch(/<script[^>]*src="script\.js"[^>]*async=""/) + expect(html).toMatch(/<script[^>]*src="script2\.js"[^>]*defer=""/) + }) + + test('server keeps manifest src scripts in document order', async () => { + const clientEntryAsset = { + attrs: { + src: '/entry.js', + type: 'module', + async: true, + }, + } satisfies NonNullable<Manifest['routes'][string]['scripts']>[number] + + const rootRoute = createRootRoute({ + component: () => { + return ( + <html> + <head /> + <body> + <main data-testid="content">content</main> + <Outlet /> + <Scripts /> + </body> + </html> + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + }) + + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree: rootRoute.addChildren([indexRoute]), + isServer: true, + }) + router.ssr = { + manifest: { + routes: { + [rootRoute.id]: { + scripts: [clientEntryAsset], + }, + }, + }, + } + + await router.load() + + const html = ReactDOMServer.renderToString( + <RouterProvider router={router} />, + ) + const contentIndex = html.indexOf('<main data-testid="content">') + const scriptIndex = html.indexOf('src="/entry.js"') + + expect(contentIndex).toBeGreaterThan(-1) + expect(scriptIndex).toBeGreaterThan(contentIndex) + expect(html).not.toContain('client-entry') + }) + + test('client renders scripts with attributes (including async/defer)', async () => { + const rootRoute = createRootRoute({ + scripts: () => [ + { + src: 'script.js', + async: true, + crossOrigin: 'anonymous', + }, + ], + component: () => { + return ( + <div> + <div data-testid="async-root">root</div> + <Outlet /> + <Scripts /> + </div> + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + component: () => { + return <div data-testid="async-index">index</div> + }, + }) + + // Clear head and any leftover body scripts between tests. + document.head.innerHTML = '' + document.querySelectorAll('body script').forEach((s) => s.remove()) + + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree: rootRoute.addChildren([indexRoute]), + isServer: false, // Client-side rendering + }) + + await router.load() + + await act(() => render(<RouterProvider router={router} />)) + + expect(await screen.findByTestId('async-root')).toBeInTheDocument() + + const script = document.querySelector('script[src="script.js"]') + expect(script).toBeTruthy() + + // Attributes are preserved on the client. + expect(script?.getAttribute('src')).toBe('script.js') + expect(script?.hasAttribute('async')).toBe(true) + expect(script?.getAttribute('crossorigin')).toBe('anonymous') }) }) describe('ssr HeadContent', () => { + test('renders descendant assets during a data-only hydration handoff', async () => { + const rootRoute = createRootRoute({}) + const dataOnlyRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/report', + ssr: 'data-only', + loader: () => 'report', + }) + const childRoute = createRoute({ + getParentRoute: () => dataOnlyRoute, + path: '/details', + loader: () => 'details', + head: () => ({ + meta: [{ name: 'data-only-child', content: 'visible' }], + links: [{ rel: 'preload', href: '/data-only-head-link.js' }], + styles: [ + { + id: 'data-only-route-style', + children: '.data-only-child { color: green }', + }, + ], + scripts: [ + { + id: 'data-only-head-script', + type: 'application/json', + children: '{"source":"head"}', + }, + ], + }), + scripts: () => [ + { + id: 'data-only-body-script', + type: 'application/json', + children: '{"source":"body"}', + }, + ], + }) + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/report/details'], + }), + routeTree: rootRoute.addChildren([ + dataOnlyRoute.addChildren([childRoute]), + ]), + }) + const matches = router.matchRoutes(router.latestLocation) + window.$_TSR = { + router: { + dehydratedData: {}, + manifest: { + routes: { + [childRoute.id]: { + css: ['/data-only-manifest.css'], + preloads: ['/data-only-manifest.js'], + scripts: [ + { + attrs: { + id: 'data-only-manifest-script', + type: 'application/json', + }, + children: '{"source":"manifest"}', + }, + ], + }, + }, + }, + matches: matches.map((match, index) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success', + ssr: index === 1 ? 'data-only' : true, + l: index ? (index === 1 ? 'report' : 'details') : undefined, + u: Date.now(), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + } + + await hydrate(router) + + expect(router.state.matches.map((match) => match.status)).toEqual([ + 'success', + 'pending', + 'success', + ]) + render( + <RouterContextProvider router={router}> + <HeadContent /> + <Scripts /> + </RouterContextProvider>, + ) + + expect( + document.querySelector('meta[name="data-only-child"]'), + ).not.toBeNull() + expect( + document.querySelector('link[href="/data-only-head-link.js"]'), + ).not.toBeNull() + expect(document.querySelector('#data-only-route-style')).not.toBeNull() + expect(document.querySelector('#data-only-head-script')).not.toBeNull() + expect(document.querySelector('#data-only-body-script')).not.toBeNull() + expect( + document.querySelector('link[href="/data-only-manifest.css"]'), + ).not.toBeNull() + expect( + document.querySelector('link[href="/data-only-manifest.js"]'), + ).not.toBeNull() + expect(document.querySelector('#data-only-manifest-script')).not.toBeNull() + }) + test('derives title, dedupes meta, and allows non-loader HeadContent', async () => { const rootRoute = createRootRoute({ loader: () => @@ -220,4 +546,923 @@ describe('ssr HeadContent', () => { `<title>Index`, ) }) + + test('renders manifest module preloads with low fetch priority', async () => { + const preloadHref = '/low-priority-module.js' + const rootRoute = createRootRoute({ + component: () => , + }) + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + }) + const router = createRouter({ + history: createMemoryHistory({ initialEntries: ['/'] }), + routeTree: rootRoute.addChildren([indexRoute]), + isServer: true, + }) + + router.ssr = { + manifest: createTestManifest(rootRoute.id, { preloadHref }), + } + + await router.load() + + const html = ReactDOMServer.renderToString( + , + ) + expect(html).toContain( + ``, + ) + }) + + test('keeps manifest stylesheet links mounted when history state changes', async () => { + const history = createTestBrowserHistory() + const stylesheetHref = '/history-state.css' + + const rootRoute = createRootRoute({ + component: () => { + return ( + <> + {createPortal(, document.head)} + + + + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + component: () =>
    Index
    , + }) + + const router = createRouter({ + history, + routeTree: rootRoute.addChildren([indexRoute]), + }) + + router.ssr = { + manifest: createTestManifest(rootRoute.id, { + stylesheetHref, + }), + } + + await router.load() + + await act(() => render()) + + const getStylesheetLink = () => + Array.from(document.querySelectorAll('link[rel="stylesheet"]')).find( + (link) => link.getAttribute('href') === stylesheetHref, + ) + + await waitFor(() => { + expect(getStylesheetLink()).toBeInstanceOf(HTMLLinkElement) + }) + + const initialLink = getStylesheetLink() + expect(initialLink).toBeInstanceOf(HTMLLinkElement) + + fireEvent.click(screen.getByRole('button', { name: 'Replace state' })) + + await waitFor(() => { + expect(router.state.location.state).toMatchObject({ + slideId: 'slide-2', + }) + }) + + expect(getStylesheetLink()).toBe(initialLink) + expect( + Array.from(document.querySelectorAll('link[rel="stylesheet"]')).filter( + (link) => link.getAttribute('href') === stylesheetHref, + ), + ).toHaveLength(1) + }) + + test('applies assetCrossOrigin to manifest stylesheets and preloads', async () => { + const history = createTestBrowserHistory() + const stylesheetHref = '/asset-cross-origin.css' + const preloadHref = '/asset-cross-origin.js' + + const rootRoute = createRootRoute({ + component: () => { + return ( + <> + {createPortal( + , + document.head, + )} + + + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + component: () =>
    Index
    , + }) + + const router = createRouter({ + history, + routeTree: rootRoute.addChildren([indexRoute]), + }) + + router.ssr = { + manifest: createTestManifest(rootRoute.id, { + stylesheetHref, + preloadHref, + }), + } + + await router.load() + + await act(() => render()) + + await waitFor(() => { + expect( + document.head.querySelector( + `link[rel="stylesheet"][href="${stylesheetHref}"]`, + ), + ).toBeTruthy() + expect( + document.head.querySelector( + `link[rel="modulepreload"][href="${preloadHref}"]`, + ), + ).toBeTruthy() + }) + + expect( + document.head + .querySelector(`link[rel="stylesheet"][href="${stylesheetHref}"]`) + ?.getAttribute('crossorigin'), + ).toBe('use-credentials') + expect( + document.head + .querySelector(`link[rel="modulepreload"][href="${preloadHref}"]`) + ?.getAttribute('crossorigin'), + ).toBe('anonymous') + }) + + test('renders runtime manifest inlineStyle', async () => { + const history = createTestBrowserHistory() + + const rootRoute = createRootRoute({ + component: () => { + return ( + <> + {createPortal(, document.head)} + + + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + component: () =>
    Index
    , + }) + + const router = createRouter({ + history, + routeTree: rootRoute.addChildren([indexRoute]), + }) + + router.ssr = { + manifest: { + inlineStyle: { + attrs: { id: 'runtime-inline-style' }, + children: '.runtime{color:red}', + }, + routes: { + [rootRoute.id]: {}, + }, + }, + } + + await router.load() + + await act(() => render()) + + await waitFor(() => { + expect( + document.head.querySelector('style#runtime-inline-style'), + ).toBeTruthy() + }) + + expect( + document.head.querySelector('style#runtime-inline-style')?.textContent, + ).toBe('.runtime{color:red}') + }) + + test('renders iife manifest preloads as low priority script links', async () => { + const history = createTestBrowserHistory() + const preloadHref = '/iife-preload.js' + + const rootRoute = createRootRoute({ + component: () => { + return ( + <> + {createPortal(, document.head)} + + + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + component: () =>
    Index
    , + }) + + const router = createRouter({ + history, + routeTree: rootRoute.addChildren([indexRoute]), + }) + + router.ssr = { + manifest: createTestManifest(rootRoute.id, { + preloadHref, + scriptFormat: 'iife', + }), + } + + await router.load() + + await act(() => render()) + + await waitFor(() => { + expect( + document.head.querySelector( + `link[rel="preload"][as="script"][href="${preloadHref}"]`, + ), + ).toBeTruthy() + }) + + expect( + document.head.querySelector( + `link[rel="modulepreload"][href="${preloadHref}"]`, + ), + ).toBeFalsy() + expect( + document.head + .querySelector( + `link[rel="preload"][as="script"][href="${preloadHref}"]`, + ) + ?.getAttribute('fetchpriority'), + ).toBe('low') + }) + + test('assetCrossOrigin overrides manifest crossOrigin values', async () => { + const history = createTestBrowserHistory() + const stylesheetHref = '/override-cross-origin.css' + const preloadHref = '/override-cross-origin.js' + + const rootRoute = createRootRoute({ + component: () => { + return ( + <> + {createPortal( + , + document.head, + )} + + + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + component: () =>
    Index
    , + }) + + const router = createRouter({ + history, + routeTree: rootRoute.addChildren([indexRoute]), + }) + + router.ssr = { + manifest: { + routes: { + [rootRoute.id]: { + preloads: [ + { href: preloadHref, crossOrigin: 'use-credentials' as const }, + ], + css: [ + { + href: stylesheetHref, + crossOrigin: 'use-credentials', + }, + ], + }, + }, + } as any, + } + + await router.load() + + await act(() => render()) + + await waitFor(() => { + expect( + document.head.querySelector( + `link[rel="stylesheet"][href="${stylesheetHref}"]`, + ), + ).toBeTruthy() + expect( + document.head.querySelector( + `link[rel="modulepreload"][href="${preloadHref}"]`, + ), + ).toBeTruthy() + }) + + expect( + document.head + .querySelector(`link[rel="stylesheet"][href="${stylesheetHref}"]`) + ?.getAttribute('crossorigin'), + ).toBe('anonymous') + expect( + document.head + .querySelector(`link[rel="modulepreload"][href="${preloadHref}"]`) + ?.getAttribute('crossorigin'), + ).toBe('anonymous') + }) + + test('keeps manifest stylesheet links mounted across repeated Link navigations', async () => { + const history = createTestBrowserHistory() + const stylesheetHref = '/repeated-nav.css' + + const rootRoute = createRootRoute({ + component: () => { + return ( + <> + {createPortal(, document.head)} + + + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + component: () => Go to about page, + }) + + const aboutRoute = createRoute({ + path: '/about', + getParentRoute: () => rootRoute, + component: () => Back to home, + }) + + const router = createRouter({ + history, + routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + }) + + router.ssr = { + manifest: createTestManifest(rootRoute.id, { + stylesheetHref, + }), + } + + await router.load() + + await act(() => render()) + + const getStylesheetLink = () => + Array.from(document.querySelectorAll('link[rel="stylesheet"]')).find( + (link) => link.getAttribute('href') === stylesheetHref, + ) + + await waitFor(() => { + expect(getStylesheetLink()).toBeInstanceOf(HTMLLinkElement) + }) + + const initialLink = getStylesheetLink() + expect(initialLink).toBeInstanceOf(HTMLLinkElement) + + for (let i = 0; i < 5; i++) { + fireEvent.click(screen.getByRole('link', { name: 'Go to about page' })) + + await waitFor(() => { + expect(router.state.location.pathname).toBe('/about') + }) + + await screen.findByRole('link', { name: 'Back to home' }) + + fireEvent.click(screen.getByRole('link', { name: 'Back to home' })) + + await waitFor(() => { + expect(router.state.location.pathname).toBe('/') + }) + + await screen.findByRole('link', { name: 'Go to about page' }) + } + + expect(getStylesheetLink()).toBe(initialLink) + expect( + Array.from(document.querySelectorAll('link[rel="stylesheet"]')).filter( + (link) => link.getAttribute('href') === stylesheetHref, + ), + ).toHaveLength(1) + }) + + test('does not render retained descendant assets past a terminal parent boundary', async () => { + let failParent = false + const childHeadScript = '{"source":"child-head"}' + const childBodyScript = '{"source":"child-body"}' + const childManifestScript = '{"source":"child-manifest"}' + const childPreload = '/terminal-child-preload.js' + const childHeadLink = '/terminal-child-head-link.js' + const rootRoute = createRootRoute({ + component: () => ( + <> + {createPortal(, document.head)} + + + + ), + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + shouldReload: true, + loader: () => { + if (failParent) { + throw new Error('parent failed') + } + }, + component: Outlet, + errorComponent: () =>
    Parent error
    , + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: () => ({ + meta: [{ name: 'terminal-child', content: 'visible' }], + links: [{ rel: 'preload', href: childHeadLink }], + styles: [{ children: '.terminal-child { color: red }' }], + scripts: [{ type: 'application/ld+json', children: childHeadScript }], + }), + scripts: () => [ + { type: 'application/ld+json', children: childBodyScript }, + ], + component: () =>
    Child content
    , + }) + const router = createRouter({ + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + }) + router.ssr = { + manifest: { + routes: { + [childRoute.id]: { + preloads: [childPreload], + scripts: [ + { + attrs: { type: 'application/ld+json' }, + children: childManifestScript, + }, + ], + }, + }, + }, + } + + await router.load() + await act(() => render()) + + await waitFor(() => { + expect( + document.head.querySelector('meta[name="terminal-child"]'), + ).not.toBeNull() + expect( + document.head.querySelector(`link[href="${childPreload}"]`), + ).not.toBeNull() + expect( + document.head.querySelector(`link[href="${childHeadLink}"]`), + ).not.toBeNull() + expect(document.head.textContent).toContain( + '.terminal-child { color: red }', + ) + expect(document.documentElement.textContent).toContain(childHeadScript) + expect(document.documentElement.textContent).toContain(childBodyScript) + expect(document.documentElement.textContent).toContain( + childManifestScript, + ) + }) + + failParent = true + await act(() => router.invalidate()) + await screen.findByText('Parent error') + + expect(router.state.matches).toHaveLength(3) + expect(router.state.matches[1]).toMatchObject({ + routeId: parentRoute.id, + status: 'error', + }) + expect(router.state.matches[2]).toMatchObject({ + routeId: childRoute.id, + meta: [{ name: 'terminal-child', content: 'visible' }], + scripts: [{ type: 'application/ld+json', children: childBodyScript }], + }) + await waitFor(() => { + expect( + document.head.querySelector('meta[name="terminal-child"]'), + ).toBeNull() + expect( + document.head.querySelector(`link[href="${childPreload}"]`), + ).toBeNull() + expect( + document.head.querySelector(`link[href="${childHeadLink}"]`), + ).toBeNull() + expect(document.head.textContent).not.toContain( + '.terminal-child { color: red }', + ) + expect(document.documentElement.textContent).not.toContain( + childHeadScript, + ) + expect(document.documentElement.textContent).not.toContain( + childBodyScript, + ) + expect(document.documentElement.textContent).not.toContain( + childManifestScript, + ) + }) + }) +}) + +describe('data script rendering', () => { + test('data script renders content on server (SSR)', async () => { + const jsonLd = JSON.stringify({ + '@context': 'https://schema.org', + '@type': 'Article', + headline: 'Test Article', + }) + + const rootRoute = createRootRoute({ + scripts: () => [ + { + type: 'application/ld+json', + children: jsonLd, + }, + ], + component: () => { + return ( +
    +
    root
    + + +
    + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + }) + + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree: rootRoute.addChildren([indexRoute]), + isServer: true, + }) + + await router.load() + + const html = ReactDOMServer.renderToString( + , + ) + + expect(html).toContain('application/ld+json') + expect(html).toContain(jsonLd) + }) + + test('data script preserves content on client', async () => { + const jsonLd = JSON.stringify({ + '@context': 'https://schema.org', + '@type': 'WebSite', + name: 'Test', + }) + + const rootRoute = createRootRoute({ + scripts: () => [ + { + type: 'application/ld+json', + children: jsonLd, + }, + ], + component: () => { + return ( +
    +
    root
    + + +
    + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + }) + + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree: rootRoute.addChildren([indexRoute]), + }) + + await router.load() + + const { container } = await act(() => + render(), + ) + + const rootEl = container.querySelector('[data-testid="data-client-root"]') + expect(rootEl).not.toBeNull() + + const scriptEl = container.querySelector( + 'script[type="application/ld+json"]', + ) + expect(scriptEl).not.toBeNull() + expect(scriptEl!.innerHTML).toBe(jsonLd) + }) + + test('executable script is injected into document.head via useEffect on client', async () => { + const rootRoute = createRootRoute({ + scripts: () => [ + { + children: 'console.log("hello")', + }, + ], + component: () => { + return ( +
    +
    root
    + + +
    + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + }) + + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree: rootRoute.addChildren([indexRoute]), + }) + + await router.load() + + const { container } = await act(() => + render(), + ) + + const rootEl = container.querySelector('[data-testid="exec-root"]') + expect(rootEl).not.toBeNull() + + // Executable inline scripts are injected into document.head via useEffect, + // not rendered in the React tree on the client. + const headScript = document.head.querySelector( + 'script:not([type]):not([src])', + ) + expect(headScript).not.toBeNull() + expect(headScript!.textContent).toBe('console.log("hello")') + }) + + test('module script is injected into document.head via useEffect on client', async () => { + const rootRoute = createRootRoute({ + scripts: () => [ + { + type: 'module', + children: 'import { foo } from "./foo.js"', + }, + ], + component: () => { + return ( +
    +
    root
    + + +
    + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + }) + + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree: rootRoute.addChildren([indexRoute]), + }) + + await router.load() + + const { container } = await act(() => + render(), + ) + + const rootEl = container.querySelector('[data-testid="module-root"]') + expect(rootEl).not.toBeNull() + + // Module scripts are injected into document.head via useEffect, + // not rendered in the React tree on the client. + const moduleScript = document.head.querySelector('script[type="module"]') + expect(moduleScript).not.toBeNull() + expect(moduleScript!.textContent).toBe('import { foo } from "./foo.js"') + }) + + test('application/json data script preserves content', async () => { + const jsonData = JSON.stringify({ config: { theme: 'dark' } }) + + const rootRoute = createRootRoute({ + scripts: () => [ + { + type: 'application/json', + children: jsonData, + }, + ], + component: () => { + return ( +
    +
    root
    + + +
    + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + }) + + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree: rootRoute.addChildren([indexRoute]), + }) + + await router.load() + + const { container } = await act(() => + render(), + ) + + const rootEl = container.querySelector('[data-testid="json-root"]') + expect(rootEl).not.toBeNull() + + const scriptEl = container.querySelector('script[type="application/json"]') + expect(scriptEl).not.toBeNull() + expect(scriptEl!.innerHTML).toBe(jsonData) + }) + + test('data script does not duplicate into document.head', async () => { + const jsonLd = JSON.stringify({ + '@context': 'https://schema.org', + '@type': 'Organization', + name: 'Test Org', + }) + + const rootRoute = createRootRoute({ + scripts: () => [ + { + type: 'application/ld+json', + children: jsonLd, + }, + ], + component: () => { + return ( +
    +
    root
    + + +
    + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + }) + + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree: rootRoute.addChildren([indexRoute]), + }) + + await router.load() + + const { container } = await act(() => + render(), + ) + + const rootEl = container.querySelector('[data-testid="dup-root"]') + expect(rootEl).not.toBeNull() + + // Data scripts should NOT be duplicated into document.head by useEffect + const headScripts = document.head.querySelectorAll( + 'script[type="application/ld+json"]', + ) + expect(headScripts.length).toBe(0) + + // Should only exist once in the container + const containerScripts = container.querySelectorAll( + 'script[type="application/ld+json"]', + ) + expect(containerScripts.length).toBe(1) + expect(containerScripts[0]!.innerHTML).toBe(jsonLd) + }) + + test('empty string type is treated as executable, injected via useEffect on client', async () => { + const rootRoute = createRootRoute({ + scripts: () => [ + { + type: '', + children: 'console.log("empty type")', + }, + ], + component: () => { + return ( +
    +
    root
    + + +
    + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + }) + + const router = createRouter({ + history: createMemoryHistory({ + initialEntries: ['/'], + }), + routeTree: rootRoute.addChildren([indexRoute]), + }) + + await router.load() + + const { container } = await act(() => + render(), + ) + + const rootEl = container.querySelector('[data-testid="empty-type-root"]') + expect(rootEl).not.toBeNull() + + // Empty type = text/javascript per HTML spec. Executable scripts are + // injected into document.head via useEffect on the client. + const scriptEl = document.head.querySelector('script[type=""]') + expect(scriptEl).not.toBeNull() + expect(scriptEl!.textContent).toBe('console.log("empty type")') + }) }) diff --git a/packages/react-router/tests/ancestor-loader-child-pending-min.test.tsx b/packages/react-router/tests/ancestor-loader-child-pending-min.test.tsx new file mode 100644 index 0000000000..09945bb9af --- /dev/null +++ b/packages/react-router/tests/ancestor-loader-child-pending-min.test.tsx @@ -0,0 +1,157 @@ +import * as React from 'react' +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + Outlet, + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +test('a child fallback revealed after a fresh ancestor loader keeps its own pendingMinMs', async () => { + vi.useFakeTimers() + + const parentLoader = createControlledPromise() + const childLoader = createControlledPromise() + const rootRoute = createRootRoute({ + component: () => , + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Index
    , + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => parentLoader, + component: () => , + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    Child pending
    , + loader: () => childLoader, + component: () =>
    Child content
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + }) + + await router.load() + render() + expect(screen.getByText('Index')).toBeInTheDocument() + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/parent/child' }) + await vi.advanceTimersByTimeAsync(25) + }) + + expect(screen.queryByText('Child pending')).not.toBeInTheDocument() + + await act(async () => { + parentLoader.resolve() + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByText('Child pending')).toBeInTheDocument() + expect(screen.queryByText('Child content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(25) + childLoader.resolve() + await Promise.resolve() + }) + + // The minimum is measured from the child's first visible frame, not from + // the navigation start or the ancestor's completion. + await act(async () => { + await vi.advanceTimersByTimeAsync(74) + }) + expect(screen.getByText('Child pending')).toBeInTheDocument() + expect(screen.queryByText('Child content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + await navigation + }) + expect(screen.queryByText('Child pending')).not.toBeInTheDocument() + expect(screen.getByText('Child content')).toBeInTheDocument() +}) + +test('advancing from a parent loader to a parallel child loader does not restart pendingMs', async () => { + vi.useFakeTimers() + + const parentLoader = createControlledPromise() + const childLoader = createControlledPromise() + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Index
    , + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => parentLoader, + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + pendingMs: 1_000, + pendingMinMs: 0, + pendingComponent: () =>
    Child pending
    , + loader: () => childLoader, + component: () =>
    Child content
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + render() + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/parent/child' }) + await vi.advanceTimersByTimeAsync(900) + }) + expect(screen.queryByText('Child pending')).not.toBeInTheDocument() + + await act(async () => { + parentLoader.resolve() + await vi.advanceTimersByTimeAsync(99) + }) + expect(screen.queryByText('Child pending')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + }) + expect(screen.getByText('Child pending')).toBeInTheDocument() + + await act(async () => { + childLoader.resolve() + await navigation + }) + expect(screen.getByText('Child content')).toBeInTheDocument() +}) diff --git a/packages/react-router/tests/blocker.test.tsx b/packages/react-router/tests/blocker.test.tsx index 60d1e8a821..3ed3c3039e 100644 --- a/packages/react-router/tests/blocker.test.tsx +++ b/packages/react-router/tests/blocker.test.tsx @@ -1,5 +1,4 @@ import React from 'react' -import '@testing-library/jest-dom/vitest' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { cleanup, fireEvent, render, screen } from '@testing-library/react' import combinate from 'combinate' diff --git a/packages/react-router/tests/component-preload-retry-pending-min.test.tsx b/packages/react-router/tests/component-preload-retry-pending-min.test.tsx new file mode 100644 index 0000000000..dcdd94af67 --- /dev/null +++ b/packages/react-router/tests/component-preload-retry-pending-min.test.tsx @@ -0,0 +1,150 @@ +import * as React from 'react' +import { act } from 'react' +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { createControlledPromise } from '@tanstack/router-core' +import { + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + useRouter, +} from '../src' +import type { ErrorComponentProps } from '../src' + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + cleanup() +}) + +test('delayed component preload reveals pending UI', async () => { + const componentGate = createControlledPromise() + const Page = Object.assign(() =>
    Page content
    , { + preload: () => componentGate, + }) + const rootRoute = createRootRoute({}) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + pendingMs: 10, + pendingComponent: () =>
    Loading page...
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render() + + expect(await screen.findByText('Loading page...')).toBeInTheDocument() + componentGate.resolve() + expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(screen.queryByText('Loading page...')).not.toBeInTheDocument() +}) + +/** + * A component-only route can fail while preloading its code, then retry from + * its error UI through invalidate(). The retry is a fresh pending generation: + * its fallback must remain visible until the retried component preload is + * ready and pendingMinMs has elapsed. + */ +test('component preload retry remains pending through pendingMinMs', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const retryChunk = createControlledPromise() + let preloadAttempt = 0 + let retryInvalidation!: Promise + let retrySettled = false + + const Page = Object.assign( + () =>
    Page content
    , + { + preload: vi.fn(() => { + preloadAttempt++ + return preloadAttempt === 1 + ? Promise.reject(new Error('initial chunk request failed')) + : retryChunk + }), + }, + ) + + function RetryError({ reset }: ErrorComponentProps) { + const router = useRouter() + return ( + + ) + } + + const rootRoute = createRootRoute({}) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + errorComponent: RetryError, + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () => ( +
    Loading page...
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render() + + expect( + await screen.findByRole('button', { name: 'Retry chunk' }), + ).toBeInTheDocument() + expect(Page.preload).toHaveBeenCalledTimes(1) + + vi.useFakeTimers() + fireEvent.click(screen.getByRole('button', { name: 'Retry chunk' })) + + // Let pendingMs: 0 publish the retry lane. + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + }) + expect(Page.preload).toHaveBeenCalledTimes(2) + expect(screen.getByTestId('page-pending')).toBeInTheDocument() + expect( + screen.queryByRole('button', { name: 'Retry chunk' }), + ).not.toBeInTheDocument() + + await act(async () => { + retryChunk.resolve() + await Promise.resolve() + }) + + expect.soft(retrySettled).toBe(false) + expect.soft(screen.queryByTestId('page-pending')).toBeInTheDocument() + expect.soft(screen.queryByTestId('page-content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(99) + }) + expect(screen.getByTestId('page-pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + await retryInvalidation + }) + + expect(screen.getByTestId('page-content')).toBeInTheDocument() + expect(screen.queryByTestId('page-pending')).not.toBeInTheDocument() +}) diff --git a/packages/react-router/tests/component-preload-retry.test.tsx b/packages/react-router/tests/component-preload-retry.test.tsx new file mode 100644 index 0000000000..7abe959ebc --- /dev/null +++ b/packages/react-router/tests/component-preload-retry.test.tsx @@ -0,0 +1,208 @@ +import * as React from 'react' +import { afterEach, expect, test, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { createControlledPromise } from '@tanstack/router-core' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + lazyRouteComponent, + useRouter, +} from '../src' +import type { ErrorComponentProps } from '../src' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() + vi.unstubAllGlobals() + sessionStorage.clear() +}) + +test('a successful server component download is reused', async () => { + vi.stubGlobal('window', undefined) + const importer = vi.fn().mockResolvedValue({ default: () => null }) + const Page = lazyRouteComponent(importer) + + await Page.preload?.() + await Page.preload?.() + expect(importer).toHaveBeenCalledTimes(1) +}) + +test('concurrent component preloads share the import', async () => { + const componentImport = createControlledPromise<{ + default: () => null + }>() + const importer = vi.fn(() => componentImport) + const Page = lazyRouteComponent(importer) + + const first = Page.preload?.() + const second = Page.preload?.() + expect(importer).toHaveBeenCalledOnce() + + componentImport.resolve({ default: () => null }) + await Promise.all([first, second]) +}) + +test('a resolved client component preload is reused', async () => { + const importer = vi.fn().mockResolvedValue({ default: () => null }) + const Page = lazyRouteComponent(importer) + + await Page.preload?.() + expect(Page.preload).toBeUndefined() + expect(importer).toHaveBeenCalledTimes(1) +}) + +test('revisiting a resolved lazy component skips pending UI', async () => { + const componentImport = createControlledPromise<{ + default: () => React.JSX.Element + }>() + const repeatedImport = createControlledPromise<{ + default: () => React.JSX.Element + }>() + const importer = vi + .fn() + .mockImplementationOnce(() => componentImport) + .mockImplementationOnce(() => repeatedImport) + const Page = lazyRouteComponent(importer) + const PendingComponent = vi.fn(() => ( +
    Loading page
    + )) + const rootRoute = createRootRoute({ + component: () => ( + <> + Home link + Page link + + + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home content
    , + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 0, + defaultPendingComponent: PendingComponent, + }) + + render() + expect(await screen.findByText('Home content')).toBeInTheDocument() + + fireEvent.click(screen.getByRole('link', { name: 'Page link' })) + expect(await screen.findByTestId('pending-component')).toHaveTextContent( + 'Loading page', + ) + await act(() => { + componentImport.resolve({ default: () =>
    Page content
    }) + }) + expect(await screen.findByText('Page content')).toBeInTheDocument() + + fireEvent.click(screen.getByRole('link', { name: 'Home link' })) + expect(await screen.findByText('Home content')).toBeInTheDocument() + PendingComponent.mockClear() + fireEvent.click(screen.getByRole('link', { name: 'Page link' })) + await act(() => new Promise((resolve) => setTimeout(resolve, 10))) + + const revisitedContent = screen.queryByText('Page content') + const revisitedPending = screen.queryByTestId('pending-component') + + expect(revisitedContent).toBeInTheDocument() + expect(revisitedPending).not.toBeInTheDocument() + expect(PendingComponent).not.toHaveBeenCalled() + expect(importer).toHaveBeenCalledOnce() +}) + +test('a failed component download is retried from the route error UI', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const PageContent = () =>
    Page content
    + const importer = vi + .fn<() => Promise<{ default: typeof PageContent }>>() + .mockRejectedValueOnce(new Error('component download failed')) + .mockResolvedValue({ default: PageContent }) + const Page = lazyRouteComponent(importer) + + function RouteError({ reset }: ErrorComponentProps) { + const router = useRouter() + return ( + + ) + } + + const rootRoute = createRootRoute() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + errorComponent: RouteError, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render() + + const retryButton = await screen.findByRole('button', { name: 'Retry' }) + expect(importer).toHaveBeenCalledTimes(1) + + fireEvent.click(retryButton) + + expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect( + screen.queryByRole('button', { name: 'Retry' }), + ).not.toBeInTheDocument() +}) + +test('renders after retrying a module download that failed during preload', async () => { + const PageContent = () =>
    Page content
    + const importer = vi + .fn<() => Promise<{ default: typeof PageContent }>>() + .mockRejectedValueOnce( + new TypeError( + 'Failed to fetch dynamically imported module: /assets/page.js', + ), + ) + .mockResolvedValue({ default: PageContent }) + const Page = lazyRouteComponent(importer) + + await Page.preload?.() + + const rootRoute = createRootRoute() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render() + + expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) +}) diff --git a/packages/react-router/tests/createLazyRoute.test.tsx b/packages/react-router/tests/createLazyRoute.test.tsx index a6592b7128..a4fdffd738 100644 --- a/packages/react-router/tests/createLazyRoute.test.tsx +++ b/packages/react-router/tests/createLazyRoute.test.tsx @@ -100,4 +100,29 @@ describe('preload: matched routes', { timeout: 20000 }, () => { const lazyRoute = router.routesByPath['/heavy'] expect(lazyRoute.options.component).toBeDefined() }) + + it('should render a lazy route errorComponent when the loader throws on first load', async () => { + const history = createMemoryHistory({ initialEntries: ['/lazy-error'] }) + + const rootRoute = createRootRoute() + const lazyErrorRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/lazy-error', + loader: () => { + throw new Error('lazy error') + }, + }).lazy(() => import('./lazy/error').then((d) => d.Route('/lazy-error'))) + + const router = createRouter({ + routeTree: rootRoute.addChildren([lazyErrorRoute]), + history, + }) + + render() + + expect( + await screen.findByText('Lazy Error: lazy error'), + ).toBeInTheDocument() + expect(screen.queryByText('About route content')).not.toBeInTheDocument() + }) }) diff --git a/packages/react-router/tests/errorBoundary.test-d.tsx b/packages/react-router/tests/errorBoundary.test-d.tsx new file mode 100644 index 0000000000..ccb66929dd --- /dev/null +++ b/packages/react-router/tests/errorBoundary.test-d.tsx @@ -0,0 +1,30 @@ +import { expectTypeOf, test } from 'vitest' +import { createRootRoute, createRouter } from '../src' +import type { ErrorComponentProps } from '../src' + +test('only boundary errors default to unknown', () => { + expectTypeOf().toEqualTypeOf() + expectTypeOf['error']>().toEqualTypeOf() + const routeTree = createRootRoute({ + errorComponent: ({ error }) => { + expectTypeOf(error).toEqualTypeOf() + return null + }, + onCatch: (error) => { + expectTypeOf(error).toEqualTypeOf() + }, + onError: (error) => { + expectTypeOf(error).toBeAny() + }, + }) + createRouter({ + routeTree, + defaultErrorComponent: ({ error }) => { + expectTypeOf(error).toEqualTypeOf() + return null + }, + defaultOnCatch: (error) => { + expectTypeOf(error).toEqualTypeOf() + }, + }) +}) diff --git a/packages/react-router/tests/errorComponent.test.tsx b/packages/react-router/tests/errorComponent.test.tsx index 2c0062a9ac..441610a2e7 100644 --- a/packages/react-router/tests/errorComponent.test.tsx +++ b/packages/react-router/tests/errorComponent.test.tsx @@ -1,18 +1,36 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' -import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { + CatchBoundary, + ErrorComponent, + HeadContent, Link, + Outlet, RouterProvider, + Scripts, createBrowserHistory, + createControlledPromise, + createLazyRoute, + createMemoryHistory, createRootRoute, createRoute, createRouter, + notFound, } from '../src' +import { + RouterServer, + createRequestHandler, + renderRouterToString, +} from '../src/ssr/server' import type { ErrorComponentProps, RouterHistory } from '../src' function MyErrorComponent(props: ErrorComponentProps) { - return
    Error: {props.error.message}
    + return
    Error: {getErrorMessage(props.error)}
    +} + +function getErrorMessage(error: unknown) { + return error instanceof Error ? error.message : String(error) } async function asyncToThrowFn() { @@ -24,6 +42,10 @@ function throwFn() { throw new Error('error thrown') } +function primitiveThrowFn() { + throw 'primitive error thrown' +} + let history: RouterHistory beforeEach(() => { @@ -38,48 +60,197 @@ afterEach(() => { cleanup() }) -describe.each([{ preload: false }, { preload: 'intent' }] as const)( - 'errorComponent is rendered when the preload=$preload', - (options) => { - describe.each([true, false])('with async=%s', (isAsync) => { - const throwableFn = isAsync ? asyncToThrowFn : throwFn +describe.each([true, false])( + 'with lazy errorComponent=%s', + (isUsingLazyError) => { + describe.each([{ preload: false }, { preload: 'intent' }] as const)( + 'errorComponent is rendered when the preload=$preload', + (options) => { + describe.each([true, false])('with async=%s', (isAsync) => { + const throwableFn = isAsync ? asyncToThrowFn : throwFn - const callers = [ - { caller: 'beforeLoad', testFn: throwableFn }, - { caller: 'loader', testFn: throwableFn }, - ] + const callers = [ + { caller: 'beforeLoad', testFn: throwableFn }, + { caller: 'loader', testFn: throwableFn }, + ] - test.each(callers)( - 'an Error is thrown on navigate in the route $caller function', - async ({ caller, testFn }) => { + test.each(callers)( + 'an Error is thrown on navigate in the route $caller function', + async ({ caller, testFn }) => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: function Home() { + return ( +
    + link to about +
    + ) + }, + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + beforeLoad: caller === 'beforeLoad' ? testFn : undefined, + loader: caller === 'loader' ? testFn : undefined, + component: function Home() { + return
    About route content
    + }, + errorComponent: isUsingLazyError ? undefined : MyErrorComponent, + }) + + if (isUsingLazyError) { + aboutRoute.lazy(() => + Promise.resolve( + createLazyRoute('/about')({ + errorComponent: MyErrorComponent, + }), + ), + ) + } + + const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]) + + const router = createRouter({ + routeTree, + defaultPreload: options.preload, + history, + }) + + render() + + const linkToAbout = await screen.findByRole('link', { + name: 'link to about', + }) + + expect(linkToAbout).toBeInTheDocument() + fireEvent.mouseOver(linkToAbout) + fireEvent.focus(linkToAbout) + fireEvent.click(linkToAbout) + + const errorComponent = await screen.findByText( + `Error: error thrown`, + undefined, + { timeout: 1500 }, + ) + await expect( + screen.findByText('About route content'), + ).rejects.toThrow() + expect(errorComponent).toBeInTheDocument() + }, + ) + + test.each(callers)( + 'an Error is thrown on first load in the route $caller function', + async ({ caller, testFn }) => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + beforeLoad: caller === 'beforeLoad' ? testFn : undefined, + loader: caller === 'loader' ? testFn : undefined, + component: function Home() { + return
    Index route content
    + }, + errorComponent: isUsingLazyError ? undefined : MyErrorComponent, + }) + + if (isUsingLazyError) { + indexRoute.lazy(() => + Promise.resolve( + createLazyRoute('/')({ + errorComponent: MyErrorComponent, + }), + ), + ) + } + + const routeTree = rootRoute.addChildren([indexRoute]) + + const router = createRouter({ + routeTree, + defaultPreload: options.preload, + history, + }) + + render() + + const errorComponent = await screen.findByText( + `Error: error thrown`, + undefined, + { timeout: 750 }, + ) + await expect( + screen.findByText('Index route content'), + ).rejects.toThrow() + expect(errorComponent).toBeInTheDocument() + }, + ) + }) + }, + ) + + describe('stale route errors do not leak after navigation', () => { + test.each([ + { + caller: 'loader' as const, + routeOptions: { + loader: throwFn, + }, + }, + { + caller: 'render' as const, + routeOptions: { + component: function RenderErrorComponent() { + throwFn() + }, + }, + }, + ])( + 'navigating away from a $caller error does not call the next route errorComponent', + async ({ routeOptions }) => { const rootRoute = createRootRoute() + const indexErrorComponent = vi.fn(() =>
    Index error
    ) + const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', component: function Home() { return (
    +
    Index route content
    link to about
    ) }, + errorComponent: indexErrorComponent, }) + const aboutRoute = createRoute({ getParentRoute: () => rootRoute, path: '/about', - beforeLoad: caller === 'beforeLoad' ? testFn : undefined, - loader: caller === 'loader' ? testFn : undefined, - component: function Home() { + component: function About() { return
    About route content
    }, - errorComponent: MyErrorComponent, + errorComponent: isUsingLazyError ? undefined : MyErrorComponent, + ...routeOptions, }) + if (isUsingLazyError) { + aboutRoute.lazy(() => + Promise.resolve( + createLazyRoute('/about')({ + errorComponent: MyErrorComponent, + }), + ), + ) + } + const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]) const router = createRouter({ routeTree, - defaultPreload: options.preload, history, }) @@ -89,59 +260,815 @@ describe.each([{ preload: false }, { preload: 'intent' }] as const)( name: 'link to about', }) - expect(linkToAbout).toBeInTheDocument() - fireEvent.mouseOver(linkToAbout) - fireEvent.focus(linkToAbout) - fireEvent.click(linkToAbout) + await act(() => fireEvent.click(linkToAbout)) - const errorComponent = await screen.findByText( - `Error: error thrown`, - undefined, - { timeout: 1500 }, - ) - await expect( - screen.findByText('About route content'), - ).rejects.toThrow() - expect(errorComponent).toBeInTheDocument() - }, - ) + expect( + await screen.findByText('Error: error thrown', undefined, { + timeout: 1500, + }), + ).toBeInTheDocument() - test.each(callers)( - 'an Error is thrown on first load in the route $caller function', - async ({ caller, testFn }) => { - const rootRoute = createRootRoute() - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - beforeLoad: caller === 'beforeLoad' ? testFn : undefined, - loader: caller === 'loader' ? testFn : undefined, - component: function Home() { - return
    Index route content
    - }, - errorComponent: MyErrorComponent, - }) + await act(() => router.navigate({ to: '/' })) - const routeTree = rootRoute.addChildren([indexRoute]) - - const router = createRouter({ - routeTree, - defaultPreload: options.preload, - history, - }) - - render() - - const errorComponent = await screen.findByText( - `Error: error thrown`, - undefined, - { timeout: 750 }, - ) - await expect( - screen.findByText('Index route content'), - ).rejects.toThrow() - expect(errorComponent).toBeInTheDocument() + expect( + await screen.findByText('Index route content'), + ).toBeInTheDocument() + expect(indexErrorComponent).not.toHaveBeenCalled() }, ) }) }, ) + +test('global catch boundary resets when a background child generation recovers', async () => { + const refresh = createControlledPromise() + let loaderCalls = 0 + const rootRoute = createRootRoute({ component: Outlet }) + const childRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: { + staleReloadMode: 'background', + handler: () => (++loaderCalls === 1 ? 1 : refresh), + }, + component: () => { + const revision = childRoute.useLoaderData() + if (revision === 1) { + throw new Error('stale child render failed') + } + return
    Recovered child revision {revision}
    + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history, + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + render() + expect( + await screen.findByText('stale child render failed'), + ).toBeInTheDocument() + + const invalidation = router.invalidate() + await vi.waitFor(() => expect(loaderCalls).toBe(2)) + expect(screen.getByText('stale child render failed')).toBeInTheDocument() + expect(screen.queryByText(/Recovered child revision/)).not.toBeInTheDocument() + refresh.resolve(2) + await invalidation + + expect( + await screen.findByText('Recovered child revision 2'), + ).toBeInTheDocument() + expect( + screen.queryByText('stale child render failed'), + ).not.toBeInTheDocument() +}) + +test('ancestor route errorComponent resets when a background child generation recovers', async () => { + const refresh = createControlledPromise() + let loaderCalls = 0 + const rootRoute = createRootRoute({ + component: Outlet, + errorComponent: ({ error }) => ( +
    Ancestor error: {getErrorMessage(error)}
    + ), + }) + const childRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: { + staleReloadMode: 'background', + handler: () => (++loaderCalls === 1 ? 1 : refresh), + }, + component: () => { + const revision = childRoute.useLoaderData() + if (revision === 1) { + throw new Error('stale child render failed') + } + return
    Recovered child revision {revision}
    + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history, + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + let invalidation: Promise | undefined + try { + render() + expect( + await screen.findByText('Ancestor error: stale child render failed'), + ).toBeInTheDocument() + + invalidation = router.invalidate({ + filter: (match) => match.routeId === childRoute.id, + }) + await vi.waitFor(() => expect(loaderCalls).toBe(2)) + expect( + screen.getByText('Ancestor error: stale child render failed'), + ).toBeInTheDocument() + refresh.resolve(2) + await invalidation + + expect( + await screen.findByText('Recovered child revision 2'), + ).toBeInTheDocument() + } finally { + refresh.resolve(2) + if (invalidation) { + await Promise.allSettled([invalidation]) + } + } +}) + +test('errorComponent receives primitive errors thrown from beforeLoad', async () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: function Home() { + return ( +
    + link to about +
    + ) + }, + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + beforeLoad: primitiveThrowFn, + component: function About() { + return
    About route content
    + }, + errorComponent: ({ error }) =>
    Error: {String(error)}
    , + }) + + const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]) + + const router = createRouter({ + routeTree, + history, + }) + + render() + + const linkToAbout = await screen.findByRole('link', { + name: 'link to about', + }) + + await act(() => fireEvent.click(linkToAbout)) + + expect( + await screen.findByText('Error: primitive error thrown', undefined, { + timeout: 750, + }), + ).toBeInTheDocument() + expect(screen.queryByText('About route content')).not.toBeInTheDocument() +}) + +test.each([ + ['false', false], + ['zero', 0], + ['negative zero', -0], + ['bigint zero', 0n], + ['empty string', ''], + ['null', null], + ['undefined', undefined], + ['NaN', NaN], +] as const)('CatchBoundary renders falsy thrown value %s', (_, thrown) => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const onCatch = vi.fn() + + function ThrowFalsy(): never { + throw thrown + } + + render( + 0} + errorComponent={({ error }) => ( +
    {Object.is(error, thrown) ? 'Caught value' : 'Wrong value'}
    + )} + onCatch={onCatch} + > + +
    , + ) + + expect(screen.getByText('Caught value')).toBeInTheDocument() + expect(screen.queryByText('Wrong value')).not.toBeInTheDocument() + expect(onCatch).toHaveBeenCalledWith(thrown, expect.anything()) +}) + +test.each([ + ['null', null], + ['undefined', undefined], +] as const)('default error UI renders thrown %s', async (_, thrown) => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + function ThrowFalsy(): never { + throw thrown + } + + const rootRoute = createRootRoute({ component: ThrowFalsy }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + + expect(await screen.findByText('Something went wrong!')).toBeInTheDocument() +}) + +test.each(['beforeLoad', 'loader'] as const)( + 'a Promise synchronously thrown from %s renders the route error UI', + async (hook) => { + const thrown = Promise.resolve('not route data') + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + beforeLoad: + hook === 'beforeLoad' + ? () => { + throw thrown + } + : undefined, + loader: + hook === 'loader' + ? () => { + throw thrown + } + : undefined, + errorComponent: ({ error }) => ( +
    + {error instanceof Error && error.cause === thrown + ? 'Promise route error' + : 'Wrong route error'} +
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + + expect(await screen.findByText('Promise route error')).toBeInTheDocument() + expect(screen.queryByText('Wrong route error')).not.toBeInTheDocument() + }, +) + +test('SSR errorComponent receives primitive errors thrown from beforeLoad', async () => { + const rootRoute = createRootRoute({ + shellComponent: function RootDocument({ children }) { + return ( + + + {children} + + + + ) + }, + component: function Root() { + return + }, + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + beforeLoad: primitiveThrowFn, + component: function About() { + return
    About route content
    + }, + errorComponent: ({ error }) =>
    Error: {String(error)}
    , + }) + + const handler = createRequestHandler({ + request: new Request('http://localhost/about'), + createRouter: () => + createRouter({ + routeTree: rootRoute.addChildren([aboutRoute]), + isServer: true, + }), + }) + + const response = await handler(({ router, responseHeaders }) => + renderRouterToString({ + router, + responseHeaders, + children: , + }), + ) + + expect(response.status).toBe(500) + const html = await response.text() + expect(html).toContain('Error:') + expect(html).toContain('primitive error thrown') +}) + +test('a later fresh ancestor loader failure owns the reachable boundary', async () => { + const parentStarted = createControlledPromise() + const childStarted = createControlledPromise() + const parentGate = createControlledPromise() + const childGate = createControlledPromise() + const childSettled = createControlledPromise() + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: Outlet, + loader: async () => { + parentStarted.resolve() + await parentGate + throw new Error('later parent failure') + }, + errorComponent: () =>
    Parent error boundary
    , + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + childStarted.resolve() + await childGate + childSettled.resolve() + throw new Error('first child failure') + }, + errorComponent: () =>
    Child error boundary
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + render() + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/parent/child' }) + await Promise.all([parentStarted, childStarted]) + }) + await act(async () => { + childGate.resolve() + await childSettled + parentGate.resolve() + await navigation + }) + + expect(screen.getByText('Parent error boundary')).toBeInTheDocument() + expect(screen.queryByText('Child error boundary')).not.toBeInTheDocument() +}) + +test('a fresh ancestor failure waits for lazy options before rendering its error', async () => { + const parentStarted = createControlledPromise() + const childStarted = createControlledPromise() + const parentGate = createControlledPromise() + const childGate = createControlledPromise() + const childSettled = createControlledPromise() + const lazyParentOptions = createLazyRoute('/parent')({ + component: () => ( + <> +
    Lazy parent shell
    + + + ), + }) + const parentChunk = createControlledPromise() + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: async () => { + parentStarted.resolve() + await parentGate + throw new Error('later parent failure') + }, + errorComponent: () =>
    Parent error boundary
    , + }).lazy(() => parentChunk) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + childStarted.resolve() + await childGate + childSettled.resolve() + throw new Error('first child failure') + }, + errorComponent: () =>
    Child error boundary
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + render() + + let navigation: Promise | undefined + try { + await act(async () => { + navigation = router.navigate({ to: '/parent/child' }) + await Promise.all([parentStarted, childStarted]) + }) + await act(async () => { + childGate.resolve() + await childSettled + parentGate.resolve() + await Promise.resolve() + }) + + expect(parentChunk.status).toBe('pending') + expect(screen.getByText('Home')).toBeInTheDocument() + expect(screen.queryByText('Parent error boundary')).not.toBeInTheDocument() + expect(screen.queryByText('Child error boundary')).not.toBeInTheDocument() + expect(screen.queryByText('Lazy parent shell')).not.toBeInTheDocument() + } finally { + await act(async () => { + childGate.resolve() + parentGate.resolve() + parentChunk.resolve(lazyParentOptions) + await navigation + }) + } + + expect(screen.getByText('Parent error boundary')).toBeInTheDocument() + expect(screen.queryByText('Lazy parent shell')).not.toBeInTheDocument() + expect(screen.queryByText('Child error boundary')).not.toBeInTheDocument() +}) + +test('SSR renders a later fresh ancestor loader failure', async () => { + const parentStarted = createControlledPromise() + const childStarted = createControlledPromise() + const parentGate = createControlledPromise() + const childGate = createControlledPromise() + const childSettled = createControlledPromise() + const rootRoute = createRootRoute({ + shellComponent: function RootDocument({ children }) { + return ( + + + {children} + + + + ) + }, + component: Outlet, + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: Outlet, + loader: async () => { + parentStarted.resolve() + await parentGate + throw new Error('later parent failure') + }, + errorComponent: () =>
    Parent error boundary
    , + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + childStarted.resolve() + await childGate + childSettled.resolve() + throw new Error('first child failure') + }, + errorComponent: () =>
    Child error boundary
    , + }) + const handler = createRequestHandler({ + request: new Request('http://localhost/parent/child'), + createRouter: () => + createRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + isServer: true, + }), + }) + + const responsePromise = handler(({ router, responseHeaders }) => + renderRouterToString({ + router, + responseHeaders, + children: , + }), + ) + await Promise.all([parentStarted, childStarted]) + childGate.resolve() + await childSettled + parentGate.resolve() + const response = await responsePromise + const html = await response.text() + + expect(response.status).toBe(500) + expect(html).toContain('Parent error boundary') + expect(html).not.toContain('Child error boundary') +}) + +// https://github.com/TanStack/router/issues/4684 +test('#4684: SSR renders head content when beforeLoad throws', async () => { + const rootRoute = createRootRoute({ + head: () => ({ + links: [{ rel: 'stylesheet', href: '/global.css' }], + }), + shellComponent: function RootDocument({ children }) { + return ( + + + + + + {children} + + + + ) + }, + component: Outlet, + }) + const failingRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/fail', + beforeLoad: () => { + throw new Error('beforeLoad failed') + }, + head: ({ match }) => ({ + meta: [{ title: match.error ? 'Error title' : 'Success title' }], + }), + component: function FailingRoute() { + return
    Route content
    + }, + errorComponent: ({ error }) => ( +
    Error UI: {getErrorMessage(error)}
    + ), + }) + + const handler = createRequestHandler({ + request: new Request('http://localhost/fail'), + createRouter: () => + createRouter({ + routeTree: rootRoute.addChildren([failingRoute]), + isServer: true, + }), + }) + + const response = await handler(({ router, responseHeaders }) => + renderRouterToString({ + router, + responseHeaders, + children: , + }), + ) + + expect(response.status).toBe(500) + const html = await response.text() + const serverDocument = new DOMParser().parseFromString(html, 'text/html') + + expect(serverDocument.body.textContent).toContain( + 'Error UI: beforeLoad failed', + ) + expect(serverDocument.head.querySelector('title')?.textContent).toBe( + 'Error title', + ) + expect( + serverDocument.head.querySelector( + 'link[rel="stylesheet"][href="/global.css"]', + ), + ).not.toBeNull() +}) + +describe('notFoundComponent is rendered when an error is thrown in params.parse', () => { + test('displays notFoundComponent when error is thrown in params.parse', async () => { + const history = createMemoryHistory({ initialEntries: ['/'] }) + const rootLoader = vi.fn(async () => { + await new Promise((resolve) => setTimeout(resolve, 1)) + return { ok: true } + }) + + const rootRoute = createRootRoute({ + component: function Root() { + return + }, + notFoundComponent: function NotFound() { + return
    No pizza
    + }, + pendingComponent: function Pending() { + return
    Loading...
    + }, + loader: rootLoader, + shouldReload: true, + pendingMs: 0, + pendingMinMs: 100, + wrapInSuspense: true, + }) + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: function Home() { + return ( +
    + + link to rotten pizza + +
    + ) + }, + }) + + const restaurantRoute = createRoute({ + getParentRoute: () => rootRoute, + id: 'restaurant', + component: function Restaurant() { + return + }, + }) + + const pizzaRoute = createRoute({ + getParentRoute: () => restaurantRoute, + path: '/pizza/$pizzaType', + component: function Pizza() { + return
    Pizza
    + }, + params: { + parse: (p) => { + if (p.pizzaType === 'rotten') { + throw new Error('404 No rotten pizzas') + } + return { pizzaType: p.pizzaType } + }, + stringify: (p) => ({ pizzaType: p.pizzaType }), + }, + onError: () => { + throw notFound() + }, + }) + + const routeTree = rootRoute.addChildren([ + indexRoute, + restaurantRoute.addChildren([pizzaRoute]), + ]) + + const router = createRouter({ + routeTree, + history, + }) + + render() + + const linkToRottenPizza = await screen.findByRole('link', { + name: 'link to rotten pizza', + }) + + expect(rootLoader).toHaveBeenCalledTimes(1) + expect(linkToRottenPizza).toBeInTheDocument() + await act(() => fireEvent.mouseOver(linkToRottenPizza)) + await act(() => fireEvent.click(linkToRottenPizza)) + + const notFoundComponent = await screen.findByText('No pizza', undefined, { + timeout: 750, + }) + expect(rootLoader).toHaveBeenCalledTimes(2) + expect(notFoundComponent).toBeInTheDocument() + }) +}) + +test.each([ + [new Error('Error message'), 'Error message'], + [{ message: 'Serialized message' }, 'Serialized message'], + [{ message: 0 }, undefined], + ['Thrown string', undefined], + [false, undefined], + [0, undefined], + [0n, undefined], + ['', undefined], + [null, undefined], + [undefined, undefined], + [NaN, undefined], + [Symbol('error'), undefined], + [Object.create(null), undefined], +])('default error details render %s', (error, expected) => { + const { container } = render() + + expect(screen.getByText('Something went wrong!')).toBeInTheDocument() + expect(container.querySelector('code')?.textContent).toBe(expected) +}) + +test.each([false, 0, -0, 0n, '', null, undefined, NaN])( + 'CatchBoundary resets after throwing %s', + (thrown) => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + let shouldThrow = true + let resetKey = 0 + const onCatch = vi.fn() + + function Child() { + if (shouldThrow) { + throw thrown + } + return
    Recovered child
    + } + + function App() { + return ( + resetKey} + onCatch={onCatch} + errorComponent={({ reset }) => } + > + + + ) + } + + const { rerender } = render() + shouldThrow = false + rerender() + expect(screen.queryByText('Recovered child')).not.toBeInTheDocument() + fireEvent.click(screen.getByText('Reset')) + expect(screen.getByText('Recovered child')).toBeInTheDocument() + + shouldThrow = true + rerender() + shouldThrow = false + resetKey++ + rerender() + expect(screen.getByText('Recovered child')).toBeInTheDocument() + expect(onCatch).toHaveBeenCalledTimes(2) + }, +) + +test('CatchBoundary tracks reset keys while healthy', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + let resetKey: unknown + let shouldThrow = false + + function Child() { + if (shouldThrow) { + throw null + } + return
    Healthy child
    + } + + function App() { + return ( + resetKey} + errorComponent={() =>
    Caught error
    } + > + +
    + ) + } + + const { rerender } = render() + expect(screen.getByText('Healthy child')).toBeInTheDocument() + + resetKey = {} + rerender() + expect(screen.getByText('Healthy child')).toBeInTheDocument() + + shouldThrow = true + rerender() + expect(screen.getByText('Caught error')).toBeInTheDocument() + + shouldThrow = false + rerender() + expect(screen.getByText('Caught error')).toBeInTheDocument() + + resetKey = undefined + rerender() + expect(screen.getByText('Healthy child')).toBeInTheDocument() + + shouldThrow = true + rerender() + expect(screen.getByText('Caught error')).toBeInTheDocument() +}) diff --git a/packages/react-router/tests/fileRoute.test-d.tsx b/packages/react-router/tests/fileRoute.test-d.tsx index c97d932325..cc0e7b265a 100644 --- a/packages/react-router/tests/fileRoute.test-d.tsx +++ b/packages/react-router/tests/fileRoute.test-d.tsx @@ -17,6 +17,31 @@ const postRoute = createFileRoute('/_postLayout/posts/$postId_')() const protectedRoute = createFileRoute('/(auth)/protected')() +const attachmentRoute = createFileRoute( + '/projects/$observationDocId/attachments/$driveId/$type/$variant/$name', +)({ + params: { + parse: ({ driveId, type, variant, name, ...rest }) => { + const blobId = + type === 'audio' + ? { + type: 'audio' as const, + variant: 'original' as const, + driveId, + name, + } + : { + type: 'photo' as const, + variant: variant as 'original' | 'preview' | 'thumbnail', + driveId, + name, + } + + return { ...rest, ...blobId } + }, + }, +}) + declare module '@tanstack/router-core' { interface FileRoutesByPath { '/': { @@ -68,6 +93,13 @@ declare module '@tanstack/router-core' { fullPath: '/posts/$postId' path: '/$postId_' } + '/projects/$observationDocId/attachments/$driveId/$type/$variant/$name': { + preLoaderRoute: typeof attachmentRoute + parentRoute: typeof rootRoute + id: '/projects/$observationDocId/attachments/$driveId/$type/$variant/$name' + fullPath: '/projects/$observationDocId/attachments/$driveId/$type/$variant/$name' + path: '/projects/$observationDocId/attachments/$driveId/$type/$variant/$name' + } } } @@ -100,3 +132,31 @@ test('when creating a folder group', () => { expectTypeOf<'(auth)/protected'>(protectedRoute.path) expectTypeOf<'/protected'>(protectedRoute.id) }) + +test('when file route params.parse returns a discriminated union', () => { + expectTypeOf(attachmentRoute.types.params).toEqualTypeOf< + | { + observationDocId: string + driveId: string + type: 'audio' + variant: 'original' + name: string + } + | { + observationDocId: string + driveId: string + type: 'photo' + variant: 'original' | 'preview' | 'thumbnail' + name: string + } + >() +}) + +test('when file route params.parse drops a path param', () => { + createFileRoute('/invoices/$invoiceId')({ + params: { + // @ts-expect-error parsed params must keep path param keys + parse: () => ({}), + }, + }) +}) diff --git a/packages/react-router/tests/fileRoute.test.ts b/packages/react-router/tests/fileRoute.test.ts index 2a8e225371..9f3fa290d3 100644 --- a/packages/react-router/tests/fileRoute.test.ts +++ b/packages/react-router/tests/fileRoute.test.ts @@ -1,5 +1,5 @@ /* eslint-disable */ -import { describe, it, expect } from 'vitest' +import { afterEach, describe, it, expect, vi } from 'vitest' import { getRouteApi, createFileRoute, @@ -7,8 +7,33 @@ import { createLazyFileRoute, LazyRoute, AnyRoute, + FileRoute, } from '../src' +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('createFileRoute', () => { + it('creates a non-root route without a deprecation warning', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + // @ts-expect-error + const route = createFileRoute('')({}) + + expect(route.isRoot).toBe(false) + expect(warn).not.toHaveBeenCalled() + }) + + it('keeps the deprecation warning for direct FileRoute usage', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + // @ts-expect-error + const route = new FileRoute('').createRoute({}) + + expect(route.isRoot).toBe(false) + expect(warn).toHaveBeenCalledOnce() + }) +}) + describe('createFileRoute has the same hooks as getRouteApi', () => { const routeApi = getRouteApi('foo') const hookNames = Object.keys(routeApi).filter((key) => key.startsWith('use')) diff --git a/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx b/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx new file mode 100644 index 0000000000..57d99c8af5 --- /dev/null +++ b/packages/react-router/tests/hydration-capped-boundary-pending.test.tsx @@ -0,0 +1,264 @@ +import * as React from 'react' +import { act } from '@testing-library/react' +import { hydrateRoot } from 'react-dom/client' +import { renderToString } from 'react-dom/server' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id' +import { hydrate } from '../src/ssr/client' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, + notFound, +} from '../src' +import type { TsrSsrGlobal } from '../src/ssr/client' + +declare global { + interface Window { + $_TSR?: TsrSsrGlobal + } +} + +const testCleanups: Array<() => void | Promise> = [] + +afterEach(async () => { + while (testCleanups.length) { + await testCleanups.pop()!() + } + vi.restoreAllMocks() + window.$_TSR = undefined + document.body.innerHTML = '' +}) + +describe('hydrating a server-capped boundary lane', () => { + test('recovers a /404 payload against a missing browser URL', async () => { + function MissingPage() { + return
    Missing page
    + } + + const makeRouteTree = () => { + const rootRoute = createRootRoute({ + component: Outlet, + notFoundComponent: MissingPage, + }) + const notFoundRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/404', + component: MissingPage, + }) + return rootRoute.addChildren([notFoundRoute]) + } + + const serverRouter = createRouter({ + routeTree: makeRouteTree(), + history: createMemoryHistory({ initialEntries: ['/404'] }), + }) + serverRouter.isServer = true + await serverRouter.load() + const serverMatches = serverRouter.stores.matches.get() + const serverHtml = renderToString() + expect(serverHtml).toContain('Missing page') + + const clientRouter = createRouter({ + routeTree: makeRouteTree(), + history: createMemoryHistory({ initialEntries: ['/missing'] }), + }) + window.$_TSR = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: serverMatches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + u: match.updatedAt, + s: match.status, + l: match.loaderData, + e: match.error, + ssr: match.ssr, + ...(match._notFound ? { g: true } : {}), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(clientRouter) + + const container = document.createElement('div') + container.innerHTML = serverHtml + document.body.appendChild(container) + let root!: ReturnType + await act(async () => { + root = hydrateRoot(container, , { + onRecoverableError: () => {}, + }) + testCleanups.push(async () => { + await act(() => root.unmount()) + }) + await Promise.resolve() + }) + + expect(container).toHaveTextContent('Missing page') + expect(clientRouter.state.resolvedLocation?.pathname).toBe('/missing') + expect(clientRouter.state.matches).toHaveLength(1) + expect(clientRouter.state.matches[0]).toMatchObject({ _notFound: true }) + }) + + test.each([ + ['error', 'parent'], + ['notFound', 'parent'], + ['error', 'root'], + ['notFound', 'root'], + ] as const)( + 'keeps the server-rendered %s %s boundary visible', + async (outcome, boundary) => { + const childLoader = vi.fn(() => 'child data') + const boundaryCommits = vi.fn() + + function BoundaryError() { + React.useEffect(() => { + boundaryCommits() + }, []) + return
    Boundary error
    + } + + function BoundaryNotFound() { + React.useEffect(() => { + boundaryCommits() + }, []) + return
    Boundary not found
    + } + + const makeRouteTree = () => { + const boundaryOptions = { + beforeLoad: () => { + throw outcome === 'notFound' + ? notFound() + : new Error('server route failure') + }, + pendingComponent: () => ( +
    Boundary pending
    + ), + errorComponent: BoundaryError, + notFoundComponent: BoundaryNotFound, + } + const rootRoute = createRootRoute({ + component: Outlet, + ...(boundary === 'root' ? boundaryOptions : {}), + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: Outlet, + ...(boundary === 'parent' ? boundaryOptions : {}), + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + component: () =>
    Child
    , + }) + return { + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + } + } + + const serverRouter = createRouter({ + ...makeRouteTree(), + history: createMemoryHistory({ + initialEntries: ['/parent/child'], + }), + }) + serverRouter.isServer = true + await serverRouter.load() + + const serverMatches = serverRouter.stores.matches.get() + expect(serverMatches).toHaveLength(3) + const serverBoundary = serverMatches[boundary === 'root' ? 0 : 1]! + if (outcome === 'notFound' && boundary === 'root') { + expect(serverBoundary).toMatchObject({ + status: 'success', + _notFound: true, + }) + } else { + expect(serverBoundary.status).toBe(outcome) + } + const serverHtml = renderToString( + , + ) + expect(serverHtml).toContain( + outcome === 'notFound' ? 'Boundary not found' : 'Boundary error', + ) + expect(boundaryCommits).not.toHaveBeenCalled() + + const clientRouter = createRouter({ + ...makeRouteTree(), + history: createMemoryHistory({ + initialEntries: ['/parent/child'], + }), + }) + + window.$_TSR = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: serverMatches + .slice(0, boundary === 'root' ? 1 : 2) + .map((match) => ({ + i: dehydrateSsrMatchId(match.id), + u: match.updatedAt, + s: match.status, + l: match.loaderData, + e: match.error, + ssr: match.ssr, + ...(match._notFound ? { g: true } : {}), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(clientRouter) + + const container = document.createElement('div') + container.innerHTML = serverHtml + document.body.appendChild(container) + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + let root!: ReturnType + await act(async () => { + root = hydrateRoot(container, ) + testCleanups.push(async () => { + await act(() => root.unmount()) + }) + await Promise.resolve() + }) + + // A shorter dehydrated lane means SPA mode only for an actual shell. + // Here it is shorter because the server already rendered a terminal + // boundary, so hydration must not replace that boundary with pending UI. + expect(boundaryCommits).toHaveBeenCalledTimes(1) + expect(container).toHaveTextContent( + outcome === 'notFound' ? 'Boundary not found' : 'Boundary error', + ) + expect(container).not.toHaveTextContent('Boundary pending') + expect(consoleError.mock.calls.flat().join(' ')).not.toMatch( + /hydration|did not match/i, + ) + expect(childLoader).not.toHaveBeenCalled() + }, + ) +}) diff --git a/packages/react-router/tests/hydration-terminal-lane.test.tsx b/packages/react-router/tests/hydration-terminal-lane.test.tsx new file mode 100644 index 0000000000..c53dc62ae3 --- /dev/null +++ b/packages/react-router/tests/hydration-terminal-lane.test.tsx @@ -0,0 +1,141 @@ +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { hydrate } from '@tanstack/router-core/ssr/client' +import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' +import type { AnyRouteMatch } from '@tanstack/router-core' +import type { TsrSsrGlobal } from '@tanstack/router-core/ssr/client' + +function bootstrap( + matches: Array<{ + match: AnyRouteMatch + status: AnyRouteMatch['status'] + ssr: AnyRouteMatch['ssr'] + data?: unknown + error?: unknown + notFound?: boolean + }>, +): void { + window.$_TSR = { + router: { + manifest: undefined, + matches: matches.map(({ match, status, ssr, data, error, notFound }) => ({ + i: dehydrateSsrMatchId(match.id), + l: data, + e: error, + s: status, + ssr, + u: Date.now(), + ...(notFound ? { g: true } : {}), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + } as TsrSsrGlobal +} + +afterEach(() => { + cleanup() + vi.useRealTimers() + delete window.$_TSR +}) + +describe('hydration terminal lane', () => { + test('keeps server data while loading only the missing client suffix', async () => { + const parentLoader = vi.fn(() => 'client-parent') + const childLoader = vi.fn(() => 'client-child') + const rootRoute = createRootRoute({ component: Outlet }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + component: () => ( + <> +
    {parentRoute.useLoaderData()}
    + + + ), + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + ssr: false, + loader: childLoader, + component: () =>
    {childRoute.useLoaderData()}
    , + }) + const router = createRouter({ + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + }) + const matches = router.matchRoutes(router.state.location) + bootstrap([ + { match: matches[0]!, status: 'success', ssr: true }, + { + match: matches[1]!, + status: 'success', + ssr: true, + data: 'server-parent', + }, + { match: matches[2]!, status: 'pending', ssr: false }, + ]) + + await hydrate(router) + render() + + expect(await screen.findByText('server-parent')).toBeInTheDocument() + expect(await screen.findByText('client-child')).toBeInTheDocument() + expect(screen.queryByText('client-parent')).not.toBeInTheDocument() + expect(parentLoader).not.toHaveBeenCalled() + expect(childLoader).toHaveBeenCalledTimes(1) + }) + + test('keeps a hydrated pending fallback through its minimum before a terminal result', async () => { + const rootRoute = createRootRoute({ + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    Missing page pending
    , + notFoundComponent: () =>
    Missing page
    , + }) + const router = createRouter({ + history: createMemoryHistory({ initialEntries: ['/missing'] }), + routeTree: rootRoute, + }) + const matches = router.matchRoutes(router.state.location) + expect(matches[0]?._notFound).toBe(true) + bootstrap([ + { + match: matches[0]!, + status: 'pending', + ssr: false, + notFound: true, + }, + ]) + + await hydrate(router) + vi.useFakeTimers() + vi.setSystemTime(0) + render() + expect(screen.getByRole('status')).toHaveTextContent('Missing page pending') + + await act(async () => { + await vi.advanceTimersByTimeAsync(99) + }) + expect(screen.getByRole('status')).toHaveTextContent('Missing page pending') + expect(screen.queryByText('Missing page')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(5) + }) + expect(screen.getByText('Missing page')).toBeInTheDocument() + }) +}) diff --git a/packages/react-router/tests/issue-2072-context-invalidate.test.tsx b/packages/react-router/tests/issue-2072-context-invalidate.test.tsx new file mode 100644 index 0000000000..41b2c11608 --- /dev/null +++ b/packages/react-router/tests/issue-2072-context-invalidate.test.tsx @@ -0,0 +1,157 @@ +import * as React from 'react' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, test } from 'vitest' +import { + RouterProvider, + createMemoryHistory, + createRootRouteWithContext, + createRoute, + createRouter, + redirect, +} from '../src' + +afterEach(cleanup) + +// https://github.com/TanStack/router/issues/2072 +// Router context updates supplied through `RouterProvider` must be observable +// by `beforeLoad` on the very next `router.invalidate()` call, even when the +// context state and `invalidate()` change in the same event handler. +test('#2072: logout invalidates the router with the fresh auth context', async () => { + const seen: Array = [] + const rootRoute = createRootRouteWithContext<{ + auth: { isAuthenticated: boolean } + }>()() + const loginRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/login', + beforeLoad: ({ context }) => { + if (context.auth.isAuthenticated) { + throw redirect({ to: '/private' }) + } + }, + component: () =>
    Login page
    , + }) + const authenticatedRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_authenticated', + beforeLoad: ({ context }) => { + seen.push(context.auth.isAuthenticated) + if (!context.auth.isAuthenticated) { + throw redirect({ to: '/login' }) + } + }, + }) + const privateRoute = createRoute({ + getParentRoute: () => authenticatedRoute, + path: '/private', + component: () =>
    Private page
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + loginRoute, + authenticatedRoute.addChildren([privateRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/private'] }), + context: { auth: { isAuthenticated: true } }, + }) + + function App() { + const [isAuthenticated, setIsAuthenticated] = React.useState(true) + return ( + <> + + + + ) + } + + render() + expect(await screen.findByText('Private page')).toBeInTheDocument() + expect(seen).toEqual([true]) + + fireEvent.click(screen.getByRole('button', { name: 'Logout' })) + + expect(await screen.findByText('Login page')).toBeInTheDocument() + expect(seen).toEqual([true, false]) +}) + +// The inverse transition: becoming authenticated must let the login route's +// `beforeLoad` observe the new context and redirect to the private route. +test('#2072: login invalidates the router with the fresh auth context', async () => { + const seen: Array = [] + const rootRoute = createRootRouteWithContext<{ + auth: { isAuthenticated: boolean } + }>()() + const loginRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/login', + beforeLoad: ({ context }) => { + if (context.auth.isAuthenticated) { + throw redirect({ to: '/private' }) + } + }, + component: () =>
    Login page
    , + }) + const authenticatedRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_authenticated', + beforeLoad: ({ context }) => { + seen.push(context.auth.isAuthenticated) + if (!context.auth.isAuthenticated) { + throw redirect({ to: '/login' }) + } + }, + }) + const privateRoute = createRoute({ + getParentRoute: () => authenticatedRoute, + path: '/private', + component: () =>
    Private page
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + loginRoute, + authenticatedRoute.addChildren([privateRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/login'] }), + context: { auth: { isAuthenticated: false } }, + }) + + function App() { + const [isAuthenticated, setIsAuthenticated] = React.useState(false) + return ( + <> + + + + ) + } + + render() + expect(await screen.findByText('Login page')).toBeInTheDocument() + expect(seen).toEqual([]) + + fireEvent.click(screen.getByRole('button', { name: 'Login' })) + + expect(await screen.findByText('Private page')).toBeInTheDocument() + expect(seen).toEqual([true]) +}) diff --git a/packages/react-router/tests/issue-2182-root-pending.test.tsx b/packages/react-router/tests/issue-2182-root-pending.test.tsx new file mode 100644 index 0000000000..9cf3f82cb7 --- /dev/null +++ b/packages/react-router/tests/issue-2182-root-pending.test.tsx @@ -0,0 +1,55 @@ +import * as React from 'react' +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +// https://github.com/TanStack/router/issues/2182 +test('root pending fallback remains visible through pendingMinMs', async () => { + vi.useFakeTimers() + + const loaderGate = createControlledPromise() + const rootRoute = createRootRoute({ + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    Pending
    , + loader: () => loaderGate, + component: () =>
    Loaded
    , + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + expect(screen.queryByTestId('root-content')).not.toBeInTheDocument() + + loaderGate.resolve('loaded') + + await act(async () => { + await vi.advanceTimersByTimeAsync(99) + }) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + expect(screen.queryByTestId('root-content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + }) + expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument() + expect(screen.getByTestId('root-content')).toBeInTheDocument() +}) diff --git a/packages/react-router/tests/issue-2905-root-beforeload-pending.test.tsx b/packages/react-router/tests/issue-2905-root-beforeload-pending.test.tsx new file mode 100644 index 0000000000..2821571c42 --- /dev/null +++ b/packages/react-router/tests/issue-2905-root-beforeload-pending.test.tsx @@ -0,0 +1,59 @@ +import * as React from 'react' +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + RouterProvider, + createMemoryHistory, + createRootRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +// https://github.com/TanStack/router/issues/2905 +test('#2905: a root pendingComponent renders while root beforeLoad is pending', async () => { + vi.useFakeTimers() + + const rootRoute = createRootRoute({ + beforeLoad: async () => { + await new Promise((resolve) => setTimeout(resolve, 3_000)) + }, + pendingComponent: () =>
    Root pending
    , + component: () =>
    Root
    , + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + }) + + await act(async () => { + await vi.advanceTimersByTimeAsync(999) + }) + expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument() + expect(screen.queryByTestId('root-content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + }) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + expect(screen.queryByTestId('root-content')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1_999) + }) + expect(screen.getByTestId('root-pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + }) + expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument() + expect(screen.getByTestId('root-content')).toBeInTheDocument() +}) diff --git a/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx b/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx new file mode 100644 index 0000000000..11e2c150cc --- /dev/null +++ b/packages/react-router/tests/issue-4467-lazy-route-pending.test.tsx @@ -0,0 +1,222 @@ +import * as React from 'react' +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, onTestFinished, test, vi } from 'vitest' + +import { + Outlet, + RouterProvider, + createControlledPromise, + createLazyRoute, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +// https://github.com/TanStack/router/issues/4467 +test('default pending component renders while lazy route options load', async () => { + const rootRoute = createRootRoute({ + component: Outlet, + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>

    Index page

    , + }) + const lazyPageOptions = createLazyRoute('/page')({ + component: () =>

    Page

    , + }) + const lazyOptions = createControlledPromise() + const loadLazyOptions = vi.fn(() => lazyOptions) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + }).lazy(loadLazyOptions) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 0, + defaultPendingComponent: () =>

    Loading page

    , + }) + let navigationPromise: Promise | undefined + + onTestFinished(async () => { + await act(async () => { + if (lazyOptions.status === 'pending') { + lazyOptions.resolve(lazyPageOptions) + } + await navigationPromise + }) + }) + + render() + + expect( + await screen.findByRole('heading', { name: 'Index page' }), + ).toBeInTheDocument() + + act(() => { + navigationPromise = router.navigate({ to: '/page' }) + }) + + expect(await screen.findByRole('status')).toHaveTextContent('Loading page') + expect( + screen.queryByRole('heading', { name: 'Page' }), + ).not.toBeInTheDocument() + expect(lazyOptions.status).toBe('pending') + expect(loadLazyOptions).toHaveBeenCalledTimes(1) + + await act(async () => { + lazyOptions.resolve(lazyPageOptions) + await navigationPromise + }) + + expect(screen.getByRole('heading', { name: 'Page' })).toBeInTheDocument() + expect(screen.queryByRole('status')).not.toBeInTheDocument() + expect(loadLazyOptions).toHaveBeenCalledTimes(1) +}) + +test('a lazy pending component is offered while the eager loader is still pending', async () => { + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>

    Index page

    , + }) + const loader = createControlledPromise() + const lazyPageOptions = createLazyRoute('/page')({ + pendingComponent: () =>

    Loading lazy page

    , + component: () =>

    Page

    , + }) + const lazyOptions = createControlledPromise() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => loader, + }).lazy(() => lazyOptions) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 0, + defaultPendingComponent: () =>

    Loading default

    , + }) + let navigation: Promise | undefined + + onTestFinished(async () => { + await act(async () => { + lazyOptions.resolve(lazyPageOptions) + loader.resolve() + await navigation + }) + }) + + render() + expect( + await screen.findByRole('heading', { name: 'Index page' }), + ).toBeInTheDocument() + + act(() => { + navigation = router.navigate({ to: '/page' }) + }) + expect(await screen.findByRole('status')).toHaveTextContent('Loading default') + + await act(async () => { + lazyOptions.resolve(lazyPageOptions) + }) + + expect(await screen.findByRole('status')).toHaveTextContent( + 'Loading lazy page', + ) + expect( + screen.queryByRole('heading', { name: 'Page' }), + ).not.toBeInTheDocument() + + await act(async () => { + loader.resolve() + await navigation + }) + + expect(screen.getByRole('heading', { name: 'Page' })).toBeInTheDocument() +}) + +test('a lazy pending component does not restart an acknowledged minimum', async () => { + const loader = createControlledPromise() + const lazyPageOptions = createLazyRoute('/page')({ + pendingComponent: () =>

    Loading lazy page

    , + component: () =>

    Page

    , + }) + const lazyOptions = createControlledPromise() + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>

    Index page

    , + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => loader, + }).lazy(() => lazyOptions) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 100, + defaultPendingComponent: () =>

    Loading default

    , + }) + + render() + expect( + await screen.findByRole('heading', { name: 'Index page' }), + ).toBeInTheDocument() + vi.useFakeTimers() + vi.setSystemTime(0) + + const navigation = router.navigate({ to: '/page' }) + let settled = false + void navigation.then(() => { + settled = true + }) + try { + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByRole('status')).toHaveTextContent('Loading default') + + await act(async () => { + await vi.advanceTimersByTimeAsync(25) + lazyOptions.resolve(lazyPageOptions) + loader.resolve() + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByRole('status')).toHaveTextContent('Loading lazy page') + + await act(async () => { + await vi.advanceTimersByTimeAsync(74) + }) + expect(screen.getByRole('status')).toHaveTextContent('Loading lazy page') + + await act(async () => { + await vi.advanceTimersByTimeAsync(5) + await Promise.resolve() + }) + expect(settled).toBe(true) + await navigation + expect(screen.getByRole('heading', { name: 'Page' })).toBeInTheDocument() + expect(Date.now()).toBeLessThan(125) + } finally { + lazyOptions.resolve(lazyPageOptions) + loader.resolve() + await act(async () => { + await vi.advanceTimersByTimeAsync(1_000) + await navigation + }) + } +}) diff --git a/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx b/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx new file mode 100644 index 0000000000..824fcc1fb7 --- /dev/null +++ b/packages/react-router/tests/issue-4476-react-query-cancellation.test.tsx @@ -0,0 +1,133 @@ +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { + QueryClient, + QueryClientProvider, + useQuery, +} from '@tanstack/react-query' +import { afterEach, expect, onTestFinished, test, vi } from 'vitest' +import { + Link, + Outlet, + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(cleanup) + +// https://github.com/TanStack/router/issues/4476 +test('#4476: pending navigation keeps the query observer mounted and its fetchQuery signal alive', async () => { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false, staleTime: 0 } }, + }) + const queryGate = createControlledPromise() + const queryKey = ['issue-4476'] as const + const routeError = vi.fn() + const pageTwoBeforeLoad = vi.fn() + const pendingComponentRendered = vi.fn() + let querySignal: AbortSignal | undefined + + const rootRoute = createRootRoute({ + component: () => ( + <> + + Page two + + + + ), + }) + function PageOneComponent() { + const query = useQuery({ + queryKey, + queryFn: () => Promise.resolve(3), + }) + return
    Page one: {query.data}
    + } + const pageOneRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: PageOneComponent, + }) + const pageTwoRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page-two', + beforeLoad: async ({ preload }) => { + pageTwoBeforeLoad(preload) + if (preload) { + return + } + const data = await queryClient.fetchQuery({ + queryKey, + queryFn: ({ signal }) => { + querySignal = signal + return queryGate + }, + }) + return { data } + }, + errorComponent: ({ error }) => { + routeError(error) + return ( +
    + {error instanceof Error ? error.name : String(error)} +
    + ) + }, + component: () => { + const { data } = pageTwoRoute.useRouteContext() + return
    Page two: {data}
    + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageOneRoute, pageTwoRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPreload: 'intent', + defaultPreloadDelay: 0, + defaultPreloadStaleTime: 0, + defaultPendingMs: 0, + defaultPendingComponent: () => { + pendingComponentRendered() + return
    Loading page two
    + }, + }) + + onTestFinished(() => { + queryGate.resolve(10) + queryClient.clear() + }) + + render( + + + , + ) + expect(await screen.findByText('Page one: 3')).toBeInTheDocument() + + const link = screen.getByRole('link', { name: 'Page two' }) + fireEvent.mouseOver(link) + await waitFor(() => expect(pageTwoBeforeLoad).toHaveBeenCalledWith(true)) + fireEvent.click(link) + + await waitFor(() => expect(querySignal).toBeDefined()) + expect(screen.getByTestId('page-one')).toBeInTheDocument() + expect(screen.getByTestId('page-two-pending')).toBeInTheDocument() + expect(querySignal?.aborted).toBe(false) + queryGate.resolve(10) + + expect(await screen.findByText('Page two: 10')).toBeInTheDocument() + expect(routeError).not.toHaveBeenCalled() + expect(screen.queryByTestId('page-one')).not.toBeInTheDocument() + expect(screen.queryByTestId('page-two-pending')).not.toBeInTheDocument() + expect(screen.queryByTestId('page-two-error')).not.toBeInTheDocument() + expect(router.state.location.pathname).toBe('/page-two') +}) diff --git a/packages/react-router/tests/issue-5778-router-provider-context-preload.test.tsx b/packages/react-router/tests/issue-5778-router-provider-context-preload.test.tsx new file mode 100644 index 0000000000..e179a1502e --- /dev/null +++ b/packages/react-router/tests/issue-5778-router-provider-context-preload.test.tsx @@ -0,0 +1,113 @@ +import * as React from 'react' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { afterEach, expect, test } from 'vitest' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRouteWithContext, + createRoute, + createRouter, +} from '../src' + +afterEach(cleanup) + +// https://github.com/TanStack/router/issues/5778 +test('#5778: intent preload sees a RouterProvider context update before the first navigation', async () => { + const seen: Array<{ + route: 'auth' | 'foo' + foo: string + cause: string + preload: boolean + }> = [] + const rootRoute = createRootRouteWithContext<{ foo: string }>()({ + component: () => ( + <> + + Foo + + + + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const authRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_authenticated', + beforeLoad: ({ context, cause, preload }) => { + seen.push({ route: 'auth', foo: context.foo, cause, preload }) + }, + component: () => , + }) + const fooRoute = createRoute({ + getParentRoute: () => authRoute, + path: '/foo', + beforeLoad: ({ context, cause, preload }) => { + seen.push({ route: 'foo', foo: context.foo, cause, preload }) + }, + component: () =>
    Foo page
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + authRoute.addChildren([fooRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + context: { foo: null! }, + defaultPreload: 'intent', + defaultPreloadDelay: 0, + }) + + function App() { + const [foo, setFoo] = React.useState('foo') + return ( + <> + {foo} + + + + ) + } + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + expect(screen.getByLabelText('Current context')).toHaveTextContent('foo') + + fireEvent.click(screen.getByRole('button', { name: 'Update context' })) + await waitFor(() => + expect(screen.getByLabelText('Current context')).toHaveTextContent('baz'), + ) + + expect(seen).toEqual([]) + const link = screen.getByRole('link', { name: 'Foo' }) + fireEvent.mouseEnter(link) + await waitFor(() => expect(seen).toHaveLength(2)) + expect(seen).toEqual([ + { route: 'auth', foo: 'baz', cause: 'preload', preload: true }, + { route: 'foo', foo: 'baz', cause: 'preload', preload: true }, + ]) + expect(screen.getByText('Home')).toBeInTheDocument() + expect(screen.queryByText('Foo page')).not.toBeInTheDocument() + expect(router.state.location.pathname).toBe('/') + + fireEvent.click(link) + expect(await screen.findByText('Foo page')).toBeInTheDocument() + expect(router.state.location.pathname).toBe('/foo') +}) diff --git a/packages/react-router/tests/issue-6107-lazy-chunk-error-component.test.tsx b/packages/react-router/tests/issue-6107-lazy-chunk-error-component.test.tsx new file mode 100644 index 0000000000..138e7f5716 --- /dev/null +++ b/packages/react-router/tests/issue-6107-lazy-chunk-error-component.test.tsx @@ -0,0 +1,93 @@ +import * as React from 'react' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + vi.restoreAllMocks() + cleanup() +}) + +// https://github.com/TanStack/router/issues/6107 +test('#6107: lazy chunk hover failure is non-fatal and navigation renders defaultErrorComponent', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const chunkError = new TypeError( + 'Failed to fetch dynamically imported module: /assets/posts.lazy.js', + ) + const defaultErrorRendered = vi.fn() + let lazyCalls = 0 + + const rootRoute = createRootRoute({ + component: () => ( + <> + + Posts + + + + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Index
    , + }) + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }).lazy(() => { + lazyCalls++ + return Promise.reject(chunkError) + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, postsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPreloadDelay: 0, + defaultErrorComponent: ({ error }) => { + defaultErrorRendered(error) + return ( +
    + {error instanceof Error ? error.message : String(error)} +
    + ) + }, + }) + const preloadRoute = vi.spyOn(router, 'preloadRoute') + + render() + expect(await screen.findByText('Index')).toBeInTheDocument() + + const link = screen.getByRole('link', { name: 'Posts' }) + fireEvent.mouseEnter(link) + await waitFor(() => expect(preloadRoute).toHaveBeenCalledTimes(1)) + await preloadRoute.mock.results[0]!.value + expect(lazyCalls).toBeGreaterThanOrEqual(1) + expect(screen.getByText('Index')).toBeInTheDocument() + expect(screen.queryByTestId('default-error')).not.toBeInTheDocument() + expect(defaultErrorRendered).not.toHaveBeenCalled() + + const callsAfterPreload = lazyCalls + fireEvent.click(link) + expect(await screen.findByTestId('default-error')).toHaveTextContent( + chunkError.message, + ) + expect(lazyCalls).toBeGreaterThan(callsAfterPreload) + expect(defaultErrorRendered).toHaveBeenCalledWith(chunkError) + expect(screen.queryByText('Index')).not.toBeInTheDocument() + expect(router.state.location.pathname).toBe('/posts') + expect(router.state.status).toBe('idle') +}) diff --git a/packages/react-router/tests/issue-6371-search-default-normalization-abort.test.tsx b/packages/react-router/tests/issue-6371-search-default-normalization-abort.test.tsx new file mode 100644 index 0000000000..836ff045bc --- /dev/null +++ b/packages/react-router/tests/issue-6371-search-default-normalization-abort.test.tsx @@ -0,0 +1,173 @@ +import { afterEach, expect, onTestFinished, test, vi } from 'vitest' +import { act, cleanup, render, screen } from '@testing-library/react' +import { + Outlet, + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + useLocation, +} from '../src' + +afterEach(() => { + cleanup() +}) + +test('#6371: initial search defaults produce one live canonical loader', async () => { + const loaderGate = createControlledPromise() + const canonicalLocation = createControlledPromise() + const abortedLoaderData = 'discarded aborted loader' + const loaderSignals: Array = [] + const loaderLocations: Array = [] + const errorComponentRendered = vi.fn() + const loader = vi.fn( + ({ + abortController, + location, + }: { + abortController: AbortController + location: { href: string } + }) => { + const signal = abortController.signal + loaderSignals.push(signal) + loaderLocations.push(location.href) + + return new Promise((resolve, reject) => { + const onAbort = () => { + resolve(abortedLoaderData) + } + + if (signal.aborted) { + onAbort() + return + } + + signal.addEventListener('abort', onAbort, { once: true }) + loaderGate.then((data) => { + signal.removeEventListener('abort', onAbort) + resolve(data) + }, reject) + }) + }, + ) + + const PendingLocation = () => { + const href = useLocation({ select: (location) => location.href }) + return
    {href}
    + } + + const rootRoute = createRootRoute({ + component: () => , + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + validateSearch: (search: Record) => ({ + page: typeof search.page === 'number' ? search.page : 1, + }), + loader, + component: () => ( +
    {aboutRoute.useLoaderData()}
    + ), + errorComponent: ({ error }) => { + errorComponentRendered(error) + return ( +
    + {error instanceof Error ? error.message : String(error)} +
    + ) + }, + }) + const history = createMemoryHistory({ initialEntries: ['/about'] }) + const unsubscribeHistory = history.subscribe(() => { + if (history.location.href === '/about?page=1') { + canonicalLocation.resolve() + } + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([aboutRoute]), + history, + defaultPendingMs: 0, + defaultPendingMinMs: 0, + defaultPendingComponent: PendingLocation, + }) + + onTestFinished(async () => { + unsubscribeHistory() + await act(() => { + canonicalLocation.resolve() + loaderGate.resolve('about data') + }) + }) + + render() + + await act(async () => { + await canonicalLocation + }) + + expect(loader).toHaveBeenCalledTimes(1) + expect(loaderLocations).toEqual(['/about?page=1']) + expect(loaderSignals).toHaveLength(1) + expect(loaderSignals[0]?.aborted).toBe(false) + + expect( + await screen.findByText('/about?page=1', { + selector: '[data-testid="pending-location"]', + }), + ).toBeInTheDocument() + + await act(() => { + loaderGate.resolve('about data') + }) + + expect(await screen.findByTestId('about-data')).toHaveTextContent( + 'about data', + ) + expect(loader).toHaveBeenCalledTimes(1) + expect(loaderSignals[0]?.aborted).toBe(false) + expect(errorComponentRendered).not.toHaveBeenCalled() + expect(screen.queryByTestId('about-error')).not.toBeInTheDocument() +}) + +test('initial canonicalization bypasses existing navigation blockers', async () => { + const loader = vi.fn( + ({ location }: { location: { href: string } }) => location.href, + ) + const rootRoute = createRootRoute({ + component: () => , + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + validateSearch: (search: Record) => ({ + page: typeof search.page === 'number' ? search.page : 1, + }), + loader, + component: () =>
    {aboutRoute.useLoaderData()}
    , + }) + const history = createMemoryHistory({ initialEntries: ['/about'] }) + const blockerFn = vi.fn(() => true) + const unblock = history.block({ + blockerFn, + enableBeforeUnload: false, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([aboutRoute]), + history, + }) + + onTestFinished(unblock) + + render() + + expect(await screen.findByText('/about?page=1')).toBeInTheDocument() + expect(loader).toHaveBeenCalledTimes(1) + expect(history.location.href).toBe('/about?page=1') + expect(router.latestLocation.href).toBe('/about?page=1') + expect(router.state.location.href).toBe('/about?page=1') + expect(router.state.resolvedLocation?.href).toBe('/about?page=1') + expect(blockerFn).not.toHaveBeenCalled() +}) diff --git a/packages/react-router/tests/issue-7051-force-pending-suspense.test.tsx b/packages/react-router/tests/issue-7051-force-pending-suspense.test.tsx new file mode 100644 index 0000000000..5640cb7477 --- /dev/null +++ b/packages/react-router/tests/issue-7051-force-pending-suspense.test.tsx @@ -0,0 +1,195 @@ +import { act } from 'react' +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, render, screen } from '@testing-library/react' +import { + Outlet, + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + vi.clearAllMocks() + cleanup() +}) + +// Ported from PR #7051. A forced-pending reload must keep showing its pending +// fallback until fresh content commits instead of exposing the error boundary. +test('invalidate({ forcePending: true }) keeps rendering the pending fallback instead of the error boundary', async () => { + const history = createMemoryHistory({ + initialEntries: ['/force-pending'], + }) + const errorComponentRendered = vi.fn() + let shouldSuspendReload = false + const reloadGate = createControlledPromise() + + const rootRoute = createRootRoute({ + component: () => , + }) + + const forcePendingRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/force-pending', + pendingMs: 0, + pendingMinMs: 10, + loader: async () => { + if (shouldSuspendReload) { + await reloadGate + } + + return 'done' + }, + component: () => ( +
    + {forcePendingRoute.useLoaderData()} +
    + ), + pendingComponent: () => ( +
    Pending...
    + ), + errorComponent: ({ error }) => { + errorComponentRendered(error) + return
    {String(error)}
    + }, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([forcePendingRoute]), + history, + }) + + render() + + await act(() => router.load()) + expect(await screen.findByTestId('force-pending-route')).toHaveTextContent( + 'done', + ) + + shouldSuspendReload = true + let invalidation!: Promise + act(() => { + invalidation = router.invalidate({ forcePending: true }) + }) + + expect( + await screen.findByTestId('force-pending-fallback'), + ).toBeInTheDocument() + expect(errorComponentRendered).not.toHaveBeenCalled() + expect(screen.queryByTestId('force-pending-error')).not.toBeInTheDocument() + + act(() => { + reloadGate.resolve() + }) + + await act(() => invalidation) + expect(await screen.findByTestId('force-pending-route')).toHaveTextContent( + 'done', + ) + expect(screen.queryByTestId('force-pending-fallback')).not.toBeInTheDocument() + expect(screen.queryByTestId('force-pending-error')).not.toBeInTheDocument() + expect(errorComponentRendered).not.toHaveBeenCalled() + expect(router.state.location.pathname).toBe('/force-pending') + expect(router.state.status).toBe('idle') +}) + +test('regular navigation keeps the current pending fallback while its loader is aborted', async () => { + const firstLoaderAborted = createControlledPromise() + const secondLoaderStarted = createControlledPromise() + const secondLoaderGate = createControlledPromise() + const firstErrorComponentRendered = vi.fn() + let firstSignal: AbortSignal | undefined + + const rootRoute = createRootRoute({ + component: () => , + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home page
    , + }) + const firstRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/first', + pendingMs: 0, + loader: async ({ abortController }) => { + firstSignal = abortController.signal + await new Promise((_resolve, reject) => { + abortController.signal.addEventListener( + 'abort', + () => { + firstLoaderAborted.resolve() + reject(new DOMException('Aborted', 'AbortError')) + }, + { once: true }, + ) + }) + return 'first' + }, + component: () => ( +
    {firstRoute.useLoaderData()}
    + ), + pendingComponent: () => ( +
    Pending first route
    + ), + errorComponent: ({ error }) => { + firstErrorComponentRendered(error) + return
    {String(error)}
    + }, + }) + const secondRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/second', + loader: async () => { + secondLoaderStarted.resolve() + await secondLoaderGate + return 'second' + }, + component: () => ( +
    {secondRoute.useLoaderData()}
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, firstRoute, secondRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPreload: false, + }) + + render() + expect(await screen.findByTestId('home-page')).toBeInTheDocument() + + act(() => { + void router.navigate({ to: '/first' }) + }) + expect(await screen.findByTestId('first-pending')).toBeInTheDocument() + expect(firstSignal?.aborted).toBe(false) + + let secondNavigation!: Promise + act(() => { + secondNavigation = router.navigate({ to: '/second' }) + }) + await act(async () => { + await Promise.all([firstLoaderAborted, secondLoaderStarted]) + }) + + expect(firstSignal?.aborted).toBe(true) + expect(screen.getByTestId('first-pending')).toBeInTheDocument() + expect(screen.queryByTestId('first-error')).not.toBeInTheDocument() + expect(firstErrorComponentRendered).not.toHaveBeenCalled() + expect(router.state.location.pathname).toBe('/second') + expect(router.state.status).toBe('pending') + + act(() => { + secondLoaderGate.resolve() + }) + await act(() => secondNavigation) + + expect(await screen.findByTestId('second-page')).toHaveTextContent('second') + expect(screen.queryByTestId('first-pending')).not.toBeInTheDocument() + expect(screen.queryByTestId('first-error')).not.toBeInTheDocument() + expect(firstErrorComponentRendered).not.toHaveBeenCalled() + expect(router.state.location.pathname).toBe('/second') + expect(router.state.status).toBe('idle') +}) diff --git a/packages/react-router/tests/issue-7367-pending-min-redirect.test.tsx b/packages/react-router/tests/issue-7367-pending-min-redirect.test.tsx new file mode 100644 index 0000000000..8edf32c133 --- /dev/null +++ b/packages/react-router/tests/issue-7367-pending-min-redirect.test.tsx @@ -0,0 +1,203 @@ +import * as React from 'react' +import { act, cleanup, render, screen } from '@testing-library/react' +import { createControlledPromise } from '@tanstack/router-core' +import { afterEach, expect, test, vi } from 'vitest' + +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + redirect, +} from '../src' +import { sleep } from './utils' + +afterEach(() => { + vi.restoreAllMocks() + cleanup() + vi.useRealTimers() +}) + +// https://github.com/TanStack/router/issues/7367 +// Root route shows a spinner immediately (pendingMs: 0) while beforeLoad +// decides where to send the user, keeps it up for pendingMinMs, and then +// redirects. This used to crash in MatchInnerImpl (white screen) because the +// redirected match was rendered/thrown after its loadPromise was cleared. +test('immediate pending spinner (pendingMs: 0 + pendingMinMs) with root beforeLoad redirect renders the target without render errors', async () => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + let hasRedirected = false + + const rootRoute = createRootRoute({ + component: () => , + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    loading
    , + errorComponent: ({ error }) => ( +
    {String(error)}
    + ), + beforeLoad: async () => { + await sleep(50) + if (!hasRedirected) { + hasRedirected = true + throw redirect({ to: '/welcome', replace: true }) + } + }, + }) + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Index
    , + }) + + const welcomeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/welcome', + component: () =>
    Welcome
    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, welcomeRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + + // pendingMs: 0 — the spinner must show right away. + expect(await screen.findByTestId('pending')).toBeInTheDocument() + + // The redirect must complete: the target renders, no error boundary output + // and no render crash. + expect( + await screen.findByTestId('welcome-page', undefined, { timeout: 5_000 }), + ).toBeInTheDocument() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.queryByTestId('root-error')).not.toBeInTheDocument() + expect(router.state.location.pathname).toBe('/welcome') + expect(consoleError).not.toHaveBeenCalled() +}) + +test('a compatible SPA redirect preserves the acknowledged pending minimum', async () => { + vi.useFakeTimers() + vi.setSystemTime(0) + const redirectReady = createControlledPromise() + let shouldRedirect = true + + const rootRoute = createRootRoute({ + component: Outlet, + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    loading
    , + beforeLoad: async () => { + if (shouldRedirect) { + shouldRedirect = false + await redirectReady + throw redirect({ to: '/welcome', replace: true }) + } + }, + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Index
    , + }) + const welcomeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/welcome', + component: () =>
    Welcome
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, welcomeRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + try { + render() + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(25) + redirectReady.resolve() + await vi.advanceTimersByTimeAsync(74) + }) + expect(screen.getByTestId('pending')).toBeInTheDocument() + expect(screen.queryByTestId('welcome-page')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(5) + }) + expect(screen.getByTestId('welcome-page')).toBeInTheDocument() + } finally { + redirectReady.resolve() + await act(async () => { + await vi.advanceTimersByTimeAsync(1_000) + }) + vi.useRealTimers() + } +}) + +test('an incompatible SPA redirect does not inherit the pending minimum', async () => { + const redirectReady = createControlledPromise() + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Index
    , + }) + const sourceRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/source', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    loading
    , + beforeLoad: async () => { + await redirectReady + throw redirect({ to: '/welcome', replace: true }) + }, + }) + const welcomeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/welcome', + component: () =>
    Welcome
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, sourceRoute, welcomeRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByTestId('index-page')).toBeVisible() + vi.useFakeTimers() + vi.setSystemTime(0) + + const navigation = router.navigate({ to: '/source' }) + try { + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByTestId('pending')).toBeVisible() + + await act(async () => { + await vi.advanceTimersByTimeAsync(25) + redirectReady.resolve() + await vi.advanceTimersByTimeAsync(5) + await navigation + }) + + expect(Date.now()).toBeLessThan(100) + expect(screen.getByTestId('welcome-page')).toBeVisible() + expect(screen.queryByTestId('index-page')).not.toBeInTheDocument() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + } finally { + redirectReady.resolve() + await act(async () => { + await vi.advanceTimersByTimeAsync(1_000) + await navigation + }) + } +}) diff --git a/packages/react-router/tests/issue-7635-error-head-after-navigation.test.tsx b/packages/react-router/tests/issue-7635-error-head-after-navigation.test.tsx new file mode 100644 index 0000000000..23bc0aa5f3 --- /dev/null +++ b/packages/react-router/tests/issue-7635-error-head-after-navigation.test.tsx @@ -0,0 +1,104 @@ +import { createPortal } from 'react-dom' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + HeadContent, + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + document.head.innerHTML = '' +}) + +// https://github.com/TanStack/router/issues/7635 +test('#7635: a parent beforeLoad error replaces the previous child title', async () => { + const appError = new Error('App beforeLoad failed') + const appErrorRendered = vi.fn() + const childHead = vi.fn(() => ({ + meta: [{ title: 'Child success title' }], + })) + + const rootRoute = createRootRoute({ + component: () => ( + <> + {createPortal(, document.head)} + + Fail app load + + + + ), + }) + const appRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_app', + validateSearch: (search: Record) => ({ + fail: search.fail === true || search.fail === 'true', + }), + beforeLoad: ({ search }) => { + if (search.fail) { + throw appError + } + }, + head: ({ match }) => ({ + meta: [ + { + title: match.error ? 'App error title' : 'App success title', + }, + ], + }), + component: Outlet, + errorComponent: ({ error }) => { + appErrorRendered(error) + return ( +
    + {error instanceof Error ? error.message : String(error)} +
    + ) + }, + }) + const childRoute = createRoute({ + getParentRoute: () => appRoute, + path: '/child', + head: childHead, + component: () =>
    Child content
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([appRoute.addChildren([childRoute])]), + history: createMemoryHistory({ + initialEntries: ['/child?fail=false'], + }), + }) + + render() + + expect(await screen.findByTestId('child-content')).toBeInTheDocument() + await waitFor(() => expect(document.title).toBe('Child success title')) + expect(childHead).toHaveBeenCalled() + childHead.mockClear() + + fireEvent.click(screen.getByRole('link', { name: 'Fail app load' })) + + expect(await screen.findByTestId('app-error')).toHaveTextContent( + appError.message, + ) + expect(appErrorRendered).toHaveBeenCalledWith(appError) + expect(screen.queryByTestId('child-content')).not.toBeInTheDocument() + await waitFor(() => expect(document.title).toBe('App error title')) + expect(childHead).not.toHaveBeenCalled() + expect(router.state.location.href).toBe('/child?fail=true') + expect(router.state.status).toBe('idle') +}) diff --git a/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx b/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx new file mode 100644 index 0000000000..e80f073896 --- /dev/null +++ b/packages/react-router/tests/issue-7638-invalidate-transition-error.test.tsx @@ -0,0 +1,192 @@ +import * as React from 'react' +import { afterEach, expect, test, vi } from 'vitest' +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { + Outlet, + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + useRouter, +} from '../src' +import type { ErrorComponentProps } from '../src' + +afterEach(() => { + cleanup() +}) + +// https://github.com/TanStack/router/issues/7638 +// router.invalidate() called inside React.startTransition while a nested +// route is showing its errorComponent must complete the reload and land back +// on the error UI without crashing React with +// "Rendered more hooks than during the previous render." +function setup({ failVia }: { failVia: 'render' | 'loader' }) { + const rootRoute = createRootRoute({ component: () => }) + const parentAction = vi.fn() + const secondChildLoad = createControlledPromise() + let invalidation: Promise | undefined + + const testRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/test', + component: function TestComponent() { + testRoute.useLoaderData() + const router = useRouter() + const [isPending, startTransition] = React.useTransition() + return ( +
    + + + +
    + ) + }, + }) + + let childLoaderCalls = 0 + const childLoader = vi.fn(async () => { + childLoaderCalls++ + if (childLoaderCalls === 2) { + await secondChildLoad + } + if (failVia === 'loader') { + throw new Error('loader error') + } + return 'data' + }) + + const testIndexRoute = createRoute({ + getParentRoute: () => testRoute, + path: '/', + loader: childLoader, + component: function ChildComponent() { + if (failVia === 'render') { + throw new Error('render error') + } + return
    child content
    + }, + }) + + let errorRenders = 0 + const router = createRouter({ + routeTree: rootRoute.addChildren([testRoute.addChildren([testIndexRoute])]), + history: createMemoryHistory({ initialEntries: ['/test'] }), + defaultErrorComponent: (props: ErrorComponentProps) => { + errorRenders++ + return ( +
    + error:{' '} + {props.error instanceof Error + ? props.error.message + : String(props.error)} +
    + ) + }, + }) + + return { + router, + childLoader, + parentAction, + secondChildLoad, + getErrorRenders: () => errorRenders, + getInvalidation: () => invalidation, + } +} + +test.each(['render', 'loader'] as const)( + 'invalidate() inside startTransition through a nested %s-error route does not crash', + async (failVia) => { + // Error boundaries log caught errors through console.error, and so does a + // hooks-order crash. Capture instead of polluting the test output, then + // inspect the captured calls for the crash signature. + const { + router, + childLoader, + parentAction, + secondChildLoad, + getErrorRenders, + getInvalidation, + } = setup({ failVia }) + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + + try { + render() + + expect(await screen.findByTestId('error-ui')).toHaveTextContent( + `error: ${failVia} error`, + ) + const initialErrorRenders = getErrorRenders() + expect(childLoader).toHaveBeenCalledTimes(1) + consoleError.mockClear() + + fireEvent.click(screen.getByTestId('invalidate')) + + await waitFor(() => { + expect(childLoader).toHaveBeenCalledTimes(2) + expect(screen.getByTestId('invalidate')).toHaveTextContent('pending') + expect(screen.getByTestId('invalidate')).toBeDisabled() + }) + expect(secondChildLoad.status).toBe('pending') + + const invalidation = getInvalidation() + if (!invalidation) { + throw new Error('invalidate action did not return its promise') + } + + await act(async () => { + secondChildLoad.resolve() + await invalidation + }) + + await waitFor(() => { + expect(screen.getByTestId('error-ui')).toHaveTextContent( + `error: ${failVia} error`, + ) + expect(getErrorRenders()).toBeGreaterThan(initialErrorRenders) + expect(screen.getByTestId('invalidate')).toHaveTextContent('invalidate') + expect(screen.getByTestId('invalidate')).toBeEnabled() + }) + + fireEvent.click(screen.getByTestId('parent-action')) + expect(parentAction).toHaveBeenCalledTimes(1) + + const hooksCrash = consoleError.mock.calls.find((call) => + call.some((arg) => + String(arg?.message ?? arg).includes('Rendered more hooks'), + ), + ) + expect(hooksCrash).toBeUndefined() + } finally { + if (secondChildLoad.status === 'pending') { + await act(async () => { + secondChildLoad.resolve() + await getInvalidation()?.catch(() => undefined) + }) + } + consoleError.mockRestore() + } + }, +) diff --git a/packages/react-router/tests/issue-7964-param-parsing-loader.test.tsx b/packages/react-router/tests/issue-7964-param-parsing-loader.test.tsx new file mode 100644 index 0000000000..54f6c19c47 --- /dev/null +++ b/packages/react-router/tests/issue-7964-param-parsing-loader.test.tsx @@ -0,0 +1,107 @@ +import { act, cleanup, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, test } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +// https://github.com/TanStack/router/issues/7964 +test('#7964: a child loader receives fresh structured params after revisiting its route', async () => { + const rootRoute = createRootRoute({ + component: Outlet, + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home page
    , + }) + const parsedParamRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/$parsedParam', + params: { + parse: ({ parsedParam }) => { + const [recordName, revisionNumber] = parsedParam.split('-') + return { + parsedParam: { + recordName: recordName!, + revisionNumber: Number(revisionNumber), + }, + } + }, + stringify: ({ parsedParam }) => ({ + parsedParam: `${parsedParam.recordName}-${parsedParam.revisionNumber}`, + }), + }, + component: Outlet, + }) + const parsedParamIndexRoute = createRoute({ + getParentRoute: () => parsedParamRoute, + path: '/', + loader: ({ params }) => params.parsedParam.revisionNumber * 100, + component: () => { + const params = parsedParamIndexRoute.useParams() + const loaderData = parsedParamIndexRoute.useLoaderData() + + return ( + <> +
    + Params have {params.parsedParam.recordName} with revision{' '} + {params.parsedParam.revisionNumber} +
    +
    Loader data is {loaderData}
    + + ) + }, + }) + const routeTree = rootRoute.addChildren([ + indexRoute, + parsedParamRoute.addChildren([parsedParamIndexRoute]), + ]) + const router = createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Home page')).toBeInTheDocument() + + await act(() => + router.navigate({ + to: '/$parsedParam', + params: { parsedParam: { recordName: 'blue', revisionNumber: 1 } }, + }), + ) + expect( + await screen.findByText('Params have blue with revision 1'), + ).toBeInTheDocument() + expect(await screen.findByText('Loader data is 100')).toBeInTheDocument() + + await act(() => router.navigate({ to: '/' })) + expect(await screen.findByText('Home page')).toBeInTheDocument() + + await act(() => + router.navigate({ + to: '/$parsedParam', + params: { parsedParam: { recordName: 'red', revisionNumber: 2 } }, + }), + ) + expect(router.state.location.pathname).toBe('/red-2') + + await waitFor(() => { + expect({ + params: screen.getByTestId('params').textContent, + loaderData: screen.getByTestId('loader-data').textContent, + }).toEqual({ + params: 'Params have red with revision 2', + loaderData: 'Loader data is 200', + }) + }) +}) diff --git a/packages/react-router/tests/issue-7986-retained-pending.test.tsx b/packages/react-router/tests/issue-7986-retained-pending.test.tsx new file mode 100644 index 0000000000..04d762df64 --- /dev/null +++ b/packages/react-router/tests/issue-7986-retained-pending.test.tsx @@ -0,0 +1,1019 @@ +import { act, cleanup, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + Outlet, + RouterProvider, + createControlledPromise, + createLazyRoute, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + vi.useRealTimers() + vi.restoreAllMocks() +}) + +const navigationDelay = 100 + +function delayNavigation() { + return new Promise((resolve) => setTimeout(resolve, navigationDelay)) +} + +function deferred() { + let resolve!: () => void + const promise = new Promise((resolver) => { + resolve = resolver + }) + return { promise, resolve } +} + +function setup() { + const navigationBeforeLoadStarted = deferred() + let beforeLoadCalls = 0 + + const rootRoute = createRootRoute({ component: Outlet }) + const layoutRoute = createRoute({ + getParentRoute: () => rootRoute, + id: 'app', + beforeLoad: async () => { + if (++beforeLoadCalls > 1) { + navigationBeforeLoadStarted.resolve() + await delayNavigation() + } + return { user: 'test' } + }, + component: Outlet, + }) + const projectRoute = createRoute({ + getParentRoute: () => layoutRoute, + path: '/projects/$projectId', + validateSearch: (search: Record): { tab?: string } => + typeof search.tab === 'string' ? { tab: search.tab } : {}, + component: Project, + }) + + function Project() { + const { projectId } = projectRoute.useParams() + const { tab } = projectRoute.useSearch() + return ( +
    + project={projectId} tab={tab ?? 'default'} +
    + ) + } + + const router = createRouter({ + routeTree: rootRoute.addChildren([layoutRoute.addChildren([projectRoute])]), + history: createMemoryHistory({ initialEntries: ['/projects/p1'] }), + defaultPendingComponent: () =>
    Pending
    , + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + return { + router, + navigationBeforeLoadStarted, + } +} + +test('a search-only navigation retains successful UI while beforeLoad reruns', async () => { + const { router, navigationBeforeLoadStarted } = setup() + render() + expect(await screen.findByTestId('content')).toHaveTextContent( + 'project=p1 tab=default', + ) + + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ + to: '/projects/$projectId', + params: { projectId: 'p1' }, + search: { tab: 'files' }, + }) + await navigationBeforeLoadStarted.promise + }) + + const contentWhileLoading = screen.getByTestId('content') + expect(contentWhileLoading).toBeVisible() + expect(contentWhileLoading).toHaveTextContent('project=p1 tab=default') + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent( + 'project=p1 tab=default', + ) + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(navigationDelay) + await navigation + }) + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toHaveTextContent( + 'project=p1 tab=files', + ) +}) + +test('a path-param navigation retains successful UI while beforeLoad reruns', async () => { + const { router, navigationBeforeLoadStarted } = setup() + render() + expect(await screen.findByTestId('content')).toHaveTextContent( + 'project=p1 tab=default', + ) + + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ + to: '/projects/$projectId', + params: { projectId: 'p2' }, + }) + await navigationBeforeLoadStarted.promise + }) + + const contentWhileLoading = screen.getByTestId('content') + expect(contentWhileLoading).toBeVisible() + expect(contentWhileLoading).toHaveTextContent('project=p1 tab=default') + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent( + 'project=p1 tab=default', + ) + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(navigationDelay) + await navigation + }) + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toHaveTextContent( + 'project=p2 tab=default', + ) +}) + +test('a blocking reload retains the exact successful match', async () => { + const reloadStarted = deferred() + let loaderCalls = 0 + + const rootRoute = createRootRoute({ component: Outlet }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + validateSearch: (search: Record): { tab?: string } => + typeof search.tab === 'string' ? { tab: search.tab } : {}, + shouldReload: true, + loader: { + staleReloadMode: 'blocking', + handler: () => { + if (++loaderCalls === 1) { + return 'initial' + } + reloadStarted.resolve() + return delayNavigation().then(() => 'reloaded') + }, + }, + component: () => ( +
    + {pageRoute.useLoaderData()} tab= + {pageRoute.useSearch().tab ?? 'default'} +
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + defaultPendingComponent: () =>
    Pending
    , + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render() + expect(await screen.findByTestId('content')).toHaveTextContent( + 'initial tab=default', + ) + + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ + to: '/page', + search: { tab: 'files' }, + }) + await reloadStarted.promise + }) + + const contentWhileLoading = screen.getByTestId('content') + expect(contentWhileLoading).toBeVisible() + expect(contentWhileLoading).toHaveTextContent('initial tab=default') + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent('initial tab=default') + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(navigationDelay) + await navigation + }) + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toHaveTextContent('reloaded tab=files') +}) + +test('a cached success retries through pending UI when an error is mounted', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const retryStarted = deferred() + const retry = deferred() + let loaderCalls = 0 + + const rootRoute = createRootRoute({ component: Outlet }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + shouldReload: true, + loader: { + staleReloadMode: 'blocking', + handler: () => { + loaderCalls++ + if (loaderCalls === 1) { + throw new Error('initial load failed') + } + if (loaderCalls === 2) { + return 'preloaded' + } + retryStarted.resolve() + return retry.promise.then(() => 'retried') + }, + }, + component: () => ( +
    {pageRoute.useLoaderData()}
    + ), + pendingComponent: () =>
    Pending
    , + errorComponent: () =>
    Failed
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render() + expect(await screen.findByTestId('error')).toBeInTheDocument() + + await router.preloadRoute({ to: '/page' }) + expect(loaderCalls).toBe(2) + expect(screen.getByTestId('error')).toBeInTheDocument() + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/page' }) + await retryStarted.promise + }) + + expect(await screen.findByTestId('pending')).toBeVisible() + expect(screen.getByTestId('error')).not.toBeVisible() + + await act(async () => { + retry.resolve() + await navigation + }) + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent('retried') +}) + +test('a cache-only success retries through pending UI over mounted success', async () => { + const retryStarted = deferred() + const retry = deferred() + let loaderCalls = 0 + + const rootRoute = createRootRoute({ component: Outlet }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + shouldReload: true, + loader: { + staleReloadMode: 'blocking', + handler: () => { + const generation = ++loaderCalls + if (generation === 3) { + retryStarted.resolve() + return retry.promise.then(() => `generation ${generation}`) + } + return `generation ${generation}` + }, + }, + component: () => ( +
    {pageRoute.useLoaderData()}
    + ), + pendingComponent: () =>
    Pending
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render() + expect(await screen.findByTestId('content')).toHaveTextContent('generation 1') + + await router.preloadRoute({ to: '/page' }) + expect(loaderCalls).toBe(2) + expect(screen.getByTestId('content')).toHaveTextContent('generation 1') + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/page' }) + await retryStarted.promise + }) + + expect(await screen.findByTestId('pending')).toBeVisible() + expect(screen.getByTestId('content')).not.toBeVisible() + + await act(async () => { + retry.resolve() + await navigation + }) + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toHaveTextContent('generation 3') +}) + +test('a success hidden below an error boundary retries through pending UI', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const childReloadStarted = deferred() + const childReload = deferred() + let parentFails = false + let childReloads = false + + const rootRoute = createRootRoute({ component: Outlet }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + shouldReload: true, + loader: () => { + if (parentFails) { + throw new Error('parent failed') + } + return 'parent data' + }, + component: Outlet, + errorComponent: () =>
    Parent failed
    , + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + shouldReload: () => childReloads, + loader: { + staleReloadMode: 'blocking', + handler: () => { + if (childReloads) { + childReloadStarted.resolve() + return childReload.promise.then(() => 'reloaded child') + } + return 'initial child' + }, + }, + component: () => ( +
    {childRoute.useLoaderData()}
    + ), + pendingComponent: () =>
    Pending child
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render() + expect(await screen.findByTestId('content')).toHaveTextContent( + 'initial child', + ) + + parentFails = true + await act(() => router.navigate({ to: '/parent/child' })) + expect(await screen.findByTestId('error')).toBeInTheDocument() + + parentFails = false + childReloads = true + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/parent/child' }) + await childReloadStarted.promise + }) + + expect(await screen.findByTestId('pending')).toBeVisible() + expect(screen.queryByTestId('error')).not.toBeInTheDocument() + + await act(async () => { + childReload.resolve() + await navigation + }) + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent('reloaded child') +}) + +test('a global not-found destination keeps pending until its terminal component is ready', async () => { + const missingStarted = deferred() + const missingLoader = deferred() + const terminalStarted = deferred() + const terminalReady = deferred() + let loaderCalls = 0 + const Missing = Object.assign( + () =>
    Missing
    , + { + preload: () => { + terminalStarted.resolve() + return terminalReady.promise + }, + }, + ) + + const rootRoute = createRootRoute({ + shouldReload: true, + loader: { + staleReloadMode: 'blocking', + handler: () => { + if (++loaderCalls === 1) { + return 'initial root' + } + missingStarted.resolve() + return missingLoader.promise + }, + }, + component: Outlet, + pendingComponent: () =>
    Pending root
    , + notFoundComponent: Missing, + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: () =>
    Page
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render() + expect(await screen.findByTestId('content')).toBeInTheDocument() + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/missing' } as any) + await missingStarted.promise + }) + + expect(await screen.findByTestId('pending')).toBeVisible() + expect(screen.getByTestId('content')).not.toBeVisible() + + let settled = false + void navigation.then(() => { + settled = true + }) + await act(async () => { + missingLoader.resolve() + await terminalStarted.promise + }) + expect(screen.getByTestId('pending')).toBeVisible() + expect(screen.queryByTestId('missing')).not.toBeInTheDocument() + expect(settled).toBe(false) + + await act(async () => { + terminalReady.resolve() + await navigation + }) + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('missing')).toBeVisible() +}) + +test('a cold global not-found presents pending only while its terminal component loads', async () => { + const terminalStarted = deferred() + const terminalReady = deferred() + const Missing = Object.assign( + () =>
    Missing
    , + { + preload: () => { + terminalStarted.resolve() + return terminalReady.promise + }, + }, + ) + const rootRoute = createRootRoute({ + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>
    Pending root
    , + notFoundComponent: Missing, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/missing'] }), + }) + + render() + await terminalStarted.promise + expect(await screen.findByTestId('pending')).toBeVisible() + expect(screen.queryByTestId('missing')).not.toBeInTheDocument() + + terminalReady.resolve() + expect(await screen.findByTestId('missing')).toBeVisible() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() +}) + +test('lazy fuzzy-boundary relocation retains the mounted parent', async () => { + const lazyStarted = deferred() + const lazyRoute = deferred() + const parentReloadStarted = deferred() + const parentReload = deferred() + let parentLoads = 0 + + const rootRoute = createRootRoute({ + component: Outlet, + notFoundComponent: () =>
    Root missing
    , + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: async () => { + if (++parentLoads > 1) { + parentReloadStarted.resolve() + await parentReload.promise + } + }, + component: () => ( +
    +
    Parent content
    + +
    + ), + pendingComponent: () => ( +
    Parent pending
    + ), + notFoundComponent: () => ( +
    Parent missing
    + ), + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + }).lazy(async () => { + lazyStarted.resolve() + await lazyRoute.promise + return createLazyRoute('/parent/child')({ + notFoundComponent: () => ( +
    Child missing
    + ), + }) + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent'] }), + defaultPendingComponent: () => ( +
    Pending
    + ), + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render() + expect(await screen.findByTestId('parent-content')).toBeVisible() + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/parent/child/missing' as any }) + await lazyStarted.promise + }) + + expect(screen.getByTestId('parent-content')).toBeVisible() + expect(screen.queryByTestId('parent-pending')).not.toBeInTheDocument() + expect(screen.queryByTestId('parent-missing')).not.toBeInTheDocument() + + await act(async () => { + lazyRoute.resolve() + await parentReloadStarted.promise + }) + + expect(screen.getByTestId('parent-content')).toBeVisible() + expect(screen.queryByTestId('parent-pending')).not.toBeInTheDocument() + expect(screen.queryByTestId('parent-missing')).not.toBeInTheDocument() + + await act(async () => { + parentReload.resolve() + await navigation + }) + + expect(screen.getByTestId('child-missing')).toBeVisible() + expect(screen.queryByTestId('root-missing')).not.toBeInTheDocument() + expect(screen.queryByTestId('parent-missing')).not.toBeInTheDocument() +}) + +test('a superseding navigation replaces an unrelated pending presentation', async () => { + const otherStarted = deferred() + const otherLoader = deferred() + const pageReloadStarted = deferred() + const pageReload = deferred() + let pageLoads = 0 + + const rootRoute = createRootRoute({ component: Outlet }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + shouldReload: true, + loader: { + staleReloadMode: 'blocking', + handler: () => { + if (++pageLoads === 1) { + return 'initial page' + } + pageReloadStarted.resolve() + return pageReload.promise.then(() => 'reloaded page') + }, + }, + component: () => ( +
    {pageRoute.useLoaderData()}
    + ), + pendingComponent: () =>
    Page pending
    , + }) + const otherRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/other', + loader: async () => { + otherStarted.resolve() + await otherLoader.promise + }, + pendingComponent: () => ( +
    Other pending
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render() + expect(await screen.findByTestId('content')).toHaveTextContent('initial page') + + await act(async () => { + void router.navigate({ to: '/other' }) + await otherStarted.promise + }) + expect(await screen.findByTestId('other-pending')).toBeVisible() + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/page' }) + await pageReloadStarted.promise + }) + + await waitFor(() => { + expect(screen.getByTestId('page-pending')).toBeVisible() + expect(screen.queryByTestId('other-pending')).not.toBeInTheDocument() + }) + + await act(async () => { + pageReload.resolve() + await navigation + }) + await act(async () => { + otherLoader.resolve() + await Promise.resolve() + }) + + expect(screen.queryByTestId('page-pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent('reloaded page') +}) + +test('a retained prefix exposes one fresh context chain before descendant pending', async () => { + const retainedStarted = deferred() + const retainedReady = deferred() + const pendingStarted = deferred() + const pendingReady = deferred() + let retainedLoads = 0 + + const rootRoute = createRootRoute({ + beforeLoad: () => ({ rootReady: true }), + component: Outlet, + }) + const aRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'a', + validateSearch: (search: Record): { user: string } => ({ + user: typeof search.user === 'string' ? search.user : 'unknown', + }), + beforeLoad: async ({ search }) => { + if (++retainedLoads > 1) { + retainedStarted.resolve() + await retainedReady.promise + } + return { user: search.user } + }, + component: () => ( +
    +
    {aRoute.useRouteContext().user}
    + +
    + ), + }) + const bRoute = createRoute({ + getParentRoute: () => aRoute, + path: 'b', + component: Outlet, + }) + const cRoute = createRoute({ + getParentRoute: () => bRoute, + path: 'c', + component: Outlet, + }) + const dRoute = createRoute({ + getParentRoute: () => cRoute, + path: 'd', + component: () =>
    Source
    , + }) + const eRoute = createRoute({ + getParentRoute: () => aRoute, + path: 'e', + component: () => ( +
    +
    {eRoute.useRouteContext().user}
    + +
    + ), + }) + const fRoute = createRoute({ + getParentRoute: () => eRoute, + path: 'f', + loader: async () => { + pendingStarted.resolve() + await pendingReady.promise + }, + pendingComponent: () => ( +
    + F pending for {fRoute.useRouteContext().user} +
    + ), + component: Outlet, + }) + const gRoute = createRoute({ + getParentRoute: () => fRoute, + path: 'g', + component: () =>
    G
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + aRoute.addChildren([ + bRoute.addChildren([cRoute.addChildren([dRoute])]), + eRoute.addChildren([fRoute.addChildren([gRoute])]), + ]), + ]), + history: createMemoryHistory({ initialEntries: ['/a/b/c/d?user=Ada'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 0, + }) + + render() + expect(await screen.findByTestId('source')).toBeVisible() + expect(screen.getByTestId('user')).toHaveTextContent('Ada') + + let navigation!: Promise + try { + await act(async () => { + navigation = router.navigate({ + to: '/a/e/f/g', + search: { user: 'Grace' }, + }) + await retainedStarted.promise + }) + + expect(screen.getByTestId('source')).toBeVisible() + expect(screen.getByTestId('user')).toHaveTextContent('Ada') + expect(screen.queryByTestId('f-pending')).not.toBeInTheDocument() + + await act(async () => { + retainedReady.resolve() + await pendingStarted.promise + }) + + expect(await screen.findByTestId('f-pending')).toBeVisible() + expect(screen.getByTestId('user')).toHaveTextContent('Grace') + expect(screen.getByTestId('e-user')).toHaveTextContent('Grace') + expect(screen.getByTestId('f-pending')).toHaveTextContent('Grace') + expect(screen.queryByTestId('source')).not.toBeInTheDocument() + expect(screen.queryByTestId('hidden-g')).not.toBeInTheDocument() + expect(router.state.matches.map((match) => match.routeId)).toContain( + gRoute.id, + ) + } finally { + retainedReady.resolve() + pendingReady.resolve() + await act(async () => { + await Promise.allSettled(navigation ? [navigation] : []) + }) + } +}) + +test.each([false, true])( + 'retained loader and component work does not own the child fallback (parent pending: %s)', + async (parentHasPending) => { + const parentReloadStarted = createControlledPromise() + const parentReload = createControlledPromise() + const parentComponent = createControlledPromise() + const childLoader = createControlledPromise() + let parentLoads = 0 + let parentPreloads = 0 + + const rootRoute = createRootRoute({ component: Outlet }) + const Parent = Object.assign( + () => ( +
    + {parentRoute.useLoaderData()} + +
    + ), + { + preload: () => (++parentPreloads === 1 ? undefined : parentComponent), + }, + ) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'parent', + shouldReload: true, + loader: { + staleReloadMode: 'blocking', + handler: async () => { + if (++parentLoads === 1) { + return 'initial parent' + } + parentReloadStarted.resolve() + await parentReload + return 'reloaded parent' + }, + }, + component: Parent, + ...(parentHasPending + ? { + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () => ( +
    Parent pending
    + ), + } + : {}), + }) + const sourceRoute = createRoute({ + getParentRoute: () => parentRoute, + path: 'source', + component: () =>
    Source
    , + }) + const childOptions = createLazyRoute('/parent/child')({ + pendingComponent: () => ( +
    Child pending
    + ), + component: () =>
    Child
    , + }) + const childLazy = createControlledPromise() + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: 'child', + pendingMs: 0, + pendingMinMs: 0, + loader: () => childLoader, + }).lazy(() => childLazy) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([sourceRoute, childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/source'] }), + }) + + render() + expect(await screen.findByTestId('source')).toBeVisible() + await waitFor(() => expect(router.state.status).toBe('idle')) + + const navigation = router.navigate({ to: '/parent/child' }) + try { + await parentReloadStarted + parentReload.resolve() + await waitFor(() => { + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.isFetching, + ).toBe(false) + }) + + childLazy.resolve(childOptions) + expect(await screen.findByTestId('child-pending')).toBeVisible() + expect(screen.getByTestId('parent-content')).toBeVisible() + expect(screen.queryByTestId('parent-pending')).not.toBeInTheDocument() + expect(screen.queryByTestId('source')).not.toBeInTheDocument() + } finally { + parentReload.resolve() + parentComponent.resolve() + childLazy.resolve(childOptions) + childLoader.resolve() + await navigation + } + + expect(screen.getByTestId('child')).toBeVisible() + }, +) + +test('a failure in the last retained guard suppresses descendant pending', async () => { + const guardStarted = createControlledPromise() + const guardReady = createControlledPromise() + const childReady = createControlledPromise() + let guardLoads = 0 + let childLoads = 0 + + const rootRoute = createRootRoute({ + beforeLoad: () => ({ rootReady: true }), + component: Outlet, + }) + const layoutRoute = createRoute({ + getParentRoute: () => rootRoute, + id: 'layout', + beforeLoad: async () => { + if (++guardLoads > 1) { + guardStarted.resolve() + await guardReady + throw new Error('blocked') + } + }, + component: Outlet, + errorComponent: () =>
    Guard error
    , + }) + const sourceRoute = createRoute({ + getParentRoute: () => layoutRoute, + path: '/source', + component: () =>
    Source
    , + }) + const childRoute = createRoute({ + getParentRoute: () => layoutRoute, + path: '/child', + loader: async () => { + childLoads++ + await childReady + }, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>
    Pending
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + layoutRoute.addChildren([sourceRoute, childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + }) + + render() + expect(await screen.findByTestId('source')).toBeVisible() + await waitFor(() => expect(router.state.status).toBe('idle')) + + const navigation = router.navigate({ to: '/child' }) + try { + await guardStarted + expect(screen.getByTestId('source')).toBeVisible() + expect(screen.queryByTestId('child-pending')).not.toBeInTheDocument() + expect(childLoads).toBe(0) + + guardReady.resolve() + await navigation + expect(await screen.findByTestId('guard-error')).toBeVisible() + expect(screen.queryByTestId('child-pending')).not.toBeInTheDocument() + expect(childLoads).toBe(0) + } finally { + guardReady.resolve() + childReady.resolve() + await navigation + } +}) diff --git a/packages/react-router/tests/issue-8115-context.test.tsx b/packages/react-router/tests/issue-8115-context.test.tsx new file mode 100644 index 0000000000..69399d26c0 --- /dev/null +++ b/packages/react-router/tests/issue-8115-context.test.tsx @@ -0,0 +1,785 @@ +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { hydrateRoot } from 'react-dom/client' +import { afterEach, expect, test, vi } from 'vitest' +import { + Outlet, + RouterProvider, + Scripts, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRootRouteWithContext, + createRoute, + createRouter, + useLocation, +} from '../src' +import { hydrate } from '../src/ssr/client' +import { + RouterServer, + createRequestHandler, + renderRouterToString, +} from '../src/ssr/server' + +declare module '@tanstack/history' { + interface HistoryState { + issue8115Revision?: 'old' | 'new' + } +} + +afterEach(() => { + cleanup() + vi.restoreAllMocks() + delete window.$_TSR + delete (window as Window & { $R?: unknown }).$R + document.body.innerHTML = '' +}) + +test('invalidate merges fresh parent beforeLoad context with cached child context', async () => { + let generation = 0 + let childContextCalls = 0 + + const rootRoute = createRootRoute({ + beforeLoad: () => { + generation++ + return { + parentGeneration: generation, + collision: `parent-${generation}`, + } + }, + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + context: ({ context }) => { + childContextCalls++ + return { + childSnapshotOfParent: context.parentGeneration, + collision: `child-snapshot-${context.parentGeneration}`, + } + }, + component: () => { + const { parentGeneration, childSnapshotOfParent, collision } = + childRoute.useRouteContext() + + return ( +
    +
    {parentGeneration}
    +
    {childSnapshotOfParent}
    +
    {collision}
    +
    + ) + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + + expect(await screen.findByTestId('parent-generation')).toHaveTextContent('1') + expect(screen.getByTestId('child-snapshot')).toHaveTextContent('1') + expect(screen.getByTestId('collision')).toHaveTextContent('child-snapshot-1') + expect(generation).toBe(1) + expect(childContextCalls).toBe(1) + const childMatchId = router.state.matches[1]!.id + + await act(() => router.invalidate()) + + // The fresh parent contribution is merged under the cached child contribution. + expect(router.state.matches[1]!.id).toBe(childMatchId) + expect(generation).toBe(2) + expect(childContextCalls).toBe(1) + expect(screen.getByTestId('parent-generation')).toHaveTextContent('2') + expect(screen.getByTestId('child-snapshot')).toHaveTextContent('1') + expect(screen.getByTestId('collision')).toHaveTextContent('child-snapshot-1') +}) + +test('a same-id child beforeLoad error observes fresh inherited context', async () => { + const childError = new Error('child beforeLoad failed') + let parentGeneration = 0 + let renderedError: unknown + + const rootRoute = createRootRoute({ component: Outlet }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loaderDeps: () => ({ stable: true }), + beforeLoad: () => ({ generation: ++parentGeneration }), + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loaderDeps: () => ({ stable: true }), + beforeLoad: ({ context }) => { + if (context.generation === 2) { + throw childError + } + }, + component: () => ( +
    + {childRoute.useRouteContext().generation} +
    + ), + errorComponent: ({ error }) => { + renderedError = error + const context = childRoute.useRouteContext() + + return ( +
    {context.generation}
    + ) + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + render() + + expect(await screen.findByTestId('child-generation')).toHaveTextContent('1') + await waitFor(() => expect(router.state.status).toBe('idle')) + const initialChildMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )?.id + expect(initialChildMatchId).toBeDefined() + + await act(() => router.invalidate()) + + expect( + await screen.findByTestId('child-error-generation'), + ).toBeInTheDocument() + expect(renderedError).toBe(childError) + expect( + router.state.matches.find((match) => match.routeId === childRoute.id)?.id, + ).toBe(initialChildMatchId) + expect(screen.getByTestId('child-error-generation')).toHaveTextContent('2') +}) + +test('a same-match reload merges new provider context with cached route context', async () => { + type ProviderContext = { + providerValue: string + collision: string + } + + const providerA: ProviderContext = { + providerValue: 'A', + collision: 'provider:A', + } + const providerB: ProviderContext = { + providerValue: 'B', + collision: 'provider:B', + } + const rootRoute = createRootRouteWithContext()() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + context: ({ context }) => ({ + derivedFromProvider: `derived:${context.providerValue}`, + collision: `route-cached:${context.providerValue}`, + }), + component: () => ( +
    +        {JSON.stringify(indexRoute.useRouteContext())}
    +      
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + context: providerA, + }) + + const view = render() + expect(await screen.findByTestId('full-context')).toHaveTextContent( + JSON.stringify({ + providerValue: 'A', + collision: 'route-cached:A', + derivedFromProvider: 'derived:A', + }), + ) + + view.rerender() + await act(() => router.invalidate()) + + expect(screen.getByTestId('full-context')).toHaveTextContent( + JSON.stringify({ + providerValue: 'B', + collision: 'route-cached:A', + derivedFromProvider: 'derived:A', + }), + ) +}) + +test('navigation merges fresh parent context with cached child preload context', async () => { + let parentBeforeLoadRuns = 0 + let childContextRuns = 0 + let childLoaderRuns = 0 + + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: ({ preload }) => { + parentBeforeLoadRuns++ + return { + parentValue: preload ? 'parent-preload' : 'parent-navigation', + } + }, + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + context: ({ context, preload }) => { + childContextRuns++ + return { + childValue: `${preload ? 'child-preload' : 'child-navigation'}:${context.parentValue}`, + } + }, + loader: () => { + childLoaderRuns++ + return 'child data' + }, + preloadStaleTime: Infinity, + component: () => { + const { parentValue, childValue } = childRoute.useRouteContext() + return ( +
    + {JSON.stringify({ parentValue, childValue })} +
    + ) + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + + await act(() => router.preloadRoute({ to: '/parent/child' })) + expect(parentBeforeLoadRuns).toBe(1) + expect(childContextRuns).toBe(1) + expect(childLoaderRuns).toBe(1) + + await act(() => router.navigate({ to: '/parent/child' })) + + expect(await screen.findByTestId('context')).toHaveTextContent( + JSON.stringify({ + parentValue: 'parent-navigation', + childValue: 'child-preload:parent-preload', + }), + ) + expect(parentBeforeLoadRuns).toBe(2) + expect(childContextRuns).toBe(1) + expect(childLoaderRuns).toBe(1) +}) + +test('a cached child context contribution is merged with fresh parent context', async () => { + const rootRoute = createRootRoute({ component: Outlet }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + version: Number(search.version), + }), + loaderDeps: ({ search }) => ({ version: search.version }), + context: ({ deps }) => ({ parentVersion: `version-${deps.version}` }), + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loaderDeps: () => ({ stable: true }), + context: ({ context }) => ({ + childSnapshot: `derived-from-${context.parentVersion}`, + }), + component: () => { + const context = childRoute.useRouteContext() + return ( +
    + Parent: {context.parentVersion}; cached child: {context.childSnapshot} +
    + ) + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ + initialEntries: ['/parent/child?version=1'], + }), + }) + + render() + + expect( + await screen.findByText( + 'Parent: version-1; cached child: derived-from-version-1', + ), + ).toBeInTheDocument() + + const initialParentMatchId = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )?.id + const initialChildMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )?.id + + expect(initialParentMatchId).toBeDefined() + expect(initialChildMatchId).toBeDefined() + + await act(() => + router.navigate({ + to: '/parent/child', + search: { version: 2 }, + }), + ) + + expect( + screen.getByText('Parent: version-2; cached child: derived-from-version-1'), + ).toBeInTheDocument() + + const nextParentMatchId = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )?.id + const nextChildMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )?.id + + expect(nextParentMatchId).not.toBe(initialParentMatchId) + expect(nextChildMatchId).toBe(initialChildMatchId) +}) + +test('#8115: hydration does not render a successful route with missing context when context reconstruction fails', async () => { + const contextError = new Error('client context reconstruction failed') + const clientSuccessRenderValues: Array = [] + let clientContextAttempts = 0 + let serverPhase = true + + const createRouteTree = () => { + const rootRoute = createRootRoute({ + component: () => ( + <> + + + + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + context: (): { locale: string } => { + if (serverPhase) { + return { locale: 'en' } + } + clientContextAttempts++ + throw contextError + }, + component: () => { + const context: { locale?: string } = indexRoute.useRouteContext() + if (!serverPhase) { + clientSuccessRenderValues.push(context.locale) + } + return ( +
    + Locale: {context.locale ?? 'missing'} +
    + ) + }, + errorComponent: ({ error }) => ( +
    + {error instanceof Error ? error.message : String(error)} +
    + ), + }) + + return rootRoute.addChildren([indexRoute]) + } + + const response = await createRequestHandler({ + request: new Request('http://localhost/'), + createRouter: () => + createRouter({ routeTree: createRouteTree(), isServer: true }), + })(({ router, responseHeaders }) => + renderRouterToString({ + router, + responseHeaders, + children: ( + + + + + + + ), + }), + ) + const html = await response.text() + const serverDocument = new DOMParser().parseFromString(html, 'text/html') + + expect(serverDocument.body.textContent).toContain('Locale: en') + const currentScriptSpy = vi.spyOn(document, 'currentScript', 'get') + try { + // These scripts come exclusively from this test's renderRouterToString output. + for (const script of serverDocument.querySelectorAll('script')) { + currentScriptSpy.mockReturnValue(script) + new Function(script.textContent ?? '')() + script.remove() + } + } finally { + currentScriptSpy.mockRestore() + } + expect(window.$_TSR?.router?.matches.at(-1)?.s).toBe('success') + + serverPhase = false + const clientRouter = createRouter({ + routeTree: createRouteTree(), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const container = document.createElement('div') + container.innerHTML = serverDocument.body.innerHTML + document.body.appendChild(container) + const recoverableHydrationErrors: Array = [] + let root: ReturnType | undefined + + try { + await hydrate(clientRouter) + await act(async () => { + root = hydrateRoot(container, , { + onRecoverableError: (error) => { + const messages = [ + error instanceof Error ? error.message : String(error), + error instanceof Error && error.cause instanceof Error + ? error.cause.message + : '', + ] + if ( + error instanceof Error && + messages.some((message) => + /hydration (?:failed|mismatch)|server rendered HTML.*client/i.test( + message, + ), + ) + ) { + recoverableHydrationErrors.push(error) + return + } + throw error + }, + }) + await Promise.resolve() + }) + + await waitFor(() => { + expect( + container.querySelector('[data-testid="route-error"]'), + ).toHaveTextContent(contextError.message) + }) + expect(clientContextAttempts).toBeGreaterThan(0) + expect(container.querySelector('[data-testid="route-success"]')).toBeNull() + expect(clientSuccessRenderValues).not.toContain(undefined) + expect(recoverableHydrationErrors.length).toBeGreaterThan(0) + } finally { + if (root) { + await act(() => root!.unmount()) + } + container.remove() + } +}) + +test('a same-id child retry presents one coherent beforeLoad context generation', async () => { + const childReloadStarted = createControlledPromise() + const childReload = createControlledPromise() + let parentGeneration = 0 + let childLoads = 0 + + const rootRoute = createRootRoute({ component: Outlet }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: () => ({ generation: ++parentGeneration }), + component: () => ( +
    +
    + Parent generation {parentRoute.useRouteContext().generation} +
    + +
    + ), + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: ({ context }) => ({ + inheritedGeneration: context.generation, + }), + loader: async () => { + if (++childLoads > 1) { + childReloadStarted.resolve() + await childReload + } + }, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () => ( +
    + Child generation {childRoute.useRouteContext().inheritedGeneration} +
    + ), + component: () => ( +
    + Child generation {childRoute.useRouteContext().inheritedGeneration} +
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + render() + expect(await screen.findByTestId('parent-generation')).toHaveTextContent( + 'Parent generation 1', + ) + expect(screen.getByTestId('child-generation')).toHaveTextContent( + 'Child generation 1', + ) + await waitFor(() => expect(router.state.status).toBe('idle')) + const initialChildId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )?.id + expect(initialChildId).toBeDefined() + + let invalidation: Promise | undefined + try { + await act(async () => { + invalidation = router.invalidate({ + filter: (match) => + match.routeId === parentRoute.id || match.routeId === childRoute.id, + forcePending: true, + }) + await childReloadStarted + }) + + expect(screen.getByTestId('parent-generation')).toHaveTextContent( + 'Parent generation 2', + ) + expect(screen.getByTestId('child-pending-generation')).toHaveTextContent( + 'Child generation 2', + ) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + status: 'success', + context: { generation: 2 }, + }) + expect( + router.state.matches.find((match) => match.routeId === childRoute.id), + ).toMatchObject({ + id: initialChildId, + status: 'pending', + context: { generation: 2, inheritedGeneration: 2 }, + }) + } finally { + childReload.resolve() + await act(async () => { + await Promise.allSettled(invalidation ? [invalidation] : []) + }) + } +}) + +test('a same-id navigation merges new inherited context with cached route context', async () => { + const history = createMemoryHistory({ initialEntries: ['/'] }) + history.replace('/', { issue8115Revision: 'old' }) + + const rootRoute = createRootRoute({ + beforeLoad: ({ location }) => ({ + inheritedRevision: location.state.issue8115Revision, + }), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + context: ({ location }) => ({ + selfRevision: location.state.issue8115Revision, + }), + component: IndexComponent, + }) + function IndexComponent() { + const location = useLocation() + const context = indexRoute.useRouteContext() + const matchId = indexRoute.useMatch({ select: (match) => match.id }) + const navigate = indexRoute.useNavigate() + + return ( + <> + {matchId} + + location: {location.state.issue8115Revision}; inherited:{' '} + {context.inheritedRevision}; self: {context.selfRevision} + + + + ) + } + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render() + + expect(await screen.findByTestId('snapshot')).toHaveTextContent( + 'location: old; inherited: old; self: old', + ) + const initialMatchId = screen.getByTestId('match-id').textContent + + fireEvent.click(screen.getByRole('button', { name: 'Update state' })) + + await waitFor(() => { + expect(screen.getByTestId('match-id').textContent).toBe(initialMatchId) + expect(screen.getByTestId('snapshot')).toHaveTextContent( + 'location: new; inherited: new; self: old', + ) + }) +}) + +test('#8115: a successful root never renders without its context while a child is pending on cold load', async () => { + let resolveChildLoader!: () => void + const childLoader = new Promise((resolve) => { + resolveChildLoader = resolve + }) + const rootRenderValues: Array = [] + + const rootRoute = createRootRoute({ + context: () => ({ locale: 'en' }), + component: () => { + const locale = rootRoute.useRouteContext().locale + rootRenderValues.push(locale) + + return ( +
    +

    Locale: {locale ?? 'missing'}

    + +
    + ) + }, + }) + const childRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: () => childLoader, + pendingMs: 0, + pendingComponent: () =>

    Loading child

    , + component: () =>

    Child content

    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + + try { + expect(await screen.findByRole('status')).toHaveTextContent('Loading child') + expect(screen.getByTestId('root-locale')).toHaveTextContent('Locale: en') + expect(rootRenderValues.length).toBeGreaterThan(0) + expect(rootRenderValues.every((locale) => locale === 'en')).toBe(true) + } finally { + await act(async () => { + resolveChildLoader() + await childLoader + }) + } +}) + +test('a same-id search navigation merges fresh inherited context with cached route context', async () => { + const rootRoute = createRootRoute({ component: Outlet }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + revision: typeof search.revision === 'string' ? search.revision : 'one', + }), + loaderDeps: ({ search }) => ({ revision: search.revision }), + context: ({ deps }) => ({ inheritedRevision: deps.revision }), + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loaderDeps: () => ({}), + context: ({ context, location }) => ({ + cachedSelfRevision: `${context.inheritedRevision}:${String((location.search as any).revision)}`, + }), + component: () => { + const context = childRoute.useRouteContext() + const search = childRoute.useSearch() + const matchId = childRoute.useMatch({ select: (match) => match.id }) + + return ( + <> +
    {matchId}
    +
    {search.revision}
    +
    {context.inheritedRevision}
    +
    + {context.cachedSelfRevision} +
    + + ) + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ + initialEntries: ['/parent/child?revision=one'], + }), + }) + + render() + + expect(await screen.findByTestId('current-search')).toHaveTextContent('one') + expect(screen.getByTestId('inherited-context')).toHaveTextContent('one') + expect(screen.getByTestId('cached-self-context')).toHaveTextContent('one:one') + const initialMatchId = screen.getByTestId('match-id').textContent + + await act(() => + router.navigate({ + to: '/parent/child', + search: { revision: 'two' }, + }), + ) + + expect(await screen.findByTestId('current-search')).toHaveTextContent('two') + expect(screen.getByTestId('match-id').textContent).toBe(initialMatchId) + expect(screen.getByTestId('inherited-context')).toHaveTextContent('two') + expect(screen.getByTestId('cached-self-context')).toHaveTextContent('one:one') +}) diff --git a/packages/react-router/tests/issue-8128-context.test.tsx b/packages/react-router/tests/issue-8128-context.test.tsx new file mode 100644 index 0000000000..f615bba8d9 --- /dev/null +++ b/packages/react-router/tests/issue-8128-context.test.tsx @@ -0,0 +1,116 @@ +import { act, cleanup, render, screen } from '@testing-library/react' +import { expect, onTestFinished, test, vi } from 'vitest' +import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' +import { hydrate } from '../src/ssr/client' +import type { DehydratedMatch } from '@tanstack/router-core/ssr/client' + +test('#8128: leaving a hydrated root not-found page preserves beforeLoad context', async () => { + const rootRenders: Array = [] + + vi.useFakeTimers() + onTestFinished(async () => { + cleanup() + delete window.$_TSR + delete (window as Window & { $R?: unknown }).$R + vi.useRealTimers() + }) + + const rootRoute = createRootRoute({ + beforeLoad: async () => { + await new Promise((resolve) => setTimeout(resolve, 250)) + return { locale: 'en' } + }, + component: () => { + const context = rootRoute.useRouteContext() + rootRenders.push(context.locale) + + return ( + <> + + Locale: {context.locale ?? 'missing'} + + + + ) + }, + notFoundComponent: () =>
    Not found
    , + }) + const dashboardRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/dashboard', + component: () =>
    Dashboard
    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([dashboardRoute]), + history: createMemoryHistory({ + initialEntries: ['/any-not-found-url'], + }), + defaultPendingComponent: () =>
    Loading
    , + defaultPendingMs: 150, + defaultPendingMinMs: 0, + }) + const rootMatch = router.matchRoutes(router.latestLocation)[0]! + // Model the server bootstrap for a hydrated root-level not-found. + const dehydratedMatch: DehydratedMatch & { b: Record } = { + i: dehydrateSsrMatchId(rootMatch.id), + b: { locale: 'en' }, + u: Date.now(), + s: 'success', + ssr: true, + g: true, + } + window.$_TSR = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: [dehydratedMatch], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + render() + + expect(router.state.matches[0]).toMatchObject({ + status: 'success', + _notFound: true, + context: { locale: 'en' }, + }) + expect(screen.getByText('Not found')).toBeInTheDocument() + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/dashboard' }) + await vi.advanceTimersByTimeAsync(150) + }) + + expect(router.state.matches[0]).toMatchObject({ + status: 'success', + _notFound: true, + context: { locale: 'en' }, + }) + expect(screen.getByTestId('root-locale')).toHaveTextContent('Locale: en') + expect(screen.getByText('Not found')).toBeInTheDocument() + expect(screen.queryByText('Loading')).not.toBeInTheDocument() + expect(rootRenders).not.toContain(undefined) + + await act(async () => { + await vi.advanceTimersByTimeAsync(100) + await navigation + }) + expect(screen.getByText('Dashboard')).toBeInTheDocument() +}) diff --git a/packages/react-router/tests/issue-8128-source-notfound-retention-boundary.test.tsx b/packages/react-router/tests/issue-8128-source-notfound-retention-boundary.test.tsx new file mode 100644 index 0000000000..58c3d8cbc7 --- /dev/null +++ b/packages/react-router/tests/issue-8128-source-notfound-retention-boundary.test.tsx @@ -0,0 +1,305 @@ +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, onTestFinished, test } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +function createGate() { + let resolve!: () => void + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise + }) + + return { promise, resolve } +} + +afterEach(cleanup) + +test('#8128: returning from a layout-owned fuzzy not-found retains only through its owner', async () => { + const beforeLoadStarted = createGate() + const beforeLoadGate = createGate() + onTestFinished(() => beforeLoadGate.resolve()) + let gateNextBeforeLoad = false + + const rootRoute = createRootRoute({ component: Outlet }) + const agentsLayoutRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_agents', + component: () => ( +
    +

    Agent operations

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

    Agent page not found

    , + }) + const agentsRoute = createRoute({ + getParentRoute: () => agentsLayoutRoute, + path: '/agents', + beforeLoad: async () => { + if (gateNextBeforeLoad) { + gateNextBeforeLoad = false + beforeLoadStarted.resolve() + await beforeLoadGate.promise + } + }, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>

    Loading agents

    , + component: () =>

    Agents directory

    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + agentsLayoutRoute.addChildren([agentsRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/agents'] }), + }) + + let navigation: Promise | undefined + try { + render() + + expect(await screen.findByText('Agents directory')).toBeVisible() + expect( + screen.getByRole('heading', { name: 'Agent operations' }), + ).toBeVisible() + + await act(async () => { + navigation = router.navigate({ to: '/agents/missing' } as any) + await navigation + }) + + expect( + screen.getByRole('heading', { name: 'Agent operations' }), + ).toBeVisible() + expect(screen.getByText('Agent page not found')).toBeVisible() + expect(screen.queryByText('Agents directory')).not.toBeInTheDocument() + + gateNextBeforeLoad = true + await act(async () => { + navigation = router.navigate({ to: '/agents' }) + await beforeLoadStarted.promise + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + + expect( + screen.getByRole('heading', { name: 'Agent operations' }), + ).toBeVisible() + expect(screen.queryByText('Agent page not found')).not.toBeInTheDocument() + expect(screen.getByRole('status')).toHaveTextContent('Loading agents') + + await act(async () => { + beforeLoadGate.resolve() + await navigation + }) + + expect(screen.getByText('Agents directory')).toBeVisible() + expect(screen.queryByRole('status')).not.toBeInTheDocument() + } finally { + await act(async () => { + await Promise.allSettled(navigation ? [navigation] : []) + }) + } +}) + +test('#8128: retention stops at the earlier committed boundary when the presented boundary is deeper', async () => { + const groupsBeforeLoadStarted = createGate() + const groupsBeforeLoadGate = createGate() + const workspaceReloadStarted = createGate() + const workspaceReloadGate = createGate() + const agentsReloadStarted = createGate() + const agentsReloadGate = createGate() + let agentsLoaderCalls = 0 + + const rootRoute = createRootRoute({ component: Outlet }) + const workspaceLayoutRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_workspace', + component: () => ( +
    +

    Workspace

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

    Workspace page not found

    , + beforeLoad: ({ location }) => { + if ( + location.pathname === '/agents' && + (location.search as { reload?: number }).reload === 1 + ) { + workspaceReloadStarted.resolve() + return workspaceReloadGate.promise + } + return undefined + }, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>

    Loading workspace

    , + }) + const agentsRoute = createRoute({ + getParentRoute: () => workspaceLayoutRoute, + path: '/agents', + validateSearch: (search: Record) => ({ + reload: Number(search.reload ?? 0), + }), + shouldReload: ({ location }) => + (location.search as { reload: number }).reload === 1, + loader: { + staleReloadMode: 'blocking', + handler: async () => { + agentsLoaderCalls++ + if (agentsLoaderCalls === 2) { + agentsReloadStarted.resolve() + await agentsReloadGate.promise + } + return { generation: agentsLoaderCalls } + }, + }, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>

    Loading agents destination

    , + component: () => ( +
    +

    Agents area

    + +
    + ), + }) + const groupsRoute = createRoute({ + getParentRoute: () => agentsRoute, + path: 'groups', + beforeLoad: async () => { + groupsBeforeLoadStarted.resolve() + await groupsBeforeLoadGate.promise + }, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>

    Loading groups

    , + component: Outlet, + }) + const groupsBoundaryRoute = createRoute({ + getParentRoute: () => groupsRoute, + id: '_groups', + component: Outlet, + notFoundComponent: () =>

    Group page not found

    , + }) + const knownGroupRoute = createRoute({ + getParentRoute: () => groupsBoundaryRoute, + path: 'known', + component: () =>

    Known group

    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + workspaceLayoutRoute.addChildren([ + agentsRoute.addChildren([ + groupsRoute.addChildren([ + groupsBoundaryRoute.addChildren([knownGroupRoute]), + ]), + ]), + ]), + ]), + history: createMemoryHistory({ initialEntries: ['/agents'] }), + }) + + let deeperNavigation: Promise | undefined + let agentsNavigation: Promise | undefined + try { + render() + expect( + await screen.findByRole('heading', { name: 'Agents area' }), + ).toBeVisible() + + await act(async () => { + await router.navigate({ to: '/agents/missing' } as any) + }) + + expect(screen.getByText('Workspace page not found')).toBeVisible() + const committedBoundaryIndex = router.state.matches.findIndex( + (match) => match._notFound, + ) + expect(committedBoundaryIndex).toBeGreaterThanOrEqual(0) + expect(router.state.matches[committedBoundaryIndex]?.routeId).toBe( + workspaceLayoutRoute.id, + ) + expect( + router.state.matches.find((match) => match.routeId === agentsRoute.id), + ).toMatchObject({ status: 'success' }) + + await act(async () => { + deeperNavigation = router.navigate({ + to: '/agents/groups/known/missing', + } as any) + await groupsBeforeLoadStarted.promise + }) + + expect(await screen.findByText('Loading groups')).toBeVisible() + const presentedBoundaryIndex = router.state.matches.findIndex( + (match) => match._notFound, + ) + expect(presentedBoundaryIndex).toBeGreaterThan(committedBoundaryIndex) + expect(router.state.matches[presentedBoundaryIndex]?.routeId).toBe( + groupsBoundaryRoute.id, + ) + expect( + router.state.matches.find((match) => match.routeId === agentsRoute.id), + ).toMatchObject({ status: 'success' }) + expect( + router.state.matches.find((match) => match.routeId === groupsRoute.id), + ).toMatchObject({ status: 'pending' }) + + await act(async () => { + agentsNavigation = router.navigate({ + to: '/agents', + search: { reload: 1 }, + }) + await workspaceReloadStarted.promise + }) + + expect(screen.getByText('Loading groups')).toBeVisible() + expect(screen.queryByText('Loading workspace')).not.toBeInTheDocument() + expect(screen.getByRole('heading', { name: 'Workspace' })).toBeVisible() + expect(router.state.matches[presentedBoundaryIndex]?.routeId).toBe( + groupsBoundaryRoute.id, + ) + + await act(async () => { + workspaceReloadGate.resolve() + await agentsReloadStarted.promise + }) + + expect(await screen.findByText('Loading agents destination')).toBeVisible() + expect( + router.state.matches.find((match) => match.routeId === agentsRoute.id), + ).toMatchObject({ status: 'pending' }) + + await act(async () => { + agentsReloadGate.resolve() + await agentsNavigation + }) + + expect(screen.queryByRole('status')).not.toBeInTheDocument() + expect(screen.getByRole('heading', { name: 'Agents area' })).toBeVisible() + expect(router.state.location).toMatchObject({ + pathname: '/agents', + search: { reload: 1 }, + }) + expect(router.state.matches.some((match) => match._notFound)).toBe(false) + expect(agentsLoaderCalls).toBe(2) + } finally { + groupsBeforeLoadGate.resolve() + workspaceReloadGate.resolve() + agentsReloadGate.resolve() + await act(async () => { + await Promise.allSettled( + [deeperNavigation, agentsNavigation].filter( + (navigation): navigation is Promise => navigation !== undefined, + ), + ) + }) + } +}) diff --git a/packages/react-router/tests/jest-dom.setup.ts b/packages/react-router/tests/jest-dom.setup.ts new file mode 100644 index 0000000000..8f7cbf15be --- /dev/null +++ b/packages/react-router/tests/jest-dom.setup.ts @@ -0,0 +1,18 @@ +import * as jestDomMatchers from '@testing-library/jest-dom/matchers' +import { expect } from 'vitest' +import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' + +// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged +// and released, and go back to `import '@testing-library/jest-dom/vitest'`. +// That entry imports `vitest` from its own install location, which can resolve +// a different Vitest copy than the one running these tests, and its types +// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. +// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting +// `@testing-library/jest-dom/vitest` when a setup file path contains it. +expect.extend(jestDomMatchers) + +declare module 'vitest' { + // Type parameter names must match Vitest's declaration for the interfaces to merge. + // eslint-disable-next-line @typescript-eslint/naming-convention + interface Matchers extends TestingLibraryMatchers {} +} diff --git a/packages/react-router/tests/lazy/error.tsx b/packages/react-router/tests/lazy/error.tsx new file mode 100644 index 0000000000..271f6a058e --- /dev/null +++ b/packages/react-router/tests/lazy/error.tsx @@ -0,0 +1,12 @@ +import { createLazyRoute } from '../../src' + +export function Route(id: string) { + return createLazyRoute(id)({ + component: () =>
    About route content
    , + errorComponent: ({ error }) => ( +
    + Lazy Error: {error instanceof Error ? error.message : String(error)} +
    + ), + }) +} diff --git a/packages/react-router/tests/lazy/normal.tsx b/packages/react-router/tests/lazy/normal.tsx index 1addf96c74..675deb83f3 100644 --- a/packages/react-router/tests/lazy/normal.tsx +++ b/packages/react-router/tests/lazy/normal.tsx @@ -2,7 +2,7 @@ import { createLazyFileRoute, createLazyRoute } from '../../src' export function Route(id: string) { return createLazyRoute(id)({ - component: () =>

    I'm a normal route

    , + component: () =>

    I'm a normal route

    , }) } diff --git a/packages/react-router/tests/link-departing-scope.test.tsx b/packages/react-router/tests/link-departing-scope.test.tsx new file mode 100644 index 0000000000..04d0c3f32d --- /dev/null +++ b/packages/react-router/tests/link-departing-scope.test.tsx @@ -0,0 +1,1122 @@ +import { setFlagsFromString } from 'node:v8' +import { runInNewContext } from 'node:vm' +import React from 'react' +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouteMask, + createRouter, + redirect, +} from '../src' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +type Deferred = { + promise: Promise + resolve: () => void +} + +function deferred(): Deferred { + let resolve!: () => void + const promise = new Promise((r) => (resolve = r)) + return { promise, resolve } +} + +type Gates = Partial> + +function setup({ + initial = '/a', + strict = false, + bAfterGate, + beforeRender, +}: { + initial?: string + strict?: boolean + bAfterGate?: () => void + beforeRender?: (router: any) => void +} = {}) { + const gates: Gates = {} + const counts = { + aUpdater: 0, + aRenders: 0, + goneUpdater: 0, + suspendedUpdater: 0, + } + // The `x` dependency of every `/a` load, preloads included. + const aLoads: Array = [] + // The `x` of every location the `a-next` link derives from. + const nextFrom: Array = [] + const controls: { + setHash?: (hash: string | undefined) => void + setExtra?: (extra: boolean) => void + setGone?: (gone: boolean) => void + setRenderPreload?: (renderPreload: boolean) => void + } = {} + let suspendGate: Deferred | undefined + + function Suspender() { + if (suspendGate) { + throw suspendGate.promise + } + return null + } + + const root = createRootRoute({ + component: () => ( + <> + + root b + + + + ), + }) + const layout = createRoute({ + getParentRoute: () => root, + id: '_layout', + component: () => ( + <> + + layout b + + + + ), + }) + function AComponent() { + const [hash, setHash] = React.useState(undefined) + const [extra, setExtra] = React.useState(false) + const [gone, setGone] = React.useState(false) + const [renderPreload, setRenderPreload] = React.useState(false) + controls.setHash = setHash + controls.setExtra = setExtra + controls.setGone = setGone + controls.setRenderPreload = setRenderPreload + return ( + <> +

    A page

    + { + counts.aUpdater++ + return prev + }} + > + {() => { + counts.aRenders++ + return 'a self' + }} + + + a dot + + { + nextFrom.push(prev.x) + return { x: `${prev.x}-next` } + }} + preload="intent" + preloadDelay={0} + data-testid="a-next" + > + a next + + {renderPreload ? ( + ({ x: `${prev.x}-render` })} + preload="render" + data-testid="a-render" + > + a render + + ) : null} + {extra ? ( + prev} data-testid="a-extra"> + a extra + + ) : null} + {gone ? null : ( + { + counts.goneUpdater++ + return prev + }} + > + a gone + + )} + suspended}> + { + counts.suspendedUpdater++ + return prev + }} + > + a suspended + + + + + ) + } + const a = createRoute({ + getParentRoute: () => layout, + path: '/a', + loaderDeps: ({ search }: { search: any }) => ({ x: search.x }), + loader: ({ deps }: { deps: { x: unknown } }) => { + aLoads.push(deps.x) + return gates.a?.promise + }, + component: AComponent, + }) + const b = createRoute({ + getParentRoute: () => layout, + path: '/b', + loader: async () => { + await gates.b?.promise + bAfterGate?.() + }, + component: () =>

    B page

    , + }) + const c = createRoute({ + getParentRoute: () => root, + path: '/c', + component: () =>

    C page

    , + }) + const items = createRoute({ + getParentRoute: () => root, + path: '/items/$id', + loader: () => gates.items?.promise, + component: () => ( + <> +

    Items page

    + + item 1 + + + item 2 + + + ), + }) + + const router = createRouter({ + routeTree: root.addChildren([layout.addChildren([a, b]), c, items]), + history: createMemoryHistory({ initialEntries: [initial] }), + }) + + beforeRender?.(router) + const app = + render(strict ? {app} : app) + + const link = (id: string) => screen.getByTestId(id) + const isActive = (id: string) => + link(id).getAttribute('aria-current') === 'page' + const href = (id: string) => link(id).getAttribute('href') + + async function start(options: any) { + await act(async () => { + void router.navigate(options) + await Promise.resolve() + }) + } + + async function settle() { + await waitFor(() => expect(router.state.status).toBe('idle')) + } + + async function release(name: keyof Gates) { + const gate = gates[name]! + gates[name] = undefined + await act(async () => { + gate.resolve() + await gate.promise + }) + } + + return { + router, + gates, + counts, + aLoads, + nextFrom, + controls, + link, + isActive, + href, + start, + settle, + release, + setSuspendGate: (gate: Deferred | undefined) => (suspendGate = gate), + } +} + +describe('links in a departing match', () => { + test('skip work at navigation start while staying links update urgently', async () => { + const t = setup() + await screen.findByText('A page') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(false) + expect(t.isActive('layout-b')).toBe(false) + + const updater = t.counts.aUpdater + const renders = t.counts.aRenders + t.gates.b = deferred() + await t.start({ to: '/b' }) + + expect(t.router.state.status).toBe('pending') + expect(t.router.state.location.pathname).toBe('/b') + expect(screen.getByText('A page')).toBeInTheDocument() + // Staying root and layout links update while the loader is pending. + expect(t.isActive('root-b')).toBe(true) + expect(t.isActive('layout-b')).toBe(true) + // The departing route's links do no work. + expect(t.counts.aUpdater).toBe(updater) + expect(t.counts.aRenders).toBe(renders) + expect(t.isActive('a-self')).toBe(true) + + await t.release('b') + await screen.findByText('B page') + expect(t.isActive('root-b')).toBe(true) + expect(t.router.state.status).toBe('idle') + }) + + test('staying route with changed params updates its links while pending', async () => { + const t = setup({ initial: '/items/1' }) + await screen.findByText('Items page') + expect(t.isActive('item-1')).toBe(true) + expect(t.isActive('item-2')).toBe(false) + + t.gates.items = deferred() + await t.start({ to: '/items/$id', params: { id: '2' } }) + expect(t.router.state.status).toBe('pending') + expect(t.isActive('item-1')).toBe(false) + expect(t.isActive('item-2')).toBe(true) + + await t.release('items') + expect(t.router.state.status).toBe('idle') + expect(t.isActive('item-2')).toBe(true) + }) + + test('a pending departure redirected back to the owner ends consistent', async () => { + const t = setup({ + bAfterGate: () => { + throw redirect({ to: '/a', search: { x: 'back' } } as any) + }, + }) + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + expect(t.isActive('a-self')).toBe(true) + expect(t.href('a-self')).toBe('/a') + + await t.release('b') + expect(t.router.state.status).toBe('idle') + expect(t.router.state.location.href).toBe('/a?x=back') + expect(screen.getByText('A page')).toBeInTheDocument() + expect(t.href('a-self')).toBe('/a?x=back') + expect(t.isActive('a-self')).toBe(true) + expect(t.href('a-dot')).toBe('/a') + expect(t.isActive('root-b')).toBe(false) + }) + + test('a pending departure superseded by a location that keeps the owner ends consistent', async () => { + const t = setup() + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + const updater = t.counts.aUpdater + await t.start({ to: '/a', search: { x: 'two' } }) + expect(t.counts.aUpdater).toBeGreaterThan(updater) + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(false) + t.gates.b.resolve() + await t.settle() + expect(t.router.state.status).toBe('idle') + expect(t.router.state.location.href).toBe('/a?x=two') + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('a-self')).toBe(true) + }) + + test('links mounting or changing in a departing match build from its held location', async () => { + const t = setup() + await screen.findByText('A page') + expect(t.href('a-dot')).toBe('/a') + t.gates.b = deferred() + await t.start({ to: '/b' }) + + act(() => { + t.controls.setHash!('h') + t.controls.setExtra!(true) + }) + // Both build from the location the rest of the match still presents. + expect(t.href('a-dot')).toBe('/a#h') + expect(t.href('a-extra')).toBe('/a') + expect(t.isActive('a-self')).toBe(true) + + await t.start({ to: '/a', search: { x: 'one' } }) + expect(t.href('a-dot')).toBe('/a#h') + expect(t.href('a-extra')).toBe('/a?x=one') + expect(t.href('a-self')).toBe('/a?x=one') + t.gates.b.resolve() + await t.settle() + expect(t.href('a-extra')).toBe('/a?x=one') + expect(t.isActive('a-extra')).toBe(true) + }) + + test('a pending navigation within the owner, then a departure, then back', async () => { + const t = setup() + await screen.findByText('A page') + + t.gates.a = deferred() + const firstA = t.gates.a + await t.start({ to: '/a', search: { x: 'one' } }) + expect(t.router.state.status).toBe('pending') + // Staying: updates while the owner's own loader is pending. + expect(t.href('a-self')).toBe('/a?x=one') + + t.gates.b = deferred() + const updater = t.counts.aUpdater + const renders = t.counts.aRenders + await t.start({ to: '/b' }) + expect(t.counts.aUpdater).toBe(updater) + expect(t.counts.aRenders).toBe(renders) + expect(t.href('a-self')).toBe('/a?x=one') + expect(t.isActive('root-b')).toBe(true) + + await t.start({ to: '/a', search: { x: 'two' } }) + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('root-b')).toBe(false) + + firstA.resolve() + t.gates.b.resolve() + await t.settle() + expect(t.router.state.status).toBe('idle') + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('a-self')).toBe(true) + }) + + test('a departing link unmounted while pending does no further work', async () => { + const error = vi.spyOn(console, 'error') + const warn = vi.spyOn(console, 'warn') + const t = setup() + await screen.findByText('A page') + t.gates.b = deferred() + const gone = t.counts.goneUpdater + await t.start({ to: '/b' }) + act(() => { + t.controls.setGone!(true) + }) + expect(screen.queryByTestId('a-gone')).toBeNull() + await t.release('b') + await screen.findByText('B page') + expect(t.counts.goneUpdater).toBe(gone) + expect(error).not.toHaveBeenCalled() + expect(warn).not.toHaveBeenCalled() + }) + + test('an abandoned suspended link render keeps links consistent', async () => { + const t = setup() + await screen.findByText('A page') + const gate = deferred() + t.setSuspendGate(gate) + // Re-render A so the boundary suspends with its link rendered but not committed. + act(() => { + t.controls.setHash!('s') + }) + t.setSuspendGate(undefined) + await act(async () => { + gate.resolve() + await gate.promise + }) + expect(t.href('a-suspended')).toBe('/a') + + await t.start({ to: '/a', search: { x: 'one' } }) + await t.settle() + expect(t.href('a-suspended')).toBe('/a?x=one') + + t.gates.b = deferred() + const suspended = t.counts.suspendedUpdater + await t.start({ to: '/b' }) + expect(t.counts.suspendedUpdater).toBe(suspended) + await t.release('b') + await screen.findByText('B page') + }) + + test('StrictMode double mounting keeps holding and updating', async () => { + const t = setup({ strict: true }) + await screen.findByText('A page') + t.gates.b = deferred() + const updater = t.counts.aUpdater + await t.start({ to: '/b' }) + expect(t.counts.aUpdater).toBe(updater) + expect(t.isActive('root-b')).toBe(true) + await t.start({ to: '/a', search: { x: 's' } }) + expect(t.href('a-self')).toBe('/a?x=s') + t.gates.b.resolve() + await t.settle() + expect(t.href('a-self')).toBe('/a?x=s') + expect(t.isActive('root-b')).toBe(false) + }) + + test.each([ + ['a-dot', '/a'], + ['a-next', '/a?x=one-next'], + ])( + 'clicking held link %s navigates to the href it displays', + async (id, displayed) => { + const t = setup({ initial: '/a?x=one' }) + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + expect(t.router.state.status).toBe('pending') + expect(t.href(id)).toBe(displayed) + + await act(async () => { + fireEvent.click(t.link(id)) + await Promise.resolve() + }) + expect(t.router.latestLocation.href).toBe(displayed) + t.gates.b.resolve() + await t.settle() + expect(t.router.state.location.href).toBe(displayed) + expect(screen.getByText('A page')).toBeInTheDocument() + }, + ) + + test.each(['mouseEnter', 'focus', 'touchStart'] as const)( + 'a %s preload of a held link loads the location it displays', + async (event) => { + const t = setup({ initial: '/a?x=one' }) + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + expect(t.href('a-next')).toBe('/a?x=one-next') + t.aLoads.length = 0 + + await act(async () => { + fireEvent[event](t.link('a-next')) + await Promise.resolve() + }) + expect(t.aLoads).toEqual(['one-next']) + await t.release('b') + await screen.findByText('B page') + }, + ) + + test('a render preload of a link mounting in a departing match loads the location it displays', async () => { + const t = setup({ initial: '/a?x=one' }) + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + t.aLoads.length = 0 + + await act(async () => { + t.controls.setRenderPreload!(true) + await Promise.resolve() + }) + expect(t.href('a-render')).toBe('/a?x=one-render') + expect(t.aLoads).toEqual(['one-render']) + await t.release('b') + await screen.findByText('B page') + }) + + test('staying links click and preload from the live location', async () => { + const t = setup({ initial: '/a?x=one' }) + await screen.findByText('A page') + t.gates.a = deferred() + await t.start({ to: '/a', search: { x: 'two' } }) + expect(t.router.state.status).toBe('pending') + expect(t.href('a-next')).toBe('/a?x=two-next') + t.aLoads.length = 0 + + await act(async () => { + fireEvent.mouseEnter(t.link('a-next')) + await Promise.resolve() + }) + expect(t.aLoads).toEqual(['two-next']) + await act(async () => { + fireEvent.click(t.link('a-next')) + await Promise.resolve() + }) + expect(t.router.latestLocation.href).toBe('/a?x=two-next') + await t.release('a') + await t.settle() + expect(t.router.state.location.href).toBe('/a?x=two-next') + expect(t.href('a-next')).toBe('/a?x=two-next-next') + }) + + test('a revisited route starts with fresh links, also ones mounting during its next departure', async () => { + const t = setup({ initial: '/a?x=one' }) + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + expect(t.href('a-next')).toBe('/a?x=one-next') + await t.release('b') + await screen.findByText('B page') + await t.settle() + + t.nextFrom.length = 0 + await act(() => t.router.navigate({ to: '/a', search: { x: 'two' } })) + await screen.findByText('A page') + await t.settle() + // The remounted links never derive from the previous visit's location. + expect(t.nextFrom).not.toContain('one') + expect(t.href('a-next')).toBe('/a?x=two-next') + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(false) + + // B is cached now: depart to a route that has not loaded yet. + t.gates.items = deferred() + const updater = t.counts.aUpdater + await t.start({ to: '/items/$id', params: { id: '1' } }) + expect(t.router.state.status).toBe('pending') + expect(t.counts.aUpdater).toBe(updater) + act(() => { + t.controls.setExtra!(true) + }) + // The new link holds this visit's location, not the previous visit's. + expect(t.href('a-extra')).toBe('/a?x=two') + expect(t.href('a-next')).toBe('/a?x=two-next') + expect(t.isActive('root-b')).toBe(false) + + await act(async () => { + fireEvent.click(t.link('a-extra')) + await Promise.resolve() + }) + expect(t.router.latestLocation.href).toBe('/a?x=two') + t.gates.items.resolve() + await t.settle() + expect(t.router.state.location.href).toBe('/a?x=two') + expect(t.isActive('a-extra')).toBe(true) + expect(t.href('a-next')).toBe('/a?x=two-next') + }) + + test('a document redirect from the destination does not break later navigations', async () => { + // jsdom reports the attempted document navigation as not implemented. + const t = setup({ + bAfterGate: () => { + throw redirect({ to: '/c', reloadDocument: true }) + }, + }) + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + await t.release('b') + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + + await act(() => t.router.navigate({ to: '/a', search: { x: 'two' } })) + await t.settle() + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(false) + }) + + test('a departure superseded by a history traversal back to the owner updates its links', async () => { + const t = setup({ initial: '/a?x=one' }) + await screen.findByText('A page') + await act(() => t.router.navigate({ to: '/a', search: { x: 'two' } })) + await t.settle() + expect(t.href('a-self')).toBe('/a?x=two') + + t.gates.b = deferred() + const updater = t.counts.aUpdater + await t.start({ to: '/b' }) + expect(t.counts.aUpdater).toBe(updater) + await act(async () => { + t.router.history.go(-2) + await Promise.resolve() + }) + await t.settle() + expect(t.router.state.location.href).toBe('/a?x=one') + expect(t.href('a-self')).toBe('/a?x=one') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(false) + t.gates.b.resolve() + await act(async () => { + await t.gates.b?.promise + }) + expect(screen.getByText('A page')).toBeInTheDocument() + expect(t.href('a-self')).toBe('/a?x=one') + }) + + test('invalidating a pending departure keeps holding until it commits', async () => { + const t = setup() + await screen.findByText('A page') + t.gates.b = deferred() + const updater = t.counts.aUpdater + const renders = t.counts.aRenders + await t.start({ to: '/b' }) + await act(async () => { + void t.router.invalidate() + await Promise.resolve() + }) + expect(t.router.state.status).toBe('pending') + expect(t.router.state.location.pathname).toBe('/b') + expect(t.counts.aUpdater).toBe(updater) + expect(t.counts.aRenders).toBe(renders) + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(true) + await t.release('b') + await screen.findByText('B page') + expect(t.counts.aUpdater).toBe(updater) + }) + + test('a departure redirected or superseded to another departing location does no work', async () => { + const t = setup({ + bAfterGate: () => { + throw redirect({ to: '/c' }) + }, + }) + await screen.findByText('A page') + const updater = t.counts.aUpdater + const renders = t.counts.aRenders + t.gates.b = deferred() + await t.start({ to: '/b' }) + t.gates.items = deferred() + await t.start({ to: '/items/$id', params: { id: '1' } }) + // B redirects to C after being superseded; neither keeps A. + await t.release('b') + expect(t.counts.aUpdater).toBe(updater) + expect(t.counts.aRenders).toBe(renders) + await t.release('items') + await screen.findByText('Items page') + expect(t.router.state.location.pathname).toBe('/items/1') + + await act(() => t.router.navigate({ to: '/a' })) + await screen.findByText('A page') + const again = t.counts.aUpdater + t.gates.b = deferred() + await t.start({ to: '/b' }) + await t.release('b') + await screen.findByText('C page') + expect(t.counts.aUpdater).toBe(again) + }) + + test('a view transition callback that throws does not break later navigations', async () => { + vi.stubGlobal('CSS', { supports: () => true }) + ;(document as any).startViewTransition = (update: () => unknown) => { + update() + return { + updateCallbackDone: Promise.resolve(), + finished: Promise.resolve(), + } + } + const failures: Array = [] + const t = setup({ + // The history listener's load rejects with the callback's error. Record + // it instead of leaving it unhandled. + beforeRender: (router) => { + const load = router.load + router.load = (opts: any) => + load(opts).catch((error: unknown) => failures.push(error)) + }, + }) + await screen.findByText('A page') + await t.start({ + to: '/b', + viewTransition: { + types: () => { + throw new Error('types failed') + }, + }, + }) + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + // The failed transaction leaves the router pending on the destination + // with the previous page displayed, without a newer publication. + expect(failures).toHaveLength(1) + expect(t.router.state.status).toBe('pending') + expect(t.router.state.location.pathname).toBe('/b') + expect(screen.getByText('A page')).toBeInTheDocument() + delete (document as any).startViewTransition + vi.unstubAllGlobals() + + // A navigation that keeps the page updates its links. + await act(() => t.router.navigate({ to: '/a', search: { x: 'two' } })) + await t.settle() + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(false) + }) + + test('links outside every match follow a pending navigation', async () => { + const t = setup() + await screen.findByText('A page') + cleanup() + const router = t.router + const InnerWrap = ({ children }: { children: React.ReactNode }) => ( + <> + + wrap b + + {children} + + ) + router.update({ ...router.options, InnerWrap }) + render() + await screen.findByText('A page') + expect(t.isActive('wrap-b')).toBe(false) + t.gates.b = deferred() + await t.start({ to: '/b' }) + expect(router.state.status).toBe('pending') + expect(t.isActive('wrap-b')).toBe(true) + await t.release('b') + await screen.findByText('B page') + expect(t.isActive('wrap-b')).toBe(true) + }) +}) + +describe('masked links in a departing match', () => { + test.each(['mask', 'routeMasks'] as const)( + 'clicking a held link with a location-dependent %s pushes the masked href it displays', + async (kind) => { + const root = createRootRoute() + const gate: { b?: Deferred } = {} + const a = createRoute({ + getParentRoute: () => root, + path: '/a', + component: () => ( + ({ id: prev.x })} + hash + mask={ + kind === 'mask' + ? ({ to: '.', search: true, hash: true } as any) + : undefined + } + data-testid="masked" + > + masked + + ), + }) + const b = createRoute({ + getParentRoute: () => root, + path: '/b', + loader: () => gate.b?.promise, + component: () =>

    B page

    , + }) + const photo = createRoute({ + getParentRoute: () => root, + path: '/photo', + component: () =>

    Photo page

    , + }) + const routeTree = root.addChildren([a, b, photo]) + const router = createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/a?x=one#h'] }), + routeMasks: + kind === 'routeMasks' + ? [ + createRouteMask({ + routeTree, + from: '/photo', + to: '/a', + search: true, + hash: true, + } as any), + ] + : undefined, + }) + render() + const link = await screen.findByTestId('masked') + expect(link).toHaveAttribute('href', '/a?x=one#h') + + gate.b = deferred() + await act(async () => { + void router.navigate({ to: '/b' }) + await Promise.resolve() + }) + expect(router.state.status).toBe('pending') + expect(link).toHaveAttribute('href', '/a?x=one#h') + + await act(async () => { + fireEvent.click(link) + await Promise.resolve() + }) + // The URL bar shows the masked href the link displayed. + expect(router.history.location.href).toBe('/a?x=one#h') + expect(router.latestLocation.pathname).toBe('/photo') + expect(router.latestLocation.search).toEqual({ id: 'one' }) + gate.b.resolve() + await screen.findByText('Photo page') + expect(router.history.location.href).toBe('/a?x=one#h') + }, + ) + + test.each(['mask', 'routeMasks'] as const)( + 'a link with a fixed %s builds its location once and does not rerender across navigations', + async (kind) => { + // Every location the router builds for the masked link passes through + // the output rewrite. + let maskedBuilds = 0 + let renders = 0 + const root = createRootRoute({ + component: () => ( + <> + + {() => { + renders++ + return 'masked' + }} + + + + ), + }) + const routes = ['a', 'b', 'photo', 'posts'].map((path) => + createRoute({ + getParentRoute: () => root, + path: `/${path}`, + component: () =>

    {path} page

    , + }), + ) + const routeTree = root.addChildren(routes) + const router = createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/a'] }), + rewrite: { + output: ({ url }) => { + if (url.pathname === '/photo' || url.pathname === '/posts') { + maskedBuilds++ + } + return url + }, + }, + routeMasks: + kind === 'routeMasks' + ? [ + createRouteMask({ + routeTree, + from: '/photo', + to: '/posts', + search: { from: 'photo' }, + } as any), + ] + : undefined, + }) + render() + const link = await screen.findByTestId('masked') + expect(link).toHaveAttribute('href', '/posts?from=photo') + const buildsAfterMount = maskedBuilds + const rendersAfterMount = renders + + for (const to of ['/b', '/a', '/b']) { + await act(() => router.navigate({ to })) + await screen.findByText(`${to.slice(1)} page`) + } + expect(link).toHaveAttribute('href', '/posts?from=photo') + expect(maskedBuilds).toBe(buildsAfterMount) + expect(renders).toBe(rendersAfterMount) + }, + ) +}) + +describe('link scope retention', () => { + setFlagsFromString('--expose-gc') + const gc: () => void = runInNewContext('gc') + async function collect() { + for (let round = 0; round < 3; round++) { + await new Promise((resolve) => setTimeout(resolve, 0)) + gc() + } + } + const alive = (refs: Array>) => + refs.flatMap((ref, index) => (ref.deref() ? [index] : [])) + + // Builds and renders a router whose route `/a` and root render Links, and + // returns a function that visits a location with a large history state. + function renderApp() { + const root = createRootRoute({ + component: () => ( + <> + + root b + + + + ), + }) + const a = createRoute({ + getParentRoute: () => root, + path: '/a', + component: () => ( + <> +

    A page

    + prev} data-testid="a-self"> + a self + + + ), + }) + const b = createRoute({ + getParentRoute: () => root, + path: '/b', + component: () =>

    B page

    , + }) + const router = createRouter({ + routeTree: root.addChildren([a, b]), + history: createMemoryHistory({ initialEntries: ['/a'] }), + }) + render() + return async (to: string, index: number) => { + await act(() => + router.navigate({ + to, + search: { i: index }, + state: { payload: new Array(100_000).fill(index) } as any, + replace: true, + } as any), + ) + await waitFor(() => expect(router.state.status).toBe('idle')) + const location: any = router.state.location + return [new WeakRef(location), new WeakRef(location.state.payload)] + } + } + + test( + 'locations with large history state are collectable after their route is left', + { timeout: 20_000 }, + async () => { + const visit = renderApp() + await screen.findByText('A page') + // The router may keep its first navigation's state (also on main). + await visit('/a', 0) + const left: Array> = [] + for (let index = 1; index < 5; index++) { + left.push(...(await visit('/a', index))) + } + for (let index = 5; index < 9; index++) { + left.push(...(await visit('/b', index))) + } + await visit('/b', 9) + await screen.findByText('B page') + await collect() + // Only the current location (and its payload) stays reachable. + expect(alive(left)).toEqual([]) + }, + ) +}) + +describe('links after a same-href navigation that changes history state', () => { + function renderStateApp() { + // The `tag` state of every `/b` load, preloads included. + const bLoads: Array = [] + const root = createRootRoute({ component: () => }) + const a = createRoute({ + getParentRoute: () => root, + path: '/a', + component: () => ( + <> +

    A page

    + + inherit + + ({ tag: `${prev.tag}-updated` }) as any} + data-testid="updater" + > + updater + + + ), + }) + const b = createRoute({ + getParentRoute: () => root, + path: '/b', + loader: ({ location }) => { + bLoads.push((location.state as any).tag) + }, + component: () =>

    B page

    , + }) + const router = createRouter({ + routeTree: root.addChildren([a, b]), + history: createMemoryHistory({ initialEntries: ['/a'] }), + }) + render() + return { router, bLoads } + } + + async function changeState(router: any) { + await screen.findByText('A page') + await act(() => + router.navigate({ + to: '/a', + state: { tag: 'latest' } as any, + replace: true, + }), + ) + expect(router.state.location.href).toBe('/a') + expect(router.state.location.state.tag).toBe('latest') + } + + test.each([ + ['inherit', 'latest'], + ['updater', 'latest-updated'], + ])( + 'clicking link %s derives its state from the latest location', + async (id, tag) => { + const { router } = renderStateApp() + await changeState(router) + + fireEvent.click(screen.getByTestId(id)) + await screen.findByText('B page') + expect(router.state.location.pathname).toBe('/b') + expect((router.state.location.state as any).tag).toBe(tag) + }, + ) + + test('preloading derives its state from the latest location', async () => { + const { router, bLoads } = renderStateApp() + await changeState(router) + + fireEvent.mouseEnter(screen.getByTestId('inherit')) + await waitFor(() => expect(bLoads).toEqual(['latest'])) + }) +}) diff --git a/packages/react-router/tests/link-destination.test.tsx b/packages/react-router/tests/link-destination.test.tsx new file mode 100644 index 0000000000..31daa6d551 --- /dev/null +++ b/packages/react-router/tests/link-destination.test.tsx @@ -0,0 +1,498 @@ +import React from 'react' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { + Link, + Outlet, + RouterContextProvider, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + retainSearchParams, +} from '../src' + +describe('Link destination updates', () => { + beforeEach(() => vi.stubEnv('NODE_ENV', 'production')) + afterEach(() => { + cleanup() + vi.unstubAllEnvs() + }) + + function setupFixedLink( + params = { id: 'fixed' }, + stringify?: (params: Record) => { id: string }, + ) { + const rootRoute = createRootRoute({ + component: () => ( + <> + + Target + + + + ), + }) + const itemsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/items/$source', + }) + const targetRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/target/$id', + params: { stringify }, + }) + const routeTree = rootRoute.addChildren([itemsRoute, targetRoute]) + const router = createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/items/one'] }), + }) + return { router, rootRoute } + } + + test('preserves a fixed destination when unrelated location inputs change', async () => { + const { router } = setupFixedLink() + render() + + const link = await screen.findByTestId('fixed-link') + expect(link).toHaveAttribute('href', '/target/fixed#details') + expect(link).not.toHaveAttribute('data-status') + + await act(() => + router.navigate({ + to: '/items/$source', + params: { source: 'two' }, + search: { tab: 'other' }, + hash: 'other', + }), + ) + + expect(link).toHaveAttribute('href', '/target/fixed#details') + expect(link).not.toHaveAttribute('data-status') + + await act(() => + router.navigate({ + to: '/target/$id', + params: { id: 'fixed' }, + }), + ) + expect(link).toHaveAttribute('data-status', 'active') + expect(link).toHaveAttribute('href', '/target/fixed#details') + }) + + test('updates the destination when router options change', async () => { + const { router } = setupFixedLink() + render() + + const link = await screen.findByTestId('fixed-link') + expect(link).toHaveAttribute('href', '/target/fixed#details') + + router.update({ trailingSlash: 'always' }) + await act(() => + router.navigate({ to: '/items/$source', params: { source: 'two' } }), + ) + expect(link).toHaveAttribute('href', '/target/fixed/#details') + + router.update({ trailingSlash: 'never' }) + await act(() => + router.navigate({ to: '/items/$source', params: { source: 'three' } }), + ) + expect(link).toHaveAttribute('href', '/target/fixed#details') + }) + + test('evaluates param stringifiers before reusing pathnames', async () => { + const stringify = vi.fn((params: Record) => ({ + id: `${params.source}-${params.id}`, + })) + const { router } = setupFixedLink({ id: 'fixed' }, stringify) + render() + + const link = await screen.findByTestId('fixed-link') + expect(link).toHaveAttribute('href', '/target/one-fixed#details') + + await act(() => + router.navigate({ to: '/items/$source', params: { source: 'two' } }), + ) + expect(link).toHaveAttribute('href', '/target/two-fixed#details') + + stringify.mockClear() + await act(() => + router.navigate({ to: '/items/$source', params: { source: 'one' } }), + ) + expect(link).toHaveAttribute('href', '/target/one-fixed#details') + expect(stringify).toHaveBeenCalled() + }) + + test('updates when the route tree is rebuilt after route options change', async () => { + const { router, rootRoute } = setupFixedLink() + render() + + const link = await screen.findByTestId('fixed-link') + expect(link).toHaveAttribute('href', '/target/fixed#details') + + // HMR updates the live route in place, then rebuilds the route tree. + rootRoute.update({ + search: { middlewares: [retainSearchParams(true)] }, + }) + router.setRoutes(router.buildRouteTree()) + await act(() => + router.navigate({ + to: '/items/$source', + params: { source: 'two' }, + search: { retained: 'value' }, + }), + ) + expect(link).toHaveAttribute('href', '/target/fixed?retained=value#details') + + rootRoute.update({ search: undefined }) + router.setRoutes(router.buildRouteTree()) + await act(() => + router.navigate({ + to: '/items/$source', + params: { source: 'three' }, + search: { retained: 'value' }, + }), + ) + expect(link).toHaveAttribute('href', '/target/fixed#details') + }) + + test('reuses the location for equal inline literals and rebuilds on nested changes', async () => { + const rootRoute = createRootRoute({ + component: function Root() { + const [page, setPage] = React.useState(1) + const [, rerender] = React.useState(0) + return ( + <> + + + + Items + + + + ) + }, + }) + const itemsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/items/$source', + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([itemsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const buildLocation = vi.spyOn(router, 'buildLocation') + render() + + const link = await screen.findByTestId('nested-link') + expect(link).toHaveAttribute( + 'href', + '/items/one?filters=%7B%22page%22%3A1%7D&tags=%5B%22a%22%5D', + ) + + // Fresh literals with equal contents must not produce a new options + // object, otherwise the router could never reuse the built location. + const builds = buildLocation.mock.calls.length + expect(builds).toBeGreaterThan(0) + fireEvent.click(screen.getByRole('button', { name: 'Rerender' })) + fireEvent.click(screen.getByRole('button', { name: 'Rerender' })) + expect(buildLocation).toHaveBeenCalledTimes(builds) + expect(link).toHaveAttribute( + 'href', + '/items/one?filters=%7B%22page%22%3A1%7D&tags=%5B%22a%22%5D', + ) + + // A nested value that changes through React state is a new object, so + // the cached location for the previous contents must not be served. + fireEvent.click(screen.getByRole('button', { name: 'Next page' })) + expect(link).toHaveAttribute( + 'href', + '/items/one?filters=%7B%22page%22%3A2%7D&tags=%5B%22a%22%5D', + ) + + await act(() => + router.navigate({ to: '/items/$source', params: { source: 'two' } }), + ) + expect(link).toHaveAttribute( + 'href', + '/items/one?filters=%7B%22page%22%3A2%7D&tags=%5B%22a%22%5D', + ) + buildLocation.mockRestore() + }) + + test('updates fixed params and hash when Link props change', async () => { + const rootRoute = createRootRoute({ + component: function Root() { + const [value, setValue] = React.useState('one') + return ( + <> + + + Item + + + + ) + }, + }) + const itemsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([itemsRoute]), + history: createMemoryHistory({ initialEntries: ['/items/one'] }), + }) + render() + + const link = await screen.findByTestId('changing-link') + expect(link).toHaveAttribute('href', '/items/one#one') + expect(link).toHaveAttribute('data-status', 'active') + + fireEvent.click(screen.getByRole('button', { name: 'Change target' })) + + expect(link).toHaveAttribute('href', '/items/two#two') + expect(link).not.toHaveAttribute('data-status') + }) + + test('updates inherited params and active state together', async () => { + const rootRoute = createRootRoute({ + component: () => ( + <> + + {({ isActive }) => (isActive ? 'Current item' : 'Another item')} + + + + ), + }) + const itemsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([itemsRoute]), + history: createMemoryHistory({ initialEntries: ['/items/one'] }), + }) + render() + + const link = await screen.findByTestId('inherited-link') + expect(link).toHaveAttribute('href', '/items/one') + expect(link).toHaveTextContent('Current item') + + await act(() => + router.navigate({ to: '/items/$id', params: { id: 'two' } }), + ) + + expect(link).toHaveAttribute('href', '/items/two') + expect(link).toHaveAttribute('data-status', 'active') + expect(link).toHaveTextContent('Current item') + }) + + test('masked destinations follow their inputs', async () => { + // A stable mask object that inherits params, and a mask prop that changes. + const inheritedMask = { to: '/visible/$id', params: true } as const + const rootRoute = createRootRoute({ + component: function Root() { + const [id, setId] = React.useState('one') + return ( + <> + + + + + + ) + }, + }) + const routes = ['/source/$id', '/target/$id', '/visible/$id'].map((path) => + createRoute({ getParentRoute: () => rootRoute, path }), + ) + const router = createRouter({ + routeTree: rootRoute.addChildren(routes), + history: createMemoryHistory({ initialEntries: ['/source/one'] }), + }) + render() + + const propMask = await screen.findByTestId('prop-mask') + const inherited = screen.getByTestId('inherited-mask') + expect(propMask).toHaveAttribute('href', '/visible/one') + expect(inherited).toHaveAttribute('href', '/visible/one') + + await act(() => + router.navigate({ to: '/source/$id', params: { id: 'two' } } as any), + ) + expect(inherited).toHaveAttribute('href', '/visible/two') + expect(propMask).toHaveAttribute('href', '/visible/one') + + fireEvent.click(screen.getByRole('button', { name: 'Change mask' })) + expect(propMask).toHaveAttribute('href', '/visible/two') + }) +}) + +describe('Link props that change without a destination prop', () => { + afterEach(() => { + cleanup() + vi.useRealTimers() + }) + + async function setup(targetLoader?: () => void, nextLoader?: () => void) { + const root = createRootRoute() + const router = createRouter({ + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: '/a' }), + createRoute({ + getParentRoute: () => root, + path: '/b', + loader: targetLoader, + }), + createRoute({ + getParentRoute: () => root, + path: '/c', + loader: nextLoader, + }), + ]), + history: createMemoryHistory({ initialEntries: ['/a'] }), + }) + await router.load() + return router + } + + test('changing reloadDocument affects the next click', async () => { + const router = await setup() + const blockedTargets: Array = [] + const unblock = router.history.block({ + blockerFn: ({ nextLocation }) => { + blockedTargets.push(nextLocation.pathname) + return true + }, + }) + function Example() { + const [reload, setReload] = React.useState(false) + return ( + <> + + + Target + + + ) + } + render( + + + , + ) + try { + fireEvent.click(screen.getByRole('button', { name: 'Enable reload' })) + await act(() => { + fireEvent.click(screen.getByRole('link', { name: 'Target' })) + }) + // A document navigation shows blockers the current history location; + // a client navigation would show the pending /b location. + expect(blockedTargets).toEqual(['/a']) + expect(router.history.location.pathname).toBe('/a') + } finally { + unblock() + } + }) + + test('changing href updates the displayed target and active state', async () => { + const router = await setup() + function Example() { + const [changed, setChanged] = React.useState(false) + return ( + <> + + + Target + + + ) + } + render( + + + , + ) + const link = screen.getByRole('link', { name: 'Target' }) + expect(link).toHaveAttribute('href', '/a') + expect(link).toHaveAttribute('aria-current', 'page') + fireEvent.click(screen.getByRole('button', { name: 'Change href' })) + expect(link).toHaveAttribute('href', '/b') + expect(link).not.toHaveAttribute('aria-current') + }) + + test('changing href cancels intent work for the old target and preloads and navigates to the new one', async () => { + const oldLoader = vi.fn() + const nextLoader = vi.fn() + const router = await setup(oldLoader, nextLoader) + vi.useFakeTimers() + function Example() { + const [href, setHref] = React.useState('/b') + return ( + <> + + + Target + + + ) + } + render( + + + , + ) + const link = screen.getByRole('link', { name: 'Target' }) + expect(link).toHaveAttribute('href', '/b') + fireEvent.mouseOver(link) + await act(() => vi.advanceTimersByTimeAsync(20)) + fireEvent.click(screen.getByRole('button', { name: 'Retarget' })) + expect(link).toHaveAttribute('href', '/c') + await act(() => vi.advanceTimersByTimeAsync(100)) + expect(oldLoader).not.toHaveBeenCalled() + expect(nextLoader).not.toHaveBeenCalled() + + fireEvent.mouseLeave(link) + fireEvent.mouseOver(link) + await act(() => vi.advanceTimersByTimeAsync(50)) + expect(nextLoader).toHaveBeenCalledTimes(1) + expect(router.state.location.pathname).toBe('/a') + + await act(() => { + fireEvent.click(link) + }) + expect(router.state.location.pathname).toBe('/c') + expect(link).toHaveAttribute('aria-current', 'page') + expect(oldLoader).not.toHaveBeenCalled() + }) +}) diff --git a/packages/react-router/tests/link-events.test.tsx b/packages/react-router/tests/link-events.test.tsx new file mode 100644 index 0000000000..0095d450a5 --- /dev/null +++ b/packages/react-router/tests/link-events.test.tsx @@ -0,0 +1,190 @@ +import React from 'react' +import { + act, + cleanup, + fireEvent, + render, + renderHook, +} from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + Link, + RouterContextProvider, + createMemoryHistory, + createRootRoute, + createRouter, + useLinkProps, +} from '../src' + +afterEach(cleanup) + +test.each([false, true])( + 'preserves caller click handlers across destination changes (cancel=%s)', + (cancel) => { + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory(), + isServer: false, + rewrite: { + output: ({ url }) => + url.pathname === '/external' + ? new URL('https://other.example/rewritten') + : url, + }, + }) + const navigate = vi.spyOn(router, 'navigate').mockResolvedValue() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const onClick = vi.fn((event: React.MouseEvent) => { + if (cancel) { + event.preventDefault() + } + }) + const content = (to: string) => ( + + + Target + + + ) + try { + const view = render(content('/safe')) + const anchor = view.getByText('Target') + for (const [to, internal] of [ + ['/safe', true], + ['https://other.example/', false], + ['/external', false], + ['javascript:blocked()', false], + ['/next', true], + ] as const) { + onClick.mockClear() + navigate.mockClear() + view.rerender(content(to)) + expect(view.getByText('Target')).toBe(anchor) + let intercepted: boolean | undefined + const preventNativeNavigation = (event: Event) => { + intercepted = event.defaultPrevented + event.preventDefault() + } + document.addEventListener('click', preventNativeNavigation) + try { + fireEvent.click(anchor) + } finally { + document.removeEventListener('click', preventNativeNavigation) + } + expect(onClick).toHaveBeenCalledOnce() + expect(intercepted).toBe(cancel || internal) + expect(navigate).toHaveBeenCalledTimes(internal && !cancel ? 1 : 0) + } + } finally { + cleanup() + navigate.mockRestore() + warn.mockRestore() + } + }, +) + +test.each(['https://other.example/', 'javascript:blocked()'])( + 'cancels delayed internal preloads when the destination changes to %s', + (destination) => { + vi.useFakeTimers() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory(), + }) + const preload = vi + .spyOn(router, 'preloadRoute') + .mockResolvedValue(undefined) + const content = (to: string) => ( + + + Target + + + ) + try { + const view = render(content('/old')) + fireEvent.mouseEnter(view.getByText('Target')) + view.rerender(content(destination)) + act(() => { + vi.advanceTimersByTime(100) + }) + expect(preload).not.toHaveBeenCalled() + view.rerender(content('/next')) + fireEvent.mouseEnter(view.getByText('Target')) + act(() => { + vi.advanceTimersByTime(100) + }) + expect(preload).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ to: '/next' }), + ) + } finally { + cleanup() + warn.mockRestore() + vi.useRealTimers() + } + }, +) + +test.each(['onClick', 'onFocus', 'onMouseEnter', 'onTouchStart'] as const)( + '%s respects cancellation before and after the user handler', + (eventName) => { + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory(), + isServer: false, + }) + const navigate = vi.spyOn(router, 'navigate').mockResolvedValue() + const preload = vi + .spyOn(router, 'preloadRoute') + .mockResolvedValue(undefined) + const userHandler = vi.fn((event: React.SyntheticEvent) => { + if (cancelInUserHandler) { + event.preventDefault() + } + }) + let cancelInUserHandler = false + const { result } = renderHook( + () => + useLinkProps({ + to: '/target', + preload: 'intent', + preloadDelay: 0, + [eventName]: userHandler, + }), + { + wrapper: ({ children }) => ( + + {children} + + ), + }, + ) + const internalHandler = eventName === 'onClick' ? navigate : preload + const anchor = document.createElement('a') + for (const initiallyPrevented of [true, false]) { + for (const cancel of [true, false]) { + cancelInUserHandler = cancel + userHandler.mockClear() + internalHandler.mockClear() + const event = { + defaultPrevented: initiallyPrevented, + preventDefault() { + this.defaultPrevented = true + }, + currentTarget: anchor, + button: 0, + } + result.current[eventName]!( + event as unknown as React.MouseEvent & + React.TouchEvent & + React.FocusEvent, + ) + expect(userHandler).toHaveBeenCalledTimes(initiallyPrevented ? 0 : 1) + expect(internalHandler).toHaveBeenCalledTimes( + initiallyPrevented || cancel ? 0 : 1, + ) + } + } + }, +) diff --git a/packages/react-router/tests/link-href-safety.test.tsx b/packages/react-router/tests/link-href-safety.test.tsx new file mode 100644 index 0000000000..5838d0b8c3 --- /dev/null +++ b/packages/react-router/tests/link-href-safety.test.tsx @@ -0,0 +1,90 @@ +import React from 'react' +import { renderToString } from 'react-dom/server' +import { cleanup, fireEvent, render } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + Link, + RouterContextProvider, + createMemoryHistory, + createRootRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +for (const isServer of [true, false]) { + test.each<[string, string | null, boolean]>([ + ['//evil.example/path', null, false], + ['/\\evil.example/path', null, false], + ['\\/evil.example/path', null, false], + ['\x01 \t//evil.example/path', null, false], + ['javascript:blocked()', null, false], + ['/formatted', '/formatted', true], + ['https://other.example/', 'https://other.example/', false], + ] as const)( + `validates final history href %j on ${isServer ? 'server' : 'client'}`, + (href, expectedHref, active) => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const history = createMemoryHistory({ initialEntries: ['/safe'] }) + // Browser history normalizes formatter output itself. Use raw history + // output to exercise the final Link validation boundary. + history.createHref = vi.fn(() => href) + const router = createRouter({ + routeTree: createRootRoute(), + history, + isServer, + }) + const navigate = vi.spyOn(router, 'navigate').mockResolvedValue() + const preload = vi + .spyOn(router, 'preloadRoute') + .mockResolvedValue(undefined) + const activeProps = { className: 'active', href: 'javascript:active()' } + const inactiveProps = { + className: 'inactive', + href: 'javascript:inactive()', + } + const tree = ( + + + {({ isActive }) => String(isActive)} + + + ) + let container: HTMLElement + if (isServer) { + container = document.createElement('div') + container.innerHTML = renderToString(tree) + } else { + container = render(tree).container + } + const anchor = container.querySelector('a')! + expect(history.createHref).toHaveBeenCalledWith('/safe') + expect(anchor.getAttribute('href')).toBe(expectedHref) + expect(anchor.textContent).toBe(String(active)) + expect(anchor.getAttribute('aria-current')).toBe(active ? 'page' : null) + expect(anchor.getAttribute('aria-disabled')).toBe( + expectedHref === null ? 'true' : null, + ) + if (expectedHref === null) { + expect(anchor).toHaveClass('inactive') + if (!isServer) { + expect(fireEvent.click(anchor)).toBe(true) + fireEvent.focus(anchor) + fireEvent.mouseEnter(anchor) + fireEvent.touchStart(anchor) + expect(navigate).not.toHaveBeenCalled() + expect(preload).not.toHaveBeenCalled() + } + } + }, + ) +} diff --git a/packages/react-router/tests/link-hydration.test.tsx b/packages/react-router/tests/link-hydration.test.tsx new file mode 100644 index 0000000000..497464b3f8 --- /dev/null +++ b/packages/react-router/tests/link-hydration.test.tsx @@ -0,0 +1,203 @@ +import React from 'react' +import { renderToString } from 'react-dom/server' +import { hydrateRoot } from 'react-dom/client' +import { act } from '@testing-library/react' +import { expect, test, vi } from 'vitest' +import { + Link, + RouterContextProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +test('only hash-sensitive links need a second hydration render', async () => { + const rootRoute = createRootRoute() + const router = createRouter({ + routeTree: rootRoute.addChildren([ + createRoute({ getParentRoute: () => rootRoute, path: '/target' }), + ]), + history: createMemoryHistory({ initialEntries: ['/target#section'] }), + }) + await router.load() + const serverRouter = createRouter({ + routeTree: router.routeTree, + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: true, + }) + await serverRouter.load() + const ordinary = vi.fn(({ isActive }: { isActive: boolean }) => + String(isActive), + ) + const hashSensitive = vi.fn(({ isActive }: { isActive: boolean }) => + String(isActive), + ) + const tree = (includeHash = false, contextRouter = router) => ( + + + {ordinary} + + + {hashSensitive} + + + ) + const container = document.createElement('div') + document.body.append(container) + container.innerHTML = renderToString(tree(false, serverRouter)) + expect(container.querySelector('[data-testid="ordinary"]')?.textContent).toBe( + 'true', + ) + expect(container.querySelector('[data-testid="hash"]')?.textContent).toBe( + 'false', + ) + ordinary.mockClear() + hashSensitive.mockClear() + const onRecoverableError = vi.fn() + const diagnostics = vi.spyOn(console, 'error').mockImplementation(() => {}) + const serverAnchor = container.querySelector('[data-testid="ordinary"]') + let root: ReturnType | undefined + try { + await act(() => { + root = hydrateRoot(container, tree(), { onRecoverableError }) + }) + expect(ordinary).toHaveBeenCalledTimes(1) + expect(container.querySelector('[data-testid="ordinary"]')).toBe( + serverAnchor, + ) + expect(hashSensitive.mock.calls.map(([state]) => state.isActive)).toEqual([ + false, + true, + ]) + expect(container.querySelector('[data-testid="hash"]')).toHaveAttribute( + 'aria-current', + 'page', + ) + expect(container.querySelector('[data-testid="hash"]')).toHaveAttribute( + 'title', + 'active', + ) + await act(() => root!.render(tree(true))) + expect( + container.querySelector('[data-testid="ordinary"]'), + ).not.toHaveAttribute('aria-current') + expect(container.querySelector('[data-testid="ordinary"]')).toHaveAttribute( + 'title', + 'inactive', + ) + await act(() => root!.render(tree(false))) + expect(container.querySelector('[data-testid="ordinary"]')).toHaveAttribute( + 'aria-current', + 'page', + ) + expect(onRecoverableError).not.toHaveBeenCalled() + expect(diagnostics).not.toHaveBeenCalled() + } finally { + await act(() => root?.unmount()) + router.history.destroy() + serverRouter.history.destroy() + diagnostics.mockRestore() + container.remove() + } +}) + +test('hash-sensitive links retain the server snapshot in a delayed hydration boundary', async () => { + const rootRoute = createRootRoute() + const routeTree = rootRoute.addChildren([ + createRoute({ getParentRoute: () => rootRoute, path: '/target' }), + ]) + const serverRouter = createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: true, + }) + const clientRouter = createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/target#section'] }), + }) + await Promise.all([serverRouter.load(), clientRouter.load()]) + let ready = true + let resolve!: () => void + const pending = new Promise((done) => { + resolve = done + }) + const ordinary = vi.fn(() => 'ordinary') + const hashSensitive = vi.fn(({ isActive }: { isActive: boolean }) => + String(isActive), + ) + function DeferredLinks() { + if (!ready) { + throw pending + } + return ( + <> + {ordinary} + + {hashSensitive} + + + ) + } + const tree = (router: typeof clientRouter) => ( + + Loading

    }> + +
    +
    + ) + const container = document.createElement('div') + document.body.append(container) + container.innerHTML = renderToString(tree(serverRouter)) + const serverAnchor = container.querySelector('a') + ordinary.mockClear() + hashSensitive.mockClear() + ready = false + const onRecoverableError = vi.fn() + const diagnostics = vi.spyOn(console, 'error').mockImplementation(() => {}) + let root: ReturnType | undefined + try { + await act(() => { + root = hydrateRoot(container, tree(clientRouter), { onRecoverableError }) + }) + expect(ordinary).not.toHaveBeenCalled() + expect(hashSensitive).not.toHaveBeenCalled() + await act(async () => { + ready = true + resolve() + await pending + }) + expect(ordinary).toHaveBeenCalledTimes(1) + expect(hashSensitive.mock.calls.map(([state]) => state.isActive)).toEqual([ + false, + true, + ]) + expect(container.querySelector('a')).toBe(serverAnchor) + expect(container.querySelectorAll('a')[1]).toHaveAttribute( + 'aria-current', + 'page', + ) + expect(onRecoverableError).not.toHaveBeenCalled() + expect(diagnostics).not.toHaveBeenCalled() + } finally { + await act(() => root?.unmount()) + serverRouter.history.destroy() + clientRouter.history.destroy() + diagnostics.mockRestore() + container.remove() + } +}) diff --git a/packages/react-router/tests/link-memo.test.tsx b/packages/react-router/tests/link-memo.test.tsx new file mode 100644 index 0000000000..873bbf9e7a --- /dev/null +++ b/packages/react-router/tests/link-memo.test.tsx @@ -0,0 +1,175 @@ +import React from 'react' +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + Link, + RouterContextProvider, + createLink, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(cleanup) + +async function createPostsRouter() { + const root = createRootRoute() + const router = createRouter({ + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: '/posts/$postId' }), + ]), + history: createMemoryHistory({ initialEntries: ['/posts/1'] }), + }) + await router.load() + return router +} + +test('a parent re-render with equal props does not re-render the Link', async () => { + let hostRenders = 0 + const Host = React.forwardRef>( + (props, ref) => { + hostRenders++ + return
    + }, + ) + const CustomLink = createLink(Host) + const router = await createPostsRouter() + + let rerender = () => {} + let setPostId: React.Dispatch> = () => {} + function Parent() { + const [, setTick] = React.useState(0) + const [postId, set] = React.useState(1) + rerender = () => setTick((tick) => tick + 1) + setPostId = set + return ( + + + Post + + + ) + } + const view = render() + const anchor = view.getByText('Post') + expect(anchor).toHaveAttribute('href', '/posts/1') + expect(anchor).toHaveClass('current') + const rendersAfterMount = hostRenders + + // Same props, new inline objects: the memoized Link is skipped. + act(() => rerender()) + expect(hostRenders).toBe(rendersAfterMount) + + // A changed destination renders again. + act(() => setPostId(2)) + expect(hostRenders).toBe(rendersAfterMount + 1) + expect(anchor).toHaveAttribute('href', '/posts/2') + expect(anchor).not.toHaveClass('current') +}) + +test('element props are compared by reference: new children re-render, a cyclic prop does not throw', async () => { + let hostRenders = 0 + const Host = React.forwardRef< + HTMLAnchorElement, + React.ComponentProps<'a'> & { payload?: object } + >(({ payload: _payload, ...props }, ref) => { + hostRenders++ + return + }) + const CustomLink = createLink(Host) + const router = await createPostsRouter() + + let rerender = () => {} + function Parent() { + const [, setTick] = React.useState(0) + rerender = () => setTick((tick) => tick + 1) + // A new cyclic object per render: deep-comparing it would never return. + const cyclic: Record = {} + cyclic.self = cyclic + return ( + + + Post + + + ) + } + render() + expect(hostRenders).toBe(1) + + // Equal router options, but `children` is a new element and `payload` a + // new object, so the Link renders again instead of comparing them deeply. + act(() => rerender()) + expect(hostRenders).toBe(2) +}) + +test('a forwarded callback ref is notified once per element, not per Link render', async () => { + const router = await createPostsRouter() + const ref = vi.fn<(element: HTMLAnchorElement | null) => void>() + + const view = render( + + + Post + + , + ) + const anchor = view.getByText('Post') + expect(ref.mock.calls).toEqual([[anchor]]) + expect(anchor).toHaveAttribute('data-status', 'active') + + // A location change re-renders the Link (it is no longer active) without + // detaching and re-attaching the consumer's ref. + await act(() => + router.navigate({ to: '/posts/$postId', params: { postId: '2' } }), + ) + expect(anchor).not.toHaveAttribute('data-status') + expect(ref).toHaveBeenCalledTimes(1) + + // A different ref is attached to the same element; the old one is released. + const next = vi.fn<(element: HTMLAnchorElement | null) => void>() + view.rerender( + + + Post + + , + ) + expect(ref.mock.calls).toEqual([[anchor], [null]]) + expect(next.mock.calls).toEqual([[anchor]]) + + view.unmount() + expect(next.mock.calls).toEqual([[anchor], [null]]) +}) + +test('a cleanup returned by a forwarded callback ref runs on unmount', async () => { + const router = await createPostsRouter() + const cleanup = vi.fn() + const ref = vi.fn((_element: HTMLAnchorElement | null) => cleanup) + + const view = render( + + + Post + + , + ) + const anchor = view.getByText('Post') + expect(ref.mock.calls).toEqual([[anchor]]) + expect(cleanup).not.toHaveBeenCalled() + + view.unmount() + // React runs the cleanup instead of calling the ref with `null`. + expect(cleanup).toHaveBeenCalledTimes(1) + expect(ref).toHaveBeenCalledTimes(1) +}) diff --git a/packages/react-router/tests/link-path-matching.test.tsx b/packages/react-router/tests/link-path-matching.test.tsx new file mode 100644 index 0000000000..232a0d8633 --- /dev/null +++ b/packages/react-router/tests/link-path-matching.test.tsx @@ -0,0 +1,58 @@ +import React from 'react' +import { renderToString } from 'react-dom/server' +import { cleanup, render } from '@testing-library/react' +import { afterEach, expect, test } from 'vitest' +import { + Link, + RouterContextProvider, + createMemoryHistory, + createRootRoute, + createRouter, +} from '../src' + +afterEach(cleanup) + +const cases = [ + { current: '/posts', to: '/posts/', exact: true, active: true }, + { current: '/posts/', to: '/posts', exact: true, active: true }, + { current: '/posts/item', to: '/posts', exact: true, active: false }, + { current: '/posts/item', to: '/posts', exact: false, active: true }, + { current: '/posts/item', to: '/posts/', exact: false, active: true }, + { current: '/posts-other', to: '/posts', exact: false, active: false }, +] + +for (const basepath of ['', '/app']) { + test.each(cases)( + `pathname matching agrees on server and client with basepath "${basepath}": $current -> $to, exact=$exact`, + ({ current, to, exact, active }) => { + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory({ initialEntries: [basepath + current] }), + basepath, + trailingSlash: 'preserve', + }) + const tree = ( + + + {({ isActive }) => String(isActive)} + + + ) + router.isServer = true + const server = document.createElement('div') + server.innerHTML = renderToString(tree) + router.isServer = false + const client = render(tree).container + for (const container of [server, client]) { + const anchor = container.querySelector('a')! + expect(anchor.textContent).toBe(String(active)) + expect(anchor.getAttribute('aria-current')).toBe(active ? 'page' : null) + expect(anchor.className).toBe(active ? 'active' : 'inactive') + } + }, + ) +} diff --git a/packages/react-router/tests/link-selector.test.tsx b/packages/react-router/tests/link-selector.test.tsx new file mode 100644 index 0000000000..eee6906265 --- /dev/null +++ b/packages/react-router/tests/link-selector.test.tsx @@ -0,0 +1,192 @@ +import React from 'react' +import { act, cleanup, render, waitFor } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + Link, + RouterContextProvider, + RouterProvider, + createHashHistory, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +async function setup(trailingSlash: 'never' | 'preserve' = 'never') { + const root = createRootRoute() + const router = createRouter({ + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: '/posts/$id' }), + ]), + history: createMemoryHistory({ initialEntries: ['/posts/1'] }), + trailingSlash, + }) + await router.load() + return router +} + +test('a fixed href follows active, inactive and active-again locations', async () => { + const router = await setup() + const view = render( + + + Post + + , + ) + const link = view.getByText('Post') + for (const [id, page, active] of [ + ['1', 1, true], + ['2', 1, false], + ['1', 2, false], + ['1', 1, true], + ] as const) { + await act(() => + router.navigate({ to: '/posts/$id', params: { id }, search: { page } }), + ) + expect(link).toHaveAttribute('href', '/posts/1?page=1') + expect(link.getAttribute('aria-current')).toBe(active ? 'page' : null) + } +}) + +test('changed destination, active options and disabled props replace prepared state', async () => { + const router = await setup() + function tree(id: string, disabled = false, includeSearch = true) { + return ( + + + Post + + + ) + } + const view = render(tree('1')) + const link = view.getByText('Post') + expect(link).not.toHaveAttribute('aria-current') + view.rerender(tree('1', false, false)) + expect(link).toHaveAttribute('aria-current', 'page') + view.rerender(tree('1', true, false)) + expect(link).not.toHaveAttribute('href') + expect(link).toHaveAttribute('aria-current', 'page') + view.rerender(tree('2', false, false)) + expect(link).toHaveAttribute('href', '/posts/2?page=1') + expect(link).not.toHaveAttribute('aria-current') + await act(() => router.navigate({ to: '/posts/$id', params: { id: '2' } })) + expect(link).toHaveAttribute('aria-current', 'page') +}) + +test('hash history refreshes a cached destination after the outer URL changes', async () => { + const original = window.location.href + window.history.replaceState(null, '', '/shell?outer=one#/posts/1') + const history = createHashHistory() + const root = createRootRoute({ + component: () => ( + + Post + + ), + }) + const router = createRouter({ + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: '/posts/$id' }), + ]), + history, + trailingSlash: 'never', + }) + try { + const view = render() + const link = await view.findByText('Post') + expect(link).toHaveAttribute('href', '/shell?outer=one#/posts/1') + expect(link).toHaveAttribute('aria-current', 'page') + act(() => { + window.history.replaceState(null, '', '/other?outer=two#/posts/2') + }) + await waitFor(() => { + expect(link).toHaveAttribute('href', '/other?outer=two#/posts/1') + expect(link).not.toHaveAttribute('aria-current') + }) + } finally { + cleanup() + history.destroy() + window.history.replaceState(null, '', original) + } +}) + +test.each([false, true])( + 'cached paths retain segment boundaries and basepaths (exact=%s)', + async (exact) => { + const router = await setup() + router.update({ basepath: '/app', trailingSlash: 'preserve' }) + const view = render( + + + Post + + , + ) + const link = view.getByText('Post') + for (const [to, active] of [ + ['/posts/1', true], + ['/posts/1/details', !exact], + ['/posts/10', false], + ['/posts/1/', true], + ] as const) { + await act(() => router.navigate({ to })) + expect(link).toHaveAttribute('href', '/app/posts/1/') + expect(link.getAttribute('aria-current')).toBe(active ? 'page' : null) + } + router.update({ basepath: '/new' }) + await act(() => router.navigate({ to: '/posts/1/' })) + expect(link).toHaveAttribute('href', '/new/posts/1/') + expect(link).toHaveAttribute('aria-current', 'page') + }, +) + +test('external classification follows changed destinations and router instances', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const router = await setup() + router.update({ protocolAllowlist: ['https:', 'custom:'] }) + function tree(to: string, currentRouter = router) { + return ( + + Destination + + ) + } + const view = render(tree('/posts/1')) + const link = view.getByText('Destination') + expect(link).toHaveAttribute('aria-current', 'page') + for (const to of ['https://other.example/', 'custom:post']) { + view.rerender(tree(to)) + await act(() => router.navigate({ to: '/posts/$id', params: { id: '2' } })) + expect(link).toHaveAttribute('href', to) + expect(link).not.toHaveAttribute('aria-current') + } + view.rerender(tree('javascript:blocked()')) + await act(() => router.navigate({ to: '/posts/$id', params: { id: '1' } })) + expect(link).not.toHaveAttribute('href') + expect(link).not.toHaveAttribute('aria-current') + view.rerender(tree('/posts/2')) + await act(() => router.navigate({ to: '/posts/$id', params: { id: '2' } })) + expect(link).toHaveAttribute('href', '/posts/2') + expect(link).toHaveAttribute('aria-current', 'page') + + // Each mounted router keeps its allowlist; switching routers resets the selector. + view.rerender(tree('custom:post')) + expect(link).toHaveAttribute('href', 'custom:post') + const otherRouter = await setup() + view.rerender(tree('custom:post', otherRouter)) + expect(link).not.toHaveAttribute('href') + expect(link).not.toHaveAttribute('aria-current') +}) diff --git a/packages/react-router/tests/link-state-props.test.tsx b/packages/react-router/tests/link-state-props.test.tsx new file mode 100644 index 0000000000..ea45a5e974 --- /dev/null +++ b/packages/react-router/tests/link-state-props.test.tsx @@ -0,0 +1,562 @@ +import React from 'react' +import { renderToString } from 'react-dom/server' +import { hydrateRoot } from 'react-dom/client' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + Link, + RouterContextProvider, + RouterProvider, + createLink, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + useLinkProps, +} from '../src' + +const disposers: Array<() => void> = [] +afterEach(() => { + cleanup() + for (const dispose of disposers.splice(0)) { + dispose() + } +}) + +test.each([false, true])( + 'filters native and custom props without changing the hook result (server: %s)', + async (server) => { + type AnchorProps = React.ComponentPropsWithoutRef<'a'> & { + disabled?: boolean + } + let customProps: AnchorProps | undefined + let hookProps: React.ComponentPropsWithRef<'a'> | undefined + const customRef = React.createRef() + const nativeRef = React.createRef() + const CustomLink = createLink( + React.forwardRef((props, ref) => { + customProps = props + return ( + + {props.children} + + ) + }), + ) + function Probe() { + hookProps = useLinkProps({ + to: '/target', + type: 'text/custom', + disabled: true, + }) + return null + } + const root = createRootRoute() + const router = createRouter({ + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: '/target' }), + ]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: server, + }) + disposers.push(router.history.destroy) + await router.load() + const tree = ( + + + Native + + + {({ isActive }) => (isActive ? 'Active custom' : 'Inactive custom')} + + + + ) + const container = server + ? document.createElement('div') + : render(tree).container + if (server) { + container.innerHTML = renderToString(tree) + } + const native = container.querySelector('a')! + const custom = container.querySelector('[data-testid="custom"]') + expect(native).not.toHaveAttribute('type') + expect(native).not.toHaveAttribute('disabled') + expect(native).toHaveAttribute('aria-disabled', 'true') + expect(custom).toHaveTextContent('Active custom') + expect(customProps).toMatchObject({ disabled: true }) + expect(customProps).not.toHaveProperty('type') + expect(hookProps).toMatchObject({ type: 'text/custom', disabled: true }) + if (!server) { + expect(nativeRef.current).toBe(native) + expect(customRef.current).toBe(custom) + } + }, +) + +test('blocked custom links keep the validated routing props and apply state props like any inactive link', () => { + const CustomLink = createLink( + React.forwardRef< + HTMLAnchorElement, + React.ComponentProps<'a'> & { disabled?: boolean } + >((props, ref) => ( + + )), + ) + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory(), + }) + const ref = React.createRef() + const stateRef = vi.fn() + const stateClick = vi.fn() + const baseClick = vi.fn() + const search = vi.fn(() => ({})) + const buildLocation = vi.spyOn(router, 'buildLocation') + const inactiveProps = vi.fn(() => ({ + href: 'javascript:override()', + disabled: false, + target: '_blank', + ref: stateRef, + onClick: stateClick, + className: 'inactive-state', + title: 'Inactive', + })) + const tree = ( + + + Target + + + ) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + router.isServer = true + const html = renderToString(tree) + expect(html).toContain('data-disabled="true"') + expect(html).toContain('class="inactive-state"') + expect(html).toContain('title="Inactive"') + expect(html).not.toContain('href=') + expect(html).not.toContain('target=') + router.isServer = false + const anchor = render(tree).getByText('Target') + expect(anchor).toHaveAttribute('data-disabled', 'true') + expect(anchor).not.toHaveAttribute('href') + expect(anchor).not.toHaveAttribute('target') + expect(anchor).toHaveClass('inactive-state') + expect(anchor).toHaveAttribute('title', 'Inactive') + // The selected state props win over the forwarded ref and base handlers, + // exactly as they do on any other inactive link. + expect(stateRef).toHaveBeenCalledWith(anchor) + expect(ref.current).toBeNull() + fireEvent.click(anchor) + expect(stateClick).toHaveBeenCalledOnce() + expect(baseClick).not.toHaveBeenCalled() + expect(inactiveProps).toHaveBeenCalled() + expect(buildLocation).not.toHaveBeenCalled() + expect(search).not.toHaveBeenCalled() + } finally { + warn.mockRestore() + buildLocation.mockRestore() + } +}) + +test.each([false, true])( + 'blocked links preserve inactive styling from SSR to client (disabled=%s)', + async (disabled) => { + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory(), + }) + const inactiveProps = { + className: 'inactive-state', + style: { color: 'blue' }, + href: 'javascript:inactive()', + title: 'Inactive', + } + const tree = ( + + + {({ isActive }) => String(isActive)} + + + ) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + router.isServer = true + const serverContainer = document.createElement('div') + serverContainer.innerHTML = renderToString(tree) + const serverLink = serverContainer.querySelector('a')! + router.isServer = false + const clientLink = render(tree).container.querySelector('a')! + expect(serverLink.className).toBe('base inactive-state') + expect(serverLink).toHaveStyle({ + color: 'rgb(0, 0, 255)', + fontWeight: '700', + }) + expect(serverLink).not.toHaveAttribute('href') + expect(serverLink).toHaveAttribute('aria-disabled', 'true') + expect(serverLink).not.toHaveAttribute('aria-current') + expect(serverLink).toHaveAttribute('title', 'Inactive') + expect(serverLink.textContent).toBe('false') + expect( + Object.fromEntries( + Array.from(clientLink.attributes, (attr) => [ + attr.name, + attr.name === 'style' ? clientLink.style.cssText : attr.value, + ]), + ), + ).toEqual( + Object.fromEntries( + Array.from(serverLink.attributes, (attr) => [ + attr.name, + attr.name === 'style' ? serverLink.style.cssText : attr.value, + ]), + ), + ) + const diagnostics = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + const recoverableError = vi.fn() + let hydrated: ReturnType | undefined + try { + await act(() => { + hydrated = hydrateRoot(serverContainer, tree, { + onRecoverableError: recoverableError, + }) + }) + expect(serverContainer.querySelector('a')).toBe(serverLink) + expect(serverLink).not.toHaveAttribute('href') + expect(serverLink).toHaveClass('inactive-state') + expect(diagnostics).not.toHaveBeenCalled() + expect(recoverableError).not.toHaveBeenCalled() + } finally { + await act(() => hydrated?.unmount()) + diagnostics.mockRestore() + } + } finally { + warn.mockRestore() + } + }, +) + +test('external destinations skip state props across mounted link transitions', async () => { + const root = createRootRoute() + const router = createRouter({ + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: '/active' }), + createRoute({ getParentRoute: () => root, path: '/other' }), + ]), + history: createMemoryHistory({ initialEntries: ['/active'] }), + rewrite: { + output: ({ url }) => + url.pathname === '/rewritten' + ? new URL('https://other.example/rewritten') + : url, + }, + }) + await router.load() + const activeProps = vi.fn(() => ({ + className: 'active-state', + style: { color: 'red' }, + href: 'javascript:active()', + })) + const inactiveProps = vi.fn(() => ({ + className: 'inactive-state', + style: { color: 'blue' }, + href: 'javascript:inactive()', + })) + const content = (to: string) => ( + + + Target + + + ) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + const view = render(content('/active')) + for (const [to, href, state] of [ + ['/active', '/active', 'active'], + [ + 'https://other.example/direct', + 'https://other.example/direct', + 'external', + ], + ['/rewritten', 'https://other.example/rewritten', 'external'], + ['javascript:blocked()', null, 'inactive'], + ['/other', '/other', 'inactive'], + ['/active', '/active', 'active'], + ] as const) { + activeProps.mockClear() + inactiveProps.mockClear() + view.rerender(content(to)) + const anchor = view.getByText('Target') + expect(anchor.getAttribute('href')).toBe(href) + expect(anchor.className).toBe( + state === 'external' ? 'base' : `base ${state}-state`, + ) + expect(anchor).toHaveStyle({ + color: + state === 'active' + ? 'rgb(255, 0, 0)' + : state === 'inactive' + ? 'rgb(0, 0, 255)' + : 'rgb(0, 0, 0)', + fontWeight: '700', + }) + expect(anchor.getAttribute('aria-current')).toBe( + state === 'active' ? 'page' : null, + ) + expect(anchor.getAttribute('aria-disabled')).toBe( + href === null ? 'true' : null, + ) + if (state === 'external') { + expect(activeProps).not.toHaveBeenCalled() + expect(inactiveProps).not.toHaveBeenCalled() + } + } + } finally { + warn.mockRestore() + } +}) + +test.each([ + { active: true, masked: false, server: false }, + { active: true, masked: true, server: false }, + { active: false, masked: false, server: false }, + { active: false, masked: true, server: false }, + { active: true, masked: false, server: true }, + { active: true, masked: true, server: true }, + { active: false, masked: false, server: true }, + { active: false, masked: true, server: true }, +])( + 'state props preserve routing while disabled changes (active: $active, masked: $masked, server: $server)', + async ({ active, masked, server }) => { + const root = createRootRoute() + const router = createRouter({ + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: '/active' }), + createRoute({ getParentRoute: () => root, path: '/inactive' }), + ]), + history: createMemoryHistory({ + initialEntries: [active ? '/active' : '/inactive'], + }), + isServer: server, + }) + disposers.push(router.history.destroy) + await router.load() + const stateProps = { + className: 'state-class', + href: 'javascript:active()', + target: '_self', + disabled: false, + } + const content = (disabled: boolean) => ( + + + Target + + + ) + const view = server ? undefined : render(content(false)) + for (const disabled of [false, true, false]) { + let anchor: HTMLElement + if (view) { + view.rerender(content(disabled)) + anchor = view.getByText('Target') + } else { + const container = document.createElement('div') + container.innerHTML = renderToString(content(disabled)) + const link = container.querySelector('a') + expect(link).not.toBeNull() + if (!link) { + throw new Error('Expected the server-rendered Link') + } + anchor = link + } + expect(anchor).toHaveClass('state-class') + expect(anchor).toHaveAttribute('target', '_blank') + if (active) { + expect(anchor).toHaveAttribute('aria-current', 'page') + } else { + expect(anchor).not.toHaveAttribute('aria-current') + } + if (disabled) { + expect(anchor).not.toHaveAttribute('href') + expect(anchor).toHaveAttribute('aria-disabled', 'true') + } else { + expect(anchor).toHaveAttribute('href', masked ? '/masked' : '/active') + expect(anchor).not.toHaveAttribute('aria-disabled') + } + } + }, +) + +test('functional state props preserve styling and href precedence across transitions', async () => { + const root = createRootRoute() + const router = createRouter({ + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: '/active' }), + createRoute({ getParentRoute: () => root, path: '/other' }), + ]), + history: createMemoryHistory({ initialEntries: ['/active'] }), + }) + await router.load() + const activeProps = vi.fn(() => ({ + className: 'active-state', + style: { color: 'red' }, + href: 'javascript:active()', + })) + const inactiveProps = vi.fn(() => ({ + className: 'inactive-state', + style: { color: 'blue' }, + href: 'javascript:inactive()', + })) + let version = 0 + const content = (to = '/active') => ( + + + Target + + + ) + const view = render(content()) + for (const pathname of ['/active', '/other', '/active']) { + await act(() => router.navigate({ to: pathname })) + activeProps.mockClear() + inactiveProps.mockClear() + view.rerender(content()) + const active = pathname === '/active' + expect(active ? activeProps : inactiveProps).toHaveBeenCalled() + expect(active ? inactiveProps : activeProps).not.toHaveBeenCalled() + const anchor = view.getByText('Target') + expect(anchor).toHaveAttribute('href', '/active') + expect(anchor.className).toBe( + `base ${active ? 'active-state' : 'inactive-state'}`, + ) + expect(anchor).toHaveStyle({ + color: active ? 'rgb(255, 0, 0)' : 'rgb(0, 0, 255)', + fontWeight: '700', + }) + } + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + view.rerender(content('javascript:blocked()')) + expect(view.getByText('Target')).not.toHaveAttribute('href') + expect(view.getByText('Target').className).toBe('base inactive-state') + } finally { + warn.mockRestore() + } +}) + +test.each([ + { active: true, server: false }, + { active: false, server: false }, + { active: true, server: true }, + { active: false, server: true }, +])( + 'selected state props override base props (active: $active, server: $server)', + async ({ active, server }) => { + const baseClick = vi.fn() + const selectedClick = vi.fn((event: React.MouseEvent) => + event.preventDefault(), + ) + const unusedClick = vi.fn() + const stateRef = React.createRef() + let resolvedRef: React.Ref | undefined + const stateProps = { + ref: stateRef, + title: 'state title', + onClick: selectedClick, + className: 'state-class', + style: { color: 'blue' }, + } + const history = createMemoryHistory({ initialEntries: ['/target'] }) + disposers.push(history.destroy) + function TestLink() { + const props = useLinkProps({ + to: active ? '/target' : '/', + target: '_blank', + title: 'base title', + onClick: baseClick, + className: 'base', + style: { color: 'red', marginTop: 2 }, + activeProps: active ? stateProps : { onClick: unusedClick }, + inactiveProps: active ? { onClick: unusedClick } : stateProps, + preload: false, + }) + resolvedRef = props.ref + return Override + } + const root = createRootRoute({ component: TestLink }) + const router = createRouter({ + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: '/' }), + createRoute({ getParentRoute: () => root, path: '/target' }), + ]), + history, + isServer: server, + scrollRestoration: false, + }) + + let link: HTMLElement + if (server) { + await router.load() + const container = document.createElement('div') + container.innerHTML = renderToString() + const anchor = container.querySelector('a') + expect(anchor).not.toBeNull() + if (!anchor) { + throw new Error('Expected the server-rendered Link') + } + link = anchor + } else { + render() + link = await screen.findByRole('link', { name: 'Override' }) + } + + expect(resolvedRef).toBe(stateRef) + expect(link).toHaveAttribute('title', 'state title') + expect(link).toHaveClass('base', 'state-class') + expect(link.style).toMatchObject({ color: 'blue', marginTop: '2px' }) + if (!server) { + fireEvent.click(link) + expect(selectedClick).toHaveBeenCalledOnce() + expect(baseClick).not.toHaveBeenCalled() + expect(unusedClick).not.toHaveBeenCalled() + } + }, +) diff --git a/packages/react-router/tests/link.bench.tsx b/packages/react-router/tests/link.bench.tsx index a04149ed61..6871afc8a4 100644 --- a/packages/react-router/tests/link.bench.tsx +++ b/packages/react-router/tests/link.bench.tsx @@ -1,5 +1,6 @@ import { render } from '@testing-library/react' -import { bench, describe } from 'vitest' +import { describe, test } from 'vitest' +import { getRouteSegments } from '@tanstack/router-core' import { Link, RouterProvider, @@ -37,8 +38,16 @@ const InterpolatePathLink = ({ to, params, children, -}: React.PropsWithChildren) => { - const href = interpolatePath({ path: to, params }).interpolatedPath +}: React.PropsWithChildren<{ + to: string + params: Record +}>) => { + const router = useRouter() + const href = interpolatePath( + to, + getRouteSegments(router.routesByPath[to])!, + params, + ) return {children} } @@ -73,9 +82,8 @@ describe.each([ ])('$name', ({ numberOfRoutes, numberOfLinks, matchedParamId }) => { const renderRouter = createRouterRenderer(numberOfRoutes) - bench( - 'hardcoded href', - () => { + test('hardcoded href', async ({ bench }) => { + await bench('hardcoded href', () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( @@ -84,13 +92,13 @@ describe.each([ )), ) render() - }, - { warmupIterations: 1 }, - ) + }).run({ + warmupIterations: 1, + }) + }) - bench( - 'interpolate path', - () => { + test('interpolate path', async ({ bench }) => { + await bench('interpolate path', () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( ) - }, - { warmupIterations: 1 }, - ) + }).run({ + warmupIterations: 1, + }) + }) - bench( - 'build location', - () => { + test('build location', async ({ bench }) => { + await bench('build location', () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( ) - }, - { warmupIterations: 1 }, - ) + }).run({ + warmupIterations: 1, + }) + }) - bench( - 'link to absolute path', - () => { + test('link to absolute path', async ({ bench }) => { + await bench('link to absolute path', () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( ) - }, - { warmupIterations: 1 }, - ) + }).run({ + warmupIterations: 1, + }) + }) - bench( - 'link to relative path', - () => { + test('link to relative path', async ({ bench }) => { + await bench('link to relative path', () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => { const to = `./params/$param${Math.min(i, matchedParamId)}` @@ -165,13 +173,13 @@ describe.each([ }), ) render() - }, - { warmupIterations: 1 }, - ) + }).run({ + warmupIterations: 1, + }) + }) - bench( - 'link to current path', - () => { + test('link to current path', async ({ bench }) => { + await bench('link to current path', () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( @@ -180,7 +188,8 @@ describe.each([ )), ) render() - }, - { warmupIterations: 1 }, - ) + }).run({ + warmupIterations: 1, + }) + }) }) diff --git a/packages/react-router/tests/link.test-d.tsx b/packages/react-router/tests/link.test-d.tsx index 143905ef38..d510d75485 100644 --- a/packages/react-router/tests/link.test-d.tsx +++ b/packages/react-router/tests/link.test-d.tsx @@ -4009,8 +4009,7 @@ test('when passing a component with props to createLink and navigating to the ro test('that createLink refs forward correctly', () => { // copied from: https://tanstack.com/router/latest/docs/framework/react/guide/custom-link#basic-example - interface BasicLinkProps - extends React.AnchorHTMLAttributes {} + interface BasicLinkProps extends React.AnchorHTMLAttributes {} const BasicLinkComponent = React.forwardRef< HTMLAnchorElement, BasicLinkProps diff --git a/packages/react-router/tests/link.test.tsx b/packages/react-router/tests/link.test.tsx index bbb9fd8f04..56c4ece9db 100644 --- a/packages/react-router/tests/link.test.tsx +++ b/packages/react-router/tests/link.test.tsx @@ -1,4 +1,5 @@ import React from 'react' +import { renderToString } from 'react-dom/server' import { afterEach, beforeEach, describe, expect, it, test, vi } from 'vitest' import { act, @@ -16,6 +17,7 @@ import { trailingSlashOptions } from '@tanstack/router-core' import { Link, Outlet, + RouterContextProvider, RouterProvider, createBrowserHistory, createHashHistory, @@ -27,9 +29,11 @@ import { createRouteMask, createRouter, getRouteApi, + notFound, redirect, retainSearchParams, stripSearchParams, + useLinkProps, useLoaderData, useMatchRoute, useParams, @@ -37,6 +41,7 @@ import { useRouterState, useSearch, } from '../src' +import { composeHandlers } from '../src/link' import { getIntersectionObserverMock, getSearchParamsFromURI, @@ -46,12 +51,16 @@ import type { RouterHistory } from '../src' const ioObserveMock = vi.fn() const ioDisconnectMock = vi.fn() +let ioCallback: IntersectionObserverCallback let history: RouterHistory beforeEach(() => { const io = getIntersectionObserverMock({ observe: ioObserveMock, disconnect: ioDisconnectMock, + onCreate: (callback) => { + ioCallback = callback + }, }) vi.stubGlobal('IntersectionObserver', io) history = createBrowserHistory() @@ -59,6 +68,7 @@ beforeEach(() => { }) afterEach(() => { + vi.useRealTimers() history.destroy() window.history.replaceState(null, 'root', '/') vi.resetAllMocks() @@ -67,6 +77,71 @@ afterEach(() => { const WAIT_TIME = 300 +describe('composeHandlers', () => { + const createEvent = (defaultPrevented = false) => { + const event = { + defaultPrevented, + preventDefault() { + event.defaultPrevented = true + }, + } + + return event as unknown as React.SyntheticEvent + } + + test('returns the internal handler directly when no user handler is supplied', () => { + const second = vi.fn() + const handler = composeHandlers(undefined, second) + + expect(handler).toBe(second) + }) + + test('preserves an already-prevented event when a user handler is supplied', () => { + const first = vi.fn() + const second = vi.fn() + const handler = composeHandlers(first, second) + + handler(createEvent(true)) + + expect(first).not.toHaveBeenCalled() + expect(second).not.toHaveBeenCalled() + }) + + test('calls the internal handler when the user handler does not prevent the event', () => { + const first = vi.fn() + const second = vi.fn() + const handler = composeHandlers(first, second) + const event = createEvent() + + handler(event) + + expect(first).toHaveBeenCalledWith(event) + expect(second).toHaveBeenCalledWith(event) + }) + + test('does not call the internal handler when the user handler prevents the event', () => { + const first = vi.fn((event: React.SyntheticEvent) => event.preventDefault()) + const second = vi.fn() + const handler = composeHandlers(first, second) + const event = createEvent() + + handler(event) + + expect(first).toHaveBeenCalledWith(event) + expect(second).not.toHaveBeenCalled() + }) + + test('calls the internal handler directly for an already-prevented event without a user handler', () => { + const second = vi.fn() + const handler = composeHandlers(undefined, second) + const event = createEvent(true) + + handler(event) + + expect(second).toHaveBeenCalledWith(event) + }) +}) + describe('Link', () => { test('when using renderHook it returns a hook with same content to prove rerender works', async () => { /** @@ -168,6 +243,7 @@ describe('Link', () => { expect(window.location.pathname).toBe('/') expect(postsLink).not.toBeDisabled() + expect(postsLink).not.toHaveAttribute('disabled') expect(postsLink).toHaveAttribute('aria-disabled', 'true') fireEvent.click(postsLink) @@ -177,6 +253,96 @@ describe('Link', () => { ).rejects.toThrow() }) + test('does not forward internal Link props to the DOM', async () => { + const consoleErrorSpy = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + const internalPropNames = [ + 'activeProps', + 'inactiveProps', + 'activeOptions', + 'to', + 'from', + 'preload', + 'preloadDelay', + 'preloadIntentProximity', + 'hashScrollIntoView', + 'replace', + 'startTransition', + 'resetScroll', + 'viewTransition', + 'ignoreBlocker', + 'params', + 'search', + 'hash', + 'state', + 'mask', + 'reloadDocument', + 'unsafeRelative', + ].map((propName) => propName.toLowerCase()) + + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + + Posts + + ), + }) + + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + component: () =>

    Posts

    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, postsRoute]), + history, + }) + + render() + + const postsLink = await screen.findByRole('link', { name: 'Posts' }) + const renderedAttributeNames = postsLink + .getAttributeNames() + .map((attributeName) => attributeName.toLowerCase()) + + for (const propName of internalPropNames) { + expect(renderedAttributeNames).not.toContain(propName) + } + + expect(consoleErrorSpy).not.toHaveBeenCalled() + }) + test('when the current route is the root', async () => { const rootRoute = createRootRoute() const indexRoute = createRoute({ @@ -421,6 +587,468 @@ describe('Link', () => { }) }) + describe('active and href updates', () => { + const createControlledPromise = () => { + let resolve!: () => void + const promise = new Promise((r) => { + resolve = r + }) + + return { promise, resolve } + } + + test('always reports external links as inactive', async () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + + {({ isActive }) => ( + {String(isActive)} + )} + + ), + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render() + + expect( + await screen.findByTestId('external-link-active'), + ).toHaveTextContent('false') + }) + + test('updates exact and fuzzy active state before the next route renders', async () => { + const postLoader = createControlledPromise() + + const rootRoute = createRootRoute({ + component: () => ( + <> + + Posts exact + + + Posts fuzzy + + + Post exact + + + + ), + }) + + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'posts', + component: () => ( + <> +

    Posts

    + + Open post + + + + ), + }) + + const postRoute = createRoute({ + getParentRoute: () => postsRoute, + path: '$postId', + loader: () => postLoader.promise, + component: () =>

    Post detail

    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([postsRoute.addChildren([postRoute])]), + history: createMemoryHistory({ initialEntries: ['/posts'] }), + defaultPendingMs: 0, + defaultPendingComponent: () =>

    Loading...

    , + }) + + render() + + const postsExact = await screen.findByTestId('posts-exact') + const postsFuzzy = await screen.findByTestId('posts-fuzzy') + const postExact = await screen.findByTestId('post-exact') + + expect(postsExact).toHaveClass('active') + expect(postsFuzzy).toHaveClass('active') + expect(postExact).toHaveClass('inactive') + + await act(() => fireEvent.click(screen.getByTestId('open-post'))) + + expect(await screen.findByText('Loading...')).toBeInTheDocument() + expect(screen.queryByText('Post detail')).not.toBeInTheDocument() + expect(router.state.location.pathname).toBe('/posts/1') + expect(postsExact).toHaveClass('inactive') + expect(postsFuzzy).toHaveClass('active') + expect(postExact).toHaveClass('active') + + postLoader.resolve() + + expect(await screen.findByText('Post detail')).toBeInTheDocument() + }) + + test('updates exact active state and href when only params change with params=true', async () => { + const postLoader = createControlledPromise() + let postLoadCount = 0 + + const rootRoute = createRootRoute({ + component: CurrentPostLinks, + }) + + function CurrentPostLinks() { + const { postId } = useParams({ strict: false }) + const nextPostId = postId === '1' ? '2' : '1' + + return ( + <> + + Current post + + + Switch post + + + + ) + } + + const postRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts/$postId', + loader: () => { + postLoadCount += 1 + return postLoadCount === 1 ? Promise.resolve() : postLoader.promise + }, + component: PostPage, + }) + + function PostPage() { + const { postId } = useParams({ strict: false }) + return

    {`Post ${postId}`}

    + } + + const router = createRouter({ + routeTree: rootRoute.addChildren([postRoute]), + history: createMemoryHistory({ initialEntries: ['/posts/1'] }), + defaultPendingMs: 0, + defaultPendingComponent: () =>

    Loading...

    , + }) + + render() + + const currentPost = await screen.findByTestId('current-post') + expect(await screen.findByText('Post 1')).toBeInTheDocument() + expect(currentPost).toHaveClass('active') + expect(currentPost).toHaveAttribute('href', '/posts/1') + + await act(() => fireEvent.click(screen.getByTestId('switch-post'))) + + expect(await screen.findByText('Loading...')).toBeInTheDocument() + expect(screen.queryByText('Post 2')).not.toBeInTheDocument() + expect(router.state.location.pathname).toBe('/posts/2') + expect(currentPost).toHaveClass('active') + + await waitFor(() => { + expect(currentPost).toHaveAttribute('href', '/posts/2') + }) + + postLoader.resolve() + + expect(await screen.findByText('Post 2')).toBeInTheDocument() + }) + + test('updates search-sensitive active state immediately with and without search=true', async () => { + const postsLoader = createControlledPromise() + let postsLoadCount = 0 + + const rootRoute = createRootRoute({ + component: CurrentSearchLinks, + }) + + function CurrentSearchLinks() { + const search = useSearch({ strict: false }) + const nextPage = Number(search.page ?? 1) === 1 ? 2 : 1 + + return ( + <> + + Static search + + + Current search + + + Switch search + + + + ) + } + + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + validateSearch: (input: Record) => ({ + page: Number(input.page ?? 1), + }), + loaderDeps: ({ search }) => ({ page: search.page }), + loader: () => { + postsLoadCount += 1 + return postsLoadCount === 1 ? Promise.resolve() : postsLoader.promise + }, + component: PostsPage, + }) + + function PostsPage() { + const search = useSearch({ strict: false }) + return

    {`Posts ${search.page}`}

    + } + + const router = createRouter({ + routeTree: rootRoute.addChildren([postsRoute]), + history: createMemoryHistory({ initialEntries: ['/posts?page=1'] }), + defaultPendingMs: 0, + defaultPendingComponent: () =>

    Loading...

    , + }) + + render() + + const staticSearch = await screen.findByTestId('static-search') + const currentSearch = await screen.findByTestId('current-search') + + expect(await screen.findByText('Posts 1')).toBeInTheDocument() + expect(staticSearch).toHaveClass('active') + expect(currentSearch).toHaveClass('active') + expect(currentSearch).toHaveAttribute('href', '/posts?page=1') + + await act(() => fireEvent.click(screen.getByTestId('switch-search'))) + + expect(await screen.findByText('Loading...')).toBeInTheDocument() + expect(screen.queryByText('Posts 2')).not.toBeInTheDocument() + expect(router.state.location.search).toEqual({ page: 2 }) + expect(staticSearch).toHaveClass('inactive') + expect(currentSearch).toHaveClass('active') + + await waitFor(() => { + expect(currentSearch).toHaveAttribute('href', '/posts?page=2') + }) + + postsLoader.resolve() + + expect(await screen.findByText('Posts 2')).toBeInTheDocument() + }) + + test('updates hash-sensitive active state immediately with and without hash=true', async () => { + const rootRoute = createRootRoute({ + component: () => ( + <> + + Static hash + + + Current hash + + + Switch hash + + + + ), + }) + + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + component: () =>

    Posts

    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([postsRoute]), + history: createMemoryHistory({ initialEntries: ['/posts#first'] }), + }) + + render() + + const staticHash = await screen.findByTestId('static-hash') + const currentHash = await screen.findByTestId('current-hash') + + expect(staticHash).toHaveClass('active') + expect(currentHash).toHaveClass('active') + expect(currentHash).toHaveAttribute('href', '/posts#first') + + await act(() => fireEvent.click(screen.getByTestId('switch-hash'))) + + expect(router.state.location.hash).toBe('second') + expect(staticHash).toHaveClass('inactive') + expect(currentHash).toHaveClass('active') + + await waitFor(() => { + expect(currentHash).toHaveAttribute('href', '/posts#second') + }) + }) + + test('eventually updates relative hrefs when the current route changes', async () => { + const rootRoute = createRootRoute({ + component: () => ( + <> + + Relative foo + + + To posts + + + To invoices + + + + ), + }) + + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + component: () =>

    Posts

    , + }) + + const postsFooRoute = createRoute({ + getParentRoute: () => postsRoute, + path: 'foo', + component: () =>

    Posts foo

    , + }) + + const invoicesRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/invoices', + component: () =>

    Invoices

    , + }) + + const invoicesFooRoute = createRoute({ + getParentRoute: () => invoicesRoute, + path: 'foo', + component: () =>

    Invoices foo

    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([ + postsRoute.addChildren([postsFooRoute]), + invoicesRoute.addChildren([invoicesFooRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + render() + + const relativeFoo = await screen.findByTestId('relative-foo') + expect(await screen.findByText('Posts')).toBeInTheDocument() + expect(relativeFoo).toHaveAttribute('href', '/posts/foo') + + await act(() => fireEvent.click(screen.getByTestId('to-invoices'))) + + expect(await screen.findByText('Invoices')).toBeInTheDocument() + + await waitFor(() => { + expect(relativeFoo).toHaveAttribute('href', '/invoices/foo') + }) + }) + + test('relative links from root keep javascript-like segments rooted', async () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => Continue, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + + expect( + await screen.findByRole('link', { name: 'Continue' }), + ).toHaveAttribute('href', '/javascript:alert(1)') + }) + }) + test('when the current route is the root with beforeLoad that throws', async () => { const onError = vi.fn() const rootRoute = createRootRoute({ @@ -523,10 +1151,13 @@ describe('Link', () => { expect(indexLink).not.toHaveAttribute('data-status', 'active') expect(indexLink).toHaveAttribute('href', '/') - expect(postsLink).toHaveAttribute('data-status', 'active') - expect(postsLink).toHaveAttribute('aria-current', 'page') - expect(postsLink).toHaveClass('active') - expect(postsLink).toHaveAttribute('href', '/posts') + // The clicked link left with the index page; check the posts page's own. + const activePostsLink = await screen.findByRole('link', { name: 'Posts' }) + expect(activePostsLink).not.toBe(postsLink) + expect(activePostsLink).toHaveAttribute('data-status', 'active') + expect(activePostsLink).toHaveAttribute('aria-current', 'page') + expect(activePostsLink).toHaveClass('active') + expect(activePostsLink).toHaveAttribute('href', '/posts') }) test('when navigating to /posts with a base url', async () => { @@ -583,10 +1214,13 @@ describe('Link', () => { expect(indexLink).not.toHaveAttribute('data-status', 'active') expect(indexLink).toHaveAttribute('href', '/app/') - expect(postsLink).toHaveAttribute('data-status', 'active') - expect(postsLink).toHaveAttribute('aria-current', 'page') - expect(postsLink).toHaveClass('active') - expect(postsLink).toHaveAttribute('href', '/app/posts') + // The clicked link left with the index page; check the posts page's own. + const activePostsLink = await screen.findByRole('link', { name: 'Posts' }) + expect(activePostsLink).not.toBe(postsLink) + expect(activePostsLink).toHaveAttribute('data-status', 'active') + expect(activePostsLink).toHaveAttribute('aria-current', 'page') + expect(activePostsLink).toHaveClass('active') + expect(activePostsLink).toHaveAttribute('href', '/app/posts') }) test('when navigating to /posts with search', async () => { @@ -1455,6 +2089,115 @@ describe('Link', () => { expect(notFoundComponent).not.toBeCalled() }) + test('404 thrown in child will bubble up to the root with beforeLoad', async () => { + const rootRoute = createRootRoute({ + notFoundComponent: () =>
    Root notFoundComponent
    , + beforeLoad: () => ({ ok: true }), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => { + return ( + <> +

    Index

    + Non existing post + + ) + }, + }) + + const postRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '$postId', + params: { + parse: (p) => { + if (p.postId === 'nonExistingPost') { + throw new Error('Post not exists') + } + return { + postId: p.postId, + } + }, + stringify: (p) => ({ postId: p.postId }), + }, + onError: () => { + throw notFound() + }, + component: () =>
    Existing Post
    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, postRoute]), + }) + + render() + + const postsLink = await screen.findByRole('link', { + name: 'Non existing post', + }) + await act(() => fireEvent.click(postsLink)) + + const errorText = await screen.findByText('Root notFoundComponent') + expect(errorText).toBeInTheDocument() + }) + + test('404 thrown in child will bubble up to the root with async loader', async () => { + const rootRoute = createRootRoute({ + notFoundComponent: () =>
    Root notFoundComponent
    , + loader: async () => { + await sleep(0) + return { ok: true } + }, + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => { + return ( + <> +

    Index

    + Non existing post + + ) + }, + }) + + const postRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '$postId', + params: { + parse: (p) => { + if (p.postId === 'nonExistingPost') { + throw new Error('Post not exists') + } + return { + postId: p.postId, + } + }, + stringify: (p) => ({ postId: p.postId }), + }, + onError: () => { + throw notFound() + }, + component: () =>
    Existing Post
    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, postRoute]), + }) + + render() + + const postsLink = await screen.findByRole('link', { + name: 'Non existing post', + }) + await act(() => fireEvent.click(postsLink)) + + const errorText = await screen.findByText('Root notFoundComponent') + expect(errorText).toBeInTheDocument() + }) + test('when navigating to /posts with params', async () => { const rootRoute = createRootRoute() const indexRoute = createRoute({ @@ -1521,6 +2264,120 @@ describe('Link', () => { expect(paramText).toBeInTheDocument() }) + test('keeps a relative link active when changing inherited params (issue #5655)', async () => { + const rootRoute = createRootRoute() + + const PostRouteComponent = () => { + const { postId } = useParams({ strict: false }) + + return ( + <> + + Step 1 + + + Step 2 + + + + ) + } + + const postRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/post/$postId', + component: PostRouteComponent, + }) + + const Step1RouteComponent = () => { + const { postId } = useParams({ strict: false }) + const otherPostId = postId === '1' ? '2' : '1' + + return ( + <> + {`Post ${postId} step1`} + {`Go to post ${otherPostId}`} + + ) + } + const step1Route = createRoute({ + getParentRoute: () => postRoute, + path: 'step1', + component: Step1RouteComponent, + }) + + const Step2RouteComponent = () => { + const { postId } = useParams({ strict: false }) + const otherPostId = postId === '1' ? '2' : '1' + + return ( + <> + {`Post ${postId} step2`} + {`Go to post ${otherPostId}`} + + ) + } + const step2Route = createRoute({ + getParentRoute: () => postRoute, + path: 'step2', + component: Step2RouteComponent, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([ + postRoute.addChildren([step1Route, step2Route]), + ]), + history: createMemoryHistory({ + initialEntries: ['/post/1/step1'], + }), + }) + + render() + + expect(await screen.findByText('Post 1 step1')).toBeInTheDocument() + expect(screen.getByTestId('step1-link')).toHaveClass('active') + + await act(() => fireEvent.click(screen.getByTestId('switch-post-link'))) + + expect(await screen.findByText('Post 2 step1')).toBeInTheDocument() + expect(router.state.location.pathname).toBe('/post/2/step1') + // This is the bug from #5655: step1 should stay active but is not. + expect(screen.getByTestId('step1-link')).toHaveClass('active') + + await act(() => fireEvent.click(screen.getByTestId('step2-link'))) + + expect(await screen.findByText('Post 2 step2')).toBeInTheDocument() + expect(router.state.location.pathname).toBe('/post/2/step2') + expect(screen.getByTestId('step2-link')).toHaveClass('active') + + await act(() => fireEvent.click(screen.getByTestId('switch-post-link'))) + + expect(await screen.findByText('Post 1 step2')).toBeInTheDocument() + expect(router.state.location.pathname).toBe('/post/1/step2') + expect(screen.getByTestId('step2-link')).toHaveClass('active') + }) + test('when navigating from /posts to ./$postId', async () => { const rootRoute = createRootRoute() const indexRoute = createRoute({ @@ -2044,10 +2901,16 @@ describe('Link', () => { const postRoute = createRoute({ getParentRoute: () => postsRoute, - path: '$postId/', + path: '$postId', component: PostComponent, }) + const postIndexRoute = createRoute({ + getParentRoute: () => postRoute, + path: '/', + component: () =>
    Post Index
    , + }) + const DetailsComponent = () => { return ( <> @@ -2080,7 +2943,11 @@ describe('Link', () => { indexRoute, layoutRoute.addChildren([ postsRoute.addChildren([ - postRoute.addChildren([detailsRoute, informationRoute]), + postRoute.addChildren([ + postIndexRoute, + detailsRoute, + informationRoute, + ]), ]), ]), ]), @@ -4332,6 +5199,270 @@ describe('Link', () => { expect(ioDisconnectMock).toBeCalledTimes(1) // it should not disconnect again }) + test('Link.preload="viewport" should respect preloadDelay', async () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + <> + + Viewport Link + + + Intent Link + + + ), + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + history, + }) + const preloadRouteSpy = vi.spyOn(router, 'preloadRoute') + + render() + + const viewportLink = await screen.findByRole('link', { + name: 'Viewport Link', + }) + const intentLink = await screen.findByRole('link', { name: 'Intent Link' }) + vi.useFakeTimers() + + ioCallback([], {} as IntersectionObserver) + ioCallback( + [ + { + isIntersecting: false, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).not.toHaveBeenCalled() + + ioCallback( + [ + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + ioCallback( + [ + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + fireEvent.mouseLeave(viewportLink) + + expect(preloadRouteSpy).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(49) + expect(preloadRouteSpy).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + expect(preloadRouteSpy).toHaveBeenCalledOnce() + + ioCallback( + [ + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + { + isIntersecting: false, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).toHaveBeenCalledOnce() + + ioCallback( + [ + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + await vi.advanceTimersByTimeAsync(49) + + ioCallback( + [ + { + isIntersecting: false, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + await vi.advanceTimersByTimeAsync(1) + expect(preloadRouteSpy).toHaveBeenCalledTimes(2) + + fireEvent.mouseEnter(intentLink) + fireEvent.mouseLeave(intentLink) + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).toHaveBeenCalledTimes(2) + }) + + test('Link.preload="viewport" should cancel and use new link options after they change', async () => { + const rootRoute = createRootRoute() + const RouteComponent = () => { + const [to, setTo] = React.useState<'/about' | '/other'>('/about') + const [preload, setPreload] = React.useState< + 'viewport' | 'intent' | false + >('viewport') + return ( + <> + + + + + Viewport Link + + + ) + } + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: RouteComponent, + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + const otherRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute, otherRoute]), + history, + }) + const preloadRouteSpy = vi.spyOn(router, 'preloadRoute') + + render() + + const viewportLink = await screen.findByRole('link', { + name: 'Viewport Link', + }) + const initialIoCallback = ioCallback + vi.useFakeTimers() + + ioCallback( + [ + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + + fireEvent.click(screen.getByRole('button', { name: 'Change destination' })) + expect(viewportLink).toHaveAttribute('href', '/other') + expect(ioCallback).not.toBe(initialIoCallback) + + ioCallback( + [ + { + isIntersecting: false, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).not.toHaveBeenCalled() + + ioCallback( + [ + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + fireEvent.click(screen.getByRole('button', { name: 'Change destination' })) + expect(viewportLink).toHaveAttribute('href', '/about') + + ioCallback( + [ + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).toHaveBeenCalledTimes(1) + expect(preloadRouteSpy).toHaveBeenCalledWith( + expect.objectContaining({ to: '/about' }), + ) + + preloadRouteSpy.mockClear() + fireEvent.click(screen.getByRole('button', { name: 'Use intent' })) + fireEvent.mouseEnter(viewportLink) + fireEvent.click(screen.getByRole('button', { name: 'Disable preload' })) + fireEvent.mouseLeave(viewportLink) + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).not.toHaveBeenCalled() + + // An effect with preloading disabled owns no resources. Re-enabling it + // must still install cancellation for a newly scheduled intent timer. + fireEvent.click(screen.getByRole('button', { name: 'Use intent' })) + fireEvent.mouseEnter(viewportLink) + await vi.advanceTimersByTimeAsync(49) + expect(preloadRouteSpy).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: 'Disable preload' })) + await vi.advanceTimersByTimeAsync(1) + expect(preloadRouteSpy).not.toHaveBeenCalled() + + fireEvent.click(screen.getByRole('button', { name: 'Use intent' })) + fireEvent.mouseEnter(viewportLink) + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).toHaveBeenCalledTimes(1) + + preloadRouteSpy.mockClear() + fireEvent.click(screen.getByRole('button', { name: 'Disable preload' })) + initialIoCallback( + [ + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).not.toHaveBeenCalled() + }) + test("Router.preload='render', should trigger the route loader on render", async () => { const mock = vi.fn() @@ -4373,6 +5504,114 @@ describe('Link', () => { expect(mock).toHaveBeenCalledTimes(1) }) + test.each([undefined, false, 'render', 'viewport'] as const)( + 'Link.preload="%s" should not preload on focus, hover, or touchstart', + async (preloadMode) => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + <> +

    Index Heading

    + + About Link + + + ), + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + component: () =>

    About Heading

    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([aboutRoute, indexRoute]), + defaultPreload: false, + defaultPreloadDelay: 0, + history, + }) + + const preloadRouteSpy = vi.spyOn(router, 'preloadRoute') + + render() + + const aboutLink = await screen.findByRole('link', { name: 'About Link' }) + expect(aboutLink).toBeInTheDocument() + + if (preloadMode === 'render') { + await waitFor(() => + expect(preloadRouteSpy.mock.calls.length).toBeGreaterThan(0), + ) + } + + const baselineCalls = preloadRouteSpy.mock.calls.length + + fireEvent.focus(aboutLink) + fireEvent.mouseOver(aboutLink) + fireEvent.touchStart(aboutLink) + + await sleep(100) + expect(preloadRouteSpy).toHaveBeenCalledTimes(baselineCalls) + }, + ) + + test('Link.preload="intent" should preload on focus, hover, and touchstart', async () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + <> +

    Index Heading

    + + About Link + + + ), + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + component: () =>

    About Heading

    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([aboutRoute, indexRoute]), + defaultPreload: false, + defaultPreloadDelay: 0, + history, + }) + + const preloadRouteSpy = vi.spyOn(router, 'preloadRoute') + + render() + + const aboutLink = await screen.findByRole('link', { name: 'About Link' }) + expect(aboutLink).toBeInTheDocument() + + const baselineCalls = preloadRouteSpy.mock.calls.length + + fireEvent.focus(aboutLink) + await waitFor(() => + expect(preloadRouteSpy).toHaveBeenCalledTimes(baselineCalls + 1), + ) + + fireEvent.mouseOver(aboutLink) + await waitFor(() => + expect(preloadRouteSpy).toHaveBeenCalledTimes(baselineCalls + 2), + ) + + fireEvent.touchStart(aboutLink) + await waitFor(() => + expect(preloadRouteSpy).toHaveBeenCalledTimes(baselineCalls + 3), + ) + }) + test('Router.preload="intent", pendingComponent renders during unresolved route loader', async () => { const rootRoute = createRootRoute() const indexRoute = createRoute({ @@ -5570,14 +6809,12 @@ describe('splat routes with empty splat', () => { async (trailingSlash) => { const tail = trailingSlash === 'always' ? '/' : '' - const rootRoute = createRootRoute() - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', + // The links stay mounted across the navigation so they can turn active. + const rootRoute = createRootRoute({ component: () => { return ( <> -

    Index Route

    + { ) }, }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => { + return

    Index Route

    + }, + }) const splatRoute = createRoute({ getParentRoute: () => rootRoute, @@ -6500,8 +7744,8 @@ describe('encoded and unicode paths', () => { name: 'with prefix', path: '/foo/prefix@대{$}', expectedPath: - '/foo/prefix@%EB%8C%80test[s%5C/.%5C/parameter%25!%F0%9F%9A%80@]', - expectedLocation: '/foo/prefix@대test[s%5C/.%5C/parameter%25!🚀@]', + '/foo/prefix@%EB%8C%80test[s%5C/.%5C/parameter%25!%F0%9F%9A%80%40]', + expectedLocation: '/foo/prefix@대test[s%5C/.%5C/parameter%25!🚀%40]', params: { _splat: 'test[s\\/.\\/parameter%!🚀@]', '*': 'test[s\\/.\\/parameter%!🚀@]', @@ -6511,8 +7755,8 @@ describe('encoded and unicode paths', () => { name: 'with suffix', path: '/foo/{$}대suffix@', expectedPath: - '/foo/test[s%5C/.%5C/parameter%25!%F0%9F%9A%80@]%EB%8C%80suffix@', - expectedLocation: '/foo/test[s%5C/.%5C/parameter%25!🚀@]대suffix@', + '/foo/test[s%5C/.%5C/parameter%25!%F0%9F%9A%80%40]%EB%8C%80suffix@', + expectedLocation: '/foo/test[s%5C/.%5C/parameter%25!🚀%40]대suffix@', params: { _splat: 'test[s\\/.\\/parameter%!🚀@]', '*': 'test[s\\/.\\/parameter%!🚀@]', @@ -6603,3 +7847,758 @@ describe('encoded and unicode paths', () => { }, ) }) + +describe('protocolAllowlist', () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + <> + + + + ), + }) + + let consoleWarn = vi.fn() + beforeEach(() => { + consoleWarn = vi.fn() + vi.spyOn(console, 'warn').mockImplementation(consoleWarn) + }) + afterEach(() => { + vi.restoreAllMocks() + }) + + it('should work like normal links when protocolAllowlist is set', async () => { + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + protocolAllowlist: ['x-safari-https:', 'intent:'], + }) + render() + const links = await screen.findAllByRole('link') + expect(links[0]).toHaveAttribute('href', 'x-safari-https://example.com') + expect(links[1]).toHaveAttribute( + 'href', + 'intent://example.com#Intent;scheme=https;end', + ) + expect(consoleWarn).not.toHaveBeenCalled() + }) + + it('should block links when protocol is not in allowlist', async () => { + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + protocolAllowlist: [], + }) + render() + expect( + await screen.findByTestId('custom-protocol-link'), + ).not.toHaveAttribute('href') + expect(screen.getByTestId('intent-protocol-link')).not.toHaveAttribute( + 'href', + ) + expect(consoleWarn).toHaveBeenCalledWith( + 'Blocked Link with dangerous protocol: x-safari-https://example.com', + ) + expect(consoleWarn).toHaveBeenCalledWith( + 'Blocked Link with dangerous protocol: intent://example.com#Intent;scheme=https;end', + ) + }) +}) + +describe('masked and custom history hrefs', () => { + test.each([false, true])( + 'updates a mounted link across destination types (rewrite: %s)', + async (rewrite) => { + const nextLoader = vi.fn(() => 'next page') + const rootRoute = createRootRoute({ + component: function ChangingDestination() { + const [phase, setPhase] = React.useState(0) + const to = + phase === 0 + ? '/target' + : phase === 3 || rewrite + ? '/next' + : phase === 1 + ? 'https://other.example/next' + : 'javascript:alert(1)' + return ( + <> + + + {({ isActive }) => String(isActive)} + + + + ) + }, + }) + const targetRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/target', + component: () =>

    target page

    , + }) + const nextRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/next', + loader: nextLoader, + component: () =>

    next page

    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([targetRoute, nextRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + rewrite: rewrite + ? { + output: ({ url }) => + url.hash === '#external' + ? new URL('https://other.example/next') + : url.hash === '#blocked' + ? new URL('javascript:alert(1)') + : url, + } + : undefined, + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + render() + const link = await screen.findByTestId('changing-link') + expect(link).toHaveTextContent('true') + expect(link).toHaveAttribute('aria-current', 'page') + + const clickWasIntercepted = () => { + let intercepted = false + // Observe the router's handling, then cancel native document navigation. + document.addEventListener( + 'click', + (event) => { + intercepted = event.defaultPrevented + event.preventDefault() + }, + { once: true }, + ) + fireEvent.click(link) + return intercepted + } + for (const href of ['https://other.example/next', null]) { + fireEvent.click(screen.getByText('Change destination')) + await waitFor(() => expect(link.getAttribute('href')).toBe(href)) + expect(link).toHaveTextContent('false') + expect(link).not.toHaveAttribute('aria-current') + expect(clickWasIntercepted()).toBe(false) + fireEvent.mouseOver(link) + await act(() => sleep(10)) + expect(nextLoader).not.toHaveBeenCalled() + expect(screen.getByText('target page')).toBeInTheDocument() + fireEvent.mouseLeave(link) + } + fireEvent.click(screen.getByText('Change destination')) + await waitFor(() => expect(link).toHaveAttribute('href', '/next')) + fireEvent.mouseOver(link) + await waitFor(() => expect(nextLoader).toHaveBeenCalledTimes(1)) + expect(clickWasIntercepted()).toBe(true) + expect(await screen.findByText('next page')).toBeInTheDocument() + await waitFor(() => expect(link).toHaveTextContent('true')) + expect(link).toHaveAttribute('aria-current', 'page') + }, + ) + + test.each([ + { output: '/mask', href: '/formatted/mask', formatted: true }, + { + output: 'https://other.example/mask', + href: 'https://other.example/mask', + formatted: false, + }, + { output: 'javascript:alert(1)', href: null, formatted: false }, + ])( + 'validates the final masked href $output on server and client', + async ({ output, href, formatted }) => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + for (const isServer of [true, false]) { + const formatHref = vi.fn((path: string) => '/formatted' + path) + const customHistory = createBrowserHistory({ createHref: formatHref }) + const targetLoader = vi.fn(() => 'target') + const rootRoute = createRootRoute() + const targetRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: targetLoader, + }) + const router = createRouter({ + isServer, + routeTree: rootRoute.addChildren([targetRoute]), + history: customHistory, + rewrite: { + output: ({ url }) => + url.pathname === '/mask' && output !== '/mask' + ? new URL(output) + : url, + }, + }) + try { + await router.load() + formatHref.mockClear() + const element = ( + + + {({ isActive }) => String(isActive)} + + + ) + let container: HTMLElement + if (isServer) { + container = document.createElement('div') + container.innerHTML = renderToString(element) + } else { + container = render(element).container + } + const link = container.querySelector('a')! + expect(link.getAttribute('href')).toBe(href) + expect(link).toHaveTextContent('false') + expect(link).not.toHaveAttribute('aria-current') + if (formatted) { + expect(formatHref).toHaveBeenCalledWith('/mask') + } else { + expect(formatHref).not.toHaveBeenCalled() + if (!isServer) { + let intercepted = false + document.addEventListener( + 'click', + (event) => { + intercepted = event.defaultPrevented + event.preventDefault() + }, + { once: true }, + ) + fireEvent.click(link) + expect(intercepted).toBe(false) + fireEvent.mouseOver(link) + await act(() => sleep(10)) + expect(targetLoader).not.toHaveBeenCalled() + } + } + } finally { + cleanup() + customHistory.destroy() + } + } + }, + ) + + test('keeps direct-scheme links safe and inactive across SSR and client', async () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + <> + + {({ isActive }) => String(isActive)} + + + {({ isActive }) => String(isActive)} + + + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + await router.load() + + router.isServer = true + const serverContainer = document.createElement('div') + serverContainer.innerHTML = renderToString( + , + ) + + router.isServer = false + const { container: clientContainer } = render( + , + ) + + const getLinkState = (container: ParentNode, testId: string) => { + const link = container.querySelector(`[data-testid="${testId}"]`)! + return { + href: link.getAttribute('href'), + active: link.getAttribute('data-status'), + ariaCurrent: link.getAttribute('aria-current'), + role: link.getAttribute('role'), + ariaDisabled: link.getAttribute('aria-disabled'), + text: link.textContent, + } + } + + const serverStates = { + allowed: getLinkState(serverContainer, 'allowed-link'), + dangerous: getLinkState(serverContainer, 'dangerous-link'), + } + const clientStates = { + allowed: getLinkState(clientContainer, 'allowed-link'), + dangerous: getLinkState(clientContainer, 'dangerous-link'), + } + + expect(clientStates).toEqual(serverStates) + expect(clientStates.allowed).toMatchObject({ + href: 'https://example.com', + active: null, + ariaCurrent: null, + role: null, + ariaDisabled: null, + text: 'false', + }) + expect(clientStates.dangerous).toMatchObject({ + href: null, + active: null, + ariaCurrent: null, + role: 'link', + ariaDisabled: 'true', + text: 'false', + }) + }) + + test('renders every internal Link on the router origin', async () => { + const inputs = [ + '//evil.example', + '/\\evil.example', + '\\/evil.example', + ' \t/\\evil.example', + ] + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + <> + {inputs.map((to, index) => ( + + ))} + + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render() + + for (let index = 0; index < inputs.length; index++) { + const link = await screen.findByTestId(`unsafe-link-${index}`) + const href = link.getAttribute('href') + expect(href).not.toBeNull() + expect(new URL(href!, window.location.href).origin).toBe( + window.location.origin, + ) + } + }) + + test('blocks a dangerous final href produced by an output rewrite', async () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + rewrite: { + output: ({ url }) => + url.pathname === '/safe' ? new URL('javascript:alert(1)') : url, + }, + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + render() + const link = await screen.findByTestId('rewritten-link') + + expect(link).not.toHaveAttribute('href') + expect(link).toHaveAttribute('role', 'link') + expect(link).toHaveAttribute('aria-disabled', 'true') + expect(fireEvent.click(link)).toBe(true) + }) + + test('normalizes protocol-relative paths from output rewrites during SSR', () => { + const origin = 'https://victim.example' + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory({ initialEntries: ['/'] }), + origin, + isServer: true, + rewrite: { + output: ({ url }) => + url.pathname === '/safe' + ? new URL(`${origin}//evil.example/path`) + : url, + }, + }) + + const html = renderToString( + + Safe + , + ) + + expect(html).toContain('href="/evil.example/path"') + expect(html).not.toContain('href="//evil.example/path"') + }) + + test('blocks a dangerous final href produced by custom history', async () => { + const customHistory = createBrowserHistory({ + createHref: () => 'javascript:alert(1)', + }) + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: customHistory, + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + render() + const link = await screen.findByTestId('custom-history-link') + + expect(link).not.toHaveAttribute('href') + expect(fireEvent.click(link)).toBe(true) + customHistory.destroy() + }) + + test('does not transform a direct HTTPS link through custom history', async () => { + const customHistory = createBrowserHistory({ + createHref: () => 'https://other.example/', + }) + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: customHistory, + }) + try { + render() + const link = await screen.findByTestId('direct-https-link') + + expect(link).toHaveAttribute('href', 'https://intended.example/') + expect(fireEvent.click(link)).toBe(true) + } finally { + customHistory.destroy() + } + }) + + test('does not intercept an external href produced by custom history', async () => { + const customHistory = createBrowserHistory({ + createHref: () => 'https://other.example/path', + }) + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: customHistory, + }) + render() + const link = await screen.findByTestId('custom-history-link') + + expect(link).toHaveAttribute('href', 'https://other.example/path') + expect(fireEvent.click(link)).toBe(true) + customHistory.destroy() + }) + + test('blocked links stay inactive and cannot regain an href', async () => { + const rootRoute = createRootRoute() + const safeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + component: () => ( + + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([safeRoute]), + history: createMemoryHistory({ initialEntries: ['/safe'] }), + rewrite: { + output: ({ url }) => + url.hash === '#blocked' ? new URL('javascript:alert(1)') : url, + }, + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + render() + const link = await screen.findByTestId('rewritten-link') + + expect(link).not.toHaveAttribute('href') + expect(link).not.toHaveAttribute('aria-current') + expect(link).not.toHaveAttribute('data-active') + expect(link).toHaveAttribute('data-inactive', 'true') + expect(fireEvent.click(link)).toBe(true) + }) +}) + +describe('link re-render bail-out', () => { + // `useLinkProps` subscribes to the location store. Counting renders of a + // component that calls it therefore measures exactly what the subscription + // publishes: a link whose resolved href and active state are unaffected by a + // navigation should not re-render at all. + // + // The components are memoized so a re-render of the route component that owns + // them cannot be mistaken for the subscription firing, and the link options are + // module-stable for the same reason. + const stableOptions = { + unaffected: { to: '/elsewhere' } as const, + becomesActive: { to: '/posts' } as const, + } + + function setup() { + const renderCounts = { unaffected: 0, becomesActive: 0 } + + const CountingLink = React.memo(function CountingLink({ + name, + }: { + name: keyof typeof renderCounts + }) { + renderCounts[name]++ + const linkProps = useLinkProps(stableOptions[name]) + return
    + }) + + const rootRoute = createRootRoute({ + component: () => ( + <> + + + + Go + + + + ), + }) + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>

    Index

    , + }) + + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + component: () =>

    Posts

    , + }) + + const elsewhereRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/elsewhere', + component: () =>

    Elsewhere

    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + postsRoute, + elsewhereRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + return { router, renderCounts } + } + + test('does not re-render a link a navigation cannot affect', async () => { + const { router, renderCounts } = setup() + render() + + await screen.findByTestId('unaffected') + const before = { ...renderCounts } + expect(screen.getByTestId('becomesActive')).not.toHaveAttribute( + 'data-status', + ) + + fireEvent.click(await screen.findByTestId('go')) + expect(await screen.findByText('Posts')).toBeInTheDocument() + + // `/posts` gains its active state, so it has to re-render. + expect(renderCounts.becomesActive).toBeGreaterThan(before.becomesActive) + expect(screen.getByTestId('becomesActive')).toHaveAttribute( + 'data-status', + 'active', + ) + + // `/elsewhere` is neither the origin nor the destination: its href and + // active state are identical before and after, so the subscription must + // bail out rather than publish an equal value. Asserting the published + // values too, so a selector that returned a constant would still fail. + expect(renderCounts.unaffected).toBe(before.unaffected) + expect(screen.getByTestId('unaffected')).toHaveAttribute( + 'href', + '/elsewhere', + ) + expect(screen.getByTestId('unaffected')).not.toHaveAttribute('data-status') + }) +}) + +describe('explicit-undefined params are not collapsed into an empty object', () => { + // `params: { category: undefined }` clears an inherited optional param while + // `params: {}` inherits it, so the two build different locations. The link + // options are stabilised by value, and that comparison must not treat them as + // equal or the link keeps publishing the stale href. + it('updates href when params goes from {} to { category: undefined }', async () => { + function CategoryLink({ + params, + }: { + params: Record + }) { + return ( + + link + + ) + } + + const rootRoute = createRootRoute({ component: () => }) + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts/{-$category}', + component: function Posts() { + const [params, setParams] = React.useState< + Record + >({}) + return ( + <> + + + + ) + }, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([postsRoute]), + history: createMemoryHistory({ initialEntries: ['/posts/tech'] }), + }) + + render() + + await waitFor(() => + expect(screen.getByTestId('lnk')).toHaveAttribute('href', '/posts/tech'), + ) + + fireEvent.click(screen.getByTestId('clear')) + + await waitFor(() => + expect(screen.getByTestId('lnk')).toHaveAttribute('href', '/posts'), + ) + }) +}) + +test('reuses unmodified Link styles and merges active styles', async () => { + const baseStyle = { color: 'red', marginTop: 2 } + let renderedStyle: React.CSSProperties | undefined + function StyledLink() { + const props = useLinkProps({ + to: '/target', + style: baseStyle, + className: 'base', + activeProps: () => ({ + className: 'selected', + style: { color: 'blue' }, + }), + inactiveProps: () => ({ className: 'unselected' }), + }) + renderedStyle = props.style + return
    Styled target + } + const rootRoute = createRootRoute({ + component: () => ( + <> + + + + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + render() + + const link = await screen.findByRole('link', { name: 'Styled target' }) + expect(renderedStyle).toBe(baseStyle) + expect(link).toHaveClass('base', 'unselected') + + await act(() => router.navigate({ to: '/target' })) + + expect(renderedStyle).toEqual({ color: 'blue', marginTop: 2 }) + expect(link).toHaveClass('base', 'selected') + + await act(() => router.navigate({ to: '/' })) + + expect(renderedStyle).toBe(baseStyle) + expect(link).toHaveClass('base', 'unselected') +}) diff --git a/packages/react-router/tests/loaders.test.tsx b/packages/react-router/tests/loaders.test.tsx index 8d8ea54e73..b96931d61a 100644 --- a/packages/react-router/tests/loaders.test.tsx +++ b/packages/react-router/tests/loaders.test.tsx @@ -430,7 +430,7 @@ test('reproducer #4546', async () => { component: () => { return ( <> -
    +
    { } }) -test('clears pendingTimeout when match resolves', async () => { +test('does not show pending UI when loaders finish before their pending delays', async () => { const defaultPendingComponentOnMountMock = vi.fn() const nestedPendingComponentOnMountMock = vi.fn() const fooPendingComponentOnMountMock = vi.fn() @@ -716,7 +716,6 @@ test('clears pendingTimeout when match resolves', async () => { }) render() - await act(() => router.latestLoadPromise) const linkToFoo = await screen.findByTestId('link-to-foo') fireEvent.click(linkToFoo) const fooElement = await screen.findByText('Nested Foo page') @@ -730,7 +729,54 @@ test('clears pendingTimeout when match resolves', async () => { expect(fooPendingComponentOnMountMock).not.toHaveBeenCalled() }) -test('cancelMatches after pending timeout', async () => { +// https://github.com/TanStack/router/pull/7673 +test('#7673: a spontaneous loader AbortError renders the boundary without executing the route component', async () => { + history.replace('/app') + history.flush() + const rootRoute = createRootRoute({}) + const abortError = new DOMException('Aborted', 'AbortError') + const routeComponentRendered = vi.fn() + const renderedError = vi.fn() + let routeSignal: AbortSignal | undefined + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: async ({ abortController }): Promise<{ value: string }> => { + routeSignal = abortController.signal + return Promise.reject(abortError) + }, + component: () => { + routeComponentRendered() + const data = indexRoute.useLoaderData() + return
    {data.value}
    + }, + errorComponent: ({ error }) => { + renderedError(error) + return
    indexErrorComponent
    + }, + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + const router = createRouter({ routeTree, history, basepath: '/app' }) + + render() + + expect(await screen.findByTestId('index-error')).toBeInTheDocument() + expect(screen.queryByTestId('index-content')).not.toBeInTheDocument() + expect(routeComponentRendered).not.toHaveBeenCalled() + expect(renderedError).toHaveBeenCalledWith(abortError) + expect(routeSignal?.aborted).toBe(false) + expect( + router.state.matches.find((match) => match.routeId === indexRoute.id), + ).toMatchObject({ + status: 'error', + error: abortError, + }) + expect(window.location.pathname).toBe('/app') +}) + +test('navigating away from a pending route aborts its loader', async () => { function getPendingComponent(onMount: () => void) { const PendingComponent = () => { useEffect(() => { @@ -743,6 +789,7 @@ test('cancelMatches after pending timeout', async () => { } const onAbortMock = vi.fn() const fooPendingComponentOnMountMock = vi.fn() + let fooSignal: AbortSignal | undefined const rootRoute = createRootRoute({ component: () => (
    @@ -760,17 +807,18 @@ test('cancelMatches after pending timeout', async () => { const fooRoute = createRoute({ getParentRoute: () => rootRoute, path: '/foo', - pendingMs: WAIT_TIME * 20, + pendingMs: 0, loader: async ({ abortController }) => { + fooSignal = abortController.signal await new Promise((resolve) => { - const timer = setTimeout(() => { - resolve() - }, WAIT_TIME * 40) - abortController.signal.addEventListener('abort', () => { - onAbortMock() - clearTimeout(timer) - resolve() - }) + abortController.signal.addEventListener( + 'abort', + () => { + onAbortMock() + resolve() + }, + { once: true }, + ) }) }, pendingComponent: getPendingComponent(fooPendingComponentOnMountMock), @@ -784,16 +832,133 @@ test('cancelMatches after pending timeout', async () => { const routeTree = rootRoute.addChildren([fooRoute, barRoute]) const router = createRouter({ routeTree, history }) render() - await act(() => router.latestLoadPromise) const fooLink = await screen.findByTestId('link-to-foo') fireEvent.click(fooLink) - await sleep(WAIT_TIME * 30) const pendingElement = await screen.findByText('Pending...') expect(pendingElement).toBeInTheDocument() - const barLink = await screen.findByTestId('link-to-bar') - fireEvent.click(barLink) - const barElement = await screen.findByText('Bar page') + expect(fooSignal?.aborted).toBe(false) + await act(() => router.navigate({ to: '/bar' })) + const barElement = screen.getByText('Bar page') expect(barElement).toBeInTheDocument() + expect(fooPendingComponentOnMountMock).toHaveBeenCalled() + expect(onAbortMock).toHaveBeenCalledTimes(1) + expect(fooSignal?.aborted).toBe(true) + expect(screen.queryByText('Pending...')).not.toBeInTheDocument() + expect(screen.queryByText('Foo page')).not.toBeInTheDocument() + expect(router.state.location.href).toBe('/bar') + expect(router.state.status).toBe('idle') +}) + +test('reproducer for #6388 - rapid navigation between parameterized routes should not trigger errorComponent', async () => { + const errorComponentRenderCount = vi.fn() + const onAbortMock = vi.fn() + const loaderCompleteMock = vi.fn() + + const rootRoute = createRootRoute({ + component: () => ( +
    + + Home + + + Param 1 + + + Param 2 + + +
    + ), + }) + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home page
    , + }) + + const paramRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/something/$id', + pendingMs: 0, + loader: async ({ params, abortController }) => { + const result = await new Promise<{ id: string; done: boolean }>( + (resolve, reject) => { + const timer = setTimeout(() => { + loaderCompleteMock(params.id) + resolve({ id: params.id, done: true }) + }, WAIT_TIME * 5) + + abortController.signal.addEventListener('abort', () => { + clearTimeout(timer) + onAbortMock(params.id) + reject(new DOMException('Aborted', 'AbortError')) + }) + }, + ) + + return result + }, + component: () => { + const data = paramRoute.useLoaderData() + return ( +
    + Param Component {data.id} {data.done ? 'Done' : 'Not done'} +
    + ) + }, + errorComponent: ({ error }) => { + errorComponentRenderCount(error) + return ( +
    + Error Component:{' '} + {error instanceof Error ? error.message : String(error)} | Name:{' '} + {error instanceof Error ? error.name : typeof error} +
    + ) + }, + pendingComponent: () =>
    Pending
    , + }) + + const routeTree = rootRoute.addChildren([indexRoute, paramRoute]) + const router = createRouter({ + routeTree, + history, + defaultPreload: false, + }) + + render() + expect(await screen.findByTestId('home-page')).toBeInTheDocument() + const param1Link = await screen.findByTestId('link-to-param-1') + fireEvent.click(param1Link) + expect(await screen.findByTestId('pending-component')).toBeInTheDocument() + + const param2Link = await screen.findByTestId('link-to-param-2') + fireEvent.click(param2Link) + expect(await screen.findByTestId('pending-component')).toBeInTheDocument() + + fireEvent.click(param1Link) + expect(await screen.findByTestId('pending-component')).toBeInTheDocument() + + const paramPage = await screen.findByTestId('param-page') + expect(onAbortMock).toHaveBeenCalled() + expect(errorComponentRenderCount).not.toHaveBeenCalled() + expect(screen.queryByTestId('error-component')).not.toBeInTheDocument() + expect(screen.queryByTestId('pending-component')).not.toBeInTheDocument() + + expect(paramPage).toBeInTheDocument() + expect(paramPage).toHaveTextContent('Param Component 1 Done') + expect(loaderCompleteMock).toHaveBeenCalled() }) diff --git a/packages/react-router/tests/match-provider.test.tsx b/packages/react-router/tests/match-provider.test.tsx new file mode 100644 index 0000000000..bc947fff05 --- /dev/null +++ b/packages/react-router/tests/match-provider.test.tsx @@ -0,0 +1,90 @@ +import * as React from 'react' +import { act, cleanup, render, screen } from '@testing-library/react' +import { renderToString } from 'react-dom/server' +import { afterEach, expect, test } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + useMatch, +} from '../src' + +afterEach(cleanup) + +function NearestMatch({ name }: { name: string }) { + const match = useMatch({ strict: false }) + return {match.routeId} +} + +function createTestRouter( + disableGlobalCatchBoundary = false, + isServer = false, +) { + const root = createRootRoute({ + shellComponent: function Shell({ children }) { + const [count, setCount] = React.useState(0) + return ( +
    + + + {children} +
    + ) + }, + component: () => ( + <> + + + + ), + }) + const first = createRoute({ + getParentRoute: () => root, + path: '/first', + component: () => , + }) + const second = createRoute({ + getParentRoute: () => root, + path: '/second', + component: () => , + }) + return createRouter({ + routeTree: root.addChildren([first, second]), + history: createMemoryHistory({ initialEntries: ['/first'] }), + disableGlobalCatchBoundary, + isServer, + }) +} + +test.each([false, true])( + 'shell keeps nearest match context and state across navigation (global catch disabled: %s)', + async (disableGlobalCatchBoundary) => { + const router = createTestRouter(disableGlobalCatchBoundary) + await router.load() + render() + expect(await screen.findByTestId('leaf-match')).toHaveTextContent('/first') + expect(screen.getByTestId('shell-match')).toHaveTextContent('__root__') + expect(screen.getByTestId('root-match')).toHaveTextContent('__root__') + const shell = screen.getByTestId('shell') + act(() => screen.getByRole('button').click()) + await act(async () => { + await router.navigate({ to: '/second' }) + }) + expect(screen.getByTestId('leaf-match')).toHaveTextContent('/second') + expect(screen.getByTestId('shell-match')).toHaveTextContent('__root__') + expect(screen.getByTestId('shell')).toBe(shell) + expect(screen.getByRole('button')).toHaveTextContent('Count 1') + }, +) + +test('server shell and nested component read their nearest match context', async () => { + const router = createTestRouter(false, true) + await router.load() + const html = renderToString() + expect(html).toContain('data-testid="shell-match">__root__') + expect(html).toContain('data-testid="root-match">__root__') + expect(html).toContain('data-testid="leaf-match">/first') +}) diff --git a/packages/react-router/tests/navigate.test.tsx b/packages/react-router/tests/navigate.test.tsx index 3aaaa7124b..dd7b252c48 100644 --- a/packages/react-router/tests/navigate.test.tsx +++ b/packages/react-router/tests/navigate.test.tsx @@ -479,17 +479,26 @@ describe('router.navigate navigation using layout routes resolves correctly', () await router.load() expect(router.state.location.pathname).toBe('/search') - expect(router.state.location.search).toStrictEqual({ 'foo=bar': 2 }) + expect(router.state.location.search).toStrictEqual( + toNullObj({ 'foo=bar': 2 }), + ) await router.navigate({ search: { 'foo=bar': 3 }, } as any) await router.invalidate() - expect(router.state.location.search).toStrictEqual({ 'foo=bar': 3 }) + expect(router.state.location.search).toStrictEqual( + toNullObj({ 'foo=bar': 3 }), + ) }) }) +function toNullObj(obj: T): T { + if (typeof obj === 'object') return Object.assign(Object.create(null), obj) + return obj +} + describe('relative navigation', () => { it('should navigate to a child route', async () => { const { router } = createTestRouter( @@ -1300,8 +1309,8 @@ describe('encoded and unicode paths', () => { name: 'with prefix', path: '/foo/prefix@대{$}', expectedPath: - '/foo/prefix@%EB%8C%80test[s%5C/.%5C/parameter%25!%F0%9F%9A%80@]', - expectedLocation: '/foo/prefix@대test[s%5C/.%5C/parameter%25!🚀@]', + '/foo/prefix@%EB%8C%80test[s%5C/.%5C/parameter%25!%F0%9F%9A%80%40]', + expectedLocation: '/foo/prefix@대test[s%5C/.%5C/parameter%25!🚀%40]', params: { _splat: 'test[s\\/.\\/parameter%!🚀@]', '*': 'test[s\\/.\\/parameter%!🚀@]', @@ -1311,8 +1320,8 @@ describe('encoded and unicode paths', () => { name: 'with suffix', path: '/foo/{$}대suffix@', expectedPath: - '/foo/test[s%5C/.%5C/parameter%25!%F0%9F%9A%80@]%EB%8C%80suffix@', - expectedLocation: '/foo/test[s%5C/.%5C/parameter%25!🚀@]대suffix@', + '/foo/test[s%5C/.%5C/parameter%25!%F0%9F%9A%80%40]%EB%8C%80suffix@', + expectedLocation: '/foo/test[s%5C/.%5C/parameter%25!🚀%40]대suffix@', params: { _splat: 'test[s\\/.\\/parameter%!🚀@]', '*': 'test[s\\/.\\/parameter%!🚀@]', diff --git a/packages/react-router/tests/not-found-pending-context.test.tsx b/packages/react-router/tests/not-found-pending-context.test.tsx new file mode 100644 index 0000000000..6d3542f96d --- /dev/null +++ b/packages/react-router/tests/not-found-pending-context.test.tsx @@ -0,0 +1,118 @@ +import { act, cleanup, render, screen } from '@testing-library/react' +import { expect, test } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRouteWithContext, + createRoute, + createRouter, +} from '../src' + +function createGate() { + let resolve!: () => void + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise + }) + + return { promise, resolve } +} + +test('an automatic not-found destination shows pending UI until owner context is ready', async () => { + const beforeLoadStarted = createGate() + const beforeLoadGate = createGate() + let gateNextBeforeLoad = false + + const rootRoute = createRootRouteWithContext<{ product: string }>()({ + beforeLoad: async () => { + if (gateNextBeforeLoad) { + gateNextBeforeLoad = false + beforeLoadStarted.resolve() + await beforeLoadGate.promise + + return { user: 'Grace', access: 'editor' } + } + + return { user: 'Ada', access: 'reader' } + }, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>

    Loading account

    , + component: () => { + const context = rootRoute.useRouteContext() + + return ( +
    +

    Account portal

    + + {context.product} / {context.user} / {context.access} + + +
    + ) + }, + notFoundComponent: () => { + const context = rootRoute.useRouteContext() + + return ( +

    + Missing page for {context.product} / {context.user} / {context.access} +

    + ) + }, + }) + const dashboardRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/dashboard', + component: () =>

    Dashboard

    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([dashboardRoute]), + history: createMemoryHistory({ initialEntries: ['/dashboard'] }), + context: { product: 'Router Cloud' }, + }) + + let navigation: Promise | undefined + try { + render() + + expect(await screen.findByText('Dashboard')).toBeVisible() + expect(screen.getByTestId('owner-context')).toHaveTextContent( + 'Router Cloud / Ada / reader', + ) + + gateNextBeforeLoad = true + await act(async () => { + navigation = router.navigate({ to: '/missing' } as any) + await beforeLoadStarted.promise + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + + expect(screen.getByRole('status')).toHaveTextContent('Loading account') + expect(screen.getByTestId('owner-context')).not.toBeVisible() + + await act(async () => { + beforeLoadGate.resolve() + await navigation + }) + + expect( + screen.getByRole('heading', { name: 'Account portal' }), + ).toBeVisible() + expect(screen.getByTestId('owner-context')).toBeVisible() + expect(screen.getByTestId('owner-context')).toHaveTextContent( + 'Router Cloud / Grace / editor', + ) + expect(screen.getByTestId('not-found-context')).toHaveTextContent( + 'Missing page for Router Cloud / Grace / editor', + ) + expect(screen.queryByText('Dashboard')).not.toBeInTheDocument() + expect(screen.queryByText('Loading account')).not.toBeInTheDocument() + } finally { + beforeLoadGate.resolve() + await act(async () => { + await Promise.allSettled(navigation ? [navigation] : []) + }) + cleanup() + } +}) diff --git a/packages/react-router/tests/not-found-route-context.test.tsx b/packages/react-router/tests/not-found-route-context.test.tsx new file mode 100644 index 0000000000..5528efabec --- /dev/null +++ b/packages/react-router/tests/not-found-route-context.test.tsx @@ -0,0 +1,184 @@ +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRootRouteWithContext, + createRoute, + createRouter, + notFound, +} from '../src' +import { + RouterServer, + createRequestHandler, + renderRouterToString, +} from '../src/ssr/server' + +afterEach(cleanup) + +const expectedContext = 'from router / from root / from parent' + +function createRouteTree() { + const rootRoute = createRootRouteWithContext<{ + routerValue: string + }>()({ + context: () => ({ rootValue: 'from root' }), + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + context: () => ({ parentValue: 'from parent' }), + component: ParentComponent, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + context: (): { childValue: string } => { + throw notFound() + }, + component: () =>
    Child content
    , + notFoundComponent: ChildNotFoundComponent, + }) + + function ParentComponent() { + const context = parentRoute.useRouteContext() + + return ( + <> + + {[context.routerValue, context.rootValue, context.parentValue].join( + ' / ', + )} + + + + ) + } + + function ChildNotFoundComponent() { + const context = parentRoute.useRouteContext() + + return ( + + {[context.routerValue, context.rootValue, context.parentValue].join( + ' / ', + )} + + ) + } + + return rootRoute.addChildren([parentRoute.addChildren([childRoute])]) +} + +test('a client load-phase not-found preserves inherited ancestor context', async () => { + const router = createRouter({ + routeTree: createRouteTree(), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + context: { routerValue: 'from router' }, + }) + + render() + + expect(await screen.findByTestId('not-found-context')).toHaveTextContent( + expectedContext, + ) + expect(screen.getByTestId('parent-context')).toHaveTextContent( + expectedContext, + ) + expect(screen.queryByText('Child content')).not.toBeInTheDocument() +}) + +test('an SSR load-phase not-found preserves inherited ancestor context', async () => { + const response = await createRequestHandler({ + request: new Request('http://localhost/parent/child'), + createRouter: () => + createRouter({ + routeTree: createRouteTree(), + context: { routerValue: 'from router' }, + isServer: true, + }), + })(({ router, responseHeaders }) => + renderRouterToString({ + router, + responseHeaders, + children: , + }), + ) + + const html = await response.text() + + const document = new DOMParser().parseFromString(html, 'text/html') + expect( + document.querySelector('[data-testid="parent-context"]')?.textContent, + ).toBe(expectedContext) + expect( + document.querySelector('[data-testid="not-found-context"]')?.textContent, + ).toBe(expectedContext) + expect(html).not.toContain('Child content') +}) + +test('a root beforeLoad not-found exposes only completed root data', async () => { + const loader = vi.fn(() => ({ loaderValue: 'from loader' })) + + const rootRoute = createRootRoute({ + context: () => ({ contextValue: 'from context' }), + beforeLoad: (): { beforeLoadValue: string } => { + throw notFound() + }, + loader, + component: RootComponent, + notFoundComponent: () => ( +
    Root not found
    + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Index content
    , + }) + + function RootComponent() { + const context = rootRoute.useRouteContext() + const loaderData = rootRoute.useLoaderData() + + return ( +
    + + Context: {context.contextValue ?? 'unavailable'} + + + Before load: {context.beforeLoadValue ?? 'unavailable'} + + + Loader: {loaderData?.loaderValue ?? 'unavailable'} + + +
    + ) + } + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + + const notFoundContent = await screen.findByTestId('root-not-found') + const rootComponent = screen.getByTestId('root-component') + + expect(rootComponent).toContainElement(notFoundContent) + expect(screen.getByTestId('context-value')).toHaveTextContent( + 'Context: from context', + ) + expect(screen.getByTestId('before-load-value')).toHaveTextContent( + 'Before load: unavailable', + ) + expect(screen.getByTestId('loader-value')).toHaveTextContent( + 'Loader: unavailable', + ) + expect(screen.queryByText('Index content')).not.toBeInTheDocument() + expect(loader).not.toHaveBeenCalled() +}) diff --git a/packages/react-router/tests/not-found-route-lifecycle.test.tsx b/packages/react-router/tests/not-found-route-lifecycle.test.tsx new file mode 100644 index 0000000000..3a648c3326 --- /dev/null +++ b/packages/react-router/tests/not-found-route-lifecycle.test.tsx @@ -0,0 +1,64 @@ +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + notFound, +} from '../src' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +test('a structural descendant below a not-found boundary does not run onEnter when its component cannot render', async () => { + const parentOnEnter = vi.fn() + const unavailableOnEnter = vi.fn() + const descendantOnEnter = vi.fn() + + const rootRoute = createRootRoute() + const tenantRoute = createRoute({ + onEnter: parentOnEnter, + getParentRoute: () => rootRoute, + path: 'tenants/$tenantId', + }) + const unavailableSettingsRoute = createRoute({ + onEnter: unavailableOnEnter, + getParentRoute: () => tenantRoute, + path: 'settings', + beforeLoad: () => { + throw notFound() + }, + notFoundComponent: () =>
    Tenant settings unavailable
    , + }) + const profileRoute = createRoute({ + getParentRoute: () => unavailableSettingsRoute, + path: 'profile', + onEnter: descendantOnEnter, + component: () =>
    Profile settings
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + tenantRoute.addChildren([ + unavailableSettingsRoute.addChildren([profileRoute]), + ]), + ]), + history: createMemoryHistory({ + initialEntries: ['/tenants/acme/settings/profile'], + }), + }) + + render() + + expect( + await screen.findByText('Tenant settings unavailable'), + ).toBeInTheDocument() + + expect(screen.queryByText('Profile settings')).not.toBeInTheDocument() + expect(parentOnEnter).toHaveBeenCalled() + expect(unavailableOnEnter).toHaveBeenCalled() + expect(descendantOnEnter).not.toHaveBeenCalled() +}) diff --git a/packages/react-router/tests/not-found.test.tsx b/packages/react-router/tests/not-found.test.tsx index ce8bdf1207..436c386694 100644 --- a/packages/react-router/tests/not-found.test.tsx +++ b/packages/react-router/tests/not-found.test.tsx @@ -1,16 +1,25 @@ import { afterEach, beforeEach, expect, test } from 'vitest' -import { cleanup, render, screen } from '@testing-library/react' +import { act, cleanup, render, screen } from '@testing-library/react' import { Link, Outlet, RouterProvider, + Scripts, createBrowserHistory, + createControlledPromise, + createLazyRoute, createRootRoute, createRoute, createRouter, notFound, + rootRouteId, } from '../src' +import { + RouterServer, + createRequestHandler, + renderRouterToString, +} from '../src/ssr/server' import type { NotFoundRouteProps, RouterHistory } from '../src' let history: RouterHistory @@ -26,6 +35,194 @@ afterEach(() => { cleanup() }) +test('navigating to an actively preloaded missing URL renders the global not-found boundary', async () => { + const missingLoaderStarted = createControlledPromise() + const missingLoader = createControlledPromise() + const rootRoute = createRootRoute({ + component: Outlet, + notFoundComponent: () =>
    Missing URL boundary
    , + loader: ({ location }) => { + if (location.pathname === '/missing') { + missingLoaderStarted.resolve() + return missingLoader + } + return + }, + shouldReload: true, + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + + const preload = router.preloadRoute({ to: '/missing' } as any) + await missingLoaderStarted + const navigation = router.navigate({ to: '/missing' } as any) + missingLoader.resolve() + await act(() => Promise.all([preload, navigation])) + + expect(screen.getByText('Missing URL boundary')).toBeInTheDocument() + expect(screen.queryByText('Home')).not.toBeInTheDocument() +}) + +test('a lazy route notFoundComponent handles an eager beforeLoad failure', async () => { + const rootRoute = createRootRoute({ + component: Outlet, + notFoundComponent: () =>
    Root not found
    , + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const failingRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/lazy-not-found', + beforeLoad: () => { + throw notFound() + }, + }).lazy(() => + Promise.resolve( + createLazyRoute('/lazy-not-found')({ + notFoundComponent: () =>
    Lazy route not found
    , + }), + ), + ) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, failingRoute]), + history, + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + + await act(() => router.navigate({ to: '/lazy-not-found' })) + + expect(screen.getByText('Lazy route not found')).toBeInTheDocument() + expect(screen.queryByText('Root not found')).not.toBeInTheDocument() +}) + +test('SSR uses a lazy route notFoundComponent for an eager beforeLoad failure', async () => { + const rootRoute = createRootRoute({ + // Streaming SSR requires the boundary in the shell. + shellComponent: ({ children }) => ( + <> + {children} + + + ), + component: Outlet, + notFoundComponent: () =>
    Root not found
    , + }) + const failingRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/lazy-not-found', + beforeLoad: () => { + throw notFound() + }, + }).lazy(() => + Promise.resolve( + createLazyRoute('/lazy-not-found')({ + notFoundComponent: () =>
    Lazy route not found
    , + }), + ), + ) + const handler = createRequestHandler({ + request: new Request('http://localhost/lazy-not-found'), + createRouter: () => + createRouter({ + routeTree: rootRoute.addChildren([failingRoute]), + isServer: true, + }), + }) + + const response = await handler(({ router, responseHeaders }) => + renderRouterToString({ + router, + responseHeaders, + children: , + }), + ) + + expect(response.status).toBe(404) + const html = await response.text() + expect(html).toContain('Lazy route not found') + expect(html).not.toContain('Root not found') +}) + +test.each(['client', 'server'] as const)( + 'a lazy child boundary handles a fuzzy URL miss on the %s', + async (environment) => { + const rootRoute = createRootRoute({ + // Streaming SSR requires the boundary in the shell; the + // client render outputs no scripts here. + shellComponent: ({ children }) => ( + <> + {children} + + + ), + component: Outlet, + notFoundComponent: () =>
    Root fuzzy boundary
    , + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: Outlet, + notFoundComponent: () =>
    Parent fuzzy boundary
    , + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + }).lazy(() => + Promise.resolve( + createLazyRoute('/parent/child')({ + notFoundComponent: () =>
    Lazy child fuzzy boundary
    , + }), + ), + ) + const routeTree = rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]) + + if (environment === 'client') { + const router = createRouter({ routeTree, history }) + render() + await act(() => router.navigate({ to: '/parent/child/missing' as any })) + + expect(screen.getByText('Lazy child fuzzy boundary')).toBeInTheDocument() + expect( + screen.queryByText('Parent fuzzy boundary'), + ).not.toBeInTheDocument() + return + } + + const response = await createRequestHandler({ + request: new Request('http://localhost/parent/child/missing'), + createRouter: () => createRouter({ routeTree, isServer: true }), + })(({ router, responseHeaders }) => + renderRouterToString({ + router, + responseHeaders, + children: , + }), + ) + + expect(response.status).toBe(404) + const html = await response.text() + expect(html).toContain('Lazy child fuzzy boundary') + expect(html).not.toContain('Parent fuzzy boundary') + }, +) + test.each([ { notFoundMode: 'fuzzy' as const, @@ -245,3 +442,205 @@ test('defaultNotFoundComponent and notFoundComponent receives data props via spr const errorMessageComponent = await screen.findByTestId('message') expect(errorMessageComponent).toHaveTextContent(customData.message) }) + +test('component-thrown bare notFound renders current route notFoundComponent', async () => { + const rootRoute = createRootRoute({ + component: () => , + notFoundComponent: () => Root, + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: () => , + notFoundComponent: () => ( + Parent not found + ), + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + notFoundComponent: () => ( + Child not found + ), + component: () => { + throw notFound() + }, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + notFoundMode: 'fuzzy', + }) + + render() + await router.navigate({ to: '/parent/child' }) + + expect(await screen.findByTestId('child-not-found')).toBeInTheDocument() + expect(screen.queryByTestId('parent-not-found')).not.toBeInTheDocument() + expect(screen.queryByTestId('root-not-found')).not.toBeInTheDocument() +}) + +test('component-thrown bare notFound falls back to nearest ancestor notFoundComponent', async () => { + const rootRoute = createRootRoute({ + component: () => , + notFoundComponent: () => Root, + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: () => , + notFoundComponent: () => ( + Parent not found + ), + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + component: () => { + throw notFound() + }, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + notFoundMode: 'fuzzy', + }) + + render() + await router.navigate({ to: '/parent/child' }) + + expect(await screen.findByTestId('parent-not-found')).toBeInTheDocument() + expect(screen.queryByTestId('root-not-found')).not.toBeInTheDocument() +}) + +test('beforeLoad notFound with routeId targets root notFoundComponent', async () => { + const rootRoute = createRootRoute({ + component: () => , + notFoundComponent: () => ( + Root not found + ), + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: () => , + notFoundComponent: () => ( + Parent not found + ), + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: () => { + throw notFound({ routeId: rootRouteId }) + }, + component: () => Child, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + notFoundMode: 'fuzzy', + }) + + render() + await router.navigate({ to: '/parent/child' }) + + expect(await screen.findByTestId('root-not-found')).toBeInTheDocument() + expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() +}) + +test('beforeLoad notFound with routeId targets parent boundary and preserves parent loader data', async () => { + const rootRoute = createRootRoute({ + component: () => , + notFoundComponent: () => ( + Root not found + ), + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => ({ message: 'ready' }), + component: () => , + notFoundComponent: () => { + const loaderData = parentRoute.useLoaderData() + return ( + + {loaderData.message} + + ) + }, + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: () => { + throw notFound({ routeId: parentRoute.id }) + }, + component: () => Child, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + notFoundMode: 'fuzzy', + }) + + render() + await router.navigate({ to: '/parent/child' }) + + expect( + await screen.findByTestId('parent-not-found-with-loader-data'), + ).toHaveTextContent('ready') + expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() +}) + +test('beforeLoad notFound with non-exact routeId falls back to root notFoundComponent', async () => { + const rootRoute = createRootRoute({ + component: () => , + notFoundComponent: () => ( + Root not found + ), + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: () => , + notFoundComponent: () => ( + Parent not found + ), + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: () => { + throw notFound({ routeId: `${parentRoute.id}/` as never }) + }, + component: () => Child, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + notFoundMode: 'fuzzy', + }) + + render() + await router.navigate({ to: '/parent/child' }) + + expect(await screen.findByTestId('root-not-found')).toBeInTheDocument() + expect(screen.queryByTestId('parent-not-found')).not.toBeInTheDocument() + expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() +}) diff --git a/packages/react-router/tests/on-rendered-same-href-state.test.tsx b/packages/react-router/tests/on-rendered-same-href-state.test.tsx new file mode 100644 index 0000000000..76e7a0cb9d --- /dev/null +++ b/packages/react-router/tests/on-rendered-same-href-state.test.tsx @@ -0,0 +1,66 @@ +import { act } from 'react' +import { cleanup, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +const testCleanups: Array<() => void> = [] + +afterEach(() => { + while (testCleanups.length) { + testCleanups.pop()!() + } + cleanup() +}) + +test('onRendered fires for a same-href navigation with a new history key', async () => { + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Index
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Index')).toBeInTheDocument() + await waitFor(() => { + expect(router.state.status).toBe('idle') + expect(router.state.resolvedLocation?.href).toBe('/') + }) + const initialHistoryKey = router.state.resolvedLocation?.state.__TSR_key + expect(initialHistoryKey).toBeDefined() + + const onRendered = vi.fn() + const unsubscribe = router.subscribe('onRendered', onRendered) + testCleanups.push(unsubscribe) + await act(() => + router.navigate({ + to: '/', + state: { sameHrefState: true } as any, + }), + ) + await waitFor(() => expect(onRendered).toHaveBeenCalledTimes(1)) + + const event = onRendered.mock.calls[0]![0] + expect(event.fromLocation?.state.sameHrefState).toBeUndefined() + expect(event.toLocation.state.sameHrefState).toBe(true) + expect(event.fromLocation?.href).toBe('/') + expect(event.toLocation.href).toBe('/') + expect(event.hrefChanged).toBe(false) + expect(event.fromLocation?.state.__TSR_key).toBe(initialHistoryKey) + expect(event.toLocation.state.__TSR_key).toBeDefined() + expect(event.toLocation.state.__TSR_key).not.toBe(initialHistoryKey) + expect(router.state.resolvedLocation?.state.__TSR_key).toBe( + event.toLocation.state.__TSR_key, + ) +}) diff --git a/packages/react-router/tests/pending-fallback-promise-replacement.test.tsx b/packages/react-router/tests/pending-fallback-promise-replacement.test.tsx new file mode 100644 index 0000000000..0f5ca3703d --- /dev/null +++ b/packages/react-router/tests/pending-fallback-promise-replacement.test.tsx @@ -0,0 +1,138 @@ +import * as React from 'react' +import { act } from 'react' +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, render, screen } from '@testing-library/react' +import { createControlledPromise } from '@tanstack/router-core' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' +import type { AnyRouter } from '../src' + +afterEach(() => { + vi.useRealTimers() + cleanup() +}) + +test.each(['child', 'root'] as const)( + 'a mounted %s pending fallback follows an overlapping load generation', + async (routeLevel) => { + const firstReload = createControlledPromise() + const secondReload = createControlledPromise() + const reloads = [firstReload, secondReload] + let loaderCall = 0 + + const routeOptions = { + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    Loading...
    , + loader: () => { + const generation = ++loaderCall + const gate = reloads[generation - 2] + return gate ? gate.then(() => ({ generation })) : { generation } + }, + } + + const makeRouter = (): AnyRouter => { + if (routeLevel === 'root') { + const rootRoute = createRootRoute({ + ...routeOptions, + component: () => ( +
    + Generation {rootRoute.useLoaderData().generation} +
    + ), + }) + return createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + } + + const rootRoute = createRootRoute({ + component: () => , + }) + const pageRoute = createRoute({ + ...routeOptions, + getParentRoute: () => rootRoute, + path: '/page', + component: () => ( +
    + Generation {pageRoute.useLoaderData().generation} +
    + ), + }) + return createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + } + const router = makeRouter() + + render() + expect(await screen.findByText('Generation 1')).toBeInTheDocument() + + vi.useFakeTimers() + + let firstInvalidation!: Promise + await act(async () => { + firstInvalidation = router.invalidate({ forcePending: true }) + await vi.advanceTimersByTimeAsync(0) + }) + + expect(loaderCall).toBe(2) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(25) + }) + + let secondInvalidation!: Promise + await act(async () => { + secondInvalidation = router.invalidate({ forcePending: true }) + await vi.advanceTimersByTimeAsync(0) + }) + + expect(loaderCall).toBe(3) + + await act(async () => { + firstReload.resolve() + await Promise.resolve() + }) + + // Completing the superseded generation cannot release the currently + // mounted fallback or restore its stale loader data. + expect(screen.getByTestId('pending')).toBeInTheDocument() + expect(screen.queryByText('Generation 2')).not.toBeInTheDocument() + + let secondSettled = false + void secondInvalidation.then(() => { + secondSettled = true + }) + await act(async () => { + secondReload.resolve() + await Promise.resolve() + }) + + expect(secondSettled).toBe(false) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(74) + }) + expect(secondSettled).toBe(false) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + await Promise.all([firstInvalidation, secondInvalidation]) + }) + + expect(screen.getByText('Generation 3')).toBeInTheDocument() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + }, +) diff --git a/packages/react-router/tests/pending-route-context.test.tsx b/packages/react-router/tests/pending-route-context.test.tsx new file mode 100644 index 0000000000..5274fb83cc --- /dev/null +++ b/packages/react-router/tests/pending-route-context.test.tsx @@ -0,0 +1,298 @@ +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, test } from 'vitest' +import { + Outlet, + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(cleanup) + +test('a pending child observes settled ancestor context during beforeLoad and loader waits', async () => { + const childBeforeLoadStarted = createControlledPromise() + const childBeforeLoadGate = createControlledPromise() + const childLoaderStarted = createControlledPromise() + const childLoaderGate = createControlledPromise() + let navigation: Promise | undefined + + const rootRoute = createRootRoute({ + context: () => ({ + workspace: 'Router Team', + role: 'maintainer', + }), + component: RootComponent, + }) + const homeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: HomeComponent, + }) + const reportsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + beforeLoad: async ({ context }) => { + childBeforeLoadStarted.resolve() + await childBeforeLoadGate + + return { + report: 'Activity', + access: `${context.workspace}:${context.role}`, + } + }, + loader: async () => { + childLoaderStarted.resolve() + await childLoaderGate + }, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: ReportsPendingComponent, + component: ReportsComponent, + }) + + function RootComponent() { + const context = rootRoute.useRouteContext() + + return ( +
    +
    +

    {context.workspace}

    + + Workspace {context.workspace}; role {context.role} + +
    + +
    + ) + } + + function HomeComponent() { + const navigate = homeRoute.useNavigate() + + return ( +
    +

    Home

    + +
    + ) + } + + function ReportsPendingComponent() { + const parentContext = rootRoute.useRouteContext() + + return ( +
    + Loading reports + + Workspace {parentContext.workspace}; role {parentContext.role} + +
    + ) + } + + function ReportsComponent() { + const context = reportsRoute.useRouteContext() + + return ( +
    +

    Reports

    + + Workspace {context.workspace}; role {context.role}; report{' '} + {context.report}; access {context.access} + +
    + ) + } + + const router = createRouter({ + routeTree: rootRoute.addChildren([homeRoute, reportsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const view = render() + + try { + expect(await screen.findByRole('heading', { name: 'Home' })).toBeVisible() + expect(screen.getByTestId('root-context')).toHaveTextContent( + 'Workspace Router Team; role maintainer', + ) + + fireEvent.click(screen.getByRole('button', { name: 'View reports' })) + await act(async () => { + await childBeforeLoadStarted + }) + + expect(await screen.findByTestId('reports-pending')).toHaveTextContent( + 'Loading reports', + ) + expect(screen.getByTestId('root-context')).toHaveTextContent( + 'Workspace Router Team; role maintainer', + ) + expect(screen.getByTestId('pending-ancestor-context')).toHaveTextContent( + 'Workspace Router Team; role maintainer', + ) + expect(screen.queryByTestId('child-context')).not.toBeInTheDocument() + + await act(async () => { + childBeforeLoadGate.resolve() + await childLoaderStarted + }) + + expect(screen.getByTestId('reports-pending')).toHaveTextContent( + 'Loading reports', + ) + expect(screen.getByTestId('root-context')).toHaveTextContent( + 'Workspace Router Team; role maintainer', + ) + expect(screen.getByTestId('pending-ancestor-context')).toHaveTextContent( + 'Workspace Router Team; role maintainer', + ) + expect(screen.queryByTestId('child-context')).not.toBeInTheDocument() + + const childNavigation = navigation + if (!childNavigation) { + throw new Error('Expected child navigation to start') + } + + await act(async () => { + childLoaderGate.resolve() + await childNavigation + }) + + expect(screen.queryByTestId('reports-pending')).not.toBeInTheDocument() + expect(screen.getByTestId('root-context')).toHaveTextContent( + 'Workspace Router Team; role maintainer', + ) + expect(screen.getByTestId('child-context')).toHaveTextContent( + 'Workspace Router Team; role maintainer; report Activity; access Router Team:maintainer', + ) + } finally { + childBeforeLoadGate.resolve() + childLoaderGate.resolve() + await act(async () => { + await Promise.allSettled(navigation ? [navigation] : []) + }) + view.unmount() + } +}) + +test('overlapping invalidations keep the latest context through completion', async () => { + const secondChildLoaderStarted = createControlledPromise() + const secondChildLoaderGate = createControlledPromise() + const thirdRootBeforeLoadStarted = createControlledPromise() + const thirdRootBeforeLoadGate = createControlledPromise() + let contextGeneration = 0 + let childLoaderGeneration = 0 + + const rootRoute = createRootRoute({ + beforeLoad: async () => { + const generation = ++contextGeneration + + if (generation === 3) { + thirdRootBeforeLoadStarted.resolve() + await thirdRootBeforeLoadGate + } + + return { generation } + }, + component: () => ( +
    + + Root generation {rootRoute.useRouteContext().generation} + + +
    + ), + }) + const childRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: async () => { + if (++childLoaderGeneration === 2) { + secondChildLoaderStarted.resolve() + await secondChildLoaderGate + } + }, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>

    Loading child

    , + component: () =>

    Child content

    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const view = render() + let firstInvalidation: Promise | undefined + let secondInvalidation: Promise | undefined + + try { + expect(await screen.findByText('Child content')).toBeInTheDocument() + expect(screen.getByTestId('root-context')).toHaveTextContent( + 'Root generation 1', + ) + + await act(async () => { + firstInvalidation = router.invalidate({ forcePending: true }) + await secondChildLoaderStarted + await Promise.resolve() + }) + expect(screen.getByTestId('child-pending')).toHaveTextContent( + 'Loading child', + ) + expect(screen.getByTestId('root-context')).toHaveTextContent( + 'Root generation 2', + ) + + await act(async () => { + secondInvalidation = router.invalidate({ forcePending: true }) + await thirdRootBeforeLoadStarted + await Promise.resolve() + }) + + expect(screen.getByTestId('child-pending')).toHaveTextContent( + 'Loading child', + ) + expect(screen.getByTestId('root-context')).toHaveTextContent( + 'Root generation 2', + ) + await act(async () => { + thirdRootBeforeLoadGate.resolve() + await secondInvalidation + }) + expect(screen.getByTestId('root-context')).toHaveTextContent( + 'Root generation 3', + ) + expect(screen.getByText('Child content')).toBeVisible() + expect(screen.queryByTestId('child-pending')).not.toBeInTheDocument() + + await act(async () => { + secondChildLoaderGate.resolve() + await firstInvalidation + }) + expect(screen.getByTestId('root-context')).toHaveTextContent( + 'Root generation 3', + ) + expect(screen.getByText('Child content')).toBeVisible() + } finally { + await act(async () => { + secondChildLoaderGate.resolve() + thirdRootBeforeLoadGate.resolve() + await Promise.allSettled( + [firstInvalidation, secondInvalidation].filter( + (invalidation): invalidation is Promise => + invalidation !== undefined, + ), + ) + }) + view.unmount() + } +}) diff --git a/packages/react-router/tests/preloaded-mount-resolution.test.tsx b/packages/react-router/tests/preloaded-mount-resolution.test.tsx new file mode 100644 index 0000000000..1679546c79 --- /dev/null +++ b/packages/react-router/tests/preloaded-mount-resolution.test.tsx @@ -0,0 +1,155 @@ +import { afterEach, beforeEach, expect, onTestFinished, test, vi } from 'vitest' +import * as React from 'react' +import { createRoot } from 'react-dom/client' +import { createMemoryHistory } from '@tanstack/history' +import { + Outlet, + RouterProvider, + createControlledPromise, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +/** + * A load that settles before RouterProvider mounts (or completes within the + * mount effect's batch) gives the Transitioner no isLoading flip to observe. + * The router status must still resolve to 'idle' with resolvedLocation set, + * and onRendered must fire — otherwise consumers waiting on those signals + * deadlock forever (this hung the memory-client benchmark for 6 hours). + * + * Uses a raw createRoot without the act() test environment: act-driven + * flushing re-renders between the isLoading toggles and masks the race. + * + * Note: vitest's jsdom scheduler still observes the flip more often than the + * benchmark's environment, so this test pins the CONTRACT; the deterministic + * regression guard for the original hang is the memory-client:react + * benchmark (benchmarks/memory/client/scenarios/mount-unmount), which CI runs. + */ + +let prevActEnv: unknown + +beforeEach(() => { + prevActEnv = (globalThis as any).IS_REACT_ACT_ENVIRONMENT + ;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = false +}) + +afterEach(() => { + ;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = prevActEnv +}) + +test('mounting after a settled load still resolves status and fires onRendered', async () => { + const lifecycle: Array<'layout' | 'rendered'> = [] + const Home = () => { + React.useLayoutEffect(() => { + lifecycle.push('layout') + }, []) + return
    Home
    + } + const rootRoute = createRootRoute({ + component: () => , + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: () => 'home data', + component: Home, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + let resolveRendered!: () => void + const rendered = new Promise((resolve) => { + resolveRendered = resolve + }) + const onRendered = vi.fn(() => { + lifecycle.push('rendered') + resolveRendered() + }) + const onResolved = vi.fn() + const onLoad = vi.fn() + const unsubscribers = [ + router.subscribe('onRendered', onRendered), + router.subscribe('onResolved', onResolved), + router.subscribe('onLoad', onLoad), + ] + const unsubscribe = () => unsubscribers.forEach((fn) => fn()) + const container = document.createElement('div') + document.body.appendChild(container) + const reactRoot = createRoot(container) + let renderedTimeout: ReturnType | undefined + + onTestFinished(() => { + clearTimeout(renderedTimeout) + unsubscribe() + reactRoot.unmount() + container.remove() + }) + + // Load fully settles before the provider mounts — the exact shape of the + // memory benchmark's mount/unmount cycle. + await router.load() + expect(router.state.status).toBe('idle') + expect(router.state.resolvedLocation?.pathname).toBe('/') + expect(onLoad).toHaveBeenCalledTimes(1) + expect(onResolved).toHaveBeenCalledTimes(1) + expect(onRendered).not.toHaveBeenCalled() + + reactRoot.render() + await Promise.race([ + rendered, + new Promise((_, reject) => { + renderedTimeout = setTimeout(() => { + reject(new Error('Timed out waiting for onRendered')) + }, 2000) + }), + ]) + + expect(container.querySelector('[data-testid="home"]')).not.toBeNull() + expect(onRendered).toHaveBeenCalledTimes(1) + expect(lifecycle).toEqual(['layout', 'rendered']) + expect(router.state.status).toBe('idle') + expect(router.state.resolvedLocation?.pathname).toBe('/') +}) + +test('mounting during a load keeps the existing generation', async () => { + const gate = createControlledPromise() + const beforeLoad = vi.fn() + const loader = vi.fn(() => gate) + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + beforeLoad, + loader, + component: () =>
    Home
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const load = router.load() + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) + + const container = document.createElement('div') + document.body.appendChild(container) + const reactRoot = createRoot(container) + + onTestFinished(() => { + reactRoot.unmount() + container.remove() + }) + + reactRoot.render() + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledOnce()) + gate.resolve() + await load + await vi.waitFor(() => { + expect(container.querySelector('[data-testid="home"]')).not.toBeNull() + }) + + expect(beforeLoad).toHaveBeenCalledOnce() + expect(loader).toHaveBeenCalledOnce() +}) diff --git a/packages/react-router/tests/public-presentation-lane-contract.test.tsx b/packages/react-router/tests/public-presentation-lane-contract.test.tsx new file mode 100644 index 0000000000..644c4887e6 --- /dev/null +++ b/packages/react-router/tests/public-presentation-lane-contract.test.tsx @@ -0,0 +1,612 @@ +import { act, cleanup, render, screen, waitFor } from '@testing-library/react' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + notFound, +} from '../src' + +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +describe('public presentation lane contracts', () => { + test('visible pending UI publishes every matched route and its loading state', async () => { + const parentGate = createControlledPromise() + + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + pendingMs: 0, + pendingComponent: () =>
    Loading parent
    , + loader: () => parentGate, + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => 'child data', + component: () =>
    Child content
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + let navigation!: Promise + await act(async () => { + navigation = router.navigate({ to: '/parent/child' }) + await Promise.resolve() + }) + + expect(await screen.findByText('Loading parent')).toBeInTheDocument() + expect(screen.queryByText('Child content')).not.toBeInTheDocument() + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ status: 'pending', isFetching: 'loader' }) + + await act(async () => { + parentGate.resolve('parent data') + await navigation + }) + + expect(screen.getByText('Child content')).toBeInTheDocument() + expect(router.state.status).toBe('idle') + }) + + test('a plain load retry presents pending UI over a committed error', async () => { + const retryStarted = createControlledPromise() + const retry = createControlledPromise() + let attempt = 0 + + const rootRoute = createRootRoute({ component: Outlet }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>
    Retrying page
    , + loader: () => { + if (!attempt++) { + throw new Error('Initial failure') + } + retryStarted.resolve() + return retry + }, + errorComponent: () =>
    Page failed
    , + component: () =>
    {pageRoute.useLoaderData()}
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + render() + expect(await screen.findByText('Page failed')).toBeInTheDocument() + + let retryLoad!: Promise + try { + await act(async () => { + retryLoad = router.load() + await retryStarted + }) + expect(screen.getByText('Retrying page')).toBeInTheDocument() + expect(screen.getByText('Page failed')).not.toBeVisible() + + await act(async () => { + retry.resolve('Page recovered') + await retryLoad + }) + expect(screen.getByText('Page recovered')).toBeInTheDocument() + } finally { + retry.resolve('Page recovered') + await act(async () => { + await retryLoad + }) + consoleWarn.mockRestore() + } + }) + + test('same-boundary takeover republishes successor search without restarting pendingMinMs', async () => { + const firstGate = createControlledPromise() + const secondGate = createControlledPromise() + + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + validateSearch: (search: Record) => ({ + revision: Number(search.revision), + }), + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    Loading page
    , + beforeLoad: ({ search }) => + search.revision === 1 ? firstGate : secondGate, + component: () => { + const search = pageRoute.useSearch() + return
    Page revision {search.revision}
    + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + vi.useFakeTimers() + vi.setSystemTime(0) + + let successorSettled = false + let settledAtOriginalDeadline = false + let renderedAtOriginalDeadline = false + try { + await act(async () => { + void router.navigate({ + to: '/page', + search: { revision: 1 }, + }) + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByText('Loading page')).toBeInTheDocument() + expect(router.state.matches.at(-1)?.search).toMatchObject({ revision: 1 }) + + await act(async () => { + await vi.advanceTimersByTimeAsync(25) + }) + + let secondNavigation!: Promise + await act(async () => { + secondNavigation = router.navigate({ + to: '/page', + search: { revision: 2 }, + }) + await vi.advanceTimersByTimeAsync(0) + }) + + expect(screen.getByText('Loading page')).toBeInTheDocument() + expect(router.state.location.search).toMatchObject({ revision: 2 }) + expect(router.state.matches.at(-1)?.search).toMatchObject({ revision: 2 }) + + void secondNavigation.then(() => { + successorSettled = true + }) + await act(async () => { + secondGate.resolve() + await Promise.resolve() + }) + + await act(async () => { + await vi.advanceTimersByTimeAsync(74) + }) + expect(successorSettled).toBe(false) + expect(screen.getByText('Loading page')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(5) + await Promise.resolve() + }) + + settledAtOriginalDeadline = successorSettled + renderedAtOriginalDeadline = + screen.queryByText('Page revision 2') !== null + } finally { + // Finish a faulty implementation too, so a deadline assertion cannot + // strand this router and contaminate the following test. + firstGate.resolve() + secondGate.resolve() + await act(async () => { + await vi.advanceTimersByTimeAsync(1_000) + await Promise.resolve() + }) + } + + expect({ + settled: settledAtOriginalDeadline, + rendered: renderedAtOriginalDeadline, + }).toEqual({ settled: true, rendered: true }) + expect(screen.getByText('Page revision 2')).toBeInTheDocument() + expect(screen.queryByText('Loading page')).not.toBeInTheDocument() + }) + + test('an earlier pending-ineligible boundary retires a deeper pending minimum', async () => { + const childReloadStarted = createControlledPromise() + const childReload = createControlledPromise() + const parentReloadStarted = createControlledPromise() + const parentReload = createControlledPromise() + let childLoads = 0 + + const rootRoute = createRootRoute({ + validateSearch: (search: Record) => ({ + revision: Number(search.revision), + }), + component: Outlet, + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loaderDeps: ({ search }) => ({ revision: search.revision }), + beforeLoad: ({ search }) => { + if (search.revision === 2) { + parentReloadStarted.resolve() + return parentReload + } + return undefined + }, + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    Loading child
    , + loader: { + staleReloadMode: 'blocking', + handler: () => { + if (childLoads++) { + childReloadStarted.resolve() + return childReload + } + return undefined + }, + }, + component: () => ( +
    Child revision {childRoute.useSearch().revision}
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ + initialEntries: ['/parent/child?revision=1'], + }), + }) + + render() + expect(await screen.findByText('Child revision 1')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + vi.useFakeTimers() + vi.setSystemTime(0) + + let firstNavigation: Promise | undefined + let secondNavigation: Promise | undefined + let settledBeforeOldMinimum = false + let renderedBeforeOldMinimum = false + try { + await act(async () => { + firstNavigation = router.invalidate({ + filter: (match) => match.routeId === childRoute.id, + forcePending: true, + }) + await childReloadStarted + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByText('Loading child')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(25) + secondNavigation = router.navigate({ + to: '/parent/child', + search: { revision: 2 }, + }) + await parentReloadStarted + }) + expect(screen.getByText('Loading child')).toBeInTheDocument() + + childReload.resolve() + + const successor = secondNavigation + if (!successor) { + throw new Error('Expected the successor navigation to start') + } + void successor.then(() => { + settledBeforeOldMinimum = true + }) + await act(async () => { + parentReload.resolve() + await vi.advanceTimersByTimeAsync(5) + }) + renderedBeforeOldMinimum = screen.queryByText('Child revision 2') !== null + } finally { + childReload.resolve() + parentReload.resolve() + await act(async () => { + await vi.advanceTimersByTimeAsync(1_000) + await Promise.allSettled( + [firstNavigation, secondNavigation].filter( + (navigation): navigation is Promise => !!navigation, + ), + ) + }) + } + + expect({ + settled: settledBeforeOldMinimum, + rendered: renderedBeforeOldMinimum, + }).toEqual({ settled: true, rendered: true }) + }) + + test('same-boundary timing survives a private retained-context barrier', async () => { + const retainedStarted = createControlledPromise() + const retainedReady = createControlledPromise() + const firstPage = createControlledPromise() + const secondPageStarted = createControlledPromise() + const secondPage = createControlledPromise() + + const rootRoute = createRootRoute({ + validateSearch: (search: Record) => ({ + revision: Number(search.revision) || 0, + }), + beforeLoad: ({ search }) => { + if (search.revision === 2) { + retainedStarted.resolve() + return retainedReady.then(() => ({ rootRevision: 2 })) + } + return { rootRevision: search.revision } + }, + component: () => ( +
    +
    Root revision {rootRoute.useRouteContext().rootRevision}
    + +
    + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    Loading page
    , + beforeLoad: ({ search }) => { + if (search.revision === 1) { + return firstPage + } + secondPageStarted.resolve() + return secondPage + }, + component: () => ( +
    Page revision {pageRoute.useSearch().revision}
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + vi.useFakeTimers() + vi.setSystemTime(0) + + let firstNavigation: Promise | undefined + let secondNavigation: Promise | undefined + try { + await act(async () => { + firstNavigation = router.navigate({ + to: '/page', + search: { revision: 1 }, + }) + await vi.advanceTimersByTimeAsync(0) + }) + expect(screen.getByText('Loading page')).toBeInTheDocument() + expect(screen.getByText('Root revision 1')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(25) + secondNavigation = router.navigate({ + to: '/page', + search: { revision: 2 }, + }) + await retainedStarted + }) + + expect(screen.getByText('Loading page')).toBeInTheDocument() + expect(screen.getByText('Root revision 1')).toBeInTheDocument() + + await act(async () => { + retainedReady.resolve() + await secondPageStarted + }) + expect(screen.getByText('Loading page')).toBeInTheDocument() + expect(screen.getByText('Root revision 2')).toBeInTheDocument() + + let settled = false + const successor = secondNavigation + if (!successor) { + throw new Error('Expected the successor navigation to start') + } + void successor.then(() => { + settled = true + }) + await act(async () => { + secondPage.resolve() + await vi.advanceTimersByTimeAsync(74) + }) + expect(settled).toBe(false) + expect(screen.getByText('Loading page')).toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(5) + await Promise.all([firstNavigation, successor]) + }) + expect(screen.getByText('Page revision 2')).toBeInTheDocument() + } finally { + retainedReady.resolve() + firstPage.resolve() + secondPage.resolve() + await act(async () => { + await vi.advanceTimersByTimeAsync(1_000) + await Promise.allSettled( + [firstNavigation, secondNavigation].filter( + (navigation): navigation is Promise => !!navigation, + ), + ) + }) + } + }) + + test('an exact-boundary terminal result supersedes an unrendered pending offer', async () => { + const pendingRenderStarted = createControlledPromise() + const pendingRender = createControlledPromise() + const terminalLoadStarted = createControlledPromise() + const terminalLoad = createControlledPromise() + + const rootRoute = createRootRoute({ + validateSearch: (search: Record) => ({ + terminal: search.terminal === true, + }), + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () => { + pendingRenderStarted.resolve() + throw pendingRender + }, + beforeLoad: async ({ search }) => { + if (search.terminal) { + terminalLoadStarted.resolve() + await terminalLoad + throw notFound() + } + }, + notFoundComponent: () =>
    Root not found
    , + component: Outlet, + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/?terminal=false'] }), + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + vi.useFakeTimers() + vi.setSystemTime(0) + + let navigation: Promise | undefined + try { + await act(async () => { + navigation = router.navigate({ + to: '/', + search: { terminal: true }, + }) + await terminalLoadStarted + await vi.advanceTimersByTimeAsync(0) + await pendingRenderStarted + }) + expect(screen.getByText('Home')).toBeInTheDocument() + + await act(async () => { + terminalLoad.resolve() + await navigation + }) + + expect(screen.getByText('Root not found')).toBeInTheDocument() + expect(Date.now()).toBe(0) + } finally { + terminalLoad.resolve() + pendingRender.resolve() + await act(async () => { + await vi.advanceTimersByTimeAsync(1_000) + await Promise.allSettled(navigation ? [navigation] : []) + }) + } + }) + + test('a reentrant navigation from onResolved suppresses the stale onRendered event', async () => { + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const firstRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/first', + component: () =>
    First
    , + }) + const secondRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/second', + component: () =>
    Second
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, firstRoute, secondRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + const renderedPaths: Array = [] + let successor: Promise | undefined + const unsubscribeResolved = router.subscribe('onResolved', (event) => { + if (event.toLocation.pathname === '/first') { + successor = router.navigate({ to: '/second' }) + } + }) + const unsubscribeRendered = router.subscribe('onRendered', (event) => { + if (event.toLocation.pathname !== '/') { + renderedPaths.push(event.toLocation.pathname) + } + }) + + try { + await act(() => router.navigate({ to: '/first' })) + await act(async () => { + await successor + }) + + expect(screen.getByText('Second')).toBeInTheDocument() + expect(screen.queryByText('First')).not.toBeInTheDocument() + expect(renderedPaths).toEqual(['/second']) + } finally { + unsubscribeResolved() + unsubscribeRendered() + } + }) +}) diff --git a/packages/react-router/tests/react-render-owner-contract.test.tsx b/packages/react-router/tests/react-render-owner-contract.test.tsx new file mode 100644 index 0000000000..0797fa5264 --- /dev/null +++ b/packages/react-router/tests/react-render-owner-contract.test.tsx @@ -0,0 +1,101 @@ +import { act } from 'react' +import { cleanup, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRouter, +} from '../src' + +const testCleanups: Array<() => void> = [] + +afterEach(() => { + while (testCleanups.length) { + testCleanups.pop()!() + } + cleanup() +}) + +test('a suspended same-membership publication cannot acknowledge its successor', async () => { + const firstRenderStarted = createControlledPromise() + const firstRenderGate = createControlledPromise() + let signaledFirstRender = false + + const rootRoute = createRootRoute({ + validateSearch: (search: Record) => ({ + revision: Number(search.revision), + }), + component: () => { + const revision = rootRoute.useSearch().revision + if (revision === 1 && firstRenderGate.status === 'pending') { + if (!signaledFirstRender) { + signaledFirstRender = true + firstRenderStarted.resolve() + } + throw firstRenderGate + } + return
    Root revision {revision}
    + }, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/?revision=0'] }), + }) + + render() + expect(await screen.findByText('Root revision 0')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + const initialIds = router.state.matches.map((match) => match.routeId) + + const renderedRevisions: Array = [] + const unsubscribe = router.subscribe('onRendered', (event) => { + renderedRevisions.push( + Number((event.toLocation.search as Record).revision), + ) + }) + testCleanups.push(unsubscribe) + + let firstNavigation!: Promise + await act(async () => { + firstNavigation = router.navigate({ + to: '/', + search: { revision: 1 }, + }) + await firstRenderStarted + }) + + const firstSettled = vi.fn() + void firstNavigation.then(firstSettled) + expect(router.state.matches.map((match) => match.routeId)).toEqual(initialIds) + expect(router.state.matches[0]?.search.revision).toBe(1) + expect(screen.getByText('Root revision 0')).toBeInTheDocument() + expect(firstSettled).not.toHaveBeenCalled() + expect(renderedRevisions).toEqual([]) + + try { + await act(() => + router.navigate({ + to: '/', + search: { revision: 2 }, + }), + ) + await firstNavigation + + expect(screen.getByText('Root revision 2')).toBeInTheDocument() + expect(router.state.matches.map((match) => match.routeId)).toEqual( + initialIds, + ) + expect(renderedRevisions).toEqual([2]) + expect(firstSettled).toHaveBeenCalledOnce() + } finally { + await act(async () => { + firstRenderGate.resolve() + await Promise.resolve() + }) + } + + expect(screen.getByText('Root revision 2')).toBeInTheDocument() + expect(renderedRevisions).toEqual([2]) +}) diff --git a/packages/react-router/tests/redirect-chain-first-load.test.tsx b/packages/react-router/tests/redirect-chain-first-load.test.tsx new file mode 100644 index 0000000000..b3f4618a28 --- /dev/null +++ b/packages/react-router/tests/redirect-chain-first-load.test.tsx @@ -0,0 +1,110 @@ +import * as React from 'react' +import { cleanup, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' + +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + redirect, +} from '../src' +import { sleep } from './utils' + +afterEach(() => { + vi.restoreAllMocks() + cleanup() +}) + +// A chain of async layout beforeLoad redirects during the very first load +// (search-stripping self-redirect -> layout redirect -> child redirect) used +// to leave a match rendering with a nulled loadPromise, crashing +// MatchInnerImpl with an uncaught `undefined`. Pending UI is enabled for +// every match (defaultPendingMs: 0) to force pending publication mid-chain. +// The production auto-code-splitting reproduction for issue #7457 lives in +// e2e/react-router/issue-7457. +test('chained layout beforeLoad redirects on first load render the final target without throwing from MatchInner', async () => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + + const rootRoute = createRootRoute({ component: () => }) + + const userLayout = createRoute({ + id: 'user', + getParentRoute: () => rootRoute, + validateSearch: (search: Record): { flag?: boolean } => ({ + flag: search.flag === true || search.flag === 'true' ? true : undefined, + }), + beforeLoad: async ({ search }) => { + if (search.flag) { + await sleep(20) + throw redirect({ + to: '.', + replace: true, + search: (prev: any) => ({ ...prev, flag: undefined }), + }) + } + }, + component: () => , + }) + + const dashboardLayout = createRoute({ + id: 'dashboard', + getParentRoute: () => userLayout, + beforeLoad: async () => { + await sleep(30) + throw redirect({ to: '/intro', replace: true }) + }, + component: () => , + }) + + const homeRoute = createRoute({ + getParentRoute: () => dashboardLayout, + path: '/home', + component: () =>
    Home
    , + }) + + const introLayout = createRoute({ + getParentRoute: () => userLayout, + path: '/intro', + beforeLoad: ({ location }) => { + if (location.pathname !== '/intro/step') { + throw redirect({ to: '/intro/step', replace: true }) + } + }, + component: () => , + }) + + const introIndexRoute = createRoute({ + getParentRoute: () => introLayout, + path: '/', + component: () =>
    Intro index
    , + }) + + const introStepRoute = createRoute({ + getParentRoute: () => introLayout, + path: 'step', + component: () =>
    Intro step
    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([ + userLayout.addChildren([ + dashboardLayout.addChildren([homeRoute]), + introLayout.addChildren([introIndexRoute, introStepRoute]), + ]), + ]), + defaultPendingMs: 0, + defaultPendingComponent: () =>
    loading
    , + history: createMemoryHistory({ initialEntries: ['/home?flag=true'] }), + }) + + render() + + expect( + await screen.findByTestId('intro-step', undefined, { timeout: 5_000 }), + ).toBeInTheDocument() + expect(router.state.location.pathname).toBe('/intro/step') + expect(consoleError).not.toHaveBeenCalled() +}) diff --git a/packages/react-router/tests/redirect.test.tsx b/packages/react-router/tests/redirect.test.tsx index 70dd6918ce..ea8cd30dd4 100644 --- a/packages/react-router/tests/redirect.test.tsx +++ b/packages/react-router/tests/redirect.test.tsx @@ -1,4 +1,6 @@ +import * as React from 'react' import { + act, cleanup, configure, fireEvent, @@ -7,13 +9,13 @@ import { } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' -import invariant from 'tiny-invariant' import { Link, + Outlet, RouterProvider, createBrowserHistory, - createMemoryHistory, createRootRoute, createRoute, createRouter, @@ -26,6 +28,10 @@ import type { RouterHistory } from '../src' let history: RouterHistory +function getErrorMessage(error: unknown) { + return error instanceof Error ? error.message : String(error) +} + beforeEach(() => { history = createBrowserHistory() expect(window.location.pathname).toBe('/') @@ -44,6 +50,165 @@ const WAIT_TIME = 100 describe('redirect', () => { describe('SPA', () => { configure({ reactStrictMode: true }) + + test('allows a same-location redirect to settle after a side effect', async () => { + let firstLoad = true + const loader = vi.fn(() => { + if (firstLoad) { + firstLoad = false + throw redirect({ to: '/' }) + } + }) + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader, + component: () =>
    Index page
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render() + + expect(await screen.findByText('Index page')).toBeInTheDocument() + expect(window.location.pathname).toBe('/') + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.status).toBe('idle') + }) + + test('renders the source error boundary when building a redirect target fails', async () => { + const boom = new Error('redirect search failed') + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const sourceRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/source', + beforeLoad: () => { + throw redirect({ + to: '/target', + search: () => { + throw boom + }, + }) + }, + errorComponent: ({ error }) => ( +
    {getErrorMessage(error)}
    + ), + }) + const targetRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/target', + component: () =>
    Target
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + sourceRoute, + targetRoute, + ]), + history, + }) + + render() + expect(await screen.findByText('Home')).toBeInTheDocument() + + await act(() => router.navigate({ to: '/source' })) + + expect(await screen.findByTestId('source-error')).toHaveTextContent( + boom.message, + ) + expect(screen.queryByText('Home')).not.toBeInTheDocument() + expect(screen.queryByText('Target')).not.toBeInTheDocument() + expect(window.location.pathname).toBe('/source') + expect(router.state.status).toBe('idle') + }) + + test('renders a root error after too many same-location redirects', async () => { + const loader = vi.fn(() => { + throw redirect({ to: '/' }) + }) + const rootRoute = createRootRoute({ + errorComponent: ({ error }) => ( +
    Root: {getErrorMessage(error)}
    + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader, + errorComponent: ({ error }) => ( +
    Index: {getErrorMessage(error)}
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render() + + expect(await screen.findByTestId('root-error')).toHaveTextContent( + 'Root: Too many redirects', + ) + expect(screen.queryByTestId('index-error')).not.toBeInTheDocument() + expect(window.location.pathname).toBe('/') + expect(loader).toHaveBeenCalledTimes(21) + expect(router.state.status).toBe('idle') + }) + + test('renders a root error after too many alternating redirects', async () => { + const indexLoader = vi.fn(() => { + throw redirect({ to: '/other' }) + }) + const otherLoader = vi.fn(() => { + throw redirect({ to: '/' }) + }) + const rootRoute = createRootRoute({ + errorComponent: ({ error }) => ( +
    Root: {getErrorMessage(error)}
    + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: indexLoader, + errorComponent: ({ error }) => ( +
    Index: {getErrorMessage(error)}
    + ), + }) + const otherRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/other', + loader: otherLoader, + errorComponent: ({ error }) => ( +
    Other: {getErrorMessage(error)}
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, otherRoute]), + history, + }) + + render() + + expect(await screen.findByTestId('root-error')).toHaveTextContent( + 'Root: Too many redirects', + ) + expect(screen.queryByTestId('index-error')).not.toBeInTheDocument() + expect(screen.queryByTestId('other-error')).not.toBeInTheDocument() + expect(window.location.pathname).toBe('/') + expect(indexLoader).toHaveBeenCalledTimes(11) + expect(otherLoader).toHaveBeenCalledTimes(10) + expect(router.state.status).toBe('idle') + }) + test('when `redirect` is thrown in `beforeLoad`', async () => { const nestedLoaderMock = vi.fn() const nestedFooLoaderMock = vi.fn() @@ -112,6 +277,61 @@ describe('redirect', () => { expect(nestedFooLoaderMock).toHaveBeenCalled() }) + test('when root `beforeLoad` redirects while root pendingComponent is showing and the target route is lazy', async () => { + let hasRedirected = false + const beforeLoad = createControlledPromise() + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + + const rootRoute = createRootRoute({ + component: () => , + pendingMs: 0, + pendingComponent: () =>
    loading
    , + beforeLoad: async () => { + await beforeLoad + if (!hasRedirected) { + hasRedirected = true + throw redirect({ to: '/posts' }) + } + }, + }) + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Index page
    , + }) + + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }).lazy(() => import('./lazy/normal').then((d) => d.Route('/posts'))) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, postsRoute]), + history, + }) + + render() + + try { + expect(await screen.findByTestId('pending')).toBeInTheDocument() + } finally { + await act(() => { + beforeLoad.resolve() + }) + } + + // The lazy target route adds the async boundary that exposes the stale + // redirected-match render path this regression is guarding. + expect(await screen.findByTestId('lazy-route-page')).toBeInTheDocument() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(router.state.location.href).toBe('/posts') + expect(router.state.status).toBe('idle') + expect(consoleError).not.toHaveBeenCalled() + }) + test('when `redirect` is thrown in `loader`', async () => { const nestedLoaderMock = vi.fn() const nestedFooLoaderMock = vi.fn() @@ -264,116 +484,4 @@ describe('redirect', () => { expect(window.location.pathname).toBe('/final') }) }) - - describe('SSR', () => { - test('when `redirect` is thrown in `beforeLoad`', async () => { - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - beforeLoad: () => { - throw redirect({ - to: '/about', - }) - }, - }) - - const aboutRoute = createRoute({ - path: '/about', - getParentRoute: () => rootRoute, - component: () => { - return 'About' - }, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), - // Mock server mode - isServer: true, - history: createMemoryHistory({ - initialEntries: ['/'], - }), - }) - - await router.load() - - expect(router.state.redirect).toBeDefined() - expect(router.state.redirect).toBeInstanceOf(Response) - invariant(router.state.redirect) - - expect(router.state.redirect.options).toEqual({ - _fromLocation: expect.objectContaining({ - hash: '', - href: '/', - pathname: '/', - search: {}, - searchStr: '', - }), - to: '/about', - href: '/about', - statusCode: 307, - }) - }) - - test('when `redirect` is thrown in `loader`', async () => { - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - loader: () => { - throw redirect({ - to: '/about', - }) - }, - }) - - const aboutRoute = createRoute({ - path: '/about', - getParentRoute: () => rootRoute, - component: () => { - return 'About' - }, - }) - - const router = createRouter({ - history: createMemoryHistory({ - initialEntries: ['/'], - }), - routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), - // Mock server mode - isServer: true, - }) - - await router.load() - - const currentRedirect = router.state.redirect - - expect(currentRedirect).toBeDefined() - expect(currentRedirect).toBeInstanceOf(Response) - invariant(currentRedirect) - expect(currentRedirect.status).toEqual(307) - expect(currentRedirect.headers.get('Location')).toEqual('/about') - expect(currentRedirect.options).toEqual({ - _fromLocation: { - hash: '', - href: '/', - publicHref: '/', - pathname: '/', - search: {}, - searchStr: '', - state: { - __TSR_index: 0, - __TSR_key: currentRedirect.options._fromLocation!.state.__TSR_key, - key: currentRedirect.options._fromLocation!.state.key, - }, - url: new URL('http://localhost/'), - }, - href: '/about', - to: '/about', - statusCode: 307, - }) - }) - }) }) diff --git a/packages/react-router/tests/renderRouterToStream.react19.test.tsx b/packages/react-router/tests/renderRouterToStream.react19.test.tsx new file mode 100644 index 0000000000..426996d60e --- /dev/null +++ b/packages/react-router/tests/renderRouterToStream.react19.test.tsx @@ -0,0 +1,227 @@ +import { Suspense } from 'react' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { attachRouterServerSsrUtils } from '@tanstack/router-core/ssr/server' +import { + RouterContextProvider, + Scripts, + createMemoryHistory, + createRootRoute, + createRouter, +} from '../src' +import type * as ReactDOMServer from 'react-dom/server' +import type { AnyRouter } from '@tanstack/router-core' + +/** + * Load the adapter against the real React 19 renderer. Node's `react-dom` + * exports both entry points; hiding `renderToReadableStream` exercises the + * pipeable path that every Node user on React < 19.2 runs. + */ +async function loadRenderRouterToStream(path: 'readable' | 'pipeable') { + vi.resetModules() + if (path === 'pipeable') { + vi.doMock('react-dom/server', async (importOriginal) => { + // The runtime module is CommonJS, so its interop `default` is the namespace. + const actual = await importOriginal<{ default: typeof ReactDOMServer }>() + return { + ...actual, + default: { ...actual.default, renderToReadableStream: undefined }, + } + }) + } else { + vi.doUnmock('react-dom/server') + } + const reactDomServer = (await import('react-dom/server')).default + const renderToPipeableStream = vi.spyOn( + reactDomServer, + 'renderToPipeableStream', + ) + const { renderRouterToStream } = + await import('../src/ssr/renderRouterToStream') + return { renderRouterToStream, renderToPipeableStream } +} + +const activeRouters: Array = [] + +afterEach(() => { + for (const router of activeRouters.splice(0)) { + router.serverSsr?.cleanup() + } +}) + +async function buildRouter(dehydratedData: { routerData: Promise }) { + const rootRoute = createRootRoute({ component: () => null }) + const router = createRouter({ + history: createMemoryHistory({ initialEntries: ['/'] }), + routeTree: rootRoute, + dehydrate: () => dehydratedData, + }) + activeRouters.push(router) + router.isServer = true + attachRouterServerSsrUtils({ router, manifest: undefined }) + await router.load() + await router.serverSsr!.dehydrate() + return router +} + +function createSuspendingComponent(id: string, text: string) { + let ready = false + let resolve!: () => void + const pending = new Promise((done) => { + resolve = () => { + ready = true + done() + } + }) + + return { + Component() { + if (!ready) { + throw pending + } + return
    {text}
    + }, + resolve, + } +} + +async function readWithTimeout( + reader: ReadableStreamDefaultReader, +) { + let timeout: ReturnType | undefined + try { + return await Promise.race([ + reader.read(), + new Promise((_resolve, reject) => { + timeout = setTimeout( + () => reject(new Error('Timed out waiting for React SSR output')), + 2000, + ) + }), + ]) + } finally { + if (timeout) { + clearTimeout(timeout) + } + } +} + +async function readUntil( + reader: ReadableStreamDefaultReader, + decoder: TextDecoder, + state: { html: string }, + condition: (html: string) => boolean, +) { + while (!condition(state.html)) { + const { done, value } = await readWithTimeout(reader) + if (done) { + throw new Error('React SSR response ended before the expected output') + } + state.html += decoder.decode(value, { stream: true }) + } +} + +describe.each(['readable', 'pipeable'] as const)( + 'renderRouterToStream - real React 19 renderer (%s)', + (path) => { + test('emits router data after a real Suspense patch while React is still rendering', async () => { + const { renderRouterToStream, renderToPipeableStream } = + await loadRenderRouterToStream(path) + let resolveRouterData!: (value: string) => void + const routerData = new Promise((resolve) => { + resolveRouterData = resolve + }) + const router = await buildRouter({ routerData }) + const first = createSuspendingComponent('first-result', 'first-resolved') + const second = createSuspendingComponent( + 'second-result', + 'second-resolved', + ) + const requestController = new AbortController() + + const { response } = await renderRouterToStream({ + request: new Request('http://localhost/', { + signal: requestController.signal, + }), + router, + responseHeaders: new Headers(), + children: ( + + + + first-fallback

    }> + +
    + second-fallback

    }> + +
    + +
    + + + ), + }) + const reader = response.body!.getReader() + const decoder = new TextDecoder() + const state = { html: '' } + + try { + // The shell ends with , whose last child is the boundary. + await readUntil(reader, decoder, state, (html) => { + const shell = html.indexOf('second-fallback') + return shell >= 0 && html.indexOf('', shell) >= 0 + }) + expect(state.html).toContain('first-fallback') + + first.resolve() + await readUntil(reader, decoder, state, (html) => { + const result = html.indexOf('first-resolved') + return result >= 0 && html.indexOf('', result) >= 0 + }) + + const firstResult = state.html.indexOf('first-resolved') + const reactPatchEnd = + state.html.indexOf('', firstResult) + ''.length + const reactPatch = state.html.slice(firstResult, reactPatchEnd) + expect(reactPatch).toContain('')).toBe(true) + expect(state.html).not.toContain('second-resolved') + expect(state.html).not.toContain('') + + resolveRouterData('late-react19-router-value') + await readUntil(reader, decoder, state, (html) => + html.includes('late-react19-router-value'), + ) + + // The second Suspense boundary still keeps React's renderer open. The + // router batch can therefore only have used React's completed patch + // script as its insertion point. + const routerValue = state.html.indexOf('late-react19-router-value') + expect(routerValue).toBeGreaterThan(reactPatchEnd) + expect(state.html).not.toContain('second-resolved') + expect(state.html).not.toContain('') + + second.resolve() + for (;;) { + const { done, value } = await readWithTimeout(reader) + if (done) { + break + } + state.html += decoder.decode(value, { stream: true }) + } + state.html += decoder.decode() + + expect(state.html).toContain('second-resolved') + expect(state.html.endsWith('')).toBe(true) + expect(router.serverSsr).toBeUndefined() + expect(renderToPipeableStream).toHaveBeenCalledTimes( + path === 'pipeable' ? 1 : 0, + ) + } finally { + first.resolve() + second.resolve() + requestController.abort(new Error('test-complete')) + await reader.cancel().catch(() => {}) + } + }) + }, +) diff --git a/packages/react-router/tests/renderRouterToStream.test.tsx b/packages/react-router/tests/renderRouterToStream.test.tsx new file mode 100644 index 0000000000..cde31d0b6a --- /dev/null +++ b/packages/react-router/tests/renderRouterToStream.test.tsx @@ -0,0 +1,895 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { attachRouterServerSsrUtils } from '@tanstack/router-core/ssr/server' +import { createMemoryHistory, createRootRoute, createRouter } from '../src' +import type { RouterManagedTag } from '@tanstack/router-core' +import type * as RouterSsrServer from '@tanstack/router-core/ssr/server' +import type * as ReactDomServer from 'react-dom/server' + +type ReadableRenderOptions = NonNullable< + Parameters[1] +> + +const reactDomServerMocks = vi.hoisted(() => ({ + renderToReadableStream: undefined as + | undefined + | ((children: unknown, options: ReadableRenderOptions) => unknown), + renderToPipeableStream: vi.fn(), +})) +const routerTransformMocks = vi.hoisted(() => ({ + readableOptions: vi.fn(), +})) + +vi.mock('@tanstack/router-core/ssr/server', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + transformReadableStreamWithRouter: ( + ...args: Parameters + ) => { + routerTransformMocks.readableOptions(args[2]) + return actual.transformReadableStreamWithRouter(...args) + }, + } +}) + +vi.mock('react-dom/server', () => ({ + default: reactDomServerMocks, + ...reactDomServerMocks, +})) + +const actualReactDomServer = await vi.importActual( + 'react-dom/server.node', +) + +const { renderRouterToStream } = await import('../src/ssr/renderRouterToStream') + +afterEach(() => { + reactDomServerMocks.renderToReadableStream = undefined + reactDomServerMocks.renderToPipeableStream.mockReset() + routerTransformMocks.readableOptions.mockReset() + vi.restoreAllMocks() +}) + +async function buildRouter(dehydratedData?: { lateData: Promise }) { + const rootRoute = createRootRoute({ component: () => null }) + const router = createRouter({ + history: createMemoryHistory({ initialEntries: ['/'] }), + routeTree: rootRoute, + ...(dehydratedData === undefined + ? {} + : { dehydrate: () => dehydratedData }), + }) + router.isServer = true + attachRouterServerSsrUtils({ router, manifest: undefined }) + await router.load() + await router.serverSsr!.dehydrate() + return router +} + +async function expectBodyRejects(response: Response, message: string) { + await expect(response.text()).rejects.toThrow(message) +} + +function unwrapResponse( + result: Awaited>, +) { + return result.response +} + +function renderScript(tag: RouterManagedTag) { + const attrs = tag.attrs ?? {} + const id = attrs.id ? ` id="${attrs.id}"` : '' + const nonce = attrs.nonce ? ` nonce="${attrs.nonce}"` : '' + const streamPart = + 'data-tsr-stream-part' in attrs ? ' data-tsr-stream-part=""' : '' + return `${tag.children ?? ''}` +} + +function takeInitialScriptHtml( + router: Awaited>, +) { + const scripts = router.serverSsr!.takeInitialHydrationScriptTags()! + return [...scripts.before, scripts.boundary].map(renderScript).join('') +} + +async function readWithTimeout( + reader: ReadableStreamDefaultReader, +) { + let timeout: ReturnType | undefined + try { + return await Promise.race([ + reader.read(), + new Promise((_resolve, reject) => { + timeout = setTimeout( + () => reject(new Error('Timed out waiting for streamed HTML')), + 2000, + ) + }), + ]) + } finally { + if (timeout) { + clearTimeout(timeout) + } + } +} + +async function readUntil( + reader: ReadableStreamDefaultReader, + decoder: TextDecoder, + state: { html: string }, + needle: string, +) { + while (!state.html.includes(needle)) { + const { done, value } = await readWithTimeout(reader) + if (done) { + throw new Error(`Response ended before it contained ${needle}`) + } + state.html += decoder.decode(value, { stream: true }) + } +} + +describe('renderRouterToStream - renderer selection and pipeable errors', () => { + test('already-aborted requests do not start the readable renderer', async () => { + const readable = vi.fn() + reactDomServerMocks.renderToReadableStream = readable + const controller = new AbortController() + controller.abort(new Error('already-gone-readable')) + const router = await buildRouter() + + try { + await expect( + renderRouterToStream({ + request: new Request('http://localhost/', { + signal: controller.signal, + }), + router, + responseHeaders: new Headers(), + children: null, + }), + ).rejects.toThrow('already-gone-readable') + + expect(readable).not.toHaveBeenCalled() + expect(reactDomServerMocks.renderToPipeableStream).not.toHaveBeenCalled() + expect(router.serverSsr).toBeUndefined() + } finally { + router.serverSsr?.cleanup() + } + }) + + test('already-aborted requests do not start the pipeable renderer', async () => { + const controller = new AbortController() + controller.abort(new Error('already-gone-pipeable')) + const router = await buildRouter() + + try { + await expect( + renderRouterToStream({ + request: new Request('http://localhost/', { + signal: controller.signal, + }), + router, + responseHeaders: new Headers(), + children: null, + }), + ).rejects.toThrow('already-gone-pipeable') + + expect(reactDomServerMocks.renderToPipeableStream).not.toHaveBeenCalled() + expect(router.serverSsr).toBeUndefined() + } finally { + router.serverSsr?.cleanup() + } + }) + + test('disables React progressive chunking for the readable renderer', async () => { + const router = await buildRouter() + const renderedScripts = takeInitialScriptHtml(router) + const rendererStream = Object.assign( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode(renderedScripts)) + controller.close() + }, + }), + { allReady: Promise.resolve() }, + ) + const renderToReadableStream = vi.fn(() => Promise.resolve(rendererStream)) + reactDomServerMocks.renderToReadableStream = renderToReadableStream + + try { + const response = unwrapResponse( + await renderRouterToStream({ + request: new Request('http://localhost/'), + router, + responseHeaders: new Headers(), + children: null, + }), + ) + await response.text() + + expect(renderToReadableStream).toHaveBeenCalledWith( + null, + expect.objectContaining({ + progressiveChunkSize: Number.POSITIVE_INFINITY, + }), + ) + } finally { + router.serverSsr?.cleanup() + } + }) + + test('disables React progressive chunking for the pipeable renderer', async () => { + const router = await buildRouter() + const renderedScripts = takeInitialScriptHtml(router) + reactDomServerMocks.renderToPipeableStream.mockImplementationOnce( + (_children, options) => { + queueMicrotask(options.onShellReady) + return { + abort: vi.fn(), + pipe(destination: NodeJS.WritableStream) { + destination.write(renderedScripts) + destination.end() + }, + } + }, + ) + + try { + const response = unwrapResponse( + await renderRouterToStream({ + request: new Request('http://localhost/'), + router, + responseHeaders: new Headers(), + children: null, + }), + ) + await response.text() + + expect( + reactDomServerMocks.renderToPipeableStream.mock.calls[0]![1], + ).toEqual( + expect.objectContaining({ + progressiveChunkSize: Number.POSITIVE_INFINITY, + }), + ) + } finally { + router.serverSsr?.cleanup() + } + }) + + test('emits late router data after a complete React patch while rendering is still open', async () => { + let resolveLateData!: (value: string) => void + const lateData = new Promise((resolve) => { + resolveLateData = resolve + }) + const router = await buildRouter({ lateData }) + const renderedScripts = takeInitialScriptHtml(router) + + let rendererController!: ReadableStreamDefaultController + let rendererClosed = false + const rendererStream = Object.assign( + new ReadableStream({ + start(controller) { + rendererController = controller + }, + }), + { allReady: new Promise(() => {}) }, + ) + reactDomServerMocks.renderToReadableStream = vi.fn(() => + Promise.resolve(rendererStream), + ) + + const patch = + '' + + '' + const response = unwrapResponse( + await renderRouterToStream({ + request: new Request('http://localhost/'), + router, + responseHeaders: new Headers(), + children: null, + }), + ) + const reader = response.body!.getReader() + const decoder = new TextDecoder() + const state = { html: '' } + + try { + rendererController.enqueue( + new TextEncoder().encode( + `${renderedScripts}${patch}`, + ), + ) + await readUntil(reader, decoder, state, patch) + + resolveLateData('late-react-router-value') + await readUntil(reader, decoder, state, 'late-react-router-value') + + // Close React only after its patch allowed the late router value through. + rendererClosed = true + rendererController.close() + for (;;) { + const { done, value } = await readWithTimeout(reader) + if (done) { + break + } + state.html += decoder.decode(value, { stream: true }) + } + state.html += decoder.decode() + + expect(state.html.indexOf(patch)).toBeLessThan( + state.html.indexOf('late-react-router-value'), + ) + expect(state.html.indexOf('late-react-router-value')).toBeLessThan( + state.html.indexOf(''), + ) + expect(routerTransformMocks.readableOptions).toHaveBeenCalledWith( + expect.objectContaining({ rendererSafePoint: 'script-close' }), + ) + } finally { + if (!rendererClosed) { + try { + rendererController.close() + } catch { + // The response may already have cancelled the renderer. + } + } + router.serverSsr?.cleanup() + } + }) + + test('prefers the readable renderer when both APIs exist', async () => { + const cancelReadable = vi.fn() + const readableStream = Object.assign( + new ReadableStream({ + cancel: cancelReadable, + }), + { allReady: Promise.resolve() }, + ) + const readable = vi.fn(() => Promise.resolve(readableStream)) + reactDomServerMocks.renderToReadableStream = readable + + const router = await buildRouter() + const requestController = new AbortController() + try { + const response = unwrapResponse( + await renderRouterToStream({ + request: new Request('http://localhost/', { + signal: requestController.signal, + }), + router, + responseHeaders: new Headers(), + children: null, + }), + ) + + expect(readable).toHaveBeenCalledOnce() + expect(reactDomServerMocks.renderToPipeableStream).not.toHaveBeenCalled() + expect(routerTransformMocks.readableOptions).toHaveBeenCalledWith( + expect.objectContaining({ rendererSafePoint: 'script-close' }), + ) + + requestController.abort(new Error('test-complete')) + await expectBodyRejects(response, 'test-complete') + expect(cancelReadable).toHaveBeenCalledOnce() + } finally { + router.serverSsr?.cleanup() + } + }) + + test('readable renderer cancellation does not log a render error', async () => { + const cancelReadable = vi.fn() + reactDomServerMocks.renderToReadableStream = vi.fn((_children, options) => { + const readableStream = Object.assign( + new ReadableStream({ + cancel(reason) { + cancelReadable(reason) + options.onError?.(reason, { componentStack: '' }) + }, + }), + { allReady: Promise.resolve() }, + ) + return Promise.resolve(readableStream) + }) + + const router = await buildRouter() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const reason = new Error('readable-consumer-gone') + try { + const response = unwrapResponse( + await renderRouterToStream({ + request: new Request('http://localhost/'), + router, + responseHeaders: new Headers(), + children: null, + }), + ) + + await response.body!.cancel(reason) + expect(cancelReadable).toHaveBeenCalledWith(reason) + expect(errorSpy).not.toHaveBeenCalled() + } finally { + errorSpy.mockRestore() + router.serverSsr?.cleanup() + } + }) + + test('request abort does not log a renderer cancellation error', async () => { + const controller = new AbortController() + const renderError = new Error('renderer cancellation') + reactDomServerMocks.renderToReadableStream = vi.fn((_children, options) => { + controller.signal.addEventListener( + 'abort', + () => options.onError?.(renderError, { componentStack: '' }), + { once: true }, + ) + return Promise.resolve( + Object.assign(new ReadableStream(), { + allReady: Promise.resolve(), + }), + ) + }) + + const router = await buildRouter() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + const response = unwrapResponse( + await renderRouterToStream({ + request: new Request('http://localhost/', { + signal: controller.signal, + }), + router, + responseHeaders: new Headers(), + children: null, + }), + ) + + controller.abort(new Error('request-gone')) + await expectBodyRejects(response, 'request-gone') + expect(errorSpy).not.toHaveBeenCalled() + } finally { + errorSpy.mockRestore() + router.serverSsr?.cleanup() + } + }) + + test('request abort unblocks the readable renderer bot wait', async () => { + let resolveCancel!: () => void + let markCancelStarted!: () => void + const cancelStarted = new Promise((resolve) => { + markCancelStarted = resolve + }) + const cancelReadable = vi.fn( + () => + new Promise((resolve) => { + resolveCancel = resolve + markCancelStarted() + }), + ) + const readableStream = Object.assign( + new ReadableStream({ + cancel: cancelReadable, + }), + { allReady: new Promise(() => {}) }, + ) + reactDomServerMocks.renderToReadableStream = vi.fn(() => + Promise.resolve(readableStream), + ) + + const router = await buildRouter() + const cleanup = vi.spyOn(router.serverSsr!, 'cleanup') + const originalServerSsr = router.serverSsr! + const controller = new AbortController() + const reason = new Error('readable-bot-gone') + try { + const responsePromise = renderRouterToStream({ + request: new Request('http://localhost/', { + headers: { 'User-Agent': 'Googlebot' }, + signal: controller.signal, + }), + router, + responseHeaders: new Headers(), + children: null, + }) + + await Promise.resolve() + controller.abort(reason) + + await cancelStarted + expect(cleanup).toHaveBeenCalledOnce() + expect(router.serverSsr).toBeUndefined() + resolveCancel() + await expect(responsePromise).rejects.toBe(reason) + expect(cancelReadable).toHaveBeenCalledOnce() + } finally { + resolveCancel?.() + originalServerSsr.cleanup() + } + }) + + test('stream lifetime rejects the readable bot wait while readiness and cancellation stay pending', async () => { + let resolveReady!: () => void + const allReady = new Promise((resolve) => { + resolveReady = resolve + }) + const cancelReadable = vi.fn(() => new Promise(() => {})) + const readableStream = Object.assign( + new ReadableStream({ cancel: cancelReadable }), + { allReady }, + ) + reactDomServerMocks.renderToReadableStream = vi.fn(() => + Promise.resolve(readableStream), + ) + + const router = await buildRouter() + const owner = router.serverSsr! + const cleanup = vi.fn() + owner.onCleanup(cleanup) + const request = new Request('http://localhost/', { + headers: { 'User-Agent': 'Googlebot' }, + }) + const resolved = vi.fn() + const rejected = vi.fn() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.useFakeTimers() + const pending = renderRouterToStream({ + request, + router, + responseHeaders: new Headers(), + children: null, + }).then(resolved, rejected) + + try { + await Promise.resolve() + expect(routerTransformMocks.readableOptions).toHaveBeenCalledOnce() + expect(rejected).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(120_000) + + const expectedError = expect.objectContaining({ + message: 'Stream lifetime exceeded', + }) + expect(rejected).toHaveBeenCalledExactlyOnceWith(expectedError) + expect(cancelReadable).toHaveBeenCalledExactlyOnceWith(expectedError) + expect(readableStream.locked).toBe(false) + expect(request.signal.aborted).toBe(false) + expect(cleanup).toHaveBeenCalledOnce() + expect(router.serverSsr).toBeUndefined() + + resolveReady() + await vi.advanceTimersByTimeAsync(0) + expect(resolved).not.toHaveBeenCalled() + } finally { + resolveReady() + await pending + owner.cleanup() + vi.useRealTimers() + warn.mockRestore() + } + }) + + test('fatal shell errors reject before a response is created', async () => { + const shellError = new Error('fatal-react-shell-error') + reactDomServerMocks.renderToPipeableStream.mockImplementationOnce( + actualReactDomServer.renderToPipeableStream, + ) + const Fatal = () => { + throw shellError + } + + const router = await buildRouter() + const cleanup = vi.spyOn(router.serverSsr!, 'cleanup') + const originalServerSsr = router.serverSsr! + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + await expect( + renderRouterToStream({ + request: new Request('http://localhost/'), + router, + responseHeaders: new Headers(), + children: , + }), + ).rejects.toBe(shellError) + + expect(routerTransformMocks.readableOptions).toHaveBeenCalledOnce() + expect(cleanup).toHaveBeenCalled() + expect(router.serverSsr).toBeUndefined() + } finally { + errorSpy.mockRestore() + originalServerSsr.cleanup() + } + }) + + test('transform abort wins after shell readiness resolves before continuation', async () => { + const reason = new Error('transform-aborted-after-ready') + const abort = vi.fn() + const pipe = vi.fn() + reactDomServerMocks.renderToPipeableStream.mockImplementationOnce( + (_children, options) => { + options.onShellReady() + return { abort, pipe } + }, + ) + routerTransformMocks.readableOptions.mockImplementationOnce((options) => { + options?.onAbort?.(reason) + }) + + const router = await buildRouter() + const cleanup = vi.spyOn(router.serverSsr!, 'cleanup') + const originalServerSsr = router.serverSsr! + try { + await expect( + renderRouterToStream({ + request: new Request('http://localhost/'), + router, + responseHeaders: new Headers(), + children: null, + }), + ).rejects.toBe(reason) + + expect(abort).toHaveBeenCalledWith(reason) + expect(pipe).not.toHaveBeenCalled() + expect(cleanup).toHaveBeenCalled() + expect(router.serverSsr).toBeUndefined() + } finally { + originalServerSsr.cleanup() + } + }) + + test('synchronous renderer and transform setup failures do not orphan shell errors', async () => { + const rendererShellError = new Error('renderer-sync-shell-error') + const rendererSetupError = new Error('renderer-sync-setup-error') + const transformShellError = new Error('transform-sync-shell-error') + const transformSetupError = new Error('transform-sync-setup-error') + const unhandled: Array = [] + const onUnhandled = (error: unknown) => { + unhandled.push(error) + } + reactDomServerMocks.renderToPipeableStream + .mockImplementationOnce((_children, options) => { + options.onShellError(rendererShellError) + throw rendererSetupError + }) + .mockImplementationOnce((_children, options) => { + options.onShellError(transformShellError) + return { abort: vi.fn(), pipe: vi.fn() } + }) + routerTransformMocks.readableOptions.mockImplementationOnce(() => { + throw transformSetupError + }) + + const rendererRouter = await buildRouter() + const transformRouter = await buildRouter() + const rendererServerSsr = rendererRouter.serverSsr! + const transformServerSsr = transformRouter.serverSsr! + process.on('unhandledRejection', onUnhandled) + try { + await expect( + renderRouterToStream({ + request: new Request('http://localhost/'), + router: rendererRouter, + responseHeaders: new Headers(), + children: null, + }), + ).rejects.toBe(rendererSetupError) + await expect( + renderRouterToStream({ + request: new Request('http://localhost/'), + router: transformRouter, + responseHeaders: new Headers(), + children: null, + }), + ).rejects.toBe(transformSetupError) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(unhandled).toEqual([]) + expect(rendererRouter.serverSsr).toBeUndefined() + expect(transformRouter.serverSsr).toBeUndefined() + } finally { + process.off('unhandledRejection', onUnhandled) + rendererServerSsr.cleanup() + transformServerSsr.cleanup() + } + }) + + test('a live AbortError is logged without aborting the stream', async () => { + const abort = vi.fn() + const renderError = new DOMException('component failed', 'AbortError') + reactDomServerMocks.renderToPipeableStream.mockImplementationOnce( + (_children, opts) => { + queueMicrotask(() => opts.onShellReady()) + return { + abort, + pipe(destination: NodeJS.WritableStream) { + destination.write('shell') + opts.onError(renderError, { + componentStack: '', + }) + destination.end('') + }, + } + }, + ) + + const router = await buildRouter() + expect(router.serverSsr!.takeInitialHydrationScriptTags()).toBeDefined() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + const response = unwrapResponse( + await renderRouterToStream({ + request: new Request('http://localhost/'), + router, + responseHeaders: new Headers(), + children: null, + }), + ) + + await expect(response.text()).resolves.toContain('shell') + expect(routerTransformMocks.readableOptions).toHaveBeenCalledWith( + expect.objectContaining({ rendererSafePoint: 'script-close' }), + ) + expect(abort).not.toHaveBeenCalled() + expect(errorSpy).toHaveBeenCalledWith( + 'Error in renderToPipeableStream:', + renderError, + { componentStack: '' }, + ) + } finally { + errorSpy.mockRestore() + router.serverSsr?.cleanup() + } + }) + + test('pipeable renderer cancellation does not log a render error', async () => { + let options: + | Parameters[1] + | undefined + const abort = vi.fn((reason: unknown) => { + options?.onError?.(reason, { componentStack: '' }) + }) + reactDomServerMocks.renderToPipeableStream.mockImplementationOnce( + (_children, nextOptions) => { + options = nextOptions + queueMicrotask(() => nextOptions.onShellReady()) + return { abort, pipe: vi.fn() } + }, + ) + + const router = await buildRouter() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const reason = new Error('pipeable-consumer-gone') + try { + const response = unwrapResponse( + await renderRouterToStream({ + request: new Request('http://localhost/'), + router, + responseHeaders: new Headers(), + children: null, + }), + ) + + await response.body!.cancel(reason) + expect(abort).toHaveBeenCalledWith(reason) + expect(errorSpy).not.toHaveBeenCalled() + } finally { + errorSpy.mockRestore() + router.serverSsr?.cleanup() + } + }) + + test('request abort cancels pipeable rendering before the response body is consumed', async () => { + const abort = vi.fn() + reactDomServerMocks.renderToPipeableStream.mockImplementationOnce( + (_children, opts) => { + queueMicrotask(() => opts.onShellReady()) + return { abort, pipe: vi.fn() } + }, + ) + + const router = await buildRouter() + const controller = new AbortController() + const request = new Request('http://localhost/', { + signal: controller.signal, + }) + try { + const response = unwrapResponse( + await renderRouterToStream({ + request, + router, + responseHeaders: new Headers(), + children: null, + }), + ) + + expect(response.body).not.toBeNull() + controller.abort(new Error('request-gone')) + await vi.waitFor(() => expect(abort).toHaveBeenCalledOnce()) + await expectBodyRejects(response, 'request-gone') + } finally { + router.serverSsr?.cleanup() + } + }) + + test('stream lifetime abort rejects before bot readiness even when React resolves onAllReady', async () => { + let options: + | Parameters[1] + | undefined + const pipe = vi.fn() + const abort = vi.fn((_reason?: unknown) => { + options?.onAllReady?.() + }) + reactDomServerMocks.renderToPipeableStream.mockImplementationOnce( + (_children, nextOptions) => { + options = nextOptions + return { abort, pipe } + }, + ) + + const router = await buildRouter() + const cleanup = vi.spyOn(router.serverSsr!, 'cleanup') + const originalServerSsr = router.serverSsr! + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.useFakeTimers() + try { + const responsePromise = renderRouterToStream({ + request: new Request('http://localhost/', { + headers: { 'User-Agent': 'Googlebot' }, + }), + router, + responseHeaders: new Headers(), + children: null, + }) + const rejection = expect(responsePromise).rejects.toThrow( + 'Stream lifetime exceeded', + ) + + expect(routerTransformMocks.readableOptions).toHaveBeenCalledOnce() + expect(options?.onAllReady).toBeTypeOf('function') + await vi.runAllTimersAsync() + + await rejection + expect(abort).toHaveBeenCalledOnce() + expect(abort.mock.calls[0]![0]).toMatchObject({ + message: 'Stream lifetime exceeded', + }) + expect(pipe).not.toHaveBeenCalled() + expect(cleanup).toHaveBeenCalled() + expect(router.serverSsr).toBeUndefined() + } finally { + vi.useRealTimers() + warnSpy.mockRestore() + originalServerSsr.cleanup() + } + }) + + test('request abort before shell readiness rejects and cleans up', async () => { + const abort = vi.fn() + const controller = new AbortController() + reactDomServerMocks.renderToPipeableStream.mockReturnValueOnce({ + abort, + pipe: vi.fn(), + }) + + const router = await buildRouter() + const cleanup = vi.spyOn(router.serverSsr!, 'cleanup') + const originalServerSsr = router.serverSsr! + const reason = new Error('request-gone-before-shell') + try { + const responsePromise = renderRouterToStream({ + request: new Request('http://localhost/', { + signal: controller.signal, + }), + router, + responseHeaders: new Headers(), + children: null, + }) + await Promise.resolve() + controller.abort(reason) + + await expect(responsePromise).rejects.toBe(reason) + expect(abort).toHaveBeenCalledOnce() + expect(cleanup).toHaveBeenCalledOnce() + expect(router.serverSsr).toBeUndefined() + } finally { + originalServerSsr.cleanup() + } + }) +}) diff --git a/packages/react-router/tests/root-pending-min.test.tsx b/packages/react-router/tests/root-pending-min.test.tsx new file mode 100644 index 0000000000..1ce8ab4822 --- /dev/null +++ b/packages/react-router/tests/root-pending-min.test.tsx @@ -0,0 +1,213 @@ +import * as React from 'react' +import { act, cleanup, render, screen } from '@testing-library/react' +import { hydrateRoot } from 'react-dom/client' +import { renderToString } from 'react-dom/server' +import { afterEach, expect, test, vi } from 'vitest' +import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id' +import { hydrate } from '../src/ssr/client' +import { + RouterProvider, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRouter, +} from '../src' + +const testCleanups: Array<() => void | Promise> = [] + +afterEach(async () => { + while (testCleanups.length) { + await testCleanups.pop()!() + } + cleanup() + vi.useRealTimers() + delete window.$_TSR +}) + +test('a post-hydration root reload keeps its fallback through pendingMinMs', async () => { + const reloadGate = createControlledPromise() + const rootLoader = vi.fn(() => reloadGate.then(() => ({ generation: 2 }))) + const rootRoute = createRootRoute({ + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    Pending
    , + loader: rootLoader, + component: () => ( +
    + Generation {rootRoute.useLoaderData().generation} +
    + ), + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const rootMatch = router.matchRoutes(router.latestLocation)[0]! + // This is the same public bootstrap shape produced by the server. Calling + // hydrate() ensures router.ssr and the active match are established through + // the real client hydration path rather than by mutating router stores. + window.$_TSR = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: [ + { + i: dehydrateSsrMatchId(rootMatch.id), + s: 'success', + ssr: true, + l: { generation: 1 }, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + expect(router.ssr).toBeDefined() + + render() + expect(screen.getByTestId('root-content')).toHaveTextContent('Generation 1') + expect(rootLoader).not.toHaveBeenCalled() + + vi.useFakeTimers() + + let invalidation!: Promise + await act(async () => { + invalidation = router.invalidate({ forcePending: true }) + await vi.advanceTimersByTimeAsync(0) + }) + + expect(rootLoader).toHaveBeenCalledTimes(1) + expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument() + expect(screen.getByTestId('root-content')).toHaveTextContent('Generation 1') + + await act(async () => { + reloadGate.resolve() + await Promise.resolve() + }) + + await act(async () => { + await vi.advanceTimersByTimeAsync(99) + }) + expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument() + + await act(async () => { + await vi.advanceTimersByTimeAsync(1) + await invalidation + }) + expect(screen.queryByTestId('root-pending')).not.toBeInTheDocument() + expect(screen.getByTestId('root-content')).toHaveTextContent('Generation 2') +}) + +test('root route hydration without a pending boundary preserves component state', async () => { + const mounts = vi.fn() + const unmounts = vi.fn() + const initializers = vi.fn(() => 'preserved') + + const rootRoute = createRootRoute({ + pendingComponent: () =>
    Root pending
    , + component: function RootComponent() { + const [value] = React.useState(initializers) + React.useEffect(() => { + mounts() + return unmounts + }, []) + return
    {value}
    + }, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + + // Model the server render and the client router produced by hydrate(). A root + // without a separate shell stays unwrapped on both sides of hydration. + router.ssr = { manifest: { routes: {} } } + router.isServer = true + const html = renderToString() + router.isServer = false + expect(html).not.toContain('') + expect(html).toContain('preserved') + + const container = document.createElement('div') + container.innerHTML = html + document.body.appendChild(container) + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + let root!: ReturnType + await act(async () => { + root = hydrateRoot(container, ) + testCleanups.push(async () => { + await act(() => root.unmount()) + consoleError.mockRestore() + container.remove() + }) + await Promise.resolve() + }) + + expect(container).toHaveTextContent('preserved') + // One initializer belongs to the server render and one to client hydration. + expect(initializers).toHaveBeenCalledTimes(2) + expect(mounts).toHaveBeenCalledTimes(1) + expect(unmounts).not.toHaveBeenCalled() + expect(consoleError).not.toHaveBeenCalled() +}) + +test('an unresolved functional ssr option does not enable a root pending boundary', async () => { + const rootRoute = createRootRoute({ + ssr: () => true, + pendingComponent: () =>
    Root pending
    , + component: () =>
    Root content
    , + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + + const match = router.stores.matches.get()[0]! + expect(typeof match.ssr).toBe('function') + + // Client match construction can expose the unresolved route option before + // hydration replaces it with its transported value. + router.ssr = { manifest: { routes: {} } } + router.isServer = true + const html = renderToString() + + expect(html).not.toContain('') + expect(html).toContain('Root content') +}) + +test('server rendering uses the root pending boundary inside its document shell', async () => { + const gate = createControlledPromise() + const rootRoute = createRootRoute({ + pendingComponent: () =>
    Server root pending
    , + shellComponent: ({ children }) => ( + + + {children} + + ), + component: () => { + throw gate + }, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + router.isServer = true + await router.load() + + const html = renderToString() + + // renderToString cannot wait for Suspense, but the boundary inside the root + // shell contains the suspension and emits its fallback. + expect(html).toContain('Server root pending') +}) diff --git a/packages/react-router/tests/route.test-d.tsx b/packages/react-router/tests/route.test-d.tsx index ed2ece1bc9..41b003e5d1 100644 --- a/packages/react-router/tests/route.test-d.tsx +++ b/packages/react-router/tests/route.test-d.tsx @@ -44,6 +44,7 @@ test('when creating the root with routeContext', () => { context: {} deps: {} matches: Array + routeId: '__root__' }>() }, }) @@ -67,6 +68,7 @@ test('when creating the root with beforeLoad', () => { context: {} search: {} matches: Array + routeId: '__root__' }>() }, }) @@ -114,6 +116,7 @@ test('when creating the root route with context and routeContext', () => { context: { userId: string } deps: {} matches: Array + routeId: '__root__' }>() }, }) @@ -155,6 +158,7 @@ test('when creating the root route with context and beforeLoad', () => { context: { userId: string } search: {} matches: Array + routeId: '__root__' }>() }, }) @@ -237,6 +241,7 @@ test('when creating the root route with context, routeContext, beforeLoad and a context: { userId: string } deps: {} matches: Array + routeId: '__root__' }>() return { @@ -255,6 +260,7 @@ test('when creating the root route with context, routeContext, beforeLoad and a context: { userId: string; env: 'env1' } search: {} matches: Array + routeId: '__root__' }>() return { permission: 'view' as const } }, @@ -361,6 +367,7 @@ test('when creating a child route with routeContext from the root route with con context: { userId: string } deps: {} matches: Array + routeId: '/invoices' }>() return { @@ -388,6 +395,7 @@ test('when creating a child route with beforeLoad from the root route with conte context: { userId: string } search: {} matches: Array + routeId: '/invoices' }>() }, }) @@ -756,6 +764,7 @@ test('when creating a child route with params, search with routeContext from the context: { userId: string } deps: {} matches: Array + routeId: '/invoices/$invoiceId' }>() }, }) @@ -804,6 +813,7 @@ test('when creating a child route with params, search with routeContext, beforeL context: { userId: string } deps: {} matches: Array + routeId: '/invoices/$invoiceId' }>() return { env: 'env1', @@ -821,6 +831,7 @@ test('when creating a child route with params, search with routeContext, beforeL context: { userId: string; env: string } search: { page: number } matches: Array + routeId: '/invoices/$invoiceId' }>() return { permission: 'view' } as const }, @@ -942,6 +953,7 @@ test('when creating a child route with routeContext from a parent with routeCont context: { userId: string } deps: {} matches: Array + routeId: '/invoices' }>() return { invoiceId: 'invoiceId1' } @@ -963,6 +975,7 @@ test('when creating a child route with routeContext from a parent with routeCont context: { userId: string; invoiceId: string } deps: {} matches: Array + routeId: '/invoices/details' }>() return { detailId: 'detailId1' } @@ -1015,6 +1028,7 @@ test('when creating a child route with beforeLoad from a parent with beforeLoad' context: { userId: string } search: {} matches: Array + routeId: '/invoices' }>() return { invoiceId: 'invoiceId1' } }, @@ -1035,6 +1049,7 @@ test('when creating a child route with beforeLoad from a parent with beforeLoad' context: { userId: string; invoiceId: string } search: {} matches: Array + routeId: '/invoices/details' }>() return { detailId: 'detailId1' } }, @@ -1087,6 +1102,7 @@ test('when creating a child route with routeContext, beforeLoad, search, params, context: { userId: string } deps: {} matches: Array + routeId: '/invoices' }>() return { env: 'env1' } }, @@ -1102,6 +1118,7 @@ test('when creating a child route with routeContext, beforeLoad, search, params, context: { userId: string; env: string } search: { page: number } matches: Array + routeId: '/invoices' }>() return { invoicePermissions: ['view'] as const } }, @@ -1132,6 +1149,7 @@ test('when creating a child route with routeContext, beforeLoad, search, params, } deps: {} matches: Array + routeId: '/invoices/$invoiceId/details' }>() return { detailEnv: 'detailEnv' } }, @@ -1152,6 +1170,7 @@ test('when creating a child route with routeContext, beforeLoad, search, params, } search: { page: number; detailPage: number } matches: Array + routeId: '/invoices/$invoiceId/details' }>() return { detailsPermissions: ['view'] as const } }, @@ -1182,6 +1201,7 @@ test('when creating a child route with routeContext, beforeLoad, search, params, } deps: { detailPage: number; invoicePage: number } matches: Array + routeId: '/invoices/$invoiceId/details/$detailId' }>() return { detailEnv: 'detailEnv' } }, diff --git a/packages/react-router/tests/routeApi.test-d.tsx b/packages/react-router/tests/routeApi.test-d.tsx index a51a50b10f..d0553a9e0b 100644 --- a/packages/react-router/tests/routeApi.test-d.tsx +++ b/packages/react-router/tests/routeApi.test-d.tsx @@ -60,6 +60,12 @@ describe('getRouteApi', () => { expectTypeOf(invoiceRouteApi.useParams()).toEqualTypeOf<{ invoiceId: string }>() + + expectTypeOf( + invoiceRouteApi.useParams({ + shouldThrow: false, + }), + ).toEqualTypeOf<{ invoiceId: string } | undefined>() }) test('useContext', () => { expectTypeOf( @@ -72,6 +78,12 @@ describe('getRouteApi', () => { expectTypeOf(invoiceRouteApi.useSearch()).toEqualTypeOf<{ page: number }>() + + expectTypeOf( + invoiceRouteApi.useSearch({ + shouldThrow: false, + }), + ).toEqualTypeOf<{ page: number } | undefined>() }) test('useLoaderData', () => { expectTypeOf(invoiceRouteApi.useLoaderData()).toEqualTypeOf<{ @@ -87,6 +99,25 @@ describe('getRouteApi', () => { expectTypeOf(invoiceRouteApi.useMatch()).toEqualTypeOf< MakeRouteMatch >() + + expectTypeOf( + invoiceRouteApi.useMatch({ shouldThrow: true }), + ).toEqualTypeOf>() + + expectTypeOf( + invoiceRouteApi.useMatch({ + shouldThrow: false, + }), + ).toEqualTypeOf< + MakeRouteMatch | undefined + >() + + expectTypeOf( + invoiceRouteApi.useMatch({ + shouldThrow: false, + select: (match) => match.params.invoiceId, + }), + ).toEqualTypeOf() }) test('Link', () => { const Link = invoiceRouteApi.Link @@ -106,3 +137,35 @@ describe('createRoute', () => { }) }) }) + +describe('fullPath type correctness', () => { + // Create a layout route (pathless route) + const layoutRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_layout', + }) + + const layoutChildRoute = createRoute({ + getParentRoute: () => layoutRoute, + path: 'dashboard', + }) + + const routeTreeWithLayout = rootRoute.addChildren([ + layoutRoute.addChildren([layoutChildRoute]), + indexRoute, + ]) + + test('index route fullPath should have trailing slash to match runtime', () => { + // At runtime, Route.fullPath returns '/invoices/' for an index route + // The type should match this behavior + const fullPath = invoicesIndexRoute.fullPath + expectTypeOf(fullPath).toEqualTypeOf<'/invoices/'>() + }) + + test('layout route fullPath should be "/" not empty string', () => { + // At runtime, a pathless layout route has fullPath of '/' + // The type should be '/' not '' + const fullPath = layoutRoute.fullPath + expectTypeOf(fullPath).toEqualTypeOf<'/'>() + }) +}) diff --git a/packages/react-router/tests/routeContext.test.tsx b/packages/react-router/tests/routeContext.test.tsx index e42b10d603..e00228e280 100644 --- a/packages/react-router/tests/routeContext.test.tsx +++ b/packages/react-router/tests/routeContext.test.tsx @@ -141,7 +141,7 @@ describe('context function', () => { }) test('when loader deps change', async () => { - const mockContextFn = vi.fn() + let generation = 0 const rootRoute = createRootRoute() const indexRoute = createRoute({ @@ -153,14 +153,21 @@ describe('context function', () => { path: '/', loaderDeps: ({ search }) => ({ foo: search.foo }), context: ({ deps }) => { - mockContextFn(deps) + return { + generation: ++generation, + deps: JSON.stringify(deps), + } }, component: () => { const navigate = indexRoute.useNavigate() + const context = indexRoute.useRouteContext() return (

    Index page

    search: {JSON.stringify(indexRoute.useSearch())}

    +

    + context: {context.generation}:{context.deps} +

    + + + + ) + } + + setup({ RootComponent }) + expect(await screen.findByText('IndexTitle')).toBeInTheDocument() + expect(screen.getByTestId('targeted-route')).toHaveTextContent('absent') + + fireEvent.click(screen.getByRole('button', { name: 'Select index' })) + expect(screen.getByTestId('targeted-route')).toHaveTextContent('/') + + fireEvent.click(screen.getByRole('button', { name: 'Select posts' })) + expect(screen.getByTestId('targeted-route')).toHaveTextContent('absent') + + fireEvent.click(screen.getByRole('link', { name: 'Posts' })) + expect(await screen.findByText('PostsTitle')).toBeInTheDocument() + expect(screen.getByTestId('targeted-route')).toHaveTextContent('/posts') + }) + + test('tracks presentation generations across replacement and re-entry', async () => { + function RootComponent() { + const targetedRevision = useMatch({ + from: '/item', + shouldThrow: false, + select: (match) => match.loaderData, + }) + + return ( + <> +
    + {targetedRevision === undefined + ? 'Targeted absent' + : `Targeted revision ${targetedRevision}`} +
    + + Revision 2 + + + Revision 3 + + Other + + + ) + } + + function ItemComponent() { + const nearestRevision = useMatch({ + strict: false, + shouldThrow: false, + select: (match) => match.loaderData as number, + }) + return
    Nearest revision {nearestRevision}
    + } + + const rootRoute = createRootRoute({ component: RootComponent }) + const itemRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/item', + validateSearch: (search: Record) => ({ + revision: Number(search.revision), + }), + loaderDeps: ({ search }) => ({ revision: search.revision }), + loader: ({ deps }) => deps.revision, + component: ItemComponent, + }) + const otherRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/other', + component: () =>
    Other route
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([itemRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/item?revision=1'] }), + }) + + render() + expect(await screen.findByText('Nearest revision 1')).toBeInTheDocument() + expect(screen.getByTestId('targeted-match')).toHaveTextContent( + 'Targeted revision 1', + ) + + fireEvent.click(screen.getByText('Revision 2')) + expect(await screen.findByText('Nearest revision 2')).toBeInTheDocument() + expect(screen.getByTestId('targeted-match')).toHaveTextContent( + 'Targeted revision 2', + ) + + fireEvent.click(screen.getByText('Other')) + expect(await screen.findByText('Other route')).toBeInTheDocument() + expect(screen.getByTestId('targeted-match')).toHaveTextContent( + 'Targeted absent', + ) + + fireEvent.click(screen.getByText('Revision 3')) + expect(await screen.findByText('Nearest revision 3')).toBeInTheDocument() + expect(screen.getByTestId('targeted-match')).toHaveTextContent( + 'Targeted revision 3', + ) + }) + + test('renders a route generation that re-enters before an intermediate route renders', async () => { + function RootComponent() { + return ( + <> + Other + + + ) + } + + function ItemComponent() { + const revision = useMatch({ + strict: false, + select: (match) => match.loaderData as number, + }) + return
    Item revision {revision}
    + } + + const rootRoute = createRootRoute({ component: RootComponent }) + const itemRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/item', + validateSearch: (search: Record) => ({ + revision: Number(search.revision), + }), + loaderDeps: ({ search }) => ({ revision: search.revision }), + loader: ({ deps }) => deps.revision, + component: ItemComponent, + }) + const otherRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/other', + component: () =>
    Other route
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([itemRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/item?revision=1'] }), + }) + + render() + expect(await screen.findByText('Item revision 1')).toBeInTheDocument() + + let returnNavigation: Promise | undefined + const unsubscribe = router.subscribe('onLoad', (event) => { + if (event.toLocation.pathname === '/other') { + returnNavigation = router.navigate({ + to: '/item', + search: { revision: 2 }, + }) + } + }) + try { + fireEvent.click(screen.getByText('Other')) + await waitFor(() => expect(returnNavigation).toBeDefined()) + await returnNavigation + + expect(await screen.findByText('Item revision 2')).toBeInTheDocument() + expect(screen.queryByText('Other route')).not.toBeInTheDocument() + } finally { + unsubscribe() + } }) describe('when match is not found', () => { diff --git a/packages/react-router/tests/useNavigate.test.tsx b/packages/react-router/tests/useNavigate.test.tsx index e3475c2e27..3acf185b22 100644 --- a/packages/react-router/tests/useNavigate.test.tsx +++ b/packages/react-router/tests/useNavigate.test.tsx @@ -1,5 +1,4 @@ import React, { act } from 'react' -import '@testing-library/jest-dom/vitest' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { cleanup, @@ -7,6 +6,7 @@ import { fireEvent, render, screen, + waitFor, } from '@testing-library/react' import { z } from 'zod' @@ -2312,9 +2312,11 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( path: 'param/$param', component: function ParamRoute() { const navigate = useNavigate() + const params = paramRoute.useParams() return ( <>

    Param Route

    + {params.param} @@ -2415,9 +2417,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(parentLink) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/a`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/a`) + }) }) test('should navigate to the parent route and keep params', async () => { @@ -2435,9 +2437,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(parentLink) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) + }) }) test('should navigate to the parent route and change params', async () => { @@ -2457,9 +2459,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(parentLink) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/param/bar/a`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/param/bar/a`) + }) }) test('should navigate to a relative link based on render location with basepath', async () => { @@ -2476,9 +2478,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(relativeLink) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) + }) }) test('should navigate to a parent link based on render location', async () => { @@ -2497,9 +2499,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(relativeLink) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/param/foo`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/param/foo`) + }) }) test('should navigate to a parent link based on active location', async () => { @@ -2515,9 +2517,9 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( // Click the link and ensure the new location fireEvent.click(relativeLink) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/param/foo/a`) + }) }) test('should navigate to same route with different params', async () => { @@ -2527,15 +2529,18 @@ describe.each([{ basepath: '' }, { basepath: '/basepath' }])( await act(async () => { history.push(`${basepath}/param/foo/a/b`) - await router.latestLoadPromise }) - expect(window.location.pathname).toBe(`${basepath}/param/foo/a/b`) + await waitFor(() => { + expect(window.location.pathname).toBe(`${basepath}/param/foo/a/b`) + }) + expect(await screen.findByTestId('param-value')).toHaveTextContent('foo') - const btn = screen.getByTestId('btn-param-bar') + const btn = await screen.findByTestId('btn-param-bar') fireEvent.click(btn) - await router.latestLoadPromise - - expect(window.location.pathname).toBe(`${basepath}/param/bar/a/b`) + await waitFor(() => { + expect(screen.getByTestId('param-value')).toHaveTextContent('bar') + expect(window.location.pathname).toBe(`${basepath}/param/bar/a/b`) + }) }) }, ) @@ -2667,8 +2672,8 @@ describe('encoded and unicode paths', () => { name: 'with prefix', path: '/foo/prefix@대{$}', expectedPath: - '/foo/prefix@%EB%8C%80test[s%5C/.%5C/parameter%25!%F0%9F%9A%80@]', - expectedLocation: '/foo/prefix@대test[s%5C/.%5C/parameter%25!🚀@]', + '/foo/prefix@%EB%8C%80test[s%5C/.%5C/parameter%25!%F0%9F%9A%80%40]', + expectedLocation: '/foo/prefix@대test[s%5C/.%5C/parameter%25!🚀%40]', params: { _splat: 'test[s\\/.\\/parameter%!🚀@]', '*': 'test[s\\/.\\/parameter%!🚀@]', @@ -2678,8 +2683,8 @@ describe('encoded and unicode paths', () => { name: 'with suffix', path: '/foo/{$}대suffix@', expectedPath: - '/foo/test[s%5C/.%5C/parameter%25!%F0%9F%9A%80@]%EB%8C%80suffix@', - expectedLocation: '/foo/test[s%5C/.%5C/parameter%25!🚀@]대suffix@', + '/foo/test[s%5C/.%5C/parameter%25!%F0%9F%9A%80%40]%EB%8C%80suffix@', + expectedLocation: '/foo/test[s%5C/.%5C/parameter%25!🚀%40]대suffix@', params: { _splat: 'test[s\\/.\\/parameter%!🚀@]', '*': 'test[s\\/.\\/parameter%!🚀@]', @@ -2699,10 +2704,10 @@ describe('encoded and unicode paths', () => { { name: 'with path param', path: `/foo/$id`, - expectedPath: '/foo/test[s%5C%2F.%5C%2Fparameter%25!%F0%9F%9A%80]', - expectedLocation: '/foo/test[s%5C%2F.%5C%2Fparameter%25!🚀]', + expectedPath: '/foo/test[s%5C%2F.%5C%2Fparameter%25!%F0%9F%9A%80%40]', + expectedLocation: '/foo/test[s%5C%2F.%5C%2Fparameter%25!🚀%40]', params: { - id: 'test[s\\/.\\/parameter%!🚀]', + id: 'test[s\\/.\\/parameter%!🚀@]', }, }, ] @@ -2775,3 +2780,59 @@ describe('encoded and unicode paths', () => { }, ) }) + +test('when navigating to /auth/sign-in with literal path (no params)', async () => { + const rootRoute = createRootRoute() + + const IndexComponent = () => { + const navigate = useNavigate() + return ( + <> +

    Index

    + + + ) + } + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: IndexComponent, + }) + + const authRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/auth/$path', + component: () => { + const params = authRoute.useParams() + return ( +
    +

    Auth Route

    + {params.path} +
    + ) + }, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, authRoute]), + history, + }) + + render() + + const btn = await screen.findByTestId('navigate-btn') + + // First click should navigate successfully + await act(() => fireEvent.click(btn)) + + // Should be at /auth/sign-in with correct params + expect(window.location.pathname).toBe('/auth/sign-in') + expect(await screen.findByTestId('auth-heading')).toBeInTheDocument() + expect((await screen.findByTestId('path-param')).textContent).toBe('sign-in') +}) diff --git a/packages/react-router/tests/useParams.test.tsx b/packages/react-router/tests/useParams.test.tsx index ec54c5e1fb..19cf096ea0 100644 --- a/packages/react-router/tests/useParams.test.tsx +++ b/packages/react-router/tests/useParams.test.tsx @@ -189,7 +189,8 @@ test('useParams must return parsed result if applicable.', async () => { expect(window.location.pathname).toBe('/posts/category_first') expect(await screen.findByTestId('post-category-heading')).toBeInTheDocument() - expect(mockedfn).toHaveBeenCalledTimes(1) + // Dev-only buildLocation roundtrip validation uses normal matching for links. + expect(mockedfn).toHaveBeenCalled() mockedfn.mockClear() await act(() => fireEvent.click(firstPostLink)) @@ -213,7 +214,9 @@ test('useParams must return parsed result if applicable.', async () => { expect(renderedPost.category).toBe('one') expect(paramCategoryValue.textContent).toBe('one') expect(paramPostIdValue.textContent).toBe('1') - expect(mockedfn).toHaveBeenCalledTimes(2) + expect(mockedfn).toHaveBeenCalled() + // maybe we could theoretically reach 1 single call, but i'm not sure, building links depends on a bunch of things + // expect(mockedfn).toHaveBeenCalledTimes(1) expect(allCategoryLink).toBeInTheDocument() mockedfn.mockClear() @@ -224,7 +227,7 @@ test('useParams must return parsed result if applicable.', async () => { expect(window.location.pathname).toBe('/posts/category_all') expect(await screen.findByTestId('post-category-heading')).toBeInTheDocument() expect(secondPostLink).toBeInTheDocument() - expect(mockedfn).toHaveBeenCalledTimes(2) + // expect(mockedfn).not.toHaveBeenCalled() mockedfn.mockClear() await act(() => fireEvent.click(secondPostLink)) @@ -246,5 +249,75 @@ test('useParams must return parsed result if applicable.', async () => { expect(renderedPost.category).toBe('two') expect(paramCategoryValue.textContent).toBe('all') expect(paramPostIdValue.textContent).toBe('2') - expect(mockedfn).toHaveBeenCalledTimes(2) + expect(mockedfn).toHaveBeenCalled() +}) + +test('useParams({ strict: false }) returns parsed params after child navigation', async () => { + const rootRoute = createRootRoute() + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'parent', + component: ParentComponent, + }) + + const versionRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '$version', + params: { + parse: (params) => ({ + ...params, + version: parseInt(params.version), + }), + stringify: (params) => ({ + ...params, + version: `${params.version}`, + }), + }, + component: VersionComponent, + }) + + function ParentComponent() { + const { version } = useParams({ strict: false }) + + return ( +
    +
    {typeof version}
    +
    {String(version)}
    + + Version 2 + + +
    + ) + } + + function VersionComponent() { + return
    Version Route
    + } + + window.history.replaceState({}, '', '/parent/1') + + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([versionRoute])]), + }) + + render() + + await act(() => router.load()) + + expect(await screen.findByTestId('version-type')).toHaveTextContent('number') + expect(await screen.findByTestId('version-value')).toHaveTextContent('1') + + const version2Link = await screen.findByTestId('version-2-link') + + await act(() => fireEvent.click(version2Link)) + + expect(await screen.findByTestId('version-route')).toBeInTheDocument() + expect(await screen.findByTestId('version-type')).toHaveTextContent('number') + expect(await screen.findByTestId('version-value')).toHaveTextContent('2') }) diff --git a/packages/react-router/tests/utils.ts b/packages/react-router/tests/utils.ts index cdc7ff82bd..da96eb2d95 100644 --- a/packages/react-router/tests/utils.ts +++ b/packages/react-router/tests/utils.ts @@ -20,20 +20,25 @@ export function createTimer() { export const getIntersectionObserverMock = ({ observe, disconnect, + onCreate, }: { observe: Mock disconnect: Mock + onCreate?: (callback: IntersectionObserverCallback) => void }) => { return class IO implements IntersectionObserver { root: Document | Element | null rootMargin: string + scrollMargin: string thresholds: Array constructor( _cb: IntersectionObserverCallback, options?: IntersectionObserverInit, ) { + onCreate?.(_cb) this.root = options?.root ?? null this.rootMargin = options?.rootMargin ?? '0px' + this.scrollMargin = options?.scrollMargin ?? '0px' this.thresholds = options?.threshold ?? ([0] as any) } diff --git a/packages/react-router/tsconfig.build.json b/packages/react-router/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/react-router/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/react-router/tsconfig.json b/packages/react-router/tsconfig.json index 372bb7b491..f406bf1c09 100644 --- a/packages/react-router/tsconfig.json +++ b/packages/react-router/tsconfig.json @@ -2,7 +2,8 @@ "extends": "../../tsconfig.json", "compilerOptions": { "jsx": "react-jsx", - "jsxImportSource": "react" + "jsxImportSource": "react", + "types": ["node"] }, "include": ["src", "tests", "vite.config.ts", "eslint.config.ts"] } diff --git a/packages/react-router/vite.config.ts b/packages/react-router/vite.config.ts index 5e60c3cd1c..798d9b74e4 100644 --- a/packages/react-router/vite.config.ts +++ b/packages/react-router/vite.config.ts @@ -1,25 +1,38 @@ import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' import react from '@vitejs/plugin-react' import packageJson from './package.json' -import type { ViteUserConfig } from 'vitest/config' const config = defineConfig({ - plugins: [react()] as ViteUserConfig['plugins'], + plugins: [react()], + // Add 'development' condition for tests to resolve @tanstack/router-core/isServer + // to the development export (isServer = undefined) instead of node (isServer = true) + ...(process.env.VITEST && { + resolve: { + conditions: ['development'], + }, + }), test: { name: packageJson.name, dir: './tests', watch: false, environment: 'jsdom', typecheck: { enabled: true }, - setupFiles: ['./tests/setupTests.tsx'], + setupFiles: ['./tests/jest-dom.setup.ts', './tests/setupTests.tsx'], }, }) export default mergeConfig( config, tanstackViteConfig({ - entry: ['./src/index.tsx', './src/ssr/client.ts', './src/ssr/server.ts'], + tsconfigPath: './tsconfig.build.json', + entry: [ + './src/index.tsx', + './src/index.rsc.ts', + './src/index.dev.tsx', + './src/ssr/client.ts', + './src/ssr/server.ts', + ], srcDir: './src', }), ) diff --git a/packages/react-start-client/CHANGELOG.md b/packages/react-start-client/CHANGELOG.md new file mode 100644 index 0000000000..1cb31dea24 --- /dev/null +++ b/packages/react-start-client/CHANGELOG.md @@ -0,0 +1,804 @@ +# @tanstack/react-start-client + +## 1.168.45 + +### Patch Changes + +- [#8653](https://github.com/TanStack/router/pull/8653) [`d66a84b`](https://github.com/TanStack/router/commit/d66a84ba0a74ffd03e22b57ccd90796274c96244) - fix: a `visible()` boundary keeps its server HTML when the intersection arrives while React waits to replay the boundary's render + +## 1.168.44 + +### Patch Changes + +- Updated dependencies [[`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c), [`689a7c5`](https://github.com/TanStack/router/commit/689a7c5419de68bce0aaaef72b9a36f115ea1398)]: + - @tanstack/react-router@1.170.46 + - @tanstack/router-core@1.171.39 + - @tanstack/start-client-core@1.170.39 + +## 1.168.43 + +### Patch Changes + +- Updated dependencies [[`18154b1`](https://github.com/TanStack/router/commit/18154b1c45454a70aa77e9d6d27c8a6e0733d031)]: + - @tanstack/router-core@1.171.38 + - @tanstack/react-router@1.170.45 + - @tanstack/start-client-core@1.170.38 + +## 1.168.42 + +### Patch Changes + +- Updated dependencies [[`d6ba115`](https://github.com/TanStack/router/commit/d6ba115d5751c75e20943f0062577cf17b446d82)]: + - @tanstack/router-core@1.171.37 + - @tanstack/start-client-core@1.170.37 + - @tanstack/react-router@1.170.44 + +## 1.168.41 + +### Patch Changes + +- Updated dependencies [[`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`550f478`](https://github.com/TanStack/router/commit/550f47881070c0558a87e1acce7f38fbc85b9549), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5)]: + - @tanstack/router-core@1.171.36 + - @tanstack/start-client-core@1.170.36 + - @tanstack/react-router@1.170.43 + +## 1.168.40 + +### Patch Changes + +- Updated dependencies [[`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`2413cc0`](https://github.com/TanStack/router/commit/2413cc009826fba4f97b166a35a8a50a4a8fe4bb), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`d35aab4`](https://github.com/TanStack/router/commit/d35aab425b07b46e222a507c0f0239644669757b), [`663282b`](https://github.com/TanStack/router/commit/663282b0ebbc494aee3595ed95867ee29d01938e)]: + - @tanstack/router-core@1.171.35 + - @tanstack/react-router@1.170.42 + - @tanstack/start-client-core@1.170.35 + +## 1.168.39 + +### Patch Changes + +- Updated dependencies [[`60b8ad1`](https://github.com/TanStack/router/commit/60b8ad1ad00812bf966a8eeee6be238c37ddad74), [`614bc27`](https://github.com/TanStack/router/commit/614bc27034c8ec98747bf305ed41d4a619640949), [`d521abd`](https://github.com/TanStack/router/commit/d521abd71c69f1ff010bb3def4d417cb5fa058cb), [`ff66a03`](https://github.com/TanStack/router/commit/ff66a03df4816f44a48a4a37189fc4021b1c8480), [`863c8a7`](https://github.com/TanStack/router/commit/863c8a736b96746c56278a16c50554356f5523d1)]: + - @tanstack/react-router@1.170.41 + - @tanstack/router-core@1.171.34 + - @tanstack/start-client-core@1.170.34 + +## 1.168.38 + +### Patch Changes + +- Updated dependencies [[`f5ffd38`](https://github.com/TanStack/router/commit/f5ffd3884ba26778a2a8ce53b379a5bded231676), [`488d046`](https://github.com/TanStack/router/commit/488d046a907d330429e2c807ef95326dad87480f), [`0c1b5e3`](https://github.com/TanStack/router/commit/0c1b5e38de71b7e81bbf1fd81c73ee0cd68ffe47), [`3cdd1af`](https://github.com/TanStack/router/commit/3cdd1af04b3e2d6f777797ee7bddf285318dd9d2), [`76a7c0b`](https://github.com/TanStack/router/commit/76a7c0bfadb42d5f7fe7b9e1748acc7333178c91)]: + - @tanstack/react-router@1.170.40 + - @tanstack/router-core@1.171.33 + - @tanstack/start-client-core@1.170.33 + +## 1.168.37 + +### Patch Changes + +- Updated dependencies [[`73bfc15`](https://github.com/TanStack/router/commit/73bfc153eef460e9b670556215a5adb2b5cbf542)]: + - @tanstack/react-router@1.170.39 + +## 1.168.36 + +### Patch Changes + +- Updated dependencies [[`cecae54`](https://github.com/TanStack/router/commit/cecae5440b8edaea77c5448fe3d74bbd20fe10a4), [`0103578`](https://github.com/TanStack/router/commit/01035782e53af9b929c784b94ddd64b95efb89c7), [`ce10dcd`](https://github.com/TanStack/router/commit/ce10dcd4d9d3d23738744e453205aad5c6dbd716), [`84936cc`](https://github.com/TanStack/router/commit/84936cc04530bba11059c57b293a794922bbc5aa), [`bbd2336`](https://github.com/TanStack/router/commit/bbd2336b8446de3f7dd85070895e7cf43980183e)]: + - @tanstack/router-core@1.171.32 + - @tanstack/react-router@1.170.38 + - @tanstack/start-client-core@1.170.32 + +## 1.168.35 + +### Patch Changes + +- Updated dependencies [[`bc80866`](https://github.com/TanStack/router/commit/bc80866f6d6eb3e6f152ee3682eb783c96403e83), [`e561fa1`](https://github.com/TanStack/router/commit/e561fa1d7118e3d29267cc3b6ce1130d6581f387), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a1c8d1a`](https://github.com/TanStack/router/commit/a1c8d1aa759c227eae9601a030321ac4c53c24bd), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a0b2ad9`](https://github.com/TanStack/router/commit/a0b2ad99aee64af08d16b0e4ff26b3ba42a99f0a), [`8e164d2`](https://github.com/TanStack/router/commit/8e164d28f9e9eb1a7301109230d7ece9817492a8), [`1ca361b`](https://github.com/TanStack/router/commit/1ca361ba52a627d2f76ab33323bd83d1d0aa65a3)]: + - @tanstack/router-core@1.171.31 + - @tanstack/react-router@1.170.37 + - @tanstack/start-client-core@1.170.31 + +## 1.168.34 + +### Patch Changes + +- Updated dependencies [[`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776), [`6cfb1e8`](https://github.com/TanStack/router/commit/6cfb1e8b564be282584765352250bf61747895ed), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8), [`873c830`](https://github.com/TanStack/router/commit/873c830ccb2610a864ee697250e10fcc99772ffa), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`f151ab0`](https://github.com/TanStack/router/commit/f151ab018eede64ae849b77e68f3cdf31cb95cc5), [`bc57fa3`](https://github.com/TanStack/router/commit/bc57fa3f12450cf34c731450947c7c8f1ea05e58), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9448caa`](https://github.com/TanStack/router/commit/9448caa03a89076b9770631c356c0cc502802c09), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef)]: + - @tanstack/router-core@1.171.30 + - @tanstack/react-router@1.170.36 + - @tanstack/start-client-core@1.170.30 + +## 1.168.33 + +### Patch Changes + +- Updated dependencies [[`8c43c71`](https://github.com/TanStack/router/commit/8c43c712523fc63dc3a814f3a19617e270ce8ed1)]: + - @tanstack/react-router@1.170.35 + +## 1.168.32 + +### Patch Changes + +- Updated dependencies [[`f9836f1`](https://github.com/TanStack/router/commit/f9836f16f0e25b0a8495f5e01e3f303b1cbc8725), [`aee42c6`](https://github.com/TanStack/router/commit/aee42c6b641d8e919bfed9e0f04bb1b72092f3a6), [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8), [`9aec5a7`](https://github.com/TanStack/router/commit/9aec5a7012c47e83ec23bb4763494b72a5e68bfc), [`9871c06`](https://github.com/TanStack/router/commit/9871c0625806001d6bf373524821a00303438a91), [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9)]: + - @tanstack/router-core@1.171.29 + - @tanstack/react-router@1.170.34 + - @tanstack/start-client-core@1.170.29 + +## 1.168.31 + +### Patch Changes + +- Updated dependencies [[`edf0e16`](https://github.com/TanStack/router/commit/edf0e16ebfe82ec6e8f68f403a1fda8de9e28889), [`2f20c00`](https://github.com/TanStack/router/commit/2f20c00224c5ba63467551914e0c37012588c4c2), [`28a5e45`](https://github.com/TanStack/router/commit/28a5e4504e4ea5cb1480667a4bea2588a53e110f), [`08eff50`](https://github.com/TanStack/router/commit/08eff50c447a154a3373909009e9e4375cea17ce), [`216c0c4`](https://github.com/TanStack/router/commit/216c0c48036fd1a33163b70dcabfed2b893808b0), [`2f91503`](https://github.com/TanStack/router/commit/2f9150309bc472f4a75cbe98adcdb50c76b12c7a), [`f0b5eda`](https://github.com/TanStack/router/commit/f0b5eda544606686a8a8d675a686ca1366428b96), [`50eafca`](https://github.com/TanStack/router/commit/50eafcaebbbedb6fde3b2816de7a0ace8cde4832), [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b), [`0caf6b9`](https://github.com/TanStack/router/commit/0caf6b9a2b7e14b0b146c74cc27cb05c19d700a5), [`ee28348`](https://github.com/TanStack/router/commit/ee283480dfa51150a2e0b096a6eff94a89ff8b3f), [`cf166d1`](https://github.com/TanStack/router/commit/cf166d160e6397007a979bfc7065b45ff69ea543), [`c18e690`](https://github.com/TanStack/router/commit/c18e69081475a7c98f9d40bd0fe6da78ccb84598)]: + - @tanstack/router-core@1.171.28 + - @tanstack/react-router@1.170.33 + - @tanstack/start-client-core@1.170.28 + +## 1.168.30 + +### Patch Changes + +- Updated dependencies [[`fa65287`](https://github.com/TanStack/router/commit/fa652872812c9433ba8b9d9a285e51b535e7367c), [`cb281d7`](https://github.com/TanStack/router/commit/cb281d70c1f5fe780f9d07bc500ea3a284a4e04b)]: + - @tanstack/router-core@1.171.27 + - @tanstack/react-router@1.170.32 + - @tanstack/start-client-core@1.170.27 + +## 1.168.29 + +### Patch Changes + +- Updated dependencies [[`3e016ac`](https://github.com/TanStack/router/commit/3e016ac84ffec8119f0c25cfdd1fb17e5292bd34)]: + - @tanstack/router-core@1.171.26 + - @tanstack/react-router@1.170.31 + - @tanstack/start-client-core@1.170.26 + +## 1.168.28 + +### Patch Changes + +- Updated dependencies [[`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175), [`63d2cc9`](https://github.com/TanStack/router/commit/63d2cc9155ff5374112f7d067d0b278bafeb8486), [`f75cada`](https://github.com/TanStack/router/commit/f75cada01707e51fb9650dd301bc04f8b2265a2a)]: + - @tanstack/react-router@1.170.30 + - @tanstack/router-core@1.171.25 + - @tanstack/start-client-core@1.170.25 + +## 1.168.27 + +### Patch Changes + +- Updated dependencies [[`4c89b15`](https://github.com/TanStack/router/commit/4c89b15dd2b46491ee5e57985559bae8e31d62c2), [`cf6ab17`](https://github.com/TanStack/router/commit/cf6ab178b39e7628bf784759f384e0f4230e6d9e), [`0fdf9ff`](https://github.com/TanStack/router/commit/0fdf9ff16fc532de9fc131d18df167ebd8038720), [`bdaf73a`](https://github.com/TanStack/router/commit/bdaf73a4063ee2b02e3c9cc105ad10ce82a5a0ff)]: + - @tanstack/router-core@1.171.24 + - @tanstack/react-router@1.170.29 + - @tanstack/start-client-core@1.170.24 + +## 1.168.26 + +### Patch Changes + +- Updated dependencies [[`0c25a7b`](https://github.com/TanStack/router/commit/0c25a7b43b5331ee6ebf94d50e9793002783adab), [`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90)]: + - @tanstack/react-router@1.170.28 + - @tanstack/router-core@1.171.23 + - @tanstack/start-client-core@1.170.23 + +## 1.168.25 + +### Patch Changes + +- Updated dependencies [[`b0817f5`](https://github.com/TanStack/router/commit/b0817f50cc639ae50b6c30cd11c5adbf7eed028c)]: + - @tanstack/react-router@1.170.27 + +## 1.168.24 + +### Patch Changes + +- Updated dependencies [[`7e93431`](https://github.com/TanStack/router/commit/7e93431ae9ff58c91c3c5ca10ffcb8414c1d0b13), [`f500760`](https://github.com/TanStack/router/commit/f5007607d62e932b8df19de866cdc6bddcff8db3), [`1aafca9`](https://github.com/TanStack/router/commit/1aafca9b45d24f8f0dba78e716fc9582346c6ca1), [`aa10b65`](https://github.com/TanStack/router/commit/aa10b6589eeda215f5a60ea0af95a3101d8c414e)]: + - @tanstack/router-core@1.171.22 + - @tanstack/react-router@1.170.26 + - @tanstack/start-client-core@1.170.22 + +## 1.168.23 + +### Patch Changes + +- Updated dependencies [[`51138a8`](https://github.com/TanStack/router/commit/51138a824cea053738f125c4c95073bd6286ff05)]: + - @tanstack/router-core@1.171.21 + - @tanstack/react-router@1.170.25 + - @tanstack/start-client-core@1.170.21 + +## 1.168.22 + +### Patch Changes + +- Updated dependencies [[`44a8c3e`](https://github.com/TanStack/router/commit/44a8c3e1d2af305064b2363d97fc7847c6f1a246), [`c59788c`](https://github.com/TanStack/router/commit/c59788ca20f2d2e7f264a859ebe01b7646ba3154), [`5253e70`](https://github.com/TanStack/router/commit/5253e70db2083d68a788fb7c9a043bb0c5518f2a)]: + - @tanstack/router-core@1.171.20 + - @tanstack/start-client-core@1.170.20 + - @tanstack/react-router@1.170.24 + +## 1.168.21 + +### Patch Changes + +- Updated dependencies [[`2fbc99f`](https://github.com/TanStack/router/commit/2fbc99f2c262b057cb957e6ebba1ee073c655186), [`95dec51`](https://github.com/TanStack/router/commit/95dec51018d01483949c6f1fe3094b019ccf3b4f), [`6bede65`](https://github.com/TanStack/router/commit/6bede65d7074dcd83455151b66b4574268bc782c)]: + - @tanstack/start-client-core@1.170.19 + - @tanstack/react-router@1.170.23 + +## 1.168.20 + +### Patch Changes + +- Updated dependencies [[`ea3a665`](https://github.com/TanStack/router/commit/ea3a665d81cbb5074c2d77ec953255ab534e7db9)]: + - @tanstack/react-router@1.170.22 + - @tanstack/router-core@1.171.19 + - @tanstack/start-client-core@1.170.18 + +## 1.168.19 + +### Patch Changes + +- Updated dependencies [[`697ebb6`](https://github.com/TanStack/router/commit/697ebb6ddbd433d052b6b4707938a5c595865d58), [`2435885`](https://github.com/TanStack/router/commit/2435885fa8b5e31c8c4b74d93920919f27316ebf), [`84db4a8`](https://github.com/TanStack/router/commit/84db4a842311df3f7e58073f6f12aaf371aeb5c7), [`9cac62a`](https://github.com/TanStack/router/commit/9cac62a5c7f99ef070991ea6f1fa7e42c746d46b), [`86bf510`](https://github.com/TanStack/router/commit/86bf510c2923afb76804223bd04afc2a809b33e7), [`6aefb33`](https://github.com/TanStack/router/commit/6aefb3392595a07a93f89301d7b5e3558ff9190c)]: + - @tanstack/react-router@1.170.21 + - @tanstack/router-core@1.171.18 + - @tanstack/start-client-core@1.170.17 + +## 1.168.18 + +### Patch Changes + +- Updated dependencies [[`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5)]: + - @tanstack/router-core@1.171.17 + - @tanstack/start-client-core@1.170.16 + - @tanstack/react-router@1.170.20 + +## 1.168.17 + +### Patch Changes + +- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: + - @tanstack/router-core@1.171.16 + - @tanstack/react-router@1.170.19 + - @tanstack/start-client-core@1.170.15 + +## 1.168.16 + +### Patch Changes + +- Updated dependencies [[`e2dd204`](https://github.com/TanStack/router/commit/e2dd2049cb42eb219d3b447b8605066d19d9c1fa)]: + - @tanstack/router-core@1.171.15 + - @tanstack/react-router@1.170.18 + - @tanstack/start-client-core@1.170.14 + +## 1.168.15 + +### Patch Changes + +- Updated dependencies [[`9809a06`](https://github.com/TanStack/router/commit/9809a0619d4ed3fe8c2a393af5b9eca4b6c7695b), [`ba52d2b`](https://github.com/TanStack/router/commit/ba52d2b8f9e95d6becd1be14c020b35f3231e02c)]: + - @tanstack/router-core@1.171.14 + - @tanstack/start-client-core@1.170.13 + - @tanstack/react-router@1.170.17 + +## 1.168.14 + +### Patch Changes + +- Updated dependencies [[`52db703`](https://github.com/TanStack/router/commit/52db7034fd83b17cc45da9ba775ec253f2a9a149), [`4a93cff`](https://github.com/TanStack/router/commit/4a93cffffca34702e419bc47db827f964fd0cb65), [`f046b06`](https://github.com/TanStack/router/commit/f046b064d32222cad0b7ea061311ca9a474f5990), [`689d88e`](https://github.com/TanStack/router/commit/689d88e04c48ec76a18453ab8b82d8d58f2668b6), [`689c5ab`](https://github.com/TanStack/router/commit/689c5ab32e9bb18d90a5a94c33237b0e418df3e3)]: + - @tanstack/react-router@1.170.16 + +## 1.168.13 + +### Patch Changes + +- Updated dependencies [[`9bebf8d`](https://github.com/TanStack/router/commit/9bebf8dc9f2bf74b680c065a5aa63d03b9622825)]: + - @tanstack/start-client-core@1.170.12 + +## 1.168.12 + +### Patch Changes + +- Updated dependencies [[`776d8ef`](https://github.com/TanStack/router/commit/776d8ef283e5bd9ffe97d43bc3a7f58064cd7e03)]: + - @tanstack/router-core@1.171.13 + - @tanstack/react-router@1.170.15 + - @tanstack/start-client-core@1.170.11 + +## 1.168.11 + +### Patch Changes + +- Updated dependencies [[`df1076c`](https://github.com/TanStack/router/commit/df1076c03ae5a51ab384bebd4d6afda20fb6f107)]: + - @tanstack/router-core@1.171.12 + - @tanstack/react-router@1.170.14 + - @tanstack/start-client-core@1.170.10 + +## 1.168.10 + +### Patch Changes + +- Updated dependencies [[`ac10815`](https://github.com/TanStack/router/commit/ac10815f387d25b15163ff711b4049e8f8482d01)]: + - @tanstack/router-core@1.171.11 + - @tanstack/react-router@1.170.13 + - @tanstack/start-client-core@1.170.9 + +## 1.168.9 + +### Patch Changes + +- Updated dependencies [[`2cca73c`](https://github.com/TanStack/router/commit/2cca73c92262ffd96dac4e283c9f69fb37f4b43a), [`7a83e67`](https://github.com/TanStack/router/commit/7a83e67e6596fbef21cb0a88a7127f5935bed2ba), [`76b3d3b`](https://github.com/TanStack/router/commit/76b3d3b24522bd3d1d216674c441252c9b8f184c)]: + - @tanstack/router-core@1.171.10 + - @tanstack/react-router@1.170.12 + - @tanstack/start-client-core@1.170.8 + +## 1.168.8 + +### Patch Changes + +- Updated dependencies [[`b4cd5af`](https://github.com/TanStack/router/commit/b4cd5af8d0f9d4aaa2d29095e6a261b9181bc778)]: + - @tanstack/router-core@1.171.9 + - @tanstack/react-router@1.170.11 + - @tanstack/start-client-core@1.170.7 + +## 1.168.7 + +### Patch Changes + +- Updated dependencies [[`2f53749`](https://github.com/TanStack/router/commit/2f5374945e2138559a51464f45a5152eae67e1dd)]: + - @tanstack/router-core@1.171.8 + - @tanstack/react-router@1.170.10 + - @tanstack/start-client-core@1.170.6 + +## 1.168.6 + +### Patch Changes + +- Updated dependencies [[`d1997b6`](https://github.com/TanStack/router/commit/d1997b66d7c24c1d64772bb8bab5caf9c6d9cc48)]: + - @tanstack/react-router@1.170.9 + - @tanstack/router-core@1.171.7 + - @tanstack/start-client-core@1.170.5 + +## 1.168.5 + +### Patch Changes + +- [#7492](https://github.com/TanStack/router/pull/7492) [`71fb329`](https://github.com/TanStack/router/commit/71fb3297e93a126e1bcfd9eeb0626cc4b8df8dd8) - Avoid pulling the client hydration entry into root `@tanstack/react-start` and `@tanstack/solid-start` imports by re-exporting `Hydrate` from framework client Hydrate-only subpaths. + +## 1.168.4 + +### Patch Changes + +- Updated dependencies [[`a82cec6`](https://github.com/TanStack/router/commit/a82cec69474c366b36efdb3f43c4efe8311c485a)]: + - @tanstack/start-client-core@1.170.4 + +## 1.168.3 + +### Patch Changes + +- Updated dependencies [[`51a97a1`](https://github.com/TanStack/router/commit/51a97a167fb3ef1b8ca70fbb63db635158f43509)]: + - @tanstack/router-core@1.171.6 + - @tanstack/react-router@1.170.8 + - @tanstack/start-client-core@1.170.3 + +## 1.168.2 + +### Patch Changes + +- Updated dependencies [[`5268ba4`](https://github.com/TanStack/router/commit/5268ba4566233ea58880df85f167ad0401a93a46)]: + - @tanstack/router-core@1.171.5 + - @tanstack/react-router@1.170.7 + - @tanstack/start-client-core@1.170.2 + +## 1.168.1 + +### Patch Changes + +- Updated dependencies [[`0300f87`](https://github.com/TanStack/router/commit/0300f87ec5a7f878ffbe0b181acf84cba9139960), [`0300f87`](https://github.com/TanStack/router/commit/0300f87ec5a7f878ffbe0b181acf84cba9139960)]: + - @tanstack/router-core@1.171.4 + - @tanstack/react-router@1.170.6 + - @tanstack/start-client-core@1.170.1 + +## 1.168.0 + +### Minor Changes + +- Add deferred Hydrate boundary support for TanStack Start. ([#7362](https://github.com/TanStack/router/pull/7362)) + + Hydrate boundaries can now be code-split by the Start compiler, preload their generated client chunks, preserve server-rendered fallback HTML, and replay interaction-triggered events after hydration. The compiler integration now uses a Start-owned compiler plugin for Hydrate virtual modules across Vite and Rsbuild, with dev invalidation for generated virtual modules. + + Shared AST utilities used by the router code-splitter and Hydrate virtual modules were moved into `@tanstack/router-utils` so both pipelines can retain referenced top-level declarations, unwrap local exports, and let dead-code elimination remove unused route module code. + +### Patch Changes + +- Updated dependencies [[`5fa9e55`](https://github.com/TanStack/router/commit/5fa9e555f3a2edb5e45586623e6bcbfa7f7c7a6b)]: + - @tanstack/start-client-core@1.170.0 + - @tanstack/router-core@1.171.3 + - @tanstack/react-router@1.170.5 + +## 1.167.4 + +### Patch Changes + +- Updated dependencies [[`b60eb36`](https://github.com/TanStack/router/commit/b60eb36e59e8a468ee0742cbcf7f47aca1ff1c67)]: + - @tanstack/router-core@1.171.2 + - @tanstack/react-router@1.170.4 + - @tanstack/start-client-core@1.169.4 + +## 1.167.3 + +### Patch Changes + +- Updated dependencies [[`d9cf933`](https://github.com/TanStack/router/commit/d9cf9331b83fcbd2abfee75d839d862f9bb18e6b)]: + - @tanstack/router-core@1.171.1 + - @tanstack/react-router@1.170.3 + - @tanstack/start-client-core@1.169.3 + +## 1.167.2 + +### Patch Changes + +- Updated dependencies [[`d533f87`](https://github.com/TanStack/router/commit/d533f87976704098a40b48f160b37c28c8182806)]: + - @tanstack/router-core@1.171.0 + - @tanstack/react-router@1.170.2 + - @tanstack/start-client-core@1.169.2 + +## 1.167.1 + +### Patch Changes + +- Updated dependencies [[`2387a2e`](https://github.com/TanStack/router/commit/2387a2eea0683004cc400b9f71bed5944eb60110)]: + - @tanstack/router-core@1.170.1 + - @tanstack/react-router@1.170.1 + - @tanstack/start-client-core@1.169.1 + +## 1.167.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +### Patch Changes + +- Updated dependencies [[`b1c061a`](https://github.com/TanStack/router/commit/b1c061aff9185cdf5fdc08c0136382a9dce0302f), [`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14)]: + - @tanstack/router-core@1.170.0 + - @tanstack/react-router@1.170.0 + - @tanstack/start-client-core@1.169.0 + +## 1.166.48 + +### Patch Changes + +- Updated dependencies [[`35e88f0`](https://github.com/TanStack/router/commit/35e88f04996d71019a1868b7b06ecb4ddbc9df9e)]: + - @tanstack/router-core@1.169.2 + - @tanstack/start-client-core@1.168.2 + - @tanstack/react-router@1.169.2 + +## 1.166.47 + +### Patch Changes + +- Updated dependencies [[`4a1e63f`](https://github.com/TanStack/router/commit/4a1e63f1d1230b1ed8234609acad4639d8982c13)]: + - @tanstack/router-core@1.169.1 + - @tanstack/react-router@1.169.1 + - @tanstack/start-client-core@1.168.1 + +## 1.166.46 + +### Patch Changes + +- Updated dependencies [[`82b0613`](https://github.com/TanStack/router/commit/82b06132af776f74603ab27977cc277d6219a845)]: + - @tanstack/start-client-core@1.168.0 + +## 1.166.45 + +### Patch Changes + +- Updated dependencies [[`c992495`](https://github.com/TanStack/router/commit/c992495bf4010ff4c3597bb1f3b1ba02594e857e)]: + - @tanstack/router-core@1.169.0 + - @tanstack/react-router@1.169.0 + - @tanstack/start-client-core@1.167.22 + +## 1.166.44 + +### Patch Changes + +- Updated dependencies [[`b5c4183`](https://github.com/TanStack/router/commit/b5c4183ab8b44be8a75647b7f7b588ad7c146ece)]: + - @tanstack/router-core@1.168.18 + - @tanstack/react-router@1.168.26 + - @tanstack/start-client-core@1.167.21 + +## 1.166.43 + +### Patch Changes + +- Updated dependencies [[`493148b`](https://github.com/TanStack/router/commit/493148bc5378b7f9de1544d87f6aaa425c12eb34)]: + - @tanstack/router-core@1.168.17 + - @tanstack/react-router@1.168.25 + - @tanstack/start-client-core@1.167.20 + +## 1.166.42 + +### Patch Changes + +- Updated dependencies [[`8b97002`](https://github.com/TanStack/router/commit/8b97002af3f6d15204e60c55d3f5735b78bd7efe)]: + - @tanstack/start-client-core@1.167.19 + +## 1.166.41 + +### Patch Changes + +- Updated dependencies [[`4d864ee`](https://github.com/TanStack/router/commit/4d864eebbd184265eabb563d326ab409c93feb17)]: + - @tanstack/react-router@1.168.24 + - @tanstack/router-core@1.168.16 + - @tanstack/start-client-core@1.167.18 + +## 1.166.40 + +### Patch Changes + +- Updated dependencies [[`cd91cee`](https://github.com/TanStack/router/commit/cd91ceebb84b7b752b5ee09ac14e89ad2beb2259)]: + - @tanstack/react-router@1.168.23 + +## 1.166.39 + +### Patch Changes + +- Updated dependencies [[`e30814d`](https://github.com/TanStack/router/commit/e30814d949110ff25829de44d729ead47555940a)]: + - @tanstack/react-router@1.168.22 + +## 1.166.38 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/react-router@1.168.21 + - @tanstack/start-client-core@1.167.17 + +## 1.166.37 + +### Patch Changes + +- Updated dependencies [[`c5ad329`](https://github.com/TanStack/router/commit/c5ad32936f6adcca0c56474677b73b212498443b)]: + - @tanstack/react-router@1.168.20 + +## 1.166.36 + +### Patch Changes + +- Updated dependencies [[`105d056`](https://github.com/TanStack/router/commit/105d05691a247779a63e7b688aa1207cce619339)]: + - @tanstack/react-router@1.168.19 + +## 1.166.35 + +### Patch Changes + +- Updated dependencies [[`0e2c900`](https://github.com/TanStack/router/commit/0e2c9003c18ae07c09969189c028f277ea562a7a)]: + - @tanstack/router-core@1.168.14 + - @tanstack/react-router@1.168.18 + - @tanstack/start-client-core@1.167.16 + +## 1.166.34 + +### Patch Changes + +- Updated dependencies [[`812792f`](https://github.com/TanStack/router/commit/812792fbda3caf97b300770855cf5641252f413b)]: + - @tanstack/router-core@1.168.13 + - @tanstack/react-router@1.168.17 + - @tanstack/start-client-core@1.167.15 + +## 1.166.33 + +### Patch Changes + +- Updated dependencies [[`8ec9ca9`](https://github.com/TanStack/router/commit/8ec9ca97b472779de878c2a6510f21deb24d386c)]: + - @tanstack/router-core@1.168.12 + - @tanstack/react-router@1.168.16 + - @tanstack/start-client-core@1.167.14 + +## 1.166.32 + +### Patch Changes + +- Updated dependencies [[`6355bb7`](https://github.com/TanStack/router/commit/6355bb75f7637ba77f06a923c18fdaf37720bb48)]: + - @tanstack/react-router@1.168.15 + - @tanstack/router-core@1.168.11 + - @tanstack/start-client-core@1.167.13 + +## 1.166.31 + +### Patch Changes + +- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: + - @tanstack/start-client-core@1.167.12 + - @tanstack/react-router@1.168.14 + - @tanstack/router-core@1.168.10 + +## 1.166.30 + +### Patch Changes + +- fix publishing ([`f8ac427`](https://github.com/TanStack/router/commit/f8ac427000c3fec99225926e72f9f2fc7a37231f)) + +- Updated dependencies [[`f8ac427`](https://github.com/TanStack/router/commit/f8ac427000c3fec99225926e72f9f2fc7a37231f)]: + - @tanstack/start-client-core@1.167.11 + +## 1.166.29 + +### Patch Changes + +- Updated dependencies [[`540d221`](https://github.com/TanStack/router/commit/540d22100d33415a1ddc9eb193f6aeb8184da77f), [`70ec1da`](https://github.com/TanStack/router/commit/70ec1da1ed8aa252fae67716f69fe8520ecf91b0)]: + - @tanstack/react-router@1.168.13 + +## 1.166.28 + +### Patch Changes + +- Updated dependencies [[`b29d64d`](https://github.com/TanStack/router/commit/b29d64de0c400183114c12f82183f80e37d9ea5c)]: + - @tanstack/react-router@1.168.12 + +## 1.166.27 + +### Patch Changes + +- Updated dependencies [[`4b9ed6c`](https://github.com/TanStack/router/commit/4b9ed6c5cb5437df8607c605728c8338dd2eb02c)]: + - @tanstack/react-router@1.168.11 + +## 1.166.26 + +### Patch Changes + +- Updated dependencies [[`f7e9c5e`](https://github.com/TanStack/router/commit/f7e9c5e323793d1b28c96871819c265fd28ae397)]: + - @tanstack/start-client-core@1.167.10 + +## 1.166.25 + +### Patch Changes + +- Updated dependencies [[`796406d`](https://github.com/TanStack/router/commit/796406da66cfb12b518bb3ca326c9d541368fb06)]: + - @tanstack/router-core@1.168.9 + - @tanstack/react-router@1.168.10 + - @tanstack/start-client-core@1.167.9 + +## 1.166.24 + +### Patch Changes + +- Updated dependencies [[`2d1ec86`](https://github.com/TanStack/router/commit/2d1ec865a446926f7db6e29dbbde82d265de6d36)]: + - @tanstack/router-core@1.168.8 + - @tanstack/react-router@1.168.9 + - @tanstack/start-client-core@1.167.8 + +## 1.166.23 + +### Patch Changes + +- Updated dependencies [[`6ee0e79`](https://github.com/TanStack/router/commit/6ee0e795b085651beb2f1ac6503cdbd7eaffedd1)]: + - @tanstack/router-core@1.168.7 + - @tanstack/react-router@1.168.8 + - @tanstack/start-client-core@1.167.7 + +## 1.166.22 + +### Patch Changes + +- Updated dependencies [[`42c3f3b`](https://github.com/TanStack/router/commit/42c3f3b3a3a478fd6d6894310ef94b2d23794b8e)]: + - @tanstack/router-core@1.168.6 + - @tanstack/react-router@1.168.7 + - @tanstack/start-client-core@1.167.6 + +## 1.166.21 + +### Patch Changes + +- Updated dependencies [[`5ca661c`](https://github.com/TanStack/router/commit/5ca661c2f8a7e50167b4112c64aa06cef4148ea9)]: + - @tanstack/react-router@1.168.6 + +## 1.166.20 + +### Patch Changes + +- Updated dependencies [[`cf5f554`](https://github.com/TanStack/router/commit/cf5f5542476137a81515099ad740747e84512f9a)]: + - @tanstack/router-core@1.168.5 + - @tanstack/react-router@1.168.5 + - @tanstack/start-client-core@1.167.5 + +## 1.166.19 + +### Patch Changes + +- Updated dependencies [[`71a8b68`](https://github.com/TanStack/router/commit/71a8b684c87c37fd4a033d99f5ba4a05c7a179f5)]: + - @tanstack/react-router@1.168.4 + - @tanstack/router-core@1.168.4 + - @tanstack/start-client-core@1.167.4 + +## 1.166.18 + +### Patch Changes + +- Updated dependencies [[`d81d21a`](https://github.com/TanStack/router/commit/d81d21ad05c9401bf54b24acd29401e1e4fd624c)]: + - @tanstack/react-router@1.168.3 + - @tanstack/router-core@1.168.3 + - @tanstack/start-client-core@1.167.3 + +## 1.166.17 + +### Patch Changes + +- Replace tiny-invariant and tiny-warning with in-house solution for bundle-size ([#7007](https://github.com/TanStack/router/pull/7007)) + +- Updated dependencies [[`c9e1855`](https://github.com/TanStack/router/commit/c9e18555f3a5531e96de8f574cfca9edcdb18e5c)]: + - @tanstack/start-client-core@1.167.2 + - @tanstack/react-router@1.168.2 + - @tanstack/router-core@1.168.2 + +## 1.166.16 + +### Patch Changes + +- Updated dependencies [[`91cc628`](https://github.com/TanStack/router/commit/91cc62899b75ca920fe83c5ee7f3dbb5c71a523f)]: + - @tanstack/react-router@1.168.1 + - @tanstack/router-core@1.168.1 + - @tanstack/start-client-core@1.167.1 + +## 1.166.15 + +### Patch Changes + +- Updated dependencies [[`0545239`](https://github.com/TanStack/router/commit/054523900b2ee19308e5a88417dadfc6923afe30)]: + - @tanstack/start-client-core@1.167.0 + - @tanstack/react-router@1.168.0 + - @tanstack/router-core@1.168.0 + +## 1.166.14 + +### Patch Changes + +- Updated dependencies [[`5ff4f0b`](https://github.com/TanStack/router/commit/5ff4f0b8dce1fac2bb0b0bfe2684fc677a8ee505)]: + - @tanstack/router-core@1.167.5 + - @tanstack/react-router@1.167.5 + - @tanstack/start-client-core@1.166.13 + +## 1.166.13 + +### Patch Changes + +- Updated dependencies [[`940151c`](https://github.com/TanStack/router/commit/940151cbed0c76c92a5cf196c0905b17a956ca7e)]: + - @tanstack/router-core@1.167.4 + - @tanstack/react-router@1.167.4 + - @tanstack/start-client-core@1.166.12 + +## 1.166.12 + +### Patch Changes + +- Updated dependencies [[`32fcba7`](https://github.com/TanStack/router/commit/32fcba7b044b03f5901308b870f70b0b4910c220)]: + - @tanstack/router-core@1.167.3 + - @tanstack/react-router@1.167.3 + - @tanstack/start-client-core@1.166.11 + +## 1.166.11 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +- Updated dependencies [[`838b0eb`](https://github.com/TanStack/router/commit/838b0eb9a8bbbb987a0a6972c1446e01423bbd7b)]: + - @tanstack/react-router@1.167.2 + - @tanstack/router-core@1.167.2 + - @tanstack/start-client-core@1.166.10 + +## 1.166.10 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) + +- Updated dependencies [[`ef9b241`](https://github.com/TanStack/router/commit/ef9b241f3cfe95cee40daa96da669f0ffd4a971a)]: + - @tanstack/start-client-core@1.166.9 + - @tanstack/react-router@1.167.1 + - @tanstack/router-core@1.167.1 + +## 1.166.9 + +### Patch Changes + +- Updated dependencies [[`6f297a2`](https://github.com/TanStack/router/commit/6f297a249424c0fd1c1a56aa4fc12c8217be7b6a)]: + - @tanstack/router-core@1.167.0 + - @tanstack/react-router@1.167.0 + - @tanstack/start-client-core@1.166.8 + +## 1.166.8 + +### Patch Changes + +- Updated dependencies [[`6069eba`](https://github.com/TanStack/router/commit/6069eba64369dbddb0d8dccdb4407f0e1a82259e)]: + - @tanstack/react-router@1.166.8 diff --git a/packages/react-start-client/package.json b/packages/react-start-client/package.json index 669ac57a98..b919d47b92 100644 --- a/packages/react-start-client/package.json +++ b/packages/react-start-client/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-start-client", - "version": "1.141.8", + "version": "1.168.45", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -30,12 +30,12 @@ "test:unit:dev": "vitest --watch", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -48,6 +48,18 @@ "default": "./dist/esm/index.js" } }, + "./hydration": { + "import": { + "types": "./dist/esm/hydration.d.ts", + "default": "./dist/esm/hydration.js" + } + }, + "./Hydrate": { + "import": { + "types": "./dist/esm/Hydrate.d.ts", + "default": "./dist/esm/Hydrate.js" + } + }, "./package.json": "./package.json" }, "sideEffects": false, @@ -61,13 +73,25 @@ "dependencies": { "@tanstack/react-router": "workspace:*", "@tanstack/router-core": "workspace:*", - "@tanstack/start-client-core": "workspace:*", - "tiny-invariant": "^1.3.3", - "tiny-warning": "^1.0.3" + "@tanstack/start-client-core": "workspace:*" }, "devDependencies": { - "@testing-library/react": "^16.2.0", - "@vitejs/plugin-react": "^4.3.4" + "@testing-library/react": "catalog:", + "@vitejs/plugin-react": "catalog:", + "vite": "*", + "@types/node": ">=20", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@eslint-react/eslint-plugin": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", diff --git a/packages/react-start-client/src/GenericHydrate.tsx b/packages/react-start-client/src/GenericHydrate.tsx new file mode 100644 index 0000000000..e92042a0d7 --- /dev/null +++ b/packages/react-start-client/src/GenericHydrate.tsx @@ -0,0 +1,436 @@ +'use client' + +import * as React from 'react' + +import { reactUse, useHydrated, useLayoutEffect } from '@tanstack/react-router' +import { isServer } from '@tanstack/router-core/isServer' +import { + hydrateIdAttribute, + hydrateWhenAttribute, +} from '@tanstack/start-client-core/hydration/constants' +import { + createResolvedGate, + getFallbackHtml, + getOrCreateGate, + onGateResolve, + releaseGate, + runHydrationStrategyCleanup, + saveFallbackHtml, + waitForHydrationPrefetchStrategy, +} from '@tanstack/start-client-core/hydration/runtime' +import { listenForDelegatedHydrationIntent } from '@tanstack/start-client-core/hydration' +import type { + HydrationRuntimeContext, + HydrationStrategy, + HydrationWhen, +} from '@tanstack/start-client-core/hydration' +import type { HydrationGateRecord } from '@tanstack/start-client-core/hydration/runtime' +import type { HydrateProps, InternalHydrateProps } from './Hydrate' + +type Gate = HydrationGateRecord & { promise: Promise } +type PrefetchController = { + abortController: AbortController + hydrationRequested: boolean + hydrationListeners: Set<() => void> + hydrationResolvePending: boolean + started: boolean + promise?: Promise + cleanup?: () => void +} + +const dynamicType = 'dynamic' +const dynamicHydrateStrategy = { + _t: dynamicType, + _d: () => true, +} satisfies HydrationStrategy + +function shouldDeferHydration(strategy: HydrationStrategy) { + return strategy._d ? strategy._d() : strategy._t !== 'load' +} + +function useLatest(value: T) { + const ref = React.useRef(value) + ref.current = value + return ref +} + +function useHydrationGate(props: InternalHydrateProps) { + const hydrated = useHydrated() + const reactId = React.useId() + const id = props.h ? `${props.h}${reactId}` : reactId + const when = props.when + const isDynamicHydrate = typeof when === 'function' + const dynamicHydrateStrategyRef = React.useRef( + undefined, + ) + if (isDynamicHydrate) { + dynamicHydrateStrategyRef.current ??= + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') + ? dynamicHydrateStrategy + : when() + } + const hydrateStrategy = isDynamicHydrate + ? dynamicHydrateStrategyRef.current! + : when + const markerHydrateType: HydrationWhen = isDynamicHydrate + ? dynamicType + : hydrateStrategy._t! + const [prefetchError, setPrefetchError] = React.useState() + const latestRef = useLatest({ + prefetch: props.prefetch, + preload: props.p, + }) + const gateRef = React.useRef(undefined) + const markerElementRef = React.useRef(null) + const shouldPreserveServerHTMLRef = React.useRef( + undefined, + ) + const shouldDeferInitialHydrationRef = React.useRef( + undefined, + ) + const didPrefetchRef = React.useRef(false) + const prefetchControllerRef = React.useRef( + undefined, + ) + + prefetchControllerRef.current ??= { + abortController: new AbortController(), + hydrationRequested: false, + hydrationListeners: new Set<() => void>(), + hydrationResolvePending: false, + started: false, + } + + shouldPreserveServerHTMLRef.current ??= + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') || !hydrated + shouldDeferInitialHydrationRef.current ??= + !hydrated && shouldDeferHydration(hydrateStrategy) + + if (!gateRef.current) { + gateRef.current = + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') + ? createResolvedGate(id, hydrateStrategy._t!) + : getOrCreateGate(id, hydrateStrategy._t!) + } + + gateRef.current.when = hydrateStrategy._t! + + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + !(isServer ?? typeof window === 'undefined') && + hydrateStrategy._t !== 'never' && + (!shouldDeferInitialHydrationRef.current || + !shouldDeferHydration(hydrateStrategy)) + ) { + gateRef.current.resolve() + } + + const markerRef = React.useCallback( + (element: HTMLDivElement | null) => { + markerElementRef.current = element + if (element) { + if ( + hydrateStrategy._t === 'never' && + !shouldPreserveServerHTMLRef.current + ) { + element.replaceChildren() + } + saveFallbackHtml(id, element) + } + }, + [hydrateStrategy._t, id], + ) + + React.useEffect(() => { + const gate = gateRef.current! + return () => { + const controller = prefetchControllerRef.current + controller?.abortController.abort() + controller?.cleanup?.() + controller?.hydrationListeners.clear() + releaseGate(gate) + } + }, []) + + React.useEffect(() => { + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') || + !latestRef.current.prefetch + ) { + return + } + + const controller = prefetchControllerRef.current! + if (controller.started) return + controller.started = true + + const onHydrate = (listener: () => void) => { + if (controller.hydrationRequested) { + listener() + return () => {} + } + + controller.hydrationListeners.add(listener) + return () => { + controller.hydrationListeners.delete(listener) + } + } + + const preload = () => latestRef.current.preload?.() ?? Promise.resolve() + const prefetchInput = latestRef.current.prefetch + + if (typeof prefetchInput === 'function') { + const promise = Promise.resolve() + .then(() => + prefetchInput({ + element: markerElementRef.current, + signal: controller.abortController.signal, + preload, + waitFor: (strategy) => + waitForHydrationPrefetchStrategy(strategy, { + element: markerElementRef.current, + signal: controller.abortController.signal, + onHydrate, + }), + }), + ) + .then(() => undefined) + + controller.promise = promise + promise.catch((error) => { + if (!controller.abortController.signal.aborted) { + setPrefetchError(error) + } + }) + return + } + + if (!latestRef.current.preload) return + + const prefetch = () => { + if (didPrefetchRef.current) return + didPrefetchRef.current = true + void preload() + } + + controller.cleanup = runHydrationStrategyCleanup( + prefetchInput._s?.({ + element: markerElementRef.current, + prefetch, + }), + ) + }, [hydrateStrategy, latestRef]) + + useLayoutEffect(() => { + const gate = gateRef.current! + if ( + !shouldDeferInitialHydrationRef.current || + hydrateStrategy._t === 'never' + ) { + return + } + + if (gate.resolved) { + return + } + + const cleanups: Array<() => void> = [] + let removeResolveListener = () => {} + let disposed = false + const resolveGate = gate.resolve + + const cleanup = () => { + if (disposed) return + disposed = true + if (gate.resolve === requestHydration) { + gate.resolve = resolveGate + } + removeResolveListener() + cleanups.forEach((fn) => fn()) + } + + const addCleanup = (fn: void | (() => void)) => { + if (!fn) return + if (disposed || gate.resolved) { + fn() + return + } + cleanups.push(fn) + } + + const requestHydration = () => { + const controller = prefetchControllerRef.current! + if (!controller.hydrationRequested) { + controller.hydrationRequested = true + controller.hydrationListeners.forEach((listener) => listener()) + controller.hydrationListeners.clear() + } + + if (!controller.promise) { + resolveGate() + return + } + if (controller.hydrationResolvePending) return + controller.hydrationResolvePending = true + + controller.promise.then( + () => resolveGate(), + (error) => { + if (!controller.abortController.signal.aborted) { + setPrefetchError(error) + } + }, + ) + } + + gate.resolve = requestHydration + removeResolveListener = onGateResolve(gate, cleanup) + + const context: HydrationRuntimeContext = { + element: markerElementRef.current, + gate, + } + addCleanup(runHydrationStrategyCleanup(hydrateStrategy._s?.(context))) + + if (hydrateStrategy._t !== 'interaction') { + addCleanup( + runHydrationStrategyCleanup( + markerElementRef.current + ? listenForDelegatedHydrationIntent( + markerElementRef.current, + context, + ) + : undefined, + ), + ) + } + + return cleanup + }, [hydrateStrategy, latestRef]) + + return { + gate: gateRef.current, + markerRef, + markerElementRef, + hydrateStrategy, + markerHydrateType, + prefetchError, + shouldPreserveServerHTML: shouldPreserveServerHTMLRef.current, + } +} + +function HydrationGate(props: { gate: Gate; children: React.ReactNode }) { + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + isServer ?? + typeof window === 'undefined' + ) { + return props.children as React.JSX.Element + } + + if (props.gate.resolved) { + return props.children as React.JSX.Element + } + + if (!reactUse) { + throw props.gate.promise + } + + reactUse(props.gate.promise) + + return props.children as React.JSX.Element +} + +function HydratedBoundary(props: { + id: string + onHydrated?: () => void + onStrategyHydrated?: (id: string) => void + children: React.ReactNode +}) { + const { id, onHydrated, onStrategyHydrated } = props + const didHydrateRef = React.useRef(false) + + React.useEffect(() => { + if (didHydrateRef.current) return + didHydrateRef.current = true + onHydrated?.() + onStrategyHydrated?.(id) + }, [id, onHydrated, onStrategyHydrated]) + + return props.children as React.JSX.Element +} + +export function GenericHydrate(props: HydrateProps): React.JSX.Element { + const internalProps = props as InternalHydrateProps + const { + gate, + hydrateStrategy, + markerHydrateType, + markerElementRef, + markerRef, + prefetchError, + shouldPreserveServerHTML, + } = useHydrationGate(internalProps) + if (prefetchError) throw prefetchError + + const fallback = shouldPreserveServerHTML + ? (() => { + const html = getFallbackHtml(gate.id) + return html ? ( +
    + ) : null + })() + : (props.fallback ?? null) + const markerAttributes = + markerHydrateType === dynamicType ? undefined : hydrateStrategy._a?.() + + const hydrateType = hydrateStrategy._t! + + if (hydrateType === 'never' && !shouldPreserveServerHTML) { + return ( +
    + {props.fallback ?? null} +
    + ) + } + + return ( +
    + + + { + markerElementRef.current?.removeAttribute(hydrateWhenAttribute) + hydrateStrategy._o?.(id) + }} + > + {props.children} + + + +
    + ) +} diff --git a/packages/react-start-client/src/Hydrate.tsx b/packages/react-start-client/src/Hydrate.tsx new file mode 100644 index 0000000000..019730f3be --- /dev/null +++ b/packages/react-start-client/src/Hydrate.tsx @@ -0,0 +1,107 @@ +'use client' + +import * as React from 'react' + +import { isServer } from '@tanstack/router-core/isServer' +import type { + HydrationStrategy as CoreHydrationStrategy, + HydrationPrefetchFunction, + HydrationPrefetchStrategy, + HydrationWhen, +} from '@tanstack/start-client-core/hydration' + +export type { + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationPrefetchContext, + HydrationPrefetchFunction, + HydrationPrefetchStrategy, + HydrationPrefetchWaitReason, + HydrationWhen, +} from '@tanstack/start-client-core/hydration' + +export type ReactHydrationStrategy< + TWhen extends HydrationWhen = HydrationWhen, + TCanPrefetch extends boolean = boolean, +> = CoreHydrationStrategy & { + _h: (this: ReactHydrationStrategy, props: HydrateProps) => React.JSX.Element +} + +export type HydrationStrategy< + TWhen extends HydrationWhen = HydrationWhen, + TCanPrefetch extends boolean = boolean, +> = ReactHydrationStrategy + +export type HydrateWhen = + | ReactHydrationStrategy + | (() => ReactHydrationStrategy) + +type HydrateCommonOptions = { + when: HydrateWhen + fallback?: React.ReactNode + onHydrated?: () => void +} + +export type HydrateOptions = + | (HydrateCommonOptions & { + prefetch?: never + split?: boolean + }) + | (HydrateCommonOptions & { + prefetch: HydrationPrefetchStrategy + split?: true + }) + | (HydrateCommonOptions & { + prefetch: HydrationPrefetchFunction + split?: boolean + }) + +export type HydrateProps = HydrateOptions & { + children: React.ReactNode +} + +export type InternalHydrateProps = HydrateProps & { + h?: string + p?: () => Promise +} + +const dynamicType = 'dynamic' +const hydrateIdAttribute = 'data-ts-hydrate-id' +const hydrateWhenAttribute = 'data-ts-hydrate-when' + +/* @__NO_SIDE_EFFECTS__ */ +function ServerDynamicHydrate(props: HydrateProps): React.JSX.Element { + const internalProps = props as InternalHydrateProps + const reactId = React.useId() + const id = internalProps.h ? `${internalProps.h}${reactId}` : reactId + + return ( +
    + + {props.children} + +
    + ) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function Hydrate(props: HydrateProps): React.JSX.Element { + if (typeof props.when === 'function') { + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + isServer ?? + typeof window === 'undefined' + ) { + return + } + + return props.when()._h(props) + } + + return props.when._h(props) +} diff --git a/packages/react-start-client/src/hydrateStart.ts b/packages/react-start-client/src/hydrateStart.ts index 22f4848de7..21f1fa2039 100644 --- a/packages/react-start-client/src/hydrateStart.ts +++ b/packages/react-start-client/src/hydrateStart.ts @@ -4,9 +4,6 @@ import type { AnyRouter } from '@tanstack/router-core' /** * React-specific wrapper for hydrateStart that signals hydration completion */ -export async function hydrateStart(): Promise { - const router = await coreHydrateStart() - // Signal that router hydration is complete so cleanup can happen if stream has ended - window.$_TSR?.h() - return router +export function hydrateStart(): Promise { + return coreHydrateStart().finally(() => window.$_TSR?.h()) } diff --git a/packages/react-start-client/src/hydration.ts b/packages/react-start-client/src/hydration.ts new file mode 100644 index 0000000000..fad458175c --- /dev/null +++ b/packages/react-start-client/src/hydration.ts @@ -0,0 +1,22 @@ +'use client' + +export { condition, interaction, media } from './hydration/generic' +export { idle } from './hydration/idle' +export { load } from './hydration/load' +export { never } from './hydration/never' +export { visible } from './hydration/visible' +export type { + HydrationCondition, + HydrationInteractionEvent, + HydrationInteractionEvents, + IdleHydrationOptions, + HydrationPrefetchContext, + HydrationPrefetchFunction, + HydrationPrefetchWhen, + HydrationPrefetchStrategy, + HydrationPrefetchWaitReason, + HydrationStrategyTypes, + HydrationWhen, + VisibleHydrationOptions, +} from '@tanstack/start-client-core/hydration' +export type { HydrationStrategy, ReactHydrationStrategy } from './Hydrate' diff --git a/packages/react-start-client/src/hydration/generic.ts b/packages/react-start-client/src/hydration/generic.ts new file mode 100644 index 0000000000..5ee6d3c3d6 --- /dev/null +++ b/packages/react-start-client/src/hydration/generic.ts @@ -0,0 +1,43 @@ +'use client' + +import { + condition as coreCondition, + interaction as coreInteraction, + media as coreMedia, + withHydrationRenderer, +} from '@tanstack/start-client-core/hydration' +import { GenericHydrate } from '../GenericHydrate' +import type { + HydrationCondition, + HydrationInteractionEvents, + HydrationPrefetchStrategy, +} from '@tanstack/start-client-core/hydration' +import type { ReactHydrationStrategy } from '../Hydrate' + +/* @__NO_SIDE_EFFECTS__ */ +export function media( + query: string, +): ReactHydrationStrategy<'media', true> & HydrationPrefetchStrategy<'media'> { + return /* @__PURE__ */ withHydrationRenderer(coreMedia(query), GenericHydrate) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function condition( + condition: HydrationCondition, +): ReactHydrationStrategy<'condition', false> { + return /* @__PURE__ */ withHydrationRenderer( + coreCondition(condition), + GenericHydrate, + ) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function interaction(options?: { + events?: HydrationInteractionEvents +}): ReactHydrationStrategy<'interaction', true> & + HydrationPrefetchStrategy<'interaction'> { + return /* @__PURE__ */ withHydrationRenderer( + coreInteraction(options), + GenericHydrate, + ) +} diff --git a/packages/react-start-client/src/hydration/idle.ts b/packages/react-start-client/src/hydration/idle.ts new file mode 100644 index 0000000000..58c7f265eb --- /dev/null +++ b/packages/react-start-client/src/hydration/idle.ts @@ -0,0 +1,22 @@ +'use client' + +import { + idle as coreIdle, + withHydrationRenderer, +} from '@tanstack/start-client-core/hydration' +import { GenericHydrate } from '../GenericHydrate' +import type { + HydrationPrefetchStrategy, + IdleHydrationOptions, +} from '@tanstack/start-client-core/hydration' +import type { ReactHydrationStrategy } from '../Hydrate' + +/* @__NO_SIDE_EFFECTS__ */ +export function idle( + options: IdleHydrationOptions = {}, +): ReactHydrationStrategy<'idle', true> & HydrationPrefetchStrategy<'idle'> { + return /* @__PURE__ */ withHydrationRenderer( + coreIdle(options), + GenericHydrate, + ) +} diff --git a/packages/react-start-client/src/hydration/load.tsx b/packages/react-start-client/src/hydration/load.tsx new file mode 100644 index 0000000000..006f4e6952 --- /dev/null +++ b/packages/react-start-client/src/hydration/load.tsx @@ -0,0 +1,49 @@ +'use client' + +import * as React from 'react' + +import { + load as coreLoad, + withHydrationRenderer, +} from '@tanstack/start-client-core/hydration' +import type { HydrationPrefetchStrategy } from '@tanstack/start-client-core/hydration' +import type { HydrateProps, ReactHydrationStrategy } from '../Hydrate' + +function HydratedBoundary(props: { + onHydrated?: () => void + children: React.ReactNode +}) { + const { onHydrated, children } = props + const didHydrateRef = React.useRef(false) + + React.useEffect(() => { + if (didHydrateRef.current) return + didHydrateRef.current = true + onHydrated?.() + }, [onHydrated]) + + return children as React.JSX.Element +} + +export function LoadHydrate(props: HydrateProps): React.JSX.Element { + return ( +
    + + + {props.children} + + +
    + ) +} + +const loadStrategy = /* @__PURE__ */ withHydrationRenderer( + coreLoad(), + LoadHydrate, +) as ReactHydrationStrategy<'load', true> & HydrationPrefetchStrategy<'load'> + +/* @__NO_SIDE_EFFECTS__ */ +export function load(): ReactHydrationStrategy<'load', true> & + HydrationPrefetchStrategy<'load'> { + return loadStrategy +} diff --git a/packages/react-start-client/src/hydration/never.tsx b/packages/react-start-client/src/hydration/never.tsx new file mode 100644 index 0000000000..250a8ed1ae --- /dev/null +++ b/packages/react-start-client/src/hydration/never.tsx @@ -0,0 +1,97 @@ +'use client' + +import * as React from 'react' + +import { reactUse, useHydrated } from '@tanstack/react-router' +import { isServer } from '@tanstack/router-core/isServer' +import { + never as coreNever, + withHydrationRenderer, +} from '@tanstack/start-client-core/hydration' +import { + hydrateIdAttribute, + hydrateWhenAttribute, +} from '@tanstack/start-client-core/hydration/constants' +import { + getFallbackHtml, + saveFallbackHtml, +} from '@tanstack/start-client-core/hydration/runtime' +import type { + HydrateProps, + InternalHydrateProps, + ReactHydrationStrategy, +} from '../Hydrate' + +const neverType = 'never' +const neverPromise = new Promise(() => {}) + +function NeverGate(props: { children: React.ReactNode }) { + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + isServer ?? + typeof window === 'undefined' + ) { + return props.children as React.JSX.Element + } + + if (!reactUse) { + throw neverPromise + } + + reactUse(neverPromise) + + return props.children as React.JSX.Element +} + +export function NeverHydrate(props: HydrateProps): React.JSX.Element { + const internalProps = props as InternalHydrateProps + const hydrated = useHydrated() + const reactId = React.useId() + const id = internalProps.h ? `${internalProps.h}${reactId}` : reactId + const shouldPreserveServerHTMLRef = React.useRef( + undefined, + ) + shouldPreserveServerHTMLRef.current ??= + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + (isServer ?? typeof window === 'undefined') || !hydrated + const markerRef = React.useCallback( + (element: HTMLDivElement | null) => { + if (!element) return + if (!shouldPreserveServerHTMLRef.current) { + element.replaceChildren() + } else { + saveFallbackHtml(id, element) + } + }, + [id], + ) + const markerProps = { + ref: markerRef, + [hydrateIdAttribute]: id, + [hydrateWhenAttribute]: neverType, + } + const fallback = (() => { + const html = getFallbackHtml(id) + return html ? ( +
    + ) : ( + (props.fallback ?? null) + ) + })() + + return ( +
    + + {props.children} + +
    + ) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function never(): ReactHydrationStrategy<'never', false> { + return /* @__PURE__ */ withHydrationRenderer(coreNever(), NeverHydrate) +} diff --git a/packages/react-start-client/src/hydration/visible.tsx b/packages/react-start-client/src/hydration/visible.tsx new file mode 100644 index 0000000000..b295d77462 --- /dev/null +++ b/packages/react-start-client/src/hydration/visible.tsx @@ -0,0 +1,141 @@ +'use client' + +import * as React from 'react' + +import { reactUse } from '@tanstack/react-router' +import { isServer } from '@tanstack/router-core/isServer' +import type { + HydrationPrefetchStrategy, + VisibleHydrationOptions, +} from '@tanstack/start-client-core/hydration' +import type { + HydrateProps, + InternalHydrateProps, + ReactHydrationStrategy, +} from '../Hydrate' + +type VisibleGate = { + p: Promise + r: boolean + s: () => void +} + +/* @__NO_SIDE_EFFECTS__ */ +function HydrationBoundary(props: { + g: VisibleGate + o?: () => void + children?: React.ReactNode +}) { + // Above the gate: a replay after `use` suspended can find the gate open and + // skip `use`, and only `use` leaves the replay's dispatcher, which rejects a + // hook the first attempt did not reach. + const { o } = props + React.useEffect(() => { + o?.() + }, [o]) + + if (!props.g.r) { + if (!reactUse) { + throw props.g.p + } + + reactUse(props.g.p) + } + + return props.children as React.JSX.Element +} + +/* @__NO_SIDE_EFFECTS__ */ +export function VisibleHydrate( + this: ReactHydrationStrategy, + props: HydrateProps, +): React.JSX.Element { + const strategy = this as ReactHydrationStrategy<'visible', true> + const prefetchStrategy = props.prefetch + const preload = (props as InternalHydrateProps).p + const markerRef = React.useRef(null) + const [gate] = React.useState(() => { + let resolvePromise!: () => void + const nextGate: VisibleGate = { + p: new Promise((resolve) => { + resolvePromise = resolve + }), + r: false, + s: () => { + nextGate.r = true + resolvePromise() + }, + } + if ( + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + isServer ?? + typeof window === 'undefined' + ) { + nextGate.s() + } + + return nextGate + }) + + React.useEffect(() => { + if (!preload || typeof prefetchStrategy === 'function') { + return + } + + return prefetchStrategy?._s?.({ + element: markerRef.current, + prefetch: preload, + }) + }, [prefetchStrategy, preload]) + + React.useEffect(() => { + if (gate.r) return + + return strategy._s?.({ + element: markerRef.current, + gate: gate as never, + }) + }, [gate, strategy]) + + return ( +
    + + + {props.children} + + +
    + ) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function visible( + options?: VisibleHydrationOptions, +): ReactHydrationStrategy<'visible', true> & + HydrationPrefetchStrategy<'visible'> { + const rootMargin = options?.rootMargin ?? '600px' + const threshold = options?.threshold ?? 0 + + return { + _s: ({ element, gate, prefetch }) => { + const callback = prefetch || (gate as never as VisibleGate).s + + if (!element) { + callback() + return + } + + const observer = new IntersectionObserver( + (entries) => { + if (!entries[0]!.isIntersecting) return + observer.disconnect() + callback() + }, + { rootMargin, threshold }, + ) + observer.observe(element) + return () => observer.disconnect() + }, + _h: VisibleHydrate, + } +} diff --git a/packages/react-start-client/src/index.tsx b/packages/react-start-client/src/index.tsx index 6c8a836f08..26e7195c39 100644 --- a/packages/react-start-client/src/index.tsx +++ b/packages/react-start-client/src/index.tsx @@ -1,3 +1,4 @@ +'use client' + export { StartClient } from './StartClient' -export { renderRsc } from './renderRSC' export { hydrateStart } from './hydrateStart' diff --git a/packages/react-start-client/src/renderRSC.tsx b/packages/react-start-client/src/renderRSC.tsx deleted file mode 100644 index 4832f074b6..0000000000 --- a/packages/react-start-client/src/renderRSC.tsx +++ /dev/null @@ -1,89 +0,0 @@ -// TODO: RSCs -import { isValidElement } from 'react' -import invariant from 'tiny-invariant' -import type React from 'react' - -export function renderRsc(input: any): React.JSX.Element { - if (isValidElement(input)) { - return input - } - - if (typeof input === 'object' && !input.state) { - input.state = { - status: 'pending', - promise: Promise.resolve() - .then(() => { - let element - - // We're in node - // TODO: RSCs - // if (reactDom.createFromNodeStream) { - // const stream = await import('node:stream') - - // let body: any = input - - // // Unwrap the response - // if (input instanceof Response) { - // body = input.body - // } - - // // Convert ReadableStream to NodeJS stream.Readable - // if (body instanceof ReadableStream) { - // body = stream.Readable.fromWeb(body as any) - // } - - // if (stream.Readable.isReadable(body)) { - // // body = copyStreamToRaw(body) - // } else if (input.text) { - // // create a readable stream by awaiting the text method - // body = new stream.Readable({ - // async read() { - // input.text().then((value: any) => { - // this.push(value) - // this.push(null) - // }) - // }, - // }) - // } else { - // console.error('input', input) - // throw new Error('Unexpected rsc input type 👆') - // } - - // element = await reactDom.createFromNodeStream(body) - // } else { - // // We're in the browser - // if (input.body instanceof ReadableStream) { - // input = input.body - // } - - // if (input instanceof ReadableStream) { - // element = await reactDom.createFromReadableStream(input) - // } - - // if (input instanceof Response) { - // // copy to the response body to cache the raw data - // element = await reactDom.createFromFetch(input) - // } - // } - - // return element - - invariant(false, 'renderRSC() is coming soon!') - }) - .then((element) => { - input.state.value = element - input.state.status = 'success' - }) - .catch((err) => { - input.state.status = 'error' - input.state.error = err - }), - } - } - - if (input.state.status === 'pending') { - throw input.state.promise - } - - return input.state.value -} diff --git a/packages/react-start-client/src/tests/Hydrate.test-d.tsx b/packages/react-start-client/src/tests/Hydrate.test-d.tsx new file mode 100644 index 0000000000..2e3726edfa --- /dev/null +++ b/packages/react-start-client/src/tests/Hydrate.test-d.tsx @@ -0,0 +1,147 @@ +import { expectTypeOf, test } from 'vitest' +import { visible } from '../hydration' +import { Hydrate } from '../Hydrate' +import type { + HydrateOptions, + HydrateProps, + HydrationPrefetchFunction, + HydrationPrefetchStrategy, + HydrationStrategy, +} from '../Hydrate' +import type { HydrationStrategy as CoreHydrationStrategy } from '@tanstack/start-client-core/hydration' +import type { ReactNode } from 'react' + +type CommonHydrateProps = { + fallback?: ReactNode + onHydrated?: () => void + children: ReactNode +} + +type SplitHydrateProps = CommonHydrateProps & { + when: HydrationStrategy | (() => HydrationStrategy) + prefetch?: never + split?: boolean +} + +type PrefetchHydrateProps = CommonHydrateProps & { + when: HydrationStrategy | (() => HydrationStrategy) + prefetch: HydrationPrefetchStrategy + split?: true +} + +type FunctionPrefetchHydrateProps = CommonHydrateProps & { + when: HydrationStrategy | (() => HydrationStrategy) + prefetch: HydrationPrefetchFunction + split?: boolean +} + +test('Hydrate component accepts the public HydrateProps type', () => { + expectTypeOf(Hydrate).toBeFunction() + expectTypeOf(Hydrate).parameter(0).branded.toEqualTypeOf() +}) + +test('HydrateOptions supports reusable spread props', () => { + const belowFoldProps = { + when: () => visible({ rootMargin: '800px' }), + } satisfies HydrateOptions + + expectTypeOf(belowFoldProps).toMatchTypeOf() + + const withFunctionPrefetch = { + when: visible(), + split: false, + prefetch: (ctx) => { + expectTypeOf(ctx.element).toEqualTypeOf() + expectTypeOf(ctx.signal).toEqualTypeOf() + expectTypeOf(ctx.preload).returns.toEqualTypeOf>() + expectTypeOf(ctx.waitFor).returns.toEqualTypeOf< + Promise<'prefetch' | 'hydrate' | 'abort'> + >() + }, + } satisfies HydrateOptions + + expectTypeOf(withFunctionPrefetch).toMatchTypeOf() +}) + +test('Hydrate props are exact for strategy and prefetch forms', () => { + expectTypeOf< + Extract + >().branded.toEqualTypeOf() + expectTypeOf< + Extract + >().branded.toEqualTypeOf() + expectTypeOf< + Extract + >().branded.toEqualTypeOf() +}) + +test('Hydrate requires a strategy', () => { + expectTypeOf<{ + when: HydrationStrategy + children: ReactNode + }>().toMatchTypeOf() + + expectTypeOf<{ + when: () => HydrationStrategy + children: ReactNode + }>().toMatchTypeOf() + + expectTypeOf<{ + children: ReactNode + }>().not.toMatchTypeOf() + + expectTypeOf<{ + when: () => true + children: ReactNode + }>().not.toMatchTypeOf() + + expectTypeOf<{ + when: false + children: ReactNode + }>().not.toMatchTypeOf() +}) + +test('Hydrate requires a framework-renderable strategy', () => { + expectTypeOf().not.toMatchTypeOf() + expectTypeOf>().toMatchTypeOf() + + expectTypeOf<{ + when: CoreHydrationStrategy + children: ReactNode + }>().not.toMatchTypeOf() +}) + +test('Hydrate enforces prefetch only with split boundaries', () => { + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchStrategy + children: ReactNode + }>().toMatchTypeOf() + + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchStrategy + split: true + children: ReactNode + }>().toMatchTypeOf() + + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchStrategy + split: false + children: ReactNode + }>().not.toMatchTypeOf() + + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchFunction + split: false + children: ReactNode + }>().toMatchTypeOf() + + expectTypeOf<{ + when: HydrationStrategy + prefetch: HydrationPrefetchFunction + children: ReactNode + }>().toMatchTypeOf() +}) diff --git a/packages/react-start-client/src/tests/Hydrate.test.tsx b/packages/react-start-client/src/tests/Hydrate.test.tsx new file mode 100644 index 0000000000..0e7abe502a --- /dev/null +++ b/packages/react-start-client/src/tests/Hydrate.test.tsx @@ -0,0 +1,763 @@ +import * as React from 'react' +import { renderToString } from 'react-dom/server' +import { hydrateRoot } from 'react-dom/client' +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { hydrateIdAttribute } from '@tanstack/start-client-core/hydration/constants' +import { Hydrate } from '../Hydrate' +import { + condition, + idle, + interaction, + load, + never, + visible, +} from '../hydration' +import type { HydrateProps, HydrationPrefetchStrategy } from '../Hydrate' + +const InternalHydrate = Hydrate as React.ComponentType< + HydrateProps & { p?: () => Promise; h?: string } +> + +const hydrateIdSelector = `[${hydrateIdAttribute}]` + +function getMarker() { + const marker = document.querySelector(hydrateIdSelector) + + if (!marker) { + throw new Error('Expected Hydrate marker to exist') + } + + return marker +} + +function InteractiveChild() { + const [count, setCount] = React.useState(0) + const [hydrated, setHydrated] = React.useState(false) + + React.useEffect(() => { + setHydrated(true) + }, []) + + return ( + + ) +} + +function NamedInteractiveChild(props: { id: string }) { + const [hydrated, setHydrated] = React.useState(false) + + React.useEffect(() => { + setHydrated(true) + }, []) + + return ( + + ) +} + +function createSuspendingChild() { + let resolve!: () => void + let resolved = false + const promise = new Promise((resolvePromise) => { + resolve = () => { + resolved = true + resolvePromise() + } + }) + + function SuspendingChild() { + if (!resolved) { + throw promise + } + + return
    child
    + } + + return { resolve, SuspendingChild } +} + +async function expectNoHydrationAfterDefaultIntentEvents() { + const marker = getMarker() + + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) + + await act(async () => { + fireEvent.pointerEnter(marker) + fireEvent.focusIn(marker) + fireEvent.pointerDown(marker) + fireEvent.click(marker) + await new Promise((resolve) => setTimeout(resolve, 20)) + }) + + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) +} + +async function fireIntent(event: () => void) { + await act(async () => { + event() + await Promise.resolve() + }) +} + +async function renderAsync(ui: React.ReactElement) { + await act(async () => { + render(ui) + await Promise.resolve() + }) +} + +async function hydrateFromServer(ui: React.ReactElement) { + vi.stubGlobal('window', undefined) + const html = renderToString(ui) + vi.unstubAllGlobals() + + const container = document.createElement('div') + document.body.append(container) + container.innerHTML = html + + let root!: ReturnType + await act(async () => { + root = hydrateRoot(container, ui) + await Promise.resolve() + }) + + return { container, html, root } +} + +async function unmountHydratedRoot( + root: ReturnType, + container: Element, +) { + await act(async () => { + root.unmount() + }) + container.remove() +} + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() +}) + +describe('Hydrate', () => { + it('uses a single custom interaction event instead of the default intent events', async () => { + const { container, html, root } = await hydrateFromServer( + fallback
    } + > + + , + ) + + try { + expect(html).toContain('data-testid="child"') + expect(html).not.toContain('data-testid="fallback"') + expect(screen.queryByTestId('fallback')).toBeNull() + await expectNoHydrationAfterDefaultIntentEvents() + + await fireIntent(() => + getMarker().dispatchEvent( + new MouseEvent('dblclick', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('uses every event in a custom interaction event list', async () => { + const { container, root } = await hydrateFromServer( + fallback
    } + > + + , + ) + + try { + expect(screen.queryByTestId('fallback')).toBeNull() + await expectNoHydrationAfterDefaultIntentEvents() + + await fireIntent(() => + getMarker().dispatchEvent( + new MouseEvent('contextmenu', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('omits never content when mounted after the app is already hydrated', async () => { + await renderAsync( + + + , + ) + + expect(screen.queryByTestId('child')).toBeNull() + }) + + it('shows fallback for a client-only mount while children suspend', async () => { + const { resolve, SuspendingChild } = createSuspendingChild() + + await renderAsync( + fallback
    } + > + + , + ) + + expect(screen.getByTestId('fallback').textContent).toBe('fallback') + expect(screen.queryByTestId('child')).toBeNull() + + await act(async () => { + resolve() + await Promise.resolve() + }) + + await screen.findByTestId('child') + expect(screen.queryByTestId('fallback')).toBeNull() + }) + + it('does not use fallback for an initial never boundary', async () => { + const { container, html, root } = await hydrateFromServer( + fallback
    } + > + + , + ) + + try { + expect(html).toContain('data-testid="child"') + expect(html).not.toContain('data-testid="fallback"') + expect(screen.queryByTestId('fallback')).toBeNull() + + fireEvent.click(screen.getByTestId('child')) + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) + expect(screen.getByTestId('child').textContent).toBe('0') + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('keeps repeated split boundaries independently gated', async () => { + const { container, root } = await hydrateFromServer( + <> + + + + + + + , + ) + + try { + const markers = container.querySelectorAll(hydrateIdSelector) + + expect(markers).toHaveLength(2) + expect(markers[0]!.getAttribute(hydrateIdAttribute)).not.toBe( + markers[1]!.getAttribute(hydrateIdAttribute), + ) + expect( + screen.getByTestId('child-one').getAttribute('data-hydrated'), + ).toBe('false') + expect( + screen.getByTestId('child-two').getAttribute('data-hydrated'), + ).toBe('false') + + await fireIntent(() => + markers[0]!.dispatchEvent( + new MouseEvent('click', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => + expect( + screen.getByTestId('child-one').getAttribute('data-hydrated'), + ).toBe('true'), + ) + expect( + screen.getByTestId('child-two').getAttribute('data-hydrated'), + ).toBe('false') + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('fires onHydrated once after the client hydration commit', async () => { + const onHydrated = vi.fn() + const app = ( + +
    child
    +
    + ) + + vi.stubGlobal('window', undefined) + const html = renderToString(app) + expect(html).toContain('child') + expect(onHydrated).not.toHaveBeenCalled() + vi.unstubAllGlobals() + + const container = document.createElement('div') + document.body.append(container) + container.innerHTML = html + + let root!: ReturnType + await act(async () => { + root = hydrateRoot(container, app) + }) + + await waitFor(() => expect(onHydrated).toHaveBeenCalledTimes(1)) + + fireEvent.click(screen.getByTestId('child')) + await new Promise((resolve) => setTimeout(resolve, 20)) + expect(onHydrated).toHaveBeenCalledTimes(1) + + await act(async () => { + root.unmount() + }) + container.remove() + }) + + it('prefetches split children without hydrating the boundary', async () => { + const preload = vi.fn(() => Promise.resolve()) + + const { container, root } = await hydrateFromServer( + + + , + ) + + try { + await waitFor(() => expect(preload).toHaveBeenCalledTimes(1)) + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) + + await fireIntent(() => + getMarker().dispatchEvent( + new MouseEvent('click', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + expect(preload).toHaveBeenCalledTimes(1) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('does not evaluate dynamic when callbacks on the server', async () => { + const when = vi.fn(() => interaction({ events: 'dblclick' })) + + vi.stubGlobal('window', undefined) + const html = renderToString( + + + , + ) + vi.unstubAllGlobals() + + expect(when).not.toHaveBeenCalled() + expect(html).toContain('data-ts-hydrate-when="dynamic"') + + const container = document.createElement('div') + document.body.append(container) + container.innerHTML = html + + let root!: ReturnType + try { + await act(async () => { + root = hydrateRoot( + container, + + + , + ) + await Promise.resolve() + }) + + expect(when).toHaveBeenCalled() + await expectNoHydrationAfterDefaultIntentEvents() + + await fireIntent(() => + getMarker().dispatchEvent( + new MouseEvent('dblclick', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('replays an interaction captured before the Hydrate component hydrates', async () => { + const when = () => interaction({ events: 'click' }) + + vi.stubGlobal('window', undefined) + const html = renderToString( + + + , + ) + vi.unstubAllGlobals() + + const container = document.createElement('div') + document.body.append(container) + container.innerHTML = html + + const button = container.querySelector('[data-testid="child"]') + if (!button) { + throw new Error('Expected server-rendered child button') + } + + button.dispatchEvent( + new MouseEvent('click', { bubbles: true, cancelable: true }), + ) + + let root!: ReturnType + try { + await act(async () => { + root = hydrateRoot( + container, + + + , + ) + await Promise.resolve() + }) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + await waitFor(() => + expect(screen.getByTestId('child').textContent).toBe('1'), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('blocks hydration on awaited procedural prefetch work', async () => { + const preload = vi.fn(() => Promise.resolve()) + let resolvePrefetch!: () => void + const prefetchBlocker = new Promise((resolve) => { + resolvePrefetch = resolve + }) + const waitReasons: Array = [] + const neverPrefetches = { + _t: 'idle', + _s: () => () => {}, + } as HydrationPrefetchStrategy<'idle'> + + const { container, root } = await hydrateFromServer( + { + waitReasons.push(await waitFor(neverPrefetches)) + await preload() + await prefetchBlocker + }} + p={preload} + > + + , + ) + + try { + await fireIntent(() => + getMarker().dispatchEvent( + new MouseEvent('click', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => expect(waitReasons).toEqual(['hydrate'])) + expect(preload).toHaveBeenCalledTimes(1) + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) + + await act(async () => { + resolvePrefetch() + await prefetchBlocker + await Promise.resolve() + }) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('hydrates when a condition strategy changes after the initial render', async () => { + function ConditionHarness() { + const [ready, setReady] = React.useState(false) + + return ( + <> + + + + + + ) + } + + const { container, root } = await hydrateFromServer() + + try { + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) + + await act(async () => { + fireEvent.click(screen.getByTestId('ready')) + await Promise.resolve() + }) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('does not block hydration on fire-and-forget procedural prefetch work', async () => { + let resolvePrefetch!: () => void + const prefetchBlocker = new Promise((resolve) => { + resolvePrefetch = resolve + }) + + const { container, root } = await hydrateFromServer( + { + void prefetchBlocker + }} + > + + , + ) + + try { + await fireIntent(() => + getMarker().dispatchEvent( + new MouseEvent('click', { bubbles: true, cancelable: true }), + ), + ) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + + await act(async () => { + resolvePrefetch() + await prefetchBlocker + }) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + it('aborts procedural prefetch when the boundary unmounts', async () => { + const signals: Array = [] + + const { container, root } = await hydrateFromServer( + { + signals.push(signal) + return new Promise(() => {}) + }} + > + + , + ) + + expect(signals).toHaveLength(1) + expect(signals[0]!.aborted).toBe(false) + + await unmountHydratedRoot(root, container) + expect(signals[0]!.aborted).toBe(true) + }) + + it('delegates nested interaction boundaries at runtime', async () => { + const { container, root } = await hydrateFromServer( + + + + + , + ) + + try { + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'false', + ) + + await fireIntent(() => { + fireEvent.click(screen.getByTestId('child')) + }) + + await waitFor(() => + expect(screen.getByTestId('child').getAttribute('data-hydrated')).toBe( + 'true', + ), + ) + } finally { + await unmountHydratedRoot(root, container) + } + }) + + // `visible()` reads its gate's mutable flag during render (`if (!g.r) use(g.p)`). + // React replays a component that suspended in `use` with its re-render + // dispatcher, and only `use` switches away from it: when the intersection + // arrives while React waits to replay, the flag is true, the replay skips + // `use`, and a hook after it would throw "Update hook called on initial render" + // (#467 in production). React would then discard the boundary's server HTML. + // Which task the intersection lands in is the browser's choice, so this runs + // it in each of the tasks around the boundary's first hydration attempt. + it('hydrates a visible boundary whichever task the intersection arrives in', async () => { + const actEnvironment = globalThis as { + IS_REACT_ACT_ENVIRONMENT?: boolean + } + const wasActEnvironment = actEnvironment.IS_REACT_ACT_ENVIRONMENT + actEnvironment.IS_REACT_ACT_ENVIRONMENT = false + const nextTask = () => new Promise((resolve) => setImmediate(resolve)) + const app = (onHydrated?: () => void) => ( + fallback

    } + onHydrated={onHydrated} + > +

    child

    +
    + ) + vi.stubGlobal('window', undefined) + const html = renderToString(app()) + vi.unstubAllGlobals() + const failed: Array<{ tasks: number; errors: Array }> = [] + try { + for (let tasks = 0; tasks < 12; tasks++) { + vi.stubGlobal( + 'IntersectionObserver', + class { + constructor(private notify: IntersectionObserverCallback) {} + observe() { + void (async () => { + for (let task = 0; task < tasks; task++) { + await nextTask() + } + this.notify( + [{ isIntersecting: true } as IntersectionObserverEntry], + this as unknown as IntersectionObserver, + ) + })() + } + disconnect() {} + }, + ) + const container = document.createElement('div') + document.body.append(container) + container.innerHTML = html + const errors: Array = [] + const hydrated = new Promise((resolve) => { + const root = hydrateRoot( + container, + app(() => { + resolve() + setImmediate(() => { + root.unmount() + container.remove() + }) + }), + { + onRecoverableError: (error) => { + errors.push(String((error as Error).cause ?? error)) + }, + }, + ) + }) + await hydrated + if (errors.length > 0) { + failed.push({ tasks, errors }) + } + } + } finally { + actEnvironment.IS_REACT_ACT_ENVIRONMENT = wasActEnvironment + } + expect(failed).toEqual([]) + }) +}) diff --git a/packages/react-start-client/src/tests/createServerFn.test-d.tsx b/packages/react-start-client/src/tests/createServerFn.test-d.tsx index e7d8c7be08..b020676956 100644 --- a/packages/react-start-client/src/tests/createServerFn.test-d.tsx +++ b/packages/react-start-client/src/tests/createServerFn.test-d.tsx @@ -24,7 +24,9 @@ test('createServerFn returns async array', () => { return result }) - expectTypeOf(serverFn()).toEqualTypeOf>>() + expectTypeOf>().toEqualTypeOf< + Promise> + >() }) test('createServerFn returns sync array', () => { @@ -33,7 +35,9 @@ test('createServerFn returns sync array', () => { return result }) - expectTypeOf(serverFn()).toEqualTypeOf>>() + expectTypeOf>().toEqualTypeOf< + Promise> + >() }) test('createServerFn returns async union', () => { @@ -42,7 +46,9 @@ test('createServerFn returns async union', () => { return result }) - expectTypeOf(serverFn()).toEqualTypeOf>() + expectTypeOf>().toEqualTypeOf< + Promise + >() }) test('createServerFn returns sync union', () => { @@ -51,5 +57,7 @@ test('createServerFn returns sync union', () => { return result }) - expectTypeOf(serverFn()).toEqualTypeOf>() + expectTypeOf>().toEqualTypeOf< + Promise + >() }) diff --git a/packages/react-start-client/src/tests/hydrateStart.test.ts b/packages/react-start-client/src/tests/hydrateStart.test.ts new file mode 100644 index 0000000000..2d34400009 --- /dev/null +++ b/packages/react-start-client/src/tests/hydrateStart.test.ts @@ -0,0 +1,33 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { hydrateStart } from '../hydrateStart' + +const coreHydrateStart = vi.hoisted(() => vi.fn()) + +vi.mock('@tanstack/start-client-core/client', () => ({ + hydrateStart: coreHydrateStart, +})) + +afterEach(() => { + delete window.$_TSR + coreHydrateStart.mockReset() +}) + +test('signals streaming cleanup after hydration succeeds', async () => { + const router = {} + coreHydrateStart.mockResolvedValue(router) + const hydrated = vi.fn() + window.$_TSR = { h: hydrated } as any + + await expect(hydrateStart()).resolves.toBe(router) + expect(hydrated).toHaveBeenCalledTimes(1) +}) + +test('signals streaming cleanup without hiding a hydration failure', async () => { + const error = new Error('hydration failed') + coreHydrateStart.mockRejectedValue(error) + const hydrated = vi.fn() + window.$_TSR = { h: hydrated } as any + + await expect(hydrateStart()).rejects.toBe(error) + expect(hydrated).toHaveBeenCalledTimes(1) +}) diff --git a/packages/react-start-client/tsconfig.build.json b/packages/react-start-client/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/react-start-client/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/react-start-client/tsconfig.json b/packages/react-start-client/tsconfig.json index 51dda9abf2..1ffe6f0c62 100644 --- a/packages/react-start-client/tsconfig.json +++ b/packages/react-start-client/tsconfig.json @@ -2,7 +2,8 @@ "extends": "../../tsconfig.json", "compilerOptions": { "jsx": "react-jsx", - "module": "esnext" + "module": "esnext", + "types": ["node"] }, "include": ["src", "vite.config.ts"] } diff --git a/packages/react-start-client/vite.config.ts b/packages/react-start-client/vite.config.ts index da4238fe1e..19e0d79d19 100644 --- a/packages/react-start-client/vite.config.ts +++ b/packages/react-start-client/vite.config.ts @@ -1,5 +1,5 @@ import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' import react from '@vitejs/plugin-react' import packageJson from './package.json' import type { ViteUserConfig } from 'vitest/config' @@ -18,8 +18,9 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ + tsconfigPath: './tsconfig.build.json', srcDir: './src', - entry: './src/index.tsx', + entry: ['./src/index.tsx', './src/Hydrate.tsx', './src/hydration.ts'], cjs: false, }), ) diff --git a/packages/react-start-rsc/CHANGELOG.md b/packages/react-start-rsc/CHANGELOG.md new file mode 100644 index 0000000000..fae6bcabee --- /dev/null +++ b/packages/react-start-rsc/CHANGELOG.md @@ -0,0 +1,1114 @@ +# @tanstack/react-start-rsc + +## 0.1.67 + +### Patch Changes + +- Updated dependencies [[`3f22686`](https://github.com/TanStack/router/commit/3f226869e0af211ff7f1de5d7343e43462dbb101), [`559c7de`](https://github.com/TanStack/router/commit/559c7ded6e2a6eeda3f91c80d8c03f4cfeb9a206)]: + - @tanstack/start-plugin-core@1.171.57 + +## 0.1.66 + +### Patch Changes + +- Updated dependencies [[`446ce1b`](https://github.com/TanStack/router/commit/446ce1b30650d85f1fc78f2d1ee42712e40b75c6), [`ff157f0`](https://github.com/TanStack/router/commit/ff157f0079982e90d62be7fdeecfb77e4fdcec69), [`01fab5a`](https://github.com/TanStack/router/commit/01fab5a6c8aed70d61d82c64bc344cbac66c240c), [`c5320d7`](https://github.com/TanStack/router/commit/c5320d7ca23eca82d720ac5629d2bad5cf7d9b02), [`545a8d3`](https://github.com/TanStack/router/commit/545a8d3790989ca502153c3292c6b1e8063257f4), [`da8c28c`](https://github.com/TanStack/router/commit/da8c28c498230a5730ce75b2693baeeb3ef68ac1)]: + - @tanstack/router-utils@1.163.0 + - @tanstack/start-plugin-core@1.171.56 + +## 0.1.65 + +### Patch Changes + +- Updated dependencies [[`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c), [`689a7c5`](https://github.com/TanStack/router/commit/689a7c5419de68bce0aaaef72b9a36f115ea1398), [`ed55775`](https://github.com/TanStack/router/commit/ed5577593a749b8c7193cc7b5d945fd084bfac2f), [`63a886d`](https://github.com/TanStack/router/commit/63a886da9040c4b039ea3bf5b3a841771375cddb), [`d9b07e8`](https://github.com/TanStack/router/commit/d9b07e8d3b724cdbfac0aa2fba4c1f7a3a241100)]: + - @tanstack/react-router@1.170.46 + - @tanstack/router-core@1.171.39 + - @tanstack/start-client-core@1.170.39 + - @tanstack/start-plugin-core@1.171.55 + - @tanstack/start-storage-context@1.167.41 + +## 0.1.64 + +### Patch Changes + +- Updated dependencies [[`18154b1`](https://github.com/TanStack/router/commit/18154b1c45454a70aa77e9d6d27c8a6e0733d031)]: + - @tanstack/router-core@1.171.38 + - @tanstack/react-router@1.170.45 + - @tanstack/start-client-core@1.170.38 + - @tanstack/start-plugin-core@1.171.54 + - @tanstack/start-storage-context@1.167.40 + +## 0.1.63 + +### Patch Changes + +- Updated dependencies [[`fdc10fa`](https://github.com/TanStack/router/commit/fdc10fa13fbac758615f9a3d37075088d1cc1e1f), [`923d98b`](https://github.com/TanStack/router/commit/923d98b18b6cd90b6219591e20e86115dc61048e)]: + - @tanstack/start-plugin-core@1.171.53 + - @tanstack/router-utils@1.162.4 + +## 0.1.62 + +### Patch Changes + +- Updated dependencies [[`740b0ce`](https://github.com/TanStack/router/commit/740b0ce17737d1f7398740136acdbeabe80df7d8), [`d6ba115`](https://github.com/TanStack/router/commit/d6ba115d5751c75e20943f0062577cf17b446d82)]: + - @tanstack/start-storage-context@1.167.39 + - @tanstack/router-core@1.171.37 + - @tanstack/start-plugin-core@1.171.52 + - @tanstack/start-client-core@1.170.37 + - @tanstack/react-router@1.170.44 + +## 0.1.61 + +### Patch Changes + +- [#8696](https://github.com/TanStack/router/pull/8696) [`f243c61`](https://github.com/TanStack/router/commit/f243c61e95dae64fe04da4499c0c4ec44f26abae) - Require Vite 8 for Vite builds. Vite 7 is no longer supported. + +- Updated dependencies [[`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`550f478`](https://github.com/TanStack/router/commit/550f47881070c0558a87e1acce7f38fbc85b9549), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`f3d7ee3`](https://github.com/TanStack/router/commit/f3d7ee3374c660e0fe82a03ac580a90ed2e2fa98), [`4104b8e`](https://github.com/TanStack/router/commit/4104b8ef11498706b5059c5a915f2ae47ffbc5ba), [`f243c61`](https://github.com/TanStack/router/commit/f243c61e95dae64fe04da4499c0c4ec44f26abae), [`19524cc`](https://github.com/TanStack/router/commit/19524ccdd75870ce1db2f324518eeb3f23cc0f97)]: + - @tanstack/router-core@1.171.36 + - @tanstack/start-storage-context@1.167.38 + - @tanstack/start-client-core@1.170.36 + - @tanstack/start-plugin-core@1.171.51 + - @tanstack/react-router@1.170.43 + +## 0.1.60 + +### Patch Changes + +- Updated dependencies [[`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`2413cc0`](https://github.com/TanStack/router/commit/2413cc009826fba4f97b166a35a8a50a4a8fe4bb), [`4191640`](https://github.com/TanStack/router/commit/41916400b93fdb62189722266ed1d77ba9c26be9), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`d35aab4`](https://github.com/TanStack/router/commit/d35aab425b07b46e222a507c0f0239644669757b), [`663282b`](https://github.com/TanStack/router/commit/663282b0ebbc494aee3595ed95867ee29d01938e)]: + - @tanstack/router-core@1.171.35 + - @tanstack/react-router@1.170.42 + - @tanstack/start-plugin-core@1.171.50 + - @tanstack/start-client-core@1.170.35 + - @tanstack/start-storage-context@1.167.37 + +## 0.1.59 + +### Patch Changes + +- Updated dependencies [[`60b8ad1`](https://github.com/TanStack/router/commit/60b8ad1ad00812bf966a8eeee6be238c37ddad74), [`41ebd28`](https://github.com/TanStack/router/commit/41ebd288677beacb8eb56953f5f8c26e9d33313e), [`614bc27`](https://github.com/TanStack/router/commit/614bc27034c8ec98747bf305ed41d4a619640949), [`05223c2`](https://github.com/TanStack/router/commit/05223c2ada4d48af4b3881f10e3b6261898b2d40), [`d521abd`](https://github.com/TanStack/router/commit/d521abd71c69f1ff010bb3def4d417cb5fa058cb), [`ff66a03`](https://github.com/TanStack/router/commit/ff66a03df4816f44a48a4a37189fc4021b1c8480), [`863c8a7`](https://github.com/TanStack/router/commit/863c8a736b96746c56278a16c50554356f5523d1)]: + - @tanstack/react-router@1.170.41 + - @tanstack/start-plugin-core@1.171.49 + - @tanstack/router-core@1.171.34 + - @tanstack/start-client-core@1.170.34 + - @tanstack/start-storage-context@1.167.36 + +## 0.1.58 + +### Patch Changes + +- Updated dependencies [[`f5ffd38`](https://github.com/TanStack/router/commit/f5ffd3884ba26778a2a8ce53b379a5bded231676), [`488d046`](https://github.com/TanStack/router/commit/488d046a907d330429e2c807ef95326dad87480f), [`0c1b5e3`](https://github.com/TanStack/router/commit/0c1b5e38de71b7e81bbf1fd81c73ee0cd68ffe47), [`3cdd1af`](https://github.com/TanStack/router/commit/3cdd1af04b3e2d6f777797ee7bddf285318dd9d2), [`76a7c0b`](https://github.com/TanStack/router/commit/76a7c0bfadb42d5f7fe7b9e1748acc7333178c91)]: + - @tanstack/react-router@1.170.40 + - @tanstack/router-core@1.171.33 + - @tanstack/start-client-core@1.170.33 + - @tanstack/start-plugin-core@1.171.48 + - @tanstack/start-storage-context@1.167.35 + +## 0.1.57 + +### Patch Changes + +- Updated dependencies [[`73bfc15`](https://github.com/TanStack/router/commit/73bfc153eef460e9b670556215a5adb2b5cbf542)]: + - @tanstack/react-router@1.170.39 + +## 0.1.56 + +### Patch Changes + +- Updated dependencies [[`222300b`](https://github.com/TanStack/router/commit/222300b82fe6f2a5e7e7f460ae21a2e35c6230d7)]: + - @tanstack/start-plugin-core@1.171.47 + +## 0.1.55 + +### Patch Changes + +- Updated dependencies [[`cecae54`](https://github.com/TanStack/router/commit/cecae5440b8edaea77c5448fe3d74bbd20fe10a4), [`0103578`](https://github.com/TanStack/router/commit/01035782e53af9b929c784b94ddd64b95efb89c7), [`ce10dcd`](https://github.com/TanStack/router/commit/ce10dcd4d9d3d23738744e453205aad5c6dbd716), [`84936cc`](https://github.com/TanStack/router/commit/84936cc04530bba11059c57b293a794922bbc5aa), [`bbd2336`](https://github.com/TanStack/router/commit/bbd2336b8446de3f7dd85070895e7cf43980183e)]: + - @tanstack/router-core@1.171.32 + - @tanstack/react-router@1.170.38 + - @tanstack/start-client-core@1.170.32 + - @tanstack/start-plugin-core@1.171.46 + - @tanstack/start-storage-context@1.167.34 + +## 0.1.54 + +### Patch Changes + +- Updated dependencies [[`bc80866`](https://github.com/TanStack/router/commit/bc80866f6d6eb3e6f152ee3682eb783c96403e83), [`e561fa1`](https://github.com/TanStack/router/commit/e561fa1d7118e3d29267cc3b6ce1130d6581f387), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a1c8d1a`](https://github.com/TanStack/router/commit/a1c8d1aa759c227eae9601a030321ac4c53c24bd), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a0b2ad9`](https://github.com/TanStack/router/commit/a0b2ad99aee64af08d16b0e4ff26b3ba42a99f0a), [`8e164d2`](https://github.com/TanStack/router/commit/8e164d28f9e9eb1a7301109230d7ece9817492a8), [`1ca361b`](https://github.com/TanStack/router/commit/1ca361ba52a627d2f76ab33323bd83d1d0aa65a3)]: + - @tanstack/router-core@1.171.31 + - @tanstack/react-router@1.170.37 + - @tanstack/start-plugin-core@1.171.45 + - @tanstack/start-client-core@1.170.31 + - @tanstack/start-storage-context@1.167.33 + +## 0.1.53 + +### Patch Changes + +- Updated dependencies [[`ab99818`](https://github.com/TanStack/router/commit/ab99818225835a1553a9f3513cd2093ff1b257be)]: + - @tanstack/start-plugin-core@1.171.44 + +## 0.1.52 + +### Patch Changes + +- Updated dependencies [[`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776), [`6cfb1e8`](https://github.com/TanStack/router/commit/6cfb1e8b564be282584765352250bf61747895ed), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8), [`873c830`](https://github.com/TanStack/router/commit/873c830ccb2610a864ee697250e10fcc99772ffa), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`f151ab0`](https://github.com/TanStack/router/commit/f151ab018eede64ae849b77e68f3cdf31cb95cc5), [`bc57fa3`](https://github.com/TanStack/router/commit/bc57fa3f12450cf34c731450947c7c8f1ea05e58), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9448caa`](https://github.com/TanStack/router/commit/9448caa03a89076b9770631c356c0cc502802c09), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef)]: + - @tanstack/router-core@1.171.30 + - @tanstack/react-router@1.170.36 + - @tanstack/start-client-core@1.170.30 + - @tanstack/start-plugin-core@1.171.43 + - @tanstack/start-storage-context@1.167.32 + +## 0.1.51 + +### Patch Changes + +- Updated dependencies [[`8c43c71`](https://github.com/TanStack/router/commit/8c43c712523fc63dc3a814f3a19617e270ce8ed1)]: + - @tanstack/react-router@1.170.35 + - @tanstack/start-plugin-core@1.171.42 + +## 0.1.50 + +### Patch Changes + +- Updated dependencies [[`f9836f1`](https://github.com/TanStack/router/commit/f9836f16f0e25b0a8495f5e01e3f303b1cbc8725), [`aee42c6`](https://github.com/TanStack/router/commit/aee42c6b641d8e919bfed9e0f04bb1b72092f3a6), [`49bcd4d`](https://github.com/TanStack/router/commit/49bcd4db743dba4a783d5533a42a0f97a5721292), [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8), [`9aec5a7`](https://github.com/TanStack/router/commit/9aec5a7012c47e83ec23bb4763494b72a5e68bfc), [`9871c06`](https://github.com/TanStack/router/commit/9871c0625806001d6bf373524821a00303438a91), [`919c397`](https://github.com/TanStack/router/commit/919c3971493374cccc963e75b9b2a4e98ebf878a), [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9)]: + - @tanstack/router-core@1.171.29 + - @tanstack/react-router@1.170.34 + - @tanstack/router-utils@1.162.3 + - @tanstack/start-plugin-core@1.171.41 + - @tanstack/start-client-core@1.170.29 + - @tanstack/start-storage-context@1.167.31 + +## 0.1.49 + +### Patch Changes + +- Updated dependencies [[`edf0e16`](https://github.com/TanStack/router/commit/edf0e16ebfe82ec6e8f68f403a1fda8de9e28889), [`2f20c00`](https://github.com/TanStack/router/commit/2f20c00224c5ba63467551914e0c37012588c4c2), [`28a5e45`](https://github.com/TanStack/router/commit/28a5e4504e4ea5cb1480667a4bea2588a53e110f), [`08eff50`](https://github.com/TanStack/router/commit/08eff50c447a154a3373909009e9e4375cea17ce), [`216c0c4`](https://github.com/TanStack/router/commit/216c0c48036fd1a33163b70dcabfed2b893808b0), [`2f91503`](https://github.com/TanStack/router/commit/2f9150309bc472f4a75cbe98adcdb50c76b12c7a), [`f0b5eda`](https://github.com/TanStack/router/commit/f0b5eda544606686a8a8d675a686ca1366428b96), [`37877da`](https://github.com/TanStack/router/commit/37877da166fe4ce055c7b85e138b6681ebd7e8b4), [`50eafca`](https://github.com/TanStack/router/commit/50eafcaebbbedb6fde3b2816de7a0ace8cde4832), [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b), [`0caf6b9`](https://github.com/TanStack/router/commit/0caf6b9a2b7e14b0b146c74cc27cb05c19d700a5), [`ee28348`](https://github.com/TanStack/router/commit/ee283480dfa51150a2e0b096a6eff94a89ff8b3f), [`cf166d1`](https://github.com/TanStack/router/commit/cf166d160e6397007a979bfc7065b45ff69ea543), [`c18e690`](https://github.com/TanStack/router/commit/c18e69081475a7c98f9d40bd0fe6da78ccb84598)]: + - @tanstack/router-core@1.171.28 + - @tanstack/react-router@1.170.33 + - @tanstack/start-plugin-core@1.171.40 + - @tanstack/start-client-core@1.170.28 + - @tanstack/start-storage-context@1.167.30 + +## 0.1.48 + +### Patch Changes + +- Updated dependencies [[`fa65287`](https://github.com/TanStack/router/commit/fa652872812c9433ba8b9d9a285e51b535e7367c), [`cb281d7`](https://github.com/TanStack/router/commit/cb281d70c1f5fe780f9d07bc500ea3a284a4e04b), [`a0041bb`](https://github.com/TanStack/router/commit/a0041bb36e700b3263b894e4d1573d924383b56b)]: + - @tanstack/router-core@1.171.27 + - @tanstack/react-router@1.170.32 + - @tanstack/start-plugin-core@1.171.39 + - @tanstack/start-client-core@1.170.27 + - @tanstack/start-storage-context@1.167.29 + +## 0.1.47 + +### Patch Changes + +- Updated dependencies [[`3e016ac`](https://github.com/TanStack/router/commit/3e016ac84ffec8119f0c25cfdd1fb17e5292bd34)]: + - @tanstack/router-core@1.171.26 + - @tanstack/react-router@1.170.31 + - @tanstack/start-client-core@1.170.26 + - @tanstack/start-plugin-core@1.171.38 + - @tanstack/start-storage-context@1.167.28 + +## 0.1.46 + +### Patch Changes + +- Updated dependencies [[`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175), [`63d2cc9`](https://github.com/TanStack/router/commit/63d2cc9155ff5374112f7d067d0b278bafeb8486), [`f75cada`](https://github.com/TanStack/router/commit/f75cada01707e51fb9650dd301bc04f8b2265a2a)]: + - @tanstack/react-router@1.170.30 + - @tanstack/router-core@1.171.25 + - @tanstack/start-client-core@1.170.25 + - @tanstack/start-plugin-core@1.171.37 + - @tanstack/start-storage-context@1.167.27 + +## 0.1.45 + +### Patch Changes + +- Updated dependencies [[`4c89b15`](https://github.com/TanStack/router/commit/4c89b15dd2b46491ee5e57985559bae8e31d62c2), [`cf6ab17`](https://github.com/TanStack/router/commit/cf6ab178b39e7628bf784759f384e0f4230e6d9e), [`0fdf9ff`](https://github.com/TanStack/router/commit/0fdf9ff16fc532de9fc131d18df167ebd8038720), [`bdaf73a`](https://github.com/TanStack/router/commit/bdaf73a4063ee2b02e3c9cc105ad10ce82a5a0ff)]: + - @tanstack/router-core@1.171.24 + - @tanstack/react-router@1.170.29 + - @tanstack/start-client-core@1.170.24 + - @tanstack/start-plugin-core@1.171.36 + - @tanstack/start-storage-context@1.167.26 + +## 0.1.44 + +### Patch Changes + +- Updated dependencies [[`0c25a7b`](https://github.com/TanStack/router/commit/0c25a7b43b5331ee6ebf94d50e9793002783adab), [`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90)]: + - @tanstack/react-router@1.170.28 + - @tanstack/router-core@1.171.23 + - @tanstack/start-client-core@1.170.23 + - @tanstack/start-plugin-core@1.171.35 + - @tanstack/start-storage-context@1.167.25 + +## 0.1.43 + +### Patch Changes + +- Updated dependencies [[`b0817f5`](https://github.com/TanStack/router/commit/b0817f50cc639ae50b6c30cd11c5adbf7eed028c)]: + - @tanstack/react-router@1.170.27 + +## 0.1.42 + +### Patch Changes + +- Updated dependencies [[`7e93431`](https://github.com/TanStack/router/commit/7e93431ae9ff58c91c3c5ca10ffcb8414c1d0b13), [`f500760`](https://github.com/TanStack/router/commit/f5007607d62e932b8df19de866cdc6bddcff8db3), [`1aafca9`](https://github.com/TanStack/router/commit/1aafca9b45d24f8f0dba78e716fc9582346c6ca1), [`aa10b65`](https://github.com/TanStack/router/commit/aa10b6589eeda215f5a60ea0af95a3101d8c414e)]: + - @tanstack/router-core@1.171.22 + - @tanstack/react-router@1.170.26 + - @tanstack/start-client-core@1.170.22 + - @tanstack/start-plugin-core@1.171.34 + - @tanstack/start-storage-context@1.167.24 + +## 0.1.41 + +### Patch Changes + +- Updated dependencies [[`51138a8`](https://github.com/TanStack/router/commit/51138a824cea053738f125c4c95073bd6286ff05)]: + - @tanstack/router-core@1.171.21 + - @tanstack/react-router@1.170.25 + - @tanstack/start-client-core@1.170.21 + - @tanstack/start-plugin-core@1.171.33 + - @tanstack/start-storage-context@1.167.23 + +## 0.1.40 + +### Patch Changes + +- Updated dependencies [[`44a8c3e`](https://github.com/TanStack/router/commit/44a8c3e1d2af305064b2363d97fc7847c6f1a246), [`c59788c`](https://github.com/TanStack/router/commit/c59788ca20f2d2e7f264a859ebe01b7646ba3154), [`5253e70`](https://github.com/TanStack/router/commit/5253e70db2083d68a788fb7c9a043bb0c5518f2a)]: + - @tanstack/router-core@1.171.20 + - @tanstack/start-client-core@1.170.20 + - @tanstack/react-router@1.170.24 + - @tanstack/start-plugin-core@1.171.32 + - @tanstack/start-storage-context@1.167.22 + +## 0.1.39 + +### Patch Changes + +- Updated dependencies [[`2fbc99f`](https://github.com/TanStack/router/commit/2fbc99f2c262b057cb957e6ebba1ee073c655186), [`95dec51`](https://github.com/TanStack/router/commit/95dec51018d01483949c6f1fe3094b019ccf3b4f), [`6bede65`](https://github.com/TanStack/router/commit/6bede65d7074dcd83455151b66b4574268bc782c)]: + - @tanstack/start-client-core@1.170.19 + - @tanstack/react-router@1.170.23 + - @tanstack/start-plugin-core@1.171.31 + +## 0.1.38 + +### Patch Changes + +- Updated dependencies [[`ea3a665`](https://github.com/TanStack/router/commit/ea3a665d81cbb5074c2d77ec953255ab534e7db9)]: + - @tanstack/react-router@1.170.22 + - @tanstack/router-core@1.171.19 + - @tanstack/start-client-core@1.170.18 + - @tanstack/start-plugin-core@1.171.30 + - @tanstack/start-storage-context@1.167.21 + +## 0.1.37 + +### Patch Changes + +- Updated dependencies [[`697ebb6`](https://github.com/TanStack/router/commit/697ebb6ddbd433d052b6b4707938a5c595865d58), [`2435885`](https://github.com/TanStack/router/commit/2435885fa8b5e31c8c4b74d93920919f27316ebf), [`84db4a8`](https://github.com/TanStack/router/commit/84db4a842311df3f7e58073f6f12aaf371aeb5c7), [`9cac62a`](https://github.com/TanStack/router/commit/9cac62a5c7f99ef070991ea6f1fa7e42c746d46b), [`86bf510`](https://github.com/TanStack/router/commit/86bf510c2923afb76804223bd04afc2a809b33e7), [`6aefb33`](https://github.com/TanStack/router/commit/6aefb3392595a07a93f89301d7b5e3558ff9190c)]: + - @tanstack/react-router@1.170.21 + - @tanstack/router-core@1.171.18 + - @tanstack/start-client-core@1.170.17 + - @tanstack/start-plugin-core@1.171.29 + - @tanstack/start-storage-context@1.167.20 + +## 0.1.36 + +### Patch Changes + +- Updated dependencies [[`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5)]: + - @tanstack/router-core@1.171.17 + - @tanstack/start-client-core@1.170.16 + - @tanstack/start-plugin-core@1.171.28 + - @tanstack/react-router@1.170.20 + - @tanstack/start-storage-context@1.167.19 + +## 0.1.35 + +### Patch Changes + +- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: + - @tanstack/router-core@1.171.16 + - @tanstack/react-router@1.170.19 + - @tanstack/start-client-core@1.170.15 + - @tanstack/start-plugin-core@1.171.27 + - @tanstack/start-storage-context@1.167.18 + +## 0.1.34 + +### Patch Changes + +- [#7944](https://github.com/TanStack/router/pull/7944) [`65f7b7f`](https://github.com/TanStack/router/commit/65f7b7f791272f2ea581a1fe0fcd43183bc01162) - Read request cancellation from the Start storage context so RSC helpers do not pull the Start server barrel into the RSC module graph. + +- Updated dependencies [[`65f7b7f`](https://github.com/TanStack/router/commit/65f7b7f791272f2ea581a1fe0fcd43183bc01162)]: + - @tanstack/start-plugin-core@1.171.26 + +## 0.1.33 + +### Patch Changes + +- Updated dependencies [[`7592555`](https://github.com/TanStack/router/commit/7592555b86c968efbc8c817ac0cf6fdae60aabe0)]: + - @tanstack/start-plugin-core@1.171.25 + +## 0.1.32 + +### Patch Changes + +- [#7900](https://github.com/TanStack/router/pull/7900) [`fc83c03`](https://github.com/TanStack/router/commit/fc83c0383f956c3ca02e5e027666c917d7e8b07a) - Raise the `@vitejs/plugin-rsc` peer range to `>=0.5.30`. Versions in `0.5.20 - 0.5.29` suppress client HMR for a route component co-located with a `createServerFn`, fixed upstream in `@vitejs/plugin-rsc@0.5.30`. + +## 0.1.31 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.171.24 + +## 0.1.30 + +### Patch Changes + +- Updated dependencies [[`ffdd64e`](https://github.com/TanStack/router/commit/ffdd64e842acacbc9d368a4803a9e474e9f0c0ff)]: + - @tanstack/start-plugin-core@1.171.23 + +## 0.1.29 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.171.22 + +## 0.1.28 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.171.21 + +## 0.1.27 + +### Patch Changes + +- Updated dependencies [[`e2dd204`](https://github.com/TanStack/router/commit/e2dd2049cb42eb219d3b447b8605066d19d9c1fa)]: + - @tanstack/router-core@1.171.15 + - @tanstack/react-router@1.170.18 + - @tanstack/start-client-core@1.170.14 + - @tanstack/start-plugin-core@1.171.20 + - @tanstack/start-server-core@1.169.17 + - @tanstack/start-storage-context@1.167.17 + +## 0.1.26 + +### Patch Changes + +- Updated dependencies [[`9809a06`](https://github.com/TanStack/router/commit/9809a0619d4ed3fe8c2a393af5b9eca4b6c7695b), [`ba52d2b`](https://github.com/TanStack/router/commit/ba52d2b8f9e95d6becd1be14c020b35f3231e02c)]: + - @tanstack/router-core@1.171.14 + - @tanstack/start-client-core@1.170.13 + - @tanstack/react-router@1.170.17 + - @tanstack/start-plugin-core@1.171.19 + - @tanstack/start-server-core@1.169.16 + - @tanstack/start-storage-context@1.167.16 + +## 0.1.25 + +### Patch Changes + +- Updated dependencies [[`52db703`](https://github.com/TanStack/router/commit/52db7034fd83b17cc45da9ba775ec253f2a9a149), [`4a93cff`](https://github.com/TanStack/router/commit/4a93cffffca34702e419bc47db827f964fd0cb65), [`96eca43`](https://github.com/TanStack/router/commit/96eca43ab8ee21917a8075521bef6dcf15fc7a43), [`f046b06`](https://github.com/TanStack/router/commit/f046b064d32222cad0b7ea061311ca9a474f5990), [`e499164`](https://github.com/TanStack/router/commit/e499164c722841271af4aa2215483476bdb94c94), [`689d88e`](https://github.com/TanStack/router/commit/689d88e04c48ec76a18453ab8b82d8d58f2668b6), [`689c5ab`](https://github.com/TanStack/router/commit/689c5ab32e9bb18d90a5a94c33237b0e418df3e3)]: + - @tanstack/react-router@1.170.16 + - @tanstack/start-server-core@1.169.15 + - @tanstack/start-plugin-core@1.171.18 + +## 0.1.24 + +### Patch Changes + +- Updated dependencies [[`9bebf8d`](https://github.com/TanStack/router/commit/9bebf8dc9f2bf74b680c065a5aa63d03b9622825)]: + - @tanstack/start-client-core@1.170.12 + - @tanstack/start-plugin-core@1.171.17 + - @tanstack/start-server-core@1.169.14 + +## 0.1.23 + +### Patch Changes + +- Updated dependencies [[`776d8ef`](https://github.com/TanStack/router/commit/776d8ef283e5bd9ffe97d43bc3a7f58064cd7e03)]: + - @tanstack/router-core@1.171.13 + - @tanstack/react-router@1.170.15 + - @tanstack/start-client-core@1.170.11 + - @tanstack/start-plugin-core@1.171.16 + - @tanstack/start-server-core@1.169.13 + - @tanstack/start-storage-context@1.167.15 + +## 0.1.22 + +### Patch Changes + +- Updated dependencies [[`df1076c`](https://github.com/TanStack/router/commit/df1076c03ae5a51ab384bebd4d6afda20fb6f107)]: + - @tanstack/router-core@1.171.12 + - @tanstack/react-router@1.170.14 + - @tanstack/start-client-core@1.170.10 + - @tanstack/start-plugin-core@1.171.15 + - @tanstack/start-server-core@1.169.12 + - @tanstack/start-storage-context@1.167.14 + +## 0.1.21 + +### Patch Changes + +- Updated dependencies [[`ac10815`](https://github.com/TanStack/router/commit/ac10815f387d25b15163ff711b4049e8f8482d01)]: + - @tanstack/router-core@1.171.11 + - @tanstack/react-router@1.170.13 + - @tanstack/start-client-core@1.170.9 + - @tanstack/start-plugin-core@1.171.14 + - @tanstack/start-server-core@1.169.11 + - @tanstack/start-storage-context@1.167.13 + +## 0.1.20 + +### Patch Changes + +- Updated dependencies [[`301f6ba`](https://github.com/TanStack/router/commit/301f6ba4599386edd6fb3b8423938c48eedb501f), [`2cca73c`](https://github.com/TanStack/router/commit/2cca73c92262ffd96dac4e283c9f69fb37f4b43a), [`7a83e67`](https://github.com/TanStack/router/commit/7a83e67e6596fbef21cb0a88a7127f5935bed2ba), [`76b3d3b`](https://github.com/TanStack/router/commit/76b3d3b24522bd3d1d216674c441252c9b8f184c)]: + - @tanstack/start-plugin-core@1.171.13 + - @tanstack/router-utils@1.162.2 + - @tanstack/router-core@1.171.10 + - @tanstack/react-router@1.170.12 + - @tanstack/start-client-core@1.170.8 + - @tanstack/start-server-core@1.169.10 + - @tanstack/start-storage-context@1.167.12 + +## 0.1.19 + +### Patch Changes + +- Updated dependencies [[`8091918`](https://github.com/TanStack/router/commit/80919186cbdd0deb948b46fe328881a14a08f414)]: + - @tanstack/start-plugin-core@1.171.12 + +## 0.1.18 + +### Patch Changes + +- Updated dependencies [[`b4cd5af`](https://github.com/TanStack/router/commit/b4cd5af8d0f9d4aaa2d29095e6a261b9181bc778)]: + - @tanstack/router-core@1.171.9 + - @tanstack/react-router@1.170.11 + - @tanstack/react-start-server@1.167.14 + - @tanstack/start-client-core@1.170.7 + - @tanstack/start-plugin-core@1.171.11 + - @tanstack/start-server-core@1.169.9 + - @tanstack/start-storage-context@1.167.11 + +## 0.1.17 + +### Patch Changes + +- [#7509](https://github.com/TanStack/router/pull/7509) [`9cb7a00`](https://github.com/TanStack/router/commit/9cb7a003e6e5fa3706711870c7b10a5266356e3b) - feat(rsbuild): add RSC support + +- Updated dependencies [[`9cb7a00`](https://github.com/TanStack/router/commit/9cb7a003e6e5fa3706711870c7b10a5266356e3b)]: + - @tanstack/start-plugin-core@1.171.10 + - @tanstack/start-server-core@1.169.8 + - @tanstack/react-start-server@1.167.13 + +## 0.1.16 + +### Patch Changes + +- Updated dependencies [[`2f53749`](https://github.com/TanStack/router/commit/2f5374945e2138559a51464f45a5152eae67e1dd)]: + - @tanstack/router-core@1.171.8 + - @tanstack/react-router@1.170.10 + - @tanstack/react-start-server@1.167.12 + - @tanstack/start-client-core@1.170.6 + - @tanstack/start-plugin-core@1.171.9 + - @tanstack/start-server-core@1.169.7 + - @tanstack/start-storage-context@1.167.10 + +## 0.1.15 + +### Patch Changes + +- Updated dependencies [[`d1997b6`](https://github.com/TanStack/router/commit/d1997b66d7c24c1d64772bb8bab5caf9c6d9cc48)]: + - @tanstack/start-server-core@1.169.6 + - @tanstack/react-router@1.170.9 + - @tanstack/router-core@1.171.7 + - @tanstack/react-start-server@1.167.11 + - @tanstack/start-plugin-core@1.171.8 + - @tanstack/start-client-core@1.170.5 + - @tanstack/start-storage-context@1.167.9 + +## 0.1.14 + +### Patch Changes + +- Updated dependencies [[`9c09bca`](https://github.com/TanStack/router/commit/9c09bca59e9613e9a6fd9b7149b0737898e705d6)]: + - @tanstack/start-plugin-core@1.171.7 + - @tanstack/start-server-core@1.169.5 + - @tanstack/react-start-server@1.167.10 + +## 0.1.13 + +### Patch Changes + +- Updated dependencies [[`a82cec6`](https://github.com/TanStack/router/commit/a82cec69474c366b36efdb3f43c4efe8311c485a), [`d8be4f8`](https://github.com/TanStack/router/commit/d8be4f8adf912128c96b7f83e9a6c49fb24b5eed)]: + - @tanstack/start-plugin-core@1.171.6 + - @tanstack/start-client-core@1.170.4 + - @tanstack/start-server-core@1.169.4 + - @tanstack/react-start-server@1.167.9 + +## 0.1.12 + +### Patch Changes + +- Updated dependencies [[`90adda9`](https://github.com/TanStack/router/commit/90adda91aab7212cbcdb6159176b39d9ed01b827)]: + - @tanstack/start-plugin-core@1.171.5 + +## 0.1.11 + +### Patch Changes + +- Updated dependencies [[`51a97a1`](https://github.com/TanStack/router/commit/51a97a167fb3ef1b8ca70fbb63db635158f43509), [`51a97a1`](https://github.com/TanStack/router/commit/51a97a167fb3ef1b8ca70fbb63db635158f43509)]: + - @tanstack/router-core@1.171.6 + - @tanstack/react-router@1.170.8 + - @tanstack/start-plugin-core@1.171.4 + - @tanstack/start-server-core@1.169.3 + - @tanstack/react-start-server@1.167.8 + - @tanstack/start-client-core@1.170.3 + - @tanstack/start-storage-context@1.167.8 + +## 0.1.10 + +### Patch Changes + +- Updated dependencies [[`5268ba4`](https://github.com/TanStack/router/commit/5268ba4566233ea58880df85f167ad0401a93a46)]: + - @tanstack/router-core@1.171.5 + - @tanstack/react-router@1.170.7 + - @tanstack/react-start-server@1.167.7 + - @tanstack/start-client-core@1.170.2 + - @tanstack/start-plugin-core@1.171.3 + - @tanstack/start-server-core@1.169.2 + - @tanstack/start-storage-context@1.167.7 + +## 0.1.9 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.171.2 + +## 0.1.8 + +### Patch Changes + +- Updated dependencies [[`0300f87`](https://github.com/TanStack/router/commit/0300f87ec5a7f878ffbe0b181acf84cba9139960), [`0300f87`](https://github.com/TanStack/router/commit/0300f87ec5a7f878ffbe0b181acf84cba9139960)]: + - @tanstack/router-core@1.171.4 + - @tanstack/react-router@1.170.6 + - @tanstack/react-start-server@1.167.6 + - @tanstack/start-client-core@1.170.1 + - @tanstack/start-plugin-core@1.171.1 + - @tanstack/start-server-core@1.169.1 + - @tanstack/start-storage-context@1.167.6 + +## 0.1.7 + +### Patch Changes + +- Updated dependencies [[`5fa9e55`](https://github.com/TanStack/router/commit/5fa9e555f3a2edb5e45586623e6bcbfa7f7c7a6b)]: + - @tanstack/start-client-core@1.170.0 + - @tanstack/start-plugin-core@1.171.0 + - @tanstack/start-server-core@1.169.0 + - @tanstack/router-core@1.171.3 + - @tanstack/router-utils@1.162.1 + - @tanstack/react-start-server@1.167.5 + - @tanstack/react-router@1.170.5 + - @tanstack/start-storage-context@1.167.5 + +## 0.1.6 + +### Patch Changes + +- Updated dependencies [[`b60eb36`](https://github.com/TanStack/router/commit/b60eb36e59e8a468ee0742cbcf7f47aca1ff1c67)]: + - @tanstack/router-core@1.171.2 + - @tanstack/react-router@1.170.4 + - @tanstack/react-start-server@1.167.4 + - @tanstack/start-client-core@1.169.4 + - @tanstack/start-plugin-core@1.170.6 + - @tanstack/start-server-core@1.168.4 + - @tanstack/start-storage-context@1.167.4 + +## 0.1.5 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.170.5 + +## 0.1.4 + +### Patch Changes + +- Updated dependencies [[`d9cf933`](https://github.com/TanStack/router/commit/d9cf9331b83fcbd2abfee75d839d862f9bb18e6b)]: + - @tanstack/router-core@1.171.1 + - @tanstack/react-router@1.170.3 + - @tanstack/react-start-server@1.167.3 + - @tanstack/start-client-core@1.169.3 + - @tanstack/start-plugin-core@1.170.4 + - @tanstack/start-server-core@1.168.3 + - @tanstack/start-storage-context@1.167.3 + +## 0.1.3 + +### Patch Changes + +- Updated dependencies [[`d533f87`](https://github.com/TanStack/router/commit/d533f87976704098a40b48f160b37c28c8182806)]: + - @tanstack/router-core@1.171.0 + - @tanstack/react-router@1.170.2 + - @tanstack/react-start-server@1.167.2 + - @tanstack/start-client-core@1.169.2 + - @tanstack/start-plugin-core@1.170.3 + - @tanstack/start-server-core@1.168.2 + - @tanstack/start-storage-context@1.167.2 + +## 0.1.2 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.170.2 + +## 0.1.1 + +### Patch Changes + +- Updated dependencies [[`2387a2e`](https://github.com/TanStack/router/commit/2387a2eea0683004cc400b9f71bed5944eb60110)]: + - @tanstack/router-core@1.170.1 + - @tanstack/start-plugin-core@1.170.1 + - @tanstack/start-server-core@1.168.1 + - @tanstack/react-router@1.170.1 + - @tanstack/react-start-server@1.167.1 + - @tanstack/start-client-core@1.169.1 + - @tanstack/start-storage-context@1.167.1 + +## 0.1.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +### Patch Changes + +- Updated dependencies [[`b1c061a`](https://github.com/TanStack/router/commit/b1c061aff9185cdf5fdc08c0136382a9dce0302f), [`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14), [`5ae2ae5`](https://github.com/TanStack/router/commit/5ae2ae5e0f8ce32e02667a482ea9be52a6150240)]: + - @tanstack/router-core@1.170.0 + - @tanstack/react-router@1.170.0 + - @tanstack/react-start-server@1.167.0 + - @tanstack/router-utils@1.162.0 + - @tanstack/start-client-core@1.169.0 + - @tanstack/start-fn-stubs@1.162.0 + - @tanstack/start-plugin-core@1.170.0 + - @tanstack/start-server-core@1.168.0 + - @tanstack/start-storage-context@1.167.0 + +## 0.0.44 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.169.20 + +## 0.0.43 + +### Patch Changes + +- Updated dependencies [[`35e88f0`](https://github.com/TanStack/router/commit/35e88f04996d71019a1868b7b06ecb4ddbc9df9e)]: + - @tanstack/router-core@1.169.2 + - @tanstack/start-client-core@1.168.2 + - @tanstack/start-plugin-core@1.169.19 + - @tanstack/start-server-core@1.167.30 + - @tanstack/react-router@1.169.2 + - @tanstack/react-start-server@1.166.52 + - @tanstack/start-storage-context@1.166.35 + +## 0.0.42 + +### Patch Changes + +- Updated dependencies [[`056337e`](https://github.com/TanStack/router/commit/056337ef02ccbeaf45ec8533a227761be869e8f3)]: + - @tanstack/router-utils@1.161.8 + - @tanstack/start-plugin-core@1.169.18 + +## 0.0.41 + +### Patch Changes + +- Updated dependencies [[`afa40ef`](https://github.com/TanStack/router/commit/afa40ef46c273c53646ba33f607fc618a07ffede)]: + - @tanstack/start-server-core@1.167.29 + - @tanstack/react-start-server@1.166.51 + - @tanstack/start-plugin-core@1.169.17 + +## 0.0.40 + +### Patch Changes + +- Updated dependencies [[`709627f`](https://github.com/TanStack/router/commit/709627f3dbc6d97daa547a1401ef42a53bc4be32)]: + - @tanstack/start-server-core@1.167.28 + - @tanstack/react-start-server@1.166.50 + - @tanstack/start-plugin-core@1.169.16 + +## 0.0.39 + +### Patch Changes + +- Updated dependencies [[`238ea4a`](https://github.com/TanStack/router/commit/238ea4a4998ab3a7fd528b317e1935766ac65df8)]: + - @tanstack/start-server-core@1.167.27 + - @tanstack/react-start-server@1.166.49 + - @tanstack/start-plugin-core@1.169.15 + +## 0.0.38 + +### Patch Changes + +- Updated dependencies [[`96818b8`](https://github.com/TanStack/router/commit/96818b8ba5ead6f1f027094841330182aff415b2)]: + - @tanstack/start-plugin-core@1.169.14 + +## 0.0.37 + +### Patch Changes + +- Add compiler-driven RSC CSS auto-injection for Start RSC render APIs and wire it into the React Start Vite and Rsbuild adapters. This ensures same-file CSS module dependencies are discovered for `renderServerComponent`, `createCompositeComponent`, and JSX-based `renderToReadableStream` calls. ([#7310](https://github.com/TanStack/router/pull/7310)) + + Also add a configurable server function provider module directive hook used by the React Rsbuild RSC adapter to emit `"use server-entry"` only for extracted provider files. + +- Updated dependencies [[`ae453b7`](https://github.com/TanStack/router/commit/ae453b78624cac1b574f0d1efbfbf6ca03922c6c)]: + - @tanstack/start-plugin-core@1.169.13 + +## 0.0.36 + +### Patch Changes + +- Updated dependencies [[`4a1e63f`](https://github.com/TanStack/router/commit/4a1e63f1d1230b1ed8234609acad4639d8982c13)]: + - @tanstack/router-core@1.169.1 + - @tanstack/react-router@1.169.1 + - @tanstack/react-start-server@1.166.48 + - @tanstack/start-client-core@1.168.1 + - @tanstack/start-plugin-core@1.169.12 + - @tanstack/start-server-core@1.167.26 + - @tanstack/start-storage-context@1.166.34 + +## 0.0.35 + +### Patch Changes + +- Updated dependencies [[`82b0613`](https://github.com/TanStack/router/commit/82b06132af776f74603ab27977cc277d6219a845)]: + - @tanstack/start-client-core@1.168.0 + - @tanstack/react-start-server@1.166.47 + - @tanstack/start-plugin-core@1.169.11 + - @tanstack/start-server-core@1.167.25 + +## 0.0.34 + +### Patch Changes + +- Updated dependencies [[`c4256c2`](https://github.com/TanStack/router/commit/c4256c2c857f392d2031cf87821e4c36a92d0382)]: + - @tanstack/start-plugin-core@1.169.10 + +## 0.0.33 + +### Patch Changes + +- Updated dependencies [[`761fcc0`](https://github.com/TanStack/router/commit/761fcc0c96dd96721b533a1fd9e2c972f222ef94)]: + - @tanstack/start-plugin-core@1.169.9 + +## 0.0.32 + +### Patch Changes + +- Updated dependencies [[`c992495`](https://github.com/TanStack/router/commit/c992495bf4010ff4c3597bb1f3b1ba02594e857e)]: + - @tanstack/router-core@1.169.0 + - @tanstack/react-router@1.169.0 + - @tanstack/react-start-server@1.166.46 + - @tanstack/start-client-core@1.167.22 + - @tanstack/start-plugin-core@1.169.8 + - @tanstack/start-server-core@1.167.24 + - @tanstack/start-storage-context@1.166.33 + +## 0.0.31 + +### Patch Changes + +- Updated dependencies [[`b5c4183`](https://github.com/TanStack/router/commit/b5c4183ab8b44be8a75647b7f7b588ad7c146ece)]: + - @tanstack/router-core@1.168.18 + - @tanstack/react-router@1.168.26 + - @tanstack/react-start-server@1.166.45 + - @tanstack/start-client-core@1.167.21 + - @tanstack/start-plugin-core@1.169.7 + - @tanstack/start-server-core@1.167.23 + - @tanstack/start-storage-context@1.166.32 + +## 0.0.30 + +### Patch Changes + +- Re-export `RenderableServerComponent`, `RenderableServerComponentAttributes`, `RenderableServerComponentBuilder`, and `AnyRenderableServerComponent` from the package's public entries. Without these, consumers with `declaration: true` hit TS2742 on `renderServerComponent` calls and are forced to annotate handlers as `Promise`. ([#7278](https://github.com/TanStack/router/pull/7278)) + +## 0.0.29 + +### Patch Changes + +- Updated dependencies [[`493148b`](https://github.com/TanStack/router/commit/493148bc5378b7f9de1544d87f6aaa425c12eb34)]: + - @tanstack/router-core@1.168.17 + - @tanstack/react-router@1.168.25 + - @tanstack/react-start-server@1.166.44 + - @tanstack/start-client-core@1.167.20 + - @tanstack/start-plugin-core@1.169.6 + - @tanstack/start-server-core@1.167.22 + - @tanstack/start-storage-context@1.166.31 + +## 0.0.28 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.169.5 + +## 0.0.27 + +### Patch Changes + +- Updated dependencies [[`8b97002`](https://github.com/TanStack/router/commit/8b97002af3f6d15204e60c55d3f5735b78bd7efe)]: + - @tanstack/start-client-core@1.167.19 + - @tanstack/react-start-server@1.166.43 + - @tanstack/start-plugin-core@1.169.4 + - @tanstack/start-server-core@1.167.21 + +## 0.0.26 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.169.3 + +## 0.0.25 + +### Patch Changes + +- Updated dependencies [[`4d864ee`](https://github.com/TanStack/router/commit/4d864eebbd184265eabb563d326ab409c93feb17)]: + - @tanstack/react-router@1.168.24 + - @tanstack/router-core@1.168.16 + - @tanstack/start-plugin-core@1.169.2 + - @tanstack/start-server-core@1.167.20 + - @tanstack/react-start-server@1.166.42 + - @tanstack/start-client-core@1.167.18 + - @tanstack/start-storage-context@1.166.30 + +## 0.0.24 + +### Patch Changes + +- Updated dependencies [[`9252206`](https://github.com/TanStack/router/commit/9252206e5aeafe53e31eb7baa491d07a597c4dc6)]: + - @tanstack/start-plugin-core@1.169.1 + +## 0.0.23 + +### Patch Changes + +- Split Start plugin core bundler APIs into explicit Vite and Rsbuild subpaths so projects only need the bundler they use. Mark both `vite` and `@rsbuild/core` peers as optional where Start exposes both integrations. ([#7249](https://github.com/TanStack/router/pull/7249)) + +- Updated dependencies [[`dda463c`](https://github.com/TanStack/router/commit/dda463c8b571519165d3adbc337db7a0b8be1072)]: + - @tanstack/start-plugin-core@1.169.0 + +## 0.0.22 + +### Patch Changes + +- rsbuild ([#7228](https://github.com/TanStack/router/pull/7228)) + +- Updated dependencies [[`91a7089`](https://github.com/TanStack/router/commit/91a708989d00537a21911e74ff60bbfec8266295)]: + - @tanstack/start-plugin-core@1.168.0 + - @tanstack/router-utils@1.161.7 + +## 0.0.21 + +### Patch Changes + +- Updated dependencies [[`cd91cee`](https://github.com/TanStack/router/commit/cd91ceebb84b7b752b5ee09ac14e89ad2beb2259)]: + - @tanstack/react-router@1.168.23 + - @tanstack/react-start-server@1.166.41 + +## 0.0.20 + +### Patch Changes + +- Updated dependencies [[`f7f0025`](https://github.com/TanStack/router/commit/f7f00250f39cf0276a984558e5d427e9270d9635)]: + - @tanstack/start-plugin-core@1.167.35 + +## 0.0.19 + +### Patch Changes + +- Updated dependencies [[`e30814d`](https://github.com/TanStack/router/commit/e30814d949110ff25829de44d729ead47555940a)]: + - @tanstack/react-router@1.168.22 + - @tanstack/react-start-server@1.166.40 + +## 0.0.18 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/react-router@1.168.21 + - @tanstack/react-start-server@1.166.39 + - @tanstack/start-client-core@1.167.17 + - @tanstack/start-plugin-core@1.167.34 + - @tanstack/start-server-core@1.167.19 + - @tanstack/start-storage-context@1.166.29 + +## 0.0.17 + +### Patch Changes + +- Updated dependencies [[`c5ad329`](https://github.com/TanStack/router/commit/c5ad32936f6adcca0c56474677b73b212498443b)]: + - @tanstack/react-router@1.168.20 + - @tanstack/react-start-server@1.166.38 + +## 0.0.16 + +### Patch Changes + +- Fix Start virtual module resolution in pnpm workspaces by serving the client entry through a real Vite virtual module. ([#7178](https://github.com/TanStack/router/pull/7178)) + + Simplify Start virtual module handling by sharing a single `createVirtualModule` helper and collapsing internal `@tanstack/start-plugin-core` imports to the root export surface. + +- Updated dependencies [[`a581680`](https://github.com/TanStack/router/commit/a581680a27530469751b8ab419ada9ce66da4ffe)]: + - @tanstack/start-plugin-core@1.167.33 + +## 0.0.15 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.167.32 + +## 0.0.14 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.167.31 + +## 0.0.13 + +### Patch Changes + +- Updated dependencies [[`105d056`](https://github.com/TanStack/router/commit/105d05691a247779a63e7b688aa1207cce619339)]: + - @tanstack/react-router@1.168.19 + - @tanstack/start-plugin-core@1.167.30 + - @tanstack/react-start-server@1.166.37 + +## 0.0.12 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.167.29 + +## 0.0.11 + +### Patch Changes + +- Updated dependencies [[`0e2c900`](https://github.com/TanStack/router/commit/0e2c9003c18ae07c09969189c028f277ea562a7a)]: + - @tanstack/start-server-core@1.167.18 + - @tanstack/router-core@1.168.14 + - @tanstack/react-start-server@1.166.36 + - @tanstack/start-plugin-core@1.167.28 + - @tanstack/react-router@1.168.18 + - @tanstack/start-client-core@1.167.16 + - @tanstack/start-storage-context@1.166.28 + +## 0.0.10 + +### Patch Changes + +- Updated dependencies [[`812792f`](https://github.com/TanStack/router/commit/812792fbda3caf97b300770855cf5641252f413b)]: + - @tanstack/router-core@1.168.13 + - @tanstack/start-plugin-core@1.167.27 + - @tanstack/start-server-core@1.167.17 + - @tanstack/react-router@1.168.17 + - @tanstack/react-start-server@1.166.35 + - @tanstack/start-client-core@1.167.15 + - @tanstack/start-storage-context@1.166.27 + +## 0.0.9 + +### Patch Changes + +- Updated dependencies [[`8ec9ca9`](https://github.com/TanStack/router/commit/8ec9ca97b472779de878c2a6510f21deb24d386c)]: + - @tanstack/router-core@1.168.12 + - @tanstack/react-router@1.168.16 + - @tanstack/react-start-server@1.166.34 + - @tanstack/start-client-core@1.167.14 + - @tanstack/start-plugin-core@1.167.26 + - @tanstack/start-server-core@1.167.16 + - @tanstack/start-storage-context@1.166.26 + +## 0.0.8 + +### Patch Changes + +- Updated dependencies [[`d3f20fb`](https://github.com/TanStack/router/commit/d3f20fbe7acf69c3bd108c5ddc9748ad47690b04)]: + - @tanstack/start-plugin-core@1.167.25 + +## 0.0.7 + +### Patch Changes + +- Updated dependencies [[`6355bb7`](https://github.com/TanStack/router/commit/6355bb75f7637ba77f06a923c18fdaf37720bb48)]: + - @tanstack/start-server-core@1.167.15 + - @tanstack/react-router@1.168.15 + - @tanstack/router-core@1.168.11 + - @tanstack/react-start-server@1.166.33 + - @tanstack/start-plugin-core@1.167.24 + - @tanstack/start-client-core@1.167.13 + - @tanstack/start-storage-context@1.166.25 + +## 0.0.6 + +### Patch Changes + +- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: + - @tanstack/start-client-core@1.167.12 + - @tanstack/start-server-core@1.167.14 + - @tanstack/react-router@1.168.14 + - @tanstack/router-core@1.168.10 + - @tanstack/react-start-server@1.166.32 + - @tanstack/start-plugin-core@1.167.23 + - @tanstack/start-storage-context@1.166.24 + +## 0.0.5 + +### Patch Changes + +- Updated dependencies [[`f8ac427`](https://github.com/TanStack/router/commit/f8ac427000c3fec99225926e72f9f2fc7a37231f)]: + - @tanstack/start-server-core@1.167.13 + - @tanstack/start-client-core@1.167.11 + - @tanstack/react-start-server@1.166.31 + - @tanstack/start-plugin-core@1.167.22 + +## 0.0.4 + +### Patch Changes + +- Updated dependencies [[`2d53c05`](https://github.com/TanStack/router/commit/2d53c056ef0b203de8a28bc92c24e8e604205d52)]: + - @tanstack/start-server-core@1.167.12 + - @tanstack/start-plugin-core@1.167.21 + - @tanstack/react-start-server@1.166.30 + +## 0.0.2 + +### Patch Changes + +- Republish the React Start RSC package chain so fresh installs resolve a `start-plugin-core` build that exports the subpaths used by `react-start-rsc`. ([`3384abc`](https://github.com/TanStack/router/commit/3384abcffd98a68eb254b11221834bcbcdebec31)) + +- Updated dependencies [[`3384abc`](https://github.com/TanStack/router/commit/3384abcffd98a68eb254b11221834bcbcdebec31)]: + - @tanstack/start-plugin-core@1.167.19 + +## 0.0.1 + +### Patch Changes + +- Bump the initial release line for `@tanstack/react-start-rsc` and `@tanstack/eslint-plugin-start` to `0.0.1` after the manual `0.0.0` publish. ([#7144](https://github.com/TanStack/router/pull/7144)) diff --git a/packages/react-start-rsc/eslint.config.js b/packages/react-start-rsc/eslint.config.js new file mode 100644 index 0000000000..daf1baa88a --- /dev/null +++ b/packages/react-start-rsc/eslint.config.js @@ -0,0 +1,58 @@ +// @ts-check + +import pluginReact from '@eslint-react/eslint-plugin' +import pluginReactHooks from 'eslint-plugin-react-hooks' +import rootConfig from '../../eslint.config.js' + +export default [ + ...rootConfig, + { + ...pluginReact.configs.recommended, + files: ['**/*.{ts,tsx}'], + }, + { + plugins: { + 'react-hooks': pluginReactHooks, + }, + rules: { + '@eslint-react/no-unstable-context-value': 'off', + '@eslint-react/no-unstable-default-props': 'off', + '@eslint-react/dom/no-missing-button-type': 'off', + 'react-hooks/exhaustive-deps': 'error', + 'react-hooks/rules-of-hooks': 'error', + }, + }, + { + name: 'react-start-rsc/import-boundaries', + files: ['src/**/*.{ts,tsx}'], + rules: { + 'no-restricted-imports': [ + 'error', + { + paths: [ + { + name: '@tanstack/start-server-core', + message: + 'Import from a dedicated @tanstack/start-server-core subpath to avoid pulling the full server barrel into the RSC module graph.', + }, + ], + }, + ], + 'no-restricted-syntax': [ + 'error', + { + selector: + "ImportExpression[source.value='@tanstack/start-server-core']", + message: + 'Dynamically import a dedicated @tanstack/start-server-core subpath instead of the root barrel.', + }, + ], + }, + }, + { + files: ['**/__tests__/**'], + rules: { + '@typescript-eslint/no-unnecessary-condition': 'off', + }, + }, +] diff --git a/packages/react-start-rsc/package.json b/packages/react-start-rsc/package.json new file mode 100644 index 0000000000..40b1847068 --- /dev/null +++ b/packages/react-start-rsc/package.json @@ -0,0 +1,146 @@ +{ + "name": "@tanstack/react-start-rsc", + "version": "0.1.67", + "description": "React Server Components support for TanStack Start", + "author": "Tanner Linsley", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/TanStack/router.git", + "directory": "packages/react-start-rsc" + }, + "homepage": "https://tanstack.com/start", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "keywords": [ + "react", + "rsc", + "server components", + "router", + "routing", + "typescript" + ], + "scripts": { + "clean": "rimraf ./dist && rimraf ./coverage", + "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit", + "test:unit": "vitest", + "test:unit:dev": "vitest --watch", + "test:eslint": "eslint ./src", + "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", + "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", + "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", + "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", + "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", + "build": "vite build" + }, + "type": "module", + "types": "dist/esm/src/index.d.ts", + "exports": { + ".": { + "react-server": { + "types": "./dist/esm/src/index.rsc.d.ts", + "default": "./dist/esm/index.rsc.js" + }, + "import": { + "types": "./dist/esm/src/index.d.ts", + "default": "./dist/esm/index.js" + } + }, + "./serialization.client": { + "import": { + "types": "./dist/esm/src/serialization.client.d.ts", + "default": "./dist/esm/serialization.client.js" + } + }, + "./serialization.server": { + "import": { + "types": "./dist/esm/src/serialization.server.d.ts", + "default": "./dist/esm/serialization.server.js" + } + }, + "./plugin/vite": { + "import": { + "types": "./dist/esm/src/plugin/vite.d.ts", + "default": "./dist/esm/plugin/vite.js" + } + }, + "./plugin/rscCssTransform": { + "import": { + "types": "./dist/esm/src/plugin/rscCssTransform.d.ts", + "default": "./dist/esm/plugin/rscCssTransform.js" + } + }, + "./rsbuild/ssr-decode": { + "import": { + "types": "./dist/esm/src/rsbuild/ssr-decode.d.ts", + "default": "./dist/esm/rsbuild/ssr-decode.js" + } + }, + "./rsbuild/browser-decode": { + "import": { + "types": "./dist/esm/src/rsbuild/browser-decode.d.ts", + "default": "./dist/esm/rsbuild/browser-decode.js" + } + }, + "./package.json": "./package.json" + }, + "files": [ + "dist", + "src" + ], + "engines": { + "node": ">=22.12.0" + }, + "dependencies": { + "@tanstack/react-router": "workspace:*", + "@tanstack/router-core": "workspace:*", + "@tanstack/router-utils": "workspace:*", + "@tanstack/start-client-core": "workspace:*", + "@tanstack/start-fn-stubs": "workspace:*", + "@tanstack/start-plugin-core": "workspace:*", + "@tanstack/start-storage-context": "workspace:*", + "pathe": "catalog:" + }, + "devDependencies": { + "@rspack/core": "2.2.7", + "@testing-library/react": "catalog:", + "@vitejs/plugin-react": "catalog:", + "@vitejs/plugin-rsc": "^0.5.39", + "react-server-dom-rspack": "^0.1.1", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@eslint-react/eslint-plugin": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" + }, + "peerDependencies": { + "@rspack/core": ">=2.0.0-0", + "@vitejs/plugin-rsc": ">=0.5.38", + "react": ">=18.0.0 || >=19.0.0", + "react-dom": ">=18.0.0 || >=19.0.0", + "react-server-dom-rspack": ">=0.1.1" + }, + "peerDependenciesMeta": { + "@rspack/core": { + "optional": true + }, + "@vitejs/plugin-rsc": { + "optional": true + }, + "react-server-dom-rspack": { + "optional": true + } + } +} diff --git a/packages/react-start-rsc/src/ClientSlot.tsx b/packages/react-start-rsc/src/ClientSlot.tsx new file mode 100644 index 0000000000..01e494049e --- /dev/null +++ b/packages/react-start-rsc/src/ClientSlot.tsx @@ -0,0 +1,34 @@ +'use client' + +import { useSlotContext } from './SlotContext' + +export interface ClientSlotProps { + slot: string + args: Array +} + +export function ClientSlot({ slot, args }: ClientSlotProps) { + const ctx = useSlotContext() + + if (!ctx) { + throw new Error('ClientSlot must be rendered within SlotProvider') + } + + const impl = ctx.implementations[slot] + + // No implementation provided + if (impl === undefined) { + if (ctx.strict) { + throw new Error(`Missing slot implementation for "${slot}"`) + } + return null + } + + // For children slot or any non-function value, render directly + if (typeof impl !== 'function') { + return <>{impl} + } + + // Render function with args + return <>{impl(...args)} +} diff --git a/packages/react-start-rsc/src/CompositeComponent.tsx b/packages/react-start-rsc/src/CompositeComponent.tsx new file mode 100644 index 0000000000..e6c81aa69a --- /dev/null +++ b/packages/react-start-rsc/src/CompositeComponent.tsx @@ -0,0 +1,165 @@ +'use client' + +import { Suspense } from 'react' +import ReactDOM from 'react-dom' + +import { SlotProvider } from './SlotContext' +import { + RSC_PROXY_GET_TREE, + RSC_PROXY_PATH, + SERVER_COMPONENT_CSS_HREFS, + SERVER_COMPONENT_JS_PRELOADS, + SERVER_COMPONENT_STREAM, +} from './ServerComponentTypes' +import type { AnyCompositeComponent } from './ServerComponentTypes' +import type { SlotImplementations } from './types' + +function splitSlotProps(props?: Record): { + implementations: SlotImplementations + strict: boolean +} { + const safeProps = props ?? {} + const { children, strict, ...slotProps } = safeProps as { + children?: unknown + strict?: unknown + [key: string]: unknown + } + + return { + implementations: { ...slotProps, children }, + strict: strict === true, + } +} + +function EmptyFallback() { + return null +} + +function CompositeRenderInner({ + getTree, + path, + slotProps, +}: { + getTree: () => unknown + path: Array + slotProps?: Record +}): React.ReactNode { + let tree: unknown = getTree() + + for (const key of path) { + if (tree === null || tree === undefined) return null + if (typeof tree !== 'object') return null + tree = (tree as Record)[key] + } + + if (tree === null || tree === undefined) return null + + const { implementations, strict } = splitSlotProps(slotProps) + + return ( + + {tree as React.ReactNode} + + ) +} + +function CompositeRenderComponent({ + getTree, + path, + slotProps, + cssHrefs, + jsPreloads, +}: { + getTree: () => unknown + path: Array + slotProps?: Record + cssHrefs?: ReadonlySet + jsPreloads?: ReadonlySet +}): React.ReactNode { + for (const href of cssHrefs ?? []) { + ReactDOM.preinit(href, { as: 'style', precedence: 'high' }) + } + + if (jsPreloads) { + for (const href of jsPreloads) { + ReactDOM.preloadModule(href) + } + } + + return ( + <> + }> + + + + ) +} + +/** + * Renders composite RSC data with slot support. + * + * Use this component to render data from `createCompositeComponent`. + * Pass slot implementations as props to fill in ClientSlot placeholders. + * + * @example + * ```tsx + * const src = await createCompositeComponent((props) => ( + *
    + *
    {props.header('Dashboard')}
    + *
    {props.children}
    + *
    + * )) + * + * // In route component + * return ( + *

    {title}

    }> + *

    Main content

    + *
    + * ) + * ``` + */ +export function CompositeComponent( + props: CompositeComponentProps, +): TComp['~types']['return'] { + const { src, ...slotProps } = props + + const stream = src[SERVER_COMPONENT_STREAM] + + if (!stream) { + throw new Error( + '[tanstack/start] missing RSC stream on src', + ) + } + + const cssHrefs = src[SERVER_COMPONENT_CSS_HREFS] + const jsPreloads = src[SERVER_COMPONENT_JS_PRELOADS] + + const path = src[RSC_PROXY_PATH] ?? [] + + const getTree = src[RSC_PROXY_GET_TREE] + + if (!getTree) { + throw new Error( + '[tanstack/start] missing getTree on RSC src. ' + + 'Make sure src comes from createCompositeComponent().', + ) + } + + return ( + + ) +} + +export type CompositeComponentProps = { + src: TComp +} & TComp['~types']['props'] diff --git a/packages/react-start-rsc/src/ReplayableStream.ts b/packages/react-start-rsc/src/ReplayableStream.ts new file mode 100644 index 0000000000..4c3e878c79 --- /dev/null +++ b/packages/react-start-rsc/src/ReplayableStream.ts @@ -0,0 +1,249 @@ +/** + * ReplayableStream is used for React Server Components (RSC) / Flight streams. + * + * In this package the same Flight payload may need to be: + * - decoded for SSR (render path), and/or + * - serialized for transport to the client for client-side decoding. + * + * Call sites: + * - `src/createServerComponent.ts`: wraps the produced Flight stream once. + * - `src/serialization.ts`: uses `createReplayStream()` to transport a fresh stream + * to the client via `RawStream`. + * + * Constraints: + * - Consumption order isn't fixed: SSR decode might start first or transport might + * start first depending on the request path. + * - Sometimes only one happens (e.g. when client calls server function directly). + * + * Why not just `ReadableStream.tee()`? + * - tee() must be called up-front before the stream is consumed/locked and only + * creates two live branches (no late "replay from byte 0"). + * - If one branch is slower or never consumed, the runtime may buffer internally + * to keep branches consistent, which can retain large Flight payloads longer + * than intended and makes cleanup less explicit. + * + * ReplayableStream reads once, buffers explicitly, can mint replay streams on + * demand, and centralizes cancellation so aborting can stop upstream work and + * free buffered data deterministically. + * + * Memory Management: + * - Memory is released when the abort signal fires (request cancelled) + * - Call `release()` to force immediate cleanup if no more replays are needed + * - No automatic release: replays can be created at unpredictable times (SSR decode + * finishes before serialization starts), so we can't safely auto-release + */ + +export interface ReplayableStreamOptions { + signal?: AbortSignal +} + +// Use Symbol.for to ensure the same symbol across different module instances +export const REPLAYABLE_STREAM_MARKER = Symbol.for( + 'tanstack.rsc.ReplayableStream', +) + +export class ReplayableStream { + // Marker for cross-environment instance checking + readonly [REPLAYABLE_STREAM_MARKER] = true + + private chunks: Array = [] + private done = false + private error: unknown = null + private waiter: PromiseWithResolvers | null = null + private aborted = false + private released = false + + private sourceReader: ReadableStreamDefaultReader | null = null + private abortSignal: AbortSignal | undefined + private abortListener: (() => void) | null = null + + constructor( + private source: ReadableStream, + private options: ReplayableStreamOptions = {}, + ) { + this.abortSignal = options.signal + this.start() + } + + private start(): void { + const signal = this.abortSignal + + if (signal?.aborted) { + this.handleAbort() + return + } + + const onAbort = () => this.handleAbort() + this.abortListener = onAbort + signal?.addEventListener('abort', onAbort, { once: true }) + + const reader = this.source.getReader() + this.sourceReader = reader + + const pump = async () => { + try { + // Keep reading until upstream ends or we are stopped. + while (!this.aborted && !this.released) { + const { done, value } = await reader.read() + if (done) break + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (this.aborted || this.released) break + this.chunks.push(value) + this.notify() + } + this.done = true + } catch (err) { + if (!this.aborted && !this.released) { + this.error = err + } + this.done = true + } finally { + this.detachAbortListener() + try { + reader.releaseLock() + } catch { + // Ignore + } + if (this.sourceReader === reader) { + this.sourceReader = null + } + this.notify() + } + } + + pump() + } + + private detachAbortListener(): void { + const signal = this.abortSignal + const listener = this.abortListener + if (signal && listener) { + signal.removeEventListener('abort', listener) + } + this.abortListener = null + } + + private cancelSource(reason: unknown): void { + const reader = this.sourceReader + this.sourceReader = null + + try { + reader?.cancel(reason).catch(() => {}) + } catch { + // Ignore + } + } + + private handleAbort(): void { + if (this.aborted) return + this.aborted = true + this.done = true + + // Try to stop upstream work immediately. + // Cancellation during an abort can throw synchronously in some runtimes + // (eg when the underlying cancel algorithm throws). Never let that escape + // an AbortSignal event handler. + const reason = + this.abortSignal?.reason ?? new Error('ReplayableStream aborted') + + this.detachAbortListener() + this.abortSignal = undefined + this.cancelSource(reason) + + this.chunks = [] // Free memory immediately on abort + this.released = true + this.notify() + } + + private notify(): void { + if (this.waiter) { + this.waiter.resolve() + this.waiter = null + } + } + + private wait(): Promise { + if (this.done || this.released) return Promise.resolve() + if (!this.waiter) { + this.waiter = Promise.withResolvers() + } + return this.waiter.promise + } + + /** + * Explicitly release buffered chunks. + * Call this when you know no more replay streams will be created. + * After calling release(), createReplayStream() will return empty streams. + */ + release(): void { + if (this.released) return + + this.released = true + this.chunks = [] + + // Release should also stop upstream work and wake any waiters. + // This is important when a Flight payload is never consumed again + // (eg. cached loader data that evicts) to avoid retaining upstream resources. + this.detachAbortListener() + this.abortSignal = undefined + this.cancelSource(new Error('ReplayableStream released')) + this.notify() + } + + /** + * Check if the stream data has been released + */ + isReleased(): boolean { + return this.released + } + + /** + * Create an independent replay stream. Each call returns a fresh reader + * that starts from the beginning of the buffered data. + * + * If the stream has been released, returns a stream that closes immediately. + */ + createReplayStream(): ReadableStream { + if (this.released) { + return new ReadableStream({ + start(controller) { + controller.close() + }, + }) + } + + let index = 0 + + return new ReadableStream({ + pull: async (controller) => { + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (true) { + if (this.released) { + controller.close() + return + } + + if (index < this.chunks.length) { + controller.enqueue(this.chunks[index++] as T) + return + } + + if (this.done) { + if (this.error && !this.aborted) { + controller.error(this.error) + } else { + controller.close() + } + return + } + + await this.wait() + } + }, + cancel: () => { + // No-op: consumers canceling a replay should not cancel upstream. + // Upstream cancellation is controlled by abort/release. + }, + }) + } +} diff --git a/packages/react-start-rsc/src/RscNodeRenderer.tsx b/packages/react-start-rsc/src/RscNodeRenderer.tsx new file mode 100644 index 0000000000..430f24ad0f --- /dev/null +++ b/packages/react-start-rsc/src/RscNodeRenderer.tsx @@ -0,0 +1,76 @@ +'use client' + +import { Suspense } from 'react' +import ReactDOM from 'react-dom' + +import { + RSC_PROXY_GET_TREE, + RSC_PROXY_PATH, + SERVER_COMPONENT_CSS_HREFS, + SERVER_COMPONENT_JS_PRELOADS, +} from './ServerComponentTypes' + +function EmptyFallback() { + return null +} + +function RscNodeRenderInner({ + getTree, + path, +}: { + getTree: () => unknown + path: Array +}): React.ReactNode { + let tree: unknown = getTree() + + for (const key of path) { + if (tree === null || tree === undefined) return null + if (typeof tree !== 'object') return null + tree = (tree as Record)[key] + } + + if (tree === null || tree === undefined) return null + + // No SlotProvider - just return the tree directly + return tree as React.ReactNode +} + +/** + * Renders a renderable RSC proxy without slot support. + * Used internally by the renderable proxy's $$typeof/type masquerade. + */ +export function RscNodeRenderer({ data }: { data: any }): React.ReactNode { + const cssHrefs = data[SERVER_COMPONENT_CSS_HREFS] as + | ReadonlySet + | undefined + const jsPreloads = data[SERVER_COMPONENT_JS_PRELOADS] as + | ReadonlySet + | undefined + + const path = (data[RSC_PROXY_PATH] as Array | undefined) ?? [] + + const getTree = data[RSC_PROXY_GET_TREE] as (() => unknown) | undefined + if (!getTree) { + throw new Error( + '[tanstack/start] RscNodeRenderer missing getTree on RSC data.', + ) + } + + for (const href of cssHrefs ?? []) { + ReactDOM.preinit(href, { as: 'style', precedence: 'high' }) + } + + if (jsPreloads) { + for (const href of jsPreloads) { + ReactDOM.preloadModule(href) + } + } + + return ( + <> + }> + + + + ) +} diff --git a/packages/react-start-rsc/src/ServerComponentTypes.ts b/packages/react-start-rsc/src/ServerComponentTypes.ts new file mode 100644 index 0000000000..5e1fa32a52 --- /dev/null +++ b/packages/react-start-rsc/src/ServerComponentTypes.ts @@ -0,0 +1,216 @@ +import type { + Constrain, + LooseAsyncReturnType, + LooseReturnType, + ValidateSerializable, +} from '@tanstack/router-core' +import type { ComponentProps, ComponentType } from 'react' + +export interface ServerComponentStream { + createReplayStream: () => ReadableStream +} + +// Symbol to attach stream to component for serialization +export const SERVER_COMPONENT_STREAM = Symbol.for('tanstack.rsc.stream') + +// Symbol to attach collected CSS hrefs to component +export const SERVER_COMPONENT_CSS_HREFS = Symbol.for('tanstack.rsc.cssHrefs') + +// Symbol to attach collected JS modulepreload hrefs to component +export const SERVER_COMPONENT_JS_PRELOADS = Symbol.for( + 'tanstack.rsc.jsPreloads', +) + +// Symbol to attach a nested selection path to the RSC data proxy +export const RSC_PROXY_PATH = Symbol.for('tanstack.rsc.path') + +// Symbol to attach the root tree getter to every nested proxy +export const RSC_PROXY_GET_TREE = Symbol.for('tanstack.rsc.getTree') + +// Symbol to mark a proxy as "renderable" (for renderServerComponent output) +// When true: from renderServerComponent (directly renderable) +// When false/undefined: from createCompositeComponent (needs ) +export const RENDERABLE_RSC = Symbol.for('tanstack.rsc.renderable') + +// Dev-only: collected slot usage data for devtools (client-side cache) +export const RSC_SLOT_USAGES = Symbol.for('tanstack.rsc.slotUsages') + +// Dev-only: stream of slot usage preview events for devtools +export const RSC_SLOT_USAGES_STREAM = Symbol.for( + 'tanstack.rsc.slotUsages.stream', +) + +export type RscSlotUsageEvent = { + slot: string + // Raw args passed to the slot call (must be serializable by the transport) + args?: Array +} + +/** + * Type guard to check if a value is a ServerComponent (Proxy with attached stream). + * The value can be either an object (proxy target) or a function (stub for server functions). + */ +export function isServerComponent( + value: unknown, +): value is AnyCompositeComponent { + if (value === null || value === undefined) return false + if (typeof value !== 'object' && typeof value !== 'function') return false + return ( + SERVER_COMPONENT_STREAM in value && + (value as any)[SERVER_COMPONENT_STREAM] !== undefined + ) +} + +export type ValidateCompositeComponent = Constrain< + TComp, + ( + props: ValidateCompositeComponentProps, + ) => ValidateCompositeComponentReturnType +> + +export type ValidateCompositeComponentProps = unknown extends TComp + ? TComp + : ValidateCompositeComponentPropsObject> + +export type ValidateCompositeComponentPropsObject = + unknown extends TProps + ? TProps + : { + [TKey in keyof TProps]: ValidateCompositeComponentProp + } + +export type CompositeComponentProps = TComp extends ( + props: infer TProps, +) => any + ? TProps + : unknown + +export type ValidateCompositeComponentProp = TProp extends ( + ...args: Array +) => any + ? (...args: ValidateReactSerializable>) => React.ReactNode + : TProp extends ComponentType + ? ComponentType>> + : TProp extends React.ReactNode + ? TProp + : React.ReactNode + +export type ValidateReactSerializable = ValidateSerializable< + T, + ReactSerializable +> + +export type ReactSerializable = + | number + | string + | bigint + | boolean + | null + | undefined + | React.ReactNode + +export type ValidateCompositeComponentReturnType = unknown extends TComp + ? React.ReactNode + : ValidateCompositeComponentResult> + +export type ValidateCompositeComponentResult = + ValidateServerComponentResult + +export type ValidateServerComponentResult = + TNode extends Promise + ? ValidateCompositeComponentPromiseResult + : TNode extends React.ReactNode + ? TNode + : TNode extends (...args: Array) => any + ? React.ReactNode + : TNode extends object + ? ValidateCompositeComponentObjectResult + : React.ReactNode + +export type ValidateCompositeComponentPromiseResult = + TPromise extends Promise + ? Promise> + : never + +export type ValidateCompositeComponentObjectResult = { + [TKey in keyof TObject]: ValidateCompositeComponentResult +} + +export type CompositeComponentResult = CompositeComponentBuilder< + TComp, + LooseAsyncReturnType +> + +export type CompositeComponentBuilder = + TReturn extends React.ReactNode + ? CompositeComponent + : { + [TKey in keyof TReturn]: CompositeComponentBuilder + } + +export interface CompositeComponent { + '~types': { + props: CompositeComponentProps + return: TReturn + } + + [SERVER_COMPONENT_STREAM]?: ServerComponentStream + + /** + * Root decoded tree getter. + */ + [RSC_PROXY_GET_TREE]?: () => unknown + /** + * Nested selection path (eg ['content','Stats']). + * Used by to render a sub-tree. + */ + [RSC_PROXY_PATH]?: Array + /** + * CSS hrefs collected from the RSC stream. + * Can be used for preloading in or emitting 103 Early Hints. + */ + [SERVER_COMPONENT_CSS_HREFS]?: ReadonlySet + + /** + * JS hrefs collected from the RSC stream. + * Emitted as modulepreload links only if the decoded tree is rendered in SSR. + */ + [SERVER_COMPONENT_JS_PRELOADS]?: ReadonlySet + + /** + * Dev-only: async stream of slot usage preview events. + * Used by devtools to show slot names and previewed call args without + * buffering/draining the Flight stream. + */ + [RSC_SLOT_USAGES_STREAM]?: ReadableStream +} + +export type ValidateRenderableServerComponent = + ValidateServerComponentResult + +export type RenderableServerComponentBuilder = T extends React.ReactNode + ? RenderableServerComponent + : { [TKey in keyof T]: RenderableServerComponentBuilder } + +export type RenderableServerComponent = TNode & + RenderableServerComponentAttributes + +export interface RenderableServerComponentAttributes { + '~types': { + node: TNode + } + [SERVER_COMPONENT_STREAM]: ServerComponentStream + [RENDERABLE_RSC]: true +} + +declare module '@tanstack/router-core' { + export interface SerializableExtensions { + CompositeComponent: AnyCompositeComponent + RenderableServerComponent: AnyRenderableServerComponent + } +} + +export type AnyCompositeComponent = CompositeComponent + +export type AnyRenderableServerComponent = + RenderableServerComponentAttributes diff --git a/packages/react-start-rsc/src/SlotContext.tsx b/packages/react-start-rsc/src/SlotContext.tsx new file mode 100644 index 0000000000..a3d0f867a1 --- /dev/null +++ b/packages/react-start-rsc/src/SlotContext.tsx @@ -0,0 +1,42 @@ +'use client' + +import { createContext, use } from 'react' +import type { SlotImplementations } from './types' + +export interface SlotContextValue { + implementations: SlotImplementations + strict: boolean +} + +const SlotContext = createContext(null) + +/** + * Hook to access slot implementations from within ClientSlot. + */ +export function useSlotContext(): SlotContextValue | null { + return use(SlotContext) +} + +export interface SlotProviderProps { + implementations: SlotImplementations + strict?: boolean + children?: React.ReactNode +} + +/** + * SlotProvider - makes slot implementations available to ClientSlot components. + * + * Must wrap the decoded RSC content so that ClientSlot components can + * access their slot implementations via React Context. + */ +export function SlotProvider({ + implementations, + strict, + children, +}: SlotProviderProps) { + return ( + + {children} + + ) +} diff --git a/packages/react-start-rsc/src/awaitLazyElements.ts b/packages/react-start-rsc/src/awaitLazyElements.ts new file mode 100644 index 0000000000..a0d8c5774e --- /dev/null +++ b/packages/react-start-rsc/src/awaitLazyElements.ts @@ -0,0 +1,94 @@ +import { ReactElement, ReactLazy, ReactSuspense } from './reactSymbols' + +/** + * Optional callback for collecting CSS hrefs during tree traversal. + * Only called server-side when processing + */ +export type CssHrefCollector = (href: string) => void + +/** + * Yields pending lazy element payloads from a tree, stopping at Suspense boundaries. + * Also collects CSS hrefs from elements. + */ +function* findPendingLazyPayloads( + obj: unknown, + seen = new Set(), + cssCollector?: CssHrefCollector, +): Generator> { + if (!obj || typeof obj !== 'object') return + if (seen.has(obj)) return + seen.add(obj) + + const el = obj as any + + // Stop at Suspense boundaries - lazy elements inside are intentionally deferred + if (el.$$typeof === ReactElement && el.type === ReactSuspense) { + return + } + + // Collect CSS hrefs from + // The active RSC bundler adapter injects these for CSS module imports + if ( + el.$$typeof === ReactElement && + el.type === 'link' && + el.props?.rel === 'stylesheet' + ) { + let cssHref: string | undefined + if ('data-rsc-css-href' in el.props) { + cssHref = el.props.href + } + if (cssHref && cssCollector) { + cssCollector(cssHref) + } + } + + // Yield pending lazy element payload + if (el.$$typeof === ReactLazy) { + const payload = el._payload + if ( + payload && + typeof payload === 'object' && + (payload.status === 'pending' || payload.status === 'blocked') && + typeof payload.then === 'function' + ) { + yield payload + } + } + + // Recurse into children + if (Array.isArray(obj)) { + for (const item of obj) { + yield* findPendingLazyPayloads(item, seen, cssCollector) + } + } else { + for (const key of Object.keys(obj)) { + if (key !== '_owner' && key !== '_store') { + yield* findPendingLazyPayloads(el[key], seen, cssCollector) + } + } + } +} + +/** + * Wait for all lazy elements in a tree to be resolved. + * This ensures client component chunks are fully loaded before rendering, + * preventing Suspense boundaries from flashing during SWR navigation. + * + * Also collects CSS hrefs from + * elements for preloading in . + * + * @param tree - The tree to process + * @param cssCollector - Optional callback to collect CSS hrefs (server-only) + */ +export async function awaitLazyElements( + tree: unknown, + cssCollector?: CssHrefCollector, +): Promise { + for (const payload of findPendingLazyPayloads( + tree, + new Set(), + cssCollector, + )) { + await Promise.resolve(payload).catch(() => {}) + } +} diff --git a/packages/react-start-rsc/src/createCompositeComponent.stub.ts b/packages/react-start-rsc/src/createCompositeComponent.stub.ts new file mode 100644 index 0000000000..8dd058ae15 --- /dev/null +++ b/packages/react-start-rsc/src/createCompositeComponent.stub.ts @@ -0,0 +1,20 @@ +import type { + CompositeComponentResult, + ValidateCompositeComponent, +} from './ServerComponentTypes' + +/** + * Client stub for createCompositeComponent. + * + * This function should never be called at runtime on the client. + * It exists only to satisfy bundler imports in client bundles. + * The real implementation only runs inside server functions. + */ +export function createCompositeComponent( + _component: ValidateCompositeComponent, +): Promise> { + throw new Error( + 'createCompositeComponent cannot be called on the client. ' + + 'This function should only be called inside a server function or route loader.', + ) +} diff --git a/packages/react-start-rsc/src/createCompositeComponent.ts b/packages/react-start-rsc/src/createCompositeComponent.ts new file mode 100644 index 0000000000..02a840dc64 --- /dev/null +++ b/packages/react-start-rsc/src/createCompositeComponent.ts @@ -0,0 +1,341 @@ +import { createElement } from 'react' +import { renderToReadableStream } from 'virtual:tanstack-rsc-runtime' +import { getStartContext } from '@tanstack/start-storage-context' +import { sanitizeSlotArgs } from './slotUsageSanitizer' +import { ReplayableStream } from './ReplayableStream' +import { ClientSlot } from './ClientSlot' +import { + RSC_SLOT_USAGES_STREAM, + SERVER_COMPONENT_STREAM, +} from './ServerComponentTypes' +import { createRscCssEnvelope } from './rscCssEnvelope' +import type { + AnyCompositeComponent, + CompositeComponentResult, + RscSlotUsageEvent, + ServerComponentStream, + ValidateCompositeComponent, +} from './ServerComponentTypes' +import type { RscCssEnvelopeOptions } from './rscCssEnvelope' + +import './rscSsrHandler' // Import for global declaration side effect + +/** + * Creates a composite server component with slot support. + * + * Supports returning: + * - A ReactNode directly + * - An object structure with ReactNodes: accessed as `src.Foo` + * - Nested structures: accessed as `src.x.Bar` + * + * Props that are functions become slots - they render as ClientSlot placeholders + * in the RSC output, filled in by the consumer with actual implementations. + * + * The returned value is NOT directly renderable. Use ``. + * + * @example + * ```tsx + * const src = await createCompositeComponent((props) => ( + *
    + *
    {props.header('Dashboard')}
    + *
    {props.children}
    + *
    + * )) + * + * // In route component + * return ( + *

    {title}

    }> + *

    Main content

    + *
    + * ) + * ``` + */ +export async function createCompositeComponent( + component: ValidateCompositeComponent, + options?: RscCssEnvelopeOptions, +): Promise> { + const isDev = process.env.NODE_ENV === 'development' + + // Dev-only: stream slot usage events (slot + raw args) + const slotUsagesEmitter = isDev + ? createReadableStreamEmitter() + : null + + // Create a wrapper component that will be rendered inside React's Flight context. + // This ensures React.cache works properly since the component is called during + // renderToReadableStream's render phase, not before it. + const { proxy: proxyProps } = createSlotProxy<{}>({ + onSlotCall: slotUsagesEmitter + ? (name, args) => { + const sanitizedArgs = sanitizeSlotArgs(args) + slotUsagesEmitter.emit({ + slot: name, + args: sanitizedArgs.length ? sanitizedArgs : undefined, + }) + } + : undefined, + }) + + // Wrapper that renders the user's component inside Flight render context + async function ServerComponentWrapper() { + return createRscCssEnvelope( + await (component as React.FC)(proxyProps), + options, + ) + } + + // Render using createElement so React calls our component during Flight rendering + // This is critical for React.cache to work - the component must be invoked + // during renderToReadableStream's execution, not before + const flightStream = renderToReadableStream( + createElement(ServerComponentWrapper as any), + ) + + // Check if this is an SSR request (router) or a direct server function call + const ctx = getStartContext({ throwIfNotFound: false }) + const isRouterRequest = ctx?.handlerType === 'router' + const ssrHandler = globalThis.__RSC_SSR__ + + // SSR path: buffer stream for replay, pre-decode for synchronous rendering + if (isRouterRequest && ssrHandler) { + const signal = ctx.request.signal + const stream = new ReplayableStream(flightStream, { signal }) + + // Pre-decode during loader phase for synchronous SSR rendering + const decoded = await ssrHandler.decode(stream) + + // For SSR we know decode fully consumed the Flight stream. + slotUsagesEmitter?.close() + + return ssrHandler.createCompositeProxy( + stream, + decoded, + slotUsagesEmitter?.stream, + ) as CompositeComponentResult + } + + // Server function call path: + // The serialization adapter will stream to the client. + const monitoredFlightStream = + isDev && slotUsagesEmitter + ? wrapReadableStream(flightStream, { + onDone: () => { + slotUsagesEmitter.close() + }, + onCancel: () => { + slotUsagesEmitter.close() + }, + onError: () => { + slotUsagesEmitter.close() + }, + }) + : flightStream + + return createCompositeHandle(monitoredFlightStream, { + slotUsagesStream: slotUsagesEmitter?.stream, + }) as CompositeComponentResult +} + +/** + * Creates a composite handle for server function responses. + * No proxy needed - the client will decode and create its own proxy. + */ +function createCompositeHandle( + flightStream: ReadableStream, + options?: { + slotUsagesStream?: ReadableStream + }, +): AnyCompositeComponent { + // Simple single-use stream wrapper. For server function calls, the stream + // is consumed exactly once by the serialization adapter for transport. + const streamWrapper: ServerComponentStream = { + createReplayStream: () => flightStream, + } + + // Create a stub function with the stream attached for serialization. + // This will never be rendered directly - it goes through serialization + // which extracts the stream and sends it to the client. + const stub = function CompositeComponentStub(): never { + throw new Error( + 'CompositeComponent from server function cannot be rendered on server. ' + + 'It should be serialized and sent to the client.', + ) + } + + ;(stub as any)[SERVER_COMPONENT_STREAM] = streamWrapper + // Note: RENDERABLE_RSC is not set (or implicitly false), indicating this is a composite component + + if (options?.slotUsagesStream) { + ;(stub as any)[RSC_SLOT_USAGES_STREAM] = options.slotUsagesStream + } + + return stub as unknown as AnyCompositeComponent +} + +/** + * Base slot props type - functions that become ClientSlot placeholders + */ +interface SlotPropsBase { + [key: string]: + | ((...args: Array) => React.ReactNode) + | React.ReactNode + | undefined + children?: React.ReactNode +} + +interface SlotProxyResult { + proxy: TSlotProps & SlotPropsBase +} + +/** + * Proxy that turns property access into ClientSlot renders. + * Also tracks accessed slot names for devtools. + */ +function createSlotProxy(options?: { + onSlotCall?: (name: string, args: Array) => void +}): SlotProxyResult { + const cache = new Map) => React.ReactNode>() + + const proxy = new Proxy({} as TSlotProps & SlotPropsBase, { + get(_target, prop) { + if (prop === 'then' || typeof prop !== 'string') return undefined + + if (prop === 'children') { + options?.onSlotCall?.('children', []) + return createElement(ClientSlot, { slot: 'children', args: [] }) + } + + let fn = cache.get(prop) + if (!fn) { + fn = (...args: Array) => { + options?.onSlotCall?.(prop, args) + return createElement(ClientSlot, { slot: prop, args }) + } + cache.set(prop, fn) + } + return fn + }, + }) + + return { + proxy, + } +} + +function createReadableStreamEmitter(): { + stream: ReadableStream + emit: (value: T) => void + close: () => void +} { + let closed = false + const queue: Array = [] + let controller: ReadableStreamDefaultController | null = null + + const stream = new ReadableStream({ + start(ctrl) { + controller = ctrl + for (const value of queue) { + try { + ctrl.enqueue(value) + } catch { + // Ignore + } + } + queue.length = 0 + if (closed) { + try { + ctrl.close() + } catch { + // Ignore + } + } + }, + cancel() { + closed = true + controller = null + queue.length = 0 + }, + }) + + const emit = (value: T) => { + if (closed) return + if (!controller) { + queue.push(value) + return + } + try { + controller.enqueue(value) + } catch { + // Ignore + } + } + + const close = () => { + if (closed) return + closed = true + if (controller) { + try { + controller.close() + } catch { + // Ignore + } + controller = null + } + } + + return { stream, emit, close } +} + +function wrapReadableStream( + source: ReadableStream, + handlers: { + onDone?: () => void + onCancel?: () => void + onError?: () => void + }, +): ReadableStream { + const reader = source.getReader() + let finished = false + + const finish = () => { + if (finished) return + finished = true + handlers.onDone?.() + try { + reader.releaseLock() + } catch { + // Ignore + } + } + + return new ReadableStream({ + async pull(controller) { + try { + const { value, done } = await reader.read() + if (done) { + controller.close() + finish() + return + } + controller.enqueue(value) + } catch (err) { + try { + controller.error(err) + } catch { + // Ignore + } + handlers.onError?.() + finish() + } + }, + async cancel(reason) { + handlers.onCancel?.() + try { + await reader.cancel(reason) + } catch { + // Ignore + } + finish() + }, + }) +} diff --git a/packages/react-start-rsc/src/createRscProxy.tsx b/packages/react-start-rsc/src/createRscProxy.tsx new file mode 100644 index 0000000000..e5e1481848 --- /dev/null +++ b/packages/react-start-rsc/src/createRscProxy.tsx @@ -0,0 +1,294 @@ +'use client' + +import { createElement } from 'react' +import { RscNodeRenderer } from './RscNodeRenderer' +import { + RENDERABLE_RSC, + RSC_PROXY_GET_TREE, + RSC_PROXY_PATH, + RSC_SLOT_USAGES, + RSC_SLOT_USAGES_STREAM, + SERVER_COMPONENT_CSS_HREFS, + SERVER_COMPONENT_JS_PRELOADS, + SERVER_COMPONENT_STREAM, +} from './ServerComponentTypes' +import type { RscSlotUsageEvent } from './ServerComponentTypes' + +export interface RscProxyOptions { + stream?: unknown // The stream to attach for serialization + cssHrefs?: ReadonlySet // CSS hrefs collected from the RSC stream + jsPreloads?: ReadonlySet // JS hrefs collected from the RSC stream + renderable?: boolean // If true, proxy masquerades as React element + slotUsagesStream?: ReadableStream // Dev only: slot usage event stream +} + +/** + * Creates a recursive Proxy for RSC data. + * + * If `renderable: true`, returns a React element that can be rendered as `{data}`. + * The element also has proxy-like behavior for nested access like `data.foo.bar`. + * + * If `renderable: false` (default), the proxy is NOT directly renderable and + * must be used with ``. + */ +export function createRscProxy( + getTree: () => T, + options: RscProxyOptions = {}, +): any { + if (options.renderable) { + // For renderable mode, create a real React element with proxy access + return createRenderableElement( + getTree, + [], + options.stream, + options.cssHrefs, + options.jsPreloads, + ) + } + let slotUsages: Array | undefined = undefined + + if ( + process.env.NODE_ENV === 'development' && + typeof window !== 'undefined' && + options.slotUsagesStream + ) { + slotUsages = [] + void consumeSlotUsages(options.slotUsagesStream, slotUsages) + } + + // Non-renderable mode: plain proxy + return createRscProxyWithPath( + getTree, + [], + options.stream, + options.cssHrefs, + options.jsPreloads, + slotUsages, + options.slotUsagesStream, + ) +} + +/** + * Creates a React element that's also a Proxy for nested access. + * This is used by renderable RSCs so they work as both {data} and {data.foo.bar}. + */ +type CreateProxyOptions = { + getTree: () => unknown + path: Array + stream: unknown | undefined + cssHrefs: ReadonlySet | undefined + jsPreloads: ReadonlySet | undefined + renderable: boolean + slotUsages: Array | undefined + slotUsagesStream: ReadableStream | undefined +} + +const UNHANDLED = Symbol('tanstack.rsc.proxy.unhandled') + +function handleProxyTrap( + kind: 'get' | 'has', + prop: PropertyKey, + options: CreateProxyOptions, +): unknown | boolean | typeof UNHANDLED { + switch (prop) { + // Seroval (>=1.5) uses string sentinels and `in` checks for internal types. + // These proxies must never look like streams/sequences. + case '__SEROVAL_STREAM__': + case '__SEROVAL_SEQUENCE__': + return kind === 'get' ? undefined : false + + // Seroval >=1.5 also checks iterability via `Symbol.iterator in value`. + case Symbol.iterator: + case Symbol.asyncIterator: + return kind === 'get' ? undefined : false + + // Our proxy branding/properties + case SERVER_COMPONENT_STREAM: + return kind === 'get' ? options.stream : options.stream !== undefined + case SERVER_COMPONENT_CSS_HREFS: + return kind === 'get' ? options.cssHrefs : options.cssHrefs !== undefined + case SERVER_COMPONENT_JS_PRELOADS: + return kind === 'get' + ? options.jsPreloads + : options.jsPreloads !== undefined + case RSC_PROXY_GET_TREE: + return kind === 'get' ? options.getTree : true + case RSC_PROXY_PATH: + return kind === 'get' ? options.path : true + case RENDERABLE_RSC: + return kind === 'get' ? options.renderable : true + case RSC_SLOT_USAGES: + return kind === 'get' + ? options.slotUsages + : options.slotUsages !== undefined + + case RSC_SLOT_USAGES_STREAM: + return kind === 'get' + ? options.slotUsagesStream + : options.slotUsagesStream !== undefined + + // Avoid promise-like checks + case 'then': + return kind === 'get' ? undefined : UNHANDLED + + // Avoid breaking primitive coercion (eg String(proxy)). + // Without these, nested-selection proxies can shadow these keys and + // cause `Cannot convert object to primitive value` errors. + case 'toString': + return kind === 'get' ? Object.prototype.toString : UNHANDLED + case 'valueOf': + return kind === 'get' ? Object.prototype.valueOf : UNHANDLED + case 'constructor': + return kind === 'get' ? Object : UNHANDLED + } + + // Non-renderable proxies claim all string keys exist for nested selection, + // but symbol presence checks should be accurate. + if (typeof prop === 'symbol') { + return kind === 'get' ? undefined : false + } + + return UNHANDLED +} + +function createRscProxyInternal(options: CreateProxyOptions): any { + // Per-proxy cache so repeated property access is referentially stable. + const childCache = new Map() + + const getChild = (key: string) => { + const cached = childCache.get(key) + if (cached) return cached + + const next = createRscProxyInternal({ + ...options, + path: [...options.path, key], + }) + childCache.set(key, next) + return next + } + + const dataProxy = options.renderable + ? createRscProxyInternal({ ...options, renderable: false }) + : undefined + + // Use a React element (renderable) or plain object (non-renderable) as Proxy target. + const proxyTarget = options.renderable + ? createElement(RscNodeRenderer, { data: dataProxy }) + : ({} as any) + + return new Proxy(proxyTarget, { + get(target, prop) { + const handled = handleProxyTrap('get', prop, options) + if (handled !== UNHANDLED) return handled + + if (options.renderable) { + // Proxy invariants: if target has a non-configurable, read-only property, + // we must return the *exact* value for that property. + if (prop === 'props') { + return target.props + } + + if (prop === 'data') { + return dataProxy + } + + if (prop in target) { + return target[prop] + } + } + + return getChild(String(prop)) + }, + + has(target, prop) { + const handled = handleProxyTrap('has', prop, options) + if (handled !== UNHANDLED) return handled as boolean + + if (options.renderable) { + if (prop in target) return true + if (typeof prop === 'string') return true + return false + } + + // Allow any property access for nested selection. + return true + }, + + getPrototypeOf(target) { + return options.renderable + ? Object.getPrototypeOf(target) + : Object.prototype + }, + + getOwnPropertyDescriptor(target, prop) { + return options.renderable + ? Object.getOwnPropertyDescriptor(target, prop) + : undefined + }, + + ownKeys(target) { + return options.renderable ? Reflect.ownKeys(target) : [] + }, + }) +} + +/** + * Creates a React element that's also a Proxy for nested access. + * This is used by renderable RSCs so they work as both {data} and {data.foo.bar}. + */ +function createRenderableElement( + getTree: () => unknown, + path: Array, + stream: unknown | undefined, + cssHrefs: ReadonlySet | undefined, + jsPreloads: ReadonlySet | undefined, +): any { + return createRscProxyInternal({ + getTree, + path, + stream, + cssHrefs, + jsPreloads, + renderable: true, + slotUsages: undefined, + slotUsagesStream: undefined, + }) +} + +function createRscProxyWithPath( + getTree: () => unknown, + path: Array, + stream: unknown | undefined, + cssHrefs: ReadonlySet | undefined, + jsPreloads: ReadonlySet | undefined, + slotUsages: Array | undefined, + slotUsagesStream: ReadableStream | undefined, +): any { + return createRscProxyInternal({ + getTree, + path, + stream, + cssHrefs, + jsPreloads, + renderable: false, + slotUsages, + slotUsagesStream, + }) +} + +async function consumeSlotUsages( + stream: ReadableStream, + slotUsages: Array, +): Promise { + try { + const reader = stream.getReader() + for (;;) { + const { value, done } = await reader.read() + if (done) break + if (!value.slot) continue + slotUsages.push(value) + } + } catch { + // Ignore - dev-only best effort + } +} diff --git a/packages/react-start-rsc/src/createServerComponentFromStream.ts b/packages/react-start-rsc/src/createServerComponentFromStream.ts new file mode 100644 index 0000000000..2616b96f44 --- /dev/null +++ b/packages/react-start-rsc/src/createServerComponentFromStream.ts @@ -0,0 +1,138 @@ +'use client' + +import { use } from 'react' +import { trackPostProcessPromise } from '@tanstack/start-client-core' +import { createFromReadableStream as browserDecode } from 'virtual:tanstack-rsc-browser-decode' + +import { awaitLazyElements } from './awaitLazyElements' +import { createRscProxy } from './createRscProxy' +import { unwrapRscCssEnvelope } from './rscCssEnvelope' +import type { + AnyCompositeComponent, + RscSlotUsageEvent, + ServerComponentStream, +} from './ServerComponentTypes' + +type StreamDecodeOptions = { + cssHrefs?: Iterable + jsPreloads?: Iterable +} + +/** + * Creates a renderable RSC proxy from a raw Flight stream. + * Client-side only - used by the client serialization adapter for `renderServerComponent`. + * + * Returns a Proxy that: + * - Can be rendered directly as `{data}` in JSX + * - Supports nested access: `{data.foo.bar}` + * - Masquerades as a React element + */ +export function createRenderableFromStream( + stream: ReadableStream, + options?: StreamDecodeOptions, +): any { + const { getTree, streamWrapper, cssHrefs, jsPreloads } = setupStreamDecode( + stream, + options, + ) + + return createRscProxy(getTree, { + stream: streamWrapper, + cssHrefs, + jsPreloads, + renderable: true, + }) +} + +/** + * Creates a composite RSC proxy from a raw Flight stream. + * Client-side only - used by the client serialization adapter for `createCompositeComponent`. + * + * Returns a Proxy that: + * - NOT directly renderable + * - Supports nested access: `src.foo.bar` + * - Must be rendered via `` + */ +export function createCompositeFromStream( + stream: ReadableStream, + options?: { + slotUsagesStream?: ReadableStream + } & StreamDecodeOptions, +): AnyCompositeComponent { + const { getTree, streamWrapper, cssHrefs, jsPreloads } = setupStreamDecode( + stream, + options, + ) + + return createRscProxy(getTree, { + stream: streamWrapper, + cssHrefs, + jsPreloads, + renderable: false, + slotUsagesStream: options?.slotUsagesStream, + }) +} + +/** + * Shared stream decode setup for both renderable and composite. + */ +function setupStreamDecode( + stream: ReadableStream, + options?: StreamDecodeOptions, +): { + getTree: () => unknown + streamWrapper: ServerComponentStream + cssHrefs: Set + jsPreloads: Set | undefined +} { + const cssHrefs = new Set(options?.cssHrefs ?? []) + const jsPreloads = options?.jsPreloads + ? new Set(options.jsPreloads) + : undefined + const shouldDeferDecode = cssHrefs.size > 0 || !!jsPreloads?.size + + // Synchronous cache for the decoded tree. + let cachedTree: unknown = undefined + let cacheReady = false + let transformedTreePromise: Promise | undefined + + const startDecode = () => { + if (!transformedTreePromise) { + // Promise for the tree with lazy elements awaited. + transformedTreePromise = Promise.resolve(browserDecode(stream)).then( + async (result) => { + await awaitLazyElements(result, (href) => { + cssHrefs.add(href) + }) + cachedTree = unwrapRscCssEnvelope(result) + cacheReady = true + return cachedTree + }, + ) + + // Track the lazy element loading - prevents flash for RPC/RSC fetches. + trackPostProcessPromise(transformedTreePromise) + } + + return transformedTreePromise + } + + if (!shouldDeferDecode) { + // Start decoding eagerly during deserialization for non-SSR streams. + startDecode() + } + + const streamWrapper: ServerComponentStream = { + createReplayStream: () => stream, + } + + const getTree = () => { + if (cacheReady) return cachedTree + // eslint-disable-next-line react-hooks/rules-of-hooks + return use(startDecode()) + } + + return { getTree, streamWrapper, cssHrefs, jsPreloads } +} +// Legacy export for backwards compatibility during migration +export const createServerComponentFromStream = createCompositeFromStream diff --git a/packages/react-start-rsc/src/entry/rsc.tsx b/packages/react-start-rsc/src/entry/rsc.tsx new file mode 100644 index 0000000000..be20ea26af --- /dev/null +++ b/packages/react-start-rsc/src/entry/rsc.tsx @@ -0,0 +1,23 @@ +/** + * Shared RSC (React Server Components) entry point. + * + * This file exports the functions needed for the active RSC environment: + * - getServerFnById: Resolves server functions by their encoded ID + * - render: Renders a React node to an RSC Flight stream + */ + +import { renderToReadableStream } from 'virtual:tanstack-rsc-runtime' +import type React from 'react' + +// Re-export getServerFnById from the virtual module which handles both dev and production +// In dev: dynamic import with base64url-decoded file path +// In production: manifest-based lookup with bundled chunks +export { getServerFnById } from '#tanstack-start-server-fn-resolver' + +/** + * Renders a React node to an RSC Flight stream. + * Used internally for streaming server component output. + */ +export function render(node: React.ReactNode): ReadableStream { + return renderToReadableStream(node) +} diff --git a/packages/react-start-rsc/src/entry/virtual-modules.d.ts b/packages/react-start-rsc/src/entry/virtual-modules.d.ts new file mode 100644 index 0000000000..00f2a2ee02 --- /dev/null +++ b/packages/react-start-rsc/src/entry/virtual-modules.d.ts @@ -0,0 +1,12 @@ +// Type declarations for virtual modules used in RSC entry +// These modules are provided by the active bundler adapter at runtime + +declare module '#tanstack-start-server-fn-resolver' { + export type ServerFnLookupAccess = { origin: 'client' } | { origin: 'server' } + + export type ServerFn = (...args: Array) => Promise + export function getServerFnById( + id: string, + access: ServerFnLookupAccess, + ): Promise +} diff --git a/packages/react-start-rsc/src/flight.rsc.ts b/packages/react-start-rsc/src/flight.rsc.ts new file mode 100644 index 0000000000..8fabd523e2 --- /dev/null +++ b/packages/react-start-rsc/src/flight.rsc.ts @@ -0,0 +1,17 @@ +/** + * Low-level Flight stream API for RSC (React Server Components) environment. + * + * This exports renderToReadableStream which generates a Flight stream from + * React elements. Only available in RSC context (react-server condition). + * + * @example + * ```tsx + * import { renderToReadableStream } from '@tanstack/react-start/rsc' + * + * const stream = renderToReadableStream() + * return new Response(stream, { + * headers: { 'Content-Type': 'text/x-component' } + * }) + * ``` + */ +export { renderToReadableStream } from 'virtual:tanstack-rsc-runtime' diff --git a/packages/react-start-rsc/src/flight.stub.ts b/packages/react-start-rsc/src/flight.stub.ts new file mode 100644 index 0000000000..872eec6f10 --- /dev/null +++ b/packages/react-start-rsc/src/flight.stub.ts @@ -0,0 +1,15 @@ +/** + * Client stub for renderToReadableStream. + * + * This function should never be called at runtime on the client. + * It exists only to provide types for bundler imports in client bundles. + * The real implementation only runs inside RSC context (server functions). + */ +export function renderToReadableStream( + _node: React.ReactNode, +): ReadableStream { + throw new Error( + 'renderToReadableStream cannot be called on the client. ' + + 'This function should only be called inside RSC context (server functions).', + ) +} diff --git a/packages/react-start-rsc/src/flight.ts b/packages/react-start-rsc/src/flight.ts new file mode 100644 index 0000000000..1639120322 --- /dev/null +++ b/packages/react-start-rsc/src/flight.ts @@ -0,0 +1,68 @@ +/** + * Low-level Flight stream APIs for decoding RSC streams. + * + * These functions provide direct access to RSC Flight stream decoding, + * allowing advanced use cases like: + * - Server functions returning raw Flight Response + * - API routes streaming Flight payloads + * - Custom Flight stream handling via RawStream + * + * `createFromReadableStream` works in both SSR and browser contexts. + * `createFromFetch` is browser-only. + * + * NOTE: Dynamic imports keep decode initialisation runtime-specific. The + * concrete implementation comes from bundler-owned virtual modules. + */ + +import { + createClientOnlyFn, + createIsomorphicFn, +} from '@tanstack/start-fn-stubs' + +/** + * Decode a Flight stream into React elements. + * Works in both SSR and browser contexts. + * + * @example + * ```tsx + * const rawStream = await getRscRawStream() + * const tree = await createFromReadableStream(rawStream) + * return <>{tree} + * ``` + */ +export const createFromReadableStream = createIsomorphicFn() + .server( + async (stream: ReadableStream): Promise => { + const { createFromReadableStream: decode } = + await import('virtual:tanstack-rsc-ssr-decode') + return decode(stream) as React.ReactNode + }, + ) + .client( + async (stream: ReadableStream): Promise => { + const { createFromReadableStream: decode } = + await import('virtual:tanstack-rsc-browser-decode') + return decode(stream) + }, + ) + +/** + * Decode a Flight stream from a fetch Response. + * Browser only - will throw if called on the server. + * + * @example + * ```tsx + * // From server function returning raw Response + * const tree = await createFromFetch(getFlightResponse()) + * + * // From API route + * const tree = await createFromFetch(fetch('/api/rsc-flight')) + * ``` + */ +export const createFromFetch = createClientOnlyFn( + async (fetchPromise: Promise): Promise => { + const { createFromFetch: decode } = + await import('virtual:tanstack-rsc-browser-decode') + return decode(fetchPromise) + }, +) diff --git a/packages/react-start-rsc/src/global.d.ts b/packages/react-start-rsc/src/global.d.ts new file mode 100644 index 0000000000..258d41eb5c --- /dev/null +++ b/packages/react-start-rsc/src/global.d.ts @@ -0,0 +1,99 @@ +/// + +declare module '@rspack/core/rsc/ssr' { + export function setOnClientReference( + callback: + | ((reference: { + id: string + deps: { js: Array; css: Array } + runtime: 'rsbuild' + }) => void) + | null + | undefined, + ): void + export function getManifest(): { + moduleCssFiles?: Record> + [key: string]: unknown + } +} + +declare module '@rspack/core/rsc/browser' { + export function getManifest(): { + moduleCssFiles?: Record> + [key: string]: unknown + } +} + +/** + * Type declarations for virtual:tanstack-rsc-runtime + * + * This virtual module is provided by the active Start bundler adapter + * and re-exports RSC runtime functions from that adapter's Flight runtime. + * + * Using a virtual module allows the imports to be resolved at runtime within + * the correct server environment context (react-server conditions). + */ +declare module 'virtual:tanstack-rsc-runtime' { + export function renderToReadableStream( + data: T, + options?: object, + ): ReadableStream + export function createFromReadableStream( + stream: ReadableStream, + options?: object, + ): Promise + export function createTemporaryReferenceSet(): object + export function decodeReply( + body: string | FormData, + options?: object, + ): Promise + export function loadServerAction(id: string): Promise<(...args: any) => any> + export function decodeAction( + body: FormData, + serverManifest?: unknown, + ): Promise<() => T> + export function decodeFormState( + actionResult: T, + body: FormData, + serverManifest?: unknown, + ): Promise +} + +declare module 'virtual:tanstack-rsc-browser-decode' { + export function createFromReadableStream( + stream: ReadableStream, + options?: object, + ): Promise + export function createFromFetch( + response: Promise, + ): Promise +} + +declare module 'virtual:tanstack-rsc-ssr-decode' { + export function setOnClientReference( + callback: + | ((reference: { + id: string + deps: { js: Array; css: Array } + runtime?: 'rsbuild' + }) => void) + | undefined, + ): void + export function createFromReadableStream( + stream: ReadableStream, + options?: object, + ): Promise +} + +/** + * Type declarations for virtual:tanstack-rsc-hmr + * + * This virtual module is provided by the active Start bundler adapter + * and sets up the RSC HMR listener in dev mode. It listens for 'rsc:update' + * events and invalidates the router to refetch server components. + * + * In production builds, this module is empty. + */ +declare module 'virtual:tanstack-rsc-hmr' { + export function setupRscHmr(): void +} diff --git a/packages/react-start-rsc/src/index.rsc.ts b/packages/react-start-rsc/src/index.rsc.ts new file mode 100644 index 0000000000..6873fc4a0e --- /dev/null +++ b/packages/react-start-rsc/src/index.rsc.ts @@ -0,0 +1,31 @@ +// Server-side exports (react-server condition) +// This file is used when importing from RSC (React Server Components) context + +// Types are always available +export type { + AnyCompositeComponent, + AnyRenderableServerComponent, + RenderableServerComponent, + RenderableServerComponentAttributes, + RenderableServerComponentBuilder, +} from './ServerComponentTypes' + +// New API: renderServerComponent - renders element to renderable proxy +export { renderServerComponent } from './renderServerComponent.js' + +// New API: createCompositeComponent - creates composite with slot support +export { createCompositeComponent } from './createCompositeComponent.js' + +// Renderer for composite RSC data (client/SSR) +export { CompositeComponent } from './CompositeComponent.js' + +// Low-level Flight stream API (RSC only) +export { renderToReadableStream } from './flight.rsc.js' + +// Low-level Flight stream APIs (also available in RSC for decode operations) +export { createFromReadableStream, createFromFetch } from './flight' + +// Note: rscSerializationAdapter is intentionally NOT exported here. +// It uses createSerializationAdapter from react-router which is marked as +// client-only in RSC environment. The adapter is only needed by SSR/client +// for serializing/deserializing server components, not by RSC itself. diff --git a/packages/react-start-rsc/src/index.ts b/packages/react-start-rsc/src/index.ts new file mode 100644 index 0000000000..f70e324082 --- /dev/null +++ b/packages/react-start-rsc/src/index.ts @@ -0,0 +1,32 @@ +// Default exports (used by client bundles and SSR) +// This file is used when importing outside of RSC (React Server Components) context + +// Types are always available +export type { + AnyCompositeComponent, + AnyRenderableServerComponent, + RenderableServerComponent, + RenderableServerComponentAttributes, + RenderableServerComponentBuilder, +} from './ServerComponentTypes' + +// CSS hrefs symbol for type-safe access +export { SERVER_COMPONENT_CSS_HREFS } from './ServerComponentTypes' + +// Stubs for RSC-only functions - throw if called outside RSC context +export { renderServerComponent } from './renderServerComponent.stub.js' +export { createCompositeComponent } from './createCompositeComponent.stub.js' + +// Renderer for composite RSC data (client/SSR) +export { CompositeComponent } from './CompositeComponent.js' + +// Low-level Flight stream APIs (client/SSR) +export { createFromReadableStream, createFromFetch } from './flight' + +// Stub for renderToReadableStream - throws if called outside RSC context +export { renderToReadableStream } from './flight.stub.js' + +// Note: rscSerializationAdapter is intentionally NOT exported here. +// It imports virtual:tanstack-rsc-hmr which is client-only (not available in SSR). +// Import directly from '@tanstack/react-start-rsc/serialization.client' or +// '@tanstack/react-start-rsc/serialization.server' as needed. diff --git a/packages/react-start-rsc/src/plugin/rscCssTransform.ts b/packages/react-start-rsc/src/plugin/rscCssTransform.ts new file mode 100644 index 0000000000..15b882ccd7 --- /dev/null +++ b/packages/react-start-rsc/src/plugin/rscCssTransform.ts @@ -0,0 +1,150 @@ +import type { + StartCompilerImportTransform, + StartCompilerTransformContext, +} from '@tanstack/start-plugin-core' + +const TSS_SERVERFN_SPLIT_PARAM = 'tss-serverfn-split' +const RSC_CSS_OPTIONS_KEY = '__tanstackStartRscCss' + +type BabelTypes = StartCompilerTransformContext['types'] +type BabelExpression = ReturnType< + StartCompilerTransformContext['parseExpression'] +> + +type RscCssTransformKind = + | 'renderServerComponent' + | 'createCompositeComponent' + | 'renderToReadableStream' + +export function createRscCssCompilerTransforms(opts: { + loadCssExpression: string + serverFnProviderOnly?: boolean | undefined +}): Array { + let loadCssExpression: BabelExpression | undefined + + const getLoadCssExpression = (context: StartCompilerTransformContext) => { + loadCssExpression ??= context.parseExpression(opts.loadCssExpression) + return loadCssExpression + } + + return [ + createRscCssCompilerTransform({ + serverFnProviderOnly: opts.serverFnProviderOnly, + getLoadCssExpression, + kind: 'renderServerComponent', + name: 'react-rsc-render-server-component-css', + }), + createRscCssCompilerTransform({ + serverFnProviderOnly: opts.serverFnProviderOnly, + getLoadCssExpression, + kind: 'createCompositeComponent', + name: 'react-rsc-create-composite-component-css', + }), + createRscCssCompilerTransform({ + serverFnProviderOnly: opts.serverFnProviderOnly, + getLoadCssExpression, + kind: 'renderToReadableStream', + name: 'react-rsc-render-to-readable-stream-css', + }), + ] +} + +function createRscCssCompilerTransform(opts: { + name: string + kind: RscCssTransformKind + getLoadCssExpression: ( + context: StartCompilerTransformContext, + ) => BabelExpression + serverFnProviderOnly?: boolean | undefined +}): StartCompilerImportTransform { + return { + name: opts.name, + environment: 'server', + imports: [ + { + libName: '@tanstack/react-start/rsc', + rootExport: opts.kind, + }, + { + libName: '@tanstack/react-start-rsc', + rootExport: opts.kind, + }, + ], + detect: new RegExp(`\\b${opts.kind}\\b`), + transform: (candidates, context) => { + if ( + opts.serverFnProviderOnly && + !context.id.includes(TSS_SERVERFN_SPLIT_PARAM) + ) { + return + } + + const t = context.types + const loadCssExpression = opts.getLoadCssExpression(context) + const cloneLoadCssExpression = () => t.cloneNode(loadCssExpression) + + for (const candidate of candidates) { + const args = candidate.path.node.arguments + if (args.length !== 1) continue + + if (opts.kind === 'renderToReadableStream') { + const firstArg = args[0] + if (!firstArg || !t.isExpression(firstArg)) continue + if (!isTopLevelJsx(t, firstArg)) continue + + args[0] = createCssFragment( + t, + firstArg, + cloneLoadCssExpression(), + ) as typeof firstArg + continue + } + + args.push( + t.objectExpression([ + t.objectProperty( + t.identifier(RSC_CSS_OPTIONS_KEY), + cloneLoadCssExpression(), + ), + ]), + ) + } + }, + } +} + +function isTopLevelJsx(t: BabelTypes, expr: BabelExpression): boolean { + const unwrapped = unwrapTransparentExpression(t, expr) + return t.isJSXElement(unwrapped) || t.isJSXFragment(unwrapped) +} + +function unwrapTransparentExpression( + t: BabelTypes, + expr: BabelExpression, +): BabelExpression { + let current = expr + while ( + t.isParenthesizedExpression(current) || + t.isTSAsExpression(current) || + t.isTSSatisfiesExpression(current) || + t.isTSTypeAssertion(current) || + t.isTSNonNullExpression(current) + ) { + current = current.expression + } + return current +} + +function createCssFragment( + t: BabelTypes, + original: BabelExpression, + loadCssExpression: BabelExpression, +) { + const unwrapped = unwrapTransparentExpression(t, original) + return t.jsxFragment(t.jsxOpeningFragment(), t.jsxClosingFragment(), [ + t.jsxExpressionContainer(loadCssExpression), + t.isJSXElement(unwrapped) || t.isJSXFragment(unwrapped) + ? unwrapped + : t.jsxExpressionContainer(original), + ]) +} diff --git a/packages/react-start-rsc/src/plugin/vite.ts b/packages/react-start-rsc/src/plugin/vite.ts new file mode 100644 index 0000000000..9aa9523c6a --- /dev/null +++ b/packages/react-start-rsc/src/plugin/vite.ts @@ -0,0 +1,238 @@ +import { fileURLToPath } from 'node:url' +import path from 'pathe' +import { createVirtualModule } from '@tanstack/start-plugin-core/vite' +import { createRscCssCompilerTransforms } from './rscCssTransform' +import type { + TanStackStartVitePluginCoreOptions, + ViteRscForwardSsrResolverStrategy, +} from '@tanstack/start-plugin-core/vite' +import type { PluginOption, UserConfig } from 'vite' + +const isClientEnvironment = (env: { config: { consumer: string } }) => + env.config.consumer === 'client' + +// Virtual module ids used by the React Start RSC runtime. +const RSC_HMR_VIRTUAL_ID = 'virtual:tanstack-rsc-hmr' +const RSC_RUNTIME_VIRTUAL_ID = 'virtual:tanstack-rsc-runtime' +const RSC_BROWSER_DECODE_VIRTUAL_ID = 'virtual:tanstack-rsc-browser-decode' +const RSC_SSR_DECODE_VIRTUAL_ID = 'virtual:tanstack-rsc-ssr-decode' +const RSC_ENV_NAME = 'rsc' + +const currentDir = path.dirname(fileURLToPath(import.meta.url)) +const entryDir = path.resolve(currentDir, '..', '..', 'plugin', 'entry') +const rscEntryPath = path.resolve(entryDir, 'rsc.tsx') + +export function configureRsc(): { + envName: string + providerEnvironmentName: TanStackStartVitePluginCoreOptions['providerEnvironmentName'] + ssrResolverStrategy: TanStackStartVitePluginCoreOptions['ssrResolverStrategy'] + serializationAdapters: TanStackStartVitePluginCoreOptions['serializationAdapters'] + compilerTransforms: TanStackStartVitePluginCoreOptions['compilerTransforms'] +} { + const serializationAdapters: TanStackStartVitePluginCoreOptions['serializationAdapters'] = + [ + // IMPORTANT: plugin-adapters-plugin only calls the top-level factory once. + // That factory must return a flat array of adapters (not nested arrays), + // otherwise router-core ends up with non-adapter entries and Seroval crashes. + { + client: { + module: '@tanstack/react-start/rsc/serialization/client', + export: 'rscSerializationAdapter', + isFactory: true, + }, + server: { + module: '@tanstack/react-start/rsc/serialization/server', + export: 'rscSerializationAdapter', + isFactory: true, + }, + }, + ] + const ssrResolverStrategy = { + type: 'vite-rsc-forward', + sourceEnvironmentName: RSC_ENV_NAME, + sourceEntry: 'index', + exportName: 'getServerFnById', + } satisfies ViteRscForwardSsrResolverStrategy + return { + envName: RSC_ENV_NAME, + providerEnvironmentName: RSC_ENV_NAME, + ssrResolverStrategy, + serializationAdapters, + compilerTransforms: createRscCssCompilerTransforms({ + loadCssExpression: 'import.meta.viteRsc.loadCss()', + }), + } +} +export function reactStartRscVitePlugin(): PluginOption { + return [ + // When RSC is enabled, SSR needs noExternal: true to ensure single React instance. + // The RSC decoder's dynamic imports for client components can cause module duplication + // without this, leading to "Invalid hook call" errors. + // We use the top-level `ssr` config option as `environments.ssr.resolve.noExternal` + // doesn't have the same effect. + { + name: 'tanstack-react-start:rsc-ssr-config', + config() { + return { + ssr: { + noExternal: true, + }, + } + }, + }, + { + name: 'tanstack-react-start:rsc-env-config', + config() { + return { + rsc: { + // Disable @vitejs/plugin-rsc's built-in server handler middleware. + // TanStack Start has its own request handling via the SSR environment. + serverHandler: false, + // Disable CSS link precedence to prevent React 19 SSR suspension + // TanStack Start handles CSS preloading via manifest injection instead + cssLinkPrecedence: false, + }, + environments: { + [RSC_ENV_NAME]: { + consumer: 'server', + // Force @tanstack packages to be processed by Vite as source code + // rather than treated as external modules. This ensures: + // 1. createIsomorphicFn transforms are applied + // 2. Imports are resolved within the RSC environment context + // with proper react-server conditions and pre-bundled deps + resolve: { + noExternal: [ + '@tanstack/start**', + '@tanstack/react-start', + '@tanstack/react-start-rsc', + '@tanstack/react-router', + ], + }, + build: { + rolldownOptions: { + input: { + index: rscEntryPath, + }, + }, + }, + }, + }, + } satisfies UserConfig & { + rsc: { + serverHandler: false + cssLinkPrecedence?: boolean + } + } + }, + }, + + { + name: 'tanstack-react-start:rsc-scan-virtual-fallback', + apply: 'build', + applyToEnvironment(env) { + return env.name === RSC_ENV_NAME + }, + load: { + filter: { + id: /^(virtual:tanstack-rsc-runtime|virtual:vite-rsc\/encryption-key)$/, + }, + handler(id) { + if (this.environment.config.build.write !== false) return + + if (id === RSC_RUNTIME_VIRTUAL_ID) { + return `export { renderToReadableStream, createFromReadableStream, createTemporaryReferenceSet, decodeReply, loadServerAction, decodeAction, decodeFormState } from '@vitejs/plugin-rsc/rsc'` + } + + if (id === 'virtual:vite-rsc/encryption-key') { + return `export default () => ''` + } + + return undefined + }, + }, + }, + + // Runtime bridge into the Vite RSC environment. + createVirtualModule({ + name: 'tanstack-react-start:rsc-runtime-virtual', + moduleId: RSC_RUNTIME_VIRTUAL_ID, + load() { + const envName = this.environment.name + if (envName === RSC_ENV_NAME) { + return `export { renderToReadableStream, createFromReadableStream, createTemporaryReferenceSet, decodeReply, loadServerAction, decodeAction, decodeFormState } from '@vitejs/plugin-rsc/rsc'` + } + return ` +export function renderToReadableStream() { throw new Error('renderToReadableStream can only be used in RSC environment'); } +export function createFromReadableStream() { throw new Error('createFromReadableStream can only be used in RSC environment'); } +export function createTemporaryReferenceSet() { throw new Error('createTemporaryReferenceSet can only be used in RSC environment'); } +export function decodeReply() { throw new Error('decodeReply can only be used in RSC environment'); } +export function loadServerAction() { throw new Error('loadServerAction can only be used in RSC environment'); } +export function decodeAction() { throw new Error('decodeAction can only be used in RSC environment'); } +export function decodeFormState() { throw new Error('decodeFormState can only be used in RSC environment'); } +` + }, + }), + createVirtualModule({ + name: 'tanstack-react-start:rsc-browser-decode-virtual', + moduleId: RSC_BROWSER_DECODE_VIRTUAL_ID, + load() { + return `export { createFromReadableStream, createFromFetch } from '@vitejs/plugin-rsc/browser'` + }, + }), + createVirtualModule({ + name: 'tanstack-react-start:rsc-ssr-decode-virtual', + moduleId: RSC_SSR_DECODE_VIRTUAL_ID, + load() { + return `export { setOnClientReference, createFromReadableStream } from '@vitejs/plugin-rsc/ssr'` + }, + }), + createVirtualModule({ + name: 'tanstack-react-start:rsc-hmr-virtual:dev', + moduleId: RSC_HMR_VIRTUAL_ID, + apply: 'serve', + applyToEnvironment: isClientEnvironment, + load() { + return ` +export function setupRscHmr() { +if (!import.meta.hot) { + return +} + + let __invalidateQueued = false + + function __queueInvalidate() { + if (__invalidateQueued) return + __invalidateQueued = true + queueMicrotask(async () => { + __invalidateQueued = false + try { + const router = window.__TSR_ROUTER__ + if (!router) { + console.warn('[rsc:hmr] No router found on window.__TSR_ROUTER__') + return + } + await router.invalidate() + } catch (e) { + console.warn('[rsc:hmr] Failed to invalidate router:', e) + } + }) + } + + import.meta.hot.on('rsc:update', () => { + __queueInvalidate() + }) +} +` + }, + }), + createVirtualModule({ + name: 'tanstack-react-start:rsc-hmr-virtual:prod', + moduleId: RSC_HMR_VIRTUAL_ID, + applyToEnvironment: isClientEnvironment, + apply: 'build', + load() { + return 'export function setupRscHmr() {} ' + }, + }), + ] +} diff --git a/packages/react-start-rsc/src/react-server-dom-rspack.d.ts b/packages/react-start-rsc/src/react-server-dom-rspack.d.ts new file mode 100644 index 0000000000..3507e6368f --- /dev/null +++ b/packages/react-start-rsc/src/react-server-dom-rspack.d.ts @@ -0,0 +1,57 @@ +/** + * Type declarations for react-server-dom-rspack. + * + * This package ships no .d.ts files. Declarations here cover only the + * subset of the API surface that TanStack Start uses. + */ + +declare module 'react-server-dom-rspack/client.node' { + export function createFromReadableStream( + stream: ReadableStream, + options?: object, + ): Promise +} + +declare module 'react-server-dom-rspack/client.browser' { + export function createFromReadableStream( + stream: ReadableStream, + options?: object, + ): Promise + + export function createFromFetch( + fetchPromise: Promise, + options?: object, + ): Promise +} + +declare module 'react-server-dom-rspack/server' { + export function renderToReadableStream( + data: T, + options?: object, + ): ReadableStream + + export function createFromReadableStream( + stream: ReadableStream, + options?: object, + ): Promise + + export function createTemporaryReferenceSet(): object + + export function decodeReply( + body: string | FormData, + options?: object, + ): Promise + + export function loadServerAction(id: string): Promise<(...args: any) => any> + + export function decodeAction( + body: FormData, + serverManifest?: unknown, + ): Promise<() => T> + + export function decodeFormState( + actionResult: T, + body: FormData, + serverManifest?: unknown, + ): Promise +} diff --git a/packages/react-start-rsc/src/reactSymbols.ts b/packages/react-start-rsc/src/reactSymbols.ts new file mode 100644 index 0000000000..c4349a6afc --- /dev/null +++ b/packages/react-start-rsc/src/reactSymbols.ts @@ -0,0 +1,6 @@ +// Inline React 19 internal $$typeof symbols to avoid depending on `react-is`. +// `react-is` is CJS-only, causing module resolution failures in strict pnpm +// setups where it can't be resolved from the consumer's node_modules. +export const ReactElement = Symbol.for('react.transitional.element') +export const ReactLazy = Symbol.for('react.lazy') +export const ReactSuspense = Symbol.for('react.suspense') diff --git a/packages/react-start-rsc/src/renderServerComponent.stub.ts b/packages/react-start-rsc/src/renderServerComponent.stub.ts new file mode 100644 index 0000000000..aefff84206 --- /dev/null +++ b/packages/react-start-rsc/src/renderServerComponent.stub.ts @@ -0,0 +1,26 @@ +import type { + RenderableServerComponentBuilder, + ValidateRenderableServerComponent, +} from './ServerComponentTypes' + +/** + * Client stub for renderServerComponent. + * + * This function should never be called at runtime on the client. + * It exists only to satisfy bundler imports in client bundles. + * The real implementation only runs inside server functions. + */ +export function renderServerComponent( + _node: ValidateRenderableServerComponent, +): Promise> { + // Unit/type tests import this stub directly and call it. + // Avoid throwing in that environment while keeping a hard runtime guard elsewhere. + if (process.env.NODE_ENV === 'test') { + return Promise.resolve(null as any) + } + + throw new Error( + 'renderServerComponent cannot be called on the client. ' + + 'This function should only be called inside a server function or route loader.', + ) +} diff --git a/packages/react-start-rsc/src/renderServerComponent.ts b/packages/react-start-rsc/src/renderServerComponent.ts new file mode 100644 index 0000000000..4ef6037821 --- /dev/null +++ b/packages/react-start-rsc/src/renderServerComponent.ts @@ -0,0 +1,112 @@ +import { renderToReadableStream } from 'virtual:tanstack-rsc-runtime' +import { getStartContext } from '@tanstack/start-storage-context' +import { ReplayableStream } from './ReplayableStream' +import { RENDERABLE_RSC, SERVER_COMPONENT_STREAM } from './ServerComponentTypes' +import { createRscCssEnvelope } from './rscCssEnvelope' +import type { + AnyRenderableServerComponent, + RenderableServerComponentBuilder, + ServerComponentStream, + ValidateRenderableServerComponent, +} from './ServerComponentTypes' +import type { RscCssEnvelopeOptions } from './rscCssEnvelope' + +import './rscSsrHandler' +// Import for global declaration side effect +export type { RscSsrHandler, RscDecodeResult } from './rscSsrHandler' + +/** + * Renderable RSC handle type - used for serialization detection. + */ + +/** + * Type guard for renderable RSC handle. + */ +export function isRenderableRscHandle( + value: unknown, +): value is AnyRenderableServerComponent { + return ( + typeof value === 'function' && + SERVER_COMPONENT_STREAM in value && + RENDERABLE_RSC in value && + (value as any)[RENDERABLE_RSC] === true + ) +} + +/** + * Renders a React element to an RSC Flight stream. + * + * Returns a "renderable proxy" that can be: + * - Rendered directly as `{data}` in JSX + * - Accessed for nested selections: `{data.foo.bar.Hello}` + * + * No slot support - for slots use `createCompositeComponent`. + * + * @example + * ```tsx + * // In a loader or server function + * const data = await renderServerComponent() + * + * // In the route component + * return ( + *
    + * {data} + * {data.sidebar.Menu} + *
    + * ) + * ``` + */ +export async function renderServerComponent( + node: ValidateRenderableServerComponent, + options?: RscCssEnvelopeOptions, +): Promise> { + const flightStream = renderToReadableStream( + createRscCssEnvelope(node, options), + ) + + // Check if this is an SSR request (router) or a direct server function call + const ctx = getStartContext({ throwIfNotFound: false }) + const isRouterRequest = ctx?.handlerType === 'router' + const ssrHandler = globalThis.__RSC_SSR__ + + // SSR path: buffer stream for replay, pre-decode for synchronous rendering + if (isRouterRequest && ssrHandler) { + const signal = ctx.request.signal + const stream = new ReplayableStream(flightStream, { signal }) + + // Pre-decode during loader phase for synchronous SSR rendering + const decoded = await ssrHandler.decode(stream) + return ssrHandler.createRenderableProxy( + stream, + decoded, + ) as RenderableServerComponentBuilder + } + + // Server function call path: return a handle for serialization + return createRenderableHandle( + flightStream, + ) as unknown as RenderableServerComponentBuilder +} + +/** + * Creates a renderable handle for server function responses. + * Tagged with RENDERABLE_RSC for the serialization adapter. + */ +function createRenderableHandle( + flightStream: ReadableStream, +): AnyRenderableServerComponent { + const streamWrapper: ServerComponentStream = { + createReplayStream: () => flightStream, + } + + const stub = function RenderableRscStub(): never { + throw new Error( + 'Renderable RSC from server function cannot be rendered on server. ' + + 'It should be serialized and sent to the client.', + ) + } + + ;(stub as any)[SERVER_COMPONENT_STREAM] = streamWrapper + ;(stub as any)[RENDERABLE_RSC] = true + return stub as unknown as AnyRenderableServerComponent +} diff --git a/packages/react-start-rsc/src/rsbuild/browser-decode.ts b/packages/react-start-rsc/src/rsbuild/browser-decode.ts new file mode 100644 index 0000000000..040e3e6bd9 --- /dev/null +++ b/packages/react-start-rsc/src/rsbuild/browser-decode.ts @@ -0,0 +1,11 @@ +/** + * Rsbuild browser decode implementation. + * + * Bundler-owned rsbuild virtual modules re-export this module for browser-side + * Flight decode. + */ + +export { + createFromReadableStream, + createFromFetch, +} from 'react-server-dom-rspack/client.browser' diff --git a/packages/react-start-rsc/src/rsbuild/ssr-decode.ts b/packages/react-start-rsc/src/rsbuild/ssr-decode.ts new file mode 100644 index 0000000000..30054d9144 --- /dev/null +++ b/packages/react-start-rsc/src/rsbuild/ssr-decode.ts @@ -0,0 +1,128 @@ +/** + * Rsbuild SSR decode implementation. + * + * Bundler-owned rsbuild virtual modules re-export this module for SSR-side + * Flight decode. + */ + +import { createFromReadableStream as decodeFlightStream } from 'react-server-dom-rspack/client.node' + +type ClientReferenceDeps = { + js: Array + css: Array +} + +type OnClientReference = (reference: { + id: string + deps: ClientReferenceDeps + runtime: 'rsbuild' +}) => void + +type ImportManifestEntry = { + id: string + chunks: Array + cssFiles?: Array + name: string + async?: boolean +} + +type ClientManifest = Record +type ServerConsumerModuleMap = null | Record< + string, + Record +> +type ModuleLoading = null | { + prefix: string + crossOrigin?: 'use-credentials' | '' +} + +declare const __rspack_rsc_manifest__: { + moduleLoading: ModuleLoading + serverConsumerModuleMap: ServerConsumerModuleMap + clientManifest: ClientManifest +} + +const CHUNK_FILENAME_INDEX = 1 +const CHUNK_PAIR_SIZE = 2 + +let onClientReference: OnClientReference | undefined +let clientReferenceDepsByModuleId: Map | undefined + +function getClientReferenceDepsByModuleId() { + if (clientReferenceDepsByModuleId) return clientReferenceDepsByModuleId + + clientReferenceDepsByModuleId = new Map() + const prefix = __rspack_rsc_manifest__.moduleLoading?.prefix ?? '' + + for (const entry of Object.values(__rspack_rsc_manifest__.clientManifest)) { + let deps = clientReferenceDepsByModuleId.get(entry.id) + if (!deps) { + deps = { js: [], css: [] } + clientReferenceDepsByModuleId.set(entry.id, deps) + } + + // React/Rspack stores JS chunks as chunk id/filename pairs. CSS files are + // separate manifest entries and are already emitted as public hrefs. + for ( + let i = CHUNK_FILENAME_INDEX; + i < entry.chunks.length; + i += CHUNK_PAIR_SIZE + ) { + deps.js.push(prefix + entry.chunks[i]) + } + + if (entry.cssFiles) { + deps.css.push(...entry.cssFiles) + } + } + + return clientReferenceDepsByModuleId +} + +function emitClientReferencePreloadsForModule(moduleId: string) { + const deps = getClientReferenceDepsByModuleId().get(moduleId) + if (!onClientReference || !deps) return + + if (deps.js.length === 0 && deps.css.length === 0) { + return + } + + onClientReference({ + id: moduleId, + deps, + runtime: 'rsbuild', + }) +} + +if (__rspack_rsc_manifest__.serverConsumerModuleMap) { + __rspack_rsc_manifest__.serverConsumerModuleMap = new Proxy( + __rspack_rsc_manifest__.serverConsumerModuleMap, + { + get(target, property, receiver) { + const moduleExports = Reflect.get(target, property, receiver) + + if (typeof property === 'string' && moduleExports !== undefined) { + emitClientReferencePreloadsForModule(property) + } + + return moduleExports + }, + }, + ) +} + +function setOnClientReference(callback: OnClientReference | undefined) { + onClientReference = callback +} + +async function createFromReadableStreamWithClientPreloads( + stream: ReadableStream, + options?: object, +): Promise { + return decodeFlightStream(stream, options) +} + +export { + setOnClientReference, + createFromReadableStreamWithClientPreloads as createFromReadableStream, +} diff --git a/packages/react-start-rsc/src/rscCssEnvelope.ts b/packages/react-start-rsc/src/rscCssEnvelope.ts new file mode 100644 index 0000000000..54e1ac4932 --- /dev/null +++ b/packages/react-start-rsc/src/rscCssEnvelope.ts @@ -0,0 +1,38 @@ +import type React from 'react' + +const RSC_CSS_ENVELOPE_MARKER = '__tanstackStartRscCssEnvelope' +const RSC_CSS_ENVELOPE_RESOURCES = '__tanstackStartRscCss' +const RSC_CSS_ENVELOPE_VALUE = '__tanstackStartRscValue' + +export interface RscCssEnvelopeOptions { + [RSC_CSS_ENVELOPE_RESOURCES]?: React.ReactNode +} + +export function createRscCssEnvelope( + value: TValue, + options?: RscCssEnvelopeOptions, +): TValue | Record { + const resources = options?.[RSC_CSS_ENVELOPE_RESOURCES] + if (resources === undefined || resources === null || resources === false) { + return value + } + + return { + [RSC_CSS_ENVELOPE_MARKER]: true, + [RSC_CSS_ENVELOPE_RESOURCES]: resources, + [RSC_CSS_ENVELOPE_VALUE]: value, + } +} + +export function unwrapRscCssEnvelope(value: unknown): unknown { + if (!value || typeof value !== 'object') { + return value + } + + const maybeEnvelope = value as Record + if (maybeEnvelope[RSC_CSS_ENVELOPE_MARKER] !== true) { + return value + } + + return maybeEnvelope[RSC_CSS_ENVELOPE_VALUE] +} diff --git a/packages/react-start-rsc/src/rscSsrHandler.ts b/packages/react-start-rsc/src/rscSsrHandler.ts new file mode 100644 index 0000000000..2969c926cf --- /dev/null +++ b/packages/react-start-rsc/src/rscSsrHandler.ts @@ -0,0 +1,39 @@ +import type { + RscSlotUsageEvent, + ServerComponentStream, +} from './ServerComponentTypes' + +/** + * Result from decoding an RSC stream for SSR. + */ +export interface RscDecodeResult { + tree: unknown + cssHrefs?: Set + jsPreloads?: Set +} + +/** + * SSR handler interface - registered by serialization.server.ts in SSR environment. + * Supports both renderable and composite proxy creation. + */ +export interface RscSsrHandler { + /** Pre-decode the stream for synchronous SSR rendering */ + decode: (stream: ServerComponentStream) => Promise + /** Create a renderable proxy (for renderServerComponent) */ + createRenderableProxy: ( + stream: ServerComponentStream, + decoded: RscDecodeResult, + ) => any + /** Create a composite proxy (for createCompositeComponent) */ + createCompositeProxy: ( + stream: ServerComponentStream, + decoded: RscDecodeResult, + slotUsagesStream?: ReadableStream, + ) => any +} + +// Single global for SSR environment communication +declare global { + // eslint-disable-next-line no-var + var __RSC_SSR__: RscSsrHandler | undefined +} diff --git a/packages/react-start-rsc/src/serialization.client.ts b/packages/react-start-rsc/src/serialization.client.ts new file mode 100644 index 0000000000..5bf8fd7d79 --- /dev/null +++ b/packages/react-start-rsc/src/serialization.client.ts @@ -0,0 +1,54 @@ +import { createSerializationAdapter } from '@tanstack/react-router' +// RSC HMR setup (dev-only, provided by the active Start bundler adapter). +import { setupRscHmr } from 'virtual:tanstack-rsc-hmr' +import { + createCompositeFromStream, + createRenderableFromStream, +} from './createServerComponentFromStream' +import type { + AnyCompositeComponent, + RscSlotUsageEvent, +} from './ServerComponentTypes' + +if (process.env.NODE_ENV === 'development') { + setupRscHmr() +} + +/** + * Client-side serialization adapter for RSC (renderable + composite). + */ +type SerializedRsc = { + kind: 'renderable' | 'composite' + stream: ReadableStream + slotUsagesStream?: ReadableStream + cssHrefs?: Array + jsPreloads?: Array +} + +const adapter = createSerializationAdapter({ + key: '$RSC', + test: (_value: unknown): _value is never => false, + toSerializable: (): never => { + throw new Error('RSC cannot be serialized on client') + }, + fromSerializable: (value: SerializedRsc): AnyCompositeComponent => { + // Rsbuild SSR sends asset deps with each serialized RSC so the client can + // preload only if that specific stream is rendered. When absent, decode + // starts eagerly and discovers assets from the Flight payload as before. + const options = { + cssHrefs: value.cssHrefs, + jsPreloads: value.jsPreloads, + } + + if (value.kind === 'renderable') { + return createRenderableFromStream(value.stream, options) + } + + return createCompositeFromStream(value.stream, { + slotUsagesStream: value.slotUsagesStream, + ...options, + }) + }, +}) + +export const rscSerializationAdapter = () => [adapter] diff --git a/packages/react-start-rsc/src/serialization.server.ts b/packages/react-start-rsc/src/serialization.server.ts new file mode 100644 index 0000000000..ee9ad0eca8 --- /dev/null +++ b/packages/react-start-rsc/src/serialization.server.ts @@ -0,0 +1,230 @@ +import { AsyncLocalStorage } from 'node:async_hooks' +import { createSerializationAdapter } from '@tanstack/react-router' +import { RawStream } from '@tanstack/router-core' +import { getStartContext } from '@tanstack/start-storage-context' +import { + setOnClientReference, + createFromReadableStream as ssrDecode, +} from 'virtual:tanstack-rsc-ssr-decode' +import { + RENDERABLE_RSC, + RSC_SLOT_USAGES_STREAM, + SERVER_COMPONENT_CSS_HREFS, + SERVER_COMPONENT_JS_PRELOADS, + SERVER_COMPONENT_STREAM, + isServerComponent, +} from './ServerComponentTypes' +import { createRscProxy } from './createRscProxy' +import { awaitLazyElements } from './awaitLazyElements' +import { unwrapRscCssEnvelope } from './rscCssEnvelope' +import type { + AnyCompositeComponent, + ServerComponentStream, +} from './ServerComponentTypes' +import type { RscDecodeResult, RscSsrHandler } from './rscSsrHandler' + +// ===== SSR Handler Registration ===== +// This handler is registered on globalThis for the RSC environment to access. +// The RSC env calls these functions during loader execution to pre-decode streams +// and create renderable proxies. +// +// This MUST happen in a module without 'use client' directive. +// Modules with 'use client' may be transformed to client references in the +// SSR environment when RSC is enabled, preventing the side effect from running. + +// AsyncLocalStorage for decode-scoped proxy asset collectors. +// Client-reference deps stay on the decoded RSC proxy so unused streams don't +// emit global request assets. CSS marker links are collected for all adapters +// because the decoded envelope is unwrapped before SSR render. +const proxyCssCollectorStorage = new AsyncLocalStorage>() +const proxyJsCollectorStorage = new AsyncLocalStorage>() + +setOnClientReference( + ({ + deps, + runtime, + }: { + deps: { js: Array; css: Array } + runtime?: 'rsbuild' + }) => { + const cssCollector = proxyCssCollectorStorage.getStore() + if (cssCollector) { + for (const href of deps.css) { + cssCollector.add(href) + } + } + + const jsCollector = proxyJsCollectorStorage.getStore() + if (jsCollector) { + for (const href of deps.js) { + jsCollector.add(href) + } + } + + if (runtime === 'rsbuild' || cssCollector || jsCollector) { + return + } + + const ctx = getStartContext({ throwIfNotFound: false }) + + // Non-Rsbuild adapters emit decoded client-reference assets through the + // request manifest. + if (!ctx || (!deps.js.length && !deps.css.length)) { + return + } + + if (!ctx.requestAssets) ctx.requestAssets = {} + const seenHrefs = new Set() + for (const preload of ctx.requestAssets.preloads ?? []) { + seenHrefs.add(typeof preload === 'string' ? preload : preload.href) + } + for (const stylesheet of ctx.requestAssets.css ?? []) { + seenHrefs.add( + typeof stylesheet === 'string' ? stylesheet : stylesheet.href, + ) + } + + let nextPreloads: typeof ctx.requestAssets.preloads | undefined + for (const href of deps.js) { + if (seenHrefs.has(href)) continue + seenHrefs.add(href) + if (!nextPreloads) { + nextPreloads = ctx.requestAssets.preloads + ? ctx.requestAssets.preloads.slice() + : [] + } + nextPreloads.push(href) + } + if (nextPreloads) { + ctx.requestAssets.preloads = nextPreloads + } + + let nextCss: typeof ctx.requestAssets.css | undefined + for (const href of deps.css) { + if (seenHrefs.has(href)) continue + seenHrefs.add(href) + if (!nextCss) { + nextCss = ctx.requestAssets.css ? ctx.requestAssets.css.slice() : [] + } + nextCss.push(href) + } + if (nextCss) { + ctx.requestAssets.css = nextCss + } + }, +) + +const ssrHandler: RscSsrHandler = { + async decode(stream: ServerComponentStream): Promise { + const readableStream = stream.createReplayStream() + + // Create a collector for this decode operation. + // Run the decode in an AsyncLocalStorage context so the onClientReference + // callback can write to this specific collector even with parallel decodes. + const proxyCssCollector = new Set() + const proxyJsCollector = new Set() + + return proxyCssCollectorStorage.run(proxyCssCollector, async () => { + return proxyJsCollectorStorage.run(proxyJsCollector, async () => { + const decodedTree = await ssrDecode(readableStream) + await awaitLazyElements(decodedTree, (href) => { + proxyCssCollector.add(href) + }) + + return { + tree: unwrapRscCssEnvelope(decodedTree), + cssHrefs: proxyCssCollector.size > 0 ? proxyCssCollector : undefined, + jsPreloads: proxyJsCollector.size > 0 ? proxyJsCollector : undefined, + } + }) + }) + }, + + createRenderableProxy(stream, decoded): any { + return createRscProxy(() => decoded.tree, { + stream, + cssHrefs: decoded.cssHrefs, + jsPreloads: decoded.jsPreloads, + renderable: true, + }) + }, + + createCompositeProxy( + stream, + decoded, + slotUsagesStream, + ): AnyCompositeComponent { + const proxy = createRscProxy(() => decoded.tree, { + stream, + cssHrefs: decoded.cssHrefs, + jsPreloads: decoded.jsPreloads, + renderable: false, + slotUsagesStream, + }) + return proxy + }, +} + +// Register SSR handler on globalThis for RSC environment to access. +globalThis.__RSC_SSR__ = ssrHandler + +// ===== End SSR Handler Registration ===== + +/** + * Helper to check if a value is a renderable RSC (from renderServerComponent). + * The value can be either an object (proxy target) or a function (stub for server functions). + */ +function isRenderableRsc(value: unknown): boolean { + if (value === null || value === undefined) return false + if (typeof value !== 'object' && typeof value !== 'function') return false + return RENDERABLE_RSC in value && (value as any)[RENDERABLE_RSC] === true +} + +/** + * Server-side serialization adapter for RSC (renderable + composite). + */ +const adapter = createSerializationAdapter({ + key: '$RSC', + test: (value: unknown): value is AnyCompositeComponent => { + return isServerComponent(value) + }, + toSerializable: (component: AnyCompositeComponent) => { + const stream = component[SERVER_COMPONENT_STREAM]!.createReplayStream() + + const kind = isRenderableRsc(component) ? 'renderable' : 'composite' + const jsPreloads = component[SERVER_COMPONENT_JS_PRELOADS] + const cssHrefs = component[SERVER_COMPONENT_CSS_HREFS] + // `cssHrefs` can also come from loadCss() marker links. Client-reference + // collection fills `jsPreloads`, so that gates per-stream serialization. + const serializedAssetDeps = jsPreloads?.size + ? { + ...(cssHrefs?.size ? { cssHrefs: Array.from(cssHrefs) } : {}), + jsPreloads: Array.from(jsPreloads), + } + : {} + + const slotUsagesStream = + process.env.NODE_ENV === 'development' && + kind === 'composite' && + RSC_SLOT_USAGES_STREAM in component + ? ((component as any)[RSC_SLOT_USAGES_STREAM] as unknown as + | ReadableStream + | undefined) + : undefined + + return { + kind, + stream: new RawStream(stream, { hint: 'text' }), + slotUsagesStream, + ...serializedAssetDeps, + } + }, + fromSerializable: (): never => { + throw new Error('Server should never deserialize RSC data') + }, +}) + +/** + * Factory function for server-side RSC serialization adapter. + */ +export const rscSerializationAdapter = () => [adapter] diff --git a/packages/react-start-rsc/src/slotUsageSanitizer.ts b/packages/react-start-rsc/src/slotUsageSanitizer.ts new file mode 100644 index 0000000000..ad6d17491e --- /dev/null +++ b/packages/react-start-rsc/src/slotUsageSanitizer.ts @@ -0,0 +1,62 @@ +import { isValidElement } from 'react' + +const REACT_ELEMENT_TYPE = Symbol.for('react.element') +const REACT_TRANSITIONAL_ELEMENT_TYPE = Symbol.for('react.transitional.element') +const REACT_PORTAL_TYPE = Symbol.for('react.portal') + +function isReactElementLike(value: unknown): boolean { + if (!value || (typeof value !== 'object' && typeof value !== 'function')) { + return false + } + + // Prefer React's own check when available. + if (isValidElement(value)) return true + + // Fallback: direct $$typeof detection (covers React 19 transitional elements). + const t = (value as any).$$typeof + return ( + t === REACT_ELEMENT_TYPE || + t === REACT_TRANSITIONAL_ELEMENT_TYPE || + t === REACT_PORTAL_TYPE + ) +} + +const REACT_ELEMENT_PLACEHOLDER = 'React element' + +function sanitizeSlotArg( + value: unknown, + seen: WeakSet, + depth: number, +): unknown { + if (isReactElementLike(value)) { + return REACT_ELEMENT_PLACEHOLDER + } + + if (value === null || value === undefined) { + return value + } + + if (typeof value !== 'object' && typeof value !== 'function') { + return value + } + + if (Array.isArray(value)) { + return value.map((d) => sanitizeSlotArg(d, seen, depth + 1)) + } + + const proto = Object.getPrototypeOf(value) + if (proto === Object.prototype || proto === null) { + const out: Record = {} + for (const [k, v] of Object.entries(value as Record)) { + out[k] = sanitizeSlotArg(v, seen, depth + 1) + } + return out + } + + return value +} + +export function sanitizeSlotArgs(args: Array): Array { + const seen = new WeakSet() + return args.map((d) => sanitizeSlotArg(d, seen, 0)) +} diff --git a/packages/react-start-rsc/src/types.ts b/packages/react-start-rsc/src/types.ts new file mode 100644 index 0000000000..061a53edba --- /dev/null +++ b/packages/react-start-rsc/src/types.ts @@ -0,0 +1,15 @@ +import type { ServerComponentStream } from './ServerComponentTypes' + +/** + * Handle returned by RSC helpers. + * Contains the RSC Flight stream that can be consumed by SSR and/or Client. + */ +export interface ServerComponentHandle { + readonly stream: ServerComponentStream +} + +/** + * Slot implementations provided to ServerComponentRenderer. + * Keys are slot names, values are either React nodes (for children) or render functions. + */ +export type SlotImplementations = Record diff --git a/packages/react-start-rsc/tests/ClientSlot.test.tsx b/packages/react-start-rsc/tests/ClientSlot.test.tsx new file mode 100644 index 0000000000..fa6fef2e9c --- /dev/null +++ b/packages/react-start-rsc/tests/ClientSlot.test.tsx @@ -0,0 +1,213 @@ +import { describe, expect, it, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import { ClientSlot } from '../src/ClientSlot' +import { SlotProvider } from '../src/SlotContext' + +describe('ClientSlot', () => { + describe('error handling', () => { + it('should throw when rendered outside SlotProvider', () => { + // Suppress React error boundary console output + const spy = vi.spyOn(console, 'error').mockImplementation(() => {}) + + expect(() => { + render() + }).toThrow('ClientSlot must be rendered within SlotProvider') + + spy.mockRestore() + }) + }) + + describe('missing implementations', () => { + it('should return null for missing slot in non-strict mode', () => { + render( + +
    + +
    +
    , + ) + + // Container should be empty (null rendered) + expect(screen.getByTestId('container').children).toHaveLength(0) + }) + + it('should throw for missing slot in strict mode', () => { + const spy = vi.spyOn(console, 'error').mockImplementation(() => {}) + + expect(() => { + render( + + + , + ) + }).toThrow('Missing slot implementation for "missing"') + + spy.mockRestore() + }) + }) + + describe('non-function implementations', () => { + it('should render string directly', () => { + render( + +
    + +
    +
    , + ) + + expect(screen.getByTestId('slot').textContent).toBe('Hello World') + }) + + it('should render number directly', () => { + render( + +
    + +
    +
    , + ) + + expect(screen.getByTestId('slot').textContent).toBe('42') + }) + + it('should render React element directly', () => { + render( + Element }}> +
    + +
    +
    , + ) + + expect(screen.getByTestId('slot').textContent).toBe('Element') + }) + + it('should render children slot', () => { + render( + Child content }}> +
    + +
    +
    , + ) + + expect(screen.getByTestId('slot').textContent).toBe('Child content') + }) + }) + + describe('function implementations', () => { + it('should call function with no args', () => { + render( + 'No args result' }}> +
    + +
    +
    , + ) + + expect(screen.getByTestId('slot').textContent).toBe('No args result') + }) + + it('should call function with single arg', () => { + render( + `Hello ${name}` }} + > +
    + +
    +
    , + ) + + expect(screen.getByTestId('slot').textContent).toBe('Hello World') + }) + + it('should call function with multiple args', () => { + render( + `Sum: ${a + b + c}`, + }} + > +
    + +
    +
    , + ) + + expect(screen.getByTestId('slot').textContent).toBe('Sum: 6') + }) + + it('should call function returning React element', () => { + render( + ( + {item.name} + ), + }} + > +
    + +
    +
    , + ) + + expect(screen.getByTestId('slot').textContent).toBe('Item One') + }) + + it('should handle function returning null', () => { + render( + null }}> +
    + +
    +
    , + ) + + expect(screen.getByTestId('slot').children).toHaveLength(0) + }) + }) + + describe('edge cases', () => { + it('should handle undefined args gracefully', () => { + render( + ) => `Args: ${args.length}`, + }} + > +
    + +
    +
    , + ) + + expect(screen.getByTestId('slot').textContent).toBe('Args: 2') + }) + + it('should handle complex object args', () => { + interface ComplexArg { + nested: { deep: { value: string } } + } + + render( + obj.nested.deep.value, + }} + > +
    + +
    +
    , + ) + + expect(screen.getByTestId('slot').textContent).toBe('Deep value') + }) + }) +}) diff --git a/packages/react-start-rsc/tests/CompositeComponent.types.test-d.tsx b/packages/react-start-rsc/tests/CompositeComponent.types.test-d.tsx new file mode 100644 index 0000000000..b6493e75a8 --- /dev/null +++ b/packages/react-start-rsc/tests/CompositeComponent.types.test-d.tsx @@ -0,0 +1,29 @@ +import { expectTypeOf, test } from 'vitest' + +import type { ComponentProps } from 'react' +import { CompositeComponent } from '../src/CompositeComponent' +import type { CompositeComponentResult } from '../src/ServerComponentTypes' + +test('CompositeComponent infers slot props from src', () => { + type Post = (props: { + children?: React.ReactNode + header: (title: string) => React.ReactNode + footer: () => React.ReactNode + }) => React.ReactNode + + const src = null as unknown as CompositeComponentResult + + expectTypeOf(CompositeComponent).toBeFunction() + + type Props = ComponentProps> + + // Type-level: ensure inferred props include slots + type Expected = { + src: typeof src + children?: React.ReactNode + header: (title: string) => React.ReactNode + footer: () => React.ReactNode + } + + expectTypeOf().branded.toEqualTypeOf() +}) diff --git a/packages/react-start-rsc/tests/ReplayableStream.test.ts b/packages/react-start-rsc/tests/ReplayableStream.test.ts new file mode 100644 index 0000000000..4c4e40566e --- /dev/null +++ b/packages/react-start-rsc/tests/ReplayableStream.test.ts @@ -0,0 +1,536 @@ +import { describe, expect, it } from 'vitest' +import { + ReplayableStream, + REPLAYABLE_STREAM_MARKER, +} from '../src/ReplayableStream' + +describe('ReplayableStream', () => { + describe('basic functionality', () => { + it('should buffer and replay chunks to single consumer', async () => { + const source = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1, 2, 3])) + controller.enqueue(new Uint8Array([4, 5, 6])) + controller.close() + }, + }) + + const replayable = new ReplayableStream(source) + const replay = replayable.createReplayStream() + const reader = replay.getReader() + + const chunks: Array = [] + while (true) { + const { done, value } = await reader.read() + if (done) break + chunks.push(value) + } + + expect(chunks).toHaveLength(2) + expect(chunks[0]).toEqual(new Uint8Array([1, 2, 3])) + expect(chunks[1]).toEqual(new Uint8Array([4, 5, 6])) + }) + + it('should allow multiple independent consumers', async () => { + const source = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([10, 20])) + controller.enqueue(new Uint8Array([30, 40])) + controller.close() + }, + }) + + const replayable = new ReplayableStream(source) + + // Create two independent replay streams + const replay1 = replayable.createReplayStream() + const replay2 = replayable.createReplayStream() + + const reader1 = replay1.getReader() + const reader2 = replay2.getReader() + + // Read from both independently + const chunks1: Array = [] + const chunks2: Array = [] + + // Read first chunk from both + const r1c1 = await reader1.read() + const r2c1 = await reader2.read() + if (!r1c1.done) chunks1.push(r1c1.value) + if (!r2c1.done) chunks2.push(r2c1.value) + + // Read remaining from both + while (true) { + const { done, value } = await reader1.read() + if (done) break + chunks1.push(value) + } + while (true) { + const { done, value } = await reader2.read() + if (done) break + chunks2.push(value) + } + + // Both should have same data + expect(chunks1).toHaveLength(2) + expect(chunks2).toHaveLength(2) + expect(chunks1[0]).toEqual(new Uint8Array([10, 20])) + expect(chunks2[0]).toEqual(new Uint8Array([10, 20])) + }) + + it('should support late subscribers (replay from beginning)', async () => { + let closeController: () => void = () => {} + const source = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1])) + controller.enqueue(new Uint8Array([2])) + closeController = () => controller.close() + }, + }) + + const replayable = new ReplayableStream(source) + + // First consumer reads immediately + const replay1 = replayable.createReplayStream() + const reader1 = replay1.getReader() + await reader1.read() // Read first chunk + + // Wait a bit for buffering + await new Promise((r) => setTimeout(r, 10)) + + // Close the source + closeController() + + // Late subscriber should still get all data from beginning + const replay2 = replayable.createReplayStream() + const reader2 = replay2.getReader() + + const chunks: Array = [] + while (true) { + const { done, value } = await reader2.read() + if (done) break + chunks.push(value) + } + + expect(chunks).toHaveLength(2) + expect(chunks[0]).toEqual(new Uint8Array([1])) + expect(chunks[1]).toEqual(new Uint8Array([2])) + }) + + it('should have REPLAYABLE_STREAM_MARKER', () => { + const source = new ReadableStream({ + start(controller) { + controller.close() + }, + }) + + const replayable = new ReplayableStream(source) + expect(replayable[REPLAYABLE_STREAM_MARKER]).toBe(true) + }) + }) + + describe('abort handling', () => { + it('should abort immediately if signal already aborted', async () => { + const controller = new AbortController() + controller.abort() + + const source = new ReadableStream({ + start(ctrl) { + ctrl.enqueue(new Uint8Array([1, 2, 3])) + ctrl.close() + }, + }) + + const replayable = new ReplayableStream(source, { + signal: controller.signal, + }) + const replay = replayable.createReplayStream() + const reader = replay.getReader() + + // Should close immediately due to abort + const { done } = await reader.read() + expect(done).toBe(true) + }) + + it('should close streams when abort signal fires', async () => { + const abortController = new AbortController() + + let enqueueFn: (chunk: Uint8Array) => void = () => {} + const source = new ReadableStream({ + start(controller) { + enqueueFn = (chunk) => controller.enqueue(chunk) + }, + }) + + const replayable = new ReplayableStream(source, { + signal: abortController.signal, + }) + const replay = replayable.createReplayStream() + const reader = replay.getReader() + + // Enqueue one chunk + enqueueFn(new Uint8Array([1])) + + // Read it + const { value, done } = await reader.read() + expect(done).toBe(false) + expect(value).toEqual(new Uint8Array([1])) + + // Abort + abortController.abort() + + // Next read should close (not error) + const result = await reader.read() + expect(result.done).toBe(true) + }) + + it('should free memory on abort', async () => { + const abortController = new AbortController() + + const source = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array(1000)) + controller.enqueue(new Uint8Array(1000)) + }, + }) + + const replayable = new ReplayableStream(source, { + signal: abortController.signal, + }) + + // Wait for buffering + await new Promise((r) => setTimeout(r, 10)) + + // Abort - should clear internal buffer + abortController.abort() + + // Creating new replay should return empty/closed stream + const replay = replayable.createReplayStream() + const reader = replay.getReader() + const { done } = await reader.read() + expect(done).toBe(true) + }) + }) + + describe('error handling', () => { + it('should propagate source stream errors to consumers', async () => { + let errorController: (err: Error) => void = () => {} + + const source = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1])) + // Store error function to call later + errorController = (err) => controller.error(err) + }, + }) + + const replayable = new ReplayableStream(source) + const replay = replayable.createReplayStream() + const reader = replay.getReader() + + // First read succeeds + const { value, done } = await reader.read() + expect(done).toBe(false) + expect(value).toEqual(new Uint8Array([1])) + + // Now trigger the error + errorController(new Error('Source stream failed')) + + // Wait for error to propagate + await new Promise((r) => setTimeout(r, 10)) + + // Next read should error + await expect(reader.read()).rejects.toThrow('Source stream failed') + }) + }) + + describe('async streaming', () => { + it('should handle slow source streams', async () => { + const source = new ReadableStream({ + async pull(controller) { + await new Promise((r) => setTimeout(r, 10)) + controller.enqueue(new Uint8Array([42])) + controller.close() + }, + }) + + const replayable = new ReplayableStream(source) + const replay = replayable.createReplayStream() + const reader = replay.getReader() + + const { value, done } = await reader.read() + expect(done).toBe(false) + expect(value).toEqual(new Uint8Array([42])) + + const { done: finalDone } = await reader.read() + expect(finalDone).toBe(true) + }) + + it('should allow consumer to read faster than producer', async () => { + let enqueueCount = 0 + const source = new ReadableStream({ + start(controller) { + // Enqueue chunks slowly + const interval = setInterval(() => { + if (enqueueCount < 3) { + controller.enqueue(new Uint8Array([enqueueCount])) + enqueueCount++ + } else { + clearInterval(interval) + controller.close() + } + }, 5) + }, + }) + + const replayable = new ReplayableStream(source) + const replay = replayable.createReplayStream() + const reader = replay.getReader() + + const chunks: Array = [] + while (true) { + const { done, value } = await reader.read() + if (done) break + chunks.push(value) + } + + expect(chunks).toHaveLength(3) + expect(chunks[0]).toEqual(new Uint8Array([0])) + expect(chunks[1]).toEqual(new Uint8Array([1])) + expect(chunks[2]).toEqual(new Uint8Array([2])) + }) + }) + + describe('edge cases', () => { + it('should handle empty source stream', async () => { + const source = new ReadableStream({ + start(controller) { + controller.close() + }, + }) + + const replayable = new ReplayableStream(source) + const replay = replayable.createReplayStream() + const reader = replay.getReader() + + const { done } = await reader.read() + expect(done).toBe(true) + }) + + it('should handle large number of chunks', async () => { + const numChunks = 100 + + const source = new ReadableStream({ + start(controller) { + for (let i = 0; i < numChunks; i++) { + controller.enqueue(new Uint8Array([i % 256])) + } + controller.close() + }, + }) + + const replayable = new ReplayableStream(source) + const replay = replayable.createReplayStream() + const reader = replay.getReader() + + const chunks: Array = [] + while (true) { + const { done, value } = await reader.read() + if (done) break + chunks.push(value) + } + + expect(chunks).toHaveLength(numChunks) + }) + + it('should create multiple replay streams from same source', async () => { + const source = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1, 2, 3])) + controller.close() + }, + }) + + const replayable = new ReplayableStream(source) + + // Create 5 replay streams + const replays = Array.from({ length: 5 }, () => + replayable.createReplayStream(), + ) + + // All should get same data + for (const replay of replays) { + const reader = replay.getReader() + const { value, done } = await reader.read() + expect(done).toBe(false) + expect(value).toEqual(new Uint8Array([1, 2, 3])) + + const { done: finalDone } = await reader.read() + expect(finalDone).toBe(true) + } + }) + }) + + describe('memory cleanup', () => { + it('should not auto-release (replays can come at unpredictable times)', async () => { + const source = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1, 2, 3])) + controller.close() + }, + }) + + const replayable = new ReplayableStream(source) + expect(replayable.isReleased()).toBe(false) + + // Create and fully consume a replay stream + const replay = replayable.createReplayStream() + const reader = replay.getReader() + await reader.read() // Read chunk + await reader.read() // Read close + + // Wait for async operations + await new Promise((r) => setTimeout(r, 10)) + + // Should NOT be auto-released (another replay might come later) + expect(replayable.isReleased()).toBe(false) + + // Can still create another replay + const replay2 = replayable.createReplayStream() + const reader2 = replay2.getReader() + const { value } = await reader2.read() + expect(value).toEqual(new Uint8Array([1, 2, 3])) + }) + + it('should allow explicit release()', async () => { + const source = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1, 2, 3])) + controller.close() + }, + }) + + const replayable = new ReplayableStream(source) + await new Promise((r) => setTimeout(r, 10)) // Wait for buffering + + expect(replayable.isReleased()).toBe(false) + + replayable.release() + + expect(replayable.isReleased()).toBe(true) + }) + + it('should return empty stream after release()', async () => { + const source = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1, 2, 3])) + controller.close() + }, + }) + + const replayable = new ReplayableStream(source) + await new Promise((r) => setTimeout(r, 10)) + + // Release explicitly + replayable.release() + + // New replay should return empty/closed stream + const replay = replayable.createReplayStream() + const reader = replay.getReader() + const { done } = await reader.read() + expect(done).toBe(true) + }) + + it('should cancel upstream when release() is called', async () => { + let canceledReason: unknown + let resolveCancel: () => void + const cancelCalled = new Promise((resolve) => { + resolveCancel = resolve + }) + + const source = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1])) + }, + cancel(reason) { + canceledReason = reason + resolveCancel() + }, + }) + + const replayable = new ReplayableStream(source) + + // Ensure the pump reads at least one chunk. + const replay = replayable.createReplayStream() + const replayReader = replay.getReader() + await replayReader.read() + + replayable.release() + await cancelCalled + + expect(canceledReason).toBeInstanceOf(Error) + }) + + it('should close active replay stream when release() is called mid-stream', async () => { + const source = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1])) + controller.enqueue(new Uint8Array([2])) + controller.close() + }, + }) + + const replayable = new ReplayableStream(source) + await new Promise((r) => setTimeout(r, 10)) + + // Create replay and read first chunk + const replay = replayable.createReplayStream() + const reader = replay.getReader() + await reader.read() // Read first chunk + + // Release mid-stream + replayable.release() + + // Next read should get close (stream closed early) + const { done } = await reader.read() + expect(done).toBe(true) + + expect(replayable.isReleased()).toBe(true) + }) + + it('should support multiple sequential replays before release', async () => { + const source = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1])) + controller.close() + }, + }) + + const replayable = new ReplayableStream(source) + await new Promise((r) => setTimeout(r, 10)) + + // First replay - full read + const replay1 = replayable.createReplayStream() + const reader1 = replay1.getReader() + await reader1.read() + await reader1.read() + + // Should not be released + expect(replayable.isReleased()).toBe(false) + + // Second replay - full read + const replay2 = replayable.createReplayStream() + const reader2 = replay2.getReader() + const { value } = await reader2.read() + expect(value).toEqual(new Uint8Array([1])) + await reader2.read() + + // Still not released + expect(replayable.isReleased()).toBe(false) + + // Now release + replayable.release() + expect(replayable.isReleased()).toBe(true) + }) + }) +}) diff --git a/packages/react-start-rsc/tests/ServerComponent.test.tsx b/packages/react-start-rsc/tests/ServerComponent.test.tsx new file mode 100644 index 0000000000..8c39d1dfe8 --- /dev/null +++ b/packages/react-start-rsc/tests/ServerComponent.test.tsx @@ -0,0 +1,118 @@ +import React from 'react' +import { describe, expect, it, vi } from 'vitest' +import { act, render } from '@testing-library/react' + +// Force the client implementation to be used in tests. +vi.mock('@tanstack/start-client-core', () => { + return { + createIsomorphicFn: () => { + const chain: any = { + client(impl: any) { + chain._client = impl + return chain + }, + server(_impl: any) { + return chain._client + }, + } + return chain + }, + trackPostProcessPromise: vi.fn(), + } +}) + +// Mock the RSC decoder so we can control resolution. +vi.mock('@vitejs/plugin-rsc/browser', () => { + return { + createFromReadableStream: vi.fn(), + } +}) + +vi.mock('@vitejs/plugin-rsc/ssr', () => { + return { + createFromReadableStream: vi.fn(), + } +}) + +import { createFromReadableStream as browserDecode } from '@vitejs/plugin-rsc/browser' + +import { + createCompositeFromStream, + createServerComponentFromStream, +} from '../src/createServerComponentFromStream' +import { + SERVER_COMPONENT_CSS_HREFS, + SERVER_COMPONENT_JS_PRELOADS, +} from '../src/ServerComponentTypes' + +describe('ServerComponent (client)', () => { + it('decodes a stream only once', async () => { + const stream = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1, 2, 3])) + controller.close() + }, + }) + + let createdReadableStream: ReadableStream | undefined + let resolvePromise: (value: React.ReactNode) => void + + const decodePromise = new Promise((resolve) => { + resolvePromise = resolve + }) + + const decodeMock = browserDecode as unknown as ReturnType + decodeMock.mockImplementation((rs: ReadableStream) => { + createdReadableStream = rs + return decodePromise + }) + + const Component = createServerComponentFromStream(stream) + + const { CompositeComponent } = await import('../src/CompositeComponent') + + await act(async () => { + render( + loading}> + + + , + ) + + // Flush Suspense/use() microtasks + await Promise.resolve() + }) + + // Should only decode once even though we render twice + expect(decodeMock).toHaveBeenCalledTimes(1) + expect(createdReadableStream).toBeDefined() + + // Resolve the decode to complete the test cleanly + resolvePromise!(React.createElement('div', null, 'ok')) + }) + + it('defers decode when SSR asset deps are provided', async () => { + const stream = new ReadableStream({ + start(controller) { + controller.close() + }, + }) + + const decodeMock = browserDecode as unknown as ReturnType + decodeMock.mockClear() + decodeMock.mockResolvedValue(React.createElement('div', null, 'ok')) + + const Component = createCompositeFromStream(stream, { + cssHrefs: ['/assets/component.css'], + jsPreloads: ['/assets/component.js'], + }) + + expect(decodeMock).not.toHaveBeenCalled() + expect(Array.from(Component[SERVER_COMPONENT_CSS_HREFS]!)).toEqual([ + '/assets/component.css', + ]) + expect(Array.from(Component[SERVER_COMPONENT_JS_PRELOADS]!)).toEqual([ + '/assets/component.js', + ]) + }) +}) diff --git a/packages/react-start-rsc/tests/SlotContext.test.tsx b/packages/react-start-rsc/tests/SlotContext.test.tsx new file mode 100644 index 0000000000..9590e44f8c --- /dev/null +++ b/packages/react-start-rsc/tests/SlotContext.test.tsx @@ -0,0 +1,114 @@ +import { describe, expect, it } from 'vitest' +import { render, screen } from '@testing-library/react' +import { SlotProvider, useSlotContext } from '../src/SlotContext' + +describe('SlotContext', () => { + describe('SlotProvider', () => { + it('should provide implementations to children', () => { + function Consumer() { + const ctx = useSlotContext() + return
    {JSON.stringify(ctx)}
    + } + + render( + + + , + ) + + const result = screen.getByTestId('result') + const ctx = JSON.parse(result.textContent!) + expect(ctx.implementations).toEqual({ foo: 'bar' }) + expect(ctx.strict).toBe(false) + }) + + it('should support strict mode', () => { + function Consumer() { + const ctx = useSlotContext() + return
    {String(ctx?.strict)}
    + } + + render( + + + , + ) + + expect(screen.getByTestId('strict').textContent).toBe('true') + }) + + it('should default strict to false', () => { + function Consumer() { + const ctx = useSlotContext() + return
    {String(ctx?.strict)}
    + } + + render( + + + , + ) + + expect(screen.getByTestId('strict').textContent).toBe('false') + }) + + it('should render children', () => { + render( + +
    Child content
    +
    , + ) + + expect(screen.getByTestId('child').textContent).toBe('Child content') + }) + }) + + describe('useSlotContext', () => { + it('should return null outside of SlotProvider', () => { + function Consumer() { + const ctx = useSlotContext() + return ( +
    {ctx === null ? 'null' : 'has value'}
    + ) + } + + render() + + expect(screen.getByTestId('ctx').textContent).toBe('null') + }) + + it('should access nested implementations', () => { + function Consumer() { + const ctx = useSlotContext() + const nested = ctx?.implementations.nested as { deep: string } + return
    {nested?.deep}
    + } + + render( + + + , + ) + + expect(screen.getByTestId('deep').textContent).toBe('value') + }) + + it('should access function implementations', () => { + function Consumer() { + const ctx = useSlotContext() + const fn = ctx?.implementations.renderItem as (n: number) => string + return
    {fn?.(42)}
    + } + + render( + `Item ${n}` }} + > + + , + ) + + expect(screen.getByTestId('fn-result').textContent).toBe('Item 42') + }) + }) +}) diff --git a/packages/react-start-rsc/tests/createRscProxy.test.tsx b/packages/react-start-rsc/tests/createRscProxy.test.tsx new file mode 100644 index 0000000000..3a17c54135 --- /dev/null +++ b/packages/react-start-rsc/tests/createRscProxy.test.tsx @@ -0,0 +1,252 @@ +import React from 'react' +import { describe, expect, it } from 'vitest' +import { render, screen } from '@testing-library/react' +import { ReactElement, ReactLazy } from '../src/reactSymbols' + +import { createRscProxy } from '../src/createRscProxy' +import { awaitLazyElements } from '../src/awaitLazyElements' + +describe('createRscProxy prop access', () => { + it('tracks which props React accesses during rendering', () => { + const accessedProps: Array = [] + const tree = React.createElement('div', null, 'test content') + + // Create a proxy that tracks all property access + const trackingProxy = new Proxy(function RscProxy() {}, { + get(_target, prop) { + accessedProps.push(prop) + + // Return values that allow React to proceed + if (prop === 'then') return undefined + if (prop === 'constructor') return Function + if (prop === Symbol.toStringTag) return 'RscProxy' + if (prop === Symbol.toPrimitive) return () => 'RscProxy' + if (prop === 'toString') return () => 'RscProxy' + if (prop === 'valueOf') return () => _target + if (prop === 'displayName') return 'RscProxy' + if (prop === 'name') return 'RscProxy' + if (prop === 'length') return 0 + if (prop === 'contextTypes') return undefined + if (prop === 'childContextTypes') return undefined + if (prop === 'getDerivedStateFromProps') return undefined + if (prop === 'defaultProps') return undefined + if (prop === 'propTypes') return undefined + if (prop === 'getDefaultProps') return undefined + if (typeof prop === 'symbol') return undefined + + return undefined + }, + apply() { + // Return actual React element when called + return tree + }, + has() { + return true + }, + getPrototypeOf() { + return Function.prototype + }, + }) + + function Wrapper() { + const Component = trackingProxy as any + return + } + + render() + + expect(screen.getByText('test content')).toBeDefined() + + const uniqueProps = [...new Set(accessedProps.map((p) => String(p)))] + + // Keep this strict: it proves what React probes in this env. + // This is NOT a contract for our proxy implementation. + expect(uniqueProps.sort()).toEqual( + [ + '$$typeof', + 'Symbol(Symbol.toStringTag)', + 'childContextTypes', + 'contextType', + 'contextTypes', + 'displayName', + 'getDerivedStateFromProps', + 'prototype', + ].sort(), + ) + }) + + it('renders correctly with minimal prop handling', () => { + const tree = React.createElement('div', null, 'minimal test') + + // Test with ONLY the critical props - no DevTools props + const minimalProxy = new Proxy(function RscProxy() {}, { + get(_target, prop) { + // Critical props only + if (prop === 'then') return undefined + if (prop === 'constructor') return Function + + // Legacy class component props + switch (prop) { + case 'contextTypes': + case 'childContextTypes': + case 'getDerivedStateFromProps': + case 'defaultProps': + case 'propTypes': + case 'getDefaultProps': + return undefined + } + + // Unknown symbols + if (typeof prop === 'symbol') return undefined + + return undefined + }, + apply() { + return tree + }, + has() { + return true + }, + getPrototypeOf() { + return Function.prototype + }, + }) + + function Wrapper() { + const Component = minimalProxy as any + return + } + + // This should render without errors even with minimal props + render() + + expect(screen.getByText('minimal test')).toBeDefined() + }) +}) + +describe('awaitLazyElements', () => { + /** + * Creates a mock lazy element similar to what Flight decoder produces. + * The _payload has a status and is thenable. + */ + function createMockLazy(initialStatus: 'pending' | 'fulfilled' = 'pending') { + let status = initialStatus + const callbacks: Array<() => void> = [] + + const payload = { + get status() { + return status + }, + then(onFulfill: () => void) { + if (status === 'fulfilled') { + queueMicrotask(onFulfill) + } else { + callbacks.push(onFulfill) + } + }, + } + + return { + $$typeof: ReactLazy, + _payload: payload, + _resolve() { + status = 'fulfilled' + callbacks.forEach((cb) => cb()) + callbacks.length = 0 + }, + } + } + + it('awaits pending lazy elements', async () => { + const lazy = createMockLazy() + + // Resolve after a microtask + queueMicrotask(() => lazy._resolve()) + + await awaitLazyElements(lazy) + + expect(lazy._payload.status).toBe('fulfilled') + }) + + it('skips already fulfilled lazy elements', async () => { + const lazy = createMockLazy('fulfilled') + + // Should complete immediately without hanging + await awaitLazyElements(lazy) + + expect(lazy._payload.status).toBe('fulfilled') + }) + + it('handles multiple lazy elements at different depths', async () => { + const lazy1 = createMockLazy() + const lazy2 = createMockLazy() + const lazy3 = createMockLazy() + + const tree = { + $$typeof: ReactElement, + type: 'div', + props: { + children: [ + lazy1, + { + $$typeof: ReactElement, + type: 'div', + props: { + children: [ + lazy2, + { + $$typeof: ReactElement, + type: 'span', + props: { children: lazy3 }, + }, + ], + }, + }, + ], + }, + } + + // Resolve all after microtasks + queueMicrotask(() => { + lazy1._resolve() + lazy2._resolve() + lazy3._resolve() + }) + + await awaitLazyElements(tree) + + expect(lazy1._payload.status).toBe('fulfilled') + expect(lazy2._payload.status).toBe('fulfilled') + expect(lazy3._payload.status).toBe('fulfilled') + }) + + it('stops at Suspense boundaries', async () => { + const lazyInsideSuspense = createMockLazy() + const lazyOutsideSuspense = createMockLazy() + + const tree = { + $$typeof: ReactElement, + type: 'div', + props: { + children: [ + lazyOutsideSuspense, + { + $$typeof: ReactElement, + type: Symbol.for('react.suspense'), + props: { children: lazyInsideSuspense }, + }, + ], + }, + } + + // Only resolve the outside one + queueMicrotask(() => lazyOutsideSuspense._resolve()) + + await awaitLazyElements(tree) + + // Outside should be resolved + expect(lazyOutsideSuspense._payload.status).toBe('fulfilled') + // Inside Suspense should NOT be awaited (still pending) + expect(lazyInsideSuspense._payload.status).toBe('pending') + }) +}) diff --git a/packages/react-start-rsc/tests/createServerComponent.test-d.tsx b/packages/react-start-rsc/tests/createServerComponent.test-d.tsx new file mode 100644 index 0000000000..320ef4f30a --- /dev/null +++ b/packages/react-start-rsc/tests/createServerComponent.test-d.tsx @@ -0,0 +1,98 @@ +import { expectTypeOf, test } from 'vitest' +import type { + CompositeComponentResult, + ValidateCompositeComponent, +} from '../src/ServerComponentTypes' +import { CompositeComponent } from '../src/CompositeComponent' + +import { JSX } from 'react' + +test('when a server component is created with no props', () => { + type Post = () => React.ReactNode + type PostComponent = CompositeComponentResult + + const node = null as unknown as JSX.Element + expectTypeOf(node).toEqualTypeOf() +}) + +test('when a server component is created with props but no slots', () => { + type Post = (props: { num: number }) => React.ReactNode + type PostComponent = CompositeComponentResult + + const node = null as unknown as JSX.Element + expectTypeOf(node).toEqualTypeOf() + expectTypeOf(null as unknown as typeof CompositeComponent) + .parameter(0) + .branded.toEqualTypeOf<{ src: PostComponent; num: number }>() +}) + +test('when a server component is created with child slots and props', () => { + type Post = (props: { + children: React.ReactNode + num: number + }) => React.ReactNode + type PostComponent = CompositeComponentResult + + const node = null as unknown as JSX.Element + expectTypeOf(node).toEqualTypeOf() + expectTypeOf(null as unknown as typeof CompositeComponent) + .parameter(0) + .branded.toEqualTypeOf<{ + src: PostComponent + num: number + children: React.ReactNode + }>() +}) + +test('when a server component is created with slots with no props', () => { + type Post = (props: { render: () => React.ReactNode }) => React.ReactNode + type PostComponent = CompositeComponentResult + + const node = null as unknown as JSX.Element + expectTypeOf(node).toEqualTypeOf() + + expectTypeOf(null as unknown as typeof CompositeComponent) + .parameter(0) + .branded.toEqualTypeOf<{ + src: PostComponent + render: () => React.ReactNode + }>() +}) + +test('when a server component is created with slots with serializable props', () => { + type Post = (props: { + render: (index: number) => React.ReactNode + }) => React.ReactNode + + type PostComponent = CompositeComponentResult + + const node = null as unknown as JSX.Element + expectTypeOf(node).toEqualTypeOf() + + expectTypeOf(null as unknown as typeof CompositeComponent) + .parameter(0) + .branded.toEqualTypeOf<{ + src: PostComponent + render: (index: number) => React.ReactNode + }>() +}) + +test('when a server component is created with slots with not serializable props', () => { + type Post = (props: { + render: (props: { func: () => void }) => React.ReactNode + }) => React.ReactNode + + expectTypeOf>().toEqualTypeOf< + (props: { + render: (props: { + func: 'Function is not serializable' + }) => React.ReactNode + }) => React.ReactNode + >() +}) + +test('when server component type has incorrect return type', () => { + expectTypeOf void>>().toEqualTypeOf< + (props: unknown) => React.ReactNode + >() +}) diff --git a/packages/react-start-rsc/tests/renderServerComponent.types.test-d.tsx b/packages/react-start-rsc/tests/renderServerComponent.types.test-d.tsx new file mode 100644 index 0000000000..5d9f6f59b4 --- /dev/null +++ b/packages/react-start-rsc/tests/renderServerComponent.types.test-d.tsx @@ -0,0 +1,30 @@ +import { expectTypeOf, test } from 'vitest' +import type { ReactElement } from 'react' + +import { renderServerComponent } from '../src/renderServerComponent.stub' +import type { + RenderServerComponentElement, + RenderServerComponentResult, +} from '../src/ServerComponentTypes' + +test('renderServerComponent infers nested access type', () => { + function MyServerComponent(_props: {}): any { + throw new Error('not executed') + } + + const element = null as unknown as RenderServerComponentElement<{ + foo: { bar: ReactElement } + }> + + const dataPromise = renderServerComponent(element) + + type Data = Awaited + + // nested selection + expectTypeOf().toHaveProperty('foo') + expectTypeOf().toHaveProperty('bar') + + // also: directly renderable at top-level + type MustBeRenderable = true + expectTypeOf().toEqualTypeOf() +}) diff --git a/packages/react-start-rsc/tests/rscCssTransform.test.tsx b/packages/react-start-rsc/tests/rscCssTransform.test.tsx new file mode 100644 index 0000000000..afc4686e94 --- /dev/null +++ b/packages/react-start-rsc/tests/rscCssTransform.test.tsx @@ -0,0 +1,215 @@ +import { describe, expect, test } from 'vitest' +import { + StartCompiler, + detectKindsInCode, + getLookupKindsForEnv, +} from '../../start-plugin-core/src/start-compiler/compiler' +import { getLookupConfigurationsForEnv } from '../../start-plugin-core/src/start-compiler/config' +import { createRscCssCompilerTransforms } from '../src/plugin/rscCssTransform' +import type { StartCompilerImportTransform } from '../../start-plugin-core/src/types' + +const TSS_SERVERFN_SPLIT_PARAM = 'tss-serverfn-split' + +async function compileWithRscCssTransform(opts: { + code: string + id?: string | undefined + loadCssExpression?: string | undefined + serverFnProviderOnly?: boolean | undefined +}) { + const compilerTransforms = createRscCssCompilerTransforms({ + loadCssExpression: + opts.loadCssExpression ?? 'import.meta.viteRsc.loadCss()', + serverFnProviderOnly: opts.serverFnProviderOnly, + }) + + const compiler = new StartCompiler({ + env: 'server', + envName: 'rsc', + root: '/test', + framework: 'react', + providerEnvName: 'rsc', + mode: 'build', + lookupKinds: getLookupKindsForEnv('server', { compilerTransforms }), + lookupConfigurations: getLookupConfigurationsForEnv('server', 'react', { + compilerTransforms, + }), + compilerTransforms, + getKnownServerFns: () => ({}), + loadModule: async () => {}, + resolveId: async (id) => id, + }) + + const result = await compiler.compile({ + id: opts.id ?? '/test/src/route.tsx', + code: opts.code, + detectedKinds: detectKindsInCode(opts.code, 'server', { + compilerTransforms, + }), + }) + + return result?.code ?? null +} + +describe('RSC CSS compiler transforms', () => { + test('injects Vite CSS resources into all supported RSC render APIs', async () => { + const code = await compileWithRscCssTransform({ + code: ` + import { + createCompositeComponent, + renderServerComponent, + renderToReadableStream, + } from '@tanstack/react-start/rsc' + + export const renderable = renderServerComponent() + export const composite = createCompositeComponent(() => ({ + Card: , + })) + export const stream = renderToReadableStream() + `, + }) + + expect(code).toMatchInlineSnapshot(` + "import { createCompositeComponent, renderServerComponent, renderToReadableStream } from '@tanstack/react-start/rsc'; + export const renderable = renderServerComponent(, { + __tanstackStartRscCss: import.meta.viteRsc.loadCss() + }); + export const composite = createCompositeComponent(() => ({ + Card: + }), { + __tanstackStartRscCss: import.meta.viteRsc.loadCss() + }); + export const stream = renderToReadableStream(<>{import.meta.viteRsc.loadCss()});" + `) + }) + + test('does not rewrite calls outside the transform constraints', async () => { + const code = await compileWithRscCssTransform({ + code: ` + import { + renderServerComponent, + renderToReadableStream, + } from '@tanstack/react-start/rsc' + + const node = + export const existingOptions = renderServerComponent(, { + alreadyConfigured: true, + }) + export const nonJsxStream = renderToReadableStream(node) + `, + }) + + expect(code).toMatchInlineSnapshot(` + "import { renderServerComponent, renderToReadableStream } from '@tanstack/react-start/rsc'; + const node = ; + export const existingOptions = renderServerComponent(, { + alreadyConfigured: true + }); + export const nonJsxStream = renderToReadableStream(node);" + `) + }) + + test('honors provider-only transforms for Rsbuild', async () => { + const source = ` + import { renderServerComponent } from '@tanstack/react-start/rsc' + + export const renderable = renderServerComponent() + ` + + const callerCode = await compileWithRscCssTransform({ + code: source, + loadCssExpression: 'import.meta.rspackRsc.loadCss()', + serverFnProviderOnly: true, + }) + + const providerCode = await compileWithRscCssTransform({ + code: source, + id: `/test/src/route.tsx?${TSS_SERVERFN_SPLIT_PARAM}`, + loadCssExpression: 'import.meta.rspackRsc.loadCss()', + serverFnProviderOnly: true, + }) + + expect({ callerCode, providerCode }).toMatchInlineSnapshot(` + { + "callerCode": "import { renderServerComponent } from '@tanstack/react-start/rsc'; + export const renderable = renderServerComponent();", + "providerCode": "import { renderServerComponent } from '@tanstack/react-start/rsc'; + export const renderable = renderServerComponent(, { + __tanstackStartRscCss: import.meta.rspackRsc.loadCss() + });", + } + `) + }) + + test('detects transform imports without enabling them outside server builds', () => { + const compilerTransforms: Array = + createRscCssCompilerTransforms({ + loadCssExpression: 'import.meta.viteRsc.loadCss()', + }) + + const code = ` + import { renderServerComponent } from '@tanstack/react-start/rsc' + export const renderable = renderServerComponent() + ` + + expect(detectKindsInCode(code, 'server', { compilerTransforms })) + .toMatchInlineSnapshot(` + Set { + "External:react-rsc-render-server-component-css", + } + `) + expect( + detectKindsInCode(code, 'client', { compilerTransforms }), + ).toMatchInlineSnapshot(`Set {}`) + }) + + test('rewrites render APIs imported from @tanstack/react-start-rsc', async () => { + const code = await compileWithRscCssTransform({ + code: ` + import { renderServerComponent } from '@tanstack/react-start-rsc' + + export const renderable = renderServerComponent() + `, + }) + + expect(code).toContain( + '__tanstackStartRscCss: import.meta.viteRsc.loadCss()', + ) + }) + + test.each([ + { wrapped: '()', bare: '' }, + { wrapped: ' as any', bare: '' }, + { wrapped: '!', bare: '' }, + { wrapped: '(<>) satisfies unknown', bare: '<>' }, + ])( + 'streams $wrapped like the bare JSX it wraps', + async ({ wrapped, bare }) => { + const compileStream = (element: string) => + compileWithRscCssTransform({ + code: ` + import { renderToReadableStream } from '@tanstack/react-start/rsc' + + export const stream = renderToReadableStream(${element}) + `, + }) + + const bareCode = await compileStream(bare) + expect(bareCode).toContain('import.meta.viteRsc.loadCss()') + expect(await compileStream(wrapped)).toBe(bareCode) + }, + ) + + test('does not stream JSX that is not the whole argument', async () => { + const code = await compileWithRscCssTransform({ + code: ` + import { renderToReadableStream } from '@tanstack/react-start/rsc' + + export const conditional = renderToReadableStream(flag ? : ) + export const spread = renderToReadableStream(...args) + `, + }) + + expect(code).toContain('renderToReadableStream(...args)') + expect(code).not.toContain('loadCss') + }) +}) diff --git a/packages/react-start-rsc/tests/setup.ts b/packages/react-start-rsc/tests/setup.ts new file mode 100644 index 0000000000..82055721d7 --- /dev/null +++ b/packages/react-start-rsc/tests/setup.ts @@ -0,0 +1,7 @@ +import { cleanup } from '@testing-library/react' +import { afterEach } from 'vitest' + +// Clean up after each test +afterEach(() => { + cleanup() +}) diff --git a/packages/react-start-rsc/tsconfig.json b/packages/react-start-rsc/tsconfig.json new file mode 100644 index 0000000000..8e611ace3b --- /dev/null +++ b/packages/react-start-rsc/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "module": "esnext", + "lib": ["DOM", "DOM.Iterable", "ESNext"] + }, + "include": ["src", "vite.config.ts"] +} diff --git a/packages/react-start-rsc/vite.config.ts b/packages/react-start-rsc/vite.config.ts new file mode 100644 index 0000000000..c8dfcf917b --- /dev/null +++ b/packages/react-start-rsc/vite.config.ts @@ -0,0 +1,58 @@ +import { defineConfig, mergeConfig } from 'vitest/config' +import { tanstackViteConfig } from '@tanstack/vite-config' +import react from '@vitejs/plugin-react' +import { copyFilesPlugin } from '@tanstack/router-utils' +import packageJson from './package.json' + +const config = defineConfig({ + resolve: { + alias: { + 'virtual:tanstack-rsc-browser-decode': '@vitejs/plugin-rsc/browser', + }, + }, + plugins: [ + react(), + copyFilesPlugin({ + pattern: ['*.ts', '*.tsx', '!*.d.ts'], + fromDir: 'src/entry', + toDir: 'dist/plugin/entry', + }), + ], + test: { + include: ['**/*.{test-d,test,spec}.?(c|m)[jt]s?(x)'], + name: packageJson.name, + watch: false, + environment: 'jsdom', + setupFiles: ['./tests/setup.ts'], + }, +}) + +export default mergeConfig( + config, + tanstackViteConfig({ + srcDir: './src', + entry: [ + './src/index.ts', + './src/index.rsc.ts', + './src/serialization.client.ts', + './src/serialization.server.ts', + './src/plugin/rscCssTransform.ts', + './src/plugin/vite.ts', + './src/entry/rsc.tsx', + './src/rsbuild/ssr-decode.ts', + './src/rsbuild/browser-decode.ts', + ], + cjs: false, + // Externalize virtual modules and SSR-only imports - resolved at runtime by Vite plugins + externalDeps: [ + 'virtual:tanstack-rsc-runtime', + 'virtual:tanstack-rsc-browser-decode', + 'virtual:tanstack-rsc-ssr-decode', + 'virtual:tanstack-rsc-hmr', + '#tanstack-start-server-fn-resolver', + 'react-server-dom-rspack/client.node', + 'react-server-dom-rspack/client.browser', + 'react-server-dom-rspack/server', + ], + }), +) diff --git a/packages/react-start-server/CHANGELOG.md b/packages/react-start-server/CHANGELOG.md new file mode 100644 index 0000000000..86d7854a59 --- /dev/null +++ b/packages/react-start-server/CHANGELOG.md @@ -0,0 +1,900 @@ +# @tanstack/react-start-server + +## 1.167.52 + +### Patch Changes + +- Updated dependencies [[`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c), [`689a7c5`](https://github.com/TanStack/router/commit/689a7c5419de68bce0aaaef72b9a36f115ea1398)]: + - @tanstack/react-router@1.170.46 + - @tanstack/router-core@1.171.39 + - @tanstack/start-server-core@1.169.45 + +## 1.167.51 + +### Patch Changes + +- Updated dependencies [[`18154b1`](https://github.com/TanStack/router/commit/18154b1c45454a70aa77e9d6d27c8a6e0733d031)]: + - @tanstack/router-core@1.171.38 + - @tanstack/start-server-core@1.169.44 + - @tanstack/react-router@1.170.45 + +## 1.167.50 + +### Patch Changes + +- Updated dependencies [[`71d9694`](https://github.com/TanStack/router/commit/71d9694da6346fbece2cda4ecde92b0b12a7ee08)]: + - @tanstack/start-server-core@1.169.43 + +## 1.167.49 + +### Patch Changes + +- Updated dependencies [[`740b0ce`](https://github.com/TanStack/router/commit/740b0ce17737d1f7398740136acdbeabe80df7d8), [`d6ba115`](https://github.com/TanStack/router/commit/d6ba115d5751c75e20943f0062577cf17b446d82)]: + - @tanstack/start-server-core@1.169.42 + - @tanstack/router-core@1.171.37 + - @tanstack/react-router@1.170.44 + +## 1.167.48 + +### Patch Changes + +- [#7588](https://github.com/TanStack/router/pull/7588) [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5) - Remove the built-in `useSession` API. Applications choose a session library, such as iron-session, and save or destroy sessions explicitly before returning or redirecting. Connect a cookie adapter through `getCookie` and `setCookie`, or append serialized cookies with `appendResponseHeader('set-cookie', cookie)`. Existing session cookies require a deliberate migration or signing in again with a new cookie name. + + `createServerEntry` keeps the complete callback, including custom error handling, inside the request context and converts errors that escape it. The built-in entry still converts errors automatically. Raw `createStartHandler` handlers now rethrow the original error. For custom reporting, catch inside `createServerEntry`, then rethrow for default conversion or return `handleStartError(error)` to preserve response-helper status, headers, and cookies. Return an explicit `Response` when choosing a custom error payload. + + Response helpers now apply consistently across server routes, SSR, server functions, redirects, errors, and middleware response replacements. Helper setters override returned values; cookie helpers preserve independent cookies and replace matching cookie identities. Use `appendResponseHeader('set-cookie', cookie)` when adding a serialized cookie without replacing other cookies. Changed responses receive copied headers and reuse the body stream, so applications should inspect the response returned by Start rather than relying on mutation of the original response. + +- Updated dependencies [[`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5)]: + - @tanstack/router-core@1.171.36 + - @tanstack/start-server-core@1.169.41 + - @tanstack/react-router@1.170.43 + +## 1.167.47 + +### Patch Changes + +- Updated dependencies [[`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`2413cc0`](https://github.com/TanStack/router/commit/2413cc009826fba4f97b166a35a8a50a4a8fe4bb), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`d35aab4`](https://github.com/TanStack/router/commit/d35aab425b07b46e222a507c0f0239644669757b), [`663282b`](https://github.com/TanStack/router/commit/663282b0ebbc494aee3595ed95867ee29d01938e)]: + - @tanstack/router-core@1.171.35 + - @tanstack/react-router@1.170.42 + - @tanstack/start-server-core@1.169.40 + +## 1.167.46 + +### Patch Changes + +- Updated dependencies [[`60b8ad1`](https://github.com/TanStack/router/commit/60b8ad1ad00812bf966a8eeee6be238c37ddad74), [`614bc27`](https://github.com/TanStack/router/commit/614bc27034c8ec98747bf305ed41d4a619640949), [`d521abd`](https://github.com/TanStack/router/commit/d521abd71c69f1ff010bb3def4d417cb5fa058cb), [`ff66a03`](https://github.com/TanStack/router/commit/ff66a03df4816f44a48a4a37189fc4021b1c8480), [`863c8a7`](https://github.com/TanStack/router/commit/863c8a736b96746c56278a16c50554356f5523d1)]: + - @tanstack/react-router@1.170.41 + - @tanstack/router-core@1.171.34 + - @tanstack/start-server-core@1.169.39 + +## 1.167.45 + +### Patch Changes + +- Updated dependencies [[`f5ffd38`](https://github.com/TanStack/router/commit/f5ffd3884ba26778a2a8ce53b379a5bded231676), [`488d046`](https://github.com/TanStack/router/commit/488d046a907d330429e2c807ef95326dad87480f), [`e81845f`](https://github.com/TanStack/router/commit/e81845ff1e4fc66d4e4a87f086be65906f7adb94), [`0c1b5e3`](https://github.com/TanStack/router/commit/0c1b5e38de71b7e81bbf1fd81c73ee0cd68ffe47), [`3cdd1af`](https://github.com/TanStack/router/commit/3cdd1af04b3e2d6f777797ee7bddf285318dd9d2)]: + - @tanstack/react-router@1.170.40 + - @tanstack/router-core@1.171.33 + - @tanstack/start-server-core@1.169.38 + +## 1.167.44 + +### Patch Changes + +- Updated dependencies [[`73bfc15`](https://github.com/TanStack/router/commit/73bfc153eef460e9b670556215a5adb2b5cbf542)]: + - @tanstack/react-router@1.170.39 + +## 1.167.43 + +### Patch Changes + +- Updated dependencies [[`cecae54`](https://github.com/TanStack/router/commit/cecae5440b8edaea77c5448fe3d74bbd20fe10a4), [`0103578`](https://github.com/TanStack/router/commit/01035782e53af9b929c784b94ddd64b95efb89c7), [`ce10dcd`](https://github.com/TanStack/router/commit/ce10dcd4d9d3d23738744e453205aad5c6dbd716), [`84936cc`](https://github.com/TanStack/router/commit/84936cc04530bba11059c57b293a794922bbc5aa), [`bbd2336`](https://github.com/TanStack/router/commit/bbd2336b8446de3f7dd85070895e7cf43980183e)]: + - @tanstack/router-core@1.171.32 + - @tanstack/react-router@1.170.38 + - @tanstack/start-server-core@1.169.37 + +## 1.167.42 + +### Patch Changes + +- Updated dependencies [[`bc80866`](https://github.com/TanStack/router/commit/bc80866f6d6eb3e6f152ee3682eb783c96403e83), [`e561fa1`](https://github.com/TanStack/router/commit/e561fa1d7118e3d29267cc3b6ce1130d6581f387), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a1c8d1a`](https://github.com/TanStack/router/commit/a1c8d1aa759c227eae9601a030321ac4c53c24bd), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a0b2ad9`](https://github.com/TanStack/router/commit/a0b2ad99aee64af08d16b0e4ff26b3ba42a99f0a), [`8e164d2`](https://github.com/TanStack/router/commit/8e164d28f9e9eb1a7301109230d7ece9817492a8), [`1ca361b`](https://github.com/TanStack/router/commit/1ca361ba52a627d2f76ab33323bd83d1d0aa65a3)]: + - @tanstack/router-core@1.171.31 + - @tanstack/react-router@1.170.37 + - @tanstack/start-server-core@1.169.36 + +## 1.167.41 + +### Patch Changes + +- Updated dependencies [[`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776), [`6cfb1e8`](https://github.com/TanStack/router/commit/6cfb1e8b564be282584765352250bf61747895ed), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8), [`873c830`](https://github.com/TanStack/router/commit/873c830ccb2610a864ee697250e10fcc99772ffa), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`f151ab0`](https://github.com/TanStack/router/commit/f151ab018eede64ae849b77e68f3cdf31cb95cc5), [`bc57fa3`](https://github.com/TanStack/router/commit/bc57fa3f12450cf34c731450947c7c8f1ea05e58), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9448caa`](https://github.com/TanStack/router/commit/9448caa03a89076b9770631c356c0cc502802c09), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef)]: + - @tanstack/router-core@1.171.30 + - @tanstack/react-router@1.170.36 + - @tanstack/start-server-core@1.169.35 + +## 1.167.40 + +### Patch Changes + +- Updated dependencies [[`8c43c71`](https://github.com/TanStack/router/commit/8c43c712523fc63dc3a814f3a19617e270ce8ed1), [`d914b08`](https://github.com/TanStack/router/commit/d914b085bb4bf29ec18a531201e377c10681b661)]: + - @tanstack/react-router@1.170.35 + - @tanstack/start-server-core@1.169.34 + +## 1.167.39 + +### Patch Changes + +- Updated dependencies [[`f9836f1`](https://github.com/TanStack/router/commit/f9836f16f0e25b0a8495f5e01e3f303b1cbc8725), [`aee42c6`](https://github.com/TanStack/router/commit/aee42c6b641d8e919bfed9e0f04bb1b72092f3a6), [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8), [`9aec5a7`](https://github.com/TanStack/router/commit/9aec5a7012c47e83ec23bb4763494b72a5e68bfc), [`9871c06`](https://github.com/TanStack/router/commit/9871c0625806001d6bf373524821a00303438a91), [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9)]: + - @tanstack/router-core@1.171.29 + - @tanstack/react-router@1.170.34 + - @tanstack/start-server-core@1.169.33 + +## 1.167.38 + +### Patch Changes + +- Updated dependencies [[`edf0e16`](https://github.com/TanStack/router/commit/edf0e16ebfe82ec6e8f68f403a1fda8de9e28889), [`2f20c00`](https://github.com/TanStack/router/commit/2f20c00224c5ba63467551914e0c37012588c4c2), [`28a5e45`](https://github.com/TanStack/router/commit/28a5e4504e4ea5cb1480667a4bea2588a53e110f), [`08eff50`](https://github.com/TanStack/router/commit/08eff50c447a154a3373909009e9e4375cea17ce), [`216c0c4`](https://github.com/TanStack/router/commit/216c0c48036fd1a33163b70dcabfed2b893808b0), [`2f91503`](https://github.com/TanStack/router/commit/2f9150309bc472f4a75cbe98adcdb50c76b12c7a), [`f0b5eda`](https://github.com/TanStack/router/commit/f0b5eda544606686a8a8d675a686ca1366428b96), [`50eafca`](https://github.com/TanStack/router/commit/50eafcaebbbedb6fde3b2816de7a0ace8cde4832), [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b), [`0caf6b9`](https://github.com/TanStack/router/commit/0caf6b9a2b7e14b0b146c74cc27cb05c19d700a5), [`ee28348`](https://github.com/TanStack/router/commit/ee283480dfa51150a2e0b096a6eff94a89ff8b3f), [`cf166d1`](https://github.com/TanStack/router/commit/cf166d160e6397007a979bfc7065b45ff69ea543), [`c18e690`](https://github.com/TanStack/router/commit/c18e69081475a7c98f9d40bd0fe6da78ccb84598)]: + - @tanstack/router-core@1.171.28 + - @tanstack/react-router@1.170.33 + - @tanstack/start-server-core@1.169.32 + +## 1.167.37 + +### Patch Changes + +- Updated dependencies [[`fa65287`](https://github.com/TanStack/router/commit/fa652872812c9433ba8b9d9a285e51b535e7367c), [`cb281d7`](https://github.com/TanStack/router/commit/cb281d70c1f5fe780f9d07bc500ea3a284a4e04b)]: + - @tanstack/router-core@1.171.27 + - @tanstack/react-router@1.170.32 + - @tanstack/start-server-core@1.169.31 + +## 1.167.36 + +### Patch Changes + +- Updated dependencies [[`3e016ac`](https://github.com/TanStack/router/commit/3e016ac84ffec8119f0c25cfdd1fb17e5292bd34)]: + - @tanstack/router-core@1.171.26 + - @tanstack/react-router@1.170.31 + - @tanstack/start-server-core@1.169.30 + +## 1.167.35 + +### Patch Changes + +- Updated dependencies [[`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175), [`63d2cc9`](https://github.com/TanStack/router/commit/63d2cc9155ff5374112f7d067d0b278bafeb8486), [`f75cada`](https://github.com/TanStack/router/commit/f75cada01707e51fb9650dd301bc04f8b2265a2a)]: + - @tanstack/react-router@1.170.30 + - @tanstack/router-core@1.171.25 + - @tanstack/start-server-core@1.169.29 + +## 1.167.34 + +### Patch Changes + +- Updated dependencies [[`4c89b15`](https://github.com/TanStack/router/commit/4c89b15dd2b46491ee5e57985559bae8e31d62c2), [`cf6ab17`](https://github.com/TanStack/router/commit/cf6ab178b39e7628bf784759f384e0f4230e6d9e), [`0fdf9ff`](https://github.com/TanStack/router/commit/0fdf9ff16fc532de9fc131d18df167ebd8038720), [`bdaf73a`](https://github.com/TanStack/router/commit/bdaf73a4063ee2b02e3c9cc105ad10ce82a5a0ff)]: + - @tanstack/router-core@1.171.24 + - @tanstack/react-router@1.170.29 + - @tanstack/start-server-core@1.169.28 + +## 1.167.33 + +### Patch Changes + +- Updated dependencies [[`0c25a7b`](https://github.com/TanStack/router/commit/0c25a7b43b5331ee6ebf94d50e9793002783adab), [`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90)]: + - @tanstack/react-router@1.170.28 + - @tanstack/router-core@1.171.23 + - @tanstack/start-server-core@1.169.27 + +## 1.167.32 + +### Patch Changes + +- Updated dependencies [[`b0817f5`](https://github.com/TanStack/router/commit/b0817f50cc639ae50b6c30cd11c5adbf7eed028c)]: + - @tanstack/react-router@1.170.27 + +## 1.167.31 + +### Patch Changes + +- Updated dependencies [[`7e93431`](https://github.com/TanStack/router/commit/7e93431ae9ff58c91c3c5ca10ffcb8414c1d0b13), [`f500760`](https://github.com/TanStack/router/commit/f5007607d62e932b8df19de866cdc6bddcff8db3), [`1aafca9`](https://github.com/TanStack/router/commit/1aafca9b45d24f8f0dba78e716fc9582346c6ca1), [`aa10b65`](https://github.com/TanStack/router/commit/aa10b6589eeda215f5a60ea0af95a3101d8c414e)]: + - @tanstack/router-core@1.171.22 + - @tanstack/react-router@1.170.26 + - @tanstack/start-server-core@1.169.26 + +## 1.167.30 + +### Patch Changes + +- Updated dependencies [[`51138a8`](https://github.com/TanStack/router/commit/51138a824cea053738f125c4c95073bd6286ff05)]: + - @tanstack/router-core@1.171.21 + - @tanstack/react-router@1.170.25 + - @tanstack/start-server-core@1.169.25 + +## 1.167.29 + +### Patch Changes + +- Updated dependencies [[`44a8c3e`](https://github.com/TanStack/router/commit/44a8c3e1d2af305064b2363d97fc7847c6f1a246), [`5253e70`](https://github.com/TanStack/router/commit/5253e70db2083d68a788fb7c9a043bb0c5518f2a)]: + - @tanstack/router-core@1.171.20 + - @tanstack/react-router@1.170.24 + - @tanstack/start-server-core@1.169.24 + +## 1.167.28 + +### Patch Changes + +- Updated dependencies [[`95dec51`](https://github.com/TanStack/router/commit/95dec51018d01483949c6f1fe3094b019ccf3b4f)]: + - @tanstack/react-router@1.170.23 + - @tanstack/start-server-core@1.169.23 + +## 1.167.27 + +### Patch Changes + +- Updated dependencies [[`ea3a665`](https://github.com/TanStack/router/commit/ea3a665d81cbb5074c2d77ec953255ab534e7db9)]: + - @tanstack/react-router@1.170.22 + - @tanstack/router-core@1.171.19 + - @tanstack/start-server-core@1.169.22 + +## 1.167.26 + +### Patch Changes + +- Updated dependencies [[`697ebb6`](https://github.com/TanStack/router/commit/697ebb6ddbd433d052b6b4707938a5c595865d58), [`2435885`](https://github.com/TanStack/router/commit/2435885fa8b5e31c8c4b74d93920919f27316ebf), [`84db4a8`](https://github.com/TanStack/router/commit/84db4a842311df3f7e58073f6f12aaf371aeb5c7), [`9cac62a`](https://github.com/TanStack/router/commit/9cac62a5c7f99ef070991ea6f1fa7e42c746d46b), [`86bf510`](https://github.com/TanStack/router/commit/86bf510c2923afb76804223bd04afc2a809b33e7), [`6aefb33`](https://github.com/TanStack/router/commit/6aefb3392595a07a93f89301d7b5e3558ff9190c)]: + - @tanstack/react-router@1.170.21 + - @tanstack/router-core@1.171.18 + - @tanstack/start-server-core@1.169.21 + +## 1.167.25 + +### Patch Changes + +- Updated dependencies [[`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5)]: + - @tanstack/router-core@1.171.17 + - @tanstack/start-server-core@1.169.20 + - @tanstack/react-router@1.170.20 + +## 1.167.24 + +### Patch Changes + +- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: + - @tanstack/router-core@1.171.16 + - @tanstack/react-router@1.170.19 + - @tanstack/start-server-core@1.169.19 + +## 1.167.23 + +### Patch Changes + +- Updated dependencies [[`65f7b7f`](https://github.com/TanStack/router/commit/65f7b7f791272f2ea581a1fe0fcd43183bc01162)]: + - @tanstack/start-server-core@1.169.18 + +## 1.167.22 + +### Patch Changes + +- Updated dependencies [[`e2dd204`](https://github.com/TanStack/router/commit/e2dd2049cb42eb219d3b447b8605066d19d9c1fa)]: + - @tanstack/router-core@1.171.15 + - @tanstack/react-router@1.170.18 + - @tanstack/start-server-core@1.169.17 + +## 1.167.21 + +### Patch Changes + +- Updated dependencies [[`9809a06`](https://github.com/TanStack/router/commit/9809a0619d4ed3fe8c2a393af5b9eca4b6c7695b)]: + - @tanstack/router-core@1.171.14 + - @tanstack/react-router@1.170.17 + - @tanstack/start-server-core@1.169.16 + +## 1.167.20 + +### Patch Changes + +- Updated dependencies [[`52db703`](https://github.com/TanStack/router/commit/52db7034fd83b17cc45da9ba775ec253f2a9a149), [`4a93cff`](https://github.com/TanStack/router/commit/4a93cffffca34702e419bc47db827f964fd0cb65), [`96eca43`](https://github.com/TanStack/router/commit/96eca43ab8ee21917a8075521bef6dcf15fc7a43), [`f046b06`](https://github.com/TanStack/router/commit/f046b064d32222cad0b7ea061311ca9a474f5990), [`689d88e`](https://github.com/TanStack/router/commit/689d88e04c48ec76a18453ab8b82d8d58f2668b6), [`689c5ab`](https://github.com/TanStack/router/commit/689c5ab32e9bb18d90a5a94c33237b0e418df3e3)]: + - @tanstack/react-router@1.170.16 + - @tanstack/start-server-core@1.169.15 + +## 1.167.19 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-server-core@1.169.14 + +## 1.167.18 + +### Patch Changes + +- Updated dependencies [[`776d8ef`](https://github.com/TanStack/router/commit/776d8ef283e5bd9ffe97d43bc3a7f58064cd7e03)]: + - @tanstack/router-core@1.171.13 + - @tanstack/react-router@1.170.15 + - @tanstack/start-server-core@1.169.13 + +## 1.167.17 + +### Patch Changes + +- Updated dependencies [[`df1076c`](https://github.com/TanStack/router/commit/df1076c03ae5a51ab384bebd4d6afda20fb6f107)]: + - @tanstack/router-core@1.171.12 + - @tanstack/react-router@1.170.14 + - @tanstack/start-server-core@1.169.12 + +## 1.167.16 + +### Patch Changes + +- Updated dependencies [[`ac10815`](https://github.com/TanStack/router/commit/ac10815f387d25b15163ff711b4049e8f8482d01)]: + - @tanstack/router-core@1.171.11 + - @tanstack/react-router@1.170.13 + - @tanstack/start-server-core@1.169.11 + +## 1.167.15 + +### Patch Changes + +- Updated dependencies [[`2cca73c`](https://github.com/TanStack/router/commit/2cca73c92262ffd96dac4e283c9f69fb37f4b43a), [`7a83e67`](https://github.com/TanStack/router/commit/7a83e67e6596fbef21cb0a88a7127f5935bed2ba), [`76b3d3b`](https://github.com/TanStack/router/commit/76b3d3b24522bd3d1d216674c441252c9b8f184c)]: + - @tanstack/router-core@1.171.10 + - @tanstack/react-router@1.170.12 + - @tanstack/start-server-core@1.169.10 + +## 1.167.14 + +### Patch Changes + +- Updated dependencies [[`b4cd5af`](https://github.com/TanStack/router/commit/b4cd5af8d0f9d4aaa2d29095e6a261b9181bc778)]: + - @tanstack/router-core@1.171.9 + - @tanstack/react-router@1.170.11 + - @tanstack/start-client-core@1.170.7 + - @tanstack/start-server-core@1.169.9 + +## 1.167.13 + +### Patch Changes + +- Updated dependencies [[`9cb7a00`](https://github.com/TanStack/router/commit/9cb7a003e6e5fa3706711870c7b10a5266356e3b)]: + - @tanstack/start-server-core@1.169.8 + +## 1.167.12 + +### Patch Changes + +- Updated dependencies [[`2f53749`](https://github.com/TanStack/router/commit/2f5374945e2138559a51464f45a5152eae67e1dd)]: + - @tanstack/router-core@1.171.8 + - @tanstack/react-router@1.170.10 + - @tanstack/start-client-core@1.170.6 + - @tanstack/start-server-core@1.169.7 + +## 1.167.11 + +### Patch Changes + +- Updated dependencies [[`d1997b6`](https://github.com/TanStack/router/commit/d1997b66d7c24c1d64772bb8bab5caf9c6d9cc48)]: + - @tanstack/start-server-core@1.169.6 + - @tanstack/react-router@1.170.9 + - @tanstack/router-core@1.171.7 + - @tanstack/start-client-core@1.170.5 + +## 1.167.10 + +### Patch Changes + +- Updated dependencies [[`9c09bca`](https://github.com/TanStack/router/commit/9c09bca59e9613e9a6fd9b7149b0737898e705d6)]: + - @tanstack/start-server-core@1.169.5 + +## 1.167.9 + +### Patch Changes + +- Updated dependencies [[`a82cec6`](https://github.com/TanStack/router/commit/a82cec69474c366b36efdb3f43c4efe8311c485a), [`d8be4f8`](https://github.com/TanStack/router/commit/d8be4f8adf912128c96b7f83e9a6c49fb24b5eed)]: + - @tanstack/start-client-core@1.170.4 + - @tanstack/start-server-core@1.169.4 + +## 1.167.8 + +### Patch Changes + +- Updated dependencies [[`51a97a1`](https://github.com/TanStack/router/commit/51a97a167fb3ef1b8ca70fbb63db635158f43509)]: + - @tanstack/router-core@1.171.6 + - @tanstack/react-router@1.170.8 + - @tanstack/start-server-core@1.169.3 + - @tanstack/start-client-core@1.170.3 + +## 1.167.7 + +### Patch Changes + +- Updated dependencies [[`5268ba4`](https://github.com/TanStack/router/commit/5268ba4566233ea58880df85f167ad0401a93a46)]: + - @tanstack/router-core@1.171.5 + - @tanstack/react-router@1.170.7 + - @tanstack/start-client-core@1.170.2 + - @tanstack/start-server-core@1.169.2 + +## 1.167.6 + +### Patch Changes + +- Updated dependencies [[`0300f87`](https://github.com/TanStack/router/commit/0300f87ec5a7f878ffbe0b181acf84cba9139960), [`0300f87`](https://github.com/TanStack/router/commit/0300f87ec5a7f878ffbe0b181acf84cba9139960)]: + - @tanstack/router-core@1.171.4 + - @tanstack/react-router@1.170.6 + - @tanstack/start-client-core@1.170.1 + - @tanstack/start-server-core@1.169.1 + +## 1.167.5 + +### Patch Changes + +- Updated dependencies [[`5fa9e55`](https://github.com/TanStack/router/commit/5fa9e555f3a2edb5e45586623e6bcbfa7f7c7a6b)]: + - @tanstack/start-client-core@1.170.0 + - @tanstack/start-server-core@1.169.0 + - @tanstack/router-core@1.171.3 + - @tanstack/react-router@1.170.5 + +## 1.167.4 + +### Patch Changes + +- Updated dependencies [[`b60eb36`](https://github.com/TanStack/router/commit/b60eb36e59e8a468ee0742cbcf7f47aca1ff1c67)]: + - @tanstack/router-core@1.171.2 + - @tanstack/react-router@1.170.4 + - @tanstack/start-client-core@1.169.4 + - @tanstack/start-server-core@1.168.4 + +## 1.167.3 + +### Patch Changes + +- Updated dependencies [[`d9cf933`](https://github.com/TanStack/router/commit/d9cf9331b83fcbd2abfee75d839d862f9bb18e6b)]: + - @tanstack/router-core@1.171.1 + - @tanstack/react-router@1.170.3 + - @tanstack/start-client-core@1.169.3 + - @tanstack/start-server-core@1.168.3 + +## 1.167.2 + +### Patch Changes + +- Updated dependencies [[`d533f87`](https://github.com/TanStack/router/commit/d533f87976704098a40b48f160b37c28c8182806)]: + - @tanstack/router-core@1.171.0 + - @tanstack/react-router@1.170.2 + - @tanstack/start-client-core@1.169.2 + - @tanstack/start-server-core@1.168.2 + +## 1.167.1 + +### Patch Changes + +- Updated dependencies [[`2387a2e`](https://github.com/TanStack/router/commit/2387a2eea0683004cc400b9f71bed5944eb60110)]: + - @tanstack/router-core@1.170.1 + - @tanstack/start-server-core@1.168.1 + - @tanstack/react-router@1.170.1 + - @tanstack/start-client-core@1.169.1 + +## 1.167.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +### Patch Changes + +- Updated dependencies [[`b1c061a`](https://github.com/TanStack/router/commit/b1c061aff9185cdf5fdc08c0136382a9dce0302f), [`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14), [`5ae2ae5`](https://github.com/TanStack/router/commit/5ae2ae5e0f8ce32e02667a482ea9be52a6150240)]: + - @tanstack/router-core@1.170.0 + - @tanstack/history@1.162.0 + - @tanstack/react-router@1.170.0 + - @tanstack/start-client-core@1.169.0 + - @tanstack/start-server-core@1.168.0 + +## 1.166.52 + +### Patch Changes + +- Updated dependencies [[`35e88f0`](https://github.com/TanStack/router/commit/35e88f04996d71019a1868b7b06ecb4ddbc9df9e)]: + - @tanstack/router-core@1.169.2 + - @tanstack/start-client-core@1.168.2 + - @tanstack/start-server-core@1.167.30 + - @tanstack/react-router@1.169.2 + +## 1.166.51 + +### Patch Changes + +- Updated dependencies [[`afa40ef`](https://github.com/TanStack/router/commit/afa40ef46c273c53646ba33f607fc618a07ffede)]: + - @tanstack/start-server-core@1.167.29 + +## 1.166.50 + +### Patch Changes + +- Add opt-in Start response Link headers for collected Early Hints. ([#7327](https://github.com/TanStack/router/pull/7327)) + +- Updated dependencies [[`709627f`](https://github.com/TanStack/router/commit/709627f3dbc6d97daa547a1401ef42a53bc4be32)]: + - @tanstack/start-server-core@1.167.28 + +## 1.166.49 + +### Patch Changes + +- Add experimental HTTP 103 Early Hints support to Start server handlers. ([#7324](https://github.com/TanStack/router/pull/7324)) + +- Updated dependencies [[`238ea4a`](https://github.com/TanStack/router/commit/238ea4a4998ab3a7fd528b317e1935766ac65df8)]: + - @tanstack/start-server-core@1.167.27 + +## 1.166.48 + +### Patch Changes + +- Updated dependencies [[`4a1e63f`](https://github.com/TanStack/router/commit/4a1e63f1d1230b1ed8234609acad4639d8982c13)]: + - @tanstack/router-core@1.169.1 + - @tanstack/react-router@1.169.1 + - @tanstack/start-client-core@1.168.1 + - @tanstack/start-server-core@1.167.26 + +## 1.166.47 + +### Patch Changes + +- Updated dependencies [[`82b0613`](https://github.com/TanStack/router/commit/82b06132af776f74603ab27977cc277d6219a845)]: + - @tanstack/start-client-core@1.168.0 + - @tanstack/start-server-core@1.167.25 + +## 1.166.46 + +### Patch Changes + +- Updated dependencies [[`c992495`](https://github.com/TanStack/router/commit/c992495bf4010ff4c3597bb1f3b1ba02594e857e)]: + - @tanstack/router-core@1.169.0 + - @tanstack/react-router@1.169.0 + - @tanstack/start-client-core@1.167.22 + - @tanstack/start-server-core@1.167.24 + +## 1.166.45 + +### Patch Changes + +- Updated dependencies [[`b5c4183`](https://github.com/TanStack/router/commit/b5c4183ab8b44be8a75647b7f7b588ad7c146ece)]: + - @tanstack/router-core@1.168.18 + - @tanstack/react-router@1.168.26 + - @tanstack/start-client-core@1.167.21 + - @tanstack/start-server-core@1.167.23 + +## 1.166.44 + +### Patch Changes + +- Updated dependencies [[`493148b`](https://github.com/TanStack/router/commit/493148bc5378b7f9de1544d87f6aaa425c12eb34)]: + - @tanstack/router-core@1.168.17 + - @tanstack/react-router@1.168.25 + - @tanstack/start-client-core@1.167.20 + - @tanstack/start-server-core@1.167.22 + +## 1.166.43 + +### Patch Changes + +- Updated dependencies [[`8b97002`](https://github.com/TanStack/router/commit/8b97002af3f6d15204e60c55d3f5735b78bd7efe)]: + - @tanstack/start-client-core@1.167.19 + - @tanstack/start-server-core@1.167.21 + +## 1.166.42 + +### Patch Changes + +- Updated dependencies [[`4d864ee`](https://github.com/TanStack/router/commit/4d864eebbd184265eabb563d326ab409c93feb17)]: + - @tanstack/react-router@1.168.24 + - @tanstack/router-core@1.168.16 + - @tanstack/start-server-core@1.167.20 + - @tanstack/start-client-core@1.167.18 + +## 1.166.41 + +### Patch Changes + +- Updated dependencies [[`cd91cee`](https://github.com/TanStack/router/commit/cd91ceebb84b7b752b5ee09ac14e89ad2beb2259)]: + - @tanstack/react-router@1.168.23 + +## 1.166.40 + +### Patch Changes + +- Updated dependencies [[`e30814d`](https://github.com/TanStack/router/commit/e30814d949110ff25829de44d729ead47555940a)]: + - @tanstack/react-router@1.168.22 + +## 1.166.39 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/react-router@1.168.21 + - @tanstack/start-client-core@1.167.17 + - @tanstack/start-server-core@1.167.19 + +## 1.166.38 + +### Patch Changes + +- Updated dependencies [[`c5ad329`](https://github.com/TanStack/router/commit/c5ad32936f6adcca0c56474677b73b212498443b)]: + - @tanstack/react-router@1.168.20 + +## 1.166.37 + +### Patch Changes + +- Updated dependencies [[`105d056`](https://github.com/TanStack/router/commit/105d05691a247779a63e7b688aa1207cce619339)]: + - @tanstack/react-router@1.168.19 + +## 1.166.36 + +### Patch Changes + +- Updated dependencies [[`0e2c900`](https://github.com/TanStack/router/commit/0e2c9003c18ae07c09969189c028f277ea562a7a)]: + - @tanstack/start-server-core@1.167.18 + - @tanstack/router-core@1.168.14 + - @tanstack/react-router@1.168.18 + - @tanstack/start-client-core@1.167.16 + +## 1.166.35 + +### Patch Changes + +- Updated dependencies [[`812792f`](https://github.com/TanStack/router/commit/812792fbda3caf97b300770855cf5641252f413b)]: + - @tanstack/router-core@1.168.13 + - @tanstack/start-server-core@1.167.17 + - @tanstack/react-router@1.168.17 + - @tanstack/start-client-core@1.167.15 + +## 1.166.34 + +### Patch Changes + +- Updated dependencies [[`8ec9ca9`](https://github.com/TanStack/router/commit/8ec9ca97b472779de878c2a6510f21deb24d386c)]: + - @tanstack/router-core@1.168.12 + - @tanstack/react-router@1.168.16 + - @tanstack/start-client-core@1.167.14 + - @tanstack/start-server-core@1.167.16 + +## 1.166.33 + +### Patch Changes + +- Updated dependencies [[`6355bb7`](https://github.com/TanStack/router/commit/6355bb75f7637ba77f06a923c18fdaf37720bb48)]: + - @tanstack/start-server-core@1.167.15 + - @tanstack/react-router@1.168.15 + - @tanstack/router-core@1.168.11 + - @tanstack/start-client-core@1.167.13 + +## 1.166.32 + +### Patch Changes + +- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: + - @tanstack/start-client-core@1.167.12 + - @tanstack/start-server-core@1.167.14 + - @tanstack/react-router@1.168.14 + - @tanstack/router-core@1.168.10 + +## 1.166.31 + +### Patch Changes + +- fix publishing ([`f8ac427`](https://github.com/TanStack/router/commit/f8ac427000c3fec99225926e72f9f2fc7a37231f)) + +- Updated dependencies [[`f8ac427`](https://github.com/TanStack/router/commit/f8ac427000c3fec99225926e72f9f2fc7a37231f)]: + - @tanstack/start-server-core@1.167.13 + - @tanstack/start-client-core@1.167.11 + +## 1.166.30 + +### Patch Changes + +- fix publishing ([`2d53c05`](https://github.com/TanStack/router/commit/2d53c056ef0b203de8a28bc92c24e8e604205d52)) + +- Updated dependencies [[`2d53c05`](https://github.com/TanStack/router/commit/2d53c056ef0b203de8a28bc92c24e8e604205d52)]: + - @tanstack/start-server-core@1.167.12 + +## 1.166.29 + +### Patch Changes + +- Updated dependencies [[`540d221`](https://github.com/TanStack/router/commit/540d22100d33415a1ddc9eb193f6aeb8184da77f), [`70ec1da`](https://github.com/TanStack/router/commit/70ec1da1ed8aa252fae67716f69fe8520ecf91b0)]: + - @tanstack/react-router@1.168.13 + +## 1.166.28 + +### Patch Changes + +- Updated dependencies [[`b29d64d`](https://github.com/TanStack/router/commit/b29d64de0c400183114c12f82183f80e37d9ea5c)]: + - @tanstack/react-router@1.168.12 + +## 1.166.27 + +### Patch Changes + +- Updated dependencies [[`4b9ed6c`](https://github.com/TanStack/router/commit/4b9ed6c5cb5437df8607c605728c8338dd2eb02c)]: + - @tanstack/react-router@1.168.11 + +## 1.166.26 + +### Patch Changes + +- Updated dependencies [[`f7e9c5e`](https://github.com/TanStack/router/commit/f7e9c5e323793d1b28c96871819c265fd28ae397)]: + - @tanstack/start-client-core@1.167.10 + - @tanstack/start-server-core@1.167.10 + +## 1.166.25 + +### Patch Changes + +- Updated dependencies [[`796406d`](https://github.com/TanStack/router/commit/796406da66cfb12b518bb3ca326c9d541368fb06)]: + - @tanstack/router-core@1.168.9 + - @tanstack/react-router@1.168.10 + - @tanstack/start-client-core@1.167.9 + - @tanstack/start-server-core@1.167.9 + +## 1.166.24 + +### Patch Changes + +- Updated dependencies [[`2d1ec86`](https://github.com/TanStack/router/commit/2d1ec865a446926f7db6e29dbbde82d265de6d36)]: + - @tanstack/router-core@1.168.8 + - @tanstack/react-router@1.168.9 + - @tanstack/start-client-core@1.167.8 + - @tanstack/start-server-core@1.167.8 + +## 1.166.23 + +### Patch Changes + +- Updated dependencies [[`6ee0e79`](https://github.com/TanStack/router/commit/6ee0e795b085651beb2f1ac6503cdbd7eaffedd1)]: + - @tanstack/router-core@1.168.7 + - @tanstack/react-router@1.168.8 + - @tanstack/start-client-core@1.167.7 + - @tanstack/start-server-core@1.167.7 + +## 1.166.22 + +### Patch Changes + +- Updated dependencies [[`42c3f3b`](https://github.com/TanStack/router/commit/42c3f3b3a3a478fd6d6894310ef94b2d23794b8e)]: + - @tanstack/router-core@1.168.6 + - @tanstack/react-router@1.168.7 + - @tanstack/start-client-core@1.167.6 + - @tanstack/start-server-core@1.167.6 + +## 1.166.21 + +### Patch Changes + +- Updated dependencies [[`5ca661c`](https://github.com/TanStack/router/commit/5ca661c2f8a7e50167b4112c64aa06cef4148ea9)]: + - @tanstack/react-router@1.168.6 + +## 1.166.20 + +### Patch Changes + +- Updated dependencies [[`cf5f554`](https://github.com/TanStack/router/commit/cf5f5542476137a81515099ad740747e84512f9a)]: + - @tanstack/router-core@1.168.5 + - @tanstack/react-router@1.168.5 + - @tanstack/start-client-core@1.167.5 + - @tanstack/start-server-core@1.167.5 + +## 1.166.19 + +### Patch Changes + +- Updated dependencies [[`71a8b68`](https://github.com/TanStack/router/commit/71a8b684c87c37fd4a033d99f5ba4a05c7a179f5)]: + - @tanstack/react-router@1.168.4 + - @tanstack/router-core@1.168.4 + - @tanstack/start-client-core@1.167.4 + - @tanstack/start-server-core@1.167.4 + +## 1.166.18 + +### Patch Changes + +- Updated dependencies [[`d81d21a`](https://github.com/TanStack/router/commit/d81d21ad05c9401bf54b24acd29401e1e4fd624c)]: + - @tanstack/react-router@1.168.3 + - @tanstack/router-core@1.168.3 + - @tanstack/start-server-core@1.167.3 + - @tanstack/start-client-core@1.167.3 + +## 1.166.17 + +### Patch Changes + +- Updated dependencies [[`c9e1855`](https://github.com/TanStack/router/commit/c9e18555f3a5531e96de8f574cfca9edcdb18e5c)]: + - @tanstack/start-client-core@1.167.2 + - @tanstack/start-server-core@1.167.2 + - @tanstack/react-router@1.168.2 + - @tanstack/router-core@1.168.2 + +## 1.166.16 + +### Patch Changes + +- Updated dependencies [[`91cc628`](https://github.com/TanStack/router/commit/91cc62899b75ca920fe83c5ee7f3dbb5c71a523f)]: + - @tanstack/react-router@1.168.1 + - @tanstack/router-core@1.168.1 + - @tanstack/start-client-core@1.167.1 + - @tanstack/start-server-core@1.167.1 + +## 1.166.15 + +### Patch Changes + +- Updated dependencies [[`0545239`](https://github.com/TanStack/router/commit/054523900b2ee19308e5a88417dadfc6923afe30)]: + - @tanstack/start-client-core@1.167.0 + - @tanstack/start-server-core@1.167.0 + - @tanstack/react-router@1.168.0 + - @tanstack/router-core@1.168.0 + +## 1.166.14 + +### Patch Changes + +- Updated dependencies [[`5ff4f0b`](https://github.com/TanStack/router/commit/5ff4f0b8dce1fac2bb0b0bfe2684fc677a8ee505)]: + - @tanstack/router-core@1.167.5 + - @tanstack/react-router@1.167.5 + - @tanstack/start-client-core@1.166.13 + - @tanstack/start-server-core@1.166.13 + +## 1.166.13 + +### Patch Changes + +- Updated dependencies [[`940151c`](https://github.com/TanStack/router/commit/940151cbed0c76c92a5cf196c0905b17a956ca7e)]: + - @tanstack/router-core@1.167.4 + - @tanstack/react-router@1.167.4 + - @tanstack/start-client-core@1.166.12 + - @tanstack/start-server-core@1.166.12 + +## 1.166.12 + +### Patch Changes + +- Updated dependencies [[`32fcba7`](https://github.com/TanStack/router/commit/32fcba7b044b03f5901308b870f70b0b4910c220)]: + - @tanstack/router-core@1.167.3 + - @tanstack/react-router@1.167.3 + - @tanstack/start-client-core@1.166.11 + - @tanstack/start-server-core@1.166.11 + +## 1.166.11 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +- Updated dependencies [[`838b0eb`](https://github.com/TanStack/router/commit/838b0eb9a8bbbb987a0a6972c1446e01423bbd7b)]: + - @tanstack/history@1.161.6 + - @tanstack/react-router@1.167.2 + - @tanstack/router-core@1.167.2 + - @tanstack/start-client-core@1.166.10 + - @tanstack/start-server-core@1.166.10 + +## 1.166.10 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) + +- Updated dependencies [[`ef9b241`](https://github.com/TanStack/router/commit/ef9b241f3cfe95cee40daa96da669f0ffd4a971a)]: + - @tanstack/start-client-core@1.166.9 + - @tanstack/start-server-core@1.166.9 + - @tanstack/react-router@1.167.1 + - @tanstack/router-core@1.167.1 + - @tanstack/history@1.161.5 + +## 1.166.9 + +### Patch Changes + +- Updated dependencies [[`6f297a2`](https://github.com/TanStack/router/commit/6f297a249424c0fd1c1a56aa4fc12c8217be7b6a)]: + - @tanstack/router-core@1.167.0 + - @tanstack/react-router@1.167.0 + - @tanstack/start-client-core@1.166.8 + - @tanstack/start-server-core@1.166.8 + +## 1.166.8 + +### Patch Changes + +- Updated dependencies [[`6069eba`](https://github.com/TanStack/router/commit/6069eba64369dbddb0d8dccdb4407f0e1a82259e)]: + - @tanstack/react-router@1.166.8 diff --git a/packages/react-start-server/package.json b/packages/react-start-server/package.json index c7b63e09f7..a725b70d9c 100644 --- a/packages/react-start-server/package.json +++ b/packages/react-start-server/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-start-server", - "version": "1.141.8", + "version": "1.167.52", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -29,12 +29,12 @@ "test:unit": "exit 0; vitest", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -58,17 +58,27 @@ "node": ">=22.12.0" }, "dependencies": { - "@tanstack/history": "workspace:*", "@tanstack/react-router": "workspace:*", "@tanstack/router-core": "workspace:*", - "@tanstack/start-client-core": "workspace:*", "@tanstack/start-server-core": "workspace:*" }, "devDependencies": { - "@vitejs/plugin-react": "^4.3.4", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "typescript": "^5.7.2" + "@vitejs/plugin-react": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@eslint-react/eslint-plugin": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", diff --git a/packages/react-start-server/tsconfig.build.json b/packages/react-start-server/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/react-start-server/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/react-start-server/vite.config.ts b/packages/react-start-server/vite.config.ts index 9a1d38f579..214b8cbc42 100644 --- a/packages/react-start-server/vite.config.ts +++ b/packages/react-start-server/vite.config.ts @@ -1,5 +1,5 @@ import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' import react from '@vitejs/plugin-react' import packageJson from './package.json' @@ -15,6 +15,7 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ + tsconfigPath: './tsconfig.build.json', srcDir: './src', entry: './src/index.tsx', cjs: false, diff --git a/packages/react-start/CHANGELOG.md b/packages/react-start/CHANGELOG.md new file mode 100644 index 0000000000..9d6432f985 --- /dev/null +++ b/packages/react-start/CHANGELOG.md @@ -0,0 +1,1644 @@ +# @tanstack/react-start + +## 1.169.6 + +### Patch Changes + +- Updated dependencies [[`3f22686`](https://github.com/TanStack/router/commit/3f226869e0af211ff7f1de5d7343e43462dbb101), [`559c7de`](https://github.com/TanStack/router/commit/559c7ded6e2a6eeda3f91c80d8c03f4cfeb9a206)]: + - @tanstack/start-plugin-core@1.171.57 + - @tanstack/react-start-rsc@0.1.67 + +## 1.169.5 + +### Patch Changes + +- [#8863](https://github.com/TanStack/router/pull/8863) [`01fab5a`](https://github.com/TanStack/router/commit/01fab5a6c8aed70d61d82c64bc344cbac66c240c) - The Rsbuild plugin keeps the app's `server.compress` setting instead of always setting it to `false`. Compression stays off by default: a compressed streamed page reaches the browser only once the stream ends. The optional `@rsbuild/core` peer is now `^2.0.5`, the first version whose compression keeps SSR response headers intact. + +- Updated dependencies [[`446ce1b`](https://github.com/TanStack/router/commit/446ce1b30650d85f1fc78f2d1ee42712e40b75c6), [`ff157f0`](https://github.com/TanStack/router/commit/ff157f0079982e90d62be7fdeecfb77e4fdcec69), [`01fab5a`](https://github.com/TanStack/router/commit/01fab5a6c8aed70d61d82c64bc344cbac66c240c), [`c5320d7`](https://github.com/TanStack/router/commit/c5320d7ca23eca82d720ac5629d2bad5cf7d9b02), [`545a8d3`](https://github.com/TanStack/router/commit/545a8d3790989ca502153c3292c6b1e8063257f4), [`da8c28c`](https://github.com/TanStack/router/commit/da8c28c498230a5730ce75b2693baeeb3ef68ac1), [`d66a84b`](https://github.com/TanStack/router/commit/d66a84ba0a74ffd03e22b57ccd90796274c96244)]: + - @tanstack/router-utils@1.163.0 + - @tanstack/start-plugin-core@1.171.56 + - @tanstack/react-start-client@1.168.45 + - @tanstack/react-start-rsc@0.1.66 + +## 1.169.4 + +### Patch Changes + +- [#8670](https://github.com/TanStack/router/pull/8670) [`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c) - Reference agent skills in other packages by their `intent load` identifier (`@tanstack/#`) instead of relative file links that break once packages are installed. + +- Updated dependencies [[`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c), [`689a7c5`](https://github.com/TanStack/router/commit/689a7c5419de68bce0aaaef72b9a36f115ea1398), [`ed55775`](https://github.com/TanStack/router/commit/ed5577593a749b8c7193cc7b5d945fd084bfac2f), [`63a886d`](https://github.com/TanStack/router/commit/63a886da9040c4b039ea3bf5b3a841771375cddb), [`d9b07e8`](https://github.com/TanStack/router/commit/d9b07e8d3b724cdbfac0aa2fba4c1f7a3a241100)]: + - @tanstack/react-router@1.170.46 + - @tanstack/start-client-core@1.170.39 + - @tanstack/start-server-core@1.169.45 + - @tanstack/start-plugin-core@1.171.55 + - @tanstack/react-start-client@1.168.44 + - @tanstack/react-start-rsc@0.1.65 + - @tanstack/react-start-server@1.167.52 + +## 1.169.3 + +### Patch Changes + +- Updated dependencies [[`18154b1`](https://github.com/TanStack/router/commit/18154b1c45454a70aa77e9d6d27c8a6e0733d031)]: + - @tanstack/start-server-core@1.169.44 + - @tanstack/react-router@1.170.45 + - @tanstack/react-start-client@1.168.43 + - @tanstack/react-start-rsc@0.1.64 + - @tanstack/react-start-server@1.167.51 + - @tanstack/start-client-core@1.170.38 + - @tanstack/start-plugin-core@1.171.54 + +## 1.169.2 + +### Patch Changes + +- Updated dependencies [[`71d9694`](https://github.com/TanStack/router/commit/71d9694da6346fbece2cda4ecde92b0b12a7ee08), [`fdc10fa`](https://github.com/TanStack/router/commit/fdc10fa13fbac758615f9a3d37075088d1cc1e1f), [`923d98b`](https://github.com/TanStack/router/commit/923d98b18b6cd90b6219591e20e86115dc61048e)]: + - @tanstack/start-server-core@1.169.43 + - @tanstack/start-plugin-core@1.171.53 + - @tanstack/router-utils@1.162.4 + - @tanstack/react-start-server@1.167.50 + - @tanstack/react-start-rsc@0.1.63 + +## 1.169.1 + +### Patch Changes + +- Updated dependencies [[`740b0ce`](https://github.com/TanStack/router/commit/740b0ce17737d1f7398740136acdbeabe80df7d8), [`d6ba115`](https://github.com/TanStack/router/commit/d6ba115d5751c75e20943f0062577cf17b446d82)]: + - @tanstack/start-server-core@1.169.42 + - @tanstack/react-start-server@1.167.49 + - @tanstack/start-plugin-core@1.171.52 + - @tanstack/react-start-rsc@0.1.62 + - @tanstack/start-client-core@1.170.37 + - @tanstack/react-router@1.170.44 + - @tanstack/react-start-client@1.168.42 + +## 1.169.0 + +### Minor Changes + +- [#8696](https://github.com/TanStack/router/pull/8696) [`f243c61`](https://github.com/TanStack/router/commit/f243c61e95dae64fe04da4499c0c4ec44f26abae) - TanStack Start is stable. To upgrade from a release candidate, follow [Migrate from the Release Candidate](https://tanstack.com/start/latest/docs/framework/react/migrate-from-release-candidate). + +### Patch Changes + +- [#8694](https://github.com/TanStack/router/pull/8694) [`550f478`](https://github.com/TanStack/router/commit/550f47881070c0558a87e1acce7f38fbc85b9549) - Remove the deprecated `.inputValidator()` from `createServerFn` and `createMiddleware`. Use `.validator()`, which takes the same validator. + +- [#7588](https://github.com/TanStack/router/pull/7588) [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5) - Keep streaming a page when request middleware returns a response that reads the page body, such as a copy made through a wrapped global `Response`, a copy in Bun, or a body piped through a transform. Start now disposes a replaced page stream only when nothing reads it. `transferResponseBodyOwnership` is removed: return the derived response directly. + +- [#7588](https://github.com/TanStack/router/pull/7588) [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5) - Remove the built-in `useSession` API. Applications choose a session library, such as iron-session, and save or destroy sessions explicitly before returning or redirecting. Connect a cookie adapter through `getCookie` and `setCookie`, or append serialized cookies with `appendResponseHeader('set-cookie', cookie)`. Existing session cookies require a deliberate migration or signing in again with a new cookie name. + + `createServerEntry` keeps the complete callback, including custom error handling, inside the request context and converts errors that escape it. The built-in entry still converts errors automatically. Raw `createStartHandler` handlers now rethrow the original error. For custom reporting, catch inside `createServerEntry`, then rethrow for default conversion or return `handleStartError(error)` to preserve response-helper status, headers, and cookies. Return an explicit `Response` when choosing a custom error payload. + + Response helpers now apply consistently across server routes, SSR, server functions, redirects, errors, and middleware response replacements. Helper setters override returned values; cookie helpers preserve independent cookies and replace matching cookie identities. Use `appendResponseHeader('set-cookie', cookie)` when adding a serialized cookie without replacing other cookies. Changed responses receive copied headers and reuse the body stream, so applications should inspect the response returned by Start rather than relying on mutation of the original response. + +- [#8696](https://github.com/TanStack/router/pull/8696) [`f243c61`](https://github.com/TanStack/router/commit/f243c61e95dae64fe04da4499c0c4ec44f26abae) - Require Vite 8 for Vite builds. Vite 7 is no longer supported. + +- Updated dependencies [[`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`550f478`](https://github.com/TanStack/router/commit/550f47881070c0558a87e1acce7f38fbc85b9549), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`f3d7ee3`](https://github.com/TanStack/router/commit/f3d7ee3374c660e0fe82a03ac580a90ed2e2fa98), [`4104b8e`](https://github.com/TanStack/router/commit/4104b8ef11498706b5059c5a915f2ae47ffbc5ba), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`f243c61`](https://github.com/TanStack/router/commit/f243c61e95dae64fe04da4499c0c4ec44f26abae), [`19524cc`](https://github.com/TanStack/router/commit/19524ccdd75870ce1db2f324518eeb3f23cc0f97)]: + - @tanstack/start-server-core@1.169.41 + - @tanstack/start-client-core@1.170.36 + - @tanstack/start-plugin-core@1.171.51 + - @tanstack/react-start-server@1.167.48 + - @tanstack/react-start-rsc@0.1.61 + - @tanstack/react-router@1.170.43 + - @tanstack/react-start-client@1.168.41 + +## 1.168.61 + +### Patch Changes + +- Updated dependencies [[`2413cc0`](https://github.com/TanStack/router/commit/2413cc009826fba4f97b166a35a8a50a4a8fe4bb), [`4191640`](https://github.com/TanStack/router/commit/41916400b93fdb62189722266ed1d77ba9c26be9), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`d35aab4`](https://github.com/TanStack/router/commit/d35aab425b07b46e222a507c0f0239644669757b)]: + - @tanstack/react-router@1.170.42 + - @tanstack/start-plugin-core@1.171.50 + - @tanstack/start-server-core@1.169.40 + - @tanstack/react-start-client@1.168.40 + - @tanstack/react-start-rsc@0.1.60 + - @tanstack/react-start-server@1.167.47 + - @tanstack/start-client-core@1.170.35 + +## 1.168.60 + +### Patch Changes + +- Updated dependencies [[`60b8ad1`](https://github.com/TanStack/router/commit/60b8ad1ad00812bf966a8eeee6be238c37ddad74), [`41ebd28`](https://github.com/TanStack/router/commit/41ebd288677beacb8eb56953f5f8c26e9d33313e), [`614bc27`](https://github.com/TanStack/router/commit/614bc27034c8ec98747bf305ed41d4a619640949), [`05223c2`](https://github.com/TanStack/router/commit/05223c2ada4d48af4b3881f10e3b6261898b2d40), [`d521abd`](https://github.com/TanStack/router/commit/d521abd71c69f1ff010bb3def4d417cb5fa058cb), [`ff66a03`](https://github.com/TanStack/router/commit/ff66a03df4816f44a48a4a37189fc4021b1c8480), [`863c8a7`](https://github.com/TanStack/router/commit/863c8a736b96746c56278a16c50554356f5523d1)]: + - @tanstack/react-router@1.170.41 + - @tanstack/start-plugin-core@1.171.49 + - @tanstack/start-server-core@1.169.39 + - @tanstack/react-start-client@1.168.39 + - @tanstack/react-start-rsc@0.1.59 + - @tanstack/react-start-server@1.167.46 + - @tanstack/start-client-core@1.170.34 + +## 1.168.59 + +### Patch Changes + +- Updated dependencies [[`f5ffd38`](https://github.com/TanStack/router/commit/f5ffd3884ba26778a2a8ce53b379a5bded231676), [`488d046`](https://github.com/TanStack/router/commit/488d046a907d330429e2c807ef95326dad87480f), [`e81845f`](https://github.com/TanStack/router/commit/e81845ff1e4fc66d4e4a87f086be65906f7adb94), [`76a7c0b`](https://github.com/TanStack/router/commit/76a7c0bfadb42d5f7fe7b9e1748acc7333178c91)]: + - @tanstack/react-router@1.170.40 + - @tanstack/start-client-core@1.170.33 + - @tanstack/start-server-core@1.169.38 + - @tanstack/start-plugin-core@1.171.48 + - @tanstack/react-start-client@1.168.38 + - @tanstack/react-start-rsc@0.1.58 + - @tanstack/react-start-server@1.167.45 + +## 1.168.58 + +### Patch Changes + +- Updated dependencies [[`73bfc15`](https://github.com/TanStack/router/commit/73bfc153eef460e9b670556215a5adb2b5cbf542)]: + - @tanstack/react-router@1.170.39 + - @tanstack/react-start-client@1.168.37 + - @tanstack/react-start-rsc@0.1.57 + - @tanstack/react-start-server@1.167.44 + +## 1.168.57 + +### Patch Changes + +- Updated dependencies [[`222300b`](https://github.com/TanStack/router/commit/222300b82fe6f2a5e7e7f460ae21a2e35c6230d7)]: + - @tanstack/start-plugin-core@1.171.47 + - @tanstack/react-start-rsc@0.1.56 + +## 1.168.56 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.170.38 + - @tanstack/react-start-client@1.168.36 + - @tanstack/react-start-rsc@0.1.55 + - @tanstack/react-start-server@1.167.43 + - @tanstack/start-client-core@1.170.32 + - @tanstack/start-plugin-core@1.171.46 + - @tanstack/start-server-core@1.169.37 + +## 1.168.55 + +### Patch Changes + +- Updated dependencies [[`e561fa1`](https://github.com/TanStack/router/commit/e561fa1d7118e3d29267cc3b6ce1130d6581f387), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a1c8d1a`](https://github.com/TanStack/router/commit/a1c8d1aa759c227eae9601a030321ac4c53c24bd), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`8e164d2`](https://github.com/TanStack/router/commit/8e164d28f9e9eb1a7301109230d7ece9817492a8)]: + - @tanstack/react-router@1.170.37 + - @tanstack/start-plugin-core@1.171.45 + - @tanstack/start-client-core@1.170.31 + - @tanstack/start-server-core@1.169.36 + - @tanstack/react-start-client@1.168.35 + - @tanstack/react-start-rsc@0.1.54 + - @tanstack/react-start-server@1.167.42 + +## 1.168.54 + +### Patch Changes + +- Updated dependencies [[`ab99818`](https://github.com/TanStack/router/commit/ab99818225835a1553a9f3513cd2093ff1b257be)]: + - @tanstack/start-plugin-core@1.171.44 + - @tanstack/react-start-rsc@0.1.53 + +## 1.168.53 + +### Patch Changes + +- Updated dependencies [[`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5)]: + - @tanstack/react-router@1.170.36 + - @tanstack/start-server-core@1.169.35 + - @tanstack/react-start-client@1.168.34 + - @tanstack/react-start-rsc@0.1.52 + - @tanstack/react-start-server@1.167.41 + - @tanstack/start-client-core@1.170.30 + - @tanstack/start-plugin-core@1.171.43 + +## 1.168.52 + +### Patch Changes + +- Updated dependencies [[`8c43c71`](https://github.com/TanStack/router/commit/8c43c712523fc63dc3a814f3a19617e270ce8ed1), [`d914b08`](https://github.com/TanStack/router/commit/d914b085bb4bf29ec18a531201e377c10681b661)]: + - @tanstack/react-router@1.170.35 + - @tanstack/start-server-core@1.169.34 + - @tanstack/react-start-client@1.168.33 + - @tanstack/react-start-rsc@0.1.51 + - @tanstack/react-start-server@1.167.40 + - @tanstack/start-plugin-core@1.171.42 + +## 1.168.51 + +### Patch Changes + +- Updated dependencies [[`aee42c6`](https://github.com/TanStack/router/commit/aee42c6b641d8e919bfed9e0f04bb1b72092f3a6), [`49bcd4d`](https://github.com/TanStack/router/commit/49bcd4db743dba4a783d5533a42a0f97a5721292), [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8), [`9aec5a7`](https://github.com/TanStack/router/commit/9aec5a7012c47e83ec23bb4763494b72a5e68bfc), [`919c397`](https://github.com/TanStack/router/commit/919c3971493374cccc963e75b9b2a4e98ebf878a)]: + - @tanstack/react-router@1.170.34 + - @tanstack/router-utils@1.162.3 + - @tanstack/start-plugin-core@1.171.41 + - @tanstack/start-server-core@1.169.33 + - @tanstack/react-start-client@1.168.32 + - @tanstack/react-start-rsc@0.1.50 + - @tanstack/react-start-server@1.167.39 + - @tanstack/start-client-core@1.170.29 + +## 1.168.50 + +### Patch Changes + +- Updated dependencies [[`2f20c00`](https://github.com/TanStack/router/commit/2f20c00224c5ba63467551914e0c37012588c4c2), [`28a5e45`](https://github.com/TanStack/router/commit/28a5e4504e4ea5cb1480667a4bea2588a53e110f), [`f0b5eda`](https://github.com/TanStack/router/commit/f0b5eda544606686a8a8d675a686ca1366428b96), [`37877da`](https://github.com/TanStack/router/commit/37877da166fe4ce055c7b85e138b6681ebd7e8b4), [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b), [`0caf6b9`](https://github.com/TanStack/router/commit/0caf6b9a2b7e14b0b146c74cc27cb05c19d700a5), [`cf166d1`](https://github.com/TanStack/router/commit/cf166d160e6397007a979bfc7065b45ff69ea543)]: + - @tanstack/react-router@1.170.33 + - @tanstack/start-plugin-core@1.171.40 + - @tanstack/react-start-client@1.168.31 + - @tanstack/react-start-rsc@0.1.49 + - @tanstack/react-start-server@1.167.38 + - @tanstack/start-client-core@1.170.28 + - @tanstack/start-server-core@1.169.32 + +## 1.168.49 + +### Patch Changes + +- Updated dependencies [[`cb281d7`](https://github.com/TanStack/router/commit/cb281d70c1f5fe780f9d07bc500ea3a284a4e04b), [`a0041bb`](https://github.com/TanStack/router/commit/a0041bb36e700b3263b894e4d1573d924383b56b)]: + - @tanstack/react-router@1.170.32 + - @tanstack/start-plugin-core@1.171.39 + - @tanstack/react-start-client@1.168.30 + - @tanstack/react-start-rsc@0.1.48 + - @tanstack/react-start-server@1.167.37 + - @tanstack/start-client-core@1.170.27 + - @tanstack/start-server-core@1.169.31 + +## 1.168.48 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.170.31 + - @tanstack/react-start-client@1.168.29 + - @tanstack/react-start-rsc@0.1.47 + - @tanstack/react-start-server@1.167.36 + - @tanstack/start-client-core@1.170.26 + - @tanstack/start-plugin-core@1.171.38 + - @tanstack/start-server-core@1.169.30 + +## 1.168.47 + +### Patch Changes + +- Updated dependencies [[`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175), [`f75cada`](https://github.com/TanStack/router/commit/f75cada01707e51fb9650dd301bc04f8b2265a2a)]: + - @tanstack/react-router@1.170.30 + - @tanstack/react-start-client@1.168.28 + - @tanstack/react-start-rsc@0.1.46 + - @tanstack/react-start-server@1.167.35 + - @tanstack/start-client-core@1.170.25 + - @tanstack/start-plugin-core@1.171.37 + - @tanstack/start-server-core@1.169.29 + +## 1.168.46 + +### Patch Changes + +- Updated dependencies [[`0fdf9ff`](https://github.com/TanStack/router/commit/0fdf9ff16fc532de9fc131d18df167ebd8038720)]: + - @tanstack/react-router@1.170.29 + - @tanstack/react-start-client@1.168.27 + - @tanstack/react-start-rsc@0.1.45 + - @tanstack/react-start-server@1.167.34 + - @tanstack/start-client-core@1.170.24 + - @tanstack/start-plugin-core@1.171.36 + - @tanstack/start-server-core@1.169.28 + +## 1.168.45 + +### Patch Changes + +- Updated dependencies [[`0c25a7b`](https://github.com/TanStack/router/commit/0c25a7b43b5331ee6ebf94d50e9793002783adab), [`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90)]: + - @tanstack/react-router@1.170.28 + - @tanstack/react-start-client@1.168.26 + - @tanstack/react-start-rsc@0.1.44 + - @tanstack/react-start-server@1.167.33 + - @tanstack/start-client-core@1.170.23 + - @tanstack/start-plugin-core@1.171.35 + - @tanstack/start-server-core@1.169.27 + +## 1.168.44 + +### Patch Changes + +- Updated dependencies [[`b0817f5`](https://github.com/TanStack/router/commit/b0817f50cc639ae50b6c30cd11c5adbf7eed028c)]: + - @tanstack/react-router@1.170.27 + - @tanstack/react-start-client@1.168.25 + - @tanstack/react-start-rsc@0.1.43 + - @tanstack/react-start-server@1.167.32 + +## 1.168.43 + +### Patch Changes + +- Updated dependencies [[`f500760`](https://github.com/TanStack/router/commit/f5007607d62e932b8df19de866cdc6bddcff8db3), [`1aafca9`](https://github.com/TanStack/router/commit/1aafca9b45d24f8f0dba78e716fc9582346c6ca1), [`aa10b65`](https://github.com/TanStack/router/commit/aa10b6589eeda215f5a60ea0af95a3101d8c414e)]: + - @tanstack/react-router@1.170.26 + - @tanstack/react-start-client@1.168.24 + - @tanstack/react-start-rsc@0.1.42 + - @tanstack/react-start-server@1.167.31 + - @tanstack/start-client-core@1.170.22 + - @tanstack/start-plugin-core@1.171.34 + - @tanstack/start-server-core@1.169.26 + +## 1.168.42 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.170.25 + - @tanstack/react-start-client@1.168.23 + - @tanstack/react-start-rsc@0.1.41 + - @tanstack/react-start-server@1.167.30 + - @tanstack/start-client-core@1.170.21 + - @tanstack/start-plugin-core@1.171.33 + - @tanstack/start-server-core@1.169.25 + +## 1.168.41 + +### Patch Changes + +- Updated dependencies [[`c59788c`](https://github.com/TanStack/router/commit/c59788ca20f2d2e7f264a859ebe01b7646ba3154)]: + - @tanstack/start-client-core@1.170.20 + - @tanstack/react-router@1.170.24 + - @tanstack/react-start-client@1.168.22 + - @tanstack/react-start-rsc@0.1.40 + - @tanstack/react-start-server@1.167.29 + - @tanstack/start-plugin-core@1.171.32 + - @tanstack/start-server-core@1.169.24 + +## 1.168.40 + +### Patch Changes + +- Updated dependencies [[`2fbc99f`](https://github.com/TanStack/router/commit/2fbc99f2c262b057cb957e6ebba1ee073c655186), [`95dec51`](https://github.com/TanStack/router/commit/95dec51018d01483949c6f1fe3094b019ccf3b4f), [`6bede65`](https://github.com/TanStack/router/commit/6bede65d7074dcd83455151b66b4574268bc782c)]: + - @tanstack/start-client-core@1.170.19 + - @tanstack/react-router@1.170.23 + - @tanstack/react-start-client@1.168.21 + - @tanstack/react-start-rsc@0.1.39 + - @tanstack/start-server-core@1.169.23 + - @tanstack/react-start-server@1.167.28 + - @tanstack/start-plugin-core@1.171.31 + +## 1.168.39 + +### Patch Changes + +- Updated dependencies [[`ea3a665`](https://github.com/TanStack/router/commit/ea3a665d81cbb5074c2d77ec953255ab534e7db9)]: + - @tanstack/react-router@1.170.22 + - @tanstack/react-start-client@1.168.20 + - @tanstack/react-start-rsc@0.1.38 + - @tanstack/react-start-server@1.167.27 + - @tanstack/start-client-core@1.170.18 + - @tanstack/start-plugin-core@1.171.30 + - @tanstack/start-server-core@1.169.22 + +## 1.168.38 + +### Patch Changes + +- Updated dependencies [[`697ebb6`](https://github.com/TanStack/router/commit/697ebb6ddbd433d052b6b4707938a5c595865d58), [`2435885`](https://github.com/TanStack/router/commit/2435885fa8b5e31c8c4b74d93920919f27316ebf), [`9cac62a`](https://github.com/TanStack/router/commit/9cac62a5c7f99ef070991ea6f1fa7e42c746d46b), [`86bf510`](https://github.com/TanStack/router/commit/86bf510c2923afb76804223bd04afc2a809b33e7), [`6aefb33`](https://github.com/TanStack/router/commit/6aefb3392595a07a93f89301d7b5e3558ff9190c)]: + - @tanstack/react-router@1.170.21 + - @tanstack/start-client-core@1.170.17 + - @tanstack/start-server-core@1.169.21 + - @tanstack/react-start-client@1.168.19 + - @tanstack/react-start-rsc@0.1.37 + - @tanstack/react-start-server@1.167.26 + - @tanstack/start-plugin-core@1.171.29 + +## 1.168.37 + +### Patch Changes + +- Updated dependencies [[`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5)]: + - @tanstack/start-client-core@1.170.16 + - @tanstack/start-plugin-core@1.171.28 + - @tanstack/start-server-core@1.169.20 + - @tanstack/react-router@1.170.20 + - @tanstack/react-start-client@1.168.18 + - @tanstack/react-start-rsc@0.1.36 + - @tanstack/react-start-server@1.167.25 + +## 1.168.36 + +### Patch Changes + +- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: + - @tanstack/react-router@1.170.19 + - @tanstack/react-start-client@1.168.17 + - @tanstack/react-start-rsc@0.1.35 + - @tanstack/react-start-server@1.167.24 + - @tanstack/start-client-core@1.170.15 + - @tanstack/start-plugin-core@1.171.27 + - @tanstack/start-server-core@1.169.19 + +## 1.168.35 + +### Patch Changes + +- Updated dependencies [[`65f7b7f`](https://github.com/TanStack/router/commit/65f7b7f791272f2ea581a1fe0fcd43183bc01162), [`65f7b7f`](https://github.com/TanStack/router/commit/65f7b7f791272f2ea581a1fe0fcd43183bc01162)]: + - @tanstack/start-server-core@1.169.18 + - @tanstack/start-plugin-core@1.171.26 + - @tanstack/react-start-rsc@0.1.34 + - @tanstack/react-start-server@1.167.23 + +## 1.168.34 + +### Patch Changes + +- Updated dependencies [[`7592555`](https://github.com/TanStack/router/commit/7592555b86c968efbc8c817ac0cf6fdae60aabe0)]: + - @tanstack/start-plugin-core@1.171.25 + - @tanstack/react-start-rsc@0.1.33 + +## 1.168.33 + +### Patch Changes + +- Updated dependencies [[`fc83c03`](https://github.com/TanStack/router/commit/fc83c0383f956c3ca02e5e027666c917d7e8b07a)]: + - @tanstack/react-start-rsc@0.1.32 + +## 1.168.32 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.171.24 + - @tanstack/react-start-rsc@0.1.31 + +## 1.168.31 + +### Patch Changes + +- Updated dependencies [[`ffdd64e`](https://github.com/TanStack/router/commit/ffdd64e842acacbc9d368a4803a9e474e9f0c0ff)]: + - @tanstack/start-plugin-core@1.171.23 + - @tanstack/react-start-rsc@0.1.30 + +## 1.168.30 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.171.22 + - @tanstack/react-start-rsc@0.1.29 + +## 1.168.29 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.171.21 + - @tanstack/react-start-rsc@0.1.28 + +## 1.168.28 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.170.18 + - @tanstack/react-start-client@1.168.16 + - @tanstack/react-start-rsc@0.1.27 + - @tanstack/react-start-server@1.167.22 + - @tanstack/start-client-core@1.170.14 + - @tanstack/start-plugin-core@1.171.20 + - @tanstack/start-server-core@1.169.17 + +## 1.168.27 + +### Patch Changes + +- Updated dependencies [[`ba52d2b`](https://github.com/TanStack/router/commit/ba52d2b8f9e95d6becd1be14c020b35f3231e02c)]: + - @tanstack/start-client-core@1.170.13 + - @tanstack/react-router@1.170.17 + - @tanstack/react-start-client@1.168.15 + - @tanstack/react-start-rsc@0.1.26 + - @tanstack/react-start-server@1.167.21 + - @tanstack/start-plugin-core@1.171.19 + - @tanstack/start-server-core@1.169.16 + +## 1.168.26 + +### Patch Changes + +- Updated dependencies [[`52db703`](https://github.com/TanStack/router/commit/52db7034fd83b17cc45da9ba775ec253f2a9a149), [`4a93cff`](https://github.com/TanStack/router/commit/4a93cffffca34702e419bc47db827f964fd0cb65), [`96eca43`](https://github.com/TanStack/router/commit/96eca43ab8ee21917a8075521bef6dcf15fc7a43), [`f046b06`](https://github.com/TanStack/router/commit/f046b064d32222cad0b7ea061311ca9a474f5990), [`e499164`](https://github.com/TanStack/router/commit/e499164c722841271af4aa2215483476bdb94c94), [`689d88e`](https://github.com/TanStack/router/commit/689d88e04c48ec76a18453ab8b82d8d58f2668b6), [`689c5ab`](https://github.com/TanStack/router/commit/689c5ab32e9bb18d90a5a94c33237b0e418df3e3)]: + - @tanstack/react-router@1.170.16 + - @tanstack/start-server-core@1.169.15 + - @tanstack/start-plugin-core@1.171.18 + - @tanstack/react-start-client@1.168.14 + - @tanstack/react-start-rsc@0.1.25 + - @tanstack/react-start-server@1.167.20 + +## 1.168.25 + +### Patch Changes + +- [#7566](https://github.com/TanStack/router/pull/7566) [`9bebf8d`](https://github.com/TanStack/router/commit/9bebf8dc9f2bf74b680c065a5aa63d03b9622825) - Add `validator()` as the canonical server function and middleware validator method. Deprecate `inputValidator()` and emit compiler warnings for remaining uses. + +- Updated dependencies [[`9bebf8d`](https://github.com/TanStack/router/commit/9bebf8dc9f2bf74b680c065a5aa63d03b9622825)]: + - @tanstack/start-client-core@1.170.12 + - @tanstack/start-plugin-core@1.171.17 + - @tanstack/react-start-client@1.168.13 + - @tanstack/react-start-rsc@0.1.24 + - @tanstack/start-server-core@1.169.14 + - @tanstack/react-start-server@1.167.19 + +## 1.168.24 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.170.15 + - @tanstack/react-start-client@1.168.12 + - @tanstack/react-start-rsc@0.1.23 + - @tanstack/react-start-server@1.167.18 + - @tanstack/start-client-core@1.170.11 + - @tanstack/start-plugin-core@1.171.16 + - @tanstack/start-server-core@1.169.13 + +## 1.168.23 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.170.14 + - @tanstack/react-start-client@1.168.11 + - @tanstack/react-start-rsc@0.1.22 + - @tanstack/react-start-server@1.167.17 + - @tanstack/start-client-core@1.170.10 + - @tanstack/start-plugin-core@1.171.15 + - @tanstack/start-server-core@1.169.12 + +## 1.168.22 + +### Patch Changes + +- Updated dependencies [[`ac10815`](https://github.com/TanStack/router/commit/ac10815f387d25b15163ff711b4049e8f8482d01)]: + - @tanstack/react-router@1.170.13 + - @tanstack/react-start-client@1.168.10 + - @tanstack/react-start-rsc@0.1.21 + - @tanstack/react-start-server@1.167.16 + - @tanstack/start-client-core@1.170.9 + - @tanstack/start-plugin-core@1.171.14 + - @tanstack/start-server-core@1.169.11 + +## 1.168.21 + +### Patch Changes + +- Updated dependencies [[`301f6ba`](https://github.com/TanStack/router/commit/301f6ba4599386edd6fb3b8423938c48eedb501f)]: + - @tanstack/start-plugin-core@1.171.13 + - @tanstack/router-utils@1.162.2 + - @tanstack/react-start-rsc@0.1.20 + - @tanstack/react-router@1.170.12 + - @tanstack/react-start-client@1.168.9 + - @tanstack/react-start-server@1.167.15 + - @tanstack/start-client-core@1.170.8 + - @tanstack/start-server-core@1.169.10 + +## 1.168.20 + +### Patch Changes + +- Updated dependencies [[`8091918`](https://github.com/TanStack/router/commit/80919186cbdd0deb948b46fe328881a14a08f414)]: + - @tanstack/start-plugin-core@1.171.12 + - @tanstack/react-start-rsc@0.1.19 + +## 1.168.19 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.170.11 + - @tanstack/react-start-client@1.168.8 + - @tanstack/react-start-rsc@0.1.18 + - @tanstack/react-start-server@1.167.14 + - @tanstack/start-client-core@1.170.7 + - @tanstack/start-plugin-core@1.171.11 + - @tanstack/start-server-core@1.169.9 + +## 1.168.18 + +### Patch Changes + +- [#7509](https://github.com/TanStack/router/pull/7509) [`9cb7a00`](https://github.com/TanStack/router/commit/9cb7a003e6e5fa3706711870c7b10a5266356e3b) - feat(rsbuild): add RSC support + +- Updated dependencies [[`9cb7a00`](https://github.com/TanStack/router/commit/9cb7a003e6e5fa3706711870c7b10a5266356e3b)]: + - @tanstack/start-plugin-core@1.171.10 + - @tanstack/start-server-core@1.169.8 + - @tanstack/react-start-rsc@0.1.17 + - @tanstack/react-start-server@1.167.13 + +## 1.168.17 + +### Patch Changes + +- [#7505](https://github.com/TanStack/router/pull/7505) [`2f53749`](https://github.com/TanStack/router/commit/2f5374945e2138559a51464f45a5152eae67e1dd) - Preserve primitive values thrown from beforeLoad error handling. + +- Updated dependencies [[`2f53749`](https://github.com/TanStack/router/commit/2f5374945e2138559a51464f45a5152eae67e1dd)]: + - @tanstack/react-router@1.170.10 + - @tanstack/react-start-client@1.168.7 + - @tanstack/react-start-rsc@0.1.16 + - @tanstack/react-start-server@1.167.12 + - @tanstack/start-client-core@1.170.6 + - @tanstack/start-plugin-core@1.171.9 + - @tanstack/start-server-core@1.169.7 + +## 1.168.16 + +### Patch Changes + +- Updated dependencies [[`d1997b6`](https://github.com/TanStack/router/commit/d1997b66d7c24c1d64772bb8bab5caf9c6d9cc48)]: + - @tanstack/start-server-core@1.169.6 + - @tanstack/react-router@1.170.9 + - @tanstack/react-start-rsc@0.1.15 + - @tanstack/react-start-server@1.167.11 + - @tanstack/start-plugin-core@1.171.8 + - @tanstack/react-start-client@1.168.6 + - @tanstack/start-client-core@1.170.5 + +## 1.168.15 + +### Patch Changes + +- Updated dependencies [[`9c09bca`](https://github.com/TanStack/router/commit/9c09bca59e9613e9a6fd9b7149b0737898e705d6)]: + - @tanstack/start-plugin-core@1.171.7 + - @tanstack/start-server-core@1.169.5 + - @tanstack/react-start-rsc@0.1.14 + - @tanstack/react-start-server@1.167.10 + +## 1.168.14 + +### Patch Changes + +- [#7492](https://github.com/TanStack/router/pull/7492) [`71fb329`](https://github.com/TanStack/router/commit/71fb3297e93a126e1bcfd9eeb0626cc4b8df8dd8) - Avoid pulling the client hydration entry into root `@tanstack/react-start` and `@tanstack/solid-start` imports by re-exporting `Hydrate` from framework client Hydrate-only subpaths. + +- Updated dependencies [[`71fb329`](https://github.com/TanStack/router/commit/71fb3297e93a126e1bcfd9eeb0626cc4b8df8dd8)]: + - @tanstack/react-start-client@1.168.5 + +## 1.168.13 + +### Patch Changes + +- Fix serialization adapter module resolution in TanStack Start. Vite dev now uses clean runtime-specific virtual module IDs instead of browser requests containing encoded null-byte virtual IDs, which avoids reverse proxy failures. When no serialization adapters are configured, Vite and Rsbuild now resolve `#tanstack-start-plugin-adapters` through the package empty-adapter fallback. ([#7484](https://github.com/TanStack/router/pull/7484)) + +- Publish matching TanStack Start dev server packages so fresh installs do not pair a Start plugin that no longer provides `tanstack-start-injected-head-scripts:v` with an older Start server runtime that still imports it. ([#7487](https://github.com/TanStack/router/pull/7487)) + +- Updated dependencies [[`a82cec6`](https://github.com/TanStack/router/commit/a82cec69474c366b36efdb3f43c4efe8311c485a), [`d8be4f8`](https://github.com/TanStack/router/commit/d8be4f8adf912128c96b7f83e9a6c49fb24b5eed)]: + - @tanstack/start-plugin-core@1.171.6 + - @tanstack/start-client-core@1.170.4 + - @tanstack/start-server-core@1.169.4 + - @tanstack/react-start-rsc@0.1.13 + - @tanstack/react-start-client@1.168.4 + - @tanstack/react-start-server@1.167.9 + +## 1.168.12 + +### Patch Changes + +- Add Vite bundled dev mode support for TanStack Start. Start now recognizes Vite's `experimental.bundledDev` opt-in, uses the bundled dev client entry in the dev manifest, keeps server requests pointed at the latest client build output, and preserves import-protection behavior for bundled client dev. ([#7482](https://github.com/TanStack/router/pull/7482)) + +- Updated dependencies [[`90adda9`](https://github.com/TanStack/router/commit/90adda91aab7212cbcdb6159176b39d9ed01b827)]: + - @tanstack/start-plugin-core@1.171.5 + - @tanstack/react-start-rsc@0.1.12 + +## 1.168.11 + +### Patch Changes + +- Add support for Rsbuild client output formats, including module output by default and IIFE output for classic script environments. ([#7477](https://github.com/TanStack/router/pull/7477)) + + Client entry scripts and preloads are now represented as root route manifest assets, script preloads follow the manifest script format, and script asset cross-origin configuration uses the `script` key. The `transformAssets` script callback context now exposes only `kind: 'script'` and `url`, keeping script format handling internal to manifest rendering. + +- Fix Rsbuild server function metadata replay when Rspack restores modules from its persistent cache. ([#7477](https://github.com/TanStack/router/pull/7477)) + + Server function metadata is now stored on Rspack module build info and replayed from cached modules before resolver modules are rebuilt, preventing warm restarts from losing server function registrations. + +- Updated dependencies [[`51a97a1`](https://github.com/TanStack/router/commit/51a97a167fb3ef1b8ca70fbb63db635158f43509), [`51a97a1`](https://github.com/TanStack/router/commit/51a97a167fb3ef1b8ca70fbb63db635158f43509)]: + - @tanstack/react-router@1.170.8 + - @tanstack/start-plugin-core@1.171.4 + - @tanstack/start-server-core@1.169.3 + - @tanstack/react-start-client@1.168.3 + - @tanstack/react-start-rsc@0.1.11 + - @tanstack/react-start-server@1.167.8 + - @tanstack/start-client-core@1.170.3 + +## 1.168.10 + +### Patch Changes + +- Explicitly re-export public API names from `@tanstack/start-client-core` (`createServerFn`, `createMiddleware`, `createStart`, `createCsrfMiddleware`, `createIsomorphicFn`, `createClientOnlyFn`, `createServerOnlyFn`) alongside the existing `export *`. The explicit named re-exports are registered at link time (via Vite SSR's `defineExport` at `fileStartIndex`), so the namespace has these getters before any import body runs — survives the cold-start SSR cycle through user middleware where `export *` would otherwise produce a partial facade (`createMiddleware is not a function`). Workaround for vitejs/vite#22491 / #22493. ([#7466](https://github.com/TanStack/router/pull/7466)) + +- Updated dependencies []: + - @tanstack/react-router@1.170.7 + - @tanstack/react-start-client@1.168.2 + - @tanstack/react-start-rsc@0.1.10 + - @tanstack/react-start-server@1.167.7 + - @tanstack/start-client-core@1.170.2 + - @tanstack/start-plugin-core@1.171.3 + - @tanstack/start-server-core@1.169.2 + +## 1.168.9 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.171.2 + - @tanstack/react-start-rsc@0.1.9 + +## 1.168.8 + +### Patch Changes + +- Updated dependencies [[`0300f87`](https://github.com/TanStack/router/commit/0300f87ec5a7f878ffbe0b181acf84cba9139960)]: + - @tanstack/react-router@1.170.6 + - @tanstack/react-start-client@1.168.1 + - @tanstack/react-start-rsc@0.1.8 + - @tanstack/react-start-server@1.167.6 + - @tanstack/start-client-core@1.170.1 + - @tanstack/start-plugin-core@1.171.1 + - @tanstack/start-server-core@1.169.1 + +## 1.168.7 + +### Patch Changes + +- Updated dependencies [[`5fa9e55`](https://github.com/TanStack/router/commit/5fa9e555f3a2edb5e45586623e6bcbfa7f7c7a6b)]: + - @tanstack/react-start-client@1.168.0 + - @tanstack/start-client-core@1.170.0 + - @tanstack/start-plugin-core@1.171.0 + - @tanstack/start-server-core@1.169.0 + - @tanstack/router-utils@1.162.1 + - @tanstack/react-start-rsc@0.1.7 + - @tanstack/react-start-server@1.167.5 + - @tanstack/react-router@1.170.5 + +## 1.168.6 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.170.4 + - @tanstack/react-start-client@1.167.4 + - @tanstack/react-start-rsc@0.1.6 + - @tanstack/react-start-server@1.167.4 + - @tanstack/start-client-core@1.169.4 + - @tanstack/start-plugin-core@1.170.6 + - @tanstack/start-server-core@1.168.4 + +## 1.168.5 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.170.5 + - @tanstack/react-start-rsc@0.1.5 + +## 1.168.4 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.170.3 + - @tanstack/react-start-client@1.167.3 + - @tanstack/react-start-rsc@0.1.4 + - @tanstack/react-start-server@1.167.3 + - @tanstack/start-client-core@1.169.3 + - @tanstack/start-plugin-core@1.170.4 + - @tanstack/start-server-core@1.168.3 + +## 1.168.3 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.170.2 + - @tanstack/react-start-client@1.167.2 + - @tanstack/react-start-rsc@0.1.3 + - @tanstack/react-start-server@1.167.2 + - @tanstack/start-client-core@1.169.2 + - @tanstack/start-plugin-core@1.170.3 + - @tanstack/start-server-core@1.168.2 + +## 1.168.2 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.170.2 + - @tanstack/react-start-rsc@0.1.2 + +## 1.168.1 + +### Patch Changes + +- Updated dependencies [[`2387a2e`](https://github.com/TanStack/router/commit/2387a2eea0683004cc400b9f71bed5944eb60110)]: + - @tanstack/start-plugin-core@1.170.1 + - @tanstack/start-server-core@1.168.1 + - @tanstack/react-router@1.170.1 + - @tanstack/react-start-client@1.167.1 + - @tanstack/react-start-rsc@0.1.1 + - @tanstack/react-start-server@1.167.1 + - @tanstack/start-client-core@1.169.1 + +## 1.168.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +### Patch Changes + +- Updated dependencies [[`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14), [`5ae2ae5`](https://github.com/TanStack/router/commit/5ae2ae5e0f8ce32e02667a482ea9be52a6150240)]: + - @tanstack/react-router@1.170.0 + - @tanstack/react-start-client@1.167.0 + - @tanstack/react-start-rsc@0.1.0 + - @tanstack/react-start-server@1.167.0 + - @tanstack/router-utils@1.162.0 + - @tanstack/start-client-core@1.169.0 + - @tanstack/start-plugin-core@1.170.0 + - @tanstack/start-server-core@1.168.0 + +## 1.167.65 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.169.20 + - @tanstack/react-start-rsc@0.0.44 + +## 1.167.64 + +### Patch Changes + +- Updated dependencies [[`35e88f0`](https://github.com/TanStack/router/commit/35e88f04996d71019a1868b7b06ecb4ddbc9df9e)]: + - @tanstack/start-client-core@1.168.2 + - @tanstack/start-plugin-core@1.169.19 + - @tanstack/start-server-core@1.167.30 + - @tanstack/react-router@1.169.2 + - @tanstack/react-start-client@1.166.48 + - @tanstack/react-start-rsc@0.0.43 + - @tanstack/react-start-server@1.166.52 + +## 1.167.63 + +### Patch Changes + +- Updated dependencies [[`056337e`](https://github.com/TanStack/router/commit/056337ef02ccbeaf45ec8533a227761be869e8f3)]: + - @tanstack/router-utils@1.161.8 + - @tanstack/start-plugin-core@1.169.18 + - @tanstack/react-start-rsc@0.0.42 + +## 1.167.62 + +### Patch Changes + +- Updated dependencies [[`afa40ef`](https://github.com/TanStack/router/commit/afa40ef46c273c53646ba33f607fc618a07ffede)]: + - @tanstack/start-server-core@1.167.29 + - @tanstack/react-start-rsc@0.0.41 + - @tanstack/react-start-server@1.166.51 + - @tanstack/start-plugin-core@1.169.17 + +## 1.167.61 + +### Patch Changes + +- Updated dependencies [[`709627f`](https://github.com/TanStack/router/commit/709627f3dbc6d97daa547a1401ef42a53bc4be32)]: + - @tanstack/start-server-core@1.167.28 + - @tanstack/react-start-server@1.166.50 + - @tanstack/react-start-rsc@0.0.40 + - @tanstack/start-plugin-core@1.169.16 + +## 1.167.60 + +### Patch Changes + +- Add experimental HTTP 103 Early Hints support to Start server handlers. ([#7324](https://github.com/TanStack/router/pull/7324)) + +- Updated dependencies [[`238ea4a`](https://github.com/TanStack/router/commit/238ea4a4998ab3a7fd528b317e1935766ac65df8)]: + - @tanstack/start-server-core@1.167.27 + - @tanstack/react-start-server@1.166.49 + - @tanstack/react-start-rsc@0.0.39 + - @tanstack/start-plugin-core@1.169.15 + +## 1.167.59 + +### Patch Changes + +- Updated dependencies [[`96818b8`](https://github.com/TanStack/router/commit/96818b8ba5ead6f1f027094841330182aff415b2)]: + - @tanstack/start-plugin-core@1.169.14 + - @tanstack/react-start-rsc@0.0.38 + +## 1.167.58 + +### Patch Changes + +- Add compiler-driven RSC CSS auto-injection for Start RSC render APIs and wire it into the React Start Vite and Rsbuild adapters. This ensures same-file CSS module dependencies are discovered for `renderServerComponent`, `createCompositeComponent`, and JSX-based `renderToReadableStream` calls. ([#7310](https://github.com/TanStack/router/pull/7310)) + + Also add a configurable server function provider module directive hook used by the React Rsbuild RSC adapter to emit `"use server-entry"` only for extracted provider files. + +- Updated dependencies [[`ae453b7`](https://github.com/TanStack/router/commit/ae453b78624cac1b574f0d1efbfbf6ca03922c6c)]: + - @tanstack/react-start-rsc@0.0.37 + - @tanstack/start-plugin-core@1.169.13 + +## 1.167.57 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.169.1 + - @tanstack/react-start-client@1.166.47 + - @tanstack/react-start-rsc@0.0.36 + - @tanstack/react-start-server@1.166.48 + - @tanstack/start-client-core@1.168.1 + - @tanstack/start-plugin-core@1.169.12 + - @tanstack/start-server-core@1.167.26 + +## 1.167.56 + +### Patch Changes + +- Updated dependencies [[`82b0613`](https://github.com/TanStack/router/commit/82b06132af776f74603ab27977cc277d6219a845)]: + - @tanstack/start-client-core@1.168.0 + - @tanstack/react-start-client@1.166.46 + - @tanstack/react-start-rsc@0.0.35 + - @tanstack/react-start-server@1.166.47 + - @tanstack/start-plugin-core@1.169.11 + - @tanstack/start-server-core@1.167.25 + +## 1.167.55 + +### Patch Changes + +- Updated dependencies [[`c4256c2`](https://github.com/TanStack/router/commit/c4256c2c857f392d2031cf87821e4c36a92d0382)]: + - @tanstack/start-plugin-core@1.169.10 + - @tanstack/react-start-rsc@0.0.34 + +## 1.167.54 + +### Patch Changes + +- Updated dependencies [[`761fcc0`](https://github.com/TanStack/router/commit/761fcc0c96dd96721b533a1fd9e2c972f222ef94)]: + - @tanstack/start-plugin-core@1.169.9 + - @tanstack/react-start-rsc@0.0.33 + +## 1.167.53 + +### Patch Changes + +- fix exports for react-start so useServerFn is available with RSC ([#7292](https://github.com/TanStack/router/pull/7292)) + +- Updated dependencies [[`c992495`](https://github.com/TanStack/router/commit/c992495bf4010ff4c3597bb1f3b1ba02594e857e)]: + - @tanstack/react-router@1.169.0 + - @tanstack/react-start-client@1.166.45 + - @tanstack/react-start-rsc@0.0.32 + - @tanstack/react-start-server@1.166.46 + - @tanstack/start-client-core@1.167.22 + - @tanstack/start-plugin-core@1.169.8 + - @tanstack/start-server-core@1.167.24 + +## 1.167.52 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.168.26 + - @tanstack/react-start-client@1.166.44 + - @tanstack/react-start-rsc@0.0.31 + - @tanstack/react-start-server@1.166.45 + - @tanstack/start-client-core@1.167.21 + - @tanstack/start-plugin-core@1.169.7 + - @tanstack/start-server-core@1.167.23 + +## 1.167.51 + +### Patch Changes + +- Updated dependencies [[`d6decca`](https://github.com/TanStack/router/commit/d6decca41807e9ca28279e2db6640e7a8bdc1229)]: + - @tanstack/react-start-rsc@0.0.30 + +## 1.167.50 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.168.25 + - @tanstack/react-start-client@1.166.43 + - @tanstack/react-start-rsc@0.0.29 + - @tanstack/react-start-server@1.166.44 + - @tanstack/start-client-core@1.167.20 + - @tanstack/start-plugin-core@1.169.6 + - @tanstack/start-server-core@1.167.22 + +## 1.167.49 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.169.5 + - @tanstack/react-start-rsc@0.0.28 + +## 1.167.48 + +### Patch Changes + +- Updated dependencies [[`8b97002`](https://github.com/TanStack/router/commit/8b97002af3f6d15204e60c55d3f5735b78bd7efe)]: + - @tanstack/start-client-core@1.167.19 + - @tanstack/react-start-client@1.166.42 + - @tanstack/react-start-rsc@0.0.27 + - @tanstack/react-start-server@1.166.43 + - @tanstack/start-plugin-core@1.169.4 + - @tanstack/start-server-core@1.167.21 + +## 1.167.47 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.169.3 + - @tanstack/react-start-rsc@0.0.26 + +## 1.167.46 + +### Patch Changes + +- Updated dependencies [[`4d864ee`](https://github.com/TanStack/router/commit/4d864eebbd184265eabb563d326ab409c93feb17)]: + - @tanstack/react-router@1.168.24 + - @tanstack/start-plugin-core@1.169.2 + - @tanstack/start-server-core@1.167.20 + - @tanstack/react-start-client@1.166.41 + - @tanstack/react-start-rsc@0.0.25 + - @tanstack/react-start-server@1.166.42 + - @tanstack/start-client-core@1.167.18 + +## 1.167.45 + +### Patch Changes + +- Updated dependencies [[`9252206`](https://github.com/TanStack/router/commit/9252206e5aeafe53e31eb7baa491d07a597c4dc6)]: + - @tanstack/start-plugin-core@1.169.1 + - @tanstack/react-start-rsc@0.0.24 + +## 1.167.44 + +### Patch Changes + +- Split Start plugin core bundler APIs into explicit Vite and Rsbuild subpaths so projects only need the bundler they use. Mark both `vite` and `@rsbuild/core` peers as optional where Start exposes both integrations. ([#7249](https://github.com/TanStack/router/pull/7249)) + +- Updated dependencies [[`dda463c`](https://github.com/TanStack/router/commit/dda463c8b571519165d3adbc337db7a0b8be1072)]: + - @tanstack/start-plugin-core@1.169.0 + - @tanstack/react-start-rsc@0.0.23 + +## 1.167.43 + +### Patch Changes + +- rsbuild ([#7228](https://github.com/TanStack/router/pull/7228)) + +- Updated dependencies [[`91a7089`](https://github.com/TanStack/router/commit/91a708989d00537a21911e74ff60bbfec8266295)]: + - @tanstack/start-plugin-core@1.168.0 + - @tanstack/react-start-rsc@0.0.22 + - @tanstack/router-utils@1.161.7 + +## 1.167.42 + +### Patch Changes + +- Updated dependencies [[`cd91cee`](https://github.com/TanStack/router/commit/cd91ceebb84b7b752b5ee09ac14e89ad2beb2259)]: + - @tanstack/react-router@1.168.23 + - @tanstack/react-start-client@1.166.40 + - @tanstack/react-start-rsc@0.0.21 + - @tanstack/react-start-server@1.166.41 + +## 1.167.41 + +### Patch Changes + +- Updated dependencies [[`f7f0025`](https://github.com/TanStack/router/commit/f7f00250f39cf0276a984558e5d427e9270d9635)]: + - @tanstack/start-plugin-core@1.167.35 + - @tanstack/react-start-rsc@0.0.20 + +## 1.167.40 + +### Patch Changes + +- Updated dependencies [[`e30814d`](https://github.com/TanStack/router/commit/e30814d949110ff25829de44d729ead47555940a)]: + - @tanstack/react-router@1.168.22 + - @tanstack/react-start-client@1.166.39 + - @tanstack/react-start-rsc@0.0.19 + - @tanstack/react-start-server@1.166.40 + +## 1.167.39 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.168.21 + - @tanstack/react-start-client@1.166.38 + - @tanstack/react-start-rsc@0.0.18 + - @tanstack/react-start-server@1.166.39 + - @tanstack/start-client-core@1.167.17 + - @tanstack/start-plugin-core@1.167.34 + - @tanstack/start-server-core@1.167.19 + +## 1.167.38 + +### Patch Changes + +- Updated dependencies [[`c5ad329`](https://github.com/TanStack/router/commit/c5ad32936f6adcca0c56474677b73b212498443b)]: + - @tanstack/react-router@1.168.20 + - @tanstack/react-start-client@1.166.37 + - @tanstack/react-start-rsc@0.0.17 + - @tanstack/react-start-server@1.166.38 + +## 1.167.37 + +### Patch Changes + +- Fix `@tanstack/react-start/server` imports inside React Server Components by adding a `react-server` export condition that resolves to the request/response APIs without pulling in the SSR renderer entrypoints. ([#7180](https://github.com/TanStack/router/pull/7180)) + + This fixes RSC routes that call `createServerFn` loaders and read request headers in dev with `@vitejs/plugin-rsc` enabled. + +## 1.167.36 + +### Patch Changes + +- Updated dependencies [[`a581680`](https://github.com/TanStack/router/commit/a581680a27530469751b8ab419ada9ce66da4ffe)]: + - @tanstack/start-plugin-core@1.167.33 + - @tanstack/react-start-rsc@0.0.16 + +## 1.167.35 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.167.32 + - @tanstack/react-start-rsc@0.0.15 + +## 1.167.34 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.167.31 + - @tanstack/react-start-rsc@0.0.14 + +## 1.167.33 + +### Patch Changes + +- Updated dependencies [[`105d056`](https://github.com/TanStack/router/commit/105d05691a247779a63e7b688aa1207cce619339)]: + - @tanstack/react-router@1.168.19 + - @tanstack/start-plugin-core@1.167.30 + - @tanstack/react-start-client@1.166.36 + - @tanstack/react-start-rsc@0.0.13 + - @tanstack/react-start-server@1.166.37 + +## 1.167.32 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.167.29 + - @tanstack/react-start-rsc@0.0.12 + +## 1.167.31 + +### Patch Changes + +- Updated dependencies [[`0e2c900`](https://github.com/TanStack/router/commit/0e2c9003c18ae07c09969189c028f277ea562a7a)]: + - @tanstack/start-server-core@1.167.18 + - @tanstack/react-start-rsc@0.0.11 + - @tanstack/react-start-server@1.166.36 + - @tanstack/start-plugin-core@1.167.28 + - @tanstack/react-router@1.168.18 + - @tanstack/react-start-client@1.166.35 + - @tanstack/start-client-core@1.167.16 + +## 1.167.30 + +### Patch Changes + +- Updated dependencies [[`812792f`](https://github.com/TanStack/router/commit/812792fbda3caf97b300770855cf5641252f413b)]: + - @tanstack/start-plugin-core@1.167.27 + - @tanstack/start-server-core@1.167.17 + - @tanstack/react-router@1.168.17 + - @tanstack/react-start-client@1.166.34 + - @tanstack/react-start-rsc@0.0.10 + - @tanstack/react-start-server@1.166.35 + - @tanstack/start-client-core@1.167.15 + +## 1.167.29 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.168.16 + - @tanstack/react-start-client@1.166.33 + - @tanstack/react-start-rsc@0.0.9 + - @tanstack/react-start-server@1.166.34 + - @tanstack/start-client-core@1.167.14 + - @tanstack/start-plugin-core@1.167.26 + - @tanstack/start-server-core@1.167.16 + +## 1.167.28 + +### Patch Changes + +- Updated dependencies [[`d3f20fb`](https://github.com/TanStack/router/commit/d3f20fbe7acf69c3bd108c5ddc9748ad47690b04)]: + - @tanstack/start-plugin-core@1.167.25 + - @tanstack/react-start-rsc@0.0.8 + +## 1.167.27 + +### Patch Changes + +- Updated dependencies [[`6355bb7`](https://github.com/TanStack/router/commit/6355bb75f7637ba77f06a923c18fdaf37720bb48)]: + - @tanstack/start-server-core@1.167.15 + - @tanstack/react-router@1.168.15 + - @tanstack/react-start-rsc@0.0.7 + - @tanstack/react-start-server@1.166.33 + - @tanstack/start-plugin-core@1.167.24 + - @tanstack/react-start-client@1.166.32 + - @tanstack/start-client-core@1.167.13 + +## 1.167.26 + +### Patch Changes + +- migrate createStore > createAtom for simpler API ([#7150](https://github.com/TanStack/router/pull/7150)) + +- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: + - @tanstack/start-client-core@1.167.12 + - @tanstack/start-server-core@1.167.14 + - @tanstack/react-router@1.168.14 + - @tanstack/react-start-client@1.166.31 + - @tanstack/react-start-rsc@0.0.6 + - @tanstack/react-start-server@1.166.32 + - @tanstack/start-plugin-core@1.167.23 + +## 1.167.25 + +### Patch Changes + +- fix publishing ([`f8ac427`](https://github.com/TanStack/router/commit/f8ac427000c3fec99225926e72f9f2fc7a37231f)) + +- Updated dependencies [[`f8ac427`](https://github.com/TanStack/router/commit/f8ac427000c3fec99225926e72f9f2fc7a37231f)]: + - @tanstack/start-server-core@1.167.13 + - @tanstack/start-client-core@1.167.11 + - @tanstack/react-start-client@1.166.30 + - @tanstack/react-start-server@1.166.31 + - @tanstack/react-start-rsc@0.0.5 + - @tanstack/start-plugin-core@1.167.22 + +## 1.167.24 + +### Patch Changes + +- fix publishing ([`2d53c05`](https://github.com/TanStack/router/commit/2d53c056ef0b203de8a28bc92c24e8e604205d52)) + +- Updated dependencies [[`2d53c05`](https://github.com/TanStack/router/commit/2d53c056ef0b203de8a28bc92c24e8e604205d52)]: + - @tanstack/start-server-core@1.167.12 + - @tanstack/start-plugin-core@1.167.21 + - @tanstack/react-start-server@1.166.30 + - @tanstack/react-start-rsc@0.0.4 + +## 1.167.22 + +### Patch Changes + +- Republish the React Start RSC package chain so fresh installs resolve a `start-plugin-core` build that exports the subpaths used by `react-start-rsc`. ([`3384abc`](https://github.com/TanStack/router/commit/3384abcffd98a68eb254b11221834bcbcdebec31)) + +- Updated dependencies [[`3384abc`](https://github.com/TanStack/router/commit/3384abcffd98a68eb254b11221834bcbcdebec31)]: + - @tanstack/start-plugin-core@1.167.19 + - @tanstack/react-start-rsc@0.0.2 + +## 1.167.21 + +### Patch Changes + +- Updated dependencies [[`f920527`](https://github.com/TanStack/router/commit/f920527e8d5a2124f0c8a1b2c9889c9d1bf29d90)]: + - @tanstack/react-start-rsc@0.0.1 + +## 1.167.20 + +### Patch Changes + +- Updated dependencies [[`540d221`](https://github.com/TanStack/router/commit/540d22100d33415a1ddc9eb193f6aeb8184da77f), [`70ec1da`](https://github.com/TanStack/router/commit/70ec1da1ed8aa252fae67716f69fe8520ecf91b0)]: + - @tanstack/react-router@1.168.13 + - @tanstack/react-start-client@1.166.29 + - @tanstack/react-start-server@1.166.29 + +## 1.167.19 + +### Patch Changes + +- Updated dependencies [[`b29d64d`](https://github.com/TanStack/router/commit/b29d64de0c400183114c12f82183f80e37d9ea5c)]: + - @tanstack/react-router@1.168.12 + - @tanstack/react-start-client@1.166.28 + - @tanstack/react-start-server@1.166.28 + +## 1.167.18 + +### Patch Changes + +- Updated dependencies [[`4b9ed6c`](https://github.com/TanStack/router/commit/4b9ed6c5cb5437df8607c605728c8338dd2eb02c)]: + - @tanstack/react-router@1.168.11 + - @tanstack/react-start-client@1.166.27 + - @tanstack/react-start-server@1.166.27 + +## 1.167.17 + +### Patch Changes + +- Updated dependencies [[`f7e9c5e`](https://github.com/TanStack/router/commit/f7e9c5e323793d1b28c96871819c265fd28ae397)]: + - @tanstack/start-client-core@1.167.10 + - @tanstack/start-server-core@1.167.10 + - @tanstack/react-start-client@1.166.26 + - @tanstack/react-start-server@1.166.26 + - @tanstack/start-plugin-core@1.167.18 + +## 1.167.16 + +### Patch Changes + +- Updated dependencies [[`796406d`](https://github.com/TanStack/router/commit/796406da66cfb12b518bb3ca326c9d541368fb06)]: + - @tanstack/react-router@1.168.10 + - @tanstack/react-start-client@1.166.25 + - @tanstack/react-start-server@1.166.25 + - @tanstack/start-client-core@1.167.9 + - @tanstack/start-plugin-core@1.167.17 + - @tanstack/start-server-core@1.167.9 + +## 1.167.15 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.168.9 + - @tanstack/react-start-client@1.166.24 + - @tanstack/react-start-server@1.166.24 + - @tanstack/start-client-core@1.167.8 + - @tanstack/start-plugin-core@1.167.16 + - @tanstack/start-server-core@1.167.8 + +## 1.167.14 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.167.15 + +## 1.167.13 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.168.8 + - @tanstack/react-start-client@1.166.23 + - @tanstack/react-start-server@1.166.23 + - @tanstack/start-client-core@1.167.7 + - @tanstack/start-plugin-core@1.167.14 + - @tanstack/start-server-core@1.167.7 + +## 1.167.12 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.168.7 + - @tanstack/react-start-client@1.166.22 + - @tanstack/react-start-server@1.166.22 + - @tanstack/start-client-core@1.167.6 + - @tanstack/start-plugin-core@1.167.13 + - @tanstack/start-server-core@1.167.6 + +## 1.167.11 + +### Patch Changes + +- Updated dependencies [[`5ca661c`](https://github.com/TanStack/router/commit/5ca661c2f8a7e50167b4112c64aa06cef4148ea9)]: + - @tanstack/react-router@1.168.6 + - @tanstack/react-start-client@1.166.21 + - @tanstack/react-start-server@1.166.21 + +## 1.167.10 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.167.12 + +## 1.167.9 + +### Patch Changes + +- Updated dependencies [[`cf5f554`](https://github.com/TanStack/router/commit/cf5f5542476137a81515099ad740747e84512f9a)]: + - @tanstack/react-router@1.168.5 + - @tanstack/react-start-client@1.166.20 + - @tanstack/react-start-server@1.166.20 + - @tanstack/start-client-core@1.167.5 + - @tanstack/start-plugin-core@1.167.11 + - @tanstack/start-server-core@1.167.5 + +## 1.167.8 + +### Patch Changes + +- Fix the `server-entry` package export types path so published packages include the expected declaration files, and add build-time package validation to catch similar export issues during CI. ([#7035](https://github.com/TanStack/router/pull/7035)) + +## 1.167.7 + +### Patch Changes + +- Updated dependencies [[`71a8b68`](https://github.com/TanStack/router/commit/71a8b684c87c37fd4a033d99f5ba4a05c7a179f5)]: + - @tanstack/react-router@1.168.4 + - @tanstack/react-start-client@1.166.19 + - @tanstack/react-start-server@1.166.19 + - @tanstack/start-client-core@1.167.4 + - @tanstack/start-plugin-core@1.167.10 + - @tanstack/start-server-core@1.167.4 + +## 1.167.6 + +### Patch Changes + +- Updated dependencies [[`ed9c43d`](https://github.com/TanStack/router/commit/ed9c43df7ab8c679f6e6833d94651a0a091b9880)]: + - @tanstack/start-plugin-core@1.167.9 + +## 1.167.5 + +### Patch Changes + +- Updated dependencies [[`d81d21a`](https://github.com/TanStack/router/commit/d81d21ad05c9401bf54b24acd29401e1e4fd624c)]: + - @tanstack/react-router@1.168.3 + - @tanstack/start-plugin-core@1.167.8 + - @tanstack/start-server-core@1.167.3 + - @tanstack/react-start-client@1.166.18 + - @tanstack/react-start-server@1.166.18 + - @tanstack/start-client-core@1.167.3 + +## 1.167.4 + +### Patch Changes + +- Updated dependencies [[`6077120`](https://github.com/TanStack/router/commit/6077120efa59125ab79a6aff7cdb54ddae986d25)]: + - @tanstack/start-plugin-core@1.167.7 + +## 1.167.3 + +### Patch Changes + +- Updated dependencies [[`c9e1855`](https://github.com/TanStack/router/commit/c9e18555f3a5531e96de8f574cfca9edcdb18e5c)]: + - @tanstack/react-start-client@1.166.17 + - @tanstack/start-client-core@1.167.2 + - @tanstack/start-server-core@1.167.2 + - @tanstack/react-router@1.168.2 + - @tanstack/react-start-server@1.166.17 + - @tanstack/start-plugin-core@1.167.6 + +## 1.167.2 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-plugin-core@1.167.5 + +## 1.167.1 + +### Patch Changes + +- Updated dependencies [[`91cc628`](https://github.com/TanStack/router/commit/91cc62899b75ca920fe83c5ee7f3dbb5c71a523f)]: + - @tanstack/react-router@1.168.1 + - @tanstack/react-start-client@1.166.16 + - @tanstack/react-start-server@1.166.16 + - @tanstack/start-client-core@1.167.1 + - @tanstack/start-plugin-core@1.167.4 + - @tanstack/start-server-core@1.167.1 + +## 1.167.0 + +### Minor Changes + +- remove pendingMatches, cachedMatches ([#6704](https://github.com/TanStack/router/pull/6704)) + move to signal-based reactivity + solid uses its own native signals + +### Patch Changes + +- Updated dependencies [[`0545239`](https://github.com/TanStack/router/commit/054523900b2ee19308e5a88417dadfc6923afe30)]: + - @tanstack/start-client-core@1.167.0 + - @tanstack/start-server-core@1.167.0 + - @tanstack/react-router@1.168.0 + - @tanstack/react-start-client@1.166.15 + - @tanstack/react-start-server@1.166.15 + - @tanstack/start-plugin-core@1.167.3 + +## 1.166.18 + +### Patch Changes + +- Updated dependencies [[`0f585d5`](https://github.com/TanStack/router/commit/0f585d5289c8a3b11697caa9b2aa3015d37d776e)]: + - @tanstack/start-plugin-core@1.167.2 + +## 1.166.17 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.167.5 + - @tanstack/react-start-client@1.166.14 + - @tanstack/react-start-server@1.166.14 + - @tanstack/start-client-core@1.166.13 + - @tanstack/start-plugin-core@1.167.1 + - @tanstack/start-server-core@1.166.13 + +## 1.166.16 + +### Patch Changes + +- Updated dependencies [[`6651473`](https://github.com/TanStack/router/commit/6651473d028a55c70f3f54af37a12b4379b46813)]: + - @tanstack/start-plugin-core@1.167.0 + +## 1.166.15 + +### Patch Changes + +- Add @tanstack/intent AI agent skills and CLI entry points for Router and Start packages ([#6866](https://github.com/TanStack/router/pull/6866)) + +- Updated dependencies [[`940151c`](https://github.com/TanStack/router/commit/940151cbed0c76c92a5cf196c0905b17a956ca7e), [`d637152`](https://github.com/TanStack/router/commit/d6371529b5ab09af7d81463a6c4082b092411967)]: + - @tanstack/react-router@1.167.4 + - @tanstack/start-client-core@1.166.12 + - @tanstack/start-server-core@1.166.12 + - @tanstack/start-plugin-core@1.166.15 + - @tanstack/react-start-client@1.166.13 + - @tanstack/react-start-server@1.166.13 + +## 1.166.14 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/react-router@1.167.3 + - @tanstack/react-start-client@1.166.12 + - @tanstack/react-start-server@1.166.12 + - @tanstack/start-client-core@1.166.11 + - @tanstack/start-plugin-core@1.166.14 + - @tanstack/start-server-core@1.166.11 + +## 1.166.13 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +- Updated dependencies [[`838b0eb`](https://github.com/TanStack/router/commit/838b0eb9a8bbbb987a0a6972c1446e01423bbd7b)]: + - @tanstack/react-router@1.167.2 + - @tanstack/react-start-client@1.166.11 + - @tanstack/react-start-server@1.166.11 + - @tanstack/router-utils@1.161.6 + - @tanstack/start-client-core@1.166.10 + - @tanstack/start-plugin-core@1.166.13 + - @tanstack/start-server-core@1.166.10 + +## 1.166.12 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) + +- Updated dependencies [[`ef9b241`](https://github.com/TanStack/router/commit/ef9b241f3cfe95cee40daa96da669f0ffd4a971a)]: + - @tanstack/react-start-client@1.166.10 + - @tanstack/react-start-server@1.166.10 + - @tanstack/start-client-core@1.166.9 + - @tanstack/start-plugin-core@1.166.12 + - @tanstack/start-server-core@1.166.9 + - @tanstack/react-router@1.167.1 + - @tanstack/router-utils@1.161.5 + +## 1.166.11 + +### Patch Changes + +- fix: add `xmlns:xhtml` to generated sitemap ([#6920](https://github.com/TanStack/router/pull/6920)) + +- Updated dependencies [[`bfd6e62`](https://github.com/TanStack/router/commit/bfd6e62780f1cb96c210ae405723c5ebc22b10b0)]: + - @tanstack/start-plugin-core@1.166.11 + +## 1.166.10 + +### Patch Changes + +- Updated dependencies [[`6f297a2`](https://github.com/TanStack/router/commit/6f297a249424c0fd1c1a56aa4fc12c8217be7b6a)]: + - @tanstack/react-router@1.167.0 + - @tanstack/react-start-client@1.166.9 + - @tanstack/react-start-server@1.166.9 + - @tanstack/start-client-core@1.166.8 + - @tanstack/start-plugin-core@1.166.10 + - @tanstack/start-server-core@1.166.8 + +## 1.166.9 + +### Patch Changes + +- Updated dependencies [[`6069eba`](https://github.com/TanStack/router/commit/6069eba64369dbddb0d8dccdb4407f0e1a82259e)]: + - @tanstack/react-router@1.166.8 + - @tanstack/start-plugin-core@1.166.9 + - @tanstack/react-start-client@1.166.8 + - @tanstack/react-start-server@1.166.8 + +## 1.166.8 + +### Patch Changes + +- Updated dependencies [[`9a4d924`](https://github.com/TanStack/router/commit/9a4d924d2b60ffb0f7f3f8f11c95195222929870)]: + - @tanstack/start-plugin-core@1.166.8 diff --git a/packages/react-start/README.md b/packages/react-start/README.md index 2504d3e4af..e614561c15 100644 --- a/packages/react-start/README.md +++ b/packages/react-start/README.md @@ -2,7 +2,21 @@ # TanStack React Start -![TanStack React Start Header](https://github.com/tanstack/router/raw/main/media/header_start.png) + + + + TanStack React Start + SSR, Streaming, Server Functions, API Routes, bundling and more powered by [TanStack Router](https://tanstack.com/router) and Vite. Ready to deploy to your favorite hosting provider. @@ -21,13 +35,13 @@ SSR, Streaming, Server Functions, API Routes, bundling and more powered by [TanS semantic-release - + Join the discussion on Github Best of JS - + @@ -37,6 +51,6 @@ SSR, Streaming, Server Functions, API Routes, bundling and more powered by [TanS -Enjoy this library? Try the entire [TanStack](https://tanstack.com)! [React Query](https://github.com/tannerlinsley/react-query), [React Table](https://github.com/tanstack/react-table), [React Charts](https://github.com/tannerlinsley/react-charts), [React Virtual](https://github.com/tannerlinsley/react-virtual) +Enjoy this library? Try the entire [TanStack](https://tanstack.com)! [React Query](https://github.com/TanStack/query), [React Table](https://github.com/TanStack/table), [React Charts](https://github.com/TanStack/react-charts), [React Virtual](https://github.com/TanStack/virtual) Visit [tanstack.com/start](https://tanstack.com/start) for docs, guides, API and more! diff --git a/packages/react-start/package.json b/packages/react-start/package.json index 8effa01e2f..6d51a4c6d0 100644 --- a/packages/react-start/package.json +++ b/packages/react-start/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-start", - "version": "1.142.0", + "version": "1.169.6", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -26,13 +26,17 @@ "scripts": { "clean": "rimraf ./dist && rimraf ./coverage", "test": "pnpm test:build", - "test:build": "exit 0; vitest", + "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build && vite build -c vite.config.server-entry.ts" }, "type": "module", "types": "dist/esm/index.d.ts", "exports": { ".": { + "react-server": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, "import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" @@ -44,6 +48,12 @@ "default": "./dist/esm/client.js" } }, + "./hydration": { + "import": { + "types": "./dist/esm/hydration.d.ts", + "default": "./dist/esm/hydration.js" + } + }, "./client-rpc": { "import": { "types": "./dist/esm/client-rpc.d.ts", @@ -51,6 +61,10 @@ } }, "./server": { + "react-server": { + "types": "./dist/esm/server.rsc.d.ts", + "default": "./dist/esm/server.rsc.js" + }, "import": { "types": "./dist/esm/server.d.ts", "default": "./dist/esm/server.js" @@ -74,35 +88,119 @@ "default": "./dist/esm/plugin/vite.js" } }, + "./plugin/rsbuild": { + "import": { + "types": "./dist/esm/plugin/rsbuild.d.ts", + "default": "./dist/esm/plugin/rsbuild.js" + } + }, "./server-entry": { "import": { "types": "./dist/default-entry/esm/server.d.ts", "default": "./dist/default-entry/esm/server.js" } }, + "./rsc": { + "react-server": { + "types": "./dist/esm/rsc.rsc.d.ts", + "default": "./dist/esm/rsc.rsc.js" + }, + "import": { + "types": "./dist/esm/rsc.d.ts", + "default": "./dist/esm/rsc.js" + } + }, + "./rsc/serialization/server": { + "import": { + "types": "./dist/esm/rsc/serialization/server.d.ts", + "default": "./dist/esm/rsc/serialization/server.js" + } + }, + "./rsc/serialization/client": { + "import": { + "types": "./dist/esm/rsc/serialization/client.d.ts", + "default": "./dist/esm/rsc/serialization/client.js" + } + }, + "./rsbuild/browser-decode": { + "import": { + "types": "./dist/esm/rsbuild/browser-decode.d.ts", + "default": "./dist/esm/rsbuild/browser-decode.js" + } + }, + "./rsbuild/ssr-decode": { + "import": { + "types": "./dist/esm/rsbuild/ssr-decode.d.ts", + "default": "./dist/esm/rsbuild/ssr-decode.js" + } + }, + "./server-only": { + "import": { + "types": "./dist/esm/server-only.d.ts", + "default": "./dist/esm/server-only.js" + } + }, + "./client-only": { + "import": { + "types": "./dist/esm/client-only.d.ts", + "default": "./dist/esm/client-only.js" + } + }, "./package.json": "./package.json" }, "sideEffects": false, "files": [ "dist", - "src" + "src", + "skills", + "bin", + "!skills/_artifacts" ], "engines": { "node": ">=22.12.0" }, "dependencies": { - "@tanstack/react-start-client": "workspace:*", - "@tanstack/react-start-server": "workspace:*", - "@tanstack/router-utils": "workspace:^", - "@tanstack/start-plugin-core": "workspace:*", "@tanstack/react-router": "workspace:*", + "@tanstack/react-start-client": "workspace:*", + "@tanstack/react-start-rsc": "workspace:*", + "@tanstack/react-start-server": "workspace:*", + "@tanstack/router-utils": "workspace:*", "@tanstack/start-client-core": "workspace:*", + "@tanstack/start-plugin-core": "workspace:*", "@tanstack/start-server-core": "workspace:*", - "pathe": "^2.0.3" + "pathe": "catalog:" }, "peerDependencies": { + "@rsbuild/core": "^2.0.5", "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", - "vite": ">=7.0.0" + "vite": ">=8.0.0" + }, + "peerDependenciesMeta": { + "@rsbuild/core": { + "optional": true + }, + "@vitejs/plugin-rsc": { + "optional": true + }, + "vite": { + "optional": true + } + }, + "devDependencies": { + "@rsbuild/core": "catalog:", + "@types/node": ">=20", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@eslint-react/eslint-plugin": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" } } diff --git a/packages/react-start/skills/_artifacts/domain_map.yaml b/packages/react-start/skills/_artifacts/domain_map.yaml new file mode 100644 index 0000000000..4e790903a6 --- /dev/null +++ b/packages/react-start/skills/_artifacts/domain_map.yaml @@ -0,0 +1,633 @@ +# domain_map.yaml +# Generated by skill-domain-discovery +# Library: TanStack Start +# Version: 1.168.32 +# Date: 2026-03-07 +# Status: reviewed + +library: + name: '@tanstack/react-start' + version: '1.168.32' + repository: 'https://github.com/TanStack/router' + description: >- + Full-stack React framework built on TanStack Router and Vite. Adds + SSR, streaming, server functions (type-safe RPCs), middleware, + server routes, and universal deployment. Isomorphic by default — + all code runs in both environments unless explicitly constrained. + primary_framework: 'React' + +domains: + - name: 'Project Setup' + slug: 'project-setup' + description: >- + Scaffolding a Start project, configuring Vite plugin, router + setup with getRouter(), root route with document shell, client + and server entry points. + + - name: 'Server Functions' + slug: 'server-functions' + description: >- + Creating type-safe RPCs with createServerFn, input validation, + calling from loaders/components/other server functions, error + handling, streaming responses. + + - name: 'Middleware and Context' + slug: 'middleware-and-context' + description: >- + Request middleware, server function middleware, context passing + with sendContext, global middleware via createStart, middleware + factories, fetch override precedence. + + - name: 'Execution Model' + slug: 'execution-model' + description: >- + Isomorphic code execution, environment functions + (createServerFn, createServerOnlyFn, createClientOnlyFn, + createIsomorphicFn), import protection, dead code elimination, + environment variable safety. + + - name: 'Server Routes' + slug: 'server-routes' + description: >- + Server-side API endpoints defined in routes, HTTP method + handlers, handler middleware, request/response patterns. + + - name: 'Deployment and Rendering' + slug: 'deployment-and-rendering' + description: >- + Hosting providers (Cloudflare, Netlify, Vercel, Node/Docker), + selective SSR, SPA mode, static prerendering, ISR with + Cache-Control headers, SEO and head management. + +skills: + # ── Project Setup ──────────────────────────────────────────────── + - name: 'Start Setup' + slug: 'start-setup' + domain: 'project-setup' + description: >- + Scaffold a TanStack Start project, configure Vite plugin with + tanstackStart(), set up router with getRouter(), create root + route with document shell (HeadContent, Scripts, Outlet), + configure client and server entry points. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-plugin-core' + covers: + - tanstackStart Vite plugin + - getRouter() factory pattern + - Root route document shell + - HeadContent / Scripts / Outlet + - Client entry point (optional) + - Server entry point (optional) + - routeTree.gen.ts + - tsconfig configuration + tasks: + - 'Scaffold a new TanStack Start project' + - 'Configure the Vite plugin' + - 'Set up the router factory' + - 'Customize client/server entry points' + failure_modes: + - mistake: 'React plugin before Start plugin in Vite config' + mechanism: >- + Start's Vite plugin must come before React's plugin. + Wrong order causes route generation and server function + compilation to fail. + wrong_pattern: | + plugins: [react(), tanstackStart()] + correct_pattern: | + plugins: [tanstackStart(), react()] + source: 'docs/start/framework/react/build-from-scratch.md' + priority: CRITICAL + status: active + + - mistake: 'Enabling verbatimModuleSyntax in tsconfig' + mechanism: >- + verbatimModuleSyntax causes server bundles to leak into + client bundles. Must be disabled. + source: 'docs/start/framework/react/build-from-scratch.md' + priority: HIGH + status: active + + - mistake: 'Missing Scripts component in root route' + mechanism: >- + The Scripts component must be rendered in the body of + the root route for proper hydration and functionality. + Without it, client-side JavaScript does not load. + source: 'docs/start/framework/react/guide/routing.md' + priority: HIGH + status: active + + # ── Server Functions ───────────────────────────────────────────── + - name: 'Server Functions' + slug: 'server-functions' + domain: 'server-functions' + description: >- + Create type-safe RPCs with createServerFn, validate inputs + with Zod or plain functions, call from loaders/components/ + event handlers, handle errors/redirects/notFound, stream + responses with ReadableStream or async generators. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-client-core' + - '@tanstack/start-server-core' + covers: + - createServerFn (GET/POST) + - validator (Zod or function) + - useServerFn hook + - Server context utilities (getRequest, getRequestHeader, setResponseHeader, setResponseStatus) + - Error handling (throw errors, redirect, notFound) + - Streaming (ReadableStream, async generators) + - File organization (.functions.ts, .server.ts) + - FormData handling + tasks: + - 'Create a server function for data fetching' + - 'Validate server function inputs' + - 'Call server functions from components' + - 'Stream data from server functions' + - 'Handle errors in server functions' + failure_modes: + - mistake: 'Putting server-only code in loaders instead of server functions' + mechanism: >- + Loaders are ISOMORPHIC — they run on both client and server. + Database queries, file system access, and secret API keys + in loaders will either fail on the client or leak to the + client bundle. Use createServerFn for server-only logic. + wrong_pattern: | + export const Route = createFileRoute('/posts')({ + loader: async () => { + const posts = await db.query('SELECT * FROM posts') + return { posts } + }, + }) + correct_pattern: | + const getPosts = createServerFn({ method: 'GET' }) + .handler(async () => { + const posts = await db.query('SELECT * FROM posts') + return { posts } + }) + + export const Route = createFileRoute('/posts')({ + loader: () => getPosts(), + }) + source: 'maintainer interview' + priority: CRITICAL + status: active + skills: ['server-functions', 'execution-model'] + + - mistake: 'Using dynamic imports for server functions' + mechanism: >- + Dynamic imports of server functions can cause bundler + issues. Static imports are safe — the build process + replaces server implementations with RPC stubs. + wrong_pattern: | + const { getUser } = await import('~/utils/users.functions') + correct_pattern: | + import { getUser } from '~/utils/users.functions' + source: 'docs/start/framework/react/guide/server-functions.md' + priority: HIGH + status: active + + - mistake: 'Not using useServerFn for component calls' + mechanism: >- + Component calls need useServerFn so redirects and not-found + responses use the active router instead of falling through as + ordinary function results. + source: 'docs/start/framework/react/guide/server-functions.md' + priority: MEDIUM + status: active + + - mistake: 'Generating Next.js or Remix server patterns' + mechanism: >- + Agents generate getServerSideProps, "use server" directives, + or Remix-style loader exports. TanStack Start uses + createServerFn for server-only code. + wrong_pattern: | + 'use server' + export async function getUser() { ... } + correct_pattern: | + const getUser = createServerFn({ method: 'GET' }) + .handler(async () => { ... }) + source: 'maintainer interview' + priority: CRITICAL + status: active + + - mistake: 'Relying on a route guard to protect a server function' + mechanism: >- + beforeLoad protects route UX, but createServerFn exposes an + independently callable endpoint. Private handlers must enforce + authentication and authorization themselves or through middleware. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + - mistake: 'Self-fetching a relative API URL from an SSR loader' + mechanism: >- + Loaders also run on the server, where relative URLs may not have a + base. App-internal loaders should call a server function directly. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + - mistake: 'Mutating without invalidating cached loader data' + mechanism: >- + Local state can show a write that was not persisted or leave route + cache stale. Await the write, invalidate, and verify a fresh reload. + source: 'protocol-v4 evaluation' + priority: HIGH + status: active + + - mistake: 'Treating typecheck as proof of output schema propagation' + mechanism: >- + A typed model can still be projected or serialized without the new + field. Assert the actual handler or HTTP payload at runtime. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + # ── Middleware and Context ─────────────────────────────────────── + - name: 'Middleware' + slug: 'middleware' + domain: 'middleware-and-context' + description: >- + Request middleware and server function middleware with + createMiddleware, context passing via next(), sendContext + for client-server transfer, global middleware via createStart + in src/start.ts, middleware factories, fetch override + precedence, header merging. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-client-core' + - '@tanstack/start-server-core' + covers: + - createMiddleware + - Request middleware (.server only) + - Server function middleware (.client + .server) + - Context passing via next({ context }) + - sendContext for client-server transfer + - Global middleware (createStart in src/start.ts) + - Middleware factories + - Fetch override precedence + - Header merging + - Method order enforcement (middleware → validator → client → server) + tasks: + - 'Add authentication middleware' + - 'Pass context through middleware chain' + - 'Configure global request middleware' + - 'Create reusable middleware factories' + failure_modes: + - mistake: 'Trusting client context without server validation' + mechanism: >- + Client context via sendContext is NOT validated by default. + Dynamic user-generated data must be validated in server-side + middleware before use. + source: 'docs/start/framework/react/guide/middleware.md' + priority: HIGH + status: active + + - mistake: 'Wrong middleware method order' + mechanism: >- + TypeScript enforces method order: middleware → validator + → client → server. Wrong order causes type errors and + runtime failures. + source: 'docs/start/framework/react/guide/middleware.md' + priority: MEDIUM + status: active + + - mistake: 'Confusing request vs server function middleware' + mechanism: >- + Request middleware runs on ALL server requests (SSR, server + routes, server functions). Server function middleware runs + only for server functions and has .client() method. Using + the wrong type causes unexpected scope. + source: 'docs/start/framework/react/guide/middleware.md' + priority: MEDIUM + status: active + + # ── Execution Model ────────────────────────────────────────────── + - name: 'Execution Model' + slug: 'execution-model' + domain: 'execution-model' + description: >- + Isomorphic code execution model, environment boundary functions + (createServerFn, createServerOnlyFn, createClientOnlyFn, + createIsomorphicFn), import protection, dead code elimination, + environment variable safety (VITE_ prefix), useHydrated hook. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-client-core' + - '@tanstack/start-server-core' + covers: + - Isomorphic-by-default principle + - createServerFn (RPC boundary) + - createServerOnlyFn (throws on client) + - createClientOnlyFn (throws on server) + - createIsomorphicFn (different impl per env) + - ClientOnly component + - useHydrated hook + - Import protection (experimental) + - Environment variables (VITE_ prefix, process.env) + - Dead code elimination / tree shaking + tasks: + - 'Protect server-only code from client bundles' + - 'Use environment-specific implementations' + - 'Handle environment variables safely' + - 'Debug import protection violations' + failure_modes: + - mistake: 'Assuming loaders are server-only' + mechanism: >- + ALL code in TanStack Start is isomorphic by default. + Loaders run on BOTH server and client. Server-only + operations must use createServerFn, createServerOnlyFn, + or server routes. + wrong_pattern: | + export const Route = createFileRoute('/dashboard')({ + loader: async () => { + const secret = process.env.API_SECRET + return fetch(`https://api.example.com/data`, { + headers: { Authorization: secret } + }) + }, + }) + correct_pattern: | + const getData = createServerFn({ method: 'GET' }) + .handler(async () => { + const secret = process.env.API_SECRET + return fetch(`https://api.example.com/data`, { + headers: { Authorization: secret } + }) + }) + + export const Route = createFileRoute('/dashboard')({ + loader: () => getData(), + }) + source: 'docs/start/framework/react/guide/execution-model.md' + priority: CRITICAL + status: active + skills: ['execution-model', 'server-functions'] + + - mistake: 'Exposing secrets via module-level process.env' + mechanism: >- + Module-level process.env access runs in both environments. + The variable value leaks into the client bundle. Access + secrets only inside createServerFn or createServerOnlyFn. + wrong_pattern: | + const apiKey = process.env.SECRET_KEY + export function fetchData() { ... } + correct_pattern: | + const fetchData = createServerFn({ method: 'GET' }) + .handler(async () => { + const apiKey = process.env.SECRET_KEY + return fetch(url, { headers: { Authorization: apiKey } }) + }) + source: 'docs/start/framework/react/guide/execution-model.md' + priority: CRITICAL + status: active + + - mistake: 'Using VITE_ prefix for server secrets' + mechanism: >- + VITE_ prefixed variables are exposed to the client bundle. + Server secrets must NOT have the VITE_ prefix. Access + them via process.env inside server functions only. + source: 'docs/start/framework/react/guide/environment-variables.md' + priority: CRITICAL + status: active + + - mistake: 'Hydration mismatches from env-dependent rendering' + mechanism: >- + Rendering different output from server-only environment state + causes the client hydration pass to disagree with the SSR HTML. + Transfer stable data or defer environment-dependent UI. + source: 'docs/start/framework/react/guide/execution-model.md' + priority: HIGH + status: active + + - mistake: 'Using a relative URL in an isomorphic loader' + mechanism: >- + Browser fetch resolves relative URLs against the document, while an + SSR runtime may have no base URL. Use a server function boundary. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + # ── Server Routes ──────────────────────────────────────────────── + - name: 'Server Routes' + slug: 'server-routes' + domain: 'server-routes' + description: >- + Define server-side API endpoints alongside app routes using + the server property with HTTP method handlers, per-handler + middleware via createHandlers, request/response patterns. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-server-core' + covers: + - server property on createFileRoute + - handlers object (GET, POST, PUT, DELETE) + - createHandlers for per-handler middleware + - Handler context (request, params, context) + - Request body parsing (json, text, formData) + - Response helpers (Response.json) + - File naming for API routes + tasks: + - 'Create a REST API endpoint' + - 'Add middleware to server route handlers' + - 'Handle different HTTP methods' + failure_modes: + - mistake: 'Duplicate path resolution for server routes' + mechanism: >- + Each route can only have a single handler file. Having + both users.ts and users/index.ts causes errors. + source: 'docs/start/framework/react/guide/server-routes.md' + priority: MEDIUM + status: active + + - mistake: 'Forgetting to await request body methods' + mechanism: >- + Request body readers return promises. Using request.json(), + request.text(), or request.formData() without await passes a promise + instead of the parsed request body. + source: 'docs/start/framework/react/guide/server-routes.md' + priority: MEDIUM + status: active + + - mistake: 'Relying on page auth to protect a server route' + mechanism: >- + API handlers are directly callable and must authenticate and + authorize private reads and writes at the handler boundary. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + - mistake: 'Self-fetching a server route from an SSR loader' + mechanism: >- + A relative API URL can fail during SSR. Share one server-side service + between a server function and server route instead. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + - mistake: 'Omitting a field from serialized response output' + mechanism: >- + Typechecking does not inspect the runtime Response payload. Test the + serialized output when a schema changes. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + # ── Deployment and Rendering ───────────────────────────────────── + - name: 'Deployment' + slug: 'deployment' + domain: 'deployment-and-rendering' + description: >- + Deploy TanStack Start to Cloudflare Workers, Netlify, Vercel, + Node.js/Docker, Bun, Railway. Configure selective SSR, SPA + mode, static prerendering, ISR with Cache-Control headers. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-plugin-core' + covers: + - Cloudflare Workers deployment + - Netlify deployment + - Vercel / Railway deployment + - Node.js / Docker deployment + - Bun deployment + - Selective SSR (ssr option per route) + - SPA mode configuration + - Static prerendering (prerender option) + - ISR with Cache-Control headers + - SEO (head property, structured data) + tasks: + - 'Deploy to Cloudflare Workers' + - 'Deploy to Netlify' + - 'Configure selective SSR per route' + - 'Enable SPA mode' + - 'Set up static prerendering' + - 'Configure ISR with cache headers' + failure_modes: + - mistake: 'Bun deployment with React 18' + mechanism: >- + Bun-specific deployment only works with React 19. + For React 18, use Node.js deployment guidelines. + source: 'docs/start/framework/react/guide/hosting.md' + priority: MEDIUM + status: active + + - mistake: 'Missing nodejs_compat flag for Cloudflare Workers' + mechanism: >- + Cloudflare Workers requires compatibility_flags: + ["nodejs_compat"] in wrangler config. Without it, + Node.js APIs used by Start fail at runtime. + source: 'docs/start/framework/react/guide/hosting.md' + priority: HIGH + status: active + + - mistake: 'Child route loosening parent SSR config' + mechanism: >- + SSR config inherits from parent and can only become MORE + restrictive (true → data-only → false). A child cannot + set ssr: true if parent has ssr: false. + source: 'docs/start/framework/react/guide/selective-ssr.md' + priority: MEDIUM + status: active + + - name: 'Server Components' + slug: 'server-components' + domain: 'deployment-and-rendering' + description: >- + Implement and debug TanStack Start React Server Components with + renderServerComponent, createCompositeComponent, low-level + Flight streaming APIs, Router vs Query cache ownership, refresh + paths, and selective SSR modes. + type: sub-skill + packages: + - '@tanstack/react-start' + - '@tanstack/react-start-rsc' + covers: + - renderServerComponent + - createCompositeComponent + - CompositeComponent + - renderToReadableStream + - createFromReadableStream + - createFromFetch + - Router-owned RSC caching + - Query-owned RSC caching + - Refresh ownership (router.invalidate, invalidateQueries, refetchQueries) + - "Selective SSR modes (ssr: 'data-only', ssr: false)" + - 'structuralSharing: false for Query-cached RSC values' + tasks: + - 'Implement route-owned React Server Components' + - 'Choose between renderServerComponent and createCompositeComponent' + - 'Debug stale RSC data and invalidation' + - 'Migrate Next App Router RSC patterns to TanStack Start' + failure_modes: + - mistake: 'Using renderServerComponent when the UI needs slots' + mechanism: >- + renderServerComponent returns a renderable value and does + not support client-provided children, render props, or + component props. Use createCompositeComponent and render it + with CompositeComponent when the server output must accept + slots. + source: 'docs/start/framework/react/guide/server-components.md' + priority: HIGH + status: active + + - mistake: 'Omitting structuralSharing: false for Query-cached RSC values' + mechanism: >- + Query-cached RSC values must disable structural sharing. + Otherwise the cache may try to merge Flight payloads across + fetches, which can cause errors. + source: 'docs/start/framework/react/guide/server-components.md' + priority: HIGH + status: active + + - mistake: 'Copying stale renderRsc or .validator examples into current code' + mechanism: >- + Older snippets may use renderRsc or .validator(...). + Normalize them to renderServerComponent and + .validator(...) before using them in current code. + source: 'docs/start/framework/react/guide/server-functions.md' + priority: MEDIUM + status: active + +tensions: + - name: 'Isomorphic defaults vs server-only expectations' + skills: ['execution-model', 'server-functions'] + description: >- + All code runs everywhere by default. Agents trained on + Next.js/Remix assume loaders and route code are server-only. + implication: >- + Agents put secrets, DB queries, and file system access in + loaders instead of server functions, causing client-side + failures or security leaks. + + - name: 'Simplicity of isomorphic code vs security boundaries' + skills: ['execution-model', 'middleware'] + description: >- + The isomorphic model makes code easy to write but requires + explicit boundaries for security. Agents don't realize they + need to actively constrain execution environment. + implication: >- + Agents expose secrets via module-level process.env or + forget to validate sendContext data in middleware. + +cross_references: + - from: 'server-functions' + to: 'execution-model' + reason: 'Server functions ARE the isomorphic boundary — understanding the execution model is prerequisite' + - from: 'server-functions' + to: 'middleware' + reason: 'Server function middleware chains compose with server functions' + - from: 'middleware' + to: 'server-routes' + reason: 'Server routes use the same middleware system' + - from: 'deployment' + to: 'execution-model' + reason: 'Deployment target affects which environment code runs in' + +gaps: [] diff --git a/packages/react-start/skills/_artifacts/skill_spec.md b/packages/react-start/skills/_artifacts/skill_spec.md new file mode 100644 index 0000000000..f550196da8 --- /dev/null +++ b/packages/react-start/skills/_artifacts/skill_spec.md @@ -0,0 +1,111 @@ +# TanStack Start — Skill Spec + +TanStack Start is a full-stack React framework built on TanStack Router and Vite. It adds SSR, streaming, server functions (type-safe RPCs), middleware, server routes, and universal deployment. All code is isomorphic by default — it runs in both server and client environments unless explicitly constrained. + +## Domains + +| Domain | Description | Skills | +| ------------------------ | ------------------------------------------------------------- | ----------------------------- | +| Project Setup | Scaffolding, Vite plugin, router factory, root route, entries | start-setup | +| Server Functions | Type-safe RPCs with createServerFn, validation, streaming | server-functions | +| Middleware and Context | Request/function middleware, context, global middleware | middleware | +| Execution Model | Isomorphic defaults, environment boundaries, env vars | execution-model | +| Server Routes | API endpoints, HTTP handlers, handler middleware | server-routes | +| Deployment and Rendering | Hosting, selective SSR, prerendering, SEO | deployment, server-components | + +## Skill Inventory + +| Skill | Type | Domain | What it covers | Failure modes | +| ------------------- | --------- | ------------------------ | ------------------------------------------------------- | ------------- | +| start-setup | core | project-setup | tanstackStart(), getRouter(), root route, entries | 3 | +| server-functions | core | server-functions | createServerFn, validation, useServerFn, streaming | 8 | +| middleware | core | middleware-and-context | createMiddleware, context, global middleware, factories | 3 | +| execution-model | core | execution-model | Isomorphic defaults, environment functions, env vars | 5 | +| server-routes | core | server-routes | server property, HTTP handlers, createHandlers | 5 | +| deployment | core | deployment-and-rendering | Hosting, SSR modes, prerendering, SEO | 3 | +| server-components | sub-skill | deployment-and-rendering | React Server Components, cache ownership, selective SSR | 3 | +| react-start | framework | project-setup | React bindings, useServerFn, full setup | 3 | +| migrate-from-nextjs | lifecycle | project-setup | Next.js App Router migration checklist | 3 | + +## Failure Mode Inventory + +### start-setup (3 failure modes) + +| # | Mistake | Priority | Source | +| --- | ----------------------------------------------- | -------- | ----------------------- | +| 1 | React plugin before Start plugin in Vite config | CRITICAL | docs/build-from-scratch | +| 2 | Enabling verbatimModuleSyntax in tsconfig | HIGH | docs/build-from-scratch | +| 3 | Missing Scripts component in root route | HIGH | docs/guide/routing | + +### server-functions (8 failure modes) + +| # | Mistake | Priority | Source | +| --- | --------------------------------------------------------------- | -------- | --------------------------- | +| 1 | Putting server-only code in loaders instead of server functions | CRITICAL | maintainer interview | +| 2 | Using dynamic imports for server functions | HIGH | docs/guide/server-functions | +| 3 | Not using useServerFn for component calls | MEDIUM | docs/guide/server-functions | +| 4 | Generating Next.js or Remix server patterns | CRITICAL | maintainer interview | +| 5 | Relying on a route guard to protect a server function | CRITICAL | protocol-v4 evaluation | +| 6 | Self-fetching a relative API URL from an SSR loader | CRITICAL | protocol-v4 evaluation | +| 7 | Mutating without invalidating cached loader data | HIGH | protocol-v4 evaluation | +| 8 | Treating typecheck as proof of output schema propagation | CRITICAL | protocol-v4 evaluation | + +### middleware (3 failure modes) + +| # | Mistake | Priority | Source | +| --- | ----------------------------------------------------- | -------- | --------------------- | +| 1 | Trusting client sendContext without server validation | HIGH | docs/guide/middleware | +| 2 | Confusing request vs server function middleware | MEDIUM | docs/guide/middleware | +| 3 | Wrong middleware method order | MEDIUM | docs/guide/middleware | + +### execution-model (5 failure modes) + +| # | Mistake | Priority | Source | +| --- | ------------------------------------------------- | -------- | -------------------------------- | +| 1 | Assuming loaders are server-only | CRITICAL | docs/guide/execution-model | +| 2 | Exposing secrets via module-level process.env | CRITICAL | docs/guide/execution-model | +| 3 | Using VITE\_ prefix for server secrets | CRITICAL | docs/guide/environment-variables | +| 4 | Hydration mismatches from env-dependent rendering | HIGH | docs/guide/execution-model | +| 5 | Using a relative URL in an isomorphic loader | CRITICAL | protocol-v4 evaluation | + +### server-routes (5 failure modes) + +| # | Mistake | Priority | Source | +| --- | ------------------------------------------------ | -------- | ------------------------ | +| 1 | Duplicate path resolution for server routes | MEDIUM | docs/guide/server-routes | +| 2 | Forgetting to await request body methods | MEDIUM | docs/guide/server-routes | +| 3 | Relying on page auth to protect a server route | CRITICAL | protocol-v4 evaluation | +| 4 | Self-fetching a server route from an SSR loader | CRITICAL | protocol-v4 evaluation | +| 5 | Omitting a field from serialized response output | CRITICAL | protocol-v4 evaluation | + +### deployment (3 failure modes) + +| # | Mistake | Priority | Source | +| --- | ------------------------------------------------- | -------- | ------------------------ | +| 1 | Missing nodejs_compat flag for Cloudflare Workers | HIGH | docs/guide/hosting | +| 2 | Bun deployment with React 18 | MEDIUM | docs/guide/hosting | +| 3 | Child route loosening parent SSR config | MEDIUM | docs/guide/selective-ssr | + +### server-components (3 failure modes) + +| # | Mistake | Priority | Source | +| --- | ------------------------------------------------------------- | -------- | ---------------------------- | +| 1 | Using renderServerComponent when the UI needs slots | HIGH | docs/guide/server-components | +| 2 | Omitting structuralSharing: false for Query-cached RSC values | HIGH | docs/guide/server-components | +| 3 | Copying stale renderRsc or .validator examples | MEDIUM | docs/guide/server-functions | + +## Tensions + +| Tension | Skills | Agent implication | +| ---------------------------------------------------- | ---------------------------------- | ----------------------------------------------------------------------------- | +| Isomorphic defaults vs server-only expectations | execution-model ↔ server-functions | Agents put secrets/DB queries in loaders instead of server functions | +| Simplicity of isomorphic code vs security boundaries | execution-model ↔ middleware | Agents expose secrets via module-level process.env or skip context validation | + +## Cross-References + +| From | To | Reason | +| ---------------- | --------------- | ----------------------------------------------- | +| server-functions | execution-model | Server functions ARE the isomorphic boundary | +| server-functions | middleware | Middleware chains compose with server functions | +| middleware | server-routes | Server routes use the same middleware system | +| deployment | execution-model | Deployment target affects where code runs | diff --git a/packages/react-start/skills/_artifacts/skill_tree.yaml b/packages/react-start/skills/_artifacts/skill_tree.yaml new file mode 100644 index 0000000000..3078228f73 --- /dev/null +++ b/packages/react-start/skills/_artifacts/skill_tree.yaml @@ -0,0 +1,177 @@ +# skills/_artifacts/start_skill_tree.yaml +library: + name: '@tanstack/react-start' + version: '1.168.32' + repository: 'https://github.com/TanStack/router' + description: >- + Full-stack React framework built on TanStack Router and Vite. + Adds SSR, streaming, server functions (type-safe RPCs), middleware, + server routes, and universal deployment. Isomorphic by default — + all code runs in both environments unless explicitly constrained. +generated_from: + domain_map: '_artifacts/start_domain_map.yaml' +generated_at: '2026-03-07' + +skills: + # ── Start Core Skills ─────────────────────────────────────────── + - name: 'Start Core' + slug: 'start-core' + type: 'core' + domain: 'project-setup' + path: 'skills/start-core/SKILL.md' + package: 'packages/start-client-core' + description: >- + Core overview for TanStack Start: tanstackStart() Vite plugin, + getRouter() factory, root route document shell (HeadContent, + Scripts, Outlet), client/server entry points, routeTree.gen.ts, + tsconfig configuration. Entry point for all Start skills. + sources: + - 'TanStack/router:docs/start/framework/react/build-from-scratch.md' + - 'TanStack/router:docs/start/framework/react/quick-start.md' + - 'TanStack/router:docs/start/framework/react/guide/routing.md' + + - name: 'Server Functions' + slug: 'start-core/server-functions' + type: 'sub-skill' + domain: 'server-functions' + path: 'skills/start-core/server-functions/SKILL.md' + package: 'packages/start-client-core' + description: >- + createServerFn (GET/POST), validator (Zod or function), + useServerFn hook, server context utilities (getRequest, + getRequestHeader, setResponseHeader, setResponseStatus), error + handling (throw errors, redirect, notFound), streaming + (ReadableStream, async generators), FormData handling, file + organization (.functions.ts, .server.ts). + requires: + - 'start-core' + sources: + - 'TanStack/router:docs/start/framework/react/guide/server-functions.md' + + - name: 'Middleware' + slug: 'start-core/middleware' + type: 'sub-skill' + domain: 'middleware-and-context' + path: 'skills/start-core/middleware/SKILL.md' + package: 'packages/start-client-core' + description: >- + createMiddleware, request middleware (.server only), server + function middleware (.client + .server), context passing via + next({ context }), sendContext for client-server transfer, + global middleware via createStart in src/start.ts, middleware + factories, method order enforcement. + requires: + - 'start-core' + - 'start-core/server-functions' + sources: + - 'TanStack/router:docs/start/framework/react/guide/middleware.md' + + - name: 'Execution Model' + slug: 'start-core/execution-model' + type: 'sub-skill' + domain: 'execution-model' + path: 'skills/start-core/execution-model/SKILL.md' + package: 'packages/start-client-core' + description: >- + Isomorphic-by-default principle, environment boundary functions + (createServerFn, createServerOnlyFn, createClientOnlyFn, + createIsomorphicFn), ClientOnly component, useHydrated hook, + import protection, dead code elimination, environment variable + safety (VITE_ prefix, process.env). + requires: + - 'start-core' + sources: + - 'TanStack/router:docs/start/framework/react/guide/execution-model.md' + - 'TanStack/router:docs/start/framework/react/guide/environment-variables.md' + + - name: 'Server Routes' + slug: 'start-core/server-routes' + type: 'sub-skill' + domain: 'server-routes' + path: 'skills/start-core/server-routes/SKILL.md' + package: 'packages/start-client-core' + description: >- + Server-side API endpoints using the server property on + createFileRoute, HTTP method handlers (GET, POST, PUT, DELETE), + createHandlers for per-handler middleware, handler context + (request, params, context), request body parsing, response + helpers, file naming for API routes. + requires: + - 'start-core' + sources: + - 'TanStack/router:docs/start/framework/react/guide/server-routes.md' + + - name: 'Deployment' + slug: 'start-core/deployment' + type: 'sub-skill' + domain: 'deployment-and-rendering' + path: 'skills/start-core/deployment/SKILL.md' + package: 'packages/start-client-core' + description: >- + Deploy to Cloudflare Workers, Netlify, Vercel, Node.js/Docker, + Bun, Railway. Selective SSR (ssr option per route), SPA mode, + static prerendering, ISR with Cache-Control headers, SEO and + head management. + requires: + - 'start-core' + sources: + - 'TanStack/router:docs/start/framework/react/guide/hosting.md' + - 'TanStack/router:docs/start/framework/react/guide/selective-ssr.md' + - 'TanStack/router:docs/start/framework/react/guide/static-prerendering.md' + - 'TanStack/router:docs/start/framework/react/guide/full-stack-seo.md' + + # ── React Start Skills ────────────────────────────────────────── + - name: 'React Start' + slug: 'react-start' + type: 'framework' + domain: 'project-setup' + path: 'skills/react-start/SKILL.md' + package: 'packages/react-start' + description: >- + React bindings for TanStack Start: createStart, StartClient, + StartServer, React-specific imports, re-exports from + @tanstack/react-router, full project setup with React. + requires: + - 'start-core' + sources: + - 'TanStack/router:packages/react-start/src' + - 'TanStack/router:docs/start/framework/react/build-from-scratch.md' + + - name: 'Server Components' + slug: 'react-start/server-components' + type: 'sub-skill' + domain: 'deployment-and-rendering' + path: 'skills/react-start/server-components/SKILL.md' + package: 'packages/react-start' + description: >- + Implement, review, debug, and refactor TanStack Start React + Server Components in React 19 apps. + requires: + - 'react-start' + - 'start-core/server-functions' + - 'start-core/execution-model' + sources: + - 'TanStack/router:docs/start/framework/react/guide/server-components.md' + - 'TanStack/router:docs/start/framework/react/guide/server-functions.md' + - 'TanStack/router:docs/start/framework/react/guide/execution-model.md' + - 'TanStack/router:docs/router/guide/data-loading.md' + + # ── Lifecycle Skills ──────────────────────────────────────────── + - name: 'Migrate from Next.js' + slug: 'lifecycle/migrate-from-nextjs' + type: 'lifecycle' + domain: 'project-setup' + path: 'skills/lifecycle/migrate-from-nextjs/SKILL.md' + package: 'packages/react-start' + description: >- + Step-by-step migration from Next.js App Router to TanStack + Start: route definition conversion, API mapping, server + function conversion from Server Actions, middleware conversion, + data fetching pattern changes. + requires: + - 'start-core' + - 'react-start' + sources: + - 'TanStack/router:docs/start/framework/react/guide/server-functions.md' + - 'TanStack/router:docs/start/framework/react/guide/middleware.md' + - 'TanStack/router:docs/start/framework/react/guide/execution-model.md' diff --git a/packages/react-start/skills/lifecycle/migrate-from-nextjs/SKILL.md b/packages/react-start/skills/lifecycle/migrate-from-nextjs/SKILL.md new file mode 100644 index 0000000000..81b020713b --- /dev/null +++ b/packages/react-start/skills/lifecycle/migrate-from-nextjs/SKILL.md @@ -0,0 +1,436 @@ +--- +name: migrate-from-nextjs +description: >- + Step-by-step migration from Next.js App Router to TanStack Start: + route definition conversion, API mapping, server function + conversion from Server Actions, middleware conversion, data + fetching pattern changes. +metadata: + type: lifecycle + library: tanstack-start + library_version: '1.168.32' +requires: + - start-core + - react-start +sources: + - TanStack/router:docs/start/framework/react/guide/server-functions.md + - TanStack/router:docs/start/framework/react/guide/middleware.md + - TanStack/router:docs/start/framework/react/guide/execution-model.md +--- + +# Migrate from Next.js App Router to TanStack Start + +This is a step-by-step migration checklist. Complete tasks in order. + +> **CRITICAL**: TanStack Start is isomorphic by default. ALL code runs in both environments unless you use `createServerFn`. This is the opposite of Next.js Server Components, where code is server-only by default. + +> **CRITICAL**: TanStack Start uses `createServerFn`, NOT `"use server"` directives. Do not carry over any `"use server"` or `"use client"` directives. + +> **CRITICAL**: Types are FULLY INFERRED in TanStack Router/Start. Never cast, never annotate inferred values. + +## Pre-Migration + +- [ ] **Create a migration branch** + +```bash +git checkout -b migrate-to-tanstack-start +``` + +- [ ] **Install TanStack Start** + +```bash +npm i @tanstack/react-start @tanstack/react-router +npm i -D vite @vitejs/plugin-react +``` + +- [ ] **Remove Next.js** + +```bash +npm uninstall next @next/font @next/image +``` + +## Concept Mapping + +| Next.js App Router | TanStack Start | +| -------------------------------- | ------------------------------------------------------------------------- | +| `app/page.tsx` | `src/routes/index.tsx` | +| `app/layout.tsx` | `src/routes/__root.tsx` | +| `app/posts/[id]/page.tsx` | `src/routes/posts/$postId.tsx` | +| `app/api/users/route.ts` | `src/routes/api/users.ts` (server property) | +| `"use server"` + Server Actions | `createServerFn()` | +| `"use client"` | Not needed (everything is isomorphic) | +| Server Components (default) | All components are isomorphic; use `createServerFn` for server-only logic | +| `next/navigation` `useRouter` | `useRouter()` from `@tanstack/react-router` | +| `next/link` `Link` | `` from `@tanstack/react-router` | +| `next/head` or `metadata` export | `head` property on route | +| `middleware.ts` (edge) | `createMiddleware()` in `src/start.ts` | +| `next.config.js` | `vite.config.ts` with `tanstackStart()` | +| `generateStaticParams` | `prerender` config in `vite.config.ts` | + +## Step 1: Vite Configuration + +Replace `next.config.js` with: + +```ts +// 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(), // MUST come before react() + viteReact(), + ], +}) +``` + +Update `package.json`: + +```json +{ + "type": "module", + "scripts": { + "dev": "vite dev", + "build": "vite build", + "start": "node .output/server/index.mjs" + } +} +``` + +## Step 2: Router Factory + +```tsx +// src/router.tsx +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + const router = createRouter({ + routeTree, + scrollRestoration: true, + }) + return router +} +``` + +## Step 3: Convert Layout → Root Route + +Next.js: + +```tsx +// app/layout.tsx +export const metadata = { title: 'My App' } +export default function RootLayout({ children }) { + return ( + + {children} + + ) +} +``` + +TanStack Start: + +```tsx +// src/routes/__root.tsx +import type { ReactNode } from 'react' +import { + Outlet, + createRootRoute, + HeadContent, + Scripts, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'My App' }, + ], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} +``` + +## Step 4: Convert Pages → File Routes + +Next.js: + +```tsx +// app/posts/[id]/page.tsx +export default function PostPage({ params }: { params: { id: string } }) { + // ... +} +``` + +TanStack Start: + +```tsx +// src/routes/posts/$postId.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts/$postId')({ + component: PostPage, +}) + +function PostPage() { + const { postId } = Route.useParams() + // ... +} +``` + +Key differences: + +- Dynamic segments use `$param` not `[param]` +- Params accessed via `Route.useParams()` not component props +- Route path in filename uses `.` or `/` separators + +## Step 5: Convert Server Actions → Server Functions + +Next.js: + +```tsx +// app/actions.ts +'use server' +export async function createPost(formData: FormData) { + const title = formData.get('title') as string + await db.posts.create({ title }) +} +``` + +TanStack Start: + +```tsx +// src/utils/posts.functions.ts +import { createServerFn } from '@tanstack/react-start' + +export const createPost = createServerFn({ method: 'POST' }) + .validator((data) => { + if (!(data instanceof FormData)) throw new Error('Expected FormData') + return { title: data.get('title')?.toString() || '' } + }) + .handler(async ({ data }) => { + await db.posts.create({ title: data.title }) + return { success: true } + }) +``` + +## Step 6: Convert Data Fetching + +Next.js Server Component: + +```tsx +// app/posts/page.tsx (Server Component — server-only by default) +export default async function PostsPage() { + const posts = await db.posts.findMany() + return +} +``` + +TanStack Start: + +```tsx +// src/routes/posts.tsx +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' + +const getPosts = createServerFn({ method: 'GET' }).handler(async () => { + return db.posts.findMany() +}) + +export const Route = createFileRoute('/posts')({ + loader: () => getPosts(), // loader is isomorphic, getPosts runs on server + component: PostsPage, +}) + +function PostsPage() { + const posts = Route.useLoaderData() + return +} +``` + +## Step 7: Convert API Routes → Server Routes + +Next.js: + +```ts +// app/api/users/route.ts +export async function GET() { + const users = await db.users.findMany() + return Response.json(users) +} +``` + +TanStack Start: + +```ts +// src/routes/api/users.ts +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/api/users')({ + server: { + handlers: { + GET: async () => { + const users = await db.users.findMany() + return Response.json(users) + }, + }, + }, +}) +``` + +## Step 8: Convert Navigation + +Next.js: + +```tsx +import Link from 'next/link' +;View Post +``` + +TanStack Start: + +```tsx +import { Link } from '@tanstack/react-router' +; + View Post + +``` + +Never interpolate params into the `to` string. Use `params` prop. + +## Step 9: Convert Middleware + +Next.js: + +```ts +// middleware.ts +export function middleware(request: NextRequest) { + const token = request.cookies.get('session') + if (!token) return NextResponse.redirect(new URL('/login', request.url)) +} +export const config = { matcher: ['/dashboard/:path*'] } +``` + +TanStack Start: + +```tsx +// src/start.ts — must be manually created +import { createStart, createMiddleware } from '@tanstack/react-start' +import { redirect } from '@tanstack/react-router' + +const authMiddleware = createMiddleware().server(async ({ next, request }) => { + const cookie = request.headers.get('cookie') + if (!cookie?.includes('session=')) { + throw redirect({ to: '/login' }) + } + return next() +}) + +export const startInstance = createStart(() => ({ + requestMiddleware: [authMiddleware], +})) +``` + +## Step 10: Convert Metadata/SEO + +Next.js: + +```tsx +export const metadata = { + title: 'Post Title', + description: 'Post description', +} +``` + +TanStack Start: + +```tsx +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params }) => fetchPost(params.postId), + head: ({ loaderData }) => ({ + meta: [ + { title: loaderData.title }, + { name: 'description', content: loaderData.excerpt }, + { property: 'og:title', content: loaderData.title }, + ], + }), +}) +``` + +## Post-Migration Checklist + +- [ ] Remove all `"use server"` and `"use client"` directives +- [ ] Remove `next.config.js` / `next.config.ts` +- [ ] Remove `app/` directory (replaced by `src/routes/`) +- [ ] Remove `middleware.ts` (replaced by `src/start.ts`) +- [ ] Verify no `next/*` imports remain +- [ ] Run `npm run dev` and check all routes +- [ ] Verify server-only code is inside `createServerFn` (not bare in components/loaders) +- [ ] Check that `` is in the root route `` + +## Common Mistakes + +### 1. CRITICAL: Keeping Server Component mental model + +```tsx +// WRONG — treating component as server-only (Next.js habit) +function PostsPage() { + const posts = await db.posts.findMany() // fails on client + return
    {posts.map(...)}
    +} + +// CORRECT — use server function + loader +const getPosts = createServerFn({ method: 'GET' }).handler(async () => { + return db.posts.findMany() +}) + +export const Route = createFileRoute('/posts')({ + loader: () => getPosts(), + component: PostsPage, +}) +``` + +### 2. CRITICAL: Using "use server" directive + +```tsx +// WRONG — "use server" is Next.js/React pattern +'use server' +export async function myAction() { ... } + +// CORRECT — use createServerFn +export const myAction = createServerFn({ method: 'POST' }) + .handler(async () => { ... }) +``` + +### 3. HIGH: Interpolating params into Link href + +```tsx +// WRONG — Next.js pattern +View + +// CORRECT — TanStack Router pattern +View +``` + +## Cross-References + +- [react-start](../../react-start/SKILL.md) — full React Start setup +- `@tanstack/start-client-core#start-core/server-functions` — server function patterns +- `@tanstack/start-client-core#start-core/execution-model` — isomorphic execution diff --git a/packages/react-start/skills/react-start/SKILL.md b/packages/react-start/skills/react-start/SKILL.md new file mode 100644 index 0000000000..988373f107 --- /dev/null +++ b/packages/react-start/skills/react-start/SKILL.md @@ -0,0 +1,296 @@ +--- +name: react-start +description: >- + React bindings for TanStack Start: createStart, StartClient, + StartServer, React-specific imports, re-exports from + @tanstack/react-router, full project setup with React, useServerFn + hook. +metadata: + type: framework + library: tanstack-start + library_version: '1.168.32' + framework: react +requires: + - start-core +sources: + - TanStack/router:packages/react-start/src + - TanStack/router:docs/start/framework/react/build-from-scratch.md +--- + +# React Start (`@tanstack/react-start`) + +This is the React Start entry skill. Use the workflow below, then load only the package skill that owns the boundary you are changing. Do not read `start-core`, Router Core, and React Router manuals in full before starting. + +For React Server Components patterns, see [react-start/server-components](./server-components/SKILL.md). + +> **CRITICAL**: All code is ISOMORPHIC by default. Loaders run on BOTH server and client. Use `createServerFn` for server-only logic. + +> **CRITICAL**: Do not confuse `@tanstack/react-start` with Next.js or Remix. They are completely different frameworks with different APIs. + +> **CRITICAL**: Types are FULLY INFERRED. Never cast, never annotate inferred values. + +## Full-Stack Workflow + +1. Define the route and component with `createFileRoute`. +2. Put private or server-only reads and writes in `createServerFn`; call reads directly from loaders. +3. Use `useServerFn` for component mutations, then invalidate the router or query cache after the write resolves. +4. Enforce auth in every private server function or server route. Add `beforeLoad` separately for navigation UX. +5. Run the initial SSR path, client navigation, mutation plus reload, direct anonymous endpoint request, runtime response assertion, type tests, and production build. + +Load `start-core/server-routes` instead of `server-functions` only when a raw HTTP endpoint is required. Load `router-core/*` only for the specific routing concern involved, such as params or search validation. + +## Package API Surface + +`@tanstack/react-start` re-exports everything from `@tanstack/start-client-core` plus: + +- `useServerFn` — React hook for calling server functions from components + +All core APIs (`createServerFn`, `createMiddleware`, `createStart`, `createIsomorphicFn`, `createServerOnlyFn`, `createClientOnlyFn`) are available from `@tanstack/react-start`. + +Server utilities (`getRequest`, `getRequestHeader`, `setResponseHeader`, `setResponseHeaders`, `setResponseStatus`) are imported from `@tanstack/react-start/server`. + +## Full Project Setup + +### 1. Install Dependencies + +```bash +npm i @tanstack/react-start @tanstack/react-router react react-dom +npm i -D vite @vitejs/plugin-react typescript @types/react @types/react-dom +``` + +### 2. package.json + +```json +{ + "type": "module", + "scripts": { + "dev": "vite dev", + "build": "vite build", + "start": "node .output/server/index.mjs" + } +} +``` + +### 3. tsconfig.json + +```json +{ + "compilerOptions": { + "jsx": "react-jsx", + "moduleResolution": "Bundler", + "module": "ESNext", + "target": "ES2022", + "skipLibCheck": true, + "strictNullChecks": true + } +} +``` + +### 4. vite.config.ts + +```ts +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [ + tanstackStart(), // MUST come before react() + viteReact(), + ], +}) +``` + +### 5. Router Factory (src/router.tsx) + +```tsx +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + const router = createRouter({ + routeTree, + scrollRestoration: true, + }) + return router +} +``` + +### 6. Root Route (src/routes/\_\_root.tsx) + +```tsx +import type { ReactNode } from 'react' +import { + Outlet, + createRootRoute, + HeadContent, + Scripts, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'My TanStack Start App' }, + ], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + ) +} + +function RootDocument({ children }: Readonly<{ children: ReactNode }>) { + return ( + + + + + + {children} + + + + ) +} +``` + +### 7. Index Route (src/routes/index.tsx) + +```tsx +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' + +const getGreeting = createServerFn({ method: 'GET' }).handler(async () => { + return 'Hello from TanStack Start!' +}) + +export const Route = createFileRoute('/')({ + loader: () => getGreeting(), + component: HomePage, +}) + +function HomePage() { + const greeting = Route.useLoaderData() + return

    {greeting}

    +} +``` + +## useServerFn Hook + +Use `useServerFn` to call server functions from React components with proper integration: + +```tsx +import { createServerFn, useServerFn } from '@tanstack/react-start' + +const updatePost = createServerFn({ method: 'POST' }) + .validator((data: { id: string; title: string }) => data) + .handler(async ({ data }) => { + await db.posts.update(data.id, { title: data.title }) + return { success: true } + }) + +function EditPostForm({ postId }: { postId: string }) { + const updatePostFn = useServerFn(updatePost) + const [title, setTitle] = useState('') + + return ( +
    { + e.preventDefault() + await updatePostFn({ data: { id: postId, title } }) + }} + > + setTitle(e.target.value)} /> + +
    + ) +} +``` + +## Global Start Configuration (src/start.ts) + +```tsx +import { createStart, createMiddleware } from '@tanstack/react-start' + +const requestLogger = createMiddleware().server(async ({ next, request }) => { + console.log(`${request.method} ${request.url}`) + return next() +}) + +export const startInstance = createStart(() => ({ + requestMiddleware: [requestLogger], +})) +``` + +## React-Specific Components + +All routing components from `@tanstack/react-router` work in Start: + +- `` — not needed in Start (handled automatically) +- `` — renders matched child route +- `` — type-safe navigation +- `` — declarative redirect +- `` — renders head tags (must be in ``) +- `` — renders body scripts (must be in ``) +- `` — renders deferred data with Suspense +- `` — renders children only after hydration +- `` — error boundary + +## Hooks Reference + +All hooks from `@tanstack/react-router` work in Start: + +- `useRouter()` — router instance +- `useRouterState()` — subscribe to router state +- `useNavigate()` — programmatic navigation +- `useSearch({ from })` — validated search params +- `useParams({ from })` — path params +- `useLoaderData({ from })` — loader data +- `useMatch({ from })` — full route match +- `useRouteContext({ from })` — route context +- `Route.useLoaderData()` — typed loader data (preferred in route files) +- `Route.useSearch()` — typed search params (preferred in route files) + +## Common Mistakes + +### 1. CRITICAL: Importing from wrong package + +```tsx +// WRONG — this is the SPA router, NOT Start +import { createServerFn } from '@tanstack/react-router' + +// CORRECT — server functions come from react-start +import { createServerFn } from '@tanstack/react-start' + +// CORRECT — routing APIs come from react-router (re-exported by Start too) +import { createFileRoute, Link } from '@tanstack/react-router' +``` + +### 2. HIGH: Using React hooks in beforeLoad or loader + +```tsx +// WRONG — beforeLoad/loader are NOT React components +beforeLoad: () => { + const auth = useAuth() // React hook, cannot be used here +} + +// CORRECT — pass state via router context +const rootRoute = createRootRouteWithContext<{ auth: AuthState }>()({}) +``` + +### 3. HIGH: Missing Scripts component + +Without `` in the root route's ``, client JavaScript doesn't load and the app won't hydrate. + +## Cross-References + +- `@tanstack/start-client-core#start-core` — core Start concepts +- `@tanstack/router-core#router-core` — routing fundamentals +- `@tanstack/react-router#react-router` — React Router hooks and components diff --git a/packages/react-start/skills/react-start/server-components/SKILL.md b/packages/react-start/skills/react-start/server-components/SKILL.md new file mode 100644 index 0000000000..81561824a0 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/SKILL.md @@ -0,0 +1,128 @@ +--- +name: server-components +description: >- + Implement, review, debug, and refactor TanStack Start React Server + Components in React 19 apps. Use when tasks mention + @tanstack/react-start/rsc, renderServerComponent, + createCompositeComponent, CompositeComponent, + renderToReadableStream, createFromReadableStream, createFromFetch, + Composite Components, React Flight streams, loader or query owned + RSC caching, router.invalidate, structuralSharing: false, + selective SSR, stale names like renderRsc or .validator, or + migration from Next App Router RSC patterns. Do not use for + generic SSR or non-TanStack RSC frameworks except brief + comparison. +metadata: + type: sub-skill + library: tanstack-start + library_version: '1.168.32' +requires: + - react-start + - start-core/server-functions + - start-core/execution-model +sources: + - TanStack/router:docs/start/framework/react/guide/server-components.md + - TanStack/router:docs/start/framework/react/guide/server-functions.md + - TanStack/router:docs/start/framework/react/guide/execution-model.md + - TanStack/router:docs/router/guide/data-loading.md +--- + +# TanStack Start React Server Components + +Treat TanStack Start RSCs as fetchable React Flight payloads, not as a framework-owned server tree. Start from data ownership and cache ownership, then choose the smallest RSC primitive that fits. + +## When this skill is active + +1. Inspect `vite.config.*` for `tanstackStart({ rsc: { enabled: true } })`, `rsc()`, and `viteReact()`. +2. Inspect route files for `loader`, `loaderDeps`, `staleTime`, `ssr`, and `errorComponent`. +3. Inspect server boundaries: `createServerFn`, `createServerOnlyFn`, `.server.*`, and imports from `@tanstack/react-start/server`. +4. Identify the cache owner: Router loader cache, TanStack Query, or HTTP/server cache. +5. Identify the refresh path: `router.invalidate()`, `invalidateQueries`, `refetchQueries`, or GET cache headers. + +## Hard invariants + +- Route loaders are isomorphic. Do not put DB access, secrets, or Node-only APIs directly in a loader. If the loader itself must use browser APIs, make that route `ssr: false`. +- `renderServerComponent(...)` returns a renderable fragment. It does not support slots. +- `createCompositeComponent(...)` is for server-rendered UI that must accept client-provided `children`, render props, or component props. +- Query-cached RSC values require `structuralSharing: false`. +- Slot payloads are opaque on the server. Do not inspect, map, or clone `props.children`. +- Render-prop and component-slot arguments must stay Flight-serializable. +- Current server function validation API is `.validator(...)`. Older snippets may still show `.validator(...)`; normalize them. +- TanStack custom serialization does not apply inside RSCs yet. Stay inside native Flight-supported values. + +## Decide three things immediately + +### 1) Transport / composition primitive + +- No client slots needed -> `renderServerComponent` +- Client interactivity must be inserted inside server-rendered markup -> `createCompositeComponent` + `` +- Need custom Flight streaming, API routes, or non-standard transport -> `renderToReadableStream`, `createFromReadableStream`, `createFromFetch` + +### 2) Cache owner + +- Route-shaped data keyed by pathname, params, or search -> Router cache +- Independent key space, background refetch, or non-route ownership -> TanStack Query +- Cross-request reuse on server or CDN -> GET `createServerFn` + response cache headers and/or external server cache + +### 3) Refresh owner + +- Router-owned RSC -> `router.invalidate()` +- Query-owned RSC -> `queryClient.invalidateQueries(...)` or `refetchQueries(...)` +- Mixed Router + Query -> invalidate both deliberately; do not assume one refreshes the other + +## Pattern chooser + +- Simple server fragment in a route loader -> `renderServerComponent` +- Interactive slot inside server markup -> `createCompositeComponent` +- Route component needs browser APIs but loader can still query on the server -> `ssr: 'data-only'` +- Loader itself needs browser APIs -> `ssr: false` +- Route cache key must include search params -> `loaderDeps` +- Query-managed RSC -> `useSuspenseQuery` + SSR `query` with `staleTime: 'static'` +- Multiple independent RSCs -> separate server functions + `Promise.all` +- Multiple RSCs sharing data or invalidating together -> one server function returning many renderables or sources +- Need isolated widget failures or staggered reveal -> return promises from the loader and resolve with `use()` inside Suspense + +## Slot choice + +- `children`: free-form composition, no server-to-client data flow +- render props: the server must pass serializable data into client-rendered UI +- component props: reusable client slot with a stable typed prop surface +- If you are about to use `Children.map`, `cloneElement`, or inspect `children` on the server, stop and convert it to a render prop + +## Review / refactor checklist + +- Is the chosen primitive the smallest one that fits? +- Does the loader own the RSC, or should Query own it? +- Are route cache keys complete (`params` + minimal `loaderDeps`)? +- Is invalidation hitting the real cache owner? +- Are query options using `structuralSharing: false` for any RSC value? +- Are mutations explicit `createServerFn({ method: 'POST' })` calls instead of hidden server actions? +- Are server-only imports kept inside server functions or server-only boundaries? +- Are examples using current names (`renderServerComponent`, `.validator`) instead of stale ones? + +## Debug fast + +- Setup, exports, or stale docs mismatch -> `docs/current-api-notes.md` +- Composite Component design or slot bug -> `docs/composite-components.md` +- Stale data, refetching, loader keys, Query vs Router ownership, or SSR mode -> `docs/caching-refresh-ssr.md` +- Review, refactor, import leaks, error boundaries, or serialization bugs -> `docs/debugging-review.md` +- Architecture and Next/App Router translation -> `docs/architecture.md` + +## Copy-paste patterns + +- `examples/01-renderable-route-loader.tsx` +- `examples/02-composite-slots.tsx` +- `examples/03-query-owned-rsc.tsx` +- `examples/04-selective-ssr-data-only.tsx` +- `examples/05-ssr-false-browser-loader.tsx` +- `examples/06-low-level-flight-api-route.tsx` + +## Default implementation sequence + +1. Keep server-only work inside `createServerFn` or `createServerOnlyFn` +2. Return an RSC from the server function +3. Consume it through the route loader unless Query has a clear ownership advantage +4. Add the smallest cache policy that satisfies freshness requirements +5. Wire invalidation exactly once at the real cache owner +6. Escalate to Composite Components only when the client must fill slots +7. Escalate to low-level Flight APIs only when high-level helpers cannot express the transport diff --git a/packages/react-start/skills/react-start/server-components/docs/architecture.md b/packages/react-start/skills/react-start/server-components/docs/architecture.md new file mode 100644 index 0000000000..f416b832ad --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/docs/architecture.md @@ -0,0 +1,84 @@ +# Architecture and mental model + +## Core model + +TanStack Start treats React Server Components as plain React Flight data: + +- create them on the server +- return them from a server function or API route +- decode and render them during SSR or on the client +- cache them with whatever already owns the data flow + +That matters because the framework is not asking you to move the whole UI tree to the server. RSCs are opt-in fragments that fit into existing Router and Query workflows. + +## Boundary model + +The fastest way to get TanStack Start RSC wrong is to think “loader = server”. + +Use these boundaries instead: + +- `createServerFn`: explicit RPC boundary; safe to call from client code because the client gets an RPC stub +- `createServerOnlyFn`: utility that must never run on the client +- route `loader`: orchestration layer that runs on the server for the initial SSR request and in the browser on client navigation unless the route is `ssr: false` + +Practical rule: loaders decide _when_ to fetch. Server functions decide _what_ must stay on the server. + +## What still works inside RSCs + +Do not over-correct and assume RSCs are a stripped-down universe. + +- TanStack Router `Link` works inside server components +- CSS Modules and global CSS imports work inside server components +- `React.cache` works for request-scoped memoization inside server components + +Use those directly when they simplify the tree. + +## When RSCs actually pay off + +Use TanStack Start RSCs when one or more of these are true: + +- a region is heavy to render but mostly static once delivered +- a server-only dependency should never enter the client bundle +- data fetching and render logic want to live together +- you want progressively streamed HTML for part of the route +- the result can be cached better as a fragment than as an entire page + +Do not force RSCs into highly interactive, state-dense client surfaces unless they materially reduce bundle size or remove awkward client/server sync. + +## Choosing tree ownership + +Think in terms of ownership: + +- client-owned UI: plain client components, Query, SPA patterns +- route-owned RSC: route loader fetches a fragment and Router cache owns freshness +- query-owned RSC: Query owns the fragment because its lifecycle is not route-shaped +- mixed ownership: the route owns coarse navigation state, Query owns sub-fragments + +The wrong smell is accidental double ownership: one RSC is fetched in a loader, then also separately cached in Query, then only one side is invalidated. + +## Composite Components in one sentence + +A Composite Component is a server-rendered fragment with placeholders the client fills later. + +That makes it the replacement for “I need server-rendered markup here, but I still need client interactivity in the middle of it.” + +The client can wrap, nest, reorder, and interleave those fragments instead of accepting a single framework-owned server tree. + +## Next App Router translation + +Use this mapping when someone is thinking in Next terms: + +- Next “server-first tree” -> Start “isomorphic-first app with opt-in RSC fragments” +- Next `'use client'` boundary -> Start Composite Component slot boundary +- Next server actions -> Start explicit `createServerFn({ method: 'POST' })` +- Next framework cache semantics -> Start Router cache, Query cache, and HTTP cache you control directly + +The useful mental shift is this: in TanStack Start, RSC is a transport and composition primitive, not the center of gravity for the whole app. + +## High-value heuristics + +- If the fragment never accepts client content, demote it to `renderServerComponent`. +- If a route-scoped RSC never needs independent refetching, keep it in the loader cache. +- If a fragment is reused across routes or refreshed independently, consider Query ownership. +- If several fragments always share data and invalidate together, bundle them in one server function. +- If one slow fragment blocks everything, stop awaiting it in the loader and defer it. diff --git a/packages/react-start/skills/react-start/server-components/docs/caching-refresh-ssr.md b/packages/react-start/skills/react-start/server-components/docs/caching-refresh-ssr.md new file mode 100644 index 0000000000..f48ba02d5b --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/docs/caching-refresh-ssr.md @@ -0,0 +1,140 @@ +# Caching, refresh, SSR modes, and loading patterns + +## Pick one cache owner first + +### Router cache + +Use Router when the RSC is route-shaped and keyed by URL state. + +Relevant facts: + +- Router loader cache keys are based on pathname and params, plus anything you add through `loaderDeps` +- default navigation `staleTime` is `0` +- default preload freshness is `30s` +- default stale reload mode is background stale-while-revalidate +- `router.invalidate()` reloads active loaders immediately and marks cached routes stale + +Use Router ownership when the fragment naturally belongs to the route and should track navigation. + +### TanStack Query + +Use Query when the fragment has its own lifecycle. + +Typical reasons: + +- reuse across routes +- background refetching independent of navigation +- manual query invalidation +- non-route ownership + +Hard rule: + +```tsx +structuralSharing: false +``` + +Without that, Query may try to merge RSC values across fetches. + +### HTTP / server cache + +Use GET server functions and response headers when you want cross-request reuse: + +- CDN caching +- edge caching +- reverse proxies +- shared server caches + +Set headers in a GET `createServerFn` via `setResponseHeaders(...)`. + +## Router-owned RSC pattern + +Use a server function to return the RSC, then fetch it in the route loader. + +Tune Router with: + +- `staleTime` when revisits should stay fresh for a window +- `loaderDeps` when search params affect the fragment +- `staleReloadMode: 'blocking'` when showing stale data during reload is unacceptable + +`loaderDeps` rule: include only values the loader actually uses. Returning the whole search object causes noisy invalidation. + +## Query-owned RSC pattern + +Use Query when you want explicit cache keys and background fetch behavior. + +Recommended shape: + +```tsx +const postQueryOptions = (postId: string) => ({ + queryKey: ['post-rsc', postId], + structuralSharing: false, + queryFn: () => getPostRsc({ data: { postId } }), + staleTime: 5 * 60 * 1000, +}) +``` + +For SSR reuse, run a static query in the route loader so cached data is reused without a stale refetch: + +```tsx +await context.queryClient.query({ + ...postQueryOptions(params.postId), + staleTime: 'static', +}) +``` + +Then read it with `useSuspenseQuery` in the component. + +## Refresh rules + +- loader-owned fragment changed -> `router.invalidate()` +- query-owned fragment changed -> `queryClient.invalidateQueries(...)` +- shared route and query state -> refresh both if both are authoritative +- CDN or response-header cache involved -> make sure the mutation path also busts or bypasses server-side cache + +Do not “spray” invalidation everywhere. Decide who owns freshness, then target that owner. + +## Selective SSR modes + +### `ssr: 'data-only'` + +Use when: + +- the route component needs browser APIs +- the loader can still fetch the RSC on the server for first paint +- you want server-fetched fragment data ready before the client component mounts + +This is often the right shape for responsive charts, viewport-dependent layout wrappers, or widgets that need `window` but still benefit from server-rendered content. + +### `ssr: false` + +Use when the loader itself depends on browser APIs such as: + +- `localStorage` +- `window` +- browser-only client state + +In this mode, both the loader and component run in the browser. The loader can still call a server function that returns an RSC. + +## Loading patterns + +### Independent fragments -> parallel + +If the fragments do not share data, fetch them with separate server functions and `Promise.all`. + +### Shared data or shared invalidation -> bundle + +If several fragments always share a fetch or invalidate together, return them from one server function. This reduces round trips and keeps ownership aligned. + +### One slow fragment should not block everything -> defer + +Return promises from the loader instead of awaiting them. Resolve them with `use()` inside Suspense. This also lets you isolate failures with a local ErrorBoundary instead of the route error boundary. + +### Large or unbounded lists -> async generators + +Use async generators when items should arrive incrementally and total size or per-item latency is unpredictable. + +## Request-scoped memoization + +`React.cache` works inside server components. Use it when several async server components in one request need the same expensive fetch or computation. + +That is request-scoped deduplication, not a cross-request cache. diff --git a/packages/react-start/skills/react-start/server-components/docs/composite-components.md b/packages/react-start/skills/react-start/server-components/docs/composite-components.md new file mode 100644 index 0000000000..738e07c632 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/docs/composite-components.md @@ -0,0 +1,115 @@ +# Composite Components and slot composition + +## The real mechanism + +Inside `createCompositeComponent`, slot props are placeholders, not real client elements. + +Server-side behavior: + +- reading `props.children` records “there will be children here” +- calling `props.renderSomething(args)` records “call this slot with these args later” +- reading a component prop like `props.AddToCart` records “render this client component here with these props later” + +Client-side behavior: + +- `` replaces those placeholders with the real props you passed at render time + +This is why slots are powerful and why some React habits stop working. + +## Choose the slot type by data flow + +### `children` + +Use when: + +- the server only needs a hole for client content +- no server data needs to flow into the slotted content +- free-form composition matters more than a rigid interface + +Do not use when the server must inject IDs, permissions, pricing, or derived data into the child content. + +### render props + +Use when: + +- the server must pass data into the client-rendered content +- the data is serializable +- you want the call site to stay flexible + +This is usually the best default when the server owns the data and the client owns the interactive control. + +### component props + +Use when: + +- you have a reusable client component +- the prop contract is stable +- you want the server to decide where it renders and which typed props it receives + +This is a good fit for buttons, menus, controls, widgets, and repeated productized patterns. + +## Rules that matter + +- `renderServerComponent` does not support slots +- do not use `React.Children.map`, `cloneElement`, or child inspection on the server +- render-prop arguments and component-slot props must be Flight-serializable +- keep slot contracts narrow; pass IDs and plain data, not giant objects by default + +## The most common anti-pattern + +Bad instinct: + +```tsx +createCompositeComponent((props: { children?: React.ReactNode }) => ( +
    + {React.Children.map(props.children, (child) => + React.cloneElement(child, { extra: 'prop' }), + )} +
    +)) +``` + +Correct rewrite: + +```tsx +createCompositeComponent<{ + renderItem?: (data: { extra: string }) => React.ReactNode +}>((props) =>
    {props.renderItem?.({ extra: 'prop' })}
    ) +``` + +Server-side slot content is opaque. If the server needs to add data, make the data explicit. + +## Good slot contracts + +Prefer contracts like: + +- `renderActions?: ({ postId, authorId }) => ReactNode` +- `AddToCart?: ComponentType<{ productId: string; price: number }>` +- `children?: ReactNode` + +Avoid contracts like: + +- `renderAnything?: (data: EntirePostRecordFromDB) => ReactNode` +- `children` plus child inspection and mutation +- opaque callbacks that expect non-serializable classes or functions from the server + +## Composition patterns that age well + +### Shell + actions + +The server renders an article, card, or panel and exposes one `renderActions` slot for buttons, menus, or controls. + +### Shell + body children + +The server renders stable framing UI and accepts `children` for optional interactive regions like comments, drawers, or editors. + +### Stable control slot + +The server accepts a component prop such as `AddToCart`, `UserMenu`, or `RowActions` and supplies clean typed props to it. + +## Refactor heuristics + +- No slot use anywhere -> replace the Composite Component with `renderServerComponent` +- Slot exists only to pass data -> prefer a render prop over `children` +- Repeated render-prop call sites with the same component -> promote to a component prop +- Giant slot arg object -> shrink it to the smallest serializable payload that the client really needs diff --git a/packages/react-start/skills/react-start/server-components/docs/current-api-notes.md b/packages/react-start/skills/react-start/server-components/docs/current-api-notes.md new file mode 100644 index 0000000000..ded96096da --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/docs/current-api-notes.md @@ -0,0 +1,74 @@ +# Current API notes and stale example corrections + +Validated against official TanStack Start, TanStack Router, TanStack blog, and Vite docs on 2026-04-13. + +## Current setup shape + +Use the current RSC setup: + +- React 19+ +- Vite 7+ +- `@vitejs/plugin-rsc` +- `tanstackStart({ rsc: { enabled: true } })` +- `rsc()` +- `viteReact()` + +## Current high-level APIs + +Prefer: + +- `renderServerComponent` +- `createCompositeComponent` +- `CompositeComponent` + +Use low-level APIs only for custom transport: + +- `renderToReadableStream` +- `createFromReadableStream` +- `createFromFetch` + +## Current validation API + +Use `.validator(...)` on `createServerFn`. + +Important because some current RSC docs snippets still show the older `.validator(...)` spelling. Normalize those examples before copying them into real code. + +## Current constraints + +- RSC support is still experimental +- TanStack custom serialization is not available inside RSCs yet +- slot args must stay Flight-serializable +- `structuralSharing: false` is mandatory for Query-cached RSC values + +## Stale example traps to avoid + +### Old `renderRsc` examples + +You may still find older official repo examples using `renderRsc` and older config shapes. Do not cargo-cult them into new code. Normalize to the current docs and current `@tanstack/react-start/rsc` APIs. + +### Old validation snippets + +If you see `.validator(z.object(...))` in an RSC example, rewrite it to `.validator(z.object(...))` to match the current server function API. + +### Old Vite config shapes + +If an example enables Start but does not also install and register `@vitejs/plugin-rsc`, treat it as stale for current TanStack Start RSC setup. + +## Maintenance rule + +When docs, examples, and repo snippets disagree: + +1. prefer the current TanStack Start docs +2. prefer the current TanStack blog announcement over older repo samples +3. cross-check with current Server Functions and Execution Model docs +4. then normalize all local examples to one coherent modern API surface + +## Official source list + +- TanStack Start Server Components docs +- TanStack Start Server Functions docs +- TanStack Start Execution Model docs +- TanStack Start Import Protection docs +- TanStack Router Data Loading docs +- TanStack blog: React Server Components Your Way +- Vite docs for `@vitejs/plugin-rsc` diff --git a/packages/react-start/skills/react-start/server-components/docs/debugging-review.md b/packages/react-start/skills/react-start/server-components/docs/debugging-review.md new file mode 100644 index 0000000000..f6435747c1 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/docs/debugging-review.md @@ -0,0 +1,141 @@ +# Debugging and review guide + +## Triage by failure stage + +### 1. Setup / build failure + +Likely causes: + +- `@vitejs/plugin-rsc` missing +- RSC not enabled in `tanstackStart({ rsc: { enabled: true } })` +- stale example using old exports +- wrong React or Vite baseline + +Checks: + +- inspect `vite.config.*` +- inspect imports from `@tanstack/react-start/rsc` +- normalize to `renderServerComponent`, `createCompositeComponent`, `CompositeComponent`, `.validator(...)` + +### 2. Wrong environment failure + +Symptoms: + +- DB or secret access explodes on client navigation +- `window` or `localStorage` explodes during SSR +- import protection complaints about server-only code + +Likely causes: + +- server-only logic placed directly in an isomorphic loader +- browser-only logic used in SSR route/component +- helper referencing `.server` imports outside a recognized server boundary + +Fixes: + +- move server-only work into `createServerFn` or `createServerOnlyFn` +- use `ssr: 'data-only'` when only the component needs browser APIs +- use `ssr: false` when the loader itself needs browser APIs +- keep server-only imports inside server-only callbacks or files + +## Composition / slot bugs + +Symptoms: + +- child content disappears or cannot be modified +- `Children.map` or `cloneElement` does nothing useful +- component prop slot receives unusable data +- Composite Component seems heavier than necessary + +Likely causes: + +- trying to inspect server-side slot placeholders +- non-serializable slot args +- using a Composite Component for a fragment that has no slots + +Fixes: + +- replace child inspection with a render prop +- narrow slot args to serializable values +- demote slotless composites to `renderServerComponent` + +## Cache / staleness bugs + +Symptoms: + +- stale UI after mutation +- route revisits do not refresh when expected +- route refreshes too often +- Query errors or weird object merging on RSC values + +Likely causes: + +- invalidating the wrong cache owner +- missing or oversized `loaderDeps` +- missing `structuralSharing: false` +- `staleTime` / `staleReloadMode` mismatch with desired UX + +Checks: + +- decide whether Router or Query owns the fragment +- inspect `loaderDeps` for only the params actually used +- verify Query key includes all real inputs +- verify `structuralSharing: false` +- use `router.invalidate()` only when the loader owns freshness + +## Error boundary surprises + +Rule: + +- awaited loader failure -> route `errorComponent` +- deferred promise failure -> local ErrorBoundary around the deferred read + +If a single failing widget should not take down the route, stop awaiting it in the loader. + +## Serialization bugs + +Symptoms: + +- odd runtime decode failures +- slot args rejected or malformed +- custom serializer assumptions fail + +Likely causes: + +- passing classes, functions, Maps/Sets with custom serialization expectations, or other non-Flight-friendly values +- relying on TanStack custom serialization inside RSCs + +Fixes: + +- reduce payloads to primitives, Dates, plain objects, arrays, and React elements where appropriate +- pass IDs, not rich server objects, unless they are plain and intentionally serialized + +## Import protection and bundling gotchas + +- static imports of server functions are safe; the client build gets RPC stubs +- dynamic imports of server functions can cause bundler issues +- dev-mode import protection warnings can be informational because there is no tree-shaking; build output is the authoritative check + +## Code review checklist + +- correct primitive: renderable vs composite vs low-level stream +- loader is orchestration, not secret storage +- `loaderDeps` only covers actual inputs +- Query-owned RSC uses `structuralSharing: false` +- invalidation targets the real cache owner +- mutations are explicit `POST` server functions +- slot contracts are narrow and serializable +- stale examples normalized to current APIs +- route-level vs component-level error handling matches the UX requirement + +## Simplify-first recovery path + +When a bug is tangled across Query, Router, Composite Components, and SSR modes: + +1. collapse to one route-owned `renderServerComponent` +2. verify the server function and loader path +3. reintroduce Query only if you need independent ownership +4. reintroduce Composite Components only if you need slots +5. reintroduce deferred loading only if you need staggered reveal or isolated failures + +This sequence removes entire classes of bugs instead of trying to patch all of them at once. diff --git a/packages/react-start/skills/react-start/server-components/docs/sources.md b/packages/react-start/skills/react-start/server-components/docs/sources.md new file mode 100644 index 0000000000..3755c01f78 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/docs/sources.md @@ -0,0 +1,39 @@ +# Official sources + +Validated on 2026-04-13. + +## TanStack Start + +- Server Components guide + https://tanstack.com/start/latest/docs/framework/react/guide/server-components + +- Server Functions guide + https://tanstack.com/start/latest/docs/framework/react/guide/server-functions + +- Execution Model guide + https://tanstack.com/start/latest/docs/framework/react/guide/execution-model + +- Import Protection guide + https://tanstack.com/start/latest/docs/framework/react/guide/import-protection + +## TanStack Router + +- Data Loading guide + https://tanstack.com/router/latest/docs/framework/react/guide/data-loading + +## TanStack blog + +- React Server Components Your Way + https://tanstack.com/blog/react-server-components + +## Vite + +- `@vitejs/plugin-rsc` documentation / discovery entry point + https://vite.dev/plugins/ + +## Notes on drift observed during validation + +- Current RSC docs and blog use `renderServerComponent`, `createCompositeComponent`, `CompositeComponent`, and low-level Flight APIs from `@tanstack/react-start/rsc`. +- Current Server Functions docs use `.validator(...)`. +- Some current RSC docs snippets still show older `.validator(...)`. +- Older official repo examples may still show `renderRsc` and older config shapes. Prefer the current docs above. diff --git a/packages/react-start/skills/react-start/server-components/examples/01-renderable-route-loader.tsx b/packages/react-start/skills/react-start/server-components/examples/01-renderable-route-loader.tsx new file mode 100644 index 0000000000..eb4a308abb --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/examples/01-renderable-route-loader.tsx @@ -0,0 +1,28 @@ +// Current TanStack Start RSC pattern. +// Replace route paths and data sources with your own app code. + +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { renderServerComponent } from '@tanstack/react-start/rsc' + +function Greeting() { + return

    Hello from TanStack Start RSC

    +} + +const getGreeting = createServerFn({ method: 'GET' }).handler(async () => { + const Renderable = await renderServerComponent() + return { Renderable } +}) + +export const Route = createFileRoute('/hello')({ + loader: async () => { + const { Renderable } = await getGreeting() + return { Greeting: Renderable } + }, + component: HelloPage, +}) + +function HelloPage() { + const { Greeting } = Route.useLoaderData() + return <>{Greeting} +} diff --git a/packages/react-start/skills/react-start/server-components/examples/02-composite-slots.tsx b/packages/react-start/skills/react-start/server-components/examples/02-composite-slots.tsx new file mode 100644 index 0000000000..0656abd40b --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/examples/02-composite-slots.tsx @@ -0,0 +1,124 @@ +// Composite Component patterns: +// - children slot for free-form composition +// - render-prop slot when the server must pass data into client UI +// - component prop slot for reusable typed interactive controls + +import type { ComponentType, ReactNode } from 'react' +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { + CompositeComponent, + createCompositeComponent, +} from '@tanstack/react-start/rsc' +import { z } from 'zod' + +// Replace with your own server-only data layer +declare const db: { + posts: { + findById(postId: string): Promise<{ + id: string + authorId: string + title: string + body: string + }> + } + products: { + findById(productId: string): Promise<{ + id: string + name: string + price: number + }> + } +} + +const getPostCard = createServerFn({ method: 'GET' }) + .validator(z.object({ postId: z.string() })) + .handler(async ({ data }) => { + const post = await db.posts.findById(data.postId) + + const src = await createCompositeComponent<{ + children?: ReactNode + renderActions?: (args: { postId: string; authorId: string }) => ReactNode + }>((props) => ( +
    +

    {post.title}

    +

    {post.body}

    + +
    + {props.renderActions?.({ + postId: post.id, + authorId: post.authorId, + })} +
    + +
    {props.children}
    +
    + )) + + return { src } + }) + +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params }) => + getPostCard({ data: { postId: params.postId } }), + component: PostPage, +}) + +function PostPage() { + const { src } = Route.useLoaderData() + + return ( + ( + + )} + > + + + ) +} + +function Comments() { + return
    Interactive comments go here
    +} + +function PostActions(props: { postId: string; authorId: string }) { + return ( + + ) +} + +// Component-prop slot variant +const getProductCard = createServerFn({ method: 'GET' }) + .validator(z.object({ productId: z.string() })) + .handler(async ({ data }) => { + const product = await db.products.findById(data.productId) + + const src = await createCompositeComponent<{ + AddToCart?: ComponentType<{ productId: string; price: number }> + }>((props) => ( +
    +

    {product.name}

    + {props.AddToCart ? ( + + ) : null} +
    + )) + + return { src } + }) + +function AddToCartButton(props: { productId: string; price: number }) { + return ( + + ) +} + +// Example usage somewhere else: +// const { src } = await getProductCard({ data: { productId: 'p-1' } }) +// diff --git a/packages/react-start/skills/react-start/server-components/examples/03-query-owned-rsc.tsx b/packages/react-start/skills/react-start/server-components/examples/03-query-owned-rsc.tsx new file mode 100644 index 0000000000..d891e2230d --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/examples/03-query-owned-rsc.tsx @@ -0,0 +1,100 @@ +// Query-owned RSC pattern. +// Assumes your router context provides a queryClient for SSR queries. + +import type { ReactNode } from 'react' +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { + CompositeComponent, + createCompositeComponent, +} from '@tanstack/react-start/rsc' +import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query' +import { z } from 'zod' + +// Replace with your own data layer +declare const db: { + posts: { + findById(postId: string): Promise<{ + id: string + title: string + body: string + }> + update( + postId: string, + patch: { title?: string; body?: string }, + ): Promise + } +} + +const getPostRsc = createServerFn({ method: 'GET' }) + .validator(z.object({ postId: z.string() })) + .handler(async ({ data }) => { + const post = await db.posts.findById(data.postId) + + const src = await createCompositeComponent<{ + renderActions?: (args: { postId: string }) => ReactNode + }>((props) => ( +
    +

    {post.title}

    +

    {post.body}

    +
    {props.renderActions?.({ postId: post.id })}
    +
    + )) + + return { src } + }) + +const updatePost = createServerFn({ method: 'POST' }) + .validator( + z.object({ + postId: z.string(), + title: z.string().optional(), + body: z.string().optional(), + }), + ) + .handler(async ({ data }) => { + await db.posts.update(data.postId, { + title: data.title, + body: data.body, + }) + }) + +const postQueryOptions = (postId: string) => ({ + queryKey: ['post-rsc', postId], + structuralSharing: false, + queryFn: () => getPostRsc({ data: { postId } }), + staleTime: 5 * 60 * 1000, +}) + +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ context, params }) => { + await context.queryClient.query({ + ...postQueryOptions(params.postId), + staleTime: 'static', + }) + }, + component: PostPage, +}) + +function PostPage() { + const { postId } = Route.useParams() + const queryClient = useQueryClient() + + const { data } = useSuspenseQuery(postQueryOptions(postId)) + + const handleRename = async () => { + await updatePost({ data: { postId, title: 'Updated title' } }) + await queryClient.invalidateQueries({ queryKey: ['post-rsc', postId] }) + } + + return ( + ( + + )} + /> + ) +} diff --git a/packages/react-start/skills/react-start/server-components/examples/04-selective-ssr-data-only.tsx b/packages/react-start/skills/react-start/server-components/examples/04-selective-ssr-data-only.tsx new file mode 100644 index 0000000000..a068c3c001 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/examples/04-selective-ssr-data-only.tsx @@ -0,0 +1,72 @@ +// Selective SSR: the loader fetches the RSC on the server, +// but the route component renders on the client because it needs browser APIs. + +import * as React from 'react' +import type { ReactNode } from 'react' +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { + CompositeComponent, + createCompositeComponent, +} from '@tanstack/react-start/rsc' + +// Replace with your own server-side data source +declare function getDashboardStats(): Promise<{ + series: Array<{ x: number; y: number }> + totalUsers: number +}> + +const getDashboard = createServerFn({ method: 'GET' }).handler(async () => { + const stats = await getDashboardStats() + + const src = await createCompositeComponent<{ + renderChart?: (args: { + series: Array<{ x: number; y: number }> + }) => ReactNode + }>((props) => ( +
    +

    Users: {stats.totalUsers}

    + {props.renderChart?.({ series: stats.series })} +
    + )) + + return { src } +}) + +export const Route = createFileRoute('/dashboard')({ + ssr: 'data-only', + loader: async () => ({ + Dashboard: await getDashboard(), + }), + component: DashboardPage, +}) + +function DashboardPage() { + const { Dashboard } = Route.useLoaderData() + const [width, setWidth] = React.useState(0) + + React.useEffect(() => { + setWidth(window.innerWidth) + }, []) + + return ( + ( + + )} + /> + ) +} + +// Replace with your real chart component +function ResponsiveChart(props: { + data: Array<{ x: number; y: number }> + width: number +}) { + return ( +
    +      {JSON.stringify({ width: props.width, points: props.data.length })}
    +    
    + ) +} diff --git a/packages/react-start/skills/react-start/server-components/examples/05-ssr-false-browser-loader.tsx b/packages/react-start/skills/react-start/server-components/examples/05-ssr-false-browser-loader.tsx new file mode 100644 index 0000000000..cfa50490b4 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/examples/05-ssr-false-browser-loader.tsx @@ -0,0 +1,40 @@ +// Browser-owned loader pattern. +// Use when the loader itself needs browser APIs such as localStorage. + +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { renderServerComponent } from '@tanstack/react-start/rsc' +import { z } from 'zod' + +const getDrawingTools = createServerFn({ method: 'POST' }) + .validator(z.object({ savedState: z.string().nullable() })) + .handler(async ({ data }) => { + const Tools = await renderServerComponent( + , + ) + + return { Tools } + }) + +export const Route = createFileRoute('/canvas')({ + ssr: false, + loader: async () => { + const savedState = localStorage.getItem('canvas-state') + return getDrawingTools({ data: { savedState } }) + }, + component: CanvasPage, +}) + +function CanvasPage() { + const { Tools } = Route.useLoaderData() + return <>{Tools} +} + +function ToolPalette(props: { savedState: string | null }) { + return ( +
    +

    Canvas tools

    +
    {props.savedState ?? 'no saved state'}
    +
    + ) +} diff --git a/packages/react-start/skills/react-start/server-components/examples/06-low-level-flight-api-route.tsx b/packages/react-start/skills/react-start/server-components/examples/06-low-level-flight-api-route.tsx new file mode 100644 index 0000000000..17415d00a8 --- /dev/null +++ b/packages/react-start/skills/react-start/server-components/examples/06-low-level-flight-api-route.tsx @@ -0,0 +1,40 @@ +// Low-level Flight stream APIs. +// Prefer high-level helpers unless you need a custom transport. + +import { createAPIFileRoute } from '@tanstack/react-start/api' +import { createServerFn } from '@tanstack/react-start' +import { + createFromFetch, + renderToReadableStream, +} from '@tanstack/react-start/rsc' +import { useSuspenseQuery } from '@tanstack/react-query' + +const getFlightStream = createServerFn({ method: 'GET' }).handler(async () => { + return renderToReadableStream(
    Server rendered content
    ) +}) + +export const APIRoute = createAPIFileRoute('/api/rsc')({ + GET: async () => { + const stream = await getFlightStream() + + return new Response(stream, { + headers: { + 'Content-Type': 'text/x-component', + }, + }) + }, +}) + +const rscQueryOptions = () => ({ + queryKey: ['api-rsc'], + structuralSharing: false, + queryFn: async () => { + const Renderable = await createFromFetch(fetch('/api/rsc')) + return { Renderable } + }, +}) + +export function ApiBackedRscWidget() { + const { data } = useSuspenseQuery(rscQueryOptions()) + return <>{data.Renderable} +} diff --git a/packages/react-start/src/client-only.ts b/packages/react-start/src/client-only.ts new file mode 100644 index 0000000000..716466a404 --- /dev/null +++ b/packages/react-start/src/client-only.ts @@ -0,0 +1,15 @@ +/** + * Side-effect-only marker import. + * + * Usage: + * import '@tanstack/react-start/client-only' + * + * When this import appears in a module, the import-protection plugin marks + * that module as client-only. Importing a client-only module from the server + * environment will trigger a violation (error or mock depending on config). + * + * At build time, the plugin intercepts this specifier in `resolveId` and + * replaces it with a virtual empty module — this source file exists only + * so that TypeScript and IDE tooling can resolve the import. + */ +export {} diff --git a/packages/react-start/src/default-entry/server.ts b/packages/react-start/src/default-entry/server.ts index 8e734a7e49..638ac3c0a6 100644 --- a/packages/react-start/src/default-entry/server.ts +++ b/packages/react-start/src/default-entry/server.ts @@ -1,6 +1,7 @@ import { createStartHandler, defaultStreamHandler, + createServerEntry as createCoreServerEntry, } from '@tanstack/react-start/server' import type { Register } from '@tanstack/react-router' import type { RequestHandler } from '@tanstack/react-start/server' @@ -10,12 +11,8 @@ const fetch = createStartHandler(defaultStreamHandler) // Providing `RequestHandler` from `@tanstack/react-start/server` is required so that the output types don't import it from `@tanstack/start-server-core` export type ServerEntry = { fetch: RequestHandler } -export function createServerEntry(entry: ServerEntry): ServerEntry { - return { - async fetch(...args) { - return await entry.fetch(...args) - }, - } -} +// Bind the shared request context and fallback error handling to React's Register. +export const createServerEntry: (entry: ServerEntry) => ServerEntry = + createCoreServerEntry export default createServerEntry({ fetch }) diff --git a/packages/react-start/src/hydration.ts b/packages/react-start/src/hydration.ts new file mode 100644 index 0000000000..e86169e71d --- /dev/null +++ b/packages/react-start/src/hydration.ts @@ -0,0 +1,18 @@ +export { + condition, + idle, + interaction, + load, + media, + never, + visible, +} from '@tanstack/react-start-client/hydration' +export type { + HydrationCondition, + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationPrefetchStrategy, + HydrationStrategy, + HydrationWhen, + VisibleHydrationOptions, +} from '@tanstack/react-start-client/hydration' diff --git a/packages/react-start/src/index.ts b/packages/react-start/src/index.ts index 8b51b6c783..6ea839a967 100644 --- a/packages/react-start/src/index.ts +++ b/packages/react-start/src/index.ts @@ -1,2 +1,34 @@ export { useServerFn } from './useServerFn' export * from '@tanstack/start-client-core' +// Explicit re-exports shadow `export *` above so these public-API names are +// registered on the namespace at link time (via Vite SSR's `defineExport` +// at fileStartIndex), surviving the cold-start SSR cycle through user +// middleware. See vitejs/vite#22491 / #22493. Trim list to genuine public +// API only; internals fall through `export *` and are safe because they +// aren't imported at top level in the cycle path. +export { + createClientOnlyFn, + createCsrfMiddleware, + createIsomorphicFn, + createMiddleware, + createServerFn, + createServerOnlyFn, + createStart, +} from '@tanstack/start-client-core' + +// Keep root `@tanstack/react-start` imports from evaluating the client barrel. +// The barrel also exports `hydrateStart`, which imports the virtual client +// entry. That virtual entry imports the user's router module, so route modules +// that import the root package can be pulled back into the same graph and +// create circular HMR updates. Re-exporting from the Hydrate-only subpath +// preserves the public API without introducing that import edge. +export { Hydrate } from '@tanstack/react-start-client/Hydrate' +export type { + HydrateOptions, + HydrateProps, + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationPrefetchStrategy, + HydrationStrategy, + HydrationWhen, +} from '@tanstack/react-start-client/Hydrate' diff --git a/packages/react-start/src/plugin/rsbuild.ts b/packages/react-start/src/plugin/rsbuild.ts new file mode 100644 index 0000000000..7e0fcbb6c2 --- /dev/null +++ b/packages/react-start/src/plugin/rsbuild.ts @@ -0,0 +1,79 @@ +import { + RSBUILD_ENVIRONMENT_NAMES, + tanStackStartRsbuild, +} from '@tanstack/start-plugin-core/rsbuild' +import { createRscCssCompilerTransforms } from '@tanstack/react-start-rsc/plugin/rscCssTransform' +import { reactStartDefaultEntryPaths } from './shared' +import type { + TanStackStartRsbuildInputConfig, + TanStackStartRsbuildPluginCoreOptions, +} from '@tanstack/start-plugin-core/rsbuild' +import type { RsbuildPlugin } from '@rsbuild/core' + +export function tanstackStart( + options?: TanStackStartRsbuildInputConfig & { rsc?: { enabled?: boolean } }, +): RsbuildPlugin { + const rscEnabled = options?.rsc?.enabled ?? false + + let corePluginOpts: TanStackStartRsbuildPluginCoreOptions = { + framework: 'react', + defaultEntryPaths: reactStartDefaultEntryPaths, + providerEnvironmentName: RSBUILD_ENVIRONMENT_NAMES.server, + ssrIsProvider: true, + } + + if (rscEnabled) { + const rscConfig = configureRscRsbuild() + corePluginOpts = { + ...corePluginOpts, + providerEnvironmentName: rscConfig.providerEnvironmentName, + ssrIsProvider: false, + serializationAdapters: rscConfig.serializationAdapters, + compilerTransforms: rscConfig.compilerTransforms, + serverFnProviderModuleDirectives: + rscConfig.serverFnProviderModuleDirectives, + rsc: true, + } + } + + return tanStackStartRsbuild(corePluginOpts, options) +} + +/** + * Configure RSC options for the rsbuild adapter. + * + * Returns provider env, serialization adapters, and core RSC options. + * + * The SSR resolver strategy is intentionally NOT changed from 'default' — + * in the rspack layered model, SSR and RSC live in the same + * compilation so they share the same resolver file. No forwarding needed. + */ +function configureRscRsbuild(): { + providerEnvironmentName: TanStackStartRsbuildPluginCoreOptions['providerEnvironmentName'] + serializationAdapters: TanStackStartRsbuildPluginCoreOptions['serializationAdapters'] + compilerTransforms: TanStackStartRsbuildPluginCoreOptions['compilerTransforms'] + serverFnProviderModuleDirectives: TanStackStartRsbuildPluginCoreOptions['serverFnProviderModuleDirectives'] +} { + return { + providerEnvironmentName: RSBUILD_ENVIRONMENT_NAMES.server, + serializationAdapters: [ + { + client: { + module: '@tanstack/react-start/rsc/serialization/client', + export: 'rscSerializationAdapter', + isFactory: true, + }, + server: { + module: '@tanstack/react-start/rsc/serialization/server', + export: 'rscSerializationAdapter', + isFactory: true, + }, + }, + ], + compilerTransforms: createRscCssCompilerTransforms({ + loadCssExpression: 'import.meta.rspackRsc.loadCss()', + serverFnProviderOnly: true, + }), + serverFnProviderModuleDirectives: ['use server-entry'], + } +} diff --git a/packages/react-start/src/plugin/shared.ts b/packages/react-start/src/plugin/shared.ts new file mode 100644 index 0000000000..aba8a7ba65 --- /dev/null +++ b/packages/react-start/src/plugin/shared.ts @@ -0,0 +1,22 @@ +import { fileURLToPath } from 'node:url' +import path from 'pathe' + +const currentDir = path.dirname(fileURLToPath(import.meta.url)) +export const reactStartPluginDir = currentDir +const defaultEntryDir = path.resolve( + currentDir, + '..', + '..', + 'plugin', + 'default-entry', +) + +export const reactStartDefaultEntryPaths = { + client: path.resolve(defaultEntryDir, 'client.tsx'), + server: path.resolve(defaultEntryDir, 'server.ts'), + start: path.resolve(defaultEntryDir, 'start.ts'), +} + +export function resolvePackageEntryPath(packageName: string): string { + return fileURLToPath(import.meta.resolve(packageName)) +} diff --git a/packages/react-start/src/plugin/vite.ts b/packages/react-start/src/plugin/vite.ts index 3d47aad887..8849f39ea6 100644 --- a/packages/react-start/src/plugin/vite.ts +++ b/packages/react-start/src/plugin/vite.ts @@ -1,36 +1,72 @@ -import { fileURLToPath } from 'node:url' import { - TanStackStartVitePluginCore, - VITE_ENVIRONMENT_NAMES, -} from '@tanstack/start-plugin-core' + START_ENVIRONMENT_NAMES, + tanStackStartVite, +} from '@tanstack/start-plugin-core/vite' +import type { + TanStackStartViteInputConfig, + TanStackStartVitePluginCoreOptions, +} from '@tanstack/start-plugin-core/vite' +import { + configureRsc, + reactStartRscVitePlugin, +} from '@tanstack/react-start-rsc/plugin/vite' import path from 'pathe' -import type { TanStackStartInputConfig } from '@tanstack/start-plugin-core' +import { reactStartDefaultEntryPaths, reactStartPluginDir } from './shared' import type { PluginOption } from 'vite' -const currentDir = path.dirname(fileURLToPath(import.meta.url)) -const defaultEntryDir = path.resolve( - currentDir, - '..', - '..', - 'plugin', - 'default-entry', -) -const defaultEntryPaths = { - client: path.resolve(defaultEntryDir, 'client.tsx'), - server: path.resolve(defaultEntryDir, 'server.ts'), - start: path.resolve(defaultEntryDir, 'start.ts'), -} - const isInsideRouterMonoRepo = - path.basename(path.resolve(currentDir, '../../../../')) === 'packages' + path.basename(path.resolve(reactStartPluginDir, '../../../../')) === + 'packages' export function tanstackStart( - options?: TanStackStartInputConfig, + options?: TanStackStartViteInputConfig & { rsc?: { enabled?: boolean } }, ): Array { + const rscEnabled = options?.rsc?.enabled ?? false + const rscConfig = rscEnabled ? configureRsc() : undefined + let corePluginOpts: TanStackStartVitePluginCoreOptions = { + framework: 'react', + defaultEntryPaths: reactStartDefaultEntryPaths, + providerEnvironmentName: START_ENVIRONMENT_NAMES.server, + ssrIsProvider: true, + ssrResolverStrategy: { + type: 'default', + }, + } + + const serverEnvironments: Array = [ + START_ENVIRONMENT_NAMES.server, + ...(rscConfig ? [rscConfig.envName] : []), + ] + + if (rscConfig) { + corePluginOpts = { + ...corePluginOpts, + providerEnvironmentName: rscConfig.providerEnvironmentName, + ssrIsProvider: false, + ssrResolverStrategy: rscConfig.ssrResolverStrategy, + serializationAdapters: rscConfig.serializationAdapters, + compilerTransforms: rscConfig.compilerTransforms, + } + } return [ { name: 'tanstack-react-start:config', configEnvironment(environmentName, options) { + const needsOptimizeDeps = + environmentName === START_ENVIRONMENT_NAMES.client || + (serverEnvironments.includes(environmentName) && + // This indicates that the server environment has opted in to dependency optimization + options.optimizeDeps?.noDiscovery === false) + + // Check if @tanstack/react-router is in noExternal (as array) + const reactRouterInNoExternal = + Array.isArray(options.resolve?.noExternal) && + options.resolve.noExternal.some( + (pattern) => + pattern === '@tanstack/react-router' || + (typeof pattern === 'string' && pattern.includes('react-router')), + ) + return { resolve: { dedupe: [ @@ -39,52 +75,49 @@ export function tanstackStart( '@tanstack/react-start', '@tanstack/react-router', ], + // Don't mark react-router as external if: + // 1. noExternal is true (bundle everything) + // 2. We're not in the router monorepo + // 3. react-router is explicitly in noExternal for this environment external: - options.resolve?.noExternal === true || !isInsideRouterMonoRepo + options.resolve?.noExternal === true || + !isInsideRouterMonoRepo || + reactRouterInNoExternal ? undefined : ['@tanstack/react-router', '@tanstack/react-router-devtools'], }, - optimizeDeps: - environmentName === VITE_ENVIRONMENT_NAMES.client || - (environmentName === VITE_ENVIRONMENT_NAMES.server && - // This indicates that the server environment has opted in to dependency optimization - options.optimizeDeps?.noDiscovery === false) - ? { - // As `@tanstack/react-start` depends on `@tanstack/react-router`, we should exclude both. - exclude: [ - '@tanstack/react-start', - '@tanstack/react-router', - '@tanstack/react-router-devtools', - '@tanstack/start-static-server-functions', - ], - include: [ - 'react', - 'react/jsx-runtime', - 'react/jsx-dev-runtime', - 'react-dom', - ...(environmentName === VITE_ENVIRONMENT_NAMES.client - ? ['react-dom/client'] - : ['react-dom/server']), - // `@tanstack/react-store` has a dependency on `use-sync-external-store`, which is CJS. - // It therefore needs to be included so that it is converted to ESM. - '@tanstack/react-router > @tanstack/react-store', - ...(options.optimizeDeps?.exclude?.find( - (x) => x === '@tanstack/react-form', - ) - ? ['@tanstack/react-form > @tanstack/react-store'] - : []), - ], - } - : undefined, + optimizeDeps: needsOptimizeDeps + ? { + // As `@tanstack/react-start` depends on `@tanstack/react-router`, we should exclude both. + exclude: [ + '@tanstack/react-start', + '@tanstack/react-router', + '@tanstack/react-router-devtools', + '@tanstack/start-static-server-functions', + ], + include: [ + 'react', + 'react/jsx-runtime', + 'react/jsx-dev-runtime', + 'react-dom', + ...(environmentName === START_ENVIRONMENT_NAMES.client + ? ['react-dom/client'] + : ['react-dom/server']), + // `@tanstack/react-store` has a dependency on `use-sync-external-store`, which is CJS. + // It therefore needs to be included so that it is converted to ESM. + '@tanstack/react-router > @tanstack/react-store', + ...(options.optimizeDeps?.exclude?.find( + (x) => x === '@tanstack/react-form', + ) + ? ['@tanstack/react-form > @tanstack/react-store'] + : []), + ], + } + : undefined, } }, }, - TanStackStartVitePluginCore( - { - framework: 'react', - defaultEntryPaths, - }, - options, - ), + rscConfig ? reactStartRscVitePlugin() : null, + tanStackStartVite(corePluginOpts, options), ] } diff --git a/packages/react-start/src/rsbuild/browser-decode.ts b/packages/react-start/src/rsbuild/browser-decode.ts new file mode 100644 index 0000000000..5232414e97 --- /dev/null +++ b/packages/react-start/src/rsbuild/browser-decode.ts @@ -0,0 +1 @@ +export * from '@tanstack/react-start-rsc/rsbuild/browser-decode' diff --git a/packages/react-start/src/rsbuild/ssr-decode.ts b/packages/react-start/src/rsbuild/ssr-decode.ts new file mode 100644 index 0000000000..aa56c87e13 --- /dev/null +++ b/packages/react-start/src/rsbuild/ssr-decode.ts @@ -0,0 +1 @@ +export * from '@tanstack/react-start-rsc/rsbuild/ssr-decode' diff --git a/packages/react-start/src/rsc.rsc.ts b/packages/react-start/src/rsc.rsc.ts new file mode 100644 index 0000000000..b6624de42a --- /dev/null +++ b/packages/react-start/src/rsc.rsc.ts @@ -0,0 +1,2 @@ +// Re-export from react-start-rsc for react-server condition +export * from '@tanstack/react-start-rsc' diff --git a/packages/react-start/src/rsc.tsx b/packages/react-start/src/rsc.tsx new file mode 100644 index 0000000000..481210a6ab --- /dev/null +++ b/packages/react-start/src/rsc.tsx @@ -0,0 +1,3 @@ +// Re-export from react-start-rsc +// The package's export conditions handle server vs client differentiation +export * from '@tanstack/react-start-rsc' diff --git a/packages/react-start/src/rsc/serialization/client.ts b/packages/react-start/src/rsc/serialization/client.ts new file mode 100644 index 0000000000..0b7890f4eb --- /dev/null +++ b/packages/react-start/src/rsc/serialization/client.ts @@ -0,0 +1 @@ +export { rscSerializationAdapter } from '@tanstack/react-start-rsc/serialization.client' diff --git a/packages/react-start/src/rsc/serialization/server.ts b/packages/react-start/src/rsc/serialization/server.ts new file mode 100644 index 0000000000..74edf24cb8 --- /dev/null +++ b/packages/react-start/src/rsc/serialization/server.ts @@ -0,0 +1 @@ +export { rscSerializationAdapter } from '@tanstack/react-start-rsc/serialization.server' diff --git a/packages/react-start/src/server-only.ts b/packages/react-start/src/server-only.ts new file mode 100644 index 0000000000..9276941896 --- /dev/null +++ b/packages/react-start/src/server-only.ts @@ -0,0 +1,15 @@ +/** + * Side-effect-only marker import. + * + * Usage: + * import '@tanstack/react-start/server-only' + * + * When this import appears in a module, the import-protection plugin marks + * that module as server-only. Importing a server-only module from the client + * environment will trigger a violation (error or mock depending on config). + * + * At build time, the plugin intercepts this specifier in `resolveId` and + * replaces it with a virtual empty module — this source file exists only + * so that TypeScript and IDE tooling can resolve the import. + */ +export {} diff --git a/packages/react-start/src/server.rsc.ts b/packages/react-start/src/server.rsc.ts new file mode 100644 index 0000000000..d1fd428186 --- /dev/null +++ b/packages/react-start/src/server.rsc.ts @@ -0,0 +1 @@ +export * from '@tanstack/start-server-core/request-response' diff --git a/packages/react-start/src/useServerFn.ts b/packages/react-start/src/useServerFn.ts index 67a09a4358..66f3525937 100644 --- a/packages/react-start/src/useServerFn.ts +++ b/packages/react-start/src/useServerFn.ts @@ -18,7 +18,7 @@ export function useServerFn) => Promise>( return res } catch (err) { if (isRedirect(err)) { - err.options._fromLocation = router.state.location + err.options._fromLocation = router.stores.location.get() return router.navigate(router.resolveRedirect(err).options) } diff --git a/packages/react-start/tsconfig.build.json b/packages/react-start/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/react-start/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/react-start/tsconfig.json b/packages/react-start/tsconfig.json index 81f8715af3..c07753e18c 100644 --- a/packages/react-start/tsconfig.json +++ b/packages/react-start/tsconfig.json @@ -2,7 +2,8 @@ "extends": "../../tsconfig.json", "compilerOptions": { "jsx": "react-jsx", - "module": "esnext" + "module": "esnext", + "types": ["node"] }, "include": ["src", "vite.config.ts", "vite.config.server-entry.ts"] } diff --git a/packages/react-start/tsconfig.server-entry.json b/packages/react-start/tsconfig.server-entry.json new file mode 100644 index 0000000000..fca708fa0e --- /dev/null +++ b/packages/react-start/tsconfig.server-entry.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src", + "paths": { + "@tanstack/react-start/server": ["./src/server.tsx"] + } + }, + "include": ["src/default-entry"] +} diff --git a/packages/react-start/vite.config.server-entry.ts b/packages/react-start/vite.config.server-entry.ts index a89b75a497..8b64d36cc7 100644 --- a/packages/react-start/vite.config.server-entry.ts +++ b/packages/react-start/vite.config.server-entry.ts @@ -1,6 +1,7 @@ -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' export default tanstackViteConfig({ + tsconfigPath: './tsconfig.server-entry.json', srcDir: './src/default-entry', exclude: ['./src/default-entry/client.tsx'], entry: ['./src/default-entry/server.ts'], diff --git a/packages/react-start/vite.config.ts b/packages/react-start/vite.config.ts index d7ab699a07..652e4ef842 100644 --- a/packages/react-start/vite.config.ts +++ b/packages/react-start/vite.config.ts @@ -1,5 +1,5 @@ import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' import { copyFilesPlugin } from '@tanstack/router-utils' import packageJson from './package.json' @@ -21,16 +21,28 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ + tsconfigPath: './tsconfig.build.json', srcDir: './src', exclude: ['./src/default-entry'], entry: [ './src/index.ts', './src/client.tsx', + './src/hydration.ts', './src/client-rpc.ts', './src/server.tsx', + './src/server.rsc.ts', './src/server-rpc.ts', './src/ssr-rpc.ts', + './src/rsc.tsx', + './src/rsc.rsc.ts', + './src/rsc/serialization/server.ts', + './src/rsc/serialization/client.ts', + './src/rsbuild/browser-decode.ts', + './src/rsbuild/ssr-decode.ts', + './src/plugin/rsbuild.ts', './src/plugin/vite.ts', + './src/server-only.ts', + './src/client-only.ts', ], externalDeps: [ '@tanstack/react-start-client', diff --git a/packages/router-cli/CHANGELOG.md b/packages/router-cli/CHANGELOG.md new file mode 100644 index 0000000000..67101c3e51 --- /dev/null +++ b/packages/router-cli/CHANGELOG.md @@ -0,0 +1,604 @@ +# @tanstack/router-cli + +## 1.168.0 + +### Minor Changes + +- [#8855](https://github.com/TanStack/router/pull/8855) [`446ce1b`](https://github.com/TanStack/router/commit/446ce1b30650d85f1fc78f2d1ee42712e40b75c6) - Require Node `^20.19.0 || >=22.12.0` (was `>=20.19`), so the CommonJS builds can load ESM-only dependencies through `require(esm)`. Node 21 and Node 22.0–22.11 do not enable it by default, so they are no longer supported. + +### Patch Changes + +- Updated dependencies [[`446ce1b`](https://github.com/TanStack/router/commit/446ce1b30650d85f1fc78f2d1ee42712e40b75c6), [`ad5b3b7`](https://github.com/TanStack/router/commit/ad5b3b7a0990eed7351d672ea6695d341108e0d6)]: + - @tanstack/router-generator@1.168.0 + +## 1.167.46 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.46 + +## 1.167.45 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.45 + +## 1.167.44 + +### Patch Changes + +- [#8711](https://github.com/TanStack/router/pull/8711) [`a80cd74`](https://github.com/TanStack/router/commit/a80cd7410591396aa203f754c34caff2628f21fd) - Replace `yargs` with the dependency-free `cac` for parsing `tsr` arguments. `tsr generate` and `tsr watch` work as before. Running `tsr` with no command now prints help, and unknown commands, unknown options, or extra arguments now print an error and exit with code 1 instead of being ignored. + +- Updated dependencies []: + - @tanstack/router-generator@1.167.44 + +## 1.167.43 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.43 + +## 1.167.42 + +### Patch Changes + +- Updated dependencies [[`57bd1a9`](https://github.com/TanStack/router/commit/57bd1a92f9839af5bf773c3b36d039569fb1a41e)]: + - @tanstack/router-generator@1.167.42 + +## 1.167.41 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.41 + +## 1.167.40 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.40 + +## 1.167.39 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.39 + +## 1.167.38 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.38 + +## 1.167.37 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.37 + +## 1.167.36 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.36 + +## 1.167.35 + +### Patch Changes + +- Updated dependencies [[`49bcd4d`](https://github.com/TanStack/router/commit/49bcd4db743dba4a783d5533a42a0f97a5721292)]: + - @tanstack/router-generator@1.167.35 + +## 1.167.34 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.34 + +## 1.167.33 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.33 + +## 1.167.32 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.32 + +## 1.167.31 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.31 + +## 1.167.30 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.30 + +## 1.167.29 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.29 + +## 1.167.28 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.28 + +## 1.167.27 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.27 + +## 1.167.26 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.26 + +## 1.167.25 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.25 + +## 1.167.24 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.24 + +## 1.167.23 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.23 + +## 1.167.22 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.22 + +## 1.167.21 + +### Patch Changes + +- Updated dependencies [[`78dd1a6`](https://github.com/TanStack/router/commit/78dd1a645dc1a9e9f4f649d9aff12005044d4fcc)]: + - @tanstack/router-generator@1.167.21 + +## 1.167.20 + +### Patch Changes + +- Updated dependencies [[`e56a677`](https://github.com/TanStack/router/commit/e56a67742da9021b009b8db0cdc8bfe99878c25b)]: + - @tanstack/router-generator@1.167.20 + +## 1.167.19 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.19 + +## 1.167.18 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.18 + +## 1.167.17 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.17 + +## 1.167.16 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.16 + +## 1.167.15 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.15 + +## 1.167.14 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.14 + +## 1.167.13 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.13 + +## 1.167.12 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.12 + +## 1.167.11 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.11 + +## 1.167.10 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.10 + +## 1.167.9 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.9 + +## 1.167.8 + +### Patch Changes + +- Updated dependencies [[`7df0d02`](https://github.com/TanStack/router/commit/7df0d02bfb1407b1f07731ef69af24e2f0e415d7)]: + - @tanstack/router-generator@1.167.8 + +## 1.167.7 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.7 + +## 1.167.6 + +### Patch Changes + +- Update chokidar to v5. ([#7439](https://github.com/TanStack/router/pull/7439)) + +- Updated dependencies []: + - @tanstack/router-generator@1.167.6 + +## 1.167.5 + +### Patch Changes + +- Updated dependencies [[`b60eb36`](https://github.com/TanStack/router/commit/b60eb36e59e8a468ee0742cbcf7f47aca1ff1c67)]: + - @tanstack/router-generator@1.167.5 + +## 1.167.4 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.4 + +## 1.167.3 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.3 + +## 1.167.2 + +### Patch Changes + +- Updated dependencies [[`742941e`](https://github.com/TanStack/router/commit/742941e2f1bf069c950d0a4985b2cd733639509e)]: + - @tanstack/router-generator@1.167.2 + +## 1.167.1 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.167.1 + +## 1.167.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +### Patch Changes + +- Updated dependencies [[`038cd12`](https://github.com/TanStack/router/commit/038cd123b70bc6154d75abb6404a744c376f8f6a), [`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14)]: + - @tanstack/router-generator@1.167.0 + +## 1.166.43 + +### Patch Changes + +- Updated dependencies [[`c5811aa`](https://github.com/TanStack/router/commit/c5811aacb59b69a8179f14cd9529a51b2206d504)]: + - @tanstack/router-generator@1.166.42 + +## 1.166.42 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.41 + +## 1.166.41 + +### Patch Changes + +- Updated dependencies [[`056337e`](https://github.com/TanStack/router/commit/056337ef02ccbeaf45ec8533a227761be869e8f3)]: + - @tanstack/router-generator@1.166.40 + +## 1.166.40 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.39 + +## 1.166.39 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.38 + +## 1.166.38 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.37 + +## 1.166.37 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.36 + +## 1.166.36 + +### Patch Changes + +- Updated dependencies [[`a2ad394`](https://github.com/TanStack/router/commit/a2ad394598e2079ab4050ebb16bb03b31d69c32a)]: + - @tanstack/router-generator@1.166.35 + +## 1.166.35 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.34 + +## 1.166.34 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.33 + +## 1.166.33 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.32 + +## 1.166.32 + +### Patch Changes + +- Updated dependencies [[`328d7e5`](https://github.com/TanStack/router/commit/328d7e5ebc6b8074242a07d68ccafafb83e37a0e)]: + - @tanstack/router-generator@1.166.31 + +## 1.166.31 + +### Patch Changes + +- Updated dependencies [[`105d056`](https://github.com/TanStack/router/commit/105d05691a247779a63e7b688aa1207cce619339)]: + - @tanstack/router-generator@1.166.30 + +## 1.166.30 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.29 + +## 1.166.29 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.28 + +## 1.166.28 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.27 + +## 1.166.27 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.26 + +## 1.166.26 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.25 + +## 1.166.25 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.24 + +## 1.166.24 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.23 + +## 1.166.23 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.22 + +## 1.166.22 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.21 + +## 1.166.21 + +### Patch Changes + +- Updated dependencies [[`70b2225`](https://github.com/TanStack/router/commit/70b222513720d99c6d44bd3f28d1e9b19dc91a43)]: + - @tanstack/router-generator@1.166.20 + +## 1.166.20 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.19 + +## 1.166.19 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.18 + +## 1.166.18 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.17 + +## 1.166.17 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.16 + +## 1.166.16 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.15 + +## 1.166.15 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.14 + +## 1.166.14 + +### Patch Changes + +- fix(router-cli): pass process.argv to yargs to fix silent CLI failure ([#6981](https://github.com/TanStack/router/pull/6981)) + +## 1.166.13 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.13 + +## 1.166.12 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.12 + +## 1.166.11 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.11 + +## 1.166.10 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +- Updated dependencies [[`838b0eb`](https://github.com/TanStack/router/commit/838b0eb9a8bbbb987a0a6972c1446e01423bbd7b)]: + - @tanstack/router-generator@1.166.10 + +## 1.166.9 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) + +- Updated dependencies [[`ef9b241`](https://github.com/TanStack/router/commit/ef9b241f3cfe95cee40daa96da669f0ffd4a971a)]: + - @tanstack/router-generator@1.166.9 + +## 1.166.8 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/router-generator@1.166.8 diff --git a/packages/router-cli/package.json b/packages/router-cli/package.json index ee6e66d6c6..51a729d79b 100644 --- a/packages/router-cli/package.json +++ b/packages/router-cli/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-cli", - "version": "1.142.0", + "version": "1.168.0", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -27,12 +27,12 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -63,14 +63,20 @@ "bin/**" ], "engines": { - "node": ">=12" + "node": "^20.19.0 || >=22.12.0" }, "dependencies": { "@tanstack/router-generator": "workspace:*", - "chokidar": "^3.6.0", - "yargs": "^17.7.2" + "cac": "^7.1.0", + "chokidar": "catalog:" }, "devDependencies": { - "@types/yargs": "^17.0.33" + "@types/node": ">=20", + "vite": "catalog:", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" } } diff --git a/packages/router-cli/src/index.ts b/packages/router-cli/src/index.ts index e8ca50e93a..7610fde457 100644 --- a/packages/router-cli/src/index.ts +++ b/packages/router-cli/src/index.ts @@ -1,25 +1,51 @@ -import * as yargs from 'yargs' +import { cac } from 'cac' import { getConfig } from '@tanstack/router-generator' import { generate } from './generate' import { watch } from './watch' +declare const __TSR_VERSION__: string + main() export function main() { - yargs - // @ts-expect-error - .scriptName('tsr') - .usage('$0 [args]') - .command('generate', 'Generate the routes for a project', async () => { + const cli = cac('tsr') + + cli + .command('generate', 'Generate the routes for a project') + .action(async () => { const config = getConfig() await generate(config, process.cwd()) }) + + cli .command( 'watch', 'Continuously watch and generate the routes for a project', - () => { - watch(process.cwd()) - }, ) - .help().argv + .action(() => { + watch(process.cwd()) + }) + + cli.help() + cli.version(__TSR_VERSION__) + + try { + cli.parse() + } catch (err) { + // cac throws `CACError` for invalid usage (unknown option, extra args) + if (err instanceof Error && err.name === 'CACError') { + console.error(err.message) + process.exit(1) + } + throw err + } + + if (!cli.matchedCommand && !cli.options.help && !cli.options.version) { + // `tsr` and `tsr help` print help; unknown commands also exit with 1 + if (cli.args.length && cli.args[0] !== 'help') { + console.error(`Unknown command: ${cli.args.join(' ')}\n`) + process.exitCode = 1 + } + cli.outputHelp() + } } diff --git a/packages/router-cli/tsconfig.build.json b/packages/router-cli/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/router-cli/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/router-cli/tsconfig.json b/packages/router-cli/tsconfig.json index b36d1bf924..09d7037393 100644 --- a/packages/router-cli/tsconfig.json +++ b/packages/router-cli/tsconfig.json @@ -1,4 +1,7 @@ { "extends": "../../tsconfig.json", - "include": ["src", "vite.config.ts"] + "include": ["src", "vite.config.ts"], + "compilerOptions": { + "types": ["node"] + } } diff --git a/packages/router-cli/vite.config.ts b/packages/router-cli/vite.config.ts index f64d6aa39f..0eac9e6ed4 100644 --- a/packages/router-cli/vite.config.ts +++ b/packages/router-cli/vite.config.ts @@ -1,11 +1,17 @@ import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' +import packageJson from './package.json' -const config = defineConfig({}) +const config = defineConfig({ + define: { + __TSR_VERSION__: JSON.stringify(packageJson.version), + }, +}) export default mergeConfig( config, tanstackViteConfig({ + tsconfigPath: './tsconfig.build.json', entry: './src/index.ts', srcDir: './src', }), diff --git a/packages/router-core/AGENTS.md b/packages/router-core/AGENTS.md new file mode 100644 index 0000000000..7402f0bdfe --- /dev/null +++ b/packages/router-core/AGENTS.md @@ -0,0 +1,12 @@ +# Router core + +- `RouterCore.update` gates shared route-tree caching with `process.env.NODE_ENV !== 'development'`. `loadRouteChunk` checks promise ownership outside production so obsolete lazy imports cannot overwrite HMR changes. Preserve both behaviors; validate hot updates while imports are pending. +- Route hooks, lifecycle callbacks, and abort listeners can navigate synchronously. Recheck the internal navigation owner after callbacks and awaits before publishing state/assets. Public loader abort signals belong to shared data generations; self-aborting a loader does not discard its result or error. Preserve loader ownership when transferring work between preload, navigation, cache, and background loads; see [`tests/preload-public-signal-lifetime.test.ts`](tests/preload-public-signal-lifetime.test.ts). +- Reusing loader work/data does not reuse `beforeLoad`: each active preload and subsequent navigation reruns it. Keep its returned context separate from reusable route-context contributions; see [`tests/public-preload-lane-contract.test.ts`](tests/public-preload-lane-contract.test.ts). +- Code emitted into HTML (`?script-string` entries and RawStream factories) executes without module scope. Keep it self-contained; pass dependencies explicitly. Validate emitted strings through the existing execution tests after refactors (`RawStream`, `scroll-restoration-script`, `tsr-script-teardown`). +- Before changing SSR streaming or hydration transport, read [`src/ssr/STREAMING.md`](src/ssr/STREAMING.md). Byte ordering, renderer safe points, and completion handling have framework-specific contracts. +- Backpressure tests are excluded from normal unit runs. For buffering/backpressure changes, run the gated suite below. Its memory case requires exposed GC; bypass Nx cache so a previous run with the gate disabled cannot count as validation. + +```sh +RUN_BACKPRESSURE_PERF=1 CI=1 NX_DAEMON=false pnpm nx run-many -p @tanstack/router-core -t test:unit --skipRemoteCache --skipNxCache -- tests/transformStreamBackpressure.perf.test.ts --pool=forks --execArgv=--expose-gc +``` diff --git a/packages/router-core/CHANGELOG.md b/packages/router-core/CHANGELOG.md new file mode 100644 index 0000000000..b01991e223 --- /dev/null +++ b/packages/router-core/CHANGELOG.md @@ -0,0 +1,666 @@ +# @tanstack/router-core + +## 1.171.39 + +### Patch Changes + +- [#8670](https://github.com/TanStack/router/pull/8670) [`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c) - Reference agent skills in other packages by their `intent load` identifier (`@tanstack/#`) instead of relative file links that break once packages are installed. + +## 1.171.38 + +### Patch Changes + +- [#8212](https://github.com/TanStack/router/pull/8212) [`18154b1`](https://github.com/TanStack/router/commit/18154b1c45454a70aa77e9d6d27c8a6e0733d031) - Render generated script preloads (`modulepreload`, or `preload as="script"` for IIFE output) with `fetchPriority="low"` and forward it into static Early Hints, so they no longer compete with render-blocking stylesheets, fonts and images. + +## 1.171.37 + +### Patch Changes + +- [#8441](https://github.com/TanStack/router/pull/8441) [`d6ba115`](https://github.com/TanStack/router/commit/d6ba115d5751c75e20943f0062577cf17b446d82) - Reuse the parsed request location during SSR instead of repeating input rewrites. Match server routes against the app router's parsed pathname while preserving encoded pathnames for server handlers and middleware. + +## 1.171.36 + +### Patch Changes + +- [#7588](https://github.com/TanStack/router/pull/7588) [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5) - Reduce per-request work in Start: `getNormalizedURL` reads a `URL` input without cloning it, and `runWithStartContext` returns the callback's own result instead of wrapping it in a promise, so a synchronous throw from the callback now propagates synchronously. + +## 1.171.35 + +### Patch Changes + +- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Drop a duplicated current-location flag and a redundant `createHref` wrapper. + +- [#8602](https://github.com/TanStack/router/pull/8602) [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb) - Links of a route that the pending navigation leaves skip deriving the destination location, and clicks and preloads follow the href a Link displays. `buildLocation` now builds `mask` and `routeMasks` locations from the same `_fromLocation` as the destination. + +- [#8602](https://github.com/TanStack/router/pull/8602) [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb) - Fixed Link destinations that resolve to a route mask are now reused across navigations instead of being rebuilt every time. A mounted Link now follows changes to its `href` and `reloadDocument` props, and React Links no longer each subscribe to a hydration flag. + +- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Use `slice` instead of `substring` where the bounds are always ordered and non-negative. + +- [#7654](https://github.com/TanStack/router/pull/7654) [`663282b`](https://github.com/TanStack/router/commit/663282b0ebbc494aee3595ed95867ee29d01938e) - Encode slashes in dehydrated SSR match IDs with `#` instead of a null byte, so the inlined hydration payload no longer contains U+0000 (which is invalid in HTML and rejected by markup validators) + +- Updated dependencies [[`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2)]: + - @tanstack/history@1.162.5 + +## 1.171.34 + +### Patch Changes + +- [#8573](https://github.com/TanStack/router/pull/8573) [`d521abd`](https://github.com/TanStack/router/commit/d521abd71c69f1ff010bb3def4d417cb5fa058cb) - Align server function request and response handling. + +## 1.171.33 + +### Patch Changes + +- [#8297](https://github.com/TanStack/router/pull/8297) [`488d046`](https://github.com/TanStack/router/commit/488d046a907d330429e2c807ef95326dad87480f) - Update `seroval` and `seroval-plugins` from 1.6.2 to 1.6.7. This picks up the typed array length guard, the `maxBase64Length` and `compactArrayBufferViews` options, and the `isStream` export. + +- [#8460](https://github.com/TanStack/router/pull/8460) [`0c1b5e3`](https://github.com/TanStack/router/commit/0c1b5e38de71b7e81bbf1fd81c73ee0cd68ffe47) - Abort reserved loader generations with no remaining owners when invalidation removes them from discovery, ensuring their public abort signals are retired. + +- [#8519](https://github.com/TanStack/router/pull/8519) [`3cdd1af`](https://github.com/TanStack/router/commit/3cdd1af04b3e2d6f777797ee7bddf285318dd9d2) - Hand native scroll restoration back to the browser on pagehide, including entries entering BFCache, and reclaim manual restoration when a cached document resumes. + +## 1.171.32 + +### Patch Changes + +- [#8363](https://github.com/TanStack/router/pull/8363) [`cecae54`](https://github.com/TanStack/router/commit/cecae5440b8edaea77c5448fe3d74bbd20fe10a4) - Detect plain objects by constructor instead of `Object.prototype.toString` dispatches in `isPlainObject`, which gates every `deepEqual` and `replaceEqualDeep` recursion step. Object literals, `JSON.parse` output and null-prototype objects are still plain; objects from another realm no longer are. Records with an own `constructor` key (for example the search params of `?constructor=foo`) fall back to a prototype check, so they keep structural sharing while class instances stay opaque. + +- [#8364](https://github.com/TanStack/router/pull/8364) [`0103578`](https://github.com/TanStack/router/commit/01035782e53af9b929c784b94ddd64b95efb89c7) - Compare and copy plain objects in `replaceEqualDeep` by their string keys only, skipping the symbol-key lookup that dominated key enumeration. Objects with non-enumerable own properties, or symbol keys on the incoming value, now pass through untouched instead of being structurally shared. + +- [#8411](https://github.com/TanStack/router/pull/8411) [`ce10dcd`](https://github.com/TanStack/router/commit/ce10dcd4d9d3d23738744e453205aad5c6dbd716) - Reduce structural-sharing allocations by reusing array key storage and returning incoming objects when their children need no replacements. Preserve signed zero consistently, remove stale symbol properties, and keep sparse arrays with extra keys and built-ins with an own `constructor` opaque. + + Null-prototype mode now applies only when constructing a copy; existing incoming objects can be reused with their original prototype. + +- [#8362](https://github.com/TanStack/router/pull/8362) [`84936cc`](https://github.com/TanStack/router/commit/84936cc04530bba11059c57b293a794922bbc5aa) - Allocate the `replaceEqualDeep` result only at the first difference, so structural sharing of search, params, state and loader data no longer allocates when the new value is deeply equal to the previous one. + +- [#8389](https://github.com/TanStack/router/pull/8389) [`bbd2336`](https://github.com/TanStack/router/commit/bbd2336b8446de3f7dd85070895e7cf43980183e) - Split `replaceEqualDeep` into an equality scan and a copy phase: arrays and objects are scanned by dedicated loops up to the first difference, matching keys prove ownership without a `hasOwnProperty` lookup, and once a difference is found the result is built without any further equality bookkeeping. Deeply equal search, params, state and loader data are recognised faster and changed values are copied with less work per entry. + +## 1.171.31 + +### Patch Changes + +- [#8417](https://github.com/TanStack/router/pull/8417) [`bc80866`](https://github.com/TanStack/router/commit/bc80866f6d6eb3e6f152ee3682eb783c96403e83) - Speed up `deepEqual`: identical array elements no longer recurse, the exact comparison keeps a single key counter, and the redundant `typeof` early exit is gone. Equal numeric arrays compare ~70% faster and record comparisons 5–12% faster in the mixed-mode workloads that Link option stabilization and active-state checks produce, with a slightly smaller bundle. Behavior, including key enumeration and getter read order, is unchanged. + +- [#8418](https://github.com/TanStack/router/pull/8418) [`e561fa1`](https://github.com/TanStack/router/commit/e561fa1d7118e3d29267cc3b6ce1130d6581f387) - `deepEqual` now takes its flags as positional arguments — `deepEqual(a, b, partial?, explicitUndefined?)` — instead of an options object. The router's hot callers (Link option stabilization and active-state checks, `matchRoute`) no longer allocate an options object per comparison, and the comparator reads two booleans instead of a polymorphic object. `explicitUndefined` replaces `ignoreUndefined: false`. `deepEqual` is an internal helper; it stays exported for compatibility of two-argument calls. + +- [#8204](https://github.com/TanStack/router/pull/8204) [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26) - Reduce per-request SSR overhead: abort settled route matches with one shared `AbortError`-shaped reason instead of building a stack-capturing `DOMException` per match, skip `JSON.parse` for search values that cannot start JSON, wait on request signals with one listener per wait, and keep resolved server-function modules in production builds instead of re-importing them on every call. + +- [#8419](https://github.com/TanStack/router/pull/8419) [`a1c8d1a`](https://github.com/TanStack/router/commit/a1c8d1aa759c227eae9601a030321ac4c53c24bd) - `resolvePath` (internal helper) now takes positional arguments — `resolvePath(base, to, trailingSlash?, cache?)` — so `buildLocation` and `matchRoute` no longer allocate an options object per path resolution. + +- [#8204](https://github.com/TanStack/router/pull/8204) [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26) - Stream large deferred SSR hydration payloads through a backpressure-aware router transport, fail known setup errors before response creation, and close cancelled or expired transforms safely. + + Start now cancels discarded middleware and HEAD response bodies, including plain streams and derived branches. + + Server-function raw streams share one ordered response. Arbitrary or sequential consumption can require potentially unbounded buffering of unread data on the client. Cancelling one raw stream discards it locally, while aborting the whole call cancels the response and server work. Consume streams concurrently, cancel unused streams promptly, or use separate calls when independent backpressure is required. A raw stream that exceeds its unread-byte limit now fails alone; sibling streams and the JSON result keep flowing. + + The JSON wire shape of a `RawStream` server-function argument changed. Clients and servers must run matching versions for requests that pass a `RawStream`. + + The frame-protocol constants (`FRAME_TYPE_*`, `MAX_FRAME_PAYLOAD_SIZE`, `MAX_FRAMED_STREAMS`) moved from the `@tanstack/start-client-core` root to the `@tanstack/start-client-core/client-rpc` subpath. + + Router requests whose `Accept` header allows neither `text/html` nor `*/*` now receive `406 Not Acceptable` instead of `500`. + + Framework adapters share the body `` composition (`getSsrBodyScriptParts`, `composeSsrBodyScripts`) and the eager HTML response wrapper (`renderSsrHtmlResponse`) from `@tanstack/router-core`. + + Solid SSR now emits one document type and renders late lazy errors through route boundaries. A Solid `` without a `fallback` no longer holds the streamed shell; it renders inside the nearest `` boundary like React and Vue, and now renders falsy resolved values. + + Static server functions decode cached `RawStream` values with the client deserializer plugins. + + SSR Query integrations now keep request cleanup and stream ownership aligned with the router lifecycle. + +- [#8422](https://github.com/TanStack/router/pull/8422) [`a0b2ad9`](https://github.com/TanStack/router/commit/a0b2ad99aee64af08d16b0e4ff26b3ba42a99f0a) - Parse the location once when `router.update()` changes the basepath or rewrite, collect `invalidate()` match ids in a single pass, and specialize internal basepath composition without arrays or loops. Preserve basepath case sensitivity when creating and updating the router. + + Rebuild server route trees when `caseSensitive` changes and reuse the server cache only when the route tree and case sensitivity both match. + +- [#8421](https://github.com/TanStack/router/pull/8421) [`1ca361b`](https://github.com/TanStack/router/commit/1ca361ba52a627d2f76ab33323bd83d1d0aa65a3) - Parse masked locations without mutating shared state and simplify input rewrite handling. + +## 1.171.30 + +### Patch Changes + +- [#8321](https://github.com/TanStack/router/pull/8321) [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6) - Cache route branches and interpolated paths on their route objects, removing the fixed template limit for registered routes and reusing cached paths across server requests. Rebuild tree-dependent caches together, preserve decoder and trailing-slash isolation, and keep unregistered templates bounded. + +- [#8390](https://github.com/TanStack/router/pull/8390) [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776) - Keep the Link location cache out of server bundles: `buildLocation` only creates, reads and writes it when `isServer` is false. Render React Links on the server without the extra prop copies and the forwarded-ref hook. Link SSR rendering is 20-40% faster in the Link benchmarks and the React Start SSR request loop about 7% faster. + + React `activeProps` and `inactiveProps` now follow one precedence rule on every link, including links whose destination is blocked for using a disallowed scheme: state props override element props, `ref` and event handlers, while `href`, `disabled` and `target` stay controlled by the router. Previously a blocked link ignored a `ref` or handler from its inactive props. + + React `Link` and `useLinkProps` split router options from element props with one key set on the client and the server. Element props pass through as given: external links forward them verbatim, falsy values included, and `useLinkProps` now returns `children` for router-controlled links as it already did for external ones. + +- [#8382](https://github.com/TanStack/router/pull/8382) [`6cfb1e8`](https://github.com/TanStack/router/commit/6cfb1e8b564be282584765352250bf61747895ed) - `buildLocation` no longer structurally shares the built `search` and `state` with the current location. The observable `location.search` and `location.state` still preserve equal nested references across navigations, because `parseLocation` stabilizes them once a location is committed. A search whose contents equal the current search but list its keys in a different order now serializes in the requested order, so navigating to it creates a new history entry instead of being treated as the same location. A `state` object passed to `navigate` or `buildLocation` is never mutated. + +- [#8325](https://github.com/TanStack/router/pull/8325) [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274) - Reuse the already-owned raw-param snapshot during lightweight source matching instead of copying it again. + +- [#8325](https://github.com/TanStack/router/pull/8325) [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274) - Reduce transient JIT compilation memory during navigation by separating search middleware collection from recursive execution. + +- [#8252](https://github.com/TanStack/router/pull/8252) [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734) - Collect shared pathname-cache keys during interpolation instead of parsing templates twice, and share dynamic-segment handling to reduce bundle size. + +- [#8319](https://github.com/TanStack/router/pull/8319) [`873c830`](https://github.com/TanStack/router/commit/873c830ccb2610a864ee697250e10fcc99772ffa) - Simplify path interpolation into ordered segment-type blocks with shared prefix/value/suffix assembly. Preserve one-pass parsing and optional metadata collection, and reuse the public result object instead of allocating and clearing a missing-parameter callback. + +- [#8252](https://github.com/TanStack/router/pull/8252) [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734) - Reuse pathname interpolation across Links with bounded router-scoped caches. Keep parameter callbacks and navigation state independent of the cache. + +- [#8327](https://github.com/TanStack/router/pull/8327) [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef) - Make `pathParamsAllowedCharacters` initialization-only. Configure it when creating the router; changing allowed characters requires a new router instance. Remove decoder-update bookkeeping and decoder-change checks from route-owned path caches. + +- [#8370](https://github.com/TanStack/router/pull/8370) [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5) - Stop exporting the internal `isPlainObject` and `isPlainArray` helpers. + +- [#8327](https://github.com/TanStack/router/pull/8327) [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef) - Initialize routes directly during route-tree processing, removing the callback indirection while preserving parent-first initialization and route indexes. + +- [#8328](https://github.com/TanStack/router/pull/8328) [`f151ab0`](https://github.com/TanStack/router/commit/f151ab018eede64ae849b77e68f3cdf31cb95cc5) - Reduce duplication in navigation parameter handling while preserving parameter inheritance, null-prototype dictionaries, and updater isolation. + +- [#8410](https://github.com/TanStack/router/pull/8410) [`bc57fa3`](https://github.com/TanStack/router/commit/bc57fa3f12450cf34c731450947c7c8f1ea05e58) - Treat `0` and `false` as provided `_splat` values when interpolating paths. Only `undefined`, `null`, and `''` now omit a splat segment, matching how other path params are stringified. + +- [#8354](https://github.com/TanStack/router/pull/8354) [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244) - Use lightweight request history for SSR and make server navigation a no-op. Use redirect() to issue HTTP redirects. Server hrefs use the same normalization as browser history to handle protocol-relative URLs and control characters. + +- [#8321](https://github.com/TanStack/router/pull/8321) [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6) - Consolidate internal path interpolation into `interpolatePath`, returning a pathname directly and collecting metadata only when requested. Update router and devtools callers without changing route parsing or interpolation caching. + +- [#8327](https://github.com/TanStack/router/pull/8327) [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef) - Reduce route-tree initialization work by avoiding temporary path-joining arrays and duplicate ID normalization. + +- [#8327](https://github.com/TanStack/router/pull/8327) [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef) - Reuse parsed route segments when generating paths for navigation, Links, and Devtools. Preserve interpolation metadata and refresh segments when the route tree is rebuilt, without reparsing templates for new parameter values. + +- [#8252](https://github.com/TanStack/router/pull/8252) [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734) - Reduce the bundle cost of shared Link pathname interpolation while preserving its rendering performance. Reuse one interpolation pass for pathname and optional metadata, keep the bounded cache on the router, and simplify React Link active-state and prop merging. + +- [#8385](https://github.com/TanStack/router/pull/8385) [`9448caa`](https://github.com/TanStack/router/commit/9448caa03a89076b9770631c356c0cc502802c09) - Collect search middlewares with a counted loop so the optimized code stays valid across navigations. This removes a JIT recompilation that raised peak memory in the interrupted-navigations client memory benchmark. + +- [#8370](https://github.com/TanStack/router/pull/8370) [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5) - Reuse built locations for Links whose destination does not depend on the current location. `buildLocation` keeps the result per options object when the build never read the current location, and the React `Link` passes one stable options object per instance, so navigations resolve unchanged Links with a lookup instead of a full build. The per-route pathname interpolation cache this replaces is removed. Link `params`, `search` and `activeOptions` are compared by value on render, so inline object literals with unchanged contents keep reusing the Link's location. Pass a new object to change a destination; like any other React prop, an object mutated in place is not re-read. + +- [#8325](https://github.com/TanStack/router/pull/8325) [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274) - Cache normalized route pathnames so repeated Link destinations do not decode the same interpolation result again. + +- [#8327](https://github.com/TanStack/router/pull/8327) [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef) - Share compact parsed route segments between matching and interpolation, preserve original parameter names, and avoid reparsing templates while building paths. Simplify route-tree traversal, reuse existing path helpers, and keep Devtools-only navigation validation out of the production formatter. Preserve dynamic match identity for standalone legacy fallback routes. + +- [#8327](https://github.com/TanStack/router/pull/8327) [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef) - Pass route initialization indexes directly instead of wrapping each index in an options object. + +- Updated dependencies [[`8fff7fa`](https://github.com/TanStack/router/commit/8fff7fa1f2e6f061916b0bf5e0ec486b2e732f94), [`f021f6d`](https://github.com/TanStack/router/commit/f021f6d1c6dce6c9b54d70766f1d636d8fd9e184), [`ae68535`](https://github.com/TanStack/router/commit/ae68535929043607d4ee9438f8ae401f3a064862), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244)]: + - @tanstack/history@1.162.4 + +## 1.171.29 + +### Patch Changes + +- [#8313](https://github.com/TanStack/router/pull/8313) [`f9836f1`](https://github.com/TanStack/router/commit/f9836f16f0e25b0a8495f5e01e3f303b1cbc8725) - Avoid constructing a query serializer when search is empty or all values are undefined. + +- [#8308](https://github.com/TanStack/router/pull/8308) [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8) - Validate navigation and redirect destinations, keep ambiguous relative URLs on the current origin, and constrain prerender requests and output paths. Prevent redirect headers from appearing in serialized server function response bodies. + + Preserve native form HTTP redirects, route error handling and masks for document redirects, and per-navigation destinations for shared loader redirects. Avoid redundant origin parsing and reduce link styling and server-rendering work. Configured origins must already be normalized. + + Keep blocked-link inactive props consistent during React hydration, honor explicit redirect Location headers before checking route options, and refresh Vue link state when destinations become internal. Reuse the protocol-relative URL check while parsing redirect schemes once. + + Reduce React link bundle size by sharing pathname comparisons, state-prop selection, and element creation. + + Share normalized pathname comparisons in Solid and Vue links to reduce bundle size. + +- [#8288](https://github.com/TanStack/router/pull/8288) [`9871c06`](https://github.com/TanStack/router/commit/9871c0625806001d6bf373524821a00303438a91) - Reduce cache maintenance work during navigation by indexing incoming match IDs once per commit. + +- [#8287](https://github.com/TanStack/router/pull/8287) [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9) - Use full-document navigation when an output rewrite produces a cross-origin destination, including the public URL of a route mask. + + Respect registered history blockers during document navigation, passing history locations and the requested push or replace action. + +- Updated dependencies [[`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8), [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9)]: + - @tanstack/history@1.162.3 + +## 1.171.28 + +### Patch Changes + +- [#8222](https://github.com/TanStack/router/pull/8222) [`edf0e16`](https://github.com/TanStack/router/commit/edf0e16ebfe82ec6e8f68f403a1fda8de9e28889) - Make each load transaction's completion follow its current successor so a burst of back-to-back loads wakes each superseded waiter once instead of once per successor. Previously every superseded `load()` re-polled the current transaction on each later completion, which was quadratic in microtask work. + +- [#8165](https://github.com/TanStack/router/pull/8165) [`2f20c00`](https://github.com/TanStack/router/commit/2f20c00224c5ba63467551914e0c37012588c4c2) - Exclude structural descendants below error and not-found boundaries from route lifecycle callbacks. Preserve lifecycle membership through invalidation, hydration, background reloads, and superseded navigation publication. + +- [#8209](https://github.com/TanStack/router/pull/8209) [`28a5e45`](https://github.com/TanStack/router/commit/28a5e4504e4ea5cb1480667a4bea2588a53e110f) - Preserve falsy thrown values in React and Vue error boundaries. Type React and Vue boundary error components and `onCatch` callbacks as `unknown`. Solid boundary errors remain typed as `Error`; SSR now wraps non-`Error` loader errors to match Solid’s native boundary behavior, preserving the original value in `cause`. Router state and loader `onError` values are unchanged. + + When upgrading React or Vue, narrow boundary errors (for example, with `error instanceof Error`) before reading `message` or `stack`. `ErrorComponentProps` remains available for values narrowed to a specific error type. Route `onError` types are unchanged. + +- [#8207](https://github.com/TanStack/router/pull/8207) [`08eff50`](https://github.com/TanStack/router/commit/08eff50c447a154a3373909009e9e4375cea17ce) - Fix consumer typechecking with `skipLibCheck: false` by omitting the internal beforeLoad context field from published dehydrated match declarations. + + Retain the exported `isAbsoluteUrl` declaration used by framework bindings so the package entry point does not reference a stripped symbol. + +- [#8259](https://github.com/TanStack/router/pull/8259) [`216c0c4`](https://github.com/TanStack/router/commit/216c0c48036fd1a33163b70dcabfed2b893808b0) - Reduce Promise allocations during client navigation and static server SSR policy resolution. Skip cancellable waits for synchronous beforeLoad results while preserving navigation cancellation. + +- [#8240](https://github.com/TanStack/router/pull/8240) [`2f91503`](https://github.com/TanStack/router/commit/2f9150309bc472f4a75cbe98adcdb50c76b12c7a) - Avoid quadratic resource handoff scans when navigating with many cached route matches. + +- [#8161](https://github.com/TanStack/router/pull/8161) [`f0b5eda`](https://github.com/TanStack/router/commit/f0b5eda544606686a8a8d675a686ca1366428b96) - Retain successful not-found matches as terminal shared boundaries during client navigation, preserving route context while the destination loads. + +- [#8142](https://github.com/TanStack/router/pull/8142) [`50eafca`](https://github.com/TanStack/router/commit/50eafcaebbbedb6fde3b2816de7a0ace8cde4832) - Avoid unnecessary JSON.parse calls for search parameter values that cannot begin valid JSON, while preserving custom parser behavior. + +- [#8251](https://github.com/TanStack/router/pull/8251) [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b) - Use URL.canParse for absolute URL checks in links, navigation, redirects, and build configuration. Preserve a URL constructor fallback for older browsers. + +- [#8230](https://github.com/TanStack/router/pull/8230) [`ee28348`](https://github.com/TanStack/router/commit/ee283480dfa51150a2e0b096a6eff94a89ff8b3f) - Replace the internal LRU cache behind path resolution, route matching and the SSR manifest lookup with a smaller SIEVE cache whose hits no longer relink a list, and fix an eviction edge case in the old implementation. + +- [#8244](https://github.com/TanStack/router/pull/8244) [`c18e690`](https://github.com/TanStack/router/commit/c18e69081475a7c98f9d40bd0fe6da78ccb84598) - Reduce promise allocations during client navigation when loader data and route components are already available. + +- Updated dependencies [[`9035abc`](https://github.com/TanStack/router/commit/9035abc41163d83409ef582f7743a3c7be57dd93)]: + - @tanstack/history@1.162.2 + +## 1.171.27 + +### Patch Changes + +- [#8132](https://github.com/TanStack/router/pull/8132) [`fa65287`](https://github.com/TanStack/router/commit/fa652872812c9433ba8b9d9a285e51b535e7367c) - Build client preload locations on demand and remove the prebuilt-location argument used by framework links. + +- [#8130](https://github.com/TanStack/router/pull/8130) [`cb281d7`](https://github.com/TanStack/router/commit/cb281d70c1f5fe780f9d07bc500ea3a284a4e04b) - preserve context during reloads + +## 1.171.26 + +### Patch Changes + +- [#8117](https://github.com/TanStack/router/pull/8117) [`3e016ac`](https://github.com/TanStack/router/commit/3e016ac84ffec8119f0c25cfdd1fb17e5292bd34) - optimize buildLocation path resolution https://github.com/TanStack/router/pull/8108 + skip building search validation when disabled https://github.com/TanStack/router/pull/8112 + skip location state sharing when impossible https://github.com/TanStack/router/pull/8110 + fix cache hits for mask resolution when entry is null https://github.com/TanStack/router/pull/8111 + +## 1.171.25 + +### Patch Changes + +- [#8084](https://github.com/TanStack/router/pull/8084) [`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175) - preserve pending UI across retained routes + +- [#8092](https://github.com/TanStack/router/pull/8092) [`63d2cc9`](https://github.com/TanStack/router/commit/63d2cc9155ff5374112f7d067d0b278bafeb8486) - Render route errors when redirect target construction fails and let successor transactions own navigation and HMR presentation. + +## 1.171.24 + +### Patch Changes + +- [#8071](https://github.com/TanStack/router/pull/8071) [`4c89b15`](https://github.com/TanStack/router/commit/4c89b15dd2b46491ee5e57985559bae8e31d62c2) - inline getOpenAndCloseBraces in parseSegment for byte shaving + +- [#8069](https://github.com/TanStack/router/pull/8069) [`cf6ab17`](https://github.com/TanStack/router/commit/cf6ab178b39e7628bf784759f384e0f4230e6d9e) - inline isFunction utility fn for byte shaving + +- [#8070](https://github.com/TanStack/router/pull/8070) [`bdaf73a`](https://github.com/TanStack/router/commit/bdaf73a4063ee2b02e3c9cc105ad10ce82a5a0ff) - inline buildWithMatches inside buildLocation for byte shaving + +## 1.171.23 + +### Patch Changes + +- [#8054](https://github.com/TanStack/router/pull/8054) [`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90) - Reuse resolved lazy route components when revisiting code-split routes, preventing unnecessary pending UI. + +## 1.171.22 + +### Patch Changes + +- [#8039](https://github.com/TanStack/router/pull/8039) [`7e93431`](https://github.com/TanStack/router/commit/7e93431ae9ff58c91c3c5ca10ffcb8414c1d0b13) - load-client can cache settles abandonned loader work without preload authority + +## 1.171.21 + +### Patch Changes + +- [#8019](https://github.com/TanStack/router/pull/8019) [`51138a8`](https://github.com/TanStack/router/commit/51138a824cea053738f125c4c95073bd6286ff05) - handle excessive parent relative links + +## 1.171.20 + +### Patch Changes + +- [#8006](https://github.com/TanStack/router/pull/8006) [`44a8c3e`](https://github.com/TanStack/router/commit/44a8c3e1d2af305064b2363d97fc7847c6f1a246) - skip impossible JSON parse attempts + +- [#8010](https://github.com/TanStack/router/pull/8010) [`5253e70`](https://github.com/TanStack/router/commit/5253e70db2083d68a788fb7c9a043bb0c5518f2a) - perf: speed up structural sharing (`replaceEqualDeep`) by computing enumerable own keys with `Object.keys` + a length compare instead of `getOwnPropertyNames` followed by a `propertyIsEnumerable` call per key. This runs on every selector result on every state update when `defaultStructuralSharing` is enabled, and is ~1.3-1.5x faster on typical router state objects with identical behavior. + +## 1.171.19 + +### Patch Changes + +- [#7992](https://github.com/TanStack/router/pull/7992) [`ea3a665`](https://github.com/TanStack/router/commit/ea3a665d81cbb5074c2d77ec953255ab534e7db9) - retain mounted UI during revalidation + +## 1.171.18 + +### Patch Changes + +- [#7984](https://github.com/TanStack/router/pull/7984) [`84db4a8`](https://github.com/TanStack/router/commit/84db4a842311df3f7e58073f6f12aaf371aeb5c7) - Improve route-tree construction and matching performance by fusing static and + dynamic node creation, sorting only dynamic sibling lists that need it, and + deriving matcher depth from trie nodes. + +- [#7985](https://github.com/TanStack/router/pull/7985) [`9cac62a`](https://github.com/TanStack/router/commit/9cac62a5c7f99ef070991ea6f1fa7e42c746d46b) - perf: compact private bundle boundaries- [#7975](https://github.com/TanStack/router/issues/7975) + +- [#7967](https://github.com/TanStack/router/pull/7967) [`6aefb33`](https://github.com/TanStack/router/commit/6aefb3392595a07a93f89301d7b5e3558ff9190c) - Preserve path params in their raw string form while matching routes so structured values returned by `params.parse` produce stable match IDs and do not reuse stale loader data. + + `RouterCore.getMatchedRoutes()` now returns `[matchedRoutes, rawParams, foundRoute]` instead of an object. + +- Updated dependencies [[`9cac62a`](https://github.com/TanStack/router/commit/9cac62a5c7f99ef070991ea6f1fa7e42c746d46b)]: + - @tanstack/history@1.162.1 + +## 1.171.17 + +### Patch Changes + +- [#7962](https://github.com/TanStack/router/pull/7962) [`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5) - Update Seroval dependencies to version 1.6.2. + +## 1.171.16 + +### Patch Changes + +- [#7805](https://github.com/TanStack/router/pull/7805) [`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd) - Rewrite match loading around a lane-based scheduler that tracks each navigation, preload, and background reload as an ordered unit of work. This fixes pending/redirect/retry state leaking between overlapping navigations, restores correct SSR status codes for redirects, errors, and not-found responses, and closes hydration gaps where the client re-ran work the server had already completed. + - Invalidation now retires matching active preloads so older speculative loader results cannot become fresh cache data after invalidation. + - Route `headers()` now only runs on the server, matching the documented behavior — it is no longer invoked during client-side asset projection. + - The documented default `gcTime` and `preloadGcTime` now match the existing runtime default of 5 minutes (`300_000`). + + **Removed / changed exported internals** + - `RouterState` no longer includes `loadedAt`, `isTransitioning`, `statusCode`, or `redirect`. Use `match.updatedAt` in place of `loadedAt`; subscribe to `router.state.status` / `router.state.isLoading` in place of `isTransitioning`; server response status and redirect handling are now internal to the server loader and are no longer exposed on `router.state`. + - `RouteMatch.fetchCount` has been removed, with no replacement — it was purely informational. + - `RouteMatch.status` no longer includes `'redirected'` (it remains `'pending' | 'success' | 'error' | 'notFound'`) — redirected matches are dropped from the match list instead of being rendered. + - `RouteMatch.globalNotFound` has been renamed and privatized to the internal `_notFound` field. Use `match.status === 'notFound'` instead. + - The exported React, Solid, and Vue `Match` components now accept `routeId` instead of `matchId`. + - The exported `RouterStores` adapter contract now uses route-keyed presentation stores: `matchesId` is replaced by `ids`, `matchStores` by `byRoute`, and `getRouteMatchStore()` by `getMatchStore()`. The separate `loadedAt`, `isLoading`, `isTransitioning`, `statusCode`, and `redirect` stores have been removed, along with the pending/cache stores and their setters. `StoreConfig.init` has also been removed. Read application-facing state from `router.state`; preload and cache coordination are now internal. + - Removed `RouterCore` members `getMatch()`, `updateMatch()`, `cancelMatch()`, and `cancelMatches()` — read matches from `router.state.matches` (e.g. `router.state.matches.find((m) => m.id === id)`); there is no replacement for mutating or cancelling an individual in-flight match from outside the router. + - Removed `RouterCore.hasNotFoundMatch()` — use `router.state.matches.some((m) => m.status === 'notFound')`. + - Removed `RouterCore.looseRoutesById` — use `routesById`. + - Removed `RouterCore.isPrerendering()`, `RouterCore.isViewTransitionTypesSupported`, and `RouterCore.viewTransitionPromise`, with no replacement. + - Removed `RouterCore.getParsedLocationHref()` and `RouterCore.clearExpiredCache()`, with no replacement — expired cache entries are now reconciled automatically as part of match commit. + - Removed `RouterCore.latestLoadPromise` and `RouterCore.beforeLoad()`, with no replacement. + - `RouterCore.commitLocationPromise` and `RouterCore.pendingBuiltLocation` have been replaced by the internal `_commitPromise` and `_pendingLocation` fields. + - Removed the exported `GetMatchFn` and `UpdateMatchFn` types, along with the methods they typed. + - Removed the standalone `getMatchedRoutes()` export from `@tanstack/router-core` — use the `router.getMatchedRoutes()` instance method instead. + - `RouterCore.loadRouteChunk()` no longer accepts an array of component types as its second argument. One-argument usage is unchanged; the optional second argument is now `'errorComponent'`, `'notFoundComponent'`, or `false` for internal boundary loading. + - Removed `Redirect.redirectHandled`, which was internal redirect bookkeeping. + - `MatchRoutesOpts.preload` and `MatchRoutesOpts.dest` have been removed. + - `StartTransitionFn` is now `(fn, expected) => Promise` (previously `(fn) => void`). This only affects custom framework adapters that implement `startTransition`. + +## 1.171.15 + +### Patch Changes + +- [#7807](https://github.com/TanStack/router/pull/7807) [`e2dd204`](https://github.com/TanStack/router/commit/e2dd2049cb42eb219d3b447b8605066d19d9c1fa) - fix(router-core): handle window and element scroll restoration independently + + Window and element scroll targets are now handled independently. Restoring one target no longer suppresses resets for other uncached configured targets, and a restored element is no longer reset when the window has no cached position. + + Hash navigation no longer resets elements configured through `scrollToTopSelectors` and retains precedence over stale window positions through destination invalidations. + + Scroll positions are sampled when leaving a route, preserving live changes made after the most recent scroll event. This also prevents client hydration from undoing nested positions restored by the SSR script. + + Fixes [#7687](https://github.com/TanStack/router/issues/7687). + +## 1.171.14 + +### Patch Changes + +- [#7695](https://github.com/TanStack/router/pull/7695) [`9809a06`](https://github.com/TanStack/router/commit/9809a0619d4ed3fe8c2a393af5b9eca4b6c7695b) - fix(router-core): re-encode URL-unsafe characters in `sanitizePathSegment` to prevent infinite redirect loops + + `sanitizePathSegment` now re-encodes characters in the WHATWG URL "path percent-encode set" (`<`, `>`, `"`, `` ` ``, `{`, `}`) and ASCII control characters back to their percent-encoded form, instead of stripping control characters. This prevents mismatches between the original URL and the router's internal representation that previously caused infinite 307 redirect loops on paths containing these characters (e.g. `/%7B%7Btemplate%7D%7D`). + + Fixes [#7587](https://github.com/TanStack/router/issues/7587). + +## 1.171.13 + +### Patch Changes + +- [#7562](https://github.com/TanStack/router/pull/7562) [`776d8ef`](https://github.com/TanStack/router/commit/776d8ef283e5bd9ffe97d43bc3a7f58064cd7e03) - Prevent scroll restoration listeners from being installed when scroll restoration is disabled. + +## 1.171.12 + +### Patch Changes + +- [#7559](https://github.com/TanStack/router/pull/7559) [`df1076c`](https://github.com/TanStack/router/commit/df1076c03ae5a51ab384bebd4d6afda20fb6f107) - Fix retained search params overriding explicit default-valued navigations when used with `stripSearchParams`. + +## 1.171.11 + +### Patch Changes + +- [#7555](https://github.com/TanStack/router/pull/7555) [`ac10815`](https://github.com/TanStack/router/commit/ac10815f387d25b15163ff711b4049e8f8482d01) - Fix search middleware composition so `retainSearchParams` does not restore search params that a downstream `stripSearchParams` removed. + +## 1.171.10 + +### Patch Changes + +- [#7381](https://github.com/TanStack/router/pull/7381) [`2cca73c`](https://github.com/TanStack/router/commit/2cca73c92262ffd96dac4e283c9f69fb37f4b43a) - fix(router-core): use search validator output type for search middleware context + +- [#7549](https://github.com/TanStack/router/pull/7549) [`7a83e67`](https://github.com/TanStack/router/commit/7a83e67e6596fbef21cb0a88a7127f5935bed2ba) - Fix `retainSearchParams` preserving current search params when validation adds default search values during navigation. + +- [#7533](https://github.com/TanStack/router/pull/7533) [`76b3d3b`](https://github.com/TanStack/router/commit/76b3d3b24522bd3d1d216674c441252c9b8f184c) - delete $\_TSR immediately on stream end + +## 1.171.9 + +### Patch Changes + +- [#7524](https://github.com/TanStack/router/pull/7524) [`b4cd5af`](https://github.com/TanStack/router/commit/b4cd5af8d0f9d4aaa2d29095e6a261b9181bc778) - defer `$_TSR` teardown until DOMContentLoaded + +## 1.171.8 + +### Patch Changes + +- [#7505](https://github.com/TanStack/router/pull/7505) [`2f53749`](https://github.com/TanStack/router/commit/2f5374945e2138559a51464f45a5152eae67e1dd) - Preserve primitive values thrown from beforeLoad error handling. + +## 1.171.7 + +### Patch Changes + +- [#7497](https://github.com/TanStack/router/pull/7497) [`d1997b6`](https://github.com/TanStack/router/commit/d1997b66d7c24c1d64772bb8bab5caf9c6d9cc48) - fix streaming + +## 1.171.6 + +### Patch Changes + +- Add support for Rsbuild client output formats, including module output by default and IIFE output for classic script environments. ([#7477](https://github.com/TanStack/router/pull/7477)) + + Client entry scripts and preloads are now represented as root route manifest assets, script preloads follow the manifest script format, and script asset cross-origin configuration uses the `script` key. The `transformAssets` script callback context now exposes only `kind: 'script'` and `url`, keeping script format handling internal to manifest rendering. + +## 1.171.5 + +### Patch Changes + +- Fix hash scrolling with `resetScroll={false}` ([#7464](https://github.com/TanStack/router/pull/7464)) + +## 1.171.4 + +### Patch Changes + +- Fix hash navigation being overridden by stale scroll restoration entries. ([#7447](https://github.com/TanStack/router/pull/7447)) + +- Preserve carried scroll positions across SPA navigations that create new restoration keys. ([#7447](https://github.com/TanStack/router/pull/7447)) + +## 1.171.3 + +### Patch Changes + +- Add deferred Hydrate boundary support for TanStack Start. ([#7362](https://github.com/TanStack/router/pull/7362)) + + Hydrate boundaries can now be code-split by the Start compiler, preload their generated client chunks, preserve server-rendered fallback HTML, and replay interaction-triggered events after hydration. The compiler integration now uses a Start-owned compiler plugin for Hydrate virtual modules across Vite and Rsbuild, with dev invalidation for generated virtual modules. + + Shared AST utilities used by the router code-splitter and Hydrate virtual modules were moved into `@tanstack/router-utils` so both pipelines can retain referenced top-level declarations, unwrap local exports, and let dead-code elimination remove unused route module code. + +## 1.171.2 + +### Patch Changes + +- Fix route mismatch warnings, HMR route index refresh, and generated route type preferences for duplicate pathless/index routes. ([#7422](https://github.com/TanStack/router/pull/7422)) + +## 1.171.1 + +### Patch Changes + +- Run custom router hydration before the initial client route match so hydrated router configuration, such as request-specific URL rewrites, can be installed before SSR hydration compares matches. ([#7416](https://github.com/TanStack/router/pull/7416)) + +## 1.171.0 + +### Minor Changes + +- params.priority route option as tie breaker in route matching algorithm ([#7411](https://github.com/TanStack/router/pull/7411)) + +## 1.170.1 + +### Patch Changes + +- Add runtime-configurable inline CSS and opt-in CSS URL templates for transformAssets. ([#7380](https://github.com/TanStack/router/pull/7380)) + +## 1.170.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +### Patch Changes + +- fix(router-core): fix missing closing paren in CSS.supports check for view transition types ([#7369](https://github.com/TanStack/router/pull/7369)) + +- Updated dependencies [[`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14)]: + - @tanstack/history@1.162.0 + +## 1.169.2 + +### Patch Changes + +- Update seroval dependencies to version 1.5.4. ([#7340](https://github.com/TanStack/router/pull/7340)) + +## 1.169.1 + +### Patch Changes + +- Fix params.parse inference for discriminated union path params while preserving path key validation. ([#7306](https://github.com/TanStack/router/pull/7306)) + +## 1.169.0 + +### Minor Changes + +- Allow `params.parse` to experimentally return `false` to skip an incoming route candidate during path matching. Thrown parse errors still surface on the selected match instead of falling through, and outgoing typed route-template links continue to use exact route lookup followed by `params.stringify` for URL generation. ([#7263](https://github.com/TanStack/router/pull/7263)) + +## 1.168.18 + +### Patch Changes + +- prevent isServer exports from being transformed to top-level vars so rspack can dead-code eliminate them ([#7293](https://github.com/TanStack/router/pull/7293)) + +## 1.168.17 + +### Patch Changes + +- wildcard nodes have the same priority rules as other nodes in route matching ([#7273](https://github.com/TanStack/router/pull/7273)) + +## 1.168.16 + +### Patch Changes + +- Add TanStack Start inline CSS manifest support for SSR so route styles can be embedded in the HTML response and hydrated without duplicate stylesheet links. ([#7253](https://github.com/TanStack/router/pull/7253)) + +## 1.168.15 + +### Patch Changes + +- Fix async loaders that throw or return `notFound()` so they do not briefly mark the match as `success` before the final not-found boundary is resolved. ([#7184](https://github.com/TanStack/router/pull/7184)) + + This prevents route components from rendering with missing loader data during navigation when React observes the intermediate match state before not-found finalization completes. + +## 1.168.14 + +### Patch Changes + +- chore: bump to h3 v2-rc.20 ([#7140](https://github.com/TanStack/router/pull/7140)) + +## 1.168.13 + +### Patch Changes + +- Reduce React Start SSR manifest payload size by omitting unmatched route assets from dehydrated router state while keeping start-manifest asset serialization deduplicated by shared object identity. ([#7157](https://github.com/TanStack/router/pull/7157)) + + This improves SSR HTML size for apps with many routes that share the same CSS assets and adds regression coverage for CSS module hydration, navigation, and start-manifest asset reuse. + +## 1.168.12 + +### Patch Changes + +- avoid false notFound matches for proxied loader data ([#7156](https://github.com/TanStack/router/pull/7156)) + +## 1.168.11 + +### Patch Changes + +- shorten internal non-minifiable store names for byte shaving ([#7152](https://github.com/TanStack/router/pull/7152)) + +## 1.168.10 + +### Patch Changes + +- migrate createStore > createAtom for simpler API ([#7150](https://github.com/TanStack/router/pull/7150)) + +## 1.168.9 + +### Patch Changes + +- Preserve component-thrown `notFound()` errors through framework error boundaries so route `notFoundComponent` handlers render without requiring an explicit `routeId`. ([#7077](https://github.com/TanStack/router/pull/7077)) + +## 1.168.8 + +### Patch Changes + +- Fix preload from continuing into child `beforeLoad` and `head` handlers after a parent `beforeLoad` fails. ([#7075](https://github.com/TanStack/router/pull/7075)) + +## 1.168.7 + +### Patch Changes + +- Avoid re-running hash scrolling after SSR hydration when later preload or invalidate cycles resolve without a location change. ([#7066](https://github.com/TanStack/router/pull/7066)) + +## 1.168.6 + +### Patch Changes + +- Fix a regression where browser back/forward navigation could fail to restore the previous scroll position for an existing history entry. ([#7055](https://github.com/TanStack/router/pull/7055)) + +## 1.168.5 + +### Patch Changes + +- fix: scroll restoration without throttling ([#7042](https://github.com/TanStack/router/pull/7042)) + +## 1.168.4 + +### Patch Changes + +- tanstack/store 0.9.3 ([#7041](https://github.com/TanStack/router/pull/7041)) + +## 1.168.3 + +### Patch Changes + +- feat: transformAssets ([#7023](https://github.com/TanStack/router/pull/7023)) + +## 1.168.2 + +### Patch Changes + +- Replace tiny-invariant and tiny-warning with in-house solution for bundle-size ([#7007](https://github.com/TanStack/router/pull/7007)) + +## 1.168.1 + +### Patch Changes + +- Update store to 0.9.2 ([#6993](https://github.com/TanStack/router/pull/6993)) + +## 1.168.0 + +### Minor Changes + +- remove pendingMatches, cachedMatches ([#6704](https://github.com/TanStack/router/pull/6704)) + move to signal-based reactivity + solid uses its own native signals + +## 1.167.5 + +### Patch Changes + +- chore: bump esbuild to 0.27.4 ([#6975](https://github.com/TanStack/router/pull/6975)) + +## 1.167.4 + +### Patch Changes + +- Add @tanstack/intent AI agent skills and CLI entry points for Router and Start packages ([#6866](https://github.com/TanStack/router/pull/6866)) + +## 1.167.3 + +### Patch Changes + +- Fix retained chained router promise refs during route loads and commits. ([#6929](https://github.com/TanStack/router/pull/6929)) + +## 1.167.2 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +- Updated dependencies [[`838b0eb`](https://github.com/TanStack/router/commit/838b0eb9a8bbbb987a0a6972c1446e01423bbd7b)]: + - @tanstack/history@1.161.6 + +## 1.167.1 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) + +- Updated dependencies [[`ef9b241`](https://github.com/TanStack/router/commit/ef9b241f3cfe95cee40daa96da669f0ffd4a971a)]: + - @tanstack/history@1.161.5 + +## 1.167.0 + +### Minor Changes + +- feat: add staleReloadMode ([#6921](https://github.com/TanStack/router/pull/6921)) diff --git a/packages/router-core/INTERNALS.md b/packages/router-core/INTERNALS.md new file mode 100644 index 0000000000..4ef0dfa031 --- /dev/null +++ b/packages/router-core/INTERNALS.md @@ -0,0 +1,1410 @@ +# Match loading internals + +This document describes the architecture that loads route matches on the +client, on the server, and across hydration. It is for maintainers of router +core and the framework adapters. + +Match loading coordinates several asynchronous flows, but its runtime +coordination state is limited to actual writers and owned resources. Phase names +and invalid transitions belong in TypeScript whenever possible; they do not +justify a second runtime state machine. + +All `_`-prefixed fields mentioned here are internal. Their spelling and shape +may change, but the ownership rules in this document must continue to hold. + +## Vocabulary and the short version + +- A **match** is one route at one concrete set of path params, search-derived + loader dependencies, and loader/cache identity. +- A **lane** is one location plus its ordered array of matches. +- A **generation** is one concrete match result for a match ID. Several + generations can share an ID while holding different loader data or ownership; + a newer one can exist without being the one currently displayed. +- A **loader flight** is one loader invocation together with its promise and + abort controller. `router._flights` lets later consumers find the newest + same-ID flight. +- A **lease** is one match's ownership of a flight. Registry membership makes a + flight discoverable; leases keep it alive. +- **Semantic state** is the accepted lane used for reuse and lifecycle + decisions. **Presentation state** is the lane currently exposed to rendering + and selectors. +- A **cutoff** is the end of the match prefix allowed to render or contribute a + particular output. The first pending or terminal boundary normally sets it, + even though later matches remain structurally present. +- To **publish** is to replace router state that renderers or users can observe. + An **identity check** means that publication is allowed only while the exact + owner or base reference used to produce the result is still current. + +The normal client flow is: + +```text +match a private lane + -> build context and run beforeLoad parent-first + -> run eligible loaders and component readiness work + -> select one final outcome and derive assets + -> publish only if the navigation still owns the result +``` + +An ordinary foreground or preload loader success can gain an independent cache +owner while its lane is still private. This is per-match data reuse, not lane +publication; unresolved loader work remains owned only by its consumers. + +Preloads run the same work without publishing a lane. Server loading uses a +request signal instead of a client navigation owner. Hydration reconstructs the +accepted server prefix, then hands any remaining client work to the initial +client load. + +## The architectural rule + +For each mutable result, there must be one answer to each of these questions: + +1. Who may publish it? +2. Who owns the work and cancellation signal that produce it? +3. What proves that the answer is still current after an `await`? + +Do not add a flag, counter, copied deadline, or second completion promise merely +to describe an existing fact. Add runtime state only when it removes an +independent writer, resource owner, or invalid transition. + +The main authorities are: + +| Authority | What it owns | +| ---------------------------- | ------------------------------------------------------------------- | +| `_tx` | The client navigation allowed to commit and publish foreground flow | +| `_preflight` | The current client plan or asynchronous hydration reconstruction | +| `_handoff` | The temporary right to transfer one reconstructed SSR prefix | +| `_committed` | The accepted current lane and lifecycle/background identity base | +| `stores.matches` | The current match presentation exposed to renderers and users | +| `router._cache` | Off-screen loader generations preferred during same-ID planning | +| Active preload entry | Cancellation, cache clearing, and private redirect-chain ownership | +| Loader flight registry entry | The latest same-ID loader generation available to new consumers | +| Match flight lease | Ownership keeping that loader work alive | +| Pending session | One reveal/minimum-visible deadline and its current owner | +| React acknowledgement slot | The one requested publication whose render may settle a transition | +| Refresh transaction | Forced rematerialization and an optional hydration handoff | +| Request signal | Lifetime of one server request and any accepted SSR stream | +| Accepted SSR stream response | Cleanup ownership transferred from the handler to the response body | + +These authorities are related, but none is a substitute for another. In +particular, presentation is not semantic authority, registry membership is not +resource ownership, and a promise settling is not permission to publish. + +## Code map + +- `src/router.ts` matches locations, creates match objects, owns public router + state, history, cache operations, and entry points into loading. +- `src/stores.ts` reconciles route-keyed presentation stores and their ordered + aggregate. +- `src/load-client.ts` owns client planning, transactions, preloads, loader + flights, lazy route and component readiness, reduction, pending presentation, + background reloads, commits, and hydration reconstruction. +- `src/load-server.ts` runs the request-local server lane. +- `src/ssr/createRequestHandler.ts` connects request lifetime, server loading, + dehydration, redirects, rendering, and cleanup. +- `src/ssr/handlerCallback.ts`, `src/ssr/ssr-server.ts`, and + `src/ssr/transformStreamWithRouter.ts` transfer stream ownership and + coordinate serialization, injection, abort, and cleanup. + `src/ssr/hydrationScripts.ts` owns the request-local hydration script queue + and framing; `src/ssr/htmlBoundaryScanner.ts` owns the byte matchers. + See `src/ssr/STREAMING.md` for the transport contract. +- Framework `Transitioner` and `Matches` implementations acknowledge exact + publications and render only through the selected boundary. Framework + `RouterClient` and render-to-stream implementations complete hydration and + connect request abort to their renderer. + +## Semantic state and presentation state + +The rewrite deliberately separates two views of matches. + +### Semantic matches + +`_committed` is the accepted current semantic lane. It supplies lifecycle +identity and is the exact base checked before a background publication. Pending +presentation never replaces it as a planning base. + +For an individual match ID, matching first consults `router._cache` and then +falls back to `_committed`. A cached loader generation can therefore shadow the +currently displayed same-ID generation for future planning without becoming +current presentation or lifecycle authority. + +Semantic matches may own loader-flight leases. They are not mutated by losing +transactions or by pending presentation. + +### Presented matches + +`stores.matches` is the array visible to router state and framework stores. +Before `pendingMs` expires it can still contain the source presentation. Once +pending presentation is published, it contains the whole destination lane, +including descendants that are still loading. Terminal publication follows the +same membership rule: an error is retained at the throwing match, while +not-found is moved to its selected boundary, but neither removes +structurally matched descendants. The framework renderer derives its cutoff +from the first pending or terminal boundary instead of requiring core to hide +descendants. + +The render cutoff also bounds route response headers, SSR manifest assets, +dehydration, and cache exclusion during commit. Framework construction of head +and scripts uses the closely related asset cutoff. It normally stops at the +same boundary, with one selective-SSR hydration exception: a verified +`'data-only'` prefix can carry `_assetEnd`, allowing already-projected assets +from verified descendants to remain active past a pending render boundary until +the client continuation commits. A structural descendant below the relevant +cutoff remains observable in state, but it cannot contribute that output or +evict a newer cache generation merely because it is present in the lane. + +Start's static early hints are another deliberate exception. They are +speculative route-tree hints emitted before loading selects a terminal boundary, +and an already-sent 103 response cannot be retracted. + +The presentation pool is keyed by route ID, not match ID. `stores.ids` defines +active membership and order, while `stores.getMatchStore` obtains the one stable +mutable atom in `stores.byRoute` for a route. That atom contains the route's +presented match or `undefined`. An active route branch contains a route at most +once, so this shape cannot alias two visible matches. When params, search, or +loader dependencies produce a new semantic match ID for the same route, +reconciliation replaces the value in that route's existing atom. Leaving a +route tombstones that atom with `undefined`; re-entering fills the same atom +again. Route components and `useMatch({ from })` therefore keep one subscription +across match generations and A-to-B-to-A membership changes. `ids` is published +before departure tombstones so framework trees stop reading a leaving route +before its atom is cleared. The pool retains atoms for route IDs encountered +during the router's lifetime; it is not an LRU or a cache of match generations. +Semantic caches and loader flights remain keyed by match ID and must not use the +presentation pool as their authority. + +This distinction matters for user code. Once the destination is presented, a +selector can inspect every destination match and observe `isFetching` while the +renderer still shows only the valid prefix. Before that publication, same-ID +matches in the source presentation can expose updated fetching state, but a new +destination-only match is still private. + +Pending entries are flight-free snapshots. They may copy loader data and context +for presentation, but they never become a planning base and never own semantic +resources. + +### Location state + +`stores.location` is the requested location. It can advance before loading +finishes. For foreground client navigation, `stores.resolvedLocation` advances +only after the framework transition acknowledgement settles. Settlement, not a +`true` render result, is what permits navigation completion. Router `status` is +`pending` during that interval and returns to `idle` at completion. A `true` +result separately permits `onRendered` and pending minimum timing. Server +publication and hydration perform their request/initial-load handoffs directly, +as described below. + +### Canonical locations and rewrites + +Initial client and server canonicalization compares `publicHref`, the +browser-facing URL produced by the rewrite contract. Parsed semantic `href` and +rebuilt `href` are not necessarily symmetric: input and output rewrites run in +opposite directions. The client ignores a trailing-slash-only difference while +the server can redirect to the exact browser-facing canonical URL. + +## A lane and its phases + +A lane is one location plus an ordered array of work matches. Its phase is +encoded in TypeScript: + +```text +matched -> contextualized -> reduced -> projected +``` + +### Matched + +Matching establishes route order, params, validated search results, loader +dependencies, match IDs, initial status, and possible semantic reuse. It does +not run `beforeLoad` or grant publication authority. + +A match ID identifies loader/cache compatibility. It is derived from route +identity, interpolated path params, and serialized `loaderDeps`. Other search +values affect loader identity only when the route includes them in `loaderDeps`. + +Matching treats `params.parse`, `validateSearch`, and `loaderDeps` as pure +planning functions. For the same input they must return the same value without +navigating or mutating router/application state. A `loaderDeps` result and its +serialization hooks must also be side-effect-free. These callbacks may be +evaluated more than once; supporting reentrancy from them would add runtime +ownership checks to every planning step without representing a supported use. + +### Contextualized + +Contextualization walks parent to child. For each route it: + +1. computes route context from the completed parent context, +2. handles params/search validation, +3. runs the route's `beforeLoad`, when defined, and +4. merges the result before moving to the child. + +This serial order guarantees that child route context, child `beforeLoad`, and +child loader context cannot observe a partially completed parent guard. + +Route context is synchronous in the public type contract. Its own contribution +is cached on the match as `_ctx`, and match identity includes route identity, +path params, and `loaderDeps`. A same-ID cache hit may therefore reuse that +route-local result, including one produced by a completed preload. The merged +context is still rebuilt parent-first from the current parent's merged context, +the route's `_ctx`, and the current `beforeLoad` result. Reusing `_ctx` must never +reuse an older merged context or `beforeLoad` contribution. + +Server requests have fresh matches and execute route context normally. +Hydration executes each accepted route context locally, stores its `_ctx`, and +then merges transported `beforeLoad` output. Every normal client lane, +including every preload, performs its own contextualization and `beforeLoad` +chain. + +### Reduced + +On the client, eligible loaders and normal component chunks start concurrently. +On the server, loaders reduce before normal render chunks are consumed. +Reduction turns their outcomes into one terminal semantic lane and one cutoff. +No task publishes semantic or presentation state while reduction is in +progress. An eligible successful client loader may independently enter the +off-screen cache at settlement; that admission neither accepts the lane nor +selects its terminal outcome. + +### Projected + +After semantic reduction, client asset hooks derive `meta`, `links`, styles, and +scripts from the final lane. Server projection additionally derives response +headers. Projection cannot replace the selected loader/before-load result. + +Only an owner that remains current after projection may publish. + +## Client planning and the single writer + +Planning is intentionally separate from transaction installation. Lifecycle +events and route execution callbacks can synchronously reenter the router. +Planning callbacks used for params, search, and loader-key derivation are the +pure functions described above and do not create a second reentrancy boundary. + +A planning controller is installed before `onBeforeNavigate`, `onBeforeLoad`, +and matching, invalidating an older synchronous plan. The planner checks its +authority after supported reentrant callbacks and before installing a +transaction. A stale plan exits without installing a transaction or altering +semantic state. + +Once planning succeeds, the router installs one `_tx`. The transaction owns: + +- the destination and its private matches, +- one lane cancellation controller, +- `done`, the transaction-completion promise used by current transaction + waiters and by React to retain the Suspense source tree while a published + pending match is still loading, +- redirect depth for the chain currently being executed, and +- any pending session transferred to it. + +`LoadTransaction`, the lane execution options, and the pending session are +labeled TypeScript tuples. They are deliberately not runtime state machines: +the labels make each slot type-safe for maintainers, while the compact runtime +shape avoids repeating property names throughout the client loader. Changing a +slot means updating the tuple declaration and every typed consumer together; +it must not introduce a second owner or completion signal. + +Throwing `done` from a pending React match does not stop the transaction's work. +Once the lane has reduced and projected, its successful destination is +published inside the framework transition; that render acknowledgement then +allows `done` to settle. `_commitPromise` is the internal promise backing public +history/navigation completion. Current completion resolves it, and a +superseding transaction can chain it forward, but it is also not permission to +publish. These promises describe different wait relationships; `_tx` remains +the only client writer authority. + +Redirect depth transfers only through the exact `_pendingLocation` created by +`followRedirect`. It is not inherited from the previous transaction: a user +navigation that reenters during a redirect starts a fresh chain even though the +redirecting transaction is still alive. + +The latest `_tx` remains installed after it settles. Its presence is writer +identity, not a loading flag; public loading state comes from router `status` +and per-match `isFetching`. + +Installing a successor removes the predecessor's publication authority. The +predecessor must still settle and release everything it owns; cancellation is a +liveness mechanism, not a license to abandon cleanup. + +Commit and cache handoff install the accepted semantic/cache recipients before +releasing replaced resources. Releasing the last flight lease aborts a public +signal and can synchronously reenter user code, so an old generation must never +be released while it still appears to be the accepted owner. The committed lane +is also removed from the transaction's private ownership before publication. + +Every asynchronous navigation or presentation publication checks `_tx` +immediately before the write. Background publication additionally checks the +exact committed base array from which it was derived. Per-match cache admission +is not lane publication: it requires the producing lane's controller to remain +live and the cache entry captured during planning to remain the exact current +entry. Navigation lanes use their transaction controller, while preloads use +their independently owned controller. Private preload redirect continuation +uses the active preload entry as its additional authority. + +## `beforeLoad`: execution and hydration + +`beforeLoad` context is not a cache. + +Client `beforeLoad` only installs a cancellable wait for Promise results. +Synchronous context still crosses an `await` before the cancellation check: +a hook can queue a replacement navigation before its loader is planned. +Promise detection assumes ordinary Promise behavior. + +A completed client preload never stores reusable `beforeLoad` output. When its +loader data enters the route cache, the merged context is discarded; the +same-ID route-local `_ctx` may remain reusable. A later navigation rebuilds the +merged context from the current parent and `_ctx`, then reruns `beforeLoad`, even +when it reuses completed loader data. + +There is one deliberate exception: hydration. + +### Client lanes + +Every navigation and every preload rematches and runs its own serial +`beforeLoad` chain. This remains true for identical concurrent preloads and for +a navigation that targets a still-running preload. A call made with +`preload: true` is never accepted as the navigation's call with +`preload: false`; that call's context and control or terminal outcome stay +private to its speculative lane. This does not isolate the normalized outcome of +a same-ID loader flight that multiple lanes deliberately share. + +`router._preloads` has no semantic adoption role. Its controller entry owns +cancellation, invalidation, and cache clearing and proves that a standalone +preload remained active through normal settlement; successful removal authorizes +private redirect continuation. Its live lane signal is also the final authority +for cache publication, including the microtask window after a loader outcome has +fulfilled. Loader results remain independently reusable: a completed preload may +seed the match cache, and a still-running preload may donate its same-ID loader +flight after the receiving lane has run its own `beforeLoad` and made its reload +decision. + +### Hydration + +The server-resolved prefix is authoritative for the initial document. Hydration +therefore restores transported `beforeLoad` output for the accepted prefix +without rerunning it on the client. This applies to the server-rendered prefix +in selective SSR; the unresolved client suffix follows normal navigation +rules. + +Hydration is not a general `beforeLoad` cache. Its temporary handoff is valid +only for the initial client load of the same document entry and exact committed +owner; rejection, invalidation, or any later load returns to normal serial +execution. The claim also requires the same raw browser href and history-state +object. Finish-time match-ID validation proves that rematching still produced +the accepted prefix; opaque router context and route-tree objects are not +compared. That initial load may transfer the accepted hydration prefix and keep +its transported context while it completes a selective-SSR suffix. A preload +never claims this prefix. Frameworks must start the initial client load before +descendant route code can preload; invoking a preload in the gap after raw +`hydrate()` and before that load is outside the supported handoff protocol. + +## Loader data, cache entries, and flights + +Loader data is designed to be reusable. It is independent from `beforeLoad` +provenance. + +### Completed cache entries + +Successful loader-backed matches can be cached by match ID. Staleness, +invalidation, `shouldReload`, stale reload mode, and GC policy decide whether a +lane uses that data or requires a loader generation. A discoverable same-ID +flight may satisfy that requirement, including when `shouldReload` returns +`true`. + +Every eligible successful blocking loader task from a foreground navigation, +development refresh, or preload attempts cache admission immediately after loader +settlement. It does not wait for component readiness, whole-lane reduction, +projection, commit, or render acknowledgement. The cache receives a +non-terminal copy with merged context removed and an additional flight lease; +the private lane keeps its own match and lease until it commits or is discarded. +If a navigation is superseded, a settled cached generation therefore survives +the lane's lease release, while an unresolved loader has no cache owner and is +aborted when its last consumer releases it. Navigation-produced entries retain +normal navigation staleness and GC semantics rather than becoming synthetic +preloads. + +Background loader candidates remain private until their exact transaction and +committed base authorize background publication. A development refresh may +admit successful loader work while its lane is private, but refresh commit +discards every cache generation instead of preserving stale rematerialization +inputs. + +It is valid for cached loader data to have been produced under context from an +older `beforeLoad` generation. Loaders are the cache boundary; guards are not. +Likewise, a shared in-flight invocation may have started with another lane's +older context. Only a newly started loader invocation receives the current +lane's freshly built context. + +An invalid successful entry may remain in the cache as stale data and preserve +its generation identity, but it can never satisfy freshness and must reload. +Failed, canceled, loaderless, and expired generations do not become reusable +loader-cache entries. + +A private client lane can contain independently successful loader generations +when its eventual terminal outcome comes from `beforeLoad`, validation, another +route, or when a descendant is still loading as the navigation is superseded. +Settlement-time cache admission works even below the eventual render boundary +and does not preserve the private parent chain: merged context and `beforeLoad` +output are cleared. Same-ID `_ctx`, loader identity, and successful loader data +remain reusable by design. + +Hydration retry is the transported-work exception because it did not run those +client loader tasks. There, `loaderData` membership together with +`invalid === false` proves a transported successful generation even when +terminal boundary state is attached to the match. Hydration normalizes that copy +before passing it through the same cache identity and lease rules. + +The dehydrated payload omits `loaderData` both when no loader result exists and +when the accepted result is `undefined`. This deliberately keeps the HTML +payload smaller at the cost of making those states indistinguishable after +transport. Reconstruction preserves the absence and does not treat an omitted +value as reusable loader success during hydration retry. + +The cache may deliberately contain a successful generation with the same match +ID as a committed match. For example, a navigation can finish an ancestor +loader and then be superseded while a descendant is still pending, or a private +lane can produce reusable ancestor data before failing below it while an older +committed generation remains visible. Cache-first matching lets the next lane +use that newer loader generation. Its merged context and `beforeLoad` +contribution have been removed; the merged chain is rebuilt from current parents +and same-ID route-local context before `beforeLoad` reruns. + +Commit removes a cache entry when the accepted render prefix contains that ID, +or when a successful match anywhere in the committed lane contains it. A +non-success descendant below the render cutoff is only structural membership; +it must not evict a newer same-ID cache generation. + +### Same-ID in-flight work + +`router._flights` is the only registry from which a new consumer discovers +same-ID loader work. Every new loader generation registers there, whether it +was started by navigation, preload, or background refresh. A newer generation +replaces the registry entry synchronously. A flight has its own abort +controller; it does not use one consumer transaction's controller as its +lifetime. + +Two facts must remain separate: + +- registry membership means new consumers may join the flight; +- a match lease means an existing consumer keeps the flight alive. + +Registry membership normally owns no lease. A successfully settled generation +may remain discoverable while at least one semantic or cached match owns it. A +non-success outcome removes the exact current flight from the registry as it +settles; existing leases keep that outcome alive only for consumers that already +joined, while later planners start a fresh generation. Releasing the last lease +removes a successful generation only if it is still the current registry entry, +then aborts its controller. Every copied semantic match that retains a flight +must acquire a lease, and every discarded match must release one exactly once. + +There is one short exception to normal zero-lease cleanup. When one navigation +replaces another with the same match ID, the predecessor's loader flight can +reach zero leases before the successor finishes `beforeLoad` and decides whether +to reuse it. While the current transaction is visibly running `beforeLoad` for +that same-ID successor, the flight remains discoverable. The same grace period +applies if any other same-ID flight loses its final lease during that phase. +Outside this phase, merely having a current `_tx` is not enough to retain a +zero-lease flight. + +Loader planning ends the grace period synchronously. The successor either +acquires the discoverable flight or one sweep removes and aborts it. A lane with +no `beforeLoad` reaches loader planning before contextualization yields; an +asynchronous `beforeLoad` keeps the grace period visible until it settles. +Preloads neither create nor sweep this navigation-only reservation. An explicit +`shouldReload: false` declines the flight, while invalidation removes discovery +for selected IDs before starting the replacement load. No extra flag, counter, +or completion promise represents the grace period. + +Releasing a set of matches is deliberately two-phase. First every outgoing +match drops its `_flight` lease and every zero-owner generation not reserved by +the current transaction is removed from the discovery registry. Only after the +entire outgoing set is detached are the collected flight controllers aborted. +Do not interleave one flight abort with detaching later matches in the same +replacement: an abort listener can synchronously reenter, and that load must +observe every logically removed lease and registry entry as already gone. + +A successful accepted match may keep its lease after the loader promise has +settled. This keeps the loader's public `AbortSignal` alive for that semantic +generation. The signal aborts when the last active or cached owner is replaced, +unloaded, expired, or discarded; promise settlement alone does not end it. + +Loader error normalization, including route `onError`, runs once while the exact +flight still has a match lease. The terminal flight leaves the discovery +registry before normalization, so a navigation reentered by `onError` starts a +fresh generation. Releasing every match before a late rejection makes the +generation semantically discarded; abort-triggered rejection must not call user +error hooks. This is an ownership check, not a separate cancellation flag. A +loader that aborts its own flight controller while its match remains owned can +still fulfill or reject normally. + +A planned match holds only the lease for the accepted generation copied from +cache or committed state. After `beforeLoad` and `shouldReload` decide that a +loader will run, it may synchronously acquire the registry's latest different +same-ID generation. It never reacquires its own accepted generation merely to +avoid a requested reload. A blocking reload replaces the accepted lease with +the donor; a background reload keeps accepted data visible and gives the donor +lease to its private candidate. This one lookup covers work started by active +preloads, navigation, and background refresh without scanning those owners. + +Active preload flights need no special handoff. Their speculative matches keep +positive leases until the preload settles or is canceled, so another lane can +discover and acquire the flight without adopting the preload lane. + +Consumers already joined to one loader flight observe its single normalized +outcome, including error and not-found. Per-lane cancellation can stop only that +consumer's wait. A non-success flight retires from discovery at settlement, so +only lanes planned afterward retry. Redirect remains control flow and is never +cached as loader data. + +### Semantic parent chain + +`parentMatchPromise` represents the semantic parent generation, not merely the +currently displayed parent. + +This distinction is essential for mixed reload modes. If a parent is refreshing +in the background while a child reloads in blocking mode, the child borrows the +fresh parent candidate. The final lane must not combine fresh parent data with +child data derived from the stale visible parent. + +The same semantic-parent chain is used by blocking and background loader work. +Task arrays track readiness/outcomes; they are not a second parent authority. + +### Components and lazy route options + +There is no router-level component-promise cache. The browser module cache and +framework lazy-component machinery already cache loaded JavaScript. + +Lazy route loading retains only the authority needed to install lazy route +options, ignore obsolete HMR settlements, and retry failed imports. It is not a +general JavaScript-module cache. + +Lazy option installation has one route-owned promise. Success installs options +only while that promise is still the route's owner. Rejection clears the owner +so a later load can retry, and development refresh can clear ownership so an +obsolete import cannot install options afterward. + +Normal component readiness is part of route readiness, not merely an asset +prefetch side effect. Client loader and normal component work may run in +parallel, and a blocking match becomes successful only after both are ready. +When a client lane installs a `pendingComponent` from lazy options, that +component wakes pending selection once it is itself ready, without waiting for +the normal component. This does not require retaining a component promise on +the match: the route's lazy-option owner and the framework/module loader provide +the necessary work identity. + +Client and server not-found boundary searches settle lazy options on each +candidate route before testing for `notFoundComponent`. A lazy rejection while +locating the boundary does not replace an already selected not-found, but +cancellation or request abort still stops the search. The selected terminal +boundary component is then loaded best effort. + +## Outcomes and failure selection + +Internal work normalizes returned and thrown values into a small closed set: + +```text +success | error | not-found | redirect | canceled/skipped +``` + +Redirect and cancellation are control flow, not committed match statuses. +Error and not-found are terminal semantic outcomes assigned once during +reduction. + +Returned and thrown redirects/not-founds normalize identically. Only an error +invokes route `onError`; if `onError` throws, its value is normalized again and +may itself become an error, not-found, or redirect. +Client and server lanes build a route redirect while its source route still owns +the outcome. Target-construction failures therefore become that route's error, +and a successful client target travels with the redirect so navigation does not +run functional updaters twice. +Client loader flights retain the raw redirect because a flight can be shared. +Each consuming lane materializes that redirect against its own location and +policy before exposing the lane-owned task outcome to settlement and reduction. +Router cancellation and request abort bypass `onError`. Aborting the +`AbortController` exposed to a loader is not by itself proof that the router +discarded the work: a still-owned loader may fulfill or reject afterward, and +that settlement is normalized normally. On the client, zero flight leases prove +that an aborted generation was discarded. On the server, the request signal +proves request cancellation, while the already selected failure/control outcome +proves that an aborted descendant is obsolete. The client calls a discarded +non-result `canceled`, while the server calls it `skipped`; neither is a +publishable terminal state. +The transaction controller exposed to client `context` and `beforeLoad` is +router-owned; route code may observe its signal but must not abort it. A canceled +client lane has therefore already lost writer authority to a successor. +Canceled client lanes release only their private work; the transaction that +superseded them owns presentation and completion. + +The client and server use the same settlement order and renderable-ancestor +rules. + +### Serial phase + +Route context, validation, and `beforeLoad` run parent-first. The first terminal +serial outcome stops descent and wins over later loader or chunk work when the +ancestors needed to render its boundary remain usable. + +An error from the serial phase allows loaders strictly above the throwing route +to finish. A serial not-found allows work through its effective ancestor +boundary, but never past the throwing route. A serial redirect or cancellation +starts no loader work. + +### Parallel loader phase + +Eligible loaders start concurrently. The first loader error or not-found to +settle becomes the provisional failure. The choice follows promise settlement +order, not route order or boundary depth. After settlement, the required render +prefix is checked root-to-leaf. The first failed ancestor without its own accepted +`loaderData` property replaces a deeper failure because that deeper boundary is +not reachable. Locally retained loader data, including an accepted `undefined`, +keeps the ancestor renderable with stale data and preserves settlement +chronology. An `undefined` result reconstructed from SSR is intentionally absent +under the transport policy above. + +A redirect is control flow and wins even after an ancestor loader has already +failed. Reduction therefore waits for started descendant loader work to reveal +a redirect, including a descendant already refreshing in the +background. An error or not-found does not cancel already-started descendants +before this selection completes. Once all relevant work has settled, the first +such failure is used only if no redirect won. The client retains the full +structural branch and releases only work that no accepted semantic or background +candidate owns; the server may abort work below the selected boundary. + +Loader settlement does not immediately make each error or not-found terminal. +As an internal staging state, a failed attempt is reset to `status: 'success'` +and marked `invalid: true`. This lets already-started descendants settle, allows +a descendant redirect to remain control flow, and gives reduction one place to +choose the terminal failure that will be published. Reduction then installs the +selected error or not-found on its boundary. A failed ancestor without accepted +loader data replaces a deeper failure because that deeper boundary cannot +render. Every non-selected failed attempt stays invalid and must reload rather +than becoming fresh cache data. Semantic `parentMatchPromise` snapshots still +expose each loader's own outcome to its descendants. + +No error-over-not-found sort is performed. The selected not-found is moved to +its effective not-found boundary; an untargeted not-found searches eligible +ancestors, while a targeted not-found respects its target. + +A global path miss is terminal by `_notFound` even when the selected match +remains successful and has no error attached. An explicit not-found reduced to +root also attaches its error there. Both forms cap rendering and hydration and +produce a 404 response. + +For a fuzzy global miss, synchronous matching installs the best boundary visible +from eager route options. Before contextualization, client and server feed that +fallback through the same lazy-aware ancestor search used for explicit +not-found outcomes. This prevents serial hooks below the effective boundary +from running and prevents loader tasks from starting there, while retaining the +complete structural branch. The historical deepest-route-with-children fallback +still applies when no route supplies a not-found component. When `notFoundMode` +is `'root'`, the search is bypassed but the same execution cap applies at root. + +### Chunk readiness + +Normal route chunks needed before the selected cutoff are awaited. Although the +work may start concurrently, readiness outcomes are consumed root-to-leaf. The +first relevant chunk error replaces a deeper selected serial or loader failure +because that boundary is no longer reachable; a redirect from relevant +readiness remains control flow. + +The resolved boundary is retained while that selected failure remains current. +A later lazy retry in the same lane cannot expand the required prefix after its +readiness has already been consumed. +Terminal boundary-component preloading is best effort during normal loading; it +does not start a second failure-selection algorithm. + +On the client, lazy/chunk readiness starts independently of loader completion +and notifies pending selection when it settles. A `pendingComponent` installed +by lazy options can therefore become the visible boundary while an eager loader +is still unresolved. + +### Projection errors + +Client `head` and `scripts`, plus server `head`, `scripts`, and `headers`, are +decorative with respect to route control flow. They run only after semantic +reduction. Rejections are logged and swallowed; they never replace the chosen +loader/before-load outcome or trigger another boundary-selection pass. + +The implementation should stay this simple. If a proposed fix requires a new +error candidate list, ranking pass, boundary score, or convergence loop, it is +almost certainly rebuilding the discarded complex architecture. + +## Terminal commit and lifecycle + +A successful client lane remains private through projection. At commit, one +framework transition publishes semantic matches, cache changes, and route +lifecycle callbacks. + +The client order is: + +1. publish final matches/cache and run `onLeave`/`onEnter`/`onStay`, +2. emit `onLoad`, then `onBeforeRouteMount`, while the transaction is current, +3. wait for the framework transition acknowledgement to settle, +4. publish `resolvedLocation` and `idle`, +5. emit `onResolved`, and +6. emit `onRendered` only if the acknowledgement was `true` and the same + transaction is still current. + +Each reentrant callback can start another navigation. Checking that the +transaction is still current after each publication boundary suppresses stale +later events. In particular, an `onResolved` navigation suppresses the old +transaction's `onRendered`. + +Route lifecycle callbacks are invoked directly and are expected not to throw. +The coordinator does not carry a second error-handling path for callback +failures. All `onLeave` callbacks run before callbacks for retained or newly +entered routes; the relative ordering of `onEnter` and `onStay` is not a public +contract. + +Server render results are published request-locally and run the documented +route `onLeave`/`onEnter`/`onStay` callbacks against the previous server +generation after final matches have been installed. Server redirects do not +publish a render lane or run those callbacks. + +Terminal outcomes do not change route membership. Client and server state keep +the complete structurally matched branch, lifecycle compares that full branch, +and renderers derive the visible prefix from match status. Projection likewise +stops after the terminal match. SSR transport may serialize only that terminal +prefix because the client can reconstruct hidden structural descendants without +executing them. + +## Pending presentation + +Pending UI is presentation, not partial semantic commit. + +An exact successful match remains successful while `beforeLoad` or a blocking +loader revalidates it only when the same successful, non-not-found prefix is in +both the transaction's committed base and its starting presentation. +`isFetching` exposes that work without replacing its rendered UI. A cache-only +success, a different match ID, or a success hidden below a terminal boundary has +no retained presentation and remains eligible for pending UI. Explicit +force-pending invalidation already changes the committed generation to pending +and therefore overrides retention. + +The initial pending offer for a fuzzy not-found lane waits until lazy route +options resolve its boundary. This prevents a provisional ancestor boundary +from replacing the mounted presentation before ownership moves to a lazy child. + +The first unresolved boundary is the only pending candidate. Its route or the +router default must provide a pending component, and its effective `pendingMs` +must allow presentation. Core does not skip an ineligible ancestor to expose an +unrelated deeper fallback. + +A successful route without a loader still participates in chunk readiness and +projection, but is not changed back to pending merely because a descendant has +blocking work. + +When pending is offered: + +- `stores.matches` receives a flight-free snapshot of the complete destination + lane; +- the selected boundary is marked pending; +- descendants remain observable in state; and +- the renderer stops at the boundary. + +There is one pending session in `router._pending` and one absolute deadline: + +```text +reveal deadline -> exact render acknowledgement -> minimum-visible deadline +``` + +The session also remembers the pending component identity. An active client +lane loading a lazy route chunk can install a more specific `pendingComponent` +after the default fallback has already rendered. Once that pending component is +ready, core re-offers the same lane so the framework can replace the fallback +without creating another pending session or deadline. + +The reveal deadline is anchored to the transaction's lane-level `startedAt`. +Discovering lazy pending options later, advancing to another boundary, or +retrying the offer does not restart `pendingMs`. If the absolute deadline is +already past when a pending component becomes eligible, core publishes it in +the current turn instead of introducing a `setTimeout(0)` race. + +`pendingMinMs` starts only after the framework confirms that the pending +publication rendered. A superseded publication that never rendered creates no +minimum-visible obligation. + +Core considers actual non-success matches and an exact pending presentation in +route order. An earlier ineligible successor boundary therefore retires the old +clock without replacing the painted fallback, and a later occurrence of that +old boundary in the same transaction cannot resurrect its minimum. + +Hydration or a redirect can leave an already visible pending presentation +without a pending session that owns its original acknowledgement. When there is +no competing semantic boundary, core conservatively treats that presentation as +rendered and starts its minimum from the takeover time instead of delaying its +reveal again. + +A successor may take over timing only when its selected boundary has the same +match ID. It keeps the existing deadline but republishes a full snapshot from +the successor, so pending UI cannot show stale search, params, or context from +the superseded navigation. Normal route matches preserve position with their +IDs; the deprecated relocatable `notFoundRoute` is not given separate positional +session identity. Changing the selected boundary discards the old session. + +## Exact framework acknowledgement + +`startTransition` returns a promise whose boolean result has a precise meaning: + +- settlement means the framework transition can no longer block navigation + completion; +- `true` means the exact requested match publication rendered; +- `false` means core must finish without emitting `onRendered` or starting a + pending minimum based on that publication. + +Framework transition wrappers are controlled adapters. Supersession settles an +older acknowledgement as `false`; core does not retain a prior presentation or +install a compensating restoration path for wrapper failure. + +React cannot await `React.startTransition` directly. Its adapter keeps one +router-owned acknowledgement tuple, and `Matches` settles that tuple from a +layout effect. A new expected publication first settles the previous receipt as +`false`, then stores the exact offered array before the transition callback +runs. This ordering matters because publication can invoke a route lifecycle +callback that synchronously starts and publishes a successor navigation. +Installing the expectation after the callback would let the superseded +publication replace the successor's receipt. + +An already-settled router mounted into React uses the same acknowledgement slot +for its initial `onRendered` event. It therefore emits only after the exact match +tree and its descendant layout effects have committed, rather than from the +earlier history-subscription effect. + +While a receipt is pending, the aggregate match subscription selects the exact +offered array instead of reconstructing an equivalent presentation. The layout +effect acknowledges only that reference. A suspended older render can therefore +never satisfy a newer receipt merely because its IDs or statuses look the same. +No generation counter or structural signature is needed. + +Solid awaits its transition, and Vue awaits its render tick. For an +already-settled Solid mount, history subscription remains before the route tree +while a post-match notifier emits the initial `onRendered` event after +descendant mount effects. + +React assumes one provider and one router. Keeping the tuple on that router lets +the render tree and core share the exact same receipt without component-local +generation state, structural signatures, or router-swap machinery. + +Every core write passed to `startTransition` must notify the aggregate matches +store even if much of the lane is structurally reused. Suppressing the write can +strand the acknowledgement promise. + +## `isFetching` and background reloads + +`isFetching` is public presentation state. It is observable during normal +`beforeLoad`, normal loaders, and background loader refreshes. + +For a foreground navigation this means the destination match exposes its phase +once the destination lane is presented. Before pending publication, a +destination-only match remains private; a same-ID source match can be reconciled +to the active phase earlier. Background reloads operate on the already +presented lane and therefore expose their phase immediately. + +A background reload keeps successful loader data visible while a private +candidate runs. The full presented lane remains installed and the affected +match reports the active phase. Completion clears fetching state whether the +candidate publishes, fails, or is superseded. A successor may join its loader +flight, but never adopts the private candidate lane. + +Background loader and chunk work may begin and settle while the foreground +publication renders. Background reduction, projection, and publication do not +start until the foreground transition acknowledgement settles. A fast refresh +therefore cannot replace the exact generation that the framework still needs to +acknowledge. + +When background tasks exist, execution creates their settlement observer +eagerly alongside foreground reduction and retains that promise in the lane +result. `runBackground` consumes the same settlement chronology after the +foreground acknowledgement. Recreating the observer then would process work +that already settled by task attachment or iteration order and could change +which error, not-found, or descendant redirect wins. Retaining this promise +preserves the observed settlement order; it does not grant permission to publish +or define when the lane is complete. + +Background work starts from an exact committed base. Before projection it uses a +fully private lane, including clones of untouched matches, so asynchronous asset +hooks cannot mutate committed objects without a store publication. + +Final background publication requires both: + +```text +router._tx is the owner +router._committed is the exact base +``` + +If either check fails, the entire staged lane is discarded and all candidate +and clone resources are released. A successful background publication replaces +the semantic/presented lane atomically but does not change location, foreground +status, or foreground navigation lifecycle events. + +Foreground completion does not join background publication. After the +foreground acknowledgement, the refresh continues independently and may publish +before or after `resolvedLocation`, `idle`, and `onResolved`. Active work +remains publicly observable through `isFetching`; any later publication still +requires the owner/base identity check. + +An error or not-found from background work also stays private through reduction +and projection, then may atomically replace the successful base with the full +matched branch carrying its terminal boundary. Hidden descendants retain route +membership, so background publication does not synthesize leave/enter lifecycle +events. It is not published incrementally. + +Background redirects use the same control-flow and ownership rules as foreground +redirects. A losing background lane cannot redirect. + +## Invalidation, cache clearing, and development refresh + +Invalidation creates a new semantic generation and reloads through the normal +transaction path. It does not turn `stores.matches` into a planning lane. + +Filtered invalidation evaluates committed, cached, active-transaction, and +active-preload matches and collects the selected match IDs. Every committed and +cached generation with one of those IDs is made invalid. Cached matches are +already settled successes, so their data owner is marked invalid in place. +Matching active preload owners are retired first, which prevents older +speculative work from clearing that stale mark or publishing fresh cache data; +the lane signal remains the publication fence if its loader outcome already +fulfilled. The loader discovery entry is also detached before the superseding +load. Unselected preload lanes remain active. This ID-wide rule prevents a +cache-first or in-flight same-ID generation from escaping invalidation merely +because a different generation was the one passed to the filter. Route context +retains same-ID cacheability across this replacement and needs no separate +invalidation marker. + +Invalidated successful data may remain visible until pending or terminal +publication, depending on reload mode. Error/not-found generations reset through +the same loading protocol rather than becoming cache successes. + +Cache clearing first snapshots every selected cache match and active preload so +a throwing public filter changes no authority. It then prunes both authorities +and directly releases every discarded match lease. When the last lease is +discarded, cache clearing removes the discovery entry +instead of preserving the normal zero-owner navigation handoff. Only after all +leases and discovery entries are detached does it abort the collected flight and +preload-lane controllers. A public loader signal can synchronously reenter from +its abort listener; that reentrant load must observe the cleared authorities and +every removed lease as already detached. Unselected concurrent preloads keep +shared flights discoverable, and every later cache admission must still have a +live producing-lane signal and pass the per-match cache-entry identity check +captured during planning. Cache clearing does not cancel the current transaction, +so an active navigation loader that settles afterward may establish a new cache +generation. Invalidation is the API that replaces active semantic generations. + +Development refresh is deliberately aggressive about reuse. It removes all +loader flights from discovery, discards active preloads and cache entries, and +rematches with committed/cache reuse disabled so obsolete params, context, +loader data, or projected assets cannot seed the refreshed lane. Selected cache +and preload resources are detached before their controllers are aborted. + +Before publication, a failed or superseded refresh leaves the painted +presentation alone because its candidate is still private. Once published, the +refresh is the accepted semantic and presentation generation even while exact +framework acknowledgement is pending. Publication uses the ordinary commit +ownership transfer, releases the replaced generation immediately, consumes any +obsolete hydration handoff, and retains no prior cache or presentation +checkpoint. + +A rapid successor refresh rematerializes again, settles the older framework +receipt as `false`, and owns convergence and public completion through the same +`_tx` and `awaitCurrent` chain as ordinary navigation. The older transaction +releases only private background work that did not transfer. No refresh has +authority to restore a predecessor or resolve a successor's commit promise. + +## Speculative preloading + +A preload uses the same match, contextualize, reduce, and project phases as +navigation, but it never becomes `_tx` and never publishes match presentation. + +Its match/cache ownership effects are limited to: + +- joinable same-ID loader flights; and +- individual successful preload loader generations entering the loader cache as + they settle. + +A preload can also install durable lazy route options through the separate +route-chunk owner described above. That is route definition readiness, not +authority over a completed match lane or `beforeLoad` result. + +Preload lane-local matching, route context, validation, cancellation, and +`beforeLoad` outcomes do not become authority for another preload or a later +navigation. Consumers that join its same-ID loader flight nevertheless share +that flight's normalized outcome. After a normal standalone preload redirect, +the private chain continues only if that lane's controller was still present and +was successfully removed from `_preloads`; replacing an unrelated `_tx` does not +suppress it. The chain remains depth-bounded, never follows `reloadDocument`, +and never publishes presentation or history. + +The public `preloadRoute` result describes the speculative lane, not merely its +cacheable subset. An error or not-found therefore resolves with the terminal +match array while any eligible successful loader generations can still enter +the cache. Cancellation or control flow that does not yield a reusable lane can +resolve `undefined`. + +Each preload loader task uses the shared settlement-time cache admission rule: +it compares the current cache entry for its match ID with the entry captured when +that task was planned. It cannot overwrite a cache generation installed since +that plan. Admission does not wait for whole-lane success. A distinct successful +generation may coexist with an older committed same-ID generation; this changes +future planning precedence, not current presentation. A duplicate sharing the +already accepted flight is discarded. + +`preloadRoute` also works on a server router. It runs the same speculative +protocol with `preload: true`, can return matches and populate that router's +loader cache, and does not replace the request's location, committed lane, or +presentation. Normal request loading still uses the request-local server lane +and calls its hooks with `preload: false`. + +## Server loading and request lifetime + +Server loading is request-local, so it does not need the client `_tx` +coordinator. It still uses the same semantic phases, context ordering, outcome +normalization, settlement-order failure selection, semantic parent promises, +and projection behavior. + +Each server match gets the public controller passed to its callbacks. The +request signal—not the mere fact that a callback aborted that controller—is the +request-liveness authority checked across contextualization, loaders, chunk +readiness, terminal boundary readiness, and projection. A request abort cancels +the whole lane. A loader error or not-found does not abort already-started +descendants before selection, so a later descendant redirect can still win. +After selection, applying the terminal boundary aborts the hidden suffix that +the result no longer owns. Redirect aborts the whole request-local lane. + +The request signal also governs the surrounding request pipeline. The generic +handler races manifest lookup, route loading, custom dehydration, and the +handler/render callback. Start applies the same rule to entry and router +resolution, middleware, manifest work, and redirect finalization. An abort can +therefore settle the handler during every awaited phase rather than waiting for +user code that ignores its signal. + +A raced promise may still fulfill after abort. If that late value owns an SSR +stream, the race disposes it instead of allowing it to regain response or +cleanup authority. Other user promises may continue executing, but after abort +they cannot publish a response or inject SSR output. If cleanup occurs while +application dehydration is awaited, dehydration returns before starting +serialization; injection and serialization completion also ignore later work. + +A server result has one of two forms: render status plus matches, or an HTTP +redirect. Redirects short-circuit framework rendering and preserve their real +status, `Location`, and custom headers. + +Projection parity is intentional: server `head`, `scripts`, and `headers` use +the final reduced lane and loader data. As on the client, failures are logged and +swallowed. + +### Stream cleanup handoff + +Until a response is accepted, the request handler owns router SSR cleanup. A +non-stream response, redirect, or failure leaves cleanup with the handler. An +accepted SSR stream transfers that ownership to the response and is immediately +bound to the request signal, so an abort after handoff still disposes it. + +Disposal is idempotent and severs router SSR ownership before best-effort body +cancellation. This order matters because a custom or framework stream may ignore +or indefinitely delay cancellation. Replacing a stream response, resolving a +redirect from it, or stripping a HEAD body disposes the old stream under the +same request signal before accepting the replacement. + +Framework renderers connect request abort to their upstream renderer as well as +the router stream transform. Normal completion, downstream cancellation, +request abort, renderer failure, and stream lifetime timeout all converge on the +same cleanup authority; none creates a second response owner. + +Once a server lane is accepted for rendering, its match controllers are +registered with that same SSR cleanup authority. They remain live through +dehydration and response streaming so deferred loader work can finish while the +response is active, then abort when the response or stream lifetime ends. + +## Selective SSR + +SSR policy is the first parent-to-child serial step, before route context, +params/search validation handling, and `beforeLoad`: + +- `true` runs server `beforeLoad` and loaders, loads render chunks, projects + assets, and renders the component. +- `'data-only'` runs server `beforeLoad` and loaders and projects `head`, + `scripts`, and `headers`, but does not render that route component. +- `false` skips server `beforeLoad`, loaders, and component chunks. The first + `false` boundary still projects `head`, `scripts`, and `headers` for its server + shell, then projection stops before descendants that inherit `false`. Route + context and params/search validation still run, so their errors remain real + server outcomes. + +A parent restriction cannot be relaxed by a child: `false` remains false, and a +`'data-only'` parent caps a child requesting `true` at `'data-only'`. + +If a functional `ssr` option throws, the inherited/default policy is established +before calling it. The failure therefore retains the correct boundary +renderability instead of leaving `ssr` undefined. An error or not-found from +the policy still reconstructs route context for its boundary. If route context +also fails, the original policy failure keeps precedence. Redirects remain +control flow and skip route-context reconstruction. + +Shell mode resolves and dehydrates the root semantic match while the presented +server lane may include the first client-only pending boundary and its +descendants. This permits server and initial client presentation to agree. + +## Hydration handoff + +Hydration reconstructs server work; it does not run a competing hydration +loader. While reconstruction is asynchronous, its controller is `_preflight`. +Under the framework-supported startup order, `RouterClient` finishes hydration +before mounting the provider that starts the initial client load, so no client +transaction or descendant preload competes with reconstruction. Core does +not enforce that ordering as a blanket guard. A navigation can supersede hydration +by installing a new `_preflight`; a preload started directly in this gap is +unsupported rather than blocked. + +The identity of `_preflight` proves that reconstruction is still current. A +replacement installs itself before aborting the prior controller. The same +controller interrupts asynchronous application hydration and chunk work, and +every asynchronous phase checks that identity before mutating or publishing. + +Once hydration has accepted a semantic prefix and is ready to publish it, +`_preflight` is no longer the right authority: no planning operation is in +progress, but the first normal client load may still need to continue that +prefix. Hydration therefore installs `_handoff`, a temporary two-phase transfer, +and detaches its controller from `_preflight`. The handoff is the one owner that +can decide whether the initial load may continue the prefix; it is not a second +completion promise or a general cache. + +The client router is fresh when hydration begins. Application `hydrate` hooks +may restore external integration state or update router options, but must not +call router loading or preloading before reconstruction finishes. Core does not +guard those calls; this is part of the supported startup order. + +The high-level process is: + +1. install serialization adapters and application-dehydrated data, +2. match a fresh candidate lane for the browser location, +3. accept the identity-compatible serialized lane as the ordered prefix + guaranteed by the document protocol, +4. copy server loader data, `beforeLoad` context, terminal state, and effective + SSR policy into private candidates, and install each transported effective + SSR value on its route so a functional server policy is not re-evaluated, +5. start exactly the chunks required by the accepted prefix and any selected + terminal boundary concurrently, then consume their outcomes in route order + so the earliest failed position can retire its suffix without waiting for + irrelevant descendants, +6. rebuild route context parent-first, +7. project client `head` and `scripts` through the same projection + function used after a normal client load, and +8. publish accepted semantic work and the complete structural presentation. + +Hydration relies on the framework transport contract. For normal and selective +SSR, the data was produced for the exact document URL by the same route build, +and its serialized matches form an ordered prefix of the client lane. An SPA +shell uses the same prefix protocol for its root-only payload; the framework is +responsible for serving a shell that applies to the document. Core does not +serialize a second URL identity. Instead, hydration bounds reconstruction to +the local lane and validates every transported position with a compact match ID. + +A mismatch ends the accepted prefix and leaves the local suffix for normal +client loading. A longer server lane is accepted only through a local global +not-found boundary that already caps the branch; otherwise no transported +prefix is accepted. A terminal server error, not-found, or global not-found caps +client execution so omitted descendants do not run. The client still creates +those descendants as structurally matched but unexecuted matches. A loaderless +descendant may initially have `status: 'success'`, so status alone does not prove +that hydration ran its context or route hooks. Terminal hydration loads the +chunks required by the selected error/not-found boundary, but not normal +component chunks below it. Neither route context nor projection runs below the +transported boundary. +The transported terminal route remains authoritative even when its effective +SSR policy is `false` or `'data-only'`: route context or validation was still +allowed to fail on the server, so hydration must not turn that outcome into an +unresolved client-only route. Before-load and loader work remain skipped there +according to the server policy. + +Every executed context, `head`, and `scripts` hook nevertheless receives the +complete locally matched candidate lane. Hook arguments describe structural +membership; the accepted prefix describes execution authority. + +If a required chunk or route-context reconstruction fails, hydration preserves +only the successfully reconstructed committed prefix. The public presentation +still contains the complete locally matched lane, so a +terminal server boundary does not make route membership disappear while its +client reconstruction is retried. Eligible transported loader successes cross +the normal loader-cache boundary with merged context and `beforeLoad` +contribution removed. Because `resolvedLocation` remains unset, normal +initial client loading retries the failed boundary or context and finishes the +unresolved suffix. + +For a non-terminal selective-SSR handoff, the semantic committed prefix is the +complete contiguous transported prefix accepted as resolved. The first +`'data-only'` match is the presentation continuation boundary, but it does not +truncate semantic adoption: later transported successful data-only matches are +also committed and keep their server loader and `beforeLoad` results. A `false`, +pending, or otherwise unresolved match is the first semantic continuation +boundary and is not committed. Presentation can still contain the complete +candidate lane and marks its first presentation boundary pending as needed. In +particular, a shorter non-terminal server payload ending in a pending +`ssr: false` match is a valid selective-SSR handoff: hydration accepts the +resolved ancestors, presents the complete local branch, and lets the normal +initial client load execute from that client-only boundary. + +For a successfully reconstructed terminal handoff, transport remains +prefix-capped but committed and presented membership use the complete locally +matched branch. Matches below the terminal boundary remain unexecuted and +hidden; they own no transported `beforeLoad` result or loader data. This keeps +public membership and lifecycle stable without increasing the SSR payload or +loading unreachable client chunks. If reconstruction fails, only the accepted +prefix is committed as described above; the complete branch remains +presentation, not semantic reuse authority. + +Only the subsequent normal client load may transfer the whole hydration +prefix, and only while the exact committed-prefix owner, raw history-state +object, browser href, and live hydration controller remain current with no +active transaction. Core captures the raw browser href and history-state object +so a reentrant navigation from an initial lifecycle event cannot hand the old +document's work to a successor location. Finish also validates the transported +match IDs against the newly matched lane. Core does not coordinate speculative +work started between raw `hydrate()` and that load; framework adapters own the +supported ordering. + +The two-phase transfer proceeds as follows: + +1. Before public navigation events or matching, the initial client-load planner + probes the handoff without consuming it. +2. It installs its own `_preflight`, emits the events, matches a private lane, + and asks the handoff to finish the transfer. +3. Finish revalidates handoff identity, transaction absence, hydration + controller liveness, captured location identity, and the exact committed + owner. +4. On rejection, the handoff clears itself before aborting its controller, + so abort listeners cannot reenter and claim a rejected handoff. +5. On acceptance, the accepted matches replace the planner's private copies. A + successfully reconstructed terminal handoff owns the complete local branch, + even though its SSR payload was prefix-capped, so it has no local suffix to + remove. For a non-terminal handoff, the remaining suffix stays in the lane + and transfers to the hydration controller so one signal owns the + continuation. +6. The handoff remains available across synchronous reentrancy until the + current load installs `_tx`. That load installs `_tx` before clearing the + handoff; stale planners may release only their own private work. + +This ordering closes the gap between hydration publication and client +transaction installation without making the handoff an independent completion +authority. If reconstruction is superseded before publication, the `_preflight` +identity check aborts its private work. If the published handoff becomes +incompatible, its failed identity check retires the hydration controller +and starts normal client loading from a fresh preflight. + +Development refresh rematerializes instead of claiming the prefix. Its +transaction carries the existing handoff only until refreshed matches publish; +that one-way publication consumes the handoff and retires the hydration +controller before lifecycle reentrancy. A refresh superseded before publication +leaves the handoff for its rematerializing successor. + +Generic framework `RouterClient` components signal streaming hydration +completion after the hydration attempt settles, including rejection. This +finally-style handoff allows bootstrap globals to be removed once the server +stream has also ended without stranding the stream on a hydration failure. + +Each framework owns one module-level hydration promise for the document. The +SSR protocol provides one global bootstrap and one `RouterClient`; additional +client-only routers use `RouterProvider` and do not independently consume that +bootstrap. The promise deduplicates framework rendering/replay only. It replaces +neither `_preflight` reconstruction authority nor `_handoff` +continuation authority. + +## Change checklist + +The detailed sections above are the source of truth. Use this shorter checklist +to find the failure modes a change needs to test; do not duplicate the full +algorithm here. + +### Publication and reentrancy + +- Does every asynchronous write recheck its exact owner immediately before the + write: `_tx`, `_preflight`, `_handoff`, an active-preload controller, or the + request signal? +- Does a background publication check both its `_tx` and the exact `_committed` + base from which it was derived? +- If an abort, lifecycle callback, or store publication can synchronously + reenter, are replacement owners installed and discarded resources detached + before that callback can run? +- Does framework acknowledgement settlement still gate resolved/idle + completion, with only an exact rendered publication producing `true` and + enabling `onRendered` or `pendingMinMs`? + +### Matches, loaders, and cache ownership + +- Are `_committed` semantic state and `stores.matches` presentation kept + separate? Are match-ID cache compatibility and route-ID lifecycle identity + also kept separate? +- Does every normal client lane run its own `beforeLoad` chain? Hydration is + the only completed-work exception; preloads may share loader data or flights, + but never their merged context, `beforeLoad` result, or control flow. +- Is flight discovery separate from lease ownership? Does every copied owner + acquire exactly one lease and every discarded owner release it exactly once? +- Are registry entries and all discarded leases detached before any collected + controller is aborted? +- Do cache admission, invalidation, and clearing preserve the intended + generation identity, including the rule that an unexecuted descendant below a + cutoff cannot evict a newer same-ID cache entry? +- Does each child `parentMatchPromise` follow the fresh semantic parent + generation rather than the visible stale parent? + +### Outcomes and presentation + +- Do error/not-found selection, required ancestor readiness, component chunks, + and descendant redirects still reduce to one final outcome? +- Are redirects materialized while their source route owns target-construction + errors, with shared flights retaining only the raw redirect and each lane + building its own target once? +- Does cancellation require both exact signal identity and proof that the signal + is aborted, and does a canceled lane release every private background + candidate without changing presentation? +- Does pending or terminal publication retain the complete structural branch + while rendering and outputs apply their relevant cutoff, including the + selective-SSR hydration asset-prefix exception? +- Are pending snapshots flight-free, and do reveal/minimum timing remain owned + by one transferable pending session? +- Do projection failures remain logged and swallowed, and does `isFetching` + clear on every success, failure, cancellation, and supersession path? + +### Server and hydration lifetime + +- Can request abort settle every awaited server phase, and can late work no + longer publish a response or injected output? +- Does exactly one owner perform SSR cleanup, with router ownership released + before best-effort stream cancellation? +- Does hydration validate transported match IDs, execute only the accepted + prefix, retain the complete local branch, and preserve any verified + `'data-only'` asset prefix? +- Does the initial-load handoff revalidate its controller, browser history entry, + committed owner, and rematched IDs? Do framework adapters still obey the + no-preload startup gap described above? + +If a fix fails one of these checks, consolidate ownership instead of layering a +special case on top. + +## Testing changes + +Tests must assert public behavior, not the internal tuple shape, phase tag, +private promise, timer, or field name used to implement it. + +Useful assertions include: + +- rendered pending/error/not-found content and the boundary that rendered it; +- the complete public matches array and `isFetching` transitions; +- loader/before-load call counts, contexts, parent promises, and abort signals; +- navigation completion, lifecycle callbacks, and their surrounding router + events, without asserting a relative `onEnter`/`onStay` order; +- preload/cache reuse observable through user loader calls; +- HTTP status, headers, redirects, and absence of renderer invocation; +- request-abort settlement, late-stream disposal, and single stream cleanup; +- hydration output, completion on rejection, and absence of client reruns below + server terminal boundaries; +- absence of stale data/assets after supersession; and +- framework acknowledgement tied to the actual rendered destination. + +While `tx.done` suspends a pending React destination, React may retain the previous +source tree in the DOM but hide it. Pending tests should assert visible user +content, not physical absence of the old route's nodes. + +When testing a boundary, give root, parent, and child visibly distinct output. +An assertion such as `/Not Found/` or `/Error/` can pass at the wrong boundary +and is not sufficient. + +Run focused category tests while changing the loader, then affected core and +framework unit/type suites, selective-SSR E2E tests for server/hydration changes, +and the bundle-size benchmark for any client runtime change. diff --git a/packages/router-core/benchmarks/ssr-streaming/.gitignore b/packages/router-core/benchmarks/ssr-streaming/.gitignore new file mode 100644 index 0000000000..6628455c0a --- /dev/null +++ b/packages/router-core/benchmarks/ssr-streaming/.gitignore @@ -0,0 +1 @@ +/results/ diff --git a/packages/router-core/benchmarks/ssr-streaming/README.md b/packages/router-core/benchmarks/ssr-streaming/README.md new file mode 100644 index 0000000000..bda5d4ee12 --- /dev/null +++ b/packages/router-core/benchmarks/ssr-streaming/README.md @@ -0,0 +1,162 @@ +# SSR streaming benchmark + +This harness compares two Git revisions of router-core SSR streaming. Transform +runs validate byte count, SHA-256 digest, markers, selected transport API, and +lifecycle counts. Isolated transform timing includes hashing and marker scans; +warm transform timing moves those two checks into preflight requests. +Production-owner suites validate byte count, final owner state, and the 64 KiB +output chunk cap. Isolated owner timing includes hashing; warm and soak suites +use one separate digest-validating preflight per implementation. + +Generated JSON and Markdown summaries stay under `results/` and are ignored by +Git. CPU profiles default to a `*-profiles/` directory beside the configured +JSON output. `--profile-dir` overrides that location. + +## Quick start + +Compare the latest `origin/main` with `HEAD`: + +```sh +node packages/router-core/benchmarks/ssr-streaming/run.mjs \ + --origin=origin/main \ + --candidate=HEAD \ + --suite=common \ + --warmups=20 \ + --iterations=30 \ + --batch-requests=1000 \ + --output=packages/router-core/benchmarks/ssr-streaming/results/common.json +``` + +Use `--candidate=worktree` while testing an uncommitted optimization. Final +comparisons should use Git revisions so the result can be reproduced. + +Run the focused queue-mechanism benchmark with: + +```sh +pnpm --dir packages/router-core exec vitest bench \ + tests/hydrationQueue.bench.ts --run +``` + +## Suites + +| Suite | Purpose | Default measurement | +| ----------------- | ------------------------------------------------------------------------ | ------------------------------------------------- | +| `smoke` | Short raw, fast, and merge check | One isolated process per cell | +| `common` | Normal 1–64 KiB hydration payloads across React, Solid, and Vue profiles | Warm paired batches | +| `safe-points` | Many small React and Solid renderer records | Warm paired batches | +| `coalesced-close` | React script safe points inside large renderer chunks | Warm paired batches | +| `small-memory` | Small React raw, fast, and merge responses | Isolated processes with forced GC | +| `primary` | Large hydration, closing-tag, renderer-record, and backlog stress | Isolated processes with forced GC | +| `source` | Large flat and rope router sources | Isolated processes and direct `encodeInto` probes | +| `strings` | Large flat and rope renderer string records | Warm paired batches | +| `owner` | Production hydration owner and maximum legal backlogs | Isolated processes with forced GC | +| `owner-warm` | Production hydration owner latency | Warm paired batches | +| `owner-soak` | Production hydration owner retention after repeated requests | Post-return forced-GC checkpoints | + +Filter cells with comma-separated `--scenario` and `--mode` values. Isolated +suites also accept `--implementation` and `--runs`. Warm suites accept +`--warmups`, `--iterations`, and `--batch-requests`. + +The `coalesced-close` suite keeps hydration waiting until renderer EOF. Its +1 KiB and 64 KiB filler follows a script in one chunk, so returning at that +script can repeat the document-close search over the remaining bytes. It also +covers a close in the next chunk and a late-script control with little content +left to rescan. The filler contains complete HTML elements. An empty final +input record prevents source prefetch from finishing hydration before the +coalesced content drains. These cases measure repeated scanning within one +chunk; `safe-points` continues to measure separate small renderer records. + +The `owner-warm` suite requires both revisions to contain +`packages/router-core/src/ssr/hydrationScripts.ts`. Older `origin/main` +revisions do not contain this file. After the owner exists in a committed +baseline, use `--origin=HEAD --candidate=worktree` for later changes. + +During the initial owner introduction, run an isolated worktree-only cell: + +```sh +node packages/router-core/benchmarks/ssr-streaming/run.mjs \ + --candidate=worktree \ + --suite=owner \ + --implementation=worktree \ + --scenario=hydration-owner-16x1k \ + --runs=1 +``` + +For example: + +```sh +node packages/router-core/benchmarks/ssr-streaming/run.mjs \ + --origin=HEAD \ + --candidate=worktree \ + --suite=common \ + --scenario=hydration-32k \ + --warmups=30 \ + --iterations=50 \ + --batch-requests=2000 \ + --output=packages/router-core/benchmarks/ssr-streaming/results/candidate.json +``` + +## What the numbers mean + +Warm suites load both implementations into one Node process. They alternate which +implementation runs first for every request pair and at every batch boundary. +The warm-up count is per implementation: each warm-up iteration runs one +request against both revisions. Timed samples are complete request batches. + +For isolated transform cells, `elapsedMs` includes incremental hashing and +marker validation. For warm transform cells, it measures a byte-counted drain +after validated warm-up requests. `wallElapsedMs` also includes synthetic +request setup and lifecycle checks. Merge cells include source creation by the +fake producer. + +Isolated suites start a new Node process for each cell. Memory values are +sampled high-water deltas above a forced-GC baseline, not exact allocation +peaks and not proof that a leak is absent. + +Treat changes below 1% as inconclusive unless several independent processes +repeat the result. In soak output, heap, external, and ArrayBuffer checkpoints +describe retained JavaScript-visible memory after forced GC. RSS is allocator +high-water behavior and is not, by itself, evidence of a leak. Use unit and +integration tests for backpressure, cancellation, abort, timeout, Unicode, and +split-boundary correctness. The throughput harness does not replace those +tests. + +## Scope and limits + +- Normal transform suites use `Uint8Array` renderer records. The `strings` + suite isolates Node renderer string records. +- React uses the `script-close` safe point, Solid uses `record-end`, and Vue + uses only the universal router boundary, document close, and EOF points. +- The fixed boundary suffix lets old and new implementations consume identical + bytes and matches the production transport. +- The worker supplies the legacy `origin/main` transport and the current + hydration-output transport so the intended baseline and candidate can share + one fixture. It does not preserve intermediate private transport fields or + benchmark the complete production hydration producer. +- The `owner` suites call the production hydration owner directly. They do not + include the transform or a framework renderer. +- CPU results describe this Node and machine. They do not establish browser or + Cloudflare Worker performance. + +## Reproducibility + +The runner materializes the complete tracked `packages/router-core/src` tree +for both inputs before it builds. With `--candidate=worktree`, it first copies +one immutable worktree snapshot so later edits cannot change the measured +artifact. Results record available commit IDs, both source-tree hashes, bundle +hashes, platform details, and a hash of the measured source pair. Child +processes and bundles use `NODE_ENV=production`. + +Before publishing a conclusion: + +1. Use clean Git revision names for both sides. +2. Run the same harness revision for both implementations. +3. Verify matching output bytes and digests. +4. Repeat latency comparisons in fresh processes when the expected change is + small. +5. Run memory and correctness tests before retaining an optimization. + +For attribution only, `--cpu-prof=true` writes profiles into a sibling +`*-profiles/` directory by default. Use `--profile-dir=...` to choose another +new or empty directory. Profiles also contain fixture and validation work, so +use them as hints rather than standalone proof. diff --git a/packages/router-core/benchmarks/ssr-streaming/run.mjs b/packages/router-core/benchmarks/ssr-streaming/run.mjs new file mode 100644 index 0000000000..2d1f2245c2 --- /dev/null +++ b/packages/router-core/benchmarks/ssr-streaming/run.mjs @@ -0,0 +1,860 @@ +import { execFileSync, spawnSync } from 'node:child_process' +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { arch, cpus, platform, tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { createHash } from 'node:crypto' +import { build } from 'esbuild' + +const here = dirname(fileURLToPath(import.meta.url)) +const repo = resolve(here, '../../../..') +const dependencyNodePaths = [resolve(repo, 'packages/router-core/node_modules')] +const args = Object.fromEntries( + process.argv.slice(2).map((arg) => { + const [name, value = 'true'] = arg.replace(/^--/, '').split('=', 2) + return [name, value] + }), +) +const knownArgs = new Set([ + 'suite', + 'origin', + 'candidate', + 'runs', + 'output', + 'keep-artifacts', + 'cpu-prof', + 'profile-dir', + 'scenario', + 'mode', + 'implementation', + 'warmups', + 'iterations', + 'batch-requests', +]) +for (const name of Object.keys(args)) { + if (!knownArgs.has(name)) { + throw new Error(`Unknown benchmark option: --${name}`) + } +} +const suite = args.suite ?? 'primary' +const suites = new Set([ + 'common', + 'safe-points', + 'coalesced-close', + 'small-memory', + 'smoke', + 'source', + 'strings', + 'owner', + 'owner-warm', + 'owner-soak', + 'primary', +]) +if (!suites.has(suite)) { + throw new Error(`Unknown benchmark suite: ${suite}`) +} +const isWarmSuite = + suite === 'common' || + suite === 'safe-points' || + suite === 'coalesced-close' || + suite === 'strings' || + suite === 'owner-warm' +const selectedImplementations = isWarmSuite + ? [] + : ['origin', 'worktree'].filter((implementation) => { + if (!args.implementation || args.implementation === 'all') { + return true + } + return args.implementation.split(',').includes(implementation) + }) +const unsupportedSuiteOption = ( + isWarmSuite + ? ['runs', 'implementation'] + : ['warmups', 'iterations', 'batch-requests'] +).find((name) => args[name] !== undefined) +if (unsupportedSuiteOption) { + throw new Error( + `--${unsupportedSuiteOption} is not supported by the ${suite} suite`, + ) +} +if ( + args['cpu-prof'] !== undefined && + !['true', 'false'].includes(args['cpu-prof']) +) { + throw new Error('--cpu-prof must be true or false') +} +const cpuProfiled = args['cpu-prof'] === 'true' +if (args['profile-dir'] !== undefined && !cpuProfiled) { + throw new Error('--profile-dir requires --cpu-prof=true') +} +const originRef = args.origin ?? 'origin/main' +const candidateRef = args.candidate ?? 'HEAD' +const originSha = execFileSync('git', ['rev-parse', `${originRef}^{commit}`], { + cwd: repo, + encoding: 'utf8', +}).trim() +const candidateSha = + candidateRef === 'worktree' + ? undefined + : execFileSync('git', ['rev-parse', `${candidateRef}^{commit}`], { + cwd: repo, + encoding: 'utf8', + }).trim() +const headSha = execFileSync('git', ['rev-parse', 'HEAD^{commit}'], { + cwd: repo, + encoding: 'utf8', +}).trim() +const runs = Number(args.runs ?? (suite === 'smoke' ? 1 : 3)) +const outputPath = resolve( + repo, + args.output ?? + `packages/router-core/benchmarks/ssr-streaming/results/${suite}.json`, +) +if (!outputPath.endsWith('.json')) { + throw new Error('Benchmark output must end in .json') +} +if (!Number.isInteger(runs) || runs < 1) { + throw new Error('--runs must be an integer greater than zero') +} +const keepArtifacts = args['keep-artifacts'] + ? resolve(repo, args['keep-artifacts']) + : undefined +if ( + keepArtifacts && + existsSync(keepArtifacts) && + readdirSync(keepArtifacts).length +) { + throw new Error('--keep-artifacts must name a new or empty directory') +} +const temp = keepArtifacts ?? mkdtempSync(join(tmpdir(), 'tsr-ssr-streaming-')) +mkdirSync(temp, { recursive: true }) +function cleanupTemporaryArtifacts() { + if (!keepArtifacts) { + rmSync(temp, { recursive: true, force: true }) + } +} +// Some setup and child-failure paths exit before the main try/finally can +// unwind. Register cleanup as soon as the temporary directory exists. +process.once('exit', cleanupTemporaryArtifacts) +const profileDir = cpuProfiled + ? resolve( + repo, + args['profile-dir'] ?? outputPath.replace(/\.json$/, '-profiles'), + ) + : undefined +if (profileDir) { + if (existsSync(profileDir) && readdirSync(profileDir).length) { + throw new Error( + `${args['profile-dir'] === undefined ? 'Default profile directory' : '--profile-dir'} must name a new or empty directory`, + ) + } + mkdirSync(profileDir, { recursive: true }) +} +const childEnvironment = { ...process.env, NODE_ENV: 'production' } + +function sourcePathsAt(ref) { + const output = execFileSync( + 'git', + ['ls-tree', '-r', '--name-only', ref, '--', 'packages/router-core/src'], + { cwd: repo, encoding: 'utf8' }, + ).trim() + return output ? output.split('\n') : [] +} + +function worktreeSourcePaths() { + const output = execFileSync( + 'git', + [ + 'ls-files', + '--cached', + '--others', + '--exclude-standard', + '--', + 'packages/router-core/src', + ], + { cwd: repo, encoding: 'utf8' }, + ).trim() + return output + ? output + .split('\n') + .filter((repositoryPath) => existsSync(resolve(repo, repositoryPath))) + .sort() + : [] +} + +function materializeSourceSnapshot(ref, sourceRoot, repositoryPaths) { + for (const repositoryPath of repositoryPaths) { + const target = join( + sourceRoot, + repositoryPath.slice('packages/router-core/src/'.length), + ) + mkdirSync(dirname(target), { recursive: true }) + writeFileSync( + target, + execFileSync('git', ['show', `${ref}:${repositoryPath}`], { cwd: repo }), + ) + } +} + +function materializeWorktreeSnapshot(sourceRoot, repositoryPaths) { + for (const repositoryPath of repositoryPaths) { + const target = join( + sourceRoot, + repositoryPath.slice('packages/router-core/src/'.length), + ) + mkdirSync(dirname(target), { recursive: true }) + writeFileSync(target, readFileSync(resolve(repo, repositoryPath))) + } +} + +function sourceSnapshotSha256(sourceRoot, repositoryPaths) { + const hash = createHash('sha256') + for (const repositoryPath of repositoryPaths) { + hash.update(repositoryPath) + hash.update('\0') + hash.update( + readFileSync( + join( + sourceRoot, + repositoryPath.slice('packages/router-core/src/'.length), + ), + ), + ) + hash.update('\0') + } + return hash.digest('hex') +} + +const originSourceRoot = join(temp, 'origin/packages/router-core/src') +const candidateSourceRoot = join(temp, 'worktree/packages/router-core/src') +const originSourcePaths = sourcePathsAt(originSha) +const candidateSourcePaths = + candidateRef === 'worktree' + ? worktreeSourcePaths() + : sourcePathsAt(candidateSha) +if (suite.startsWith('owner')) { + const ownerSourcePath = 'packages/router-core/src/ssr/hydrationScripts.ts' + const missingImplementations = [] + const requiredImplementations = isWarmSuite + ? ['origin', 'worktree'] + : selectedImplementations + if ( + requiredImplementations.includes('origin') && + !originSourcePaths.includes(ownerSourcePath) + ) { + missingImplementations.push(`origin (${originRef})`) + } + if ( + requiredImplementations.includes('worktree') && + !candidateSourcePaths.includes(ownerSourcePath) + ) { + missingImplementations.push(`candidate (${candidateRef})`) + } + if (missingImplementations.length > 0) { + throw new Error( + `The ${suite} suite requires hydrationScripts.ts in the selected revision(s). ` + + `Missing from ${missingImplementations.join(' and ')}.`, + ) + } +} +materializeSourceSnapshot(originSha, originSourceRoot, originSourcePaths) +if (candidateRef === 'worktree') { + materializeWorktreeSnapshot(candidateSourceRoot, candidateSourcePaths) +} else { + materializeSourceSnapshot( + candidateSha, + candidateSourceRoot, + candidateSourcePaths, + ) +} +const originSourceSha256 = sourceSnapshotSha256( + originSourceRoot, + originSourcePaths, +) +const candidateSourceSha256 = sourceSnapshotSha256( + candidateSourceRoot, + candidateSourcePaths, +) +const measuredSourcePairSha256 = createHash('sha256') + .update(originSourceSha256) + .update('\0') + .update(candidateSourceSha256) + .digest('hex') +const transformSources = { + origin: readFileSync( + join(originSourceRoot, 'ssr/transformStreamWithRouter.ts'), + 'utf8', + ), + worktree: readFileSync( + join(candidateSourceRoot, 'ssr/transformStreamWithRouter.ts'), + 'utf8', + ), +} +const hasHistoricalBufferGuards = { + origin: transformSources.origin.includes( + 'SSR router HTML exceeded maximum buffer', + ), + worktree: transformSources.worktree.includes( + 'SSR router HTML exceeded maximum buffer', + ), +} +const transformExportNames = { + origin: transformSources.origin.includes( + 'export function transformStreamWithRouter(', + ) + ? 'transformStreamWithRouter' + : 'transformReadableStreamWithRouter', + worktree: transformSources.worktree.includes( + 'export function transformStreamWithRouter(', + ) + ? 'transformStreamWithRouter' + : 'transformReadableStreamWithRouter', +} + +// The worktree transform imports protocol constants from hydrationScripts. +// Its producer is not used by this benchmark worker, so the Vite-only script +// string can stay empty in the benchmark bundle. +const scriptStringPlugin = { + name: 'script-string', + setup(build) { + build.onResolve({ filter: /\?script-string$/ }, (args) => ({ + path: args.path, + namespace: 'script-string', + })) + build.onLoad({ filter: /.*/, namespace: 'script-string' }, () => ({ + contents: 'export default ""', + loader: 'js', + })) + }, +} + +async function bundle(implementation) { + const sourceRoot = + implementation === 'origin' ? originSourceRoot : candidateSourceRoot + const entry = join(temp, `${implementation}-entry.ts`) + writeFileSync( + entry, + suite === 'owner' || suite === 'owner-soak' + ? `import { runHydrationOwner, runHydrationOwnerSoak } from ${JSON.stringify(resolve(here, 'worker.ts'))}\n` + + `import { createHydrationScripts } from ${JSON.stringify(join(sourceRoot, 'ssr/hydrationScripts.ts'))}\n` + + `const values = Object.fromEntries(process.argv.slice(2).map((value) => value.replace(/^--/, '').split('=', 2)))\n` + + `${suite === 'owner-soak' ? 'runHydrationOwnerSoak' : 'runHydrationOwner'}(createHydrationScripts, ${JSON.stringify(implementation)}, values.scenario)\n` + : `import { run, runProbe } from ${JSON.stringify(resolve(here, 'worker.ts'))}\n` + + `import { ${transformExportNames[implementation]} as transform } from ${JSON.stringify(join(sourceRoot, 'ssr/transformStreamWithRouter.ts'))}\n` + + `const values = Object.fromEntries(process.argv.slice(2).map((value) => value.replace(/^--/, '').split('=', 2)))\n` + + `if (values.probe) { runProbe(values.shape, Number(values.size), values.strategy) } else { await run(transform, ${JSON.stringify(implementation)}, values.scenario, values.mode) }\n`, + ) + const outfile = join(temp, `${implementation}.mjs`) + await build({ + entryPoints: [entry], + outfile, + bundle: true, + platform: 'node', + format: 'esm', + target: 'node20', + logLevel: 'silent', + nodePaths: dependencyNodePaths, + plugins: [scriptStringPlugin], + define: { 'process.env.NODE_ENV': '"production"' }, + }) + return outfile +} + +async function bundleWarmComparison() { + const entry = join(temp, 'warm-comparison-entry.ts') + writeFileSync( + entry, + suite === 'owner-warm' + ? `import { runWarmHydrationOwnerComparison } from ${JSON.stringify(resolve(here, 'worker.ts'))}\n` + + `import { createHydrationScripts as origin } from ${JSON.stringify(join(originSourceRoot, 'ssr/hydrationScripts.ts'))}\n` + + `import { createHydrationScripts as worktree } from ${JSON.stringify(join(candidateSourceRoot, 'ssr/hydrationScripts.ts'))}\n` + + `const values = Object.fromEntries(process.argv.slice(2).map((value) => value.replace(/^--/, '').split('=', 2)))\n` + + `const result = runWarmHydrationOwnerComparison({ origin, worktree }, values.scenarios.split(','), Number(values.warmups), Number(values.iterations), Number(values.batchRequests))\n` + + `process.stdout.write(JSON.stringify(result) + '\\n')\n` + : `import { runWarmComparison } from ${JSON.stringify(resolve(here, 'worker.ts'))}\n` + + `import { ${transformExportNames.origin} as origin } from ${JSON.stringify(join(originSourceRoot, 'ssr/transformStreamWithRouter.ts'))}\n` + + `import { ${transformExportNames.worktree} as worktree } from ${JSON.stringify(join(candidateSourceRoot, 'ssr/transformStreamWithRouter.ts'))}\n` + + `const values = Object.fromEntries(process.argv.slice(2).map((value) => value.replace(/^--/, '').split('=', 2)))\n` + + `const result = await runWarmComparison({ origin, worktree }, values.scenarios.split(','), values.modes.split(','), Number(values.warmups), Number(values.iterations), Number(values.batchRequests))\n` + + `process.stdout.write(JSON.stringify(result) + '\\n')\n`, + ) + const outfile = join(temp, 'warm-comparison.mjs') + await build({ + entryPoints: [entry], + outfile, + bundle: true, + platform: 'node', + format: 'esm', + target: 'node20', + logLevel: 'silent', + nodePaths: dependencyNodePaths, + plugins: [scriptStringPlugin], + define: { 'process.env.NODE_ENV': '"production"' }, + }) + return outfile +} + +function tasksForSuite() { + if (suite === 'common') { + return [ + 'hydration-1k', + 'hydration-4k', + 'hydration-16k', + 'hydration-32k', + 'hydration-64k', + 'hydration-solid-32k', + 'hydration-vue-32k', + ] + } + if (suite === 'safe-points') { + return ['react-patches-64-records', 'solid-patches-64-records'] + } + if (suite === 'coalesced-close') { + return [ + 'react-coalesced-early-script-1k', + 'react-coalesced-early-script-64k', + 'react-coalesced-next-close-64k', + 'react-coalesced-late-script-64k', + ] + } + if (suite === 'small-memory') { + return ['hydration-1k', 'hydration-4k'] + } + if (suite === 'smoke') { + return ['closing-heavy-17m'] + } + if (suite === 'source') { + return [ + 'router-string-flat-1m', + 'router-string-flat-4m', + 'router-string-flat-17m', + 'router-string-flat-32m', + 'router-string-rope-1m', + 'router-string-rope-4m', + 'router-string-rope-17m', + 'router-string-rope-32m', + ] + } + if (suite === 'strings') { + return [ + 'application-string-flat-1m', + 'application-string-flat-4m', + 'application-string-flat-17m', + 'application-string-rope-1m', + 'application-string-rope-4m', + 'application-string-rope-17m', + ] + } + if (suite === 'owner' || suite === 'owner-warm') { + return [ + 'hydration-owner-1x1k', + 'hydration-owner-16x1k', + 'hydration-owner-400x40k', + 'hydration-owner-4095x4k', + ] + } + if (suite === 'owner-soak') { + return ['hydration-owner-16x1k', 'hydration-owner-4095x4k'] + } + return [ + 'hydration-32k', + 'hydration-17m', + 'router-records-15m', + 'closing-heavy-17m', + 'react18-patches-17m', + 'react19-patches-17m', + ] +} + +function writeSummary(results, path, warmComparison) { + const provenance = [ + `Origin: ${originRef} (${originSha})`, + `Candidate: ${candidateRef} (${candidateSha ?? `worktree snapshot ${candidateSourceSha256}`})`, + `Node: ${process.version}; NODE_ENV=production`, + ] + if (warmComparison) { + const lines = [ + '# Warm SSR streaming benchmark results', + '', + ...provenance, + `Requests per timed batch: ${warmComparison.batchRequests}`, + '', + '| baseline | scenario | framework | safe point | mode | baseline mean us/request | candidate mean us/request | aggregate change | paired geometric mean | paired median | paired p10 | paired p90 | wall aggregate |', + '| --- | --- | --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |', + ] + for (const comparison of warmComparison.comparisons) { + const baseline = results.find( + (value) => + value.scenario === comparison.scenario && + value.framework === comparison.framework && + value.rendererSafePoint === comparison.rendererSafePoint && + value.mode === comparison.mode && + value.implementation === comparison.baseline && + value.comparisonBaseline === comparison.baseline, + ) + const worktree = results.find( + (value) => + value.scenario === comparison.scenario && + value.framework === comparison.framework && + value.rendererSafePoint === comparison.rendererSafePoint && + value.mode === comparison.mode && + value.implementation === 'worktree' && + value.comparisonBaseline === comparison.baseline, + ) + if (!baseline || !worktree) { + throw new Error( + `Missing warm result row for ${comparison.scenario}/${comparison.framework}/${comparison.rendererSafePoint ?? '-'}/${comparison.mode}/${comparison.baseline}`, + ) + } + lines.push( + `| ${comparison.baseline} | ${comparison.scenario} | ${comparison.framework} | ${comparison.rendererSafePoint ?? '-'} | ${comparison.mode} | ${(baseline.statistics.elapsedMs.mean * 1000).toFixed(2)} | ${(worktree.statistics.elapsedMs.mean * 1000).toFixed(2)} | ${comparison.aggregateElapsedPercent.toFixed(1)}% | ${comparison.pairedElapsedPercent.geometricMean.toFixed(1)}% | ${comparison.pairedElapsedPercent.median.toFixed(1)}% | ${comparison.pairedElapsedPercent.p10.toFixed(1)}% | ${comparison.pairedElapsedPercent.p90.toFixed(1)}% | ${comparison.aggregateWallElapsedPercent.toFixed(1)}% |`, + ) + } + writeFileSync(path, `${lines.join('\n')}\n`) + return + } + + const lines = [ + '# SSR streaming benchmark results', + '', + ...provenance, + '', + '| implementation | run | scenario | framework | safe point | mode | TTFB ms | first router ms | MiB/s | heap peak MiB | external peak MiB | max chunk | records HWM |', + '| --- | ---: | --- | --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |', + ] + const soakRows = [] + for (const value of results) { + if (value.outcome === 'expected-error') { + lines.push( + `| ${value.implementation} | ${value.run ?? '-'} | ${value.scenario} | ${value.framework} | ${value.rendererSafePoint ?? '-'} | ${value.mode} | - | - | expected guard | - | - | - | - |`, + ) + continue + } + if (value.implementation === 'v8-probe') { + for (const pass of value.passes) { + lines.push( + `| v8-probe | ${pass.pass} | ${value.scenario} | - | - | ${value.mode} | - | - | ${pass.throughputMiBPerSecond.toFixed(1)} | ${(pass.memoryPeakBytes.heapUsed / 1048576).toFixed(1)} | ${(pass.memoryPeakBytes.external / 1048576).toFixed(1)} | ${value.outputChunkBytes} | 0 |`, + ) + } + continue + } + if (value.mode === 'owner-soak') { + soakRows.push(value) + continue + } + lines.push( + `| ${value.implementation} | ${value.run ?? '-'} | ${value.scenario} | ${value.framework} | ${value.rendererSafePoint ?? '-'} | ${value.mode} | ${value.ttfbMs?.toFixed(2) ?? '-'} | ${value.firstRouterScriptMs?.toFixed(2) ?? '-'} | ${value.throughputMiBPerSecond.toFixed(1)} | ${(value.memoryPeakBytes.heapUsed / 1048576).toFixed(1)} | ${(value.memoryPeakBytes.external / 1048576).toFixed(1)} | ${value.maxOutputChunkBytes} | ${value.sourceRecordHighWater} |`, + ) + } + if (soakRows.length > 0) { + lines.push( + '', + '## Post-GC retention soak', + '', + '| implementation | run | scenario | requests | MiB/s including checkpoint GC | retained heap HWM MiB | retained external HWM MiB | retained ArrayBuffer HWM MiB |', + '| --- | ---: | --- | ---: | ---: | ---: | ---: | ---: |', + ) + for (const value of soakRows) { + lines.push( + `| ${value.implementation} | ${value.run ?? '-'} | ${value.scenario} | ${value.requests} | ${value.throughputIncludingGcMiBPerSecond.toFixed(1)} | ${(value.retainedHighWaterBytes.heapUsed / 1048576).toFixed(1)} | ${(value.retainedHighWaterBytes.external / 1048576).toFixed(1)} | ${(value.retainedHighWaterBytes.arrayBuffers / 1048576).toFixed(1)} |`, + ) + } + } + writeFileSync(path, `${lines.join('\n')}\n`) +} + +try { + const bundles = {} + for (const implementation of selectedImplementations) { + bundles[implementation] = await bundle(implementation) + } + const scenarios = tasksForSuite().filter( + (scenario) => !args.scenario || args.scenario.split(',').includes(scenario), + ) + const supportedModes = + suite === 'owner' || suite === 'owner-warm' || suite === 'owner-soak' + ? ['owner'] + : suite === 'source' || + suite === 'strings' || + suite === 'safe-points' || + suite === 'coalesced-close' + ? ['merge'] + : isWarmSuite + ? ['fast', 'merge'] + : ['raw', 'fast', 'merge'] + const modes = supportedModes.filter( + (mode) => !args.mode || args.mode.split(',').includes(mode), + ) + const implementations = selectedImplementations + const results = [] + const artifactPaths = { ...bundles } + let warmComparison + if ( + scenarios.length === 0 || + modes.length === 0 || + (!isWarmSuite && implementations.length === 0) + ) { + throw new Error('Benchmark filters selected no cells') + } + if (isWarmSuite) { + const warmBundle = await bundleWarmComparison() + artifactPaths['warm-comparison'] = warmBundle + const focusedSafePoints = + suite === 'safe-points' || suite === 'coalesced-close' + const warmups = Number(args.warmups ?? (focusedSafePoints ? 20 : 50)) + const iterations = Number(args.iterations ?? (focusedSafePoints ? 20 : 50)) + const batchRequests = Number( + args['batch-requests'] ?? (focusedSafePoints ? 250 : 1000), + ) + if ( + scenarios.length === 0 || + !Number.isInteger(warmups) || + warmups < 0 || + !Number.isInteger(iterations) || + iterations < 1 || + !Number.isInteger(batchRequests) || + batchRequests < 1 + ) { + throw new Error('Invalid warm-suite scenario or iteration count') + } + const child = spawnSync( + process.execPath, + [ + '--expose-gc', + ...(profileDir + ? [ + '--cpu-prof', + `--cpu-prof-dir=${profileDir}`, + `--cpu-prof-name=warm-${suite}.cpuprofile`, + ] + : []), + warmBundle, + `--scenarios=${scenarios.join(',')}`, + `--modes=${modes.join(',')}`, + `--warmups=${warmups}`, + `--iterations=${iterations}`, + `--batchRequests=${batchRequests}`, + ], + { + cwd: repo, + encoding: 'utf8', + maxBuffer: 10 * 1024 * 1024, + env: childEnvironment, + }, + ) + if (child.status !== 0) { + process.stderr.write(child.stderr) + process.stderr.write(child.stdout) + process.exit(child.status ?? 1) + } + warmComparison = JSON.parse(child.stdout.trim()) + if (warmComparison.comparisons.length === 0) { + throw new Error('Benchmark filters selected no warm comparison cells') + } + results.push(...warmComparison.results) + for (const comparison of warmComparison.comparisons) { + process.stdout.write( + `${comparison.baseline}->candidate ${comparison.scenario} ${comparison.framework} ${comparison.rendererSafePoint ?? 'no-extra-safe-point'} ${comparison.mode}: aggregate ${comparison.aggregateElapsedPercent.toFixed(1)}%, paired geometric mean ${comparison.pairedElapsedPercent.geometricMean.toFixed(1)}%\n`, + ) + } + } + for (const scenario of scenarios) { + const framework = + scenario.startsWith('hydration-solid-') || scenario.startsWith('solid-') + ? 'solid' + : scenario.startsWith('hydration-vue-') + ? 'vue' + : 'react' + const rendererSafePoint = + framework === 'react' + ? 'script-close' + : framework === 'solid' + ? 'record-end' + : undefined + for (const mode of modes) { + for (let run = 1; run <= runs; run++) { + const orders = [ + ['origin', 'worktree'], + ['worktree', 'origin'], + ] + const implementationOrder = orders[(run - 1) % orders.length].filter( + (implementation) => implementations.includes(implementation), + ) + for (const implementation of implementationOrder) { + const profileArgs = profileDir + ? [ + '--cpu-prof', + `--cpu-prof-dir=${profileDir}`, + `--cpu-prof-name=${implementation}-${scenario}-${mode}-${run}.cpuprofile`, + ] + : [] + const child = spawnSync( + process.execPath, + [ + '--expose-gc', + ...profileArgs, + bundles[implementation], + `--scenario=${scenario}`, + `--mode=${mode}`, + ], + { + cwd: repo, + encoding: 'utf8', + maxBuffer: 10 * 1024 * 1024, + env: childEnvironment, + }, + ) + if (child.status !== 0) { + const expectedHistoricalLimit = + mode !== 'merge' || !hasHistoricalBufferGuards[implementation] + ? undefined + : scenario === 'react18-patches-17m' + ? 'SSR stream tail exceeded maximum buffer' + : scenario === 'hydration-17m' || + /^router-string-(flat|rope)-(17|32)m$/.test(scenario) + ? 'SSR router HTML exceeded maximum buffer' + : undefined + const diagnostic = `${child.stderr}\n${child.stdout}` + if ( + expectedHistoricalLimit && + diagnostic.includes(expectedHistoricalLimit) + ) { + results.push({ + implementation, + scenario, + framework, + rendererSafePoint, + mode, + outcome: 'expected-error', + error: expectedHistoricalLimit, + run, + }) + process.stdout.write( + `${implementation} ${scenario} ${mode} ${run}/${runs}: expected historical buffer guard\n`, + ) + continue + } + process.stderr.write(child.stderr) + process.stderr.write(child.stdout) + process.exit(child.status ?? 1) + } + const value = JSON.parse(child.stdout.trim()) + value.run = run + results.push(value) + const throughput = + value.throughputMiBPerSecond ?? + value.throughputIncludingGcMiBPerSecond + process.stdout.write( + `${implementation} ${scenario} ${mode} ${run}/${runs}: ${throughput.toFixed(1)} MiB/s\n`, + ) + } + } + } + } + if (suite === 'source' && !args.scenario && !args.mode) { + for (const shape of ['flat', 'rope']) { + for (const size of [1, 4, 17, 32]) { + for (const strategy of ['suffix', 'window']) { + const profileArgs = profileDir + ? [ + '--cpu-prof', + `--cpu-prof-dir=${profileDir}`, + `--cpu-prof-name=probe-${shape}-${size}m-${strategy}.cpuprofile`, + ] + : [] + const child = spawnSync( + process.execPath, + [ + '--expose-gc', + ...profileArgs, + bundles.worktree ?? bundles.origin, + '--probe=true', + `--shape=${shape}`, + `--size=${size}`, + `--strategy=${strategy}`, + ], + { + cwd: repo, + encoding: 'utf8', + maxBuffer: 10 * 1024 * 1024, + env: childEnvironment, + }, + ) + if (child.status !== 0) { + process.stderr.write(child.stderr) + process.stderr.write(child.stdout) + process.exit(child.status ?? 1) + } + results.push(JSON.parse(child.stdout.trim())) + } + } + } + } + mkdirSync(dirname(outputPath), { recursive: true }) + writeFileSync( + outputPath, + `${JSON.stringify( + { + generatedAt: new Date().toISOString(), + node: process.version, + nodeEnv: 'production', + cpuProfiled, + platform: { os: platform(), arch: arch(), cpu: cpus()[0]?.model }, + originRef, + originSha, + originSourceSha256, + candidateRef, + candidateSha, + headSha, + candidateSourceSha256, + benchmarkInput: + suite === 'strings' + ? 'renderer string records' + : suite.startsWith('owner') + ? 'production hydration owner' + : 'Uint8Array renderer records', + measuredSourcePairSha256, + artifactSha256: Object.fromEntries( + Object.entries(artifactPaths) + .map(([name, path]) => [ + name, + createHash('sha256').update(readFileSync(path)).digest('hex'), + ]) + .concat( + profileDir + ? readdirSync(profileDir) + .filter((name) => name.endsWith('.cpuprofile')) + .sort() + .map((name) => [ + `profile:${name}`, + createHash('sha256') + .update(readFileSync(join(profileDir, name))) + .digest('hex'), + ]) + : [], + ), + ), + suite, + runs: isWarmSuite ? undefined : runs, + warmComparison, + results: isWarmSuite ? undefined : results, + }, + null, + 2, + )}\n`, + ) + const summaryPath = outputPath.replace(/\.json$/, '.md') + writeSummary(results, summaryPath, warmComparison) + process.stdout.write(`Raw results: ${outputPath}\nSummary: ${summaryPath}\n`) +} finally { + cleanupTemporaryArtifacts() + process.removeListener('exit', cleanupTemporaryArtifacts) +} diff --git a/packages/router-core/benchmarks/ssr-streaming/worker.ts b/packages/router-core/benchmarks/ssr-streaming/worker.ts new file mode 100644 index 0000000000..5a12fe2920 --- /dev/null +++ b/packages/router-core/benchmarks/ssr-streaming/worker.ts @@ -0,0 +1,2254 @@ +import { createHash } from 'node:crypto' +import { ReadableStream } from 'node:stream/web' +import { performance } from 'node:perf_hooks' + +const MiB = 1024 * 1024 +// Shared legacy-compatible input: origin finds the ID, while the current +// transform finds the exact boundary suffix. Both benchmark the same bytes. +const BARRIER = + '' +const SHELL_PREFIX = '
    done
    ' +const PREFIX = `${SHELL_PREFIX}${BARRIER}` +const SUFFIX = '' +const SCRIPT_OPEN = '' +const REACT_PATCH_PREFIX = '' +const REACT_PATCH_BYTES = 32 * 1024 +const REACT_PATCH = + REACT_PATCH_PREFIX + + 'x'.repeat( + REACT_PATCH_BYTES - REACT_PATCH_PREFIX.length - REACT_PATCH_SUFFIX.length, + ) + + REACT_PATCH_SUFFIX +const SMALL_REACT_PATCH = + '' +const SMALL_SOLID_RECORD = '' +const COALESCED_PATCH = '' +const COALESCED_LAST_PATCH = '' +const COALESCED_FILLER = '
    ordinary text
    ' +// Mirrors of `src/ssr/hydrationScripts.ts` limits and states. The worker +// also runs against a baseline worktree, so it cannot import them; keep these +// in step with MAX_HYDRATION_OUTPUT_CHUNK_BYTES, MAX_DIRECT_CODE_UNITS, +// MIN_OUTPUT_BYTES, and HydrationScriptOutputState. +const OUTPUT_BYTES = 64 * 1024 +const FILL_BYTES = 64 * 1024 +const DIRECT_HYDRATION_CODE_UNITS = 16 * 1024 +const MIN_HYDRATION_OUTPUT_BYTES = 256 + +const HydrationOutputState = { + Waiting: 0, + Ready: 1, + Active: 2, + Done: 3, + Failed: 4, +} as const +type HydrationOutputState = + (typeof HydrationOutputState)[keyof typeof HydrationOutputState] +const HydrationRecordPhase = { + Opening: 0, + Source: 1, + Closing: 2, +} as const +type HydrationRecordPhase = + (typeof HydrationRecordPhase)[keyof typeof HydrationRecordPhase] +const hydrationEncoder = new TextEncoder() + +type Mode = 'raw' | 'fast' | 'merge' +type Shape = 'flat' | 'rope' +type Framework = 'react' | 'solid' | 'vue' +type RendererSafePoint = 'script-close' | 'record-end' +type BaselineImplementation = 'origin' +type AppStreamValue = Uint8Array | string +type Transform = ( + router: any, + stream: ReadableStream, + options?: { rendererSafePoint?: RendererSafePoint }, +) => ReadableStream + +type Memory = { + heapUsed: number + external: number + arrayBuffers: number + rss: number +} + +type ScenarioMetadata = { + name: string + framework: Framework + rendererSafePoint?: RendererSafePoint +} + +type Scenario = + | (ScenarioMetadata & { + kind: 'hydration' + records: number + recordBytes: number + shape: Shape + }) + | (ScenarioMetadata & { + kind: 'closing' + bytes: number + framework: 'react' + rendererSafePoint: 'script-close' + }) + | (ScenarioMetadata & { + kind: 'renderer-records' + record: string + records: number + closeBeforeRecords: boolean + routerRecordBytes: number + framework: 'react' | 'solid' + rendererSafePoint: RendererSafePoint + }) + | (ScenarioMetadata & { + kind: 'coalesced-close' + bytes: number + scriptAtEnd: boolean + closeInNextChunk: boolean + framework: 'react' + rendererSafePoint: 'script-close' + }) + | (ScenarioMetadata & { + kind: 'application-string' + bytes: number + shape: Shape + routerRecordBytes: number + framework: 'react' + rendererSafePoint: 'script-close' + }) + +function parseScenario(name: string): Scenario { + const coalescedCloseMatch = + /^react-coalesced-(early-script|next-close|late-script)-(1|64)k$/.exec(name) + if (coalescedCloseMatch) { + return { + kind: 'coalesced-close', + name, + bytes: Number(coalescedCloseMatch[2]) * 1024, + scriptAtEnd: coalescedCloseMatch[1] === 'late-script', + closeInNextChunk: coalescedCloseMatch[1] === 'next-close', + framework: 'react', + rendererSafePoint: 'script-close', + } + } + const commonHydrationMatch = + /^hydration(?:(?:-(solid|vue))?)-(1|4|16|32|64)k$/.exec(name) + if (commonHydrationMatch) { + const framework = + (commonHydrationMatch[1] as Framework | undefined) ?? 'react' + return { + kind: 'hydration', + name, + records: 1, + recordBytes: Number(commonHydrationMatch[2]) * 1024, + shape: 'flat', + framework, + rendererSafePoint: + framework === 'react' + ? 'script-close' + : framework === 'solid' + ? 'record-end' + : undefined, + } + } + if (name === 'hydration-17m') { + return { + kind: 'hydration', + name, + records: 1, + recordBytes: 17 * MiB, + shape: 'flat', + framework: 'react', + rendererSafePoint: 'script-close', + } + } + if (name === 'router-records-15m') { + return { + kind: 'hydration', + name, + records: 480, + recordBytes: 32 * 1024, + shape: 'flat', + framework: 'react', + rendererSafePoint: 'script-close', + } + } + if (name === 'closing-heavy-17m') { + return { + kind: 'closing', + name, + bytes: 17 * MiB, + framework: 'react', + rendererSafePoint: 'script-close', + } + } + if (name === 'react18-patches-17m') { + return { + kind: 'renderer-records', + name, + record: REACT_PATCH, + records: (17 * MiB) / REACT_PATCH_BYTES, + closeBeforeRecords: true, + routerRecordBytes: 32 * 1024, + framework: 'react', + rendererSafePoint: 'script-close', + } + } + if (name === 'react19-patches-17m') { + return { + kind: 'renderer-records', + name, + record: REACT_PATCH, + records: (17 * MiB) / REACT_PATCH_BYTES, + closeBeforeRecords: false, + routerRecordBytes: 32 * 1024, + framework: 'react', + rendererSafePoint: 'script-close', + } + } + if (name === 'react-patches-64-records') { + return { + kind: 'renderer-records', + name, + record: SMALL_REACT_PATCH, + records: 64, + closeBeforeRecords: false, + routerRecordBytes: 1024, + framework: 'react', + rendererSafePoint: 'script-close', + } + } + if (name === 'solid-patches-64-records') { + return { + kind: 'renderer-records', + name, + record: SMALL_SOLID_RECORD, + records: 64, + closeBeforeRecords: false, + routerRecordBytes: 1024, + framework: 'solid', + rendererSafePoint: 'record-end', + } + } + const applicationStringMatch = + /^application-string-(flat|rope)-(1|4|17)m$/.exec(name) + if (applicationStringMatch) { + return { + kind: 'application-string', + name, + bytes: Number(applicationStringMatch[2]) * MiB, + shape: applicationStringMatch[1] as Shape, + routerRecordBytes: 1024, + framework: 'react', + rendererSafePoint: 'script-close', + } + } + const routerMatch = /^(router-string)-(flat|rope)-(1|4|17|32)m$/.exec(name) + if (routerMatch) { + return { + kind: 'hydration', + name, + records: 1, + recordBytes: Number(routerMatch[3]) * MiB, + shape: routerMatch[2] as Shape, + framework: 'react', + rendererSafePoint: 'script-close', + } + } + throw new Error(`Unknown benchmark scenario: ${name}`) +} + +function forceGc() { + if (typeof globalThis.gc !== 'function') { + throw new Error('The benchmark worker requires node --expose-gc') + } + globalThis.gc() + globalThis.gc() +} + +function memory(): Memory { + const value = process.memoryUsage() + return { + heapUsed: value.heapUsed, + external: value.external, + arrayBuffers: value.arrayBuffers, + rss: value.rss, + } +} + +function delta(value: Memory, baseline: Memory): Memory { + return { + heapUsed: value.heapUsed - baseline.heapUsed, + external: value.external - baseline.external, + arrayBuffers: value.arrayBuffers - baseline.arrayBuffers, + rss: value.rss - baseline.rss, + } +} + +function maxMemory(target: Memory, value: Memory) { + target.heapUsed = Math.max(target.heapUsed, value.heapUsed) + target.external = Math.max(target.external, value.external) + target.arrayBuffers = Math.max(target.arrayBuffers, value.arrayBuffers) + target.rss = Math.max(target.rss, value.rss) +} + +function marker(index: number) { + return `r${index.toString(36).padStart(6, '0')}:` +} + +function fillCode(index: number) { + return 97 + (index % 20) +} + +function createSource(bytes: number, index: number, shape: Shape) { + const recordMarker = marker(index) + const remaining = bytes - recordMarker.length + if (remaining < 0) { + throw new Error('Source record is smaller than its marker') + } + if (shape === 'flat') { + const source = Buffer.allocUnsafe(bytes) + source.fill(fillCode(index)) + source.write(recordMarker, 0, 'ascii') + return source.toString('latin1') + } + const piece = String.fromCharCode(fillCode(index)).repeat(4096) + let source = recordMarker + let left = remaining + while (left > 0) { + source += left >= piece.length ? piece : piece.slice(0, left) + left -= Math.min(left, piece.length) + } + return source +} + +function updateRepeated( + hash: ReturnType, + code: number, + bytes: number, +) { + const buffer = Buffer.allocUnsafe(Math.min(FILL_BYTES, bytes || 1)).fill(code) + let left = bytes + while (left > 0) { + const length = Math.min(left, buffer.length) + hash.update(buffer.subarray(0, length)) + left -= length + } +} + +function updateSource( + hash: ReturnType, + bytes: number, + index: number, +) { + const recordMarker = marker(index) + hash.update(recordMarker) + updateRepeated(hash, fillCode(index), bytes - recordMarker.length) +} + +type RouterSource = { + records: number + recordBytes: number + shape: Shape +} + +function getRouterSource(scenario: Scenario): RouterSource | undefined { + if (scenario.kind === 'hydration') { + return { + records: scenario.records, + recordBytes: scenario.recordBytes, + shape: scenario.shape, + } + } + if (scenario.kind === 'renderer-records') { + return { + records: 1, + recordBytes: scenario.routerRecordBytes, + shape: 'flat', + } + } + if (scenario.kind === 'application-string') { + return { + records: 1, + recordBytes: scenario.routerRecordBytes, + shape: 'flat', + } + } + return undefined +} + +function expected(scenario: Scenario, mode: Mode) { + const hash = createHash('sha256') + let bytes = 0 + const add = (value: string) => { + hash.update(value) + bytes += Buffer.byteLength(value) + } + const addRouterRecord = (recordBytes: number, index: number) => { + add(SCRIPT_OPEN) + updateSource(hash, recordBytes, index) + bytes += recordBytes + add(SCRIPT_CLOSE) + } + const addRouterSources = () => { + const source = getRouterSource(scenario) + if (!source) { + return + } + for (let index = 0; index < source.records; index++) { + addRouterRecord(source.recordBytes, index) + } + } + const addRendererRecords = (record: string, records: number) => { + for (let index = 0; index < records; index++) { + add(record) + } + } + + if (scenario.kind === 'coalesced-close') { + add(PREFIX) + if (!scenario.scriptAtEnd) { + add(COALESCED_PATCH) + } + add(createCoalescedFiller(scenario.bytes)) + if (scenario.scriptAtEnd) { + add(COALESCED_PATCH) + } + if (mode !== 'merge') { + add(SUFFIX) + } + add(COALESCED_LAST_PATCH) + if (mode === 'merge') { + add(SUFFIX) + } + } else if (scenario.kind === 'closing') { + add(SHELL_PREFIX) + const pattern = '
    x
    ' + const repetitions = Math.floor(scenario.bytes / pattern.length) + const remainder = scenario.bytes % pattern.length + for (let index = 0; index < repetitions; index++) { + add(pattern) + } + add(pattern.slice(0, remainder)) + add(BARRIER) + add(SUFFIX) + } else if (scenario.kind === 'hydration') { + if (mode === 'merge') { + add(PREFIX) + addRouterSources() + } else { + add(SHELL_PREFIX) + addRouterSources() + add(BARRIER) + } + add(SUFFIX) + } else if (scenario.kind === 'renderer-records') { + if (mode === 'merge') { + add(PREFIX) + addRendererRecords(scenario.record, scenario.records) + addRouterSources() + add(SUFFIX) + } else { + add(SHELL_PREFIX) + addRouterSources() + add(BARRIER) + if (scenario.closeBeforeRecords) { + add(SUFFIX) + } + addRendererRecords(scenario.record, scenario.records) + if (!scenario.closeBeforeRecords) { + add(SUFFIX) + } + } + } else { + if (mode === 'merge') { + add(PREFIX) + addRouterSources() + } else { + add(SHELL_PREFIX) + addRouterSources() + add(BARRIER) + } + updateRepeated(hash, 'x'.charCodeAt(0), scenario.bytes) + bytes += scenario.bytes + add(SUFFIX) + } + return { bytes, digest: hash.digest('hex') } +} + +const expectedOutputCache = new Map>() + +function getExpectedOutput(scenario: Scenario, mode: Mode) { + const key = `${scenario.name}:${mode}` + let value = expectedOutputCache.get(key) + if (!value) { + value = expected(scenario, mode) + expectedOutputCache.set(key, value) + } + return value +} + +function* repeatedPatternBytes(pattern: string, bytes: number) { + const chunk = pattern.repeat(Math.floor(FILL_BYTES / pattern.length)) + let left = bytes + while (left > 0) { + const value = chunk.slice(0, Math.min(left, chunk.length)) + yield Buffer.from(value) + left -= value.length + } +} + +function* repeatedCompletePatternBytes( + pattern: string, + bytes: number, + maxChunkBytes = FILL_BYTES, +) { + let repetitions = Math.floor(bytes / pattern.length) + const repetitionsPerChunk = Math.max( + 1, + Math.floor(maxChunkBytes / pattern.length), + ) + const fullChunk = pattern.repeat(repetitionsPerChunk) + while (repetitions > 0) { + const count = Math.min(repetitions, repetitionsPerChunk) + yield Buffer.from( + count === repetitionsPerChunk ? fullChunk : pattern.repeat(count), + ) + repetitions -= count + } +} + +function* routerScriptBytes(source: RouterSource): Generator { + for (let index = 0; index < source.records; index++) { + yield Buffer.from(SCRIPT_OPEN + marker(index)) + let left = source.recordBytes - marker(index).length + while (left > 0) { + const length = Math.min(left, FILL_BYTES) + yield Buffer.alloc(length, fillCode(index)) + left -= length + } + yield Buffer.from(SCRIPT_CLOSE) + } +} + +function* integratedBytes(scenario: Scenario): Generator { + if (scenario.kind === 'coalesced-close') { + yield* coalescedCloseApplicationBytes(scenario) + return + } + if (scenario.kind === 'closing') { + yield Buffer.from(SHELL_PREFIX) + yield* repeatedPatternBytes('
    x
    ', scenario.bytes) + yield Buffer.from(BARRIER) + yield Buffer.from(SUFFIX) + return + } + + yield Buffer.from(SHELL_PREFIX) + const source = getRouterSource(scenario) + if (source) { + yield* routerScriptBytes(source) + } + yield Buffer.from(BARRIER) + + if (scenario.kind === 'hydration') { + yield Buffer.from(SUFFIX) + } else if (scenario.kind === 'renderer-records') { + if (scenario.closeBeforeRecords) { + yield Buffer.from(SUFFIX) + } + yield* repeatedCompletePatternBytes( + scenario.record, + scenario.record.length * scenario.records, + scenario.record.length, + ) + if (!scenario.closeBeforeRecords) { + yield Buffer.from(SUFFIX) + } + } else { + yield Buffer.alloc(scenario.bytes, 'x'.charCodeAt(0)) + yield Buffer.from(SUFFIX) + } +} + +function createCoalescedFiller(bytes: number) { + return ( + COALESCED_FILLER.repeat(Math.floor(bytes / COALESCED_FILLER.length)) + + 'x'.repeat(bytes % COALESCED_FILLER.length) + ) +} + +function* coalescedCloseApplicationBytes( + scenario: Extract, +) { + const filler = createCoalescedFiller(scenario.bytes) + const content = + PREFIX + + (scenario.scriptAtEnd ? filler + COALESCED_PATCH : COALESCED_PATCH + filler) + const close = SUFFIX + COALESCED_LAST_PATCH + yield Buffer.from(content + (scenario.closeInNextChunk ? '' : close)) + if (scenario.closeInNextChunk) { + yield Buffer.from(close) + } + // Keep hydration Waiting while the coalesced bytes drain. Without this + // record, source prefetch can report EOF before the transform scans them. + yield new Uint8Array(0) +} + +function* rendererRecordApplicationBytes( + scenario: Extract, +) { + yield Buffer.from(PREFIX) + if (scenario.closeBeforeRecords) { + yield Buffer.from(SUFFIX) + } + yield* repeatedCompletePatternBytes( + scenario.record, + scenario.record.length * scenario.records, + scenario.record.length, + ) + if (!scenario.closeBeforeRecords) { + yield Buffer.from(SUFFIX) + } + // This empty record lets the transform consume all renderer bytes before + // the source reports EOF and starts the independent router producer. + yield new Uint8Array(0) +} + +function streamFromIterator( + iterator: Iterator, + onEof?: () => void, + beforeEof?: Promise, + onBeforeEof?: () => void, +) { + return new ReadableStream({ + async pull(controller) { + const next = iterator.next() + if (next.done) { + onBeforeEof?.() + await beforeEof + onEof?.() + controller.close() + } else { + controller.enqueue(next.value) + } + }, + }) +} + +function createApplicationString( + scenario: Extract, +) { + if (scenario.shape === 'flat') { + const value = Buffer.allocUnsafe( + PREFIX.length + scenario.bytes + SUFFIX.length, + ) + value.write(PREFIX, 0, 'ascii') + value.fill('x'.charCodeAt(0), PREFIX.length, PREFIX.length + scenario.bytes) + value.write(SUFFIX, PREFIX.length + scenario.bytes, 'ascii') + return value.toString('latin1') + } + const piece = 'x'.repeat(4096) + let value = PREFIX + let left = scenario.bytes + while (left > 0) { + value += left >= piece.length ? piece : piece.slice(0, left) + left -= Math.min(left, piece.length) + } + return value + SUFFIX +} + +function makeRouter(serializationFinished: boolean) { + let finished = serializationFinished + let streamFastPathReserved = false + let cleanupCount = 0 + let renderFinishedCount = 0 + let reserveCalls = 0 + let scriptSubscriptions = 0 + let htmlSubscriptions = 0 + let bufferedHtmlReads = 0 + let fastPathGrants = 0 + let hydrationOutputClaims = 0 + let hydrationOutputSubscriptions = 0 + let hydrationOutputPulls = 0 + const scriptListeners = new Set<(parts: ReadonlyArray) => void>() + const htmlListeners = new Set<(html: string) => void>() + const finishedListeners = new Set<() => void>() + const pendingScripts: Array = [] + const bufferedHtml: Array = [] + const hydrationSources: Array = [] + let hydrationSourceHead = 0 + let hydrationSource: string | undefined + let hydrationSegment = '' + let hydrationSegmentOffset = 0 + let hydrationPhase: HydrationRecordPhase = HydrationRecordPhase.Opening + let hydrationOutputCapacity = MIN_HYDRATION_OUTPUT_BYTES + let hydrationState: HydrationOutputState = HydrationOutputState.Waiting + let hydrationError: unknown + let hydrationListener: (() => void) | undefined + let hydrationOutput: + | { + readonly state: number + readonly error: unknown + pullChunk(): Uint8Array + subscribe(onChange: () => void): () => void + } + | undefined + let liftBarrier!: () => void + const barrier = new Promise((resolve) => { + liftBarrier = resolve + }) + + function hydrationQueueIsEmpty() { + return hydrationSourceHead === hydrationSources.length + } + + function refreshHydrationState(notify = true) { + const next = hydrationSource + ? HydrationOutputState.Active + : !hydrationQueueIsEmpty() + ? HydrationOutputState.Ready + : finished + ? HydrationOutputState.Done + : HydrationOutputState.Waiting + if (hydrationState !== next) { + hydrationState = next + if (notify) { + hydrationListener?.() + } + } + } + + function releaseHydrationSource() { + hydrationSources[hydrationSourceHead++] = undefined + if (hydrationQueueIsEmpty()) { + hydrationSources.length = 0 + hydrationSourceHead = 0 + } + hydrationSource = undefined + hydrationSegment = '' + hydrationSegmentOffset = 0 + hydrationPhase = HydrationRecordPhase.Opening + refreshHydrationState(false) + } + + function startHydrationSource(codeUnits: number) { + hydrationSource = hydrationSources[hydrationSourceHead]! + hydrationPhase = HydrationRecordPhase.Opening + hydrationSegment = SCRIPT_OPEN + hydrationSegmentOffset = 0 + hydrationOutputCapacity = Math.max( + MIN_HYDRATION_OUTPUT_BYTES, + Math.min(OUTPUT_BYTES, codeUnits), + ) + hydrationState = HydrationOutputState.Active + } + + function advanceHydrationSegment() { + if (hydrationPhase === HydrationRecordPhase.Opening) { + hydrationPhase = HydrationRecordPhase.Source + hydrationSegment = hydrationSource! + hydrationSegmentOffset = 0 + } else if (hydrationPhase === HydrationRecordPhase.Source) { + hydrationPhase = HydrationRecordPhase.Closing + hydrationSegment = SCRIPT_CLOSE + hydrationSegmentOffset = 0 + } else { + releaseHydrationSource() + } + } + + function pullHydrationChunk() { + hydrationOutputPulls++ + if ( + hydrationState !== HydrationOutputState.Ready && + hydrationState !== HydrationOutputState.Active + ) { + throw new Error('Benchmark hydration output is not ready') + } + + try { + if (hydrationState === HydrationOutputState.Ready) { + const source = hydrationSources[hydrationSourceHead]! + const codeUnits = + SCRIPT_OPEN.length + source.length + SCRIPT_CLOSE.length + if (codeUnits <= DIRECT_HYDRATION_CODE_UNITS) { + const bytes = hydrationEncoder.encode( + SCRIPT_OPEN + source + SCRIPT_CLOSE, + ) + hydrationSource = source + releaseHydrationSource() + return bytes + } + startHydrationSource(codeUnits) + } + + const bytes = new Uint8Array(hydrationOutputCapacity) + let outputOffset = 0 + while (hydrationSource) { + if (hydrationSegmentOffset === hydrationSegment.length) { + advanceHydrationSegment() + } else if (outputOffset === bytes.length) { + break + } else { + const target = + outputOffset === 0 ? bytes : bytes.subarray(outputOffset) + const result = hydrationEncoder.encodeInto( + hydrationSegment.slice(hydrationSegmentOffset), + target, + ) + if (result.read === 0) { + if (outputOffset === 0) { + throw new Error('Benchmark hydration encoder made no progress') + } + break + } + hydrationSegmentOffset += result.read + outputOffset += result.written + } + } + if (outputOffset === 0) { + throw new Error('Benchmark hydration record produced no output') + } + return outputOffset === bytes.length + ? bytes + : bytes.subarray(0, outputOffset) + } catch (error) { + hydrationError = error + hydrationState = HydrationOutputState.Failed + hydrationListener?.() + throw error + } + } + + function reserveFastPath(output?: typeof hydrationOutput) { + reserveCalls++ + if ( + !finished || + streamFastPathReserved || + pendingScripts.length > 0 || + hydrationSource !== undefined || + !hydrationQueueIsEmpty() || + (hydrationOutput ? output !== hydrationOutput : output !== undefined) + ) { + return false + } + streamFastPathReserved = true + fastPathGrants++ + return true + } + + function claimOutput() { + hydrationOutputClaims++ + if (hydrationOutput) { + throw new Error('Benchmark hydration output already has a consumer') + } + hydrationOutput = { + get state() { + return hydrationState + }, + get error() { + return hydrationError + }, + pullChunk: pullHydrationChunk, + subscribe(onChange: () => void) { + hydrationOutputSubscriptions++ + if (hydrationListener) { + throw new Error('Benchmark hydration output already has a subscriber') + } + hydrationListener = onChange + return () => { + if (hydrationListener === onChange) { + hydrationListener = undefined + } + } + }, + } + refreshHydrationState(false) + return hydrationOutput + } + + const hydrationScripts = { + reserveFastPath, + claimOutput, + liftBarrier, + // The worktree transform skips barrier scanning until the initial take. + // The synthetic fixture renders the boundary in its input, so report the + // take as already done. + isInitialTaken: () => true, + // The worktree transform arms the serialization deadline through the + // transport; the fixture manages its own timing. + startSerializationTimeout: (_timeoutMs: number) => {}, + } + + const serverSsr = { + hydrationScripts, + isSerializationFinished: () => finished, + // Keep the old transport shape so this one fixture can run origin and the + // candidate baseline against the same synthetic request. + reserveStreamFastPath: reserveFastPath, + claimHydrationScriptOutput: claimOutput, + onScriptBatch(listener: (parts: ReadonlyArray) => void) { + scriptSubscriptions++ + scriptListeners.add(listener) + if (pendingScripts.length > 0) { + const parts = pendingScripts.splice(0) + listener(parts) + } + return () => scriptListeners.delete(listener) + }, + onInjectedHtml(listener: (html: string) => void) { + htmlSubscriptions++ + htmlListeners.add(listener) + return () => htmlListeners.delete(listener) + }, + takeBufferedHtml() { + bufferedHtmlReads++ + return bufferedHtml.shift() + }, + onSerializationFinished(listener: () => void) { + finishedListeners.add(listener) + return () => finishedListeners.delete(listener) + }, + setRenderFinished() { + renderFinishedCount++ + liftBarrier() + }, + liftScriptBarrier: liftBarrier, + // The worktree transform registers a cleanup listener to tear down + // promptly on external cleanup. The fixture drives termination itself, + // so registration is accepted and ignored. + onCleanup(_listener: () => void) {}, + cleanup() { + cleanupCount++ + scriptListeners.clear() + htmlListeners.clear() + finishedListeners.clear() + pendingScripts.length = 0 + bufferedHtml.length = 0 + hydrationSources.length = 0 + hydrationSourceHead = 0 + hydrationSource = undefined + hydrationSegment = '' + hydrationSegmentOffset = 0 + hydrationPhase = HydrationRecordPhase.Opening + hydrationOutputCapacity = MIN_HYDRATION_OUTPUT_BYTES + hydrationListener = undefined + hydrationOutput = undefined + hydrationError = undefined + hydrationState = HydrationOutputState.Done + }, + } + return { + router: { options: {}, serverSsr }, + emit(source: string) { + if (hydrationOutput) { + hydrationSources.push(source) + refreshHydrationState() + } else if (scriptListeners.size > 0) { + for (const listener of scriptListeners) { + listener([source]) + } + } else { + pendingScripts.push(source) + } + if (htmlListeners.size > 0) { + const html = SCRIPT_OPEN + source + SCRIPT_CLOSE + bufferedHtml.push(html) + for (const listener of htmlListeners) { + listener(html) + } + if (bufferedHtml[0] === html) { + bufferedHtml.shift() + } + } + }, + finish() { + finished = true + refreshHydrationState() + for (const listener of finishedListeners) { + listener() + } + }, + barrier, + counts: () => ({ + cleanupCount, + renderFinishedCount, + reserveCalls, + fastPathGrants, + scriptSubscriptions, + htmlSubscriptions, + bufferedHtmlReads, + hydrationOutputClaims, + hydrationOutputSubscriptions, + hydrationOutputPulls, + }), + } +} + +function createInput( + scenario: Scenario, + mode: Mode, + onEof: () => void, + beforeEof?: Promise, + onBeforeEof?: () => void, +) { + if (mode === 'merge' && scenario.kind === 'application-string') { + return streamFromIterator( + [createApplicationString(scenario)][Symbol.iterator](), + onEof, + beforeEof, + onBeforeEof, + ) + } + if (mode === 'merge' && scenario.kind === 'hydration') { + return streamFromIterator( + [Buffer.from(PREFIX), Buffer.from(SUFFIX)][Symbol.iterator](), + onEof, + beforeEof, + onBeforeEof, + ) + } + if (mode === 'merge' && scenario.kind === 'renderer-records') { + return streamFromIterator( + rendererRecordApplicationBytes(scenario), + onEof, + beforeEof, + onBeforeEof, + ) + } + return streamFromIterator( + integratedBytes(scenario), + onEof, + beforeEof, + onBeforeEof, + ) +} + +function findNeedle(chunk: Uint8Array, needle: Buffer, tail: Buffer) { + const value = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) + let count = 0 + + if (tail.length > 0 && value.length > 0) { + const headLength = Math.min(value.length, needle.length - 1) + const boundary = Buffer.allocUnsafe(tail.length + headLength) + boundary.set(tail) + boundary.set(value.subarray(0, headLength), tail.length) + let offset = 0 + for (;;) { + const found = boundary.indexOf(needle, offset) + if (found === -1) { + break + } + if (found < tail.length && found + needle.length > tail.length) { + count++ + } + offset = found + 1 + } + } + + let offset = 0 + for (;;) { + const found = value.indexOf(needle, offset) + if (found === -1) { + break + } + count++ + offset = found + 1 + } + + const keep = Math.min(needle.length - 1, tail.length + value.length) + let nextTail: Buffer + if (keep === 0) { + nextTail = Buffer.alloc(0) + } else if (value.length >= keep) { + nextTail = Buffer.from(value.subarray(value.length - keep)) + } else { + nextTail = Buffer.allocUnsafe(keep) + const tailBytes = keep - value.length + nextTail.set(tail.subarray(tail.length - tailBytes)) + nextTail.set(value, tailBytes) + } + return { + count, + tail: nextTail, + } +} + +export async function run( + transform: Transform, + implementation: string, + scenarioName: string, + mode: Mode, + writeResult = true, + measureMemory = true, + validateOutput = true, +) { + const scenario = parseScenario(scenarioName) + const expectedOutput = getExpectedOutput(scenario, mode) + const routerSource = getRouterSource(scenario) + const containsRouterScripts = routerSource !== undefined + const hasLateScripts = mode === 'merge' && containsRouterScripts + const fake = makeRouter(mode !== 'merge') + let resolveProducerComplete!: () => void + const producerComplete = new Promise((resolve) => { + resolveProducerComplete = resolve + }) + if (!hasLateScripts) { + resolveProducerComplete() + } + let resolveAppContentConsumed!: () => void + const appContentConsumed = new Promise((resolve) => { + resolveAppContentConsumed = resolve + }) + if (scenario.kind !== 'renderer-records' || mode !== 'merge') { + resolveAppContentConsumed() + } + let startedAt = 0 + let rendererEofMs: number | null = null + const input = createInput( + scenario, + mode, + () => { + rendererEofMs = performance.now() - startedAt + if (mode === 'merge' && !hasLateScripts) { + fake.finish() + } + }, + hasLateScripts ? producerComplete : undefined, + resolveAppContentConsumed, + ) + if (measureMemory) { + forceGc() + } + const baseline = measureMemory ? memory() : undefined + const peak: Memory = { heapUsed: 0, external: 0, arrayBuffers: 0, rss: 0 } + const sample = () => { + if (!measureMemory) { + return + } + const value = delta(memory(), baseline!) + maxMemory(peak, value) + } + + startedAt = performance.now() + const output = + mode === 'raw' + ? (input as ReadableStream) + : transform( + fake.router, + input, + scenario.rendererSafePoint + ? { rendererSafePoint: scenario.rendererSafePoint } + : {}, + ) + + let sourceProducerMs = 0 + let producerFinishedMs: number | null = null + let outstandingSourceRecords = 0 + let outstandingSourceCodeUnits = 0 + let sourceRecordHighWater = 0 + let sourceCodeUnitHighWater = 0 + const producer = hasLateScripts + ? (async () => { + await fake.barrier + await appContentConsumed + const sourceStartedAt = performance.now() + for (let index = 0; index < routerSource!.records; index++) { + const source = createSource( + routerSource!.recordBytes, + index, + routerSource!.shape, + ) + outstandingSourceRecords++ + outstandingSourceCodeUnits += source.length + sourceRecordHighWater = Math.max( + sourceRecordHighWater, + outstandingSourceRecords, + ) + sourceCodeUnitHighWater = Math.max( + sourceCodeUnitHighWater, + outstandingSourceCodeUnits, + ) + fake.emit(source) + if (index % 16 === 15) { + await new Promise((resolve) => setImmediate(resolve)) + } + } + fake.finish() + sourceProducerMs = performance.now() - sourceStartedAt + producerFinishedMs = performance.now() - startedAt + sample() + resolveProducerComplete() + })() + : Promise.resolve() + + const reader = output.getReader() + const hash = validateOutput ? createHash('sha256') : undefined + const firstScriptNeedle = Buffer.from(marker(0)) + const completedScriptNeedle = Buffer.from(SCRIPT_CLOSE) + let firstScriptTail: Buffer = Buffer.alloc(0) + let completedScriptTail: Buffer = Buffer.alloc(0) + let firstRouterScriptMs: number | null = null + let bytes = 0 + let chunks = 0 + let maxOutputChunkBytes = 0 + let ttfbMs: number | null = null + for (;;) { + const result = await reader.read() + if (result.done) { + break + } + const now = performance.now() + if (ttfbMs === null) { + ttfbMs = now - startedAt + } + const value = result.value + bytes += value.byteLength + chunks++ + maxOutputChunkBytes = Math.max(maxOutputChunkBytes, value.byteLength) + hash?.update(value) + if ( + validateOutput && + containsRouterScripts && + firstRouterScriptMs === null + ) { + const match = findNeedle(value, firstScriptNeedle, firstScriptTail) + firstScriptTail = match.tail + if (match.count > 0) { + firstRouterScriptMs = now - startedAt + } + } + if (validateOutput && hasLateScripts) { + const completed = findNeedle( + value, + completedScriptNeedle, + completedScriptTail, + ) + completedScriptTail = completed.tail + if (completed.count > 0) { + outstandingSourceRecords -= completed.count + outstandingSourceCodeUnits -= + completed.count * routerSource!.recordBytes + } + } + if (chunks % 16 === 0) { + sample() + } + } + await producer + sample() + const elapsedMs = performance.now() - startedAt + const digest = hash?.digest('hex') ?? expectedOutput.digest + const memoryBeforeFinalGc = measureMemory ? memory() : undefined + if (measureMemory) { + maxMemory(peak, delta(memoryBeforeFinalGc!, baseline!)) + forceGc() + } + const finalMemory = measureMemory ? memory() : undefined + const counts = fake.counts() + let selectedApi: + | 'none' + | 'hydration-output' + | 'script-batch' + | 'injected-html' + | 'buffered-html' = 'none' + if ( + bytes !== expectedOutput.bytes || + (validateOutput && digest !== expectedOutput.digest) + ) { + throw new Error( + `Output validation failed: ${bytes}/${digest} !== ${expectedOutput.bytes}/${expectedOutput.digest}`, + ) + } + if (validateOutput && hasLateScripts && outstandingSourceRecords !== 0) { + throw new Error( + `Only ${routerSource!.records - outstandingSourceRecords} router records completed`, + ) + } + if (validateOutput && containsRouterScripts && firstRouterScriptMs === null) { + throw new Error('The output did not contain the first router script') + } + if ( + validateOutput && + hasLateScripts && + scenario.kind === 'hydration' && + (firstRouterScriptMs === null || + rendererEofMs === null || + firstRouterScriptMs >= rendererEofMs) + ) { + throw new Error( + `Router source did not start before renderer EOF: ${firstRouterScriptMs}/${rendererEofMs}`, + ) + } + if ( + validateOutput && + hasLateScripts && + (producerFinishedMs === null || + rendererEofMs === null || + producerFinishedMs > rendererEofMs) + ) { + throw new Error( + `Router producer finished after renderer EOF: ${producerFinishedMs}/${rendererEofMs}`, + ) + } + if ( + mode !== 'raw' && + (counts.cleanupCount < 1 || counts.renderFinishedCount !== 1) + ) { + throw new Error(`Invalid lifecycle counts: ${JSON.stringify(counts)}`) + } + if ( + mode === 'fast' && + (counts.reserveCalls !== 1 || + counts.fastPathGrants !== 1 || + counts.hydrationOutputClaims !== 0 || + counts.hydrationOutputSubscriptions !== 0 || + counts.hydrationOutputPulls !== 0) + ) { + throw new Error( + `Fast path was not selected exactly once: ${JSON.stringify(counts)}`, + ) + } + if (mode === 'merge') { + const mergeApi = + counts.hydrationOutputClaims === 1 && + counts.hydrationOutputSubscriptions === 1 && + counts.scriptSubscriptions === 0 && + counts.htmlSubscriptions === 0 + ? 'hydration-output' + : counts.hydrationOutputClaims === 0 && + counts.scriptSubscriptions === 1 && + counts.htmlSubscriptions === 0 + ? 'script-batch' + : counts.hydrationOutputClaims === 0 && + counts.scriptSubscriptions === 0 && + counts.htmlSubscriptions === 1 + ? counts.bufferedHtmlReads > 0 + ? 'buffered-html' + : 'injected-html' + : undefined + if (!mergeApi || counts.reserveCalls < 1) { + throw new Error( + `Merge path/API assertion failed: ${JSON.stringify(counts)}`, + ) + } + selectedApi = mergeApi + } + const dynamicPassThroughSelected = + mode === 'merge' && counts.fastPathGrants === 1 + const result = { + implementation, + scenario: scenario.name, + framework: scenario.framework, + rendererSafePoint: scenario.rendererSafePoint, + mode, + memoryMeasured: measureMemory, + selectedApi, + dynamicPassThroughSelected, + outputBytes: bytes, + outputSha256: digest, + chunks, + maxOutputChunkBytes, + ttfbMs, + firstRouterScriptMs, + producerFinishedMs, + rendererEofMs, + elapsedMs, + throughputMiBPerSecond: bytes / MiB / (elapsedMs / 1000), + sourceProducerMs, + sourceRecordHighWater, + sourceCodeUnitHighWater, + memoryBaselineBytes: baseline, + memoryPeakBytes: measureMemory ? peak : undefined, + memoryBeforeFinalGcBytes: memoryBeforeFinalGc, + memoryBeforeFinalGcDeltaBytes: measureMemory + ? delta(memoryBeforeFinalGc!, baseline!) + : undefined, + memoryAfterFinalGcBytes: finalMemory, + memoryAfterFinalGcDeltaBytes: measureMemory + ? delta(finalMemory!, baseline!) + : undefined, + resourceUsage: measureMemory ? process.resourceUsage() : undefined, + lifecycle: counts, + } + if (writeResult) { + process.stdout.write(`${JSON.stringify(result)}\n`) + } + return result +} + +type NumericSummary = { + mean: number + median: number + p10: number + p90: number + min: number + max: number +} + +function summarizeNumbers(values: Array): NumericSummary { + const sorted = values.slice().sort((a, b) => a - b) + const at = (fraction: number) => + sorted[Math.floor((sorted.length - 1) * fraction)]! + const middle = Math.floor(sorted.length / 2) + const median = + sorted.length % 2 === 0 + ? (sorted[middle - 1]! + sorted[middle]!) / 2 + : sorted[middle]! + return { + mean: values.reduce((sum, value) => sum + value, 0) / values.length, + median, + p10: at(0.1), + p90: at(0.9), + min: sorted[0]!, + max: sorted[sorted.length - 1]!, + } +} + +type MeasuredRun = Awaited> + +type WarmBatch = { + requests: number + elapsedMs: number + wallElapsedMs: number + ttfbMs: number + outputBytes: number + outputSha256: string + chunks: number + maxOutputChunkBytes: number + sourceRecordHighWater: number + dynamicPassThroughRequests: number +} + +type WarmBatchAccumulator = Omit< + WarmBatch, + 'outputBytes' | 'outputSha256' | 'chunks' +> & { + first?: MeasuredRun +} + +function createWarmBatchAccumulator(requests: number): WarmBatchAccumulator { + return { + requests, + elapsedMs: 0, + wallElapsedMs: 0, + ttfbMs: 0, + maxOutputChunkBytes: 0, + sourceRecordHighWater: 0, + dynamicPassThroughRequests: 0, + } +} + +function recordWarmRun( + batch: WarmBatchAccumulator, + row: MeasuredRun, + wallElapsedMs: number, +) { + batch.first ??= row + batch.elapsedMs += row.elapsedMs + batch.wallElapsedMs += wallElapsedMs + batch.ttfbMs += row.ttfbMs! + batch.maxOutputChunkBytes = Math.max( + batch.maxOutputChunkBytes, + row.maxOutputChunkBytes, + ) + batch.sourceRecordHighWater = Math.max( + batch.sourceRecordHighWater, + row.sourceRecordHighWater, + ) + if (row.dynamicPassThroughSelected) { + batch.dynamicPassThroughRequests++ + } +} + +function finishWarmBatch(batch: WarmBatchAccumulator): WarmBatch { + const { first, ...totals } = batch + if (!first) { + throw new Error('A warm benchmark batch did not run any requests') + } + return { + ...totals, + outputBytes: first.outputBytes, + outputSha256: first.outputSha256, + chunks: first.chunks, + } +} + +async function runWarmPair( + baselineName: BaselineImplementation, + baselineTransform: Transform, + worktreeTransform: Transform, + scenario: Scenario, + mode: Mode, + requests: number, + startWith: 'baseline' | 'worktree', +) { + const batches = { + baseline: createWarmBatchAccumulator(requests), + worktree: createWarmBatchAccumulator(requests), + } + + for (let index = 0; index < requests; index++) { + const baselineFirst = (index & 1) === (startWith === 'baseline' ? 0 : 1) + let implementation: 'baseline' | 'worktree' = baselineFirst + ? 'baseline' + : 'worktree' + for (let position = 0; position < 2; position++) { + const wallStartedAt = performance.now() + const row = await run( + implementation === 'baseline' ? baselineTransform : worktreeTransform, + implementation === 'baseline' ? baselineName : 'worktree', + scenario.name, + mode, + false, + false, + false, + ) + recordWarmRun( + batches[implementation], + row, + performance.now() - wallStartedAt, + ) + implementation = implementation === 'baseline' ? 'worktree' : 'baseline' + } + } + + return { + baseline: finishWarmBatch(batches.baseline), + worktree: finishWarmBatch(batches.worktree), + } +} + +function summarizeWarmBatches( + implementation: string, + scenario: Scenario, + mode: Mode, + rows: Array, +) { + const batchRequests = rows[0]!.requests + const elapsedMs = summarizeNumbers( + rows.map((row) => row.elapsedMs / row.requests), + ) + const batchElapsedMs = summarizeNumbers(rows.map((row) => row.elapsedMs)) + const batchWallElapsedMs = summarizeNumbers( + rows.map((row) => row.wallElapsedMs), + ) + const ttfbMs = summarizeNumbers(rows.map((row) => row.ttfbMs / row.requests)) + const throughputMiBPerSecond = summarizeNumbers( + rows.map( + (row) => (row.outputBytes * row.requests) / MiB / (row.elapsedMs / 1000), + ), + ) + const dynamicPassThroughRequests = rows.reduce( + (total, row) => total + row.dynamicPassThroughRequests, + 0, + ) + return { + implementation, + scenario: scenario.name, + framework: scenario.framework, + rendererSafePoint: scenario.rendererSafePoint, + mode, + measurement: 'warm', + memoryMeasured: false, + iterations: rows.length, + batchRequests, + measuredRequests: rows.length * batchRequests, + dynamicPassThroughRequests, + dynamicPassThroughRate: + dynamicPassThroughRequests / (rows.length * batchRequests), + outputBytes: rows[0]!.outputBytes, + outputSha256: rows[0]!.outputSha256, + chunks: rows[0]!.chunks, + maxOutputChunkBytes: Math.max( + ...rows.map((row) => row.maxOutputChunkBytes), + ), + ttfbMs: ttfbMs.median, + elapsedMs: elapsedMs.median, + throughputMiBPerSecond: throughputMiBPerSecond.median, + sourceRecordHighWater: Math.max( + ...rows.map((row) => row.sourceRecordHighWater), + ), + statistics: { + elapsedMs, + batchElapsedMs, + batchWallElapsedMs, + ttfbMs, + throughputMiBPerSecond, + }, + } +} + +function summarizePercentRatios(values: Array) { + const logs = summarizeNumbers(values.map((value) => Math.log(value))) + const toPercent = (value: number) => (Math.exp(value) - 1) * 100 + return { + geometricMean: toPercent(logs.mean), + median: toPercent(logs.median), + p10: toPercent(logs.p10), + p90: toPercent(logs.p90), + min: toPercent(logs.min), + max: toPercent(logs.max), + } +} + +async function measureWarmComparison( + baselineName: BaselineImplementation, + baselineTransform: Transform, + worktreeTransform: Transform, + scenarioNames: Array, + requestedModes: Array, + warmups: number, + iterations: number, + batchRequests: number, +) { + const results = [] + const comparisons = [] + + for (const scenarioName of scenarioNames) { + const scenario = parseScenario(scenarioName) + const availableModes: Array = + scenario.kind === 'application-string' || + scenario.kind === 'coalesced-close' + ? ['merge'] + : scenario.kind !== 'renderer-records' && scenario.framework === 'react' + ? ['fast', 'merge'] + : ['merge'] + const modes = availableModes.filter((mode) => requestedModes.includes(mode)) + for (const mode of modes) { + await run( + baselineTransform, + baselineName, + scenario.name, + mode, + false, + false, + true, + ) + await run( + worktreeTransform, + 'worktree', + scenario.name, + mode, + false, + false, + true, + ) + forceGc() + for (let index = 0; index < warmups; index++) { + const order: Array<'baseline' | 'worktree'> = + index % 2 === 0 ? ['baseline', 'worktree'] : ['worktree', 'baseline'] + for (const implementation of order) { + await run( + implementation === 'baseline' + ? baselineTransform + : worktreeTransform, + implementation === 'baseline' ? baselineName : 'worktree', + scenario.name, + mode, + false, + false, + ) + } + } + + const rows: Record<'baseline' | 'worktree', Array> = { + baseline: [], + worktree: [], + } + const elapsedRatios: Array = [] + const wallElapsedRatios: Array = [] + for (let index = 0; index < iterations; index++) { + const pair = await runWarmPair( + baselineName, + baselineTransform, + worktreeTransform, + scenario, + mode, + batchRequests, + index % 2 === 0 ? 'baseline' : 'worktree', + ) + rows.baseline.push(pair.baseline) + rows.worktree.push(pair.worktree) + elapsedRatios.push(pair.worktree.elapsedMs / pair.baseline.elapsedMs) + wallElapsedRatios.push( + pair.worktree.wallElapsedMs / pair.baseline.wallElapsedMs, + ) + } + + const baseline = summarizeWarmBatches( + baselineName, + scenario, + mode, + rows.baseline, + ) + const worktree = summarizeWarmBatches( + 'worktree', + scenario, + mode, + rows.worktree, + ) + const baselineElapsedTotal = rows.baseline.reduce( + (total, row) => total + row.elapsedMs, + 0, + ) + const worktreeElapsedTotal = rows.worktree.reduce( + (total, row) => total + row.elapsedMs, + 0, + ) + const baselineWallTotal = rows.baseline.reduce( + (total, row) => total + row.wallElapsedMs, + 0, + ) + const worktreeWallTotal = rows.worktree.reduce( + (total, row) => total + row.wallElapsedMs, + 0, + ) + results.push( + { ...baseline, comparisonBaseline: baselineName }, + { ...worktree, comparisonBaseline: baselineName }, + ) + comparisons.push({ + baseline: baselineName, + scenario: scenario.name, + framework: scenario.framework, + rendererSafePoint: scenario.rendererSafePoint, + mode, + pairedElapsedPercent: summarizePercentRatios(elapsedRatios), + pairedWallElapsedPercent: summarizePercentRatios(wallElapsedRatios), + aggregateElapsedPercent: + (worktreeElapsedTotal / baselineElapsedTotal - 1) * 100, + aggregateWallElapsedPercent: + (worktreeWallTotal / baselineWallTotal - 1) * 100, + elapsedMedianPercent: + (worktree.statistics.elapsedMs.median / + baseline.statistics.elapsedMs.median - + 1) * + 100, + samples: rows.baseline.map((baselineRow, index) => ({ + baselineElapsedMs: baselineRow.elapsedMs, + candidateElapsedMs: rows.worktree[index]!.elapsedMs, + baselineWallElapsedMs: baselineRow.wallElapsedMs, + candidateWallElapsedMs: rows.worktree[index]!.wallElapsedMs, + elapsedRatio: elapsedRatios[index]!, + wallElapsedRatio: wallElapsedRatios[index]!, + })), + }) + } + } + + return { + warmups, + iterations, + batchRequests, + measuredRequestsPerImplementation: iterations * batchRequests, + scenarios: scenarioNames, + order: `${baselineName}/worktree order alternates for every request and reverses at each batch start`, + validation: + 'SHA-256 and marker checks in untimed preflight/warm-up requests; timed requests retain byte, lifecycle, and API checks', + source: + 'fresh renderer bytes for fast mode and one fresh router source string for merge mode', + memory: 'not measured in the warm latency loop', + garbageCollection: + 'forced once before warm-up; natural GC remains enabled for all measured batches', + results, + comparisons, + } +} + +export function runWarmComparison( + transforms: Record<'origin' | 'worktree', Transform>, + scenarioNames: Array, + requestedModes: Array, + warmups: number, + iterations: number, + batchRequests: number, +) { + return measureWarmComparison( + 'origin', + transforms.origin, + transforms.worktree, + scenarioNames, + requestedModes, + warmups, + iterations, + batchRequests, + ) +} + +function safeWindowEnd(value: string, start: number, wantedEnd: number) { + const end = Math.min(wantedEnd, value.length) + if (end <= start || end >= value.length) { + return end + } + const previous = value.charCodeAt(end - 1) + const next = value.charCodeAt(end) + return previous >= 0xd800 && + previous <= 0xdbff && + next >= 0xdc00 && + next <= 0xdfff + ? end - 1 + : end +} + +export function runProbe( + shape: Shape, + sizeMiB: number, + strategy: 'suffix' | 'window', +) { + const bytes = sizeMiB * MiB + const source = createSource(bytes, 0, shape) + const expectedHash = createHash('sha256') + updateSource(expectedHash, bytes, 0) + const expectedDigest = expectedHash.digest('hex') + forceGc() + const baseline = memory() + const encoder = new TextEncoder() + const passes = [] + for (let pass = 1; pass <= 2; pass++) { + const hash = createHash('sha256') + const peak: Memory = { heapUsed: 0, external: 0, arrayBuffers: 0, rss: 0 } + let offset = 0 + let chunks = 0 + const startedAt = performance.now() + while (offset < source.length) { + const output = new Uint8Array(OUTPUT_BYTES) + const input = + strategy === 'suffix' + ? source.slice(offset) + : source.slice( + offset, + safeWindowEnd(source, offset, offset + OUTPUT_BYTES), + ) + const encoded = encoder.encodeInto(input, output) + if (encoded.read === 0) { + throw new Error('Probe encoder made no progress') + } + offset += encoded.read + hash.update(output.subarray(0, encoded.written)) + chunks++ + if (chunks % 16 === 0) { + maxMemory(peak, delta(memory(), baseline)) + } + } + const elapsedMs = performance.now() - startedAt + const digest = hash.digest('hex') + if (digest !== expectedDigest || offset !== source.length) { + throw new Error('Source-window probe validation failed') + } + maxMemory(peak, delta(memory(), baseline)) + forceGc() + const afterGc = delta(memory(), baseline) + passes.push({ + pass, + elapsedMs, + throughputMiBPerSecond: bytes / MiB / (elapsedMs / 1000), + chunks, + memoryPeakBytes: peak, + memoryAfterGcBytes: afterGc, + }) + } + process.stdout.write( + `${JSON.stringify({ + implementation: 'v8-probe', + scenario: `encode-${shape}-${sizeMiB}m`, + mode: strategy, + sourceReadyBaselineBytes: baseline, + outputBytes: bytes, + outputChunkBytes: OUTPUT_BYTES, + outputSha256: expectedDigest, + passes, + })}\n`, + ) +} + +type HydrationOwner = { + takeInitialHydrationScriptTags(): unknown + claimOutput(): { + state: number + pullChunk(): Uint8Array + } + liftBarrier(): void + pushSource(source: string): void + finish(): void + cleanup(): void +} + +type CreateHydrationOwner = ( + nonce: string | undefined, + initialSources: ReadonlyArray, +) => HydrationOwner + +type HydrationOwnerExpected = { + records: number + recordBytes: number + bytes: number + digest: string +} + +const hydrationOwnerExpectedCache = new Map() + +function getHydrationOwnerExpected(scenarioName: string) { + const cached = hydrationOwnerExpectedCache.get(scenarioName) + if (cached) { + return cached + } + const match = /^hydration-owner-(\d+)x(\d+)k$/.exec(scenarioName) + if (!match) { + throw new Error(`Unknown hydration-owner scenario: ${scenarioName}`) + } + const records = Number(match[1]) + const recordBytes = Number(match[2]) * 1024 + const hash = createHash('sha256') + let bytes = 0 + const addExpected = (value: string) => { + hash.update(value) + bytes += Buffer.byteLength(value) + } + let partIndex = 0 + while (partIndex <= records) { + const batchStart = partIndex + let codeUnits = SCRIPT_OPEN.length + SCRIPT_CLOSE.length - 1 + while (partIndex <= records) { + const partLength = + partIndex === records ? '$_TSR.e()'.length : recordBytes + const nextCodeUnits = codeUnits + 1 + partLength + if (partIndex > batchStart && nextCodeUnits > OUTPUT_BYTES) { + break + } + codeUnits = nextCodeUnits + partIndex++ + if (codeUnits > OUTPUT_BYTES) { + break + } + } + addExpected(SCRIPT_OPEN) + for (let index = batchStart; index < partIndex; index++) { + if (index > batchStart) { + addExpected(';') + } + if (index === records) { + addExpected('$_TSR.e()') + } else { + updateSource(hash, recordBytes, index) + bytes += recordBytes + } + } + addExpected(SCRIPT_CLOSE) + } + const expected = { + records, + recordBytes, + bytes, + digest: hash.digest('hex'), + } + hydrationOwnerExpectedCache.set(scenarioName, expected) + return expected +} + +function measureHydrationOwner( + createHydrationOwner: CreateHydrationOwner, + implementation: string, + scenarioName: string, + measureMemory: boolean, + validateOutput = true, +) { + const expected = getHydrationOwnerExpected(scenarioName) + if (measureMemory) { + forceGc() + } + const baseline = measureMemory ? memory() : undefined + const peak: Memory = { heapUsed: 0, external: 0, arrayBuffers: 0, rss: 0 } + const sample = () => { + if (measureMemory) { + maxMemory(peak, delta(memory(), baseline!)) + } + } + const owner = createHydrationOwner(undefined, []) + owner.takeInitialHydrationScriptTags() + const output = owner.claimOutput() + owner.liftBarrier() + for (let index = 0; index < expected.records; index++) { + owner.pushSource(createSource(expected.recordBytes, index, 'flat')) + } + owner.finish() + sample() + const hash = validateOutput ? createHash('sha256') : undefined + let bytes = 0 + let chunks = 0 + let maxOutputChunkBytes = 0 + const startedAt = performance.now() + while ( + output.state === HydrationOutputState.Ready || + output.state === HydrationOutputState.Active + ) { + const chunk = output.pullChunk() + hash?.update(chunk) + bytes += chunk.byteLength + chunks++ + maxOutputChunkBytes = Math.max(maxOutputChunkBytes, chunk.byteLength) + if (measureMemory && (chunks & 15) === 0) { + sample() + } + } + const elapsedMs = performance.now() - startedAt + if (measureMemory) { + sample() + } + const digest = hash?.digest('hex') ?? expected.digest + if ( + output.state !== HydrationOutputState.Done || + bytes !== expected.bytes || + (validateOutput && digest !== expected.digest) || + maxOutputChunkBytes > OUTPUT_BYTES + ) { + throw new Error( + `Hydration-owner validation failed: ${output.state}/${bytes}/${digest}/${maxOutputChunkBytes}`, + ) + } + owner.cleanup() + return { + implementation, + scenario: scenarioName, + framework: 'router-core', + mode: 'owner', + outputBytes: bytes, + outputSha256: digest, + chunks, + maxOutputChunkBytes, + elapsedMs, + throughputMiBPerSecond: bytes / MiB / (elapsedMs / 1000), + memoryPeakBytes: measureMemory ? peak : undefined, + sourceRecordHighWater: expected.records + 1, + } +} + +export function runHydrationOwner( + createHydrationOwner: CreateHydrationOwner, + implementation: string, + scenarioName: string, +) { + process.stdout.write( + `${JSON.stringify( + measureHydrationOwner( + createHydrationOwner, + implementation, + scenarioName, + true, + ), + )}\n`, + ) +} + +export function runHydrationOwnerSoak( + createHydrationOwner: CreateHydrationOwner, + implementation: string, + scenarioName: string, +) { + const expected = getHydrationOwnerExpected(scenarioName) + const requestsPerBlock = expected.records > 1000 ? 5 : 500 + const blocks = 10 + measureHydrationOwner( + createHydrationOwner, + implementation, + scenarioName, + false, + true, + ) + for (let index = 0; index < Math.min(100, requestsPerBlock); index++) { + measureHydrationOwner( + createHydrationOwner, + implementation, + scenarioName, + false, + false, + ) + } + forceGc() + const baseline = memory() + const highWater: Memory = { + heapUsed: 0, + external: 0, + arrayBuffers: 0, + rss: 0, + } + const checkpoints = [] + const startedAt = performance.now() + for (let block = 1; block <= blocks; block++) { + for (let request = 0; request < requestsPerBlock; request++) { + measureHydrationOwner( + createHydrationOwner, + implementation, + scenarioName, + false, + false, + ) + } + forceGc() + const retained = delta(memory(), baseline) + maxMemory(highWater, retained) + checkpoints.push({ block, requests: block * requestsPerBlock, retained }) + } + const elapsedMs = performance.now() - startedAt + const finalRetained = checkpoints.at(-1)!.retained + process.stdout.write( + `${JSON.stringify({ + implementation, + scenario: scenarioName, + framework: 'router-core', + mode: 'owner-soak', + requests: blocks * requestsPerBlock, + aggregateOutputBytes: expected.bytes * blocks * requestsPerBlock, + validatedPerRequestOutputSha256: expected.digest, + elapsedIncludingGcMs: elapsedMs, + throughputIncludingGcMiBPerSecond: + (expected.bytes * blocks * requestsPerBlock) / MiB / (elapsedMs / 1000), + retainedHighWaterBytes: highWater, + retainedAfterFinalGcBytes: finalRetained, + retentionCheckpoints: checkpoints, + sourceRecordHighWater: expected.records + 1, + })}\n`, + ) +} + +export function runWarmHydrationOwnerComparison( + factories: Record<'origin' | 'worktree', CreateHydrationOwner>, + scenarioNames: Array, + warmups: number, + iterations: number, + batchRequests: number, +) { + const results = [] + const comparisons = [] + for (const scenarioName of scenarioNames) { + measureHydrationOwner(factories.origin, 'origin', scenarioName, false, true) + measureHydrationOwner( + factories.worktree, + 'worktree', + scenarioName, + false, + true, + ) + forceGc() + for (let index = 0; index < warmups; index++) { + const first = index % 2 === 0 ? 'origin' : 'worktree' + const second = first === 'origin' ? 'worktree' : 'origin' + measureHydrationOwner(factories[first], first, scenarioName, false, false) + measureHydrationOwner( + factories[second], + second, + scenarioName, + false, + false, + ) + } + const elapsed: Record<'origin' | 'worktree', Array> = { + origin: [], + worktree: [], + } + const wall: Record<'origin' | 'worktree', Array> = { + origin: [], + worktree: [], + } + const samples = [] + const firstResult: Partial< + Record<'origin' | 'worktree', ReturnType> + > = {} + for (let iteration = 0; iteration < iterations; iteration++) { + const totals = { + origin: { elapsed: 0, wall: 0 }, + worktree: { elapsed: 0, wall: 0 }, + } + for (let request = 0; request < batchRequests; request++) { + const originFirst = (request & 1) === (iteration & 1) + const order: Array<'origin' | 'worktree'> = originFirst + ? ['origin', 'worktree'] + : ['worktree', 'origin'] + for (const implementation of order) { + const startedAt = performance.now() + const row = measureHydrationOwner( + factories[implementation], + implementation, + scenarioName, + false, + false, + ) + firstResult[implementation] ??= row + totals[implementation].wall += performance.now() - startedAt + totals[implementation].elapsed += row.elapsedMs + } + } + elapsed.origin.push(totals.origin.elapsed / batchRequests) + elapsed.worktree.push(totals.worktree.elapsed / batchRequests) + wall.origin.push(totals.origin.wall / batchRequests) + wall.worktree.push(totals.worktree.wall / batchRequests) + samples.push({ + baselineElapsedMs: totals.origin.elapsed, + candidateElapsedMs: totals.worktree.elapsed, + baselineWallElapsedMs: totals.origin.wall, + candidateWallElapsedMs: totals.worktree.wall, + elapsedRatio: totals.worktree.elapsed / totals.origin.elapsed, + wallElapsedRatio: totals.worktree.wall / totals.origin.wall, + }) + } + const originElapsed = summarizeNumbers(elapsed.origin) + const worktreeElapsed = summarizeNumbers(elapsed.worktree) + for (const implementation of ['origin', 'worktree'] as const) { + const statistics = summarizeNumbers(elapsed[implementation]) + results.push({ + ...firstResult[implementation], + implementation, + measurement: 'warm', + memoryMeasured: false, + iterations, + batchRequests, + measuredRequests: iterations * batchRequests, + elapsedMs: statistics.median, + throughputMiBPerSecond: + firstResult[implementation]!.outputBytes / + MiB / + (statistics.median / 1000), + statistics: { elapsedMs: statistics }, + comparisonBaseline: 'origin', + }) + } + comparisons.push({ + baseline: 'origin', + scenario: scenarioName, + framework: 'router-core', + mode: 'owner', + pairedElapsedPercent: summarizePercentRatios( + samples.map((sample) => sample.elapsedRatio), + ), + pairedWallElapsedPercent: summarizePercentRatios( + samples.map((sample) => sample.wallElapsedRatio), + ), + aggregateElapsedPercent: + (worktreeElapsed.mean / originElapsed.mean - 1) * 100, + aggregateWallElapsedPercent: + (summarizeNumbers(wall.worktree).mean / + summarizeNumbers(wall.origin).mean - + 1) * + 100, + elapsedMedianPercent: + (worktreeElapsed.median / originElapsed.median - 1) * 100, + samples, + }) + } + return { + warmups, + iterations, + batchRequests, + measuredRequestsPerImplementation: iterations * batchRequests, + scenarios: scenarioNames, + order: 'origin/worktree order alternates for every request and batch', + validation: + 'SHA-256 in one untimed preflight per implementation; timed requests retain byte, state, and output-limit checks', + memory: 'not measured in the warm latency loop', + garbageCollection: 'forced once before each scenario warm-up', + results, + comparisons, + } +} diff --git a/packages/router-core/eslint.config.js b/packages/router-core/eslint.config.js index 657b7e420b..ca29e6c97b 100644 --- a/packages/router-core/eslint.config.js +++ b/packages/router-core/eslint.config.js @@ -7,7 +7,6 @@ export default [ { files: ['src/**/*.{ts,tsx}', 'tests/**/*.{ts,tsx}'], rules: { - 'unused-imports/no-unused-vars': 'off', '@typescript-eslint/no-unnecessary-condition': 'off', }, }, diff --git a/packages/router-core/package.json b/packages/router-core/package.json index 697ed81ce5..ed2b794278 100644 --- a/packages/router-core/package.json +++ b/packages/router-core/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-core", - "version": "1.141.8", + "version": "1.171.39", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -22,12 +22,12 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch", @@ -68,26 +68,135 @@ "default": "./dist/cjs/ssr/client.cjs" } }, + "./isServer": { + "development": { + "import": { + "types": "./dist/esm/isServer/development.d.ts", + "default": "./dist/esm/isServer/development.js" + }, + "require": { + "types": "./dist/cjs/isServer/development.d.cts", + "default": "./dist/cjs/isServer/development.cjs" + } + }, + "workerd": { + "import": { + "types": "./dist/esm/isServer/server.d.ts", + "default": "./dist/esm/isServer/server.js" + }, + "require": { + "types": "./dist/cjs/isServer/server.d.cts", + "default": "./dist/cjs/isServer/server.cjs" + } + }, + "worker": { + "import": { + "types": "./dist/esm/isServer/server.d.ts", + "default": "./dist/esm/isServer/server.js" + }, + "require": { + "types": "./dist/cjs/isServer/server.d.cts", + "default": "./dist/cjs/isServer/server.cjs" + } + }, + "browser": { + "import": { + "types": "./dist/esm/isServer/client.d.ts", + "default": "./dist/esm/isServer/client.js" + }, + "require": { + "types": "./dist/cjs/isServer/client.d.cts", + "default": "./dist/cjs/isServer/client.cjs" + } + }, + "deno": { + "import": { + "types": "./dist/esm/isServer/server.d.ts", + "default": "./dist/esm/isServer/server.js" + }, + "require": { + "types": "./dist/cjs/isServer/server.d.cts", + "default": "./dist/cjs/isServer/server.cjs" + } + }, + "node": { + "import": { + "types": "./dist/esm/isServer/server.d.ts", + "default": "./dist/esm/isServer/server.js" + }, + "require": { + "types": "./dist/cjs/isServer/server.d.cts", + "default": "./dist/cjs/isServer/server.cjs" + } + }, + "bun": { + "import": { + "types": "./dist/esm/isServer/server.d.ts", + "default": "./dist/esm/isServer/server.js" + }, + "require": { + "types": "./dist/cjs/isServer/server.d.cts", + "default": "./dist/cjs/isServer/server.cjs" + } + }, + "import": { + "types": "./dist/esm/isServer/client.d.ts", + "default": "./dist/esm/isServer/client.js" + }, + "require": { + "types": "./dist/cjs/isServer/client.d.cts", + "default": "./dist/cjs/isServer/client.cjs" + } + }, + "./scroll-restoration-script": { + "browser": { + "import": { + "types": "./dist/esm/scroll-restoration-script/client.d.ts", + "default": "./dist/esm/scroll-restoration-script/client.js" + }, + "require": { + "types": "./dist/cjs/scroll-restoration-script/client.d.cts", + "default": "./dist/cjs/scroll-restoration-script/client.cjs" + } + }, + "import": { + "types": "./dist/esm/scroll-restoration-script/server.d.ts", + "default": "./dist/esm/scroll-restoration-script/server.js" + }, + "require": { + "types": "./dist/cjs/scroll-restoration-script/server.d.cts", + "default": "./dist/cjs/scroll-restoration-script/server.cjs" + } + }, "./package.json": "./package.json" }, "sideEffects": false, "files": [ "dist", - "src" + "src", + "skills", + "bin", + "!skills/_artifacts" ], "engines": { - "node": ">=12" + "node": ">=20.19" }, "dependencies": { "@tanstack/history": "workspace:*", - "@tanstack/store": "^0.8.0", - "cookie-es": "^2.0.0", - "seroval": "^1.4.1", - "seroval-plugins": "^1.4.0", - "tiny-invariant": "^1.3.3", - "tiny-warning": "^1.0.3" + "cookie-es": "^3.0.0", + "seroval": "^1.6.7", + "seroval-plugins": "^1.6.7" }, "devDependencies": { - "esbuild": "^0.25.0" + "@tanstack/store": "^0.11.2", + "@types/node": "25.0.9", + "esbuild": "^0.27.4", + "vite": "catalog:", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" } } diff --git a/packages/router-core/skills/router-core/SKILL.md b/packages/router-core/skills/router-core/SKILL.md new file mode 100644 index 0000000000..cadb832037 --- /dev/null +++ b/packages/router-core/skills/router-core/SKILL.md @@ -0,0 +1,158 @@ +--- +name: router-core +description: >- + Framework-agnostic core concepts for TanStack Router: route trees, + createRouter, createRoute, createRootRoute, createRootRouteWithContext, + addChildren, Register type declaration, route matching, route sorting, + file naming conventions. Entry point for all router skills. +metadata: + type: core + library: tanstack-router + library_version: '1.171.15' +--- + +# TanStack Router Core + +TanStack Router is a type-safe router for React and Solid with built-in SWR caching, JSON-first search params, file-based route generation, and end-to-end type inference. The core is framework-agnostic; React and Solid bindings layer on top. + +> **CRITICAL**: TanStack Router types are FULLY INFERRED. Never cast, never annotate inferred values. This is the #1 AI agent mistake. + +> **CRITICAL**: TanStack Router is CLIENT-FIRST. Loaders run on the client by default, NOT server-only like Remix/Next.js. Do not confuse TanStack Router APIs with Next.js or React Router. + +Use this entry skill to choose one primary sub-skill. Do not load the full catalog. Load a second sub-skill only when the task crosses a real boundary, such as an authenticated loader that needs both `auth-and-guards` and `data-loading`. + +## Sub-Skills + +| Task | Sub-Skill | +| -------------------------------------------------- | ---------------------------------------------------------------------------- | +| Validate, read, write, transform search params | [router-core/search-params/SKILL.md](./search-params/SKILL.md) | +| Dynamic segments, splats, optional params | [router-core/path-params/SKILL.md](./path-params/SKILL.md) | +| Link, useNavigate, preloading, blocking | [router-core/navigation/SKILL.md](./navigation/SKILL.md) | +| Route loaders, SWR caching, context, deferred data | [router-core/data-loading/SKILL.md](./data-loading/SKILL.md) | +| Auth guards, RBAC, beforeLoad redirects | [router-core/auth-and-guards/SKILL.md](./auth-and-guards/SKILL.md) | +| Automatic and manual code splitting | [router-core/code-splitting/SKILL.md](./code-splitting/SKILL.md) | +| 404 handling, error boundaries, notFound() | [router-core/not-found-and-errors/SKILL.md](./not-found-and-errors/SKILL.md) | +| Inference, Register, from narrowing, TS perf | [router-core/type-safety/SKILL.md](./type-safety/SKILL.md) | +| Streaming/non-streaming SSR, hydration, head mgmt | [router-core/ssr/SKILL.md](./ssr/SKILL.md) | + +## Quick Decision Tree + +``` +Need to add/read/write URL query parameters? + → router-core/search-params + +Need dynamic URL segments like /posts/$postId? + → router-core/path-params + +Need to create links or navigate programmatically? + → router-core/navigation + +Need to fetch data for a route? + Is it client-side only or client+server? + → router-core/data-loading + Using TanStack Query as external cache? + → compositions/router-query (separate skill) + +Need to protect routes behind auth? + → router-core/auth-and-guards + +Need to reduce bundle size per route? + → router-core/code-splitting + +Need custom 404 or error handling? + → router-core/not-found-and-errors + +Having TypeScript issues or performance problems? + → router-core/type-safety + +Need server-side rendering? + → router-core/ssr +``` + +## Cross-Cutting Completion Checks + +For route refactors: + +1. Rename or move the route file; do not hand-edit the generated `createFileRoute` path. +2. Regenerate `routeTree.gen.ts` with the configured Router plugin or CLI. +3. Update links, redirects, `from` narrowing, params, and tests that reference the old route. +4. Run type tests and a production build. A typecheck alone does not prove route generation or bundling works. + +For response schema changes: + +1. Update the source model and shared validation schema. +2. Update the server function or API serializer so the field exists at runtime. +3. Update loader and component consumers without casts. +4. Assert the actual response payload in a unit or integration test. Typechecking cannot catch a serializer that omits the new field. + +## Minimal Working Example + +```tsx +// src/routes/__root.tsx +import { createRootRoute, Outlet } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: () => , +}) +``` + +```tsx +// src/routes/index.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: () =>

    Home

    , +}) +``` + +```tsx +// src/router.tsx +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ routeTree }) + +// REQUIRED for type safety — without this, Link/useNavigate have no autocomplete +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +export default router +``` + +```tsx +// src/main.tsx +import { RouterProvider } from '@tanstack/react-router' +import router from './router' + +function App() { + return +} +``` + +## Common Mistakes + +### HIGH: createFileRoute path string must match the file path + +The Vite plugin manages the path string in `createFileRoute`. Do not change it manually — it must match the file's location under `src/routes/`: + +```tsx +// File: src/routes/posts/$postId.tsx +export const Route = createFileRoute('/posts/$postId')({ + // ✅ matches file path + component: PostPage, +}) + +export const Route = createFileRoute('/post/$postId')({ + // ❌ silent mismatch + component: PostPage, +}) +``` + +The plugin auto-generates this string. If you rename a route file, the plugin updates it. Never edit the path string by hand. + +## Version Note + +This skill targets `@tanstack/router-core` v1.171.15. Splat routes use `$` (not `*`); the `*` compat alias will be removed in v2. diff --git a/packages/router-core/skills/router-core/auth-and-guards/SKILL.md b/packages/router-core/skills/router-core/auth-and-guards/SKILL.md new file mode 100644 index 0000000000..4d1a6a3b6e --- /dev/null +++ b/packages/router-core/skills/router-core/auth-and-guards/SKILL.md @@ -0,0 +1,499 @@ +--- +name: auth-and-guards +description: >- + Route protection with beforeLoad, redirect()/throw redirect(), + isRedirect helper, authenticated layout routes (_authenticated), + non-redirect auth (inline login), RBAC with roles and permissions, + auth provider integration (Auth0, Clerk, Supabase), router context + for auth state. +metadata: + type: sub-skill + library: tanstack-router + library_version: '1.171.15' +requires: + - router-core +sources: + - TanStack/router:docs/router/guide/authenticated-routes.md + - TanStack/router:docs/router/how-to/setup-authentication.md + - TanStack/router:docs/router/how-to/setup-auth-providers.md + - TanStack/router:docs/router/how-to/setup-rbac.md +--- + +# Auth and Guards + +> **This skill covers the routing side of auth.** Route guards are UX and navigation control; the data/API boundary still belongs in the server function, server route, or API endpoint that reads or mutates private data. For the **server-side primitives** — session cookies (`HttpOnly`/`Secure`/`SameSite`), external session helpers, OAuth `state` + PKCE, password-reset enumeration defense, CSRF, rate limiting — see `@tanstack/start-client-core#start-core/auth-server-primitives`. +> +> **CRITICAL**: A route guard (`beforeLoad`) does NOT protect a `createServerFn` declared on that route. Server functions are API endpoints reachable independently of the route that calls them. See "Route guards do not protect server functions" below. + +## Setup + +Protect routes with `beforeLoad` + `redirect()` in a pathless layout route (`_authenticated`): + +```tsx +// src/routes/_authenticated.tsx +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/_authenticated')({ + beforeLoad: ({ context, location }) => { + if (!context.auth.isAuthenticated) { + throw redirect({ + to: '/login', + search: { + redirect: location.href, + }, + }) + } + }, + // component defaults to Outlet — no need to declare it +}) +``` + +Any route file placed under `src/routes/_authenticated/` is automatically protected: + +```tsx +// src/routes/_authenticated/dashboard.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_authenticated/dashboard')({ + component: DashboardComponent, +}) + +function DashboardComponent() { + const { auth } = Route.useRouteContext() + return
    Welcome, {auth.user?.username}
    +} +``` + +## Core Patterns + +### Router Context for Auth State + +Auth state flows into the router via `createRootRouteWithContext` and `RouterProvider`'s `context` prop: + +```tsx +// src/routes/__root.tsx +import { createRootRouteWithContext, Outlet } from '@tanstack/react-router' + +interface AuthState { + isAuthenticated: boolean + user: { id: string; username: string; email: string } | null + login: (username: string, password: string) => Promise + logout: () => void +} + +interface MyRouterContext { + auth: AuthState +} + +export const Route = createRootRouteWithContext()({ + component: () => , +}) +``` + +```tsx +// src/router.tsx +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export const router = createRouter({ + routeTree, + context: { + auth: undefined!, // placeholder — filled by RouterProvider context prop + }, +}) + +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} +``` + +```tsx +// src/App.tsx +import { RouterProvider } from '@tanstack/react-router' +import { AuthProvider, useAuth } from './auth' +import { router } from './router' + +function InnerApp() { + const auth = useAuth() + // context prop injects live auth state WITHOUT recreating the router + return +} + +function App() { + return ( + + + + ) +} +``` + +The router is created once with a placeholder. `RouterProvider`'s `context` prop injects the live auth state on each render — this avoids recreating the router on auth changes (which would reset caches and rebuild the route tree). + +### Redirect-Based Auth with Redirect-Back + +Save the current location in search params so you can redirect back after login: + +```tsx +// src/routes/_authenticated.tsx +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/_authenticated')({ + beforeLoad: ({ context, location }) => { + if (!context.auth.isAuthenticated) { + throw redirect({ + to: '/login', + search: { redirect: location.href }, + }) + } + }, +}) +``` + +```tsx +// src/routes/login.tsx +import { createFileRoute, redirect } from '@tanstack/react-router' +import { useState, type FormEvent } from 'react' + +// Validate redirect target to prevent open redirect attacks +function sanitizeRedirect(url: unknown): string { + if (typeof url !== 'string' || !url.startsWith('/') || url.startsWith('//')) { + return '/' + } + return url +} + +export const Route = createFileRoute('/login')({ + validateSearch: (search) => ({ + redirect: sanitizeRedirect(search.redirect), + }), + beforeLoad: ({ context, search }) => { + if (context.auth.isAuthenticated) { + throw redirect({ to: search.redirect }) + } + }, + component: LoginComponent, +}) + +function LoginComponent() { + const { auth } = Route.useRouteContext() + const search = Route.useSearch() + const navigate = Route.useNavigate() + const [username, setUsername] = useState('') + const [password, setPassword] = useState('') + const [error, setError] = useState('') + + const handleSubmit = async (e: FormEvent) => { + e.preventDefault() + try { + await auth.login(username, password) + navigate({ to: search.redirect }) + } catch { + setError('Invalid credentials') + } + } + + return ( +
    + {error &&
    {error}
    } + setUsername(e.target.value)} /> + setPassword(e.target.value)} + /> + +
    + ) +} +``` + +### Non-Redirect Auth (Inline Login) + +Instead of redirecting, show a login form in place of the `Outlet`: + +```tsx +// src/routes/_authenticated.tsx +import { createFileRoute, Outlet } from '@tanstack/react-router' + +export const Route = createFileRoute('/_authenticated')({ + component: AuthenticatedLayout, +}) + +function AuthenticatedLayout() { + const { auth } = Route.useRouteContext() + + if (!auth.isAuthenticated) { + return + } + + return +} +``` + +This keeps the URL unchanged — the user stays on the same page and sees a login form instead of protected content. After authentication, `` renders and child routes appear. + +### RBAC with Roles and Permissions + +Extend auth state with role/permission helpers, then check in `beforeLoad`: + +```tsx +// src/auth.tsx +interface User { + id: string + username: string + email: string + roles: string[] + permissions: string[] +} + +interface AuthState { + isAuthenticated: boolean + user: User | null + hasRole: (role: string) => boolean + hasAnyRole: (roles: string[]) => boolean + hasPermission: (permission: string) => boolean + hasAnyPermission: (permissions: string[]) => boolean + login: (username: string, password: string) => Promise + logout: () => void +} +``` + +Admin-only layout route: + +```tsx +// src/routes/_authenticated/_admin.tsx +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/_authenticated/_admin')({ + beforeLoad: ({ context, location }) => { + if (!context.auth.hasRole('admin')) { + throw redirect({ + to: '/unauthorized', + search: { redirect: location.href }, + }) + } + }, +}) +``` + +Multi-role access: + +```tsx +// src/routes/_authenticated/_moderator.tsx +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/_authenticated/_moderator')({ + beforeLoad: ({ context, location }) => { + if (!context.auth.hasAnyRole(['admin', 'moderator'])) { + throw redirect({ + to: '/unauthorized', + search: { redirect: location.href }, + }) + } + }, +}) +``` + +Permission-based: + +```tsx +// src/routes/_authenticated/_users.tsx +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/_authenticated/_users')({ + beforeLoad: ({ context, location }) => { + if (!context.auth.hasAnyPermission(['users:read', 'users:write'])) { + throw redirect({ + to: '/unauthorized', + search: { redirect: location.href }, + }) + } + }, +}) +``` + +Page-level permission check (nested under an already-role-protected layout): + +```tsx +// src/routes/_authenticated/_users/manage.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_authenticated/_users/manage')({ + beforeLoad: ({ context }) => { + if (!context.auth.hasPermission('users:write')) { + throw new Error('Write permission required') + } + }, + component: UserManagement, +}) + +function UserManagement() { + const { auth } = Route.useRouteContext() + const canDelete = auth.hasPermission('users:delete') + + return ( +
    +

    User Management

    + {canDelete && } +
    + ) +} +``` + +### Handling Auth Check Failures (isRedirect) + +When `beforeLoad` has a try/catch, redirects (which work by throwing) can get swallowed. Use `isRedirect` to re-throw: + +```tsx +import { createFileRoute, redirect, isRedirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/_authenticated')({ + beforeLoad: async ({ context, location }) => { + try { + const user = await verifySession(context.auth) + if (!user) { + throw redirect({ + to: '/login', + search: { redirect: location.href }, + }) + } + return { user } + } catch (error) { + if (isRedirect(error)) throw error // re-throw redirect, don't swallow it + // Actual error — redirect to login + throw redirect({ + to: '/login', + search: { redirect: location.href }, + }) + } + }, +}) +``` + +## Common Mistakes + +### CRITICAL: Route guards do not protect server functions + +A `beforeLoad` redirect protects the **route's UI**, not the **server functions** declared on it. `createServerFn` produces an RPC endpoint reachable directly with its declared HTTP method regardless of which route renders the calling UI. An attacker doesn't have to load `/_authenticated/orders` — they can call this GET RPC endpoint directly. + +```tsx +// WRONG — handler has no auth check; the route guard doesn't help +import { createServerFn } from '@tanstack/react-start' +import { createFileRoute, redirect } from '@tanstack/react-router' + +const getMyOrders = createServerFn({ method: 'GET' }).handler(async () => { + return db.orders.findMany() // ← anyone can hit the RPC +}) + +export const Route = createFileRoute('/_authenticated/orders')({ + beforeLoad: ({ context }) => { + if (!context.auth.isAuthenticated) throw redirect({ to: '/login' }) + }, + loader: () => getMyOrders(), +}) +``` + +```tsx +// CORRECT — auth enforced on the handler itself, via middleware +import { createServerFn } from '@tanstack/react-start' +import { authMiddleware } from '~/server/auth-middleware' + +const getMyOrders = createServerFn({ method: 'GET' }) + .middleware([authMiddleware]) + .handler(async ({ context }) => { + return db.orders.findMany({ where: { userId: context.session.userId } }) + }) +``` + +Rule of thumb: every `createServerFn`, server route, or API endpoint that touches user data needs `authMiddleware` (or an equivalent in-handler check). The route guard is for the page experience; the endpoint guard is for the data. See `@tanstack/start-client-core#start-core/auth-server-primitives` for the full session/middleware pattern. + +### CRITICAL: The anonymous destination can still disclose protected data + +Protect the entire anonymous response, not only the API call. A public login or unauthorized page still leaks data if its title, copy, search params, or serialized loader state names the protected user, tenant, record, or resource. Test a direct anonymous request and follow redirects. Assert that the handler rejects before reading private data, no protected loader runs, the final HTML and serialized state contain no protected identity, and the redirect contains only a sanitized relative return URL. + +### HIGH: Auth check in component instead of beforeLoad + +Component-level auth checks cause a **flash of protected content** before the redirect: + +```tsx +// WRONG — protected content renders briefly before redirect +export const Route = createFileRoute('/_authenticated/dashboard')({ + component: () => { + const auth = useAuth() + if (!auth.isAuthenticated) return + return + }, +}) + +// CORRECT — beforeLoad runs before any rendering +export const Route = createFileRoute('/_authenticated/dashboard')({ + beforeLoad: ({ context }) => { + if (!context.auth.isAuthenticated) { + throw redirect({ to: '/login' }) + } + }, + component: Dashboard, +}) +``` + +### HIGH: Not re-throwing redirects in try/catch + +`redirect()` works by throwing. If `beforeLoad` has a try/catch, the redirect gets swallowed: + +```tsx +// WRONG — redirect is caught and swallowed +beforeLoad: async ({ context }) => { + try { + await validateSession(context.auth) + } catch (e) { + console.error(e) // swallows the redirect! + } +} + +// CORRECT — use isRedirect to distinguish intentional redirects from errors +import { isRedirect } from '@tanstack/react-router' + +beforeLoad: async ({ context }) => { + try { + await validateSession(context.auth) + } catch (e) { + if (isRedirect(e)) throw e + console.error(e) + } +} +``` + +### MEDIUM: Conditionally rendering root route component + +The root route always renders regardless of auth state. You cannot conditionally render its component: + +```tsx +// WRONG — root route always renders, this doesn't protect anything +export const Route = createRootRoute({ + component: () => { + if (!isAuthenticated()) return + return + }, +}) + +// CORRECT — use a pathless layout route for auth boundaries +// src/routes/_authenticated.tsx +export const Route = createFileRoute('/_authenticated')({ + beforeLoad: ({ context }) => { + if (!context.auth.isAuthenticated) { + throw redirect({ to: '/login' }) + } + }, +}) +``` + +Place protected routes as children of the `_authenticated` layout route. Public routes (login, home, etc.) live outside it. + +## Cross-References + +- See also: **router-core/data-loading/SKILL.md** — `beforeLoad` runs before `loader`; auth context flows into loader via route context +- See also: **start-core/auth-server-primitives/SKILL.md** — server-side session cookies, OAuth state + PKCE, CSRF, password-reset hardening, rate limiting (the server half of authentication) +- See also: **start-core/middleware/SKILL.md** — `authMiddleware` factory pattern for protecting individual `createServerFn` calls diff --git a/packages/router-core/skills/router-core/code-splitting/SKILL.md b/packages/router-core/skills/router-core/code-splitting/SKILL.md new file mode 100644 index 0000000000..aac9098121 --- /dev/null +++ b/packages/router-core/skills/router-core/code-splitting/SKILL.md @@ -0,0 +1,323 @@ +--- +name: code-splitting +description: >- + Automatic code splitting (autoCodeSplitting), .lazy.tsx convention, + createLazyFileRoute, createLazyRoute, lazyRouteComponent, getRouteApi + for typed hooks in split files, codeSplitGroupings per-route override, + splitBehavior programmatic config, critical vs non-critical properties. +metadata: + type: sub-skill + library: tanstack-router + library_version: '1.171.15' +requires: + - router-core +sources: + - TanStack/router:docs/router/guide/code-splitting.md + - TanStack/router:docs/router/guide/automatic-code-splitting.md +--- + +# Code Splitting + +TanStack Router separates route code into **critical** (required to match and start loading) and **non-critical** (can be lazy-loaded). The bundler plugin can split automatically, or you can split manually with `.lazy.tsx` files. + +> **CRITICAL**: Never `export` component functions from route files — exported functions are included in the main bundle and bypass code splitting entirely. + +> **CRITICAL**: Use `getRouteApi('/path')` in code-split files, NOT `import { Route } from './route'`. Importing Route defeats code splitting. + +## What Stays in the Main Bundle (Critical) + +- Path parsing/serialization +- `validateSearch` +- `loader`, `beforeLoad` +- Route context, static data +- Links, scripts, styles + +## What Gets Split (Non-Critical) + +- `component` +- `errorComponent` +- `pendingComponent` +- `notFoundComponent` + +> The `loader` is NOT split by default. It is already async, so splitting it adds a double async cost: fetch the chunk, then execute the loader. Only split the loader if you have a specific reason. + +## Setup: Automatic Code Splitting + +Enable `autoCodeSplitting: true` in the bundler plugin. This is the recommended approach. + +```ts +// vite.config.ts +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + // TanStack Router plugin MUST come before the framework plugin + tanstackRouter({ + autoCodeSplitting: true, + }), + react(), + ], +}) +``` + +With this enabled, route files are automatically transformed. Components are split into separate chunks; loaders stay in the main bundle. No `.lazy.tsx` files needed. + +```tsx +// src/routes/posts.tsx — everything in one file, splitting is automatic +import { createFileRoute } from '@tanstack/react-router' +import { fetchPosts } from '../api' + +export const Route = createFileRoute('/posts')({ + loader: fetchPosts, + component: PostsComponent, +}) + +// NOT exported — this is critical for automatic code splitting to work +function PostsComponent() { + const posts = Route.useLoaderData() + return ( +
      + {posts.map((post) => ( +
    • {post.title}
    • + ))} +
    + ) +} +``` + +## Manual Splitting with `.lazy.tsx` + +If you cannot use automatic code splitting (e.g. CLI-only, no bundler plugin), split manually into two files: + +```tsx +// src/routes/posts.tsx — critical route config only +import { createFileRoute } from '@tanstack/react-router' +import { fetchPosts } from '../api' + +export const Route = createFileRoute('/posts')({ + loader: fetchPosts, +}) +``` + +```tsx +// src/routes/posts.lazy.tsx — non-critical (lazy-loaded) +import { createLazyFileRoute } from '@tanstack/react-router' + +export const Route = createLazyFileRoute('/posts')({ + component: PostsComponent, +}) + +function PostsComponent() { + // Use getRouteApi to access typed hooks without importing Route + return
    Posts
    +} +``` + +`createLazyFileRoute` supports only: `component`, `errorComponent`, `pendingComponent`, `notFoundComponent`. + +## Virtual Routes + +If splitting leaves the critical route file empty, delete it entirely. A virtual route is auto-generated in `routeTree.gen.ts`: + +```tsx +// src/routes/about.lazy.tsx — no about.tsx needed +import { createLazyFileRoute } from '@tanstack/react-router' + +export const Route = createLazyFileRoute('/about')({ + component: () =>

    About Us

    , +}) +``` + +## Code-Based Splitting + +For code-based (non-file-based) routing, use `createLazyRoute` and the `.lazy()` method: + +```tsx +// src/posts.lazy.tsx +import { createLazyRoute } from '@tanstack/react-router' + +export const Route = createLazyRoute('/posts')({ + component: PostsComponent, +}) + +function PostsComponent() { + return
    Posts
    +} +``` + +```tsx +// src/app.tsx +import { createRoute } from '@tanstack/react-router' + +const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', +}).lazy(() => import('./posts.lazy').then((d) => d.Route)) +``` + +## Accessing Typed Hooks in Split Files: `getRouteApi` + +When your component lives in a separate file, use `getRouteApi` to get typed access to route hooks without importing the Route object: + +```tsx +// src/routes/posts.lazy.tsx +import { createLazyFileRoute, getRouteApi } from '@tanstack/react-router' + +const routeApi = getRouteApi('/posts') + +export const Route = createLazyFileRoute('/posts')({ + component: PostsComponent, +}) + +function PostsComponent() { + const posts = routeApi.useLoaderData() + const { page } = routeApi.useSearch() + const params = routeApi.useParams() + const context = routeApi.useRouteContext() + return
    Posts page {page}
    +} +``` + +`getRouteApi` provides: `useLoaderData`, `useLoaderDeps`, `useMatch`, `useParams`, `useRouteContext`, `useSearch`. + +## Per-Route Split Overrides: `codeSplitGroupings` + +Override split behavior for a specific route by adding `codeSplitGroupings` directly in the route file: + +```tsx +// src/routes/posts.tsx +import { createFileRoute } from '@tanstack/react-router' +import { loadPostsData } from './-heavy-posts-utils' + +export const Route = createFileRoute('/posts')({ + // Bundle loader and component together for this route + codeSplitGroupings: [['loader', 'component']], + loader: () => loadPostsData(), + component: PostsComponent, +}) + +function PostsComponent() { + const data = Route.useLoaderData() + return
    {data.title}
    +} +``` + +## Global Split Configuration + +### `defaultBehavior` — Change Default Groupings + +```ts +// vite.config.ts +import { defineConfig } from 'vite' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ + autoCodeSplitting: true, + codeSplittingOptions: { + defaultBehavior: [ + // Bundle all UI components into one chunk + [ + 'component', + 'pendingComponent', + 'errorComponent', + 'notFoundComponent', + ], + ], + }, + }), + ], +}) +``` + +### `splitBehavior` — Programmatic Per-Route Logic + +```ts +// vite.config.ts +import { defineConfig } from 'vite' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ + autoCodeSplitting: true, + codeSplittingOptions: { + splitBehavior: ({ routeId }) => { + if (routeId.startsWith('/posts')) { + return [['loader', 'component']] + } + // All other routes use defaultBehavior + }, + }, + }), + ], +}) +``` + +### Precedence Order + +1. Per-route `codeSplitGroupings` (highest) +2. `splitBehavior` function +3. `defaultBehavior` option (lowest) + +## Common Mistakes + +### 1. HIGH: Exporting component functions prevents code splitting + +```tsx +// WRONG — export puts PostsComponent in the main bundle +export function PostsComponent() { + return
    Posts
    +} + +// CORRECT — no export, function stays in the split chunk +function PostsComponent() { + return
    Posts
    +} +``` + +### 2. MEDIUM: Trying to code-split the root route + +`__root.tsx` does not support code splitting. It is always rendered regardless of the current route. Do not create `__root.lazy.tsx`. + +### 3. MEDIUM: Splitting the loader adds double async cost + +```tsx +// AVOID unless you have a specific reason +codeSplittingOptions: { + defaultBehavior: [ + ['loader'], // Fetch chunk THEN execute loader = two network waterfalls + ['component'], + ], +} + +// PREFERRED — loader stays in main bundle (default behavior) +codeSplittingOptions: { + defaultBehavior: [ + ['component'], + ['errorComponent'], + ['notFoundComponent'], + ], +} +``` + +### 4. HIGH: Importing Route in code-split files for typed hooks + +```tsx +// WRONG — importing Route pulls route config into the lazy chunk +import { Route } from './posts.tsx' +const data = Route.useLoaderData() + +// CORRECT — getRouteApi gives typed hooks without pulling in the route +import { getRouteApi } from '@tanstack/react-router' +const routeApi = getRouteApi('/posts') +const data = routeApi.useLoaderData() +``` + +## Cross-References + +- **router-core/data-loading** — Loader splitting decisions affect data loading performance. Splitting the loader adds latency before data can be fetched. +- **router-core/type-safety** — `getRouteApi` is the type-safe way to access hooks from split files. diff --git a/packages/router-core/skills/router-core/data-loading/SKILL.md b/packages/router-core/skills/router-core/data-loading/SKILL.md new file mode 100644 index 0000000000..6a4364ff1f --- /dev/null +++ b/packages/router-core/skills/router-core/data-loading/SKILL.md @@ -0,0 +1,497 @@ +--- +name: data-loading +description: >- + Route loader option, loaderDeps for cache keys, staleTime/gcTime/ + defaultPreloadStaleTime SWR caching, pendingComponent/pendingMs/ + pendingMinMs, errorComponent/onError/onCatch, beforeLoad, router + context and createRootRouteWithContext DI pattern, router.invalidate, + Await component, deferred data loading with unawaited promises. +metadata: + type: sub-skill + library: tanstack-router + library_version: '1.171.15' +requires: + - router-core +sources: + - TanStack/router:docs/router/guide/data-loading.md + - TanStack/router:docs/router/guide/deferred-data-loading.md + - TanStack/router:docs/router/guide/router-context.md + - TanStack/router:docs/router/guide/data-mutations.md +--- + +# Data Loading + +## Setup + +Basic loader returning data, consumed via `useLoaderData`: + +```tsx +// src/routes/posts.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts')({ + loader: () => fetchPosts(), + component: PostsComponent, +}) + +function PostsComponent() { + const posts = Route.useLoaderData() + return ( +
      + {posts.map((post) => ( +
    • {post.title}
    • + ))} +
    + ) +} +``` + +In code-split components, use `getRouteApi` instead of importing Route: + +```tsx +import { getRouteApi } from '@tanstack/react-router' + +const routeApi = getRouteApi('/posts') + +function PostsComponent() { + const posts = routeApi.useLoaderData() + return
      {/* ... */}
    +} +``` + +## Route Loading Lifecycle + +The router executes this sequence on every URL/history update: + +1. **Route Matching** (top-down) + - `route.params.parse` + - `route.validateSearch` +2. **Route Pre-Loading** (serial) + - `route.beforeLoad` + - `route.onError` → `route.errorComponent` +3. **Route Loading** (parallel) + - `route.component.preload?` + - `route.loader` + - `route.pendingComponent` (optional) + - `route.component` + - `route.onError` → `route.errorComponent` + +Key: `beforeLoad` runs before `loader`. `beforeLoad` for a parent runs before its children's `beforeLoad`. Throwing in `beforeLoad` prevents all children from loading. + +## Core Patterns + +### loaderDeps for Search-Param-Driven Cache Keys + +Loaders don't receive search params directly. Use `loaderDeps` to declare which search params affect the cache key: + +```tsx +// src/routes/posts.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts')({ + validateSearch: (search) => ({ + offset: Number(search.offset) || 0, + limit: Number(search.limit) || 10, + }), + loaderDeps: ({ search: { offset, limit } }) => ({ offset, limit }), + loader: ({ deps: { offset, limit } }) => fetchPosts({ offset, limit }), +}) +``` + +When deps change, the route reloads regardless of `staleTime`. + +### SWR Caching Configuration + +TanStack Router has built-in Stale-While-Revalidate caching keyed on the route's parsed pathname + `loaderDeps`. + +Defaults: + +- **`staleTime`: 0** — data is always considered stale, reloads in background on re-match +- **`preloadStaleTime`: 30 seconds** — preloaded data won't be refetched for 30s +- **`gcTime`: 30 minutes** — unused cache entries garbage collected after 30min + +```tsx +export const Route = createFileRoute('/posts')({ + loader: () => fetchPosts(), + staleTime: 10_000, // 10s: data considered fresh for 10 seconds + gcTime: 5 * 60 * 1000, // 5min: garbage collect after 5 minutes +}) +``` + +Disable SWR caching entirely: + +```tsx +export const Route = createFileRoute('/posts')({ + loader: () => fetchPosts(), + staleTime: Infinity, +}) +``` + +Globally: + +```tsx +const router = createRouter({ + routeTree, + defaultStaleTime: Infinity, +}) +``` + +### Pending States (pendingComponent / pendingMs / pendingMinMs) + +By default, a pending component shows after 1 second (`pendingMs: 1000`) and stays for at least 500ms (`pendingMinMs: 500`) to avoid flash. + +```tsx +export const Route = createFileRoute('/posts')({ + loader: () => fetchPosts(), + pendingMs: 500, + pendingMinMs: 300, + pendingComponent: () =>
    Loading posts...
    , + component: PostsComponent, +}) +``` + +### Router Context with createRootRouteWithContext (Factory Pattern) + +`createRootRouteWithContext` is a factory that returns a function. You must call it twice — the first call passes the generic type, the second passes route options: + +```tsx +// src/routes/__root.tsx +import { createRootRouteWithContext, Outlet } from '@tanstack/react-router' + +interface MyRouterContext { + auth: { userId: string } + fetchPosts: () => Promise +} + +// NOTE: double call — createRootRouteWithContext()({...}) +export const Route = createRootRouteWithContext()({ + component: () => , +}) +``` + +Supply the context when creating the router: + +```tsx +// src/router.tsx +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ + routeTree, + context: { + auth: { userId: '123' }, + fetchPosts, + }, +}) +``` + +Consume in loaders and beforeLoad: + +```tsx +// src/routes/posts.tsx +export const Route = createFileRoute('/posts')({ + loader: ({ context: { fetchPosts } }) => fetchPosts(), +}) +``` + +To pass React hook values into the router context, call the hook above `RouterProvider` and inject via the `context` prop: + +```tsx +import { RouterProvider } from '@tanstack/react-router' + +function InnerApp() { + const auth = useAuth() + return +} + +function App() { + return ( + + + + ) +} +``` + +Route-level context via `beforeLoad`: + +```tsx +export const Route = createFileRoute('/posts')({ + beforeLoad: ({ context }) => ({ + fetchPosts: context.fetchPosts, + }), + loader: ({ context: { fetchPosts } }) => fetchPosts(), +}) +``` + +Keep the implementation SSR-safe when the router is used by TanStack Start. A relative `fetch('/api/posts')` works in a browser event handler, but Node and many server runtimes require an absolute URL during SSR. For app-internal data in Start, call a server function from the loader: + +```tsx +import { createServerFn } from '@tanstack/react-start' + +const getPosts = createServerFn({ method: 'GET' }).handler(() => { + return db.posts.findMany() +}) + +export const Route = createFileRoute('/posts')({ + loader: () => getPosts(), +}) +``` + +Use a server route plus an origin-derived absolute URL only when the HTTP boundary itself is required. Do not hard-code the production origin. + +### Deferred Data Loading + +Return unawaited promises from the loader for non-critical data. Use the `Await` component to render them: + +```tsx +import { createFileRoute, Await } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params: { postId } }) => { + // Slow data — do NOT await + const slowDataPromise = fetchComments(postId) + // Fast data — await + const post = await fetchPost(postId) + + return { post, deferredComments: slowDataPromise } + }, + component: PostComponent, +}) + +function PostComponent() { + const { post, deferredComments } = Route.useLoaderData() + + return ( +
    +

    {post.title}

    + Loading comments...
    } + > + {(comments) => ( +
      + {comments.map((c) => ( +
    • {c.body}
    • + ))} +
    + )} +
    + + ) +} +``` + +### Invalidation After Mutations + +`router.invalidate()` forces all active route loaders to re-run and marks all cached data as stale: + +```tsx +import { useRouter } from '@tanstack/react-router' + +function AddPostButton() { + const router = useRouter() + + const handleAdd = async () => { + await createPost({ title: 'New post' }) + await router.invalidate({ sync: true }) + } + + return +} +``` + +Use `await router.invalidate({ sync: true })` when the next step requires refreshed loader data. + +Treat the mutation and invalidation as one workflow. The mutation must persist before invalidation starts, and the loader must read from the same authoritative store. Verify create, update, and delete through the rendered route, including a fresh reload; local component state can hide a stale loader or non-persistent write. + +### Error Handling + +```tsx +import { + createFileRoute, + ErrorComponent, + useRouter, +} from '@tanstack/react-router' + +export const Route = createFileRoute('/posts')({ + loader: () => fetchPosts(), + errorComponent: ({ error, reset }) => { + const router = useRouter() + + if (error instanceof CustomError) { + return
    {error.message}
    + } + + return ( +
    + + +
    + ) + }, +}) +``` + +### Loader Parameters + +The `loader` function receives: + +- `params` — parsed path params +- `deps` — object from `loaderDeps` +- `context` — merged parent + beforeLoad context +- `abortController` — cancelled when route unloads or becomes stale +- `cause` — `'enter'`, `'stay'`, or `'preload'` +- `preload` — `true` during preloading +- `location` — current location object +- `parentMatchPromise` — promise of parent route match +- `route` — the route object itself + +```tsx +export const Route = createFileRoute('/posts/$postId')({ + loader: ({ params: { postId }, abortController }) => + fetchPost(postId, { signal: abortController.signal }), +}) +``` + +## Common Mistakes + +### CRITICAL: Assuming loaders only run on the server + +TanStack Router is **client-first**. Loaders run on the **client** by default. They also run on the server when using TanStack Start for SSR, but the default mental model is client-side execution. + +```tsx +// WRONG — this will crash in the browser +export const Route = createFileRoute('/posts')({ + loader: async () => { + const fs = await import('fs') // Node.js only! + return JSON.parse(fs.readFileSync('...')) // fails in browser + }, +}) + +// CORRECT for an SPA — use a client-safe API helper +export const Route = createFileRoute('/posts')({ + loader: () => fetchPosts(), +}) +``` + +Do NOT put database queries, filesystem access, or server-only code directly in loaders. In TanStack Start, put that work in a server function and call the function from the loader. Do not use a relative `fetch('/api/...')` in an SSR loader. + +### MEDIUM: Not understanding staleTime default is 0 + +Default `staleTime` is `0`. This means data reloads in the background on every route re-match. This is intentional — it ensures fresh data. But if your data is expensive or static, set `staleTime`: + +```tsx +export const Route = createFileRoute('/posts')({ + loader: () => fetchPosts(), + staleTime: 60_000, // Consider fresh for 1 minute +}) +``` + +### HIGH: Using reset() instead of router.invalidate() in error components + +`reset()` only resets the error boundary UI. It does NOT re-run the loader. For loader errors, use `router.invalidate()` which re-runs loaders and resets the boundary: + +```tsx +// WRONG — resets boundary but loader still has stale error +function PostErrorComponent({ error, reset }) { + return +} + +// CORRECT — re-runs loader and resets the error boundary +function PostErrorComponent({ error }) { + const router = useRouter() + return +} +``` + +### HIGH: Missing double parentheses on createRootRouteWithContext + +`createRootRouteWithContext()` is a factory — it returns a function. Must call twice: + +```tsx +// WRONG — missing second call, passes options to the factory +const rootRoute = createRootRouteWithContext<{ auth: AuthState }>({ + component: RootComponent, +}) + +// CORRECT — factory()({options}) +const rootRoute = createRootRouteWithContext<{ auth: AuthState }>()({ + component: RootComponent, +}) +``` + +### HIGH: Using React hooks in beforeLoad or loader + +`beforeLoad` and `loader` are NOT React components. You cannot call hooks inside them. Use router context to inject values from hooks: + +```tsx +// WRONG — hooks cannot be called outside React components +export const Route = createFileRoute('/posts')({ + loader: () => { + const auth = useAuth() // This will crash! + return fetchPosts(auth.userId) + }, +}) + +// CORRECT — inject hook values via router context +// In your App component: +function InnerApp() { + const auth = useAuth() + return +} + +// In your route: +export const Route = createFileRoute('/posts')({ + loader: ({ context: { auth } }) => fetchPosts(auth.userId), +}) +``` + +### HIGH: Property order affects TypeScript inference + +Router infers types from earlier properties into later ones. Declaring `beforeLoad` after `loader` means context from `beforeLoad` is unknown in the loader: + +```tsx +// WRONG — context.user is unknown because beforeLoad declared after loader +export const Route = createFileRoute('/admin')({ + loader: ({ context }) => fetchData(context.user), + beforeLoad: () => ({ user: getUser() }), +}) + +// CORRECT — validateSearch → loaderDeps → beforeLoad → loader +export const Route = createFileRoute('/admin')({ + beforeLoad: () => ({ user: getUser() }), + loader: ({ context }) => fetchData(context.user), +}) +``` + +### HIGH: Returning entire search object from loaderDeps + +```tsx +// WRONG — loader re-runs on ANY search param change +loaderDeps: ({ search }) => search + +// CORRECT — only re-run when page changes +loaderDeps: ({ search }) => ({ page: search.page }) +``` + +Returning the whole `search` object means unrelated param changes (e.g., `sortDirection`, `viewMode`) trigger unnecessary reloads because deep equality fails on the entire object. + +## Tensions + +- **Client-first loaders vs SSR expectations**: Loaders run on the client by default. When using SSR (TanStack Start), they run on both client and server. Browser-only APIs work by default but break under SSR. Server-only APIs (fs, db) break by default but work under Start server functions. See **router-core/ssr/SKILL.md**. +- **Built-in SWR cache vs external cache coordination**: Router has built-in caching. When using TanStack Query, set `defaultPreloadStaleTime: 0` to avoid double-caching. See **compositions/router-query/SKILL.md**. + +--- + +## Cross-References + +- See also: **router-core/search-params/SKILL.md** — `loaderDeps` consumes validated search params as cache keys +- See also: **compositions/router-query/SKILL.md** — for external cache coordination with TanStack Query diff --git a/packages/router-core/skills/router-core/navigation/SKILL.md b/packages/router-core/skills/router-core/navigation/SKILL.md new file mode 100644 index 0000000000..ba1f0fd2e6 --- /dev/null +++ b/packages/router-core/skills/router-core/navigation/SKILL.md @@ -0,0 +1,449 @@ +--- +name: navigation +description: >- + Link component, useNavigate, Navigate component, router.navigate, + ToOptions/NavigateOptions/LinkOptions, from/to relative navigation, + activeOptions/activeProps, preloading (intent/viewport/render), + preloadDelay, navigation blocking (useBlocker, Block), createLink, + linkOptions helper, scroll restoration, MatchRoute. +metadata: + type: sub-skill + library: tanstack-router + library_version: '1.171.15' +requires: + - router-core +sources: + - TanStack/router:docs/router/guide/navigation.md + - TanStack/router:docs/router/guide/preloading.md + - TanStack/router:docs/router/guide/navigation-blocking.md + - TanStack/router:docs/router/guide/link-options.md + - TanStack/router:docs/router/guide/custom-link.md + - TanStack/router:docs/router/guide/scroll-restoration.md +--- + +# Navigation + +## Setup + +Basic type-safe `Link` with `to` and `params`: + +```tsx +import { Link } from '@tanstack/react-router' + +function PostLink({ postId }: { postId: string }) { + return ( + + View Post + + ) +} +``` + +## Core Patterns + +### Link with Active States + +```tsx +import { Link } from '@tanstack/react-router' + +function NavLink() { + return ( + + Posts + + ) +} +``` + +The `data-status` attribute is also set to `"active"` on active links for CSS-based styling. + +`activeOptions` controls matching behavior: + +- `exact` (default `false`) — when `true`, only matches the exact path (not children) +- `includeHash` (default `false`) — include hash in active matching +- `includeSearch` (default `true`) — include search params in active matching + +Children can receive `isActive` as a render function: + +```tsx + + {({ isActive }) => Posts} + +``` + +### Relative Navigation with `from` + +Without `from`, navigation resolves from root `/`. To use relative paths like `..`, provide `from`: + +```tsx +import { createFileRoute, Link } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts/$postId')({ + component: PostComponent, +}) + +function PostComponent() { + return ( +
    + {/* Relative to current route */} + + Back to Posts + + + {/* "." reloads the current route */} + + Reload + +
    + ) +} +``` + +### useNavigate for Programmatic Navigation + +Use `useNavigate` only for side-effect-driven navigation (e.g., after a form submission). For anything the user clicks, prefer `Link`. + +```tsx +import { useNavigate } from '@tanstack/react-router' + +function CreatePostForm() { + const navigate = useNavigate({ from: '/posts' }) + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault() + const response = await fetch('/api/posts', { method: 'POST', body: '...' }) + const { id: postId } = await response.json() + + if (response.ok) { + navigate({ to: '/posts/$postId', params: { postId } }) + } + } + + return
    {/* ... */}
    +} +``` + +The `Navigate` component performs an immediate client-side navigation on mount: + +```tsx +import { Navigate } from '@tanstack/react-router' + +function LegacyRedirect() { + return +} +``` + +`router.navigate` is available anywhere you have the router instance, including outside of React. + +### Preloading + +Strategies: `intent` (hover/touchstart), `viewport` (intersection observer), `render` (on mount). + +Set globally: + +```tsx +import { createRouter } from '@tanstack/react-router' + +const router = createRouter({ + routeTree, + defaultPreload: 'intent', + defaultPreloadDelay: 50, // ms, default is 50 +}) +``` + +Or per-link: + +```tsx + + View Post + +``` + +Preloaded data stays fresh for 30 seconds by default (`defaultPreloadStaleTime: 30_000`). During that window it won't be refetched. When using an external cache like TanStack Query, set `defaultPreloadStaleTime: 0` to let the external library control freshness. + +Manual preloading via the router instance: + +```tsx +import { useRouter } from '@tanstack/react-router' + +function Component() { + const router = useRouter() + + useEffect(() => { + router.preloadRoute({ to: '/posts/$postId', params: { postId: '1' } }) + }, [router]) + + return
    +} +``` + +### Navigation Blocking + +Use `useBlocker` to prevent navigation when a form has unsaved changes: + +```tsx +import { useBlocker } from '@tanstack/react-router' +import { useState } from 'react' + +function EditForm() { + const [formIsDirty, setFormIsDirty] = useState(false) + + useBlocker({ + shouldBlockFn: () => { + if (!formIsDirty) return false + const shouldLeave = confirm('Are you sure you want to leave?') + return !shouldLeave + }, + }) + + return
    {/* ... */}
    +} +``` + +With custom UI using `withResolver`: + +```tsx +import { useBlocker } from '@tanstack/react-router' +import { useState } from 'react' + +function EditForm() { + const [formIsDirty, setFormIsDirty] = useState(false) + + const { proceed, reset, status } = useBlocker({ + shouldBlockFn: () => formIsDirty, + withResolver: true, + }) + + return ( + <> +
    {/* ... */}
    + {status === 'blocked' && ( +
    +

    Are you sure you want to leave?

    + + +
    + )} + + ) +} +``` + +Control `beforeunload` separately: + +```tsx +useBlocker({ + shouldBlockFn: () => formIsDirty, + enableBeforeUnload: formIsDirty, +}) +``` + +### linkOptions for Reusable Navigation Options + +`linkOptions` provides eager type-checking on navigation options objects, so errors surface at definition, not at spread-site: + +```tsx +import { + linkOptions, + Link, + useNavigate, + redirect, +} from '@tanstack/react-router' + +const dashboardLinkOptions = linkOptions({ + to: '/dashboard', + search: { search: '' }, +}) + +// Use anywhere: Link, navigate, redirect +function Nav() { + const navigate = useNavigate() + + return ( +
    + Dashboard + +
    + ) +} + +// Also works in an array for navigation bars +const navOptions = linkOptions([ + { to: '/dashboard', label: 'Summary', activeOptions: { exact: true } }, + { to: '/dashboard/invoices', label: 'Invoices' }, + { to: '/dashboard/users', label: 'Users' }, +]) + +function NavBar() { + return ( + + ) +} +``` + +### createLink for Custom Components + +Wraps any component with TanStack Router's type-safe navigation: + +```tsx +import * as React from 'react' +import { createLink, LinkComponent } from '@tanstack/react-router' + +interface BasicLinkProps extends React.AnchorHTMLAttributes {} + +const BasicLinkComponent = React.forwardRef( + (props, ref) => { + return + }, +) + +const CreatedLinkComponent = createLink(BasicLinkComponent) + +export const CustomLink: LinkComponent = (props) => { + return +} +``` + +Usage retains full type safety: + +```tsx + +``` + +### Scroll Restoration + +Enable globally on the router: + +```tsx +const router = createRouter({ + routeTree, + scrollRestoration: true, +}) +``` + +For nested scrollable areas: + +```tsx +const router = createRouter({ + routeTree, + scrollRestoration: true, + scrollToTopSelectors: ['#main-scrollable-area'], +}) +``` + +Custom cache keys: + +```tsx +const router = createRouter({ + routeTree, + scrollRestoration: true, + getScrollRestorationKey: (location) => location.pathname, +}) +``` + +Prevent scroll reset for a specific navigation: + +```tsx + + Posts + +``` + +### MatchRoute for Pending UI + +```tsx +import { Link, MatchRoute } from '@tanstack/react-router' + +function Nav() { + return ( + + Users + + + + + ) +} +``` + +## Common Mistakes + +### CRITICAL: Interpolating params into the `to` string + +```tsx +// WRONG — breaks type safety and param encoding +Post + +// CORRECT — use the params option +Post +``` + +Dynamic segments are declared with `$` in the route path. Always pass them via `params`. This applies to `Link`, `useNavigate`, `Navigate`, and `router.navigate`. + +### MEDIUM: Using useNavigate for clickable elements + +```tsx +// WRONG — no href, no cmd+click, no preloading, no accessibility +function BadNav() { + const navigate = useNavigate() + return +} + +// CORRECT — real tag with href, accessible, preloadable +function GoodNav() { + return Posts +} +``` + +Use `useNavigate` only for programmatic side-effect navigation (after form submit, async action, etc). + +### HIGH: Not providing `from` for relative navigation + +```tsx +// WRONG — without from, ".." resolves from root +Back + +// CORRECT — provide from for relative resolution +Back +``` + +Without `from`, only absolute paths are autocompleted and type-safe. Relative paths like `..` resolve from root instead of the current route. + +### HIGH: Using search as object instead of function loses existing params + +```tsx +// WRONG — replaces ALL search params with just { page: 2 } +Page 2 + +// CORRECT — preserves existing search params, updates page + ({ ...prev, page: 2 })}>Page 2 +``` + +When you pass `search` as a plain object, it replaces all search params. Use the function form to spread previous params and selectively update. + +--- + +## Cross-References + +- See also: **router-core/search-params/SKILL.md** — Link `search` prop interacts with search param validation +- See also: **router-core/type-safety/SKILL.md** — `from` narrowing improves type inference on Link diff --git a/packages/router-core/skills/router-core/not-found-and-errors/SKILL.md b/packages/router-core/skills/router-core/not-found-and-errors/SKILL.md new file mode 100644 index 0000000000..45b231f41e --- /dev/null +++ b/packages/router-core/skills/router-core/not-found-and-errors/SKILL.md @@ -0,0 +1,445 @@ +--- +name: not-found-and-errors +description: >- + notFound() function, notFoundComponent, defaultNotFoundComponent, + notFoundMode (fuzzy/root), errorComponent, CatchBoundary, + CatchNotFound, isNotFound, NotFoundRoute (deprecated), route + masking (mask option, createRouteMask, unmaskOnReload). +metadata: + type: sub-skill + library: tanstack-router + library_version: '1.171.15' +requires: + - router-core +sources: + - TanStack/router:docs/router/guide/not-found-errors.md + - TanStack/router:docs/router/guide/route-masking.md +--- + +# Not Found and Errors + +TanStack Router handles two categories of "not found": unmatched URL paths (automatic) and missing resources like a post that doesn't exist (manual via `notFound()`). Error boundaries are configured per-route via `errorComponent`. + +> **CRITICAL**: Do NOT use the deprecated `NotFoundRoute`. When present, `notFound()` and `notFoundComponent` will NOT work. Remove it and use `notFoundComponent` instead. +> **CRITICAL**: `useLoaderData` may be undefined inside `notFoundComponent`. Use `useParams`, `useSearch`, or `useRouteContext` instead. + +## Not Found Handling + +### Global 404: `notFoundComponent` on Root Route + +```tsx +// src/routes/__root.tsx +import { createRootRoute, Outlet, Link } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: () => , + notFoundComponent: () => { + return ( +
    +

    404 — Page Not Found

    + Go Home +
    + ) + }, +}) +``` + +### Router-Wide Default: `defaultNotFoundComponent` + +```tsx +// src/router.tsx +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ + routeTree, + defaultNotFoundComponent: () => { + return ( +
    +

    Not found!

    + Go home +
    + ) + }, +}) +``` + +### Per-Route 404: Missing Resources with `notFound()` + +Throw `notFound()` in `loader` or `beforeLoad` when a resource doesn't exist. It works like `redirect()` — throw it to trigger the not-found boundary. + +```tsx +// src/routes/posts.$postId.tsx +import { createFileRoute, notFound } from '@tanstack/react-router' +import { getPost } from '../api' + +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params: { postId } }) => { + const post = await getPost(postId) + if (!post) throw notFound() + return { post } + }, + component: PostComponent, + notFoundComponent: ({ data }) => { + const { postId } = Route.useParams() + return

    Post "{postId}" not found

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

    {post.title}

    +} +``` + +### Targeting a Specific Route with `notFound({ routeId })` + +You can force a specific parent route to handle the not-found error: + +```tsx +// src/routes/_layout/posts.$postId.tsx +import { createFileRoute, notFound } from '@tanstack/react-router' + +export const Route = createFileRoute('/_layout/posts/$postId')({ + loader: async ({ params: { postId } }) => { + const post = await getPost(postId) + if (!post) throw notFound({ routeId: '/_layout' }) + return { post } + }, +}) +``` + +### Targeting Root Route with `rootRouteId` + +```tsx +import { createFileRoute, notFound, rootRouteId } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params: { postId } }) => { + const post = await getPost(postId) + if (!post) throw notFound({ routeId: rootRouteId }) + return { post } + }, +}) +``` + +## `notFoundMode`: Fuzzy vs Root + +### `fuzzy` (default) + +The router finds the nearest parent route with children and a `notFoundComponent`. Preserves as much parent layout as possible. + +Given routes: `__root__` → `posts` → `$postId`, accessing `/posts/1/edit`: + +- `` renders +- `` renders +- `` renders (nearest parent with children + notFoundComponent) + +### `root` + +All not-found errors go to the root route's `notFoundComponent`, regardless of matching: + +```tsx +const router = createRouter({ + routeTree, + notFoundMode: 'root', +}) +``` + +## Error Handling + +### `errorComponent` Per Route + +`errorComponent` receives `error`, `info`, and `reset` props. For loader errors, use `router.invalidate()` to re-run the loader — it automatically resets the error boundary. + +```tsx +// src/routes/posts.$postId.tsx +import { createFileRoute, useRouter } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params: { postId } }) => { + const res = await fetch(`/api/posts/${postId}`) + if (!res.ok) throw new Error('Failed to load post') + return res.json() + }, + component: PostComponent, + errorComponent: PostErrorComponent, +}) + +function PostErrorComponent({ + error, +}: { + error: unknown + info?: { componentStack: string } + reset: () => void +}) { + const router = useRouter() + + return ( +
    +

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

    + +
    + ) +} + +function PostComponent() { + const data = Route.useLoaderData() + return

    {data.title}

    +} +``` + +### Router-Wide Default Error Component + +```tsx +const router = createRouter({ + routeTree, + defaultErrorComponent: ({ error }) => { + const router = useRouter() + return ( +
    +

    + Something went wrong:{' '} + {error instanceof Error ? error.message : String(error)} +

    + +
    + ) + }, +}) +``` + +## Data in `notFoundComponent` + +`notFoundComponent` cannot reliably use `useLoaderData` because the loader may not have completed. Safe hooks: + +```tsx +notFoundComponent: ({ data }) => { + // SAFE — always available: + const params = Route.useParams() + const search = Route.useSearch() + const context = Route.useRouteContext() + + // UNSAFE — may be undefined: + // const loaderData = Route.useLoaderData() + + return

    Item {params.id} not found

    +} +``` + +To forward partial data, use the `data` option on `notFound()`: + +```tsx +loader: async ({ params }) => { + const partialData = await getPartialData(params.id) + if (!partialData.fullResource) { + throw notFound({ data: { name: partialData.name } }) + } + return partialData +}, +notFoundComponent: ({ data }) => { + // data is typed as unknown — validate it + const info = data as { name: string } | undefined + return

    {info?.name ?? 'Resource'} not found

    +}, +``` + +## Route Masking + +Route masking shows a different URL in the browser bar than the actual route being rendered. Masking data is stored in `location.state` and is lost when the URL is shared or opened in a new tab. + +### Imperative Masking on `` + +```tsx +import { Link } from '@tanstack/react-router' + +function PhotoGrid({ photoId }: { photoId: string }) { + return ( + + Open Photo + + ) +} +``` + +### Imperative Masking with `useNavigate` + +```tsx +import { useNavigate } from '@tanstack/react-router' + +function OpenPhotoButton({ photoId }: { photoId: string }) { + const navigate = useNavigate() + + return ( + + ) +} +``` + +### Declarative Masking with `createRouteMask` + +```tsx +import { createRouter, createRouteMask } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const photoModalMask = createRouteMask({ + routeTree, + from: '/photos/$photoId/modal', + to: '/photos/$photoId', + params: (prev) => ({ photoId: prev.photoId }), +}) + +const router = createRouter({ + routeTree, + routeMasks: [photoModalMask], +}) +``` + +### Unmasking on Reload + +By default, masks survive local page reloads. To unmask on reload: + +```tsx +// Per-mask +const mask = createRouteMask({ + routeTree, + from: '/photos/$photoId/modal', + to: '/photos/$photoId', + params: (prev) => ({ photoId: prev.photoId }), + unmaskOnReload: true, +}) + +// Per-link + + Open Photo + + +// Router-wide default +const router = createRouter({ + routeTree, + unmaskOnReload: true, +}) +``` + +## Common Mistakes + +### 1. HIGH: Using deprecated `NotFoundRoute` + +```tsx +// WRONG — NotFoundRoute blocks notFound() and notFoundComponent from working +import { NotFoundRoute } from '@tanstack/react-router' +const notFoundRoute = new NotFoundRoute({ component: () =>

    404

    }) +const router = createRouter({ routeTree, notFoundRoute }) + +// CORRECT — use notFoundComponent on root route +export const Route = createRootRoute({ + component: () => , + notFoundComponent: () =>

    404

    , +}) +``` + +### 2. MEDIUM: Expecting `useLoaderData` in `notFoundComponent` + +```tsx +// WRONG — loader may not have completed +notFoundComponent: () => { + const data = Route.useLoaderData() // may be undefined! + return

    {data.title} not found

    +} + +// CORRECT — use safe hooks +notFoundComponent: () => { + const { postId } = Route.useParams() + return

    Post {postId} not found

    +} +``` + +### 3. MEDIUM: Leaf routes cannot handle not-found errors + +Only routes with children (and therefore an ``) can render `notFoundComponent`. Leaf routes (routes without children) will never catch not-found errors — the error bubbles up to the nearest parent with children. + +```tsx +// This route has NO children — notFoundComponent here will not catch +// unmatched child paths (there are no child paths to unmatch) +export const Route = createFileRoute('/posts/$postId')({ + // notFoundComponent here only works for notFound() thrown in THIS route's loader + // It does NOT catch path-based not-founds + notFoundComponent: () =>

    Not found

    , +}) +``` + +### 4. MEDIUM: Expecting masked URLs to survive sharing + +Masking data lives in `location.state` (browser history). When a masked URL is copied, shared, or opened in a new tab, the masking data is lost. The browser navigates to the visible (masked) URL directly. + +### 5. HIGH (cross-skill): Using `reset()` alone instead of `router.invalidate()` + +```tsx +// WRONG — reset() clears the error boundary but does NOT re-run the loader +function ErrorFallback({ + error, + reset, +}: { + error: unknown + reset: () => void +}) { + return +} + +// CORRECT — invalidate re-runs loaders and resets the error boundary +function ErrorFallback({ error }: { error: unknown; reset: () => void }) { + const router = useRouter() + return ( + + ) +} +``` + +## Cross-References + +- **router-core/data-loading** — `notFound()` thrown in loaders interacts with error boundaries and loader data availability. `errorComponent` retry requires `router.invalidate()`. +- **router-core/type-safety** — `notFoundComponent` data is typed as `unknown`; validate before use. diff --git a/packages/router-core/skills/router-core/path-params/SKILL.md b/packages/router-core/skills/router-core/path-params/SKILL.md new file mode 100644 index 0000000000..b4819f04b5 --- /dev/null +++ b/packages/router-core/skills/router-core/path-params/SKILL.md @@ -0,0 +1,383 @@ +--- +name: path-params +description: >- + Dynamic path segments ($paramName), splat routes ($ / _splat), + optional params ({-$paramName}), prefix/suffix patterns ({$param}.ext), + useParams, params.parse/stringify, pathParamsAllowedCharacters, + i18n locale patterns. +metadata: + type: sub-skill + library: tanstack-router + library_version: '1.171.15' +requires: + - router-core +sources: + - TanStack/router:docs/router/guide/path-params.md + - TanStack/router:docs/router/routing/routing-concepts.md + - TanStack/router:docs/router/guide/internationalization-i18n.md +--- + +# Path Params + +Path params capture dynamic URL segments into named variables. They are defined with a `$` prefix in the route path. + +> **CRITICAL**: Never interpolate params into the `to` string. Always use the `params` prop. This is the most common agent mistake for path params. + +> **CRITICAL**: Types are fully inferred. Never annotate the return of `useParams()`. + +## Dynamic Segments + +A segment prefixed with `$` captures text until the next `/`. + +```tsx +// src/routes/posts.$postId.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params }) => { + // params.postId is string — fully inferred, do not annotate + return fetchPost(params.postId) + }, + component: PostComponent, +}) + +function PostComponent() { + const { postId } = Route.useParams() + const data = Route.useLoaderData() + return ( +

    + Post {postId}: {data.title} +

    + ) +} +``` + +Multiple dynamic segments work across path levels: + +```tsx +// src/routes/teams.$teamId.members.$memberId.tsx +export const Route = createFileRoute('/teams/$teamId/members/$memberId')({ + component: MemberComponent, +}) + +function MemberComponent() { + const { teamId, memberId } = Route.useParams() + return ( +
    + Team {teamId}, Member {memberId} +
    + ) +} +``` + +## Splat / Catch-All Routes + +A route with a path ending in `$` (bare dollar sign) captures everything after it. The value is available under the `_splat` key. + +```tsx +// src/routes/files.$.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/files/$')({ + component: FileViewer, +}) + +function FileViewer() { + const { _splat } = Route.useParams() + // URL: /files/documents/report.pdf → _splat = "documents/report.pdf" + return
    File path: {_splat}
    +} +``` + +## Optional Params + +Optional params use `{-$paramName}` syntax. The segment may or may not be present. When absent, the value is `undefined`. + +```tsx +// src/routes/posts.{-$category}.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts/{-$category}')({ + component: PostsComponent, +}) + +function PostsComponent() { + const { category } = Route.useParams() + // URL: /posts → category is undefined + // URL: /posts/tech → category is "tech" + return
    {category ? `Posts in ${category}` : 'All Posts'}
    +} +``` + +Multiple optional params: + +```tsx +// Matches: /posts, /posts/tech, /posts/tech/hello-world +export const Route = createFileRoute('/posts/{-$category}/{-$slug}')({ + component: PostComponent, +}) +``` + +### i18n with Optional Locale + +```tsx +// src/routes/{-$locale}/about.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/{-$locale}/about')({ + component: AboutComponent, +}) + +function AboutComponent() { + const { locale } = Route.useParams() + const currentLocale = locale || 'en' + return

    {currentLocale === 'fr' ? 'À Propos' : 'About Us'}

    +} +// Matches: /about, /en/about, /fr/about +``` + +## Prefix and Suffix Patterns + +Curly braces `{}` around `$paramName` allow text before or after the dynamic part within a single segment. + +### Prefix + +```tsx +// src/routes/posts/post-{$postId}.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts/post-{$postId}')({ + component: PostComponent, +}) + +function PostComponent() { + const { postId } = Route.useParams() + // URL: /posts/post-123 → postId = "123" + return
    Post ID: {postId}
    +} +``` + +### Suffix + +```tsx +// src/routes/files/{$fileName}[.]txt.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/files/{$fileName}.txt')({ + component: FileComponent, +}) + +function FileComponent() { + const { fileName } = Route.useParams() + // URL: /files/readme.txt → fileName = "readme" + return
    File: {fileName}.txt
    +} +``` + +### Combined Prefix + Suffix + +```tsx +// URL: /users/user-456.json → userId = "456" +export const Route = createFileRoute('/users/user-{$userId}.json')({ + component: UserComponent, +}) + +function UserComponent() { + const { userId } = Route.useParams() + return
    User: {userId}
    +} +``` + +## Navigating with Path Params + +### Object Form + +```tsx +import { Link } from '@tanstack/react-router' + +function PostLink({ postId }: { postId: string }) { + return ( + + View Post + + ) +} +``` + +### Function Form (Preserves Other Params) + +```tsx +function PostLink({ postId }: { postId: string }) { + return ( + ({ ...prev, postId })}> + View Post + + ) +} +``` + +### Programmatic Navigation + +```tsx +import { useNavigate } from '@tanstack/react-router' + +function GoToPost({ postId }: { postId: string }) { + const navigate = useNavigate() + + return ( + + ) +} +``` + +### Navigating with Optional Params + +```tsx +// Include the optional param + + Tech Posts + + +// Omit the optional param (renders /posts) + + All Posts + +``` + +## Reading Params Outside Route Components + +### `useParams` with `from` + +```tsx +import { useParams } from '@tanstack/react-router' + +function PostHeader() { + const { postId } = useParams({ from: '/posts/$postId' }) + return

    Post {postId}

    +} +``` + +### `useParams` with `strict: false` + +```tsx +function GenericBreadcrumb() { + const params = useParams({ strict: false }) + // params is a union of all possible route params + return {params.postId ?? 'Home'} +} +``` + +## Params in Loaders and `beforeLoad` + +```tsx +export const Route = createFileRoute('/posts/$postId')({ + beforeLoad: async ({ params }) => { + // params.postId available here + const canView = await checkPermission(params.postId) + if (!canView) throw redirect({ to: '/unauthorized' }) + }, + loader: async ({ params }) => { + return fetchPost(params.postId) + }, +}) +``` + +## Allowed Characters + +By default, params are encoded with `encodeURIComponent`. Allow extra characters via router config: + +```tsx +import { createRouter } from '@tanstack/react-router' + +const router = createRouter({ + routeTree, + pathParamsAllowedCharacters: ['@', '+'], +}) +``` + +Allowed characters: `;`, `:`, `@`, `&`, `=`, `+`, `$`, `,`. + +## Common Mistakes + +### 1. CRITICAL (cross-skill): Interpolating path params into `to` string + +```tsx +// WRONG — breaks type safety and param encoding +Post + +// CORRECT — use params prop +Post +``` + +### 2. MEDIUM: Using `*` for splat routes instead of `$` + +TanStack Router uses `$` for splat routes. The captured value is under `_splat`, not `*`. + +```tsx +// WRONG (React Router / other frameworks) +// + +// CORRECT (TanStack Router) +// File: src/routes/files.$.tsx +export const Route = createFileRoute('/files/$')({ + component: () => { + const { _splat } = Route.useParams() + return
    {_splat}
    + }, +}) +``` + +> Note: `*` works in v1 for backwards compatibility but will be removed in v2. Always use `_splat`. + +### 3. MEDIUM: Using curly braces for basic dynamic segments + +Curly braces are ONLY for prefix/suffix patterns and optional params. Basic dynamic segments use bare `$`. + +```tsx +// WRONG — braces not needed for basic params +createFileRoute('/posts/{$postId}') + +// CORRECT — bare $ for basic dynamic segments +createFileRoute('/posts/$postId') + +// CORRECT — braces for prefix pattern +createFileRoute('/posts/post-{$postId}') + +// CORRECT — braces for optional param +createFileRoute('/posts/{-$category}') +``` + +### 4. Params are always strings + +Path params are always parsed as strings. If you need a number, parse in the loader or component: + +```tsx +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params }) => { + const id = parseInt(params.postId, 10) + if (isNaN(id)) throw notFound() + return fetchPost(id) + }, +}) +``` + +You can also use `params.parse` and `params.stringify` on the route for bidirectional transformation: + +```tsx +export const Route = createFileRoute('/posts/$postId')({ + params: { + parse: (raw) => ({ postId: parseInt(raw.postId, 10) }), + stringify: (parsed) => ({ postId: String(parsed.postId) }), + }, + loader: async ({ params }) => { + // params.postId is now number + return fetchPost(params.postId) + }, +}) +``` diff --git a/packages/router-core/skills/router-core/search-params/SKILL.md b/packages/router-core/skills/router-core/search-params/SKILL.md new file mode 100644 index 0000000000..0960297d00 --- /dev/null +++ b/packages/router-core/skills/router-core/search-params/SKILL.md @@ -0,0 +1,350 @@ +--- +name: search-params +description: >- + validateSearch, search param validation with Zod/Valibot/ArkType adapters, + fallback(), search middlewares (retainSearchParams, stripSearchParams), + custom serialization (parseSearch, stringifySearch), search param + inheritance, loaderDeps for cache keys, reading and writing search params. +metadata: + type: sub-skill + library: tanstack-router + library_version: '1.171.15' +requires: + - router-core +sources: + - TanStack/router:docs/router/guide/search-params.md + - TanStack/router:docs/router/how-to/setup-basic-search-params.md + - TanStack/router:docs/router/how-to/validate-search-params.md + - TanStack/router:docs/router/how-to/navigate-with-search-params.md + - TanStack/router:docs/router/how-to/share-search-params-across-routes.md + - TanStack/router:docs/router/guide/custom-search-param-serialization.md +--- + +# Search Params + +TanStack Router treats search params as JSON-first application state. They are automatically parsed from the URL into structured objects (numbers, booleans, arrays, nested objects) and validated via `validateSearch` on each route. + +> **CRITICAL**: When using `zodValidator()` and Zod v3, use `fallback()` from `@tanstack/zod-adapter`, NOT zod's `.catch()`. Using `.catch()` with the zod adapter makes the output type `unknown`, destroying type safety. This does not apply to Valibot or ArkType (which use their own fallback mechanisms). It also does not apply to Zod v4, which should use `.catch()` and not use the `zodValidator()`. +> **CRITICAL**: Types are fully inferred. Never annotate the return of `useSearch()`. + +## Setup: Zod Adapter (Recommended) + +```bash +npm install zod @tanstack/zod-adapter +``` + +```tsx +// src/routes/products.tsx +import { createFileRoute } from '@tanstack/react-router' +import { z } from 'zod' + +const productSearchSchema = z.object({ + page: z.number().default(1).catch(1), + filter: z.string().default(''), + sort: z.enum(['newest', 'oldest', 'price']).default('newest').catch('newest'), +}) + +export const Route = createFileRoute('/products')({ + validateSearch: productSearchSchema, + component: ProductsPage, +}) + +function ProductsPage() { + // page: number, filter: string, sort: 'newest' | 'oldest' | 'price' + // ALL INFERRED — do not annotate + const { page, filter, sort } = Route.useSearch() + + return ( +
    +

    + Page {page}, filter: {filter}, sort: {sort} +

    +
    + ) +} +``` + +## Reading Search Params + +### In Route Components: `Route.useSearch()` + +```tsx +function ProductsPage() { + const { page, sort } = Route.useSearch() + return
    Page {page}
    +} +``` + +### In Code-Split Components: `getRouteApi()` + +```tsx +import { getRouteApi } from '@tanstack/react-router' + +const routeApi = getRouteApi('/products') + +function ProductFilters() { + const { sort } = routeApi.useSearch() + return +} +``` + +### From Any Component: `useSearch({ from })` + +```tsx +import { useSearch } from '@tanstack/react-router' + +function SortIndicator() { + const { sort } = useSearch({ from: '/products' }) + return Sorted by: {sort} +} +``` + +### Loose Access: `useSearch({ strict: false })` + +```tsx +function GenericPaginator() { + const search = useSearch({ strict: false }) + // search.page is number | undefined (union of all routes) + return Page: {search.page ?? 1} +} +``` + +## Writing Search Params + +### Link with Function Form (Preserves Existing Params) + +```tsx +import { Link } from '@tanstack/react-router' + +function Pagination() { + return ( + ({ ...prev, page: prev.page + 1 })} + > + Next Page + + ) +} +``` + +### Link with Object Form (Replaces All Params) + +```tsx + + Reset + +``` + +### Programmatic: `useNavigate()` + +```tsx +import { useNavigate } from '@tanstack/react-router' + +function SortDropdown() { + const navigate = useNavigate({ from: '/products' }) + + return ( + + ) +} +``` + +## Search Param Inheritance + +Parent route search params are automatically merged into child routes: + +```tsx +// src/routes/shop.tsx — parent defines shared params +import { createFileRoute } from '@tanstack/react-router' +import { z } from 'zod' + +const shopSearchSchema = z.object({ + currency: z.enum(['USD', 'EUR']).default('USD').catch('USD'), +}) + +export const Route = createFileRoute('/shop')({ + validateSearch: shopSearchSchema, +}) +``` + +```tsx +// src/routes/shop/products.tsx — child inherits currency +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/shop/products')({ + component: ShopProducts, +}) + +function ShopProducts() { + // currency is available here from parent — fully typed + const { currency } = Route.useSearch() + return
    Currency: {currency}
    +} +``` + +## Search Middlewares + +### `retainSearchParams` — Keep Params Across Navigation + +```tsx +import { createRootRoute, retainSearchParams } from '@tanstack/react-router' +import { z } from 'zod' + +const rootSearchSchema = z.object({ + debug: z.boolean().optional(), +}) + +export const Route = createRootRoute({ + validateSearch: rootSearchSchema, + search: { + middlewares: [retainSearchParams(['debug'])], + }, +}) +``` + +### `stripSearchParams` — Remove Default Values from URL + +```tsx +import { createFileRoute, stripSearchParams } from '@tanstack/react-router' +import { z } from 'zod' + +const defaults = { sort: 'newest', page: 1 } + +const searchSchema = z.object({ + sort: z.string().default(defaults.sort), + page: z.number().default(defaults.page), +}) + +export const Route = createFileRoute('/items')({ + validateSearch: searchSchema, + search: { + middlewares: [stripSearchParams(defaults)], + }, +}) +``` + +### Chaining Middlewares + +```tsx +export const Route = createFileRoute('/search')({ + validateSearch: z.object({ + retainMe: z.string().optional(), + arrayWithDefaults: z.string().array().default(['foo', 'bar']), + required: z.string(), + }), + search: { + middlewares: [ + retainSearchParams(['retainMe']), + stripSearchParams({ arrayWithDefaults: ['foo', 'bar'] }), + ], + }, +}) +``` + +## Custom Serialization + +Override the default JSON serialization at the router level: + +```tsx +import { + createRouter, + parseSearchWith, + stringifySearchWith, +} from '@tanstack/react-router' + +const router = createRouter({ + routeTree, + // Example: use JSURL2 for compact, human-readable URLs + parseSearch: parseSearchWith(parse), + stringifySearch: stringifySearchWith(stringify), +}) +``` + +## Using Search Params in Loaders via `loaderDeps` + +```tsx +export const Route = createFileRoute('/products')({ + validateSearch: productSearchSchema, + // Pick ONLY the params the loader needs — not the entire search object + loaderDeps: ({ search }) => ({ page: search.page }), + loader: async ({ deps }) => { + return fetchProducts({ page: deps.page }) + }, +}) +``` + +## Common Mistakes + +### 1. HIGH: Using zod v3's `.catch()` with `zodValidator()` instead of adapter `fallback()` + +```tsx +// WRONG — .catch() with zodValidator makes the type unknown +const schema = z.object({ page: z.number().catch(1) }) +validateSearch: zodValidator(schema) // page is typed as unknown! + +// CORRECT — fallback() preserves the inferred type +import { fallback } from '@tanstack/zod-adapter' +const schema = z.object({ page: fallback(z.number(), 1) }) +``` + +**Important:** This only applies when using Zod v3, not when using Zod v4. For v4, using `.catch()` is correct. + +### 2. HIGH: Returning entire search object from `loaderDeps` + +```tsx +// WRONG — loader re-runs on ANY search param change +loaderDeps: ({ search }) => search + +// CORRECT — loader only re-runs when page changes +loaderDeps: ({ search }) => ({ page: search.page }) +``` + +### 3. HIGH: Passing Date objects in search params + +```tsx +// WRONG — Date does not serialize correctly to JSON in URLs + + +// CORRECT — convert to ISO string + +``` + +### 4. MEDIUM: Parent route missing `validateSearch` blocks inheritance + +```tsx +// WRONG — child cannot access shared params +export const Route = createRootRoute({ + component: RootComponent, + // no validateSearch! +}) + +// CORRECT — parent must define validateSearch for children to inherit +export const Route = createRootRoute({ + validateSearch: globalSearchSchema, + component: RootComponent, +}) +``` + +### 5. HIGH (cross-skill): Using search as object instead of function loses params + +```tsx +// WRONG — replaces ALL search params, losing any existing ones +Page 2 + +// CORRECT — preserves existing params, updates only page + ({ ...prev, page: 2 })}>Page 2 +``` + +## References + +- [Validation Patterns Reference](./references/validation-patterns.md) — comprehensive patterns for all validation libraries diff --git a/packages/router-core/skills/router-core/search-params/references/validation-patterns.md b/packages/router-core/skills/router-core/search-params/references/validation-patterns.md new file mode 100644 index 0000000000..a0c72c7bd2 --- /dev/null +++ b/packages/router-core/skills/router-core/search-params/references/validation-patterns.md @@ -0,0 +1,384 @@ +# Search Param Validation Patterns Reference + +Comprehensive validation patterns for TanStack Router search params across all supported validation approaches. + +## Zod with `@tanstack/zod-adapter` + +Zod v3 does not implement Standard Schema, so the `@tanstack/zod-adapter` wrapper is required. Always use `fallback()` from the adapter instead of zod's `.catch()`. Always wrap with `zodValidator()`. + +### Basic Types + +```tsx +import { zodValidator, fallback } from '@tanstack/zod-adapter' +import { z } from 'zod' + +const schema = z.object({ + count: fallback(z.number(), 0), + name: fallback(z.string(), ''), + active: fallback(z.boolean(), true), +}) + +export const Route = createFileRoute('/example')({ + validateSearch: zodValidator(schema), +}) +``` + +### Optional Params + +```tsx +const schema = z.object({ + // Truly optional — can be undefined in component + searchTerm: z.string().optional(), + // Optional in URL but always has a value in component + page: fallback(z.number(), 1).default(1), +}) +``` + +### Default Values + +```tsx +const schema = z.object({ + // .default() means the param is optional during navigation + // but always present (with default) when reading + page: fallback(z.number(), 1).default(1), + sort: fallback(z.enum(['name', 'date', 'price']), 'name').default('name'), + ascending: fallback(z.boolean(), true).default(true), +}) +``` + +### Array Params + +```tsx +const schema = z.object({ + tags: fallback(z.string().array(), []).default([]), + selectedIds: fallback(z.number().array(), []).default([]), +}) + +// URL: /items?tags=%5B%22react%22%2C%22typescript%22%5D&selectedIds=%5B1%2C2%2C3%5D +// Parsed: { tags: ['react', 'typescript'], selectedIds: [1, 2, 3] } +``` + +### Nested Object Params + +```tsx +const schema = z.object({ + filters: fallback( + z.object({ + status: z.enum(['active', 'inactive']).optional(), + tags: z.string().array().optional(), + priceRange: z + .object({ + min: z.number().min(0), + max: z.number().min(0), + }) + .optional(), + }), + {}, + ).default({}), +}) +``` + +### Enum with Constraints + +```tsx +const schema = z.object({ + sort: fallback(z.enum(['newest', 'oldest', 'price']), 'newest').default( + 'newest', + ), + page: fallback(z.number().int().min(1).max(1000), 1).default(1), + limit: fallback(z.number().int().min(10).max(100), 20).default(20), +}) +``` + +### Discriminated Union + +```tsx +const schema = z.object({ + searchType: fallback(z.enum(['basic', 'advanced']), 'basic').default('basic'), + query: fallback(z.string(), '').default(''), + // Advanced-only fields are optional + category: z.string().optional(), + minPrice: z.number().optional(), + maxPrice: z.number().optional(), +}) +``` + +For true discriminated union validation: + +```tsx +const basicSearch = z.object({ + searchType: z.literal('basic'), + query: z.string(), +}) + +const advancedSearch = z.object({ + searchType: z.literal('advanced'), + query: z.string(), + category: z.string(), + minPrice: z.number(), + maxPrice: z.number(), +}) + +const schema = z.discriminatedUnion('searchType', [basicSearch, advancedSearch]) + +export const Route = createFileRoute('/search')({ + validateSearch: zodValidator(schema), +}) +``` + +### Input Transforms (String to Number) + +When using the zod adapter with transforms, configure `input` and `output` types: + +```tsx +const schema = z.object({ + page: fallback(z.number(), 1).default(1), + filter: fallback(z.string(), '').default(''), +}) + +export const Route = createFileRoute('/items')({ + // Default: input type used for navigation, output type used for reading + validateSearch: zodValidator(schema), + + // Advanced: swap input/output inference + // validateSearch: zodValidator({ schema, input: 'output', output: 'input' }), +}) +``` + +### Schema Composition + +```tsx +const paginationSchema = z.object({ + page: fallback(z.number().int().positive(), 1).default(1), + limit: fallback(z.number().int().min(1).max(100), 20).default(20), +}) + +const sortSchema = z.object({ + sortBy: z.enum(['name', 'date', 'relevance']).optional(), + sortOrder: z.enum(['asc', 'desc']).optional(), +}) + +// Compose for specific routes +const productSearchSchema = paginationSchema.extend({ + category: z.string().optional(), + inStock: fallback(z.boolean(), true).default(true), +}) + +const userSearchSchema = paginationSchema.merge(sortSchema).extend({ + role: z.enum(['admin', 'user']).optional(), +}) +``` + +--- + +## Valibot (Standard Schema) + +Valibot 1.0+ implements Standard Schema. No adapter wrapper needed — pass the schema directly to `validateSearch`. The `@tanstack/valibot-adapter` is optional and only needed for explicit input/output type control. + +```bash +npm install valibot +``` + +```tsx +import { createFileRoute } from '@tanstack/react-router' +import * as v from 'valibot' + +const productSearchSchema = v.object({ + page: v.optional(v.fallback(v.number(), 1), 1), + filter: v.optional(v.fallback(v.string(), ''), ''), + sort: v.optional( + v.fallback(v.picklist(['newest', 'oldest', 'price']), 'newest'), + 'newest', + ), +}) + +export const Route = createFileRoute('/products')({ + // Pass schema directly — Standard Schema compliant + validateSearch: productSearchSchema, + component: ProductsPage, +}) + +function ProductsPage() { + const { page, filter, sort } = Route.useSearch() + return
    Page {page}
    +} +``` + +### Valibot with Constraints + +```tsx +import * as v from 'valibot' + +const schema = v.object({ + page: v.optional( + v.fallback(v.pipe(v.number(), v.integer(), v.minValue(1)), 1), + 1, + ), + query: v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(100))), + tags: v.optional(v.fallback(v.array(v.string()), []), []), +}) +``` + +### Valibot with Adapter (Alternative) + +If you need explicit input/output type control: + +```tsx +import { valibotValidator } from '@tanstack/valibot-adapter' +import * as v from 'valibot' + +const schema = v.object({ + page: v.optional(v.fallback(v.number(), 1), 1), +}) + +export const Route = createFileRoute('/items')({ + validateSearch: valibotValidator(schema), +}) +``` + +--- + +## ArkType (Standard Schema) + +ArkType 2.0-rc+ implements Standard Schema. No adapter needed — pass the type directly to `validateSearch`. The `@tanstack/arktype-adapter` is optional and only needed for explicit input/output type control. + +```bash +npm install arktype +``` + +```tsx +import { createFileRoute } from '@tanstack/react-router' +import { type } from 'arktype' + +const productSearchSchema = type({ + page: 'number = 1', + filter: 'string = ""', + sort: '"newest" | "oldest" | "price" = "newest"', +}) + +export const Route = createFileRoute('/products')({ + // Pass directly — Standard Schema compliant + validateSearch: productSearchSchema, + component: ProductsPage, +}) + +function ProductsPage() { + const { page, filter, sort } = Route.useSearch() + return
    Page {page}
    +} +``` + +### ArkType with Constraints + +```tsx +import { type } from 'arktype' + +const searchSchema = type({ + 'query?': 'string>0&<=100', + page: 'number>0 = 1', + 'sortBy?': "'name'|'date'|'relevance'", + 'filters?': 'string[]', +}) +``` + +--- + +## Manual Validation Function + +For full control without any library. The function receives raw JSON-parsed (but unvalidated) search params. + +```tsx +import { createFileRoute } from '@tanstack/react-router' + +type ProductSearch = { + page: number + filter: string + sort: 'newest' | 'oldest' | 'price' +} + +export const Route = createFileRoute('/products')({ + validateSearch: (search: Record): ProductSearch => ({ + page: Number(search?.page ?? 1), + filter: (search.filter as string) || '', + sort: + search.sort === 'newest' || + search.sort === 'oldest' || + search.sort === 'price' + ? search.sort + : 'newest', + }), + component: ProductsPage, +}) + +function ProductsPage() { + const { page, filter, sort } = Route.useSearch() + return
    Page {page}
    +} +``` + +### Manual Validation with Error Throwing + +If `validateSearch` throws, the route's `errorComponent` renders instead: + +```tsx +export const Route = createFileRoute('/products')({ + validateSearch: (search: Record) => { + const page = Number(search.page) + if (isNaN(page) || page < 1) { + throw new Error('Invalid page number') + } + return { page } + }, + errorComponent: ({ error }) => ( +
    + Bad search params:{' '} + {error instanceof Error ? error.message : String(error)} +
    + ), +}) +``` + +--- + +## Pattern: Object with `parse` Method + +Any object with a `.parse()` method works as `validateSearch`: + +```tsx +const mySchema = { + parse: (input: Record) => ({ + page: Number(input.page ?? 1), + query: String(input.query ?? ''), + }), +} + +export const Route = createFileRoute('/search')({ + validateSearch: mySchema, +}) +``` + +--- + +## Dates in Search Params + +Never put `Date` objects in search params. Always use ISO strings: + +```tsx +const schema = z.object({ + // Store as string, parse in component if needed + startDate: z.string().optional(), + endDate: z.string().optional(), +}) + +// In component: +function DateFilter() { + const { startDate } = Route.useSearch() + const date = startDate ? new Date(startDate) : null + return
    {date?.toLocaleDateString()}
    +} + +// When navigating: +; ({ ...prev, startDate: new Date().toISOString() })}> + Set Start Date + +``` diff --git a/packages/router-core/skills/router-core/ssr/SKILL.md b/packages/router-core/skills/router-core/ssr/SKILL.md new file mode 100644 index 0000000000..752fb837a5 --- /dev/null +++ b/packages/router-core/skills/router-core/ssr/SKILL.md @@ -0,0 +1,492 @@ +--- +name: ssr +description: >- + Non-streaming and streaming SSR, RouterClient/RouterServer, + renderRouterToString/renderRouterToStream, createRequestHandler, + defaultRenderHandler/defaultStreamHandler, HeadContent/Scripts + components, head route option (meta/links/styles/scripts), + ScriptOnce, automatic loader dehydration/hydration, memory + history on server, data serialization, document head management. +metadata: + type: sub-skill + library: tanstack-router + library_version: '1.171.15' +requires: + - router-core + - router-core/data-loading +sources: + - TanStack/router:docs/router/guide/ssr.md + - TanStack/router:docs/router/guide/document-head-management.md + - TanStack/router:docs/router/how-to/setup-ssr.md +--- + +# SSR (Server-Side Rendering) + +> **WARNING**: SSR APIs are experimental. They share internal implementations with TanStack Start and may change. **TanStack Start is the recommended way to do SSR in production** — use manual SSR setup only when integrating with an existing server. + +> **CRITICAL**: TanStack Router is CLIENT-FIRST. Loaders run on the client by default. With SSR enabled, loaders run on BOTH client AND server. They are NOT server-only like Remix/Next.js loaders. See [router-core/data-loading](../data-loading/SKILL.md). + +> **CRITICAL**: Do not generate Next.js patterns (`getServerSideProps`, App Router, server components) or Remix patterns (server-only loader exports). TanStack Router has its own SSR API. + +## Concepts + +There are two SSR flavors: + +- **Non-streaming**: Full page rendered on server, sent as one HTML response, then hydrated on client. +- **Streaming**: Critical first paint sent immediately; remaining content streamed incrementally as it resolves. + +Key behaviors: + +- Memory history is used automatically on the server (no `window`). +- Loader data is automatically dehydrated on the server and hydrated on the client. +- Data serialization supports `Date`, `Error`, `FormData`, and `undefined` out of the box. + +## Setup: Shared Router Factory + +The router must be created identically on server and client. Export a factory function from a shared file: + +```tsx +// src/router.tsx +import { createRouter as createTanstackRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function createRouter() { + return createTanstackRouter({ routeTree }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} +``` + +## Non-Streaming SSR + +### Server Entry (using `defaultRenderHandler`) + +```tsx +// src/entry-server.tsx +import { + createRequestHandler, + defaultRenderHandler, +} from '@tanstack/react-router/ssr/server' +import { createRouter } from './router' + +export async function render({ request }: { request: Request }) { + const handler = createRequestHandler({ request, createRouter }) + return await handler(defaultRenderHandler) +} +``` + +### Server Entry (using `renderRouterToString` for custom wrappers) + +```tsx +// src/entry-server.tsx +import { + createRequestHandler, + renderRouterToString, + RouterServer, +} from '@tanstack/react-router/ssr/server' +import { createRouter } from './router' + +export function render({ request }: { request: Request }) { + const handler = createRequestHandler({ request, createRouter }) + + return handler(({ responseHeaders, router }) => + renderRouterToString({ + responseHeaders, + router, + children: , + }), + ) +} +``` + +### Client Entry + +```tsx +// src/entry-client.tsx +import { hydrateRoot } from 'react-dom/client' +import { RouterClient } from '@tanstack/react-router/ssr/client' +import { createRouter } from './router' + +const router = createRouter() + +hydrateRoot(document, ) +``` + +## Streaming SSR + +### Server Entry (using `defaultStreamHandler`) + +```tsx +// src/entry-server.tsx +import { + createRequestHandler, + defaultStreamHandler, +} from '@tanstack/react-router/ssr/server' +import { createRouter } from './router' + +export async function render({ request }: { request: Request }) { + const handler = createRequestHandler({ request, createRouter }) + return await handler(defaultStreamHandler) +} +``` + +### Server Entry (using `renderRouterToStream` for custom wrappers) + +```tsx +// src/entry-server.tsx +import { + createRequestHandler, + renderRouterToStream, + RouterServer, +} from '@tanstack/react-router/ssr/server' +import { createRouter } from './router' + +export function render({ request }: { request: Request }) { + const handler = createRequestHandler({ request, createRouter }) + + return handler(({ request, responseHeaders, router }) => + renderRouterToStream({ + request, + responseHeaders, + router, + children: , + }), + ) +} +``` + +Streaming is automatic — deferred data (unawaited promises from loaders) and streamed markup just work when using `defaultStreamHandler` or `renderRouterToStream`. + +## Document Head Management + +Use the `head` route option to manage ``, `<meta>`, `<link>`, and `<style>` tags. Render `<HeadContent />` in `<head>` and `<Scripts />` in `<body>`. + +### Root Route with Head + +```tsx +// src/routes/__root.tsx +import { + createRootRoute, + HeadContent, + Outlet, + Scripts, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'UTF-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1.0' }, + { title: 'My App' }, + ], + links: [{ rel: 'icon', href: '/favicon.ico' }], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + <html lang="en"> + <head> + <HeadContent /> + </head> + <body> + <Outlet /> + <Scripts /> + </body> + </html> + ) +} +``` + +### Per-Route Head (Nested Deduplication) + +Child route `title` and `meta` tags override parent tags with the same `name`/`property`: + +```tsx +// src/routes/posts/$postId.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params }) => { + const post = await fetchPost(params.postId) + return { post } + }, + head: ({ loaderData }) => ({ + meta: [ + { title: loaderData.post.title }, + { name: 'description', content: loaderData.post.excerpt }, + ], + }), + component: PostPage, +}) + +function PostPage() { + const { post } = Route.useLoaderData() + return <article>{post.content}</article> +} +``` + +### SPA Head (No Full HTML Control) + +For SPAs without server-rendered HTML, render `<HeadContent />` at the top of the component tree: + +```tsx +import { createRootRoute, HeadContent, Outlet } from '@tanstack/react-router' + +const rootRoute = createRootRoute({ + head: () => ({ + meta: [{ title: 'My SPA' }], + }), + component: () => ( + <> + <HeadContent /> + <Outlet /> + </> + ), +}) +``` + +## Body Scripts + +Use `scripts` (separate from `head.scripts`) to inject scripts into `<body>` before the app entry point: + +```tsx +export const Route = createRootRoute({ + scripts: () => [{ children: 'console.log("runs before hydration")' }], +}) +``` + +The `<Scripts />` component renders these. Place it at the end of `<body>`. + +## ScriptOnce for Pre-Hydration Scripts + +`ScriptOnce` renders a `<script>` during SSR that executes immediately and self-removes. On client navigation, it does nothing (no duplicate execution). + +```tsx +import { ScriptOnce } from '@tanstack/react-router' + +const themeScript = `(function() { + try { + const theme = localStorage.getItem('theme') || 'auto'; + const resolved = theme === 'auto' + ? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') + : theme; + document.documentElement.classList.add(resolved); + } catch (e) {} +})();` + +function ThemeProvider({ children }: { children: React.ReactNode }) { + return ( + <> + <ScriptOnce children={themeScript} /> + {children} + </> + ) +} +``` + +If the script modifies the DOM (e.g., adds a class to `<html>`), use `suppressHydrationWarning` on the element: + +```tsx +<html lang="en" suppressHydrationWarning> +``` + +## Express Integration Example + +`createRequestHandler` expects a Web API `Request` and returns a Web API `Response`. For Express, convert between formats: + +```tsx +// src/entry-server.tsx +import { pipeline } from 'node:stream/promises' +import { + RouterServer, + createRequestHandler, + renderRouterToString, +} from '@tanstack/react-router/ssr/server' +import { createRouter } from './router' +import type express from 'express' + +export async function render({ + req, + res, +}: { + req: express.Request + res: express.Response +}) { + const protocol = req.get('x-forwarded-proto') ?? req.protocol + const host = req.get('x-forwarded-host') ?? req.get('host') + const url = new URL(req.originalUrl || req.url, `${protocol}://${host}`).href + + const request = new Request(url, { + method: req.method, + headers: (() => { + const headers = new Headers() + for (const [key, value] of Object.entries(req.headers)) { + headers.set(key, value as any) + } + return headers + })(), + }) + + const handler = createRequestHandler({ request, createRouter }) + + const response = await handler(({ responseHeaders, router }) => + renderRouterToString({ + responseHeaders, + router, + children: <RouterServer router={router} />, + }), + ) + + res.status(response.status) + response.headers.forEach((value, name) => { + res.setHeader(name, value) + }) + + return pipeline(response.body as any, res) +} +``` + +## Common Mistakes + +### 1. HIGH: Using browser APIs in loaders without environment check + +Loaders run on BOTH client and server with SSR. Browser-only APIs (`window`, `document`, `localStorage`) throw on the server. + +```tsx +// WRONG — crashes on server +loader: async () => { + const token = localStorage.getItem('token') + return fetchData(token) +} + +// CORRECT — guard with environment check +loader: async () => { + const token = + typeof window !== 'undefined' ? localStorage.getItem('token') : null + return fetchData(token) +} +``` + +### 2. MEDIUM: Using hash fragments for server-rendered content + +Hash fragments (`#section`) are never sent to the server. Conditional rendering based on hash causes hydration mismatches. + +```tsx +// WRONG — server has no hash, client does → mismatch +component: () => { + const hash = window.location.hash + return hash === '#admin' ? <AdminPanel /> : <UserPanel /> +} + +// CORRECT — use search params for server-visible state +validateSearch: z.object({ view: fallback(z.enum(['admin', 'user']), 'user') }), +component: () => { + const { view } = Route.useSearch() + return view === 'admin' ? <AdminPanel /> : <UserPanel /> +} +``` + +### 3. CRITICAL: Generating Next.js, Remix, or React Router DOM patterns + +TanStack Router does NOT use `getServerSideProps`, `getStaticProps`, App Router `page.tsx`, Remix-style server-only `loader` exports, or anything from `react-router-dom`. + +#### Wrong file structures + +```text +WRONG (Next.js Pages Router): + src/pages/index.tsx + src/pages/_app.tsx + src/pages/posts/[id].tsx + +WRONG (Next.js App Router): + app/layout.tsx + app/page.tsx + app/posts/[id]/page.tsx + +WRONG (Next.js custom App): + _app/index.tsx + pages/_app.tsx, pages/_document.tsx + +CORRECT (TanStack Router file-based routing): + src/routes/__root.tsx + src/routes/index.tsx + src/routes/posts/$postId.tsx +``` + +#### Wrong imports + +```tsx +// WRONG — react-router-dom is a different library +import { + Link, + useNavigate, + BrowserRouter, + Route, + Routes, +} from 'react-router-dom' + +// WRONG — Next.js Link/router +import Link from 'next/link' +import { useRouter } from 'next/router' // Pages Router +import { useRouter } from 'next/navigation' // App Router + +// CORRECT — everything routing-related lives in @tanstack/react-router +import { + Link, + useNavigate, + useRouter, + useLocation, + redirect, +} from '@tanstack/react-router' +``` + +#### Wrong loader/data-fetching patterns + +```tsx +// WRONG — Next.js Pages Router +export async function getServerSideProps() { + return { props: { data: await fetchData() } } +} + +// WRONG — Remix +export async function loader({ request }: LoaderFunctionArgs) { + return json({ data: await fetchData() }) +} + +// CORRECT — TanStack Router +export const Route = createFileRoute('/data')({ + loader: async () => { + const data = await fetchData() + return { data } + }, + component: DataPage, +}) + +function DataPage() { + const { data } = Route.useLoaderData() + return <div>{data}</div> +} +``` + +If you see `src/pages/`, `app/layout.tsx`, `react-router-dom`, or any of the above in agent output, the agent is generating for the wrong framework. The build will either fail or produce duplicate `/` routes that conflict at runtime. + +## Tension: Client-First Loaders vs SSR + +TanStack Router loaders are client-first by design. When SSR is enabled, they run in both environments. This means: + +- Browser APIs work by default (client-only) but break under SSR +- Database access does NOT belong in loaders (unlike Remix/Next) — use API routes +- For server-only data logic with SSR, use TanStack Start's server functions + +See [router-core/data-loading](../data-loading/SKILL.md) for loader fundamentals. + +## Cross-References + +- [router-core/data-loading](../data-loading/SKILL.md) — SSR changes where loaders execute +- `@tanstack/react-router#compositions/router-query` — SSR dehydration/hydration with TanStack Query diff --git a/packages/router-core/skills/router-core/type-safety/SKILL.md b/packages/router-core/skills/router-core/type-safety/SKILL.md new file mode 100644 index 0000000000..15b9d35770 --- /dev/null +++ b/packages/router-core/skills/router-core/type-safety/SKILL.md @@ -0,0 +1,499 @@ +--- +name: type-safety +description: >- + Full type inference philosophy (never cast, never annotate inferred + values), Register module declaration, from narrowing on hooks and + Link, strict:false for shared components, getRouteApi for code-split + typed access, addChildren with object syntax for TS perf, LinkProps + and ValidateLinkOptions type utilities, as const satisfies pattern. +metadata: + type: sub-skill + library: tanstack-router + library_version: '1.171.15' +requires: + - router-core +sources: + - TanStack/router:docs/router/guide/type-safety.md + - TanStack/router:docs/router/guide/type-utilities.md + - TanStack/router:docs/router/guide/render-optimizations.md +--- + +# Type Safety + +TanStack Router is FULLY type-inferred. Params, search params, context, and loader data all flow through the route tree automatically. The **#1 AI agent mistake** is adding type annotations, casts, or generic parameters to values that are already inferred. + +> **CRITICAL**: NEVER use `as Type`, explicit generic params, `satisfies` on hook returns, or type annotations on inferred values. Every cast masks real type errors and breaks the inference chain. +> **CRITICAL**: Do NOT confuse TanStack Router with Next.js or React Router. There is no `getServerSideProps`, no `useSearchParams()`, no `useLoaderData()` from `react-router-dom`. + +## The ONE Required Type Annotation: Register + +Without this, top-level exports like `Link`, `useNavigate`, `useSearch` have no type safety. + +```tsx +// src/router.tsx +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +const router = createRouter({ routeTree }) + +// THIS IS REQUIRED — the single type registration for the entire app +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +export default router +``` + +After registration, every `Link`, `useNavigate`, `useSearch`, `useParams` across the app is fully typed. + +## Types Flow Automatically + +### Route Hooks — No Annotation Needed + +```tsx +// src/routes/posts.$postId.tsx +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts/$postId')({ + validateSearch: (search: Record<string, unknown>) => ({ + page: Number(search.page ?? 1), + }), + loader: async ({ params }) => { + // params.postId is already typed as string — do not annotate + const post = await fetchPost(params.postId) + return { post } + }, + component: PostComponent, +}) + +function PostComponent() { + // ALL of these are fully inferred — do NOT add type annotations + const { postId } = Route.useParams() + // ^? string + + const { page } = Route.useSearch() + // ^? number + + const { post } = Route.useLoaderData() + // ^? { id: string; title: string; body: string } + + return ( + <div> + <h1>{post.title}</h1> + <p>Page {page}</p> + </div> + ) +} +``` + +### Context Flows Through the Tree + +```tsx +// src/routes/__root.tsx +import { createRootRouteWithContext, Outlet } from '@tanstack/react-router' + +interface RouterContext { + auth: { userId: string; role: 'admin' | 'user' } | null +} + +// Note: createRootRouteWithContext is a FACTORY — call it TWICE: ()() +export const Route = createRootRouteWithContext<RouterContext>()({ + component: () => <Outlet />, +}) +``` + +```tsx +// src/routes/dashboard.tsx +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/dashboard')({ + beforeLoad: ({ context }) => { + // context.auth is already typed as { userId: string; role: 'admin' | 'user' } | null + // NO annotation needed + if (!context.auth) throw redirect({ to: '/login' }) + return { user: context.auth } + }, + loader: ({ context }) => { + // context.user is typed as { userId: string; role: 'admin' | 'user' } + // This was added by beforeLoad above — fully inferred + return fetchDashboard(context.user.userId) + }, + component: DashboardComponent, +}) + +function DashboardComponent() { + const data = Route.useLoaderData() + const { user } = Route.useRouteContext() + return <h1>Welcome {user.userId}</h1> +} +``` + +## Narrowing with `from` + +Without `from`, hooks return a union of ALL routes' types — slow for TypeScript and imprecise. + +### On Hooks + +```tsx +import { useSearch, useParams, useNavigate } from '@tanstack/react-router' + +function PostSidebar() { + // WRONG — search is a union of ALL routes' search params + const search = useSearch() + + // CORRECT — search is narrowed to /posts/$postId's search params + const search = useSearch({ from: '/posts/$postId' }) + // ^? { page: number } + + // CORRECT — params narrowed to this route + const { postId } = useParams({ from: '/posts/$postId' }) + + // CORRECT — navigate narrowed for relative paths + const navigate = useNavigate({ from: '/posts/$postId' }) +} +``` + +### On `Link` + +```tsx +import { Link } from '@tanstack/react-router' + +// WRONG — search resolves to union of ALL routes' search params, slow TS check +<Link to=".." search={{ page: 0 }} /> + +// CORRECT — narrowed, fast TS check +<Link from="/posts/$postId" to=".." search={{ page: 0 }} /> + +// Also correct — Route.fullPath in route components +<Link from={Route.fullPath} to=".." search={{ page: 0 }} /> +``` + +## Shared Components: `strict: false` + +When a component is used across multiple routes, use `strict: false` instead of `from`: + +```tsx +import { useSearch } from '@tanstack/react-router' + +function GlobalSearch() { + // Returns union of all routes' search params — no runtime error if route doesn't match + const search = useSearch({ strict: false }) + return <span>Query: {search.q ?? ''}</span> +} +``` + +## Code-Split Files: `getRouteApi` + +Use `getRouteApi` instead of importing `Route` to avoid pulling route config into the lazy chunk: + +```tsx +// src/routes/posts.lazy.tsx +import { createLazyFileRoute, getRouteApi } from '@tanstack/react-router' + +const routeApi = getRouteApi('/posts') + +export const Route = createLazyFileRoute('/posts')({ + component: PostsComponent, +}) + +function PostsComponent() { + const data = routeApi.useLoaderData() + const { page } = routeApi.useSearch() + return <div>Page {page}</div> +} +``` + +## TypeScript Performance + +### Use Object Syntax for `addChildren` in Large Route Trees + +```tsx +// SLOWER — tuple syntax +const routeTree = rootRoute.addChildren([ + postsRoute.addChildren([postRoute, postsIndexRoute]), + indexRoute, +]) + +// FASTER — object syntax (TS checks objects faster than large tuples) +const routeTree = rootRoute.addChildren({ + postsRoute: postsRoute.addChildren({ postRoute, postsIndexRoute }), + indexRoute, +}) +``` + +With file-based routing the route tree is generated, so this is handled for you. + +### Avoid Returning Unused Inferred Types from Loaders + +When using external caches like TanStack Query, don't let the router infer complex return types you never consume: + +```tsx +// SLOWER — TS infers the full query return type into the route tree +export const Route = createFileRoute('/posts/$postId')({ + loader: ({ context: { queryClient }, params: { postId } }) => + queryClient.query({ ...postQueryOptions(postId), staleTime: 'static' }), + component: PostComponent, +}) + +// FASTER — async loader returns no query data, inference stays out of the route tree +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ context: { queryClient }, params: { postId: id } }) => { + await queryClient.query({ ...postQueryOptions(id), staleTime: 'static' }) + }, + component: PostComponent, +}) +``` + +### `as const satisfies` for Link Option Objects + +Never use `LinkProps` as a variable type — it's an enormous union: + +```tsx +import type { LinkProps, RegisteredRouter } from '@tanstack/react-router' + +// WRONG — LinkProps is a massive union, extremely slow TS check +const wrongProps: LinkProps = { to: '/posts' } + +// CORRECT — infer a precise type, validate against LinkProps +const goodProps = { to: '/posts' } as const satisfies LinkProps + +// EVEN BETTER — narrow LinkProps with generic params +const narrowedProps = { + to: '/posts', +} as const satisfies LinkProps<RegisteredRouter, string, '/posts'> +``` + +### Type-Safe Link Option Arrays + +```tsx +import type { LinkProps } from '@tanstack/react-router' + +export const navLinks = [ + { to: '/posts' }, + { to: '/posts/$postId', params: { postId: '1' } }, +] as const satisfies ReadonlyArray<LinkProps> + +// Use the precise inferred type, not LinkProps directly +export type NavLink = (typeof navLinks)[number] +``` + +## Type Utilities for Generic Components + +### `ValidateLinkOptions` — Type-Safe Link Props in Custom Components + +```tsx +import { + Link, + type RegisteredRouter, + type ValidateLinkOptions, +} from '@tanstack/react-router' + +interface NavItemProps< + TRouter extends RegisteredRouter = RegisteredRouter, + TOptions = unknown, +> { + label: string + linkOptions: ValidateLinkOptions<TRouter, TOptions> +} + +export function NavItem<TRouter extends RegisteredRouter, TOptions>( + props: NavItemProps<TRouter, TOptions>, +): React.ReactNode +export function NavItem(props: NavItemProps): React.ReactNode { + return ( + <li> + <Link {...props.linkOptions}>{props.label}</Link> + </li> + ) +} + +// Usage — fully type-safe +<NavItem label="Posts" linkOptions={{ to: '/posts' }} /> +<NavItem label="Post" linkOptions={{ to: '/posts/$postId', params: { postId: '1' } }} /> +``` + +### `ValidateNavigateOptions` and `ValidateRedirectOptions` + +Same pattern as `ValidateLinkOptions` above, for `useNavigate` and `redirect`. Declare a generic public overload plus a non-generic implementation signature so the call site stays narrowed and the body works without casts: + +```tsx +import { + useNavigate, + type RegisteredRouter, + type ValidateNavigateOptions, +} from '@tanstack/react-router' + +export function useDelayedNavigate< + TRouter extends RegisteredRouter = RegisteredRouter, + TOptions = unknown, +>( + options: ValidateNavigateOptions<TRouter, TOptions>, + delayMs: number, +): () => void +export function useDelayedNavigate( + options: ValidateNavigateOptions, + delayMs: number, +) { + const navigate = useNavigate() + return () => { + setTimeout(() => navigate(options), delayMs) + } +} +``` + +`ValidateRedirectOptions` works identically — declare a generic overload accepting `ValidateRedirectOptions<TRouter, TOptions>` and an impl signature accepting `ValidateRedirectOptions`, then call `redirect(options)` in the body. + +### Render Props for Maximum Performance + +Instead of accepting `LinkProps`, invert control so `Link` is narrowed at the call site: + +```tsx +function Card(props: { title: string; renderLink: () => React.ReactNode }) { + return ( + <div> + <h2>{props.title}</h2> + {props.renderLink()} + </div> + ) +} + +// Link narrowed to exactly /posts — no union check +;<Card title="All Posts" renderLink={() => <Link to="/posts">View</Link>} /> +``` + +## Render Optimizations + +### Fine-Grained Selectors with `select` + +```tsx +function PostTitle() { + // Only re-renders when page changes, not when other search params change + const page = Route.useSearch({ select: ({ page }) => page }) + return <span>Page {page}</span> +} +``` + +### Structural Sharing + +Preserve referential identity across re-renders for search params: + +```tsx +const router = createRouter({ + routeTree, + defaultStructuralSharing: true, // Enable globally +}) + +// Or per-hook +const result = Route.useSearch({ + select: (search) => ({ foo: search.foo, label: `Page ${search.foo}` }), + structuralSharing: true, +}) +``` + +Structural sharing only works with JSON-compatible data. TypeScript will error if you return class instances with `structuralSharing: true`. + +## Common Mistakes + +### 1. CRITICAL: Adding type annotations or casts to inferred values + +```tsx +// WRONG — casting masks real type errors +const search = useSearch({ from: '/posts' }) as { page: number } + +// WRONG — unnecessary annotation +const params: { postId: string } = useParams({ from: '/posts/$postId' }) + +// WRONG — generic param on hook +const data = useLoaderData<{ posts: Post[] }>({ from: '/posts' }) + +// CORRECT — let inference work +const search = useSearch({ from: '/posts' }) +const params = useParams({ from: '/posts/$postId' }) +const data = useLoaderData({ from: '/posts' }) +``` + +### 2. HIGH: Using un-narrowed `LinkProps` type + +```tsx +// WRONG — LinkProps is a massive union, causes severe TS slowdown +const myProps: LinkProps = { to: '/posts' } + +// CORRECT — use as const satisfies for precise inference +const myProps = { to: '/posts' } as const satisfies LinkProps +``` + +### 3. HIGH: Not narrowing `Link`/`useNavigate` with `from` + +```tsx +// WRONG — search is a union of ALL routes, TS check grows with route count +<Link to=".." search={{ page: 0 }} /> + +// CORRECT — narrowed, fast check +<Link from={Route.fullPath} to=".." search={{ page: 0 }} /> +``` + +### 4. CRITICAL (cross-skill): Missing router type registration + +```tsx +// WRONG — Link/useNavigate have no autocomplete, all paths are untyped strings +const router = createRouter({ routeTree }) +// (no declare module) + +// CORRECT — always register +const router = createRouter({ routeTree }) +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} +``` + +### 5. CRITICAL (cross-skill): Wrong-framework imports and file structure + +Wrong-framework code looks plausible (it's React) but breaks the build or produces conflicting `/` routes at runtime. + +```tsx +// WRONG — react-router-dom and next/* are different libraries +import { Link, useNavigate, useSearchParams } from 'react-router-dom' +import Link from 'next/link' +import { useRouter, useParams } from 'next/navigation' + +// CORRECT — all routing exports come from @tanstack/react-router +import { + Link, + Outlet, + useNavigate, + useRouter, + useLocation, + useParams, + redirect, +} from '@tanstack/react-router' +``` + +```tsx +// WRONG file structures + APIs: +// src/pages/*.tsx with getServerSideProps / getStaticProps (Next.js Pages Router) +// app/layout.tsx + app/page.tsx (Next.js App Router) +// _app/index.tsx, pages/_app.tsx, pages/_document.tsx (Next.js custom App) +// loader/action exports (Remix) + +// CORRECT — TanStack file-based routing at src/routes/*.tsx +export const Route = createFileRoute('/posts')({ + loader: async () => { ... }, + validateSearch: zodValidator(schema), + component: PostsComponent, +}) +const search = Route.useSearch() +``` + +If a build error mentions `react-router-dom`, `next/`, `pages/_app`, or duplicate `/` routes, fix the import — don't paper over with type assertions. + +### 6. CRITICAL: Treating typecheck as proof of runtime schema propagation + +Types can say a field exists while a database projection, API serializer, or server function omits it. When adding or renaming a field, trace the value through storage, validation, handler output, loader data, and rendered UI. Do not cast the response to the desired type. +Add a runtime assertion against the real handler or serialized response, such as `expect(await getOrder({ data: { id } })).toMatchObject({ totalCents: 2599 })`. +Then run the route-level test and production build. The type test remains necessary, but it is not the runtime contract test. + +See also: router-core (Register setup), router-core/navigation (from narrowing), router-core/code-splitting (getRouteApi). diff --git a/packages/router-core/src/Matches.ts b/packages/router-core/src/Matches.ts index 852d186b67..41fd4018b5 100644 --- a/packages/router-core/src/Matches.ts +++ b/packages/router-core/src/Matches.ts @@ -9,7 +9,7 @@ import type { RouteIds, } from './routeInfo' import type { AnyRouter, RegisteredRouter, SSROption } from './router' -import type { Constrain, ControlledPromise } from './utils' +import type { Constrain } from './utils' export type AnyMatchAndValue = { match: any; value: any } @@ -131,47 +131,32 @@ export interface RouteMatch< pathname: string params: TAllParams _strictParams: TAllParams - status: 'pending' | 'success' | 'error' | 'redirected' | 'notFound' + status: 'pending' | 'success' | 'error' | 'notFound' isFetching: false | 'beforeLoad' | 'loader' error: unknown paramsError: unknown searchError: unknown updatedAt: number - _nonReactive: { - /** @internal */ - beforeLoadPromise?: ControlledPromise<void> - /** @internal */ - loaderPromise?: ControlledPromise<void> - /** @internal */ - pendingTimeout?: ReturnType<typeof setTimeout> - loadPromise?: ControlledPromise<void> - displayPendingPromise?: Promise<void> - minPendingPromise?: ControlledPromise<void> - dehydrated?: boolean - /** @internal */ - error?: unknown - } loaderData?: TLoaderData + /** @internal Exclusive end of the SSR-verified asset prefix. */ + _assetEnd?: number /** @internal */ - __routeContext?: Record<string, unknown> + _ctx?: Record<string, unknown> /** @internal */ __beforeLoadContext?: Record<string, unknown> context: TAllContext search: TFullSearchSchema _strictSearch: TFullSearchSchema - fetchCount: number abortController: AbortController cause: 'preload' | 'enter' | 'stay' loaderDeps: TLoaderDeps preload: boolean invalid: boolean headers?: Record<string, string> - globalNotFound?: boolean + _notFound?: boolean staticData: StaticDataRouteOption /** This attribute is not reactive */ ssr?: SSROption - _forcePending?: boolean - _displayPending?: boolean } export interface PreValidationErrorHandlingRouteMatch< diff --git a/packages/router-core/src/await-signal.ts b/packages/router-core/src/await-signal.ts new file mode 100644 index 0000000000..61d59bde2d --- /dev/null +++ b/packages/router-core/src/await-signal.ts @@ -0,0 +1,61 @@ +function observeLate<T>( + callback: ((value: T) => unknown) | undefined, + value: T, +) { + if (!callback) { + return + } + + try { + const result = callback(value) + if (result !== undefined) { + void Promise.resolve(result).catch(() => {}) + } + } catch {} +} + +/** + * Await `value` unless `signal` aborts first. A result that settles after the + * abort is passed to `onLate` / `onLateError` instead. + * + * One abort listener per wait: SSR requests nest at most a few waits on one + * signal, so pooling them was measurably slower than this. + */ +export function waitForReason<T>( + value: T | PromiseLike<T>, + signal: AbortSignal, + onLate?: (value: T) => unknown, + onLateError?: (reason: unknown) => unknown, +): Promise<T> { + const promise = Promise.resolve(value) + if (signal.aborted) { + void promise.then( + (result) => observeLate(onLate, result), + (error) => observeLate(onLateError, error), + ) + return Promise.reject(signal.reason) + } + + return new Promise<T>((resolve, reject) => { + const abort = () => reject(signal.reason) + signal.addEventListener('abort', abort, { once: true }) + void promise.then( + (result) => { + signal.removeEventListener('abort', abort) + if (signal.aborted) { + observeLate(onLate, result) + } else { + resolve(result) + } + }, + (error) => { + signal.removeEventListener('abort', abort) + if (signal.aborted) { + observeLate(onLateError, error) + } else { + reject(error) + } + }, + ) + }) +} diff --git a/packages/router-core/src/config.ts b/packages/router-core/src/config.ts index 44a369b498..d6c41fb40f 100644 --- a/packages/router-core/src/config.ts +++ b/packages/router-core/src/config.ts @@ -27,8 +27,8 @@ export interface RouterConfigTypes< } export const createRouterConfig = < - const TSerializationAdapters extends - ReadonlyArray<AnySerializationAdapter> = [], + const TSerializationAdapters extends ReadonlyArray<AnySerializationAdapter> = + [], TDefaultSsr extends SSROption = SSROption, >( options: RouterConfigOptions<TSerializationAdapters, TDefaultSsr>, diff --git a/packages/router-core/src/fileRoute.ts b/packages/router-core/src/fileRoute.ts index 5f39b88143..90b47ab643 100644 --- a/packages/router-core/src/fileRoute.ts +++ b/packages/router-core/src/fileRoute.ts @@ -49,7 +49,9 @@ export interface FileRouteOptions< TSSR = unknown, TServerMiddlewares = unknown, THandlers = undefined, -> extends FileBaseRouteOptions< +> + extends + FileBaseRouteOptions< TRegister, TParentRoute, TId, diff --git a/packages/router-core/src/index.ts b/packages/router-core/src/index.ts index 73019ccbb6..9206ef60dd 100644 --- a/packages/router-core/src/index.ts +++ b/packages/router-core/src/index.ts @@ -2,6 +2,7 @@ export * from './global' export { TSR_DEFERRED_PROMISE, defer } from './defer' export type { DeferredPromiseState, DeferredPromise } from './defer' +export { invariant } from './invariant' export { preloadWarning } from './link' export type { IsRequiredParams, @@ -14,7 +15,6 @@ export type { ResolveCurrentPath, ResolveParentPath, ResolveRelativePath, - LinkCurrentTargetElement, FindDescendantToPaths, InferDescendantToPaths, RelativeToPath, @@ -39,8 +39,6 @@ export type { RequiredToOptions, } from './link' -export { componentTypes } from './load-matches' - export type { RouteToPath, TrailingSlashOptionByRouter, @@ -70,8 +68,47 @@ export type { } from './fileRoute' export type { ParsedLocation } from './location' -export type { Manifest, RouterManagedTag } from './manifest' +export type { + Manifest, + ServerManifest, + ManifestRoute, + ManifestRouteAssets, + ServerManifestRoute, + ManifestCssLink, + ManifestInlineCss, + ServerManifestInlineCss, + InlineCssTemplate, + ManifestScript, + RouterManagedTag, + RouterManagedTitleTag, + RouterManagedMetaTag, + RouterManagedInlineCssTag, + RouterManagedScriptTag, + RouterManagedLinkTag, + RouterManagedStyleTag, + AssetCrossOrigin, + AssetCrossOriginConfig, + ManifestAssetLink, + ScriptFormat, +} from './manifest' +export { + DEV_STYLES_ATTR, + appendUniqueUserTags, + createInlineCssStyleAsset, + getAssetCrossOrigin, + getManifestScriptFormat, + getScriptPreloadAttrs, + getStylesheetHref, + resolveManifestAssetLink, + resolveManifestCssLink, +} from './manifest' export { isMatch } from './Matches' +export { + _getAssetMatches, + _getRenderedMatches, + _isRouteDeparting, +} from './load-client' +export { composeSsrBodyScripts, getSsrBodyScriptParts } from './ssr/bodyScripts' export type { AnyMatchAndValue, FindValueByIndex, @@ -101,6 +138,8 @@ export { exactPathTest, resolvePath, interpolatePath, + getRouteSegments, + hasMissingPathParams, } from './path' export { encode, decode } from './qss' export { rootRouteId } from './root' @@ -131,6 +170,8 @@ export type { DefaultSearchValidator, ErrorRouteProps, ErrorComponentProps, + DefaultErrorBoundaryTypes, + ErrorBoundaryTypes, NotFoundRouteProps, ResolveParams, ParseParamsFn, @@ -167,11 +208,14 @@ export type { FileBaseRouteOptions, BaseRouteOptions, UpdatableRouteOptions, + LoaderStaleReloadMode, RouteLoaderFn, + RouteLoaderEntry, LoaderFnContext, RouteContextFn, ContextOptions, RouteContextOptions, + SsrContextOptions, BeforeLoadContextOptions, RootRouteOptions, RootRouteOptionsExtensions, @@ -189,6 +233,17 @@ export type { RootRoute, FilebaseRouteOptionsInterface, } from './route' +export { + createNonReactiveMutableStore, + createNonReactiveReadonlyStore, +} from './stores' +export type { + RouterBatchFn, + RouterReadableStore, + GetStoreConfig, + RouterStores, + RouterWritableStore, +} from './stores' export { defaultSerializeError, getLocationChangeInfo, @@ -197,7 +252,6 @@ export { SearchParamError, PathParamError, getInitialRouterState, - getMatchedRoutes, trailingSlashOptions, } from './router' @@ -226,12 +280,9 @@ export type { ParseLocationFn, InvalidateFn, ControllablePromise, - InjectedHtmlEntry, EmitFn, LoadFn, - GetMatchFn, SubscribeFn, - UpdateMatchFn, CommitLocationFn, GetMatchRoutesFn, MatchRoutesFn, @@ -264,15 +315,18 @@ export type { SearchSerializer, SearchParser } from './searchParams' export type { OptionalStructuralSharing } from './structuralSharing' export { - last, functionalUpdate, + hasKeys, replaceEqualDeep, - isPlainObject, - isPlainArray, deepEqual, createControlledPromise, + isPromise, isModuleNotFoundError, - decodePath, + DEFAULT_PROTOCOL_ALLOWLIST, + escapeHtml, + getUrlScheme, + isDangerousProtocol, + buildDevStylesUrl, } from './utils' export type { NoInfer, @@ -359,6 +413,8 @@ export type { UseLoaderDataResult, ResolveUseLoaderData } from './useLoaderData' export type { Redirect, RedirectOptions, + RedirectOptionsRoute, + RedirectFnRoute, ResolvedRedirect, AnyRedirect, } from './redirect' @@ -375,12 +431,9 @@ export { isNotFound, notFound } from './not-found' export { defaultGetScrollRestorationKey, - restoreScroll, + getElementScrollRestorationEntry, storageKey, - getCssSelector, - scrollRestorationCache, setupScrollRestoration, - handleHashScroll, } from './scroll-restoration' export type { @@ -413,7 +466,6 @@ export type { AnySerializationAdapter, SerializationAdapter, ValidateSerializableInput, - ValidateSerializableInputResult, SerializerExtensions, ValidateSerializable, RegisteredSerializableInput, @@ -422,19 +474,18 @@ export type { Serializable, TSR_SERIALIZABLE, TsrSerializable, + SerializationError, } from './ssr/serializer/transformer' -export { - createSerializationAdapter, - makeSerovalPlugin, - makeSsrSerovalPlugin, -} from './ssr/serializer/transformer' +export { createSerializationAdapter } from './ssr/serializer/transformer' +export { makeSerovalPlugin } from './ssr/serializer/makeSerovalPlugin' -export { defaultSerovalPlugins } from './ssr/serializer/seroval-plugins' +export { RawStream } from './ssr/serializer/RawStream' +export type { + OnRawStreamCallback, + RawStreamHint, + RawStreamOptions, +} from './ssr/serializer/RawStream' -export { - composeRewrites, - executeRewriteInput, - executeRewriteOutput, -} from './rewrite' +export { composeRewrites, executeRewriteInput } from './rewrite' export type { LocationRewrite, LocationRewriteFunction } from './router' diff --git a/packages/router-core/src/invariant.ts b/packages/router-core/src/invariant.ts new file mode 100644 index 0000000000..926b8793a9 --- /dev/null +++ b/packages/router-core/src/invariant.ts @@ -0,0 +1,3 @@ +export function invariant(): never { + throw new Error('Invariant failed') +} diff --git a/packages/router-core/src/isServer/client.ts b/packages/router-core/src/isServer/client.ts new file mode 100644 index 0000000000..e12407f409 --- /dev/null +++ b/packages/router-core/src/isServer/client.ts @@ -0,0 +1,2 @@ +export const isServer = false +export const loadServerRoute: never = undefined as never diff --git a/packages/router-core/src/isServer/development.ts b/packages/router-core/src/isServer/development.ts new file mode 100644 index 0000000000..e4f13879ad --- /dev/null +++ b/packages/router-core/src/isServer/development.ts @@ -0,0 +1,3 @@ +// Development/test mode - returns undefined so fallback to router.isServer is used +export const isServer: boolean | undefined = undefined +export { loadServerRoute } from '../load-server' diff --git a/packages/router-core/src/isServer/server.ts b/packages/router-core/src/isServer/server.ts new file mode 100644 index 0000000000..d13401a9e9 --- /dev/null +++ b/packages/router-core/src/isServer/server.ts @@ -0,0 +1,2 @@ +export const isServer = process.env.NODE_ENV === 'test' ? undefined : true +export { loadServerRoute } from '../load-server' diff --git a/packages/router-core/src/link.ts b/packages/router-core/src/link.ts index e2ec7f8253..799ae50811 100644 --- a/packages/router-core/src/link.ts +++ b/packages/router-core/src/link.ts @@ -353,6 +353,8 @@ export interface NavigateOptionProps { * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#href) */ href?: string + /** @internal */ + publicHref?: string } export type ToOptions< @@ -669,13 +671,15 @@ export interface LinkOptionsProps { /** * The preloading strategy for this link * - `false` - No preloading - * - `'intent'` - Preload the linked route on hover and cache it for this many milliseconds in hopes that the user will eventually navigate there. + * - `'intent'` - Preload the linked route when the user focuses, hovers over, or touches the link * - `'viewport'` - Preload the linked route when it enters the viewport + * - `'render'` - Preload the linked route as soon as it renders */ preload?: false | 'intent' | 'viewport' | 'render' /** - * When a preload strategy is set, this delays the preload by this many milliseconds. - * If the user exits the link before this delay, the preload will be cancelled. + * Delays focus, hover, and viewport preloading by this many milliseconds. + * Touch intent preloads immediately. If focus or hover ends, or the link + * leaves the viewport before this delay, the preload will be cancelled. */ preloadDelay?: number /** @@ -699,8 +703,4 @@ export type LinkOptions< TMaskTo extends string = '.', > = NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & LinkOptionsProps -export type LinkCurrentTargetElement = { - preloadTimeout?: null | ReturnType<typeof setTimeout> -} - export const preloadWarning = 'Error preloading route! ☝️' diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts new file mode 100644 index 0000000000..e84bb8fba5 --- /dev/null +++ b/packages/router-core/src/load-client.ts @@ -0,0 +1,2570 @@ +// Keep this filename free of a secondary extension so declaration generation +// can rewrite relative imports for both ESM and CJS. +import { isNotFound } from './not-found' +import { isRedirect } from './redirect' +import { + getLocationChangeInfo, + lifecycleEnd, + runRouteLifecycle, +} from './router' +import { dehydrateSsrMatchId } from './ssr/ssr-match-id' +import type { GLOBAL_SEROVAL, GLOBAL_TSR } from './ssr/constants' +import type { TsrSsrGlobal } from './ssr/types' +import type { ParsedLocation } from './location' +import type { NavigateOptions } from './link' +import type { AnyRouteMatch } from './Matches' +import type { NotFoundError } from './not-found' +import type { + AnyRoute, + LoaderFnContext, + RouteContextOptions, + RouteLoaderFn, +} from './route' +import type { AnyRedirect } from './redirect' +import type { AnyRouter, RouterCore, TrailingSlashOption } from './router' +import type { RoutePaths } from './routeInfo' +import type { RouterHistory } from '@tanstack/history' + +type RouteComponentType = + | 'component' + | 'pendingComponent' + | 'errorComponent' + | 'notFoundComponent' + +export function replaceRouteChunk( + route: AnyRoute, + lazyFn: AnyRoute['lazyFn'], +): void { + route.lazyFn = lazyFn ?? route.lazyFn + route._lazy = undefined +} + +function preloadComponent( + route: AnyRoute, + type: RouteComponentType, +): Promise<void> | undefined { + return (route.options[type] as any)?.preload?.() +} + +function loadComponents( + route: AnyRoute, + onPendingReady?: () => void, +): Promise<void> | undefined { + const component = preloadComponent(route, 'component') + let pending = preloadComponent(route, 'pendingComponent') + if (onPendingReady) { + if (pending) { + pending = pending.then(onPendingReady) + } else { + onPendingReady() + } + } + if (component && pending) { + return Promise.all([component, pending]).then(() => {}) + } + return component ?? pending +} + +export function loadRouteChunk( + route: AnyRoute, + // `false` waits only for lazy route options, before a boundary is selected. + componentType?: 'errorComponent' | 'notFoundComponent' | false, + onPendingReady?: () => void, +): Promise<void> | undefined { + const afterLazy = () => + componentType === false + ? undefined + : componentType + ? preloadComponent(route, componentType) + : loadComponents(route, onPendingReady) + const current = route._lazy + if (current) { + return current === true ? afterLazy() : current.then(afterLazy) + } + if (!route.lazyFn) { + return afterLazy() + } + + const promise = route.lazyFn().then( + (lazyRoute) => { + // HMR clears the owner before an obsolete import can settle. + if (process.env.NODE_ENV === 'production' || route._lazy === promise) { + const { id: _id, ...options } = lazyRoute.options + Object.assign(route.options, options) + route._lazy = true + } + }, + (error) => { + if (process.env.NODE_ENV === 'production' || route._lazy === promise) { + route._lazy = undefined + } + throw error + }, + ) + route._lazy = promise + return promise.then(afterLazy) +} + +/** Return the structural lane through the first terminal render boundary. */ +export function _getRenderedMatches( + matches: Array<AnyRouteMatch>, +): Array<AnyRouteMatch> { + const end = + matches.findIndex( + (match) => match.status !== 'success' || match._notFound, + ) + 1 + return end && end < matches.length ? matches.slice(0, end) : matches +} + +/** + * Truthy when the transaction publishing `location` leaves `routeId` out of its + * matches, so subscribers scoped to that route can skip the publication: the + * route unmounts when the transaction commits, and a transaction that ends + * otherwise is superseded or redirected by a newer publication. Only valid + * synchronously inside the publication: the transaction's matches are emptied + * at commit and before following a redirect. Publications without a matching + * transaction (hydration) and scopes without a route never depart. + */ +export function _isRouteDeparting( + router: AnyRouter, + routeId: string | undefined, + location: ParsedLocation, +): unknown { + const tx = router._tx + return ( + routeId && + tx?.[2 /* location */] === location && + !tx[3 /* matches */].some((match) => match.routeId === routeId) + ) +} + +/** Return the lane whose document assets belong to the current presentation. */ +export function _getAssetMatches( + matches: Array<AnyRouteMatch>, +): Array<AnyRouteMatch> { + let end = matches.length + for (let index = 0; index < end; index++) { + const match = matches[index]! + // `_assetEnd` is only ever set on hydration presentation clones that are + // `status: 'pending'`, `ssr: 'data-only'`, error-free, and not not-found + // (see hydrate.ts), and commits clear it — so its presence alone is the guard. + if (match._assetEnd !== undefined) { + end = Math.min(end, Math.max(index + 1, match._assetEnd)) + continue + } + if (match.status !== 'success' || match._notFound) { + end = index + 1 + break + } + } + // `end` only ever shrinks to `index + 1 >= 1`, so no zero guard is needed. + return end < matches.length ? matches.slice(0, end) : matches +} + +declare const lanePhase: unique symbol + +type LanePhase = 'matched' | 'contextualized' | 'reduced' | 'projected' + +/** + * Lane matches carry their lane's phase so functions can demand evidence of + * pipeline position (e.g. `commitMatches` only accepts a projected lane's + * matches). The brand is phantom — it never exists at runtime. + */ +type LaneMatches<TPhase extends LanePhase> = Array<WorkMatch> & { + readonly [lanePhase]?: TPhase +} + +type Lane<TPhase extends LanePhase> = [ + location: ParsedLocation, + matches: LaneMatches<TPhase>, + background?: Array<BackgroundLoaderTask>, + backgroundSettlement?: Promise<IndexedOutcome | undefined>, +] & { readonly [lanePhase]?: TPhase } + +type MatchedLane = Lane<'matched'> +type ContextualizedLane = Lane<'contextualized'> +type ReducedLane = Lane<'reduced'> +type ProjectedLane = Lane<'projected'> + +const SUCCESS = 0 +const ERROR = 1 +const NOT_FOUND = 2 +// Control outcomes stay contiguous so the hot path can test them together. +const REDIRECTED = 3 +const CANCELED = 4 +const CANCELED_OUTCOME: [kind: typeof CANCELED] = [CANCELED] + +type RedirectOutcome = [ + kind: typeof REDIRECTED, + redirect: AnyRedirect, + location?: ParsedLocation, +] + +type NonRedirectOutcome = + | [kind: typeof SUCCESS, data: unknown] + | [kind: typeof ERROR, error: unknown] + | [kind: typeof NOT_FOUND, error: NotFoundError] + | [kind: typeof CANCELED] + +type RawLoaderOutcome = + | NonRedirectOutcome + | [kind: typeof REDIRECTED, redirect: AnyRedirect] + +type LoaderOutcome = NonRedirectOutcome | RedirectOutcome + +type IndexedOutcome = [index: number, outcome: LoaderOutcome, boundary?: number] + +export type LoaderFlight = [ + outcome: Promise<RawLoaderOutcome>, + controller: AbortController, + leases: number, +] + +type WorkMatch = AnyRouteMatch & { + _flight?: LoaderFlight +} + +declare const matchPhase: unique symbol + +/** + * A match whose loader outcome has been applied by `settleInto`, which is the + * sole granter of this brand (phantom, zero-runtime). Consumers that require + * it — e.g. `cacheLoaderMatch` — can only be reached after settlement, so the + * compiler enforces the loader→settle→cache ordering. Sources that arrive + * already settled (dehydrated server data) must cast at a named boundary. + */ +type SettledMatch = WorkMatch & { readonly [matchPhase]: 'settled' } + +export type LoadTransaction = [ + controller: AbortController, + redirects: number, + location: ParsedLocation, + matches: Array<AnyRouteMatch>, + startedAt: number, + done: Promise<void>, + /** + * Dev-only HMR refresh mode. Presence forces successor rematerialization + * until this publication is acknowledged. The optional hydration handoff is + * retired when the refresh publishes. + */ + refresh?: [handoff: NonNullable<AnyRouter['_handoff']> | undefined], +] + +export type PendingSession = [ + generation: LoadTransaction, + boundaryId: string, + /** Pending reveal time until acknowledged, then minimum-visible-until time. */ + deadline: number, + revealTimer?: ReturnType<typeof setTimeout>, + ack?: Promise<boolean> | true, + component?: unknown, +] + +type CoordinatorRouter = AnyRouter & { + /** Active speculative lanes retained for cancellation, invalidation, and cache clearing. */ + _preloads?: Map<AbortController, Array<AnyRouteMatch>> + _refreshNextLoad?: boolean +} + +type LoaderTask = [ + index: number, + outcome: Promise<LoaderOutcome>, + chunkFailure: Promise<IndexedOutcome | undefined | void>, + candidate?: WorkMatch, +] + +type BackgroundLoaderTask = [ + index: number, + outcome: Promise<LoaderOutcome>, + chunkFailure: Promise<IndexedOutcome | undefined | void>, + candidate: WorkMatch, +] + +type ExecuteLaneOptions = [ + controller: AbortController, + redirects: number, + base: Array<AnyRouteMatch>, + preload?: boolean, + sync?: boolean, + forceStaleReload?: boolean, + resolvedPrefix?: number, + onReady?: () => void, +] + +type ControlOutcome = RedirectOutcome | [kind: typeof CANCELED] + +type LaneResult = ProjectedLane | ControlOutcome + +function isControl( + result: Lane<any> | ControlOutcome, +): result is ControlOutcome { + return typeof result[0 /* location or kind */] === 'number' +} + +export function waitFor<T>( + value: T | PromiseLike<T>, + signal: AbortSignal, +): Promise<T> { + if (signal.aborted) { + return Promise.race([Promise.reject(signal), value]) + } + return new Promise<T>((resolve, reject) => { + const abort = () => reject(signal) + signal.addEventListener('abort', abort, { once: true }) + Promise.resolve(value) + .then(resolve, reject) + // Both settlement callbacks return normally, so this chain fulfills. + .then(() => signal.removeEventListener('abort', abort)) + }) +} + +export function getRoute(router: AnyRouter, match: WorkMatch): AnyRoute { + return (router.routesById as Record<string, AnyRoute>)[match.routeId]! +} + +function normalize( + value: unknown, + rejected: boolean, + routeId?: string, +): RawLoaderOutcome { + if (isRedirect(value)) { + return [REDIRECTED, value] + } + if (isNotFound(value)) { + value.routeId ||= routeId + return [NOT_FOUND, value] + } + if (!rejected) { + return [SUCCESS, value] + } + if (typeof (value as any)?.then === 'function') { + value = new Error('A Promise was thrown', { cause: value }) + } + return [ERROR, value] +} + +function normalizeError(route: AnyRoute, cause: unknown): RawLoaderOutcome { + let outcome = normalize(cause, true, route.id) + if (outcome[0 /* kind */] !== ERROR) { + return outcome + } + try { + route.options.onError?.(outcome[1 /* error */]) + } catch (onErrorCause) { + outcome = normalize(onErrorCause, true, route.id) + } + return outcome +} + +function normalizeLaneError( + router: AnyRouter, + lane: Lane<any>, + route: AnyRoute, + cause: unknown, + options: ExecuteLaneOptions, +): LoaderOutcome { + if (options[0 /* controller */].signal.aborted) { + return CANCELED_OUTCOME + } + return materializeRedirect( + router, + lane, + route, + normalizeError(route, cause), + options, + ) +} + +async function contextualize( + router: AnyRouter, + lane: MatchedLane, + options: ExecuteLaneOptions, + end: number, + planSuccessfulLane: () => void, + retainedEnd: number, +): Promise<IndexedOutcome | undefined> { + const [location, matches] = lane + const signal = options[0 /* controller */].signal + const preload = !!options[3 /* preload */] + for (let index = options[6 /* resolvedPrefix */] ?? 0; index < end; index++) { + const match = matches[index]! + const route = getRoute(router, match) + + match.abortController = options[0 /* controller */] + // Contextualization is serial, so the previous match already contains the + // complete parent context for this route. + const parentContext = + matches[index - 1]?.context ?? router.options.context ?? {} + const common = { + params: match.params, + location, + navigate: (opts: any) => + router.navigate({ + ...opts, + _fromLocation: location, + }), + buildLocation: router.buildLocation, + cause: preload ? ('preload' as const) : match.cause, + abortController: options[0 /* controller */], + preload, + matches, + routeId: route.id, + } + try { + // Reuse the route's cached contribution while rebuilding its inheritance. + const routeContext = (match._ctx ||= route.options.context + ? route.options.context({ + ...common, + deps: match.loaderDeps, + context: parentContext, + } satisfies RouteContextOptions<any, any, any, any, any>) || {} + : undefined) + match.context = { + ...parentContext, + ...routeContext, + } + } catch (cause) { + releaseFlight(router, match) + return [index, normalizeLaneError(router, lane, route, cause, options)] + } + if (signal.aborted) { + return [index, CANCELED_OUTCOME] + } + const validationError = match.paramsError ?? match.searchError + if (validationError !== undefined) { + releaseFlight(router, match) + return [ + index, + normalizeLaneError(router, lane, route, validationError, options), + ] + } + const beforeLoad = route.options.beforeLoad + if (!beforeLoad) { + continue + } + + const previousStatus = match.status + if (index >= retainedEnd) { + match.status = 'pending' + options[7 /* onReady */]?.() + } + try { + setFetching(router, match, 'beforeLoad', options[0 /* controller */]) + const value = beforeLoad({ + ...common, + search: match.search, + context: match.context, + ...router.options.additionalContext, + }) + // Always await to give a queued replacement navigation one microtask to + // kick in before checking cancellation, even for synchronous context. + const result = await (typeof value?.then === 'function' + ? waitFor(value, signal) + : value) + if (signal.aborted) { + return [index, CANCELED_OUTCOME] + } + const outcome = materializeRedirect( + router, + lane, + route, + normalize(result, false, route.id), + options, + ) + if (outcome[0 /* kind */] !== SUCCESS) { + releaseFlight(router, match) + return [index, outcome] + } + match.context = { + ...match.context, + ...result, + } + } catch (cause) { + releaseFlight(router, match) + return [index, normalizeLaneError(router, lane, route, cause, options)] + } finally { + match.status = previousStatus + setFetching(router, match, false, options[0 /* controller */]) + } + } + + // Let a synchronous lane claim predecessor flights before this frame yields. + planSuccessfulLane() + return +} + +function releaseOwnedFlight( + router: AnyRouter, + match: WorkMatch, + flight?: LoaderFlight, +): AbortController | undefined { + if (!flight || --flight[2 /* leases */]) { + return + } + if (router._flights?.get(match.id) === flight) { + const current = router._tx + if ( + current && + !current[0 /* controller */].signal.aborted && + !current[3 /* matches */].includes(match) && + current[3 /* matches */].some((candidate) => candidate.id === match.id) && + current[3 /* matches */].some( + (candidate) => candidate.isFetching === 'beforeLoad', + ) + ) { + // Keep work discoverable only while the current lane is still running + // beforeLoad. Loader planning performs the matching zero-owner sweep. + return + } + router._flights.delete(match.id) + } + return flight[1 /* controller */] +} + +function releaseFlight(router: AnyRouter, match: WorkMatch): void { + const flight = match._flight + match._flight = undefined + releaseOwnedFlight(router, match, flight)?.abort() +} +/** + * Not passing in a `next` ownership recipient + * is equivalent to discarding the match resources + */ +function transferMatchResources( + router: AnyRouter, + previous: Array<AnyRouteMatch>, + next?: Array<AnyRouteMatch>, + deferSameIdFlight?: true, +): void { + const abort: Array<AbortController> = [] + for (const match of previous as Array<WorkMatch>) { + if (!next?.includes(match)) { + const flight = match._flight + match._flight = undefined + if ( + deferSameIdFlight && + flight?.[2 /* leases */] === 1 && + router._flights?.get(match.id) === flight && + next?.some((candidate) => candidate.id === match.id) + ) { + // The successor has not made its same-ID reload decision yet. + flight[2 /* leases */] = 0 + } else { + const controller = releaseOwnedFlight(router, match, flight) + if (controller) { + abort.push(controller) + } + } + } + } + for (const controller of abort) { + controller.abort() + } +} + +function acquireMatchResources(matches: Array<AnyRouteMatch>): void { + for (const match of matches as Array<WorkMatch>) { + const flight = match._flight + if (flight) { + flight[2 /* leases */]++ + } + } +} + +function setFetching( + router: AnyRouter, + match: WorkMatch, + value: AnyRouteMatch['isFetching'], + owner?: AbortController, +): void { + match.isFetching = value + if (owner && router._tx?.[0 /* controller */] !== owner) { + return + } + const store = router.stores.byRoute.get(match.routeId) + const presented = store?.get() + if (presented?.id === match.id) { + store!.set({ ...presented, isFetching: value }) + } +} + +function getLoaderContext( + router: AnyRouter, + lane: ContextualizedLane, + match: WorkMatch, + route: AnyRoute, + controller: AbortController, + parentMatchPromise: Promise<WorkMatch> | undefined, + preload: boolean, +): LoaderFnContext { + const location = lane[0 /* location */] + return { + params: match.params, + location, + navigate: (opts: any) => + router.navigate({ + ...opts, + _fromLocation: location, + }), + cause: preload ? ('preload' as const) : match.cause, + abortController: controller, + preload, + deps: match.loaderDeps, + parentMatchPromise: parentMatchPromise as any, + context: match.context, + route, + ...router.options.additionalContext, + } +} + +async function loadResource( + router: AnyRouter, + lane: ContextualizedLane, + match: WorkMatch, + route: AnyRoute, + loader: RouteLoaderFn<any> | undefined, + parentMatchPromise: Promise<WorkMatch> | undefined, + options: ExecuteLaneOptions, +): Promise<LoaderOutcome> { + const owner = options[0 /* controller */] + const signal = owner.signal + if (signal.aborted) { + return CANCELED_OUTCOME + } + if (!loader) { + return [SUCCESS, undefined] + } + + let flight = match._flight + setFetching(router, match, 'loader', owner) + try { + if (!flight) { + const controller = new AbortController() + flight = [ + Promise.resolve() + .then(() => + loader( + getLoaderContext( + router, + lane, + match, + route, + controller, + parentMatchPromise, + !!options[3 /* preload */], + ), + ), + ) + .then( + (value) => normalize(value, false, route.id), + (cause) => normalize(cause, true, route.id), + ) + .then((result): RawLoaderOutcome => { + // The registry controls discovery; leases keep current consumers + // sharing the same terminal outcome. + if ( + result[0 /* kind */] !== SUCCESS && + router._flights?.get(match.id) === flight + ) { + router._flights!.delete(match.id) + if (!flight![2 /* leases */]) { + controller.abort() + } + } + return result[0 /* kind */] === ERROR && flight![2 /* leases */] + ? normalizeError(route, result[1 /* error */]) + : result + }), + controller, + 1, + ] + ;(router._flights ??= new Map()).set(match.id, flight) + } + match._flight = flight + match.abortController = flight[1 /* controller */] + return materializeRedirect( + router, + lane, + route, + await waitFor(flight[0 /* outcome */], signal), + options, + ) + } catch (cause) { + if (cause !== signal || !signal.aborted) { + throw cause + } + releaseFlight(router, match) + return CANCELED_OUTCOME + } finally { + setFetching(router, match, false, owner) + } +} + +function settleInto( + match: WorkMatch, + result: LoaderOutcome, + preload: boolean, +): asserts match is SettledMatch { + if (result[0 /* kind */] === REDIRECTED) { + return + } + // Reduction installs only the selected terminal failure. Every other + // settled attempt remains a renderable, stale match in that lane. + match.status = 'success' + match.error = undefined + if (result[0 /* kind */] === SUCCESS) { + match.loaderData = result[1 /* data */] + match.invalid = false + match.updatedAt = Date.now() + match.preload = preload + } else { + match.invalid = true + } +} + +export function cacheLoaderMatch( + router: CoordinatorRouter, + match: SettledMatch, + planned: AnyRouteMatch | undefined, +): void { + const current = router._cache.get(match.id) as WorkMatch | undefined + if ( + current !== planned || + router._committed.some( + (candidate) => + candidate.id === match.id && + (candidate as WorkMatch)._flight === match._flight, + ) + ) { + return + } + const cached = { + ...match, + _notFound: undefined, + context: {}, + } as WorkMatch + if (cached._flight) { + cached._flight[2 /* leases */]++ + } + router._cache.set(match.id, cached) + if (current) { + releaseFlight(router, current) + } +} + +function getParentSnapshot( + match: WorkMatch, + outcome: LoaderOutcome, +): WorkMatch { + if (outcome[0 /* kind */] === ERROR || outcome[0 /* kind */] === NOT_FOUND) { + return { + ...match, + status: outcome[0 /* kind */] === ERROR ? 'error' : 'notFound', + error: outcome[1 /* error */], + _flight: undefined, + } + } + return match +} + +function createLoaderTask( + router: AnyRouter, + lane: ContextualizedLane, + index: number, + tasks: Array<LoaderTask>, + semanticParent: Promise<WorkMatch> | undefined, + options: ExecuteLaneOptions, + retainedEnd: number, +): Promise<WorkMatch> { + const match = lane[1 /* matches */][index]! + const route = getRoute(router, match) + const preload = !!options[3 /* preload */] + const plannedCacheMatch = router._cache.get(match.id) + let configured + let reload = false + let reloadFailure: LoaderOutcome | undefined + try { + if (match.status === 'success') { + configured = route.options.shouldReload + if (typeof configured === 'function') { + configured = configured( + getLoaderContext( + router, + lane, + match, + route, + options[0 /* controller */], + semanticParent, + preload, + ), + ) + } + if (options[0 /* controller */].signal.aborted) { + reloadFailure = CANCELED_OUTCOME + } + } + if (!reloadFailure) { + if (match.status !== 'success') { + reload = true + } else { + const staleAge = + preload || match.preload + ? (route.options.preloadStaleTime ?? + router.options.defaultPreloadStaleTime ?? + 30_000) + : (route.options.staleTime ?? router.options.defaultStaleTime ?? 0) + reload = !!( + match.invalid || + configured || + (configured === undefined && + Date.now() - match.updatedAt >= staleAge && + (options[5 /* forceStaleReload */] || + match.cause === 'enter' || + options[2 /* base */].some( + (candidate) => + candidate.routeId === match.routeId && + candidate.id !== match.id, + ))) + ) + } + } + } catch (cause) { + match.invalid = true + releaseFlight(router, match) + reloadFailure = normalizeLaneError(router, lane, route, cause, options) + } + const routeLoader = route.options.loader + const isLoaderFn = typeof routeLoader === 'function' + const loader = isLoaderFn ? routeLoader : routeLoader?.handler + const preloadable = !preload || route.options.preload !== false + let donor = + preloadable && + routeLoader && + !(process.env.NODE_ENV !== 'production' && router._tx?.[6 /* refresh */]) + ? router._flights?.get(match.id) + : undefined + if (donor === match._flight || reloadFailure) { + donor = undefined + } else if (donor && !reload && !preload && configured === undefined) { + // Normal cache policy accepts an already-running generation even when this + // lane itself would not have started another loader. + reload = true + } else if (!reload) { + donor = undefined + } + const background = !!( + routeLoader && + reload && + match.status === 'success' && + !preload && + !options[4 /* sync */] && + ((isLoaderFn ? undefined : routeLoader.staleReloadMode) ?? + router.options.defaultStaleReloadMode) !== 'blocking' + ) + const loaded = reload && preloadable + const blocking = + loaded && !background && (match.status !== 'success' || !!routeLoader) + const onReady = index >= retainedEnd ? options[7 /* onReady */] : undefined + const onLazyReady = route.lazyFn && route._lazy !== true ? onReady : undefined + if (loaded && !routeLoader) { + match.invalid = false + match.updatedAt = Date.now() + } + if (donor) { + donor[2 /* leases */]++ + } + if (blocking) { + const acceptedFlight = match._flight + match._flight = donor + releaseOwnedFlight(router, match, acceptedFlight)?.abort() + // A mounted success remains renderable while its loader revalidates. Every + // non-retained blocking generation presents pending state. + if (index >= retainedEnd) { + match.status = 'pending' + } + onReady?.() + } + if (!loaded) { + match.isFetching = false + } + const outcome = + !reloadFailure && blocking + ? loadResource( + router, + lane, + match, + route, + loader, + semanticParent, + options, + ).then((result) => { + settleInto(match, result, preload) + if (result[0 /* kind */] === SUCCESS) { + // A settled generation can outlive its lane without keeping unresolved + // navigation work alive. + if (routeLoader && !options[0 /* controller */].signal.aborted) { + cacheLoaderMatch(router, match, plannedCacheMatch) + } + // A route is renderable only after both its data and normal component + // chunk are ready. Its loader data is already available to descendants. + if (index >= retainedEnd) { + match.status = 'pending' + } + } + return result + }) + : Promise.resolve<LoaderOutcome>( + reloadFailure ?? [SUCCESS, match.loaderData], + ) + + // Keep thrown preloads and rejected chunks in the same task promise. + const chunkFailure = (async (): Promise<IndexedOutcome | void> => { + try { + const chunk = loadRouteChunk(route, undefined, onLazyReady) + if (chunk) { + await waitFor(chunk, options[0 /* controller */].signal) + } + } catch (cause) { + if ( + !lane[1 /* matches */].some( + (candidate, candidateIndex) => + candidateIndex <= index && + (candidate.status === 'error' || + candidate.status === 'notFound' || + candidate._notFound), + ) + ) { + return [ + index, + normalizeLaneError(router, lane, route, cause, options), + ] satisfies IndexedOutcome + } + } + // Readiness requires both the component chunk and loader data. + const result = await outcome + if ( + blocking && + result[0 /* kind */] === SUCCESS && + match.status === 'pending' && + !options[0 /* controller */].signal.aborted + ) { + match.status = 'success' + onReady?.() + } + })() + tasks.push([index, outcome, chunkFailure]) + if (!background) { + return outcome.then((result) => getParentSnapshot(match, result)) + } + const candidate: WorkMatch = { + ...match, + status: 'pending', + preload: false, + _flight: donor, + } + match.invalid = false + match.isFetching = 'loader' + const backgroundOutcome = loadResource( + router, + lane, + candidate, + route, + loader, + semanticParent, + options, + ).then((result) => { + match.isFetching = false + settleInto(candidate, result, false) + return result + }) + ;(lane[2 /* background */] ??= []).push([ + index, + backgroundOutcome, + chunkFailure, + candidate, + ]) + return backgroundOutcome.then((result) => + getParentSnapshot(candidate, result), + ) +} + +async function getNotFoundBoundary( + router: AnyRouter, + matches: Array<WorkMatch>, + indexed: IndexedOutcome | undefined, + signal: AbortSignal, + fallback = 0, +): Promise<number> { + const cause = indexed?.[1 /* outcome */][1 /* error or redirect */] as + | NotFoundError + | undefined + let index = cause?.routeId + ? matches.findIndex((match) => match.routeId === cause.routeId) + : (indexed?.[0 /* index */] ?? matches.length - 1) + if (index < 0) { + index = 0 + } + for (let i = index; i >= 0; i--) { + const route = getRoute(router, matches[i]!) + try { + const loading = loadRouteChunk(route, false) + if (loading) { + await waitFor(loading, signal) + } + } catch (cause) { + if (cause === signal && signal.aborted) { + throw cause + } + } + if (route.options.notFoundComponent) { + return i + } + } + return cause?.routeId ? index : fallback +} + +function discardBackground(router: AnyRouter, lane: Lane<any>): void { + if (lane[2 /* background */]) { + transferMatchResources( + router, + lane[2 /* background */].map((task) => task[3 /* candidate */]), + ) + lane[2 /* background */] = undefined + } +} + +async function settleTasks( + tasks: Array<LoaderTask>, + serialFailure?: IndexedOutcome, + redirectTasks?: Array<BackgroundLoaderTask>, + gate?: number | Promise<number>, +): Promise<IndexedOutcome | undefined> { + let loaderFailure: IndexedOutcome | undefined + + try { + await Promise.all( + tasks.map((task) => + task[1 /* outcome */].then(async (outcome) => { + const taskIndex = task[0 /* index */] + if (gate && taskIndex >= (await gate)) { + return + } + if (outcome[0 /* kind */] >= REDIRECTED) { + throw [taskIndex, outcome] as IndexedOutcome + } + if (!loaderFailure && outcome[0 /* kind */] !== SUCCESS) { + loaderFailure = [taskIndex, outcome] + // Every started descendant must settle before an ordinary failure + // wins because a redirect from any of them remains control flow. + await Promise.all( + (redirectTasks ?? []).map((nextTask) => { + if (nextTask[0 /* index */] <= taskIndex) { + return + } + return nextTask[1 /* outcome */].then((nextOutcome) => { + if (nextOutcome[0 /* kind */] === REDIRECTED) { + throw [ + nextTask[0 /* index */], + nextOutcome, + ] as IndexedOutcome + } + }) + }), + ) + } + }), + ), + ) + } catch (cause) { + return cause as IndexedOutcome + } + return serialFailure ?? loaderFailure +} + +function materializeRedirect( + router: AnyRouter, + lane: Lane<any>, + route: AnyRoute, + outcome: RawLoaderOutcome, + options: ExecuteLaneOptions, + failed?: true, +): LoaderOutcome { + while (outcome[0 /* kind */] === REDIRECTED) { + const redirect = outcome[1 /* redirect */] + const redirectOptions = redirect.options + try { + if (redirectOptions.href || redirect.headers.has('Location')) { + router.resolveRedirect(redirect) + if (redirectOptions.reloadDocument) { + return outcome + } + } + if ( + redirectOptions.reloadDocument + ? options[3 /* preload */] + : options[1 /* redirects */] >= 20 + ) { + return outcome + } + const location = router.buildLocation({ + ...redirectOptions, + _fromLocation: lane[0 /* location */], + _includeValidateSearch: true, + }) + const publicLocation = location.maskedLocation ?? location + if (publicLocation.external) { + // Loader outcomes can be shared by lanes with different search/params. + // Keep the resolved destination local to this lane. + const resolved = redirect.clone() as AnyRedirect + resolved.options = { ...redirectOptions } + resolved.headers.set('Location', publicLocation.publicHref) + router.resolveRedirect(resolved) + // A two-item outcome marks a terminal redirect for preloads. + return options[3 /* preload */] + ? [REDIRECTED, resolved] + : [REDIRECTED, resolved, publicLocation] + } + return [REDIRECTED, redirect, location] + } catch (cause) { + outcome = failed ? [ERROR, cause] : normalizeError(route, cause) + failed = true + } + } + return outcome +} + +async function reduceLane( + router: AnyRouter, + lane: ContextualizedLane, + tasks: Array<LoaderTask>, + controller: AbortController, + settlement: Promise<IndexedOutcome | undefined>, + onReady?: () => void, +): Promise<ReducedLane | ControlOutcome> { + const matches = lane[1 /* matches */] + let failure = await settlement + let redirectLimitExceeded = false + const plannedBoundary = matches.findIndex((match) => match._notFound) + const boundaryOf = (found: IndexedOutcome) => + found[1 /* outcome */][0 /* kind */] === NOT_FOUND + ? getNotFoundBoundary(router, matches, found, controller.signal) + : found[0 /* index */] + let readinessEnd = plannedBoundary < 0 ? matches.length : plannedBoundary + + if ((failure?.[1 /* outcome */][0 /* kind */] ?? 0) >= REDIRECTED) { + readinessEnd = 0 + } else if (failure) { + readinessEnd = failure[2 /* boundary */] ??= await boundaryOf(failure) + for (const task of tasks) { + if (task[0 /* index */] >= readinessEnd) { + break + } + const outcome = await task[1 /* outcome */] + // Presence means a loader previously succeeded, even with `undefined`. + if ( + outcome[0 /* kind */] !== SUCCESS && + outcome[0 /* kind */] < REDIRECTED && + !('loaderData' in matches[task[0 /* index */]]!) + ) { + failure = [task[0 /* index */], outcome] + readinessEnd = failure[2 /* boundary */] = await boundaryOf(failure) + break + } + } + } + + for (const task of tasks) { + if (task[0 /* index */] >= readinessEnd) { + break + } + const chunkFailure = await task[2 /* chunkFailure */] + if (!chunkFailure) { + continue + } + failure = chunkFailure + break + } + + if ((failure?.[1 /* outcome */][0 /* kind */] ?? 0) >= REDIRECTED) { + const outcome = failure![1 /* outcome */] + if ( + outcome[0 /* kind */] !== REDIRECTED || + outcome[1 /* redirect */].options.reloadDocument || + outcome[2 /* location */] + ) { + discardBackground(router, lane) + return outcome as ControlOutcome + } + redirectLimitExceeded = true + failure = [0, [ERROR, new Error('Too many redirects')]] + } + + const boundary = failure + ? (failure[2 /* boundary */] ?? (await boundaryOf(failure))) + : plannedBoundary + if (boundary >= 0) { + const outcome = failure?.[1 /* outcome */] + const kind = outcome?.[0 /* kind */] + const match = matches[boundary]! + const cause = outcome?.[1 /* error or redirect */] + const install = () => { + if (outcome) { + match._notFound = undefined + if (kind === ERROR) { + match.status = 'error' + } else { + ;(cause as NotFoundError).routeId = match.routeId + if (match.routeId === router.routeTree.id) { + match.status = 'success' + match._notFound = true + } else { + match.status = 'notFound' + } + } + match.error = cause + match.isFetching = false + } + } + install() + if (!outcome) { + onReady?.() + } + const route = getRoute(router, match) + try { + await waitFor<unknown>( + outcome + ? Promise.resolve().then(() => + loadRouteChunk( + route, + kind === ERROR ? 'errorComponent' : 'notFoundComponent', + ), + ) + : Promise.all([ + loadRouteChunk(route), + loadRouteChunk(route, 'notFoundComponent'), + ]), + controller.signal, + ) + } catch (cause) { + if (cause === controller.signal && controller.signal.aborted) { + discardBackground(router, lane) + return CANCELED_OUTCOME + } + } + if (!outcome) { + match.status = 'success' + } else if (redirectLimitExceeded) { + controller.abort() + await Promise.all([ + ...tasks.map((task) => task[1 /* outcome */]), + ...tasks.map((task) => task[2 /* chunkFailure */]), + ...(lane[2 /* background */] ?? []).map( + (task) => task[1 /* outcome */], + ), + ]) + discardBackground(router, lane) + transferMatchResources(router, matches) + install() + } + } + + return lane as ReducedLane +} + +export async function projectLane( + router: AnyRouter, + lane: ReducedLane, + signal: AbortSignal, + start = 0, + end = lane[1 /* matches */].length, +): Promise<ProjectedLane> { + const matches = lane[1 /* matches */] + for (let index = start; index < end; index++) { + const match = matches[index]! + const routeOptions = getRoute(router, match).options + if (routeOptions.head || routeOptions.scripts) { + try { + const context = { + ssr: router.options.ssr, + matches, + match, + params: match.params, + loaderData: match.loaderData, + } + const [head, scripts] = await waitFor( + Promise.all([ + routeOptions.head?.(context), + routeOptions.scripts?.(context), + ]), + signal, + ) + match.meta = head?.meta + match.links = head?.links + match.headScripts = head?.scripts + match.styles = head?.styles + match.scripts = scripts + } catch (cause) { + if (cause === signal && signal.aborted) { + break + } + console.error(cause) + } + } + if (match.status !== 'success' || match._notFound) { + break + } + } + return lane as ProjectedLane +} + +async function executeClientLane( + router: AnyRouter, + location: ParsedLocation, + matches: Array<AnyRouteMatch>, + options: ExecuteLaneOptions, +): Promise<LaneResult> { + const matched = [location, matches as Array<WorkMatch>] as MatchedLane + const signal = options[0 /* controller */].signal + let reduced: ReducedLane | ControlOutcome + try { + const presented = router.stores.matches.get() + let plannedBoundary = matches.findIndex((match) => match._notFound) + if (router.options.notFoundMode !== 'root' && plannedBoundary >= 0) { + const boundary = await getNotFoundBoundary( + router, + matches as Array<WorkMatch>, + undefined, + signal, + plannedBoundary, + ) + matches[plannedBoundary]!._notFound = undefined + matches[boundary]!._notFound = true + plannedBoundary = boundary + } + let end = plannedBoundary < 0 ? matches.length : plannedBoundary + 1 + let retainedEnd = 0 + while (retainedEnd < end && retainedEnd !== plannedBoundary) { + const match = matches[retainedEnd]! + const committed = options[2 /* base */][retainedEnd] + const visible = presented[retainedEnd] + if ( + committed?.id !== match.id || + committed.status !== 'success' || + match.preload || + visible?.id !== match.id || + visible.status !== 'success' + ) { + break + } + retainedEnd++ + if (committed._notFound || visible._notFound) { + break + } + } + const tasks: Array<LoaderTask> = [] + const start = options[6 /* resolvedPrefix */] ?? 0 + let semanticParent = start + ? Promise.resolve(matches[start - 1] as WorkMatch) + : undefined + const planSuccessfulLane = () => { + for (let index = start; index < end; index++) { + if (signal.aborted) { + break + } + semanticParent = createLoaderTask( + router, + matched as ContextualizedLane, + index, + tasks, + semanticParent, + options, + retainedEnd, + ) + } + } + // From here on `matched` is contextualized: `contextualize` communicates + // through mutation plus a failure return, so the phase brand is asserted at + // the two use sites below rather than granted by a (byte-costing) return. + const failure = await contextualize( + router, + matched, + options, + end, + planSuccessfulLane, + retainedEnd, + ) + if (failure) { + options[4 /* sync */] = true + end = failure[0 /* index */] + if (failure[1 /* outcome */][0 /* kind */] === NOT_FOUND) { + const boundary = await getNotFoundBoundary( + router, + matches as Array<WorkMatch>, + failure, + signal, + ) + failure[2 /* boundary */] = boundary + end = Math.min(end, boundary + 1) + } else if (failure[1 /* outcome */][0 /* kind */] >= REDIRECTED) { + end = 0 + } + planSuccessfulLane() + } + if (!signal.aborted && !options[3 /* preload */]) { + const abort: Array<AbortController> = [] + for (const [id, flight] of router._flights ?? []) { + if (!flight[2 /* leases */]) { + router._flights!.delete(id) + abort.push(flight[1 /* controller */]) + } + } + for (const controller of abort) { + controller.abort() + } + } + const reduction = reduceLane( + router, + matched as ContextualizedLane, + tasks, + options[0 /* controller */], + settleTasks(tasks, failure, matched[2 /* background */]), + options[7 /* onReady */], + ) + if (matched[2 /* background */]?.length) { + matched[3 /* backgroundSettlement */] = settleTasks( + matched[2 /* background */], + undefined, + undefined, + reduction.then( + (foreground) => + isControl(foreground) ? 0 : _getRenderedMatches(matches).length, + () => 0, + ), + ) + } + reduced = await reduction + } catch (cause) { + discardBackground(router, matched) + if (cause === signal && signal.aborted) { + return CANCELED_OUTCOME + } + throw cause + } + if (isControl(reduced)) { + return reduced + } + return projectLane( + router, + reduced, + signal, + options[6 /* resolvedPrefix */] === matches.length + ? options[6 /* resolvedPrefix */] + : 0, + ) +} + +/** + * Waits for `pendingMs`, then presents the complete lane. Rendering applies the + * selected boundary cutoff while retaining every match's structural state. + * A replacement load for the same match keeps the timer; choosing a different + * match resets it. `pendingMinMs` starts after the fallback renders. + */ +function offerPending(router: CoordinatorRouter, tx: LoadTransaction): void { + if (router._tx !== tx) { + return + } + const matches = tx[3 /* matches */] + const presented = router.stores.matches.get() + let session = router._pending + for (let index = 0; index < matches.length; index++) { + const match = matches[index]! + const success = match.status === 'success' && !match._notFound + const presentedPending = + presented[index]?.id === match.id && + presented[index]?.status === 'pending' + if (success && !presentedPending) { + continue + } + const route = getRoute(router, match as WorkMatch) + const delay = + success || match.invalid + ? 0 + : (route.options.pendingMs ?? router.options.defaultPendingMs) + const component = + route.options.pendingComponent ?? + (router.options as any).defaultPendingComponent + if (!component || typeof delay !== 'number' || delay === Infinity) { + if (session) { + session[0 /* generation */] = tx + session[2 /* deadline */] = 0 + session[4 /* ack */] = true + } + return + } + const min = + route.options.pendingMinMs ?? router.options.defaultPendingMinMs ?? 0 + let tookOver = false + if (session?.[1 /* boundaryId */] === match.id) { + tookOver = session[0 /* generation */] !== tx + session[0 /* generation */] = tx + } else { + clearTimeout(session?.[3 /* revealTimer */]) + router._pending = session = undefined + } + if (!session) { + // Hydration and redirects can preserve pending presentation without a session. + // Do not delay it again; conservatively start pendingMinMs from now. + router._pending = session = [ + tx, + match.id, + presentedPending ? Date.now() + min : tx[4 /* startedAt */] + delay, + undefined, + presentedPending || undefined, + component, + ] + } + if ( + session[4 /* ack */] && + !tookOver && + session[5 /* component */] === component + ) { + return + } + session[5 /* component */] = component + if (!session[4 /* ack */]) { + clearTimeout(session[3 /* revealTimer */]) + const remaining = session[2 /* deadline */] - Date.now() + if (remaining > 0) { + session[3 /* revealTimer */] = setTimeout( + () => offerPending(router, tx), + remaining, + ) + return + } + session[2 /* deadline */] = 0 + } + const offered = matches.map((match) => ({ + ...match, + _flight: undefined, + })) + offered[index]!.status = 'pending' + const ack = (session[4 /* ack */] = router + .startTransition(() => router.stores.setMatches(offered), offered) + .then((rendered) => { + if ( + rendered && + router._pending === session && + session![4 /* ack */] === ack && + !session![2 /* deadline */] + ) { + session![2 /* deadline */] = Date.now() + min + } + return rendered + })) + return + } +} + +/** + * Cancels pending UI timing unless the current successor can take over the + * same boundary that remains painted. + */ +function finishPending(router: CoordinatorRouter, tx: LoadTransaction): void { + const session = router._pending + if ( + router._tx === tx || + !router._tx?.[3 /* matches */].some( + (match) => match.id === session?.[1 /* boundaryId */], + ) + ) { + clearTimeout(session?.[3 /* revealTimer */]) + router._pending = undefined + } +} + +async function awaitPendingMinimum( + router: CoordinatorRouter, + tx: LoadTransaction, +): Promise<void> { + const session = router._pending + if (!session) { + return + } + clearTimeout(session[3 /* revealTimer */]) + const remaining = session[2 /* deadline */] - Date.now() + if ( + !session[4 /* ack */] || + remaining <= 0 || + !_getRenderedMatches(tx[3 /* matches */]).some( + (match) => match.id === session[1 /* boundaryId */], + ) + ) { + return + } + let timer: ReturnType<typeof setTimeout> | undefined + try { + await waitFor( + new Promise<void>((resolve) => { + timer = setTimeout(resolve, remaining) + }), + tx[0 /* controller */].signal, + ) + } catch {} + clearTimeout(timer) +} + +function publishMatches( + router: CoordinatorRouter, + matches: Array<AnyRouteMatch>, +): void { + router._committed = matches + router.stores.setMatches(matches) +} + +export function commitMatches( + router: CoordinatorRouter, + tx: LoadTransaction, + matches: LaneMatches<'projected'>, + resolvedPrefix?: number, +): void { + const previous = router._committed + const previousEnd = router._lifecycleEnd + const previousCached = router._cache + for (const match of matches) { + match.preload = false + if (resolvedPrefix) { + match._assetEnd = undefined + } + } + const cut = _getRenderedMatches(matches).length + const cached = new Map<string, AnyRouteMatch>() + if (process.env.NODE_ENV === 'production' || !tx[6 /* refresh */]) { + const now = Date.now() + // The rendered prefix and settled descendants supersede older generations. + // Unsettled matches beyond a fallback must not evict a newer preload. + const superseded = new Set<string>() + for (let index = 0; index < matches.length; index++) { + const match = matches[index]! + if (index < cut || match.status === 'success') { + superseded.add(match.id) + } + } + for (const match of [...previous, ...previousCached.values()]) { + if (match.status !== 'success' || superseded.has(match.id)) { + continue + } + const work = match as WorkMatch + const route = getRoute(router, work) + if ( + !route.options.loader || + now - match.updatedAt >= + (match.preload + ? (route.options.preloadGcTime ?? + router.options.defaultPreloadGcTime ?? + 300_000) + : (route.options.gcTime ?? router.options.defaultGcTime ?? 300_000)) + ) { + continue + } + cached.set( + match.id, + previousCached.get(match.id) === match + ? match + : ({ + ...match, + _flight: undefined, + isFetching: false, + context: {}, + } as WorkMatch), + ) + } + } + // The lane becomes committed before publication can synchronously reenter. + tx[3 /* matches */] = [] + router._cache = cached + // Publish lifecycle membership with its branch before observers can reenter. + const nextEnd = (router._lifecycleEnd = lifecycleEnd(matches)) + publishMatches(router, matches) + // Retained cache objects keep their leases; only departing owners need handoff. + const previousMatches = [...previousCached.values(), ...previous] + transferMatchResources( + router, + previousMatches.filter( + (match: WorkMatch) => match._flight && cached.get(match.id) !== match, + ), + matches, + ) + if (process.env.NODE_ENV !== 'production') { + const handoff = tx[6 /* refresh */]?.[0 /* handoff */] + if (handoff && router._handoff === handoff) { + handoff[1 /* finish */]() + } + } + runRouteLifecycle(router, previous, matches, previousEnd, nextEnd, tx) +} + +/** + * Resolve once the router has settled on a transaction other than `owner`. + * Each transaction's completion follows its current successor, so all waiters + * share the same chain instead of polling every successor independently. + */ +async function awaitCurrent( + router: CoordinatorRouter, + owner?: LoadTransaction, +): Promise<void> { + let current = router._tx + while (current && current !== owner) { + owner = current + await current[5 /* done */] + current = router._tx + } +} + +function followRedirect( + router: CoordinatorRouter, + tx: LoadTransaction, + outcome: RedirectOutcome, +): Promise<void> { + const options = outcome[1 /* redirect */].options + const location = outcome[2 /* location */] + if (!location) { + return router.navigate({ + ...options, + replace: true, + ignoreBlocker: true, + } as any) + } + if (options.reloadDocument) { + return router.navigate({ + href: (location.maskedLocation ?? location).publicHref, + reloadDocument: true, + replace: true, + ignoreBlocker: true, + } as any) + } + ;(location as ParsedLocation & { _redirects?: number })._redirects = + tx[1 /* redirects */] + 1 + router._pendingLocation = location + const committed = router.commitLocation({ + ...location, + viewTransition: options.viewTransition, + replace: true, + resetScroll: options.resetScroll, + hashScrollIntoView: options.hashScrollIntoView, + ignoreBlocker: true, + }) + queueMicrotask(() => { + if (router._pendingLocation === location) { + router._pendingLocation = undefined + } + }) + return committed +} + +async function runBackground( + router: CoordinatorRouter, + tx: LoadTransaction, + base: Array<AnyRouteMatch>, + tasks: Array<BackgroundLoaderTask>, + settlement: Promise<IndexedOutcome | undefined>, +): Promise<void> { + const next = base.map((match) => ({ ...match })) + acquireMatchResources(next) + for (const task of tasks) { + releaseFlight(router, next[task[0 /* index */]]!) + next[task[0 /* index */]] = task[3 /* candidate */] + } + // Phase jump: the clones inherit beforeLoad context from the committed + // foreground lane, which already ran `contextualize` for these matches. + const lane = [tx[2 /* location */], next] as ContextualizedLane + let reduced: ReducedLane | ControlOutcome + try { + reduced = await reduceLane( + router, + lane, + tasks, + tx[0 /* controller */], + settlement, + ) + } catch (cause) { + transferMatchResources(router, next) + throw cause + } + if (isControl(reduced)) { + transferMatchResources(router, next) + if ( + reduced[0 /* kind */] === REDIRECTED && + router._tx === tx && + router._committed === base + ) { + await followRedirect(router, tx, reduced) + } + return + } + await projectLane(router, reduced, tx[0 /* controller */].signal) + if (router._tx !== tx || router._committed !== base) { + transferMatchResources(router, next) + return + } + for (const match of next as Array<WorkMatch>) { + const cached = router._cache.get(match.id) as WorkMatch | undefined + if (cached?._flight && cached._flight === match._flight) { + router._cache.delete(match.id) + releaseFlight(router, cached) + } + } + publishMatches(router, next) + transferMatchResources(router, base, next) +} + +async function runClientTransaction( + router: CoordinatorRouter, + tx: LoadTransaction, + forceStaleReload: boolean, + onReady?: () => void, + sync?: boolean, + resolvedPrefix?: number, +): Promise<void> { + const result = await executeClientLane( + router, + tx[2 /* location */], + tx[3 /* matches */], + [ + tx[0 /* controller */], + tx[1 /* redirects */], + router._committed, + undefined, + sync, + forceStaleReload, + resolvedPrefix, + onReady, + ], + ) + + if (isControl(result)) { + const follow = result[0 /* kind */] === REDIRECTED && router._tx === tx + if (!follow || result[1 /* redirect */].options.reloadDocument) { + finishPending(router, tx) + } + transferMatchResources(router, tx[3 /* matches */]) + tx[3 /* matches */] = [] + if (!follow) { + return + } + if (router._tx !== tx) { + finishPending(router, tx) + return + } + if (process.env.NODE_ENV !== 'production' && tx[6 /* refresh */]) { + router._refreshNextLoad = true + } + await followRedirect(router, tx, result) + return + } + const matches = result[1 /* matches */] + if (router._tx === tx) { + // Only an acknowledged fallback owns a minimum. Recheck at the commit + // boundary because native view transitions can defer their update callback. + await awaitPendingMinimum(router, tx) + } + if (router._tx !== tx) { + finishPending(router, tx) + transferMatchResources(router, matches) + discardBackground(router, result) + return + } + const toLocation = tx[2 /* location */] + const changeInfo = getLocationChangeInfo( + toLocation, + router.stores.resolvedLocation.get(), + ) + const background = result[2 /* background */] + await router.startViewTransition(async () => { + if (router._tx === tx) { + await awaitPendingMinimum(router, tx) + } + if (router._tx !== tx) { + finishPending(router, tx) + transferMatchResources(router, matches) + discardBackground(router, result) + return + } + const commit = () => { + finishPending(router, tx) + commitMatches(router, tx, matches, resolvedPrefix) + if (router._tx !== tx) { + return + } + router.emit({ type: 'onLoad', ...changeInfo }) + if (router._tx === tx) { + router.emit({ type: 'onBeforeRouteMount', ...changeInfo }) + } + } + const rendered = await router.startTransition(commit, matches) + if (process.env.NODE_ENV !== 'production' && tx[6 /* refresh */]) { + tx[6 /* refresh */] = undefined + } + if (router._tx !== tx) { + discardBackground(router, result) + return + } + if (background?.length) { + // Publish background matches only after the foreground acknowledgement. + // Otherwise fast work can replace the acknowledged generation + // before the framework commits it and strand the navigation. + runBackground( + router, + tx, + matches, + background, + result[3 /* backgroundSettlement */]!, + ).catch(console.error) + } + router.batch(() => { + router.stores.resolvedLocation.set(toLocation) + router.stores.status.set('idle') + if (router._tx === tx) { + router.emit({ type: 'onResolved', ...changeInfo }) + } + if (rendered && router._tx === tx) { + router.emit({ type: 'onRendered', ...changeInfo }) + } + }) + if (router._tx !== tx) { + return + } + router._commitPromise?.resolve() + router._commitPromise = undefined + }) +} + +export async function loadClientRoute( + router: CoordinatorRouter, + opts?: { sync?: boolean }, +): Promise<void> { + let rematerialize = false + if (process.env.NODE_ENV !== 'production') { + rematerialize = !!router._refreshNextLoad || !!router._tx?.[6 /* refresh */] + } + const previousOwner = router._tx + const resolvedLocation = router.stores.resolvedLocation.get() + const previousLocation = resolvedLocation ?? router.stores.location.get() + const location = router.latestLocation + const pendingLocation = router._pendingLocation as + | (ParsedLocation & { _redirects?: number }) + | undefined + const redirects = + pendingLocation?.href === location.href + ? (pendingLocation._redirects ?? 0) + : 0 + const handoff = router._handoff + const hydrationController = rematerialize + ? undefined + : handoff?.[0 /* claim */]() + const preflight = new AbortController() + const previousPreflight = router._preflight + router._preflight = preflight + if (!rematerialize && !hydrationController) { + handoff?.[1 /* finish */]() + } + previousPreflight?.abort() + // The preflight controller is not exposed to route hooks. Every replacement + // aborts its predecessor, so a live signal is the sole authority here. + if (!preflight.signal.aborted) { + const changeInfo = getLocationChangeInfo(location, resolvedLocation) + router.emit({ type: 'onBeforeNavigate', ...changeInfo }) + if (!preflight.signal.aborted) { + router.emit({ type: 'onBeforeLoad', ...changeInfo }) + } + } + if (preflight.signal.aborted) { + await awaitCurrent(router, previousOwner) + return + } + const sameHref = previousLocation.href === location.href + let controller = preflight + const matches = + process.env.NODE_ENV !== 'production' && rematerialize + ? router.matchRoutes(location, { + _controller: preflight, + _rematerialize: true, + }) + : router.matchRoutes(location, { _controller: preflight }) + acquireMatchResources(matches) + const resolvedPrefix = hydrationController + ? handoff![1 /* finish */](matches) + : undefined + if (resolvedPrefix) { + controller = hydrationController! + } else { + hydrationController?.abort() + } + if (preflight.signal.aborted) { + transferMatchResources(router, matches) + await awaitCurrent(router, previousOwner) + return + } + router._preflight = undefined + + let settle: ((value: void | PromiseLike<void>) => void) | undefined + const run = () => + runClientTransaction( + router, + tx, + sameHref, + () => offerPending(router, tx), + opts?.sync, + resolvedPrefix, + ) + const done = opts?.sync + ? new Promise<void>((resolve) => (settle = resolve)) + : Promise.resolve().then(run) + const tx: LoadTransaction = [ + controller, + redirects, + location, + matches, + Date.now(), + done.then(() => awaitCurrent(router, tx)), + ] + if (process.env.NODE_ENV !== 'production' && rematerialize) { + tx[6 /* refresh */] = [handoff] + router._refreshNextLoad = undefined + } + router._tx = tx + if (previousOwner) { + for (const match of router.stores.matches.get() as Array<WorkMatch>) { + if (router._tx !== tx) { + break + } + if (match.isFetching) { + setFetching(router, match, false) + } + } + previousOwner[0 /* controller */].abort() + transferMatchResources( + router, + previousOwner[3 /* matches */], + tx[3 /* matches */], + true, + ) + } + if (router._tx !== tx) { + transferMatchResources(router, tx[3 /* matches */]) + tx[3 /* matches */] = [] + settle?.() + await awaitCurrent(router, tx) + return + } + router.batch(() => { + router.stores.status.set('pending') + router.stores.location.set(location) + }) + // An unresolved cold root has no UI to retain. Provisional not-found waits + // for lazy routes to place the final boundary. + if ( + resolvedPrefix || + (!router._committed.length && + matches[0]?.status !== 'success' && + !matches.some((match) => match._notFound)) + ) { + offerPending(router, tx) + } + // Let explicit synchronous loads publish ready pending work before paint. + settle?.(run()) + await tx[5 /* done */] +} + +export async function refreshClientRoute( + router: CoordinatorRouter, +): Promise<void> { + const pending = router._tx + if ( + pending && + !pending[6 /* refresh */] && + router.stores.status.get() === 'pending' + ) { + await pending[5 /* done */] + if (router._tx !== pending) { + await awaitCurrent(router, pending) + } + } + // Existing owners remain presented but cannot donate stale work. + router._flights?.clear() + router.clearCache() + router._refreshNextLoad = true + await loadClientRoute(router, { sync: true }) +} + +export async function preloadClientRoute< + TRouteTree extends AnyRoute, + TTrailingSlashOption extends TrailingSlashOption, + TDefaultStructuralSharingOption extends boolean, + TRouterHistory extends RouterHistory, + TDehydrated extends Record<string, any> = Record<string, any>, + TFrom extends RoutePaths<TRouteTree> | string = string, + TTo extends string | undefined = undefined, + TMaskFrom extends RoutePaths<TRouteTree> | string = TFrom, + TMaskTo extends string = '', +>( + router: RouterCore< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated + >, + opts: NavigateOptions< + RouterCore< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated + >, + TFrom, + TTo, + TMaskFrom, + TMaskTo + >, +): Promise<Array<AnyRouteMatch> | undefined> { + if ( + process.env.NODE_ENV !== 'production' && + ((router as CoordinatorRouter)._refreshNextLoad || + router._tx?.[6 /* refresh */]) + ) { + return + } + let location = router.buildLocation( + opts as Parameters<typeof router.buildLocation>[0], + ) + for (let redirects = 0; ; redirects++) { + const base = router._committed + const controller = new AbortController() + let matches: Array<AnyRouteMatch> | undefined + let active: boolean | Map<AbortController, Array<AnyRouteMatch>> | undefined + let result: LaneResult + try { + try { + matches = router.matchRoutes(location, { + _controller: controller, + }) + acquireMatchResources(matches) + active = (router._preloads ??= new Map()).set(controller, matches) + result = await executeClientLane(router, location, matches, [ + controller, + redirects, + base, + true, + ]) + } finally { + if (active) { + active = ( + active as Map<AbortController, Array<AnyRouteMatch>> + ).delete(controller) + transferMatchResources(router, matches!) + } + controller.abort() + } + if (!isControl(result)) { + return result[1 /* matches */] + } + // Only a materialized redirect has a third tuple item. + if ( + !active || + result.length < 3 || + (process.env.NODE_ENV !== 'production' && + ((router as CoordinatorRouter)._refreshNextLoad || + router._tx?.[6 /* refresh */])) + ) { + return + } + location = result[2 /* location */]! + } catch (cause) { + if (!isNotFound(cause)) { + console.error(cause) + } + return + } + } +} + +// --- SSR hydration (client entry via @tanstack/router-core/ssr/client) --- + +declare global { + interface Window { + [GLOBAL_TSR]?: TsrSsrGlobal + [GLOBAL_SEROVAL]?: any + } +} + +export async function hydrate(router: AnyRouter): Promise<void> { + if (process.env.NODE_ENV !== 'production' && !window.$_TSR) { + throw new Error( + 'Invariant failed: Expected to find bootstrap data on window.$_TSR, but we did not. Please file an issue!', + ) + } + const tsr = window.$_TSR! + + const adapters = router.options.serializationAdapters + if (adapters?.length) { + tsr.t = new Map( + adapters.map((adapter) => [adapter.key, adapter.fromSerializable]), + ) + tsr.buffer.forEach((script) => script()) + } + tsr.initialized = true + + const dehydratedRouter = tsr.router + if (process.env.NODE_ENV !== 'production' && !dehydratedRouter) { + throw new Error( + 'Invariant failed: Expected to find a dehydrated data on window.$_TSR.router, but we did not. Please file an issue!', + ) + } + router.ssr = { manifest: dehydratedRouter!.manifest } + router.options.ssr = { + nonce: ( + document.querySelector('meta[property="csp-nonce"]') as + | HTMLMetaElement + | undefined + )?.content, + } + + const dehydratedMatches = dehydratedRouter!.matches + + const controller = new AbortController() + const previousPreflight = router._preflight + router._preflight = controller + previousPreflight?.abort() + // Only a new slot owner supersedes hydration. + const isCurrent = () => router._preflight === controller + + let location!: AnyRouter['latestLocation'] + let candidates!: Array<AnyRouteMatch> + let handoffHistoryHref!: string + let handoffHistoryState: unknown + try { + await waitFor( + router.options.hydrate?.(dehydratedRouter!.dehydratedData), + controller.signal, + ) + if (!isCurrent()) { + return + } + // Hydration trusts transported context and beforeLoad. The raw history + // entry owns the handoff; route structure is verified after rematching. + const historyLocation = router.history.location + handoffHistoryHref = historyLocation.href + handoffHistoryState = historyLocation.state + router.updateLatestLocation() + location = router.latestLocation + router.stores.location.set(location) + candidates = router.matchRoutes(location, { + _controller: controller, + }) + } catch (cause) { + if (isCurrent()) { + router._preflight = undefined + } + controller.abort(cause) + if (cause !== controller.signal) { + throw cause + } + } + if (!isCurrent()) { + return + } + const committed: Array<AnyRouteMatch> = [] + let pendingBoundary: number | undefined + let verifiedAssetEnd = 0 + const retryFrom = (index: number) => { + // The failing route's identity is still verified, but no descendant is. + verifiedAssetEnd = Math.min(verifiedAssetEnd, index + 1) + const removed = committed.splice(index) + for (const match of removed) { + if ( + getRoute(router, match).options.loader && + (match.status === 'success' || + (!match.invalid && 'loaderData' in match)) + ) { + cacheLoaderMatch( + router, + // Phase jump: dehydrated server data is already past the loader + // phase — the guard above verified a settled success (or transported + // loaderData), so this clone is settled without a client settleInto. + { + ...match, + status: 'success', + error: undefined, + preload: true, + } as SettledMatch, + router._cache.get(match.id), + ) + } + } + transferMatchResources(router, removed) + } + + // A longer server lane is valid only when the local match already caps the + // branch at a global not-found boundary. Otherwise no transported work is + // safe to attach to the shorter client lane. + const shared = + dehydratedMatches.length > candidates.length + ? candidates.findIndex((match) => match._notFound) + 1 + : dehydratedMatches.length + let isTerminal = false + for (let index = 0; index < shared; index++) { + const candidate = candidates[index]! + const dehydrated = dehydratedMatches[index]! + if (dehydrated.i !== dehydrateSsrMatchId(candidate.id)) { + pendingBoundary ??= index + break + } + verifiedAssetEnd = index + 1 + const route = getRoute(router, candidate) + if ( + 'l' in dehydrated || + (dehydrated.s === 'success' && + dehydrated.e === undefined && + route.options.loader) + ) { + candidate.loaderData = dehydrated.l + } + candidate.status = dehydrated.s + candidate.ssr = dehydrated.ssr + route.options.ssr = candidate.ssr + candidate.updatedAt = dehydrated.u + candidate.error = dehydrated.e + candidate._notFound ||= dehydrated.g + const terminal = + candidate.status === 'error' || + candidate.status === 'notFound' || + candidate._notFound + if (terminal) { + isTerminal = true + committed.push(candidate) + if (candidate.ssr === false || candidate.ssr === 'data-only') { + pendingBoundary ??= index + } + break + } + if (candidate.status === 'pending') { + pendingBoundary ??= index + break + } + + committed.push(candidate) + if (candidate.ssr === 'data-only') { + pendingBoundary ??= index + } + } + if ( + !isTerminal && + committed.length === shared && + shared < candidates.length + ) { + pendingBoundary = shared + } + + // Hooks observe structural membership. Execution remains limited to + // `committed`, the accepted server prefix. + const chunks = committed.map(async (match) => { + try { + const route = getRoute(router, match) + await (match._notFound + ? Promise.all([ + loadRouteChunk(route), + loadRouteChunk(route, 'notFoundComponent'), + ]) + : loadRouteChunk( + route, + match.status === 'error' + ? 'errorComponent' + : match.status === 'notFound' + ? 'notFoundComponent' + : undefined, + )) + return true + } catch { + return false + } + }) + let chunkFailure = 0 + try { + while ( + chunkFailure < chunks.length && + (await waitFor(chunks[chunkFailure]!, controller.signal)) + ) { + chunkFailure++ + } + } catch { + return + } + if (!isCurrent()) { + return + } + if (chunkFailure < committed.length) { + retryFrom(chunkFailure) + } + + // The first pending match is already visible, so prepare its route context + // without granting its beforeLoad or loader any hydration authority. + const contextEnd = Math.max( + pendingBoundary === committed.length + ? committed.length + 1 + : committed.length, + // `chunks.length` keeps the pre-retry committed length, so a smaller + // `chunkFailure` is the exclusive bound of the verified context prefix. + chunkFailure < chunks.length ? chunkFailure : verifiedAssetEnd, + ) + for (let index = 0; index < contextEnd; index++) { + const match = candidates[index]! + const route = getRoute(router, match) + const parentContext = + candidates[index - 1]?.context ?? router.options.context ?? {} + let routeContext + if (route.options.context) { + try { + routeContext = match._ctx = + route.options.context({ + deps: match.loaderDeps, + params: match.params, + context: parentContext, + location, + navigate: (opts: any) => + router.navigate({ + ...opts, + _fromLocation: location, + }), + buildLocation: router.buildLocation, + cause: match.cause, + abortController: controller, + preload: false, + matches: candidates, + routeId: route.id, + }) || {} + } catch { + if (!isCurrent()) { + return + } + if ( + match.status !== 'error' && + match.status !== 'notFound' && + !match._notFound + ) { + // Never present transported success without reconstructed context. + pendingBoundary = Math.min(pendingBoundary ?? index, index) + retryFrom(index) + break + } + } + if (!isCurrent()) { + return + } + } + match.context = { + ...parentContext, + ...routeContext, + ...(committed[index] && dehydratedMatches[index]!.b), + } + } + + await projectLane( + router, + [location, candidates] as any, + controller.signal, + 0, + verifiedAssetEnd, + ) + if (!isCurrent()) { + return + } + const needsClientLoad = + pendingBoundary !== undefined || committed.length < shared + const committedMatches = + isTerminal && committed.length === shared ? candidates : committed + let presented = needsClientLoad ? candidates : committedMatches + let dataOnlyAssetEnd: number | undefined + if (needsClientLoad && pendingBoundary !== undefined) { + const boundary = presented[pendingBoundary]! + // A verified descendant proves this data-only boundary was nonterminal. + dataOnlyAssetEnd = + boundary.ssr === 'data-only' && verifiedAssetEnd > pendingBoundary + 1 + ? verifiedAssetEnd + : undefined + presented = presented.slice() + presented[pendingBoundary] = { + ...boundary, + status: 'pending', + ssr: boundary.ssr === 'data-only' ? 'data-only' : false, + _assetEnd: dataOnlyAssetEnd, + } + } + + const claim = () => { + const historyLocation = router.history.location + return needsClientLoad && + !router._tx && + historyLocation.href === handoffHistoryHref && + historyLocation.state === handoffHistoryState && + router._committed === committedMatches && + committedMatches.length && + !controller.signal.aborted + ? controller + : undefined + } + const handoff: NonNullable<AnyRouter['_handoff']> = [ + claim, + (matches) => { + if (router._handoff !== handoff) { + return + } + // `finish` is single-use. Consume the slot before validating or moving + // resources so reentrant work cannot claim the same handoff. + router._handoff = undefined + const prefix = committedMatches.length + if ( + !matches || + !claim() || + committedMatches.some((match, index) => match.id !== matches[index]?.id) + ) { + controller.abort() + return + } + let handoffAssetEnd = dataOnlyAssetEnd + if (handoffAssetEnd !== undefined) { + for (let index = prefix; index < handoffAssetEnd; index++) { + if (candidates[index]?.id !== matches[index]?.id) { + handoffAssetEnd = index > pendingBoundary! + 1 ? index : undefined + break + } + } + } + const clones = committedMatches.map((match) => ({ ...match })) + if (handoffAssetEnd !== undefined) { + clones[pendingBoundary!]!._assetEnd = handoffAssetEnd + } + transferMatchResources(router, matches.splice(0, prefix, ...clones)) + for (let index = prefix; index < matches.length; index++) { + const match = matches[index]! + const hydrated = candidates[index] + if (hydrated?.id === match.id && hydrated._ctx) { + match._ctx = hydrated._ctx + } + match.abortController = controller + } + return prefix + }, + ] + router._committed = committedMatches + router._lifecycleEnd = lifecycleEnd(committedMatches) + router._handoff = handoff + router._preflight = undefined + router.batch(() => { + router.stores.setMatches(presented) + router.stores.status.set('idle') + if (!needsClientLoad) { + router.stores.resolvedLocation.set(router.stores.location.get()) + } + }) +} diff --git a/packages/router-core/src/load-matches.ts b/packages/router-core/src/load-matches.ts deleted file mode 100644 index 2909d6d25a..0000000000 --- a/packages/router-core/src/load-matches.ts +++ /dev/null @@ -1,1017 +0,0 @@ -import { batch } from '@tanstack/store' -import invariant from 'tiny-invariant' -import { createControlledPromise, isPromise } from './utils' -import { isNotFound } from './not-found' -import { rootRouteId } from './root' -import { isRedirect } from './redirect' -import type { NotFoundError } from './not-found' -import type { ParsedLocation } from './location' -import type { - AnyRoute, - BeforeLoadContextOptions, - LoaderFnContext, - SsrContextOptions, -} from './route' -import type { AnyRouteMatch, MakeRouteMatch } from './Matches' -import type { AnyRouter, SSROption, UpdateMatchFn } from './router' - -/** - * An object of this shape is created when calling `loadMatches`. - * It contains everything we need for all other functions in this file - * to work. (It's basically the function's argument, plus a few mutable states) - */ -type InnerLoadContext = { - /** the calling router instance */ - router: AnyRouter - location: ParsedLocation - /** mutable state, scoped to a `loadMatches` call */ - firstBadMatchIndex?: number - /** mutable state, scoped to a `loadMatches` call */ - rendered?: boolean - updateMatch: UpdateMatchFn - matches: Array<AnyRouteMatch> - preload?: boolean - onReady?: () => Promise<void> - sync?: boolean - /** mutable state, scoped to a `loadMatches` call */ - matchPromises: Array<Promise<AnyRouteMatch>> -} - -const triggerOnReady = (inner: InnerLoadContext): void | Promise<void> => { - if (!inner.rendered) { - inner.rendered = true - return inner.onReady?.() - } -} - -const resolvePreload = (inner: InnerLoadContext, matchId: string): boolean => { - return !!( - inner.preload && !inner.router.state.matches.some((d) => d.id === matchId) - ) -} - -/** - * Builds the accumulated context from router options and all matches up to (and optionally including) the given index. - * Merges __routeContext and __beforeLoadContext from each match. - */ -const buildMatchContext = ( - inner: InnerLoadContext, - index: number, - includeCurrentMatch: boolean = true, -): Record<string, unknown> => { - const context: Record<string, unknown> = { - ...(inner.router.options.context ?? {}), - } - const end = includeCurrentMatch ? index : index - 1 - for (let i = 0; i <= end; i++) { - const innerMatch = inner.matches[i] - if (!innerMatch) continue - const m = inner.router.getMatch(innerMatch.id) - if (!m) continue - Object.assign(context, m.__routeContext, m.__beforeLoadContext) - } - return context -} - -const _handleNotFound = (inner: InnerLoadContext, err: NotFoundError) => { - // Find the route that should handle the not found error - // First check if a specific route is requested to show the error - const routeCursor = - inner.router.routesById[err.routeId ?? ''] ?? inner.router.routeTree - - // Ensure a NotFoundComponent exists on the route - if ( - !routeCursor.options.notFoundComponent && - (inner.router.options as any)?.defaultNotFoundComponent - ) { - routeCursor.options.notFoundComponent = ( - inner.router.options as any - ).defaultNotFoundComponent - } - - // Ensure we have a notFoundComponent - invariant( - routeCursor.options.notFoundComponent, - 'No notFoundComponent found. Please set a notFoundComponent on your route or provide a defaultNotFoundComponent to the router.', - ) - - // Find the match for this route - const matchForRoute = inner.matches.find((m) => m.routeId === routeCursor.id) - - invariant(matchForRoute, 'Could not find match for route: ' + routeCursor.id) - - // Assign the error to the match - using non-null assertion since we've checked with invariant - inner.updateMatch(matchForRoute.id, (prev) => ({ - ...prev, - status: 'notFound', - error: err, - isFetching: false, - })) - - if ((err as any).routerCode === 'BEFORE_LOAD' && routeCursor.parentRoute) { - err.routeId = routeCursor.parentRoute.id - _handleNotFound(inner, err) - } -} - -const handleRedirectAndNotFound = ( - inner: InnerLoadContext, - match: AnyRouteMatch | undefined, - err: unknown, -): void => { - if (!isRedirect(err) && !isNotFound(err)) return - - if (isRedirect(err) && err.redirectHandled && !err.options.reloadDocument) { - throw err - } - - // in case of a redirecting match during preload, the match does not exist - if (match) { - match._nonReactive.beforeLoadPromise?.resolve() - match._nonReactive.loaderPromise?.resolve() - match._nonReactive.beforeLoadPromise = undefined - match._nonReactive.loaderPromise = undefined - - const status = isRedirect(err) ? 'redirected' : 'notFound' - - match._nonReactive.error = err - - inner.updateMatch(match.id, (prev) => ({ - ...prev, - status, - isFetching: false, - error: err, - })) - - if (isNotFound(err) && !err.routeId) { - err.routeId = match.routeId - } - - match._nonReactive.loadPromise?.resolve() - } - - if (isRedirect(err)) { - inner.rendered = true - err.options._fromLocation = inner.location - err.redirectHandled = true - err = inner.router.resolveRedirect(err) - throw err - } else { - _handleNotFound(inner, err) - throw err - } -} - -const shouldSkipLoader = ( - inner: InnerLoadContext, - matchId: string, -): boolean => { - const match = inner.router.getMatch(matchId)! - // upon hydration, we skip the loader if the match has been dehydrated on the server - if (!inner.router.isServer && match._nonReactive.dehydrated) { - return true - } - - if (inner.router.isServer && match.ssr === false) { - return true - } - - return false -} - -const handleSerialError = ( - inner: InnerLoadContext, - index: number, - err: any, - routerCode: string, -): void => { - const { id: matchId, routeId } = inner.matches[index]! - const route = inner.router.looseRoutesById[routeId]! - - // Much like suspense, we use a promise here to know if - // we've been outdated by a new loadMatches call and - // should abort the current async operation - if (err instanceof Promise) { - throw err - } - - err.routerCode = routerCode - inner.firstBadMatchIndex ??= index - handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err) - - try { - route.options.onError?.(err) - } catch (errorHandlerErr) { - err = errorHandlerErr - handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err) - } - - inner.updateMatch(matchId, (prev) => { - prev._nonReactive.beforeLoadPromise?.resolve() - prev._nonReactive.beforeLoadPromise = undefined - prev._nonReactive.loadPromise?.resolve() - - return { - ...prev, - error: err, - status: 'error', - isFetching: false, - updatedAt: Date.now(), - abortController: new AbortController(), - } - }) -} - -const isBeforeLoadSsr = ( - inner: InnerLoadContext, - matchId: string, - index: number, - route: AnyRoute, -): void | Promise<void> => { - const existingMatch = inner.router.getMatch(matchId)! - const parentMatchId = inner.matches[index - 1]?.id - const parentMatch = parentMatchId - ? inner.router.getMatch(parentMatchId)! - : undefined - - // in SPA mode, only SSR the root route - if (inner.router.isShell()) { - existingMatch.ssr = route.id === rootRouteId - return - } - - if (parentMatch?.ssr === false) { - existingMatch.ssr = false - return - } - - const parentOverride = (tempSsr: SSROption) => { - if (tempSsr === true && parentMatch?.ssr === 'data-only') { - return 'data-only' - } - return tempSsr - } - - const defaultSsr = inner.router.options.defaultSsr ?? true - - if (route.options.ssr === undefined) { - existingMatch.ssr = parentOverride(defaultSsr) - return - } - - if (typeof route.options.ssr !== 'function') { - existingMatch.ssr = parentOverride(route.options.ssr) - return - } - const { search, params } = existingMatch - - const ssrFnContext: SsrContextOptions<any, any, any> = { - search: makeMaybe(search, existingMatch.searchError), - params: makeMaybe(params, existingMatch.paramsError), - location: inner.location, - matches: inner.matches.map((match) => ({ - index: match.index, - pathname: match.pathname, - fullPath: match.fullPath, - staticData: match.staticData, - id: match.id, - routeId: match.routeId, - search: makeMaybe(match.search, match.searchError), - params: makeMaybe(match.params, match.paramsError), - ssr: match.ssr, - })), - } - - const tempSsr = route.options.ssr(ssrFnContext) - if (isPromise(tempSsr)) { - return tempSsr.then((ssr) => { - existingMatch.ssr = parentOverride(ssr ?? defaultSsr) - }) - } - - existingMatch.ssr = parentOverride(tempSsr ?? defaultSsr) - return -} - -const setupPendingTimeout = ( - inner: InnerLoadContext, - matchId: string, - route: AnyRoute, - match: AnyRouteMatch, -): void => { - if (match._nonReactive.pendingTimeout !== undefined) return - - const pendingMs = - route.options.pendingMs ?? inner.router.options.defaultPendingMs - const shouldPending = !!( - inner.onReady && - !inner.router.isServer && - !resolvePreload(inner, matchId) && - (route.options.loader || - route.options.beforeLoad || - routeNeedsPreload(route)) && - typeof pendingMs === 'number' && - pendingMs !== Infinity && - (route.options.pendingComponent ?? - (inner.router.options as any)?.defaultPendingComponent) - ) - - if (shouldPending) { - const pendingTimeout = setTimeout(() => { - // Update the match and prematurely resolve the loadMatches promise so that - // the pending component can start rendering - triggerOnReady(inner) - }, pendingMs) - match._nonReactive.pendingTimeout = pendingTimeout - } -} - -const preBeforeLoadSetup = ( - inner: InnerLoadContext, - matchId: string, - route: AnyRoute, -): void | Promise<void> => { - const existingMatch = inner.router.getMatch(matchId)! - - // If we are in the middle of a load, either of these will be present - // (not to be confused with `loadPromise`, which is always defined) - if ( - !existingMatch._nonReactive.beforeLoadPromise && - !existingMatch._nonReactive.loaderPromise - ) - return - - setupPendingTimeout(inner, matchId, route, existingMatch) - - const then = () => { - const match = inner.router.getMatch(matchId)! - if ( - match.preload && - (match.status === 'redirected' || match.status === 'notFound') - ) { - handleRedirectAndNotFound(inner, match, match.error) - } - } - - // Wait for the previous beforeLoad to resolve before we continue - return existingMatch._nonReactive.beforeLoadPromise - ? existingMatch._nonReactive.beforeLoadPromise.then(then) - : then() -} - -const executeBeforeLoad = ( - inner: InnerLoadContext, - matchId: string, - index: number, - route: AnyRoute, -): void | Promise<void> => { - const match = inner.router.getMatch(matchId)! - - // explicitly capture the previous loadPromise - const prevLoadPromise = match._nonReactive.loadPromise - match._nonReactive.loadPromise = createControlledPromise<void>(() => { - prevLoadPromise?.resolve() - }) - - const { paramsError, searchError } = match - - if (paramsError) { - handleSerialError(inner, index, paramsError, 'PARSE_PARAMS') - } - - if (searchError) { - handleSerialError(inner, index, searchError, 'VALIDATE_SEARCH') - } - - setupPendingTimeout(inner, matchId, route, match) - - const abortController = new AbortController() - - const parentMatchId = inner.matches[index - 1]?.id - const parentMatch = parentMatchId - ? inner.router.getMatch(parentMatchId)! - : undefined - const parentMatchContext = - parentMatch?.context ?? inner.router.options.context ?? undefined - - let isPending = false - const pending = () => { - if (isPending) return - isPending = true - inner.updateMatch(matchId, (prev) => ({ - ...prev, - isFetching: 'beforeLoad', - fetchCount: prev.fetchCount + 1, - abortController, - // Note: We intentionally don't update context here. - // Context should only be updated after beforeLoad resolves to avoid - // components seeing incomplete context during async beforeLoad execution. - })) - } - - const resolve = () => { - match._nonReactive.beforeLoadPromise?.resolve() - match._nonReactive.beforeLoadPromise = undefined - inner.updateMatch(matchId, (prev) => ({ - ...prev, - isFetching: false, - })) - } - - // if there is no `beforeLoad` option, just mark as pending and resolve - // Context will be updated later in loadRouteMatch after loader completes - if (!route.options.beforeLoad) { - batch(() => { - pending() - resolve() - }) - return - } - - match._nonReactive.beforeLoadPromise = createControlledPromise<void>() - - // Build context from all parent matches, excluding current match's __beforeLoadContext - // (since we're about to execute beforeLoad for this match) - const context = { - ...buildMatchContext(inner, index, false), - ...match.__routeContext, - } - const { search, params, cause } = match - const preload = resolvePreload(inner, matchId) - const beforeLoadFnContext: BeforeLoadContextOptions< - any, - any, - any, - any, - any, - any, - any, - any - > = { - search, - abortController, - params, - preload, - context, - location: inner.location, - navigate: (opts: any) => - inner.router.navigate({ - ...opts, - _fromLocation: inner.location, - }), - buildLocation: inner.router.buildLocation, - cause: preload ? 'preload' : cause, - matches: inner.matches, - ...inner.router.options.additionalContext, - } - - const updateContext = (beforeLoadContext: any) => { - if (beforeLoadContext === undefined) { - batch(() => { - pending() - resolve() - }) - return - } - if (isRedirect(beforeLoadContext) || isNotFound(beforeLoadContext)) { - pending() - handleSerialError(inner, index, beforeLoadContext, 'BEFORE_LOAD') - } - - batch(() => { - pending() - // Only store __beforeLoadContext here, don't update context yet - // Context will be updated in loadRouteMatch after loader completes - inner.updateMatch(matchId, (prev) => ({ - ...prev, - __beforeLoadContext: beforeLoadContext, - })) - resolve() - }) - } - - let beforeLoadContext - try { - beforeLoadContext = route.options.beforeLoad(beforeLoadFnContext) - if (isPromise(beforeLoadContext)) { - pending() - return beforeLoadContext - .catch((err) => { - handleSerialError(inner, index, err, 'BEFORE_LOAD') - }) - .then(updateContext) - } - } catch (err) { - pending() - handleSerialError(inner, index, err, 'BEFORE_LOAD') - } - - updateContext(beforeLoadContext) - return -} - -const handleBeforeLoad = ( - inner: InnerLoadContext, - index: number, -): void | Promise<void> => { - const { id: matchId, routeId } = inner.matches[index]! - const route = inner.router.looseRoutesById[routeId]! - - const serverSsr = () => { - // on the server, determine whether SSR the current match or not - if (inner.router.isServer) { - const maybePromise = isBeforeLoadSsr(inner, matchId, index, route) - if (isPromise(maybePromise)) return maybePromise.then(queueExecution) - } - return queueExecution() - } - - const execute = () => executeBeforeLoad(inner, matchId, index, route) - - const queueExecution = () => { - if (shouldSkipLoader(inner, matchId)) return - const result = preBeforeLoadSetup(inner, matchId, route) - return isPromise(result) ? result.then(execute) : execute() - } - - return serverSsr() -} - -const executeHead = ( - inner: InnerLoadContext, - matchId: string, - route: AnyRoute, -): void | Promise< - Pick< - AnyRouteMatch, - 'meta' | 'links' | 'headScripts' | 'headers' | 'scripts' | 'styles' - > -> => { - const match = inner.router.getMatch(matchId) - // in case of a redirecting match during preload, the match does not exist - if (!match) { - return - } - if (!route.options.head && !route.options.scripts && !route.options.headers) { - return - } - const assetContext = { - matches: inner.matches, - match, - params: match.params, - loaderData: match.loaderData, - } - - return Promise.all([ - route.options.head?.(assetContext), - route.options.scripts?.(assetContext), - route.options.headers?.(assetContext), - ]).then(([headFnContent, scripts, headers]) => { - const meta = headFnContent?.meta - const links = headFnContent?.links - const headScripts = headFnContent?.scripts - const styles = headFnContent?.styles - - return { - meta, - links, - headScripts, - headers, - scripts, - styles, - } - }) -} - -const getLoaderContext = ( - inner: InnerLoadContext, - matchId: string, - index: number, - route: AnyRoute, -): LoaderFnContext => { - const parentMatchPromise = inner.matchPromises[index - 1] as any - const { params, loaderDeps, abortController, cause } = - inner.router.getMatch(matchId)! - - const context = buildMatchContext(inner, index) - - const preload = resolvePreload(inner, matchId) - - return { - params, - deps: loaderDeps, - preload: !!preload, - parentMatchPromise, - abortController, - context, - location: inner.location, - navigate: (opts) => - inner.router.navigate({ - ...opts, - _fromLocation: inner.location, - }), - cause: preload ? 'preload' : cause, - route, - ...inner.router.options.additionalContext, - } -} - -const runLoader = async ( - inner: InnerLoadContext, - matchId: string, - index: number, - route: AnyRoute, -): Promise<void> => { - try { - // If the Matches component rendered - // the pending component and needs to show it for - // a minimum duration, we''ll wait for it to resolve - // before committing to the match and resolving - // the loadPromise - - const match = inner.router.getMatch(matchId)! - - // Actually run the loader and handle the result - try { - if (!inner.router.isServer || match.ssr === true) { - loadRouteChunk(route) - } - - // Kick off the loader! - const loaderResult = route.options.loader?.( - getLoaderContext(inner, matchId, index, route), - ) - const loaderResultIsPromise = - route.options.loader && isPromise(loaderResult) - - const willLoadSomething = !!( - loaderResultIsPromise || - route._lazyPromise || - route._componentsPromise || - route.options.head || - route.options.scripts || - route.options.headers || - match._nonReactive.minPendingPromise - ) - - if (willLoadSomething) { - inner.updateMatch(matchId, (prev) => ({ - ...prev, - isFetching: 'loader', - })) - } - - if (route.options.loader) { - const loaderData = loaderResultIsPromise - ? await loaderResult - : loaderResult - - handleRedirectAndNotFound( - inner, - inner.router.getMatch(matchId), - loaderData, - ) - if (loaderData !== undefined) { - inner.updateMatch(matchId, (prev) => ({ - ...prev, - loaderData, - })) - } - } - - // Lazy option can modify the route options, - // so we need to wait for it to resolve before - // we can use the options - if (route._lazyPromise) await route._lazyPromise - const headResult = executeHead(inner, matchId, route) - const head = headResult ? await headResult : undefined - const pendingPromise = match._nonReactive.minPendingPromise - if (pendingPromise) await pendingPromise - - // Last but not least, wait for the the components - // to be preloaded before we resolve the match - if (route._componentsPromise) await route._componentsPromise - inner.updateMatch(matchId, (prev) => ({ - ...prev, - error: undefined, - status: 'success', - isFetching: false, - updatedAt: Date.now(), - ...head, - })) - } catch (e) { - let error = e - - const pendingPromise = match._nonReactive.minPendingPromise - if (pendingPromise) await pendingPromise - - if (isNotFound(e)) { - await (route.options.notFoundComponent as any)?.preload?.() - } - - handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), e) - - try { - route.options.onError?.(e) - } catch (onErrorError) { - error = onErrorError - handleRedirectAndNotFound( - inner, - inner.router.getMatch(matchId), - onErrorError, - ) - } - const headResult = executeHead(inner, matchId, route) - const head = headResult ? await headResult : undefined - inner.updateMatch(matchId, (prev) => ({ - ...prev, - error, - status: 'error', - isFetching: false, - ...head, - })) - } - } catch (err) { - const match = inner.router.getMatch(matchId) - // in case of a redirecting match during preload, the match does not exist - if (match) { - const headResult = executeHead(inner, matchId, route) - if (headResult) { - const head = await headResult - inner.updateMatch(matchId, (prev) => ({ - ...prev, - ...head, - })) - } - match._nonReactive.loaderPromise = undefined - } - handleRedirectAndNotFound(inner, match, err) - } -} - -const loadRouteMatch = async ( - inner: InnerLoadContext, - index: number, -): Promise<AnyRouteMatch> => { - const { id: matchId, routeId } = inner.matches[index]! - let loaderShouldRunAsync = false - let loaderIsRunningAsync = false - const route = inner.router.looseRoutesById[routeId]! - - const commitContext = () => { - inner.updateMatch(matchId, (prev) => ({ - ...prev, - context: buildMatchContext(inner, index), - })) - } - - if (shouldSkipLoader(inner, matchId)) { - if (inner.router.isServer) { - const headResult = executeHead(inner, matchId, route) - if (headResult) { - const head = await headResult - inner.updateMatch(matchId, (prev) => ({ - ...prev, - ...head, - })) - } - return inner.router.getMatch(matchId)! - } - } else { - const prevMatch = inner.router.getMatch(matchId)! - // there is a loaderPromise, so we are in the middle of a load - if (prevMatch._nonReactive.loaderPromise) { - // do not block if we already have stale data we can show - // but only if the ongoing load is not a preload since error handling is different for preloads - // and we don't want to swallow errors - if (prevMatch.status === 'success' && !inner.sync && !prevMatch.preload) { - return prevMatch - } - await prevMatch._nonReactive.loaderPromise - const match = inner.router.getMatch(matchId)! - const error = match._nonReactive.error || match.error - if (error) { - handleRedirectAndNotFound(inner, match, error) - } - } else { - // This is where all of the stale-while-revalidate magic happens - const age = Date.now() - prevMatch.updatedAt - - const preload = resolvePreload(inner, matchId) - - const staleAge = preload - ? (route.options.preloadStaleTime ?? - inner.router.options.defaultPreloadStaleTime ?? - 30_000) // 30 seconds for preloads by default - : (route.options.staleTime ?? - inner.router.options.defaultStaleTime ?? - 0) - - const shouldReloadOption = route.options.shouldReload - - // Default to reloading the route all the time - // Allow shouldReload to get the last say, - // if provided. - const shouldReload = - typeof shouldReloadOption === 'function' - ? shouldReloadOption(getLoaderContext(inner, matchId, index, route)) - : shouldReloadOption - - const nextPreload = - !!preload && !inner.router.state.matches.some((d) => d.id === matchId) - const match = inner.router.getMatch(matchId)! - match._nonReactive.loaderPromise = createControlledPromise<void>() - if (nextPreload !== match.preload) { - inner.updateMatch(matchId, (prev) => ({ - ...prev, - preload: nextPreload, - })) - } - - // If the route is successful and still fresh, just resolve - const { status, invalid } = match - loaderShouldRunAsync = - status === 'success' && (invalid || (shouldReload ?? age > staleAge)) - if (preload && route.options.preload === false) { - // Do nothing - } else if (loaderShouldRunAsync && !inner.sync) { - loaderIsRunningAsync = true - ;(async () => { - try { - await runLoader(inner, matchId, index, route) - commitContext() - const match = inner.router.getMatch(matchId)! - match._nonReactive.loaderPromise?.resolve() - match._nonReactive.loadPromise?.resolve() - match._nonReactive.loaderPromise = undefined - } catch (err) { - if (isRedirect(err)) { - await inner.router.navigate(err.options) - } - } - })() - } else if (status !== 'success' || (loaderShouldRunAsync && inner.sync)) { - await runLoader(inner, matchId, index, route) - } else { - // if the loader did not run, still update head. - // reason: parent's beforeLoad may have changed the route context - // and only now do we know the route context (and that the loader would not run) - const headResult = executeHead(inner, matchId, route) - if (headResult) { - const head = await headResult - inner.updateMatch(matchId, (prev) => ({ - ...prev, - ...head, - })) - } - } - } - } - const match = inner.router.getMatch(matchId)! - if (!loaderIsRunningAsync) { - match._nonReactive.loaderPromise?.resolve() - match._nonReactive.loadPromise?.resolve() - } - - clearTimeout(match._nonReactive.pendingTimeout) - match._nonReactive.pendingTimeout = undefined - if (!loaderIsRunningAsync) match._nonReactive.loaderPromise = undefined - match._nonReactive.dehydrated = undefined - - // Commit context now that loader has completed (or was skipped) - // For async loaders, this was already done in the async callback - if (!loaderIsRunningAsync) { - commitContext() - } - - const nextIsFetching = loaderIsRunningAsync ? match.isFetching : false - if (nextIsFetching !== match.isFetching || match.invalid !== false) { - inner.updateMatch(matchId, (prev) => ({ - ...prev, - isFetching: nextIsFetching, - invalid: false, - })) - return inner.router.getMatch(matchId)! - } else { - return match - } -} - -export async function loadMatches(arg: { - router: AnyRouter - location: ParsedLocation - matches: Array<AnyRouteMatch> - preload?: boolean - onReady?: () => Promise<void> - updateMatch: UpdateMatchFn - sync?: boolean -}): Promise<Array<MakeRouteMatch>> { - const inner: InnerLoadContext = Object.assign(arg, { - matchPromises: [], - }) - - // make sure the pending component is immediately rendered when hydrating a match that is not SSRed - // the pending component was already rendered on the server and we want to keep it shown on the client until minPendingMs is reached - if ( - !inner.router.isServer && - inner.router.state.matches.some((d) => d._forcePending) - ) { - triggerOnReady(inner) - } - - try { - // Execute all beforeLoads one by one - for (let i = 0; i < inner.matches.length; i++) { - const beforeLoad = handleBeforeLoad(inner, i) - if (isPromise(beforeLoad)) await beforeLoad - } - - // Execute all loaders in parallel - const max = inner.firstBadMatchIndex ?? inner.matches.length - for (let i = 0; i < max; i++) { - inner.matchPromises.push(loadRouteMatch(inner, i)) - } - await Promise.all(inner.matchPromises) - - const readyPromise = triggerOnReady(inner) - if (isPromise(readyPromise)) await readyPromise - } catch (err) { - if (isNotFound(err) && !inner.preload) { - const readyPromise = triggerOnReady(inner) - if (isPromise(readyPromise)) await readyPromise - throw err - } - if (isRedirect(err)) { - throw err - } - } - - return inner.matches -} - -export async function loadRouteChunk(route: AnyRoute) { - if (!route._lazyLoaded && route._lazyPromise === undefined) { - if (route.lazyFn) { - route._lazyPromise = route.lazyFn().then((lazyRoute) => { - // explicitly don't copy over the lazy route's id - const { id: _id, ...options } = lazyRoute.options - Object.assign(route.options, options) - route._lazyLoaded = true - route._lazyPromise = undefined // gc promise, we won't need it anymore - }) - } else { - route._lazyLoaded = true - } - } - - // If for some reason lazy resolves more lazy components... - // We'll wait for that before we attempt to preload the - // components themselves. - if (!route._componentsLoaded && route._componentsPromise === undefined) { - const loadComponents = () => { - const preloads = [] - for (const type of componentTypes) { - const preload = (route.options[type] as any)?.preload - if (preload) preloads.push(preload()) - } - if (preloads.length) - return Promise.all(preloads).then(() => { - route._componentsLoaded = true - route._componentsPromise = undefined // gc promise, we won't need it anymore - }) - route._componentsLoaded = true - route._componentsPromise = undefined // gc promise, we won't need it anymore - return - } - route._componentsPromise = route._lazyPromise - ? route._lazyPromise.then(loadComponents) - : loadComponents() - } - return route._componentsPromise -} - -function makeMaybe<TValue, TError>( - value: TValue, - error: TError, -): { status: 'success'; value: TValue } | { status: 'error'; error: TError } { - if (error) { - return { status: 'error' as const, error } - } - return { status: 'success' as const, value } -} - -export function routeNeedsPreload(route: AnyRoute) { - for (const componentType of componentTypes) { - if ((route.options[componentType] as any)?.preload) { - return true - } - } - return false -} - -export const componentTypes = [ - 'component', - 'errorComponent', - 'pendingComponent', - 'notFoundComponent', -] as const diff --git a/packages/router-core/src/load-server.ts b/packages/router-core/src/load-server.ts new file mode 100644 index 0000000000..325f8d63f7 --- /dev/null +++ b/packages/router-core/src/load-server.ts @@ -0,0 +1,964 @@ +// Keep this filename free of a secondary extension so declaration generation +// can rewrite relative imports for both ESM and CJS. +import { isNotFound } from './not-found' +import { isRedirect, redirect } from './redirect' +import { rootRouteId } from './root' +import { loadRouteChunk } from './load-client' +import { waitForReason } from './await-signal' +import { + getLocationChangeInfo, + lifecycleEnd, + runRouteLifecycle, +} from './router' +import type { ParsedLocation } from './location' +import type { AnyRouteMatch } from './Matches' +import type { NotFoundError } from './not-found' +import type { + AnyRoute, + BeforeLoadContextOptions, + LoaderFnContext, + RouteContextOptions, + SsrContextOptions, +} from './route' +import type { AnyRedirect } from './redirect' +import type { AnyRouter, SSROption } from './router' + +declare const serverLanePhase: unique symbol + +type ServerLane<TPhase extends 'matched' | 'contextualized' | 'reduced'> = { + readonly [serverLanePhase]: TPhase + location: ParsedLocation + matches: Array<AnyRouteMatch> +} + +type MatchedLane = ServerLane<'matched'> + +type IndexedOutcome = [index: number, outcome: LoaderOutcome, boundary?: number] + +type ContextualizedLane = ServerLane<'contextualized'> & { + end: number + failure?: IndexedOutcome +} + +type ReducedLane = ServerLane<'reduced'> + +const SUCCESS = 0 +const ERROR = 1 +const NOT_FOUND = 2 +const REDIRECTED = 3 +const SKIPPED = 4 + +const MATCH_SETTLED_ABORT_REASON = Object.freeze({ + name: 'AbortError', + message: 'TanStack Router aborted this server match because it settled.', +}) + +const REDIRECT_ABORT_REASON = Object.freeze({ + name: 'AbortError', + message: 'TanStack Router aborted this server match because of a redirect.', +}) + +type LoaderOutcome = + | [typeof SUCCESS, data: unknown] + | [typeof ERROR, error: unknown] + | [typeof NOT_FOUND, error: NotFoundError] + | [typeof REDIRECTED, redirect: AnyRedirect] + | [typeof SKIPPED] + +type LoaderTask = { + index: number + outcome: Promise<LoaderOutcome> + match: Promise<AnyRouteMatch> +} + +export type ServerLoadResult = + | { + type: 'render' + status: 200 | 404 | 500 + matches: Array<AnyRouteMatch> + } + | { type: 'redirect'; redirect: AnyRedirect } + +function getRoute(router: AnyRouter, match: AnyRouteMatch): AnyRoute { + return router.routesById[match.routeId] +} + +function normalize(value: unknown, rejected: boolean): LoaderOutcome { + if (isRedirect(value)) { + return [REDIRECTED, value] + } + if (isNotFound(value)) { + return [NOT_FOUND, value] + } + if (rejected && typeof (value as any)?.then === 'function') { + value = new Error('A Promise was thrown', { cause: value }) + } + return rejected ? [ERROR, value] : [SUCCESS, value] +} + +function normalizeError( + router: AnyRouter, + lane: { location: ParsedLocation }, + route: AnyRoute, + cause: unknown, + signal?: AbortSignal, + notify = true, +): LoaderOutcome { + signal?.throwIfAborted() + let outcome = normalize(cause, true) + if (outcome[0] !== ERROR) { + return materializeRedirect(router, lane, route, outcome, signal, notify) + } + try { + route.options.onError?.(outcome[1]) + } catch (onErrorCause) { + outcome = normalize(onErrorCause, true) + } + signal?.throwIfAborted() + return materializeRedirect(router, lane, route, outcome, signal, notify) +} + +function materializeRedirect( + router: AnyRouter, + lane: { location: ParsedLocation }, + route: AnyRoute, + outcome: LoaderOutcome, + signal?: AbortSignal, + notify = true, +): LoaderOutcome { + if (outcome[0] !== REDIRECTED) { + return outcome + } + signal?.throwIfAborted() + try { + outcome[1].options._fromLocation = lane.location + router.resolveRedirect(outcome[1]) + signal?.throwIfAborted() + return outcome + } catch (cause) { + signal?.throwIfAborted() + return notify + ? normalizeError(router, lane, route, cause, signal, false) + : [ERROR, cause] + } +} + +function maybe<TValue>( + value: TValue, + cause: unknown, +): { status: 'success'; value: TValue } | { status: 'error'; error: unknown } { + if (cause !== undefined) { + return { status: 'error', error: cause } + } + return { status: 'success', value } +} + +function navigateFrom(router: AnyRouter, location: ParsedLocation) { + return (options: any) => + router.navigate({ + ...options, + _fromLocation: location, + }) +} + +function waitFor<T>(value: Promise<T>, signal?: AbortSignal): Promise<T> { + return signal ? waitForReason(value, signal) : value +} + +function resolveSsr( + router: AnyRouter, + lane: MatchedLane, + index: number, +): SSROption | Promise<SSROption> { + const match = lane.matches[index]! + const route = getRoute(router, match) + const parentSsr = lane.matches[index - 1]?.ssr + + if (router.isShell()) { + return route.id === rootRouteId + } + if (parentSsr === false) { + return false + } + + const inherit = (value: SSROption): SSROption => { + return value === true && parentSsr === 'data-only' ? 'data-only' : value + } + const defaultSsr = router.options.defaultSsr ?? true + const inheritedDefault = inherit(defaultSsr) + // A functional override can fail. Establish the inherited policy first so + // the selected error boundary retains the route's actual renderability. + match.ssr = inheritedDefault + const option = route.options.ssr + if (option === undefined) { + return inheritedDefault + } + if (typeof option !== 'function') { + return inherit(option) + } + + const context: SsrContextOptions<any, any, any> = { + search: maybe(match.search, match.searchError), + params: maybe(match.params, match.paramsError), + location: lane.location, + matches: lane.matches.map((candidate) => ({ + index: candidate.index, + pathname: candidate.pathname, + fullPath: candidate.fullPath, + staticData: candidate.staticData, + id: candidate.id, + routeId: candidate.routeId, + search: maybe(candidate.search, candidate.searchError), + params: maybe(candidate.params, candidate.paramsError), + ssr: candidate.ssr, + })), + } + try { + return Promise.resolve(option(context)).then((value) => + inherit(value ?? defaultSsr), + ) + } catch (cause) { + // Functional failures keep their asynchronous cancellation checkpoint. + return Promise.reject(cause) + } +} + +function stampNotFound( + match: AnyRouteMatch, + outcome: LoaderOutcome, +): LoaderOutcome { + if (outcome[0] === NOT_FOUND && !outcome[1].routeId) { + outcome[1].routeId = match.routeId + } + return outcome +} + +async function contextualize( + router: AnyRouter, + lane: MatchedLane, + signal?: AbortSignal, +): Promise<ContextualizedLane> { + const globalBoundary = lane.matches.findIndex((match) => match._notFound) + let end = globalBoundary < 0 ? lane.matches.length : globalBoundary + 1 + let failure: IndexedOutcome | undefined + let parentContext: Record<string, unknown> = { + ...(router.options.context ?? {}), + } + + for (let index = 0; index < end; index++) { + const match = lane.matches[index]! + const route = getRoute(router, match) + try { + const ssr = resolveSsr(router, lane, index) + // Functional policies are assimilated into a native Promise above. + match.ssr = ssr instanceof Promise ? await ssr : ssr + } catch (cause) { + signal?.throwIfAborted() + failure = [ + index, + stampNotFound( + match, + normalizeError(router, lane, route, cause, signal), + ), + ] + end = index + } + signal?.throwIfAborted() + if (failure?.[1][0] === REDIRECTED) { + break + } + + match.__beforeLoadContext = undefined + let context = parentContext + try { + let routeContext + if (route.options.context) { + const routeContextOptions: RouteContextOptions< + any, + any, + any, + any, + any + > = { + deps: match.loaderDeps, + params: match.params, + context: parentContext, + location: lane.location, + navigate: navigateFrom(router, lane.location), + buildLocation: router.buildLocation, + cause: match.cause, + abortController: match.abortController, + preload: false, + matches: lane.matches, + routeId: route.id, + } + routeContext = route.options.context(routeContextOptions) ?? undefined + } + context = { + ...parentContext, + ...routeContext, + } + match.context = context + } catch (cause) { + signal?.throwIfAborted() + if (!failure) { + failure = [ + index, + stampNotFound( + match, + normalizeError(router, lane, route, cause, signal), + ), + ] + } + end = index + break + } + signal?.throwIfAborted() + if (failure) { + break + } + const validationError = match.paramsError ?? match.searchError + if (validationError !== undefined) { + failure = [ + index, + stampNotFound( + match, + normalizeError(router, lane, route, validationError, signal), + ), + ] + end = index + break + } + signal?.throwIfAborted() + + if (match.ssr === false || !route.options.beforeLoad) { + parentContext = context + continue + } + + const abortController = match.abortController + const options: BeforeLoadContextOptions< + any, + any, + any, + any, + any, + any, + any, + any, + any + > = { + search: match.search, + abortController, + params: match.params, + preload: false, + context, + location: lane.location, + navigate: navigateFrom(router, lane.location), + buildLocation: router.buildLocation, + cause: match.cause, + matches: lane.matches, + routeId: route.id, + ...router.options.additionalContext, + } + + try { + const beforeLoadContext = await route.options.beforeLoad(options) + signal?.throwIfAborted() + const outcome = stampNotFound( + match, + materializeRedirect( + router, + lane, + route, + normalize(beforeLoadContext, false), + signal, + ), + ) + if (outcome[0] !== SUCCESS) { + failure = [index, outcome] + end = index + break + } + match.__beforeLoadContext = beforeLoadContext + match.context = { + ...context, + ...beforeLoadContext, + } + parentContext = match.context + } catch (cause) { + signal?.throwIfAborted() + failure = [ + index, + stampNotFound( + match, + normalizeError(router, lane, route, cause, signal), + ), + ] + end = index + break + } + } + + return { + location: lane.location, + matches: lane.matches, + end, + failure, + } as ContextualizedLane +} + +function getLoaderContext( + router: AnyRouter, + lane: ContextualizedLane, + match: AnyRouteMatch, + route: AnyRoute, + index: number, + tasks: Array<LoaderTask>, +): LoaderFnContext { + return { + params: match.params, + deps: match.loaderDeps, + preload: false, + parentMatchPromise: tasks[index - 1]?.match, + abortController: match.abortController, + context: match.context, + location: lane.location, + navigate: navigateFrom(router, lane.location), + cause: match.cause, + route, + ...router.options.additionalContext, + } +} + +function createLoaderTask( + router: AnyRouter, + lane: ContextualizedLane, + index: number, + tasks: Array<LoaderTask>, + signal?: AbortSignal, +): LoaderTask { + const match = lane.matches[index]! + const route = getRoute(router, match) + let outcome: Promise<LoaderOutcome> + + if (match.ssr === false) { + outcome = Promise.resolve<LoaderOutcome>([SKIPPED]) + } else { + const routeLoader = route.options.loader + const loader = + typeof routeLoader === 'function' ? routeLoader : routeLoader?.handler + if (!loader) { + outcome = Promise.resolve<LoaderOutcome>([SUCCESS, undefined]) + } else { + outcome = Promise.resolve() + .then(() => + loader(getLoaderContext(router, lane, match, route, index, tasks)), + ) + .then( + (result) => normalize(result, false), + (cause) => normalize(cause, true), + ) + .then((result): LoaderOutcome => { + if ( + signal?.aborted || + match.abortController.signal.reason === REDIRECT_ABORT_REASON + ) { + return [SKIPPED] + } + if (result[0] === ERROR) { + result = normalizeError(router, lane, route, result[1], signal) + } else { + result = materializeRedirect(router, lane, route, result, signal) + } + return stampNotFound(match, result) + }) + } + } + + const parentMatch = outcome.then((result) => { + const snapshot = { ...match } + if (result[0] === SUCCESS) { + snapshot.loaderData = result[1] + snapshot.status = 'success' + snapshot.error = undefined + snapshot.invalid = false + snapshot.isFetching = false + } else if (result[0] === ERROR) { + snapshot.status = 'error' + snapshot.error = result[1] + } else if (result[0] === NOT_FOUND) { + snapshot.status = 'notFound' + snapshot.error = result[1] + } + return snapshot + }) + + return { index, outcome, match: parentMatch } +} + +async function getNotFoundBoundary( + router: AnyRouter, + matches: Array<AnyRouteMatch>, + indexed: IndexedOutcome | undefined, + signal?: AbortSignal, + fallback = 0, +): Promise<number> { + const cause = indexed?.[1][1] as NotFoundError | undefined + let index = cause?.routeId + ? matches.findIndex((match) => match.routeId === cause.routeId) + : (indexed?.[0] ?? matches.length - 1) + if (index < 0) { + index = 0 + } + for (let candidate = index; candidate >= 0; candidate--) { + const route = getRoute(router, matches[candidate]!) + try { + const loading = loadRouteChunk(route, false) + if (loading) { + await loading + } + } catch { + signal?.throwIfAborted() + } + signal?.throwIfAborted() + if (route.options.notFoundComponent) { + return candidate + } + } + return cause?.routeId ? index : fallback +} + +function abortMatches( + matches: Array<AnyRouteMatch>, + start = 0, + reason: unknown = MATCH_SETTLED_ABORT_REASON, +): void { + for (let index = start; index < matches.length; index++) { + matches[index]!.abortController.abort(reason) + } +} + +async function applyFailure( + router: AnyRouter, + lane: ContextualizedLane, + indexed: IndexedOutcome | undefined, + signal?: AbortSignal, +): Promise<{ status: 200 | 404 | 500; boundary?: number; kind?: number }> { + if (!indexed) { + const boundary = lane.matches.findIndex((match) => match._notFound) + if (boundary >= 0) { + abortMatches(lane.matches, boundary + 1) + return { status: 404, boundary, kind: NOT_FOUND } + } + return { status: 200 } + } + + const [index, outcome] = indexed + if (outcome[0] === ERROR) { + const match = lane.matches[index]! + match._notFound = undefined + match.status = 'error' + match.error = outcome[1] + match.isFetching = false + abortMatches(lane.matches, index + 1) + return { status: 500, boundary: index, kind: ERROR } + } + + const boundary = + indexed[2] ?? + (await getNotFoundBoundary(router, lane.matches, indexed, signal)) + const match = lane.matches[boundary]! + const cause = outcome[1] as NotFoundError + cause.routeId = match.routeId + match._notFound = undefined + if (match.routeId === router.routeTree.id) { + match.status = 'success' + match._notFound = true + match.error = cause + } else { + match.status = 'notFound' + match.error = cause + } + match.isFetching = false + abortMatches(lane.matches, boundary + 1) + return { status: 404, boundary, kind: NOT_FOUND } +} + +async function loadNormalChunks( + router: AnyRouter, + lane: ContextualizedLane, + end: number, + signal?: AbortSignal, +): Promise<IndexedOutcome | undefined> { + const chunks: Array<IndexedOutcome | Promise<IndexedOutcome | undefined>> = [] + for (let index = 0; index < lane.matches.length; index++) { + const match = lane.matches[index]! + if (index >= end || match.ssr !== true || match.status !== 'success') { + continue + } + const route = getRoute(router, match) + try { + const loading = loadRouteChunk(route) + if (loading) { + const chunk = loading.then( + () => { + signal?.throwIfAborted() + return undefined + }, + (cause) => { + signal?.throwIfAborted() + return [ + index, + stampNotFound( + match, + normalizeError(router, lane, route, cause, signal), + ), + ] as IndexedOutcome + }, + ) + // Route-order reduction can return before later chunks settle. + void chunk.catch(() => {}) + chunks.push(chunk) + } + } catch (cause) { + signal?.throwIfAborted() + chunks.push([ + index, + stampNotFound( + match, + normalizeError(router, lane, route, cause, signal), + ), + ]) + } + } + for (const chunk of chunks) { + const indexed = Array.isArray(chunk) ? chunk : await chunk + if (indexed) { + return indexed + } + } + return undefined +} + +async function projectLane( + router: AnyRouter, + lane: ReducedLane, + signal?: AbortSignal, +): Promise<void> { + for (const match of lane.matches) { + const routeOptions = getRoute(router, match).options + if (routeOptions.head || routeOptions.scripts || routeOptions.headers) { + const context = { + ssr: router.options.ssr, + matches: lane.matches, + match, + params: match.params, + loaderData: match.loaderData, + } + try { + const [head, scripts, headers] = await Promise.all([ + routeOptions.head?.(context), + routeOptions.scripts?.(context), + routeOptions.headers?.(context), + ]) + signal?.throwIfAborted() + match.meta = head?.meta + match.links = head?.links + match.headScripts = head?.scripts + match.styles = head?.styles + match.scripts = scripts + match.headers = headers + } catch (cause) { + signal?.throwIfAborted() + console.error(cause) + } + } + if (match.ssr === false || match.status !== 'success' || match._notFound) { + break + } + } +} + +async function executeServerLane( + router: AnyRouter, + location: ParsedLocation, + matchedMatches: Array<AnyRouteMatch>, + signal?: AbortSignal, +): Promise<ServerLoadResult> { + const matched = { + location, + matches: matchedMatches.map((match) => ({ + ...match, + __beforeLoadContext: undefined, + context: {}, + isFetching: false, + abortController: new AbortController(), + })), + } as MatchedLane + const abortLane = () => + abortMatches( + matched.matches, + 0, + signal?.reason ?? MATCH_SETTLED_ABORT_REASON, + ) + if (signal?.aborted) { + abortLane() + signal.throwIfAborted() + } + signal?.addEventListener('abort', abortLane, { once: true }) + + try { + const plannedGlobalBoundary = matched.matches.findIndex( + (match) => match._notFound, + ) + if (router.options.notFoundMode !== 'root' && plannedGlobalBoundary >= 0) { + const boundary = await getNotFoundBoundary( + router, + matched.matches, + undefined, + signal, + plannedGlobalBoundary, + ) + if (boundary !== plannedGlobalBoundary) { + matched.matches[plannedGlobalBoundary]!._notFound = undefined + matched.matches[boundary]!._notFound = true + } + } + const lane = await contextualize(router, matched, signal) + signal?.throwIfAborted() + + let loaderEnd = lane.end + if (lane.failure?.[1][0] === REDIRECTED) { + loaderEnd = 0 + } else if (lane.failure?.[1][0] === NOT_FOUND) { + lane.failure[2] = await getNotFoundBoundary( + router, + lane.matches, + lane.failure, + signal, + ) + loaderEnd = Math.min(loaderEnd, lane.failure[2] + 1) + } + + const tasks: Array<LoaderTask> = [] + for (let index = 0; index < loaderEnd; index++) { + const task = createLoaderTask(router, lane, index, tasks, signal) + tasks.push(task) + } + + let loaderFailure: IndexedOutcome | undefined + let control = lane.failure?.[1][0] === REDIRECTED ? lane.failure : undefined + try { + await Promise.all( + tasks.map((task) => + task.outcome.then((loadedOutcome) => { + const match = lane.matches[task.index]! + const outcome = loadedOutcome + if (outcome[0] === SUCCESS) { + match.loaderData = outcome[1] + match.status = 'success' + match.error = undefined + match.invalid = false + match.isFetching = false + match.updatedAt = Date.now() + } else if (outcome[0] === REDIRECTED) { + control = [task.index, outcome] + throw control + } else { + // A selective-SSR skip must stay pending for hydration. Every + // settled server attempt is otherwise renderable unless + // reduction selects it as the lane's terminal failure. + if (match.ssr !== false) { + match.status = 'success' + match.error = undefined + match.invalid = true + match.isFetching = false + } + if (!loaderFailure && outcome[0] !== SKIPPED) { + loaderFailure = [task.index, outcome] + } + } + }), + ), + ) + } catch (cause) { + if (!Array.isArray(cause)) { + throw cause + } + control = cause as IndexedOutcome + } + signal?.throwIfAborted() + + if (control?.[1][0] === REDIRECTED) { + abortMatches(lane.matches, 0, REDIRECT_ABORT_REASON) + return { type: 'redirect', redirect: control[1][1] } + } + + let failure = lane.failure ?? loaderFailure + const plannedBoundary = lane.matches.findIndex((match) => match._notFound) + let readinessEnd: number + if (failure) { + const outcomeEnd = (failure[2] ??= + failure[1][0] === NOT_FOUND + ? await getNotFoundBoundary(router, lane.matches, failure, signal) + : failure[0]) + for (const task of tasks) { + if (task.index >= outcomeEnd) { + break + } + const outcome = await task.outcome + // Presence means a loader previously succeeded, even with `undefined`. + if ( + outcome[0] !== SUCCESS && + outcome[0] < REDIRECTED && + !('loaderData' in lane.matches[task.index]!) + ) { + failure = [task.index, outcome] + failure[2] = + outcome[0] === NOT_FOUND + ? await getNotFoundBoundary(router, lane.matches, failure, signal) + : task.index + break + } + } + readinessEnd = failure[2] + } else { + readinessEnd = plannedBoundary < 0 ? lane.matches.length : plannedBoundary + } + const requiredFailure = await loadNormalChunks( + router, + lane, + readinessEnd, + signal, + ) + signal?.throwIfAborted() + if (requiredFailure) { + if (requiredFailure[1][0] === REDIRECTED) { + abortMatches(lane.matches, 0, REDIRECT_ABORT_REASON) + return { type: 'redirect', redirect: requiredFailure[1][1] } + } + failure = requiredFailure + } + + const terminal = await applyFailure(router, lane, failure, signal) + if (terminal.boundary !== undefined) { + const match = lane.matches[terminal.boundary]! + if (match.ssr === true) { + const route = getRoute(router, match) + try { + if (terminal.kind === ERROR) { + await loadRouteChunk(route, 'errorComponent') + } else if (match._notFound) { + await Promise.all([ + loadRouteChunk(route), + loadRouteChunk(route, 'notFoundComponent'), + ]) + } else { + await loadRouteChunk(route, 'notFoundComponent') + } + } catch {} + signal?.throwIfAborted() + } + } + + signal?.throwIfAborted() + await projectLane( + router, + { + location: lane.location, + matches: lane.matches, + } as ReducedLane, + signal, + ) + signal?.throwIfAborted() + // Deferred loader work can outlive this lane, and the request signal above + // only covers one way a response ends. SSR cleanup covers them all: + // + // - client disconnected -> abort (work may be pending) + // - serialization or lifetime timeout -> abort (a deferred value hung) + // - body disposed server-side (HEAD strip, + // middleware replaced the response) -> abort (never delivered) + // - plain response / `hydrate: false`: the + // loader data was never dehydrated -> abort (never consumed) + // - stream completed: every dehydrated value + // already settled -> nothing left to abort + // + // `settled` is false in exactly the first four cases. + router.serverSsr?.onCleanup((settled) => { + if (!settled) { + abortLane() + } + }) + return { type: 'render', status: terminal.status, matches: lane.matches } + } finally { + signal?.removeEventListener('abort', abortLane) + } +} + +type ServerLoadOptions = NonNullable<Parameters<AnyRouter['load']>[0]> & { + _signal?: AbortSignal +} + +export async function loadServerRoute( + router: AnyRouter, + opts?: ServerLoadOptions, +): Promise<void> { + if (!opts?._skipLocationUpdate) { + router.updateLatestLocation() + } + const next = router.latestLocation + const previous = router._committed + const previousEnd = router._lifecycleEnd + let result: ServerLoadResult + try { + const canonical = router.buildLocation({ + to: next.pathname, + search: true, + params: true, + hash: true, + state: true, + _includeValidateSearch: true, + }) + if (next.publicHref !== canonical.publicHref) { + const href = canonical.publicHref || '/' + throw redirect({ href }) + } + + const fromLocation = router.stores.resolvedLocation.get() + const changeInfo = getLocationChangeInfo(next, fromLocation) + router.emit({ type: 'onBeforeNavigate', ...changeInfo }) + router.emit({ type: 'onBeforeLoad', ...changeInfo }) + opts?._signal?.throwIfAborted() + result = await waitFor( + executeServerLane(router, next, router.matchRoutes(next), opts?._signal), + opts?._signal, + ) + opts?._signal?.throwIfAborted() + } catch (cause) { + opts?._signal?.throwIfAborted() + if (!isRedirect(cause)) { + throw cause + } + cause.options._fromLocation = next + result = { type: 'redirect', redirect: router.resolveRedirect(cause) } + } + + router._serverResult = result + let nextEnd = 0 + router.batch(() => { + router.stores.location.set(next) + router.stores.status.set('idle') + if (result.type === 'render') { + router._committed = result.matches + nextEnd = router._lifecycleEnd = lifecycleEnd(result.matches) + router.stores.setMatches(result.matches) + router.stores.resolvedLocation.set(next) + } + }) + if (result.type === 'render') { + runRouteLifecycle(router, previous, result.matches, previousEnd, nextEnd) + } + router._commitPromise?.resolve() + router._commitPromise = undefined +} diff --git a/packages/router-core/src/location.ts b/packages/router-core/src/location.ts index 2e2c8042cf..956b88a80a 100644 --- a/packages/router-core/src/location.ts +++ b/packages/router-core/src/location.ts @@ -25,7 +25,8 @@ export interface ParsedLocation<TSearchObj extends AnySchema = {}> { */ state: ParsedHistoryState /** - * The hash of the location, including the leading hash character. + * The hash of the location, excluding the leading hash character. + * (e.g., '123' instead of '#123') */ hash: string /** @@ -44,8 +45,7 @@ export interface ParsedLocation<TSearchObj extends AnySchema = {}> { publicHref: string /** * @private - * @description The full URL of the location. - * @private + * @description Whether the publicHref is external (different origin from rewrite). */ - url: URL + external: boolean } diff --git a/packages/router-core/src/lru-cache.ts b/packages/router-core/src/lru-cache.ts deleted file mode 100644 index ee3ec7d7a0..0000000000 --- a/packages/router-core/src/lru-cache.ts +++ /dev/null @@ -1,74 +0,0 @@ -export type LRUCache<TKey, TValue> = { - get: (key: TKey) => TValue | undefined - set: (key: TKey, value: TValue) => void - clear: () => void -} - -export function createLRUCache<TKey, TValue>( - max: number, -): LRUCache<TKey, TValue> { - type Node = { prev?: Node; next?: Node; key: TKey; value: TValue } - const cache = new Map<TKey, Node>() - let oldest: Node | undefined - let newest: Node | undefined - - const touch = (entry: Node) => { - if (!entry.next) return - if (!entry.prev) { - entry.next.prev = undefined - oldest = entry.next - entry.next = undefined - if (newest) { - entry.prev = newest - newest.next = entry - } - } else { - entry.prev.next = entry.next - entry.next.prev = entry.prev - entry.next = undefined - if (newest) { - newest.next = entry - entry.prev = newest - } - } - newest = entry - } - - return { - get(key) { - const entry = cache.get(key) - if (!entry) return undefined - touch(entry) - return entry.value - }, - set(key, value) { - if (cache.size >= max && oldest) { - const toDelete = oldest - cache.delete(toDelete.key) - if (toDelete.next) { - oldest = toDelete.next - toDelete.next.prev = undefined - } - if (toDelete === newest) { - newest = undefined - } - } - const existing = cache.get(key) - if (existing) { - existing.value = value - touch(existing) - } else { - const entry: Node = { key, value, prev: newest } - if (newest) newest.next = entry - newest = entry - if (!oldest) oldest = entry - cache.set(key, entry) - } - }, - clear() { - cache.clear() - oldest = undefined - newest = undefined - }, - } -} diff --git a/packages/router-core/src/manifest.ts b/packages/router-core/src/manifest.ts index e789e00af4..b43f485236 100644 --- a/packages/router-core/src/manifest.ts +++ b/packages/router-core/src/manifest.ts @@ -1,32 +1,215 @@ -export type Manifest = { - routes: Record< - string, - { - filePath?: string - preloads?: Array<string> - assets?: Array<RouterManagedTag> +export type AssetCrossOrigin = 'anonymous' | 'use-credentials' +export type ScriptFormat = 'module' | 'iife' + +export const DEV_STYLES_ATTR = 'data-tanstack-router-dev-styles' + +export type AssetCrossOriginConfig = + | AssetCrossOrigin + | Partial<Record<'script' | 'stylesheet', AssetCrossOrigin>> + +export type ManifestAssetLink = + | string + | { + href: string + crossOrigin?: AssetCrossOrigin } - > + +export function getAssetCrossOrigin( + assetCrossOrigin: AssetCrossOriginConfig | undefined, + kind: 'script' | 'stylesheet', +): AssetCrossOrigin | undefined { + if (!assetCrossOrigin) { + return undefined + } + + if (typeof assetCrossOrigin === 'string') { + return assetCrossOrigin + } + + return assetCrossOrigin[kind] +} + +export function getManifestScriptFormat( + manifest: { scriptFormat?: ScriptFormat } | undefined, +): ScriptFormat { + return manifest?.scriptFormat ?? 'module' +} + +export function getScriptPreloadAttrs( + manifest: { scriptFormat?: ScriptFormat } | undefined, + link: ManifestAssetLink, + assetCrossOrigin?: AssetCrossOriginConfig, +): { + rel: 'modulepreload' | 'preload' + as?: 'script' + href: string + fetchPriority: 'low' + crossOrigin?: AssetCrossOrigin +} { + const preloadLink = resolveManifestAssetLink(link) + const crossOrigin = + getAssetCrossOrigin(assetCrossOrigin, 'script') ?? preloadLink.crossOrigin + + return { + ...(getManifestScriptFormat(manifest) === 'iife' + ? { rel: 'preload', as: 'script' } + : { rel: 'modulepreload' }), + href: preloadLink.href, + fetchPriority: 'low', + ...(crossOrigin ? { crossOrigin } : {}), + } +} + +export function resolveManifestAssetLink(link: ManifestAssetLink) { + if (typeof link === 'string') { + return { href: link, crossOrigin: undefined } + } + + return link +} + +export type Manifest = { + scriptFormat?: ScriptFormat + inlineStyle?: ManifestInlineCss + routes: Record<string, ManifestRoute> +} + +export type ServerManifest = { + scriptFormat?: ScriptFormat + inlineCss?: ServerManifestInlineCss + routes: Record<string, ServerManifestRoute> +} + +export type ServerManifestInlineCss = { + styles: Record<string, string> + templates?: Record<string, InlineCssTemplate> +} + +export type InlineCssTemplate = { + strings: Array<string> + urls: Array<string> +} + +export type ManifestRoute = { + filePath?: string + preloads?: Array<ManifestAssetLink> + scripts?: Array<ManifestScript> + css?: Array<ManifestCssLink> +} + +export type ServerManifestRoute = ManifestRoute + +export type ManifestRouteAssets = Pick< + ManifestRoute, + 'preloads' | 'scripts' | 'css' +> + +export type RouterManagedTitleTag = { + tag: 'title' + attrs?: Record<string, any> + children: string +} + +export type RouterManagedMetaTag = { + tag: 'meta' + attrs?: Record<string, any> + children?: never +} + +export type RouterManagedLinkTag = { + tag: 'link' + attrs?: Record<string, any> + children?: never +} + +export type RouterManagedScriptTag = { + tag: 'script' + attrs?: Record<string, any> + children?: string +} + +export type ManifestScript = Omit<RouterManagedScriptTag, 'tag'> + +export type RouterManagedStyleTag = { + tag: 'style' + attrs?: Record<string, any> + children?: string + inlineCss?: true } export type RouterManagedTag = - | { - tag: 'title' - attrs?: Record<string, any> - children: string + | RouterManagedTitleTag + | RouterManagedMetaTag + | RouterManagedLinkTag + | RouterManagedScriptTag + | RouterManagedStyleTag + +export function appendUniqueUserTags( + target: Array<RouterManagedTag>, + tags: Array<RouterManagedTag>, +) { + if (tags.length === 0) { + return + } + + if (tags.length === 1) { + target.push(tags[0]!) + return + } + + const seen = new Set<string>() + for (const tag of tags) { + const key = JSON.stringify(tag) + if (seen.has(key)) { + continue } + seen.add(key) + target.push(tag) + } +} + +export type ManifestCssLink = + | string | { - tag: 'meta' | 'link' - attrs?: Record<string, any> - children?: never - } - | { - tag: 'script' - attrs?: Record<string, any> - children?: string - } - | { - tag: 'style' - attrs?: Record<string, any> - children?: string + href: string + crossOrigin?: AssetCrossOrigin + [DEV_STYLES_ATTR]?: true } + +export type ManifestInlineCss = { + attrs?: Record<string, any> + children?: string +} + +export type RouterManagedInlineCssTag = RouterManagedStyleTag & { + inlineCss: true +} + +export function getStylesheetHref(asset: ManifestCssLink) { + return resolveManifestCssLink(asset).href +} + +export function resolveManifestCssLink(link: ManifestCssLink) { + if (typeof link === 'string') { + return { href: link, crossOrigin: undefined } + } + + return link +} + +export function createInlineCssStyleAsset(css: string): ManifestInlineCss { + return { + attrs: { + suppressHydrationWarning: true, + }, + children: css, + } +} + +export function createInlineCssPlaceholderAsset(): ManifestInlineCss { + return { + attrs: { + suppressHydrationWarning: true, + }, + } +} diff --git a/packages/router-core/src/new-process-route-tree.ts b/packages/router-core/src/new-process-route-tree.ts index 64abb685b6..fd63889df2 100644 --- a/packages/router-core/src/new-process-route-tree.ts +++ b/packages/router-core/src/new-process-route-tree.ts @@ -1,365 +1,319 @@ -import invariant from 'tiny-invariant' -import { createLRUCache } from './lru-cache' +import { invariant } from './invariant' +import { trimPathRight } from './path' +import { createSieveCache } from './sieve-cache' import { last } from './utils' -import type { LRUCache } from './lru-cache' +import type { SieveCache } from './sieve-cache' +import type { InterpolationSegment, RouteInterpolation } from './path' export const SEGMENT_TYPE_PATHNAME = 0 export const SEGMENT_TYPE_PARAM = 1 export const SEGMENT_TYPE_WILDCARD = 2 export const SEGMENT_TYPE_OPTIONAL_PARAM = 3 +const SEGMENT_TYPE_INDEX = 4 +const SEGMENT_TYPE_PATHLESS = 5 // only used in matching to represent pathless routes that need to carry more information +/** + * All the kinds of segments that can be present in a route path. + */ export type SegmentKind = | typeof SEGMENT_TYPE_PATHNAME | typeof SEGMENT_TYPE_PARAM | typeof SEGMENT_TYPE_WILDCARD | typeof SEGMENT_TYPE_OPTIONAL_PARAM -const PARAM_W_CURLY_BRACES_RE = - /^([^{]*)\{\$([a-zA-Z_$][a-zA-Z0-9_$]*)\}([^}]*)$/ // prefix{$paramName}suffix -const OPTIONAL_PARAM_W_CURLY_BRACES_RE = - /^([^{]*)\{-\$([a-zA-Z_$][a-zA-Z0-9_$]*)\}([^}]*)$/ // prefix{-$paramName}suffix -const WILDCARD_W_CURLY_BRACES_RE = /^([^{]*)\{\$\}([^}]*)$/ // prefix{$}suffix +/** + * All the kinds of segments that can be present in the segment tree. + */ +type ExtendedSegmentKind = + | SegmentKind + | typeof SEGMENT_TYPE_INDEX + | typeof SEGMENT_TYPE_PATHLESS -type ParsedSegment = Uint16Array & { - /** segment type (0 = pathname, 1 = param, 2 = wildcard, 3 = optional param) */ - 0: SegmentKind - /** index of the end of the prefix */ - 1: number - /** index of the start of the value */ - 2: number - /** index of the end of the value */ - 3: number - /** index of the start of the suffix */ - 4: number - /** index of the end of the segment */ - 5: number +export type DynamicPathSegment = [ + kind: Exclude<SegmentKind, typeof SEGMENT_TYPE_PATHNAME>, + key: string, + prefix: string, + /** Undefined marks a bare splat, which discards the remaining template. */ + suffix: string | undefined, +] + +export function getParamNames(data: RouteInterpolation): Array<string> { + const cached = data.names + if (cached) { + return cached + } + const keys: Array<string> = [] + for (const segment of data) { + if (typeof segment !== 'string') { + keys.push(segment[1 /* key */]) + } + } + return (data.names = keys) } -/** - * Populates the `output` array with the parsed representation of the given `segment` string. - * - * Usage: - * ```ts - * let output - * let cursor = 0 - * while (cursor < path.length) { - * output = parseSegment(path, cursor, output) - * const end = output[5] - * cursor = end + 1 - * ``` - * - * `output` is stored outside to avoid allocations during repeated calls. It doesn't need to be typed - * or initialized, it will be done automatically. - */ +/** Parse one segment for matching and retain the same record for interpolation. */ export function parseSegment( /** The full path string containing the segment. */ path: string, /** The starting index of the segment within the path. */ start: number, - /** A Uint16Array (length: 6) to populate with the parsed segment data. */ - output: Uint16Array = new Uint16Array(6), -): ParsedSegment { - const next = path.indexOf('/', start) - const end = next === -1 ? path.length : next - const part = path.substring(start, end) - - if (!part || !part.includes('$')) { - // early escape for static pathname - output[0] = SEGMENT_TYPE_PATHNAME - output[1] = start - output[2] = start - output[3] = end - output[4] = end - output[5] = end - return output as ParsedSegment - } - - // $ (wildcard) - if (part === '$') { - const total = path.length - output[0] = SEGMENT_TYPE_WILDCARD - output[1] = start - output[2] = start - output[3] = total - output[4] = total - output[5] = total - return output as ParsedSegment - } - - // $paramName + /** The next slash, or the length of the path. */ + end: number, +): InterpolationSegment { + const part = path.slice(start, end) if (part.charCodeAt(0) === 36) { - output[0] = SEGMENT_TYPE_PARAM - output[1] = start - output[2] = start + 1 // skip '$' - output[3] = end - output[4] = end - output[5] = end - return output as ParsedSegment + return part.length === 1 + ? [SEGMENT_TYPE_WILDCARD, '_splat', '', undefined] + : [SEGMENT_TYPE_PARAM, part.slice(1), '', ''] } - - const wildcardBracesMatch = part.match(WILDCARD_W_CURLY_BRACES_RE) - if (wildcardBracesMatch) { - const prefix = wildcardBracesMatch[1]! - const pLength = prefix.length - output[0] = SEGMENT_TYPE_WILDCARD - output[1] = start + pLength - output[2] = start + pLength + 1 // skip '{' - output[3] = start + pLength + 2 // '$' - output[4] = start + pLength + 3 // skip '}' - output[5] = path.length - return output as ParsedSegment + const open = part.indexOf('{') + if (open >= 0) { + const close = part.indexOf('}', open) + const optional = part.charCodeAt(open + 1) === 45 + const nameStart = open + (optional ? 3 : 2) + if ( + close >= 0 && + part.charCodeAt(nameStart - 1) === 36 && + (!optional || nameStart < close) + ) { + const key = part.slice(nameStart, close) + return [ + optional + ? SEGMENT_TYPE_OPTIONAL_PARAM + : key + ? SEGMENT_TYPE_PARAM + : SEGMENT_TYPE_WILDCARD, + key || '_splat', + part.slice(0, open), + path.slice(start + close + 1, key ? end : path.length), + ] + } } - - const optionalParamBracesMatch = part.match(OPTIONAL_PARAM_W_CURLY_BRACES_RE) - if (optionalParamBracesMatch) { - const prefix = optionalParamBracesMatch[1]! - const paramName = optionalParamBracesMatch[2]! - const suffix = optionalParamBracesMatch[3]! - const pLength = prefix.length - output[0] = SEGMENT_TYPE_OPTIONAL_PARAM - output[1] = start + pLength - output[2] = start + pLength + 3 // skip '{-$' - output[3] = start + pLength + 3 + paramName.length - output[4] = end - suffix.length - output[5] = end - return output as ParsedSegment - } - - const paramBracesMatch = part.match(PARAM_W_CURLY_BRACES_RE) - if (paramBracesMatch) { - const prefix = paramBracesMatch[1]! - const paramName = paramBracesMatch[2]! - const suffix = paramBracesMatch[3]! - const pLength = prefix.length - output[0] = SEGMENT_TYPE_PARAM - output[1] = start + pLength - output[2] = start + pLength + 2 // skip '{$' - output[3] = start + pLength + 2 + paramName.length - output[4] = end - suffix.length - output[5] = end - return output as ParsedSegment - } - - // fallback to static pathname (should never happen) - output[0] = SEGMENT_TYPE_PATHNAME - output[1] = start - output[2] = start - output[3] = end - output[4] = end - output[5] = end - return output as ParsedSegment + return part } -/** - * Recursively parses the segments of the given route tree and populates a segment trie. - * - * @param data A reusable Uint16Array for parsing segments. (non important, we're just avoiding allocations) - * @param route The current route to parse. - * @param start The starting index for parsing within the route's full path. - * @param node The current segment node in the trie to populate. - * @param onRoute Callback invoked for each route processed. - */ -function parseSegments<TRouteLike extends RouteLike>( +type ParsedRoute<T extends RouteLike> = [ + node: AnySegmentNode<T>, + cursor: number, + segments: RouteInterpolation | undefined, +] + +/** Compile a template, optionally attaching its new segments to the matching trie. */ +export function parseSegments<TRouteLike extends RouteLike>( + defaultCaseSensitive: boolean, + route: TRouteLike, + start: number, +): RouteInterpolation +export function parseSegments<TRouteLike extends RouteLike>( defaultCaseSensitive: boolean, - data: Uint16Array, route: TRouteLike, start: number, node: AnySegmentNode<TRouteLike>, - depth: number, - onRoute?: (route: TRouteLike) => void, -) { - onRoute?.(route) + dynamicListsToSort?: Array<Array<DynamicSegmentNode<TRouteLike>>>, + parentInterpolation?: RouteInterpolation, +): ParsedRoute<TRouteLike> +export function parseSegments<TRouteLike extends RouteLike>( + defaultCaseSensitive: boolean, + route: TRouteLike, + start: number, + node?: AnySegmentNode<TRouteLike>, + /** Each dynamic sibling list is recorded once, when it first needs sorting. */ + dynamicListsToSort?: Array<Array<DynamicSegmentNode<TRouteLike>>>, + parentInterpolation?: RouteInterpolation, +): RouteInterpolation | ParsedRoute<TRouteLike> { let cursor = start - { - const path = route.fullPath ?? route.from - const length = path.length - const caseSensitive = route.options?.caseSensitive ?? defaultCaseSensitive - while (cursor < length) { - const segment = parseSegment(path, cursor, data) - let nextNode: AnySegmentNode<TRouteLike> - const start = cursor - const end = segment[5] - cursor = end + 1 - depth++ - const kind = segment[0] - switch (kind) { - case SEGMENT_TYPE_PATHNAME: { - const value = path.substring(segment[2], segment[3]) - if (caseSensitive) { - const existingNode = node.static?.get(value) - if (existingNode) { - nextNode = existingNode - } else { - node.static ??= new Map() - const next = createStaticNode<TRouteLike>( - route.fullPath ?? route.from, - ) - next.parent = node - next.depth = depth - nextNode = next - node.static.set(value, next) - } - } else { - const name = value.toLowerCase() - const existingNode = node.staticInsensitive?.get(name) - if (existingNode) { - nextNode = existingNode - } else { - node.staticInsensitive ??= new Map() - const next = createStaticNode<TRouteLike>( - route.fullPath ?? route.from, - ) - next.parent = node - next.depth = depth - nextNode = next - node.staticInsensitive.set(name, next) - } - } - break - } - case SEGMENT_TYPE_PARAM: { - const prefix_raw = path.substring(start, segment[1]) - const suffix_raw = path.substring(segment[4], end) - const actuallyCaseSensitive = - caseSensitive && !!(prefix_raw || suffix_raw) - const prefix = !prefix_raw - ? undefined - : actuallyCaseSensitive - ? prefix_raw - : prefix_raw.toLowerCase() - const suffix = !suffix_raw - ? undefined - : actuallyCaseSensitive - ? suffix_raw - : suffix_raw.toLowerCase() - const existingNode = node.dynamic?.find( - (s) => - s.caseSensitive === actuallyCaseSensitive && - s.prefix === prefix && - s.suffix === suffix, - ) - if (existingNode) { - nextNode = existingNode - } else { - const next = createDynamicNode<TRouteLike>( - SEGMENT_TYPE_PARAM, - route.fullPath ?? route.from, - actuallyCaseSensitive, - prefix, - suffix, - ) - nextNode = next - next.depth = depth - next.parent = node - node.dynamic ??= [] - node.dynamic.push(next) - } - break - } - case SEGMENT_TYPE_OPTIONAL_PARAM: { - const prefix_raw = path.substring(start, segment[1]) - const suffix_raw = path.substring(segment[4], end) - const actuallyCaseSensitive = - caseSensitive && !!(prefix_raw || suffix_raw) - const prefix = !prefix_raw - ? undefined - : actuallyCaseSensitive - ? prefix_raw - : prefix_raw.toLowerCase() - const suffix = !suffix_raw - ? undefined - : actuallyCaseSensitive - ? suffix_raw - : suffix_raw.toLowerCase() - const existingNode = node.optional?.find( - (s) => - s.caseSensitive === actuallyCaseSensitive && - s.prefix === prefix && - s.suffix === suffix, - ) - if (existingNode) { - nextNode = existingNode - } else { - const next = createDynamicNode<TRouteLike>( - SEGMENT_TYPE_OPTIONAL_PARAM, - route.fullPath ?? route.from, - actuallyCaseSensitive, - prefix, - suffix, - ) - nextNode = next - next.parent = node - next.depth = depth - node.optional ??= [] - node.optional.push(next) - } - break - } - case SEGMENT_TYPE_WILDCARD: { - const prefix_raw = path.substring(start, segment[1]) - const suffix_raw = path.substring(segment[4], end) - const actuallyCaseSensitive = - caseSensitive && !!(prefix_raw || suffix_raw) - const prefix = !prefix_raw - ? undefined - : actuallyCaseSensitive - ? prefix_raw - : prefix_raw.toLowerCase() - const suffix = !suffix_raw - ? undefined - : actuallyCaseSensitive - ? suffix_raw - : suffix_raw.toLowerCase() - const next = createDynamicNode<TRouteLike>( - SEGMENT_TYPE_WILDCARD, - route.fullPath ?? route.from, - actuallyCaseSensitive, - prefix, - suffix, - ) - nextNode = next - next.parent = node - next.depth = depth - node.wildcard ??= [] - node.wildcard.push(next) - } - } - node = nextNode - } - if ((route.path || !route.children) && !route.isRoot) { - const isIndex = path.endsWith('/') - // we cannot fuzzy match an index route, - // but if there is *also* a layout route at this path, save it as notFound - // we can use it when fuzzy matching to display the NotFound component in the layout route - if (!isIndex) node.notFound = route - // does the new route take precedence over an existing one? - // yes if previous is not an index route and new one is an index route - if (!node.route || (!node.isIndex && isIndex)) { - node.route = route - // when replacing, replace all attributes that are route-specific (`fullPath` only at the moment) - node.fullPath = route.fullPath ?? route.from - } - node.isIndex ||= isIndex + const path = route.fullPath ?? route.from + const options = route.options + const length = path.length + const literalEnd = path.endsWith('/') ? length - 1 : length + const caseSensitive = options?.caseSensitive ?? defaultCaseSensitive + const parseParams = options?.params?.parse ?? options?.parseParams + let interpolation: Array<InterpolationSegment> | undefined + let literalStart = parentInterpolation ? start - 1 : 0 + if (!node || path.includes('$')) { + interpolation = parentInterpolation?.slice() ?? [] + const tail = last(interpolation) + if ( + tail && + typeof tail !== 'string' && + tail[0 /* kind */] === SEGMENT_TYPE_WILDCARD + ) { + // A parent's wildcard consumes the child's template too. + // `start` follows that entire template, including its trailing slash. + interpolation[interpolation.length - 1] = [ + tail[0 /* kind */], + tail[1 /* key */], + tail[2 /* prefix */], + tail[3 /* suffix */] === undefined + ? undefined + : tail[3 /* suffix */] + + path.substring( + start - (path[start - 2] === '/' ? 2 : 1), + literalEnd, + ), + ] + literalStart = length } } - if (route.children) - for (const child of route.children) { - parseSegments( - defaultCaseSensitive, - data, - child as TRouteLike, - cursor, - node, - depth, - onRoute, - ) + while (cursor < length) { + const start = cursor + const next = path.indexOf('/', start) + let end = next === -1 ? length : next + const segment = parseSegment(path, start, end) + cursor = end + 1 + let nextNode: AnySegmentNode<TRouteLike> + if (typeof segment === 'string') { + if (!node) { + continue + } + let name = segment + let staticChildren: Map<string, StaticSegmentNode<TRouteLike>> + if (caseSensitive) { + staticChildren = node.static ??= new Map() + } else { + name = segment.toLowerCase() + staticChildren = node.staticInsensitive ??= new Map() + } + const existingNode = staticChildren.get(name) + if (existingNode) { + nextNode = existingNode + } else { + const next = createSegmentNode(node) + nextNode = next + staticChildren.set(name, next) + } + } else { + const kind = segment[0 /* kind */] + let prefix = segment[2 /* prefix */] + let suffix = segment[3 /* suffix */] ?? '' + if (kind === SEGMENT_TYPE_WILDCARD) { + end = length + cursor = end + 1 + } + if (interpolation && literalStart < end) { + // Retain original spelling before matcher case folding. + if (literalStart < start - 1) { + interpolation.push(path.slice(literalStart, start - 1)) + } + segment[2 /* prefix */] = '/' + prefix + if ( + kind === SEGMENT_TYPE_WILDCARD && + segment[3 /* suffix */] !== undefined && + literalEnd < length + ) { + segment[3 /* suffix */] = suffix.slice(0, -1) + } + interpolation.push(segment) + literalStart = end + } + if (!node) { + continue + } + const actuallyCaseSensitive = caseSensitive && !!(prefix || suffix) + if (!caseSensitive) { + prefix = prefix.toLowerCase() + suffix = suffix.toLowerCase() + } + const siblings = + kind === SEGMENT_TYPE_PARAM + ? (node.dynamic ??= []) + : kind === SEGMENT_TYPE_OPTIONAL_PARAM + ? (node.optional ??= []) + : (node.wildcard ??= []) + const existingNode = + // Keep wildcard aliases as separate match candidates, even when + // they have the same shape and no parser. + kind !== SEGMENT_TYPE_WILDCARD && + !parseParams && + siblings.find( + (s) => + !s.parse && + s.caseSensitive === actuallyCaseSensitive && + s.prefix === prefix && + s.suffix === suffix, + ) + if (existingNode) { + nextNode = existingNode + } else { + const next = createSegmentNode( + node, + kind, + actuallyCaseSensitive, + prefix, + suffix, + ) + nextNode = next + siblings.push(next) + if (siblings.length === 2) { + dynamicListsToSort?.push(siblings) + } + } } + node = nextNode + } + + if (interpolation && literalStart < literalEnd) { + interpolation.push(path.slice(literalStart, literalEnd)) + } + // Discard push()'s spare capacity before retaining this array on both owners. + const segmentData = interpolation?.slice() + if (!node) { + return segmentData! + } + + // create pathless node + if ( + parseParams && + route.children && + !route.isRoot && + route.id && + route.id.charCodeAt(route.id.lastIndexOf('/') + 1) === 95 /* '_' */ + ) { + const pathlessNode = createSegmentNode(node, SEGMENT_TYPE_PATHLESS) + ;(node.pathless ??= []).push(pathlessNode) + node = pathlessNode + } + + const isLeaf = (route.path || !route.children) && !route.isRoot + // create index node + if (isLeaf && literalEnd < length) { + const indexNode = createSegmentNode(node, SEGMENT_TYPE_INDEX) + node.index = indexNode + node = indexNode + } + + node.parse = parseParams ?? null + node.priority = options?.params?.priority ?? 0 + // A shared candidate keeps the original names of its first terminal route. + if (!node.route) { + node.data = segmentData + if (isLeaf) { + node.route = route + } + } + return [node, cursor, segmentData] } function sortDynamic( - a: { prefix?: string; suffix?: string; caseSensitive: boolean }, - b: { prefix?: string; suffix?: string; caseSensitive: boolean }, + a: { + prefix: string + suffix: string + caseSensitive: boolean + parse: null | ((params: Record<string, string>) => unknown) + priority: number + }, + b: { + prefix: string + suffix: string + caseSensitive: boolean + parse: null | ((params: Record<string, string>) => unknown) + priority: number + }, ) { + if (a.parse && !b.parse) return -1 + if (!a.parse && b.parse) return 1 + if (a.parse && b.parse && (a.priority || b.priority)) + return b.priority - a.priority if (a.prefix && b.prefix && a.prefix !== b.prefix) { if (a.prefix.startsWith(b.prefix)) return -1 if (b.prefix.startsWith(a.prefix)) return 1 @@ -375,88 +329,46 @@ function sortDynamic( if (a.caseSensitive && !b.caseSensitive) return -1 if (!a.caseSensitive && b.caseSensitive) return 1 - // we don't need a tiebreaker here - // at this point the 2 nodes cannot conflict during matching + // Equal specificity preserves route declaration order through stable sort. return 0 } -function sortTreeNodes(node: SegmentNode<RouteLike>) { - if (node.static) { - for (const child of node.static.values()) { - sortTreeNodes(child) - } - } - if (node.staticInsensitive) { - for (const child of node.staticInsensitive.values()) { - sortTreeNodes(child) - } - } - if (node.dynamic?.length) { - node.dynamic.sort(sortDynamic) - for (const child of node.dynamic) { - sortTreeNodes(child) - } - } - if (node.optional?.length) { - node.optional.sort(sortDynamic) - for (const child of node.optional) { - sortTreeNodes(child) - } - } - if (node.wildcard?.length) { - node.wildcard.sort(sortDynamic) - for (const child of node.wildcard) { - sortTreeNodes(child) - } - } -} - -function createStaticNode<T extends RouteLike>( - fullPath: string, -): StaticSegmentNode<T> { - return { - kind: SEGMENT_TYPE_PATHNAME, - depth: 0, - static: null, - staticInsensitive: null, - dynamic: null, - optional: null, - wildcard: null, - route: null, - fullPath, - parent: null, - isIndex: false, - notFound: null, - } -} - -/** - * Keys must be declared in the same order as in `SegmentNode` type, - * to ensure they are represented as the same object class in the engine. - */ -function createDynamicNode<T extends RouteLike>( +function createSegmentNode<T extends RouteLike>( + parent?: AnySegmentNode<T>, + kind?: StaticSegmentNode<T>['kind'], +): StaticSegmentNode<T> +function createSegmentNode<T extends RouteLike>( + parent: AnySegmentNode<T>, kind: | typeof SEGMENT_TYPE_PARAM | typeof SEGMENT_TYPE_WILDCARD | typeof SEGMENT_TYPE_OPTIONAL_PARAM, - fullPath: string, caseSensitive: boolean, + prefix: string, + suffix: string, +): DynamicSegmentNode<T> +function createSegmentNode<T extends RouteLike>( + parent?: AnySegmentNode<T>, + kind: ExtendedSegmentKind = SEGMENT_TYPE_PATHNAME, + caseSensitive?: boolean, prefix?: string, suffix?: string, -): DynamicSegmentNode<T> { +): SegmentNode<T> { return { kind, - depth: 0, + depth: parent ? parent.depth + 1 : 0, + pathless: null, + index: null, static: null, staticInsensitive: null, dynamic: null, optional: null, wildcard: null, route: null, - fullPath, - parent: null, - isIndex: false, - notFound: null, + data: undefined, + parent, + parse: null, + priority: 0, caseSensitive, prefix, suffix, @@ -464,7 +376,10 @@ function createDynamicNode<T extends RouteLike>( } type StaticSegmentNode<T extends RouteLike> = SegmentNode<T> & { - kind: typeof SEGMENT_TYPE_PATHNAME + kind: + | typeof SEGMENT_TYPE_PATHNAME + | typeof SEGMENT_TYPE_PATHLESS + | typeof SEGMENT_TYPE_INDEX } type DynamicSegmentNode<T extends RouteLike> = SegmentNode<T> & { @@ -472,8 +387,8 @@ type DynamicSegmentNode<T extends RouteLike> = SegmentNode<T> & { | typeof SEGMENT_TYPE_PARAM | typeof SEGMENT_TYPE_WILDCARD | typeof SEGMENT_TYPE_OPTIONAL_PARAM - prefix?: string - suffix?: string + prefix: string + suffix: string caseSensitive: boolean } @@ -482,12 +397,20 @@ type AnySegmentNode<T extends RouteLike> = | DynamicSegmentNode<T> type SegmentNode<T extends RouteLike> = { - kind: SegmentKind + kind: ExtendedSegmentKind + prefix?: string + suffix?: string + caseSensitive?: boolean - /** Static segments (highest priority) */ + pathless: Array<StaticSegmentNode<T>> | null + + /** Exact index segment (highest priority) */ + index: StaticSegmentNode<T> | null + + /** Static segments (2nd priority) */ static: Map<string, StaticSegmentNode<T>> | null - /** Case insensitive static segments (second highest priority) */ + /** Case insensitive static segments (3rd highest priority) */ staticInsensitive: Map<string, StaticSegmentNode<T>> | null /** Dynamic segments ($param) */ @@ -502,27 +425,34 @@ type SegmentNode<T extends RouteLike> = { /** Terminal route (if this path can end here) */ route: T | null - /** The full path for this segment node (will only be valid on leaf nodes) */ - fullPath: string + /** Original template data for this candidate or parse gate. */ + data: RouteInterpolation | undefined - parent: AnySegmentNode<T> | null + parent: AnySegmentNode<T> | undefined depth: number - /** is it an index route (trailing / path), only valid for nodes with a `route` */ - isIndex: boolean + /** route.options.params.parse function, set on the last node of the route */ + parse: null | ((params: Record<string, string>) => unknown) - /** Same as `route`, but only present if both an "index route" and a "layout route" exist at this path */ - notFound: T | null + /** route.options.params.priority ?? 0 */ + priority: number } type RouteLike = { + _interpolation?: RouteInterpolation + id?: string path?: string // relative path from the parent, children?: Array<RouteLike> // child routes, parentRoute?: RouteLike // parent route, isRoot?: boolean options?: { caseSensitive?: boolean + parseParams?: (params: Record<string, string>) => unknown + params?: { + parse?: (params: Record<string, string>) => unknown + priority?: number + } } } & // router tree @@ -541,11 +471,11 @@ export type ProcessedTree< /** a mini route tree generated from the flat `routeMasks` list */ masksTree: AnySegmentNode<TFlat> | null /** @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree */ - singleCache: LRUCache<string, AnySegmentNode<TSingle>> + singleCache: SieveCache<string, AnySegmentNode<TSingle>> /** a cache of route matches from the `segmentTree` */ - matchCache: LRUCache<string, RouteMatch<TTree> | null> + matchCache: SieveCache<string, RouteMatch<TTree> | null> /** a cache of route matches from the `masksTree` */ - flatCache: LRUCache<string, ReturnType<typeof findMatch<TFlat>>> | null + flatCache: SieveCache<string, ReturnType<typeof findMatch<TFlat>>> | null } export function processRouteMasks< @@ -554,14 +484,36 @@ export function processRouteMasks< routeList: Array<TRouteLike>, processedTree: ProcessedTree<any, TRouteLike, any>, ) { - const segmentTree = createStaticNode<TRouteLike>('/') - const data = new Uint16Array(6) + const segmentTree = createSegmentNode<TRouteLike>() + const dynamicListsToSort: Array<Array<DynamicSegmentNode<TRouteLike>>> = [] + function visit( + route: TRouteLike, + start: number, + parentNode: AnySegmentNode<TRouteLike>, + parentInterpolation?: RouteInterpolation, + ) { + const [node, cursor, segments] = parseSegments( + false, + route, + start, + parentNode, + dynamicListsToSort, + parentInterpolation, + ) + if (route.children) { + for (const child of route.children) { + visit(child as TRouteLike, cursor, node, segments) + } + } + } for (const route of routeList) { - parseSegments(false, data, route, 1, segmentTree, 0) + visit(route, 1, segmentTree) + } + for (const nodes of dynamicListsToSort) { + nodes.sort(sortDynamic) } - sortTreeNodes(segmentTree) processedTree.masksTree = segmentTree - processedTree.flatCache = createLRUCache< + processedTree.flatCache = createSieveCache< string, ReturnType<typeof findMatch<TRouteLike>> >(1000) @@ -578,7 +530,7 @@ export function findFlatMatch<T extends Extract<RouteLike, { from: string }>>( ) { path ||= '/' const cached = processedTree.flatCache!.get(path) - if (cached) return cached + if (cached !== undefined) return cached const result = findMatch(path, processedTree.masksTree!) processedTree.flatCache!.set(path, result) return result @@ -601,9 +553,8 @@ export function findSingleMatch( if (!tree) { // single flat routes (router.matchRoute) are not eagerly processed, // if we haven't seen this route before, process it now - tree = createStaticNode<{ from: string }>('/') - const data = new Uint16Array(6) - parseSegments(caseSensitive, data, { from }, 1, tree, 0) + tree = createSegmentNode<{ from: string }>() + parseSegments(caseSensitive, { from }, 1, tree) processedTree.singleCache.set(key, tree) } return findMatch(path, tree, fuzzy) @@ -611,7 +562,7 @@ export function findSingleMatch( type RouteMatch<T extends Extract<RouteLike, { fullPath: string }>> = { route: T - params: Record<string, string> + rawParams: Record<string, string> branch: ReadonlyArray<T> } @@ -629,19 +580,36 @@ export function findRouteMatch< const cached = processedTree.matchCache.get(key) if (cached !== undefined) return cached path ||= '/' - const result = findMatch( - path, - processedTree.segmentTree, - fuzzy, - ) as RouteMatch<T> | null + let result: RouteMatch<T> | null + + try { + result = findMatch( + path, + processedTree.segmentTree, + fuzzy, + ) as RouteMatch<T> | null + } catch (err) { + if (err instanceof URIError) { + result = null + } else { + throw err + } + } + if (result) result.branch = buildRouteBranch(result.route) processedTree.matchCache.set(key, result) return result } -/** Trim trailing slashes (except preserving root '/'). */ -export function trimPathRight(path: string) { - return path === '/' ? path : path.replace(/\/{1,}$/, '') +export interface ProcessRouteTreeResult< + TRouteLike extends Extract<RouteLike, { fullPath: string }> & { id: string }, +> { + /** Should be considered a black box, needs to be provided to all matching functions in this module. */ + processedTree: ProcessedTree<TRouteLike, any, any> + /** A lookup map of routes by their unique IDs. */ + routesById: Record<string, TRouteLike> + /** A lookup map of routes by their trimmed full paths. */ + routesByPath: Record<string, TRouteLike> } /** @@ -649,51 +617,71 @@ export function trimPathRight(path: string) { * Also builds lookup maps for routes by ID and by trimmed full path. */ export function processRouteTree< - TRouteLike extends Extract<RouteLike, { fullPath: string }> & { id: string }, + TRouteLike extends Extract<RouteLike, { fullPath: string }> & { + id: string + init: (originalIndex: number) => void + }, >( /** The root of the route tree to process. */ routeTree: TRouteLike, /** Whether matching should be case sensitive by default (overridden by individual route options). */ caseSensitive: boolean = false, - /** Optional callback invoked for each route during processing. */ - initRoute?: (route: TRouteLike, index: number) => void, -): { - /** Should be considered a black box, needs to be provided to all matching functions in this module. */ - processedTree: ProcessedTree<TRouteLike, any, any> - /** A lookup map of routes by their unique IDs. */ - routesById: Record<string, TRouteLike> - /** A lookup map of routes by their trimmed full paths. */ - routesByPath: Record<string, TRouteLike> -} { - const segmentTree = createStaticNode<TRouteLike>(routeTree.fullPath) - const data = new Uint16Array(6) +): ProcessRouteTreeResult<TRouteLike> { + const segmentTree = createSegmentNode<TRouteLike>() + const dynamicListsToSort: Array<Array<DynamicSegmentNode<TRouteLike>>> = [] const routesById = {} as Record<string, TRouteLike> const routesByPath = {} as Record<string, TRouteLike> let index = 0 - parseSegments(caseSensitive, data, routeTree, 1, segmentTree, 0, (route) => { - initRoute?.(route, index) + function visit( + route: TRouteLike, + start: number, + parentNode: AnySegmentNode<TRouteLike>, + parentInterpolation?: RouteInterpolation, + ) { + route.init(index) - invariant( - !(route.id in routesById), - `Duplicate routes found with id: ${String(route.id)}`, - ) + if (route.id in routesById) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + `Invariant failed: Duplicate routes found with id: ${String(route.id)}`, + ) + } + + invariant() + } routesById[route.id] = route - if (index !== 0 && route.path) { const trimmedFullPath = trimPathRight(route.fullPath) if (!routesByPath[trimmedFullPath] || route.fullPath.endsWith('/')) { routesByPath[trimmedFullPath] = route } } - index++ - }) - sortTreeNodes(segmentTree) + + const [node, cursor, segments] = parseSegments( + caseSensitive, + route, + start, + parentNode, + dynamicListsToSort, + parentInterpolation, + ) + route._interpolation = segments + if (route.children) { + for (const child of route.children) { + visit(child as TRouteLike, cursor, node, segments) + } + } + } + visit(routeTree, 1, segmentTree) + for (const nodes of dynamicListsToSort) { + nodes.sort(sortDynamic) + } const processedTree: ProcessedTree<TRouteLike, any, any> = { segmentTree, - singleCache: createLRUCache<string, AnySegmentNode<any>>(1000), - matchCache: createLRUCache<string, RouteMatch<TRouteLike> | null>(1000), + singleCache: createSieveCache<string, AnySegmentNode<any>>(1000), + matchCache: createSieveCache<string, RouteMatch<TRouteLike> | null>(1000), flatCache: null, masksTree: null, } @@ -708,93 +696,121 @@ function findMatch<T extends RouteLike>( path: string, segmentTree: AnySegmentNode<T>, fuzzy = false, -): { route: T; params: Record<string, string> } | null { +): { + route: T + /** + * The raw (unparsed) params extracted from the path. + * This will be the exhaustive list of all params defined in the route's path. + */ + rawParams: Record<string, string> +} | null { const parts = path.split('/') const leaf = getNodeMatch(path, parts, segmentTree, fuzzy) if (!leaf) return null - const params = extractParams(path, parts, leaf) - const isFuzzyMatch = '**' in leaf - if (isFuzzyMatch) params['**'] = leaf['**'] - const route = isFuzzyMatch - ? (leaf.node.notFound ?? leaf.node.route!) - : leaf.node.route! + const [rawParams] = extractParams(path, parts, leaf) return { - route, - params, + route: leaf.node.route!, + rawParams, } } +type ParamExtractionState = { + part: number + node: number + path: number + param: number +} + +/** + * This function is "resumable": + * - the `leaf` input can contain `extract` and `rawParams` properties from a previous `extractParams` call + * - the returned `state` can be passed back as `extract` in a future call to continue extracting params from where we left off + * + * Inputs are *not* mutated. + */ function extractParams<T extends RouteLike>( path: string, parts: Array<string>, - leaf: { node: AnySegmentNode<T>; skipped: number }, -) { + leaf: { + node: AnySegmentNode<T> + skipped: number + extract?: ParamExtractionState + rawParams?: Record<string, string> + }, +): [rawParams: Record<string, string>, state: ParamExtractionState] { const list = buildBranch(leaf.node) - let nodeParts: Array<string> | null = null - const params: Record<string, string> = {} - for ( - let partIndex = 0, nodeIndex = 0, pathIndex = 0; - nodeIndex < list.length; - partIndex++, nodeIndex++, pathIndex++ - ) { + const names = leaf.node.data && getParamNames(leaf.node.data) + const rawParams: Record<string, string> = Object.create(null) + /** which segment of the path we're currently processing */ + let partIndex = leaf.extract?.part ?? 0 + /** which node of the route tree branch we're currently processing */ + let nodeIndex = leaf.extract?.node ?? 0 + /** index of the 1st character of the segment we're processing in the path string */ + let pathIndex = leaf.extract?.path ?? 0 + /** Next original parameter name, independent of pathless/static nodes. */ + let paramIndex = leaf.extract?.param ?? 0 + for (; nodeIndex < list.length; partIndex++, nodeIndex++, pathIndex++) { const node = list[nodeIndex]! + // index nodes are terminating nodes, nothing to extract, just leave + if (node.kind === SEGMENT_TYPE_INDEX) break + // pathless nodes do not consume a path segment + if (node.kind === SEGMENT_TYPE_PATHLESS) { + partIndex-- + pathIndex-- + continue + } const part = parts[partIndex] const currentPathIndex = pathIndex if (part) pathIndex += part.length - if (node.kind === SEGMENT_TYPE_PARAM) { - nodeParts ??= leaf.node.fullPath.split('/') - const nodePart = nodeParts[nodeIndex]! - const preLength = node.prefix?.length ?? 0 - // we can't rely on the presence of prefix/suffix to know whether it's curly-braced or not, because `/{$param}/` is valid, but has no prefix/suffix - const isCurlyBraced = nodePart.charCodeAt(preLength) === 123 // '{' - // param name is extracted at match-time so that tree nodes that are identical except for param name can share the same node - if (isCurlyBraced) { - const sufLength = node.suffix?.length ?? 0 - const name = nodePart.substring( - preLength + 2, - nodePart.length - sufLength - 1, - ) - const value = part!.substring(preLength, part!.length - sufLength) - params[name] = decodeURIComponent(value) - } else { - const name = nodePart.substring(1) - params[name] = decodeURIComponent(part!) - } - } else if (node.kind === SEGMENT_TYPE_OPTIONAL_PARAM) { - if (leaf.skipped & (1 << nodeIndex)) { + if ( + node.kind === SEGMENT_TYPE_PARAM || + node.kind === SEGMENT_TYPE_OPTIONAL_PARAM + ) { + const name = names![paramIndex++]! + if ( + node.kind === SEGMENT_TYPE_OPTIONAL_PARAM && + leaf.skipped & (1 << nodeIndex) + ) { partIndex-- // stay on the same part + pathIndex = currentPathIndex - 1 // undo pathIndex advancement; -1 to account for loop increment continue } - nodeParts ??= leaf.node.fullPath.split('/') - const nodePart = nodeParts[nodeIndex]! - const preLength = node.prefix?.length ?? 0 - const sufLength = node.suffix?.length ?? 0 - const name = nodePart.substring( - preLength + 3, - nodePart.length - sufLength - 1, - ) const value = node.suffix || node.prefix - ? part!.substring(preLength, part!.length - sufLength) - : part - if (value) params[name] = decodeURIComponent(value) + ? part!.substring( + node.prefix.length, + part!.length - node.suffix.length, + ) + : part! + if (value || node.kind === SEGMENT_TYPE_PARAM) { + rawParams[name] = decodeURIComponent(value) + } } else if (node.kind === SEGMENT_TYPE_WILDCARD) { const n = node const value = path.substring( - currentPathIndex + (n.prefix?.length ?? 0), - path.length - (n.suffix?.length ?? 0), + currentPathIndex + n.prefix.length, + path.length - n.suffix.length, ) const splat = decodeURIComponent(value) // TODO: Deprecate * - params['*'] = splat - params._splat = splat + rawParams['*'] = splat + rawParams._splat = splat break } } - return params + if (leaf.rawParams) Object.assign(rawParams, leaf.rawParams) + return [ + rawParams, + { + part: partIndex, + node: nodeIndex, + path: pathIndex, + param: paramIndex, + }, + ] } -function buildRouteBranch<T extends RouteLike>(route: T) { +export function buildRouteBranch<T extends RouteLike>(route: T) { const list = [route] while (route.parentRoute) { route = route.parentRoute as T @@ -817,8 +833,6 @@ type MatchStackFrame<T extends RouteLike> = { node: AnySegmentNode<T> /** index of the segment of path */ index: number - /** how many nodes between `node` and the root of the segment tree */ - depth: number /** * Bitmask of skipped optional segments. * @@ -826,9 +840,14 @@ type MatchStackFrame<T extends RouteLike> = { * If we really really need to support more than 32 segments we can switch to using a `BigInt` here. It's about 2x slower in worst case scenarios. */ skipped: number + /** Positional bitmasks tracking which consumed URL segments matched each segment kind. */ statics: number dynamics: number optionals: number + /** intermediary state for param extraction */ + extract?: ParamExtractionState + /** intermediary params from param extraction */ + rawParams?: Record<string, string> } function getNodeMatch<T extends RouteLike>( @@ -837,6 +856,14 @@ function getNodeMatch<T extends RouteLike>( segmentTree: AnySegmentNode<T>, fuzzy: boolean, ) { + // quick check for root index + // this is an optimization, algorithm should work correctly without this block + if (path === '/' && segmentTree.index) + return { node: segmentTree.index, skipped: 0 } as Pick< + Frame, + 'node' | 'skipped' + > + const trailingSlash = !last(parts) const pathIsIndex = trailingSlash && path !== '/' const partsLength = parts.length - (trailingSlash ? 1 : 0) @@ -855,47 +882,107 @@ function getNodeMatch<T extends RouteLike>( node: segmentTree, index: 1, skipped: 0, - depth: 1, - statics: 1, + statics: 0, dynamics: 0, optionals: 0, }, ] - let wildcardMatch: Frame | null = null let bestFuzzy: Frame | null = null let bestMatch: Frame | null = null while (stack.length) { const frame = stack.pop()! - // eslint-disable-next-line prefer-const - let { node, index, skipped, depth, statics, dynamics, optionals } = frame + const { node, index, skipped, statics, dynamics, optionals } = frame + let { extract, rawParams } = frame + + // Wildcard candidates are pushed speculatively as fallbacks in case a + // higher-priority wildcard later fails params.parse. If a better wildcard + // has already validated and become bestMatch, lower-priority wildcard + // fallbacks cannot win anymore and should not run params.parse. + if ( + node.kind === SEGMENT_TYPE_WILDCARD && + node.route && + !isFrameMoreSpecific(bestMatch, frame) + ) { + continue + } + + if (node.parse) { + const result = validateParseParams(path, parts, frame) + if (!result) continue + rawParams = frame.rawParams + extract = frame.extract + } // In fuzzy mode, track the best partial match we've found so far - if (fuzzy && node.notFound && isFrameMoreSpecific(bestFuzzy, frame)) { + if ( + fuzzy && + node.route && + node.kind !== SEGMENT_TYPE_INDEX && + isFrameMoreSpecific(bestFuzzy, frame) + ) { bestFuzzy = frame } const isBeyondPath = index === partsLength if (isBeyondPath) { - if (node.route && (!pathIsIndex || node.isIndex)) { - if (isFrameMoreSpecific(bestMatch, frame)) { - bestMatch = frame - } - - // perfect match, no need to continue - if (statics === partsLength && node.isIndex) return bestMatch + if ( + node.route && + (!pathIsIndex || + node.kind === SEGMENT_TYPE_INDEX || + node.kind === SEGMENT_TYPE_WILDCARD) && + isFrameMoreSpecific(bestMatch, frame) + ) { + bestMatch = frame } - // beyond the length of the path parts, only skipped optional segments or wildcard segments can match - if (!node.optional && !node.wildcard) continue + // beyond the length of the path parts, only some segment types can match + if (!node.optional && !node.wildcard && !node.index && !node.pathless) + continue } const part = isBeyondPath ? undefined : parts[index]! let lowerPart: string + // 0. Try index match + if (isBeyondPath && node.index) { + const indexFrame = { + node: node.index, + index, + skipped, + statics, + dynamics, + optionals, + extract, + rawParams, + } + let indexValid = true + if (node.index.parse) { + const result = validateParseParams(path, parts, indexFrame) + if (!result) indexValid = false + } + if (indexValid) { + // perfect match, no need to continue + // this is an optimization, algorithm should work correctly without this block + if ( + !dynamics && + !optionals && + !skipped && + isPerfectStaticMatch(statics, partsLength) + ) { + return indexFrame + } + if (isFrameMoreSpecific(bestMatch, indexFrame)) { + // index matches skip the stack because they cannot have children + bestMatch = indexFrame + } + } + } + // 5. Try wildcard match - if (node.wildcard && isFrameMoreSpecific(wildcardMatch, frame)) { - for (const segment of node.wildcard) { + if (node.wildcard) { + for (let i = node.wildcard.length - 1; i >= 0; i--) { + const segment = node.wildcard[i]! const { prefix, suffix } = segment if (prefix) { if (isBeyondPath) continue @@ -906,39 +993,48 @@ function getNodeMatch<T extends RouteLike>( } if (suffix) { if (isBeyondPath) continue - const end = parts.slice(index).join('/').slice(-suffix.length) - const casePart = segment.caseSensitive ? end : end.toLowerCase() - if (casePart !== suffix) continue + const end = parts.slice(index).join('/') + const suffixPart = end.slice(-suffix.length) + const casePart = segment.caseSensitive + ? suffixPart + : suffixPart.toLowerCase() + if ( + casePart !== suffix || + end.length - suffix.length < prefix.length + ) { + continue + } } - // the first wildcard match is the highest priority one - wildcardMatch = { + // wildcard matches consume the rest of the URL and cannot have children + stack.push({ node: segment, - index, + index: partsLength, skipped, - depth, statics, dynamics, optionals, - } - break + extract, + rawParams, + }) } } // 4. Try optional match if (node.optional) { - const nextSkipped = skipped | (1 << depth) - const nextDepth = depth + 1 + // A skipped optional is keyed by the child node's trie depth. + const nextSkipped = skipped | (1 << (node.depth + 1)) for (let i = node.optional.length - 1; i >= 0; i--) { const segment = node.optional[i]! - // when skipping, node and depth advance by 1, but index doesn't + // when skipping, the node advances by 1, but the index doesn't stack.push({ node: segment, index, skipped: nextSkipped, - depth: nextDepth, statics, dynamics, optionals, + extract, + rawParams, }) // enqueue skipping the optional } if (!isBeyondPath) { @@ -950,16 +1046,23 @@ function getNodeMatch<T extends RouteLike>( ? part! : (lowerPart ??= part!.toLowerCase()) if (prefix && !casePart.startsWith(prefix)) continue - if (suffix && !casePart.endsWith(suffix)) continue + if ( + suffix && + casePart.indexOf(suffix, casePart.length - suffix.length) < + prefix.length + ) { + continue + } } stack.push({ node: segment, index: index + 1, skipped, - depth: nextDepth, statics, dynamics, - optionals: optionals + 1, + optionals: optionals + segmentScore(partsLength, index), + extract, + rawParams, }) } } @@ -975,16 +1078,23 @@ function getNodeMatch<T extends RouteLike>( ? part : (lowerPart ??= part.toLowerCase()) if (prefix && !casePart.startsWith(prefix)) continue - if (suffix && !casePart.endsWith(suffix)) continue + if ( + suffix && + casePart.indexOf(suffix, casePart.length - suffix.length) < + prefix.length + ) { + continue + } } stack.push({ node: segment, index: index + 1, skipped, - depth: depth + 1, statics, - dynamics: dynamics + 1, + dynamics: dynamics + segmentScore(partsLength, index), optionals, + extract, + rawParams, }) } } @@ -999,10 +1109,11 @@ function getNodeMatch<T extends RouteLike>( node: match, index: index + 1, skipped, - depth: depth + 1, - statics: statics + 1, + statics: statics + segmentScore(partsLength, index), dynamics, optionals, + extract, + rawParams, }) } } @@ -1015,41 +1126,91 @@ function getNodeMatch<T extends RouteLike>( node: match, index: index + 1, skipped, - depth: depth + 1, - statics: statics + 1, + statics: statics + segmentScore(partsLength, index), dynamics, optionals, + extract, + rawParams, + }) + } + } + + // 0. Try pathless match + if (node.pathless) { + for (let i = node.pathless.length - 1; i >= 0; i--) { + const segment = node.pathless[i]! + stack.push({ + node: segment, + index, + skipped, + statics, + dynamics, + optionals, + extract, + rawParams, }) } } } - if (bestMatch && wildcardMatch) { - return isFrameMoreSpecific(wildcardMatch, bestMatch) - ? bestMatch - : wildcardMatch - } - if (bestMatch) return bestMatch - if (wildcardMatch) return wildcardMatch - if (fuzzy && bestFuzzy) { let sliceIndex = bestFuzzy.index for (let i = 0; i < bestFuzzy.index; i++) { sliceIndex += parts[i]!.length } const splat = sliceIndex === path.length ? '/' : path.slice(sliceIndex) - return { - node: bestFuzzy.node, - skipped: bestFuzzy.skipped, - '**': decodeURIComponent(splat), - } + bestFuzzy.rawParams ??= Object.create(null) + bestFuzzy.rawParams!['**'] = decodeURIComponent(splat) + return bestFuzzy } return null } +function segmentScore(partsLength: number, index: number): number { + // The specificity scores are bitmasks over consumed URL segments. Earlier + // URL segments should dominate later ones when comparing scores, so the + // first real segment gets the highest bit and the last gets bit 0. Since + // `parts[0]` is the empty string before the leading slash, real URL segments + // are [1, partsLength), making this segment's bit `partsLength - index - 1`. + return 2 ** (partsLength - index - 1) +} + +function isPerfectStaticMatch(statics: number, partsLength: number): boolean { + return statics === 2 ** (partsLength - 1) - 1 +} + +function validateParseParams<T extends RouteLike>( + path: string, + parts: Array<string>, + frame: MatchStackFrame<T>, +) { + let rawParams: Record<string, string> + let state: ParamExtractionState + + try { + ;[rawParams, state] = extractParams(path, parts, frame) + } catch { + return null + } + + frame.rawParams = rawParams + frame.extract = state + + if (!frame.node.parse) return true + + try { + if (frame.node.parse(rawParams) === false) return null + } catch { + // Thrown parse errors should be surfaced on the selected match by + // extractStrictParams, not used as fallback route selection. + } + + return true +} + function isFrameMoreSpecific( // the stack frame previously saved as "best match" prev: MatchStackFrame<any> | null, @@ -1064,8 +1225,10 @@ function isFrameMoreSpecific( (next.dynamics === prev.dynamics && (next.optionals > prev.optionals || (next.optionals === prev.optionals && - (next.node.isIndex > prev.node.isIndex || - (next.node.isIndex === prev.node.isIndex && - next.depth > prev.depth))))))) + ((next.node.kind === SEGMENT_TYPE_INDEX) > + (prev.node.kind === SEGMENT_TYPE_INDEX) || + ((next.node.kind === SEGMENT_TYPE_INDEX) === + (prev.node.kind === SEGMENT_TYPE_INDEX) && + next.node.depth > prev.node.depth))))))) ) } diff --git a/packages/router-core/src/not-found.ts b/packages/router-core/src/not-found.ts index 0681b82054..ddf8f0a259 100644 --- a/packages/router-core/src/not-found.ts +++ b/packages/router-core/src/not-found.ts @@ -37,5 +37,5 @@ export function notFound(options: NotFoundError = {}) { /** Determine if a value is a TanStack Router not-found error. */ export function isNotFound(obj: any): obj is NotFoundError { - return !!obj?.isNotFound + return obj?.isNotFound === true } diff --git a/packages/router-core/src/path.ts b/packages/router-core/src/path.ts index 859a900496..1b6288dc36 100644 --- a/packages/router-core/src/path.ts +++ b/packages/router-core/src/path.ts @@ -2,11 +2,11 @@ import { last } from './utils' import { SEGMENT_TYPE_OPTIONAL_PARAM, SEGMENT_TYPE_PARAM, - SEGMENT_TYPE_PATHNAME, SEGMENT_TYPE_WILDCARD, - parseSegment, } from './new-process-route-tree' -import type { LRUCache } from './lru-cache' +import type { SieveCache } from './sieve-cache' +import type { DynamicPathSegment } from './new-process-route-tree' +import type { AnyRoute } from './route' /** Join path segments, cleaning duplicate slashes between parts. */ export function joinPaths(paths: Array<string | undefined>) { @@ -27,13 +27,13 @@ export function cleanPath(path: string) { /** Trim leading slashes (except preserving root '/'). */ export function trimPathLeft(path: string) { - return path === '/' ? path : path.replace(/^\/{1,}/, '') + return path === '/' ? path : path.replace(/^\/+/, '') } /** Trim trailing slashes (except preserving root '/'). */ export function trimPathRight(path: string) { const len = path.length - return len > 1 && path[len - 1] === '/' ? path.replace(/\/{1,}$/, '') : path + return len > 1 && path[len - 1] === '/' ? path.replace(/\/+$/, '') : path } /** Trim both leading and trailing slashes. */ @@ -94,30 +94,38 @@ export function exactPathTest( // /a/b/c + d = /a/b/c/d // /a/b/c + d/ = /a/b/c/d // /a/b/c + d/e = /a/b/c/d/e -interface ResolvePathOptions { - base: string - to: string - trailingSlash?: 'always' | 'never' | 'preserve' - cache?: LRUCache<string, string> -} - /** * Resolve a destination path against a base, honoring trailing-slash policy * and supporting relative segments (`.`/`..`) and absolute `to` values. + * + * Internal: parameters are positional so the router's hot callers pass no + * options object. */ -export function resolvePath({ - base, - to, - trailingSlash = 'never', - cache, -}: ResolvePathOptions) { - const isAbsolute = to.startsWith('/') - const isBase = !isAbsolute && to === '.' +export function resolvePath( + base: string, + to: string, + trailingSlash: 'always' | 'never' | 'preserve' = 'never', + cache?: SieveCache<string, string>, +) { + if (to.includes('//')) { + to = cleanPath(to) + } + if (to.startsWith('/')) { + if (to.length === 1 || trailingSlash === 'preserve') { + return to + } + if (trailingSlash === 'always') { + return to.endsWith('/') ? to : `${to}/` + } + return to.endsWith('/') ? to.slice(0, -1) : to + } + + const isBase = to === '.' let key if (cache) { // `trailingSlash` is static per router, so it doesn't need to be part of the cache key - key = isAbsolute ? to : isBase ? base : base + '\0' + to + key = isBase ? base : base + '\0' + to const cached = cache.get(key) if (cached) return cached } @@ -125,9 +133,10 @@ export function resolvePath({ let baseSegments: Array<string> if (isBase) { baseSegments = base.split('/') - } else if (isAbsolute) { - baseSegments = to.split('/') } else { + if (base.includes('//')) { + base = cleanPath(base) + } baseSegments = base.split('/') while (baseSegments.length > 1 && last(baseSegments) === '') { baseSegments.pop() @@ -147,7 +156,11 @@ export function resolvePath({ // ignore inter-slashes } } else if (value === '..') { - baseSegments.pop() + if (baseSegments.length > 1) { + baseSegments.pop() + } else { + baseSegments = [''] + } } else if (value === '.') { // ignore } else { @@ -166,175 +179,128 @@ export function resolvePath({ } } - let segment - let joined = '' - for (let i = 0; i < baseSegments.length; i++) { - if (i > 0) joined += '/' - const part = baseSegments[i]! - if (!part) continue - segment = parseSegment(part, 0, segment) - const kind = segment[0] - if (kind === SEGMENT_TYPE_PATHNAME) { - joined += part - continue - } - const end = segment[5] - const prefix = part.substring(0, segment[1]) - const suffix = part.substring(segment[4], end) - const value = part.substring(segment[2], segment[3]) - if (kind === SEGMENT_TYPE_PARAM) { - joined += prefix || suffix ? `${prefix}{$${value}}${suffix}` : `$${value}` - } else if (kind === SEGMENT_TYPE_WILDCARD) { - joined += prefix || suffix ? `${prefix}{$}${suffix}` : '$' - } else { - // SEGMENT_TYPE_OPTIONAL_PARAM - joined += `${prefix}{-$${value}}${suffix}` - } - } - joined = cleanPath(joined) - const result = joined || '/' + const joined = baseSegments.join('/') + const result = (isBase ? cleanPath(joined) : joined) || '/' if (key && cache) cache.set(key, result) return result } -interface InterpolatePathOptions { - path?: string - params: Record<string, unknown> - // Map of encoded chars to decoded chars (e.g. '%40' -> '@') that should remain decoded in path params - decodeCharMap?: Map<string, string> +/** + * Create a pre-compiled decode config from allowed characters. + * Created once for the router's fixed encoding configuration. + */ +export function compileDecodeCharMap( + pathParamsAllowedCharacters: ReadonlyArray<string>, +) { + const charMap = new Map( + pathParamsAllowedCharacters.map((char) => [encodeURIComponent(char), char]), + ) + // Encoded keys contain no '|', and only these four regexp metacharacters. + const regex = new RegExp( + [...charMap.keys()].join('|').replace(/[.*()]/g, '\\$&'), + 'g', + ) + return (encoded: string) => + encoded.replace(regex, (match) => charMap.get(match) ?? match) } -type InterPolatePathResult = { - interpolatedPath: string - usedParams: Record<string, unknown> - isMissingParams: boolean // true if any params were not available when being looked up in the params object +export type InterpolationSegment = string | DynamicPathSegment + +export type RouteInterpolation = Array<InterpolationSegment> & { + names?: Array<string> +} + +export function getRouteSegments(route: AnyRoute) { + return route._interpolation +} + +/** A splat is missing when it has no value; `0` and `false` are stringified like any other param. */ +function isMissingSplat(value: unknown): boolean { + return value == null || value === '' +} + +/** Devtools checks navigation availability separately from the hot formatter. */ +export function hasMissingPathParams( + segments: RouteInterpolation, + params: Record<string, unknown>, +): boolean { + return segments.some((part) => { + if (typeof part === 'string') { + return false + } + const [kind, key] = part + return kind === SEGMENT_TYPE_WILDCARD + ? isMissingSplat(params[key]) + : kind === SEGMENT_TYPE_PARAM && !(key in params) + }) } function encodeParam( key: string, - params: InterpolatePathOptions['params'], - decodeCharMap: InterpolatePathOptions['decodeCharMap'], -): any { - const value = params[key] - if (typeof value !== 'string') return value - - if (key === '_splat') { - // the splat/catch-all routes shouldn't have the '/' encoded out - return encodeURI(value) - } else { - return encodePathParam(value, decodeCharMap) + value: unknown, + decoder: ((encoded: string) => string) | undefined, +): string { + if (typeof value !== 'string') { + return '' + (value ?? undefined) } + + const splat = key === '_splat' + // Early return if the splat contains only URL-safe characters. + if (splat && (!value || /^[a-zA-Z0-9\-._~!/]*$/.test(value))) { + return value + } + let encoded = encodeURIComponent(value) + if (splat) { + // Splats preserve '/', but still encode spaces, '+', '?' and '#'. + // Restore separators before allowed characters can decode a literal '%2F'. + encoded = encoded.replaceAll('%2F', '/') + } + return decoder ? decoder(encoded) : encoded } -/** - * Interpolate params and wildcards into a route path template. - * - * - Encodes params safely (configurable allowed characters) - * - Supports `{-$optional}` segments, `{prefix{$id}suffix}` and `{$}` wildcards - */ -export function interpolatePath({ - path, - params, - decodeCharMap, -}: InterpolatePathOptions): InterPolatePathResult { - // Tracking if any params are missing in the `params` object - // when interpolating the path - let isMissingParams = false - const usedParams: Record<string, unknown> = {} - - if (!path || path === '/') - return { interpolatedPath: '/', usedParams, isMissingParams } - if (!path.includes('$')) - return { interpolatedPath: path, usedParams, isMissingParams } - - const length = path.length - let cursor = 0 - let segment +/** Substitute current values into parsed segments, optionally collecting raw params. */ +export function interpolatePath( + path: string, + segments: RouteInterpolation, + params: Record<string, unknown>, + decoder?: (encoded: string) => string, + usedParams?: Record<string, unknown>, +): string { + // One parsed template serves both trailing-slash variants. + const trailingSlash = path.endsWith('/') ? '/' : '' let joined = '' - while (cursor < length) { - const start = cursor - segment = parseSegment(path, start, segment) - const end = segment[5] - cursor = end + 1 - - if (start === end) continue - - const kind = segment[0] - - if (kind === SEGMENT_TYPE_PATHNAME) { - joined += '/' + path.substring(start, end) + for (const part of segments) { + if (typeof part === 'string') { + joined += part continue } - - if (kind === SEGMENT_TYPE_WILDCARD) { - const splat = params._splat - usedParams._splat = splat + const [kind, key, prefix, rawSuffix] = part + const splat = kind === SEGMENT_TYPE_WILDCARD + const suffix = + splat && rawSuffix !== undefined ? rawSuffix + trailingSlash : rawSuffix + let paramValue = params[key] + // An omitted optional contributes neither a segment nor used-param metadata. + if (kind === SEGMENT_TYPE_OPTIONAL_PARAM && paramValue == null) { + continue + } + if (usedParams) { + // Match identity needs current raw values, never data retained from another call. + usedParams[key] = paramValue // TODO: Deprecate * - usedParams['*'] = splat - - const prefix = path.substring(start, segment[1]) - const suffix = path.substring(segment[4], end) - - // Check if _splat parameter is missing. _splat could be missing if undefined or an empty string or some other falsy value. - if (!splat) { - isMissingParams = true - // For missing splat parameters, just return the prefix and suffix without the wildcard - // If there is a prefix or suffix, return them joined, otherwise omit the segment - if (prefix || suffix) { - joined += '/' + prefix + suffix - } + if (splat) { + usedParams['*'] = paramValue + } + } + if (splat && isMissingSplat(paramValue)) { + // A missing wildcard keeps its affixes, but omits a bare segment. + if (prefix === '/' && !suffix) { continue } - - const value = encodeParam('_splat', params, decodeCharMap) - joined += '/' + prefix + value + suffix - continue + paramValue = '' } - if (kind === SEGMENT_TYPE_PARAM) { - const key = path.substring(segment[2], segment[3]) - if (!isMissingParams && !(key in params)) { - isMissingParams = true - } - usedParams[key] = params[key] - - const prefix = path.substring(start, segment[1]) - const suffix = path.substring(segment[4], end) - const value = encodeParam(key, params, decodeCharMap) ?? 'undefined' - joined += '/' + prefix + value + suffix - continue - } - - if (kind === SEGMENT_TYPE_OPTIONAL_PARAM) { - const key = path.substring(segment[2], segment[3]) - const valueRaw = params[key] - - // Check if optional parameter is missing or undefined - if (valueRaw == null) continue - - usedParams[key] = valueRaw - - const prefix = path.substring(start, segment[1]) - const suffix = path.substring(segment[4], end) - const value = encodeParam(key, params, decodeCharMap) ?? '' - joined += '/' + prefix + value + suffix - continue - } + joined += prefix + encodeParam(key, paramValue, decoder) + (suffix || '') } - if (path.endsWith('/')) joined += '/' - - const interpolatedPath = joined || '/' - - return { usedParams, interpolatedPath, isMissingParams } -} - -function encodePathParam(value: string, decodeCharMap?: Map<string, string>) { - let encoded = encodeURIComponent(value) - if (decodeCharMap) { - for (const [encodedChar, char] of decodeCharMap) { - encoded = encoded.replaceAll(encodedChar, char) - } - } - return encoded + return joined + trailingSlash || '/' } diff --git a/packages/router-core/src/qss.ts b/packages/router-core/src/qss.ts index df6e24a7c3..2a4125fdad 100644 --- a/packages/router-core/src/qss.ts +++ b/packages/router-core/src/qss.ts @@ -26,16 +26,16 @@ export function encode( obj: Record<string, any>, stringify: (value: any) => string = String, ): string { - const result = new URLSearchParams() + let result: URLSearchParams | undefined for (const key in obj) { const val = obj[key] if (val !== undefined) { - result.set(key, stringify(val)) + ;(result ||= new URLSearchParams()).set(key, stringify(val)) } } - return result.toString() + return result ? result.toString() : '' } /** @@ -64,7 +64,7 @@ function toValue(str: unknown) { export function decode(str: any): any { const searchParams = new URLSearchParams(str) - const result: Record<string, unknown> = {} + const result: Record<string, unknown> = Object.create(null) for (const [key, value] of searchParams.entries()) { const previousValue = result[key] diff --git a/packages/router-core/src/redirect.ts b/packages/router-core/src/redirect.ts index d2093a0eb6..dc6551d174 100644 --- a/packages/router-core/src/redirect.ts +++ b/packages/router-core/src/redirect.ts @@ -14,7 +14,6 @@ export type Redirect< TMaskTo extends string = '.', > = Response & { options: NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> - redirectHandled?: boolean } export type RedirectOptions< @@ -54,16 +53,45 @@ export type ResolvedRedirect< TMaskTo extends string = '', > = Redirect<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> +/** + * Options for route-bound redirect, where 'from' is automatically set. + * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType) + */ +export type RedirectOptionsRoute< + TDefaultFrom extends string = string, + TRouter extends AnyRouter = RegisteredRouter, + TTo extends string | undefined = undefined, + TMaskTo extends string = '', +> = Omit< + RedirectOptions<TRouter, TDefaultFrom, TTo, TDefaultFrom, TMaskTo>, + 'from' +> + +/** + * A redirect function bound to a specific route, with 'from' pre-set to the route's fullPath. + * This enables relative redirects like `Route.redirect({ to: './overview' })`. + * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType) + */ +export interface RedirectFnRoute<in out TDefaultFrom extends string = string> { + < + TRouter extends AnyRouter = RegisteredRouter, + const TTo extends string | undefined = undefined, + const TMaskTo extends string = '', + >( + opts: RedirectOptionsRoute<TDefaultFrom, TRouter, TTo, TMaskTo>, + ): Redirect<TRouter, TDefaultFrom, TTo, TDefaultFrom, TMaskTo> +} + /** * Create a redirect Response understood by TanStack Router. * * Use from route `loader`/`beforeLoad` or server functions to trigger a * navigation. If `throw: true` is set, the redirect is thrown instead of - * returned. When an absolute `href` is supplied and `reloadDocument` is not - * set, a full-document navigation is inferred. + * returned. External `href` values are classified as full-document + * navigations when the router resolves the redirect. * * @param opts Options for the redirect. Common fields: - * - `href`: absolute URL for external redirects; infers `reloadDocument`. + * - `href`: absolute URL for external redirects. * - `statusCode`: HTTP status code to use (defaults to 307). * - `headers`: additional headers to include on the Response. * - Standard navigation options like `to`, `params`, `search`, `replace`, @@ -82,13 +110,6 @@ export function redirect< ): Redirect<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> { opts.statusCode = opts.statusCode || opts.code || 307 - if (!opts.reloadDocument && typeof opts.href === 'string') { - try { - new URL(opts.href) - opts.reloadDocument = true - } catch {} - } - const headers = new Headers(opts.headers) if (opts.href && headers.get('Location') === null) { headers.set('Location', opts.href) @@ -109,13 +130,11 @@ export function redirect< return response as Redirect<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> } -/** Check whether a value is a TanStack Router redirect Response. */ /** Check whether a value is a TanStack Router redirect Response. */ export function isRedirect(obj: any): obj is AnyRedirect { return obj instanceof Response && !!(obj as any).options } -/** True if value is a redirect with a resolved `href` location. */ /** True if value is a redirect with a resolved `href` location. */ export function isResolvedRedirect( obj: any, @@ -123,7 +142,6 @@ export function isResolvedRedirect( return isRedirect(obj) && !!obj.options.href } -/** Parse a serialized redirect object back into a redirect Response. */ /** Parse a serialized redirect object back into a redirect Response. */ export function parseRedirect(obj: any) { if (obj !== null && typeof obj === 'object' && obj.isSerializedRedirect) { diff --git a/packages/router-core/src/rewrite.ts b/packages/router-core/src/rewrite.ts index 0da50c5b62..901880104e 100644 --- a/packages/router-core/src/rewrite.ts +++ b/packages/router-core/src/rewrite.ts @@ -1,7 +1,6 @@ -import { joinPaths, trimPath } from './path' +import { cleanPath, trimPath } from './path' import type { LocationRewrite } from './router' -/** Compose multiple rewrite pairs into a single in/out rewrite. */ /** Compose multiple rewrite pairs into a single in/out rewrite. */ export function composeRewrites(rewrites: Array<LocationRewrite>) { return { @@ -21,26 +20,21 @@ export function composeRewrites(rewrites: Array<LocationRewrite>) { } /** Create a rewrite pair that strips/adds a basepath on input/output. */ -/** Create a rewrite pair that strips/adds a basepath on input/output. */ -export function rewriteBasepath(opts: { - basepath: string - caseSensitive?: boolean -}) { - const trimmedBasepath = trimPath(opts.basepath) +export function rewriteBasepath( + basepath: string, + caseSensitive?: boolean, + rewrite?: LocationRewrite, +) { + const trimmedBasepath = trimPath(basepath) const normalizedBasepath = `/${trimmedBasepath}` - const normalizedBasepathWithSlash = `${normalizedBasepath}/` - const checkBasepath = opts.caseSensitive + const checkBasepath = caseSensitive ? normalizedBasepath : normalizedBasepath.toLowerCase() - const checkBasepathWithSlash = opts.caseSensitive - ? normalizedBasepathWithSlash - : normalizedBasepathWithSlash.toLowerCase() + const checkBasepathWithSlash = `${checkBasepath}/` - return { + const basepathRewrite = { input: ({ url }) => { - const pathname = opts.caseSensitive - ? url.pathname - : url.pathname.toLowerCase() + const pathname = caseSensitive ? url.pathname : url.pathname.toLowerCase() // Handle exact basepath match (e.g., /my-app -> /) if (pathname === checkBasepath) { @@ -52,13 +46,24 @@ export function rewriteBasepath(opts: { return url }, output: ({ url }) => { - url.pathname = joinPaths(['/', trimmedBasepath, url.pathname]) + // `url.pathname` always starts with "/", so only slashes already inside + // it can repeat; cleanPath keeps the joinPaths normalization. + url.pathname = cleanPath(`/${trimmedBasepath}${url.pathname}`) return url }, } satisfies LocationRewrite + + // Strip the basepath before custom input and restore it after custom output. + return rewrite + ? ({ + input: ({ url }) => + executeRewriteInput(rewrite, basepathRewrite.input({ url })), + output: ({ url }) => + basepathRewrite.output({ url: executeRewriteOutput(rewrite, url) }), + } satisfies LocationRewrite) + : basepathRewrite } -/** Execute a location input rewrite if provided. */ /** Execute a location input rewrite if provided. */ export function executeRewriteInput( rewrite: LocationRewrite | undefined, @@ -75,7 +80,6 @@ export function executeRewriteInput( return url } -/** Execute a location output rewrite if provided. */ /** Execute a location output rewrite if provided. */ export function executeRewriteOutput( rewrite: LocationRewrite | undefined, diff --git a/packages/router-core/src/route.ts b/packages/router-core/src/route.ts index 53d726ef05..089369b454 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -1,9 +1,12 @@ -import invariant from 'tiny-invariant' -import { joinPaths, trimPathLeft } from './path' +import { invariant } from './invariant' +import { cleanPath, trimPathLeft, trimPathRight } from './path' import { notFound } from './not-found' +import { redirect } from './redirect' import { rootRouteId } from './root' import type { LazyRoute } from './fileRoute' +import type { RouteInterpolation } from './path' import type { NotFoundError } from './not-found' +import type { RedirectFnRoute } from './redirect' import type { NavigateOptions, ParsePathParams } from './link' import type { ParsedLocation } from './location' import type { @@ -53,7 +56,7 @@ export type AnyContext = {} export interface RouteContext {} -export type PreloadableObj = { preload?: () => Promise<void> } +export type PreloadableObj = { preload?: () => Promise<void> | undefined } export type RoutePathOptions<TCustomId, TPath> = | { @@ -72,9 +75,17 @@ export type RoutePathOptionsIntersection<TCustomId, TPath> = { export type SearchFilter<TInput, TResult = TInput> = (prev: TInput) => TResult +export type SearchMiddlewareMeta = { + removed?: Map<string, unknown> + removedAny?: Set<string> + defaulted?: Map<string, unknown> + explicit?: unknown +} + export type SearchMiddlewareContext<TSearchSchema> = { search: TSearchSchema next: (newSearch: TSearchSchema) => TSearchSchema + meta?: SearchMiddlewareMeta } export type SearchMiddleware<TSearchSchema> = ( @@ -171,9 +182,13 @@ export type ResolveParams< export type ParseParamsFn<in out TPath extends string, in out TParams> = ( rawParams: Expand<ResolveParams<TPath>>, -) => TParams extends ResolveParams<TPath, any> - ? TParams - : ResolveParams<TPath, any> +) => TParams | false + +type ValidateParsedParams<TPath extends string, TParams> = [TParams] extends [ + ResolveParams<TPath, any>, +] + ? unknown + : never export type StringifyParamsFn<in out TPath extends string, in out TParams> = ( params: TParams, @@ -181,14 +196,22 @@ export type StringifyParamsFn<in out TPath extends string, in out TParams> = ( export type ParamsOptions<in out TPath extends string, in out TParams> = { params?: { - parse?: ParseParamsFn<TPath, TParams> + parse?: ParseParamsFn<TPath, TParams> & ValidateParsedParams<TPath, TParams> + /** + * When multiple route candidates use `params.parse` during matching, + * higher priorities are tried first. + * + * @default 0 + */ + priority?: number stringify?: StringifyParamsFn<TPath, TParams> } /** @deprecated Use params.parse instead */ - parseParams?: ParseParamsFn<TPath, TParams> + parseParams?: ParseParamsFn<TPath, TParams> & + ValidateParsedParams<TPath, TParams> /** @deprecated Use params.stringify instead @@ -290,11 +313,44 @@ export type ResolveRouteContext<TRouteContextFn, TBeforeLoadFn> = Assign< ContextAsyncReturnType<TBeforeLoadFn> > +export type ResolveRouteLoaderFn<TLoaderFn> = TLoaderFn extends { + handler: infer THandler +} + ? THandler + : TLoaderFn + +export type RouteLoaderObject< + TRegister, + TParentRoute extends AnyRoute = AnyRoute, + TId extends string = string, + TParams = {}, + TLoaderDeps = {}, + TRouterContext = {}, + TRouteContextFn = AnyContext, + TBeforeLoadFn = AnyContext, + TServerMiddlewares = unknown, + THandlers = undefined, +> = { + handler: RouteLoaderFn< + TRegister, + TParentRoute, + TId, + TParams, + TLoaderDeps, + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TServerMiddlewares, + THandlers + > + staleReloadMode?: LoaderStaleReloadMode +} + export type ResolveLoaderData<TLoaderFn> = unknown extends TLoaderFn ? TLoaderFn - : LooseAsyncReturnType<TLoaderFn> extends never + : LooseAsyncReturnType<ResolveRouteLoaderFn<TLoaderFn>> extends never ? undefined - : LooseAsyncReturnType<TLoaderFn> + : LooseAsyncReturnType<ResolveRouteLoaderFn<TLoaderFn>> export type ResolveFullSearchSchema< TParentRoute extends AnyRoute, @@ -645,10 +701,6 @@ export interface Route< THandlers > isRoot: TParentRoute extends AnyRoute ? true : false - /** @internal */ - _componentsPromise?: Promise<void> - /** @internal */ - _componentsLoaded?: boolean lazyFn?: () => Promise< LazyRoute< Route< @@ -674,12 +726,14 @@ export interface Route< > > /** @internal */ - _lazyPromise?: Promise<void> + _lazy?: Promise<void> | true /** @internal */ - _lazyLoaded?: boolean + _branch?: ReadonlyArray<AnyRoute> + /** @internal */ + _interpolation?: RouteInterpolation rank: number to: TrimPathRight<TFullPath> - init: (opts: { originalIndex: number }) => void + init: (originalIndex: number) => void update: ( options: UpdatableRouteOptions< TParentRoute, @@ -773,6 +827,14 @@ export interface Route< TServerMiddlewares, THandlers > + /** + * Create a redirect with `from` automatically set to this route's path. + * Enables relative redirects like `Route.redirect({ to: './overview' })`. + * @param opts Redirect options (same as `redirect()` but without `from`) + * @returns A redirect Response that can be thrown from loaders/beforeLoad + * @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction + */ + redirect: RedirectFnRoute<TFullPath> } export type AnyRoute = Route< @@ -852,12 +914,14 @@ export type RouteContextFn< in out TSearchValidator, in out TParams, in out TRouterContext, + in out TRouteId, > = ( ctx: RouteContextOptions< TParentRoute, TSearchValidator, TParams, - TRouterContext + TRouterContext, + TRouteId >, ) => any @@ -939,7 +1003,8 @@ export interface FilebaseRouteOptionsInterface< TParentRoute, TParams, TRouterContext, - TLoaderDeps + TLoaderDeps, + TId >, ) => any > @@ -967,6 +1032,7 @@ export interface FilebaseRouteOptionsInterface< TParams, TRouterContext, TRouteContextFn, + TId, TServerMiddlewares, THandlers >, @@ -996,8 +1062,7 @@ export interface FilebaseRouteOptionsInterface< loader?: Constrain< TLoaderFn, - ( - ctx: LoaderFnContext< + | RouteLoaderFn< TRegister, TParentRoute, TId, @@ -1008,13 +1073,19 @@ export interface FilebaseRouteOptionsInterface< TBeforeLoadFn, TServerMiddlewares, THandlers - >, - ) => ValidateSerializableLifecycleResult< - TRegister, - TParentRoute, - TSSR, - TLoaderFn - > + > + | RouteLoaderObject< + TRegister, + TParentRoute, + TId, + TParams, + TLoaderDeps, + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TServerMiddlewares, + THandlers + > > } @@ -1058,6 +1129,7 @@ export type BaseRouteOptions< export interface ContextOptions< in out TParentRoute extends AnyRoute, in out TParams, + in out TRouteId, > { abortController: AbortController preload: boolean @@ -1070,6 +1142,7 @@ export interface ContextOptions< buildLocation: BuildLocationFn cause: 'preload' | 'enter' | 'stay' matches: Array<MakeRouteMatchUnion> + routeId: TRouteId } export interface RouteContextOptions< @@ -1077,7 +1150,8 @@ export interface RouteContextOptions< in out TParams, in out TRouterContext, in out TLoaderDeps, -> extends ContextOptions<TParentRoute, TParams> { + in out TRouteId, +> extends ContextOptions<TParentRoute, TParams, TRouteId> { deps: TLoaderDeps context: Expand<RouteContextParameter<TParentRoute, TRouterContext>> } @@ -1110,9 +1184,12 @@ export interface BeforeLoadContextOptions< in out TParams, in out TRouterContext, in out TRouteContextFn, + in out TRouteId, in out TServerMiddlewares, in out THandlers, -> extends ContextOptions<TParentRoute, TParams>, +> + extends + ContextOptions<TParentRoute, TParams, TRouteId>, FullSearchSchemaOption<TParentRoute, TSearchValidator> { context: Expand< BeforeLoadContextParameter<TParentRoute, TRouterContext, TRouteContextFn> @@ -1131,6 +1208,9 @@ type AssetFnContextOptions< in out TBeforeLoadFn, in out TLoaderDeps, > = { + ssr?: { + nonce?: string + } matches: Array< RouteMatch< TRouteId, @@ -1172,8 +1252,7 @@ export interface DefaultUpdatableRouteOptionsExtensions { pendingComponent?: unknown } -export interface UpdatableRouteOptionsExtensions - extends DefaultUpdatableRouteOptionsExtensions {} +export interface UpdatableRouteOptionsExtensions extends DefaultUpdatableRouteOptionsExtensions {} export interface UpdatableRouteOptions< in out TParentRoute extends AnyRoute, @@ -1186,11 +1265,17 @@ export interface UpdatableRouteOptions< in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn, -> extends UpdatableStaticRouteOption, - UpdatableRouteOptionsExtensions { - // If true, this route will be matched as case-sensitive +> + extends UpdatableStaticRouteOption, UpdatableRouteOptionsExtensions { + /** + * If true, this route will be matched as case-sensitive + * + * @default false + */ caseSensitive?: boolean - // If true, this route will be forcefully wrapped in a suspense boundary + /** + * If true, this route will be forcefully wrapped in a suspense boundary + */ wrapInSuspense?: boolean // The content to be rendered when the route is matched. If no component is provided, defaults to `<Outlet />` @@ -1203,9 +1288,7 @@ export interface UpdatableRouteOptions< preloadGcTime?: number search?: { middlewares?: Array< - SearchMiddleware< - ResolveFullSearchSchemaInput<TParentRoute, TSearchValidator> - > + SearchMiddleware<ResolveFullSearchSchema<TParentRoute, TSearchValidator>> > } /** @@ -1220,7 +1303,7 @@ export interface UpdatableRouteOptions< postSearchFilters?: Array< SearchFilter<ResolveFullSearchSchema<TParentRoute, TSearchValidator>> > - onCatch?: (error: Error) => void + onCatch?: (error: ErrorBoundaryTypes['error']) => void onError?: (err: any) => void // These functions are called as route matches are loaded, stick around and leave the active // matches @@ -1285,7 +1368,7 @@ export interface UpdatableRouteOptions< TBeforeLoadFn, TLoaderDeps >, - ) => Awaitable<Record<string, string>> + ) => Awaitable<Record<string, string> | undefined> head?: ( ctx: AssetFnContextOptions< TRouteId, @@ -1356,6 +1439,45 @@ export type RouteLoaderFn< >, ) => any +export type LoaderStaleReloadMode = 'background' | 'blocking' + +export type RouteLoaderEntry< + TRegister, + TParentRoute extends AnyRoute = AnyRoute, + TId extends string = string, + TParams = {}, + TLoaderDeps = {}, + TRouterContext = {}, + TRouteContextFn = AnyContext, + TBeforeLoadFn = AnyContext, + TServerMiddlewares = unknown, + THandlers = undefined, +> = + | RouteLoaderFn< + TRegister, + TParentRoute, + TId, + TParams, + TLoaderDeps, + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TServerMiddlewares, + THandlers + > + | RouteLoaderObject< + TRegister, + TParentRoute, + TId, + TParams, + TLoaderDeps, + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TServerMiddlewares, + THandlers + > + export interface LoaderFnContext< in out TRegister = unknown, in out TParentRoute extends AnyRoute = AnyRoute, @@ -1397,8 +1519,7 @@ export interface DefaultRootRouteOptionsExtensions { shellComponent?: unknown } -export interface RootRouteOptionsExtensions - extends DefaultRootRouteOptionsExtensions {} +export interface RootRouteOptionsExtensions extends DefaultRootRouteOptionsExtensions {} export interface RootRouteOptions< TRegister = unknown, @@ -1411,7 +1532,9 @@ export interface RootRouteOptions< TSSR = unknown, TServerMiddlewares = unknown, THandlers = undefined, -> extends Omit< +> + extends + Omit< RouteOptions< TRegister, any, // TParentRoute @@ -1483,7 +1606,14 @@ export type ErrorRouteProps = { reset: () => void } -export type ErrorComponentProps<TError = Error> = { +export interface DefaultErrorBoundaryTypes { + error: unknown +} + +/** Frameworks can specialize the error exposed by boundary components and callbacks. */ +export interface ErrorBoundaryTypes extends DefaultErrorBoundaryTypes {} + +export type ErrorComponentProps<TError = ErrorBoundaryTypes['error']> = { error: TError info?: { componentStack: string } reset: () => void @@ -1587,10 +1717,11 @@ export class BaseRoute< > > /** @internal */ - _lazyPromise?: Promise<void> + _lazy?: Promise<void> | true /** @internal */ - _componentsPromise?: Promise<void> - + _branch?: ReadonlyArray<AnyRoute> + /** @internal */ + _interpolation?: RouteInterpolation constructor( options?: RouteOptions< TRegister, @@ -1640,8 +1771,10 @@ export class BaseRoute< THandlers > - init = (opts: { originalIndex: number }): void => { - this.originalIndex = opts.originalIndex + init = (originalIndex: number): void => { + this.originalIndex = originalIndex + // Rebuilding a tree can change the ancestors of an existing route. + this._branch = undefined const options = this.options as | (RouteOptions< @@ -1671,10 +1804,13 @@ export class BaseRoute< if (isRoot) { this._path = rootRouteId as TPath } else if (!this.parentRoute) { - invariant( - false, - `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a Route instance.`, - ) + if (process.env.NODE_ENV !== 'production') { + throw new Error( + `Invariant failed: Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a Route instance.`, + ) + } + + invariant() } let path: undefined | string = isRoot ? rootRouteId : options?.path @@ -1687,28 +1823,29 @@ export class BaseRoute< const customId = options?.id || path // Strip the parentId prefix from the first level of children - let id = isRoot + const id = isRoot ? rootRouteId - : joinPaths([ - this.parentRoute.id === rootRouteId ? '' : this.parentRoute.id, - customId, - ]) + : cleanPath( + (this.parentRoute.id === rootRouteId ? '' : this.parentRoute.id) + + '/' + + (customId ?? ''), + ) if (path === rootRouteId) { path = '/' } - if (id !== rootRouteId) { - id = joinPaths(['/', id]) - } - const fullPath = - id === rootRouteId ? '/' : joinPaths([this.parentRoute.fullPath, path]) + id === rootRouteId + ? '/' + : path === undefined + ? this.parentRoute.fullPath + : cleanPath(this.parentRoute.fullPath + '/' + path) this._path = path as TPath this._id = id as TId this._fullPath = fullPath as TFullPath - this._to = fullPath as TrimPathRight<TFullPath> + this._to = trimPathRight(fullPath) as TrimPathRight<TFullPath> } addChildren: RouteAddChildrenFn< @@ -1866,18 +2003,39 @@ export class BaseRoute< this.lazyFn = lazyFn return this } + + /** + * Create a redirect with `from` automatically set to this route's fullPath. + * Enables relative redirects like `Route.redirect({ to: './overview' })`. + * @param opts Redirect options (same as `redirect()` but without `from`) + * @returns A redirect Response that can be thrown from loaders/beforeLoad + * @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction + */ + redirect: RedirectFnRoute<TFullPath> = (opts) => + redirect({ from: this.fullPath, ...opts } as any) } export class BaseRouteApi<TId, TRouter extends AnyRouter = RegisteredRouter> { id: TId constructor({ id }: { id: TId }) { - this.id = id as any + this.id = id } notFound = (opts?: NotFoundError) => { return notFound({ routeId: this.id as string, ...opts }) } + + /** + * Create a redirect with `from` automatically set to this route's path. + * Enables relative redirects like `routeApi.redirect({ to: './overview' })`. + * @param opts Redirect options (same as `redirect()` but without `from`) + * @returns A redirect Response that can be thrown from loaders/beforeLoad + * @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction + */ + redirect: RedirectFnRoute<RouteTypesById<TRouter, TId>['fullPath']> = ( + opts, + ) => redirect({ from: this.id as string, ...opts } as any) } export interface RootRoute< @@ -1894,25 +2052,25 @@ export interface RootRoute< in out TServerMiddlewares = unknown, in out THandlers = undefined, > extends Route< - TRegister, - any, // TParentRoute - '/', // TPath - '/', // TFullPath - string, // TCustomId - RootRouteId, // TId - TSearchValidator, // TSearchValidator - {}, // TParams - TRouterContext, - TRouteContextFn, - TBeforeLoadFn, - TLoaderDeps, - TLoaderFn, - TChildren, // TChildren - TFileRouteTypes, - TSSR, - TServerMiddlewares, - THandlers - > {} + TRegister, + any, // TParentRoute + '/', // TPath + '/', // TFullPath + string, // TCustomId + RootRouteId, // TId + TSearchValidator, // TSearchValidator + {}, // TParams + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TLoaderDeps, + TLoaderFn, + TChildren, // TChildren + TFileRouteTypes, + TSSR, + TServerMiddlewares, + THandlers +> {} export class BaseRootRoute< in out TRegister = Register, diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 54da83a33e..ecf443168d 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -1,54 +1,86 @@ -import { Store, batch } from '@tanstack/store' -import { createBrowserHistory, parseHref } from '@tanstack/history' import { - createControlledPromise, + createBrowserHistory, + normalizeProtocolRelative, + parseHref, +} from '@tanstack/history' +import { isServer, loadServerRoute } from '@tanstack/router-core/isServer' +import { + DEFAULT_PROTOCOL_ALLOWLIST, + createNull, decodePath, deepEqual, + encodePathLikeUrl, findLast, functionalUpdate, + getUrlScheme, + hasKeys, + hasOwn, + isDangerousProtocol, last, + nullReplaceEqualDeep, + protocolRelativePrefixRegex, replaceEqualDeep, } from './utils' import { + buildRouteBranch, findFlatMatch, findRouteMatch, findSingleMatch, + parseSegments, processRouteMasks, processRouteTree, } from './new-process-route-tree' import { - cleanPath, + compileDecodeCharMap, interpolatePath, resolvePath, trimPath, trimPathRight, } from './path' -import { createLRUCache } from './lru-cache' +import { createSieveCache } from './sieve-cache' import { isNotFound } from './not-found' import { setupScrollRestoration } from './scroll-restoration' import { defaultParseSearch, defaultStringifySearch } from './searchParams' import { rootRouteId } from './root' -import { isRedirect, redirect } from './redirect' -import { loadMatches, loadRouteChunk, routeNeedsPreload } from './load-matches' +import { isRedirect } from './redirect' +import { + loadClientRoute, + loadRouteChunk, + preloadClientRoute, + refreshClientRoute, + replaceRouteChunk, +} from './load-client' import { - composeRewrites, executeRewriteInput, executeRewriteOutput, rewriteBasepath, } from './rewrite' -import type { ProcessedTree } from './new-process-route-tree' +import { createRouterStores } from './stores' +import type { SieveCache } from './sieve-cache' +import type { RouteInterpolation } from './path' +import type { + ProcessRouteTreeResult, + ProcessedTree, +} from './new-process-route-tree' import type { SearchParser, SearchSerializer } from './searchParams' import type { AnyRedirect, ResolvedRedirect } from './redirect' import type { + LoadTransaction, + LoaderFlight, + PendingSession, +} from './load-client' +import type { ServerLoadResult } from './load-server' +import type { + HistoryAction, HistoryLocation, HistoryState, ParsedHistoryState, RouterHistory, } from '@tanstack/history' + import type { Awaitable, Constrain, - ControlledPromise, NoInfer, NonNullableUpdater, PickAsRequired, @@ -59,11 +91,11 @@ import type { AnyContext, AnyRoute, AnyRouteWithContext, + LoaderStaleReloadMode, MakeRemountDepsOptionsUnion, - RouteContextOptions, - RouteLike, RouteMask, SearchMiddleware, + SearchMiddlewareMeta, } from './route' import type { FullSearchSchema, @@ -83,23 +115,37 @@ import type { CommitLocationOptions, NavigateFn, } from './RouterProvider' -import type { Manifest, RouterManagedTag } from './manifest' +import type { Manifest, ManifestRouteAssets } from './manifest' import type { AnySchema, AnyValidator } from './validators' import type { NavigateOptions, ResolveRelativePath, ToOptions } from './link' -import type { NotFoundError } from './not-found' import type { AnySerializationAdapter, ValidateSerializableInput, } from './ssr/serializer/transformer' -// import type { AnyRouterConfig } from './config' +import type { + HydrationScriptOutput, + InitialHydrationScriptTags, +} from './ssr/hydrationScripts' +import type { GetStoreConfig, RouterStores } from './stores' + +function isExternalUrl(url: URL, origin: string) { + return ( + (url.protocol !== 'http:' && url.protocol !== 'https:') || + url.origin !== origin || + !!url.username || + !!url.password + ) +} + +function getUrlPath(url: URL) { + return url.pathname + url.search + url.hash +} export type ControllablePromise<T = any> = Promise<T> & { resolve: (value: T) => void reject: (value?: any) => void } -export type InjectedHtmlEntry = Promise<string> - export interface Register { // Lots of things on here like... // router @@ -137,8 +183,7 @@ export type DefaultRemountDepsFn<TRouteTree extends AnyRoute> = ( export interface DefaultRouterOptionsExtensions {} -export interface RouterOptionsExtensions - extends DefaultRouterOptionsExtensions {} +export interface RouterOptionsExtensions extends DefaultRouterOptionsExtensions {} export type SSROption = boolean | 'data-only' @@ -187,7 +232,8 @@ export interface RouterOptions< */ defaultPreload?: false | 'intent' | 'viewport' | 'render' /** - * The delay in milliseconds that a route must be hovered over or touched before it is preloaded. + * The delay in milliseconds before intent focus/hover and viewport preloading. + * Touch intent preloads immediately. * * @default 50 * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreloaddelay-property) @@ -226,6 +272,15 @@ export interface RouterOptions< * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#key-options) */ defaultStaleTime?: number + /** + * The default stale reload mode a route loader should use if no `loader.staleReloadMode` is provided. + * + * `'background'` preserves the current stale-while-revalidate behavior. + * `'blocking'` waits for stale loader reloads to complete before resolving navigation. + * + * @default 'background' + */ + defaultStaleReloadMode?: LoaderStaleReloadMode /** * The default `preloadStaleTime` a route should use if no preloadStaleTime is provided. * @@ -235,9 +290,9 @@ export interface RouterOptions< */ defaultPreloadStaleTime?: number /** - * The default `defaultPreloadGcTime` a route should use if no preloadGcTime is provided. + * The default `preloadGcTime` a route should use if none is provided. * - * @default 1_800_000 `(30 minutes)` + * @default 300_000 `(5 minutes)` * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreloadgctime-property) * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading) */ @@ -269,7 +324,7 @@ export interface RouterOptions< /** * The default `gcTime` a route should use if no gcTime is provided. * - * @default 1_800_000 `(30 minutes)` + * @default 300_000 `(5 minutes)` * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultgctime-property) * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#key-options) */ @@ -318,9 +373,8 @@ export interface RouterOptions< * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#dehydrate-method) * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/external-data-loading#critical-dehydrationhydration) */ - dehydrate?: () => Constrain< - TDehydrated, - ValidateSerializableInput<Register, TDehydrated> + dehydrate?: () => Awaitable< + Constrain<TDehydrated, ValidateSerializableInput<Register, TDehydrated>> > /** * A function that will be called when the router is hydrated. @@ -412,11 +466,12 @@ export interface RouterOptions< /** * Configures which URI characters are allowed in path params that would ordinarily be escaped by encodeURIComponent. + * This is read only during initialization. Create a new router to change it. * * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#pathparamsallowedcharacters-property) * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/path-params#allowed-characters) */ - pathParamsAllowedCharacters?: Array< + readonly pathParamsAllowedCharacters?: ReadonlyArray< ';' | ':' | '@' | '&' | '=' | '+' | '$' | ',' > @@ -461,6 +516,15 @@ export interface RouterOptions< */ disableGlobalCatchBoundary?: boolean + /** + * An array of URL protocols to allow in links, redirects, and navigation. + * Absolute URLs with protocols not in this list will be rejected. + * + * @default DEFAULT_PROTOCOL_ALLOWLIST (http:, https:, mailto:, tel:) + * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#protocolallowlist-property) + */ + protocolAllowlist?: Array<string> + serializationAdapters?: ReadonlyArray<AnySerializationAdapter> /** * Configures how the router will rewrite the location between the actual href and the internal href of the router. @@ -470,6 +534,11 @@ export interface RouterOptions< * This is useful for shifting data from the origin to the path (for things like subdomain routing), or other advanced use cases. */ rewrite?: LocationRewrite + /** + * The origin used to resolve URLs. Pass a normalized origin, such as + * `https://example.com` or `http://localhost:3000`, without a path or trailing slash. + * Defaults to the browser origin, or `http://localhost` on the server. + */ origin?: string ssr?: { nonce?: string @@ -508,16 +577,10 @@ export interface RouterState< in out TRouteMatch = MakeRouteMatchUnion, > { status: 'pending' | 'idle' - loadedAt: number isLoading: boolean - isTransitioning: boolean matches: Array<TRouteMatch> - pendingMatches?: Array<TRouteMatch> - cachedMatches: Array<TRouteMatch> location: ParsedLocation<FullSearchSchema<TRouteTree>> resolvedLocation?: ParsedLocation<FullSearchSchema<TRouteTree>> - statusCode: number - redirect?: AnyRedirect } export interface BuildNextOptions { @@ -585,10 +648,21 @@ export type SubscribeFn = <TType extends keyof RouterEvents>( ) => () => void export interface MatchRoutesOpts { - preload?: boolean throwOnError?: boolean - _buildLocation?: boolean - dest?: BuildNextOptions + /** @internal */ + _controller?: AbortController + /** @internal */ + _rematerialize?: boolean +} + +function routeNeedsLoad(route: AnyRoute): unknown { + return ( + route.options.loader || + route.options.beforeLoad || + route.lazyFn || + (route.options.component as any)?.preload || + (route.options.pendingComponent as any)?.preload + ) } export type InferRouterContext<TRouteTree extends AnyRoute> = @@ -626,6 +700,7 @@ export type PreloadRouteFn< TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean, TRouterHistory extends RouterHistory, + TDehydrated extends Record<string, any> = Record<string, any>, > = < TFrom extends RoutePaths<TRouteTree> | string = string, TTo extends string | undefined = undefined, @@ -637,7 +712,8 @@ export type PreloadRouteFn< TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, - TRouterHistory + TRouterHistory, + TDehydrated >, TFrom, TTo, @@ -676,12 +752,15 @@ export type UpdateFn< TRouterHistory extends RouterHistory, TDehydrated extends Record<string, any>, > = ( - newOptions: RouterConstructorOptions< - TRouteTree, - TTrailingSlashOption, - TDefaultStructuralSharingOption, - TRouterHistory, - TDehydrated + newOptions: Omit< + RouterConstructorOptions< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated + >, + 'pathParamsAllowedCharacters' >, ) => void @@ -696,15 +775,22 @@ export type ParseLocationFn<TRouteTree extends AnyRoute> = ( previousLocation?: ParsedLocation<FullSearchSchema<TRouteTree>>, ) => ParsedLocation<FullSearchSchema<TRouteTree>> -export type GetMatchRoutesFn = (pathname: string) => { - matchedRoutes: ReadonlyArray<AnyRoute> - routeParams: Record<string, string> - foundRoute: AnyRoute | undefined -} +export type GetMatchRoutesFn = (pathname: string) => [ + matchedRoutes: ReadonlyArray<AnyRoute>, + /** exhaustive params, still in their string form */ + rawParams: Record<string, string>, + foundRoute: AnyRoute | undefined, +] export type EmitFn = (routerEvent: RouterEvent) => void -export type LoadFn = (opts?: { sync?: boolean }) => Promise<void> +export type LoadFn = (opts?: { + sync?: boolean + action?: { type: HistoryAction } + _signal?: AbortSignal + /** @private Reuse the location already prepared for this SSR request. */ + _skipLocationUpdate?: boolean +}) => Promise<void> export type CommitLocationFn = ({ viewTransition, @@ -712,7 +798,10 @@ export type CommitLocationFn = ({ ...next }: ParsedLocation & CommitLocationOptions) => Promise<void> -export type StartTransitionFn = (fn: () => void) => void +export type StartTransitionFn = ( + fn: () => void, + expected: Array<AnyRouteMatch>, +) => Promise<boolean> export interface MatchRoutesFn { ( @@ -731,13 +820,6 @@ export interface MatchRoutesFn { ): Array<AnyRouteMatch> } -export type GetMatchFn = (matchId: string) => AnyRouteMatch | undefined - -export type UpdateMatchFn = ( - id: string, - updater: (match: AnyRouteMatch) => AnyRouteMatch, -) => void - export type LoadRouteChunkFn = (route: AnyRoute) => Promise<Array<void>> export type ResolveRedirect = (err: AnyRedirect) => ResolvedRedirect @@ -746,18 +828,63 @@ export type ClearCacheFn<TRouter extends AnyRouter> = (opts?: { filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean }) => void +/** + * Server-side SSR request contract. + * + * Tiering rule: the flat methods are the adapter/framework contract; + * `hydrationScripts` is transport for the core SSR stream merger only. + * New members must land on the matching tier. + */ export interface ServerSsr { - injectedHtml: Array<InjectedHtmlEntry> - injectHtml: (getHtml: () => string | Promise<string>) => Promise<void> - injectScript: ( - getScript: () => string | Promise<string>, - opts?: { logScript?: boolean }, - ) => Promise<void> - isDehydrated: () => boolean + /** @internal Transport access for the core SSR stream merger. */ + readonly hydrationScripts: { + /** Request signal already observed by the live response transform. */ + requestSignal?: AbortSignal + reserveFastPath: (output?: HydrationScriptOutput) => boolean + claimOutput: () => HydrationScriptOutput + liftBarrier: () => void + isInitialTaken: () => boolean + skipInitialTake: () => void + startSerializationTimeout: (timeoutMs: number) => void + } + /** Framework-only. */ onRenderFinished: (listener: () => void) => void - dehydrate: () => Promise<void> - takeBufferedScripts: () => RouterManagedTag | undefined - liftScriptBarrier: () => void + /** Framework-only. */ + setRenderFinished: () => void + /** Framework-only. */ + cleanup: () => void + /** + * Register a listener invoked when the SSR request lifecycle ends (success, + * error, abort, or stream lifetime expiry). Use to tear down per-request + * resources whose references would otherwise pin the router (e.g. query + * cache subscriptions, gcTime timers, abort controllers). + * + * `settled` is true when every value the router dehydrated has settled, so + * no loader work can still be pending. It is false when the response ended + * early (abort, cancellation, timeout) or never consumed the loader data. + * + * Listeners run synchronously and exactly once. Errors are caught and logged. + * A listener registered after cleanup already ran is invoked immediately. + */ + onCleanup: (listener: (settled: boolean) => void) => void + /** Framework-only. */ + dehydrate: (opts?: { + requestAssets?: ManifestRouteAssets + signal?: AbortSignal + }) => Promise<void> + /** + * Framework-only: opt this request out of hydration output entirely (for + * example a `hydrate: false` page). Call instead of `dehydrate()`, before + * rendering starts. No hydration scripts are emitted, `<Scripts>` renders + * no boundary, and the response takes the pass-through stream path. + */ + disableHydration: () => void + /** Framework-only. */ + takeInitialHydrationScriptTags: () => InitialHydrationScriptTags | undefined +} + +export interface RouterSsrLifecycle { + onServerSsrAttach?: Array<(serverSsr: ServerSsr) => void> } export type AnyRouterWithContext<TContext> = RouterCore< @@ -818,20 +945,106 @@ export type TrailingSlashOption = /** * Compute whether path, href or hash changed between previous and current - * resolved locations in router state. + * resolved locations. */ -export function getLocationChangeInfo(routerState: { - resolvedLocation?: ParsedLocation - location: ParsedLocation -}) { - const fromLocation = routerState.resolvedLocation - const toLocation = routerState.location - const pathChanged = fromLocation?.pathname !== toLocation.pathname - const hrefChanged = fromLocation?.href !== toLocation.href - const hashChanged = fromLocation?.hash !== toLocation.hash - return { fromLocation, toLocation, pathChanged, hrefChanged, hashChanged } +export function getLocationChangeInfo( + location: ParsedLocation, + resolvedLocation?: ParsedLocation, +) { + return { + fromLocation: resolvedLocation, + toLocation: location, + pathChanged: resolvedLocation?.pathname !== location.pathname, + hrefChanged: resolvedLocation?.href !== location.href, + hashChanged: resolvedLocation?.hash !== location.hash, + } } +/** + * Return only state owned by the application, excluding volatile history + * bookkeeping. Mask payloads (`__tempLocation`/`__tempKey`) are kept: they + * distinguish otherwise-identical locations. + */ +export function _getUserHistoryState({ + key: _key, + __TSR_key: _tsrKey, + __TSR_index: _tsrIndex, + __hashScrollIntoViewOptions: _hashScroll, + ...state +}: ParsedHistoryState): HistoryState { + return state +} + +export function lifecycleEnd(matches: Array<AnyRouteMatch>) { + return ( + matches.findIndex( + (match) => + match.status === 'error' || + match.status === 'notFound' || + match._notFound, + ) + 1 + ) +} + +/** Run route lifecycle callbacks in leave/enter/stay phases. */ +export function runRouteLifecycle( + router: AnyRouter, + previous: Array<AnyRouteMatch>, + matches: Array<AnyRouteMatch>, + previousEnd: number | undefined, + nextEnd: number, + owner?: LoadTransaction, +): void { + // Zero or undefined means the full branch; copy only at a fallback. + if (previousEnd) { + previous = previous.slice(0, previousEnd) + } + if (nextEnd) { + matches = matches.slice(0, nextEnd) + } + for (const match of previous) { + if (owner && router._tx !== owner) { + return + } + if (!matches.some((candidate) => candidate.routeId === match.routeId)) { + ;(router.routesById as Record<string, AnyRoute>)[ + match.routeId + ]!.options.onLeave?.(match) + } + } + for (const match of matches) { + if (owner && router._tx !== owner) { + return + } + const route = (router.routesById as Record<string, AnyRoute>)[ + match.routeId + ]! + route.options[ + previous.some((candidate) => candidate.routeId === match.routeId) + ? 'onStay' + : 'onEnter' + ]?.(match) + } +} + +type LightweightRouteMatchResult = [ + matchedRoutes: ReadonlyArray<AnyRoute>, + fullPath: string, + search: Record<string, unknown>, + params: Record<string, unknown>, +] + +type LightweightRouteMatchCacheEntry = [ + lastMatchId: string | undefined, + result: LightweightRouteMatchResult, +] + +/** Indexes and caches rebuilt together when the route tree changes. */ +type RouteTreeCaches<TRouteTree extends AnyRoute> = + ProcessRouteTreeResult<TRouteTree> & { + resolvePathCache: SieveCache<string, string> + } + export type CreateRouterFn = < TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption = 'never', @@ -856,6 +1069,62 @@ export type CreateRouterFn = < TDehydrated > +declare global { + // eslint-disable-next-line no-var + var __TSR_CACHE__: + | { + routeTree: AnyRoute + caseSensitive: boolean | undefined + processRouteTreeResult: RouteTreeCaches<AnyRoute> + } + | undefined +} + +export interface RouterCore< + in out TRouteTree extends AnyRoute, + in out TTrailingSlashOption extends TrailingSlashOption, + in out TDefaultStructuralSharingOption extends boolean, + in out TRouterHistory extends RouterHistory = RouterHistory, + in out TDehydrated extends Record<string, any> = Record<string, any>, +> { + shouldViewTransition?: boolean | ViewTransitionOptions + /** + * Foreground lifecycle boundary survives invalidation/background statuses. + * Zero or undefined means the whole branch participates. + */ + _lifecycleEnd?: number + /** Current client load transaction and owner of navigation writes. */ + _tx?: LoadTransaction + /** Joinable in-flight loader generations keyed by match ID. */ + _flights?: Map<string, LoaderFlight> + /** Active speculative lanes retained for cancellation, invalidation, and cache clearing. */ + _preloads?: Map<AbortController, Array<AnyRouteMatch>> + /** Owns cancellable work before a client transaction publishes. */ + _preflight?: AbortController + /** Transfers one reconstructed SSR prefix into its initial client load. */ + _handoff?: HydrationHandoff + /** Pending-boundary reveal and minimum-visible timing state. */ + _pending?: PendingSession + /** Result of the latest server load, used to render or redirect. */ + _serverResult?: ServerLoadResult + /** Framework publication waiting for an exact render acknowledgement. */ + _rendered?: [ + offered?: Array<AnyRouteMatch>, + settle?: (rendered: boolean) => void, + ] + /** Development-only HMR reload for a route and its descendants. */ + _refreshRoute: (() => Promise<void>) | undefined + /** Development-only replacement for a route's lazy chunk owner. */ + _replaceRouteChunk: + | ((route: AnyRoute, lazyFn: AnyRoute['lazyFn']) => void) + | undefined +} + +export type HydrationHandoff = [ + claim: () => AbortController | undefined, + finish: (matches?: Array<AnyRouteMatch>) => number | undefined, +] + /** * Core, framework-agnostic router engine that powers TanStack Router. * @@ -876,16 +1145,25 @@ export class RouterCore< tempLocationKey: string | undefined = `${Math.round( Math.random() * 10000000, )}` - resetNextScroll = true - shouldViewTransition?: boolean | ViewTransitionOptions = undefined - isViewTransitionTypesSupported?: boolean = undefined + _scroll: { + n: boolean // Reset scroll on the next render. + // True until the current PUSH/REPLACE renders, so its hash owns window scroll. + h?: boolean + e?: boolean // Restoration enabled. + s?: boolean // Snapshot/lifecycle listeners installed. + r?: boolean // Render listener installed. + } = { n: true } subscribers = new Set<RouterListener<RouterEvent>>() - viewTransitionPromise?: ControlledPromise<true> - isScrollRestoring = false - isScrollRestorationSetup = false + /** Accepted off-screen loader generations keyed by match ID. */ + _cache = new Map<string, AnyRouteMatch>() + /** Accepted semantic lane, excluding temporary pending presentation. */ + _committed: Array<AnyRouteMatch> = [] // Must build in constructor - __store!: Store<RouterState<TRouteTree>> + stores!: RouterStores<TRouteTree> + private getStoreConfig!: GetStoreConfig + batch!: (fn: () => void) => void + options!: PickAsRequired< RouterOptions< TRouteTree, @@ -898,16 +1176,27 @@ export class RouterCore< > history!: TRouterHistory rewrite?: LocationRewrite - origin?: string + origin!: string latestLocation!: ParsedLocation<FullSearchSchema<TRouteTree>> - pendingBuiltLocation?: ParsedLocation<FullSearchSchema<TRouteTree>> + _pendingLocation?: ParsedLocation<FullSearchSchema<TRouteTree>> basepath!: string routeTree!: TRouteTree routesById!: RoutesById<TRouteTree> routesByPath!: RoutesByPath<TRouteTree> processedTree!: ProcessedTree<TRouteTree, any, any> + resolvePathCache!: SieveCache<string, string> + private lightweightCache!: WeakMap< + ParsedLocation, + LightweightRouteMatchCacheEntry + > + // Locations built without reading the current location, keyed by the stable + // options object a Link owns. Links pass a new object when their values change. + // Client only: server renders never repeat an options object, so server + // bundles fold `isServer` and drop the cache entirely. + private staticLocations: WeakMap<object, ParsedLocation> | undefined isServer!: boolean - pathParamsDecodeCharMap?: Map<string, string> + readonly pathParamsDecoder?: (encoded: string) => string + protocolAllowlist!: Set<string> /** * @deprecated Use the `createRouter` function instead @@ -920,7 +1209,15 @@ export class RouterCore< TRouterHistory, TDehydrated >, + getStoreConfig: GetStoreConfig, ) { + this.getStoreConfig = getStoreConfig + if (options.pathParamsAllowedCharacters?.length) { + this.pathParamsDecoder = compileDecodeCharMap( + options.pathParamsAllowedCharacters, + ) + } + this.update({ defaultPreloadDelay: 50, defaultPendingMs: 1000, @@ -931,26 +1228,23 @@ export class RouterCore< notFoundMode: options.notFoundMode ?? 'fuzzy', stringifySearch: options.stringifySearch ?? defaultStringifySearch, parseSearch: options.parseSearch ?? defaultParseSearch, + protocolAllowlist: + options.protocolAllowlist ?? DEFAULT_PROTOCOL_ALLOWLIST, }) - if (typeof document !== 'undefined') { + if (!(isServer ?? typeof document === 'undefined')) { self.__TSR_ROUTER__ = this } } - // These are default implementations that can optionally be overridden - // by the router provider once rendered. We provide these so that the - // router can be used in a non-react environment if necessary - startTransition: StartTransitionFn = (fn) => fn() - + startTransition: StartTransitionFn = async (fn) => { + fn() + return false + } isShell() { return !!this.options.isShell } - isPrerendering() { - return !!this.options.isPrerendering - } - update: UpdateFn< TRouteTree, TTrailingSlashOption, @@ -958,39 +1252,36 @@ export class RouterCore< TRouterHistory, TDehydrated > = (newOptions) => { - if (newOptions.notFoundRoute) { - console.warn( - 'The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/framework/react/guide/not-found-errors#migrating-from-notfoundroute for more info.', - ) + if (process.env.NODE_ENV !== 'production') { + if (newOptions.notFoundRoute) { + console.warn( + 'The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/framework/react/guide/not-found-errors#migrating-from-notfoundroute for more info.', + ) + } } const prevOptions = this.options - const prevBasepath = this.basepath ?? prevOptions?.basepath ?? '/' - const basepathWasUnset = this.basepath === undefined - const prevRewriteOption = prevOptions?.rewrite this.options = { ...prevOptions, ...newOptions, } - this.isServer = this.options.isServer ?? typeof document === 'undefined' + this.isServer = + this.options.isServer ?? isServer ?? typeof document === 'undefined' + // `isServer` is a per-bundle constant, so server builds drop the cache. + if (!(isServer ?? this.isServer)) { + this.staticLocations = new WeakMap() + } - this.pathParamsDecodeCharMap = this.options.pathParamsAllowedCharacters - ? new Map( - this.options.pathParamsAllowedCharacters.map((char) => [ - encodeURIComponent(char), - char, - ]), - ) - : undefined + this.protocolAllowlist = new Set(this.options.protocolAllowlist) if ( !this.history || (this.options.history && this.options.history !== this.history) ) { if (!this.options.history) { - if (!this.isServer) { + if (!(isServer ?? this.isServer)) { this.history = createBrowserHistory() as TRouterHistory } } else { @@ -998,9 +1289,13 @@ export class RouterCore< } } - this.origin = this.options.origin + this.origin = this.options.origin! if (!this.origin) { - if (!this.isServer && window?.origin && window.origin !== 'null') { + if ( + !(isServer ?? this.isServer) && + window?.origin && + window.origin !== 'null' + ) { this.origin = window.origin } else { // fallback for the server, can be overridden by calling router.update({origin}) on the server @@ -1008,85 +1303,83 @@ export class RouterCore< } } + const nextBasepath = this.options.basepath ?? '/' + const nextRewriteOption = this.options.rewrite + const rewriteChanged = + this.basepath !== nextBasepath || + prevOptions?.rewrite !== nextRewriteOption || + prevOptions?.caseSensitive !== this.options.caseSensitive + + if (rewriteChanged) { + this.basepath = nextBasepath + + this.rewrite = + nextBasepath !== '/' && trimPath(nextBasepath) + ? rewriteBasepath( + nextBasepath, + this.options.caseSensitive, + nextRewriteOption, + ) + : nextRewriteOption + } + + // Parse once, with the final rewrite in place. if (this.history) { this.updateLatestLocation() } - if (this.options.routeTree !== this.routeTree) { - this.routeTree = this.options.routeTree as TRouteTree - this.buildRouteTree() - } - - if (!this.__store && this.latestLocation) { - this.__store = new Store(getInitialRouterState(this.latestLocation), { - onUpdate: () => { - this.__store.state = { - ...this.state, - cachedMatches: this.state.cachedMatches.filter( - (d) => !['redirected'].includes(d.status), - ), - } - }, - }) - - setupScrollRestoration(this) - } - - let needsLocationUpdate = false - const nextBasepath = this.options.basepath ?? '/' - const nextRewriteOption = this.options.rewrite - const basepathChanged = basepathWasUnset || prevBasepath !== nextBasepath - const rewriteChanged = prevRewriteOption !== nextRewriteOption - - if (basepathChanged || rewriteChanged) { - this.basepath = nextBasepath - - const rewrites: Array<LocationRewrite> = [] - if (trimPath(nextBasepath) !== '') { - rewrites.push( - rewriteBasepath({ - basepath: nextBasepath, - }), - ) - } - if (nextRewriteOption) { - rewrites.push(nextRewriteOption) - } - - this.rewrite = - rewrites.length === 0 - ? undefined - : rewrites.length === 1 - ? rewrites[0] - : composeRewrites(rewrites) - - if (this.history) { - this.updateLatestLocation() - } - - needsLocationUpdate = true - } - - if (needsLocationUpdate && this.__store) { - this.__store.state = { - ...this.state, - location: this.latestLocation, - } - } - if ( - typeof window !== 'undefined' && - 'CSS' in window && - typeof window.CSS?.supports === 'function' + this.options.routeTree !== this.routeTree || + ((isServer ?? this.isServer) && + prevOptions?.caseSensitive !== this.options.caseSensitive) ) { - this.isViewTransitionTypesSupported = window.CSS.supports( - 'selector(:active-view-transition-type(a)', - ) + this.routeTree = this.options.routeTree as TRouteTree + let processRouteTreeResult: RouteTreeCaches<TRouteTree> + if ( + process.env.NODE_ENV !== 'development' && + (isServer ?? this.isServer) && + globalThis.__TSR_CACHE__ && + globalThis.__TSR_CACHE__.routeTree === this.routeTree && + globalThis.__TSR_CACHE__.caseSensitive === this.options.caseSensitive + ) { + const cached = globalThis.__TSR_CACHE__ + processRouteTreeResult = cached.processRouteTreeResult as any + } else { + processRouteTreeResult = this.buildRouteTree() + // only cache if nothing else is cached yet + if ( + process.env.NODE_ENV !== 'development' && + (isServer ?? this.isServer) && + globalThis.__TSR_CACHE__ === undefined + ) { + globalThis.__TSR_CACHE__ = { + routeTree: this.routeTree, + caseSensitive: this.options.caseSensitive, + processRouteTreeResult: processRouteTreeResult as any, + } + } + } + this.setRoutes(processRouteTreeResult) + } + + if (!this.stores) { + if (this.latestLocation) { + const config = this.getStoreConfig(this) + this.batch = config.batch + this.stores = createRouterStores(this.latestLocation, config) + + if (!(isServer ?? this.isServer)) { + setupScrollRestoration(this) + } + } + } else if (rewriteChanged) { + // Existing stores hold the location parsed with the previous rewrite. + this.stores.location.set(this.latestLocation) } } get state(): RouterState<TRouteTree> { - return this.__store.state + return this.stores.__store.get() } updateLatestLocation = () => { @@ -1096,30 +1389,33 @@ export class RouterCore< ) } - buildRouteTree = () => { - const { routesById, routesByPath, processedTree } = processRouteTree( - this.routeTree, - this.options.caseSensitive, - (route, i) => { - route.init({ - originalIndex: i, - }) - }, - ) + buildRouteTree = (): RouteTreeCaches<TRouteTree> => { + const result = processRouteTree(this.routeTree, this.options.caseSensitive) if (this.options.routeMasks) { - processRouteMasks(this.options.routeMasks, processedTree) + processRouteMasks(this.options.routeMasks, result.processedTree) } - this.routesById = routesById as RoutesById<TRouteTree> - this.routesByPath = routesByPath as RoutesByPath<TRouteTree> - this.processedTree = processedTree + return { + ...result, + resolvePathCache: createSieveCache(1000), + } + } + + setRoutes(caches: RouteTreeCaches<TRouteTree>) { + Object.assign(this, caches) + this.lightweightCache = new WeakMap() + if (!(isServer ?? this.isServer)) { + this.staticLocations = new WeakMap() + } const notFoundRoute = this.options.notFoundRoute if (notFoundRoute) { - notFoundRoute.init({ - originalIndex: 99999999999, - }) + notFoundRoute.init(99999999999) + if (this.routesById[notFoundRoute.id] !== notFoundRoute) { + // Standalone legacy fallbacks are not processed by the matching tree. + notFoundRoute._interpolation = parseSegments(false, notFoundRoute, 0) + } this.routesById[notFoundRoute.id] = notFoundRoute } } @@ -1144,11 +1440,15 @@ export class RouterCore< } emit: EmitFn = (routerEvent) => { - this.subscribers.forEach((listener) => { + for (const listener of this.subscribers) { if (listener.eventType === routerEvent.type) { - listener.fn(routerEvent) + try { + listener.fn(routerEvent) + } catch (e) { + console.error(e) + } } - }) + } } /** @@ -1159,14 +1459,35 @@ export class RouterCore< locationToParse, previousLocation, ) => { - const parse = ({ - href, - state, - }: HistoryLocation): ParsedLocation<FullSearchSchema<TRouteTree>> => { - // Before we do any processing, we need to allow rewrites to modify the URL - // build up the full URL by combining the href from history with the router's origin - const fullUrl = new URL(href, this.origin) - const url = executeRewriteInput(this.rewrite, fullUrl) + const parse = ( + { pathname, search, hash, href }: HistoryLocation, + state: HistoryLocation['state'], + ): ParsedLocation<FullSearchSchema<TRouteTree>> => { + // Fast path: no rewrite configured and pathname doesn't need encoding + // Characters that need encoding: space, high unicode, control chars + // eslint-disable-next-line no-control-regex + if (!this.rewrite && !/[ \x00-\x1f\x7f\u0080-\uffff]/.test(pathname)) { + const parsedSearch = this.options.parseSearch(search) + const searchStr = this.options.stringifySearch(parsedSearch) + + return { + href: pathname + searchStr + hash, + publicHref: pathname + searchStr + hash, + pathname: decodePath(pathname), + external: false, + searchStr, + search: nullReplaceEqualDeep( + previousLocation?.search, + parsedSearch, + ) as any, + hash: decodePath(hash.slice(1)), + state: replaceEqualDeep(previousLocation?.state, state), + } + } + + // The URL constructor normalizes the encoding of the history href; an + // input rewrite may then change the URL before it is parsed. + const url = executeRewriteInput(this.rewrite, new URL(href, this.origin)) const parsedSearch = this.options.parseSearch(url.search) const searchStr = this.options.stringifySearch(parsedSearch) @@ -1174,57 +1495,43 @@ export class RouterCore< // (We were already doing this, so just keeping it for now) url.search = searchStr - const fullPath = url.href.replace(url.origin, '') - return { - href: fullPath, + href: url.href.replace(url.origin, ''), publicHref: href, - url: url, - pathname: decodePath(url.pathname), + // An input rewrite can expose a path like "//evil.example". + // Normalize it to "/evil.example" to keep it on the current origin. + pathname: decodePath(normalizeProtocolRelative(url.pathname)), + external: !!this.rewrite && isExternalUrl(url, this.origin), searchStr, - search: replaceEqualDeep(previousLocation?.search, parsedSearch) as any, - hash: url.hash.split('#').reverse()[0] ?? '', + search: nullReplaceEqualDeep( + previousLocation?.search, + parsedSearch, + ) as any, + hash: decodePath(url.hash.slice(1)), state: replaceEqualDeep(previousLocation?.state, state), } } - const location = parse(locationToParse) + const location = parse(locationToParse, locationToParse.state) const { __tempLocation, __tempKey } = location.state if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) { - // Sync up the location keys - const parsedTempLocation = parse(__tempLocation) as any - parsedTempLocation.state.key = location.state.key // TODO: Remove in v2 - use __TSR_key instead - parsedTempLocation.state.__TSR_key = location.state.__TSR_key - - delete parsedTempLocation.state.__tempLocation - - return { - ...parsedTempLocation, - maskedLocation: location, - } + // A masked entry stores the real location in its state. That location is + // presented, adopting the committed entry's keys, while the URL that was + // written to history remains available as `maskedLocation`. + const parsedTempLocation = parse(__tempLocation, { + ...__tempLocation.state, + __tempLocation: undefined, + key: location.state.key, // TODO: Remove in v2 - use __TSR_key instead + __TSR_key: location.state.__TSR_key, + }) + parsedTempLocation.maskedLocation = location + return parsedTempLocation } return location } - resolvePathCache = createLRUCache<string, string>(1000) - - /** Resolve a path against the router basepath and trailing-slash policy. */ - resolvePathWithBase = (from: string, path: string) => { - const resolvedPath = resolvePath({ - base: from, - to: cleanPath(path), - trailingSlash: this.options.trailingSlash, - cache: this.resolvePathCache, - }) - return resolvedPath - } - - get looseRoutesById() { - return this.routesById as Record<string, AnyRoute> - } - matchRoutes: MatchRoutesFn = ( pathnameOrNext: string | ParsedLocation, locationSearchOrOpts?: AnySchema | MatchRoutesOpts, @@ -1247,16 +1554,17 @@ export class RouterCore< next: ParsedLocation, opts?: MatchRoutesOpts, ): Array<AnyRouteMatch> { - const matchedRoutesResult = this.getMatchedRoutes(next.pathname) - const { foundRoute, routeParams } = matchedRoutesResult - let { matchedRoutes } = matchedRoutesResult + const [initialMatchedRoutes, rawParams, foundRoute] = this.getMatchedRoutes( + next.pathname, + ) + let matchedRoutes = initialMatchedRoutes let isGlobalNotFound = false // Check to see if the route needs a 404 entry if ( // If we found a route, and it's not an index route and we have left over path foundRoute - ? foundRoute.path !== '/' && routeParams['**'] + ? foundRoute.path !== '/' && rawParams['**'] : // Or if we didn't find a route and we have left over path trimPathRight(next.pathname) ) { @@ -1269,36 +1577,24 @@ export class RouterCore< } } - const globalNotFoundRouteId = (() => { - if (!isGlobalNotFound) { - return undefined - } + const _notFoundRouteId = isGlobalNotFound + ? findGlobalNotFoundRouteId(this.options.notFoundMode, matchedRoutes) + : undefined - if (this.options.notFoundMode !== 'root') { - for (let i = matchedRoutes.length - 1; i >= 0; i--) { - const route = matchedRoutes[i]! - if (route.children) { - return route.id - } - } - } - - return rootRouteId - })() - - const matches: Array<AnyRouteMatch> = [] - - const getParentContext = (parentMatch?: AnyRouteMatch) => { - const parentMatchId = parentMatch?.id - - const parentContext = !parentMatchId - ? ((this.options.context as any) ?? undefined) - : (parentMatch.context ?? this.options.context ?? undefined) - - return parentContext + const matches = new Array<AnyRouteMatch>(matchedRoutes.length) + const committed = this._committed + const previousAt = (route: AnyRoute, index: number) => { + const match = committed[index] + return match?.routeId === route.id + ? match + : route === this.options.notFoundRoute + ? committed.find((candidate) => candidate.routeId === route.id) + : undefined } - matchedRoutes.forEach((route, index) => { + let strictParams: AnyRouteMatch['_strictParams'] | undefined + for (let index = 0; index < matchedRoutes.length; index++) { + const route = matchedRoutes[index]! // Take each matched route and resolve + validate its search params // This has to happen serially because each route's search params // can depend on the parent route's search params @@ -1308,11 +1604,10 @@ export class RouterCore< const parentMatch = matches[index - 1] - const [preMatchSearch, strictMatchSearch, searchError]: [ - Record<string, any>, - Record<string, any>, - any, - ] = (() => { + let preMatchSearch: Record<string, any> + let strictMatchSearch: Record<string, any> + let searchError: any + { // Validate the search params and stabilize them const parentSearch = parentMatch?.search ?? next.search const parentStrictSearch = parentMatch?._strictSearch ?? undefined @@ -1322,14 +1617,11 @@ export class RouterCore< validateSearch(route.options.validateSearch, { ...parentSearch }) ?? undefined - return [ - { - ...parentSearch, - ...strictSearch, - }, - { ...parentStrictSearch, ...strictSearch }, - undefined, - ] + preMatchSearch = { + ...parentSearch, + ...strictSearch, + } + strictMatchSearch = { ...parentStrictSearch, ...strictSearch } } catch (err: any) { let searchParamError = err if (!(err instanceof SearchParamError)) { @@ -1342,34 +1634,45 @@ export class RouterCore< throw searchParamError } - return [parentSearch, {}, searchParamError] + preMatchSearch = parentSearch + strictMatchSearch = {} + searchError = searchParamError } - })() - + } // This is where we need to call route.options.loaderDeps() to get any additional // deps that the route's loader function might need to run. We need to do this // before we create the match so that we can pass the deps to the route's // potential key function which is used to uniquely identify the route match in state - const loaderDeps = - route.options.loaderDeps?.({ - search: preMatchSearch, - }) ?? '' + let loaderDeps: any = '' + let loaderDepsHash = '' + try { + loaderDeps = + route.options.loaderDeps?.({ + search: preMatchSearch, + }) ?? '' + loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) || '' : '' + } catch (cause) { + if (opts?.throwOnError) { + throw cause + } + searchError ??= cause + } + // Match identity must only use the raw params captured from the URL. + const usedParams: Record<string, unknown> = createNull() + const interpolatedPath = route._interpolation + ? interpolatePath( + route.fullPath, + route._interpolation, + rawParams, + this.pathParamsDecoder, + usedParams, + ) + : route.fullPath - const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : '' - - const { interpolatedPath, usedParams } = interpolatePath({ - path: route.fullPath, - params: routeParams, - decodeCharMap: this.pathParamsDecodeCharMap, - }) - - // Waste not, want not. If we already have a match for this route, - // reuse it. This is important for layout routes, which might stick - // around between navigation actions that only change leaf routes. - - // Existing matches are matches that are already loaded along with - // pending matches that are still loading + // Seed planning from the accepted same-ID cache generation first, then + // from the committed generation for this route. Presentation stores are + // deliberately not a semantic reuse authority. const matchId = // route.id for disambiguation route.id + @@ -1378,44 +1681,37 @@ export class RouterCore< // explicit deps loaderDepsHash - const existingMatch = this.getMatch(matchId) + const previousMatch = previousAt(route, index) + const existingMatch = + process.env.NODE_ENV !== 'production' && opts?._rematerialize + ? undefined + : (this._cache.get(matchId) ?? + (previousMatch?.id === matchId ? previousMatch : undefined)) - const previousMatch = this.state.matches.find( - (d) => d.routeId === route.id, - ) + // Carry parsed ancestors forward without mutating the raw route params. + strictParams = + existingMatch?._strictParams ?? Object.assign(usedParams, strictParams) - const strictParams = existingMatch?._strictParams ?? usedParams - - let paramsError: unknown = undefined + let paramsError: unknown if (!existingMatch) { - const strictParseParams = - route.options.params?.parse ?? route.options.parseParams + try { + extractStrictParams(route, strictParams) + } catch (err: any) { + if (isNotFound(err) || isRedirect(err)) { + paramsError = err + } else { + paramsError = new PathParamError(err.message, { + cause: err, + }) + } - if (strictParseParams) { - try { - Object.assign( - strictParams, - strictParseParams(strictParams as Record<string, string>), - ) - } catch (err: any) { - if (isNotFound(err) || isRedirect(err)) { - paramsError = err - } else { - paramsError = new PathParamError(err.message, { - cause: err, - }) - } - - if (opts?.throwOnError) { - throw paramsError - } + if (opts?.throwOnError) { + throw paramsError } } } - Object.assign(routeParams, strictParams) - const cause = previousMatch ? 'stay' : 'enter' let match: AnyRouteMatch @@ -1424,203 +1720,234 @@ export class RouterCore< match = { ...existingMatch, cause, - params: previousMatch - ? replaceEqualDeep(previousMatch.params, routeParams) - : routeParams, - _strictParams: strictParams, search: previousMatch - ? replaceEqualDeep(previousMatch.search, preMatchSearch) - : replaceEqualDeep(existingMatch.search, preMatchSearch), + ? nullReplaceEqualDeep(previousMatch.search, preMatchSearch) + : nullReplaceEqualDeep(existingMatch.search, preMatchSearch), _strictSearch: strictMatchSearch, + searchError, } } else { - const status = - route.options.loader || - route.options.beforeLoad || - route.lazyFn || - routeNeedsPreload(route) - ? 'pending' - : 'success' + const status = routeNeedsLoad(route) ? 'pending' : 'success' match = { id: matchId, - ssr: this.isServer ? undefined : route.options.ssr, + ssr: (isServer ?? this.isServer) ? undefined : route.options.ssr, index, routeId: route.id, - params: previousMatch - ? replaceEqualDeep(previousMatch.params, routeParams) - : routeParams, + params: previousMatch?.params ?? strictParams, _strictParams: strictParams, pathname: interpolatedPath, updatedAt: Date.now(), search: previousMatch - ? replaceEqualDeep(previousMatch.search, preMatchSearch) + ? nullReplaceEqualDeep(previousMatch.search, preMatchSearch) : preMatchSearch, _strictSearch: strictMatchSearch, - searchError: undefined, + searchError, status, isFetching: false, error: undefined, paramsError, - __routeContext: undefined, - _nonReactive: { - loadPromise: createControlledPromise(), - }, - __beforeLoadContext: undefined, context: {}, - abortController: new AbortController(), - fetchCount: 0, + abortController: opts?._controller ?? new AbortController(), cause, loaderDeps: previousMatch ? replaceEqualDeep(previousMatch.loaderDeps, loaderDeps) : loaderDeps, invalid: false, preload: false, - links: undefined, - scripts: undefined, - headScripts: undefined, - meta: undefined, staticData: route.options.staticData || {}, fullPath: route.fullPath, } } - if (!opts?.preload) { - // If we have a global not found, mark the right match as global not found - match.globalNotFound = globalNotFoundRouteId === route.id + // If we have a global not found, mark the right match as global not found + const _notFound = _notFoundRouteId === route.id + if (match._notFound && !_notFound) { + match.error = undefined } + match._notFound = _notFound - // update the searchError if there is one - match.searchError = searchError + matches[index] = match + } - const parentContext = getParentContext(parentMatch) - - match.context = { - ...parentContext, - ...match.__routeContext, - ...match.__beforeLoadContext, + for (let index = 0; index < matches.length; index++) { + const match = matches[index]! + match.params = + match.cause === 'stay' + ? nullReplaceEqualDeep(match.params, strictParams) + : strictParams! + if (opts?._controller) { + match.context = {} } - - matches.push(match) - }) - - matches.forEach((match, index) => { - const route = this.looseRoutesById[match.routeId]! - const existingMatch = this.getMatch(match.id) - - // only execute `context` if we are not calling from router.buildLocation - - if (!existingMatch && opts?._buildLocation !== true) { - const parentMatch = matches[index - 1] - const parentContext = getParentContext(parentMatch) - - // Update the match's context - - if (route.options.context) { - const contextFnContext: RouteContextOptions<any, any, any, any> = { - deps: match.loaderDeps, - params: match.params, - context: parentContext ?? {}, - location: next, - navigate: (opts: any) => - this.navigate({ ...opts, _fromLocation: next }), - buildLocation: this.buildLocation, - cause: match.cause, - abortController: match.abortController, - preload: !!match.preload, - matches, - } - // Get the route context - match.__routeContext = - route.options.context(contextFnContext) ?? undefined - } - - match.context = { - ...parentContext, - ...match.__routeContext, - ...match.__beforeLoadContext, - } - } - }) + } return matches } getMatchedRoutes: GetMatchRoutesFn = (pathname) => { - return getMatchedRoutes({ - pathname, - routesById: this.routesById, - processedTree: this.processedTree, - }) + const rawParams: Record<string, string> = Object.create(null) + const match = findRouteMatch( + trimPathRight(pathname), + this.processedTree, + true, + ) + if (match) { + Object.assign(rawParams, match.rawParams) + } + return [ + match?.branch || [this.routesById[rootRouteId]!], + rawParams, + match?.route, + ] } - cancelMatch = (id: string) => { - const match = this.getMatch(id) + /** + * Lightweight route matching for buildLocation. + * Only computes fullPath, accumulated search, and params - skipping expensive + * operations like AbortController, loaderDeps, and full match objects. + */ + private matchRoutesLightweight( + location: ParsedLocation, + ): LightweightRouteMatchResult { + const lastRouteId = last(this.stores.ids.get()) + const lastStateMatch = lastRouteId + ? this.stores.byRoute.get(lastRouteId)!.get() + : undefined + const lastStateMatchId = lastStateMatch?.id + const cached = this.lightweightCache.get(location) + if (cached && cached[0 /* lastMatchId */] === lastStateMatchId) { + return cached[1 /* result */] + } - if (!match) return + const [matchedRoutes, rawParams] = this.getMatchedRoutes(location.pathname) + const lastRoute = last(matchedRoutes)! - match.abortController.abort() - clearTimeout(match._nonReactive.pendingTimeout) - match._nonReactive.pendingTimeout = undefined - } + // I don't know if we should run the full search middleware chain, or just validateSearch + // // Accumulate search validation through the route chain + // const accumulatedSearch: Record<string, unknown> = applySearchMiddleware({ + // search: { ...location.search }, + // dest: location, + // destRoutes: matchedRoutes, + // _includeValidateSearch: true, + // }) - cancelMatches = () => { - const currentPendingMatches = this.state.matches.filter( - (match) => match.status === 'pending', - ) - const currentLoadingMatches = this.state.matches.filter( - (match) => match.isFetching === 'loader', - ) - const matchesToCancelArray = new Set([ - ...(this.state.pendingMatches ?? []), - ...currentPendingMatches, - ...currentLoadingMatches, - ]) - matchesToCancelArray.forEach((match) => { - this.cancelMatch(match.id) - }) + // Accumulate search validation through route chain + const accumulatedSearch = { ...location.search } + for (const route of matchedRoutes) { + try { + Object.assign( + accumulatedSearch, + validateSearch(route.options.validateSearch, accumulatedSearch), + ) + } catch { + // Ignore errors, we're not actually routing + } + } + + // Determine params: reuse from state if possible, otherwise parse + const canReuseParams = + lastStateMatch && + lastStateMatch.routeId === lastRoute.id && + lastStateMatch.pathname === location.pathname + + let params: Record<string, unknown> + if (canReuseParams) { + params = lastStateMatch.params + } else { + // Parse params through the route chain + // getMatchedRoutes already copied the cached raw params. + const strictParams: Record<string, unknown> = rawParams + for (const route of matchedRoutes) { + try { + extractStrictParams(route, strictParams) + } catch { + // Ignore errors, we're not actually routing + } + } + params = strictParams + } + + const result: LightweightRouteMatchResult = [ + matchedRoutes, + lastRoute.fullPath, + accumulatedSearch, + params, + ] + this.lightweightCache.set(location, [lastStateMatchId, result]) + return result } /** * Build the next ParsedLocation from navigation options without committing. * Resolves `to`/`from`, params/search/hash/state, applies search validation - * and middlewares, and returns a stable, stringified location object. + * and middlewares, and returns a stringified location object. The built + * `search` and `state` are not structurally shared with the current + * location; `parseLocation` stabilizes them once the location is committed. * * @link https://tanstack.com/router/latest/docs/framework/react/api/router/RouterType#buildlocation-method */ buildLocation: BuildLocationFn = (opts) => { + if (!(isServer ?? this.isServer)) { + const cached = this.staticLocations!.get(opts) + if (cached) { + return cached + } + } + + // Set by `current()` whenever a build reads the current location. A + // location built without it depends only on `opts` and the route tree. + let usedCurrent = false + const build = ( dest: BuildNextOptions & { unmaskOnReload?: boolean } = {}, ): ParsedLocation => { - // We allow the caller to override the current location + if (dest.href) { + const parsed = parseHref(dest.href, {} as ParsedHistoryState) + dest = { + ...dest, + to: executeRewriteInput( + this.rewrite, + new URL(parsed.pathname, this.origin), + ).pathname, + search: this.options.parseSearch(parsed.search), + hash: parsed.hash.slice(1), + } + } + + // We allow the caller to override the current location. Masks build + // from the same location as the destination they mask. const currentLocation = - dest._fromLocation || this.pendingBuiltLocation || this.latestLocation + opts._fromLocation || this._pendingLocation || this.latestLocation - const allCurrentLocationMatches = this.matchRoutes(currentLocation, { - _buildLocation: true, - }) - - // Now let's find the starting pathname - // This should default to the current location if no from is provided - const lastMatch = last(allCurrentLocationMatches)! + // Value-affecting reads of the current location go through these two. + // The lightweight match (fullPath, search, params without full match + // objects) is only computed when a build actually reads it. + let lightweight: LightweightRouteMatchResult | undefined + const current = () => { + usedCurrent = true + return currentLocation + } + const currentMatch = () => + (lightweight ??= this.matchRoutesLightweight(current())) // check that from path exists in the current route tree // do this check only on navigations during test or development if ( - dest.from && process.env.NODE_ENV !== 'production' && + dest.from && dest._isNavigate ) { - const allFromMatches = this.getMatchedRoutes(dest.from).matchedRoutes + const [allFromMatches] = this.getMatchedRoutes(dest.from) + const [matchedRoutes, fullPath] = currentMatch() - const matchedFrom = findLast(allCurrentLocationMatches, (d) => { + const matchedFrom = findLast(matchedRoutes, (d) => { return comparePaths(d.fullPath, dest.from!) }) const matchedCurrent = findLast(allFromMatches, (d) => { - return comparePaths(d.fullPath, lastMatch.fullPath) + return comparePaths(d.fullPath, fullPath) }) // for from to be invalid it shouldn't just be unmatched to currentLocation @@ -1630,100 +1957,157 @@ export class RouterCore< } } - const defaultedFromPath = - dest.unsafeRelative === 'path' - ? currentLocation.pathname - : (dest.from ?? lastMatch.fullPath) + const to = dest.to ? `${dest.to}` : '.' + const nextTo = resolvePath( + // Absolute destinations resolve without a base. + to[0] === '/' + ? '' + : dest.unsafeRelative === 'path' + ? current().pathname + : (dest.from ?? currentMatch()[1 /* fullPath */]), + to, + this.options.trailingSlash, + this.resolvePathCache, + ) - // ensure this includes the basePath if set - const fromPath = this.resolvePathWithBase(defaultedFromPath, '.') + const destRoute = this.routesByPath[ + trimPathRight(nextTo) as keyof typeof this.routesByPath + ] as AnyRoute | undefined - // From search should always use the current location - const fromSearch = lastMatch.search - // Same with params. It can't hurt to provide as many as possible - const fromParams = { ...lastMatch.params } + const isTemplate = nextTo.includes('$') + let destRoutes: ReadonlyArray<AnyRoute> + if (destRoute) { + destRoutes = destRoute._branch ??= buildRouteBranch(destRoute) + } else if (isTemplate) { + // Route templates must match routesByPath exactly. A miss here is a + // typed destination mismatch, not a concrete URL to route-match. + destRoutes = [] + } else { + const [matchedRoutes, rawParams, foundRoute] = + this.getMatchedRoutes(nextTo) + destRoutes = matchedRoutes - // Resolve the next to - // ensure this includes the basePath if set - const nextTo = dest.to - ? this.resolvePathWithBase(fromPath, `${dest.to}`) - : this.resolvePathWithBase(fromPath, '.') - - // Resolve the next params - const nextParams = - dest.params === false || dest.params === null - ? {} - : (dest.params ?? true) === true - ? fromParams - : Object.assign( - fromParams, - functionalUpdate(dest.params as any, fromParams), - ) - - // Interpolate the path first to get the actual resolved path, then match against that - const interpolatedNextTo = interpolatePath({ - path: nextTo, - params: nextParams, - }).interpolatedPath - - const destRoutes = this.matchRoutes(interpolatedNextTo, undefined, { - _buildLocation: true, - }).map((d) => this.looseRoutesById[d.routeId]!) - - // If there are any params, we need to stringify them - if (Object.keys(nextParams).length > 0) { - for (const route of destRoutes) { - const fn = - route.options.params?.stringify ?? route.options.stringifyParams - if (fn) { - Object.assign(nextParams, fn(nextParams)) - } + if ( + this.options.notFoundRoute && + (!foundRoute || (foundRoute.path !== '/' && rawParams['**'])) + ) { + destRoutes = [...destRoutes, this.options.notFoundRoute] } } + // One parsed template serves both trailing-slash variants. + const interpolation = isTemplate + ? (destRoute?._interpolation ?? + parseSegments(false, { fullPath: nextTo }, 0)) + : undefined + + let nextParams: Record<string, unknown> | undefined + for (const route of destRoutes) { + const fn = + route.options.params?.stringify ?? route.options.stringifyParams + if (fn) { + // Stringifiers receive the merged params, so they always see inherited ones. + const fromParams = currentMatch()[3 /* params */] + nextParams ??= resolveNextParams(dest.params, fromParams) + if (!hasKeys(nextParams)) { + break + } + if (nextParams === fromParams) { + nextParams = Object.assign( + createNull() as Record<string, unknown>, + nextParams, + ) + } + try { + Object.assign(nextParams, fn(nextParams)) + } catch { + // Ignore errors here. When a paired parseParams is defined, + // extractStrictParams will re-throw during route matching, + // storing the error on the match and allowing the route's + // errorComponent to render. If no parseParams is defined, + // the stringify error is silently dropped. + } + } + } + nextParams ??= resolveNextParams( + dest.params, + needsInheritedParams(dest.params, interpolation) + ? currentMatch()[3 /* params */] + : EMPTY_RECORD, + ) + const nextPathname = opts.leaveParams - ? // Use the original template path for interpolation - // This preserves the original parameter syntax including optional parameters + ? // Keep path params uninterpolated for matchRoute/template matching. nextTo - : decodePath( - interpolatePath({ - path: nextTo, - params: nextParams, - decodeCharMap: this.pathParamsDecodeCharMap, - }).interpolatedPath, + : normalizeProtocolRelative( + decodePath( + interpolation + ? interpolatePath( + nextTo, + interpolation, + nextParams, + this.pathParamsDecoder, + ) + : nextTo, + ), ) - // Resolve the next search - let nextSearch = fromSearch - if (opts._includeValidateSearch && this.options.search?.strict) { - const validatedSearch = {} - destRoutes.forEach((route) => { - if (route.options.validateSearch) { - try { - Object.assign( - validatedSearch, - validateSearch(route.options.validateSearch, { - ...validatedSearch, - ...nextSearch, - }), - ) - } catch { - // ignore errors here because they are already handled in matchRoutes - } + if ( + process.env.NODE_ENV !== 'production' && + destRoute && + !opts.leaveParams + ) { + try { + const foundRoute = this.getMatchedRoutes(nextPathname)[2] + if (foundRoute?.id !== destRoute.id) { + console.warn( + `Generated path "${nextPathname}" for route "${destRoute.id}" matched route "${foundRoute?.id}" instead. This can happen when multiple route templates resolve to the same URL. Use the route template that matches the intended route, or adjust params.stringify if it changed the target path.`, + ) } - }) - nextSearch = validatedSearch + } catch { + // Ignore roundtrip validation errors. The generated location will be + // handled by the normal navigation flow. + } } - nextSearch = applySearchMiddleware({ - search: nextSearch, - dest, + // Resolve the next search + const middlewares = getSearchMiddlewares( destRoutes, - _includeValidateSearch: opts._includeValidateSearch, - }) - - // Replace the equal deep - nextSearch = replaceEqualDeep(fromSearch, nextSearch) + opts._includeValidateSearch, + ) + const fromSearch = () => { + let search = currentMatch()[2 /* search */] + if (opts._includeValidateSearch && this.options.search?.strict) { + const validatedSearch = {} + destRoutes.forEach((route) => { + if (route.options.validateSearch) { + try { + Object.assign( + validatedSearch, + validateSearch(route.options.validateSearch, { + ...validatedSearch, + ...search, + }), + ) + } catch { + // ignore errors here because they are already handled in matchRoutes + } + } + }) + search = validatedSearch + } + return search + } + // A literal search never reads the current one. The result is not + // structurally shared with the current search: `parseLocation` keeps + // equal nested values stable once the location is committed. + const nextSearch: Record<string, unknown> = middlewares.length + ? applySearchMiddleware(middlewares, fromSearch(), dest) + : dest.search === true + ? fromSearch() + : typeof dest.search === 'function' + ? dest.search(fromSearch()) + : (dest.search as Record<string, unknown>) || EMPTY_RECORD // Stringify the next search const searchStr = this.options.stringifySearch(nextSearch) @@ -1731,149 +2115,152 @@ export class RouterCore< // Resolve the next hash const hash = dest.hash === true - ? currentLocation.hash - : dest.hash - ? functionalUpdate(dest.hash, currentLocation.hash) - : undefined + ? current().hash + : typeof dest.hash === 'function' + ? dest.hash(current().hash) + : dest.hash || undefined // Resolve the next hash string const hashStr = hash ? `#${hash}` : '' - // Resolve the next state - let nextState = - dest.state === true - ? currentLocation.state - : dest.state - ? functionalUpdate(dest.state, currentLocation.state) - : {} - - // Replace the equal deep - nextState = replaceEqualDeep(currentLocation.state, nextState) + // Resolve the next state. A literal state never reads the current one + // and, like the search, is not shared with it here. + const nextState: HistoryState = !dest.state + ? EMPTY_RECORD + : dest.state === true + ? current().state + : typeof dest.state === 'function' + ? dest.state(current().state) + : dest.state // Create the full path of the location const fullPath = `${nextPathname}${searchStr}${hashStr}` - // Create the new href with full origin - const url = new URL(fullPath, this.origin) + // Compute href and publicHref without URL construction when no rewrite + let href: string + let publicHref: string + let external = false - // If a rewrite function is provided, use it to rewrite the URL - const rewrittenUrl = executeRewriteOutput(this.rewrite, url) + if (this.rewrite) { + // With rewrite, we need to construct URL to apply the rewrite + const url = new URL(fullPath, this.origin) + const origin = url.origin + const rewrittenUrl = executeRewriteOutput(this.rewrite, url) + href = getUrlPath(url) + // If rewrite changed the origin, publicHref needs full URL + // Otherwise just use the path components + if (isExternalUrl(rewrittenUrl, origin)) { + publicHref = rewrittenUrl.href + external = true + } else { + // A same-origin rewrite can produce a pathname like "//evil.example". + // Normalize it to "/evil.example" so the link stays on this origin. + publicHref = normalizeProtocolRelative(getUrlPath(rewrittenUrl)) + } + } else { + // Fast path: no rewrite, skip URL construction entirely + // fullPath is already the correct href (origin-stripped) + // We need to encode non-ASCII (unicode) characters for the href + // since decodePath decoded them from the interpolated path + href = encodePathLikeUrl(fullPath) + publicHref = href + } return { - publicHref: - rewrittenUrl.pathname + rewrittenUrl.search + rewrittenUrl.hash, - href: fullPath, - url: rewrittenUrl, + publicHref, + href, pathname: nextPathname, search: nextSearch, searchStr, state: nextState as any, hash: hash ?? '', + external, unmaskOnReload: dest.unmaskOnReload, } } - const buildWithMatches = ( - dest: BuildNextOptions = {}, - maskedDest?: BuildNextOptions, - ) => { - const next = build(dest) - - let maskedNext = maskedDest ? build(maskedDest) : undefined - - if (!maskedNext) { - const params = {} - - if (this.options.routeMasks) { - const match = findFlatMatch<RouteMask<TRouteTree>>( - next.pathname, - this.processedTree, - ) - if (match) { - Object.assign(params, match.params) // Copy params, because they're cached - const { - from: _from, - params: maskParams, - ...maskProps - } = match.route - - // If mask has a params function, call it with the matched params as context - // Otherwise, use the matched params or the provided params value - const nextParams = - maskParams === false || maskParams === null - ? {} - : (maskParams ?? true) === true - ? params - : Object.assign(params, functionalUpdate(maskParams, params)) - - maskedDest = { - from: opts.from, - ...maskProps, - params: nextParams, - } - maskedNext = build(maskedDest) - } - } - } - - if (maskedNext) { - next.maskedLocation = maskedNext - } - - return next - } + const next = build(opts) if (opts.mask) { - return buildWithMatches(opts, { + next.maskedLocation = build({ from: opts.from, ...opts.mask, }) + } else if (this.options.routeMasks) { + const match = findFlatMatch<RouteMask<TRouteTree>>( + next.pathname, + this.processedTree, + ) + if (match) { + const params = Object.assign(createNull(), match.rawParams) + const { from: _from, params: maskParams, ...maskProps } = match.route + + // If mask has a params function, call it with the matched params as context + // Otherwise, use the matched params or the provided params value + const nextParams = resolveNextParams(maskParams, params) + + next.maskedLocation = build({ + from: opts.from, + ...maskProps, + params: nextParams, + }) + } } - return buildWithMatches(opts) + // A mask that reads the current location marks the whole result through + // `usedCurrent`. Route masks belong to the route tree and options, whose + // updates replace the cache. + if (!(isServer ?? this.isServer) && !usedCurrent && opts._fromLocation) { + this.staticLocations!.set(opts, next) + } + + return next } - commitLocationPromise: undefined | ControlledPromise<void> + _commitPromise: (Promise<void> & { resolve: () => void }) | undefined /** * Commit a previously built location to history (push/replace), optionally * using view transitions and scroll restoration options. */ - commitLocation: CommitLocationFn = ({ + commitLocation: CommitLocationFn = async ({ viewTransition, ignoreBlocker, ...next }) => { - const isSameState = () => { - // the following props are ignored but may still be provided when navigating, - // temporarily add the previous values to the next state so they don't affect - // the comparison - const ignoredProps = [ - 'key', // TODO: Remove in v2 - use __TSR_key instead - '__TSR_key', - '__TSR_index', - '__hashScrollIntoViewOptions', - ] as const - ignoredProps.forEach((prop) => { - ;(next.state as any)[prop] = this.latestLocation.state[prop] - }) - const isEqual = deepEqual(next.state, this.latestLocation.state) - ignoredProps.forEach((prop) => { - delete next.state[prop] - }) - return isEqual + if (isServer ?? this.isServer) { + return } - const isSameUrl = - trimPathRight(this.latestLocation.href) === trimPathRight(next.href) + const nextLocation = next.maskedLocation ?? next + if (nextLocation.external && !(isServer ?? this.isServer)) { + return documentNavigation(this, nextLocation.publicHref, { + replace: next.replace, + ignoreBlocker, + }) + } - const previousCommitPromise = this.commitLocationPromise - this.commitLocationPromise = createControlledPromise<void>(() => { + let historyAction: HistoryAction | undefined + const isSameLocation = + trimPathRight(this.latestLocation.href) === trimPathRight(next.href) && + deepEqual( + _getUserHistoryState(next.state), + _getUserHistoryState(this.latestLocation.state), + ) + + const previousCommitPromise = this._commitPromise + let resolve!: () => void + const commitPromise = new Promise<void>((done) => { + resolve = done + }) as Promise<void> & { resolve: () => void } + commitPromise.resolve = () => { + resolve() previousCommitPromise?.resolve() - }) + } + this._commitPromise = commitPromise // Don't commit to history if nothing changed - if (isSameUrl && isSameState()) { + if (isSameLocation) { this.load() } else { let { @@ -1881,9 +2268,6 @@ export class RouterCore< maskedLocation, // eslint-disable-next-line prefer-const hashScrollIntoView, - // don't pass url into history since it is a URL instance that cannot be serialized - // eslint-disable-next-line prefer-const - url: _url, ...nextHistory } = next @@ -1916,25 +2300,32 @@ export class RouterCore< } } - nextHistory.state.__hashScrollIntoViewOptions = - hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true + nextHistory.state = { + ...nextHistory.state, + __hashScrollIntoViewOptions: + hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true, + } this.shouldViewTransition = viewTransition - this.history[next.replace ? 'replace' : 'push']( + historyAction = next.replace ? 'REPLACE' : 'PUSH' + + this.history[historyAction === 'REPLACE' ? 'replace' : 'push']( nextHistory.publicHref, nextHistory.state, { ignoreBlocker }, ) + + // Without a subscribed adapter the history commit cannot trigger the + // load itself. The same-location branch already loads directly. + if (!this.history.subscribers.size) { + this.load({ action: { type: historyAction } }) + } } - this.resetNextScroll = next.resetScroll ?? true + this._scroll.n = next.resetScroll ?? true - if (!this.history.subscribers.size) { - this.load() - } - - return this.commitLocationPromise + return this._commitPromise } /** Convenience helper: build a location from options, then commit it. */ @@ -1944,19 +2335,10 @@ export class RouterCore< hashScrollIntoView, viewTransition, ignoreBlocker, - href, ...rest - }: BuildNextOptions & CommitLocationOptions = {}) => { - if (href) { - const currentIndex = this.history.location.state.__TSR_index - - const parsed = parseHref(href, { - __TSR_index: replace ? currentIndex : currentIndex + 1, - }) - rest.to = parsed.pathname - rest.search = this.options.parseSearch(parsed.search) - // remove the leading `#` from the hash - rest.hash = parsed.hash.slice(1) + }: BuildNextOptions & CommitLocationOptions = {}): Promise<void> => { + if (isServer ?? this.isServer) { + return Promise.resolve() } const location = this.buildLocation({ @@ -1964,7 +2346,7 @@ export class RouterCore< _includeValidateSearch: true, }) - this.pendingBuiltLocation = location as ParsedLocation< + this._pendingLocation = location as ParsedLocation< FullSearchSchema<TRouteTree> > @@ -1979,9 +2361,9 @@ export class RouterCore< // Clear pending location after commit starts // We do this on next microtask to allow synchronous navigate calls to chain - Promise.resolve().then(() => { - if (this.pendingBuiltLocation === location) { - this.pendingBuiltLocation = undefined + queueMicrotask(() => { + if (this._pendingLocation === location) { + this._pendingLocation = undefined } }) @@ -1995,45 +2377,37 @@ export class RouterCore< * * @link https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType */ - navigate: NavigateFn = async ({ to, reloadDocument, href, ...rest }) => { - if (!reloadDocument && href) { - try { - new URL(`${href}`) - reloadDocument = true - } catch {} + navigate: NavigateFn = async ({ + to, + reloadDocument, + href, + publicHref, + ...rest + }) => { + if (isServer ?? this.isServer) { + return } - if (reloadDocument) { - if (!href) { + const hrefScheme = href ? getUrlScheme(href) : undefined + + if (hrefScheme || reloadDocument) { + // When to is provided, always build a location to get the proper publicHref + // (this handles redirects where href might be an internal path from resolveRedirect) + // When only href is provided (no to), use it directly as it should already + // be a complete path (possibly with basepath) + if (to !== undefined || !href) { const location = this.buildLocation({ to, ...rest } as any) - href = location.url.href + const publicLocation = location.maskedLocation ?? location + // Use publicHref which contains the path (origin-stripped is fine for reload) + href ??= publicLocation.publicHref + publicHref ??= publicLocation.publicHref } - // Check blockers for external URLs unless ignoreBlocker is true - if (!rest.ignoreBlocker) { - // Cast to access internal getBlockers method - const historyWithBlockers = this.history as any - const blockers = historyWithBlockers.getBlockers?.() ?? [] - for (const blocker of blockers) { - if (blocker?.blockerFn) { - const shouldBlock = await blocker.blockerFn({ - currentLocation: this.latestLocation, - nextLocation: this.latestLocation, // External URLs don't have a next location in our router - action: 'PUSH', - }) - if (shouldBlock) { - return Promise.resolve() - } - } - } - } + // Use publicHref when available and href is not a full URL, + // otherwise use href directly (which may already include basepath) + const reloadHref = !hrefScheme && publicHref ? publicHref : href - if (rest.replace) { - window.location.replace(href) - } else { - window.location.href = href - } - return Promise.resolve() + return documentNavigation(this, reloadHref, rest) } return this.buildAndCommitLocation({ @@ -2044,220 +2418,17 @@ export class RouterCore< }) } - latestLoadPromise: undefined | Promise<void> + load: LoadFn = async (opts): Promise<void> => { + if (isServer ?? this.isServer) { + return loadServerRoute(this, opts) + } - beforeLoad = () => { - // Cancel any pending matches - this.cancelMatches() this.updateLatestLocation() - - if (this.isServer) { - // for SPAs on the initial load, this is handled by the Transitioner - const nextLocation = this.buildLocation({ - to: this.latestLocation.pathname, - search: true, - params: true, - hash: true, - state: true, - _includeValidateSearch: true, - }) - - if ( - this.latestLocation.publicHref !== nextLocation.publicHref || - nextLocation.url.origin !== this.origin - ) { - const href = this.getParsedLocationHref(nextLocation) - - throw redirect({ href }) - } - } - - // Match the routes - const pendingMatches = this.matchRoutes(this.latestLocation) - - // Ingest the new matches - this.__store.setState((s) => ({ - ...s, - status: 'pending', - statusCode: 200, - isLoading: true, - location: this.latestLocation, - pendingMatches, - // If a cached moved to pendingMatches, remove it from cachedMatches - cachedMatches: s.cachedMatches.filter( - (d) => !pendingMatches.some((e) => e.id === d.id), - ), - })) - } - - load: LoadFn = async (opts?: { sync?: boolean }): Promise<void> => { - let redirect: AnyRedirect | undefined - let notFound: NotFoundError | undefined - let loadPromise: Promise<void> - - // eslint-disable-next-line prefer-const - loadPromise = new Promise<void>((resolve) => { - this.startTransition(async () => { - try { - this.beforeLoad() - const next = this.latestLocation - const prevLocation = this.state.resolvedLocation - - if (!this.state.redirect) { - this.emit({ - type: 'onBeforeNavigate', - ...getLocationChangeInfo({ - resolvedLocation: prevLocation, - location: next, - }), - }) - } - - this.emit({ - type: 'onBeforeLoad', - ...getLocationChangeInfo({ - resolvedLocation: prevLocation, - location: next, - }), - }) - - await loadMatches({ - router: this, - sync: opts?.sync, - matches: this.state.pendingMatches as Array<AnyRouteMatch>, - location: next, - updateMatch: this.updateMatch, - // eslint-disable-next-line @typescript-eslint/require-await - onReady: async () => { - // Wrap batch in framework-specific transition wrapper (e.g., Solid's startTransition) - this.startTransition(() => { - this.startViewTransition(async () => { - // this.viewTransitionPromise = createControlledPromise<true>() - - // Commit the pending matches. If a previous match was - // removed, place it in the cachedMatches - let exitingMatches: Array<AnyRouteMatch> = [] - let enteringMatches: Array<AnyRouteMatch> = [] - let stayingMatches: Array<AnyRouteMatch> = [] - - batch(() => { - this.__store.setState((s) => { - const previousMatches = s.matches - const newMatches = s.pendingMatches || s.matches - - exitingMatches = previousMatches.filter( - (match) => !newMatches.some((d) => d.id === match.id), - ) - enteringMatches = newMatches.filter( - (match) => - !previousMatches.some((d) => d.id === match.id), - ) - stayingMatches = newMatches.filter((match) => - previousMatches.some((d) => d.id === match.id), - ) - - return { - ...s, - isLoading: false, - loadedAt: Date.now(), - matches: newMatches, - pendingMatches: undefined, - /** - * When committing new matches, cache any exiting matches that are still usable. - * Routes that resolved with `status: 'error'` or `status: 'notFound'` are - * deliberately excluded from `cachedMatches` so that subsequent invalidations - * or reloads re-run their loaders instead of reusing the failed/not-found data. - */ - cachedMatches: [ - ...s.cachedMatches, - ...exitingMatches.filter( - (d) => - d.status !== 'error' && d.status !== 'notFound', - ), - ], - } - }) - this.clearExpiredCache() - }) - - // - ;( - [ - [exitingMatches, 'onLeave'], - [enteringMatches, 'onEnter'], - [stayingMatches, 'onStay'], - ] as const - ).forEach(([matches, hook]) => { - matches.forEach((match) => { - this.looseRoutesById[match.routeId]!.options[hook]?.( - match, - ) - }) - }) - }) - }) - }, - }) - } catch (err) { - if (isRedirect(err)) { - redirect = err - if (!this.isServer) { - this.navigate({ - ...redirect.options, - replace: true, - ignoreBlocker: true, - }) - } - } else if (isNotFound(err)) { - notFound = err - } - - this.__store.setState((s) => ({ - ...s, - statusCode: redirect - ? redirect.status - : notFound - ? 404 - : s.matches.some((d) => d.status === 'error') - ? 500 - : 200, - redirect, - })) - } - - if (this.latestLoadPromise === loadPromise) { - this.commitLocationPromise?.resolve() - this.latestLoadPromise = undefined - this.commitLocationPromise = undefined - } - - resolve() - }) - }) - - this.latestLoadPromise = loadPromise - - await loadPromise - - while ( - (this.latestLoadPromise as any) && - loadPromise !== this.latestLoadPromise - ) { - await this.latestLoadPromise - } - - let newStatusCode: number | undefined = undefined - if (this.hasNotFoundMatch()) { - newStatusCode = 404 - } else if (this.__store.state.matches.some((d) => d.status === 'error')) { - newStatusCode = 500 - } - if (newStatusCode !== undefined) { - this.__store.setState((s) => ({ - ...s, - statusCode: newStatusCode, - })) + if (opts?.action) { + this._scroll.h = + opts.action.type === 'PUSH' || opts.action.type === 'REPLACE' } + await loadClientRoute(this, opts) } startViewTransition = (fn: () => Promise<void>) => { @@ -2267,13 +2438,13 @@ export class RouterCore< this.shouldViewTransition ?? this.options.defaultViewTransition // Reset the view transition flag - delete this.shouldViewTransition + this.shouldViewTransition = undefined + // Attempt to start a view transition (or just apply the changes if we can't) if ( shouldViewTransition && - typeof document !== 'undefined' && - 'startViewTransition' in document && - typeof document.startViewTransition === 'function' + !(isServer ?? typeof document === 'undefined') && + typeof (document as any).startViewTransition === 'function' ) { // lib.dom.ts doesn't support viewTransition types variant yet. // TODO: Fix this when dom types are updated @@ -2281,24 +2452,20 @@ export class RouterCore< if ( typeof shouldViewTransition === 'object' && - this.isViewTransitionTypesSupported + window.CSS?.supports?.('selector(:active-view-transition-type(a))') ) { const next = this.latestLocation - const prevLocation = this.state.resolvedLocation + const prevLocation = this.stores.resolvedLocation.get() const resolvedViewTransitionTypes = typeof shouldViewTransition.types === 'function' ? shouldViewTransition.types( - getLocationChangeInfo({ - resolvedLocation: prevLocation, - location: next, - }), + getLocationChangeInfo(next, prevLocation), ) : shouldViewTransition.types if (resolvedViewTransitionTypes === false) { - fn() - return + return fn() } startViewTransitionParams = { @@ -2309,49 +2476,21 @@ export class RouterCore< startViewTransitionParams = fn } - document.startViewTransition(startViewTransitionParams) - } else { - fn() + return (document as any).startViewTransition(startViewTransitionParams) + .updateCallbackDone } - } - - updateMatch: UpdateMatchFn = (id, updater) => { - this.startTransition(() => { - const matchesKey = this.state.pendingMatches?.some((d) => d.id === id) - ? 'pendingMatches' - : this.state.matches.some((d) => d.id === id) - ? 'matches' - : this.state.cachedMatches.some((d) => d.id === id) - ? 'cachedMatches' - : '' - - if (matchesKey) { - this.__store.setState((s) => ({ - ...s, - [matchesKey]: s[matchesKey]?.map((d) => - d.id === id ? updater(d) : d, - ), - })) - } - }) - } - - getMatch: GetMatchFn = (matchId: string): AnyRouteMatch | undefined => { - const findFn = (d: { id: string }) => d.id === matchId - return ( - this.state.cachedMatches.find(findFn) ?? - this.state.pendingMatches?.find(findFn) ?? - this.state.matches.find(findFn) - ) + return fn() } /** - * Invalidate the current matches and optionally force them back into a pending state. + * Invalidate selected match generations and optionally force current matches + * back into a pending state. * - * - Marks all matches that pass the optional `filter` as `invalid: true`. - * - If `forcePending` is true, or a match is currently in `'error'` or `'notFound'` status, - * its status is reset to `'pending'` and its `error` cleared so that the loader is re-run - * on the next `load()` call (eg. after HMR or a manual invalidation). + * - Marks committed and cached matches whose IDs are selected as invalid. + * - Retires selected active preloads so older work cannot publish fresh data. + * + * The next load decides when to publish pending UI, so invalidation does not + * mutate the currently rendered status. */ invalidate: InvalidateFn< RouterCore< @@ -2362,174 +2501,177 @@ export class RouterCore< TDehydrated > > = (opts) => { + const committedMatches = this._committed + const filter = opts?.filter + const preloads = this._preloads + const invalidIds = new Set<string>() + const consider = (match: AnyRouteMatch) => { + if (!filter || filter(match as MakeRouteMatchUnion<this>)) { + invalidIds.add(match.id) + } + } + committedMatches.forEach(consider) + this._cache.forEach(consider) + preloads?.forEach((matches) => matches.forEach(consider)) + this._tx?.[3 /* matches */].forEach(consider) + const abort: Array<AbortController> = [] + for (const [controller, matches] of preloads ?? []) { + if (matches.some((match) => invalidIds.has(match.id))) { + preloads!.delete(controller) + abort.push(controller) + } + } const invalidate = (d: MakeRouteMatch<TRouteTree>) => { - if (opts?.filter?.(d as MakeRouteMatchUnion<this>) ?? true) { - return { + if (invalidIds.has(d.id)) { + const route = this.routesById[d.routeId] as AnyRoute + const next = { ...d, invalid: true, - ...(opts?.forcePending || - d.status === 'error' || - d.status === 'notFound' + ...((opts?.forcePending || + d.status === 'error' || + d.status === 'notFound') && + routeNeedsLoad(route) ? ({ status: 'pending', error: undefined } as const) : undefined), } + // Invalidation replaces this owner; it does not create another lease. + ;(d as AnyRouteMatch & { _flight?: LoaderFlight })._flight = undefined + return next } return d } - this.__store.setState((s) => ({ - ...s, - matches: s.matches.map(invalidate), - cachedMatches: s.cachedMatches.map(invalidate), - pendingMatches: s.pendingMatches?.map(invalidate), - })) + this._committed = committedMatches.map(invalidate) + // Cache entries are settled successes. Retiring matching active preload + // owners makes an in-place stale mark sufficient while preserving data. + for (const [id, match] of this._cache) { + if (invalidIds.has(id)) { + match.invalid = true + if (opts?.forcePending) { + match.status = 'pending' + } + } + } + // The superseding load must not discover any same-ID generation selected + // for replacement. Existing owners release it in their normal order. + for (const id of invalidIds) { + const flight = this._flights?.get(id) + this._flights?.delete(id) + // A reserved discovery has no remaining match owner to retire it later. + if (flight && !flight[2 /* leases */]) { + abort.push(flight[1 /* controller */]) + } + } + for (const controller of abort) { + controller.abort() + } this.shouldViewTransition = false return this.load({ sync: opts?.sync }) } - getParsedLocationHref = (location: ParsedLocation) => { - let href = location.url.href - if (this.origin && location.url.origin === this.origin) { - href = href.replace(this.origin, '') || '/' - } - return href - } - resolveRedirect = (redirect: AnyRedirect): AnyRedirect => { - if (!redirect.options.href) { - const location = this.buildLocation(redirect.options) - const href = this.getParsedLocationHref(location) - redirect.options.href = location.href - redirect.headers.set('Location', href) + const options = redirect.options + let href = redirect.headers.get('Location') || options.href + + if (!href) { + const location = this.buildLocation(options) + href = (location.maskedLocation ?? location).publicHref || '/' } - if (!redirect.headers.get('Location')) { - redirect.headers.set('Location', redirect.options.href) + + let scheme: string | undefined + // Reject protocol-relative URLs such as "//evil.example", including + // backslash and control-character variants, before checking the protocol. + if ( + protocolRelativePrefixRegex.test(href) || + ((scheme = getUrlScheme(href)) && !this.protocolAllowlist.has(scheme)) + ) { + throw new Error( + process.env.NODE_ENV !== 'production' + ? `Redirect blocked: unsafe protocol in href "${href}". Allowed protocols: ${Array.from(this.protocolAllowlist).join(', ')}.` + : 'Redirect blocked: unsafe protocol', + ) } + + if (scheme === 'http:' || scheme === 'https:') { + const url = new URL(href) + if (url.pathname.startsWith('//')) { + href = url.href + } else if (!isExternalUrl(url, this.origin)) { + href = getUrlPath(url) + scheme = undefined + } + } + if (scheme) { + options.reloadDocument = true + } + + options.href = href + redirect.headers.set('Location', href) + return redirect } clearCache: ClearCacheFn<this> = (opts) => { + const cached = this._cache + const preloads = this._preloads const filter = opts?.filter - if (filter !== undefined) { - this.__store.setState((s) => { - return { - ...s, - cachedMatches: s.cachedMatches.filter( - (m) => !filter(m as MakeRouteMatchUnion<this>), - ), - } - }) - } else { - this.__store.setState((s) => { - return { - ...s, - cachedMatches: [], - } - }) - } - } - - clearExpiredCache = () => { - // This is where all of the garbage collection magic happens - const filter = (d: MakeRouteMatch<TRouteTree>) => { - const route = this.looseRoutesById[d.routeId]! - - if (!route.options.loader) { - return true + const discarded: Array<AnyRouteMatch> = [] + const discardedIds: Array<string> = [] + for (const [id, match] of cached) { + if (!filter || filter(match as MakeRouteMatchUnion<this>)) { + discardedIds.push(id) + discarded.push(match) } - - // If the route was preloaded, use the preloadGcTime - // otherwise, use the gcTime - const gcTime = - (d.preload - ? (route.options.preloadGcTime ?? this.options.defaultPreloadGcTime) - : (route.options.gcTime ?? this.options.defaultGcTime)) ?? - 5 * 60 * 1000 - - const isError = d.status === 'error' - if (isError) return true - - const gcEligible = Date.now() - d.updatedAt >= gcTime - return gcEligible } - this.clearCache({ filter }) + const abort: Array<AbortController> = [] + for (const [controller, matches] of preloads ?? []) { + if (!filter || matches.some(filter as any)) { + abort.push(controller) + discarded.push(...matches) + } + } + + // Run every public filter before changing authority, then prune both maps + // before releasing a public loader + // signal, whose abort listeners can synchronously reenter the router. + for (const id of discardedIds) { + cached.delete(id) + } + for (const controller of abort) { + preloads!.delete(controller) + } + // clearCache is a force-retirement boundary, so a final discarded lease + // must not use the normal zero-owner handoff window. + for (const match of discarded as Array< + AnyRouteMatch & { _flight?: LoaderFlight } + >) { + const flight = match._flight + match._flight = undefined + if (flight && !--flight[2 /* leases */]) { + if (this._flights?.get(match.id) === flight) { + this._flights.delete(match.id) + } + abort.push(flight[1 /* controller */]) + } + } + for (const controller of abort) { + controller.abort() + } } - loadRouteChunk = loadRouteChunk + loadRouteChunk: ( + route: AnyRoute, + componentType?: 'errorComponent' | 'notFoundComponent' | false, + ) => Promise<void> | undefined = loadRouteChunk preloadRoute: PreloadRouteFn< TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, - TRouterHistory - > = async (opts) => { - const next = this.buildLocation(opts as any) - - let matches = this.matchRoutes(next, { - throwOnError: true, - preload: true, - dest: opts, - }) - - const activeMatchIds = new Set( - [...this.state.matches, ...(this.state.pendingMatches ?? [])].map( - (d) => d.id, - ), - ) - - const loadedMatchIds = new Set([ - ...activeMatchIds, - ...this.state.cachedMatches.map((d) => d.id), - ]) - - // If the matches are already loaded, we need to add them to the cachedMatches - batch(() => { - matches.forEach((match) => { - if (!loadedMatchIds.has(match.id)) { - this.__store.setState((s) => ({ - ...s, - cachedMatches: [...(s.cachedMatches as any), match], - })) - } - }) - }) - - try { - matches = await loadMatches({ - router: this, - matches, - location: next, - preload: true, - updateMatch: (id, updater) => { - // Don't update the match if it's currently loaded - if (activeMatchIds.has(id)) { - matches = matches.map((d) => (d.id === id ? updater(d) : d)) - } else { - this.updateMatch(id, updater) - } - }, - }) - - return matches - } catch (err) { - if (isRedirect(err)) { - if (err.options.reloadDocument) { - return undefined - } - - return await this.preloadRoute({ - ...err.options, - _fromLocation: next, - }) - } - if (!isNotFound(err)) { - // Preload errors are not fatal, but we should still log them - console.error(err) - } - return undefined - } - } + TRouterHistory, + TDehydrated + > = (opts) => preloadClientRoute(this, opts) matchRoute: MatchRouteFn< TRouteTree, @@ -2540,9 +2682,11 @@ export class RouterCore< const matchLocation = { ...location, to: location.to - ? this.resolvePathWithBase( - (location.from || '') as string, + ? resolvePath( + location.from || '', location.to as string, + this.options.trailingSlash, + this.resolvePathCache, ) : undefined, params: location.params || {}, @@ -2550,16 +2694,16 @@ export class RouterCore< } const next = this.buildLocation(matchLocation as any) - if (opts?.pending && this.state.status !== 'pending') { + const isPending = this.stores.status.get() === 'pending' + if (opts?.pending && !isPending) { return false } - const pending = - opts?.pending === undefined ? !this.state.isLoading : opts.pending + const pending = opts?.pending ?? !isPending const baseLocation = pending ? this.latestLocation - : this.state.resolvedLocation || this.state.location + : this.stores.resolvedLocation.get() || this.stores.location.get() const match = findSingleMatch( next.pathname, @@ -2574,18 +2718,18 @@ export class RouterCore< } if (location.params) { - if (!deepEqual(match.params, location.params, { partial: true })) { + if (!deepEqual(match.rawParams, location.params, true)) { return false } } if (opts?.includeSearch ?? true) { - return deepEqual(baseLocation.search, next.search, { partial: true }) - ? match.params + return deepEqual(baseLocation.search, next.search, true) + ? match.rawParams : false } - return match.params + return match.rawParams } ssr?: { @@ -2594,10 +2738,65 @@ export class RouterCore< serverSsr?: ServerSsr - hasNotFoundMatch = () => { - return this.__store.state.matches.some( - (d) => d.status === 'notFound' || d.globalNotFound, - ) + serverSsrLifecycle?: RouterSsrLifecycle +} + +async function documentNavigation( + router: AnyRouter, + href: string, + { + replace, + ignoreBlocker, + }: Pick<CommitLocationOptions, 'replace' | 'ignoreBlocker'>, +) { + // Block dangerous protocols like javascript:, blob:, data: + // These could execute arbitrary code if passed to window.location + if (isDangerousProtocol(href, router.protocolAllowlist)) { + if (process.env.NODE_ENV !== 'production') { + console.warn(`Blocked navigation to dangerous protocol: ${href}`) + } + return + } + + // Check blockers for external URLs unless ignoreBlocker is true + if (!ignoreBlocker) { + const blockers = router.history._getBlockers() + for (const blocker of blockers) { + if (blocker?.blockerFn) { + const shouldBlock = await blocker.blockerFn({ + currentLocation: router.history.location, + nextLocation: router.history.location, // External URLs don't have a next location in our router + action: replace ? 'REPLACE' : 'PUSH', + }) + if (shouldBlock) { + return + } + } + } + } + + // All blockers have allowed this navigation (or were explicitly skipped). + // Avoid asking for approval again in the native beforeunload handler. + router.history._ignoreNextBeforeUnload?.(href) + if (replace) { + window.location.replace(href) + } else { + window.location.href = href + } + return +} + +/** + * In non-production environments, + * augment the RouterCore class with a `_refreshRoute` method + * dedicated to HMR. + */ +if (process.env.NODE_ENV !== 'production') { + RouterCore.prototype._replaceRouteChunk = replaceRouteChunk + RouterCore.prototype._refreshRoute = async function () { + this._serverResult = undefined + this.updateLatestLocation() + await refreshClientRoute(this) } } @@ -2634,16 +2833,11 @@ export function getInitialRouterState( location: ParsedLocation, ): RouterState<any> { return { - loadedAt: 0, isLoading: false, - isTransitioning: false, status: 'idle', resolvedLocation: undefined, location, matches: [], - pendingMatches: [], - cachedMatches: [], - statusCode: 200, } } @@ -2675,145 +2869,186 @@ function validateSearch(validateSearch: AnyValidator, input: unknown): unknown { return {} } -/** - * Build the matched route chain and extract params for a pathname. - * Falls back to the root route if no specific route is found. - */ -export function getMatchedRoutes<TRouteLike extends RouteLike>({ - pathname, - routesById, - processedTree, -}: { - pathname: string - routesById: Record<string, TRouteLike> - processedTree: ProcessedTree<any, any, any> -}) { - const routeParams: Record<string, string> = {} - const trimmedPath = trimPathRight(pathname) - - let foundRoute: TRouteLike | undefined = undefined - const match = findRouteMatch<TRouteLike>(trimmedPath, processedTree, true) - if (match) { - foundRoute = match.route - Object.assign(routeParams, match.params) // Copy params, because they're cached +function resolveNextParams( + spec: unknown, + base: Record<string, unknown>, +): Record<string, unknown> { + if (spec === undefined || spec === true) { + return base } - - const matchedRoutes = match?.branch || [routesById[rootRouteId]!] - - return { matchedRoutes, routeParams, foundRoute } + const next = Object.create(null) + if (spec === false || spec === null) { + return next + } + if (typeof spec === 'function') { + Object.assign(next, base) + return Object.assign(next, spec(next)) + } + return Object.assign(next, base, spec) } -function applySearchMiddleware({ - search, - dest, - destRoutes, - _includeValidateSearch, -}: { - search: any - dest: BuildNextOptions - destRoutes: Array<AnyRoute> - _includeValidateSearch: boolean | undefined -}) { - const allMiddlewares = - destRoutes.reduce( - (acc, route) => { - const middlewares: Array<SearchMiddleware<any>> = [] +// Inherited params are read by param updaters and by template keys the +// destination leaves open. `interpolation` is undefined without template keys. +function needsInheritedParams( + spec: unknown, + interpolation: RouteInterpolation | undefined, +) { + if (typeof spec === 'function') { + return true + } + if (!interpolation || spec === false || spec === null) { + return false + } + return ( + spec === undefined || + spec === true || + interpolation.some( + (part) => + typeof part !== 'string' && !hasOwn.call(spec, part[1 /* key */]), + ) + ) +} - if ('search' in route.options) { - if (route.options.search?.middlewares) { - middlewares.push(...route.options.search.middlewares) - } - } - // TODO remove preSearchFilters and postSearchFilters in v2 - else if ( - route.options.preSearchFilters || - route.options.postSearchFilters - ) { - const legacyMiddleware: SearchMiddleware<any> = ({ - search, - next, - }) => { - let nextSearch = search +const EMPTY_RECORD: Record<string, never> = Object.freeze({}) - if ( - 'preSearchFilters' in route.options && - route.options.preSearchFilters - ) { - nextSearch = route.options.preSearchFilters.reduce( - (prev, next) => next(prev), - search, - ) - } +// Keep this separate from recursive execution to limit JIT compiler memory. +// A counted loop instead of `for...of`: Maglev's inlined array iteration +// deoptimizes on route option shapes and recompiles later, whereas indexed +// reads stay optimized once compiled. +function getSearchMiddlewares( + destRoutes: ReadonlyArray<AnyRoute>, + includeValidateSearch: boolean | undefined, +) { + const middlewares = [] as Array<SearchMiddleware<any>> - const result = next(nextSearch) + for (let i = 0; i < destRoutes.length; i++) { + const routeOptions = destRoutes[i]!.options + if ('search' in routeOptions) { + if (routeOptions.search?.middlewares) { + middlewares.push(...routeOptions.search.middlewares) + } + } + // TODO remove preSearchFilters and postSearchFilters in v2 + else if (routeOptions.preSearchFilters || routeOptions.postSearchFilters) { + const legacyMiddleware: SearchMiddleware<any> = ({ search, next }) => { + const nextSearch = routeOptions.preSearchFilters + ? routeOptions.preSearchFilters.reduce( + (prev, next) => next(prev), + search, + ) + : search - if ( - 'postSearchFilters' in route.options && - route.options.postSearchFilters - ) { - return route.options.postSearchFilters.reduce( - (prev, next) => next(prev), - result, - ) - } + const result = next(nextSearch) - return result - } - middlewares.push(legacyMiddleware) - } + return routeOptions.postSearchFilters + ? routeOptions.postSearchFilters.reduce( + (prev, next) => next(prev), + result, + ) + : result + } + middlewares.push(legacyMiddleware) + } - if (_includeValidateSearch && route.options.validateSearch) { - const validate: SearchMiddleware<any> = ({ search, next }) => { - const result = next(search) - try { - const validatedSearch = { - ...result, - ...(validateSearch(route.options.validateSearch, result) ?? - undefined), + const routeValidateSearch = routeOptions.validateSearch + if (includeValidateSearch && routeValidateSearch) { + const validate: SearchMiddleware<any> = ({ search, next, meta }) => { + const result = next(search) + try { + const validated = validateSearch(routeValidateSearch, result) as any + + if (meta && validated) { + for (const key in validated) { + if (!(key in result)) { + ;(meta.defaulted ||= new Map()).set(key, validated[key]) } - return validatedSearch - } catch { - // ignore errors here because they are already handled in matchRoutes - return result } } - - middlewares.push(validate) + return { ...result, ...validated } + } catch { + // ignore errors here because they are already handled in matchRoutes } + return result + } - return acc.concat(middlewares) - }, - [] as Array<SearchMiddleware<any>>, - ) ?? [] - - // the chain ends here since `next` is not called - const final: SearchMiddleware<any> = ({ search }) => { - if (!dest.search) { - return {} + middlewares.push(validate) } - if (dest.search === true) { - return search - } - return functionalUpdate(dest.search, search) } - allMiddlewares.push(final) + return middlewares +} - const applyNext = (index: number, currentSearch: any): any => { +function applySearchMiddleware( + middlewares: Array<SearchMiddleware<any>>, + search: any, + dest: BuildNextOptions, +) { + const applyNext = ( + index: number, + currentSearch: any, + meta?: SearchMiddlewareMeta, + ): any => { // no more middlewares left, return the current search - if (index >= allMiddlewares.length) { - return currentSearch + if (index >= middlewares.length) { + if (!dest.search) { + return {} + } + if (dest.search === true) { + return currentSearch + } + const result = functionalUpdate(dest.search, currentSearch) + if (meta) { + meta.explicit = result + } + return result } - const middleware = allMiddlewares[index]! - - const next = (newSearch: any): any => { - return applyNext(index + 1, newSearch) + const next = (newSearch: any, collectMeta?: true): any => { + if (collectMeta) { + const nextMeta = meta || ({} as SearchMiddlewareMeta) + return { + search: applyNext(index + 1, newSearch, nextMeta), + meta: nextMeta, + } + } + return applyNext(index + 1, newSearch, meta) } - return middleware({ search: currentSearch, next }) + return (middlewares[index]! as any)({ search: currentSearch, next, meta }) } - // Start applying middlewares return applyNext(0, search) } + +function findGlobalNotFoundRouteId( + notFoundMode: 'root' | 'fuzzy' | undefined, + routes: ReadonlyArray<AnyRoute>, +) { + if (notFoundMode !== 'root') { + let fallback + for (let i = routes.length - 1; i >= 0; i--) { + const route = routes[i]! + if (route.options.notFoundComponent) { + return route.id + } + fallback ||= route.children && route.id + } + if (fallback) { + return fallback + } + } + return rootRouteId +} + +function extractStrictParams( + route: AnyRoute, + accumulatedParams: Record<string, unknown>, +) { + const parseParams = route.options.params?.parse ?? route.options.parseParams + if (parseParams) { + Object.assign( + accumulatedParams, + parseParams(accumulatedParams as Record<string, string>), + ) + } +} diff --git a/packages/router-core/src/scroll-restoration-inline.ts b/packages/router-core/src/scroll-restoration-inline.ts new file mode 100644 index 0000000000..76ab0027b3 --- /dev/null +++ b/packages/router-core/src/scroll-restoration-inline.ts @@ -0,0 +1,53 @@ +export default function (storageKey: string, key?: string) { + let byKey + + try { + byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}') + } catch { + return + } + + const elementEntries = byKey?.[key || history.state?.__TSR_key] + let windowRestored = false + + for (const elementSelector in elementEntries) { + const entry = elementEntries[elementSelector] + const scrollX = entry?.scrollX + const scrollY = entry?.scrollY + + if (Number.isFinite(scrollX) && Number.isFinite(scrollY)) { + if (elementSelector === 'window') { + scrollTo(scrollX, scrollY) + windowRestored = true + } else if (elementSelector) { + try { + const element = document.querySelector(elementSelector) + if (element) { + element.scrollLeft = scrollX + element.scrollTop = scrollY + } + } catch {} + } + } + } + + if (windowRestored) return + + const hash = location.hash.slice(1) + + if (hash) { + const hashScrollIntoViewOptions = + history.state?.__hashScrollIntoViewOptions ?? true + + if (hashScrollIntoViewOptions) { + const el = document.getElementById(hash) + if (el) { + el.scrollIntoView(hashScrollIntoViewOptions) + } + } + + return + } + + scrollTo(0, 0) +} diff --git a/packages/router-core/src/scroll-restoration-script/client.ts b/packages/router-core/src/scroll-restoration-script/client.ts new file mode 100644 index 0000000000..7552ebcce3 --- /dev/null +++ b/packages/router-core/src/scroll-restoration-script/client.ts @@ -0,0 +1,5 @@ +import type { AnyRouter } from '../router' + +export function getScrollRestorationScriptForRouter(_router: AnyRouter) { + return null +} diff --git a/packages/router-core/src/scroll-restoration-script/server.ts b/packages/router-core/src/scroll-restoration-script/server.ts new file mode 100644 index 0000000000..5c5ce5e734 --- /dev/null +++ b/packages/router-core/src/scroll-restoration-script/server.ts @@ -0,0 +1,43 @@ +import minifiedScrollRestorationScript from '../scroll-restoration-inline?script-string' +import { + defaultGetScrollRestorationKey, + storageKey, +} from '../scroll-restoration' +import { escapeHtml } from '../utils' +import type { AnyRouter } from '../router' + +const defaultInlineScrollRestorationScript = `(${minifiedScrollRestorationScript})(${escapeHtml( + JSON.stringify(storageKey), +)})` + +function getScrollRestorationScript(key?: string) { + if (key === undefined) { + return defaultInlineScrollRestorationScript + } + + return `(${minifiedScrollRestorationScript})(${escapeHtml(JSON.stringify(storageKey))},${escapeHtml(JSON.stringify(key))})` +} + +export function getScrollRestorationScriptForRouter(router: AnyRouter) { + if ( + typeof router.options.scrollRestoration === 'function' && + !router.options.scrollRestoration({ location: router.latestLocation }) + ) { + return null + } + + const getKey = router.options.getScrollRestorationKey + if (!getKey) { + return defaultInlineScrollRestorationScript + } + + const location = router.latestLocation + const userKey = getKey(location) + const defaultKey = defaultGetScrollRestorationKey(location) + + if (userKey === defaultKey) { + return defaultInlineScrollRestorationScript + } + + return getScrollRestorationScript(userKey) +} diff --git a/packages/router-core/src/scroll-restoration.ts b/packages/router-core/src/scroll-restoration.ts index 22d5ecb558..972da92da1 100644 --- a/packages/router-core/src/scroll-restoration.ts +++ b/packages/router-core/src/scroll-restoration.ts @@ -1,19 +1,13 @@ -import { functionalUpdate } from './utils' +import { isServer } from '@tanstack/router-core/isServer' import type { AnyRouter } from './router' import type { ParsedLocation } from './location' -import type { NonNullableUpdater } from './utils' -import type { HistoryLocation } from '@tanstack/history' export type ScrollRestorationEntry = { scrollX: number; scrollY: number } -export type ScrollRestorationByElement = Record<string, ScrollRestorationEntry> +type ScrollRestorationByElement = Record<string, ScrollRestorationEntry> -export type ScrollRestorationByKey = Record<string, ScrollRestorationByElement> +type ScrollRestorationByKey = Record<string, ScrollRestorationByElement> -export type ScrollRestorationCache = { - state: ScrollRestorationByKey - set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void -} export type ScrollRestorationOptions = { getKey?: (location: ParsedLocation) => string scrollBehavior?: ScrollToOptions['behavior'] @@ -21,60 +15,31 @@ export type ScrollRestorationOptions = { function getSafeSessionStorage() { try { - if ( - typeof window !== 'undefined' && - typeof window.sessionStorage === 'object' - ) { - return window.sessionStorage - } + // Accessing sessionStorage itself can throw SecurityError in locked-down + // contexts, e.g. sandboxed/opaque origins or blocked storage policies. + return sessionStorage } catch { - // silent + return } - return undefined } -/** SessionStorage key used to persist scroll restoration state. */ -/** SessionStorage key used to store scroll positions across navigations. */ -/** SessionStorage key used to store scroll positions across navigations. */ +// SessionStorage key used to store scroll positions across navigations. export const storageKey = 'tsr-scroll-restoration-v1_3' +const safeSessionStorage = getSafeSessionStorage() -const throttle = (fn: (...args: Array<any>) => void, wait: number) => { - let timeout: any - return (...args: Array<any>) => { - if (!timeout) { - timeout = setTimeout(() => { - fn(...args) - timeout = null - }, wait) - } +function createScrollRestorationCache() { + try { + return JSON.parse( + safeSessionStorage?.getItem(storageKey) || '{}', + ) as ScrollRestorationByKey + } catch { + // ignore invalid session storage payloads + return {} } } -function createScrollRestorationCache(): ScrollRestorationCache | null { - const safeSessionStorage = getSafeSessionStorage() - if (!safeSessionStorage) { - return null - } - - const persistedState = safeSessionStorage.getItem(storageKey) - let state: ScrollRestorationByKey = persistedState - ? JSON.parse(persistedState) - : {} - - return { - state, - // This setter is simply to make sure that we set the sessionStorage right - // after the state is updated. It doesn't necessarily need to be a functional - // update. - set: (updater) => ( - (state = functionalUpdate(updater, state) || state), - safeSessionStorage.setItem(storageKey, JSON.stringify(state)) - ), - } -} - -/** In-memory handle to the persisted scroll restoration cache. */ -export const scrollRestorationCache = createScrollRestorationCache() +const scrollRestorationCache = /* @__PURE__ */ createScrollRestorationCache() +const scrollRestorationIdAttribute = 'data-scroll-restoration-id' /** * The default `getKey` function for `useScrollRestoration`. @@ -82,314 +47,332 @@ export const scrollRestorationCache = createScrollRestorationCache() * * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render. */ - -/** - * Default scroll restoration cache key: location state key or full href. - */ export const defaultGetScrollRestorationKey = (location: ParsedLocation) => { return location.state.__TSR_key! || location.href } -/** Best-effort nth-child CSS selector for a given element. */ -export function getCssSelector(el: any): string { - const path = [] +function getScrollRestorationSelector(element: Element): string { + const attrId = element.getAttribute(scrollRestorationIdAttribute) + if (attrId) { + return `[${scrollRestorationIdAttribute}="${attrId}"]` + } + + let selector = '' + let el: any = element let parent: HTMLElement + while ((parent = el.parentNode)) { - path.push( - `${el.tagName}:nth-child(${Array.prototype.indexOf.call(parent.children, el) + 1})`, - ) + let index = 1 + let sibling = el + while ((sibling = sibling.previousElementSibling)) { + index++ + } + + const part = `${el.localName}:nth-child(${index})` + selector = selector ? `${part} > ${selector}` : part el = parent } - return `${path.reverse().join(' > ')}`.toLowerCase() + + return selector } -let ignoreScroll = false +export function getElementScrollRestorationEntry( + router: AnyRouter, + options: ( + | { + id: string + getElement?: () => Window | Element | undefined | null + } + | { + id?: string + getElement: () => Window | Element | undefined | null + } + ) & { + getKey?: (location: ParsedLocation) => string + }, +): ScrollRestorationEntry | undefined { + const getKey = options.getKey || defaultGetScrollRestorationKey + const restoreKey = getKey(router.latestLocation) + const entries = scrollRestorationCache[restoreKey] -// NOTE: This function must remain pure and not use any outside variables -// unless they are passed in as arguments. Why? Because we need to be able to -// toString() it into a script tag to execute as early as possible in the browser -// during SSR. Additionally, we also call it from within the router lifecycle -export function restoreScroll({ - storageKey, - key, - behavior, - shouldScrollRestoration, - scrollToTopSelectors, - location, -}: { - storageKey: string - key?: string - behavior?: ScrollToOptions['behavior'] - shouldScrollRestoration?: boolean - scrollToTopSelectors?: Array<string | (() => Element | null | undefined)> - location?: HistoryLocation -}) { - let byKey: ScrollRestorationByKey - - try { - byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}') - } catch (error) { - console.error(error) + if (!entries) { return } - const resolvedKey = key || window.history.state?.__TSR_key - const elementEntries = byKey[resolvedKey] + if (options.id) { + return entries[`[${scrollRestorationIdAttribute}="${options.id}"]`] + } - // - ignoreScroll = true + const element = options.getElement?.() + if (!element) { + return + } + + return entries[ + element === window + ? windowScrollTarget + : getScrollRestorationSelector(element as Element) + ] +} + +let ignoreScroll = false +const windowScrollTarget = 'window' + +function getElement(selector: string | (() => Element | null | undefined)) { + try { + return typeof selector === 'function' + ? selector() + : document.querySelector(selector) + } catch {} + return +} + +function getScrollToTopElements( + scrollToTopSelectors: NonNullable< + AnyRouter['options']['scrollToTopSelectors'] + >, +) { + const elements = new Set<Element>() + + for (const selector of scrollToTopSelectors) { + if (selector === windowScrollTarget) { + continue + } + + const element = getElement(selector) + if (element) { + elements.add(element) + } + } + + return elements +} + +export function setupScrollRestoration(router: AnyRouter, force?: boolean) { + // Keep hash/top scrolling active even when sessionStorage is unavailable. + const shouldSetupScrollRestoration = force ?? router.options.scrollRestoration + const scroll = router._scroll + + if (shouldSetupScrollRestoration) { + scroll.e = true + } + + if (isServer ?? router.isServer) { + return + } + + const getKey = + router.options.getScrollRestorationKey || defaultGetScrollRestorationKey + const trackedScrollTargets = new Set<Document | Element>() + + // Snapshot the current page's tracked scroll targets before navigation or unload. + const snapshotCurrentScrollTargets = (restoreKey: string) => { + const keyEntry = (scrollRestorationCache[restoreKey] ||= + {} as ScrollRestorationByElement) + + for (const target of trackedScrollTargets) { + if (target === document) { + keyEntry[windowScrollTarget] = { scrollX, scrollY } + } else if ((target as Element).isConnected) { + keyEntry[getScrollRestorationSelector(target as Element)] = { + scrollX: (target as Element).scrollLeft, + scrollY: (target as Element).scrollTop, + } + } + } + } + + if (shouldSetupScrollRestoration && !scroll.s) { + scroll.s = true + ignoreScroll = false + + history.scrollRestoration = 'manual' + + document.addEventListener( + 'scroll', + (event) => { + if (ignoreScroll) { + return + } + trackedScrollTargets.add(event.target as Document | Element) + }, + true, + ) + router.subscribe('onBeforeLoad', (event) => { + if (event.fromLocation) { + snapshotCurrentScrollTargets(getKey(event.fromLocation)) + } + trackedScrollTargets.clear() + }) + addEventListener('pagehide', () => { + // Allow native restoration on reload or a later return to this entry. + // Reset even when entering BFCache: the cached document may be evicted. + // Do this first so a failing getKey/snapshot cannot leave it in manual mode. + history.scrollRestoration = 'auto' + + // Save positions for our own restoration if a new document loads. + snapshotCurrentScrollTargets( + getKey( + router.stores.resolvedLocation.get() ?? router.stores.location.get(), + ), + ) + try { + safeSessionStorage?.setItem( + storageKey, + JSON.stringify(scrollRestorationCache), + ) + } catch { + if (process.env.NODE_ENV !== 'production') { + console.warn( + '[ts-router] Could not persist scroll restoration state to sessionStorage.', + ) + } + } + }) + + addEventListener('pageshow', (event) => { + if (event.persisted) { + // BFCache resumes the existing document without rerunning router setup. + // Reclaim restoration so the browser and router don't both control it. + // Fresh documents already set manual mode during setup. + history.scrollRestoration = 'manual' + } + }) + } + + if (scroll.r) { + return + } + + scroll.r = true + + // Restore destination scroll after the new route has rendered. + router.subscribe('onRendered', (event) => { + const behavior = router.options.scrollRestorationBehavior + const scrollToTopSelectors = router.options.scrollToTopSelectors + const shouldResetScroll = scroll.n + const hashNavigation = scroll.h + let scrollToTopElements: Set<Element> | undefined + trackedScrollTargets.clear() + scroll.n = true + scroll.h = false - // - scroll: { - // If we have a cached entry for this location state, - // we always need to prefer that over the hash scroll. if ( - shouldScrollRestoration && - elementEntries && - Object.keys(elementEntries).length > 0 + typeof router.options.scrollRestoration === 'function' && + !router.options.scrollRestoration({ location: router.latestLocation }) ) { - for (const elementSelector in elementEntries) { - const entry = elementEntries[elementSelector]! - if (elementSelector === 'window') { - window.scrollTo({ - top: entry.scrollY, - left: entry.scrollX, + return + } + + const cacheKey = getKey(event.toLocation) + const fromCacheKey = event.fromLocation && getKey(event.fromLocation) + + if (scroll.e && fromCacheKey && fromCacheKey !== cacheKey) { + const fromElementEntries = scrollRestorationCache[fromCacheKey] + + if (fromElementEntries) { + let toElementEntries = scrollRestorationCache[cacheKey] + + for (const elementSelector in fromElementEntries) { + if (elementSelector === windowScrollTarget) { + if (shouldResetScroll) { + continue + } + } else { + const element = getElement(elementSelector) + if (!element) { + continue + } + + if (shouldResetScroll && scrollToTopSelectors) { + scrollToTopElements ??= + getScrollToTopElements(scrollToTopSelectors) + if (scrollToTopElements.has(element)) { + continue + } + } + } + + if (!toElementEntries) { + toElementEntries = scrollRestorationCache[cacheKey] = + {} as ScrollRestorationByElement + } + + toElementEntries[elementSelector] ??= + fromElementEntries[elementSelector]! + } + } + } + + ignoreScroll = true + + try { + const hash = event.toLocation.hash + const hashScrollIntoViewOptions = + event.toLocation.state.__hashScrollIntoViewOptions ?? true + let windowRestored = false + + if (shouldResetScroll) { + if (!hash && scrollToTopSelectors) { + scrollToTopElements ??= getScrollToTopElements(scrollToTopSelectors) + } + + const skipWindowRestore = + hash && hashScrollIntoViewOptions && hashNavigation + + const elementEntries = scroll.e + ? scrollRestorationCache[cacheKey] + : undefined + + if (elementEntries) { + for (const elementSelector in elementEntries) { + const { scrollX, scrollY } = elementEntries[elementSelector]! + + if (elementSelector === windowScrollTarget) { + if (skipWindowRestore) { + continue + } + + scrollTo({ + top: scrollY, + left: scrollX, + behavior, + }) + windowRestored = true + } else { + const element = getElement(elementSelector) + if (element) { + element.scrollLeft = scrollX + element.scrollTop = scrollY + scrollToTopElements?.delete(element) + } + } + } + } + + if (!hash) { + const scrollOptions = { + top: 0, + left: 0, behavior, - }) - } else if (elementSelector) { - const element = document.querySelector(elementSelector) - if (element) { - element.scrollLeft = entry.scrollX - element.scrollTop = entry.scrollY + } + + if (!windowRestored) { + scrollTo(scrollOptions) + } + if (scrollToTopElements) { + for (const element of scrollToTopElements) { + element.scrollTo(scrollOptions) + } } } } - break scroll - } - - // If we don't have a cached entry for the hash, - // Which means we've never seen this location before, - // we need to check if there is a hash in the URL. - // If there is, we need to scroll it's ID into view. - const hash = (location ?? window.location).hash.split('#', 2)[1] - - if (hash) { - const hashScrollIntoViewOptions = - window.history.state?.__hashScrollIntoViewOptions ?? true - - if (hashScrollIntoViewOptions) { - const el = document.getElementById(hash) - if (el) { - el.scrollIntoView(hashScrollIntoViewOptions) - } + if (!windowRestored && hash && hashScrollIntoViewOptions) { + document.getElementById(hash)?.scrollIntoView(hashScrollIntoViewOptions) } - - break scroll - } - - // If there is no cached entry for the hash and there is no hash in the URL, - // we need to scroll to the top of the page for every scrollToTop element - const scrollOptions = { top: 0, left: 0, behavior } - window.scrollTo(scrollOptions) - if (scrollToTopSelectors) { - for (const selector of scrollToTopSelectors) { - if (selector === 'window') continue - const element = - typeof selector === 'function' - ? selector() - : document.querySelector(selector) - if (element) element.scrollTo(scrollOptions) - } - } - } - - // - ignoreScroll = false -} - -/** Setup global listeners and hooks to support scroll restoration. */ -/** Setup global listeners and hooks to support scroll restoration. */ -export function setupScrollRestoration(router: AnyRouter, force?: boolean) { - if (!scrollRestorationCache && !router.isServer) { - return - } - const shouldScrollRestoration = - force ?? router.options.scrollRestoration ?? false - - if (shouldScrollRestoration) { - router.isScrollRestoring = true - } - - if ( - router.isServer || - router.isScrollRestorationSetup || - !scrollRestorationCache - ) { - return - } - - router.isScrollRestorationSetup = true - - // - ignoreScroll = false - - const getKey = - router.options.getScrollRestorationKey || defaultGetScrollRestorationKey - - window.history.scrollRestoration = 'manual' - - // // Create a MutationObserver to monitor DOM changes - // const mutationObserver = new MutationObserver(() => { - // ;ignoreScroll = true - // requestAnimationFrame(() => { - // ;ignoreScroll = false - - // // Attempt to restore scroll position on each dom - // // mutation until the user scrolls. We do this - // // because dynamic content may come in at different - // // ticks after the initial render and we want to - // // keep up with that content as much as possible. - // // As soon as the user scrolls, we no longer need - // // to attempt router. - // // console.log('mutation observer restoreScroll') - // restoreScroll( - // storageKey, - // getKey(router.state.location), - // router.options.scrollRestorationBehavior, - // ) - // }) - // }) - - // const observeDom = () => { - // // Observe changes to the entire document - // mutationObserver.observe(document, { - // childList: true, // Detect added or removed child nodes - // subtree: true, // Monitor all descendants - // characterData: true, // Detect text content changes - // }) - // } - - // const unobserveDom = () => { - // mutationObserver.disconnect() - // } - - // observeDom() - - const onScroll = (event: Event) => { - // unobserveDom() - - if (ignoreScroll || !router.isScrollRestoring) { - return - } - - let elementSelector = '' - - if (event.target === document || event.target === window) { - elementSelector = 'window' - } else { - const attrId = (event.target as Element).getAttribute( - 'data-scroll-restoration-id', - ) - - if (attrId) { - elementSelector = `[data-scroll-restoration-id="${attrId}"]` - } else { - elementSelector = getCssSelector(event.target) - } - } - - const restoreKey = getKey(router.state.location) - - scrollRestorationCache.set((state) => { - const keyEntry = (state[restoreKey] ||= {} as ScrollRestorationByElement) - - const elementEntry = (keyEntry[elementSelector] ||= - {} as ScrollRestorationEntry) - - if (elementSelector === 'window') { - elementEntry.scrollX = window.scrollX || 0 - elementEntry.scrollY = window.scrollY || 0 - } else if (elementSelector) { - const element = document.querySelector(elementSelector) - if (element) { - elementEntry.scrollX = element.scrollLeft || 0 - elementEntry.scrollY = element.scrollTop || 0 - } - } - - return state - }) - } - - // Throttle the scroll event to avoid excessive updates - if (typeof document !== 'undefined') { - document.addEventListener('scroll', throttle(onScroll, 100), true) - } - - router.subscribe('onRendered', (event) => { - // unobserveDom() - - const cacheKey = getKey(event.toLocation) - - // If the user doesn't want to restore the scroll position, - // we don't need to do anything. - if (!router.resetNextScroll) { - router.resetNextScroll = true - return - } - if (typeof router.options.scrollRestoration === 'function') { - const shouldRestore = router.options.scrollRestoration({ - location: router.latestLocation, - }) - if (!shouldRestore) { - return - } - } - - restoreScroll({ - storageKey, - key: cacheKey, - behavior: router.options.scrollRestorationBehavior, - shouldScrollRestoration: router.isScrollRestoring, - scrollToTopSelectors: router.options.scrollToTopSelectors, - location: router.history.location, - }) - - if (router.isScrollRestoring) { - // Mark the location as having been seen - scrollRestorationCache.set((state) => { - state[cacheKey] ||= {} as ScrollRestorationByElement - - return state - }) + } finally { + ignoreScroll = false } }) } - -/** - * @private - * Handles hash-based scrolling after navigation completes. - * To be used in framework-specific <Transitioner> components during the onResolved event. - * - * Provides hash scrolling for programmatic navigation when default browser handling is prevented. - * @param router The router instance containing current location and state - */ -/** - * @private - * Handles hash-based scrolling after navigation completes. - * To be used in framework-specific Transitioners. - */ -export function handleHashScroll(router: AnyRouter) { - if (typeof document !== 'undefined' && (document as any).querySelector) { - const hashScrollIntoViewOptions = - router.state.location.state.__hashScrollIntoViewOptions ?? true - - if (hashScrollIntoViewOptions && router.state.location.hash !== '') { - const el = document.getElementById(router.state.location.hash) - if (el) { - el.scrollIntoView(hashScrollIntoViewOptions) - } - } - } -} diff --git a/packages/router-core/src/searchMiddleware.ts b/packages/router-core/src/searchMiddleware.ts index e90d453350..a78732d833 100644 --- a/packages/router-core/src/searchMiddleware.ts +++ b/packages/router-core/src/searchMiddleware.ts @@ -1,8 +1,17 @@ -import { deepEqual } from './utils' +import { deepEqual, hasOwn } from './utils' import type { NoInfer, PickOptional } from './utils' -import type { SearchMiddleware } from './route' +import type { + SearchMiddleware, + SearchMiddlewareContext, + SearchMiddlewareMeta, +} from './route' import type { IsRequiredParams } from './link' +type SearchMiddlewareNextWithMeta<TSearchSchema> = ( + newSearch: TSearchSchema, + collectMeta: true, +) => { search: TSearchSchema; meta: SearchMiddlewareMeta } + /** * Retain specified search params across navigations. * @@ -17,17 +26,65 @@ export function retainSearchParams<TSearchSchema extends object>( keys: Array<keyof TSearchSchema> | true, ): SearchMiddleware<TSearchSchema> { return ({ search, next }) => { - const result = next(search) + const { search: resultSearch, meta } = ( + next as unknown as SearchMiddlewareNextWithMeta<TSearchSchema> + )(search, true) + if (keys === true) { - return { ...search, ...result } - } - // add missing keys from search to result - keys.forEach((key) => { - if (!(key in result)) { - result[key] = search[key] + const copy = { ...search, ...resultSearch } + const removed = meta.removed + const explicit = meta.explicit + for (const key of removed?.keys() || []) { + if ( + (explicit && hasOwn.call(explicit, key)) || + deepEqual(search[key as keyof TSearchSchema], removed!.get(key)) + ) { + delete copy[key as keyof TSearchSchema] + } } - }) - return result + for (const key of meta.removedAny || []) { + delete copy[key as keyof TSearchSchema] + } + for (const key of meta.defaulted?.keys() || []) { + if ( + key in search && + !meta.removedAny?.has(key) && + !( + meta.removed?.has(key) && + ((explicit && hasOwn.call(explicit, key)) || + deepEqual( + search[key as keyof TSearchSchema], + meta.removed.get(key), + )) + ) + ) { + copy[key as keyof TSearchSchema] = search[key as keyof TSearchSchema] + } + } + return copy + } + + const copy = { ...resultSearch } + const explicit = meta.explicit + // add missing keys from search to copy + for (const key of keys) { + const stringKey = key as string + const removed = + meta.removedAny?.has(stringKey) || + (meta.removed?.has(stringKey) && + ((explicit && hasOwn.call(explicit, stringKey)) || + deepEqual(search[key], meta.removed.get(stringKey)))) + if ( + !removed && + (!(key in copy) || + (key in search && + meta.defaulted?.has(stringKey) && + deepEqual(copy[key], meta.defaulted.get(stringKey)))) + ) { + copy[key] = search[key] + } + } + return copy } } @@ -44,31 +101,41 @@ export function retainSearchParams<TSearchSchema extends object>( export function stripSearchParams< TSearchSchema, TOptionalProps = PickOptional<NoInfer<TSearchSchema>>, - const TValues = - | Partial<NoInfer<TOptionalProps>> - | Array<keyof TOptionalProps>, + const TValues = Partial<NoInfer<TSearchSchema>> | Array<keyof TOptionalProps>, const TInput = IsRequiredParams<TSearchSchema> extends never ? TValues | true : TValues, >(input: NoInfer<TInput>): SearchMiddleware<TSearchSchema> { - return ({ search, next }) => { + return (({ search, next, meta }: SearchMiddlewareContext<TSearchSchema>) => { if (input === true) { + Object.keys(search as object).forEach((key) => { + if (meta) { + ;(meta.removedAny ||= new Set()).add(key) + } + }) return {} } - const result = next(search) as Record<string, unknown> + const nextResult = next(search) + const result = { ...nextResult } as Record<string, unknown> if (Array.isArray(input)) { input.forEach((key) => { - delete result[key] + delete result[key as string] + if (meta) { + ;(meta.removedAny ||= new Set()).add(key as string) + } }) } else { Object.entries(input as Record<string, unknown>).forEach( ([key, value]) => { if (deepEqual(result[key], value)) { delete result[key] + if (meta) { + ;(meta.removed ||= new Map()).set(key, value) + } } }, ) } return result as any - } + }) as SearchMiddleware<TSearchSchema> } diff --git a/packages/router-core/src/searchParams.ts b/packages/router-core/src/searchParams.ts index 740d36441c..19155586e8 100644 --- a/packages/router-core/src/searchParams.ts +++ b/packages/router-core/src/searchParams.ts @@ -1,6 +1,10 @@ import { decode, encode } from './qss' import type { AnySchema } from './validators' +// JSON can start with whitespace, ", [, {, -, a digit, or fa/nu/tr. +// False positives safely fall through to JSON.parse. +const jsonStart = /^(?:\s|["[{\d-]|fa|nu|tr)/ + /** Default `parseSearch` that strips leading '?' and JSON-parses values. */ export const defaultParseSearch = parseSearchWith(JSON.parse) /** Default `stringifySearch` using JSON.stringify for complex values. */ @@ -20,9 +24,10 @@ export const defaultStringifySearch = stringifySearchWith( * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization */ export function parseSearchWith(parser: (str: string) => any) { + const isJsonParser = parser === JSON.parse return (searchStr: string): AnySchema => { if (searchStr[0] === '?') { - searchStr = searchStr.substring(1) + searchStr = searchStr.slice(1) } const query: Record<string, unknown> = decode(searchStr) @@ -31,6 +36,10 @@ export function parseSearchWith(parser: (str: string) => any) { for (const key in query) { const value = query[key] if (typeof value === 'string') { + // Skip JSON.parse when the value cannot begin valid JSON. + if (isJsonParser && !jsonStart.test(value)) { + continue + } try { query[key] = parser(value) } catch (_err) { @@ -59,15 +68,19 @@ export function stringifySearchWith( stringify: (search: any) => string, parser?: (str: string) => any, ) { - const hasParser = typeof parser === 'function' + const isJsonParser = parser === JSON.parse function stringifyValue(val: any) { - if (typeof val === 'object' && val !== null) { + if (val && typeof val === 'object') { try { return stringify(val) } catch (_err) { // silent } - } else if (hasParser && typeof val === 'string') { + } else if (parser && typeof val === 'string') { + // Skip JSON.parse when the value cannot begin valid JSON. + if (isJsonParser && !jsonStart.test(val)) { + return val + } try { // Check if it's a valid parseable string. // If it is, then stringify it again. diff --git a/packages/router-core/src/sieve-cache.ts b/packages/router-core/src/sieve-cache.ts new file mode 100644 index 0000000000..c977c12e6d --- /dev/null +++ b/packages/router-core/src/sieve-cache.ts @@ -0,0 +1,75 @@ +export type SieveCache<TKey, TValue> = { + get: (key: TKey) => TValue | undefined + set: (key: TKey, value: TValue) => void + clear: () => void +} + +/** + * A fixed-capacity cache using the SIEVE eviction algorithm + * (https://cachemon.github.io/SIEVE-website/). + * + * Entries live in the Map's FIFO insertion order; a hit only flips a `visited` + * bit instead of relinking the entry, which makes `get` (by far the hottest + * operation here) one `Map.get` plus a boolean store. Eviction sweeps a `hand` + * from the oldest entry towards the newest, clearing `visited` bits until it + * finds an unvisited entry to drop, so entries touched since the last sweep + * survive one more round. This keeps LRU-like hit ratios while being + * scan-resistant. + */ +export function createSieveCache<TKey, TValue>( + max: number, +): SieveCache<TKey, TValue> { + type Node = { + key: TKey + value: TValue + visited: boolean + } + const cache = new Map<TKey, Node>() + let hand: IterableIterator<Node> | undefined + let newest: Node | undefined + + return { + get(key) { + const entry = cache.get(key) + if (!entry) { + return undefined + } + entry.visited = true + return entry.value + }, + set(key, value) { + const existing = cache.get(key) + if (existing) { + existing.value = value + return + } + if (cache.size >= max) { + // sweep from `hand` towards `newest` (wrapping around to `oldest`), + // clearing `visited` bits, and evict the first unvisited entry + let node = hand?.next().value + while (!node || node.visited) { + if (node) { + node.visited = false + } else { + hand = cache.values() + } + node = hand!.next().value + } + // Live Map iterators see later insertions. Reset at the boundary so the + // next sweep wraps to the oldest entry instead of visiting a replacement. + if (node === newest) { + hand = undefined + } + cache.delete(node.key) + } + const entry: Node = { key, value, visited: false } + newest = entry + cache.set(key, entry) + }, + clear() { + cache.clear() + hand = undefined + newest = undefined + }, + } +} diff --git a/packages/router-core/src/ssr/STREAMING.md b/packages/router-core/src/ssr/STREAMING.md new file mode 100644 index 0000000000..12d3bd7b08 --- /dev/null +++ b/packages/router-core/src/ssr/STREAMING.md @@ -0,0 +1,617 @@ +# SSR streaming + +This document explains how TanStack Router adds hydration scripts to server-rendered HTML. +It describes the transport in `router-core` and the React, Solid, and Vue adapters. + +## Main terms + +The renderer and Seroval produce output independently. + +- The **application output** is the HTML from the framework renderer. +- A **hydration source** is one complete JavaScript source string from the router or Seroval. +- An **initial tag** is a hydration `<script>` that `<Scripts>` renders with the application HTML. +- A **late record** is a self-removing hydration `<script>` that the transform inserts later. +- When hydration is enabled, the **boundary** is the final script from the first server render of `<Scripts>`. +- A **safe point** is a position where the transform can insert a late record. +- The **canonical close** is the exact byte sequence `</body></html>`. + +The transport keeps the order from each producer. +It does not define one arrival order across both producers. +Instead, it inserts ready hydration sources at safe points in the application output. + +The canonical close is the only application output that the merge path moves intentionally. + +## Main components + +A framework adapter produces application output as UTF-8 bytes or as an eager HTML string. +Seroval produces complete hydration sources. + +`attachRouterServerSsrUtils()` creates one request-local hydration state with `createHydrationScripts()`. +`ServerSsr` stores this state directly. + +The hydration state owns these tasks: + +- It stores the request nonce. +- It creates the initial tags and the boundary. +- It frames late records. +- It keeps sources in FIFO order. +- It applies backlog limits. +- It reports output state and failures. +- It removes retained data during cleanup. + +The stream transform reads this state. +It does not create the `<script>` framing. +It treats each late record as opaque bytes. + +The transform only recognizes fixed protocol bytes in application output. +It is not an HTML parser. + +## Request flow + +A normal hydration request has these steps: + +1. The hydration state starts with the Seroval cross-reference header and the router bootstrap. +2. `serverSsr.dehydrate()` builds the router state and starts Seroval. +3. Seroval sends complete hydration sources to the hydration state. +4. The first server render of `<Scripts>` takes all hydration sources that are ready. +5. `<Scripts>` renders initial tags, route scripts, manifest scripts, and one boundary. +6. The transform inserts later hydration sources at safe points. +7. Natural completion, cancellation, or failure cleans Router-owned request state. + +The serialized router state contains rendered route-match data. +It can also contain data from `router.options.dehydrate()`. +Promises and streams in that data can produce hydration sources later. +The request signal stops Router's wait for this hook, but is not passed into +the application callback. + +## Initial hydration tags + +The hydration state counts each retained source when the source arrives. +This count includes the cross-reference header and router bootstrap. +It also includes sources that arrive before `<Scripts>` renders. + +The first `<Scripts>` render takes all queued sources. +The initial tags then own those sources. +The hydration state removes them from its backlog count. + +The take is a one-time operation. +A later `<Scripts>` render cannot create a second boundary. + +### Initial tag size + +Small adjacent sources can share one initial tag. +Their source text and separators must fit in 16 Ki UTF-16 code units. + +A source that exceeds this limit stays in its own tag. +The code does not join that source to another source. + +Every initial hydration tag has the `data-tsr-stream-part` attribute. + +### Initial tag cleanup + +The final initial tag normally includes cleanup code. +The cleanup code walks through preceding element siblings with `data-tsr-stream-part`. +It removes those siblings and then removes its own tag. + +The cleanup code uses sibling links. +It does not create a DOM collection or call `document.querySelectorAll()`. + +If appending cleanup makes the final initial tag exceed 16 Ki, the code creates a separate cleanup tag. +It never appends cleanup code to an already oversized source. + +If no initial source exists, `<Scripts>` emits no initial cleanup tag. +It can still emit the boundary. + +A hydration syntax error or runtime error can prevent cleanup. +In that case, temporary initial tags can remain in the document. + +### Order inside `<Scripts>` + +`<Scripts>` emits server content in this order: + +1. Initial hydration tags. +2. Route and manifest script elements. +3. The boundary. + +The boundary is the last child emitted by `<Scripts>`. +It is not required to be the last child in `<body>`. + +React can hoist eligible external route scripts under its renderer rules. +The transport does not control when asynchronous or external scripts run. + +## Placement of `<Scripts>` + +`<Scripts>` marks the first position where late records can appear. +Render it in `<body>`. + +Application markup, framework-owned deferred patch records, and closing markup can follow the boundary. +Late router records can appear between these output parts at the safe points below. +The byte-pattern rules below still apply. + +While the transform remains in the `Merge` phase, it treats the first exact `</body></html>` after the boundary as the real document close. +The structural document close normally supplies this sequence. +Raw application data after the boundary must not contain an earlier exact copy. + +React treats each exact lowercase `</script>` as a safe point. +After the boundary, each such sequence must be a position where script insertion is valid. + +These rules are application and adapter contracts. +The byte scanner cannot tell structural markup from matching text. + +## The boundary + +The boundary is a private transport marker emitted by `<Scripts>`. +The boundary script removes itself in the browser. + +The transform scans for the boundary only after the initial take. +Before that take, it forwards consumed application bytes without a boundary scan. + +When the transform finds the boundary, it enters the `Merge` phase and lifts the hydration barrier. +Queued late sources then become eligible for output. + +If application EOF arrives before the boundary, hydration-enabled merge mode releases the initial sources as late records. +The transform then drains them after the delivered document, as it does for any EOF safe point. +The page cannot hydrate without the route scripts that `<Scripts>` renders, but the response completes. +Disabled hydration and initial pass-through do not require a boundary. + +## Transform paths + +One stream implementation serves every request. +It starts in pass-through when the hydration state can reserve the fast path before any application output. +Otherwise it starts in merge mode and can change to pass-through later. +Both entries use the same `PassThrough` phase. + +### Initial pass-through + +The hydration state reserves initial pass-through only when all these conditions are true: + +- The state is live and has no failure. +- Serialization is complete. +- The initial take or `disableHydration()` committed the initial output. +- No queued or active hydration output remains. +- No consumer or earlier fast-path reservation conflicts with this reservation. + +The stream then never claims the hydration output and never scans. +It forwards each `Uint8Array` from the renderer unchanged. +It does not scan, copy, or move those bytes. + +A Node renderer can also send string records. +The path encodes one string record at a time in chunks of at most 64 KiB. +It does not join separate string records. + +At application EOF, the path marks rendering as complete and closes normally. + +### Disabled hydration + +`serverSsr.disableHydration()` disables router hydration output for one request. +Call it instead of `dehydrate()`, before rendering starts. + +The runtime also rejects calls after any of these events: + +- `dehydrate()` starts. +- The first `<Scripts>` take commits initial output. +- The transform claims the hydration output. +- The hydration producer completes or starts an active record. + +The call removes the queued bootstrap sources. +It commits the initial state, lifts the barrier, and marks the producer as complete. + +The request emits no hydration tags or router boundary. +`<Scripts>` can still render normal route and manifest scripts. +The transform can use initial pass-through. + +### Merge mode + +The transform uses merge mode when it cannot reserve initial pass-through. +Merge mode claims the request hydration output for one consumer. +A second consumer causes an error. + +Merge mode recognizes these universal byte patterns: + +1. The fixed router boundary suffix. +2. The exact canonical close. + +An adapter can add one safe-point profile: + +- `script-close` matches exact lowercase `</script>`. +- `record-end` uses the end of a complete renderer record. + +The core does not select a profile from a framework name. +The adapter selects it. + +The boundary and script-close matchers keep partial matches across input chunks. +Their patterns have a unique first byte. + +The canonical close repeats its first byte. +The transform uses an exact search and a carry of at most 13 bytes for that pattern. + +### Merge phases + +| Phase | Meaning | +| ---------------- | -------------------------------------------------------------- | +| `BeforeBoundary` | Forward application output and wait for the one-time boundary. | +| `Merge` | Find safe points and the canonical close. | +| `HeldClose` | Keep the canonical close while later output drains. | +| `PassThrough` | Forward all later application output without scanning. | + +A stream starts in `PassThrough` when initial pass-through is reserved; otherwise only `Merge` can enter it. +`HeldClose` must preserve final document order, so it cannot enter that phase. + +A ready late record starts only after the boundary and at a safe point. +An active late record drains completely before application output resumes. + +### Dynamic pass-through + +Merge mode can stop scanning after the boundary. +It does this only when all these conditions are true: + +- The hydration output is `Done`. +- No hydration source or active record remains. +- The transform holds no partial canonical close. +- The hydration state can reserve the fast path for the current consumer. + +After the switch, all later application output passes through unchanged. +The transform does not scan or move later document closes. + +## Adapter safe points + +| Adapter or path | Additional safe point | +| --------------- | --------------------------------- | +| React | Exact lowercase `</script>` | +| Solid | End of a complete renderer record | +| Vue | None | +| Eager string | None | + +The boundary and canonical close are safe points for every adapter. +Ordinary EOF is also a safe point after the boundary. +A partial canonical close at EOF is forwarded as ordinary content, as described below. + +### React + +The transform treats React chunk boundaries as arbitrary. +It does not use them as safe points. + +The script-close profile lets a late record follow a complete React patch script. +It can also emit router data while React waits for later Suspense work. + +The adapter uses `renderToReadableStream` when that function exists. +Otherwise, it uses `renderToPipeableStream`. +Both paths use the same script-close profile. +Both paths set `progressiveChunkSize` to positive infinity so React does not split completed Suspense boundaries into separate patches based only on output size. +The adapter does not inspect the React version. + +### Solid + +The Solid adapter preserves each complete shell or patch string as one renderer record. +It uses the end of that record as a safe point. + +An internal 64 KiB encoding chunk is not a record end. +The safe point occurs only after the complete source record drains. + +### Vue + +The Vue adapter does not treat renderer record ends as safe points. +It uses only the boundary, the canonical close, and eligible EOF. + +The Vue application output must have one `<html>` element as its outer root. +An outer Vue Fragment or root array is not supported. +Its closing marker follows `</html>`, and the transform does not preserve that position. +Fragments inside `<html>` are supported. + +## Canonical document close + +Merge mode recognizes only this exact adjacent lowercase sequence: + +```html +</body></html> +``` + +While the transform remains in the `Merge` phase, the first matching sequence after the boundary becomes the held canonical close. +The transform emits preceding application bytes and holds the 14-byte close. + +A match inside one byte chunk advances past the close without copying it. +The transform can emit the preceding prefix as a view of that chunk. +A match across chunks uses the carry and one small combined buffer. +The transform caches the search result for the current byte chunk, including a missing match. +Returning from a renderer safe point reuses that result; advancing to another byte chunk clears it. + +The transform continues to process renderer patches and late records after it holds the close. +All other application bytes keep their order. +Late records keep FIFO order. +The two streams can interleave only at safe points. + +After successful completion, the transform emits a fresh 14-byte copy of the held close last. +On failure or cancellation, the transform does not emit the held close. +Bytes already delivered to the consumer remain delivered. + +The match is case-sensitive and byte-exact. +Whitespace or a text node between `</body>` and `</html>` prevents a match. + +If the transform completes successfully without a canonical match, it preserves all application bytes. +A later record can then appear after `</html>`. +This can happen at a React script close, a Solid record end, or EOF. + +Supporting every equivalent HTML form requires an HTML parser. +This transport uses exact byte matching instead. + +Initial and dynamic pass-through never move a document close. +They also preserve bytes that follow `</html>`. + +### EOF rules + +After the boundary, ordinary EOF can provide the final safe point. +If a late record is `Active`, it drains first. +These rules apply after no record is active: + +- If output is `Ready`, the transform drains ready late records at EOF. +- If output is `Waiting`, the transform waits for a state change. +- If normal serialization reaches `Done`, the transform completes. +- If output is `Failed`, the transform fails immediately. + +A partial canonical-close prefix at EOF is ordinary application content. +The transform forwards those bytes first and then applies the rules above. +A late record can follow them, exactly as after a document without a canonical close. + +Server cleanup terminates the transform instead of using these `Done` rules. + +## Hydration output states + +`claimOutput()` creates one pull view for merge mode. +The view has five states: + +| State | Meaning | +| --------- | ---------------------------------------------------------------------------------- | +| `Waiting` | No late record is eligible. The queue can still contain blocked sources. | +| `Ready` | Queued sources can start at the next safe point. | +| `Active` | One late record is in progress and must finish. | +| `Done` | Normal output drained, hydration is disabled, or cleanup made the output inactive. | +| `Failed` | The response must fail immediately. | + +The hydration output permits one consumer claim. +While it is live, it permits one active subscriber at a time. +Another subscriber can register after the first subscriber unregisters. +After cleanup, subscription returns a function that does nothing. + +The transform calls `pullChunk()` only from a response-stream pull. +Each call returns at most 64 KiB of bytes. + +## Late record framing + +`hydrationScripts.ts` owns the complete framing of every late record. +The framing includes the opening tag, escaped nonce, separators, self-removal source, and closing tag. + +A late record has this logical form: + +```text +<script nonce="...">source;source;document.currentScript.remove()</script> +``` + +The nonce attribute is absent when the request has no nonce. +The code escapes `&`, double quotes, single quotes, `<`, and `>` in a dynamic nonce. + +The transform does not inspect this framing. + +### Late record size + +The hydration output selects a FIFO source prefix for each late record. +Its target is at most 64 Ki UTF-16 code units for the complete framed record. + +The hydration output never splits one hydration source across script tags. +Therefore, one large source can create a record above the target. + +If a complete record is at most 16 Ki code units, the hydration output joins and encodes it once. +The hydration output encodes larger records in bounded parts with `encodeInto()`. + +Every returned byte chunk is at most 64 KiB. +Application output cannot appear inside an active record. + +### Queue ownership + +The queue uses one source array and a head index. +When it selects the complete unconsumed array, it can reuse that array internally. + +For a partial selection, it copies the selected prefix. +It replaces consumed queue slots with empty slots instead of shifting the live suffix. + +The queue removes its backing array when it becomes empty. +For a busy queue, it can compact after at least 1,024 consumed entries. +The consumed prefix must also be at least as large as the live suffix. + +Compaction keeps FIFO order. + +The hydration output releases a source from backlog accounting after its text finishes encoding. +The record stays `Active` until its separators and closing code drain. + +The boundary does not move or copy queued source strings. +It only makes them eligible for a pull. + +Normal serialization adds `$_TSR.e()` as the final hydration source. +The hydration output becomes `Done` after that source and all earlier sources drain. + +A backlog error changes the state to `Failed`, drops queued and active sources, +and causes Router to dispose of the SSR serializer. +Cleanup clears the queue and changes a claimed output to `Done`. + +## Backpressure and memory limits + +One downstream pull emits at most one output chunk. +The transform starts at most one application read ahead. + +The merge path can retain these main values: + +- One current application record and its encoder cursor, or one in-flight or prefetched nonterminal application read. +- One encoded application-string chunk of at most 64 KiB. The current input string record can be larger. +- At most 13 bytes from a partial canonical close. +- One active late record with its selected sources. +- One queue of later hydration sources. +- One hydration output buffer of at most 64 KiB. + +The hydration state permits at most 4,096 retained sources across initial, queued, and active output. +It also permits at most 16,777,216 UTF-16 code units of regular retained source text. + +These limits include constructor seeds and later sources. +They apply before and after the initial take. + +The limits apply to the pending backlog, not to total response output. +Initial-source accounting ends at the initial take. +Late-source accounting ends when each source finishes encoding. + +One source can exceed the 16 Mi-code-unit limit. +This exception supports one large loader or query value. +A second oversized source cannot be retained while the first is queued or being encoded. + +Cleanup clears source arrays, active encoder state, callbacks, timers, and stored errors. + +New eligible output and failures can wake the transform through one subscription. +`pullChunk()` does not notify the subscriber about successful state transitions. +When a producer update or barrier transition changes the output state, the hydration state still notifies the transform. +This notification can occur while a response-stream pull is pending. +Server cleanup terminates through a separate cleanup listener. +Application reads wake the transform separately. +The transform uses one waiting resolver at a time. +It does not create `Promise.race()` handlers in its pump. + +## Unicode and string input + +Built-in streaming adapters send UTF-8 `Uint8Array` records. +The transform forwards application bytes without decoding them. +A UTF-8 character can span byte records. + +A Node pipeable stream can also send string records. +The transform encodes each string record independently in chunks of at most 64 KiB. + +It does not repair a surrogate pair that spans two separate string records. +A record-end safe point occurs after the complete string, not after an internal encoding chunk. + +Each hydration source is one complete JavaScript string. +A semicolon separates adjacent sources in one tag. +HTML markup separates sources in different tags. + +`TextEncoder` and `encodeInto()` do not split a valid surrogate pair inside one source. +The implementation does not cut sources at estimated UTF-16 offsets. + +### Eager string output + +The eager helper uses the same merge path when initial pass-through is unavailable. +It encodes `<!DOCTYPE html>` and the HTML string in bounded parts. + +It decodes merged output incrementally with `TextDecoder`. +It does not first collect one complete byte buffer or call `Response.text()`. + +When initial pass-through is available, the helper returns `<!DOCTYPE html>` plus the original HTML string. +It then cleans the server state in a `finally` block. + +## Completion and cleanup + +The streaming paths use one finalizer. +The eager fast path uses its own `try` and `finally` because it has no response stream. + +| Result | Response output | Application reader | `onAbort` | +| ------------------------ | --------------- | ------------------ | --------- | +| Natural completion | Close | Release | No | +| Request abort | Error | Cancel | Yes | +| Consumer cancellation | No extra signal | Cancel | Yes | +| Stream or output failure | Error | Cancel | Yes | +| Serialization timeout | Error | Cancel | Yes | +| Lifetime timeout | Error | Cancel | Yes | +| External server cleanup | Error | Cancel | Yes | + +The terminal guard makes cleanup run once. +A non-success result calls the adapter `onAbort` function at most once. + +After natural completion, the transform releases the application reader. +After another result, it cancels the reader. +Reader cancellation can finish after router cleanup. + +Finally, server cleanup disposes of the SSR serializer and clears Router-owned hydration state. +It also stops the reader pump that Router's SSR RawStream bridge creates. +It clears the request router's `router.ssr` and `router.serverSsr` slots. + +Cleanup listeners receive one boolean, `settled`. +It is true when every value the router dehydrated has settled. +Rejected hydration output, including a backlog failure, stops serialization without marking deferred values as settled. +Router aborts the request's route-match controllers only when `settled` is false, because only then can loader work still be pending. + +Canceling a RawStream that the SSR or JSON bridge reconstructs removes Router's Seroval-stream listener. +Seroval and its official plugins remain responsible for work that they create. + +### Timeouts + +In merge mode, application EOF starts the serialization timeout and calls `setRenderFinished()`. +This happens as soon as a prefetched read reports EOF, even if the consumer pauses. +The default serialization timeout is 60 seconds. + +The timeout runs only while Seroval remains active. +It changes hydration output to `Failed` when it expires. + +Every live streaming transform also has a lifetime timeout. +Its default is twice the serialization timeout. + +Some Web runtimes return numeric timer IDs with no `unref()` method. +The code calls `unref()` only when the returned timer handle provides it. + +The serialization timeout stays referenced because it protects active work after application rendering ends. + +### External cleanup and response disposal + +`ServerSsr.cleanup()` notifies each live transform. +The transform then fails with an `AbortError`, cancels its reader, and calls the adapter abort function. + +A stream response also provides an idempotent `dispose()` function. +Disposal removes router ownership before it cancels the response body. +A renderer can ignore that body cancellation. + +After response handoff, request-abort binding has four cases: + +- If the request is already aborted, handoff disposes the stream immediately. +- If the live transform already observes the same request signal, handoff reuses its listener. On request abort, SSR cleanup also disposes the final response, including a body wrapped by middleware. +- Otherwise, with live router SSR state, handoff adds a listener to dispose the stream, and SSR cleanup removes that listener. +- Without live router SSR state, abort still disposes the stream. The one-time listener ends with the request signal. + +### Adapter cancellation limits + +Every streaming adapter rejects a request that is already aborted before renderer setup. +The adapters and core transform also detect an abort during synchronous setup before they return a response. + +The React readable path passes the request signal to `renderToReadableStream`. +The React pipeable path passes `abort()` to the transform. + +For Solid, cancelling the transform's reader errors the writable used by its renderer. +Vue pipes its public readable renderer stream into the transform, so reader cancellation propagates to Vue. +Neither renderer provides a disposal handle for unresolved component work. + +The adapters stop outgoing bytes and release router-owned state. +An unresolved Solid or Vue resource can retain its renderer closure until that resource settles. + +React and Solid bot-readiness waits observe an adapter signal that the transform aborts on failure or cancellation, including request abort, lifetime expiry, and external SSR cleanup. +These waits cannot keep the response promise pending after the transform terminates. +The extra controller is allocated only for bot waits on the readable-stream paths. +Each wait removes its listener when the wait ends. + +## Test coverage + +Unit tests cover every byte split of the boundary and script-close patterns. +They also cover every internal split of the canonical close. + +Hydration-state tests cover initial ownership, exact framing, nonce escaping, FIFO order, size limits, completion, failure, and cleanup. + +Transform tests cover safe points, content after `<Scripts>`, EOF, close carry, ordering, cancellation, timeouts, Unicode, and stream errors. + +Adapter tests make sure that React, Solid, and Vue select the documented safe-point profiles. +Real-renderer tests cover React 19 script closes and Solid record ends. + +React and Solid browser suites cover CSP for ordinary SSR output. +No browser CSP test forces a late dynamic hydration record. +Vue has no equivalent browser CSP suite. + +Normal unit tests cover backpressure correctness and lost-record prevention. +Slow-consumer memory tests run only when `RUN_BACKPRESSURE_PERF=1`. + +Browser tests cover hydration data, interaction, data order, and removal of initial hydration tags and the boundary. + +The [SSR streaming benchmark](../../benchmarks/ssr-streaming/README.md) measures throughput and retained memory. +Use interleaved warm runs for latency comparisons. +Use isolated processes with forced garbage collection for memory comparisons. + +Treat machine-specific measurements as supporting evidence. +They are not part of the transport contract. diff --git a/packages/router-core/src/ssr/bodyScripts.ts b/packages/router-core/src/ssr/bodyScripts.ts new file mode 100644 index 0000000000..b2472ec30b --- /dev/null +++ b/packages/router-core/src/ssr/bodyScripts.ts @@ -0,0 +1,57 @@ +import { _getAssetMatches } from '../load-client' +import type { Manifest, RouterManagedTag } from '../manifest' +import type { AnyRouteMatch } from '../Matches' +import type { InitialHydrationScriptTags } from './hydrationScripts' + +type ScriptTags = Array<RouterManagedTag> +export type SsrBodyScriptParts = readonly [ScriptTags, ScriptTags] + +export function getSsrBodyScriptParts( + matches: Array<AnyRouteMatch>, + manifest: Manifest | undefined, + nonce: string | undefined, + routeScriptAttrs?: Record<string, unknown>, +): SsrBodyScriptParts { + const assetMatches = _getAssetMatches(matches) + const routeScripts: ScriptTags = [] + const manifestScripts: ScriptTags = [] + for (const match of assetMatches) { + for (const script of Array.isArray(match.scripts) ? match.scripts : []) { + if (!script) { + continue + } + const { children, ...attrs } = script + routeScripts.push({ + tag: 'script', + attrs: { ...attrs, ...routeScriptAttrs, nonce }, + children, + }) + } + } + if (manifest) { + for (const match of assetMatches) { + for (const asset of manifest.routes[match.routeId]?.scripts ?? []) { + manifestScripts.push({ + tag: 'script', + attrs: { ...asset.attrs, nonce }, + children: asset.children, + }) + } + } + } + return [routeScripts, manifestScripts] +} +export function composeSsrBodyScripts( + [routeScripts, manifestScripts]: SsrBodyScriptParts, + initialHydrationScripts?: InitialHydrationScriptTags, +): Array<RouterManagedTag> { + if (!initialHydrationScripts) { + return [...routeScripts, ...manifestScripts] + } + return [ + ...initialHydrationScripts.before, + ...routeScripts, + ...manifestScripts, + initialHydrationScripts.boundary, + ] +} diff --git a/packages/router-core/src/ssr/client.ts b/packages/router-core/src/ssr/client.ts index 91499e22c9..dc769e7495 100644 --- a/packages/router-core/src/ssr/client.ts +++ b/packages/router-core/src/ssr/client.ts @@ -1,6 +1,14 @@ -export { mergeHeaders, headersInitToObject } from './headers' +export { mergeHeaders } from './headers' export { json } from './json' export type { JsonResponse } from './json' export { hydrate } from './ssr-client' export * from './ssr-client' export type { TsrSsrGlobal, DehydratedMatch, DehydratedRouter } from './types' +export { + createDefaultSerovalPlugins, + defaultSerovalPlugins, + defaultSerovalDeserializerPlugins, +} from './serializer/seroval-plugins' +export { makeSerovalPlugin } from './serializer/makeSerovalPlugin' +export type { AnySerializationAdapter } from './serializer/transformer' +export { createRawStreamDeserializePlugin } from './serializer/RawStreamRPCPlugin' diff --git a/packages/router-core/src/ssr/createRequestHandler.ts b/packages/router-core/src/ssr/createRequestHandler.ts index 29b7c1e25d..21e48ca242 100644 --- a/packages/router-core/src/ssr/createRequestHandler.ts +++ b/packages/router-core/src/ssr/createRequestHandler.ts @@ -1,14 +1,36 @@ -import { createMemoryHistory } from '@tanstack/history' +import { createServerHistory } from '@tanstack/history' +import { _getRenderedMatches } from '../load-client' +import { waitForReason as waitForRequest } from '../await-signal' import { mergeHeaders } from './headers' -import { attachRouterServerSsrUtils, getOrigin } from './ssr-server' +import { + attachRouterServerSsrUtils, + getNormalizedURL, + getOrigin, +} from './ssr-server' +import { + bindSsrResponseToRequest, + disposeSsrResponse, + isSsrResponse, +} from './handlerCallback' import type { HandlerCallback } from './handlerCallback' +import type { AnyHeaders } from './headers' import type { AnyRouter } from '../router' -import type { Manifest } from '../manifest' +import type { ServerManifest } from '../manifest' export type RequestHandler<TRouter extends AnyRouter> = ( cb: HandlerCallback<TRouter>, ) => Promise<Response> +export { waitForRequest } + +function createLateResponseDisposer(signal: AbortSignal) { + return (result: unknown) => { + if (result instanceof Response || isSsrResponse(result)) { + disposeSsrResponse(result, signal.reason) + } + } +} + export function createRequestHandler<TRouter extends AnyRouter>({ createRouter, request, @@ -16,27 +38,31 @@ export function createRequestHandler<TRouter extends AnyRouter>({ }: { createRouter: () => TRouter request: Request - getRouterManifest?: () => Manifest | Promise<Manifest> + getRouterManifest?: () => ServerManifest | Promise<ServerManifest> }): RequestHandler<TRouter> { return async (cb) => { + const signal = request.signal + signal.throwIfAborted() + const manifest = getRouterManifest + ? await waitForRequest(getRouterManifest(), signal) + : undefined + signal.throwIfAborted() const router = createRouter() - // Track whether the callback will handle cleanup - let cbWillCleanup = false + let responseOwnsCleanup = false try { attachRouterServerSsrUtils({ router, - manifest: await getRouterManifest?.(), + manifest, }) - const url = new URL(request.url, 'http://localhost') + // normalizing and sanitizing the pathname here for server, so we always deal with the same format during SSR. + const { url } = getNormalizedURL(request.url, 'http://localhost') const origin = getOrigin(request) const href = url.href.replace(url.origin, '') // Create a history for the router - const history = createMemoryHistory({ - initialEntries: [href], - }) + const history = createServerHistory(href) // Update the router with the history and context router.update({ @@ -44,27 +70,45 @@ export function createRequestHandler<TRouter extends AnyRouter>({ origin: router.options.origin ?? origin, }) - await router.load() + await router.load({ + _signal: signal, + _skipLocationUpdate: true, + }) + signal.throwIfAborted() - await router.serverSsr?.dehydrate() + const result = router._serverResult + if (result?.type === 'redirect') { + return result.redirect + } + + await router.serverSsr?.dehydrate({ signal }) + signal.throwIfAborted() const responseHeaders = getRequestHeaders({ router, }) - // Mark that the callback will handle cleanup - cbWillCleanup = true - return cb({ - request, - router, - responseHeaders, - } as any) + signal.throwIfAborted() + const disposeLate = createLateResponseDisposer(signal) + const response = await waitForRequest( + cb({ + request, + router, + responseHeaders, + }), + signal, + disposeLate, + disposeLate, + ) + const ssrResponse = bindSsrResponseToRequest(router, response, signal) + signal.throwIfAborted() + responseOwnsCleanup = ssrResponse.serverSsrCleanup === 'stream' + return ssrResponse.response } finally { - if (!cbWillCleanup) { + if (!responseOwnsCleanup) { // Clean up router SSR state if the callback won't handle it // (e.g., if an error occurred before the callback was invoked). - // When the callback runs, it handles cleanup (either via transformStreamWithRouter - // for streaming, or directly in renderRouterToString for non-streaming). + // Transformed streaming response bodies clean up when consumed/cancelled. router.serverSsr?.cleanup() } } @@ -72,21 +116,15 @@ export function createRequestHandler<TRouter extends AnyRouter>({ } function getRequestHeaders(opts: { router: AnyRouter }): Headers { - let headers = mergeHeaders( + const matchHeaders: Array<AnyHeaders> = [] + for (const match of _getRenderedMatches(opts.router.stores.matches.get())) { + matchHeaders.push(match.headers) + } + + return mergeHeaders( { 'Content-Type': 'text/html; charset=UTF-8', }, - ...opts.router.state.matches.map((match) => { - return match.headers - }), + ...matchHeaders, ) - - // Handle Redirects - const { redirect } = opts.router.state - - if (redirect) { - headers = mergeHeaders(headers, redirect.headers) - } - - return headers } diff --git a/packages/router-core/src/ssr/handlerCallback.ts b/packages/router-core/src/ssr/handlerCallback.ts index e9ae2cd3ba..45f3255c5b 100644 --- a/packages/router-core/src/ssr/handlerCallback.ts +++ b/packages/router-core/src/ssr/handlerCallback.ts @@ -1,11 +1,173 @@ import type { AnyRouter } from '../router' +export type SsrResponse = + | { + response: Response + serverSsrCleanup: 'none' + } + | { + response: Response + serverSsrCleanup: 'stream' + dispose: (reason?: unknown) => undefined + } + +export type HandlerCallbackResult = Response | SsrResponse + +export function isSsrResponse(value: unknown): value is SsrResponse { + if ( + typeof value !== 'object' || + value === null || + !('response' in value) || + !(value.response instanceof Response) || + !('serverSsrCleanup' in value) + ) { + return false + } + + if (value.serverSsrCleanup === 'none') { + return true + } + + return ( + value.serverSsrCleanup === 'stream' && + 'dispose' in value && + typeof value.dispose === 'function' + ) +} + +export function normalizeSsrResponse( + result: HandlerCallbackResult, +): SsrResponse { + if (result instanceof Response) { + return { response: result, serverSsrCleanup: 'none' } + } + if (isSsrResponse(result)) { + return result + } + + throw new TypeError('Expected a Response from the SSR handler') +} + +function cancelResponseBody(response: Response, reason?: unknown): void { + const body = response.body + if (!body) { + return + } + void body.cancel(reason).catch(console.error) +} + +export function disposeSsrResponse( + result: HandlerCallbackResult, + reason?: unknown, +): undefined { + const response = normalizeSsrResponse(result) + if (response.serverSsrCleanup === 'stream') { + response.dispose(reason) + } else { + cancelResponseBody(response.response, reason) + } +} + +/** The HTTP status that Router's server load selected for this render. */ +export function getSsrStatus(router: AnyRouter) { + return router._serverResult?.type === 'render' + ? router._serverResult.status + : 200 +} + +export function createSsrStreamResponse( + router: AnyRouter, + response: Response, +): Extract<SsrResponse, { serverSsrCleanup: 'stream' }> { + const body = response.body + if (!body) { + throw new Error('Invariant failed: SSR stream response requires a body') + } + + return { + response, + serverSsrCleanup: 'stream', + dispose(reason?: unknown): undefined { + // Sever router ownership before asking user/renderer stream machinery to + // cancel. A custom stream is allowed to ignore cancellation forever. + router.serverSsr?.cleanup() + + void body.cancel(reason).catch(() => {}) + }, + } +} + +export function bindSsrResponseToRequest( + router: AnyRouter | undefined, + result: HandlerCallbackResult, + signal: AbortSignal, +): SsrResponse { + const ssrResponse = normalizeSsrResponse(result) + if (ssrResponse.serverSsrCleanup !== 'stream') { + if (signal.aborted) { + disposeSsrResponse(result, signal.reason) + } + return ssrResponse + } + + const abort = () => { + disposeSsrResponse(ssrResponse, signal.reason) + } + if (signal.aborted) { + abort() + return ssrResponse + } + + const serverSsr = router?.serverSsr + if (serverSsr?.hydrationScripts.requestSignal === signal) { + // The transform already observes this request. Its cleanup must also + // dispose the final response, including any middleware-owned body. + serverSsr.onCleanup(() => { + if (signal.aborted) { + abort() + } + }) + return ssrResponse + } + + signal.addEventListener('abort', abort, { once: true }) + if (!serverSsr) { + return ssrResponse + } + + serverSsr.onCleanup(() => { + signal.removeEventListener('abort', abort) + }) + return ssrResponse +} + +export function replaceSsrResponse( + result: HandlerCallbackResult, + response: Response, + reason?: unknown, +): Extract<SsrResponse, { serverSsrCleanup: 'none' }> { + disposeSsrResponse(result, reason) + return { response, serverSsrCleanup: 'none' } +} + +export function stripSsrResponseBody( + result: HandlerCallbackResult, + reason?: unknown, +): Extract<SsrResponse, { serverSsrCleanup: 'none' }> { + const ssrResponse = normalizeSsrResponse(result) + disposeSsrResponse(ssrResponse, reason) + return { + response: new Response(null, ssrResponse.response), + serverSsrCleanup: 'none', + } +} + export interface HandlerCallback<TRouter extends AnyRouter> { (ctx: { request: Request router: TRouter responseHeaders: Headers - }): Response | Promise<Response> + }): HandlerCallbackResult | Promise<HandlerCallbackResult> } export function defineHandlerCallback<TRouter extends AnyRouter>( diff --git a/packages/router-core/src/ssr/headers.ts b/packages/router-core/src/ssr/headers.ts index 51bc2f4f4d..a31a41c161 100644 --- a/packages/router-core/src/ssr/headers.ts +++ b/packages/router-core/src/ssr/headers.ts @@ -1,19 +1,7 @@ import { splitSetCookieString } from 'cookie-es' import type { OutgoingHttpHeaders } from 'node:http2' -// A utility function to turn HeadersInit into an object -export function headersInitToObject( - headers: HeadersInit, -): Record<keyof OutgoingHttpHeaders, string> { - const obj: Record<keyof OutgoingHttpHeaders, string> = {} - const headersInstance = new Headers(headers) - for (const [key, value] of headersInstance.entries()) { - obj[key] = value - } - return obj -} - -type AnyHeaders = +export type AnyHeaders = | Headers | HeadersInit | Record<string, string> @@ -24,13 +12,13 @@ type AnyHeaders = // Helper function to convert various HeaderInit types to a Headers instance function toHeadersInstance(init: AnyHeaders) { if (init instanceof Headers) { - return new Headers(init) + return init } else if (Array.isArray(init)) { return new Headers(init) } else if (typeof init === 'object') { return new Headers(init as HeadersInit) } else { - return new Headers() + return null } } @@ -38,6 +26,7 @@ function toHeadersInstance(init: AnyHeaders) { export function mergeHeaders(...headers: Array<AnyHeaders>) { return headers.reduce((acc: Headers, header) => { const headersInstance = toHeadersInstance(header) + if (!headersInstance) return acc for (const [key, value] of headersInstance.entries()) { if (key === 'set-cookie') { const splitCookies = splitSetCookieString(value) diff --git a/packages/router-core/src/ssr/htmlBoundaryScanner.ts b/packages/router-core/src/ssr/htmlBoundaryScanner.ts new file mode 100644 index 0000000000..4a46f7c55f --- /dev/null +++ b/packages/router-core/src/ssr/htmlBoundaryScanner.ts @@ -0,0 +1,138 @@ +const textEncoder = new TextEncoder() + +const DOCUMENT_CLOSE = '</body></html>' +export const SCRIPT_CLOSE = '</script>' +export const DOCUMENT_CLOSE_ANCHOR_INDEX = DOCUMENT_CLOSE.indexOf('y') +export const SCRIPT_CLOSE_ANCHOR_INDEX = SCRIPT_CLOSE.indexOf('p') + +export const DOCUMENT_CLOSE_BYTES = textEncoder.encode(DOCUMENT_CLOSE) +export const SCRIPT_CLOSE_BYTES = textEncoder.encode(SCRIPT_CLOSE) + +export function encodeIntoBoundedChunk( + source: string, + sourceOffset: number, + output: Uint8Array, + outputOffset = 0, +) { + // encodeInto() stops before a code point that does not fit, so it never + // splits a surrogate pair across chunks. + return textEncoder.encodeInto( + sourceOffset === 0 ? source : source.slice(sourceOffset), + outputOffset === 0 ? output : output.subarray(outputOffset), + ) +} + +/** + * State for matching a fixed ASCII sequence across input chunks. + * + * The pattern must be non-empty, its first byte must be unique, and the anchor + * index must point inside the pattern. + */ +export type ByteMatcherState = { + readonly pattern: Uint8Array + readonly anchorIndex: number + matched: number +} + +/** Advance matcher state and return the local offset after a complete match. */ +export function advanceByteMatcher( + matcher: ByteMatcherState, + value: Uint8Array, + startIndex = 0, + findLast = false, +) { + const { pattern, anchorIndex } = matcher + let matched = matcher.matched + let lastMatchEnd: number | undefined + let index = startIndex + while (index < value.length) { + if (matched === 0) { + if (anchorIndex > 0 && index < value.length - anchorIndex) { + const anchor = value.indexOf(pattern[anchorIndex]!, index + anchorIndex) + if (anchor < 0) { + index = value.length - anchorIndex + continue + } + index = anchor - anchorIndex + } else { + index = value.indexOf(pattern[0]!, index) + if (index < 0) { + matcher.matched = matched + return lastMatchEnd + } + } + } + + const byte = value[index]! + if (byte === pattern[matched]) { + matched++ + } else { + matched = byte === pattern[0] ? 1 : 0 + } + index++ + + if (matched === pattern.length) { + matched = 0 + if (!findLast) { + matcher.matched = matched + return index + } + lastMatchEnd = index + } + } + matcher.matched = matched + return lastMatchEnd +} + +/** Find a complete fixed sequence that is contained in one byte chunk. */ +export function findExactBytes( + value: Uint8Array, + pattern: Uint8Array, + startIndex = 0, + anchorIndex = 0, +) { + let anchor = value.indexOf(pattern[anchorIndex]!, startIndex + anchorIndex) + while (anchor >= 0) { + const candidate = anchor - anchorIndex + if (candidate + pattern.length > value.length) { + return -1 + } + let patternIndex = 0 + while ( + patternIndex < pattern.length && + value[candidate + patternIndex] === pattern[patternIndex] + ) { + patternIndex++ + } + if (patternIndex === pattern.length) { + return candidate + } + anchor = value.indexOf(pattern[anchorIndex]!, anchor + 1) + } + return -1 +} + +/** + * Find the longest suffix that can become the fixed sequence in the next + * chunk. The returned index starts that suffix. + */ +export function getExactBytesPrefixAtEnd( + value: Uint8Array, + pattern: Uint8Array, + startIndex = 0, +) { + candidate: for ( + let length = Math.min(pattern.length - 1, value.length - startIndex); + length > 0; + length-- + ) { + const candidateStart = value.length - length + for (let index = 0; index < length; index++) { + if (value[candidateStart + index] !== pattern[index]) { + continue candidate + } + } + return candidateStart + } + return undefined +} diff --git a/packages/router-core/src/ssr/hydrationScripts.ts b/packages/router-core/src/ssr/hydrationScripts.ts new file mode 100644 index 0000000000..79222e5d73 --- /dev/null +++ b/packages/router-core/src/ssr/hydrationScripts.ts @@ -0,0 +1,689 @@ +/* eslint-disable @typescript-eslint/triple-slash-reference */ +/// <reference path="../vite-env.d.ts" /> + +import { getCrossReferenceHeader } from 'seroval' +import { invariant } from '../invariant' +import minifiedTsrBootStrapScript from './tsrScript?script-string' +import { GLOBAL_TSR } from './constants' +import { encodeIntoBoundedChunk } from './htmlBoundaryScanner' +import type { RouterManagedTag } from '../manifest' + +export const SSR_SERIALIZATION_SCOPE_ID = 'tsr' +const HYDRATION_SCRIPT_BOUNDARY_TAIL = ';/*$tsr-stream-boundary*/' + +const encoder = new TextEncoder() +const SOURCE_SEPARATOR = ';' +const MAX_INITIAL_SOURCE_CODE_UNITS = 16 * 1024 +const MAX_BACKLOG_CODE_UNITS = 16 * 1024 * 1024 +const MAX_BACKLOG_SOURCES = 4_096 +const MIN_OUTPUT_BYTES = 256 +const MAX_DIRECT_CODE_UNITS = 16 * 1024 +export const MAX_HYDRATION_OUTPUT_CHUNK_BYTES = 64 * 1024 +const MAX_DYNAMIC_RECORD_CODE_UNITS = MAX_HYDRATION_OUTPUT_CHUNK_BYTES + +const STREAM_PART_ATTRIBUTE = 'data-tsr-stream-part' +const INITIAL_CLEANUP_SOURCE = `{let s=document.currentScript,p;while((p=s.previousElementSibling)&&p.hasAttribute('${STREAM_PART_ATTRIBUTE}'))p.remove();s.remove()}` +const INITIAL_CLEANUP_SUFFIX = SOURCE_SEPARATOR + INITIAL_CLEANUP_SOURCE +const DYNAMIC_CLOSE_SOURCE = 'document.currentScript.remove()</script>' +const HYDRATION_SCRIPT_BOUNDARY_SOURCE = + `document.currentScript.remove()` + HYDRATION_SCRIPT_BOUNDARY_TAIL +const HYDRATION_SCRIPT_BOUNDARY_SUFFIX = + HYDRATION_SCRIPT_BOUNDARY_TAIL + '</script>' +export const HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX = + HYDRATION_SCRIPT_BOUNDARY_SUFFIX.lastIndexOf('*') +export const HYDRATION_SCRIPT_BOUNDARY_BYTES = encoder.encode( + HYDRATION_SCRIPT_BOUNDARY_SUFFIX, +) + +const ROUTER_PREFIX = GLOBAL_TSR + '.router=' +const PROMISE_PREFIX = GLOBAL_TSR + '.p(()=>' +const DEFAULT_INITIAL_SOURCES = [ + getCrossReferenceHeader(SSR_SERIALIZATION_SCOPE_ID), + minifiedTsrBootStrapScript, +] + +export const HydrationScriptOutputState = { + Waiting: 0, + Ready: 1, + Active: 2, + Done: 3, + Failed: 4, +} as const + +export type HydrationScriptOutputState = + (typeof HydrationScriptOutputState)[keyof typeof HydrationScriptOutputState] + +/** A request-local, single-consumer stream of complete records. */ +export type HydrationScriptOutput = { + readonly state: HydrationScriptOutputState + readonly error: unknown + pullChunk: () => Uint8Array + subscribe: (onChange: () => void) => () => void +} + +type ConsumerOwnership = + | HydrationScriptOutput + | 'fast-path' + | 'cleaned' + | undefined + +/** The one-time initial `<Scripts>` take: hydration tags plus the boundary. */ +export type InitialHydrationScriptTags = { + before: Array<RouterManagedTag> + boundary: RouterManagedTag +} + +function escapeAttribute(value: string) { + return value.replace(/[&"'<>]/g, (char) => `&#${char.charCodeAt(0)};`) +} + +function createInitialTags( + sources: ReadonlyArray<string>, + nonce: string | undefined, +): InitialHydrationScriptTags { + const before: Array<RouterManagedTag> = [] + for (const source of sources) { + if (!source) { + continue + } + const previous = before[before.length - 1] + if ( + previous?.children && + previous.children.length + SOURCE_SEPARATOR.length + source.length <= + MAX_INITIAL_SOURCE_CODE_UNITS + ) { + previous.children += SOURCE_SEPARATOR + source + } else { + before.push({ + tag: 'script', + attrs: { nonce, [STREAM_PART_ATTRIBUTE]: '' }, + children: source, + }) + } + } + // Cleanup runs before route and asset scripts. If hydration code fails, its + // transport tags can remain because that page cannot hydrate successfully. + const lastHydrationTag = before[before.length - 1] + if (lastHydrationTag) { + const lastSource = lastHydrationTag.children! + if ( + lastSource.length + INITIAL_CLEANUP_SUFFIX.length <= + MAX_INITIAL_SOURCE_CODE_UNITS + ) { + lastHydrationTag.children = lastSource + INITIAL_CLEANUP_SUFFIX + } else { + // Do not concatenate onto a large source. A renderer could flatten the + // result and temporarily retain a second copy of the hydration payload. + before.push({ + tag: 'script', + attrs: { nonce, [STREAM_PART_ATTRIBUTE]: '' }, + children: INITIAL_CLEANUP_SOURCE, + }) + } + } + return { + before, + boundary: { + tag: 'script', + attrs: { nonce }, + children: HYDRATION_SCRIPT_BOUNDARY_SOURCE, + } satisfies RouterManagedTag, + } +} + +type HydrationScripts = { + pushSerializedSource: ( + data: string, + initial: boolean, + wrap: boolean, + ) => boolean + pushSource: (nextSource: string) => boolean + fail: (reason: unknown) => void + finish: () => void + takeInitialHydrationScriptTags: () => InitialHydrationScriptTags | undefined + disableHydration: () => void + isInitialTaken: () => boolean + skipInitialTake: () => void + liftBarrier: () => void + claimOutput: () => HydrationScriptOutput + reserveFastPath: (output?: HydrationScriptOutput) => boolean + startSerializationTimeout: (timeoutMs: number) => void + cleanup: () => void +} + +class HydrationScriptsOwner implements HydrationScriptOutput { + private queuedSources: Array<string | undefined> = [] + private queuedSourceHead = 0 + private initialTaken = false + private barrierLifted = false + private producerDone = false + private consumer: ConsumerOwnership + private listener: (() => void) | undefined + + private active: Array<string | undefined> | undefined + private retainedSources = 0 + private regularCodeUnits = 0 + private hasOversizedSource = false + + private segmentIndex = 0 + private closingSegmentIndex = 0 + private source = '' + private sourceOffset = 0 + private outputCapacity = MIN_OUTPUT_BYTES + + private outputState: HydrationScriptOutputState = + HydrationScriptOutputState.Waiting + private outputError: unknown + private timeout: ReturnType<typeof setTimeout> | undefined + private opening: string | undefined + + constructor( + private readonly nonce: string | undefined, + initialSources?: ReadonlyArray<string>, + ) { + // ServerSsr exposes this method as a bare callback, so keep this single + // method bound while all other owner operations live on the prototype. + this.takeInitialHydrationScriptTags = + this.takeInitialHydrationScriptTags.bind(this) + + const seedSources = initialSources ?? DEFAULT_INITIAL_SOURCES + for (const seedSource of seedSources) { + if (!this.account(seedSource)) { + break + } + this.queuedSources.push(seedSource) + } + } + + get state() { + return this.outputState + } + + get error() { + return this.outputError + } + + private notify() { + try { + this.listener?.() + } catch (listenerError) { + console.error('Hydration script output listener error:', listenerError) + } + } + + private refresh(notifyChange = true) { + const next = + this.outputState === HydrationScriptOutputState.Failed + ? HydrationScriptOutputState.Failed + : this.active + ? HydrationScriptOutputState.Active + : typeof this.consumer === 'object' && + this.initialTaken && + this.barrierLifted && + !this.queueIsEmpty() + ? HydrationScriptOutputState.Ready + : this.producerDone && this.initialTaken && this.queueIsEmpty() + ? HydrationScriptOutputState.Done + : HydrationScriptOutputState.Waiting + if (this.outputState !== next) { + this.outputState = next + if (notifyChange) { + this.notify() + } + } + } + + private clearTimeoutIfSet() { + if (this.timeout !== undefined) { + clearTimeout(this.timeout) + this.timeout = undefined + } + } + + private queueIsEmpty() { + return this.queuedSourceHead === this.queuedSources.length + } + + private clearQueue() { + this.queuedSources = [] + this.queuedSourceHead = 0 + } + + private dropBufferedOutput() { + this.clearQueue() + this.active = undefined + this.retainedSources = 0 + this.regularCodeUnits = 0 + this.hasOversizedSource = false + this.segmentIndex = 0 + this.closingSegmentIndex = 0 + this.source = '' + this.sourceOffset = 0 + this.outputCapacity = MIN_OUTPUT_BYTES + this.opening = undefined + } + + fail(reason: unknown) { + if ( + this.consumer === 'cleaned' || + this.outputState === HydrationScriptOutputState.Failed + ) { + return + } + this.outputError = reason + this.clearTimeoutIfSet() + this.dropBufferedOutput() + this.outputState = HydrationScriptOutputState.Failed + this.notify() + } + + private rejectBacklog(kind: 'source-part' | 'code-unit') { + this.fail(new Error(`SSR hydration backlog exceeded maximum ${kind} count`)) + return false + } + + private account(nextSource: string) { + if (this.retainedSources === MAX_BACKLOG_SOURCES) { + return this.rejectBacklog('source-part') + } + if (nextSource.length > MAX_BACKLOG_CODE_UNITS) { + if (this.hasOversizedSource) { + return this.rejectBacklog('code-unit') + } + this.hasOversizedSource = true + } else if ( + this.regularCodeUnits + nextSource.length > + MAX_BACKLOG_CODE_UNITS + ) { + return this.rejectBacklog('code-unit') + } else { + this.regularCodeUnits += nextSource.length + } + this.retainedSources++ + return true + } + + private releaseSource(part: string) { + this.retainedSources-- + if (part.length > MAX_BACKLOG_CODE_UNITS) { + this.hasOversizedSource = false + } else { + this.regularCodeUnits -= part.length + } + } + + private releaseAccounting(batch: ReadonlyArray<string | undefined>) { + for (const part of batch) { + if (part !== undefined) { + this.releaseSource(part) + } + } + } + + liftBarrier() { + if (this.consumer !== 'cleaned' && !this.barrierLifted) { + this.barrierLifted = true + this.refresh() + } + } + + private producerCanWrite() { + return ( + this.consumer !== 'cleaned' && + this.outputState !== HydrationScriptOutputState.Failed && + !this.producerDone + ) + } + + pushSource(nextSource: string) { + if (!this.producerCanWrite()) { + return false + } + if (this.account(nextSource)) { + this.queuedSources.push(nextSource) + if (this.initialTaken) { + this.refresh() + } + } else { + return false + } + // A notification can synchronously fail or clean up this owner. + return this.producerCanWrite() + } + + private takeQueuedBatch(batchLength: number) { + if ( + this.queuedSourceHead === 0 && + batchLength === this.queuedSources.length + ) { + const batch = this.queuedSources + this.clearQueue() + return batch + } + const end = this.queuedSourceHead + batchLength + const batch = this.queuedSources.slice(this.queuedSourceHead, end) + for (let index = this.queuedSourceHead; index < end; index++) { + this.queuedSources[index] = undefined + } + this.queuedSourceHead = end + if (this.queueIsEmpty()) { + this.clearQueue() + } else if ( + this.queuedSourceHead >= 1024 && + this.queuedSourceHead >= this.queuedSources.length - this.queuedSourceHead + ) { + this.queuedSources = this.queuedSources.slice(this.queuedSourceHead) + this.queuedSourceHead = 0 + } + return batch + } + + private release(batch: Array<string | undefined>) { + this.releaseAccounting(batch) + this.active = undefined + this.source = '' + this.sourceOffset = 0 + this.refresh(false) + } + + private advanceSource() { + const batch = this.active! + if (this.segmentIndex > 0 && this.segmentIndex < this.closingSegmentIndex) { + const partIndex = (this.segmentIndex - 1) >> 1 + if (this.segmentIndex % 2 === 1) { + const part = batch[partIndex] + if (part !== undefined) { + this.releaseSource(part) + batch[partIndex] = undefined + } + } + } + this.segmentIndex++ + // Segment 0 is the opening tag. Sources and separators alternate until + // the closing segment. The next advance releases the complete record. + if (this.segmentIndex < this.closingSegmentIndex) { + const partIndex = (this.segmentIndex - 1) >> 1 + this.source = + this.segmentIndex % 2 === 1 ? batch[partIndex]! : SOURCE_SEPARATOR + } else if (this.segmentIndex === this.closingSegmentIndex) { + this.source = DYNAMIC_CLOSE_SOURCE + } else { + this.release(batch) + } + this.sourceOffset = 0 + } + + private pullActive() { + const bytes = new Uint8Array(this.outputCapacity) + let offset = 0 + while (this.active) { + if (this.sourceOffset === this.source.length) { + this.advanceSource() + } else if (offset === bytes.length) { + break + } else { + const result = encodeIntoBoundedChunk( + this.source, + this.sourceOffset, + bytes, + offset, + ) + if (result.read === 0) { + break + } + this.sourceOffset += result.read + offset += result.written + } + } + if (offset === 0) { + throw new Error('SSR router script record produced no output') + } + if (offset === bytes.length) { + return bytes + } + // A subarray view pins the whole output buffer. Copy mostly-empty tail + // chunks (typically the final close-tag remnant) so the large buffer can + // be collected immediately. + return offset * 2 < bytes.length + ? bytes.slice(0, offset) + : bytes.subarray(0, offset) + } + + private pullReady() { + const scriptOpening = (this.opening ??= this.nonce + ? `<script nonce="${escapeAttribute(this.nonce)}">` + : '<script>') + let codeUnits = scriptOpening.length + DYNAMIC_CLOSE_SOURCE.length + let batchLength = 0 + for ( + let index = this.queuedSourceHead; + index < this.queuedSources.length; + index++ + ) { + const part = this.queuedSources[index]! + const nextCodeUnits = codeUnits + SOURCE_SEPARATOR.length + part.length + if (batchLength > 0 && nextCodeUnits > MAX_DYNAMIC_RECORD_CODE_UNITS) { + break + } + codeUnits = nextCodeUnits + batchLength++ + if (codeUnits > MAX_DYNAMIC_RECORD_CODE_UNITS) { + // A complete JavaScript source is not safely splittable across tags. + break + } + } + const batch = this.takeQueuedBatch(batchLength) + if (codeUnits <= MAX_DIRECT_CODE_UNITS) { + const joined = + batch.length === 1 ? batch[0]! : batch.join(SOURCE_SEPARATOR) + const bytes = encoder.encode( + scriptOpening + joined + SOURCE_SEPARATOR + DYNAMIC_CLOSE_SOURCE, + ) + this.release(batch) + return bytes + } + this.active = batch + this.segmentIndex = 0 + this.closingSegmentIndex = (batch.length << 1) + 1 + this.source = scriptOpening + this.sourceOffset = 0 + this.outputCapacity = Math.max( + MIN_OUTPUT_BYTES, + Math.min(MAX_HYDRATION_OUTPUT_CHUNK_BYTES, codeUnits), + ) + this.outputState = HydrationScriptOutputState.Active + return this.pullActive() + } + + pullChunk() { + if ( + this.outputState !== HydrationScriptOutputState.Ready && + this.outputState !== HydrationScriptOutputState.Active + ) { + throw new Error('Hydration script output is not ready') + } + try { + return this.outputState === HydrationScriptOutputState.Ready + ? this.pullReady() + : this.pullActive() + } catch (cause) { + this.fail(cause) + throw cause + } + } + + subscribe(onChange: () => void) { + if (this.consumer === 'cleaned') { + return () => {} + } + if (this.listener) { + throw new Error('SSR hydration output already has a subscriber') + } + this.listener = onChange + return () => { + if (this.listener === onChange) { + this.listener = undefined + } + } + } + + pushSerializedSource(data: string, initial: boolean, wrap: boolean) { + let serialized = initial ? ROUTER_PREFIX + data : data + if (wrap) { + serialized = PROMISE_PREFIX + serialized + ')' + } + return this.pushSource(serialized) + } + + finish() { + if (!this.pushSource(GLOBAL_TSR + '.e()')) { + return + } + this.producerDone = true + this.clearTimeoutIfSet() + this.refresh() + } + + takeInitialHydrationScriptTags() { + if ( + this.consumer === 'cleaned' || + this.outputState === HydrationScriptOutputState.Failed || + this.initialTaken + ) { + return undefined + } + // No source can drain before the initial take, so the queue has no + // cleared prefix. Once tags are composed, the same empty array can become + // the dynamic queue without allocating a replacement. + const sources = this.queuedSources as Array<string> + const tags = createInitialTags(sources, this.nonce) + this.initialTaken = true + this.releaseAccounting(sources) + sources.length = 0 + this.queuedSourceHead = 0 + this.refresh() + return tags + } + + /** + * Opt this request out of hydration output entirely (for example a + * `hydrate: false` page). Drops the queued bootstrap sources, marks the + * producer done, and makes the fast pass-through path reservable without + * a rendered `<Scripts>` boundary. Must run before the initial take and + * before serialization produces output. + */ + disableHydration() { + if ( + this.consumer === 'cleaned' || + this.outputState === HydrationScriptOutputState.Failed + ) { + return + } + if (this.initialTaken || this.consumer !== undefined || this.producerDone) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + 'Invariant failed: hydration output is already committed; ' + + 'disableHydration() must run before <Scripts> renders and ' + + 'before serialization starts.', + ) + } + + invariant() + } + this.releaseAccounting(this.queuedSources) + this.clearQueue() + this.initialTaken = true + this.barrierLifted = true + this.producerDone = true + this.refresh() + } + + // The rendered boundary can only exist after the initial take. The merger + // uses this to skip barrier scanning for all earlier renderer bytes. + isInitialTaken() { + return this.initialTaken + } + + // Application EOF without a rendered <Scripts> boundary. The initial + // sources become late records after the document so the response still + // completes instead of failing after its HTML was already delivered. + skipInitialTake() { + if (this.consumer !== 'cleaned' && !this.initialTaken) { + this.initialTaken = true + this.refresh() + } + } + + claimOutput(): HydrationScriptOutput { + if (this.consumer === 'cleaned') { + throw new Error('SSR hydration script output is already cleaned up') + } + if (this.consumer !== undefined) { + throw new Error('SSR hydration script output already has a consumer') + } + this.consumer = this + this.refresh(false) + return this + } + + reserveFastPath(output?: HydrationScriptOutput) { + const ownsConsumer = this.consumer === output + if ( + this.outputState === HydrationScriptOutputState.Failed || + !this.producerDone || + !this.initialTaken || + !this.queueIsEmpty() || + this.active || + !ownsConsumer + ) { + return false + } + this.consumer = 'fast-path' + return true + } + + // Arms the serialization deadline once the renderer finished. The + // lifecycle signal stays separate from this merge-transport concern. + startSerializationTimeout(timeoutMs: number) { + if ( + this.consumer === 'cleaned' || + this.outputState === HydrationScriptOutputState.Failed || + this.producerDone || + this.timeout !== undefined + ) { + return + } + this.timeout = setTimeout(() => { + this.timeout = undefined + if ( + this.consumer !== 'cleaned' && + this.outputState !== HydrationScriptOutputState.Failed && + !this.producerDone + ) { + console.error('Serialization timeout after app render finished') + this.fail(new Error('Serialization timeout after app render finished')) + } + }, timeoutMs) + } + + cleanup() { + if (this.consumer === 'cleaned') { + return + } + this.consumer = 'cleaned' + this.clearTimeoutIfSet() + this.dropBufferedOutput() + this.listener = undefined + this.outputError = undefined + this.producerDone = true + this.outputState = HydrationScriptOutputState.Done + } +} + +/** Create the hydration-script owner for one server request. */ +export function createHydrationScripts( + nonce: string | undefined, + initialSources?: ReadonlyArray<string>, +): HydrationScripts { + return new HydrationScriptsOwner(nonce, initialSources) +} diff --git a/packages/router-core/src/ssr/json.ts b/packages/router-core/src/ssr/json.ts index 051a153f73..90226f9c8c 100644 --- a/packages/router-core/src/ssr/json.ts +++ b/packages/router-core/src/ssr/json.ts @@ -1,18 +1,16 @@ -import { mergeHeaders } from './headers' - +/** + * @deprecated Use [`Response.json`](https://developer.mozilla.org/en-US/docs/Web/API/Response/json_static) from the standard Web API directly. + */ export interface JsonResponse<TData> extends Response { json: () => Promise<TData> } +/** + * @deprecated Use [`Response.json`](https://developer.mozilla.org/en-US/docs/Web/API/Response/json_static) from the standard Web API directly. + */ export function json<TData>( payload: TData, init?: ResponseInit, ): JsonResponse<TData> { - return new Response(JSON.stringify(payload), { - ...init, - headers: mergeHeaders( - { 'content-type': 'application/json' }, - init?.headers, - ), - }) + return Response.json(payload, init) } diff --git a/packages/router-core/src/ssr/renderSsrHtmlResponse.ts b/packages/router-core/src/ssr/renderSsrHtmlResponse.ts new file mode 100644 index 0000000000..32f7919b1d --- /dev/null +++ b/packages/router-core/src/ssr/renderSsrHtmlResponse.ts @@ -0,0 +1,29 @@ +import { getSsrStatus } from './handlerCallback' +import { transformHtmlStringWithRouter } from './transformStreamWithRouter' +import type { AnyRouter } from '../router' + +export async function renderSsrHtmlResponse({ + router, + responseHeaders, + render, +}: { + router: AnyRouter + responseHeaders: Headers + render: () => string | Promise<string> +}) { + try { + const html = await transformHtmlStringWithRouter(router, await render()) + return new Response(html, { + status: getSsrStatus(router), + headers: responseHeaders, + }) + } catch (error) { + console.error('Render to string error:', error) + return new Response('Internal Server Error', { + status: 500, + headers: responseHeaders, + }) + } finally { + router.serverSsr?.cleanup() + } +} diff --git a/packages/router-core/src/ssr/serializer/RawStream.ts b/packages/router-core/src/ssr/serializer/RawStream.ts new file mode 100644 index 0000000000..26827d6e96 --- /dev/null +++ b/packages/router-core/src/ssr/serializer/RawStream.ts @@ -0,0 +1,58 @@ +import type { PluginInfo, SerovalNode } from 'seroval' + +export type RawStreamHint = 'binary' | 'text' + +export interface RawStreamOptions { + /** + * Encoding hint for JSON and SSR serialization. + * - 'binary' (default): Always use base64 encoding + * - 'text': Try UTF-8 first, fallback to base64 for invalid UTF-8 chunks + */ + hint?: RawStreamHint +} + +/** + * Marker class for ReadableStream<Uint8Array> that should be serialized + * with base64/text encoding (JSON and SSR) or binary framing + * (server-function responses). + * + * Wrap your binary streams with this to get efficient serialization: + * ```ts + * // For binary data (files, images, etc.) + * return { data: new RawStream(file.stream()) } + * + * // For text-heavy data (RSC payloads, etc.) + * return { data: new RawStream(rscStream, { hint: 'text' }) } + * ``` + * + * RawStreams returned from one server function share one ordered response. + * Arbitrary or sequential consumption can require potentially unbounded client + * buffering for unread data. Cancelling one RawStream discards it locally; + * abort the whole server-function call to cancel the response and server work. + * Consume streams concurrently, cancel unused streams promptly, or use separate + * calls when independent backpressure is required. + */ +export class RawStream { + public readonly hint: RawStreamHint + + constructor( + public readonly stream: ReadableStream<Uint8Array>, + options?: RawStreamOptions, + ) { + this.hint = options?.hint ?? 'binary' + } +} + +export type OnRawStreamCallback = ( + streamId: number, + stream: ReadableStream<Uint8Array>, +) => void + +export interface RawStreamJSONNode extends PluginInfo { + text: SerovalNode + stream: SerovalNode +} + +export interface RawStreamRPCNode extends PluginInfo { + streamId: SerovalNode +} diff --git a/packages/router-core/src/ssr/serializer/RawStreamJSONPlugin.ts b/packages/router-core/src/ssr/serializer/RawStreamJSONPlugin.ts new file mode 100644 index 0000000000..cafe363bab --- /dev/null +++ b/packages/router-core/src/ssr/serializer/RawStreamJSONPlugin.ts @@ -0,0 +1,64 @@ +import { createPlugin } from 'seroval' +import { RawStream } from './RawStream' +import { + decodeText, + encodeText, + fromBase64, + fromEncodedStream, + pumpEncodedStream, + toBase64, +} from './rawStreamCodec' +import type { createStream } from 'seroval' +import type { RawStreamJSONNode } from './RawStream' + +/** + * Serializes a RawStream into JSON requests and static-cache responses. + * The optional signal stops the source pump when the request is aborted. + */ +/* @__NO_SIDE_EFFECTS__ */ +export function createRawStreamJSONPlugin(signal?: AbortSignal) { + return /* @__PURE__ */ createPlugin<RawStream, RawStreamJSONNode>({ + tag: 'tss/RawStream', + test: (value) => value instanceof RawStream, + parse: { + async: async (value, ctx) => { + // Parse the hint before touching the source so a failed parse never + // locks the caller's stream. + const text = await ctx.parse(value.hint === 'text') + const [stream] = pumpEncodedStream( + value.stream, + value.hint === 'text' ? encodeText : toBase64, + signal, + ) + return { text, stream: await ctx.parse(stream) } + }, + }, + serialize: undefined as never, + deserialize: undefined as never, + }) +} + +export const RawStreamJSONPlugin = /* @__PURE__ */ createRawStreamJSONPlugin() + +/** + * Deserializes the JSON shape above back into a `ReadableStream<Uint8Array>`. + * `test` never matches, so this plugin is inert during serialization and can + * share a plugin list with `RawStreamJSONPlugin`. + */ +export const RawStreamJSONDeserializePlugin = /* @__PURE__ */ createPlugin< + ReadableStream<Uint8Array>, + RawStreamJSONNode +>({ + tag: 'tss/RawStream', + test: () => false, + parse: {}, + serialize: undefined as never, + deserialize(node, ctx) { + return fromEncodedStream( + ctx.deserialize<ReturnType<typeof createStream<string | undefined>>>( + node.stream, + ), + ctx.deserialize<boolean>(node.text) ? decodeText : fromBase64, + ) + }, +}) diff --git a/packages/router-core/src/ssr/serializer/RawStreamRPCPlugin.ts b/packages/router-core/src/ssr/serializer/RawStreamRPCPlugin.ts new file mode 100644 index 0000000000..7080cae17c --- /dev/null +++ b/packages/router-core/src/ssr/serializer/RawStreamRPCPlugin.ts @@ -0,0 +1,47 @@ +import { createPlugin } from 'seroval' +import { RawStream } from './RawStream' +import type { OnRawStreamCallback, RawStreamRPCNode } from './RawStream' + +/** + * Server-side RawStream plugin for multiplexed server-function responses. + * The `hint` is ignored: framed responses always carry raw bytes. + */ +/* @__NO_SIDE_EFFECTS__ */ +export function createRawStreamRPCPlugin(onRawStream: OnRawStreamCallback) { + let nextStreamId = 1 + + return /* @__PURE__ */ createPlugin<RawStream, RawStreamRPCNode>({ + tag: 'tss/RawStream', + test(value: unknown) { + return value instanceof RawStream + }, + parse: { + stream(value, ctx) { + const streamId = nextStreamId++ + onRawStream(streamId, value.stream) + return { streamId: ctx.parse(streamId) } + }, + }, + serialize: undefined as never, + deserialize: undefined as never, + }) +} + +/** Client-side RawStream plugin for multiplexed server-function responses. */ +/* @__NO_SIDE_EFFECTS__ */ +export function createRawStreamDeserializePlugin( + getStream: (id: number) => ReadableStream<Uint8Array>, +) { + return /* @__PURE__ */ createPlugin< + ReadableStream<Uint8Array>, + RawStreamRPCNode + >({ + tag: 'tss/RawStream', + test: () => false, + parse: {}, + serialize: undefined as never, + deserialize(node, ctx) { + return getStream(ctx.deserialize<number>(node.streamId)) + }, + }) +} diff --git a/packages/router-core/src/ssr/serializer/RawStreamSSRPlugin.ts b/packages/router-core/src/ssr/serializer/RawStreamSSRPlugin.ts new file mode 100644 index 0000000000..0f0a641a54 --- /dev/null +++ b/packages/router-core/src/ssr/serializer/RawStreamSSRPlugin.ts @@ -0,0 +1,97 @@ +import { createPlugin } from 'seroval' +import { RawStream } from './RawStream' +import { encodeText, pumpEncodedStream, toBase64 } from './rawStreamCodec' +import type { PluginInfo, SerovalNode } from 'seroval' + +// This module is server-only. Node's Buffer encodes base64 ~25x faster than +// the web fallback; the view avoids copying the chunk first. +const nodeBuffer: typeof Buffer | undefined = (globalThis as any).Buffer +const toBase64Fast = nodeBuffer + ? (bytes: Uint8Array) => + nodeBuffer + .from(bytes.buffer, bytes.byteOffset, bytes.byteLength) + .toString('base64') + : toBase64 + +const BINARY_FACTORY = () => {} +const TEXT_FACTORY = () => {} +type RawStreamFactory = typeof BINARY_FACTORY + +// These factories are injected into HTML and must be self-contained. Clearing +// both captured values on terminal events releases Seroval's encoded buffer. +const FACTORY_BINARY = `((s,u=1)=>new ReadableStream({start(c,f){f=s.on({next(b){const d=atob(b),a=new Uint8Array(d.length);for(let i=0;i<d.length;i++)a[i]=d.charCodeAt(i);c.enqueue(a)},throw(e){s=u=0;c.error(e)},return(){s=u=0;c.close()}});u=u&&f},cancel(){u&&u()}}))` + +const FACTORY_TEXT = `((s,u=1,e=new TextEncoder)=>new ReadableStream({start(c,f){f=s.on({next(v){const x=v.slice(1);if(v[0]==='t')c.enqueue(e.encode(x));else{const d=atob(x),a=new Uint8Array(d.length);for(let i=0;i<d.length;i++)a[i]=d.charCodeAt(i);c.enqueue(a)}},throw(x){s=u=0;c.error(x)},return(){s=u=0;c.close()}});u=u&&f},cancel(){u&&u()}}))` + +function makeFactoryPlugin( + tag: string, + sentinel: RawStreamFactory, + source: string, +) { + return createPlugin<RawStreamFactory, PluginInfo>({ + tag, + test(value) { + return value === sentinel + }, + parse: { + stream() { + return {} + }, + }, + serialize() { + return source + }, + deserialize: undefined as never, + }) +} + +const RawStreamFactoryBinaryPlugin = /* @__PURE__ */ makeFactoryPlugin( + 'tss/RawStreamFactory', + BINARY_FACTORY, + FACTORY_BINARY, +) + +const RawStreamFactoryTextPlugin = /* @__PURE__ */ makeFactoryPlugin( + 'tss/RawStreamFactoryText', + TEXT_FACTORY, + FACTORY_TEXT, +) + +interface RawStreamSSRNode extends PluginInfo { + factory: SerovalNode + stream: SerovalNode +} + +/** SSR-only RawStream plugin for streaming JavaScript into HTML. */ +export const RawStreamSSRPlugin = /* @__PURE__ */ createPlugin< + RawStream, + RawStreamSSRNode +>({ + tag: 'tss/RawStream', + extends: [RawStreamFactoryBinaryPlugin, RawStreamFactoryTextPlugin], + test(value: unknown) { + return value instanceof RawStream + }, + parse: { + stream(value, ctx) { + const text = value.hint === 'text' + const factory = ctx.parse(text ? TEXT_FACTORY : BINARY_FACTORY) + const [stream, stop] = pumpEncodedStream( + value.stream, + text ? encodeText : toBase64Fast, + ) + ctx.addCleanup(stop) + return { factory, stream: ctx.parse(stream) } + }, + }, + serialize(node, ctx) { + return ( + '(' + + ctx.serialize(node.factory) + + ')(' + + ctx.serialize(node.stream) + + ')' + ) + }, + deserialize: undefined as never, +}) diff --git a/packages/router-core/src/ssr/serializer/ShallowErrorPlugin.ts b/packages/router-core/src/ssr/serializer/ShallowErrorPlugin.ts index f3cc6290c8..e6b12983a5 100644 --- a/packages/router-core/src/ssr/serializer/ShallowErrorPlugin.ts +++ b/packages/router-core/src/ssr/serializer/ShallowErrorPlugin.ts @@ -1,7 +1,7 @@ import { createPlugin } from 'seroval' -import type { SerovalNode } from 'seroval' +import type { PluginInfo, SerovalNode } from 'seroval' -export interface ErrorNode { +export interface ErrorNode extends PluginInfo { message: SerovalNode } diff --git a/packages/router-core/src/ssr/serializer/makeSerovalPlugin.ts b/packages/router-core/src/ssr/serializer/makeSerovalPlugin.ts new file mode 100644 index 0000000000..6d15a9773b --- /dev/null +++ b/packages/router-core/src/ssr/serializer/makeSerovalPlugin.ts @@ -0,0 +1,31 @@ +import { createPlugin } from 'seroval' +import type { AdapterNode, AnySerializationAdapter } from './transformer' +import type { Plugin } from 'seroval' + +/** Create a Seroval plugin for client/server symmetric (de)serialization. */ +/* @__NO_SIDE_EFFECTS__ */ +export function makeSerovalPlugin( + serializationAdapter: AnySerializationAdapter, +): Plugin<any, AdapterNode> { + return /* @__PURE__ */ createPlugin<any, AdapterNode>({ + tag: '$TSR/t/' + serializationAdapter.key, + test: serializationAdapter.test, + parse: { + sync(value, ctx) { + return { v: ctx.parse(serializationAdapter.toSerializable(value)) } + }, + async async(value, ctx) { + return { + v: await ctx.parse(serializationAdapter.toSerializable(value)), + } + }, + stream(value, ctx) { + return { v: ctx.parse(serializationAdapter.toSerializable(value)) } + }, + }, + serialize: undefined as never, + deserialize(node, ctx) { + return serializationAdapter.fromSerializable(ctx.deserialize(node.v)) + }, + }) +} diff --git a/packages/router-core/src/ssr/serializer/makeSsrSerovalPlugin.ts b/packages/router-core/src/ssr/serializer/makeSsrSerovalPlugin.ts new file mode 100644 index 0000000000..794561cb00 --- /dev/null +++ b/packages/router-core/src/ssr/serializer/makeSsrSerovalPlugin.ts @@ -0,0 +1,40 @@ +import { createPlugin } from 'seroval' +import { GLOBAL_TSR } from '../constants' +import type { AdapterNode, AnySerializationAdapter } from './transformer' +import type { Plugin } from 'seroval' + +/** + * Create a Seroval plugin for server-side serialization only. `tracker.didRun` + * becomes true once the plugin serialized a value. + */ +/* @__NO_SIDE_EFFECTS__ */ +export function makeSsrSerovalPlugin( + serializationAdapter: AnySerializationAdapter, + tracker?: { didRun: boolean }, +): Plugin<any, AdapterNode> { + return /* @__PURE__ */ createPlugin<any, AdapterNode>({ + tag: '$TSR/t/' + serializationAdapter.key, + test: serializationAdapter.test, + parse: { + stream(value, ctx) { + return { + v: ctx.parse(serializationAdapter.toSerializable(value)), + } + }, + }, + serialize(node, ctx) { + if (tracker) { + tracker.didRun = true + } + return ( + GLOBAL_TSR + + '.t.get("' + + serializationAdapter.key + + '")(' + + ctx.serialize(node.v) + + ')' + ) + }, + deserialize: undefined as never, + }) +} diff --git a/packages/router-core/src/ssr/serializer/rawStreamCodec.ts b/packages/router-core/src/ssr/serializer/rawStreamCodec.ts new file mode 100644 index 0000000000..e88958f95d --- /dev/null +++ b/packages/router-core/src/ssr/serializer/rawStreamCodec.ts @@ -0,0 +1,163 @@ +import { createStream } from 'seroval' + +// Web-only primitives shared by the JSON and SSR RawStream plugins. This +// module is part of the client bundle: it must not reference `Buffer`, and +// the encode and decode halves must stay independently tree-shakeable. + +export function toBase64(bytes: Uint8Array) { + const chunks: Array<string> = [] + for (let i = 0; i < bytes.length; i += 0x8000) { + chunks.push( + String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000) as any), + ) + } + return btoa(chunks.join('')) +} + +export function fromBase64(value: string) { + const binary = atob(value) + const bytes = new Uint8Array(binary.length) + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i) + } + return bytes +} + +const textDecoder = /* @__PURE__ */ new TextDecoder('utf-8', { + fatal: true, + ignoreBOM: true, +}) + +/** `'t' + utf8` for a valid UTF-8 chunk, otherwise `'b' + base64`. */ +export function encodeText(value: Uint8Array) { + try { + return 't' + textDecoder.decode(value) + } catch { + return 'b' + toBase64(value) + } +} + +const textEncoder = /* @__PURE__ */ new TextEncoder() + +export function decodeText(value: string) { + const data = value.slice(1) + return value[0] === 't' ? textEncoder.encode(data) : fromBase64(data) +} + +/** + * Pump a byte stream into a Seroval stream, one encoded chunk per read. + * Returns the Seroval stream and a `stop` function that cancels the reader + * without signalling the Seroval stream; the abort signal and read failures + * stop the pump and throw through the Seroval stream. + */ +export function pumpEncodedStream( + readable: ReadableStream<Uint8Array>, + encode: (value: Uint8Array) => string, + signal?: AbortSignal, +) { + signal?.throwIfAborted() + + const stream = createStream<string | undefined>() + const reader = readable.getReader() + let active = true + + const release = () => { + active = false + signal?.removeEventListener('abort', abort) + reader.releaseLock() + } + const stop = (reason?: unknown) => { + if (!active) { + return false + } + void reader.cancel(reason).catch(() => {}) + release() + return true + } + const abort = () => { + if (stop(signal!.reason)) { + stream.throw(signal!.reason) + } + } + + signal?.addEventListener('abort', abort) + ;(async () => { + try { + while (active) { + const { done, value } = await reader.read() + if (!active) { + return + } + if (done) { + release() + stream.return(undefined) + return + } + stream.next(encode(value)) + } + } catch (error) { + if (stop(error)) { + stream.throw(error) + } + } + })() + + return [stream, stop] as const +} + +/** Rebuild a byte stream from encoded Seroval stream chunks. */ +export function fromEncodedStream( + source: ReturnType<typeof createStream<string | undefined>>, + decode: (value: string) => Uint8Array, +) { + // Dropping the disposer after a terminal event lets Seroval's buffer be + // collected while application code still holds the finished stream. + let unsubscribe: (() => void) | undefined + let done = false + + return new ReadableStream<Uint8Array>({ + start(controller) { + const dispose = source.on({ + next(value) { + if (done) { + return + } + try { + controller.enqueue(decode(value!)) + } catch (error) { + // A malformed chunk fails this stream and abandons the source. + done = true + const stop = unsubscribe + unsubscribe = undefined + stop?.() + controller.error(error) + } + }, + throw(error) { + if (!done) { + done = true + unsubscribe = undefined + controller.error(error) + } + }, + return() { + if (!done) { + done = true + unsubscribe = undefined + controller.close() + } + }, + }) + if (done) { + dispose() + } else { + unsubscribe = dispose + } + }, + cancel() { + const dispose = unsubscribe + unsubscribe = undefined + dispose?.() + }, + }) +} diff --git a/packages/router-core/src/ssr/serializer/seroval-plugins.ssr.ts b/packages/router-core/src/ssr/serializer/seroval-plugins.ssr.ts new file mode 100644 index 0000000000..3b2913d27b --- /dev/null +++ b/packages/router-core/src/ssr/serializer/seroval-plugins.ssr.ts @@ -0,0 +1,11 @@ +import { ReadableStreamPlugin } from 'seroval-plugins/web' +import { ShallowErrorPlugin } from './ShallowErrorPlugin' +import { RawStreamSSRPlugin } from './RawStreamSSRPlugin' +import type { Plugin } from 'seroval' + +/** Server-only plugins for streaming hydration data into HTML. */ +export const ssrSerovalPlugins: Array<Plugin<any, any>> = [ + ShallowErrorPlugin, + RawStreamSSRPlugin, + ReadableStreamPlugin, +] diff --git a/packages/router-core/src/ssr/serializer/seroval-plugins.ts b/packages/router-core/src/ssr/serializer/seroval-plugins.ts index 669df5eb23..4595f5c0ad 100644 --- a/packages/router-core/src/ssr/serializer/seroval-plugins.ts +++ b/packages/router-core/src/ssr/serializer/seroval-plugins.ts @@ -1,9 +1,37 @@ import { ReadableStreamPlugin } from 'seroval-plugins/web' import { ShallowErrorPlugin } from './ShallowErrorPlugin' +import { + RawStreamJSONDeserializePlugin, + RawStreamJSONPlugin, + createRawStreamJSONPlugin, +} from './RawStreamJSONPlugin' import type { Plugin } from 'seroval' -export const defaultSerovalPlugins = [ - ShallowErrorPlugin as Plugin<Error, any>, - // ReadableStreamNode is not exported by seroval - ReadableStreamPlugin as Plugin<ReadableStream, any>, +/** + * Plugins for JSON transport from a client: serializes RawStream arguments + * and reads plain JSON responses, which never carry RawStream nodes. + */ +/* @__NO_SIDE_EFFECTS__ */ +export function createDefaultSerovalPlugins( + signal?: AbortSignal, +): Array<Plugin<any, any>> { + return [ + ShallowErrorPlugin, + signal ? createRawStreamJSONPlugin(signal) : RawStreamJSONPlugin, + ReadableStreamPlugin, + ] +} + +export const defaultSerovalPlugins = + /* @__PURE__ */ createDefaultSerovalPlugins() + +/** + * `defaultSerovalPlugins` plus RawStream deserialization, for JSON that may + * carry RawStream nodes: server-function request bodies and cached static + * responses. Seroval deserializes by first tag match, so the deserialize half + * precedes the serialize half; it never matches during serialization. + */ +export const defaultSerovalDeserializerPlugins: Array<Plugin<any, any>> = [ + RawStreamJSONDeserializePlugin, + ...defaultSerovalPlugins, ] diff --git a/packages/router-core/src/ssr/serializer/transformer.ts b/packages/router-core/src/ssr/serializer/transformer.ts index df86f965ed..6fe99f2c43 100644 --- a/packages/router-core/src/ssr/serializer/transformer.ts +++ b/packages/router-core/src/ssr/serializer/transformer.ts @@ -1,6 +1,4 @@ -import { createPlugin } from 'seroval' -import { GLOBAL_TSR } from '../constants' -import type { Plugin, SerovalNode } from 'seroval' +import type { PluginInfo, SerovalNode } from 'seroval' import type { RegisteredConfigType, RegisteredSsr, @@ -8,11 +6,13 @@ import type { } from '../../router' import type { LooseReturnType } from '../../utils' import type { AnyRoute, ResolveAllSSR } from '../../route' +import type { RawStream } from './RawStream' declare const TSR_SERIALIZABLE: unique symbol export type TSR_SERIALIZABLE = typeof TSR_SERIALIZABLE export type TsrSerializable = { [TSR_SERIALIZABLE]: true } + export interface DefaultSerializable { number: number string: string @@ -21,7 +21,10 @@ export interface DefaultSerializable { undefined: undefined bigint: bigint Date: Date + Uint8Array: Uint8Array + RawStream: RawStream TsrSerializable: TsrSerializable + void: void } export interface SerializableExtensions extends DefaultSerializable {} @@ -45,6 +48,22 @@ export function createSerializationAdapter< >( opts: CreateSerializationAdapterOptions<TInput, TOutput, TExtendsAdapters>, ): SerializationAdapter<TInput, TOutput, TExtendsAdapters> { + if (process.env.NODE_ENV !== 'production') { + // Seroval escapes most of these characters before plugin lookup. NUL and + // lone surrogates are transport-unstable. Reject every surrogate code unit + // to keep adapter keys and this development-only check simple. + if ( + !opts.key || + /[\0"\\<\b\t\f\r\n\u2028\u2029\uD800-\uDFFF]/.test(opts.key) + ) { + throw new Error( + `createSerializationAdapter: key ${JSON.stringify(opts.key)} is ` + + 'invalid. Serialization adapter keys must be non-empty and not ' + + 'contain NUL, ", \\, <, backspace, tab, form feed, line ' + + 'terminators, or UTF-16 surrogate code units.', + ) + } + } return opts as unknown as SerializationAdapter< TInput, TOutput, @@ -57,6 +76,13 @@ export interface CreateSerializationAdapterOptions< TOutput, TExtendsAdapters extends ReadonlyArray<AnySerializationAdapter> | never, > { + /** + * A non-empty Seroval plugin identifier. + * + * Must not contain NUL, `"`, `\\`, `<`, backspace, tab, form feed, line + * terminators, or UTF-16 surrogate code units. Key validation runs only in + * development. + */ key: string extends?: TExtendsAdapters test: (value: unknown) => value is TInput @@ -69,13 +95,14 @@ export interface CreateSerializationAdapterOptions< fromSerializable: (value: TOutput) => TInput } -export type ValidateSerializable<T, TSerializable> = - T extends ReadonlyArray<unknown> - ? ResolveArrayShape<T, TSerializable, 'input'> - : T extends TSerializable - ? T - : T extends (...args: Array<any>) => any - ? 'Function is not serializable' +export type ValidateSerializable<T, TSerializable> = T extends TSerializable + ? T + : T extends (...args: Array<any>) => any + ? SerializationError<'Function may not be serializable'> + : T extends RegisteredReadableStream + ? SerializationError<'JSX is not be serializable'> + : T extends ReadonlyArray<any> + ? ValidateSerializableArray<T, TSerializable> : T extends Promise<any> ? ValidateSerializablePromise<T, TSerializable> : T extends ReadableStream<any> @@ -86,9 +113,9 @@ export type ValidateSerializable<T, TSerializable> = ? ValidateSerializableMap<T, TSerializable> : T extends AsyncGenerator<any, any> ? ValidateSerializableAsyncGenerator<T, TSerializable> - : { - [K in keyof T]: ValidateSerializable<T[K], TSerializable> - } + : T extends object + ? ValidateSerializableMapped<T, TSerializable> + : SerializationError<'Type may not be serializable'> export type ValidateSerializableAsyncGenerator<T, TSerializable> = T extends AsyncGenerator<infer T, infer TReturn, infer TNext> @@ -122,16 +149,26 @@ export type ValidateSerializableMap<T, TSerializable> = > : never -export type RegisteredReadableStream = - unknown extends SerializerExtensions['ReadableStream'] - ? never - : SerializerExtensions['ReadableStream'] +export type ValidateSerializableArray<T, TSerializable> = T extends readonly [ + any, + ...Array<any>, +] + ? ValidateSerializableMapped<T, TSerializable> + : T extends Array<infer U> + ? Array<ValidateSerializable<U, TSerializable>> + : T extends ReadonlyArray<infer U> + ? ReadonlyArray<ValidateSerializable<U, TSerializable>> + : never -export interface DefaultSerializerExtensions { - ReadableStream: unknown +export type ValidateSerializableMapped<T, TSerializable> = { + [K in keyof T]: ValidateSerializable<T[K], TSerializable> } -export interface SerializerExtensions extends DefaultSerializerExtensions {} +const SERIALIZATION_ERROR = Symbol.for('TSR_SERIALIZATION_ERROR') + +export interface SerializationError<in out TMessage extends string> { + [SERIALIZATION_ERROR]: TMessage +} export interface SerializationAdapter< TInput, @@ -158,59 +195,8 @@ export interface SerializationAdapterTypes< export type AnySerializationAdapter = SerializationAdapter<any, any, any> -/** Create a Seroval plugin for server-side serialization only. */ -export function makeSsrSerovalPlugin( - serializationAdapter: AnySerializationAdapter, - options: { didRun: boolean }, -): Plugin<any, SerovalNode> { - return createPlugin<any, SerovalNode>({ - tag: '$TSR/t/' + serializationAdapter.key, - test: serializationAdapter.test, - parse: { - stream(value, ctx) { - return ctx.parse(serializationAdapter.toSerializable(value)) - }, - }, - serialize(node, ctx) { - options.didRun = true - return ( - GLOBAL_TSR + - '.t.get("' + - serializationAdapter.key + - '")(' + - ctx.serialize(node) + - ')' - ) - }, - // we never deserialize on the server during SSR - deserialize: undefined as never, - }) -} - -/** Create a Seroval plugin for client/server symmetric (de)serialization. */ -export function makeSerovalPlugin( - serializationAdapter: AnySerializationAdapter, -): Plugin<any, SerovalNode> { - return createPlugin<any, SerovalNode>({ - tag: '$TSR/t/' + serializationAdapter.key, - test: serializationAdapter.test, - parse: { - sync(value, ctx) { - return ctx.parse(serializationAdapter.toSerializable(value)) - }, - async async(value, ctx) { - return await ctx.parse(serializationAdapter.toSerializable(value)) - }, - stream(value, ctx) { - return ctx.parse(serializationAdapter.toSerializable(value)) - }, - }, - // we don't generate JS code outside of SSR (for now) - serialize: undefined as never, - deserialize(node, ctx) { - return serializationAdapter.fromSerializable(ctx.deserialize(node)) - }, - }) +export interface AdapterNode extends PluginInfo { + v: SerovalNode } export type ValidateSerializableInput<TRegister, T> = ValidateSerializable< @@ -231,20 +217,6 @@ export type RegisteredSerializationAdapters<TRegister> = RegisteredConfigType< 'serializationAdapters' > -export type ValidateSerializableInputResult<TRegister, T> = - ValidateSerializableResult<T, RegisteredSerializableInput<TRegister>> - -export type ValidateSerializableResult<T, TSerializable> = - T extends ReadonlyArray<unknown> - ? ResolveArrayShape<T, TSerializable, 'result'> - : T extends TSerializable - ? T - : unknown extends SerializerExtensions['ReadableStream'] - ? { [K in keyof T]: ValidateSerializableResult<T[K], TSerializable> } - : T extends SerializerExtensions['ReadableStream'] - ? ReadableStream - : { [K in keyof T]: ValidateSerializableResult<T[K], TSerializable> } - export type RegisteredSSROption<TRegister> = unknown extends RegisteredConfigType<TRegister, 'defaultSsr'> ? SSROption @@ -279,31 +251,13 @@ export type ValidateSerializableLifecycleResultSSR< ? any : ValidateSerializableInput<TRegister, LooseReturnType<TFn>> -type ResolveArrayShape< - T extends ReadonlyArray<unknown>, - TSerializable, - TMode extends 'input' | 'result', -> = number extends T['length'] - ? T extends Array<infer U> - ? Array<ArrayModeResult<TMode, U, TSerializable>> - : ReadonlyArray<ArrayModeResult<TMode, T[number], TSerializable>> - : ResolveTupleShape<T, TSerializable, TMode> +export type RegisteredReadableStream = + unknown extends SerializerExtensions['ReadableStream'] + ? never + : SerializerExtensions['ReadableStream'] -type ResolveTupleShape< - T extends ReadonlyArray<unknown>, - TSerializable, - TMode extends 'input' | 'result', -> = T extends readonly [infer THead, ...infer TTail] - ? readonly [ - ArrayModeResult<TMode, THead, TSerializable>, - ...ResolveTupleShape<Readonly<TTail>, TSerializable, TMode>, - ] - : T +export interface DefaultSerializerExtensions { + ReadableStream: unknown +} -type ArrayModeResult< - TMode extends 'input' | 'result', - TValue, - TSerializable, -> = TMode extends 'input' - ? ValidateSerializable<TValue, TSerializable> - : ValidateSerializableResult<TValue, TSerializable> +export interface SerializerExtensions extends DefaultSerializerExtensions {} diff --git a/packages/router-core/src/ssr/server.ts b/packages/router-core/src/ssr/server.ts index de39fb8136..84c34976c9 100644 --- a/packages/router-core/src/ssr/server.ts +++ b/packages/router-core/src/ssr/server.ts @@ -1,10 +1,33 @@ -export { createRequestHandler } from './createRequestHandler' +export { createRequestHandler, waitForRequest } from './createRequestHandler' export type { RequestHandler } from './createRequestHandler' -export { defineHandlerCallback } from './handlerCallback' -export type { HandlerCallback } from './handlerCallback' +export { + bindSsrResponseToRequest, + createSsrStreamResponse, + defineHandlerCallback, + disposeSsrResponse, + getSsrStatus, + isSsrResponse, + normalizeSsrResponse, + replaceSsrResponse, + stripSsrResponseBody, +} from './handlerCallback' +export type { + HandlerCallback, + HandlerCallbackResult, + SsrResponse, +} from './handlerCallback' export { transformPipeableStreamWithRouter, - transformStreamWithRouter, + transformHtmlStringWithRouter, transformReadableStreamWithRouter, } from './transformStreamWithRouter' -export { attachRouterServerSsrUtils, getOrigin } from './ssr-server' +export type { TransformStreamWithRouterOptions } from './transformStreamWithRouter' +export { renderSsrHtmlResponse } from './renderSsrHtmlResponse' +export { + attachRouterServerSsrUtils, + getNormalizedURL, + getOrigin, +} from './ssr-server' +export { defaultSerovalDeserializerPlugins } from './serializer/seroval-plugins' +export { createRawStreamRPCPlugin } from './serializer/RawStreamRPCPlugin' +export { makeSsrSerovalPlugin } from './serializer/makeSsrSerovalPlugin' diff --git a/packages/router-core/src/ssr/ssr-client.ts b/packages/router-core/src/ssr/ssr-client.ts index a58e1041d5..6b0921c8db 100644 --- a/packages/router-core/src/ssr/ssr-client.ts +++ b/packages/router-core/src/ssr/ssr-client.ts @@ -1,278 +1 @@ -import invariant from 'tiny-invariant' -import { batch } from '@tanstack/store' -import { isNotFound } from '../not-found' -import { createControlledPromise } from '../utils' -import type { GLOBAL_SEROVAL, GLOBAL_TSR } from './constants' -import type { DehydratedMatch, TsrSsrGlobal } from './types' -import type { AnyRouteMatch } from '../Matches' -import type { AnyRouter } from '../router' -import type { RouteContextOptions } from '../route' -import type { AnySerializationAdapter } from './serializer/transformer' - -declare global { - interface Window { - [GLOBAL_TSR]?: TsrSsrGlobal - [GLOBAL_SEROVAL]?: any - } -} - -function hydrateMatch( - match: AnyRouteMatch, - deyhydratedMatch: DehydratedMatch, -): void { - match.id = deyhydratedMatch.i - match.__beforeLoadContext = deyhydratedMatch.b - match.loaderData = deyhydratedMatch.l - match.status = deyhydratedMatch.s - match.ssr = deyhydratedMatch.ssr - match.updatedAt = deyhydratedMatch.u - match.error = deyhydratedMatch.e -} - -export async function hydrate(router: AnyRouter): Promise<any> { - invariant( - window.$_TSR, - 'Expected to find bootstrap data on window.$_TSR, but we did not. Please file an issue!', - ) - - const serializationAdapters = router.options.serializationAdapters as - | Array<AnySerializationAdapter> - | undefined - - if (serializationAdapters?.length) { - const fromSerializableMap = new Map() - serializationAdapters.forEach((adapter) => { - fromSerializableMap.set(adapter.key, adapter.fromSerializable) - }) - window.$_TSR.t = fromSerializableMap - window.$_TSR.buffer.forEach((script) => script()) - } - window.$_TSR.initialized = true - - invariant( - window.$_TSR.router, - 'Expected to find a dehydrated data on window.$_TSR.router, but we did not. Please file an issue!', - ) - - const { manifest, dehydratedData, lastMatchId } = window.$_TSR.router - - router.ssr = { - manifest, - } - const meta = document.querySelector('meta[property="csp-nonce"]') as - | HTMLMetaElement - | undefined - const nonce = meta?.content - router.options.ssr = { - nonce, - } - - // Hydrate the router state - const matches = router.matchRoutes(router.state.location) - - // kick off loading the route chunks - const routeChunkPromise = Promise.all( - matches.map((match) => { - const route = router.looseRoutesById[match.routeId]! - return router.loadRouteChunk(route) - }), - ) - - function setMatchForcePending(match: AnyRouteMatch) { - // usually the minPendingPromise is created in the Match component if a pending match is rendered - // however, this might be too late if the match synchronously resolves - const route = router.looseRoutesById[match.routeId]! - const pendingMinMs = - route.options.pendingMinMs ?? router.options.defaultPendingMinMs - if (pendingMinMs) { - const minPendingPromise = createControlledPromise<void>() - match._nonReactive.minPendingPromise = minPendingPromise - match._forcePending = true - - setTimeout(() => { - minPendingPromise.resolve() - // We've handled the minPendingPromise, so we can delete it - router.updateMatch(match.id, (prev) => { - prev._nonReactive.minPendingPromise = undefined - return { - ...prev, - _forcePending: undefined, - } - }) - }, pendingMinMs) - } - } - - function setRouteSsr(match: AnyRouteMatch) { - const route = router.looseRoutesById[match.routeId] - if (route) { - route.options.ssr = match.ssr - } - } - // Right after hydration and before the first render, we need to rehydrate each match - // First step is to reyhdrate loaderData and __beforeLoadContext - let firstNonSsrMatchIndex: number | undefined = undefined - matches.forEach((match) => { - const dehydratedMatch = window.$_TSR!.router!.matches.find( - (d) => d.i === match.id, - ) - if (!dehydratedMatch) { - match._nonReactive.dehydrated = false - match.ssr = false - setRouteSsr(match) - return - } - - hydrateMatch(match, dehydratedMatch) - setRouteSsr(match) - - match._nonReactive.dehydrated = match.ssr !== false - - if (match.ssr === 'data-only' || match.ssr === false) { - if (firstNonSsrMatchIndex === undefined) { - firstNonSsrMatchIndex = match.index - setMatchForcePending(match) - } - } - }) - - router.__store.setState((s) => { - return { - ...s, - matches, - } - }) - - // Allow the user to handle custom hydration data - await router.options.hydrate?.(dehydratedData) - - // now that all necessary data is hydrated: - // 1) fully reconstruct the route context - // 2) execute `head()` and `scripts()` for each match - await Promise.all( - router.state.matches.map(async (match) => { - try { - const route = router.looseRoutesById[match.routeId]! - - const parentMatch = router.state.matches[match.index - 1] - const parentContext = parentMatch?.context ?? router.options.context - - // `context()` was already executed by `matchRoutes`, however route context was not yet fully reconstructed - // so run it again and merge route context - if (route.options.context) { - const contextFnContext: RouteContextOptions<any, any, any, any> = { - deps: match.loaderDeps, - params: match.params, - context: parentContext ?? {}, - location: router.state.location, - navigate: (opts: any) => - router.navigate({ - ...opts, - _fromLocation: router.state.location, - }), - buildLocation: router.buildLocation, - cause: match.cause, - abortController: match.abortController, - preload: false, - matches, - } - match.__routeContext = - route.options.context(contextFnContext) ?? undefined - } - - match.context = { - ...parentContext, - ...match.__routeContext, - ...match.__beforeLoadContext, - } - - const assetContext = { - matches: router.state.matches, - match, - params: match.params, - loaderData: match.loaderData, - } - const headFnContent = await route.options.head?.(assetContext) - - const scripts = await route.options.scripts?.(assetContext) - - match.meta = headFnContent?.meta - match.links = headFnContent?.links - match.headScripts = headFnContent?.scripts - match.styles = headFnContent?.styles - match.scripts = scripts - } catch (err) { - if (isNotFound(err)) { - match.error = { isNotFound: true } - console.error( - `NotFound error during hydration for routeId: ${match.routeId}`, - err, - ) - } else { - match.error = err as any - console.error( - `Error during hydration for route ${match.routeId}:`, - err, - ) - throw err - } - } - }), - ) - - const isSpaMode = matches[matches.length - 1]!.id !== lastMatchId - const hasSsrFalseMatches = matches.some((m) => m.ssr === false) - // all matches have data from the server and we are not in SPA mode so we don't need to kick of router.load() - if (!hasSsrFalseMatches && !isSpaMode) { - matches.forEach((match) => { - // remove the dehydrated flag since we won't run router.load() which would remove it - match._nonReactive.dehydrated = undefined - }) - return routeChunkPromise - } - - // schedule router.load() to run after the next tick so we can store the promise in the match before loading starts - const loadPromise = Promise.resolve() - .then(() => router.load()) - .catch((err) => { - console.error('Error during router hydration:', err) - }) - - // in SPA mode we need to keep the first match below the root route pending until router.load() is finished - // this will prevent that other pending components are rendered but hydration is not blocked - if (isSpaMode) { - const match = matches[1] - invariant( - match, - 'Expected to find a match below the root match in SPA mode.', - ) - setMatchForcePending(match) - - match._displayPending = true - match._nonReactive.displayPendingPromise = loadPromise - - loadPromise.then(() => { - batch(() => { - // ensure router is not in status 'pending' anymore - // this usually happens in Transitioner but if loading synchronously resolves, - // Transitioner won't be rendered while loading so it cannot track the change from loading:true to loading:false - if (router.__store.state.status === 'pending') { - router.__store.setState((s) => ({ - ...s, - status: 'idle', - resolvedLocation: s.location, - })) - } - // hide the pending component once the load is finished - router.updateMatch(match.id, (prev) => { - return { - ...prev, - _displayPending: undefined, - displayPendingPromise: undefined, - } - }) - }) - }) - } - return routeChunkPromise -} +export { hydrate } from '../load-client' diff --git a/packages/router-core/src/ssr/ssr-match-id.ts b/packages/router-core/src/ssr/ssr-match-id.ts new file mode 100644 index 0000000000..1c725374ec --- /dev/null +++ b/packages/router-core/src/ssr/ssr-match-id.ts @@ -0,0 +1,9 @@ +// Inlined match ids must not look like relative URLs to crawlers, and must only +// contain characters that are valid in the HTML input stream. '#' cannot come +// from a decoded pathname or an encoded param, Seroval emits it unescaped, and +// it keeps the HTML one-byte: a single char above U+00FF makes V8 widen the +// whole concatenated HTML string to two bytes per char, which slows SSR. +// The client compares ids in this encoded form, so no decoder is needed. +export function dehydrateSsrMatchId(id: string): string { + return id.replaceAll('/', '#') +} diff --git a/packages/router-core/src/ssr/ssr-server.ts b/packages/router-core/src/ssr/ssr-server.ts index fcaf7bd155..e7c9cc2fa6 100644 --- a/packages/router-core/src/ssr/ssr-server.ts +++ b/packages/router-core/src/ssr/ssr-server.ts @@ -1,35 +1,38 @@ -import { crossSerializeStream, getCrossReferenceHeader } from 'seroval' -import invariant from 'tiny-invariant' -import { createControlledPromise } from '../utils' -import minifiedTsrBootStrapScript from './tsrScript?script-string' -import { GLOBAL_TSR } from './constants' -import { defaultSerovalPlugins } from './serializer/seroval-plugins' -import { makeSsrSerovalPlugin } from './serializer/transformer' -import { TSR_SCRIPT_BARRIER_ID } from './transformStreamWithRouter' +import { crossSerializeStream } from 'seroval' +import { invariant } from '../invariant' +import { + createInlineCssPlaceholderAsset, + createInlineCssStyleAsset, + getStylesheetHref, +} from '../manifest' +import { decodePath } from '../utils' +import { createSieveCache } from '../sieve-cache' +import { rootRouteId } from '../root' +import { _getRenderedMatches } from '../load-client' +import { waitForReason } from '../await-signal' +import { + SSR_SERIALIZATION_SCOPE_ID, + createHydrationScripts, +} from './hydrationScripts' +import { dehydrateSsrMatchId } from './ssr-match-id' +import { ssrSerovalPlugins } from './serializer/seroval-plugins.ssr' +import { makeSsrSerovalPlugin } from './serializer/makeSsrSerovalPlugin' +import type { SieveCache } from '../sieve-cache' import type { DehydratedMatch, DehydratedRouter } from './types' -import type { AnySerializationAdapter } from './serializer/transformer' -import type { AnyRouter } from '../router' +import type { AnyRouter, ServerSsr } from '../router' import type { AnyRouteMatch } from '../Matches' -import type { Manifest, RouterManagedTag } from '../manifest' +import type { + Manifest, + ManifestRoute, + ManifestRouteAssets, + ServerManifest, +} from '../manifest' -declare module '../router' { - interface ServerSsr { - setRenderFinished: () => void - cleanup: () => void - } - interface RouterEvents { - onInjectedHtml: { - type: 'onInjectedHtml' - promise: Promise<string> - } - } -} - -const SCOPE_ID = 'tsr' +type DehydrationPhase = 'idle' | 'started' | 'disabled' export function dehydrateMatch(match: AnyRouteMatch): DehydratedMatch { const dehydratedMatch: DehydratedMatch = { - i: match.id, + i: dehydrateSsrMatchId(match.id), u: match.updatedAt, s: match.status, } @@ -46,237 +49,651 @@ export function dehydrateMatch(match: AnyRouteMatch): DehydratedMatch { dehydratedMatch[shorthand] = match[key] } } + if (match._notFound) { + dehydratedMatch.g = true + } return dehydratedMatch } -const INITIAL_SCRIPTS = [ - getCrossReferenceHeader(SCOPE_ID), - minifiedTsrBootStrapScript, -] - -class ScriptBuffer { - private router: AnyRouter | undefined - private _queue: Array<string> = [...INITIAL_SCRIPTS] - private _scriptBarrierLifted = false - private _cleanedUp = false - - constructor(router: AnyRouter) { - this.router = router +function disposeSerializationSafely(dispose?: () => void) { + try { + dispose?.() + } catch (err) { + console.error('Error disposing SSR serialization:', err) } +} - enqueue(script: string) { - if (this._cleanedUp) return - if (this._scriptBarrierLifted && this._queue.length === 0) { - queueMicrotask(() => { - this.injectBufferedScripts() - }) +function notifyAndClearListeners<T>( + listeners: Array<(arg: T) => void>, + errorMessage: string, + arg: T, +) { + const pending = listeners.slice() + listeners.length = 0 + for (const listener of pending) { + try { + listener(arg) + } catch (error) { + console.error(errorMessage, error) } - this._queue.push(script) + } +} + +const isProd = process.env.NODE_ENV === 'production' + +type FilteredRoutes = Manifest['routes'] + +type PreparedMatchedManifestRoutes = { + routes: FilteredRoutes + hasStrippedRoutes: boolean + inlineCssHrefs?: Array<string> +} + +type ManifestCache = SieveCache<string, PreparedMatchedManifestRoutes> + +const MANIFEST_CACHE_SIZE = 100 +const manifestCaches = new WeakMap<ServerManifest, ManifestCache>() + +function getManifestCache(manifest: ServerManifest): ManifestCache { + const cache = manifestCaches.get(manifest) + if (cache) { + return cache + } + const newCache = createSieveCache<string, PreparedMatchedManifestRoutes>( + MANIFEST_CACHE_SIZE, + ) + manifestCaches.set(manifest, newCache) + return newCache +} + +function getInlineCssForPreparedRoutes( + manifest: ServerManifest, + preparedRoutes: PreparedMatchedManifestRoutes, +) { + const styles = manifest.inlineCss?.styles + const hrefs = preparedRoutes.inlineCssHrefs + if (!styles || !hrefs?.length) { + return undefined } - liftBarrier() { - if (this._scriptBarrierLifted || this._cleanedUp) return - this._scriptBarrierLifted = true - if (this._queue.length > 0) { - queueMicrotask(() => { - this.injectBufferedScripts() - }) + // Joined once per matched route set and request. Retaining the joined copy + // on the module cache entry would permanently duplicate shared CSS across + // up to MANIFEST_CACHE_SIZE route combinations. + let css = '' + for (const href of hrefs) { + css += styles[href]! + } + + return css +} + +function getInlineCssAssetForPreparedRoutes( + manifest: ServerManifest, + preparedRoutes: PreparedMatchedManifestRoutes, +) { + const css = getInlineCssForPreparedRoutes(manifest, preparedRoutes) + + return css === undefined ? undefined : createInlineCssStyleAsset(css) +} + +function getMatchedRoutesCacheKey(matches: Array<AnyRouteMatch>) { + let cacheKey = '' + for (let i = 0; i < matches.length; i++) { + cacheKey += (i === 0 ? '' : '\0') + matches[i]!.routeId + } + return cacheKey +} + +function getPreparedMatchedManifestRoutes( + manifest: ServerManifest, + matches: Array<AnyRouteMatch>, + cacheKey: string, +) { + if (isProd) { + const cached = getManifestCache(manifest).get(cacheKey) + if (cached) { + return cached } } - takeAll() { - const bufferedScripts = this._queue - this._queue = [] - if (bufferedScripts.length === 0) { - return undefined - } - bufferedScripts.push(`document.currentScript.remove()`) - const joinedScripts = bufferedScripts.join(';') - return joinedScripts + const preparedRoutes = prepareMatchedManifestRoutes(manifest, matches) + + if (isProd) { + getManifestCache(manifest).set(cacheKey, preparedRoutes) } - injectBufferedScripts() { - if (this._cleanedUp) return - const scriptsToInject = this.takeAll() - if (scriptsToInject && this.router?.serverSsr) { - this.router.serverSsr.injectScript(() => scriptsToInject) + return preparedRoutes +} + +function prepareMatchedManifestRoutes( + manifest: ServerManifest, + matches: Array<AnyRouteMatch>, +): PreparedMatchedManifestRoutes { + const inlineStyles = manifest.inlineCss?.styles + const routes: FilteredRoutes = {} + + if (!inlineStyles) { + for (const match of matches) { + const route = manifest.routes[match.routeId] + if (route) { + routes[match.routeId] = route + } + } + return { routes, hasStrippedRoutes: false } + } + + const inlineCssHrefs: Array<string> = [] + const seenInlineCssHrefs = new Set<string>() + let hasStrippedRoutes = false + + for (const match of matches) { + const routeId = match.routeId + const route = manifest.routes[routeId] + if (!route) { + continue + } + + const nextRoute = stripInlinedStylesheetAssetsFromRoute( + inlineStyles, + route, + inlineCssHrefs, + seenInlineCssHrefs, + ) + + if (nextRoute !== route) { + hasStrippedRoutes = true + } + routes[routeId] = nextRoute + } + + return { + routes, + hasStrippedRoutes, + ...(inlineCssHrefs.length ? { inlineCssHrefs } : {}), + } +} + +function stripInlinedStylesheetAssetsFromRoute( + inlineStyles: Record<string, string>, + route: ManifestRoute, + inlineCssHrefs: Array<string>, + seenInlineCssHrefs: Set<string>, +): ManifestRoute { + const css = route.css + if (!css) { + return route + } + + if (css.length === 0) { + const nextRoute = { ...route } + delete nextRoute.css + return nextRoute + } + + let cssLinks: typeof css | undefined + for (let i = 0; i < css.length; i++) { + const link = css[i]! + const href = getStylesheetHref(link) + if (inlineStyles[href] === undefined) { + if (cssLinks) { + cssLinks.push(link) + } + continue + } + + if (!seenInlineCssHrefs.has(href)) { + seenInlineCssHrefs.add(href) + inlineCssHrefs.push(href) + } + + if (!cssLinks) { + cssLinks = css.slice(0, i) } } - cleanup() { - this._cleanedUp = true - this._queue = [] - this.router = undefined + if (!cssLinks) { + return route + } + + if (cssLinks.length > 0) { + return { ...route, css: cssLinks } + } + + const nextRoute = { ...route } + delete nextRoute.css + return nextRoute +} + +function hasRouteAssets(route: ManifestRoute) { + return !!route.scripts?.length || !!route.css?.length +} + +function hasRequestAssets(assets: ManifestRouteAssets | undefined) { + return !!assets && (!!assets.preloads?.length || hasRouteAssets(assets)) +} + +function mergeRequestAssetsIntoRootRoute( + rootRoute: ManifestRoute | undefined, + requestAssets: ManifestRouteAssets | undefined, +): ManifestRoute { + const preloads = requestAssets?.preloads?.length + ? [...requestAssets.preloads, ...(rootRoute?.preloads ?? [])] + : rootRoute?.preloads + const scripts = requestAssets?.scripts?.length + ? [...requestAssets.scripts, ...(rootRoute?.scripts ?? [])] + : rootRoute?.scripts + const cssLinks = requestAssets?.css?.length + ? [...requestAssets.css, ...(rootRoute?.css ?? [])] + : rootRoute?.css + + return { + ...(rootRoute ?? {}), + ...(preloads?.length ? { preloads } : {}), + ...(scripts?.length ? { scripts } : {}), + ...(cssLinks?.length ? { css: cssLinks } : {}), + } +} + +/** + * Compose a client-facing manifest from prepared routes, an optional inline + * style, and optional request-scoped assets merged into the root route. + * Shared by the `router.ssr.manifest` getter and `dehydrate()` so the two + * compositions cannot drift. + */ +function composeManifest( + scriptFormat: ServerManifest['scriptFormat'], + inlineStyle: Manifest['inlineStyle'], + routes: FilteredRoutes, + requestAssets: ManifestRouteAssets | undefined, +): Manifest { + const base: Manifest = { + ...(scriptFormat ? { scriptFormat } : {}), + ...(inlineStyle ? { inlineStyle } : {}), + routes, + } + if (!hasRequestAssets(requestAssets)) { + return base + } + // Merge request-scoped assets into the root route without mutating any + // cached route map. + return { + ...base, + routes: { + ...routes, + [rootRouteId]: mergeRequestAssetsIntoRootRoute( + routes[rootRouteId], + requestAssets, + ), + }, } } export function attachRouterServerSsrUtils({ router, manifest, + getRequestAssets, }: { router: AnyRouter - manifest: Manifest | undefined + manifest: ServerManifest | undefined + getRequestAssets?: () => ManifestRouteAssets | undefined }) { + // Inline CSS joining and route filtering depend only on matched route ids, + // so keep that immutable preparation request-local. Request assets can be + // discovered between head and Scripts reads and may mutate in place; always + // compose their current contents instead of caching by object identity. + let memoizedPreparedManifest: + | { + cacheKey: string + inlineCssAsset: Manifest['inlineStyle'] | undefined + routes: FilteredRoutes + } + | undefined router.ssr = { - manifest, - } - let _dehydrated = false - const listeners: Array<() => void> = [] - const scriptBuffer = new ScriptBuffer(router) + get manifest() { + if (!manifest) { + return manifest + } - router.serverSsr = { - injectedHtml: [], - injectHtml: (getHtml) => { - const promise = Promise.resolve().then(getHtml) - router.serverSsr!.injectedHtml.push(promise) - router.emit({ - type: 'onInjectedHtml', - promise, - }) + const requestAssets = getRequestAssets?.() + const hasAssets = hasRequestAssets(requestAssets) - return promise.then(() => {}) - }, - injectScript: (getScript) => { - return router.serverSsr!.injectHtml(async () => { - const script = await getScript() - if (!script) { - return '' + if (!hasAssets && !manifest.inlineCss) { + return manifest + } + + let inlineCssAsset: Manifest['inlineStyle'] | undefined + let routes = manifest.routes + if (manifest.inlineCss) { + const matches = _getRenderedMatches(router.stores.matches.get()) + const cacheKey = getMatchedRoutesCacheKey(matches) + if (memoizedPreparedManifest?.cacheKey === cacheKey) { + inlineCssAsset = memoizedPreparedManifest.inlineCssAsset + routes = memoizedPreparedManifest.routes + } else { + const preparedManifest = getPreparedMatchedManifestRoutes( + manifest, + matches, + cacheKey, + ) + inlineCssAsset = getInlineCssAssetForPreparedRoutes( + manifest, + preparedManifest, + ) + if (preparedManifest.hasStrippedRoutes) { + routes = { ...manifest.routes, ...preparedManifest.routes } + } + memoizedPreparedManifest = { cacheKey, inlineCssAsset, routes } } - return `<script${router.options.ssr?.nonce ? ` nonce='${router.options.ssr.nonce}'` : ''}>${script}</script>` - }) + } + + return composeManifest( + manifest.scriptFormat, + inlineCssAsset, + routes, + hasAssets ? requestAssets : undefined, + ) }, - dehydrate: async () => { - invariant(!_dehydrated, 'router is already dehydrated!') - let matchesToDehydrate = router.state.matches - if (router.isShell()) { + } + let dehydrationPhase: DehydrationPhase = 'idle' + let renderFinished = false + const renderFinishedListeners: Array<() => void> = [] + const cleanupListeners: Array<(settled: boolean) => void> = [] + let cleanupStarted = false + // Every value the router dehydrated has settled: nothing it started can + // still be pending when the response ends. + let settled = false + let disposeSerialization: (() => void) | undefined + const hydrationScripts = createHydrationScripts(router.options.ssr?.nonce) + + const serverSsr: ServerSsr = { + hydrationScripts, + dehydrate: async (opts?: { + requestAssets?: ManifestRouteAssets + signal?: AbortSignal + }) => { + // Guard synchronously before the first await: a concurrent second call + // would double-serialize and corrupt the hydration payload. + if (dehydrationPhase !== 'idle') { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + dehydrationPhase === 'disabled' + ? 'Invariant failed: hydration is disabled for this request!' + : 'Invariant failed: router is already dehydrated!', + ) + } + + invariant() + } + opts?.signal?.throwIfAborted() + dehydrationPhase = 'started' + let matchesToDehydrate = _getRenderedMatches(router.stores.matches.get()) + const isShell = router.isShell() + if (isShell) { // In SPA mode we only want to dehydrate the root match matchesToDehydrate = matchesToDehydrate.slice(0, 1) } const matches = matchesToDehydrate.map(dehydrateMatch) let manifestToDehydrate: Manifest | undefined = undefined - // For currently matched routes, send full manifest (preloads + assets) - // For all other routes, only send assets (no preloads as they are handled via dynamic imports) + // Only currently matched routes are dehydrated. Other route assets are + // loaded through dynamic imports when those routes become active. if (manifest) { - const currentRouteIds = new Set( - router.state.matches.map((k) => k.routeId), + const cacheKey = getMatchedRoutesCacheKey(matchesToDehydrate) + const preparedManifest = getPreparedMatchedManifestRoutes( + manifest, + matchesToDehydrate, + cacheKey, ) - const filteredRoutes = Object.fromEntries( - Object.entries(manifest.routes).flatMap( - ([routeId, routeManifest]) => { - if (currentRouteIds.has(routeId)) { - return [[routeId, routeManifest]] - } else if ( - routeManifest.assets && - routeManifest.assets.length > 0 - ) { - return [ - [ - routeId, - { - assets: routeManifest.assets, - }, - ], - ] - } - return [] - }, - ), + + manifestToDehydrate = composeManifest( + manifest.scriptFormat, + preparedManifest.inlineCssHrefs + ? createInlineCssPlaceholderAsset() + : undefined, + preparedManifest.routes, + opts?.requestAssets, ) - manifestToDehydrate = { - routes: filteredRoutes, - } } const dehydratedRouter: DehydratedRouter = { manifest: manifestToDehydrate, matches, } - const lastMatchId = matchesToDehydrate[matchesToDehydrate.length - 1]?.id - if (lastMatchId) { - dehydratedRouter.lastMatchId = lastMatchId + const dehydrate = router.options.dehydrate + const dehydratedData = dehydrate + ? opts?.signal + ? await waitForReason(dehydrate.call(router.options), opts.signal) + : await dehydrate.call(router.options) + : undefined + opts?.signal?.throwIfAborted() + if (cleanupStarted) { + return } - const dehydratedData = await router.options.dehydrate?.() - if (dehydratedData) { + if (dehydratedData !== undefined) { dehydratedRouter.dehydratedData = dehydratedData } - _dehydrated = true - - const p = createControlledPromise<string>() const trackPlugins = { didRun: false } - const plugins = - ( - router.options.serializationAdapters as - | Array<AnySerializationAdapter> - | undefined - )?.map((t) => makeSsrSerovalPlugin(t, trackPlugins)) ?? [] + const serializationAdapters = router.options.serializationAdapters + const plugins = serializationAdapters + ? [ + ...serializationAdapters.map((adapter) => + makeSsrSerovalPlugin(adapter, trackPlugins), + ), + ...ssrSerovalPlugins, + ] + : ssrSerovalPlugins - crossSerializeStream(dehydratedRouter, { + let serializationCompleteSignaled = false + let initialSerialized = false + const completeScriptSerialization = ( + result: boolean | { error: unknown }, + ) => { + if (serializationCompleteSignaled || cleanupStarted) { + return + } + serializationCompleteSignaled = true + const dispose = disposeSerialization + disposeSerialization = undefined + if (result === true) { + settled = true + hydrationScripts.finish() + } else if (result) { + hydrationScripts.fail(result.error) + } + if (dispose) { + // Seroval invokes completion callbacks before it marks its stream as + // inactive. Clear ownership before notifying the hydration consumer, + // which can synchronously clean up this request, then dispose later. + queueMicrotask(() => disposeSerializationSafely(dispose)) + } + } + + let synchronousFailure: { error: unknown } | undefined + const dispose = crossSerializeStream(dehydratedRouter, { refs: new Map(), - plugins: [...plugins, ...defaultSerovalPlugins], + plugins, onSerialize: (data, initial) => { - let serialized = initial ? GLOBAL_TSR + '.router=' + data : data - if (trackPlugins.didRun) { - serialized = GLOBAL_TSR + '.p(()=>' + serialized + ')' + if (serializationCompleteSignaled || cleanupStarted) { + return } - scriptBuffer.enqueue(serialized) + initialSerialized ||= initial + if ( + !hydrationScripts.pushSerializedSource( + data, + initial, + trackPlugins.didRun, + ) + ) { + // Rejected output stops the producer while deferred work may remain. + completeScriptSerialization(false) + } + }, + onError: (err: unknown) => { + if (serializationCompleteSignaled || cleanupStarted) { + return + } + console.error('Serialization error:', err) + synchronousFailure = { error: err } + completeScriptSerialization({ error: err }) }, - scopeId: SCOPE_ID, + scopeId: SSR_SERIALIZATION_SCOPE_ID, onDone: () => { - scriptBuffer.enqueue(GLOBAL_TSR + '.e()') - p.resolve('') + if (initialSerialized) { + completeScriptSerialization(true) + } }, - onError: (err) => p.reject(err), }) - // make sure the stream is kept open until the promise is resolved - router.serverSsr!.injectHtml(() => p) - }, - isDehydrated() { - return _dehydrated - }, - onRenderFinished: (listener) => listeners.push(listener), - setRenderFinished: () => { - listeners.forEach((l) => l()) - // Clear listeners after calling them to prevent memory leaks - listeners.length = 0 - scriptBuffer.liftBarrier() - }, - takeBufferedScripts() { - const scripts = scriptBuffer.takeAll() - const serverBufferedScript: RouterManagedTag = { - tag: 'script', - attrs: { - nonce: router.options.ssr?.nonce, - className: '$tsr', - id: TSR_SCRIPT_BARRIER_ID, - }, - children: scripts, + // Seroval can call onDone synchronously before it returns dispose(). + if (cleanupStarted || serializationCompleteSignaled) { + disposeSerializationSafely(dispose) + } else { + disposeSerialization = dispose + } + if (synchronousFailure) { + throw synchronousFailure.error } - return serverBufferedScript }, - liftScriptBarrier() { - scriptBuffer.liftBarrier() + onRenderFinished: (listener) => { + if (cleanupStarted) { + return + } + if (renderFinished) { + try { + listener() + } catch (error) { + console.error('Error in render finished listener:', error) + } + return + } + renderFinishedListeners.push(listener) }, + onCleanup: (listener) => { + if (cleanupStarted) { + // Cleanup already happened (or is running). Invoke immediately so + // late registrants can still release their resources instead of + // silently retaining them (standard disposer convention). + try { + listener(settled) + } catch (error) { + console.error('Error in SSR cleanup listener:', error) + } + return + } + cleanupListeners.push(listener) + }, + setRenderFinished: () => { + if (cleanupStarted || renderFinished) { + return + } + renderFinished = true + hydrationScripts.liftBarrier() + notifyAndClearListeners( + renderFinishedListeners, + 'Error in render finished listener:', + undefined, + ) + }, + disableHydration: () => { + if (cleanupStarted || dehydrationPhase === 'disabled') { + return + } + if (dehydrationPhase !== 'idle') { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + 'Invariant failed: cannot disable hydration after dehydrate()!', + ) + } + + invariant() + } + // The owner rejects later takes/claims; guard order matters so a + // throwing owner does not leave the phase half-set. + hydrationScripts.disableHydration() + dehydrationPhase = 'disabled' + }, + takeInitialHydrationScriptTags: + hydrationScripts.takeInitialHydrationScriptTags, cleanup() { - // Guard against multiple cleanup calls - if (!router.serverSsr) return - listeners.length = 0 - scriptBuffer.cleanup() - router.serverSsr.injectedHtml = [] + // Guard against multiple/reentrant cleanup calls. A listener could call + // cleanup() again indirectly; snapshot + clear before invoking so each + // listener runs exactly once and reentry is a no-op. + if (cleanupStarted) { + return + } + cleanupStarted = true + hydrationScripts.cleanup() + const dispose = disposeSerialization + disposeSerialization = undefined + disposeSerializationSafely(dispose) + notifyAndClearListeners( + cleanupListeners, + 'Error in SSR cleanup listener:', + settled, + ) + renderFinishedListeners.length = 0 + router.ssr = undefined router.serverSsr = undefined }, } + + router.serverSsr = serverSsr + for (const listener of router.serverSsrLifecycle?.onServerSsrAttach ?? []) { + try { + listener(serverSsr) + } catch (err) { + console.error('SSR attach listener error:', err) + } + } } +/** + * Get the origin for the request. + * + * SECURITY: We intentionally do NOT trust the Origin header for determining + * the router's origin. The Origin header can be spoofed by attackers, which + * could lead to SSRF-like vulnerabilities where redirects are constructed + * using a malicious origin (CVE-2024-34351). + * + * Instead, we derive the origin from request.url, which is typically set by + * the server infrastructure (not client-controlled headers). + * + * For applications behind proxies that need to trust forwarded headers, + * use the router's `origin` option to explicitly configure a trusted origin. + */ export function getOrigin(request: Request) { - const originHeader = request.headers.get('Origin') - if (originHeader) { - try { - new URL(originHeader) - return originHeader - } catch {} - } try { return new URL(request.url).origin } catch {} return 'http://localhost' } + +// server and browser can decode/encode characters differently in paths and search params. +// Server generally strictly follows the WHATWG URL Standard, while browsers may differ for legacy reasons. +// for example, in paths "|" is not encoded on the server but is encoded on chromium (and not on firefox) while "대" is encoded on both sides. +// Another anomaly is that in Node new URLSearchParams and new URL also decode/encode characters differently. +// new URLSearchParams() encodes "|" while new URL() does not, and in this instance +// chromium treats search params differently than paths, i.e. "|" is not encoded in search params. +export function getNormalizedURL(url: string | URL, base?: string | URL) { + // Encode backslashes in a string URL. A URL object is already parsed and is + // only read here. + const rawUrl = + typeof url === 'string' ? new URL(url.replace('\\', '%5C'), base) : url + // URL parsing has already handled backslashes and ignored controls. A pathname + // like "//evil.example" would become a protocol-relative URL when rebuilt below. + const handledProtocolRelativeURL = rawUrl.pathname.startsWith('//') + const decodedPathname = decodePath( + handledProtocolRelativeURL + ? rawUrl.pathname.replace(/^\/+/, '/') + : rawUrl.pathname, + ) + const searchParams = new URLSearchParams(rawUrl.search) + const normalizedHref = + decodedPathname + + (searchParams.size > 0 ? '?' : '') + + searchParams.toString() + + rawUrl.hash + + return { + url: new URL(normalizedHref, rawUrl.origin), + handledProtocolRelativeURL, + } +} diff --git a/packages/router-core/src/ssr/transformStreamWithRouter.ts b/packages/router-core/src/ssr/transformStreamWithRouter.ts index 848f1a6800..d253034073 100644 --- a/packages/router-core/src/ssr/transformStreamWithRouter.ts +++ b/packages/router-core/src/ssr/transformStreamWithRouter.ts @@ -1,334 +1,967 @@ -import { ReadableStream } from 'node:stream/web' import { Readable } from 'node:stream' -import { createControlledPromise } from '../utils' +import { + DOCUMENT_CLOSE_ANCHOR_INDEX, + DOCUMENT_CLOSE_BYTES, + SCRIPT_CLOSE_ANCHOR_INDEX, + SCRIPT_CLOSE_BYTES, + advanceByteMatcher, + encodeIntoBoundedChunk, + findExactBytes, + getExactBytesPrefixAtEnd, +} from './htmlBoundaryScanner' +import { + HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX, + HYDRATION_SCRIPT_BOUNDARY_BYTES, + HydrationScriptOutputState, +} from './hydrationScripts' +import type { ReadableStream as NodeReadableStream } from 'node:stream/web' import type { AnyRouter } from '../router' +import type { ByteMatcherState } from './htmlBoundaryScanner' +import type { HydrationScriptOutput } from './hydrationScripts' -export function transformReadableStreamWithRouter( - router: AnyRouter, - routerStream: ReadableStream, -) { - return transformStreamWithRouter(router, routerStream) +export type TransformStreamWithRouterOptions = { + /** Timeout for serialization to complete after app render finishes (default: 60000ms) */ + timeoutMs?: number + /** Maximum lifetime of the stream transform. Defaults to twice timeoutMs. */ + lifetimeMs?: number + /** Cancels the transform and releases SSR state when the request ends. */ + signal?: AbortSignal + /** + * Additional point after which the renderer guarantees that a router script + * can be inserted. This is an adapter contract, not a user streaming policy. + * The router boundary, canonical document close, and EOF are always safe. + */ + rendererSafePoint?: 'script-close' | 'record-end' + /** + * Called exactly once when the stream is torn down due to abort/error/ + * cancel/timeout — NOT on natural successful completion. Use this to + * abort a hidden producer upstream of any stream passed to this transform. + * Errors thrown from this callback are swallowed. + */ + onAbort?: (reason?: unknown) => void } +type AppStreamValue = Uint8Array | string +/** Renderer output: UTF-8 bytes, or string records from a Node pipeable. */ +type AppStream = + | ReadableStream<Uint8Array> + | ReadableStream<string> + | ReadableStream<AppStreamValue> + | NodeReadableStream<AppStreamValue> + export function transformPipeableStreamWithRouter( router: AnyRouter, routerStream: Readable, + opts?: TransformStreamWithRouterOptions, ) { return Readable.fromWeb( - transformStreamWithRouter(router, Readable.toWeb(routerStream)), + transformReadableStreamWithRouter( + router, + Readable.toWeb(routerStream) as AppStream, + opts, + ) as NodeReadableStream<Uint8Array>, ) } -export const TSR_SCRIPT_BARRIER_ID = '$tsr-stream-barrier' - -// regex pattern for matching closing body and html tags -const patternBodyEnd = /(<\/body>)/ -const patternHtmlEnd = /(<\/html>)/ -// regex pattern for matching closing tags -const patternClosingTag = /(<\/[a-zA-Z][\w:.-]*?>)/g - -type ReadablePassthrough = { - stream: ReadableStream - write: (chunk: unknown) => void - end: (chunk?: string) => void - destroy: (error: unknown) => void - destroyed: boolean -} - -function createPassthrough(onCancel: () => void) { - let controller: ReadableStreamDefaultController<any> - const encoder = new TextEncoder() - const stream = new ReadableStream({ - start(c) { - controller = c - }, - cancel() { - res.destroyed = true - onCancel() - }, - }) - - const res: ReadablePassthrough = { - stream, - write: (chunk) => { - // Don't write to destroyed stream - if (res.destroyed) return - if (typeof chunk === 'string') { - controller.enqueue(encoder.encode(chunk)) - } else { - controller.enqueue(chunk) +export async function transformHtmlStringWithRouter( + router: AnyRouter, + html: string, + opts?: TransformStreamWithRouterOptions, +) { + const serverSsr = router.serverSsr + if (!serverSsr) { + throw new Error('Invariant failed: router.serverSsr is required') + } + const hydrationScripts = serverSsr.hydrationScripts + if (hydrationScripts.reserveFastPath()) { + try { + opts?.signal?.throwIfAborted() + serverSsr.setRenderFinished() + return '<!DOCTYPE html>' + html + } catch (error) { + try { + opts?.onAbort?.(error) + } catch { + // User cleanup must not block SSR cleanup. } - }, - end: (chunk) => { - // Don't end already destroyed stream - if (res.destroyed) return - if (chunk) { - res.write(chunk) - } - res.destroyed = true - controller.close() - }, - destroy: (error) => { - // Don't destroy already destroyed stream - if (res.destroyed) return - res.destroyed = true - controller.error(error) - }, - destroyed: false, + throw error + } finally { + serverSsr.cleanup() + } } - return res + // The merge path chunks string records itself. + const appStream = new ReadableStream<string>({ + start(controller) { + controller.enqueue('<!DOCTYPE html>') + controller.enqueue(html) + controller.close() + }, + }) + const output = transformReadableStreamWithRouter(router, appStream, opts) + return readUtf8Stream(output) } -async function readStream( - stream: ReadableStream, - opts: { - onData?: (chunk: ReadableStreamReadValueResult<any>) => void - onEnd?: () => void - onError?: (error: unknown) => void - }, -) { +async function readUtf8Stream(stream: ReadableStream<Uint8Array>) { const reader = stream.getReader() + const decoder = new TextDecoder() + let text = '' try { - let chunk - while (!(chunk = await reader.read()).done) { - opts.onData?.(chunk) + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + text += decoder.decode(value, { stream: true }) } - opts.onEnd?.() - } catch (error) { - opts.onError?.(error) + return text + decoder.decode() } finally { reader.releaseLock() } } -export function transformStreamWithRouter( - router: AnyRouter, - appStream: ReadableStream, - opts?: { - timeoutMs?: number - }, +const DEFAULT_SERIALIZATION_TIMEOUT_MS = 60_000 +const MIN_APPLICATION_STRING_CHUNK_BYTES = 256 +const MAX_APPLICATION_STRING_CHUNK_BYTES = 64 * 1024 + +const ApplicationPhase = { + BeforeBoundary: 0, + Merge: 1, + HeldClose: 2, + PassThrough: 3, +} as const + +type ApplicationPhase = (typeof ApplicationPhase)[keyof typeof ApplicationPhase] +type Termination = 'complete' | 'cancel' | 'failure' +type AppStreamReader = ReadableStreamDefaultReader<AppStreamValue> + +function releaseReader(reader: AppStreamReader) { + try { + reader.releaseLock() + } catch { + // A nonstandard reader may still reject lock release. + } +} + +function cancelReader(reader: AppStreamReader, reason?: unknown) { + const cancelled = reader.cancel(reason).catch(() => {}) + // Native readers close synchronously when cancel() starts. Release the lock + // before an arbitrary underlying cancel promise has a chance to park. + releaseReader(reader) + return cancelled +} + +function finalizeSsrStream( + kind: Termination, + reason: unknown, + controller: ReadableStreamDefaultController<Uint8Array>, + reader: AppStreamReader, + serverSsr: NonNullable<AnyRouter['serverSsr']>, + onAbort?: (reason?: unknown) => void, ) { - let stopListeningToInjectedHtml: (() => void) | undefined = undefined - let timeoutHandle: NodeJS.Timeout - let cleanedUp = false - - function cleanup() { - if (cleanedUp) return - cleanedUp = true - if (stopListeningToInjectedHtml) { - stopListeningToInjectedHtml() - stopListeningToInjectedHtml = undefined + try { + if (kind === 'complete') { + controller.close() + } else if (kind === 'failure') { + controller.error(reason) } - clearTimeout(timeoutHandle) - router.serverSsr?.cleanup() + } catch { + // The stream already reached a terminal state. } - const finalPassThrough = createPassthrough(cleanup) - const textDecoder = new TextDecoder() - - let isAppRendering = true - let routerStreamBuffer = '' - let pendingClosingTags = '' - let streamBarrierLifted = false - let leftover = '' - let leftoverHtml = '' - - function getBufferedRouterStream() { - const html = routerStreamBuffer - routerStreamBuffer = '' - return html - } - - function decodeChunk(chunk: unknown): string { - if (chunk instanceof Uint8Array) { - return textDecoder.decode(chunk, { stream: true }) + const aborted = kind !== 'complete' + if (aborted) { + try { + onAbort?.(reason) + } catch { + // User cleanup must not block SSR cleanup. } - return String(chunk) } - const injectedHtmlDonePromise = createControlledPromise<void>() + const readerDone = aborted + ? cancelReader(reader, reason) + : releaseReader(reader) + serverSsr.cleanup() + return readerDone +} - let processingCount = 0 - - // Process any already-injected HTML - handleInjectedHtml() - - // Listen for any new injected HTML - stopListeningToInjectedHtml = router.subscribe( - 'onInjectedHtml', - handleInjectedHtml, +function getLifetimeMs(opts?: TransformStreamWithRouterOptions) { + return ( + opts?.lifetimeMs ?? + (opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS) * 2 ) +} - function handleInjectedHtml() { - // Don't process if already cleaned up - if (cleanedUp) return +// External serverSsr.cleanup() severs router ownership. The transform must +// release the renderer, timers, listeners, and buffers immediately instead of +// retaining them until the lifetime backstop fires. AbortError identifies this +// intentional cancellation to downstream consumers. +function createCleanupAbortError() { + const error = new Error('SSR stream transform aborted by router SSR cleanup') + error.name = 'AbortError' + return error +} - router.serverSsr!.injectedHtml.forEach((promise) => { - processingCount++ +function listenForAbort( + signal: AbortSignal | undefined, + onAbort: (reason: unknown) => void, +) { + if (!signal) { + return undefined + } + const listener = () => onAbort(signal.reason) + signal.addEventListener('abort', listener, { once: true }) + return () => signal.removeEventListener('abort', listener) +} - promise - .then((html) => { - // Don't write to destroyed stream or after cleanup - if (cleanedUp || finalPassThrough.destroyed) { +/** + * Create a timer that does not keep the Node.js process alive when this + * last-resort stream backstop is the only remaining work. + * + * Node's global `setTimeout()` returns a `Timeout` object with `unref()`. + * Web-standard runtimes return a numeric timer ID instead. Cloudflare Workers + * retain that Web behavior for global timers even when `nodejs_compat` is + * enabled. Accessing an optional property on a numeric ID is safe, so timer + * creation can normalize the Node-only capability without allocating a + * wrapper object. The native handle is returned unchanged for `clearTimeout`. + */ +function setUnrefTimeout(callback: () => void, timeoutMs: number) { + const handle = setTimeout(callback, timeoutMs) + const portableHandle = handle as typeof handle & { unref?: () => void } + portableHandle.unref?.() + return handle +} + +/** + * Arm the shared teardown triggers of a transform stream: the lifetime + * backstop timer, the request-abort listener, and the external-cleanup + * listener. Returns a disarm function that `terminate()` calls exactly once; + * teardown ordering must stay identical between the fast and merge paths. + */ +function armStreamLifecycle( + serverSsr: NonNullable<AnyRouter['serverSsr']>, + opts: TransformStreamWithRouterOptions | undefined, + isTerminal: () => boolean, + terminate: (kind: Termination, reason?: unknown) => unknown, +) { + const signal = opts?.signal + let lifetimeTimeoutHandle: ReturnType<typeof setTimeout> | undefined + let stopAbortListener: (() => void) | undefined + const disarm = () => { + stopAbortListener?.() + stopAbortListener = undefined + if (signal && serverSsr.hydrationScripts.requestSignal === signal) { + serverSsr.hydrationScripts.requestSignal = undefined + } + if (lifetimeTimeoutHandle !== undefined) { + clearTimeout(lifetimeTimeoutHandle) + lifetimeTimeoutHandle = undefined + } + } + + const lifetimeMs = getLifetimeMs(opts) + lifetimeTimeoutHandle = setUnrefTimeout(() => { + if (isTerminal()) { + return + } + const error = new Error('Stream lifetime exceeded') + console.warn( + `SSR stream transform exceeded maximum lifetime (${lifetimeMs}ms), forcing cleanup`, + ) + terminate('failure', error) + }, lifetimeMs) + stopAbortListener = listenForAbort(signal, (reason) => { + terminate('failure', reason) + }) + if (signal) { + serverSsr.hydrationScripts.requestSignal = signal + } + // External serverSsr.cleanup() must release the reader, renderer, timer, + // and buffers promptly — a parked pump only wakes through its own + // subscriptions, and a discarded response never pulls at all. + serverSsr.onCleanup(() => { + if (!isTerminal()) { + terminate('failure', createCleanupAbortError()) + } + }) + return disarm +} + +function cleanupFailedStreamCreation( + serverSsr: NonNullable<AnyRouter['serverSsr']>, + onAbort: TransformStreamWithRouterOptions['onAbort'], + error: unknown, +) { + try { + onAbort?.(error) + } catch { + // User cleanup must not block SSR cleanup. + } + serverSsr.cleanup() +} + +function encodeStringSource(value: string, offset: number) { + const remaining = value.length - offset + const capacity = Math.min( + MAX_APPLICATION_STRING_CHUNK_BYTES, + Math.max( + MIN_APPLICATION_STRING_CHUNK_BYTES, + Math.min(value.length, remaining * 3), + ), + ) + const output = new Uint8Array(capacity) + const { read, written } = encodeIntoBoundedChunk(value, offset, output) + return { + bytes: written === output.length ? output : output.subarray(0, written), + read, + } +} + +export function transformReadableStreamWithRouter( + router: AnyRouter, + appStream: AppStream, + opts?: TransformStreamWithRouterOptions, +) { + const serverSsr = router.serverSsr + if (!serverSsr) { + throw new Error('Invariant failed: router.serverSsr is required') + } + const hydrationScripts = serverSsr.hydrationScripts + + let reader: AppStreamReader + try { + reader = appStream.getReader() as AppStreamReader + } catch (error) { + cleanupFailedStreamCreation(serverSsr, opts?.onAbort, error) + throw error + } + + try { + opts?.signal?.throwIfAborted() + if (hydrationScripts.reserveFastPath()) { + // Hydration already drained: pass application output through from the + // first byte. The merge stream handles this with the same pass-through + // it uses after hydration finishes mid-stream. + return makeMergeStream(serverSsr, reader, undefined, opts) + } + const hydrationOutput = hydrationScripts.claimOutput() + if (hydrationOutput.state === HydrationScriptOutputState.Failed) { + throw hydrationOutput.error + } + return makeMergeStream(serverSsr, reader, hydrationOutput, opts) + } catch (error) { + void cancelReader(reader, error) + cleanupFailedStreamCreation(serverSsr, opts?.onAbort, error) + throw error + } +} + +// The merge path searches only router- and renderer-owned ASCII delimiters. +// Application bytes otherwise leave through zero-copy subarray views. +// Without a hydration output the stream starts in pass-through. +function makeMergeStream( + serverSsr: NonNullable<AnyRouter['serverSsr']>, + reader: AppStreamReader, + hydrationOutput: HydrationScriptOutput | undefined, + opts?: TransformStreamWithRouterOptions, +) { + const hydrationScripts = serverSsr.hydrationScripts + let controller!: ReadableStreamDefaultController<Uint8Array> + let terminal = false + let appDone = false + let applicationPhase: ApplicationPhase = hydrationOutput + ? ApplicationPhase.BeforeBoundary + : ApplicationPhase.PassThrough + let insertionBoundary = false + + let stopHydrationOutputListener: (() => void) | undefined + let appReadPending = false + let settledAppRead: ReadableStreamReadValueResult<AppStreamValue> | undefined + + let appBytes: Uint8Array | undefined + let appOffset = 0 + let documentCloseIndex: number | undefined + let appString: string | undefined + let appStringOffset = 0 + + const useScriptCloseSafePoints = opts?.rendererSafePoint === 'script-close' + const useRecordEndSafePoints = opts?.rendererSafePoint === 'record-end' + + // Both matchers are created on first use; pass-through never needs them. + let barrierMatcher: ByteMatcherState | undefined + let safePointMatcher: ByteMatcherState | undefined + // Split document closes carry at most 13 bytes across chunks. This uses + // findExactBytes + getExactBytesPrefixAtEnd instead of advanceByteMatcher + // because `</body></html>` repeats its first byte (`<` at 0 and 7), which + // violates the matcher's unique-first-byte resync precondition. + let closeCarry: Uint8Array | undefined + + let wakeResolve: (() => void) | undefined + // Assigned after the stream exists; `terminate` can run before that when an + // already-cleaned owner fires its cleanup listener synchronously. + let disarmLifecycle = (): void => {} + + function waitForWake() { + return new Promise<void>((resolve) => { + wakeResolve = resolve + }) + } + + function wakePump() { + const resolve = wakeResolve + wakeResolve = undefined + resolve?.() + } + + // Returns true when a chunk was enqueued. Every process* function + // propagates this boolean so pump() emits at most one chunk per downstream + // pull — the backpressure contract of this transform. + function enqueueAppBytes(value: Uint8Array) { + if (value.length === 0) { + return false + } + controller.enqueue(value) + return true + } + + function finishAppChunk() { + appBytes = undefined + documentCloseIndex = undefined + if ( + appString === undefined && + useRecordEndSafePoints && + closeCarry === undefined + ) { + insertionBoundary = true + } + } + + function emitAppRange( + end: number, + safePoint: boolean, + finishCurrentChunk = end === appBytes!.length, + ) { + const value = appBytes! + const output = + appOffset === 0 && end === value.length + ? value + : value.subarray(appOffset, end) + appOffset = end + if (safePoint) { + insertionBoundary = true + } + if (finishCurrentChunk) { + finishAppChunk() + } + return enqueueAppBytes(output) + } + + function loadNextAppStringChunk() { + const value = appString! + const encoded = encodeStringSource(value, appStringOffset) + appStringOffset += encoded.read + appBytes = encoded.bytes + appOffset = 0 + if (appStringOffset === value.length) { + appString = undefined + } + } + + function processUntilBarrier() { + const value = appBytes! + if (!hydrationScripts.isInitialTaken()) { + // The rendered boundary can only exist after the initial script take, + // so earlier renderer bytes pass through without scanning. This skips + // the barrier scan for the whole pre-<Scripts> document and prevents + // barrier-lookalike bytes in application content from lifting the + // barrier early. + return emitAppRange(value.length, false) + } + const matchEnd = advanceByteMatcher( + (barrierMatcher ??= { + pattern: HYDRATION_SCRIPT_BOUNDARY_BYTES, + anchorIndex: HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX, + matched: 0, + }), + value, + appOffset, + ) + if (matchEnd === undefined) { + return emitAppRange(value.length, false) + } + + applicationPhase = ApplicationPhase.Merge + hydrationScripts.liftBarrier() + return emitAppRange(matchEnd, true) + } + + // Advance past a canonical close that ends `consumed` bytes into the current + // chunk and hold it until the transform completes. + function enterHeldClose(consumed: number, prefix: Uint8Array | undefined) { + appOffset = consumed + applicationPhase = ApplicationPhase.HeldClose + if (safePointMatcher) { + // The removed close breaks byte continuity with later renderer bytes. + safePointMatcher.matched = 0 + } + insertionBoundary = true + if (appOffset === appBytes!.length) { + finishAppChunk() + } + return prefix ? enqueueAppBytes(prefix) : false + } + + function holdDocumentClose(matchStart: number) { + const value = appBytes! + return enterHeldClose( + matchStart + DOCUMENT_CLOSE_BYTES.length, + matchStart === appOffset + ? undefined + : value.subarray(appOffset, matchStart), + ) + } + + function processUntilSafePoint(endIndex: number) { + const value = appBytes! + const matchEnd = findSafePointEnd(value, appOffset, endIndex) + if (matchEnd === undefined) { + return false + } + + return emitAppRange(matchEnd, true) + } + + function findSafePointEnd( + value: Uint8Array, + startIndex: number, + endIndex: number, + ) { + // Merge-only: pass-through never scans for safe points. + const hydrationState = hydrationOutput!.state + if ( + endIndex === startIndex || + hydrationState === HydrationScriptOutputState.Done + ) { + return undefined + } + + const scanValue = + endIndex === value.length ? value : value.subarray(0, endIndex) + const matcher = (safePointMatcher ??= { + pattern: SCRIPT_CLOSE_BYTES, + anchorIndex: SCRIPT_CLOSE_ANCHOR_INDEX, + matched: 0, + }) + // Active drains before app bytes, Done is excluded above, and Failed + // terminates through the subscriber; only Ready and Waiting reach here. + const waiting = hydrationState === HydrationScriptOutputState.Waiting + const matchEnd = advanceByteMatcher(matcher, scanValue, startIndex, waiting) + if (matchEnd === undefined) { + return undefined + } + if (waiting) { + // Bytes after the last match are processed again on the next pull. + matcher.matched = 0 + } + return matchEnd + } + + function processCloseCarry() { + const value = appBytes! + const carry = closeCarry! + const headLength = Math.min( + value.length - appOffset, + DOCUMENT_CLOSE_BYTES.length, + ) + const combined = new Uint8Array(carry.length + headLength) + combined.set(carry) + combined.set( + value.subarray(appOffset, appOffset + headLength), + carry.length, + ) + + const matchStart = findExactBytes( + combined, + DOCUMENT_CLOSE_BYTES, + 0, + DOCUMENT_CLOSE_ANCHOR_INDEX, + ) + const partial = + matchStart < 0 + ? getExactBytesPrefixAtEnd(combined, DOCUMENT_CLOSE_BYTES) + : undefined + const safeEnd = matchStart >= 0 ? matchStart : (partial ?? combined.length) + + if (useScriptCloseSafePoints) { + const safePointEnd = findSafePointEnd(combined, 0, safeEnd) + if (safePointEnd !== undefined) { + appOffset += safePointEnd - carry.length + closeCarry = undefined + insertionBoundary = true + if (appOffset === value.length) { + finishAppChunk() + } + return enqueueAppBytes(combined.subarray(0, safePointEnd)) + } + } + + if (matchStart >= 0) { + closeCarry = undefined + return enterHeldClose( + appOffset + matchStart + DOCUMENT_CLOSE_BYTES.length - carry.length, + matchStart === 0 ? undefined : combined.subarray(0, matchStart), + ) + } + + closeCarry = partial === undefined ? undefined : combined.slice(partial) + appOffset += headLength + return enqueueAppBytes( + safeEnd === combined.length ? combined : combined.subarray(0, safeEnd), + ) + } + + function processUntilDocumentClose() { + const value = appBytes! + + if (closeCarry) { + if (processCloseCarry()) { + return true + } + if (applicationPhase === ApplicationPhase.HeldClose) { + return false + } + if (appOffset >= value.length) { + finishAppChunk() + return false + } + } + + // Safe points only advance within this chunk, so keep its close or miss. + const matchStart = (documentCloseIndex ??= findExactBytes( + value, + DOCUMENT_CLOSE_BYTES, + appOffset, + DOCUMENT_CLOSE_ANCHOR_INDEX, + )) + if (matchStart >= 0) { + if (useScriptCloseSafePoints && processUntilSafePoint(matchStart)) { + return true + } + return holdDocumentClose(matchStart) + } + + const partial = getExactBytesPrefixAtEnd( + value, + DOCUMENT_CLOSE_BYTES, + appOffset, + ) + const safeEnd = partial ?? value.length + if (useScriptCloseSafePoints && processUntilSafePoint(safeEnd)) { + return true + } + closeCarry = partial === undefined ? undefined : value.slice(partial) + return emitAppRange(safeEnd, false, true) + } + + function processAppChunk() { + if (appOffset >= appBytes!.length) { + finishAppChunk() + return false + } + insertionBoundary = false + if (applicationPhase === ApplicationPhase.BeforeBoundary) { + return processUntilBarrier() + } + if (applicationPhase === ApplicationPhase.Merge) { + return processUntilDocumentClose() + } + const value = appBytes! + if (useScriptCloseSafePoints && processUntilSafePoint(value.length)) { + return true + } + + return emitAppRange(value.length, false) + } + + function terminate(kind: Termination, reason?: unknown) { + if (terminal) { + return + } + terminal = true + + stopHydrationOutputListener?.() + stopHydrationOutputListener = undefined + disarmLifecycle() + + settledAppRead = undefined + appBytes = undefined + documentCloseIndex = undefined + appString = undefined + closeCarry = undefined + wakePump() + + return finalizeSsrStream( + kind, + reason, + controller, + reader, + serverSsr, + opts?.onAbort, + ) + } + + function startAppRead() { + if (appReadPending || settledAppRead || terminal) { + return + } + appReadPending = true + void reader.read().then( + (result) => { + appReadPending = false + if (!terminal) { + if (result.done) { + acceptAppRead(result) + } else { + settledAppRead = result + } + wakePump() + } + }, + (error) => { + appReadPending = false + if (!terminal) { + handlePumpError(error) + } + }, + ) + } + + function acceptAppRead(result: ReadableStreamReadResult<AppStreamValue>) { + if (result.done) { + appDone = true + insertionBoundary = closeCarry === undefined + // The serialization deadline is a transport concern of this merge + // path; the lifecycle signal below stays a plain notification. + hydrationScripts.startSerializationTimeout( + opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS, + ) + serverSsr.setRenderFinished() + return + } + const value = result.value + if (typeof value === 'string') { + if (value.length === 0) { + return + } + appString = value + appStringOffset = 0 + insertionBoundary = false + loadNextAppStringChunk() + return + } + if (value.byteLength === 0) { + return + } + appBytes = value + appOffset = 0 + insertionBoundary = false + } + + async function loadNextAppChunk() { + if (appString !== undefined) { + loadNextAppStringChunk() + return + } + if (settledAppRead) { + const settled = settledAppRead + settledAppRead = undefined + acceptAppRead(settled) + return + } + + const scriptsCanInterruptRead = + applicationPhase !== ApplicationPhase.BeforeBoundary && + insertionBoundary && + hydrationOutput!.state !== HydrationScriptOutputState.Done + if (!scriptsCanInterruptRead && !appReadPending) { + const result = await reader.read() + if (terminal) { + return + } + acceptAppRead(result) + return + } + + const wake = waitForWake() + startAppRead() + await wake + } + + // Pass-through forwards application records unchanged and only encodes + // string records; it skips the merge bookkeeping entirely. + async function pumpPassThrough() { + try { + for (;;) { + if (appBytes) { + const remainder = + appOffset === 0 ? appBytes : appBytes.subarray(appOffset) + appBytes = undefined + if (enqueueAppBytes(remainder)) { return } - if (isAppRendering) { - routerStreamBuffer += html - } else { - finalPassThrough.write(html) + continue + } + if (appString !== undefined) { + loadNextAppStringChunk() + continue + } + if (appDone) { + terminate('complete') + return + } + if (appReadPending) { + // A merge-phase prefetch is still in flight; it wakes the pump. + await waitForWake() + continue + } + let result: ReadableStreamReadResult<AppStreamValue> | undefined = + settledAppRead + if (result) { + settledAppRead = undefined + } else { + result = await reader.read() + if (terminal) { + return } - }) - .catch((err) => { - injectedHtmlDonePromise.reject(err) - }) - .finally(() => { - processingCount-- - - if (!isAppRendering && processingCount === 0) { - injectedHtmlDonePromise.resolve() - } - }) - }) - router.serverSsr!.injectedHtml = [] - } - - injectedHtmlDonePromise - .then(() => { - // Don't process if already cleaned up or destroyed - if (cleanedUp || finalPassThrough.destroyed) { - return - } - - clearTimeout(timeoutHandle) - const finalHtml = - leftover + leftoverHtml + getBufferedRouterStream() + pendingClosingTags - - leftover = '' - leftoverHtml = '' - pendingClosingTags = '' - - finalPassThrough.end(finalHtml) - }) - .catch((err) => { - // Don't process if already cleaned up - if (cleanedUp || finalPassThrough.destroyed) { - return - } - - console.error('Error reading routerStream:', err) - finalPassThrough.destroy(err) - }) - .finally(cleanup) - - // Transform the appStream - readStream(appStream, { - onData: (chunk) => { - // Don't process if already cleaned up - if (cleanedUp || finalPassThrough.destroyed) { - return - } - - const text = decodeChunk(chunk.value) - const chunkString = leftover + text - const bodyEndMatch = chunkString.match(patternBodyEnd) - const htmlEndMatch = chunkString.match(patternHtmlEnd) - - if (!streamBarrierLifted) { - const streamBarrierIdIncluded = chunkString.includes( - TSR_SCRIPT_BARRIER_ID, - ) - if (streamBarrierIdIncluded) { - streamBarrierLifted = true - router.serverSsr!.liftScriptBarrier() + } + if (result.done || typeof result.value === 'string') { + acceptAppRead(result) + continue + } + if (result.value.byteLength > 0) { + controller.enqueue(result.value) + return } } + } catch (error) { + handlePumpError(error) + } + } - // If either the body end or html end is in the chunk, - // We need to get all of our data in asap + async function pump() { + const output = hydrationOutput! + while (!terminal) { + const hydrationState = output.state + if (hydrationState === HydrationScriptOutputState.Active) { + controller.enqueue(output.pullChunk()) + return + } if ( - bodyEndMatch && - htmlEndMatch && - bodyEndMatch.index! < htmlEndMatch.index! + applicationPhase !== ApplicationPhase.BeforeBoundary && + insertionBoundary && + hydrationState === HydrationScriptOutputState.Ready ) { - const bodyEndIndex = bodyEndMatch.index! - pendingClosingTags = chunkString.slice(bodyEndIndex) + if (!appDone && !appBytes && appString === undefined) { + startAppRead() + } + controller.enqueue(output.pullChunk()) + return + } + if ( + applicationPhase === ApplicationPhase.Merge && + hydrationState === HydrationScriptOutputState.Done && + closeCarry === undefined && + hydrationScripts.reserveFastPath(output) + ) { + applicationPhase = ApplicationPhase.PassThrough + stopHydrationOutputListener?.() + stopHydrationOutputListener = undefined + return pumpPassThrough() + } + if (appBytes) { + if (processAppChunk()) { + return + } + continue + } - finalPassThrough.write( - chunkString.slice(0, bodyEndIndex) + - getBufferedRouterStream() + - leftoverHtml, - ) - - leftover = '' - leftoverHtml = '' + if (appDone) { + if (applicationPhase === ApplicationPhase.BeforeBoundary) { + // No <Scripts> boundary was rendered. The document is already + // delivered, so emit the hydration sources after it instead of + // failing the response. + hydrationScripts.skipInitialTake() + applicationPhase = ApplicationPhase.Merge + insertionBoundary = true + continue + } + if (closeCarry) { + // A close prefix that never completed is ordinary content, exactly + // like a document without a canonical close. + const carry = closeCarry + closeCarry = undefined + insertionBoundary = true + if (enqueueAppBytes(carry)) { + return + } + continue + } + if (hydrationState === HydrationScriptOutputState.Waiting) { + await waitForWake() + continue + } + if (applicationPhase === ApplicationPhase.HeldClose) { + controller.enqueue(DOCUMENT_CLOSE_BYTES.slice()) + terminate('complete') + return + } + terminate('complete') return } - let result: RegExpExecArray | null - let lastIndex = 0 - // Reset regex lastIndex since it's global and stateful across exec() calls - patternClosingTag.lastIndex = 0 - while ((result = patternClosingTag.exec(chunkString)) !== null) { - lastIndex = result.index + result[0].length - } + await loadNextAppChunk() + } + } - if (lastIndex > 0) { - const processed = - chunkString.slice(0, lastIndex) + - getBufferedRouterStream() + - leftoverHtml + function handlePumpError(error: unknown) { + if (terminal) { + return + } + console.error('Error processing appStream:', error) + terminate('failure', error) + } - finalPassThrough.write(processed) - leftover = chunkString.slice(lastIndex) - leftoverHtml = '' - } else { - leftover = chunkString - leftoverHtml += getBufferedRouterStream() - } + const stream = new ReadableStream<Uint8Array>({ + start(c) { + controller = c }, - onEnd: () => { - // Don't process if stream was already destroyed/cancelled or cleaned up - if (cleanedUp || finalPassThrough.destroyed) { - return - } - - // Mark the app as done rendering - isAppRendering = false - router.serverSsr!.setRenderFinished() - - // If there are no pending promises, resolve the injectedHtmlDonePromise - if (processingCount === 0) { - injectedHtmlDonePromise.resolve() - } else { - const timeoutMs = opts?.timeoutMs ?? 60000 - timeoutHandle = setTimeout(() => { - injectedHtmlDonePromise.reject( - new Error('Injected HTML timeout after app render finished'), - ) - }, timeoutMs) - } + pull() { + // One async frame per pull: pass-through must stay as cheap as a plain + // read-and-forward loop. + return applicationPhase === ApplicationPhase.PassThrough + ? pumpPassThrough() + : pump().catch(handlePumpError) }, - onError: (error) => { - // Don't process if already cleaned up - if (cleanedUp) { - return - } - - console.error('Error reading appStream:', error) - isAppRendering = false - router.serverSsr!.setRenderFinished() - // Clear timeout to prevent it from firing after error - clearTimeout(timeoutHandle) - // Clear string buffers to prevent memory leaks - leftover = '' - leftoverHtml = '' - routerStreamBuffer = '' - pendingClosingTags = '' - finalPassThrough.destroy(error) - injectedHtmlDonePromise.reject(error) + cancel(reason) { + return terminate('cancel', reason) }, }) - return finalPassThrough.stream + if (hydrationOutput) { + stopHydrationOutputListener = hydrationOutput.subscribe(() => { + if (hydrationOutput.state === HydrationScriptOutputState.Failed) { + terminate('failure', hydrationOutput.error) + return + } + wakePump() + }) + } + disarmLifecycle = armStreamLifecycle( + serverSsr, + opts, + () => terminal, + terminate, + ) + + return stream } diff --git a/packages/router-core/src/ssr/types.ts b/packages/router-core/src/ssr/types.ts index ec0feee41a..48b8c8d0e9 100644 --- a/packages/router-core/src/ssr/types.ts +++ b/packages/router-core/src/ssr/types.ts @@ -3,18 +3,19 @@ import type { MakeRouteMatch } from '../Matches' export interface DehydratedMatch { i: MakeRouteMatch['id'] + /** @internal */ b?: MakeRouteMatch['__beforeLoadContext'] l?: MakeRouteMatch['loaderData'] e?: MakeRouteMatch['error'] u: MakeRouteMatch['updatedAt'] s: MakeRouteMatch['status'] ssr?: MakeRouteMatch['ssr'] + g?: true } export interface DehydratedRouter { manifest: Manifest | undefined dehydratedData?: any - lastMatchId?: string matches: Array<DehydratedMatch> } diff --git a/packages/router-core/src/stores.ts b/packages/router-core/src/stores.ts new file mode 100644 index 0000000000..8c2beeb2e7 --- /dev/null +++ b/packages/router-core/src/stores.ts @@ -0,0 +1,180 @@ +import { arraysEqual, functionalUpdate } from './utils' + +import type { AnyRoute } from './route' +import type { RouterState } from './router' +import type { FullSearchSchema } from './routeInfo' +import type { ParsedLocation } from './location' +import type { AnyRouteMatch } from './Matches' + +export interface RouterReadableStore<TValue> { + get: () => TValue +} + +export interface RouterWritableStore< + TValue, +> extends RouterReadableStore<TValue> { + set: ((updater: (prev: TValue) => TValue) => void) & ((value: TValue) => void) +} + +export type RouterBatchFn = (fn: () => void) => void + +export type MutableStoreFactory = <TValue>( + initialValue: TValue, +) => RouterWritableStore<TValue> + +export type ReadonlyStoreFactory = <TValue>( + read: () => TValue, +) => RouterReadableStore<TValue> + +export type GetStoreConfig = (opts: { isServer?: boolean }) => StoreConfig + +export type StoreConfig = { + createMutableStore: MutableStoreFactory + createReadonlyStore: ReadonlyStoreFactory + batch: RouterBatchFn +} + +type MatchStore = RouterWritableStore<AnyRouteMatch | undefined> +type ReadableStore<TValue> = RouterReadableStore<TValue> + +/** SSR non-reactive createMutableStore */ +export function createNonReactiveMutableStore<TValue>( + initialValue: TValue, +): RouterWritableStore<TValue> { + let value = initialValue + + return { + get() { + return value + }, + set(nextOrUpdater: TValue | ((prev: TValue) => TValue)) { + value = functionalUpdate(nextOrUpdater, value) + }, + } +} + +/** SSR non-reactive createReadonlyStore */ +export function createNonReactiveReadonlyStore<TValue>( + read: () => TValue, +): RouterReadableStore<TValue> { + return { + get() { + return read() + }, + } +} + +export interface RouterStores<in out TRouteTree extends AnyRoute> { + status: RouterWritableStore<RouterState<TRouteTree>['status']> + location: RouterWritableStore<ParsedLocation<FullSearchSchema<TRouteTree>>> + resolvedLocation: RouterWritableStore< + ParsedLocation<FullSearchSchema<TRouteTree>> | undefined + > + ids: RouterWritableStore<Array<string>> + matches: ReadableStore<Array<AnyRouteMatch>> + __store: RouterReadableStore<RouterState<TRouteTree>> + + byRoute: Map<string, MatchStore> + + /** + * Get the stable atom for a route's presented match. The atom remains in the + * pool when the route leaves and contains `undefined` until it re-enters. + */ + getMatchStore: ( + routeId: string, + ) => RouterReadableStore<AnyRouteMatch | undefined> + + setMatches: (nextMatches: Array<AnyRouteMatch>) => void +} + +export function createRouterStores<TRouteTree extends AnyRoute>( + initialLocation: RouterState<TRouteTree>['location'], + config: StoreConfig, +): RouterStores<TRouteTree> { + const { createMutableStore, createReadonlyStore, batch } = config + + // non reactive utilities + const byRoute = new Map<string, MatchStore>() + + // atoms + const status = createMutableStore<RouterState<TRouteTree>['status']>('idle') + const location = createMutableStore(initialLocation) + const resolvedLocation = + createMutableStore<RouterState<TRouteTree>['resolvedLocation']>(undefined) + const ids = createMutableStore<Array<string>>([]) + + // 1st order derived stores + const matches = createReadonlyStore(() => + ids.get().map((id) => byRoute.get(id)!.get()!), + ) + + // compatibility "big" state store + const __store = createReadonlyStore(() => ({ + status: status.get(), + isLoading: status.get() === 'pending', + matches: matches.get(), + location: location.get(), + resolvedLocation: resolvedLocation.get(), + })) + + function getMatchStore(routeId: string): MatchStore { + let matchStore = byRoute.get(routeId) + if (!matchStore) { + matchStore = createMutableStore<AnyRouteMatch | undefined>(undefined) + byRoute.set(routeId, matchStore) + } + return matchStore + } + + const store = { + // atoms + status, + location, + resolvedLocation, + ids, + + // derived + matches, + + // non-reactive state + byRoute, + + // compatibility "big" state + __store, + + // stable per-route presentation atoms + getMatchStore, + + // methods + setMatches, + } + + // setters to update non-reactive utilities in sync with the reactive stores + function setMatches(nextMatches: Array<AnyRouteMatch>) { + const previousIds = ids.get() + const nextIds = nextMatches.map((match) => match.routeId) + + batch(() => { + // Publish lane membership first so framework trees reconcile departures + // before observers of a leaving route receive its tombstone. + if (!arraysEqual(previousIds, nextIds)) { + ids.set(nextIds) + } + + for (const id of previousIds) { + if (!nextIds.includes(id)) { + byRoute.get(id)!.set(() => undefined) + } + } + + for (const nextMatch of nextMatches) { + const matchStore = getMatchStore(nextMatch.routeId) + if (matchStore.get() !== nextMatch) { + matchStore.set(nextMatch) + } + } + }) + } + + return store +} diff --git a/packages/router-core/src/utils.ts b/packages/router-core/src/utils.ts index eb8d3025e7..63aa518695 100644 --- a/packages/router-core/src/utils.ts +++ b/packages/router-core/src/utils.ts @@ -1,3 +1,4 @@ +import { isServer } from '@tanstack/router-core/isServer' import type { RouteIds } from './routeInfo' import type { AnyRouter } from './router' @@ -188,14 +189,10 @@ export type LooseAsyncReturnType<T> = T extends ( * Return the last element of an array. * Intended for non-empty arrays used within router internals. */ -export function last<T>(arr: Array<T>) { +export function last<T>(arr: ReadonlyArray<T>) { return arr[arr.length - 1] } -function isFunction(d: any): d is Function { - return typeof d === 'function' -} - /** * Apply a value-or-updater to a previous value. * Accepts either a literal value or a function of the previous value. @@ -204,119 +201,163 @@ export function functionalUpdate<TPrevious, TResult = TPrevious>( updater: Updater<TPrevious, TResult> | NonNullableUpdater<TPrevious, TResult>, previous: TPrevious, ): TResult { - if (isFunction(updater)) { - return updater(previous) + if (typeof updater === 'function') { + return (updater as Function)(previous) } return updater } -const hasOwn = Object.prototype.hasOwnProperty +export const hasOwn = Object.prototype.hasOwnProperty + +export function hasKeys(obj: Record<string, unknown>) { + for (const key in obj) { + if (hasOwn.call(obj, key)) return true + } + return false +} + +export const createNull = () => Object.create(null) +// Search and params objects use null prototypes so keys like `__proto__` stay data. +export const nullReplaceEqualDeep: typeof replaceEqualDeep = (prev, next) => + replaceEqualDeep(prev, next, true) /** - * This function returns `prev` if `_next` is deeply equal. - * If not, it will replace any deeply equal children of `b` with those of `a`. - * This can be used for structural sharing between immutable JSON values for example. - * Do not use this with signals + * Reuse equal children between immutable plain objects and dense arrays. + * Return `prev` for deeply equal values; otherwise return an object already + * containing the resolved children or create a copy with the shared children. + * Getters and own `__proto__` keys in ordinary object copies are unsupported. + * Do not use this with signals. */ -export function replaceEqualDeep<T>(prev: any, _next: T): T { - if (prev === _next) { +export function replaceEqualDeep<T>( + prev: any, + next: T, + _nullProto?: boolean, + _depth?: number, +): T +export function replaceEqualDeep( + prev: any, + next: any, + _nullProto?: boolean, + _depth = 0, +): any { + if (isServer) { + return next + } + if (prev === next) { return prev } - const next = _next as any + if (_depth++ > 500) { + return next + } - const array = isPlainArray(prev) && isPlainArray(next) + const array = Array.isArray(prev) && Array.isArray(next) - if (!array && !(isPlainObject(prev) && isPlainObject(next))) return next + if (!array && !(isPlainObject(prev) && isPlainObject(next))) { + return next + } - const prevItems = array ? prev : getEnumerableOwnKeys(prev) - if (!prevItems) return next - const nextItems = array ? next : getEnumerableOwnKeys(next) - if (!nextItems) return next - const prevSize = prevItems.length - const nextSize = nextItems.length - const copy: any = array ? new Array(nextSize) : {} + const prevKeys: Array<any> = Object.keys(prev) + const previousCount = prevKeys.length + const nextKeys: Array<any> = Object.keys(next) + const length = nextKeys.length + // Hidden object keys and symbols on next make the value opaque. Arrays + // must have only dense enumerable indices: a hole and an extra key can + // cancel out in the count, so also check the last key of both arrays. + if ( + array + ? previousCount !== prev.length || + length !== next.length || + (previousCount && last(prevKeys) !== `${previousCount - 1}`) || + (length && last(nextKeys) !== `${length - 1}`) + : previousCount !== Object.getOwnPropertyNames(prev).length || + length !== Object.getOwnPropertyNames(next).length || + Object.getOwnPropertySymbols(next).length + ) { + return next + } - let equalItems = 0 + let i = 0 + let child: any + let previous: any + let key: any - for (let i = 0; i < nextSize; i++) { - const key = array ? i : (nextItems[i] as any) - const p = prev[key] - const n = next[key] - - if (p === n) { - copy[key] = p - if (array ? i < prevSize : hasOwn.call(prev, key)) equalItems++ - continue + if (array) { + // Entries before the first difference already resolve to prev. + for (; i < length; i++) { + key = i + previous = prev[key] + child = next[key] + child = + previous === child + ? previous + : typeof previous === 'object' + ? replaceEqualDeep(previous, child, _nullProto, _depth) + : child + if (child !== previous) { + break + } } - - if ( - p === null || - n === null || - typeof p !== 'object' || - typeof n !== 'object' - ) { - copy[key] = n - continue + if (i === length && previousCount === length) { + return prev + } + } else { + let equal = previousCount === length + let unchanged = true + for (; i < length; i++) { + key = nextKeys[i]! + previous = prev[key] + const incoming = next[key] + child = + previous === incoming + ? previous + : typeof previous === 'object' + ? replaceEqualDeep(previous, incoming, _nullProto, _depth) + : incoming + equal &&= + child === previous && (prevKeys[i] === key || hasOwn.call(prev, key)) + unchanged &&= Object.is(child, incoming) + // This key has been checked; its private slot can hold the result. + prevKeys[i] = child + } + if (equal) { + return Object.getOwnPropertySymbols(prev).length ? next : prev + } + if (unchanged) { + return next } - - const v = replaceEqualDeep(p, n) - copy[key] = v - if (v === p) equalItems++ } - return prevSize === nextSize && equalItems === prevSize ? prev : copy + // Reuse the validated array key list; it is private and has the right length. + const copy: any = array ? nextKeys.fill(0) : _nullProto ? createNull() : {} + for (let j = 0; j < length; j++) { + key = array ? j : nextKeys[j]! + if (array) { + previous = prev[key] + if (j > i) { + child = next[key] + child = + previous === child + ? previous + : typeof previous === 'object' + ? replaceEqualDeep(previous, child, _nullProto, _depth) + : child + } + copy[key] = j < i ? previous : child + } else { + copy[key] = prevKeys[j] + } + } + return copy } -/** - * Equivalent to `Reflect.ownKeys`, but ensures that objects are "clone-friendly": - * will return false if object has any non-enumerable properties. - */ -function getEnumerableOwnKeys(o: object) { - const keys = [] - const names = Object.getOwnPropertyNames(o) - for (const name of names) { - if (!Object.prototype.propertyIsEnumerable.call(o, name)) return false - keys.push(name) - } - const symbols = Object.getOwnPropertySymbols(o) - for (const symbol of symbols) { - if (!Object.prototype.propertyIsEnumerable.call(o, symbol)) return false - keys.push(symbol) - } - return keys -} - -// Copied from: https://github.com/jonschlinkert/is-plain-object -export function isPlainObject(o: any) { - if (!hasObjectPrototype(o)) { +export function isPlainObject(o: unknown): boolean { + if (!o || typeof o !== 'object') { return false } - - // If has modified constructor - const ctor = o.constructor - if (typeof ctor === 'undefined') { - return true - } - - // If has modified prototype - const prot = ctor.prototype - if (!hasObjectPrototype(prot)) { - return false - } - - // If constructor does not have an Object-specific method - if (!prot.hasOwnProperty('isPrototypeOf')) { - return false - } - - // Most likely a plain Object - return true -} - -function hasObjectPrototype(o: any) { - return Object.prototype.toString.call(o) === '[object Object]' + // An own constructor is data, so classify the actual prototype. + return (Object.getPrototypeOf(o)?.constructor ?? Object) === Object } /** @@ -327,44 +368,48 @@ export function isPlainArray(value: unknown): value is Array<unknown> { } /** - * Perform a deep equality check with options for partial comparison and - * ignoring `undefined` values. Optimized for router state comparisons. + * Perform a deep equality check optimized for router state comparisons. + * + * - `partial`: `b` may omit keys that `a` has (arrays stay length-exact). + * - `explicitUndefined`: keys holding `undefined` take part in the comparison + * instead of being ignored. + * + * Internal: the flags are positional so hot callers pass no options object. */ export function deepEqual( a: any, b: any, - opts?: { partial?: boolean; ignoreUndefined?: boolean }, + partial?: boolean, + explicitUndefined?: boolean, ): boolean { if (a === b) { return true } - if (typeof a !== typeof b) { - return false - } - if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) return false for (let i = 0, l = a.length; i < l; i++) { - if (!deepEqual(a[i], b[i], opts)) return false + const av = a[i] + const bv = b[i] + if (av !== bv && !deepEqual(av, bv, partial, explicitUndefined)) { + return false + } } return true } if (isPlainObject(a) && isPlainObject(b)) { - const ignoreUndefined = opts?.ignoreUndefined ?? true - - if (opts?.partial) { + if (partial) { for (const k in b) { - if (!ignoreUndefined || b[k] !== undefined) { - if (!deepEqual(a[k], b[k], opts)) return false + if (explicitUndefined || b[k] !== undefined) { + if (!deepEqual(a[k], b[k], partial, explicitUndefined)) return false } } return true } let aCount = 0 - if (!ignoreUndefined) { + if (explicitUndefined) { aCount = Object.keys(a).length } else { for (const k in a) { @@ -372,15 +417,18 @@ export function deepEqual( } } - let bCount = 0 for (const k in b) { - if (!ignoreUndefined || b[k] !== undefined) { - bCount++ - if (bCount > aCount || !deepEqual(a[k], b[k], opts)) return false + if (explicitUndefined || b[k] !== undefined) { + if ( + aCount-- === 0 || + !deepEqual(a[k], b[k], partial, explicitUndefined) + ) { + return false + } } } - return aCount === bCount + return aCount === 0 } return false @@ -473,8 +521,8 @@ export function isPromise<T>( ): value is Promise<Awaited<T>> { return Boolean( value && - typeof value === 'object' && - typeof (value as Promise<T>).then === 'function', + typeof value === 'object' && + typeof (value as Promise<T>).then === 'function', ) } @@ -489,12 +537,36 @@ export function findLast<T>( return undefined } +/** + * Re-encode characters that are unsafe in URL paths. + * Includes ASCII control characters (0x00-0x1F, 0x7F) and a subset of the + * WHATWG URL "path percent-encode set" (", <, >, `, {, }). + * + * Space (0x20) is intentionally excluded — decodeURI decodes %20 to space + * and the router stores decoded spaces in location.pathname. The existing + * encodePathLikeUrl already handles re-encoding spaces for outgoing URLs. + * + * These characters are decoded by decodeURI but must remain percent-encoded + * in paths to match how upstream layers (CDNs, edge middleware, browsers) + * interpret the URL, preventing infinite redirect loops and path mismatches. + */ +// eslint-disable-next-line no-control-regex +const PATH_UNSAFE_RE = /[\x00-\x1f\x7f"<>`{}]/g + +function sanitizePathSegment(segment: string): string { + return segment.replace( + PATH_UNSAFE_RE, + (ch) => '%' + ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0'), + ) +} + function decodeSegment(segment: string): string { + let decoded: string try { - return decodeURI(segment) + decoded = decodeURI(segment) } catch { // if the decoding fails, try to decode the various parts leaving the malformed tags in place - return segment.replaceAll(/%[0-9A-F]{2}/gi, (match) => { + decoded = segment.replaceAll(/%[0-9A-F]{2}/gi, (match) => { try { return decodeURI(match) } catch { @@ -502,19 +574,188 @@ function decodeSegment(segment: string): string { } }) } + return sanitizePathSegment(decoded) } -export function decodePath(path: string, decodeIgnore?: Array<string>): string { - if (!path) return path - const re = decodeIgnore - ? new RegExp(`${decodeIgnore.join('|')}`, 'gi') - : /%25|%5C/gi - let cursor = 0 - let result = '' - let match - while (null !== (match = re.exec(path))) { - result += decodeSegment(path.slice(cursor, match.index)) + match[0] - cursor = re.lastIndex +/** + * Default list of URL protocols to allow in links, redirects, and navigation. + * Any absolute URL protocol not in this list is treated as dangerous by default. + */ +export const DEFAULT_PROTOCOL_ALLOWLIST = [ + // Standard web navigation + 'http:', + 'https:', + + // Common browser-safe actions + 'mailto:', + 'tel:', +] + +/** + * Extract the explicit URL scheme, including its colon, using WHATWG + * normalization rules. This does not validate the rest of the URL. + * + * Returning `undefined` means "no explicit scheme", not "safe URL"; + * protocol-relative URLs such as "//evil.example" require a separate check. + */ +export function getUrlScheme(url: string): string | undefined { + if (url[0] === '/') { + return undefined } - return result + decodeSegment(cursor ? path.slice(cursor) : path) + if (!url.includes(':')) { + return undefined + } + // WHATWG strips leading C0/space and TAB/LF/CR within a scheme. + // Match the prefix first so relative paths and URL bodies need no copying. + // eslint-disable-next-line no-control-regex + return /^[\x00-\x20]*([a-z][a-z\d+.\t\n\r-]*:)/i + .exec(url)?.[1] + ?.replace(/[\t\n\r]/g, '') + .toLowerCase() +} + +// Match protocol-relative URLs such as "//evil.example", including backslash +// and control-character variants. Stop at the second separator so validation +// does not scan or normalize the URL body. +// eslint-disable-next-line no-control-regex +export const protocolRelativePrefixRegex = /^[\x00-\x20]*[\\/][\t\n\r]*[\\/]/ + +/** + * Check if a URL string uses a protocol that is not in the allowlist or is + * protocol-relative (e.g. "//evil.example"), which can navigate to another host. + * Returns true for blocked protocols like javascript:, blob:, and data:, as + * well as slash/backslash variants of protocol-relative URLs. + * + * Scheme parsing normalizes: + * - Mixed case (JavaScript: → javascript:) + * - Whitespace/control characters (java\nscript: → javascript:) + * - Leading whitespace + * + * For relative URLs without a protocol-relative prefix, returns false. + * + * @param url - The URL string to check + * @param allowlist - Set of protocols to allow + * @returns true if the URL uses a protocol that is not allowed or can escape + * the current origin through a protocol-relative URL + */ +export function isDangerousProtocol( + url: string, + allowlist: Set<string>, +): boolean { + if (!url) return false + + // Inputs like "/\evil.example" can navigate to another host just like + // "//evil.example", even with leading whitespace or ignored control characters. + if (protocolRelativePrefixRegex.test(url)) { + return true + } + + const scheme = getUrlScheme(url) + return scheme ? !allowlist.has(scheme) : false +} + +// This utility is based on https://github.com/zertosh/htmlescape +// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE +const HTML_ESCAPE_LOOKUP: { [match: string]: string } = { + '&': '\\u0026', + '>': '\\u003e', + '<': '\\u003c', + '\u2028': '\\u2028', + '\u2029': '\\u2029', +} + +const HTML_ESCAPE_REGEX = /[&><\u2028\u2029]/g + +/** + * Escape HTML special characters in a string to prevent XSS attacks + * when embedding strings in script tags during SSR. + * + * This is essential for preventing XSS vulnerabilities when user-controlled + * content is embedded in inline scripts. + */ +export function escapeHtml(str: string): string { + return str.replace(HTML_ESCAPE_REGEX, (match) => HTML_ESCAPE_LOOKUP[match]!) +} + +// Decode component data only. Leave protocol-relative URL handling to callers; +// this decoder also receives fragments, where slashes and backslashes are data. +export function decodePath(path: string) { + if (!path) { + return path + } + let result = path + // eslint-disable-next-line no-control-regex + if (/[%\\\x00-\x1f\x7f]/.test(path)) { + const re = /%25|%5C/gi + let cursor = 0 + let match + result = '' + while (null !== (match = re.exec(path))) { + result += decodeSegment(path.slice(cursor, match.index)) + match[0] + cursor = re.lastIndex + } + result += decodeSegment(cursor ? path.slice(cursor) : path) + } + + return result +} + +/** + * Encodes a path the same way `new URL()` would, but without the overhead of full URL parsing. + * + * This function encodes: + * - Whitespace characters (spaces → %20, tabs → %09, etc.) + * - Non-ASCII/Unicode characters (emojis, accented characters, etc.) + * + * It preserves: + * - Already percent-encoded sequences (won't double-encode %2F, %25, etc.) + * - ASCII special characters valid in URL paths (@, $, &, +, etc.) + * - Forward slashes as path separators + * + * Used to generate proper href values for SSR without constructing URL objects. + * + * @example + * encodePathLikeUrl('/path/file name.pdf') // '/path/file%20name.pdf' + * encodePathLikeUrl('/path/日本語') // '/path/%E6%97%A5%E6%9C%AC%E8%AA%9E' + * encodePathLikeUrl('/path/already%20encoded') // '/path/already%20encoded' (preserved) + */ +export function encodePathLikeUrl(path: string): string { + // Encode whitespace and non-ASCII characters that browsers encode in URLs. + // The test uses one character class: it matches the same code units as the + // replacement pattern below and is cheaper than the alternation. + if (!/[\s\u0080-\uFFFF]/.test(path)) { + return path + } + // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ASCII range check + // eslint-disable-next-line no-control-regex + return path.replace(/\s|[^\u0000-\u007F]/gu, encodeURIComponent) +} + +/** + * Builds the dev-mode CSS styles URL for route-scoped CSS collection. + * Used by HeadContent components in all framework implementations to construct + * the URL for the `/@tanstack-start/styles.css` endpoint. + * + * @param basepath - The router's basepath (may or may not have leading slash) + * @param routeIds - Array of matched route IDs to include in the CSS collection + * @returns The full URL path for the dev styles CSS endpoint + */ +export function buildDevStylesUrl( + basepath: string, + routeIds: Array<string>, +): string { + // Trim all leading and trailing slashes from basepath + const trimmedBasepath = basepath.replace(/^\/+|\/+$/g, '') + // Build normalized basepath: empty string for root, or '/path' for non-root + const normalizedBasepath = trimmedBasepath === '' ? '' : `/${trimmedBasepath}` + return `${normalizedBasepath}/@tanstack-start/styles.css?routes=${encodeURIComponent(routeIds.join(','))}` +} + +export function arraysEqual<T>(a: Array<T>, b: Array<T>) { + if (a === b) return true + if (a.length !== b.length) return false + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false + } + return true } diff --git a/packages/router-core/tests/RawStream.test.ts b/packages/router-core/tests/RawStream.test.ts new file mode 100644 index 0000000000..aa3a2aca48 --- /dev/null +++ b/packages/router-core/tests/RawStream.test.ts @@ -0,0 +1,628 @@ +import { describe, expect, it, vi } from 'vitest' +import { + createStream, + crossSerializeStream, + toCrossJSONAsync, + toCrossJSONStream, + fromCrossJSON, +} from 'seroval' +import type { SerovalNode } from 'seroval' +import { RawStream } from '../src/ssr/serializer/RawStream' +import { + RawStreamJSONDeserializePlugin, + RawStreamJSONPlugin, + createRawStreamJSONPlugin, +} from '../src/ssr/serializer/RawStreamJSONPlugin' +import { + createRawStreamDeserializePlugin, + createRawStreamRPCPlugin, +} from '../src/ssr/serializer/RawStreamRPCPlugin' +import { RawStreamSSRPlugin } from '../src/ssr/serializer/RawStreamSSRPlugin' +import { + defaultSerovalDeserializerPlugins, + defaultSerovalPlugins, +} from '../src/ssr/serializer/seroval-plugins' + +type EncodedStream = ReturnType<typeof createStream<any>> +type EncodedStreamListener = Parameters<EncodedStream['on']>[0] +type RawStreamFactory = (stream: EncodedStream) => ReadableStream<Uint8Array> + +function getRawStreamFactory( + pluginIndex: number, + emitted: boolean, +): RawStreamFactory { + if (emitted) { + const plugin = RawStreamSSRPlugin.extends![pluginIndex]! + const source = (plugin.serialize as () => string)() + return new Function(`return ${source}`)() as RawStreamFactory + } + + return (stream) => { + const textNode = {} as SerovalNode + const streamNode = {} as SerovalNode + return (RawStreamJSONDeserializePlugin.deserialize as any)( + { text: textNode, stream: streamNode }, + { + deserialize(node: SerovalNode) { + return node === textNode ? pluginIndex === 1 : stream + }, + }, + ) + } +} + +function createTrackedEncodedStream() { + const listeners = new Set<EncodedStreamListener>() + let unsubscribeCalls = 0 + const stream: EncodedStream = { + __SEROVAL_STREAM__: true, + on(listener) { + listeners.add(listener) + let subscribed = true + return () => { + if (subscribed) { + subscribed = false + unsubscribeCalls++ + listeners.delete(listener) + } + } + }, + next(value) { + for (const listener of listeners) { + listener.next(value) + } + }, + throw(value) { + for (const listener of listeners) { + listener.throw(value) + } + listeners.clear() + }, + return(value) { + for (const listener of listeners) { + listener.return(value) + } + listeners.clear() + }, + } + return { + stream, + get listenerCount() { + return listeners.size + }, + get unsubscribeCalls() { + return unsubscribeCalls + }, + } +} + +describe('RawStream', () => { + describe('RawStream class', () => { + it('should wrap a ReadableStream<Uint8Array>', () => { + const stream = new ReadableStream<Uint8Array>({ + start(controller) { + controller.enqueue(new Uint8Array([1, 2, 3])) + controller.close() + }, + }) + const rawStream = new RawStream(stream) + expect(rawStream.stream).toBe(stream) + }) + + it('should be an instance of RawStream', () => { + const stream = new ReadableStream<Uint8Array>() + const rawStream = new RawStream(stream) + expect(rawStream instanceof RawStream).toBe(true) + }) + + it('should default to binary hint', () => { + const stream = new ReadableStream<Uint8Array>() + const rawStream = new RawStream(stream) + expect(rawStream.hint).toBe('binary') + }) + + it('should accept binary hint option', () => { + const stream = new ReadableStream<Uint8Array>() + const rawStream = new RawStream(stream, { hint: 'binary' }) + expect(rawStream.hint).toBe('binary') + }) + + it('should accept text hint option', () => { + const stream = new ReadableStream<Uint8Array>() + const rawStream = new RawStream(stream, { hint: 'text' }) + expect(rawStream.hint).toBe('text') + }) + }) + + describe('createRawStreamRPCPlugin', () => { + it('should call onRawStream callback with stream id and stream', () => { + const collectedStreams = new Map<number, ReadableStream<Uint8Array>>() + + const plugin = createRawStreamRPCPlugin((id, stream) => { + collectedStreams.set(id, stream) + }) + + const testStream = new ReadableStream<Uint8Array>({ + start(controller) { + controller.enqueue(new Uint8Array([1, 2, 3])) + controller.close() + }, + }) + + const rawStream = new RawStream(testStream) + + toCrossJSONStream(rawStream, { + refs: new Map(), + plugins: [plugin], + onParse() {}, + }) + + expect(collectedStreams.size).toBe(1) + // Stream ID is assigned by our internal counter (sequential starting at 1) + const streamEntry = Array.from(collectedStreams.entries())[0] + expect(streamEntry).toBeDefined() + expect(streamEntry![1]).toBe(testStream) + }) + + it('should serialize with tss/RawStream tag', () => { + const plugin = createRawStreamRPCPlugin(() => {}) + + const testStream = new ReadableStream<Uint8Array>() + const rawStream = new RawStream(testStream) + + const serialized = new Array<unknown>() + toCrossJSONStream(rawStream, { + refs: new Map(), + plugins: [plugin], + onParse(value) { + serialized.push(value) + }, + }) + + // The serialized output should have the plugin tag and contain streamId + const jsonStr = JSON.stringify(serialized) + expect(jsonStr).toContain('tss/RawStream') + expect(jsonStr).toContain('streamId') + }) + + it('should collect multiple streams with unique ids', () => { + const collectedStreams = new Map<number, ReadableStream<Uint8Array>>() + + const plugin = createRawStreamRPCPlugin((id, stream) => { + collectedStreams.set(id, stream) + }) + + const stream1 = new ReadableStream<Uint8Array>() + const stream2 = new ReadableStream<Uint8Array>() + + const data = { + first: new RawStream(stream1), + second: new RawStream(stream2), + } + + toCrossJSONStream(data, { + refs: new Map(), + plugins: [plugin], + onParse() {}, + }) + + expect(collectedStreams.size).toBe(2) + const ids = Array.from(collectedStreams.keys()) + expect(ids[0]).not.toBe(ids[1]) + }) + }) + + describe('round-trip serialization', () => { + it('does not acquire the source reader when hint parsing fails', async () => { + const getReader = vi.fn() + const stream = { getReader } as unknown as ReadableStream<Uint8Array> + const failure = new Error('hint parse failed') + const parse = RawStreamJSONPlugin.parse.async! as any + + await expect( + parse(new RawStream(stream), { + parse: () => Promise.reject(failure), + }), + ).rejects.toBe(failure) + expect(getReader).not.toHaveBeenCalled() + }) + + it('does not acquire the source reader when request serialization is already aborted', async () => { + const getReader = vi.fn() + const stream = { getReader } as unknown as ReadableStream<Uint8Array> + const controller = new AbortController() + const reason = new Error('request aborted') + controller.abort(reason) + + await expect( + toCrossJSONAsync(new RawStream(stream), { + refs: new Map(), + plugins: [createRawStreamJSONPlugin(controller.signal)], + }), + ).rejects.toMatchObject({ cause: reason }) + expect(getReader).not.toHaveBeenCalled() + }) + + it('preserves malformed UTF-8 and BOM bytes in text chunks', async () => { + const cancel = vi.fn() + const stream = new ReadableStream<Uint8Array>({ + start(controller) { + controller.enqueue(Uint8Array.of(0x41, 0xe2)) + controller.enqueue(Uint8Array.of(0x28)) + controller.enqueue(Uint8Array.of(0xef, 0xbb, 0xbf, 0x42)) + controller.close() + }, + cancel, + }) + + const serialized = await new Promise<Array<string>>((resolve, reject) => { + const sources = new Array<string>() + crossSerializeStream(new RawStream(stream, { hint: 'text' }), { + refs: new Map(), + plugins: [RawStreamSSRPlugin], + scopeId: 'raw-stream-test', + onSerialize(source) { + sources.push(source) + }, + onError: reject, + onDone() { + expect(stream.locked).toBe(false) + resolve(sources) + }, + }) + }) + + const output = serialized.join(';') + expect(output).toContain('QeI=') + expect(output).toContain('\ufeffB') + expect(cancel).not.toHaveBeenCalled() + expect(stream.locked).toBe(false) + }) + + it('preserves a UTF-8 character split across text chunks', async () => { + // Each half is invalid UTF-8 by itself. Text mode must encode both as + // binary instead of retaining decoder state across chunk boundaries. + const expected = [Uint8Array.of(0xf0, 0x9f), Uint8Array.of(0x98, 0x80)] + const input = new ReadableStream<Uint8Array>({ + start(controller) { + for (const chunk of expected) { + controller.enqueue(chunk) + } + controller.close() + }, + }) + + const serialized = await toCrossJSONAsync( + new RawStream(input, { hint: 'text' }), + { + refs: new Map(), + plugins: [RawStreamJSONPlugin], + }, + ) + const output = fromCrossJSON(serialized, { + refs: new Map(), + plugins: [RawStreamJSONDeserializePlugin], + }) as ReadableStream<Uint8Array> + const reader = output.getReader() + + await expect(reader.read()).resolves.toEqual({ + done: false, + value: expected[0], + }) + await expect(reader.read()).resolves.toEqual({ + done: false, + value: expected[1], + }) + await expect(reader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it.each([ + ['default', 'binary', defaultSerovalDeserializerPlugins], + ['default', 'text', defaultSerovalDeserializerPlugins], + ['deserialize-only', 'binary', [RawStreamJSONDeserializePlugin]], + ['deserialize-only', 'text', [RawStreamJSONDeserializePlugin]], + ] as const)( + 'preserves every %s-plugin decoded %s-hinted chunk through async JSON', + async (_, hint, deserializePlugins) => { + const expected = [ + new Uint8Array(), + Uint8Array.of(0x41, 0x42), + Uint8Array.of(0x41, 0xe2), + Uint8Array.of(0xef, 0xbb, 0xbf, 0x42), + ] + const input = new ReadableStream<Uint8Array>({ + start(controller) { + for (const chunk of expected) { + controller.enqueue(chunk) + } + controller.close() + }, + }) + + const serialized = await toCrossJSONAsync( + new RawStream(input, { hint }), + { + refs: new Map(), + plugins: [RawStreamJSONPlugin], + }, + ) + const output = fromCrossJSON(serialized, { + refs: new Map(), + plugins: [...deserializePlugins], + }) as ReadableStream<Uint8Array> + const reader = output.getReader() + const actual: Array<Uint8Array> = [] + + while (true) { + const next = await reader.read() + if (next.done) { + break + } + actual.push(next.value) + } + + expect(actual.map((chunk) => Array.from(chunk))).toEqual( + expected.map((chunk) => Array.from(chunk)), + ) + }, + ) + + it('round-trips: client default plugins write, deserializer plugins read', async () => { + const input = new ReadableStream<Uint8Array>({ + start(controller) { + controller.enqueue(Uint8Array.of(1, 2, 3)) + controller.close() + }, + }) + const serialized = await toCrossJSONAsync( + { stream: new RawStream(input), error: new Error('boom') }, + { refs: new Map(), plugins: defaultSerovalPlugins }, + ) + const output = fromCrossJSON(serialized, { + refs: new Map(), + plugins: defaultSerovalDeserializerPlugins, + }) as { stream: ReadableStream<Uint8Array>; error: Error } + + expect(output.error).toBeInstanceOf(Error) + expect(output.error.message).toBe('boom') + const reader = output.stream.getReader() + await expect(reader.read()).resolves.toEqual({ + done: false, + value: Uint8Array.of(1, 2, 3), + }) + await expect(reader.read()).resolves.toMatchObject({ done: true }) + }) + + it('should serialize and deserialize RawStream correctly', async () => { + // Collect streams during serialization + const collectedStreams = new Map<number, ReadableStream<Uint8Array>>() + const rpcPlugin = createRawStreamRPCPlugin((id, stream) => { + collectedStreams.set(id, stream) + }) + + const testStream = new ReadableStream<Uint8Array>({ + start(controller) { + controller.enqueue(new Uint8Array([1, 2, 3])) + controller.close() + }, + }) + + const data = { + message: 'test', + rawData: new RawStream(testStream), + } + + // Serialize using RPC plugin + const refs = new Map() + let serialized: SerovalNode | undefined + toCrossJSONStream(data, { + refs, + plugins: [rpcPlugin], + onParse(value) { + serialized = value + }, + }) + + // Verify we collected the stream + expect(collectedStreams.size).toBe(1) + const streamId = Array.from(collectedStreams.keys())[0]! + + // Create getOrCreateStream function + const getOrCreateStream = (id: number) => { + const stream = collectedStreams.get(id) + if (!stream) { + throw new Error(`Stream ${id} not found in collected streams`) + } + return stream + } + + // Create deserialize plugin with function + const deserializePlugin = + createRawStreamDeserializePlugin(getOrCreateStream) + + // Deserialize + const deserialized = fromCrossJSON(serialized!, { + refs: new Map(), + plugins: [deserializePlugin], + }) as any + + expect(deserialized.message).toBe('test') + expect(deserialized.rawData).toBe(testStream) + }) + }) + + describe('SSR stream lifecycle', () => { + it.each(['chunk', 'eof', 'error'] as const)( + 'ignores a late %s read result after disposal', + async (settlement) => { + let resolveRead!: (result: ReadableStreamReadResult<Uint8Array>) => void + let rejectRead!: (error: unknown) => void + const readResult = new Promise<ReadableStreamReadResult<Uint8Array>>( + (resolve, reject) => { + resolveRead = resolve + rejectRead = reject + }, + ) + const reader = { + read: vi.fn(() => readResult), + cancel: vi.fn(() => Promise.resolve()), + releaseLock: vi.fn(), + } + const readable = { + getReader: () => reader, + } as unknown as ReadableStream<Uint8Array> + const sources = new Array<string>() + const dispose = crossSerializeStream(new RawStream(readable), { + refs: new Map(), + plugins: [RawStreamSSRPlugin], + scopeId: 'raw-stream-disposal-test', + onSerialize(source) { + sources.push(source) + }, + }) + + expect(reader.read).toHaveBeenCalledTimes(1) + const sourceCount = sources.length + dispose() + dispose() + expect(reader.cancel).toHaveBeenCalledTimes(1) + expect(reader.releaseLock).toHaveBeenCalledTimes(1) + + if (settlement === 'error') { + rejectRead(new Error('late read failure')) + } else { + resolveRead( + settlement === 'eof' + ? { done: true, value: undefined } + : { done: false, value: Uint8Array.of(1) }, + ) + } + await Promise.resolve() + await Promise.resolve() + + expect(sources).toHaveLength(sourceCount) + expect(reader.read).toHaveBeenCalledTimes(1) + expect(reader.cancel).toHaveBeenCalledTimes(1) + expect(reader.releaseLock).toHaveBeenCalledTimes(1) + }, + ) + }) + + describe.each([ + { hint: 'binary', pluginIndex: 0, encoded: 'QQ==' }, + { hint: 'text', pluginIndex: 1, encoded: 'tA' }, + ] as const)('$hint browser factory', ({ pluginIndex, encoded }) => { + it.each([ + ['local', false], + ['emitted', true], + ] as const)( + 'unsubscribes the %s factory on cancellation', + async (_, emitted) => { + const factory = getRawStreamFactory(pluginIndex, emitted) + const encodedStream = createTrackedEncodedStream() + const output = factory(encodedStream.stream) + const reader = output.getReader() + + expect(encodedStream.listenerCount).toBe(1) + encodedStream.stream.next(encoded) + const chunk = await reader.read() + expect(chunk.done).toBe(false) + expect(Array.from(chunk.value!)).toEqual([65]) + + await reader.cancel() + await reader.cancel() + expect(encodedStream.unsubscribeCalls).toBe(1) + expect(encodedStream.listenerCount).toBe(0) + + encodedStream.stream.next(encoded) + expect(encodedStream.listenerCount).toBe(0) + }, + ) + + it.each([ + ['local', false], + ['emitted', true], + ] as const)( + 'does not retain a synchronous terminal disposer in the %s factory', + async (_, emitted) => { + const unsubscribe = vi.fn() + const stream = { + __SEROVAL_STREAM__: true, + on(listener: EncodedStreamListener) { + listener.next(encoded) + listener.return(undefined) + return unsubscribe + }, + next() {}, + throw() {}, + return() {}, + } as EncodedStream + const reader = getRawStreamFactory( + pluginIndex, + emitted, + )(stream).getReader() + + expect(unsubscribe).toHaveBeenCalledTimes(emitted ? 0 : 1) + await reader.cancel() + expect(unsubscribe).toHaveBeenCalledTimes(emitted ? 0 : 1) + }, + ) + + it.each([false, true])( + 'disposes a malformed buffered JSON stream (ended: %s)', + async (ended) => { + const stream = createStream<string | undefined>() + stream.next(pluginIndex === 1 ? 'b%' : '%') + stream.next(encoded) + if (ended) { + stream.return(undefined) + } + const on = stream.on.bind(stream) + const unsubscribe = vi.fn() + vi.spyOn(stream, 'on').mockImplementation((listener) => { + unsubscribe.mockImplementation(on(listener)) + return unsubscribe + }) + + const reader = getRawStreamFactory( + pluginIndex, + false, + )(stream).getReader() + + expect(unsubscribe).toHaveBeenCalledOnce() + await expect(reader.read()).rejects.toMatchObject({ + name: 'InvalidCharacterError', + }) + stream.next(encoded) + await expect(reader.cancel()).rejects.toMatchObject({ + name: 'InvalidCharacterError', + }) + expect(unsubscribe).toHaveBeenCalledOnce() + reader.releaseLock() + }, + ) + + it.each([ + ['local', false], + ['emitted', true], + ] as const)( + 'does not retain a live terminal disposer in the %s factory', + async (_, emitted) => { + const encodedStream = createTrackedEncodedStream() + const reader = getRawStreamFactory( + pluginIndex, + emitted, + )(encodedStream.stream).getReader() + + encodedStream.stream.next(encoded) + encodedStream.stream.return(undefined) + await reader.cancel() + + expect(encodedStream.unsubscribeCalls).toBe(0) + }, + ) + }) +}) diff --git a/packages/router-core/tests/asset-projection-order.test.ts b/packages/router-core/tests/asset-projection-order.test.ts new file mode 100644 index 0000000000..0748895afe --- /dev/null +++ b/packages/router-core/tests/asset-projection-order.test.ts @@ -0,0 +1,121 @@ +import { createMemoryHistory } from '@tanstack/history' +import { describe, expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' +import type { AnyRouteMatch } from '../src' + +type AssetContext = { + matches: Array<AnyRouteMatch> + match: AnyRouteMatch +} + +function setup(isServer = false) { + const parentHead = vi.fn((_context: AssetContext) => ({ + meta: [{ title: 'Parent' }], + })) + const parentScripts = vi.fn((_context: AssetContext) => [ + { children: 'window.parent = true' }, + ]) + const childHead = vi.fn(({ matches, match }: AssetContext) => { + const parentMatch = matches[match.index - 1] + const parentTitle = (parentMatch?.meta as Array<{ title?: string }>)[0] + ?.title + return { meta: [{ title: `${parentTitle} | Child` }] } + }) + const childScripts = vi.fn(({ matches, match }: AssetContext) => { + const parentMatch = matches[match.index - 1] + const parentScript = ( + parentMatch?.scripts as Array<{ children?: string }> | undefined + )?.[0]?.children + return [{ children: `${parentScript}; window.child = true` }] + }) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + head: parentHead, + scripts: parentScripts, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + head: childHead, + scripts: childScripts, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer, + }) + + return { + parentHead, + parentScripts, + childHead, + childScripts, + parentRoute, + childRoute, + router, + } +} + +function expectSequentialProjection(result: ReturnType<typeof setup>): void { + expect(result.parentHead).toHaveBeenCalledTimes(1) + expect(result.parentScripts).toHaveBeenCalledTimes(1) + expect(result.childHead).toHaveBeenCalledTimes(1) + expect(result.childScripts).toHaveBeenCalledTimes(1) + + const childHeadContext = result.childHead.mock.calls[0]![0] + expect(childHeadContext.match.routeId).toBe(result.childRoute.id) + expect( + childHeadContext.matches[childHeadContext.match.index - 1], + ).toMatchObject({ + routeId: result.parentRoute.id, + meta: [{ title: 'Parent' }], + }) + + const childScriptsContext = result.childScripts.mock.calls[0]![0] + expect(childScriptsContext.match.routeId).toBe(result.childRoute.id) + expect( + childScriptsContext.matches[childScriptsContext.match.index - 1], + ).toMatchObject({ + routeId: result.parentRoute.id, + scripts: [{ children: 'window.parent = true' }], + }) + + expect( + result.router.state.matches.find( + (match) => match.routeId === result.parentRoute.id, + ), + ).toMatchObject({ + meta: [{ title: 'Parent' }], + scripts: [{ children: 'window.parent = true' }], + }) + expect( + result.router.state.matches.find( + (match) => match.routeId === result.childRoute.id, + ), + ).toMatchObject({ + meta: [{ title: 'Parent | Child' }], + scripts: [{ children: 'window.parent = true; window.child = true' }], + }) +} + +describe('asset projection order', () => { + test('client calls head and scripts sequentially from parent to child', async () => { + const result = setup() + + await result.router.load() + + expectSequentialProjection(result) + }) + + test('server calls head and scripts sequentially from parent to child', async () => { + const result = setup(true) + + const response = await loadServerResponse(result.router, '/parent/child') + + expect(response.status).toBe(200) + expectSequentialProjection(result) + }) +}) diff --git a/packages/router-core/tests/background-assets-stale.test.ts b/packages/router-core/tests/background-assets-stale.test.ts new file mode 100644 index 0000000000..1c39969185 --- /dev/null +++ b/packages/router-core/tests/background-assets-stale.test.ts @@ -0,0 +1,79 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +describe('background decorative asset failure', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(0) + }) + + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + test('commits fresh loader data while preserving the previous projected assets', async () => { + const projectionError = new Error('head projection failed') + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + let resolveStaleReload!: (data: { title: string }) => void + let loaderCalls = 0 + const loader = () => { + loaderCalls += 1 + if (loaderCalls === 1) { + return { title: 'old' } + } + + return new Promise<{ title: string }>((resolve) => { + resolveStaleReload = resolve + }) + } + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + head: ({ loaderData }) => { + // The loader always resolves before head runs in this test, so + // loaderData is never undefined here. + if (loaderData!.title === 'fresh') { + throw projectionError + } + + return { + meta: [{ title: loaderData!.title }], + } + }, + staleTime: 0, + gcTime: 60_000, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + const matchId = router.state.matches.find( + (match) => match.routeId === fooRoute.id, + )!.id + const getMatch = () => + router.state.matches.find((match) => match.id === matchId) + + expect(getMatch()?.loaderData).toEqual({ title: 'old' }) + expect(getMatch()?.meta).toEqual([{ title: 'old' }]) + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await vi.waitFor(() => expect(loaderCalls).toBe(2)) + + resolveStaleReload({ title: 'fresh' }) + await vi.waitFor(() => + expect(getMatch()?.loaderData).toEqual({ title: 'fresh' }), + ) + + expect(getMatch()?.meta).toEqual([{ title: 'old' }]) + expect(log).toHaveBeenCalledWith(projectionError) + }) +}) diff --git a/packages/router-core/tests/background-trim-abort.test.ts b/packages/router-core/tests/background-trim-abort.test.ts new file mode 100644 index 0000000000..7d23824972 --- /dev/null +++ b/packages/router-core/tests/background-trim-abort.test.ts @@ -0,0 +1,246 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +test.each(['success', 'error', 'notFound'] as const)( + 'departure after a background %s preserves lifecycle membership and current data', + async (outcome) => { + let revision = 0 + const onLeave = vi.fn() + const childOnLeave = vi.fn() + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + revision++ + if (revision > 1 && outcome !== 'success') { + throw outcome === 'error' ? new Error('reload failed') : notFound() + } + return revision + }, + errorComponent: () => null, + notFoundComponent: () => null, + onLeave, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + onLeave: childOnLeave, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const history = createMemoryHistory({ initialEntries: ['/parent/child'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + otherRoute, + ]), + history, + }) + try { + await router.load() + await router.invalidate() + await expect.poll(() => router.state.matches[1]?.status).toBe(outcome) + if (outcome === 'success') { + await expect.poll(() => router.state.matches[1]?.loaderData).toBe(2) + } + expect(childOnLeave).not.toHaveBeenCalled() + await router.navigate({ to: '/other' }) + expect(childOnLeave).toHaveBeenCalledOnce() + expect(onLeave).toHaveBeenCalledOnce() + expect(onLeave.mock.calls[0]![0]).toMatchObject({ + status: outcome, + ...(outcome === 'success' && { loaderData: 2 }), + }) + await router.invalidate() + expect(childOnLeave).toHaveBeenCalledOnce() + } finally { + history.destroy() + } + }, +) + +test('a background boundary keeps the matched branch and its lifecycle stable', async () => { + let parentLoads = 0 + const parentError = new Error('parent background reload failed') + const childOnEnter = vi.fn() + const childOnLeave = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + if (++parentLoads === 2) { + throw parentError + } + return `parent data ${parentLoads}` + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => { + return 'child data' + }, + onEnter: childOnEnter, + onLeave: childOnLeave, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + await router.invalidate() + + await expect.poll(() => router.state.matches[1]?.status).toBe('error') + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]) + expect(router.state.matches[1]).toMatchObject({ + status: 'error', + error: parentError, + }) + expect(router.state.matches[2]).toMatchObject({ + status: 'success', + loaderData: 'child data', + }) + expect(childOnEnter).toHaveBeenCalledTimes(1) + expect(childOnLeave).not.toHaveBeenCalled() + + await router.invalidate() + await expect.poll(() => router.state.matches[1]?.status).toBe('success') + expect(childOnEnter).toHaveBeenCalledTimes(1) + expect(childOnLeave).not.toHaveBeenCalled() +}) + +test('a background notFound stays private until its parent boundary is ready', async () => { + const boundaryReady = createControlledPromise<void>() + const ParentNotFound = Object.assign(() => null, { + preload: () => boundaryReady, + }) + let childLoads = 0 + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + notFoundComponent: ParentNotFound, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => { + if (++childLoads > 1) { + throw notFound() + } + return 'initial child data' + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + await router.invalidate({ + filter: (match) => match.routeId === childRoute.id, + }) + await vi.waitFor(() => expect(childLoads).toBe(2)) + + expect(router.state.matches.map((match) => match.status)).toEqual([ + 'success', + 'success', + 'success', + ]) + + boundaryReady.resolve() + await vi.waitFor(() => { + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]) + expect(router.state.matches[1]?.status).toBe('notFound') + expect(router.state.matches[2]?.status).toBe('success') + }) +}) + +test('foreground supersession aborts every loader in a background batch', async () => { + let parentLoads = 0 + let childLoads = 0 + const backgroundSignals: Array<AbortSignal> = [] + + const waitForAbort = (signal: AbortSignal) => + new Promise<never>((_resolve, reject) => { + signal.addEventListener( + 'abort', + () => { + const error = new Error('aborted') + error.name = 'AbortError' + reject(error) + }, + { once: true }, + ) + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: ({ abortController }) => { + if (++parentLoads > 1) { + backgroundSignals.push(abortController.signal) + return waitForAbort(abortController.signal) + } + return 'initial parent data' + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: ({ abortController }) => { + if (++childLoads > 1) { + backgroundSignals.push(abortController.signal) + return waitForAbort(abortController.signal) + } + return 'initial child data' + }, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + otherRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + const revalidation = router.invalidate() + await vi.waitFor(() => expect(backgroundSignals).toHaveLength(2)) + + await router.navigate({ to: '/other' }) + await revalidation + + expect(backgroundSignals[0]).not.toBe(backgroundSignals[1]) + expect(backgroundSignals.every((signal) => signal.aborted)).toBe(true) + expect(router.state.matches.at(-1)?.routeId).toBe(otherRoute.id) +}) diff --git a/packages/router-core/tests/blocked-navigation-current-load.test.ts b/packages/router-core/tests/blocked-navigation-current-load.test.ts new file mode 100644 index 0000000000..e307f35934 --- /dev/null +++ b/packages/router-core/tests/blocked-navigation-current-load.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * A history blocker can discard a navigation commit AFTER + * buildAndCommitLocation set router._pendingLocation (it is cleared a + * microtask later). A continuation of the still-current in-flight load that + * resumes inside that window must not treat the merely-built location as + * ownership loss: a blocked commit never starts a replacement load, so + * abandoning the pass would leave the router with status 'pending', + * isLoading true, and a populated pending pool forever. + */ + +describe('blocked navigation does not cancel the current load', () => { + test('loader continuation resuming while a blocked navigation is built still commits', async () => { + const loaderGate = createControlledPromise<string>() + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const slowRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/slow', + loader: () => loaderGate, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, slowRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + // Framework transitioners turn committed history changes into router + // loads. A blocked commit never reaches this subscriber. + const unsubscribe = router.history.subscribe(router.load) + let unblock: (() => void) | undefined + + try { + const navigation = router.navigate({ to: '/slow' }) + + // Discard every later navigation commit. The blocker is async, so the + // discarded commit still sets _pendingLocation for one microtask. + unblock = router.history.block({ blockerFn: async () => true }) + + // Same tick: settle the loader, then issue a navigation the blocker + // discards. The loader continuation resumes inside the window where + // _pendingLocation still points at /other. + loaderGate.resolve('slow data') + const blockedNavigation = router.navigate({ to: '/other' }) + + await Promise.all([navigation, blockedNavigation]) + + expect(router.state.location.pathname).toBe('/slow') + expect(router.history.location.pathname).toBe('/slow') + expect( + router.state.matches.find((m) => m.routeId === slowRoute.id), + ).toMatchObject({ + status: 'success', + loaderData: 'slow data', + }) + } finally { + unblock?.() + unsubscribe() + } + }) +}) diff --git a/packages/router-core/tests/boundary-component-chunk.test.ts b/packages/router-core/tests/boundary-component-chunk.test.ts new file mode 100644 index 0000000000..e1302003d2 --- /dev/null +++ b/packages/router-core/tests/boundary-component-chunk.test.ts @@ -0,0 +1,370 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * boundary component preloads should not be blocked by an unrelated + * normal route component preload. A route load starts the normal component + * preload before the loader settles; if that loader throws, the error boundary + * asks to load only the route's errorComponent. + * + * This test uses a real client router load. It keeps the normal route component + * preload pending, resolves the errorComponent preload, and expects the route + * error state to be committed without waiting for the normal component chunk. + */ + +const pendingGates: Array<ReturnType<typeof createControlledPromise<void>>> = [] +const pendingLoads: Array<Promise<unknown>> = [] + +afterEach(async () => { + for (const gate of pendingGates) { + gate.resolve() + } + + await Promise.allSettled(pendingLoads) + + pendingGates.length = 0 + pendingLoads.length = 0 +}) + +describe('route boundary component preloads', () => { + test('errorComponent preload resolves without waiting for a pending route component preload', async () => { + const componentGate = createControlledPromise<void>() + const errorComponentGate = createControlledPromise<void>() + const routeError = new Error('loader failed') + let errorComponentPreloadCalls = 0 + pendingGates.push(componentGate, errorComponentGate) + + const SlowRouteComponent = Object.assign(() => null, { + preload: () => componentGate, + }) + const ErrorBoundary = Object.assign(() => null, { + preload: () => { + errorComponentPreloadCalls++ + return errorComponentGate + }, + }) + + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/chunked', + loader: () => { + throw routeError + }, + component: SlowRouteComponent as any, + errorComponent: ErrorBoundary as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/chunked'] }), + }) + + const loadPromise = router.load() + pendingLoads.push(loadPromise) + + await vi.waitFor(() => expect(errorComponentPreloadCalls).toBe(1)) + errorComponentGate.resolve() + + // The route component chunk (componentGate) is still pending: the error + // state and the public load promise must settle without waiting for it. + await loadPromise + expect(componentGate.status).toBe('pending') + const match = router.state.matches.find((item) => item.routeId === route.id) + expect(match?.status).toBe('error') + expect(match?.error).toBe(routeError) + + componentGate.resolve() + }) + + test('an error boundary ignores a late normal component failure', async () => { + const componentGate = createControlledPromise<void>() + const errorComponentGate = createControlledPromise<void>() + const routeError = new Error('loader failed') + const componentError = new Error('component chunk failed') + const onError = vi.fn() + let errorComponentPreloadCalls = 0 + pendingGates.push(errorComponentGate) + + const SlowRouteComponent = Object.assign(() => null, { + preload: () => componentGate, + }) + const ErrorBoundary = Object.assign(() => null, { + preload: () => { + errorComponentPreloadCalls++ + return errorComponentGate + }, + }) + + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/chunked', + loader: () => { + throw routeError + }, + onError, + component: SlowRouteComponent as any, + errorComponent: ErrorBoundary as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/chunked'] }), + }) + + const loadPromise = router.load() + pendingLoads.push(loadPromise) + + await vi.waitFor(() => expect(errorComponentPreloadCalls).toBe(1)) + errorComponentGate.resolve() + await loadPromise + + const match = router.state.matches.find((item) => item.routeId === route.id) + expect(match?.status).toBe('error') + expect(match?.error).toBe(routeError) + expect(onError).toHaveBeenCalledOnce() + + componentGate.reject(componentError) + await expect(componentGate).rejects.toBe(componentError) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(onError).toHaveBeenCalledOnce() + expect(match?.error).toBe(routeError) + }) + + test('an ancestor error boundary ignores a hidden descendant component failure', async () => { + const componentGate = createControlledPromise<void>() + const routeError = new Error('parent loader failed') + const componentError = new Error('child component chunk failed') + const childOnError = vi.fn() + pendingGates.push(componentGate) + + const HiddenComponent = Object.assign(() => null, { + preload: () => componentGate, + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw routeError + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + component: HiddenComponent as any, + onError: childOnError, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + const loading = router.load() + pendingLoads.push(loading) + await loading + + expect(router.state.matches[1]).toMatchObject({ + routeId: parentRoute.id, + status: 'error', + error: routeError, + }) + expect(componentGate.status).toBe('pending') + + componentGate.reject(componentError) + await expect(componentGate).rejects.toBe(componentError) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(childOnError).not.toHaveBeenCalled() + expect(router.state.matches[1]?.error).toBe(routeError) + }) + + test('global notFound does not wait for component chunks below its boundary', async () => { + const hiddenComponentGate = createControlledPromise<void>() + const componentError = new Error('hidden component chunk failed') + const hiddenOnError = vi.fn() + const notFoundPreload = vi.fn(() => Promise.resolve()) + pendingGates.push(hiddenComponentGate) + + const NotFoundBoundary = Object.assign(() => null, { + preload: notFoundPreload, + }) + const HiddenComponent = Object.assign(() => null, { + preload: () => hiddenComponentGate, + }) + + const rootRoute = new BaseRootRoute({}) + const layoutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + id: '_layout', + notFoundComponent: NotFoundBoundary as any, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '/child', + component: HiddenComponent as any, + onError: hiddenOnError, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([layoutRoute.addChildren([childRoute])]), + history: createMemoryHistory({ + initialEntries: ['/child/does-not-exist'], + }), + notFoundMode: 'fuzzy', + }) + + const loading = router.load() + pendingLoads.push(loading) + await loading + + expect(hiddenComponentGate.status).toBe('pending') + expect(notFoundPreload).toHaveBeenCalledOnce() + expect(router.state.matches.find((match) => match._notFound)?.routeId).toBe( + layoutRoute.id, + ) + + hiddenComponentGate.reject(componentError) + await expect(hiddenComponentGate).rejects.toBe(componentError) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(hiddenOnError).not.toHaveBeenCalled() + }) + + test('a root not-found boundary ignores a late root component failure', async () => { + const componentGate = createControlledPromise<void>() + const notFoundGate = createControlledPromise<void>() + const componentError = new Error('root component chunk failed') + const onError = vi.fn() + const notFoundPreload = vi.fn(() => notFoundGate) + pendingGates.push(componentGate, notFoundGate) + + const RootComponent = Object.assign(() => null, { + preload: () => componentGate, + }) + const NotFoundBoundary = Object.assign(() => null, { + preload: notFoundPreload, + }) + const rootRoute = new BaseRootRoute({ + component: RootComponent as any, + notFoundComponent: NotFoundBoundary as any, + onError, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + beforeLoad: () => { + throw notFound({ routeId: rootRoute.id }) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + }) + + const loading = router.load() + pendingLoads.push(loading) + await vi.waitFor(() => expect(notFoundPreload).toHaveBeenCalledOnce()) + notFoundGate.resolve() + await loading + + expect(router.state.matches[0]).toMatchObject({ + status: 'success', + _notFound: true, + }) + + componentGate.reject(componentError) + await expect(componentGate).rejects.toBe(componentError) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(onError).not.toHaveBeenCalled() + }) + + test('a late normal component chunk cannot replace a selected not-found boundary', async () => { + const componentGate = createControlledPromise<void>() + const notFoundGate = createControlledPromise<void>() + const notFoundPreload = vi.fn(() => notFoundGate) + pendingGates.push(componentGate, notFoundGate) + + const ParentComponent = Object.assign(() => null, { + preload: () => componentGate, + }) + const NotFoundBoundary = Object.assign(() => null, { + preload: notFoundPreload, + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => 'ready', + component: ParentComponent as any, + notFoundComponent: NotFoundBoundary as any, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: () => { + throw notFound({ routeId: parentRoute.id }) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + const loading = router.load() + pendingLoads.push(loading) + await vi.waitFor(() => expect(notFoundPreload).toHaveBeenCalledOnce()) + + componentGate.resolve() + await Promise.resolve() + notFoundGate.resolve() + await loading + + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + status: 'notFound', + loaderData: 'ready', + }) + }) + + test('a required ancestor lazy chunk failure wins over a deeper loader notFound', async () => { + const chunkError = new Error('ancestor lazy chunk failed') + const rootRoute = new BaseRootRoute({}) + const ancestorRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/ancestor', + errorComponent: () => null, + }).lazy(() => Promise.reject(chunkError)) + const childRoute = new BaseRoute({ + getParentRoute: () => ancestorRoute, + path: '/child', + loader: () => { + throw notFound() + }, + notFoundComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + ancestorRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/ancestor/child'] }), + }) + + await router.load() + + expect( + router.state.matches.find((match) => match.routeId === ancestorRoute.id), + ).toMatchObject({ status: 'error', error: chunkError }) + }) +}) diff --git a/packages/router-core/tests/build-location.bench.ts b/packages/router-core/tests/build-location.bench.ts new file mode 100644 index 0000000000..2b93731d2c --- /dev/null +++ b/packages/router-core/tests/build-location.bench.ts @@ -0,0 +1,155 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, retainSearchParams } from '../src' +import { createTestRouter } from './routerTestUtils' +import type { AnyRouter, ParsedLocation } from '../src' + +// Mirrors what `useLinkProps` does on every location publication: each link +// owns one stable `dest` object, points `_fromLocation` at the new location +// and calls `router.buildLocation(dest)` inside its store selector. + +const LINKS = 32 + +function createBenchRouter(withMiddleware: boolean) { + const root = new BaseRootRoute({ + validateSearch: (search: Record<string, unknown>) => ({ + page: Number(search.page ?? 1), + }), + }) + const posts = new BaseRoute({ + getParentRoute: () => root, + path: '/posts', + // Only routes with middleware get a `search` key, like real route trees. + ...(withMiddleware + ? { search: { middlewares: [retainSearchParams(['page'])] } } + : {}), + } as any) + const post = new BaseRoute({ + getParentRoute: () => posts, + path: '/$postId', + }) + const edit = new BaseRoute({ + getParentRoute: () => post, + path: '/edit', + }) + const history = createMemoryHistory({ initialEntries: ['/posts/1?page=2'] }) + const router = createTestRouter({ + routeTree: root.addChildren([ + posts.addChildren([post.addChildren([edit])]), + ]), + history, + scrollRestoration: false, + }) + history.destroy() + return router +} + +type Dest = Record<string, unknown> & { _fromLocation?: ParsedLocation } + +function publication(router: AnyRouter, dests: Array<Dest>) { + // A fresh location object per publication, like a committed navigation. + const location = { ...router.latestLocation } + let checksum = 0 + for (const dest of dests) { + dest._fromLocation = location + checksum += router.buildLocation(dest as any).href.length + } + return checksum +} + +function defineCase( + name: string, + withMiddleware: boolean, + makeDest: (index: number) => Dest, + expectedHref: (index: number) => string, +) { + const router = createBenchRouter(withMiddleware) + const dests = Array.from({ length: LINKS }, (_, index) => makeDest(index)) + const expected = dests.reduce( + (sum, _dest, index) => sum + expectedHref(index).length, + 0, + ) + // Correctness before timing: every link resolves to the expected href. + dests.forEach((dest, index) => { + dest._fromLocation = router.latestLocation + expect(router.buildLocation(dest as any).href).toBe(expectedHref(index)) + }) + let checksum = 0 + test(name, async ({ bench }) => { + await bench( + name, + { + afterAll: () => { + expect(checksum).toBe(expected) + }, + }, + () => { + checksum = publication(router, dests) + }, + ).run({ + time: 1000, + warmupTime: 200, + throws: true, + }) + }) +} + +describe(`buildLocation per publication (${LINKS} links)`, () => { + defineCase( + 'absolute to + literal params (static cache hit)', + false, + (index) => ({ to: '/posts/$postId', params: { postId: String(index) } }), + (index) => `/posts/${index}`, + ) + + defineCase( + 'absolute to + search updater (reads current search)', + false, + (index) => ({ + to: '/posts', + search: (prev: Record<string, unknown>) => ({ ...prev, page: index }), + }), + (index) => `/posts?page=${index}`, + ) + + defineCase( + 'absolute to + search updater + retainSearchParams middleware', + true, + (index) => ({ + to: '/posts/$postId', + params: { postId: String(index) }, + search: () => ({ page: index }), + }), + (index) => `/posts/${index}?page=${index}`, + ) + + defineCase( + 'relative to from the current match', + false, + (index) => ({ + to: './edit', + search: (prev: unknown) => prev, + hash: `h${index}`, + }), + (index) => `/posts/1/edit?page=2#h${index}`, + ) + + defineCase( + 'params: true (inherits current params)', + false, + (index) => ({ to: '/posts/$postId/edit', params: true, hash: `h${index}` }), + (index) => `/posts/1/edit#h${index}`, + ) + + defineCase( + 'masked destination', + false, + (index) => ({ + to: '/posts/$postId', + params: { postId: String(index) }, + search: () => ({ page: index }), + mask: { to: '/posts' }, + }), + (index) => `/posts/${index}?page=${index}`, + ) +}) diff --git a/packages/router-core/tests/build-location.test.ts b/packages/router-core/tests/build-location.test.ts new file mode 100644 index 0000000000..99bbbc60cf --- /dev/null +++ b/packages/router-core/tests/build-location.test.ts @@ -0,0 +1,2858 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { isServer as serverEnvironment } from '@tanstack/router-core/isServer' +import * as pathUtils from '../src/path' +import { + BaseRootRoute, + BaseRoute, + retainSearchParams, + stripSearchParams, +} from '../src' +import { _getUserHistoryState } from '../src/router' +import { createTestRouter } from './routerTestUtils' +import type { SearchMiddleware } from '../src' + +test('_getUserHistoryState removes volatile router bookkeeping but keeps mask payloads', () => { + expect( + _getUserHistoryState({ + key: 'legacy-key', + __TSR_key: 'key', + __TSR_index: 1, + __hashScrollIntoViewOptions: true, + __tempLocation: {} as any, + __tempKey: 'temp-key', + user: 'state', + } as any), + ).toEqual({ user: 'state', __tempLocation: {}, __tempKey: 'temp-key' }) +}) + +test.each([false, true])( + 'interpolates matches from raw params when router.isServer is %s', + (isServer) => { + expect(serverEnvironment).toBeUndefined() + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/items/one'] }), + isServer, + }) + const interpolate = vi.spyOn(pathUtils, 'interpolatePath') + try { + const matches = router.matchRoutes('/items/one', {}) + expect(matches.at(-1)?.pathname).toBe('/items/one') + const call = interpolate.mock.calls.find( + ([path]) => path === '/items/$id', + ) + expect(call).toHaveLength(5) + expect(call?.[1]).toBe(route._interpolation) + expect(call?.[2]).toEqual({ id: 'one' }) + expect(matches.at(-1)?._strictParams).toEqual({ id: 'one' }) + } finally { + interpolate.mockRestore() + } + }, +) + +describe('buildLocation - params function receives parsed params', () => { + test('prev params should contain parsed params from route params.parse', async () => { + const rootRoute = new BaseRootRoute({}) + + // Create a route with params.parse that transforms string to number + const userRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId', + params: { + parse: ({ userId }: { userId: string }) => ({ + userId: parseInt(userId, 10), + }), + }, + }) + + const routeTree = rootRoute.addChildren([userRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/users/123'] }), + }) + + // Load to establish current location with parsed params + await router.load() + + // Track what params the function receives (clone to avoid mutation) + const updater = vi.fn() + + router.buildLocation({ + from: '/users/$userId', + to: '/users/$userId', + params: updater, + }) + + // The prev params should be parsed (number), not raw string + expect(updater).toHaveBeenCalledOnce() + expect(updater).toHaveBeenCalledWith({ userId: 123 }) + }) + + test('prev params should accumulate parsed params from all routes in the branch', async () => { + const rootRoute = new BaseRootRoute({}) + + // Parent route with params.parse + const orgRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/orgs/$orgId', + params: { + parse: ({ orgId }: { orgId: string }) => ({ + orgId: parseInt(orgId, 10), + }), + }, + }) + + // Child route with its own params.parse + const userRoute = new BaseRoute({ + getParentRoute: () => orgRoute, + path: '/users/$userId', + params: { + parse: ({ userId }: { userId: string }) => ({ + userId: parseInt(userId, 10), + }), + }, + }) + + const routeTree = rootRoute.addChildren([orgRoute.addChildren([userRoute])]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/orgs/42/users/123'] }), + }) + + await router.load() + + const updater = vi.fn() + + router.buildLocation({ + from: '/orgs/$orgId/users/$userId', + to: '/orgs/$orgId/users/$userId', + params: updater, + }) + + // Both params should be parsed (numbers) + expect(updater).toHaveBeenCalledOnce() + expect(updater).toHaveBeenCalledWith({ orgId: 42, userId: 123 }) + }) + + test('prev params should contain parsed params when navigating to different route', async () => { + const rootRoute = new BaseRootRoute({}) + + const userRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId', + params: { + parse: ({ userId }: { userId: string }) => ({ + userId: parseInt(userId, 10), + }), + }, + }) + + const postRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts/$postId', + params: { + parse: ({ postId }: { postId: string }) => ({ + postId: parseInt(postId, 10), + }), + }, + }) + + const routeTree = rootRoute.addChildren([userRoute, postRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/users/123'] }), + }) + + await router.load() + + const updater = vi.fn() + + // Navigate from /users/$userId to /posts/$postId + // The prev should contain parsed params from the current (from) route + router.buildLocation({ + from: '/users/$userId', + to: '/posts/$postId', + params: updater, + }) + + // The prev params should be from the current route (parsed userId) + // Note: prev may also contain the new postId param merged in + expect(updater).toHaveBeenCalledOnce() + expect(updater).toHaveBeenCalledWith({ userId: 123 }) + }) + + test('params without parse function remain as strings in prev', async () => { + const rootRoute = new BaseRootRoute({}) + + // Route without params.parse + const userRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId', + }) + + const routeTree = rootRoute.addChildren([userRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/users/123'] }), + }) + + await router.load() + + const updater = vi.fn() + + router.buildLocation({ + from: '/users/$userId', + to: '/users/$userId', + params: updater, + }) + + // Without params.parse, the param should remain a string + expect(updater).toHaveBeenCalledOnce() + expect(updater).toHaveBeenCalledWith({ userId: '123' }) + }) + + test('mixed routes with and without params.parse', async () => { + const rootRoute = new BaseRootRoute({}) + + // Parent route WITH params.parse + const orgRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/orgs/$orgId', + params: { + parse: ({ orgId }: { orgId: string }) => ({ + orgId: parseInt(orgId, 10), + }), + }, + }) + + // Child route WITHOUT params.parse + const teamRoute = new BaseRoute({ + getParentRoute: () => orgRoute, + path: '/teams/$teamSlug', + }) + + const routeTree = rootRoute.addChildren([orgRoute.addChildren([teamRoute])]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/orgs/42/teams/engineering'], + }), + }) + + await router.load() + + const updater = vi.fn() + + router.buildLocation({ + from: '/orgs/$orgId/teams/$teamSlug', + to: '/orgs/$orgId/teams/$teamSlug', + params: updater, + }) + + expect(updater).toHaveBeenCalledOnce() + expect(updater).toHaveBeenCalledWith({ orgId: 42, teamSlug: 'engineering' }) + }) +}) + +describe('buildLocation - search params', () => { + test('collects updated middleware options from the whole route branch', () => { + const rootRoute = new BaseRootRoute({ + search: { + middlewares: [({ search, next }) => next({ ...search, root: true })], + }, + }) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + search: { + middlewares: [ + ({ search, next }) => ({ ...next(search), value: 'initial' }), + ], + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const buildSearch = () => + router.buildLocation({ to: '/', search: true }).search + + expect(buildSearch()).toEqual({ root: true, value: 'initial' }) + + route.update({ + search: { + middlewares: [ + ({ search, next }) => ({ ...next(search), value: 'updated' }), + ], + }, + }) + expect(buildSearch()).toEqual({ root: true, value: 'updated' }) + + route.update({ search: { middlewares: [] } }) + expect(buildSearch()).toEqual({ root: true }) + rootRoute.update({ search: { middlewares: [] } }) + expect(buildSearch()).toEqual({}) + }) + + test('only applies route validation when requested', async () => { + const events: Array<string> = [] + const validateSearch = vi.fn((search: Record<string, unknown>) => { + events.push('validate') + return { ...search, validated: true } + }) + const middleware = vi.fn<SearchMiddleware<{ validated: boolean }>>( + ({ search, next }) => { + events.push('middleware:before') + const result = next(search) + events.push('middleware:after') + return { ...result, middleware: true } + }, + ) + const rootRoute = new BaseRootRoute({ + validateSearch, + search: { middlewares: [middleware] }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + + router.buildLocation({ to: '/' }) + validateSearch.mockClear() + middleware.mockClear() + events.length = 0 + + const unvalidated = router.buildLocation({ + to: '/', + search: { explicit: true }, + }) + expect(validateSearch).not.toHaveBeenCalled() + expect(middleware).toHaveBeenCalledOnce() + expect(events).toEqual(['middleware:before', 'middleware:after']) + expect(unvalidated.search).toEqual({ explicit: true, middleware: true }) + + events.length = 0 + const validated = router.buildLocation({ + to: '/', + search: { explicit: true }, + _includeValidateSearch: true, + }) + expect(validateSearch).toHaveBeenCalledOnce() + expect(events).toEqual([ + 'middleware:before', + 'validate', + 'middleware:after', + ]) + expect(validated.search).toEqual({ + explicit: true, + middleware: true, + validated: true, + }) + }) + + test('retainSearchParams should preserve current search over defaults during navigation', async () => { + const rootRoute = new BaseRootRoute({ + validateSearch: (search: Record<string, unknown>) => ({ + Auth: search.Auth === undefined ? 'true' : `${search.Auth}`, + }), + search: { + middlewares: [retainSearchParams(['Auth'])], + }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + + const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/about?Auth=false'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/', + _includeValidateSearch: true, + } as any) + + expect(location.search).toEqual({ Auth: 'false' }) + }) + + test('retainSearchParams should not replace defaults with missing current search', async () => { + const rootRoute = new BaseRootRoute({ + validateSearch: (search: Record<string, unknown>) => ({ + Auth: search.Auth === undefined ? 'true' : `${search.Auth}`, + }), + search: { + middlewares: [retainSearchParams(['Auth'])], + }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/', + _includeValidateSearch: true, + } as any) + + expect(location.search).toEqual({ Auth: 'true' }) + }) + + test('retainSearchParams should not restore default-valued params removed by stripSearchParams', async () => { + const defaults = { + param1: 1, + param2: 2, + } + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + validateSearch: (search: Record<string, unknown>) => ({ + param1: search.param1 === undefined ? defaults.param1 : search.param1, + param2: search.param2 === undefined ? defaults.param2 : search.param2, + }), + search: { + middlewares: [ + retainSearchParams(['param2']), + stripSearchParams(defaults), + ], + }, + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/?param2=2'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/', + search: { param1: 10 }, + _includeValidateSearch: true, + } as any) + + expect(location.search).toEqual({ param1: 10 }) + }) + + test('retainSearchParams should allow explicit default params to reset current params when stripSearchParams removes them', async () => { + const defaults = { + param1: 1, + param2: 2, + } + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + validateSearch: (search: Record<string, unknown>) => ({ + param1: search.param1 === undefined ? defaults.param1 : search.param1, + param2: search.param2 === undefined ? defaults.param2 : search.param2, + }), + search: { + middlewares: [ + retainSearchParams(['param1', 'param2']), + stripSearchParams(defaults), + ], + }, + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/?param1=10'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/', + search: defaults, + _includeValidateSearch: true, + } as any) + + expect(location.search).toEqual({}) + }) + + test('retainSearchParams(true) should allow explicit default params to reset current params when stripSearchParams removes them', async () => { + const defaults = { + param1: 1, + param2: 2, + } + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + validateSearch: (search: Record<string, unknown>) => ({ + param1: search.param1 === undefined ? defaults.param1 : search.param1, + param2: search.param2 === undefined ? defaults.param2 : search.param2, + }), + search: { + middlewares: [retainSearchParams(true), stripSearchParams(defaults)], + }, + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/?param1=10'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/', + search: defaults, + _includeValidateSearch: true, + } as any) + + expect(location.search).toEqual({}) + }) + + test('retainSearchParams should not restore params explicitly removed by stripSearchParams', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + search: { + middlewares: [ + retainSearchParams(['param2']), + stripSearchParams<Record<string, unknown>>(['param2']), + ], + }, + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/?param2=not-default'], + }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/', + search: { param1: 10 }, + } as any) + + expect(location.search).toEqual({ param1: 10 }) + }) + + test('nested retainSearchParams should preserve stripped param metadata', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + search: { + middlewares: [ + retainSearchParams(['param1']), + retainSearchParams(['param2']), + stripSearchParams<Record<string, unknown>>(['param1']), + ], + }, + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/?param1=stripped¶m2=retained'], + }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/', + search: { param3: 'next' }, + } as any) + + expect(location.search).toEqual({ param2: 'retained', param3: 'next' }) + }) + + test('retainSearchParams should preserve non-default params when defaults are stripped', async () => { + const rootRoute = new BaseRootRoute({ + validateSearch: (search: Record<string, unknown>) => ({ + Auth: search.Auth === undefined ? 'true' : `${search.Auth}`, + }), + search: { + middlewares: [ + retainSearchParams(['Auth']), + stripSearchParams({ Auth: 'true' }), + ], + }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + + const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/about?Auth=false'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/', + _includeValidateSearch: true, + } as any) + + expect(location.search).toEqual({ Auth: 'false' }) + }) + + test('retainSearchParams should keep downstream values added after validation', async () => { + const rootRoute = new BaseRootRoute({ + validateSearch: (search: Record<string, unknown>) => ({ + Auth: search.Auth === undefined ? 'default' : `${search.Auth}`, + }), + search: { + middlewares: [ + retainSearchParams(['Auth']), + ({ search, next }) => ({ ...next(search), Auth: 'explicit' }), + ], + }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/?Auth=current'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/', + _includeValidateSearch: true, + } as any) + + expect(location.search).toEqual({ Auth: 'explicit' }) + }) + + test('retainSearchParams(true) should preserve nested current search over defaults during navigation', async () => { + const rootRoute = new BaseRootRoute({ + validateSearch: (search: Record<string, unknown>) => ({ + filter: Array.isArray(search.filter) ? search.filter : ['default'], + filterOrder: + typeof search.filterOrder === 'object' && search.filterOrder + ? search.filterOrder + : {}, + anotherFilterOrder: Array.isArray(search.anotherFilterOrder) + ? search.anotherFilterOrder + : [], + }), + search: { + middlewares: [retainSearchParams(true)], + }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const currentLocation = router.buildLocation({ + to: '/', + search: { filterOrder: { filter1: [1], filter2: [0] } }, + _includeValidateSearch: true, + } as any) + + const location = router.buildLocation({ + to: '/', + _fromLocation: currentLocation, + _includeValidateSearch: true, + } as any) + + expect(location.search).toEqual({ + filter: ['default'], + filterOrder: { filter1: [1], filter2: [0] }, + anotherFilterOrder: [], + }) + }) + + test('retainSearchParams(true) should preserve nested search when navigating to the same route', async () => { + const rootRoute = new BaseRootRoute({ + validateSearch: (search: Record<string, unknown>) => ({ + filter: Array.isArray(search.filter) ? search.filter : ['default'], + filterOrder: + typeof search.filterOrder === 'object' && search.filterOrder + ? search.filterOrder + : {}, + anotherFilterOrder: Array.isArray(search.anotherFilterOrder) + ? search.anotherFilterOrder + : [], + }), + search: { + middlewares: [retainSearchParams(true)], + }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + await router.navigate({ + to: '/', + search: { filterOrder: { filter1: [1], filter2: [0] } }, + } as any) + + expect(router.latestLocation.search).toEqual({ + filter: ['default'], + filterOrder: { filter1: [1], filter2: [0] }, + anotherFilterOrder: [], + }) + + await router.navigate({ to: '/' }) + + expect(router.latestLocation.search).toEqual({ + filter: ['default'], + filterOrder: { filter1: [1], filter2: [0] }, + anotherFilterOrder: [], + }) + }) + + test('retainSearchParams should preserve root search during navigation', async () => { + const rootRoute = new BaseRootRoute({ + validateSearch: (search: Record<string, unknown>) => ({ + rootValue: search.rootValue as string | undefined, + }), + search: { + middlewares: [retainSearchParams(['rootValue'])], + }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const settingsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/settings', + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + validateSearch: (search: Record<string, unknown>) => ({ + param1: search.param1 as string | undefined, + }), + }) + + const routeTree = rootRoute.addChildren([ + indexRoute, + settingsRoute, + aboutRoute, + ]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/settings?rootValue=value'], + }), + }) + + await router.load() + + const linkLocation = router.buildLocation({ to: '/about' }) + expect(linkLocation.search).toEqual({ rootValue: 'value' }) + + await router.navigate({ to: '/about' }) + + expect(router.latestLocation.pathname).toBe('/about') + expect(router.latestLocation.search).toEqual({ rootValue: 'value' }) + }) + + test('search as object should set search params', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + search: { page: 1, filter: 'active' }, + }) + + expect(location.search).toEqual({ page: 1, filter: 'active' }) + expect(location.searchStr).toContain('page=1') + expect(location.searchStr).toContain('filter=active') + }) + + test('search as function should receive current search and return new search', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts?page=1'] }), + }) + + await router.load() + + const searchUpdater = vi.fn((prev: { page?: number }) => ({ + ...prev, + page: (prev.page || 0) + 1, + })) + + const location = router.buildLocation({ + to: '/posts', + search: searchUpdater, + }) + + expect(searchUpdater).toHaveBeenCalledOnce() + expect(searchUpdater).toHaveBeenCalledWith({ page: 1 }) + expect(location.search).toEqual({ page: 2 }) + }) + + test('search: true should preserve current search params', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/posts?page=5&filter=active'], + }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + search: true, + }) + + expect(location.search).toEqual({ page: 5, filter: 'active' }) + }) + + test('search object should merge with current search when using function', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/posts?existing=value'], + }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + search: (prev: Record<string, unknown>) => ({ + ...prev, + newKey: 'newValue', + }), + }) + + expect(location.search).toEqual({ existing: 'value', newKey: 'newValue' }) + }) + + test('search with validateSearch on route should validate search params', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + validateSearch: (search: Record<string, unknown>) => ({ + page: Number(search.page) + 1, + }), + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts?page=5'] }), + search: { strict: true }, + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + search: { page: 10 }, + _includeValidateSearch: true, + } as any) + + expect(location.search).toEqual({ page: 11 }) + }) + + test('empty search object should clear search params', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/posts?page=1&filter=active'], + }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + search: {}, + }) + + expect(location.search).toEqual({}) + expect(location.searchStr).toBe('') + }) + + test('search function returning empty object should clear search params', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/posts?page=1'], + }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + search: () => ({}), + }) + + expect(location.search).toEqual({}) + }) +}) + +describe('buildLocation - hash', () => { + test('hash as string should set the hash', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + hash: 'section1', + }) + + expect(location.hash).toBe('section1') + expect(location.href).toContain('#section1') + }) + + test('hash as function should receive current hash and return new hash', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts#current'] }), + }) + + await router.load() + + const hashUpdater = vi.fn((prev?: string) => `${prev}-updated`) + + const location = router.buildLocation({ + to: '/posts', + hash: hashUpdater, + }) + + expect(hashUpdater).toHaveBeenCalledOnce() + expect(hashUpdater).toHaveBeenCalledWith('current') + expect(location.hash).toBe('current-updated') + }) + + test('hash: true should preserve current hash', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts#existing'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + hash: true, + }) + + expect(location.hash).toBe('existing') + expect(location.href).toContain('#existing') + }) + + test('no hash option should result in empty hash', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts#existing'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + }) + + expect(location.hash).toBe('') + expect(location.href).not.toContain('#') + }) + + test('empty string hash should clear the hash', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts#existing'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + hash: '', + }) + + expect(location.hash).toBe('') + expect(location.href).not.toContain('#') + }) +}) + +describe('buildLocation - state', () => { + test('state as object should set state', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + state: { modal: true, count: 5 } as any, + }) + + expect(location.state).toEqual({ modal: true, count: 5 }) + }) + + test('state as function should receive current state and return new state', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const history = createMemoryHistory({ initialEntries: ['/posts'] }) + // Set initial state on history + history.replace('/posts', { existing: 'value' }) + + const router = createTestRouter({ + routeTree, + history, + }) + + await router.load() + + const stateUpdater = vi.fn((prev: Record<string, unknown>) => ({ + ...prev, + newKey: 'newValue', + })) + + const location = router.buildLocation({ + to: '/posts', + state: stateUpdater as any, + }) + + expect(stateUpdater).toHaveBeenCalledOnce() + // State includes internal router keys, so use toMatchObject + expect(location.state).toMatchObject({ + existing: 'value', + newKey: 'newValue', + }) + }) + + test('state: true should preserve current state', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const history = createMemoryHistory({ initialEntries: ['/posts'] }) + history.replace('/posts', { preserved: true }) + + const router = createTestRouter({ + routeTree, + history, + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + state: true, + }) + + // State includes internal router keys, so use toMatchObject + expect(location.state).toMatchObject({ preserved: true }) + }) + + test('no state option should result in empty state', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const history = createMemoryHistory({ initialEntries: ['/posts'] }) + history.replace('/posts', { existing: 'value' }) + + const router = createTestRouter({ + routeTree, + history, + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + }) + + expect(location.state).toEqual({}) + expect(location.state).not.toBe(router.state.location.state) + }) + + test('no state option replaces an already-empty custom state', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([postsRoute]), + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + await router.load() + + const emptyState = {} + const location = router.buildLocation({ + to: '/posts', + _fromLocation: { + ...router.state.location, + state: emptyState, + }, + } as any) + + expect(location.state).toEqual({}) + expect(location.state).not.toBe(emptyState) + }) + + test('state can contain complex nested objects', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const complexState = { + user: { id: 1, name: 'Test' }, + items: [1, 2, 3], + nested: { deep: { value: true } }, + } + + const location = router.buildLocation({ + to: '/posts', + state: complexState as any, + }) + + expect(location.state).toEqual(complexState) + }) +}) + +describe('buildLocation - no structural sharing with the current location', () => { + function createPostsRouter( + history = createMemoryHistory({ initialEntries: ['/posts'] }), + ) { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + return createTestRouter({ + routeTree: rootRoute.addChildren([postsRoute]), + history, + }) + } + + test('explicit state is returned as-is and equal nested values are shared only after navigation', async () => { + const history = createMemoryHistory({ initialEntries: ['/posts'] }) + history.replace('/posts', { + user: { id: 1, name: 'Test' }, + count: 1, + }) + const router = createPostsRouter(history) + await router.load() + + const previousState = router.state.location.state as any + const nextState = { + user: { id: 1, name: 'Test' }, + count: 2, + } + const location = router.buildLocation({ + to: '/posts', + state: nextState as any, + }) + + // The built location carries the caller's object untouched. + expect(location.state).toBe(nextState) + expect((location.state as any).user).not.toBe(previousState.user) + + await router.navigate({ to: '/posts', state: nextState as any }) + + // parseLocation still stabilizes the committed state against the + // previous one, which is what location selectors rely on. + const committedState = router.state.location.state as any + expect(committedState).toMatchObject({ + user: { id: 1, name: 'Test' }, + count: 2, + }) + expect(committedState).not.toBe(previousState) + expect(committedState.user).toBe(previousState.user) + expect(nextState.user).not.toBe(previousState.user) + }) + + test('explicit search is returned as-is and equal nested values are shared only after navigation', async () => { + const router = createPostsRouter() + await router.load() + + await router.navigate({ + to: '/posts', + search: { page: 1, filter: { tags: ['a'] } } as any, + }) + const previousSearch = router.state.location.search as any + expect(previousSearch).toEqual({ page: 1, filter: { tags: ['a'] } }) + + const nextSearch = { page: 2, filter: { tags: ['a'] } } + const location = router.buildLocation({ + to: '/posts', + search: nextSearch as any, + }) + + expect(location.search).toBe(nextSearch) + expect((location.search as any).filter).not.toBe(previousSearch.filter) + + await router.navigate({ to: '/posts', search: nextSearch as any }) + + const committedSearch = router.state.location.search as any + expect(committedSearch).toEqual({ page: 2, filter: { tags: ['a'] } }) + expect(committedSearch).not.toBe(previousSearch) + expect(committedSearch.filter).toBe(previousSearch.filter) + expect(nextSearch.filter).not.toBe(previousSearch.filter) + }) + + test('navigate does not mutate a caller-supplied state object', async () => { + const history = createMemoryHistory({ initialEntries: ['/posts'] }) + const router = createPostsRouter(history) + await router.load() + + const state = { user: { id: 1 } } + await router.navigate({ + to: '/posts', + state: state as any, + hashScrollIntoView: true, + }) + + expect(state).toEqual({ user: { id: 1 } }) + expect(Object.keys(state)).toEqual(['user']) + const committedState = router.state.location.state as any + expect(committedState).not.toBe(state) + expect(committedState.user).toBe(state.user) + expect(committedState.__hashScrollIntoViewOptions).toBe(true) + expect(committedState.__TSR_key).toBeTypeOf('string') + expect(committedState.key).toBe(committedState.__TSR_key) + + // A frozen state (for example produced by an immutable store) commits + // without any write hitting it: in strict mode such a write would throw. + const frozenState = Object.freeze({ user: Object.freeze({ id: 2 }) }) + await router.navigate({ to: '/posts', state: frozenState as any }) + + expect(router.state.location.state).toMatchObject({ user: { id: 2 } }) + expect(router.state.location.state).not.toBe(frozenState) + expect(history.length).toBe(3) + }) + + test('an equal search in a different key order serializes in the requested order', async () => { + const router = createPostsRouter( + createMemoryHistory({ initialEntries: ['/posts?a=1&b=2'] }), + ) + await router.load() + + expect(router.state.location.href).toBe('/posts?a=1&b=2') + + const location = router.buildLocation({ + to: '/posts', + search: { b: 2, a: 1 } as any, + }) + + expect(location.search).toEqual({ a: 1, b: 2 }) + expect(Object.keys(location.search)).toEqual(['b', 'a']) + expect(location.searchStr).toBe('?b=2&a=1') + expect(location.href).toBe('/posts?b=2&a=1') + }) + + test('navigating to an equal search in a different key order pushes a new history entry', async () => { + const history = createMemoryHistory({ initialEntries: ['/posts?a=1&b=2'] }) + const router = createPostsRouter(history) + await router.load() + + expect(history.length).toBe(1) + + // Same contents and order: nothing to commit. + await router.navigate({ to: '/posts', search: { a: 1, b: 2 } as any }) + + expect(history.length).toBe(1) + expect(router.state.location.href).toBe('/posts?a=1&b=2') + + // Same contents, different order: the URL changes, so history grows. + await router.navigate({ to: '/posts', search: { b: 2, a: 1 } as any }) + + expect(history.length).toBe(2) + expect(history.location.href).toBe('/posts?b=2&a=1') + expect(router.state.location.href).toBe('/posts?b=2&a=1') + expect(router.state.location.search).toEqual({ a: 1, b: 2 }) + }) +}) + +describe('buildLocation - relative paths', () => { + test('absolute path should navigate to exact route', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + + const routeTree = rootRoute.addChildren([postsRoute, aboutRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + from: '/posts', + to: '/about', + }) + + expect(location.pathname).toBe('/about') + }) + + test('./ prefix should resolve relative to current route', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + const postDetailRoute = new BaseRoute({ + getParentRoute: () => postsRoute, + path: '/detail', + }) + + const routeTree = rootRoute.addChildren([ + postsRoute.addChildren([postDetailRoute]), + ]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: './detail', + }) + + expect(location.pathname).toBe('/posts/detail') + }) + + test('../ prefix should resolve up one path segment', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + const postDetailRoute = new BaseRoute({ + getParentRoute: () => postsRoute, + path: '/detail', + }) + const postAboutRoute = new BaseRoute({ + getParentRoute: () => postsRoute, + path: '/about', + }) + + const routeTree = rootRoute.addChildren([ + postsRoute.addChildren([postDetailRoute, postAboutRoute]), + ]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts/detail'] }), + }) + + await router.load() + + // ../ goes up one segment from 'detail' to 'posts', then adds 'about' + const location = router.buildLocation({ + to: '../about', + }) + + expect(location.pathname).toBe('/posts/about') + }) + + test('multiple ../ should navigate up multiple path segments', async () => { + const rootRoute = new BaseRootRoute({}) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + }) + const bRoute = new BaseRoute({ + getParentRoute: () => aRoute, + path: '/b', + }) + const cRoute = new BaseRoute({ + getParentRoute: () => bRoute, + path: '/c', + }) + const dRoute = new BaseRoute({ + getParentRoute: () => aRoute, + path: '/d', + }) + + const routeTree = rootRoute.addChildren([ + aRoute.addChildren([bRoute.addChildren([cRoute]), dRoute]), + ]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/a/b/c'] }), + }) + + await router.load() + + // ../../d from /a/b/c goes up from 'c' to 'b', then from 'b' to 'a', then adds 'd' + const location = router.buildLocation({ + to: '../../d', + }) + + expect(location.pathname).toBe('/a/d') + }) + + test('unsafe path-relative navigation ignores repeated slash segments', async () => { + const rootRoute = new BaseRootRoute({}) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + }) + const bRoute = new BaseRoute({ + getParentRoute: () => aRoute, + path: '/b', + }) + const cRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/c', + }) + const routeTree = rootRoute.addChildren([ + aRoute.addChildren([bRoute]), + cRoute, + ]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/a//b'] }), + }) + + await router.load() + + expect( + router.buildLocation({ + to: '../../c', + unsafeRelative: 'path', + }).pathname, + ).toBe('/c') + }) + + test('over-root traversal stays rooted for javascript-like segments', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '../javascript:alert(1)', + }) + + expect(location.pathname).toBe('/javascript:alert(1)') + expect(location.href).toBe('/javascript:alert(1)') + expect(location.publicHref).toBe('/javascript:alert(1)') + }) + + test('. should stay on current route', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '.', + }) + + expect(location.pathname).toBe('/posts') + }) + + test('relative path with child segment', async () => { + const rootRoute = new BaseRootRoute({}) + const usersRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users', + }) + const userRoute = new BaseRoute({ + getParentRoute: () => usersRoute, + path: '/$userId', + }) + const settingsRoute = new BaseRoute({ + getParentRoute: () => userRoute, + path: '/settings', + }) + + const routeTree = rootRoute.addChildren([ + usersRoute.addChildren([userRoute.addChildren([settingsRoute])]), + ]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/users'] }), + }) + + await router.load() + + const location = router.buildLocation({ + from: '/users/$userId', + to: './settings', + params: { userId: '123' }, + }) + + expect(location.pathname).toBe('/users/123/settings') + }) +}) + +describe('buildLocation - basepath', () => { + test('basepath should be included in href but not pathname', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + basepath: '/app', + history: createMemoryHistory({ initialEntries: ['/app/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + }) + + // pathname is the route path without basepath + expect(location.pathname).toBe('/posts') + // href includes the basepath + expect(location.href).toBe('/app/posts') + }) + + test('basepath should work with nested routes', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + const postRoute = new BaseRoute({ + getParentRoute: () => postsRoute, + path: '/$postId', + }) + + const routeTree = rootRoute.addChildren([ + postsRoute.addChildren([postRoute]), + ]) + + const router = createTestRouter({ + routeTree, + basepath: '/app', + history: createMemoryHistory({ initialEntries: ['/app/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts/$postId', + params: { postId: '123' }, + }) + + expect(location.pathname).toBe('/posts/123') + expect(location.href).toBe('/app/posts/123') + }) + + test('basepath with trailing slash should work correctly', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + basepath: '/app/', + history: createMemoryHistory({ initialEntries: ['/app/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + }) + + // Should normalize the basepath correctly + expect(location.pathname).toBe('/posts') + expect(location.href).toBe('/app/posts') + }) + + test('navigating to root with basepath', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + basepath: '/app', + history: createMemoryHistory({ initialEntries: ['/app/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/', + }) + + expect(location.pathname).toBe('/') + // Root with basepath includes trailing slash + expect(location.href).toBe('/app/') + }) +}) + +describe('buildLocation - params edge cases', () => { + test.each([false, true])( + 'keeps cached raw params intact across mutating lightweight parsers (throws: %s)', + (throws) => { + const root = new BaseRootRoute({}) + const parse = vi.fn((params: Record<string, string>) => { + expect(params.id).toBe('original') + params.id = 'parsed' + if (throws) { + throw new Error('parse failed') + } + return { id: params.id } + }) + const item = new BaseRoute({ + getParentRoute: () => root, + path: '/items/$id', + }) + const history = createMemoryHistory({ + initialEntries: ['/items/original'], + }) + const router = createTestRouter({ + routeTree: root.addChildren([item]), + history, + }) + // Isolate live lightweight parsing from the matcher's captured route gate. + item.options.params = { parse } + const update = vi.fn((params: Record<string, unknown>) => { + expect(params.id).toBe('parsed') + return { id: 'target' } + }) + try { + for (let repeat = 0; repeat < 2; repeat++) { + const location = router.buildLocation({ + to: '/items/$id', + _fromLocation: { ...router.latestLocation }, + params: update, + }) + expect(location.pathname).toBe('/items/target') + expect(router.getMatchedRoutes('/items/original')[1]).toEqual({ + id: 'original', + }) + } + expect(parse).toHaveBeenCalledTimes(2) + expect(parse.mock.calls[0]![0]).not.toBe(parse.mock.calls[1]![0]) + expect(update).toHaveBeenCalledTimes(2) + } finally { + history.destroy() + } + }, + ) + + test('isolates mutating params updaters while preserving inherit and clear modes', () => { + const rootRoute = new BaseRootRoute({}) + const userRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/{-$userId}', + }) + const history = createMemoryHistory({ initialEntries: ['/users/123'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([userRoute]), + history, + }) + const updater = vi.fn((params: { userId?: string }) => { + expect(Object.getPrototypeOf(params)).toBeNull() + expect(params).toEqual({ userId: '123' }) + params.userId = '456' + return params + }) + + try { + for (let i = 0; i < 2; i++) { + expect( + router.buildLocation({ + to: '/users/{-$userId}', + params: updater, + }).pathname, + ).toBe('/users/456') + } + expect(updater).toHaveBeenCalledTimes(2) + expect(updater.mock.calls[0]![0]).not.toBe(updater.mock.calls[1]![0]) + expect(router.buildLocation({ to: '/users/{-$userId}' }).pathname).toBe( + '/users/123', + ) + expect( + router.buildLocation({ to: '/users/{-$userId}', params: true }) + .pathname, + ).toBe('/users/123') + expect( + router.buildLocation({ to: '/users/{-$userId}', params: false }) + .pathname, + ).toBe('/users') + } finally { + history.destroy() + } + }) + + test('copies static param getters once without mutating inherited params', () => { + const rootRoute = new BaseRootRoute({}) + const userRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([userRoute]), + history: createMemoryHistory({ initialEntries: ['/users/123'] }), + }) + const getUserId = vi.fn(() => '456') + const params = { + get userId() { + return getUserId() + }, + } + + expect( + router.buildLocation({ to: '/users/$userId', params }).pathname, + ).toBe('/users/456') + expect(getUserId).toHaveBeenCalledOnce() + expect( + router.buildLocation({ to: '/users/$userId', params: true }).pathname, + ).toBe('/users/123') + }) + + test('params: true should preserve current params', async () => { + const rootRoute = new BaseRootRoute({}) + const userRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId', + }) + + const routeTree = rootRoute.addChildren([userRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/users/123'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/users/$userId', + params: true, + }) + + expect(location.pathname).toBe('/users/123') + }) + + test('params as object should set specific params', async () => { + const rootRoute = new BaseRootRoute({}) + const userRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId', + }) + + const routeTree = rootRoute.addChildren([userRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/users/123'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/users/$userId', + params: { userId: '456' }, + }) + + expect(location.pathname).toBe('/users/456') + }) + + test('params as object should merge with current params', async () => { + const rootRoute = new BaseRootRoute({}) + const orgRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/orgs/$orgId', + }) + const userRoute = new BaseRoute({ + getParentRoute: () => orgRoute, + path: '/users/$userId', + }) + + const routeTree = rootRoute.addChildren([orgRoute.addChildren([userRoute])]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/orgs/abc/users/123'] }), + }) + + await router.load() + + // Only update userId, orgId should be preserved + const location = router.buildLocation({ + to: '/orgs/$orgId/users/$userId', + params: (prev: { orgId: string; userId: string }) => ({ + ...prev, + userId: '456', + }), + }) + + expect(location.pathname).toBe('/orgs/abc/users/456') + }) + + test('params.stringify should transform params with custom formatting', async () => { + const rootRoute = new BaseRootRoute({}) + const userRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId', + params: { + parse: ({ userId }: { userId: string }) => ({ + userId: parseInt(userId, 10), + }), + // Stringify pads the userId to 6 digits + stringify: ({ userId }: { userId: number }) => ({ + userId: String(userId).padStart(6, '0'), + }), + }, + }) + + const routeTree = rootRoute.addChildren([userRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/users/000123'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/users/$userId', + params: { userId: 42 }, + }) + + // Without stringify, this would be '/users/42' + // With stringify, it should be padded to 6 digits + expect(location.pathname).toBe('/users/000042') + }) + + test('params.stringify should not mutate current params', async () => { + const rootRoute = new BaseRootRoute({}) + const userRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId', + params: { + parse: ({ userId }: { userId: string }) => ({ + userId: parseInt(userId, 10), + }), + stringify: (params: { userId: number }) => { + const userId = params.userId + params.userId = 999 + return { userId: String(userId).padStart(6, '0') } + }, + }, + }) + + const routeTree = rootRoute.addChildren([userRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/users/000123'] }), + }) + + await router.load() + + expect(router.buildLocation({ to: '/users/$userId' }).pathname).toBe( + '/users/000123', + ) + expect(router.state.matches.at(-1)?.params).toEqual({ userId: 123 }) + }) + + test('params.stringify should run for params.parse route templates', async () => { + const rootRoute = new BaseRootRoute({}) + const languageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/{$language}', + params: { + parse: ({ language }: { language: string }) => { + if (language === 'en') return { language: 'en-US' as const } + if (language === 'pl') return { language: 'pl-PL' as const } + return false + }, + stringify: ({ language }: { language: 'en-US' | 'pl-PL' }) => { + if (language === 'en-US') return { language: 'en' } + if (language === 'pl-PL') return { language: 'pl' } + return { language } + }, + }, + }) + + const routeTree = rootRoute.addChildren([languageRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/en'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/{$language}', + params: { language: 'pl-PL' }, + }) + + expect(location.pathname).toBe('/pl') + + const currentRouteLocation = router.buildLocation({ + params: { language: 'pl-PL' }, + } as any) + + expect(currentRouteLocation.pathname).toBe('/pl') + }) + + test('params.stringify should use the exact route template over path matching priority', async () => { + const rootRoute = new BaseRootRoute({}) + const dollarRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/$value', + params: { + parse: ({ value }: { value: string }) => { + if (value.startsWith('dollar-')) return { value } + return false + }, + stringify: ({ value }: { value: string }) => ({ + value: `dollar-${value}`, + }), + }, + }) + const curlyRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/{$value}', + params: { + parse: ({ value }: { value: string }) => { + if (value.startsWith('curly-')) return { value } + return false + }, + stringify: ({ value }: { value: string }) => ({ + value: `curly-${value}`, + }), + }, + }) + + const routeTree = rootRoute.addChildren([dollarRoute, curlyRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/dollar-home'] }), + }) + + await router.load() + + const curlyLocation = router.buildLocation({ + to: '/{$value}', + params: { value: 'alpha' }, + }) + const dollarLocation = router.buildLocation({ + to: '/$value', + params: { value: 'alpha' }, + }) + + expect(curlyLocation.pathname).toBe('/curly-alpha') + expect(dollarLocation.pathname).toBe('/dollar-alpha') + }) + + test('params.parse should gate path matching and provide typed params', async () => { + const rootRoute = new BaseRootRoute({}) + const userRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId', + params: { + parse: ({ userId }: { userId: string }) => { + const parsed = Number(userId) + if (!Number.isInteger(parsed)) return false + return { userId: parsed } + }, + stringify: ({ userId }: { userId: number }) => ({ + userId: String(userId), + }), + }, + }) + + const routeTree = rootRoute.addChildren([userRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/users/123'] }), + }) + + await router.load() + + expect(router.state.matches.at(-1)?.params).toEqual({ userId: 123 }) + + const location = router.buildLocation({ + to: '/users/$userId', + params: { userId: 456 }, + }) + + expect(location.pathname).toBe('/users/456') + }) + + test('buildLocation should warn in development when stringified params do not match the target route', async () => { + const rootRoute = new BaseRootRoute({}) + const staticRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/no', + }) + const dynamicRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/$foo', + params: { + stringify: () => ({ foo: 'no' }), + }, + }) + + const routeTree = rootRoute.addChildren([staticRoute, dynamicRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/yes'] }), + }) + + await router.load() + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + try { + const location = router.buildLocation({ + to: '/$foo', + params: { foo: 'yes' }, + }) + + expect(location.pathname).toBe('/no') + expect(warn).toHaveBeenCalledWith( + 'Generated path "/no" for route "/$foo" matched route "/no" instead. This can happen when multiple route templates resolve to the same URL. Use the route template that matches the intended route, or adjust params.stringify if it changed the target path.', + ) + } finally { + warn.mockRestore() + } + }) + + test('buildLocation should warn in development when a generated path matches an optional route template', async () => { + const rootRoute = new BaseRootRoute({}) + const timeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/time', + }) + const dayRoute = new BaseRoute({ + getParentRoute: () => timeRoute, + path: '{-$day}', + }) + + const routeTree = rootRoute.addChildren([timeRoute.addChildren([dayRoute])]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + try { + const location = router.buildLocation({ + to: '/time', + }) + + expect(location.pathname).toBe('/time') + expect(warn).toHaveBeenCalledWith( + 'Generated path "/time" for route "/time" matched route "/time/{-$day}" instead. This can happen when multiple route templates resolve to the same URL. Use the route template that matches the intended route, or adjust params.stringify if it changed the target path.', + ) + } finally { + warn.mockRestore() + } + }) + + test('params.stringify in nested routes should all be applied', async () => { + const rootRoute = new BaseRootRoute({}) + const orgRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/orgs/$orgId', + params: { + parse: ({ orgId }: { orgId: string }) => ({ + orgId: parseInt(orgId, 10), + }), + // Prefix org IDs with 'org-' + stringify: ({ orgId }: { orgId: number }) => ({ + orgId: `org-${orgId}`, + }), + }, + }) + const userRoute = new BaseRoute({ + getParentRoute: () => orgRoute, + path: '/users/$userId', + params: { + parse: ({ userId }: { userId: string }) => ({ + userId: parseInt(userId, 10), + }), + // Prefix user IDs with 'user-' + stringify: ({ userId }: { userId: number }) => ({ + userId: `user-${userId}`, + }), + }, + }) + + const routeTree = rootRoute.addChildren([orgRoute.addChildren([userRoute])]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/orgs/org-1/users/user-1'], + }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/orgs/$orgId/users/$userId', + params: { orgId: 42, userId: 123 }, + }) + + // Both stringify functions should be applied + expect(location.pathname).toBe('/orgs/org-42/users/user-123') + }) + + test('params function can transform params', async () => { + const rootRoute = new BaseRootRoute({}) + const userRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId', + }) + + const routeTree = rootRoute.addChildren([userRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/users/123'] }), + }) + + await router.load() + + // Transform the userId by appending a suffix + const location = router.buildLocation({ + to: '/users/$userId', + params: (prev: { userId: string }) => ({ + userId: `${prev.userId}-updated`, + }), + }) + + expect(location.pathname).toBe('/users/123-updated') + }) +}) + +describe('buildLocation - location output structure', () => { + test('location should contain all expected properties', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + search: { page: 1 }, + hash: 'section', + state: { modal: true } as any, + }) + + // Verify all expected properties exist + expect(location).toEqual({ + external: false, + hash: 'section', + href: '/posts?page=1#section', + pathname: '/posts', + publicHref: '/posts?page=1#section', + search: { + page: 1, + }, + searchStr: '?page=1', + state: { + modal: true, + }, + unmaskOnReload: undefined, + }) + }) + + test('empty search should result in empty searchStr', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + search: {}, + }) + + expect(location.searchStr).toBe('') + expect(location.href).toBe('/posts') + }) + + test('href options are not mutated', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([postsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const options = Object.freeze({ href: '/posts?page=1#section' }) + + const location = router.buildLocation(options as any) + + expect(location).toMatchObject({ + pathname: '/posts', + search: { page: 1 }, + hash: 'section', + }) + expect(options).toEqual({ href: '/posts?page=1#section' }) + }) +}) + +describe('buildLocation - optional params', () => { + test('optional param provided should be included in pathname', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts/{-$category}', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts/{-$category}', + params: { category: 'tech' }, + }) + + expect(location.pathname).toBe('/posts/tech') + }) + + test('optional param omitted should not appear in pathname', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts/{-$category}', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts/{-$category}', + params: {}, + }) + + expect(location.pathname).toBe('/posts') + }) + + test('multiple optional params - all provided', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts/{-$category}/{-$slug}', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts/{-$category}/{-$slug}', + params: { category: 'tech', slug: 'hello-world' }, + }) + + expect(location.pathname).toBe('/posts/tech/hello-world') + }) + + test('multiple optional params - partially provided', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts/{-$category}/{-$slug}', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts/{-$category}/{-$slug}', + params: { category: 'tech' }, + }) + + expect(location.pathname).toBe('/posts/tech') + }) + + test('mixed required and optional params', async () => { + const rootRoute = new BaseRootRoute({}) + const usersRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId/{-$tab}', + }) + + const routeTree = rootRoute.addChildren([usersRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/users/123'] }), + }) + + await router.load() + + // With optional param + const locationWithTab = router.buildLocation({ + to: '/users/$userId/{-$tab}', + params: { userId: '123', tab: 'settings' }, + }) + expect(locationWithTab.pathname).toBe('/users/123/settings') + + // Without optional param + const locationWithoutTab = router.buildLocation({ + to: '/users/$userId/{-$tab}', + params: { userId: '123' }, + }) + expect(locationWithoutTab.pathname).toBe('/users/123') + }) +}) + +describe('buildLocation - splat params', () => { + test('splat param should capture path segments', async () => { + const rootRoute = new BaseRootRoute({}) + const docsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/docs/$', + }) + + const routeTree = rootRoute.addChildren([docsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/docs'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/docs/$', + params: { _splat: 'getting-started/installation' }, + }) + + expect(location.pathname).toBe('/docs/getting-started/installation') + }) + + test('splat param with single segment', async () => { + const rootRoute = new BaseRootRoute({}) + const docsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/docs/$', + }) + + const routeTree = rootRoute.addChildren([docsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/docs'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/docs/$', + params: { _splat: 'overview' }, + }) + + expect(location.pathname).toBe('/docs/overview') + }) + + test('splat param empty should result in base path', async () => { + const rootRoute = new BaseRootRoute({}) + const docsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/docs/$', + }) + + const routeTree = rootRoute.addChildren([docsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/docs'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/docs/$', + params: { _splat: '' }, + }) + + expect(location.pathname).toBe('/docs') + }) + + test('splat param with prefix', async () => { + const rootRoute = new BaseRootRoute({}) + const filesRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/files/prefix{$}', + }) + + const routeTree = rootRoute.addChildren([filesRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/files'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/files/prefix{$}', + params: { _splat: 'path/to/file' }, + }) + + expect(location.pathname).toBe('/files/prefixpath/to/file') + }) +}) + +describe('buildLocation - _fromLocation override', () => { + test('_fromLocation should override current location for search resolution', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts?page=1'] }), + }) + + await router.load() + + // Override the current location with a different search + const location = router.buildLocation({ + to: '/posts', + search: true, // Preserve search from _fromLocation + _fromLocation: { + pathname: '/posts', + search: { page: 5 }, + searchStr: '?page=5', + hash: '', + href: '/posts?page=5', + state: {}, + }, + } as any) + + // Should use search from _fromLocation, not current location + expect(location.search).toEqual({ page: 5 }) + }) + + test('_fromLocation should override current location for hash resolution', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts#original'] }), + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + hash: true, // Preserve hash from _fromLocation + _fromLocation: { + pathname: '/posts', + search: {}, + searchStr: '', + hash: 'overridden', + href: '/posts#overridden', + state: {}, + }, + } as any) + + expect(location.hash).toBe('overridden') + }) + + test('_fromLocation should override current location for state resolution', async () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + + const routeTree = rootRoute.addChildren([postsRoute]) + + const history = createMemoryHistory({ initialEntries: ['/posts'] }) + history.replace('/posts', { original: true }) + + const router = createTestRouter({ + routeTree, + history, + }) + + await router.load() + + const location = router.buildLocation({ + to: '/posts', + state: true, // Preserve state from _fromLocation + _fromLocation: { + pathname: '/posts', + search: {}, + searchStr: '', + hash: '', + href: '/posts', + state: { overridden: true }, + }, + } as any) + + expect(location.state).toMatchObject({ overridden: true }) + }) + + test('_fromLocation should be used for relative path resolution', async () => { + const rootRoute = new BaseRootRoute({}) + const usersRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users', + }) + const userRoute = new BaseRoute({ + getParentRoute: () => usersRoute, + path: '/$userId', + }) + const settingsRoute = new BaseRoute({ + getParentRoute: () => userRoute, + path: '/settings', + }) + + const routeTree = rootRoute.addChildren([ + usersRoute.addChildren([userRoute.addChildren([settingsRoute])]), + ]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/users/123'] }), + }) + + await router.load() + + // When _fromLocation is provided, it affects the context for resolution + const location = router.buildLocation({ + to: './settings', + params: { userId: '456' }, + _fromLocation: { + pathname: '/users/456', + search: {}, + searchStr: '', + hash: '', + href: '/users/456', + state: {}, + }, + } as any) + + expect(location.pathname).toBe('/users/456/settings') + }) +}) diff --git a/packages/router-core/tests/cache-commit.bench.ts b/packages/router-core/tests/cache-commit.bench.ts new file mode 100644 index 0000000000..d570e55bf2 --- /dev/null +++ b/packages/router-core/tests/cache-commit.bench.ts @@ -0,0 +1,120 @@ +import { describe, expect, test } from 'vitest' +import { commitMatches } from '../src/load-client' +import type { AnyRouteMatch, AnyRouter } from '../src' +import type { LoaderFlight, LoadTransaction } from '../src/load-client' + +type Match = AnyRouteMatch & { _flight?: LoaderFlight } + +const workloads = [0, 4, 10, 100, 1000, 5000].flatMap((size) => [ + [size, 4], + [size, 16], +]) + +// Run each family separately with -t to keep GC from other workloads out of +// short operations. This measures commit/cache maintenance, not navigation. +for (const family of ['snapshots', 'mixed flights', 'preload flights']) { + describe.each(workloads)( + `${family}: %i cached matches, %i active matches`, + (size, activeCount) => { + for (const retainedFraction of [1, 0.5, 0]) { + const retainedCount = Math.floor(size * retainedFraction) + let aborts = 0 + const entries = Array.from({ length: size }, (_, index) => { + const retained = + retainedFraction === 1 || + (retainedFraction === 0.5 && index % 2 === 1) + const hasFlight = + family === 'preload flights' || + (family === 'mixed flights' && index % 10 === 0) + // Keep loader scheduling and AbortController allocation outside this + // ownership benchmark. Real abort events are covered in the unit tests. + const flight: LoaderFlight | undefined = hasFlight + ? [ + Promise.resolve([0, undefined]), + { + abort: () => { + aborts++ + }, + } as AbortController, + 1, + ] + : undefined + const match = { + id: String(index), + routeId: retained ? 'retained' : 'expired', + status: 'success', + updatedAt: 0, + _flight: flight, + } as Match + return { match, flight, retained } + }) + const cached = new Map(entries.map(({ match }) => [match.id, match])) + const departing = entries.filter( + (entry) => !entry.retained && entry.flight, + ) + const matches = Array.from({ length: activeCount }, (_, index) => ({ + id: `active-${index}`, + routeId: 'retained', + status: 'success', + })) as Array<Match> + const tx = [ + new AbortController(), + 0, + undefined, + [], + 0, + Promise.resolve(), + ] as unknown as LoadTransaction + const router = { + _tx: tx, + _committed: matches, + _cache: cached, + options: {}, + routesById: { + retained: { options: { loader: () => {}, gcTime: Infinity } }, + expired: { options: { loader: () => {}, gcTime: 0 } }, + }, + stores: { setMatches: () => {} }, + } as unknown as AnyRouter + const run = () => { + router._cache = cached + for (const entry of departing) { + entry.match._flight = entry.flight + entry.flight![2] = 1 + } + commitMatches(router, tx, matches) + } + run() + expect(router._cache.size).toBe(retainedCount) + expect(aborts).toBe(departing.length) + for (const entry of entries) { + if (entry.retained) { + expect(router._cache.get(entry.match.id)).toBe(entry.match) + expect(entry.match._flight).toBe(entry.flight) + if (entry.flight) { + expect(entry.flight[2]).toBe(1) + } + } else { + expect(entry.match._flight).toBeUndefined() + } + } + const batch = size <= 100 ? 100 : 1 + test(`${retainedFraction * 100}% retained (${batch} commits)`, async ({ + bench, + }) => { + await bench( + `${retainedFraction * 100}% retained (${batch} commits)`, + () => { + for (let index = 0; index < batch; index++) { + run() + } + }, + ).run({ + time: 500, + warmupTime: 100, + }) + }) + } + }, + ) +} diff --git a/packages/router-core/tests/cache-commit.test.ts b/packages/router-core/tests/cache-commit.test.ts new file mode 100644 index 0000000000..c7417da2e5 --- /dev/null +++ b/packages/router-core/tests/cache-commit.test.ts @@ -0,0 +1,255 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { commitMatches } from '../src/load-client' +import { createTestRouter } from './routerTestUtils' +import type { AnyRouteMatch, AnyRouter } from '../src' +import type { LoaderFlight, LoadTransaction } from '../src/load-client' + +type Match = AnyRouteMatch & { _flight?: LoaderFlight } + +function resource(leases = 1): LoaderFlight { + return [Promise.resolve([0, undefined]), new AbortController(), leases] +} + +function match(id: string, flight?: LoaderFlight): Match { + return { + id, + routeId: '/items/$id', + status: 'success', + updatedAt: 0, + _flight: flight, + } as Match +} + +function setup( + previous: Array<Match>, + cached: Array<Match>, + next = [match('next')], +) { + const tx = [ + new AbortController(), + 0, + undefined, + next, + 0, + Promise.resolve(), + ] as unknown as LoadTransaction + const publish = vi.fn() + const router = { + _tx: tx, + _committed: previous, + _cache: new Map(cached.map((entry) => [entry.id, entry])), + _flights: new Map( + [...previous, ...cached, ...next] + .filter((entry) => entry._flight) + .map((entry) => [entry.id, entry._flight!]), + ), + options: {}, + routesById: { + '/items/$id': { + options: { + loader: () => {}, + gcTime: Infinity, + preloadGcTime: Infinity, + }, + }, + }, + stores: { setMatches: publish }, + } as unknown as AnyRouter + return { + router, + publish, + tx, + next, + commit: () => commitMatches(router, tx, next), + } +} + +describe('commit cache ownership', () => { + test.each(['error', 'notFound', 'pending', 'global not found'] as const)( + 'only supersedes the rendered prefix and settled descendants at a %s boundary', + (boundaryKind) => { + const cached = [ + 'prefix', + 'boundary', + 'settled', + 'pending', + 'failed', + 'unrelated', + ].map((id) => match(id, resource())) + const next = cached.slice(0, -1).map((entry) => match(entry.id)) + if (boundaryKind === 'global not found') { + next[1]!._notFound = true + } else { + next[1]!.status = boundaryKind + } + next[3]!.status = 'pending' + next[4]!.status = 'error' + const { router, commit } = setup([], cached, next) + + commit() + + expect([...router._cache.keys()]).toEqual([ + 'pending', + 'failed', + 'unrelated', + ]) + for (const [index, entry] of cached.entries()) { + if (index < 3) { + expect(entry._flight).toBeUndefined() + } else { + expect(router._cache.get(entry.id)).toBe(entry) + expect(entry._flight?.[1].signal.aborted).toBe(false) + } + } + }, + ) + + test('retains cached identities and releases the committed owner cloned into cache', () => { + const retainedFlight = resource() + const departedFlight = resource() + const retained = match('retained', retainedFlight) + const departed = match('departed', departedFlight) + const { router, commit } = setup([departed], [retained]) + + commit() + + expect(router._cache.get('retained')).toBe(retained) + expect(retained._flight).toBe(retainedFlight) + expect(retainedFlight[2]).toBe(1) + expect(retainedFlight[1].signal.aborted).toBe(false) + expect(router._cache.get('departed')).not.toBe(departed) + expect((router._cache.get('departed') as Match)._flight).toBeUndefined() + expect(departed._flight).toBeUndefined() + expect(departedFlight[1].signal.aborted).toBe(true) + }) + + test('keeps a retained generation alive when a departing generation shares its flight', () => { + const shared = resource(2) + const departed = match('same', shared) + const retained = match('same', shared) + const { router, commit } = setup([departed], [retained]) + + commit() + + expect(router._cache.get('same')).toBe(retained) + expect(departed._flight).toBeUndefined() + expect(retained._flight).toBe(shared) + expect(shared[2]).toBe(1) + expect(shared[1].signal.aborted).toBe(false) + }) + + test('releases the old same-id generation without releasing its replacement', () => { + const oldFlight = resource() + const newFlight = resource() + const old = match('same', oldFlight) + const replacement = match('same', newFlight) + const { router, commit } = setup([], [old], [replacement]) + + commit() + + expect(router._cache.has('same')).toBe(false) + expect(old._flight).toBeUndefined() + expect(oldFlight[1].signal.aborted).toBe(true) + expect(replacement._flight).toBe(newFlight) + expect(newFlight[1].signal.aborted).toBe(false) + expect(router._flights?.get('same')).toBe(newFlight) + }) + + test('detaches all expired owners before abort listeners run, including duplicate objects', () => { + const shared = resource(2) + const first = match('first', shared) + const second = match('second', shared) + first.status = second.status = 'error' + const { router, tx, next, commit } = setup([first], [first, second]) + const onAbort = vi.fn(() => { + expect(first._flight).toBeUndefined() + expect(second._flight).toBeUndefined() + expect(router._cache.size).toBe(0) + expect(router._committed).toBe(next) + expect(tx[3]).toEqual([]) + }) + shared[1].signal.addEventListener('abort', onAbort) + + commit() + + expect(shared[2]).toBe(0) + expect(onAbort).toHaveBeenCalledOnce() + }) + + test('uses cache contents after synchronous publication mutation', () => { + const retainedFlight = resource() + const retained = match('retained', retainedFlight) + const { router, publish, commit } = setup([], [retained]) + publish.mockImplementation(() => router._cache.delete('retained')) + + commit() + + expect(retained._flight).toBeUndefined() + expect(retainedFlight[1].signal.aborted).toBe(true) + }) + + test('uses the captured cache if publication replaces the router cache', () => { + const retainedFlight = resource() + const retained = match('retained', retainedFlight) + const { router, publish, commit } = setup([], [retained]) + publish.mockImplementation(() => { + router._cache = new Map() + }) + + commit() + + expect(router._cache.size).toBe(0) + expect(retained._flight).toBe(retainedFlight) + expect(retainedFlight[1].signal.aborted).toBe(false) + }) +}) + +test('an unrelated navigation retains a fresh preload flight and evicts an expired one', async () => { + let freshSignal: AbortSignal | undefined + let expiredSignal: AbortSignal | undefined + const root = new BaseRootRoute({}) + const home = new BaseRoute({ getParentRoute: () => root, path: '/' }) + const other = new BaseRoute({ getParentRoute: () => root, path: '/other' }) + const freshLoader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + freshSignal = abortController.signal + return 'fresh data' + }, + ) + const fresh = new BaseRoute({ + getParentRoute: () => root, + path: '/fresh', + loader: freshLoader, + staleTime: Infinity, + preloadStaleTime: Infinity, + preloadGcTime: Infinity, + }) + const expired = new BaseRoute({ + getParentRoute: () => root, + path: '/expired', + loader: ({ abortController }) => { + expiredSignal = abortController.signal + return 'expired data' + }, + preloadGcTime: 0, + }) + const router = createTestRouter({ + routeTree: root.addChildren([home, other, fresh, expired]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + await router.preloadRoute({ to: '/fresh' }) + await router.preloadRoute({ to: '/expired' }) + expect(freshSignal?.aborted).toBe(false) + expect(expiredSignal?.aborted).toBe(false) + + await router.navigate({ to: '/other' }) + + expect(freshSignal?.aborted).toBe(false) + expect(expiredSignal?.aborted).toBe(true) + await router.navigate({ to: '/fresh' }) + expect(freshLoader).toHaveBeenCalledOnce() + expect(router.state.matches.at(-1)?.loaderData).toBe('fresh data') +}) diff --git a/packages/router-core/tests/cache-navigation.bench.ts b/packages/router-core/tests/cache-navigation.bench.ts new file mode 100644 index 0000000000..053aa645ac --- /dev/null +++ b/packages/router-core/tests/cache-navigation.bench.ts @@ -0,0 +1,52 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +// A public-API cross-check for the isolated commit benchmark. Preload seeding +// is outside the timed loop; replace navigations keep history size stationary. +for (const size of [0, 100, 1000, 5000]) { + const root = new BaseRootRoute({}) + const home = new BaseRoute({ getParentRoute: () => root, path: '/' }) + const other = new BaseRoute({ getParentRoute: () => root, path: '/other' }) + let loads = 0 + const item = new BaseRoute({ + getParentRoute: () => root, + path: '/items/$id', + loader: ({ params }) => { + loads++ + return params.id + }, + staleTime: Infinity, + preloadStaleTime: Infinity, + preloadGcTime: Infinity, + gcTime: Infinity, + }) + const router = createTestRouter({ + routeTree: root.addChildren([home, other, item]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + for (let index = 0; index < size; index++) { + await router.preloadRoute({ + to: '/items/$id', + params: { id: String(index) }, + }) + } + const navigate = async () => { + await router.navigate({ to: '/other', replace: true }) + await router.navigate({ to: '/', replace: true }) + } + await navigate() + expect(loads).toBe(size) + expect(router._cache.size).toBe(size) + expect(router.state.location.pathname).toBe('/') + describe(`${size} cached preloads`, () => { + test('two unrelated navigations', async ({ bench }) => { + await bench('two unrelated navigations', navigate).run({ + time: 1000, + warmupTime: 200, + }) + }) + }) +} diff --git a/packages/router-core/tests/callbacks.test.ts b/packages/router-core/tests/callbacks.test.ts index b6a5343eb6..7a1b062d4f 100644 --- a/packages/router-core/tests/callbacks.test.ts +++ b/packages/router-core/tests/callbacks.test.ts @@ -1,6 +1,7 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it, test, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' -import { BaseRootRoute, BaseRoute, RouterCore } from '../src' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' describe('callbacks', () => { const setup = ({ @@ -32,13 +33,42 @@ describe('callbacks', () => { const routeTree = rootRoute.addChildren([fooRoute, barRoute]) - const router = new RouterCore({ + const router = createTestRouter({ routeTree, history: createMemoryHistory(), }) return router } + + const createFooRouter = ( + opts: { + onEnter?: () => void + onLeave?: () => void + onStay?: () => void + loader?: () => unknown + staleTime?: number + } = {}, + ) => { + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loaderDeps: ({ search }: { search: Record<string, unknown> }) => ({ + page: search['page'], + }), + onEnter: opts.onEnter, + onLeave: opts.onLeave, + onStay: opts.onStay, + loader: opts.loader, + staleTime: opts.staleTime, + gcTime: opts.staleTime, + }) + return createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute]), + history: createMemoryHistory(), + }) + } describe('onEnter', () => { it('runs on navigate to a new route', async () => { const onEnter = vi.fn() @@ -102,5 +132,150 @@ describe('callbacks', () => { expect.objectContaining({ id: '/foo/foo', search: { foo: 'quux' } }), ) }) + + it('runs instead of onLeave/onEnter when loaderDeps change from search param updates', async () => { + const onEnter = vi.fn() + const onLeave = vi.fn() + const onStay = vi.fn() + const router = createFooRouter({ onEnter, onLeave, onStay }) + + // Navigate to foo — onEnter should fire + await router.navigate({ to: '/foo', search: { page: '1' } }) + expect(onEnter).toHaveBeenCalledTimes(1) + expect(onLeave).toHaveBeenCalledTimes(0) + expect(onStay).toHaveBeenCalledTimes(0) + + // Update search param that's in loaderDeps — onStay should fire, not onLeave+onEnter + await router.navigate({ to: '/foo', search: { page: '2' } }) + expect(onEnter).toHaveBeenCalledTimes(1) // no new onEnter + expect(onLeave).toHaveBeenCalledTimes(0) // no onLeave + expect(onStay).toHaveBeenCalledTimes(1) // onStay fires + + // Update again — onStay fires again + await router.navigate({ to: '/foo', search: { page: '3' } }) + expect(onEnter).toHaveBeenCalledTimes(1) + expect(onLeave).toHaveBeenCalledTimes(0) + expect(onStay).toHaveBeenCalledTimes(2) + }) + }) + + // Regression tests: switching lifecycle hooks to use routeId must NOT break + // match-level caching, which still relies on match.id (routeId + params + loaderDeps). + describe('same-route match caching', () => { + const setupWithPathParams = ({ + loader, + staleTime, + }: { + loader?: () => unknown + staleTime?: number + }) => { + const rootRoute = new BaseRootRoute({}) + const postRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts/$postId', + loader, + staleTime, + gcTime: staleTime, + }) + const routeTree = rootRoute.addChildren([postRoute]) + return createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + } + + test('keeps previous loaderDeps variant cached and reuses it within staleTime', async () => { + const loader = vi.fn() + const router = createFooRouter({ loader, staleTime: 60_000 }) + + await router.navigate({ to: '/foo', search: { page: '1' } }) + const page1MatchId = router.state.matches.find( + (d) => d.routeId === '/foo', + )?.id + expect(page1MatchId).toBeDefined() + + await router.navigate({ to: '/foo', search: { page: '2' } }) + const page2MatchId = router.state.matches.find( + (d) => d.routeId === '/foo', + )?.id + expect(page2MatchId).toBeDefined() + expect(page2MatchId).not.toBe(page1MatchId) + await router.navigate({ to: '/foo', search: { page: '1' } }) + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.some((d) => d.id === page1MatchId)).toBe(true) + }) + + test('keeps previous params variant cached and reuses it within staleTime', async () => { + const loader = vi.fn() + const router = setupWithPathParams({ loader, staleTime: 60_000 }) + + await router.navigate({ to: '/posts/$postId', params: { postId: '1' } }) + const post1MatchId = router.state.matches.find( + (d) => d.routeId === '/posts/$postId', + )?.id + expect(post1MatchId).toBeDefined() + + await router.navigate({ to: '/posts/$postId', params: { postId: '2' } }) + const post2MatchId = router.state.matches.find( + (d) => d.routeId === '/posts/$postId', + )?.id + expect(post2MatchId).toBeDefined() + expect(post2MatchId).not.toBe(post1MatchId) + await router.navigate({ to: '/posts/$postId', params: { postId: '1' } }) + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.some((d) => d.id === post1MatchId)).toBe(true) + }) + }) + + // Verify that router-level subscription events still fire correctly. + // These are used by integrations like Sentry's TanStack Router instrumentation + // (https://github.com/getsentry/sentry-javascript/blob/develop/packages/react/src/tanstackrouter.ts) + // to track page transitions. + describe('onBeforeNavigate event', () => { + it('fires when navigating to a new route', async () => { + const router = setup({}) + const onBeforeNavigate = vi.fn() + router.subscribe('onBeforeNavigate', onBeforeNavigate) + + await router.navigate({ to: '/foo' }) + expect(onBeforeNavigate).toHaveBeenCalledTimes(1) + expect(onBeforeNavigate).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'onBeforeNavigate', + pathChanged: true, + }), + ) + }) + + it('fires on every navigation including same-route loaderDeps changes', async () => { + const router = createFooRouter({}) + const onBeforeNavigate = vi.fn() + router.subscribe('onBeforeNavigate', onBeforeNavigate) + + await router.navigate({ to: '/foo', search: { page: '1' } }) + expect(onBeforeNavigate).toHaveBeenCalledTimes(1) + + // loaderDeps change — same route, different params + await router.navigate({ to: '/foo', search: { page: '2' } }) + expect(onBeforeNavigate).toHaveBeenCalledTimes(2) + }) + + it('includes toLocation and pathChanged in the event', async () => { + const router = setup({}) + const events: Array<{ to: string; pathChanged: boolean }> = [] + router.subscribe('onBeforeNavigate', (e) => { + events.push({ + to: e.toLocation.pathname, + pathChanged: e.pathChanged, + }) + }) + + await router.navigate({ to: '/foo' }) + await router.navigate({ to: '/bar' }) + + expect(events).toHaveLength(2) + expect(events[0]).toMatchObject({ to: '/foo', pathChanged: true }) + expect(events[1]).toMatchObject({ to: '/bar', pathChanged: true }) + }) }) }) diff --git a/packages/router-core/tests/chunk-failure-lifecycle.test.ts b/packages/router-core/tests/chunk-failure-lifecycle.test.ts new file mode 100644 index 0000000000..bf9fa369d4 --- /dev/null +++ b/packages/router-core/tests/chunk-failure-lifecycle.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * primary route chunk failures should go through the same route-error + * lifecycle as loader and beforeLoad failures. Skipping normalization means + * route onError callbacks, redirects, and notFound values from lazy/chunk + * loading can behave differently from other route failures. + * + * This test uses a real router navigation to a lazy route whose chunk rejects. + * The match reaches error state with the chunk error, but the route's onError + * callback should also receive that error as part of normal route failure + * handling. + */ + +describe('route chunk failure lifecycle', () => { + test('a rejected lazy chunk is retried on the next load instead of replaying forever', async () => { + let lazyCalls = 0 + const chunkError = new Error('lazy chunk failed once') + + const rootRoute = new BaseRootRoute({}) + const lazyRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/lazy', + loader: () => 'loaded', + }).lazy(() => { + lazyCalls++ + if (lazyCalls === 1) { + return Promise.reject(chunkError) + } + return Promise.resolve({ options: {} } as any) + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([lazyRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.navigate({ to: '/lazy' }) + expect( + router.state.matches.find((match) => match.routeId === lazyRoute.id) + ?.status, + ).toBe('error') + + await router.invalidate() + expect(lazyCalls).toBe(2) + expect( + router.state.matches.find((match) => match.routeId === lazyRoute.id) + ?.status, + ).toBe('success') + }) + + test('calls route onError when lazy route chunk rejects during navigation', async () => { + const chunkError = new Error('lazy chunk failed') + let capturedError: unknown + + const rootRoute = new BaseRootRoute({}) + const lazyRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/lazy', + onError: (error) => { + capturedError = error + }, + }).lazy(() => Promise.reject(chunkError)) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([lazyRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.navigate({ to: '/lazy' }) + + const lazyMatch = router.state.matches.find( + (match) => match.routeId === lazyRoute.id, + ) + expect(lazyMatch?.status).toBe('error') + expect(lazyMatch?.error).toBe(chunkError) + expect(capturedError).toBe(chunkError) + }) +}) diff --git a/packages/router-core/tests/client-lane-adversarial.test.ts b/packages/router-core/tests/client-lane-adversarial.test.ts new file mode 100644 index 0000000000..4924576759 --- /dev/null +++ b/packages/router-core/tests/client-lane-adversarial.test.ts @@ -0,0 +1,796 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, + redirect, +} from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +afterEach(() => { + vi.useRealTimers() +}) + +function abortAwareGate(signal: AbortSignal): Promise<void> { + return new Promise((_resolve, reject) => { + signal.addEventListener( + 'abort', + () => { + const error = new Error('aborted') + error.name = 'AbortError' + reject(error) + }, + { once: true }, + ) + }) +} + +describe('adversarial client lane ownership', () => { + test('a navigation started by a pre-load listener supersedes the emitting load before it can continue', async () => { + const firstBeforeLoad = vi.fn() + const secondBeforeLoad = vi.fn() + const firstLoader = vi.fn(() => 'first data') + const secondLoader = vi.fn(() => 'second data') + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/first', + beforeLoad: firstBeforeLoad, + loader: firstLoader, + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/second', + beforeLoad: secondBeforeLoad, + loader: secondLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, firstRoute, secondRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const beforeLoadLocations: Array<string> = [] + router.subscribe('onBeforeLoad', (event) => { + beforeLoadLocations.push(event.toLocation.pathname) + }) + router.subscribe('onBeforeNavigate', (event) => { + if (event.toLocation.pathname === '/first') { + void router.navigate({ to: '/second' }) + } + }) + + await router.navigate({ to: '/first' }) + + expect(router.state.location.pathname).toBe('/second') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: secondRoute.id, + status: 'success', + }) + expect(beforeLoadLocations).toEqual(['/second']) + expect(firstBeforeLoad).not.toHaveBeenCalled() + expect(firstLoader).not.toHaveBeenCalled() + expect(secondBeforeLoad).toHaveBeenCalledTimes(1) + expect(secondLoader).toHaveBeenCalledTimes(1) + }) + + test.each(['onBeforeNavigate', 'onBeforeLoad'] as const)( + 'a throwing %s listener cannot interrupt later listeners or navigation finalization', + async (eventType) => { + const listenerError = new Error(`${eventType} listener failed`) + const laterListener = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetLoader = vi.fn(() => 'target data') + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: targetLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + router.subscribe(eventType, () => { + throw listenerError + }) + router.subscribe(eventType, laterListener) + + await router.navigate({ to: '/target' }) + + expect(laterListener).toHaveBeenCalledTimes(1) + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + expect(targetLoader).toHaveBeenCalledTimes(1) + }, + ) + + test('superseding a published pending lane diffs lifecycle hooks from the last final lane', async () => { + const aOnLeave = vi.fn() + const bOnEnter = vi.fn() + const bOnLeave = vi.fn() + const cOnEnter = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + onLeave: aOnLeave, + }) + const bRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/b', + pendingMs: 0, + pendingComponent: () => null, + loader: ({ abortController }) => abortAwareGate(abortController.signal), + onEnter: bOnEnter, + onLeave: bOnLeave, + }) + const cRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/c', + onEnter: cOnEnter, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([aRoute, bRoute, cRoute]), + history: createMemoryHistory({ initialEntries: ['/a'] }), + }) + + await router.load() + aOnLeave.mockClear() + + const bNavigation = router.navigate({ to: '/b' }) + await vi.waitFor(() => + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: bRoute.id, + status: 'pending', + }), + ) + + await router.navigate({ to: '/c' }) + await bNavigation + + expect(router.state.matches.at(-1)?.routeId).toBe(cRoute.id) + expect(aOnLeave).toHaveBeenCalledTimes(1) + expect(bOnEnter).not.toHaveBeenCalled() + expect(bOnLeave).not.toHaveBeenCalled() + expect(cOnEnter).toHaveBeenCalledTimes(1) + }) + + test('supersession cancels lazy not-found boundary lookup without leaking pending ownership', async () => { + const lazyStarted = createControlledPromise<void>() + const lazyGate = createControlledPromise<any>() + const safeHeadStarted = createControlledPromise<void>() + const safeHeadGate = createControlledPromise<void>() + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const missingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/missing', + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () => null, + beforeLoad: () => { + throw notFound() + }, + }).lazy(() => { + lazyStarted.resolve() + return lazyGate + }) + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + head: async () => { + safeHeadStarted.resolve() + await safeHeadGate + return {} + }, + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, missingRoute, safeRoute]), + history, + }) + + await router.load() + history.push('/missing') + const supersededLoad = router.load() + await lazyStarted + const supersededTx = router._tx! + expect(router._pending?.[0]).toBe(supersededTx) + + let supersededOutcome: unknown + const observedSupersededLoad = supersededLoad.then( + () => { + supersededOutcome = 'resolved' + }, + (cause) => { + supersededOutcome = cause + }, + ) + history.push('/safe') + const replacementLoad = router.load() + await safeHeadStarted + await new Promise<void>((resolve) => setTimeout(resolve, 0)) + + expect(supersededOutcome).toBeUndefined() + expect(safeHeadGate.status).toBe('pending') + expect(router._pending).toBeUndefined() + expect(router.state.matches.at(-1)?.routeId).toBe(missingRoute.id) + + safeHeadGate.resolve() + lazyGate.resolve({ options: { notFoundComponent: () => null } }) + await Promise.all([observedSupersededLoad, replacementLoad]) + + expect(supersededOutcome).toBe('resolved') + expect(router._pending).toBeUndefined() + expect(router.state).toMatchObject({ + status: 'idle', + location: { pathname: '/safe' }, + }) + expect(router.state.matches.at(-1)?.routeId).toBe(safeRoute.id) + history.destroy() + }) + + test('an unrelated third load clears a pending session awaiting same-boundary takeover', async () => { + const pageStarted = createControlledPromise<void>() + const pageGate = createControlledPromise<void>() + const retainedStarted = createControlledPromise<void>() + const retainedGate = createControlledPromise<void>() + const safeHeadStarted = createControlledPromise<void>() + const safeHeadGate = createControlledPromise<void>() + + const rootRoute = new BaseRootRoute({ + validateSearch: (search: Record<string, unknown>) => ({ + revision: Number(search.revision) || 0, + }), + beforeLoad: ({ search }) => { + if (search.revision === 2) { + retainedStarted.resolve() + return retainedGate.then(() => ({})) + } + return {} + }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () => null, + beforeLoad: ({ search }) => { + if (search.revision === 1) { + pageStarted.resolve() + return pageGate.then(() => ({})) + } + return {} + }, + }) + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + head: async () => { + safeHeadStarted.resolve() + await safeHeadGate + return {} + }, + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute, safeRoute]), + history, + }) + + await router.load() + const loads: Array<Promise<void>> = [] + try { + history.push('/page?revision=1') + const firstLoad = router.load() + loads.push(firstLoad) + await pageStarted + const firstTx = router._tx! + await vi.waitFor(() => expect(router._pending?.[0]).toBe(firstTx)) + + history.push('/page?revision=2') + const secondLoad = router.load() + loads.push(secondLoad) + await retainedStarted + await new Promise<void>((resolve) => setTimeout(resolve, 0)) + expect(router._pending?.[0]).toBe(firstTx) + + history.push('/safe') + const thirdLoad = router.load() + loads.push(thirdLoad) + await safeHeadStarted + await new Promise<void>((resolve) => setTimeout(resolve, 0)) + + expect(router._pending).toBeUndefined() + } finally { + pageGate.resolve() + retainedGate.resolve() + safeHeadGate.resolve() + await Promise.allSettled(loads) + history.destroy() + } + }) + + test('a live signal rejected by lazy not-found lookup is not treated as cancellation', async () => { + let laneSignal: AbortSignal | undefined + const rootRoute = new BaseRootRoute({}) + const missingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/missing', + beforeLoad: ({ abortController }) => { + laneSignal = abortController.signal + throw notFound() + }, + }).lazy(() => Promise.reject(laneSignal)) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([missingRoute]), + history: createMemoryHistory({ initialEntries: ['/missing'] }), + }) + + await router.load() + + expect(laneSignal?.aborted).toBe(false) + expect(router.state.status).toBe('idle') + expect(router.state.location.pathname).toBe('/missing') + expect(router.state.resolvedLocation?.pathname).toBe('/missing') + expect(router.state.matches.at(-1)?.status).not.toBe('pending') + }) + + test('keeps a hidden child matched without projecting it below a parent error', async () => { + const parentError = new Error('parent failed') + const parentOnEnter = vi.fn() + const childHead = vi.fn() + const childOnEnter = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw parentError + }, + errorComponent: () => null, + onEnter: parentOnEnter, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => { + throw notFound() + }, + notFoundComponent: () => null, + head: childHead, + onEnter: childOnEnter, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]) + expect(router.state.matches[1]).toMatchObject({ + routeId: parentRoute.id, + status: 'error', + error: parentError, + }) + expect(childHead).not.toHaveBeenCalled() + expect(childOnEnter).not.toHaveBeenCalled() + expect(parentOnEnter).toHaveBeenCalledOnce() + }) + + test('a redirect aborts the discarded loader generation', async () => { + let redirectSignal: AbortSignal | undefined + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: ({ abortController }) => { + redirectSignal = abortController.signal + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/source' }) + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + expect(redirectSignal?.aborted).toBe(true) + }) + + test('a navigation started while releasing a redirect lane supersedes that redirect', async () => { + let successorNavigation: Promise<void> | undefined + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: ({ abortController }) => { + abortController.signal.addEventListener( + 'abort', + () => { + successorNavigation = router.navigate({ to: '/successor' }) + }, + { once: true }, + ) + throw redirect({ to: '/redirect-target' }) + }, + }) + const redirectTargetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/redirect-target', + }) + const successorRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/successor', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + sourceRoute, + redirectTargetRoute, + successorRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/source' }) + await successorNavigation + + expect(router.state.location.pathname).toBe('/successor') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: successorRoute.id, + status: 'success', + }) + }) + + test('keeps successful descendant data behind an ancestor boundary', async () => { + const parentError = new Error('parent failed') + const childData = { value: 'child data' } + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw parentError + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => childData, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + + expect(router.state.matches[1]).toMatchObject({ + routeId: parentRoute.id, + status: 'error', + error: parentError, + }) + expect(router.state.matches[2]).toMatchObject({ + routeId: childRoute.id, + status: 'success', + loaderData: childData, + }) + }) + + test('a terminal preload retains reusable descendant loader data', async () => { + const parentError = new Error('preload parent failed') + const childLoader = vi.fn(() => 'child data') + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw parentError + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/parent/child' }) + await router.navigate({ to: '/parent/child' }) + + expect(childLoader).toHaveBeenCalledTimes(1) + expect(router.state.matches[2]).toMatchObject({ + routeId: childRoute.id, + status: 'success', + loaderData: 'child data', + }) + }) + + test('navigation started by route context cannot be overwritten by the stale matching pass', async () => { + const bLoaderGate = createControlledPromise<void>() + const bLoader = vi.fn(() => bLoaderGate) + let retainedLoaderSignal: AbortSignal | undefined + let abandonedContextSignal: AbortSignal | undefined + let redirected = false + + const rootRoute = new BaseRootRoute({ + staleTime: Infinity, + loader: ({ abortController }) => { + retainedLoaderSignal = abortController.signal + return 'root data' + }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + context: ({ navigate, abortController }) => { + abandonedContextSignal = abortController.signal + if (!redirected) { + redirected = true + void navigate({ to: '/b' }) + } + return { fromA: true } + }, + }) + const bRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/b', + loader: bLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, aRoute, bRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const navigation = router.navigate({ to: '/a' }) + await vi.waitFor(() => expect(bLoader).toHaveBeenCalledTimes(1)) + + bLoaderGate.resolve() + await navigation + + expect(router.state.location.pathname).toBe('/b') + expect(router.state.matches.at(-1)?.routeId).toBe(bRoute.id) + expect(abandonedContextSignal?.aborted).toBe(true) + expect(retainedLoaderSignal?.aborted).toBe(false) + }) + + test('a context-failure lane stays live until its terminal generation is replaced', async () => { + const contextError = new Error('context failed after starting work') + + let contextSignal: AbortSignal | undefined + let contextWorkAborted = false + const safeLoader = vi.fn(() => 'safe data') + + const rootRoute = new BaseRootRoute({}) + const brokenRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/broken', + context: ({ abortController }) => { + contextSignal = abortController.signal + abortController.signal.addEventListener( + 'abort', + () => { + contextWorkAborted = true + }, + { once: true }, + ) + throw contextError + }, + }) + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + loader: safeLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([brokenRoute, safeRoute]), + history: createMemoryHistory({ initialEntries: ['/broken'] }), + }) + + await router.load() + expect(contextSignal?.aborted).toBe(false) + expect(contextWorkAborted).toBe(false) + + await router.navigate({ to: '/safe' }) + expect(router.state.location.pathname).toBe('/safe') + expect(safeLoader).toHaveBeenCalledTimes(1) + expect(contextSignal?.aborted).toBe(true) + expect(contextWorkAborted).toBe(true) + }) + + test.each([ + { + isServer: false, + thrownType: 'AbortSignal', + createThrownValue: (signal: AbortSignal) => signal, + }, + { + isServer: false, + thrownType: 'AbortError', + createThrownValue: () => + new DOMException('The operation was aborted.', 'AbortError'), + }, + { + isServer: true, + thrownType: 'AbortError', + createThrownValue: () => + Object.assign(new Error('The operation was aborted.'), { + name: 'AbortError', + }), + }, + ])( + 'treats a user-thrown $thrownType in beforeLoad as an ordinary route error (isServer=$isServer)', + async ({ isServer, createThrownValue }) => { + let matchSignal: AbortSignal | undefined + let thrownValue: unknown + const rootRoute = new BaseRootRoute({}) + const brokenRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/broken', + beforeLoad: ({ abortController }) => { + matchSignal = abortController.signal + thrownValue = createThrownValue(matchSignal) + throw thrownValue + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([brokenRoute]), + history: createMemoryHistory({ initialEntries: ['/broken'] }), + isServer, + }) + + if (isServer) { + const response = await loadServerResponse(router, '/broken') + expect(response.status).toBe(500) + } else { + await router.load() + } + + const match = router.state.matches.at(-1) + // The payload finished, so the controller is left alone on both sides. + expect(matchSignal?.aborted).toBe(false) + expect(match).toMatchObject({ + routeId: brokenRoute.id, + status: 'error', + }) + expect(match?.error).toBe(thrownValue) + }, + ) + + test('a planning failure becomes the successor lane instead of stranding navigation', async () => { + const preflightError = new Error('next loaderDeps failed') + const pendingGate = createControlledPromise<void>() + const brokenPreflightReached = createControlledPromise<void>() + let pendingSignal: AbortSignal | undefined + const pendingStarted = createControlledPromise<void>() + + const rootRoute = new BaseRootRoute({}) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + }) + const pendingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/pending', + pendingMs: 0, + pendingComponent: () => null, + loader: ({ abortController }) => { + pendingSignal = abortController.signal + pendingStarted.resolve() + return Promise.race([ + pendingGate, + abortAwareGate(abortController.signal), + ]) + }, + }) + const brokenRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/broken', + loaderDeps: (): Record<string, never> => { + brokenPreflightReached.resolve() + throw preflightError + }, + loader: () => 'never runs', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([aRoute, pendingRoute, brokenRoute]), + history: createMemoryHistory({ initialEntries: ['/a'] }), + }) + + await router.load() + const pendingNavigation = router.navigate({ to: '/pending' }) + await pendingStarted + + const brokenNavigation = router.navigate({ to: '/broken' }) + await brokenPreflightReached + + await vi.waitFor(() => expect(pendingSignal?.aborted).toBe(true)) + + pendingGate.resolve() + await Promise.all([pendingNavigation, brokenNavigation]) + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: brokenRoute.id, + status: 'error', + error: preflightError, + }) + expect(router.state.location.pathname).toBe('/broken') + }) +}) diff --git a/packages/router-core/tests/closing-tag-detection.bench.ts b/packages/router-core/tests/closing-tag-detection.bench.ts new file mode 100644 index 0000000000..641c016bb4 --- /dev/null +++ b/packages/router-core/tests/closing-tag-detection.bench.ts @@ -0,0 +1,981 @@ +import { describe, test } from 'vitest' + +const BODY_END_TAG = '</body>' +const MIN_CLOSING_TAG_LENGTH = 4 + +/** + * Benchmark comparing different approaches for finding the last closing tag in HTML chunks. + * + * The goal is to find the position just after the last closing tag (e.g., </div>, </my-component>) + * so we can insert router HTML at that point. + * + * Requirements (from the regex pattern /(<\/[a-zA-Z][\w:.-]*?>)/g): + * - Closing tag starts with </ + * - First character after </ must be a letter (a-zA-Z) + * - Followed by any combination of word chars (\w = [a-zA-Z0-9_]), colons, dots, or hyphens + * - Ends with > + */ + +// ============================================================================ +// Implementation 1: Regex-based (current implementation) +// ============================================================================ +function findLastClosingTagRegex(str: string): number { + const patternClosingTag = /(<\/[a-zA-Z][\w:.-]*?>)/g + let lastIndex = 0 + let result: RegExpExecArray | null + while ((result = patternClosingTag.exec(str)) !== null) { + lastIndex = result.index + result[0].length + } + return lastIndex > 0 ? lastIndex : -1 +} + +// ============================================================================ +// Implementation 2: Manual backwards scan +// ============================================================================ +function isTagNameStartChar(char: string): boolean { + const code = char.charCodeAt(0) + // a-z: 97-122, A-Z: 65-90 + return (code >= 97 && code <= 122) || (code >= 65 && code <= 90) +} + +function isTagNameChar(char: string): boolean { + const code = char.charCodeAt(0) + // a-z: 97-122, A-Z: 65-90, 0-9: 48-57, _: 95, :: 58, .: 46, -: 45 + return ( + (code >= 97 && code <= 122) || // a-z + (code >= 65 && code <= 90) || // A-Z + (code >= 48 && code <= 57) || // 0-9 + code === 95 || // _ + code === 58 || // : + code === 46 || // . + code === 45 // - + ) +} + +function findLastClosingTagManual(str: string): number { + // Search backwards for </...> pattern + let i = str.length - 1 + + while (i >= 1) { + // Look for > + if (str[i] === '>') { + // Look backwards for </ + let j = i - 1 + let foundValidTag = false + + // Skip through valid tag name characters + while (j >= 1 && isTagNameChar(str[j]!)) { + j-- + } + + // Check if the first char after </ is a valid start char (letter only) + const tagNameStart = j + 1 + if (tagNameStart < i && isTagNameStartChar(str[tagNameStart]!)) { + // Check for </ + if (j >= 1 && str[j] === '/' && str[j - 1] === '<') { + foundValidTag = true + } + } + + if (foundValidTag) { + return i + 1 // Return position after the closing > + } + } + i-- + } + return -1 +} + +// ============================================================================ +// Implementation 3: Optimized manual with charCodeAt (avoid string indexing) +// ============================================================================ +function findLastClosingTagOptimized(str: string): number { + const len = str.length + if (len < 4) return -1 // Minimum: </a> + + let i = len - 1 + + while (i >= 3) { + // Need at least 4 chars: </a> + // Look for > (charCode 62) + if (str.charCodeAt(i) === 62) { + // Look backwards for </ + let j = i - 1 + + // Skip through valid tag name characters + while (j >= 1) { + const code = str.charCodeAt(j) + // Check if it's a valid tag name char + if ( + (code >= 97 && code <= 122) || // a-z + (code >= 65 && code <= 90) || // A-Z + (code >= 48 && code <= 57) || // 0-9 + code === 95 || // _ + code === 58 || // : + code === 46 || // . + code === 45 // - + ) { + j-- + } else { + break + } + } + + // Check if the first char after </ is a valid start char (letter only) + const tagNameStart = j + 1 + if (tagNameStart < i) { + const startCode = str.charCodeAt(tagNameStart) + // Must start with a letter + if ( + (startCode >= 97 && startCode <= 122) || + (startCode >= 65 && startCode <= 90) + ) { + // Check for </ (charCodes: < = 60, / = 47) + if ( + j >= 1 && + str.charCodeAt(j) === 47 && + str.charCodeAt(j - 1) === 60 + ) { + return i + 1 // Return position after the closing > + } + } + } + } + i-- + } + return -1 +} + +// ============================================================================ +// Implementation 4: Hybrid - use lastIndexOf to find candidates, then validate +// ============================================================================ +function findLastClosingTagHybrid(str: string): number { + let searchFrom = str.length - 1 + + while (searchFrom >= 3) { + // Find the last > starting from searchFrom + const closeIndex = str.lastIndexOf('>', searchFrom) + if (closeIndex < 3) return -1 // Not enough room for </a> + + // Look backwards for </ + let j = closeIndex - 1 + + // Skip through valid tag name characters using charCodeAt + while (j >= 1) { + const code = str.charCodeAt(j) + if ( + (code >= 97 && code <= 122) || // a-z + (code >= 65 && code <= 90) || // A-Z + (code >= 48 && code <= 57) || // 0-9 + code === 95 || // _ + code === 58 || // : + code === 46 || // . + code === 45 // - + ) { + j-- + } else { + break + } + } + + // Check if the first char after </ is a valid start char (letter only) + const tagNameStart = j + 1 + if (tagNameStart < closeIndex) { + const startCode = str.charCodeAt(tagNameStart) + if ( + (startCode >= 97 && startCode <= 122) || + (startCode >= 65 && startCode <= 90) + ) { + if ( + j >= 1 && + str.charCodeAt(j) === 47 && + str.charCodeAt(j - 1) === 60 + ) { + return closeIndex + 1 + } + } + } + + // Not a valid tag, continue searching before this > + searchFrom = closeIndex - 1 + } + + return -1 +} + +// ============================================================================ +// Body end tag detection variants +// ============================================================================ +function findBodyEndTagForward(str: string): number { + for (let i = 0; i <= str.length - BODY_END_TAG.length; i++) { + if ( + str.charCodeAt(i) === 60 && + str.charCodeAt(i + 1) === 47 && + (str.charCodeAt(i + 2) | 32) === 98 && + (str.charCodeAt(i + 3) | 32) === 111 && + (str.charCodeAt(i + 4) | 32) === 100 && + (str.charCodeAt(i + 5) | 32) === 121 && + str.charCodeAt(i + 6) === 62 + ) { + return i + } + } + return -1 +} + +function findBodyEndTagBackward(str: string): number { + for (let i = str.length - BODY_END_TAG.length; i >= 0; i--) { + if ( + str.charCodeAt(i) === 60 && + str.charCodeAt(i + 1) === 47 && + (str.charCodeAt(i + 2) | 32) === 98 && + (str.charCodeAt(i + 3) | 32) === 111 && + (str.charCodeAt(i + 4) | 32) === 100 && + (str.charCodeAt(i + 5) | 32) === 121 && + str.charCodeAt(i + 6) === 62 + ) { + return i + } + } + return -1 +} + +function findBodyEndTagLastOpenSlash(str: string): number { + let searchFrom = str.length - BODY_END_TAG.length + + while (searchFrom >= 0) { + const start = str.lastIndexOf('</', searchFrom) + if (start === -1) return -1 + + if ( + (str.charCodeAt(start + 2) | 32) === 98 && + (str.charCodeAt(start + 3) | 32) === 111 && + (str.charCodeAt(start + 4) | 32) === 100 && + (str.charCodeAt(start + 5) | 32) === 121 && + str.charCodeAt(start + 6) === 62 + ) { + return start + } + + searchFrom = start - 1 + } + + return -1 +} + +function findBodyEndTagNativeLowerThenLastOpenSlash(str: string): number { + const index = str.lastIndexOf(BODY_END_TAG) + return index === -1 ? findBodyEndTagLastOpenSlash(str) : index +} + +type BoundaryScanResult = { + bodyEndIndex: number + lastClosingTagEnd: number +} + +function findHtmlBoundaryCombined(str: string): BoundaryScanResult { + const len = str.length + let lastClosingTagEnd = -1 + let searchFrom = len - 1 + + while (searchFrom >= MIN_CLOSING_TAG_LENGTH - 1) { + const closeIndex = str.lastIndexOf('>', searchFrom) + if (closeIndex < MIN_CLOSING_TAG_LENGTH - 1) break + + let j = closeIndex - 1 + while (j >= 1) { + const code = str.charCodeAt(j) + if ( + (code >= 97 && code <= 122) || + (code >= 65 && code <= 90) || + (code >= 48 && code <= 57) || + code === 95 || + code === 58 || + code === 46 || + code === 45 + ) { + j-- + } else { + break + } + } + + const tagNameStart = j + 1 + if (tagNameStart < closeIndex) { + const startCode = str.charCodeAt(tagNameStart) + if ( + ((startCode >= 97 && startCode <= 122) || + (startCode >= 65 && startCode <= 90)) && + j >= 1 && + str.charCodeAt(j) === 47 && + str.charCodeAt(j - 1) === 60 + ) { + if (lastClosingTagEnd === -1) { + lastClosingTagEnd = closeIndex + 1 + } + + if ( + closeIndex - tagNameStart === 4 && + (str.charCodeAt(tagNameStart) | 32) === 98 && + (str.charCodeAt(tagNameStart + 1) | 32) === 111 && + (str.charCodeAt(tagNameStart + 2) | 32) === 100 && + (str.charCodeAt(tagNameStart + 3) | 32) === 121 + ) { + return { bodyEndIndex: j - 1, lastClosingTagEnd } + } + } + } + + searchFrom = closeIndex - 1 + } + + return { bodyEndIndex: -1, lastClosingTagEnd } +} + +function findHtmlBoundaryLastOpenSlash(str: string): BoundaryScanResult { + let bodyEndIndex = -1 + let lastClosingTagEnd = -1 + let searchFrom = str.length - MIN_CLOSING_TAG_LENGTH + + while (searchFrom >= 0) { + const openSlash = str.lastIndexOf('</', searchFrom) + if (openSlash === -1) break + + let i = openSlash + 2 + const startCode = str.charCodeAt(i) + if ( + (startCode >= 97 && startCode <= 122) || + (startCode >= 65 && startCode <= 90) + ) { + i++ + while (i < str.length) { + const code = str.charCodeAt(i) + if ( + (code >= 97 && code <= 122) || + (code >= 65 && code <= 90) || + (code >= 48 && code <= 57) || + code === 95 || + code === 58 || + code === 46 || + code === 45 + ) { + i++ + } else { + break + } + } + + if (str.charCodeAt(i) === 62) { + if (lastClosingTagEnd === -1) { + lastClosingTagEnd = i + 1 + } + + if ( + i - openSlash === BODY_END_TAG.length - 1 && + (str.charCodeAt(openSlash + 2) | 32) === 98 && + (str.charCodeAt(openSlash + 3) | 32) === 111 && + (str.charCodeAt(openSlash + 4) | 32) === 100 && + (str.charCodeAt(openSlash + 5) | 32) === 121 + ) { + bodyEndIndex = openSlash + break + } + } + } + + searchFrom = openSlash - 1 + } + + return { bodyEndIndex, lastClosingTagEnd } +} + +function findHtmlBoundaryLastOpenSlashLazy(str: string): BoundaryScanResult { + let lastClosingTagEnd = -1 + let searchFrom = str.length - MIN_CLOSING_TAG_LENGTH + + while (searchFrom >= 0) { + const openSlash = str.lastIndexOf('</', searchFrom) + if (openSlash === -1) break + + if ( + (str.charCodeAt(openSlash + 2) | 32) === 98 && + (str.charCodeAt(openSlash + 3) | 32) === 111 && + (str.charCodeAt(openSlash + 4) | 32) === 100 && + (str.charCodeAt(openSlash + 5) | 32) === 121 && + str.charCodeAt(openSlash + 6) === 62 + ) { + return { bodyEndIndex: openSlash, lastClosingTagEnd } + } + + if (lastClosingTagEnd === -1) { + let i = openSlash + 2 + const startCode = str.charCodeAt(i) + if ( + (startCode >= 97 && startCode <= 122) || + (startCode >= 65 && startCode <= 90) + ) { + i++ + while (i < str.length) { + const code = str.charCodeAt(i) + if ( + (code >= 97 && code <= 122) || + (code >= 65 && code <= 90) || + (code >= 48 && code <= 57) || + code === 95 || + code === 58 || + code === 46 || + code === 45 + ) { + i++ + } else { + break + } + } + + if (str.charCodeAt(i) === 62) { + lastClosingTagEnd = i + 1 + } + } + } + + searchFrom = openSlash - 1 + } + + return { bodyEndIndex: -1, lastClosingTagEnd } +} + +// Encoded return avoids allocation: body index => -index - 2; otherwise last closing tag end. +function findHtmlBoundaryLastOpenSlashLazyEncoded(str: string): number { + let lastClosingTagEnd = -1 + let searchFrom = str.length - MIN_CLOSING_TAG_LENGTH + + while (searchFrom >= 0) { + const openSlash = str.lastIndexOf('</', searchFrom) + if (openSlash === -1) break + + if ( + (str.charCodeAt(openSlash + 2) | 32) === 98 && + (str.charCodeAt(openSlash + 3) | 32) === 111 && + (str.charCodeAt(openSlash + 4) | 32) === 100 && + (str.charCodeAt(openSlash + 5) | 32) === 121 && + str.charCodeAt(openSlash + 6) === 62 + ) { + return -openSlash - 2 + } + + if (lastClosingTagEnd === -1) { + let i = openSlash + 2 + const startCode = str.charCodeAt(i) + if ( + (startCode >= 97 && startCode <= 122) || + (startCode >= 65 && startCode <= 90) + ) { + i++ + while (i < str.length) { + const code = str.charCodeAt(i) + if ( + (code >= 97 && code <= 122) || + (code >= 65 && code <= 90) || + (code >= 48 && code <= 57) || + code === 95 || + code === 58 || + code === 46 || + code === 45 + ) { + i++ + } else { + break + } + } + + if (str.charCodeAt(i) === 62) { + lastClosingTagEnd = i + 1 + } + } + } + + searchFrom = openSlash - 1 + } + + return lastClosingTagEnd +} + +// ============================================================================ +// Test Data Generation +// ============================================================================ + +// Small chunk - typical streaming chunk +function generateSmallChunk(): string { + return `<div class="container"><p>Hello World</p><span>Some text</span></div>` +} + +// Medium chunk - several elements +function generateMediumChunk(): string { + let html = '<div class="app">' + for (let i = 0; i < 10; i++) { + html += `<section id="section-${i}"><h2>Title ${i}</h2><p>Paragraph with some content ${i}</p><my-component data-id="${i}">Custom element content</my-component></section>` + } + html += '</div>' + return html +} + +// Large chunk - many elements +function generateLargeChunk(): string { + let html = '<html><head><title>Test' + for (let i = 0; i < 100; i++) { + html += `
    Label ${i}
    ` + } + html += '' + return html +} + +function generateLargeChunkNoBody(): string { + let html = '
    ' + for (let i = 0; i < 100; i++) { + html += `
    Label ${i}
    ` + } + html += '
    ' + return html +} + +function generateUppercaseBodyChunk(): string { + return generateLargeChunk().replace('', '') +} + +function generateLargePlainTextBodyChunk(): string { + return '' + 'x'.repeat(16 * 1024) + '' +} + +// Chunk with custom elements (web components) +function generateWebComponentChunk(): string { + let html = '
    ' + for (let i = 0; i < 20; i++) { + html += `` + } + html += '
    ' + return html +} + +// Chunk with no closing tags (edge case) +function generateNoClosingTagChunk(): string { + return 'This is just plain text with no HTML tags at all' +} + +// Chunk ending mid-tag (streaming edge case) +function generatePartialChunk(): string { + return '

    Content

    More' +} + +// Chunk with nested structure (realistic React output) +function generateNestedChunk(): string { + return `

    Article Title

    First paragraph with bold and italic text.

    Second paragraph with a link.

    Footer content

    ` +} + +// Verify all implementations return the same result +function verifyImplementations() { + const testCases = [ + generateSmallChunk(), + generateMediumChunk(), + generateLargeChunk(), + generateWebComponentChunk(), + generateNoClosingTagChunk(), + generatePartialChunk(), + generateNestedChunk(), + '
    ', + '
    ', + '', + 'no tags here', + '', + ] + + for (const testCase of testCases) { + const regexResult = findLastClosingTagRegex(testCase) + const manualResult = findLastClosingTagManual(testCase) + const optimizedResult = findLastClosingTagOptimized(testCase) + const hybridResult = findLastClosingTagHybrid(testCase) + + if ( + regexResult !== manualResult || + regexResult !== optimizedResult || + regexResult !== hybridResult + ) { + console.error('Mismatch for:', testCase.slice(0, 50)) + console.error(' Regex:', regexResult) + console.error(' Manual:', manualResult) + console.error(' Optimized:', optimizedResult) + console.error(' Hybrid:', hybridResult) + throw new Error('Implementation mismatch!') + } + } + console.log('All implementations verified to produce identical results') +} + +function verifyBodyImplementations() { + const testCases = [ + generateLargeChunk(), + generateUppercaseBodyChunk(), + generateLargePlainTextBodyChunk(), + generateLargeChunkNoBody(), + generateNoClosingTagChunk(), + generatePartialChunk(), + 'only body', + 'split { + const chunk = generateSmallChunk() + + test('regex', async ({ bench }) => { + await bench('regex', () => { + findLastClosingTagRegex(chunk) + }).run() + }) + + test('manual backwards scan', async ({ bench }) => { + await bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) + }).run() + }) + + test('optimized (charCodeAt)', async ({ bench }) => { + await bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) + }).run() + }) + + test('hybrid (lastIndexOf + validation)', async ({ bench }) => { + await bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) + }).run() + }) +}) + +describe('Closing Tag Detection - Medium Chunk (~1.5KB)', () => { + const chunk = generateMediumChunk() + + test('regex', async ({ bench }) => { + await bench('regex', () => { + findLastClosingTagRegex(chunk) + }).run() + }) + + test('manual backwards scan', async ({ bench }) => { + await bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) + }).run() + }) + + test('optimized (charCodeAt)', async ({ bench }) => { + await bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) + }).run() + }) + + test('hybrid (lastIndexOf + validation)', async ({ bench }) => { + await bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) + }).run() + }) +}) + +describe('Closing Tag Detection - Large Chunk (~13KB)', () => { + const chunk = generateLargeChunk() + + test('regex', async ({ bench }) => { + await bench('regex', () => { + findLastClosingTagRegex(chunk) + }).run() + }) + + test('manual backwards scan', async ({ bench }) => { + await bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) + }).run() + }) + + test('optimized (charCodeAt)', async ({ bench }) => { + await bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) + }).run() + }) + + test('hybrid (lastIndexOf + validation)', async ({ bench }) => { + await bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) + }).run() + }) +}) + +describe('Closing Tag Detection - Web Components', () => { + const chunk = generateWebComponentChunk() + + test('regex', async ({ bench }) => { + await bench('regex', () => { + findLastClosingTagRegex(chunk) + }).run() + }) + + test('manual backwards scan', async ({ bench }) => { + await bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) + }).run() + }) + + test('optimized (charCodeAt)', async ({ bench }) => { + await bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) + }).run() + }) + + test('hybrid (lastIndexOf + validation)', async ({ bench }) => { + await bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) + }).run() + }) +}) + +describe('Closing Tag Detection - No Closing Tags (worst case for regex)', () => { + const chunk = generateNoClosingTagChunk() + + test('regex', async ({ bench }) => { + await bench('regex', () => { + findLastClosingTagRegex(chunk) + }).run() + }) + + test('manual backwards scan', async ({ bench }) => { + await bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) + }).run() + }) + + test('optimized (charCodeAt)', async ({ bench }) => { + await bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) + }).run() + }) + + test('hybrid (lastIndexOf + validation)', async ({ bench }) => { + await bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) + }).run() + }) +}) + +describe('Closing Tag Detection - Nested React-like Structure', () => { + const chunk = generateNestedChunk() + + test('regex', async ({ bench }) => { + await bench('regex', () => { + findLastClosingTagRegex(chunk) + }).run() + }) + + test('manual backwards scan', async ({ bench }) => { + await bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) + }).run() + }) + + test('optimized (charCodeAt)', async ({ bench }) => { + await bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) + }).run() + }) + + test('hybrid (lastIndexOf + validation)', async ({ bench }) => { + await bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) + }).run() + }) +}) + +describe('Closing Tag Detection - Partial Chunk (streaming edge case)', () => { + const chunk = generatePartialChunk() + + test('regex', async ({ bench }) => { + await bench('regex', () => { + findLastClosingTagRegex(chunk) + }).run() + }) + + test('manual backwards scan', async ({ bench }) => { + await bench('manual backwards scan', () => { + findLastClosingTagManual(chunk) + }).run() + }) + + test('optimized (charCodeAt)', async ({ bench }) => { + await bench('optimized (charCodeAt)', () => { + findLastClosingTagOptimized(chunk) + }).run() + }) + + test('hybrid (lastIndexOf + validation)', async ({ bench }) => { + await bench('hybrid (lastIndexOf + validation)', () => { + findLastClosingTagHybrid(chunk) + }).run() + }) +}) + +function benchBodyEndTagDetection(name: string, chunk: string) { + describe(`Body End Tag Detection - ${name}`, () => { + test('forward charCodeAt', async ({ bench }) => { + await bench('forward charCodeAt', () => { + findBodyEndTagForward(chunk) + }).run() + }) + + test('backward charCodeAt', async ({ bench }) => { + await bench('backward charCodeAt', () => { + findBodyEndTagBackward(chunk) + }).run() + }) + + test('lastIndexOf( { + await bench('lastIndexOf( { + findBodyEndTagLastOpenSlash(chunk) + }).run() + }) + + test('native lowercase + lastIndexOf( { + await bench('native lowercase + lastIndexOf( { + findBodyEndTagNativeLowerThenLastOpenSlash(chunk) + }).run() + }) + + test('combined boundary scan', async ({ bench }) => { + await bench('combined boundary scan', () => { + findHtmlBoundaryCombined(chunk).bodyEndIndex + }).run() + }) + }) +} + +function benchBoundaryDetection(name: string, chunk: string) { + describe(`HTML Boundary Detection - ${name}`, () => { + test('current two-step forward body + last closing', async ({ bench }) => { + await bench('current two-step forward body + last closing', () => { + const bodyEndIndex = findBodyEndTagForward(chunk) + if (bodyEndIndex === -1) { + findLastClosingTagOptimized(chunk) + } + }).run() + }) + + test('lastIndexOf( { + await bench('lastIndexOf( { + const bodyEndIndex = findBodyEndTagLastOpenSlash(chunk) + if (bodyEndIndex === -1) { + findLastClosingTagOptimized(chunk) + } + }).run() + }) + + test('native lowercase body + last closing', async ({ bench }) => { + await bench('native lowercase body + last closing', () => { + const bodyEndIndex = findBodyEndTagNativeLowerThenLastOpenSlash(chunk) + if (bodyEndIndex === -1) { + findLastClosingTagOptimized(chunk) + } + }).run() + }) + + test('fused lastIndexOf( { + await bench('fused lastIndexOf( { + findHtmlBoundaryLastOpenSlash(chunk) + }).run() + }) + + test('lazy fused lastIndexOf( { + await bench('lazy fused lastIndexOf( { + findHtmlBoundaryLastOpenSlashLazy(chunk) + }).run() + }) + + test('lazy encoded lastIndexOf( { + await bench('lazy encoded lastIndexOf( { + findHtmlBoundaryLastOpenSlashLazyEncoded(chunk) + }).run() + }) + + test('combined boundary scan', async ({ bench }) => { + await bench('combined boundary scan', () => { + findHtmlBoundaryCombined(chunk) + }).run() + }) + }) +} + +benchBodyEndTagDetection('Large Final Chunk With ', generateLargeChunk()) +benchBodyEndTagDetection('Uppercase ', generateUppercaseBodyChunk()) +benchBodyEndTagDetection( + 'Plain Text Body Tail (~16KB)', + generateLargePlainTextBodyChunk(), +) +benchBodyEndTagDetection( + 'Large Chunk Without ', + generateLargeChunkNoBody(), +) + +benchBoundaryDetection('Large Final Chunk With ', generateLargeChunk()) +benchBoundaryDetection( + 'Large Chunk Without ', + generateLargeChunkNoBody(), +) +benchBoundaryDetection('Nested Chunk Without ', generateNestedChunk()) diff --git a/packages/router-core/tests/curly-params-smoke.test.ts b/packages/router-core/tests/curly-params-smoke.test.ts index 6184a205e7..c566b99d2f 100644 --- a/packages/router-core/tests/curly-params-smoke.test.ts +++ b/packages/router-core/tests/curly-params-smoke.test.ts @@ -1,5 +1,6 @@ import { describe, expect, test } from 'vitest' -import { findRouteMatch, processRouteTree } from '../src/new-process-route-tree' +import { findRouteMatch } from '../src/new-process-route-tree' +import { processTestRouteTree as processRouteTree } from './routerTestUtils' const testCases = [ { @@ -136,6 +137,6 @@ describe('curly params smoke tests', () => { } const processed = processRouteTree(tree) const res = findRouteMatch(nav, processed.processedTree) - expect(res?.params).toEqual(params) + expect(res?.rawParams).toEqual(params) }) }) diff --git a/packages/router-core/tests/dangerous-protocols.test.ts b/packages/router-core/tests/dangerous-protocols.test.ts new file mode 100644 index 0000000000..375c2f8925 --- /dev/null +++ b/packages/router-core/tests/dangerous-protocols.test.ts @@ -0,0 +1,864 @@ +import { URL as NodeURL } from 'node:url' +import { createBrowserHistory, createMemoryHistory } from '@tanstack/history' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + DEFAULT_PROTOCOL_ALLOWLIST, + getUrlScheme, + isDangerousProtocol, +} from '../src/utils' +import { redirect } from '../src/redirect' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +const defaultAllowlistSet = new Set(DEFAULT_PROTOCOL_ALLOWLIST) + +afterEach(() => { + vi.unstubAllGlobals() +}) + +const unsafeRelativeUrls = [ + '//evil.example', + '///evil.example', + '/\\evil.example', + '/\\\\evil.example', + '/\\/evil.example', + '\\/evil.example', + '\\\\evil.example', + ' //evil.example', + ' /\\evil.example', + '\x01//evil.example', + ...['\t', '\n', '\r'].flatMap((control) => + ['/', '\\'].flatMap((first) => + ['/', '\\'].map((second) => first + control + second + 'evil.example'), + ), + ), +] + +describe('isDangerousProtocol', () => { + describe('blocked protocols (not in default allowlist)', () => { + it('should detect javascript: protocol', () => { + expect( + isDangerousProtocol('javascript:alert(1)', defaultAllowlistSet), + ).toBe(true) + }) + + it('should detect javascript: with mixed case and whitespace', () => { + expect( + isDangerousProtocol('JavaScript:alert(1)', defaultAllowlistSet), + ).toBe(true) + expect( + isDangerousProtocol(' \t\n javascript:alert(1)', defaultAllowlistSet), + ).toBe(true) + expect( + isDangerousProtocol('java\nscript:alert(1)', defaultAllowlistSet), + ).toBe(true) + }) + + it('should detect known unsafe schemes', () => { + expect( + isDangerousProtocol( + 'data:text/html,', + defaultAllowlistSet, + ), + ).toBe(true) + expect( + isDangerousProtocol( + 'blob:https://example.com/some-uuid', + defaultAllowlistSet, + ), + ).toBe(true) + expect( + isDangerousProtocol('vbscript:msgbox(1)', defaultAllowlistSet), + ).toBe(true) + expect( + isDangerousProtocol('file:///etc/passwd', defaultAllowlistSet), + ).toBe(true) + expect(isDangerousProtocol('about:blank', defaultAllowlistSet)).toBe(true) + }) + + it('should block custom protocols by default', () => { + expect(isDangerousProtocol('custom:something', defaultAllowlistSet)).toBe( + true, + ) + expect(isDangerousProtocol('foo:bar', defaultAllowlistSet)).toBe(true) + }) + }) + + describe('allowed protocols (in default allowlist)', () => { + it('should allow http and https', () => { + expect( + isDangerousProtocol('http://example.com', defaultAllowlistSet), + ).toBe(false) + expect( + isDangerousProtocol('https://example.com', defaultAllowlistSet), + ).toBe(false) + }) + + it('should allow mailto and tel', () => { + expect( + isDangerousProtocol('mailto:user@example.com', defaultAllowlistSet), + ).toBe(false) + expect(isDangerousProtocol('tel:+1234567890', defaultAllowlistSet)).toBe( + false, + ) + }) + }) + + describe('relative URLs (no protocol)', () => { + it('should allow relative paths, query strings and hash fragments', () => { + expect(isDangerousProtocol('/path/to/page', defaultAllowlistSet)).toBe( + false, + ) + expect(isDangerousProtocol('./relative', defaultAllowlistSet)).toBe(false) + expect(isDangerousProtocol('../parent', defaultAllowlistSet)).toBe(false) + expect(isDangerousProtocol('?foo=bar', defaultAllowlistSet)).toBe(false) + expect(isDangerousProtocol('#section', defaultAllowlistSet)).toBe(false) + }) + }) + + describe('edge cases', () => { + it('should handle empty and null-ish inputs', () => { + expect(isDangerousProtocol('', defaultAllowlistSet)).toBe(false) + expect( + isDangerousProtocol(null as unknown as string, defaultAllowlistSet), + ).toBe(false) + expect( + isDangerousProtocol( + undefined as unknown as string, + defaultAllowlistSet, + ), + ).toBe(false) + }) + + it('should not be fooled by javascript in pathname or query', () => { + expect( + isDangerousProtocol( + 'https://example.com/javascript:foo', + defaultAllowlistSet, + ), + ).toBe(false) + expect(isDangerousProtocol('/javascript:foo', defaultAllowlistSet)).toBe( + false, + ) + expect(isDangerousProtocol('/path?time=12:00', defaultAllowlistSet)).toBe( + false, + ) + }) + + it('should return false for malformed/encoded scheme strings that URL rejects', () => { + expect( + isDangerousProtocol( + '%6a%61%76%61%73%63%72%69%70%74:alert(1)', + defaultAllowlistSet, + ), + ).toBe(false) + expect(isDangerousProtocol(':::', defaultAllowlistSet)).toBe(false) + expect(isDangerousProtocol('123:456', defaultAllowlistSet)).toBe(false) + expect(isDangerousProtocol('//example.com', defaultAllowlistSet)).toBe( + true, + ) + }) + + it('should detect dangerous protocol with leading control characters', () => { + expect( + isDangerousProtocol('\x00javascript:alert(1)', defaultAllowlistSet), + ).toBe(true) + expect( + isDangerousProtocol( + '\x01\x02\x03javascript:alert(1)', + defaultAllowlistSet, + ), + ).toBe(true) + }) + }) + + describe('custom allowlist', () => { + it('should use custom allowlist when provided', () => { + const customAllowlist = new Set(['ftp:', 'ssh:']) + + expect(isDangerousProtocol('ftp://example.com', customAllowlist)).toBe( + false, + ) + expect(isDangerousProtocol('ssh://example.com', customAllowlist)).toBe( + false, + ) + expect(isDangerousProtocol('javascript:alert(1)', customAllowlist)).toBe( + true, + ) + expect(isDangerousProtocol('https://example.com', customAllowlist)).toBe( + true, + ) + }) + + it('should block absolute URLs with an empty allowlist', () => { + const emptyAllowlist = new Set() + expect(isDangerousProtocol('javascript:alert(1)', emptyAllowlist)).toBe( + true, + ) + expect(isDangerousProtocol('data:text/html,test', emptyAllowlist)).toBe( + true, + ) + expect(isDangerousProtocol('https://example.com', emptyAllowlist)).toBe( + true, + ) + }) + + it('should allow extending the default allowlist', () => { + const extendedAllowlist = new Set([ + ...DEFAULT_PROTOCOL_ALLOWLIST, + 'ftp:', + 'gopher:', + ]) + + expect( + isDangerousProtocol('javascript:alert(1)', extendedAllowlist), + ).toBe(true) + expect(isDangerousProtocol('ftp://example.com', extendedAllowlist)).toBe( + false, + ) + expect( + isDangerousProtocol('gopher://example.com', extendedAllowlist), + ).toBe(false) + expect( + isDangerousProtocol('https://example.com', extendedAllowlist), + ).toBe(false) + }) + }) + + describe.each([ + { name: 'default', allowlist: defaultAllowlistSet }, + { name: 'empty', allowlist: new Set() }, + { + name: 'custom', + allowlist: new Set(['https:', 'custom+1.-:', 'javascript:']), + }, + ])('native URL parsing with the $name allowlist', ({ allowlist }) => { + it.each(['http:', 'https:'])( + 'matches native host resolution around separators with a %s base', + (protocol) => { + const base = new NodeURL(`${protocol}//app.example/current`) + const characters = [ + ...Array.from({ length: 0x80 }, (_, code) => + String.fromCharCode(code), + ), + '\u0085', + '\u00a0', + '\u200b', + '\u2028', + '\u2029', + '\ufeff', + '\uff0f', + '\uff3c', + '\ud800', + '\udfff', + ] + + // These inputs have no explicit scheme. If they supply a host, it is + // different from the base, so native origin changes identify them. + for (const character of characters) { + for (const first of ['/', '\\']) { + for (const second of ['/', '\\']) { + for (const href of [ + character + first + '\t\n\r' + second + 'evil.example/path', + first + character + second + 'evil.example/path', + ]) { + const resolved = new NodeURL(href, base) + expect( + isDangerousProtocol(href, allowlist), + JSON.stringify(href), + ).toBe(resolved.origin !== base.origin) + } + } + } + } + }, + ) + + it('allows encoded separators and URL-like text that stays within the current origin', () => { + const base = new NodeURL('https://app.example/current') + for (const href of [ + '%2f%2fevil.example', + '%5c%5cevil.example', + '/%2f/evil.example', + '/%5c/evil.example', + '/%09/evil.example', + '/.//evil.example', + '/a/..//evil.example', + '?next=//evil.example', + '#javascript:payload', + ]) { + expect(new NodeURL(href, base).origin, JSON.stringify(href)).toBe( + base.origin, + ) + expect(isDangerousProtocol(href, allowlist), JSON.stringify(href)).toBe( + false, + ) + } + }) + + it('blocks protocol-relative URLs even when they resolve to the current host', () => { + const base = new NodeURL('https://app.example/current') + for (const href of ['//app.example/target', '/\\app.example/target']) { + expect(new NodeURL(href, base).origin).toBe(base.origin) + expect(isDangerousProtocol(href, allowlist), JSON.stringify(href)).toBe( + true, + ) + } + }) + + it('checks the normalized explicit scheme against the allowlist', () => { + for (const href of [ + ' \x00H\tT\nT\rPS://other.example/path', + '\x01 \nHTtP://other.example/path', + ' \x1fjava\tsc\nri\rpt:payload', + '\rCuS\tToM+1.-:payload', + 'MaIl\tTo:user@example.com', + 'Te\nL:+1234567890', + ]) { + const scheme = new NodeURL(href).protocol + expect(isDangerousProtocol(href, allowlist), JSON.stringify(href)).toBe( + !allowlist.has(scheme), + ) + } + }) + + it.each([ + ['https://[', 'https:'], + ['javascript://[', 'javascript:'], + ['custom+1.-://[', 'custom+1.-:'], + ['//[', undefined], + ] as const)( + 'applies the protocol policy despite a malformed URL body in %j', + (href, scheme) => { + expect(() => new NodeURL(href, 'https://app.example')).toThrow() + expect(isDangerousProtocol(href, allowlist)).toBe( + scheme === undefined || !allowlist.has(scheme), + ) + }, + ) + }) + + describe('DEFAULT_PROTOCOL_ALLOWLIST', () => { + it('should contain the expected default protocols', () => { + expect(DEFAULT_PROTOCOL_ALLOWLIST).toEqual([ + 'http:', + 'https:', + 'mailto:', + 'tel:', + ]) + }) + }) +}) + +describe('redirect creation (no protocol validation)', () => { + it('should allow creating redirect with javascript: protocol', () => { + expect(() => redirect({ href: 'javascript:alert(1)' })).not.toThrow() + }) + + it('should allow creating redirect with data: protocol', () => { + expect(() => + redirect({ href: 'data:text/html,' }), + ).not.toThrow() + }) + + it('should allow creating redirect with any protocol', () => { + expect(() => redirect({ href: 'custom:something' })).not.toThrow() + expect(() => + redirect({ href: 'blob:https://example.com/uuid' }), + ).not.toThrow() + }) + + it('should allow safe protocols', () => { + expect(() => redirect({ href: 'https://example.com' })).not.toThrow() + expect(() => redirect({ href: 'http://example.com' })).not.toThrow() + expect(() => redirect({ href: 'mailto:user@example.com' })).not.toThrow() + }) + + it('should allow redirects without href', () => { + expect(() => redirect({ to: '/home' })).not.toThrow() + }) +}) + +describe('public navigation and redirect sinks', () => { + const customProtocols = [ + 'x-safari-https://example.com', + 'googlechromes://example.com', + 'intent://example.com#Intent;scheme=https;end', + 'foo:bar', + ] + + it.each(customProtocols)( + 'document-navigates to allowlisted protocol %j', + async (href) => { + const windowLocation = { href: '', replace: vi.fn() } + vi.stubGlobal('window', { location: windowLocation }) + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history: createMemoryHistory({ initialEntries: ['/'] }), + origin: 'https://victim.example', + protocolAllowlist: [ + 'x-safari-https:', + 'googlechromes:', + 'intent:', + 'foo:', + ], + isServer: false, + }) + + await router.navigate({ href, reloadDocument: true }) + + expect(windowLocation.href).toBe(href) + }, + ) + + it.each([...customProtocols, ...unsafeRelativeUrls])( + 'blocks unsafe document destination %j', + async (href) => { + const windowLocation = { href: '', replace: vi.fn() } + vi.stubGlobal('window', { location: windowLocation }) + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history: createMemoryHistory({ initialEntries: ['/'] }), + origin: 'https://victim.example', + isServer: false, + }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + if (unsafeRelativeUrls.includes(href)) { + expect(new URL(href, router.origin).origin).toBe('https://evil.example') + } + + try { + for (const replace of [false, true]) { + await router.navigate({ href, reloadDocument: true, replace }) + + expect(windowLocation.href).toBe('') + expect(windowLocation.replace).not.toHaveBeenCalled() + expect(router.history.location.href).toBe('/') + expect(warn).toHaveBeenCalledWith( + `Blocked navigation to dangerous protocol: ${href}`, + ) + } + } finally { + warn.mockRestore() + } + }, + ) + + it('validates the Location header emitted by a server redirect', async () => { + const rootRoute = new BaseRootRoute() + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => + redirect({ + href: '/safe', + headers: { Location: '/\\evil.example' }, + }), + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute]), + isServer: true, + }) + + const response = await loadServerResponse(router, '/source') + + expect(response.status).toBe(500) + expect(response.headers.get('Location')).toBeNull() + }) + + it('uses a safe explicit Location instead of a stale external href', async () => { + const rootRoute = new BaseRootRoute() + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => + redirect({ + href: 'https://other.example/ignored', + headers: { Location: '/safe' }, + }), + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute]), + isServer: true, + }) + + const response = await loadServerResponse(router, '/source') + + expect(response.status).toBe(307) + expect(response.headers.get('Location')).toBe('/safe') + }) + + it('does not emit a protocol-relative canonical Location', async () => { + const origin = 'https://victim.example' + const rootRoute = new BaseRootRoute() + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => redirect({ href: `${origin}/..//evil.example/path` }), + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute]), + origin, + isServer: true, + }) + + const response = await loadServerResponse(router, '/source') + + expect(response.headers.get('Location')).toBe( + `${origin}//evil.example/path`, + ) + }) + + it.each([false, true])( + 'blocks a dangerous output rewrite with mask=%j', + async (masked) => { + const history = createMemoryHistory({ initialEntries: ['/'] }) + const windowLocation = { href: '', replace: vi.fn() } + vi.stubGlobal('window', { location: windowLocation }) + const publicPath = masked ? '/pretty' : '/target' + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history, + origin: 'https://victim.example', + isServer: false, + rewrite: { + input: ({ url }) => url, + output: ({ url }) => + url.pathname === publicPath ? new URL('javascript:alert(1)') : url, + }, + }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + await router.navigate({ + to: '/target', + mask: masked ? { to: '/pretty' } : undefined, + }) + + expect(history.location.href).toBe('/') + expect(windowLocation.href).toBe('') + expect(warn).toHaveBeenCalledWith( + 'Blocked navigation to dangerous protocol: javascript:alert(1)', + ) + }, + ) + + it('document-navigates to a safe external masked rewrite', async () => { + const history = createMemoryHistory({ initialEntries: ['/'] }) + const windowLocation = { href: '', replace: vi.fn() } + vi.stubGlobal('window', { location: windowLocation }) + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history, + origin: 'https://victim.example', + isServer: false, + rewrite: { + input: ({ url }) => url, + output: ({ url }) => + url.pathname === '/pretty' + ? new URL('https://other.example/rewritten') + : url, + }, + }) + + await router.navigate({ to: '/safe', mask: { to: '/pretty' } }) + + expect(history.location.href).toBe('/') + expect(windowLocation.href).toBe('https://other.example/rewritten') + }) + + it('uses a safe mask for explicit full-document navigation', async () => { + const windowLocation = { href: '', replace: vi.fn() } + vi.stubGlobal('window', { location: windowLocation }) + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history: createMemoryHistory({ initialEntries: ['/'] }), + origin: 'https://victim.example', + isServer: false, + rewrite: { + input: ({ url }) => url, + output: ({ url }) => + url.pathname === '/target' + ? new URL('https://other.example/rewritten') + : url, + }, + }) + + await router.navigate({ + to: '/target', + mask: { to: '/pretty' }, + reloadDocument: true, + }) + + expect(windowLocation.href).toBe('/pretty') + }) + + it('provides the raw current location and replace action to document blockers', async () => { + const history = createMemoryHistory({ initialEntries: ['/current?q=0'] }) + const blockerFn = vi.fn(() => true) + history.block({ blockerFn }) + const windowLocation = { href: '', replace: vi.fn() } + vi.stubGlobal('window', { location: windowLocation }) + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history, + origin: 'https://victim.example', + isServer: false, + }) + + await router.navigate({ + href: 'https://other.example/target', + replace: true, + }) + + expect(blockerFn).toHaveBeenCalledWith( + expect.objectContaining({ + currentLocation: expect.objectContaining({ + href: '/current?q=0', + pathname: '/current', + search: '?q=0', + }), + action: 'REPLACE', + }), + ) + expect(windowLocation.replace).not.toHaveBeenCalled() + }) + + it.each([ + { blocked: false, ignoreBlocker: false, unsafe: false }, + { blocked: true, ignoreBlocker: false, unsafe: false }, + { blocked: true, ignoreBlocker: true, unsafe: false }, + { blocked: false, ignoreBlocker: false, unsafe: true }, + ])( + 'only exempts an accepted document navigation from beforeunload: %j', + async ({ blocked, ignoreBlocker, unsafe }) => { + const browserWindow = window + const history = createBrowserHistory({ window: browserWindow }) + const firstBlocker = vi.fn(async () => false) + const lastBlocker = vi.fn(async () => blocked) + history.block({ blockerFn: firstBlocker, enableBeforeUnload: true }) + history.block({ blockerFn: lastBlocker, enableBeforeUnload: true }) + const windowLocation = { href: '', replace: vi.fn() } + vi.stubGlobal('window', { location: windowLocation }) + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history, + origin: 'https://victim.example', + isServer: false, + }) + const href = unsafe + ? 'javascript:alert(1)' + : 'https://other.example/target' + + try { + await router.navigate({ href, ignoreBlocker }) + + const accepted = !unsafe && (ignoreBlocker || !blocked) + expect(windowLocation.href).toBe(accepted ? href : '') + expect(firstBlocker).toHaveBeenCalledTimes( + ignoreBlocker || unsafe ? 0 : 1, + ) + expect(lastBlocker).toHaveBeenCalledTimes( + ignoreBlocker || unsafe ? 0 : 1, + ) + + const beforeUnload = new Event('beforeunload', { cancelable: true }) + browserWindow.dispatchEvent(beforeUnload) + expect(beforeUnload.defaultPrevented).toBe(!accepted) + + // The exemption must not carry over to a later navigation. + const nextBeforeUnload = new Event('beforeunload', { + cancelable: true, + }) + browserWindow.dispatchEvent(nextBeforeUnload) + expect(nextBeforeUnload.defaultPrevented).toBe(true) + } finally { + history.destroy() + } + }, + ) +}) + +describe('getUrlScheme', () => { + // Generated inputs use valid URL bodies, so a native parse failure must mean + // the prefix has no explicit scheme. Compare both accepted and rejected inputs. + function expectNativeScheme(href: string) { + const expected = NodeURL.canParse(href) + ? new NodeURL(href).protocol + : undefined + expect(getUrlScheme(href), JSON.stringify(href)).toBe(expected) + } + + it.each([ + ['', undefined], + ['https', undefined], + ['javascript:', 'javascript:'], + ['a:b:payload', 'a:'], + [' \x00H\tT\nT\rPS://example.com', 'https:'], + ['CuStOm+1.-\t:value', 'custom+1.-:'], + ['https\x01://example.com', undefined], + ['https ://example.com', undefined], + ['123:payload', undefined], + ['%6aavascript:payload', undefined], + ['/path?next=https://example.com', undefined], + ['?next=javascript:payload', undefined], + ['#javascript:payload', undefined], + ['//example.com:443', undefined], + ['\t\n/\\example.com', undefined], + ] as const)('extracts only a scheme at the start of %j', (href, scheme) => { + expect(getUrlScheme(href)).toBe(scheme) + }) + + it.each([ + ['https:', 'https:'], + ['https://[', 'https:'], + ['https://example.com:99999', 'https:'], + ['https::payload', 'https:'], + ['custom://[', 'custom:'], + ])( + 'extracts the scheme despite an invalid URL body in %j', + (href, scheme) => { + expect(() => new NodeURL(href)).toThrow() + expect(getUrlScheme(href)).toBe(scheme) + }, + ) + + it.each(unsafeRelativeUrls)( + 'requires a separate safety check for protocol-relative input %j', + (href) => { + expect(getUrlScheme(href)).toBeUndefined() + expect(isDangerousProtocol(href, defaultAllowlistSet)).toBe(true) + }, + ) + + it.each([ + 'javascript', + 'HTTPS', + 'http', + 'file', + 'mailto', + 'tel', + 'CuStOm+1.-', + ])('matches native URL parsing across ASCII boundaries in %s', (scheme) => { + for (let code = 0; code <= 0x7f; code++) { + // A second ':' can invalidate the body (e.g. "https::payload"). + // Those cases have explicit expectations above. + if (code === 0x3a) { + continue + } + const character = String.fromCharCode(code) + for (let position = 0; position <= scheme.length; position++) { + expectNativeScheme( + scheme.slice(0, position) + + character + + scheme.slice(position) + + ':payload', + ) + } + } + }) + + it('matches native URL parsing for pairs of leading controls and spaces', () => { + for (let first = 0; first <= 0x20; first++) { + for (let second = 0; second <= 0x20; second++) { + expectNativeScheme( + String.fromCharCode(first, second) + 'Ja\tVa\nSc\rRiPt:payload', + ) + } + } + }) + + it('matches native URL parsing for bounded prefix combinations', () => { + const alphabet = [ + '\0', + '\t', + '\n', + '\r', + ' ', + '\x7f', + 'a', + 'Z', + '0', + '+', + '-', + '.', + '_', + '/', + '\\', + '%', + ] + function checkPrefixes(prefix: string, remaining: number) { + expectNativeScheme(prefix + 'x:payload') + if (!remaining) { + return + } + for (const character of alphabet) { + checkPrefixes(prefix + character, remaining - 1) + } + } + checkPrefixes('', 3) + }) + + it.each([ + '\u0085', + '\u00a0', + '\u1680', + '\u2000', + '\u200b', + '\u2028', + '\u2029', + '\u202f', + '\u205f', + '\u3000', + '\ufeff', + '\u017f', + '\u212a', + '\uff28', + '\uff1a', + '\ud800', + '\udfff', + '\u{1f600}', + ])('matches native URL parsing with non-ASCII character %j', (character) => { + expectNativeScheme(character + 'javascript:payload') + expectNativeScheme('java' + character + 'script:payload') + expectNativeScheme('javascript' + character + ':payload') + }) +}) + +describe('integration test on Router', () => { + const inputs = [ + 'x-safari-https://example.com', + 'googlechromes://example.com', + 'intent://example.com#Intent;scheme=https;end', + 'foo:bar', + ] + it('should accept weird protocols from the allowlist', () => { + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + protocolAllowlist: [ + 'x-safari-https:', + 'googlechromes:', + 'intent:', + 'foo:', + ], + }) + // Each protocol in the inputs should be accepted by resolveRedirect + for (const href of inputs) { + const redir = redirect({ href }) + expect(() => router.resolveRedirect(redir)).not.toThrow() + } + }) + it('should block weird protocols not in the allowlist', () => { + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + protocolAllowlist: [], + }) + // Each protocol in the inputs should be blocked by resolveRedirect + for (const href of inputs) { + const redir = redirect({ href }) + expect(() => router.resolveRedirect(redir)).toThrow( + /Redirect blocked: unsafe protocol/, + ) + } + }) +}) diff --git a/packages/router-core/tests/deep-equal-contract.test.ts b/packages/router-core/tests/deep-equal-contract.test.ts new file mode 100644 index 0000000000..70f0adda6f --- /dev/null +++ b/packages/router-core/tests/deep-equal-contract.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from 'vitest' +import { deepEqual } from '../src/utils' + +// Pins the observable contract of `deepEqual` (including existing quirks) so +// performance work on its loops cannot change it silently. +describe('deepEqual contract', () => { + it.each([ + [undefined, undefined], + [true, undefined], + [undefined, true], + [true, true], + ] as const)( + 'compares nested records and arrays with partial=%s explicitUndefined=%s', + (partial, explicitUndefined) => { + const a = Object.freeze({ + page: 1, + nested: Object.freeze({ ids: Object.freeze([1, 2]) }), + }) + expect( + deepEqual( + a, + { page: 1, nested: { ids: [1, 2] } }, + partial, + explicitUndefined, + ), + ).toBe(true) + expect( + deepEqual( + a, + { page: 1, nested: { ids: [1, 3] } }, + partial, + explicitUndefined, + ), + ).toBe(false) + }, + ) + + it('keeps partial comparison directional and arrays length-exact', () => { + expect(deepEqual({ a: 1, b: 2 }, { a: 1 }, true)).toBe(true) + expect(deepEqual({ a: 1 }, { a: 1, b: 2 }, true)).toBe(false) + expect(deepEqual([1, 2], [1], true)).toBe(false) + }) + + it('retains inherited enumeration, symbols, and hidden-property policy', () => { + const a = Object.assign(Object.create({ inherited: 1 }), { own: 2 }) + expect(deepEqual(a, { inherited: 1, own: 2 })).toBe(true) + const s = Symbol('metadata') + expect(deepEqual({ [s]: 1 }, { [s]: 2 })).toBe(true) + expect( + deepEqual(Object.defineProperty({}, 'hidden', { value: 1 }), {}), + ).toBe(true) + }) + + it('retains current undefined-key behavior rather than changing the contract', () => { + expect(deepEqual({ a: undefined }, {})).toBe(true) + expect(deepEqual({ a: undefined }, {}, false, true)).toBe(false) + // Existing quirk: this performance patch deliberately does NOT repair it. + expect(deepEqual({ a: undefined }, { b: undefined }, false, true)).toBe( + true, + ) + expect(deepEqual({}, { a: undefined }, true, true)).toBe(true) + }) + + it('retains numeric equality', () => { + expect(deepEqual(-0, 0)).toBe(true) + expect(deepEqual([NaN], [NaN])).toBe(false) + expect( + deepEqual([1n, Infinity, undefined], [1n, Infinity, undefined]), + ).toBe(true) + }) + + it('preserves default-mode getter read order', () => { + const reads: Array = [] + const a = { + get x() { + reads.push('a') + return 1 + }, + } + const b = { + get x() { + reads.push('b') + return 1 + }, + } + expect(deepEqual(a, b)).toBe(true) + expect(reads).toEqual(['a', 'b', 'a', 'b']) + }) + + it('does not read an excess comparison value in exact-defined mode', () => { + const b = { + get x() { + throw new Error('must not read') + }, + } + expect(deepEqual({}, b, false, true)).toBe(false) + }) + + it('short-circuits identical children', () => { + const shared = {} + expect(deepEqual(shared, shared, true, true)).toBe(true) + expect(deepEqual([shared], [shared], true, true)).toBe(true) + }) + + it('keeps different class instances opaque', () => { + class Foo { + value = 1 + } + expect(deepEqual(new Foo(), new Foo())).toBe(false) + }) +}) diff --git a/packages/router-core/tests/deep-equal.bench.ts b/packages/router-core/tests/deep-equal.bench.ts new file mode 100644 index 0000000000..c796add1ac --- /dev/null +++ b/packages/router-core/tests/deep-equal.bench.ts @@ -0,0 +1,166 @@ +import { describe, expect, test } from 'vitest' +import { deepEqual } from '../src/utils' + +// Workloads modeled on the router's callers: Link inline-option stabilization +// (`explicitUndefined`), active-state search comparison (`partial`), +// matchRoute params (`partial`), and search-middleware value comparisons. +// Inputs rotate over a pool so a single hidden-class or cached shape does not +// dominate; the "fresh" cases build their incoming value inside the timed op. +// +// Always compare implementations with the whole file in one process: the +// cases share `deepEqual`'s type feedback and inlining decisions, and a `-t` +// subset can rank variants very differently from the mixed-mode reality. + +const search = { page: 1, sort: 'asc', filter: 'open', tags: ['a', 'b'] } +const searchEqual = Array.from({ length: 32 }, () => ({ + page: 1, + sort: 'asc', + filter: 'open', + tags: ['a', 'b'], +})) +const searchChangedLate = Array.from({ length: 32 }, () => ({ + page: 1, + sort: 'asc', + filter: 'open', + tags: ['a', 'c'], +})) +const searchChangedEarly = Array.from({ length: 32 }, () => ({ + page: 2, + sort: 'asc', + filter: 'open', + tags: ['a', 'b'], +})) +const nested = { + user: { id: 7, roles: ['admin', 'editor'], prefs: { theme: 'dark' } }, + items: [{ id: 1 }, { id: 2 }, { id: 3 }], +} +const nestedEqual = Array.from({ length: 32 }, () => ({ + user: { id: 7, roles: ['admin', 'editor'], prefs: { theme: 'dark' } }, + items: [{ id: 1 }, { id: 2 }, { id: 3 }], +})) +const numbers = Array.from({ length: 32 }, (_, index) => index) +const numbersEqual = Array.from({ length: 32 }, () => + Array.from({ length: 32 }, (_, index) => index), +) +// Link.tsx stabilizes `[search, params, activeOptions]`-like inline values. +const linkOptions = Array.from({ length: 100 }, (_, index) => [ + { page: index, sort: 'asc' }, + { id: String(index) }, + { exact: false, includeSearch: true, includeHash: undefined }, +]) +const linkOptionsEqual = linkOptions.map((entry) => + entry.map((value) => ({ ...value })), +) +const shared = { ...search, tags: search.tags } + +let sink = 0 +let cursor = 0 +const next = (pool: Array) => pool[cursor++ & 31]! + +expect(deepEqual(search, searchEqual[0])).toBe(true) +expect(deepEqual(search, searchChangedLate[0])).toBe(false) +expect(deepEqual(search, searchChangedEarly[0])).toBe(false) +expect(deepEqual(nested, nestedEqual[0])).toBe(true) +expect(deepEqual(numbers, numbersEqual[0])).toBe(true) +expect(deepEqual(search, shared)).toBe(true) +for (let index = 0; index < linkOptions.length; index++) { + for (let slot = 0; slot < 3; slot++) { + expect( + deepEqual( + linkOptions[index]![slot], + linkOptionsEqual[index]![slot], + false, + true, + ), + ).toBe(true) + } +} + +describe('deepEqual', () => { + const options = { time: 1000, warmupTime: 200 } + + test('equal flat search record (default)', async ({ bench }) => { + await bench('equal flat search record (default)', () => { + sink += +deepEqual(search, next(searchEqual)) + }).run(options) + }) + + test('equal flat record with a shared child (default)', async ({ bench }) => { + await bench('equal flat record with a shared child (default)', () => { + sink += +deepEqual(search, shared) + }).run(options) + }) + + test('equal flat record (explicitUndefined)', async ({ bench }) => { + await bench('equal flat record (explicitUndefined)', () => { + sink += +deepEqual(search, next(searchEqual), false, true) + }).run(options) + }) + + test('equal flat record (partial)', async ({ bench }) => { + await bench('equal flat record (partial)', () => { + sink += +deepEqual(search, next(searchEqual), true) + }).run(options) + }) + + test('late mismatch in a nested array (default)', async ({ bench }) => { + await bench('late mismatch in a nested array (default)', () => { + sink += +deepEqual(search, next(searchChangedLate)) + }).run(options) + }) + + test('early mismatch (default)', async ({ bench }) => { + await bench('early mismatch (default)', () => { + sink += +deepEqual(search, next(searchChangedEarly)) + }).run(options) + }) + + test('equal nested record (default)', async ({ bench }) => { + await bench('equal nested record (default)', () => { + sink += +deepEqual(nested, next(nestedEqual)) + }).run(options) + }) + + test('equal array of 32 numbers', async ({ bench }) => { + await bench('equal array of 32 numbers', () => { + sink += +deepEqual(numbers, next(numbersEqual)) + }).run(options) + }) + + test('fresh equal flat record (explicitUndefined)', async ({ bench }) => { + await bench('fresh equal flat record (explicitUndefined)', () => { + sink += +deepEqual( + search, + { page: 1, sort: 'asc', filter: 'open', tags: search.tags }, + false, + true, + ) + }).run(options) + }) + + test('fresh partial mismatch', async ({ bench }) => { + await bench('fresh partial mismatch', () => { + sink += +deepEqual(search, { page: 1, sort: 'desc' }, true) + }).run(options) + }) + + test('link option stabilization: 100 entries x 3 equal values', async ({ + bench, + }) => { + await bench( + 'link option stabilization: 100 entries x 3 equal values', + () => { + for (let index = 0; index < linkOptions.length; index++) { + const previous = linkOptions[index]! + const incoming = linkOptionsEqual[index]! + for (let slot = 0; slot < 3; slot++) { + sink += +deepEqual(previous[slot], incoming[slot], false, true) + } + } + }, + ).run(options) + }) +}) + +// Keep the results observable so the comparisons cannot be optimized away. +expect(sink).toBeGreaterThanOrEqual(0) diff --git a/packages/router-core/tests/document-navigation-blocking.test.ts b/packages/router-core/tests/document-navigation-blocking.test.ts new file mode 100644 index 0000000000..8dfae6d265 --- /dev/null +++ b/packages/router-core/tests/document-navigation-blocking.test.ts @@ -0,0 +1,218 @@ +import { URL as NodeURL } from 'node:url' +import { createBrowserHistory, createHashHistory } from '@tanstack/history' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { BaseRootRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.unstubAllGlobals() +}) + +function setupDocumentNavigation({ + initialHref = '/current?query=1#same', + baseHref, + hashHistory = false, +}: { + initialHref?: string + baseHref?: string + hashHistory?: boolean +} = {}) { + const browserWindow = window + const originalHref = browserWindow.location.href + const originalState = browserWindow.history.state + browserWindow.history.replaceState(null, '', initialHref) + const base = baseHref ? document.createElement('base') : undefined + if (base) { + base.href = baseHref! + document.head.prepend(base) + } + const history = (hashHistory ? createHashHistory : createBrowserHistory)({ + window: browserWindow, + }) + onTestFinished(() => { + history.destroy() + base?.remove() + browserWindow.history.replaceState(originalState, '', originalHref) + }) + const blockerFn = vi.fn(() => false) + history.block({ blockerFn, enableBeforeUnload: true }) + + // Preserve native URL parse failures, but emit no navigation events. The + // first beforeunload we dispatch then belongs to a later attempt to leave. + const assign = vi.fn((href: string) => { + new NodeURL(href, browserWindow.document.baseURI) + }) + const replace = vi.fn((href: string) => assign(href)) + vi.stubGlobal('window', { + location: { + get href() { + return browserWindow.location.href + }, + set href(href: string) { + assign(href) + }, + replace, + }, + }) + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history, + origin: browserWindow.location.origin, + protocolAllowlist: [ + 'http:', + 'https:', + 'mailto:', + 'tel:', + 'custom:', + 'httpx:', + ], + isServer: false, + }) + const dispatchBeforeUnload = () => { + const event = new browserWindow.Event('beforeunload', { + cancelable: true, + }) + browserWindow.dispatchEvent(event) + return event.defaultPrevented + } + return { + router, + browserWindow, + assign, + replace, + blockerFn, + dispatchBeforeUnload, + } +} + +describe.each([false, true])( + 'document navigation with replace=%j', + (replace) => { + it.each(['https://[', 'https://example.com:99999/', ' \tHt\nTpS://['])( + 'preserves the next unload warning when %j throws', + async (href) => { + const { router, assign, dispatchBeforeUnload } = + setupDocumentNavigation() + + await expect(router.navigate({ href, replace })).rejects.toThrow() + + expect(assign).toHaveBeenCalledWith(href) + expect(dispatchBeforeUnload()).toBe(true) + }, + ) + + it.each([ + 'mailto:user@example.com', + 'tel:+15555550100', + 'custom:target', + 'httpx://example.com/', + ' \tMa\niLtO:user@example.com', + '#same', + '#changed', + '#', + '/current?query=1#same', + '/folder/../current?query=1#same', + '/current?query=1#mailto:user@example.com', + ])('preserves the next unload warning after %j', async (href) => { + const { router, assign, blockerFn, dispatchBeforeUnload } = + setupDocumentNavigation() + + await router.navigate({ href, reloadDocument: true, replace }) + + expect(assign).toHaveBeenCalledWith(href) + expect(blockerFn).toHaveBeenCalledOnce() + expect(dispatchBeforeUnload()).toBe(true) + }) + + it('preserves the next unload warning after an unchanged empty fragment', async () => { + const { router, dispatchBeforeUnload } = setupDocumentNavigation({ + initialHref: '/current?query=1#', + }) + + await router.navigate({ href: '#', reloadDocument: true, replace }) + + expect(dispatchBeforeUnload()).toBe(true) + }) + + it('compares absolute fragment destinations with the visible hash-history URL', async () => { + const { router, browserWindow, dispatchBeforeUnload } = + setupDocumentNavigation({ + initialHref: '/shell?query=1#/route', + hashHistory: true, + }) + + await router.navigate({ href: browserWindow.location.href, replace }) + + expect(dispatchBeforeUnload()).toBe(true) + }) + + it.each([ + 'https://other.example/next#section', + 'http://other.example/next', + ' \tHt\nTpS://other.example/next', + '/next#same', + '/current?query=2#same', + '/current?query=1', + ])('exempts only the first unload for %j', async (href) => { + const { + router, + assign, + replace: replaceLocation, + dispatchBeforeUnload, + } = setupDocumentNavigation() + + await router.navigate({ href, reloadDocument: true, replace }) + + expect(assign).toHaveBeenCalledWith(href) + expect(replaceLocation).toHaveBeenCalledTimes(replace ? 1 : 0) + expect(dispatchBeforeUnload()).toBe(false) + expect(dispatchBeforeUnload()).toBe(true) + }) + + it('resolves relative fragments against the document base', async () => { + const { router, dispatchBeforeUnload } = setupDocumentNavigation({ + baseHref: '/different-document', + }) + + await router.navigate({ href: '#same', reloadDocument: true, replace }) + + expect(dispatchBeforeUnload()).toBe(false) + expect(dispatchBeforeUnload()).toBe(true) + }) + + it('preserves the next unload warning when an external handler skips blockers', async () => { + const { router, blockerFn, dispatchBeforeUnload } = + setupDocumentNavigation() + + await router.navigate({ + href: 'mailto:user@example.com', + ignoreBlocker: true, + replace, + }) + + expect(blockerFn).not.toHaveBeenCalled() + expect(dispatchBeforeUnload()).toBe(true) + }) + + it.each(['https://[', 'mailto:user@example.com', '#same'])( + 'clears a previously prepared exemption before attempting %j', + async (href) => { + const { router, dispatchBeforeUnload } = setupDocumentNavigation() + await router.navigate({ href: 'https://other.example/next' }) + + const navigation = router.navigate({ + href, + reloadDocument: true, + replace, + }) + if (href === 'https://[') { + await expect(navigation).rejects.toThrow() + } else { + await navigation + } + + expect(dispatchBeforeUnload()).toBe(true) + }, + ) + }, +) diff --git a/packages/router-core/tests/document-navigation.test.ts b/packages/router-core/tests/document-navigation.test.ts new file mode 100644 index 0000000000..6c6424b01f --- /dev/null +++ b/packages/router-core/tests/document-navigation.test.ts @@ -0,0 +1,303 @@ +import { createBrowserHistory, createMemoryHistory } from '@tanstack/history' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute, redirect } from '../src' +import { createRequestHandler } from '../src/ssr/createRequestHandler' +import { createTestRouter } from './routerTestUtils' +import type { RouterHistory } from '@tanstack/history' +import type { LocationRewrite } from '../src' + +const externalHref = 'https://admin.example.com/dashboard' + +function setupRouter({ + isServer = false, + basepath, + history = createMemoryHistory({ initialEntries: ['/'] }), + rewrite = { + output: ({ url }) => { + if (url.pathname === '/admin') { + return new URL(externalHref + url.search + url.hash) + } + return url + }, + }, +}: { + isServer?: boolean + basepath?: string + history?: RouterHistory + rewrite?: LocationRewrite +} = {}) { + const rootRoute = new BaseRootRoute() + const loader = vi.fn(() => 'admin') + const routeTree = rootRoute.addChildren([ + new BaseRoute({ getParentRoute: () => rootRoute, path: '/' }), + new BaseRoute({ getParentRoute: () => rootRoute, path: '/local' }), + new BaseRoute({ getParentRoute: () => rootRoute, path: '/admin', loader }), + ]) + const router = createTestRouter({ + routeTree, + history, + origin: 'https://example.com', + isServer, + basepath, + rewrite, + }) + const windowLocation = { href: '', replace: vi.fn() } + vi.stubGlobal('window', { location: windowLocation }) + + return { router, history, windowLocation, loader } +} + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +describe('SSR redirects to cross-origin rewrites', () => { + test.each([ + { hook: 'beforeLoad', statusCode: undefined }, + { hook: 'beforeLoad', statusCode: 308 }, + { hook: 'loader', statusCode: undefined }, + { hook: 'loader', statusCode: 308 }, + ] as const)( + 'returns the rewritten HTTP redirect from $hook (statusCode=$statusCode)', + async ({ hook, statusCode }) => { + const rootRoute = new BaseRootRoute() + const throwRedirect = vi.fn(() => { + throw redirect({ + to: '/admin', + search: { page: 2 }, + hash: 'details', + statusCode, + }) + }) + const destinationLoader = vi.fn(() => 'admin') + const router = createTestRouter({ + isServer: true, + routeTree: rootRoute.addChildren([ + new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/redirecting', + [hook]: throwRedirect, + }), + new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/admin', + loader: destinationLoader, + }), + ]), + rewrite: { + output: ({ url }) => { + if (url.pathname === '/admin') { + return new URL(externalHref + url.search + url.hash) + } + return url + }, + }, + }) + const render = vi.fn(() => new Response('rendered HTML')) + vi.stubGlobal('window', undefined) + + const response = await createRequestHandler({ + createRouter: () => router, + request: new Request('https://example.com/redirecting'), + })(render) + + expect(throwRedirect).toHaveBeenCalledOnce() + expect(response.status).toBe(statusCode ?? 307) + expect(response.headers.get('Location')).toBe( + `${externalHref}?page=2#details`, + ) + expect(render).not.toHaveBeenCalled() + expect(destinationLoader).not.toHaveBeenCalled() + }, + ) +}) + +describe('document navigation', () => { + test.each([false, true])( + 'navigates to the final cross-origin output (replace=%s)', + async (replace) => { + const { router, history, windowLocation, loader } = setupRouter() + const push = vi.spyOn(history, 'push') + const replaceHistory = vi.spyOn(history, 'replace') + const location = router.state.location + + await router.navigate({ + to: '/admin', + search: { page: 2 }, + hash: 'details', + replace, + }) + + const href = `${externalHref}?page=2#details` + if (replace) { + expect(windowLocation.replace).toHaveBeenCalledWith(href) + expect(windowLocation.href).toBe('') + } else { + expect(windowLocation.href).toBe(href) + expect(windowLocation.replace).not.toHaveBeenCalled() + } + expect(push).not.toHaveBeenCalled() + expect(replaceHistory).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + expect(router.state.location).toBe(location) + expect(router._commitPromise).toBeUndefined() + }, + ) + + test('commits an external public mask without rebuilding the location', async () => { + const { router, history, windowLocation } = setupRouter() + const location = router.buildLocation({ + to: '/local', + mask: { to: '/admin', hash: 'masked' }, + }) + const buildLocation = vi.spyOn(router, 'buildLocation') + const navigate = vi.spyOn(router, 'navigate') + + await router.commitLocation({ ...location, replace: true }) + + expect(windowLocation.replace).toHaveBeenCalledWith( + `${externalHref}#masked`, + ) + expect(history.location.href).toBe('/') + expect(buildLocation).not.toHaveBeenCalled() + expect(navigate).not.toHaveBeenCalled() + }) + + test('uses history for a same-origin mask of an external output', async () => { + const { router, history, windowLocation } = setupRouter() + await router.load() + + await router.navigate({ to: '/admin', mask: { to: '/local' } }) + + expect(history.location.href).toBe('/local') + expect(router.state.location.pathname).toBe('/admin') + expect(router.state.location.maskedLocation?.pathname).toBe('/local') + expect(windowLocation.href).toBe('') + expect(windowLocation.replace).not.toHaveBeenCalled() + }) + + test('ignores server navigation to an external output', async () => { + const { router, history } = setupRouter({ isServer: true }) + vi.stubGlobal('window', undefined) + + await router.navigate({ to: '/admin' }) + + expect(history.location.href).toBe('/') + }) + + test.each([ + { + href: 'https://other.example/a%2fb?value=a+b&value=a%20b#raw%2f', + publicHref: '/ignored', + }, + { + href: '../target?value=a+b&value=a%20b#raw%2f', + reloadDocument: true, + }, + ])('preserves a raw document href: $href', async (options) => { + const output = vi.fn(({ url }) => url) + const { router, windowLocation } = setupRouter({ + basepath: '/app', + rewrite: { output }, + }) + const buildLocation = vi.spyOn(router, 'buildLocation') + + await router.navigate(options) + + expect(windowLocation.href).toBe(options.href) + expect(buildLocation).not.toHaveBeenCalled() + expect(output).not.toHaveBeenCalled() + }) + + test.each([undefined, 'https://public.example/prepared'])( + 'preserves explicit reload publicHref precedence (%s)', + async (publicHref) => { + const { router, windowLocation } = setupRouter() + const buildLocation = vi.spyOn(router, 'buildLocation') + + await router.navigate({ + to: '/admin', + href: '/admin', + publicHref, + reloadDocument: true, + }) + + expect(windowLocation.href).toBe(publicHref ?? externalHref) + expect(buildLocation).toHaveBeenCalledTimes(1) + }, + ) + + describe.each(['memory', 'browser'] as const)( + '%s history blockers', + (kind) => { + test.each([ + { reloadDocument: false, replace: false }, + { reloadDocument: false, replace: true }, + { reloadDocument: true, replace: false }, + { reloadDocument: true, replace: true }, + ])( + 'respects registered blockers and ignoreBlocker (reloadDocument=$reloadDocument, replace=$replace)', + async ({ reloadDocument, replace }) => { + const history = + kind === 'browser' + ? createBrowserHistory() + : createMemoryHistory({ initialEntries: ['/'] }) + try { + const { router, windowLocation } = setupRouter({ history }) + const blockerFn = vi.fn(async () => true) + history.block({ blockerFn, enableBeforeUnload: false }) + const location = history.location + + await router.navigate({ to: '/admin', reloadDocument, replace }) + + expect(blockerFn).toHaveBeenCalledExactlyOnceWith({ + currentLocation: location, + nextLocation: location, + action: replace ? 'REPLACE' : 'PUSH', + }) + expect(windowLocation.href).toBe('') + expect(windowLocation.replace).not.toHaveBeenCalled() + expect(history.location).toBe(location) + + await router.navigate({ + to: '/admin', + reloadDocument, + replace, + ignoreBlocker: true, + }) + + expect(blockerFn).toHaveBeenCalledTimes(1) + if (replace) { + expect(windowLocation.replace).toHaveBeenCalledWith(externalHref) + expect(windowLocation.href).toBe('') + } else { + expect(windowLocation.href).toBe(externalHref) + expect(windowLocation.replace).not.toHaveBeenCalled() + } + expect(history.location).toBe(location) + } finally { + history.destroy() + } + }, + ) + }, + ) + + test('validates the protocol of an external output before navigating', async () => { + const href = 'javascript:alert(1)' + const { router, history, windowLocation } = setupRouter({ + rewrite: { output: () => new URL(href) }, + }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + await router.navigate({ to: '/admin' }) + + expect(windowLocation.href).toBe('') + expect(windowLocation.replace).not.toHaveBeenCalled() + expect(history.location.href).toBe('/') + expect(warn).toHaveBeenCalledWith( + `Blocked navigation to dangerous protocol: ${href}`, + ) + }) +}) diff --git a/packages/router-core/tests/error-boundary-cache-generation.test.ts b/packages/router-core/tests/error-boundary-cache-generation.test.ts new file mode 100644 index 0000000000..447dace6ea --- /dev/null +++ b/packages/router-core/tests/error-boundary-cache-generation.test.ts @@ -0,0 +1,81 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('cache retention across an error-boundary commit', () => { + test('a superseded generation cannot shadow newer beyond-boundary data', async () => { + let parentFails = false + const parentGate = createControlledPromise() + const parentLoader = vi.fn(async () => { + if (parentFails) { + await parentGate + throw new Error('parent boom') + } + }) + let childVersion = 0 + let wantChildReload = false + const childLoader = vi.fn(() => ({ version: ++childVersion })) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/p', + loader: parentLoader, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: 'c', + shouldReload: () => wantChildReload, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/p/c'] }), + defaultStaleReloadMode: 'blocking', + }) + + await router.load() + expect(childLoader).toHaveBeenCalledTimes(1) + + // Same-destination refresh where the child settles a newer generation + // before the parent fails at the boundary. + parentFails = true + wantChildReload = true + const refresh = router.navigate({ to: '/p/c' }) + await vi.waitFor(() => expect(childLoader).toHaveBeenCalledTimes(2)) + parentGate.resolve() + await refresh + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ status: 'error' }) + + // Leave and return with reloads declined: the presented child data must + // be the newer generation, not the superseded one. + parentFails = false + wantChildReload = false + await router.navigate({ to: '/' }) + await router.navigate({ to: '/p/c' }) + + const child = router.state.matches.find( + (match) => match.routeId === childRoute.id, + ) + expect(childLoader).toHaveBeenCalledTimes(2) + expect(child).toMatchObject({ + status: 'success', + loaderData: { version: 2 }, + }) + }) +}) diff --git a/packages/router-core/tests/errorComponentProps.test-d.ts b/packages/router-core/tests/errorComponentProps.test-d.ts new file mode 100644 index 0000000000..23df7cdcfa --- /dev/null +++ b/packages/router-core/tests/errorComponentProps.test-d.ts @@ -0,0 +1,7 @@ +import { expectTypeOf, test } from 'vitest' +import type { ErrorComponentProps } from '../src' + +test('ErrorComponentProps defaults error to unknown', () => { + expectTypeOf().toEqualTypeOf() + expectTypeOf['error']>().toEqualTypeOf() +}) diff --git a/packages/router-core/tests/fallback-route-lifecycle.bench.ts b/packages/router-core/tests/fallback-route-lifecycle.bench.ts new file mode 100644 index 0000000000..16468d473e --- /dev/null +++ b/packages/router-core/tests/fallback-route-lifecycle.bench.ts @@ -0,0 +1,208 @@ +import { describe, expect, test } from 'vitest' +import { lifecycleEnd, runRouteLifecycle } from '../src/router' +import type { AnyRouteMatch, AnyRouter, AnyRoute } from '../src' +import type { LoadTransaction } from '../src/load-client' + +function baselineEnd(matches: Array) { + const boundary = matches.findIndex( + (match) => + match.status === 'error' || + match.status === 'notFound' || + match._notFound, + ) + return boundary < 0 ? matches.length : boundary + 1 +} + +function hasLifecycleMatch( + matches: Array, + end: number, + routeId: string, +) { + for (let index = 0; index < end; index++) { + if (matches[index]!.routeId === routeId) { + return true + } + } + return false +} + +/** Run route lifecycle callbacks in leave/enter/stay phases. */ +function baselineLifecycle( + router: AnyRouter, + previous: Array, + matches: Array, + previousEnd: number, + nextEnd: number, + owner?: LoadTransaction, +): void { + for (let index = 0; index < previousEnd; index++) { + if (owner && router._tx !== owner) { + return + } + const match = previous[index]! + if (!hasLifecycleMatch(matches, nextEnd, match.routeId)) { + ;(router.routesById as Record)[ + match.routeId + ]!.options.onLeave?.(match) + } + } + for (let index = 0; index < nextEnd; index++) { + if (owner && router._tx !== owner) { + return + } + const match = matches[index]! + ;(router.routesById as Record)[match.routeId]!.options[ + hasLifecycleMatch(previous, previousEnd, match.routeId) + ? 'onStay' + : 'onEnter' + ]?.(match) + } +} +// Freeze the published allocation-free dispatcher as the comparison baseline. +// Include membership preparation and compare client/server at every depth. +// Batch small route trees to amortize the timing overhead. +for (const depth of [1, 2, 3, 4, 5, 6]) { + for (const mode of ['client', 'server'] as const) { + for (const scenario of [ + 'stay', + 'replace', + 'sibling', + 'ascend', + 'descend', + 'hide', + 'reveal', + 'hidden', + 'first-load', + 'no-hooks', + 'sparse-hooks', + 'root-error', + 'leaf-notFound', + ] as const) { + if (depth === 1 && ['sibling', 'ascend', 'descend'].includes(scenario)) { + continue + } + if ( + process.env.LIFECYCLE_BENCH_CASE && + !`${scenario}, depth ${depth}, ${mode}`.includes( + process.env.LIFECYCLE_BENCH_CASE, + ) + ) { + continue + } + describe(`${scenario}, depth ${depth}, ${mode}`, () => { + let calls: Array | undefined + let count = 0 + const callback = (name: string) => () => { + count++ + calls?.push(name) + } + const makeMatches = (prefix: string, hidden: boolean) => + Array.from({ length: depth }, (_, index) => ({ + routeId: index < 1 ? `shared${index}` : `${prefix}${index}`, + status: 'success', + _notFound: hidden && index === Math.min(1, depth - 1), + })) as Array + const previous = + scenario === 'first-load' + ? [] + : makeMatches('a', scenario === 'reveal' || scenario === 'hidden') + const matches = makeMatches( + scenario === 'replace' ? 'b' : 'a', + scenario === 'hide' || scenario === 'hidden', + ) + if (scenario === 'sibling') { + matches[depth - 1]!.routeId = `b${depth - 1}` + } + if (scenario === 'ascend') { + matches.pop() + } + if (scenario === 'descend') { + previous.pop() + } + if (scenario === 'root-error') { + matches[0]!.status = 'error' + } + if (scenario === 'leaf-notFound') { + matches[depth - 1]!.status = 'notFound' + } + const owner = + mode === 'server' ? undefined : ([] as unknown as LoadTransaction) + const router = { + _tx: owner, + routesById: Object.fromEntries( + [...previous, ...matches].map((match) => [ + match.routeId, + { + options: + scenario === 'no-hooks' || + (scenario === 'sparse-hooks' && match.routeId !== 'shared0') + ? {} + : { + onEnter: callback(`enter:${match.routeId}`), + onStay: callback(`stay:${match.routeId}`), + onLeave: callback(`leave:${match.routeId}`), + }, + }, + ]), + ), + } as unknown as AnyRouter + const previousEnd = lifecycleEnd(previous) + const baselinePreviousEnd = baselineEnd(previous) + const candidateLifecycle = ( + router: AnyRouter, + previous: Array, + matches: Array, + owner?: LoadTransaction, + ) => { + const nextEnd = (router._lifecycleEnd = lifecycleEnd(matches)) + runRouteLifecycle( + router, + previous, + matches, + previousEnd, + nextEnd, + owner, + ) + } + const originalLifecycle = ( + router: AnyRouter, + previous: Array, + matches: Array, + owner?: LoadTransaction, + ) => { + const nextEnd = (router._lifecycleEnd = baselineEnd(matches)) + baselineLifecycle( + router, + previous, + matches, + baselinePreviousEnd, + nextEnd, + owner, + ) + } + calls = [] + originalLifecycle(router, previous, matches, owner) + const expected = calls + calls = [] + candidateLifecycle(router, previous, matches, owner) + expect(calls).toEqual(expected) + calls = undefined + for (const [name, run] of [ + ['original', originalLifecycle], + ['candidate', candidateLifecycle], + ] as const) { + test(name, async ({ bench }) => { + await bench(name, () => { + for (let i = 0; i < 100; i++) { + router._lifecycleEnd = previousEnd + run(router, previous, matches, owner) + } + }).run({ + time: 300, + }) + }) + } + }) + } + } +} diff --git a/packages/router-core/tests/fallback-route-lifecycle.test.ts b/packages/router-core/tests/fallback-route-lifecycle.test.ts new file mode 100644 index 0000000000..3d802fa6cf --- /dev/null +++ b/packages/router-core/tests/fallback-route-lifecycle.test.ts @@ -0,0 +1,288 @@ +import { createMemoryHistory } from '@tanstack/history' +import { expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute, notFound } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +test('an explicitly targeted not-found owner remains lifecycle-active', async () => { + const onEnter = vi.fn() + const rootRoute = new BaseRootRoute({ + beforeLoad: () => { + throw notFound({ routeId: '/child' }) + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + notFoundComponent: () => null, + onEnter, + }) + const history = createMemoryHistory({ initialEntries: ['/child'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history, + }) + try { + await router.load() + expect(onEnter).toHaveBeenCalledOnce() + } finally { + history.destroy() + } +}) + +test.each(['client', 'server'] as const)( + '%s lifecycle follows the active branch through fallback transitions', + async (environment) => { + for (const fallback of ['error', 'notFound', 'fuzzy'] as const) { + for (const boundary of ['root', 'parent', 'child'] as const) { + const events: Array = [] + let failed = false + const callbacks = (name: string) => ({ + onEnter: () => { + events.push(`enter:${name}`) + }, + onStay: () => { + events.push(`stay:${name}`) + }, + onLeave: () => { + events.push(`leave:${name}`) + }, + }) + const boundaryOptions = (name: string) => + name === boundary + ? { + errorComponent: () => null, + notFoundComponent: () => null, + beforeLoad: () => { + if (failed && fallback !== 'fuzzy') { + throw fallback === 'error' + ? new Error('unavailable') + : notFound() + } + }, + } + : {} + const rootRoute = new BaseRootRoute({ + ...callbacks('root'), + ...boundaryOptions('root'), + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + ...callbacks('parent'), + ...boundaryOptions('parent'), + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: 'child', + ...callbacks('child'), + ...boundaryOptions('child'), + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + ...callbacks('other'), + }) + const history = createMemoryHistory({ initialEntries: ['/other'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + otherRoute, + ]), + history, + isServer: environment === 'server', + }) + const visit = async (path: string) => { + events.length = 0 + if (environment === 'server') { + const response = await loadServerResponse(router, path) + expect(response.status).toBe( + failed && path !== '/other' + ? fallback === 'error' + ? 500 + : 404 + : 200, + ) + } else { + await router.navigate({ to: path }) + } + } + + const active = + boundary === 'root' + ? ['root'] + : boundary === 'parent' + ? ['root', 'parent'] + : ['root', 'parent', 'child'] + const hidden = + boundary === 'root' + ? ['parent', 'child'] + : boundary === 'parent' + ? ['child'] + : [] + try { + await visit('/parent/child') + expect(events).toEqual(['enter:root', 'enter:parent', 'enter:child']) + + failed = true + const missingPath = + fallback === 'fuzzy' ? '/parent/child/missing' : '/parent/child' + await visit(`${missingPath}?step=1`) + expect(events).toEqual([ + ...hidden.map((name) => `leave:${name}`), + ...active.map((name) => `stay:${name}`), + ]) + // Matching still includes the child; only its lifecycle is hidden. + expect(router.state.matches.map((match) => match.routeId)).toContain( + childRoute.id, + ) + + await visit(`${missingPath}?step=2`) + expect(events).toEqual(active.map((name) => `stay:${name}`)) + + failed = false + await visit('/parent/child') + expect(events).toEqual([ + ...active.map((name) => `stay:${name}`), + ...hidden.map((name) => `enter:${name}`), + ]) + + failed = true + await visit(`${missingPath}?step=3`) + expect(events).toEqual([ + ...hidden.map((name) => `leave:${name}`), + ...active.map((name) => `stay:${name}`), + ]) + + failed = false + await visit('/other') + expect(events).toEqual([ + ...active + .filter((name) => name !== 'root') + .map((name) => `leave:${name}`), + 'stay:root', + 'enter:other', + ]) + } finally { + history.destroy() + } + } + } + }, +) + +test('publication supersession keeps lifecycle membership with the published branch', async () => { + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: 'child', + }) + const leafRoute = new BaseRoute({ + getParentRoute: () => childRoute, + path: 'leaf', + }) + const shortEnter = vi.fn() + const otherEnter = vi.fn() + const shortRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/short', + onEnter: shortEnter, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + onEnter: otherEnter, + }) + const history = createMemoryHistory({ + initialEntries: ['/parent/child/leaf'], + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute.addChildren([leafRoute])]), + shortRoute, + otherRoute, + ]), + history, + }) + const publish = router.stores.setMatches.bind(router.stores) + let successor: Promise | undefined + try { + await router.load() + router.stores.setMatches = (matches) => { + publish(matches) + if ( + !successor && + router._committed === matches && + matches.at(-1)?.routeId === shortRoute.id + ) { + successor = router.navigate({ to: '/other' }) + } + } + await router.navigate({ to: '/short' }) + expect(successor).toBeDefined() + await successor + expect(router.state.location.pathname).toBe('/other') + expect(shortEnter).not.toHaveBeenCalled() + expect(otherEnter).toHaveBeenCalledOnce() + } finally { + router.stores.setMatches = publish + history.destroy() + } +}) + +test.each([ + ['error', false], + ['error', true], + ['notFound', false], + ['notFound', true], +] as const)( + 'invalidation preserves the previous %s lifecycle boundary (forcePending: %s)', + async (fallback, forcePending) => { + const events: Array = [] + let failed = true + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + errorComponent: () => null, + notFoundComponent: () => null, + beforeLoad: () => { + if (failed) { + throw fallback === 'error' ? new Error('unavailable') : notFound() + } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: 'child', + onEnter: () => { + events.push('enter') + }, + onStay: () => { + events.push('stay') + }, + onLeave: () => { + events.push('leave') + }, + }) + const history = createMemoryHistory({ initialEntries: ['/parent/child'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + }) + try { + await router.load() + expect(events).toEqual([]) + await router.invalidate({ forcePending }) + expect(events).toEqual([]) + failed = false + await router.invalidate({ forcePending }) + expect(events).toEqual(['enter']) + } finally { + history.destroy() + } + }, +) diff --git a/packages/router-core/tests/fixtures/wpt-url/LICENSE.md b/packages/router-core/tests/fixtures/wpt-url/LICENSE.md new file mode 100644 index 0000000000..39c46d03ac --- /dev/null +++ b/packages/router-core/tests/fixtures/wpt-url/LICENSE.md @@ -0,0 +1,11 @@ +# The 3-Clause BSD License + +Copyright © web-platform-tests contributors + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/router-core/tests/fixtures/wpt-url/README.md b/packages/router-core/tests/fixtures/wpt-url/README.md new file mode 100644 index 0000000000..0a1774ef7d --- /dev/null +++ b/packages/router-core/tests/fixtures/wpt-url/README.md @@ -0,0 +1,46 @@ +# Pinned Web Platform Tests URL cases + +The two upstream JSON files are complete, unmodified copies from Web Platform Tests revision +[`6cfafc4c0801279aa10df8e85f8799d98b8000ab`](https://github.com/web-platform-tests/wpt/commit/6cfafc4c0801279aa10df8e85f8799d98b8000ab): + +- [`url/resources/urltestdata.json`](https://github.com/web-platform-tests/wpt/blob/6cfafc4c0801279aa10df8e85f8799d98b8000ab/url/resources/urltestdata.json) +- [`url/resources/urltestdata-javascript-only.json`](https://github.com/web-platform-tests/wpt/blob/6cfafc4c0801279aa10df8e85f8799d98b8000ab/url/resources/urltestdata-javascript-only.json) + +Every one of the 893 cases in `urltestdata.json` and the single case in +`urltestdata-javascript-only.json` is tested, including all parsing failures. +The test skips only string comment entries. SHA-256 checks ensure the upstream +files remain byte-for-byte unchanged. The JavaScript-only file includes unpaired +surrogates, so the tests load the upstream files with `JSON.parse`, bypassing the +bundler's JSON transform. + +The upstream [format documentation](https://github.com/web-platform-tests/wpt/blob/6cfafc4c0801279aa10df8e85f8799d98b8000ab/url/README.md) +describes complete URL parsing. These tests exercise Router's prefix helpers +using native `URL` to derive expectations: + +- For the explicit scheme, parse the input through its first colon followed by + a fixed valid body (`//example.com`), without a base. Native `URL` validates and + normalizes the scheme even when the original body is malformed; relative + prefixes fail to parse. Also check WPT's recorded `protocol` when the input has + an explicit scheme and WPT supplies that field. +- For inputs without an explicit scheme, resolve against two HTTPS bases with + different hosts. Matching resulting hostnames identify a protocol-relative + input. Ordinary relative paths inherit the different base hosts. Four literal + inputs (`//`, `///`, `////`, and `//C|/foo/bar`) need explicit expectations + because they have no valid HTTP(S) host. + +The [test](../../url-standard.test.ts) contains the source hashes and those four +exceptions. There are no per-index annotations to maintain. Case indices in test +names are positions in the original arrays, including string comment entries. + +Router's allowlist and blanket protocol-relative rejection are application +policy. The tests apply the default, empty, and custom allowlists. They use +HTTP(S) [relative URL behavior](https://url.spec.whatwg.org/#relative-state) +even when an upstream case has a different base scheme, since the helpers have +no base parameter. Neither production helper calculates an expected result. + +To update the fixtures, copy both complete files from a new upstream commit and +update the SHA-256 hashes in the test and the revision links here. Keep both +files in upstream format and preserve the [license](./LICENSE.md). Run the core +unit and type tests and lint. If a new scheme-less input cannot be parsed against +HTTPS, review it and add an explicit expectation instead of skipping it. +Tests read only committed files and make no network requests. diff --git a/packages/router-core/tests/fixtures/wpt-url/urltestdata-javascript-only.json b/packages/router-core/tests/fixtures/wpt-url/urltestdata-javascript-only.json new file mode 100644 index 0000000000..a3793c1f47 --- /dev/null +++ b/packages/router-core/tests/fixtures/wpt-url/urltestdata-javascript-only.json @@ -0,0 +1,18 @@ +[ + "See ../README.md for a description of the format.", + { + "input": "http://example.com/\uD800\uD801\uDFFE\uDFFF\uFDD0\uFDCF\uFDEF\uFDF0\uFFFE\uFFFF?\uD800\uD801\uDFFE\uDFFF\uFDD0\uFDCF\uFDEF\uFDF0\uFFFE\uFFFF", + "base": null, + "href": "http://example.com/%EF%BF%BD%F0%90%9F%BE%EF%BF%BD%EF%B7%90%EF%B7%8F%EF%B7%AF%EF%B7%B0%EF%BF%BE%EF%BF%BF?%EF%BF%BD%F0%90%9F%BE%EF%BF%BD%EF%B7%90%EF%B7%8F%EF%B7%AF%EF%B7%B0%EF%BF%BE%EF%BF%BF", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%EF%BF%BD%F0%90%9F%BE%EF%BF%BD%EF%B7%90%EF%B7%8F%EF%B7%AF%EF%B7%B0%EF%BF%BE%EF%BF%BF", + "search": "?%EF%BF%BD%F0%90%9F%BE%EF%BF%BD%EF%B7%90%EF%B7%8F%EF%B7%AF%EF%B7%B0%EF%BF%BE%EF%BF%BF", + "hash": "" + } +] diff --git a/packages/router-core/tests/fixtures/wpt-url/urltestdata.json b/packages/router-core/tests/fixtures/wpt-url/urltestdata.json new file mode 100644 index 0000000000..aae7b1f656 --- /dev/null +++ b/packages/router-core/tests/fixtures/wpt-url/urltestdata.json @@ -0,0 +1,10643 @@ +[ + "See ../README.md for a description of the format.", + { + "input": "http://example\t.\norg", + "base": "http://example.org/foo/bar", + "href": "http://example.org/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://user:pass@foo:21/bar;par?b#c", + "base": "http://example.org/foo/bar", + "href": "http://user:pass@foo:21/bar;par?b#c", + "origin": "http://foo:21", + "protocol": "http:", + "username": "user", + "password": "pass", + "host": "foo:21", + "hostname": "foo", + "port": "21", + "pathname": "/bar;par", + "search": "?b", + "hash": "#c" + }, + { + "input": "https://test:@test", + "base": null, + "href": "https://test@test/", + "origin": "https://test", + "protocol": "https:", + "username": "test", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://:@test", + "base": null, + "href": "https://test/", + "origin": "https://test", + "protocol": "https:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "non-special://test:@test/x", + "base": null, + "href": "non-special://test@test/x", + "origin": "null", + "protocol": "non-special:", + "username": "test", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/x", + "search": "", + "hash": "" + }, + { + "input": "non-special://:@test/x", + "base": null, + "href": "non-special://test/x", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/x", + "search": "", + "hash": "" + }, + { + "input": "http:foo.com", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/foo.com", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/foo.com", + "search": "", + "hash": "" + }, + { + "input": "\t :foo.com \n", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:foo.com", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:foo.com", + "search": "", + "hash": "" + }, + { + "input": " foo.com ", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/foo.com", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/foo.com", + "search": "", + "hash": "" + }, + { + "input": "a:\t foo.com", + "base": "http://example.org/foo/bar", + "href": "a: foo.com", + "origin": "null", + "protocol": "a:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": " foo.com", + "search": "", + "hash": "" + }, + { + "input": "http://f:21/ b ? d # e ", + "base": "http://example.org/foo/bar", + "href": "http://f:21/%20b%20?%20d%20#%20e", + "origin": "http://f:21", + "protocol": "http:", + "username": "", + "password": "", + "host": "f:21", + "hostname": "f", + "port": "21", + "pathname": "/%20b%20", + "search": "?%20d%20", + "hash": "#%20e" + }, + { + "input": "lolscheme:x x#x x", + "base": null, + "href": "lolscheme:x x#x%20x", + "protocol": "lolscheme:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "x x", + "search": "", + "hash": "#x%20x" + }, + { + "input": "http://f:/c", + "base": "http://example.org/foo/bar", + "href": "http://f/c", + "origin": "http://f", + "protocol": "http:", + "username": "", + "password": "", + "host": "f", + "hostname": "f", + "port": "", + "pathname": "/c", + "search": "", + "hash": "" + }, + { + "input": "http://f:0/c", + "base": "http://example.org/foo/bar", + "href": "http://f:0/c", + "origin": "http://f:0", + "protocol": "http:", + "username": "", + "password": "", + "host": "f:0", + "hostname": "f", + "port": "0", + "pathname": "/c", + "search": "", + "hash": "" + }, + { + "input": "http://f:00000000000000/c", + "base": "http://example.org/foo/bar", + "href": "http://f:0/c", + "origin": "http://f:0", + "protocol": "http:", + "username": "", + "password": "", + "host": "f:0", + "hostname": "f", + "port": "0", + "pathname": "/c", + "search": "", + "hash": "" + }, + { + "input": "http://f:00000000000000000000080/c", + "base": "http://example.org/foo/bar", + "href": "http://f/c", + "origin": "http://f", + "protocol": "http:", + "username": "", + "password": "", + "host": "f", + "hostname": "f", + "port": "", + "pathname": "/c", + "search": "", + "hash": "" + }, + { + "input": "http://f:b/c", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://f: /c", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://f:\n/c", + "base": "http://example.org/foo/bar", + "href": "http://f/c", + "origin": "http://f", + "protocol": "http:", + "username": "", + "password": "", + "host": "f", + "hostname": "f", + "port": "", + "pathname": "/c", + "search": "", + "hash": "" + }, + { + "input": "http://f:fifty-two/c", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://f:999999/c", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "non-special://f:999999/c", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://f: 21 / b ? d # e ", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "" + }, + { + "input": " \t", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "" + }, + { + "input": ":foo.com/", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:foo.com/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:foo.com/", + "search": "", + "hash": "" + }, + { + "input": ":foo.com\\", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:foo.com/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:foo.com/", + "search": "", + "hash": "" + }, + { + "input": ":", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:", + "search": "", + "hash": "" + }, + { + "input": ":a", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:a", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:a", + "search": "", + "hash": "" + }, + { + "input": ":/", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:/", + "search": "", + "hash": "" + }, + { + "input": ":\\", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:/", + "search": "", + "hash": "" + }, + { + "input": ":#", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:#", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:", + "search": "", + "hash": "" + }, + { + "input": "#", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar#", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "#/", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar#/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "#/" + }, + { + "input": "#\\", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar#\\", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "#\\" + }, + { + "input": "#;?", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar#;?", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "#;?" + }, + { + "input": "?", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar?", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "/", + "base": "http://example.org/foo/bar", + "href": "http://example.org/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": ":23", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:23", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:23", + "search": "", + "hash": "" + }, + { + "input": "/:23", + "base": "http://example.org/foo/bar", + "href": "http://example.org/:23", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/:23", + "search": "", + "hash": "" + }, + { + "input": "\\x", + "base": "http://example.org/foo/bar", + "href": "http://example.org/x", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/x", + "search": "", + "hash": "" + }, + { + "input": "\\\\x\\hello", + "base": "http://example.org/foo/bar", + "href": "http://x/hello", + "origin": "http://x", + "protocol": "http:", + "username": "", + "password": "", + "host": "x", + "hostname": "x", + "port": "", + "pathname": "/hello", + "search": "", + "hash": "" + }, + { + "input": "::", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/::", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/::", + "search": "", + "hash": "" + }, + { + "input": "::23", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/::23", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/::23", + "search": "", + "hash": "" + }, + { + "input": "foo://", + "base": "http://example.org/foo/bar", + "href": "foo://", + "origin": "null", + "protocol": "foo:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "http://a:b@c:29/d", + "base": "http://example.org/foo/bar", + "href": "http://a:b@c:29/d", + "origin": "http://c:29", + "protocol": "http:", + "username": "a", + "password": "b", + "host": "c:29", + "hostname": "c", + "port": "29", + "pathname": "/d", + "search": "", + "hash": "" + }, + { + "input": "http://é@é", + "base": null, + "href": "http://%C3%A9@xn--9ca/", + "origin": "http://xn--9ca", + "protocol": "http:", + "username": "%C3%A9", + "password": "", + "host": "xn--9ca", + "hostname": "xn--9ca", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://é@example.com", + "base": null, + "href": "http://%C3%A9@example.com/", + "origin": "http://example.com", + "protocol": "http:", + "username": "%C3%A9", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http::@c:29", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/:@c:29", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/:@c:29", + "search": "", + "hash": "" + }, + { + "input": "http://&a:foo(b]c@d:2/", + "base": "http://example.org/foo/bar", + "href": "http://&a:foo(b%5Dc@d:2/", + "origin": "http://d:2", + "protocol": "http:", + "username": "&a", + "password": "foo(b%5Dc", + "host": "d:2", + "hostname": "d", + "port": "2", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://::@c@d:2", + "base": "http://example.org/foo/bar", + "href": "http://:%3A%40c@d:2/", + "origin": "http://d:2", + "protocol": "http:", + "username": "", + "password": "%3A%40c", + "host": "d:2", + "hostname": "d", + "port": "2", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://foo.com:b@d/", + "base": "http://example.org/foo/bar", + "href": "http://foo.com:b@d/", + "origin": "http://d", + "protocol": "http:", + "username": "foo.com", + "password": "b", + "host": "d", + "hostname": "d", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://foo.com/\\@", + "base": "http://example.org/foo/bar", + "href": "http://foo.com//@", + "origin": "http://foo.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo.com", + "hostname": "foo.com", + "port": "", + "pathname": "//@", + "search": "", + "hash": "" + }, + { + "input": "http:\\\\foo.com\\", + "base": "http://example.org/foo/bar", + "href": "http://foo.com/", + "origin": "http://foo.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo.com", + "hostname": "foo.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:\\\\a\\b:c\\d@foo.com\\", + "base": "http://example.org/foo/bar", + "href": "http://a/b:c/d@foo.com/", + "origin": "http://a", + "protocol": "http:", + "username": "", + "password": "", + "host": "a", + "hostname": "a", + "port": "", + "pathname": "/b:c/d@foo.com/", + "search": "", + "hash": "" + }, + { + "input": "http://a:b@c\\", + "base": null, + "href": "http://a:b@c/", + "origin": "http://c", + "protocol": "http:", + "username": "a", + "password": "b", + "host": "c", + "hostname": "c", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ws://a@b\\c", + "base": null, + "href": "ws://a@b/c", + "origin": "ws://b", + "protocol": "ws:", + "username": "a", + "password": "", + "host": "b", + "hostname": "b", + "port": "", + "pathname": "/c", + "search": "", + "hash": "" + }, + { + "input": "foo:/", + "base": "http://example.org/foo/bar", + "href": "foo:/", + "origin": "null", + "protocol": "foo:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "foo:/bar.com/", + "base": "http://example.org/foo/bar", + "href": "foo:/bar.com/", + "origin": "null", + "protocol": "foo:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/bar.com/", + "search": "", + "hash": "" + }, + { + "input": "foo://///////", + "base": "http://example.org/foo/bar", + "href": "foo://///////", + "origin": "null", + "protocol": "foo:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "///////", + "search": "", + "hash": "" + }, + { + "input": "foo://///////bar.com/", + "base": "http://example.org/foo/bar", + "href": "foo://///////bar.com/", + "origin": "null", + "protocol": "foo:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "///////bar.com/", + "search": "", + "hash": "" + }, + { + "input": "foo:////://///", + "base": "http://example.org/foo/bar", + "href": "foo:////://///", + "origin": "null", + "protocol": "foo:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//://///", + "search": "", + "hash": "" + }, + { + "input": "c:/foo", + "base": "http://example.org/foo/bar", + "href": "c:/foo", + "origin": "null", + "protocol": "c:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/foo", + "search": "", + "hash": "" + }, + { + "input": "//foo/bar", + "base": "http://example.org/foo/bar", + "href": "http://foo/bar", + "origin": "http://foo", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/bar", + "search": "", + "hash": "" + }, + { + "input": "http://foo/path;a??e#f#g", + "base": "http://example.org/foo/bar", + "href": "http://foo/path;a??e#f#g", + "origin": "http://foo", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/path;a", + "search": "??e", + "hash": "#f#g" + }, + { + "input": "http://foo/abcd?efgh?ijkl", + "base": "http://example.org/foo/bar", + "href": "http://foo/abcd?efgh?ijkl", + "origin": "http://foo", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/abcd", + "search": "?efgh?ijkl", + "hash": "" + }, + { + "input": "http://foo/abcd#foo?bar", + "base": "http://example.org/foo/bar", + "href": "http://foo/abcd#foo?bar", + "origin": "http://foo", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/abcd", + "search": "", + "hash": "#foo?bar" + }, + { + "input": "[61:24:74]:98", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/[61:24:74]:98", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/[61:24:74]:98", + "search": "", + "hash": "" + }, + { + "input": "http:[61:27]/:foo", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/[61:27]/:foo", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/[61:27]/:foo", + "search": "", + "hash": "" + }, + { + "input": "http://[1::2]:3:4", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://2001::1", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://2001::1]", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://2001::1]:80", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://[2001::1]", + "base": "http://example.org/foo/bar", + "href": "http://[2001::1]/", + "origin": "http://[2001::1]", + "protocol": "http:", + "username": "", + "password": "", + "host": "[2001::1]", + "hostname": "[2001::1]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://[::127.0.0.1]", + "base": "http://example.org/foo/bar", + "href": "http://[::7f00:1]/", + "origin": "http://[::7f00:1]", + "protocol": "http:", + "username": "", + "password": "", + "host": "[::7f00:1]", + "hostname": "[::7f00:1]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://[::127.0.0.1.]", + "base": "http://example.org/foo/bar", + "failure": true + }, + { + "input": "http://[0:0:0:0:0:0:13.1.68.3]", + "base": "http://example.org/foo/bar", + "href": "http://[::d01:4403]/", + "origin": "http://[::d01:4403]", + "protocol": "http:", + "username": "", + "password": "", + "host": "[::d01:4403]", + "hostname": "[::d01:4403]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://[2001::1]:80", + "base": "http://example.org/foo/bar", + "href": "http://[2001::1]/", + "origin": "http://[2001::1]", + "protocol": "http:", + "username": "", + "password": "", + "host": "[2001::1]", + "hostname": "[2001::1]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/example.com/", + "base": "http://example.org/foo/bar", + "href": "http://example.org/example.com/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "http:/", + "base": "http://example.com/", + "href": "http://example.com/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ftp:/example.com/", + "base": "http://example.org/foo/bar", + "href": "ftp://example.com/", + "origin": "ftp://example.com", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https:/example.com/", + "base": "http://example.org/foo/bar", + "href": "https://example.com/", + "origin": "https://example.com", + "protocol": "https:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "madeupscheme:/example.com/", + "base": "http://example.org/foo/bar", + "href": "madeupscheme:/example.com/", + "origin": "null", + "protocol": "madeupscheme:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "file:/example.com/", + "base": "http://example.org/foo/bar", + "href": "file:///example.com/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "file://example:1/", + "base": null, + "failure": true + }, + { + "input": "file://example:test/", + "base": null, + "failure": true + }, + { + "input": "file://example%/", + "base": null, + "failure": true + }, + { + "input": "file://[example]/", + "base": null, + "failure": true + }, + { + "input": "ftps:/example.com/", + "base": "http://example.org/foo/bar", + "href": "ftps:/example.com/", + "origin": "null", + "protocol": "ftps:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "gopher:/example.com/", + "base": "http://example.org/foo/bar", + "href": "gopher:/example.com/", + "origin": "null", + "protocol": "gopher:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "ws:/example.com/", + "base": "http://example.org/foo/bar", + "href": "ws://example.com/", + "origin": "ws://example.com", + "protocol": "ws:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss:/example.com/", + "base": "http://example.org/foo/bar", + "href": "wss://example.com/", + "origin": "wss://example.com", + "protocol": "wss:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "data:/example.com/", + "base": "http://example.org/foo/bar", + "href": "data:/example.com/", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "javascript:/example.com/", + "base": "http://example.org/foo/bar", + "href": "javascript:/example.com/", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "mailto:/example.com/", + "base": "http://example.org/foo/bar", + "href": "mailto:/example.com/", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "http:example.com/", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/example.com/", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/example.com/", + "search": "", + "hash": "" + }, + { + "input": "ftp:example.com/", + "base": "http://example.org/foo/bar", + "href": "ftp://example.com/", + "origin": "ftp://example.com", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https:example.com/", + "base": "http://example.org/foo/bar", + "href": "https://example.com/", + "origin": "https://example.com", + "protocol": "https:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "madeupscheme:example.com/", + "base": "http://example.org/foo/bar", + "href": "madeupscheme:example.com/", + "origin": "null", + "protocol": "madeupscheme:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "ftps:example.com/", + "base": "http://example.org/foo/bar", + "href": "ftps:example.com/", + "origin": "null", + "protocol": "ftps:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "gopher:example.com/", + "base": "http://example.org/foo/bar", + "href": "gopher:example.com/", + "origin": "null", + "protocol": "gopher:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "ws:example.com/", + "base": "http://example.org/foo/bar", + "href": "ws://example.com/", + "origin": "ws://example.com", + "protocol": "ws:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss:example.com/", + "base": "http://example.org/foo/bar", + "href": "wss://example.com/", + "origin": "wss://example.com", + "protocol": "wss:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "data:example.com/", + "base": "http://example.org/foo/bar", + "href": "data:example.com/", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "javascript:example.com/", + "base": "http://example.org/foo/bar", + "href": "javascript:example.com/", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "mailto:example.com/", + "base": "http://example.org/foo/bar", + "href": "mailto:example.com/", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "/a/b/c", + "base": "http://example.org/foo/bar", + "href": "http://example.org/a/b/c", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/a/b/c", + "search": "", + "hash": "" + }, + { + "input": "/a/ /c", + "base": "http://example.org/foo/bar", + "href": "http://example.org/a/%20/c", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/a/%20/c", + "search": "", + "hash": "" + }, + { + "input": "/a%2fc", + "base": "http://example.org/foo/bar", + "href": "http://example.org/a%2fc", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/a%2fc", + "search": "", + "hash": "" + }, + { + "input": "/a/%2f/c", + "base": "http://example.org/foo/bar", + "href": "http://example.org/a/%2f/c", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/a/%2f/c", + "search": "", + "hash": "" + }, + { + "input": "#β", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar#%CE%B2", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "#%CE%B2" + }, + { + "input": "data:text/html,test#test", + "base": "http://example.org/foo/bar", + "href": "data:text/html,test#test", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "text/html,test", + "search": "", + "hash": "#test" + }, + { + "input": "tel:1234567890", + "base": "http://example.org/foo/bar", + "href": "tel:1234567890", + "origin": "null", + "protocol": "tel:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "1234567890", + "search": "", + "hash": "" + }, + "# Based on https://felixfbecker.github.io/whatwg-url-custom-host-repro/", + { + "input": "ssh://example.com/foo/bar.git", + "base": "http://example.org/", + "href": "ssh://example.com/foo/bar.git", + "origin": "null", + "protocol": "ssh:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/bar.git", + "search": "", + "hash": "" + }, + "# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/file.html", + { + "input": "file:c:\\foo\\bar.html", + "base": "file:///tmp/mock/path", + "href": "file:///c:/foo/bar.html", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/c:/foo/bar.html", + "search": "", + "hash": "" + }, + { + "input": " File:c|////foo\\bar.html", + "base": "file:///tmp/mock/path", + "href": "file:///c:////foo/bar.html", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/c:////foo/bar.html", + "search": "", + "hash": "" + }, + { + "input": "C|/foo/bar", + "base": "file:///tmp/mock/path", + "href": "file:///C:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "/C|\\foo\\bar", + "base": "file:///tmp/mock/path", + "href": "file:///C:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "//C|/foo/bar", + "base": "file:///tmp/mock/path", + "href": "file:///C:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "//server/file", + "base": "file:///tmp/mock/path", + "href": "file://server/file", + "protocol": "file:", + "username": "", + "password": "", + "host": "server", + "hostname": "server", + "port": "", + "pathname": "/file", + "search": "", + "hash": "" + }, + { + "input": "\\\\server\\file", + "base": "file:///tmp/mock/path", + "href": "file://server/file", + "protocol": "file:", + "username": "", + "password": "", + "host": "server", + "hostname": "server", + "port": "", + "pathname": "/file", + "search": "", + "hash": "" + }, + { + "input": "/\\server/file", + "base": "file:///tmp/mock/path", + "href": "file://server/file", + "protocol": "file:", + "username": "", + "password": "", + "host": "server", + "hostname": "server", + "port": "", + "pathname": "/file", + "search": "", + "hash": "" + }, + { + "input": "file:///foo/bar.txt", + "base": "file:///tmp/mock/path", + "href": "file:///foo/bar.txt", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/foo/bar.txt", + "search": "", + "hash": "" + }, + { + "input": "file:///home/me", + "base": "file:///tmp/mock/path", + "href": "file:///home/me", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/home/me", + "search": "", + "hash": "" + }, + { + "input": "//", + "base": "file:///tmp/mock/path", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "///", + "base": "file:///tmp/mock/path", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "///test", + "base": "file:///tmp/mock/path", + "href": "file:///test", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "file://test", + "base": "file:///tmp/mock/path", + "href": "file://test/", + "protocol": "file:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file://localhost", + "base": "file:///tmp/mock/path", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file://localhost/", + "base": "file:///tmp/mock/path", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file://localhost/test", + "base": "file:///tmp/mock/path", + "href": "file:///test", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "test", + "base": "file:///tmp/mock/path", + "href": "file:///tmp/mock/test", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/tmp/mock/test", + "search": "", + "hash": "" + }, + { + "input": "file:test", + "base": "file:///tmp/mock/path", + "href": "file:///tmp/mock/test", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/tmp/mock/test", + "search": "", + "hash": "" + }, + { + "input": "file:///w|m", + "base": null, + "href": "file:///w|m", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/w|m", + "search": "", + "hash": "" + }, + { + "input": "file:///w||m", + "base": null, + "href": "file:///w||m", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/w||m", + "search": "", + "hash": "" + }, + { + "input": "file:///w|/m", + "base": null, + "href": "file:///w:/m", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/w:/m", + "search": "", + "hash": "" + }, + { + "input": "file:C|/m/", + "base": null, + "href": "file:///C:/m/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/m/", + "search": "", + "hash": "" + }, + { + "input": "file:C||/m/", + "base": null, + "href": "file:///C||/m/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C||/m/", + "search": "", + "hash": "" + }, + "# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/script-tests/path.js", + { + "input": "http://example.com/././foo", + "base": null, + "href": "http://example.com/foo", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/./.foo", + "base": null, + "href": "http://example.com/.foo", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/.foo", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/.", + "base": null, + "href": "http://example.com/foo/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/./", + "base": null, + "href": "http://example.com/foo/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/bar/..", + "base": null, + "href": "http://example.com/foo/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/bar/../", + "base": null, + "href": "http://example.com/foo/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/..bar", + "base": null, + "href": "http://example.com/foo/..bar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/..bar", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/bar/../ton", + "base": null, + "href": "http://example.com/foo/ton", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/ton", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/bar/../ton/../../a", + "base": null, + "href": "http://example.com/a", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/a", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/../../..", + "base": null, + "href": "http://example.com/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/../../../ton", + "base": null, + "href": "http://example.com/ton", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/ton", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/%2e", + "base": null, + "href": "http://example.com/foo/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/%2e%2", + "base": null, + "href": "http://example.com/foo/%2e%2", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/%2e%2", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/%2e./%2e%2e/.%2e/%2e.bar", + "base": null, + "href": "http://example.com/%2e.bar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%2e.bar", + "search": "", + "hash": "" + }, + { + "input": "http://example.com////../..", + "base": null, + "href": "http://example.com//", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/bar//../..", + "base": null, + "href": "http://example.com/foo/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo/bar//..", + "base": null, + "href": "http://example.com/foo/bar/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo/bar/", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo", + "base": null, + "href": "http://example.com/foo", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/%20foo", + "base": null, + "href": "http://example.com/%20foo", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%20foo", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo%", + "base": null, + "href": "http://example.com/foo%", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo%2", + "base": null, + "href": "http://example.com/foo%2", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%2", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo%2zbar", + "base": null, + "href": "http://example.com/foo%2zbar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%2zbar", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo%2©zbar", + "base": null, + "href": "http://example.com/foo%2%C3%82%C2%A9zbar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%2%C3%82%C2%A9zbar", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo%41%7a", + "base": null, + "href": "http://example.com/foo%41%7a", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%41%7a", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo\t\u0091%91", + "base": null, + "href": "http://example.com/foo%C2%91%91", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%C2%91%91", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo%00%51", + "base": null, + "href": "http://example.com/foo%00%51", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foo%00%51", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/(%28:%3A%29)", + "base": null, + "href": "http://example.com/(%28:%3A%29)", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/(%28:%3A%29)", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/%3A%3a%3C%3c", + "base": null, + "href": "http://example.com/%3A%3a%3C%3c", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%3A%3a%3C%3c", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/foo\tbar", + "base": null, + "href": "http://example.com/foobar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/foobar", + "search": "", + "hash": "" + }, + { + "input": "http://example.com\\\\foo\\\\bar", + "base": null, + "href": "http://example.com//foo//bar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "//foo//bar", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/%7Ffp3%3Eju%3Dduvgw%3Dd", + "base": null, + "href": "http://example.com/%7Ffp3%3Eju%3Dduvgw%3Dd", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%7Ffp3%3Eju%3Dduvgw%3Dd", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/@asdf%40", + "base": null, + "href": "http://example.com/@asdf%40", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/@asdf%40", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/你好你好", + "base": null, + "href": "http://example.com/%E4%BD%A0%E5%A5%BD%E4%BD%A0%E5%A5%BD", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%E4%BD%A0%E5%A5%BD%E4%BD%A0%E5%A5%BD", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/‥/foo", + "base": null, + "href": "http://example.com/%E2%80%A5/foo", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%E2%80%A5/foo", + "search": "", + "hash": "" + }, + { + "input": "http://example.com//foo", + "base": null, + "href": "http://example.com/%EF%BB%BF/foo", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%EF%BB%BF/foo", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/‮/foo/‭/bar", + "base": null, + "href": "http://example.com/%E2%80%AE/foo/%E2%80%AD/bar", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%E2%80%AE/foo/%E2%80%AD/bar", + "search": "", + "hash": "" + }, + "# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/script-tests/relative.js", + { + "input": "http://www.google.com/foo?bar=baz#", + "base": null, + "href": "http://www.google.com/foo?bar=baz#", + "origin": "http://www.google.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.google.com", + "hostname": "www.google.com", + "port": "", + "pathname": "/foo", + "search": "?bar=baz", + "hash": "" + }, + { + "input": "http://www.google.com/foo?bar=baz# »", + "base": null, + "href": "http://www.google.com/foo?bar=baz#%20%C2%BB", + "origin": "http://www.google.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.google.com", + "hostname": "www.google.com", + "port": "", + "pathname": "/foo", + "search": "?bar=baz", + "hash": "#%20%C2%BB" + }, + { + "input": "data:test# »", + "base": null, + "href": "data:test#%20%C2%BB", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "test", + "search": "", + "hash": "#%20%C2%BB" + }, + { + "input": "http://www.google.com", + "base": null, + "href": "http://www.google.com/", + "origin": "http://www.google.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.google.com", + "hostname": "www.google.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://192.0x00A80001", + "base": null, + "href": "http://192.168.0.1/", + "origin": "http://192.168.0.1", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.0.1", + "hostname": "192.168.0.1", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://www/foo%2Ehtml", + "base": null, + "href": "http://www/foo%2Ehtml", + "origin": "http://www", + "protocol": "http:", + "username": "", + "password": "", + "host": "www", + "hostname": "www", + "port": "", + "pathname": "/foo%2Ehtml", + "search": "", + "hash": "" + }, + { + "input": "http://www/foo/%2E/html", + "base": null, + "href": "http://www/foo/html", + "origin": "http://www", + "protocol": "http:", + "username": "", + "password": "", + "host": "www", + "hostname": "www", + "port": "", + "pathname": "/foo/html", + "search": "", + "hash": "" + }, + { + "input": "http://user:pass@/", + "base": null, + "failure": true + }, + { + "input": "http://%25DOMAIN:foobar@foodomain.com/", + "base": null, + "href": "http://%25DOMAIN:foobar@foodomain.com/", + "origin": "http://foodomain.com", + "protocol": "http:", + "username": "%25DOMAIN", + "password": "foobar", + "host": "foodomain.com", + "hostname": "foodomain.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:\\\\www.google.com\\foo", + "base": null, + "href": "http://www.google.com/foo", + "origin": "http://www.google.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.google.com", + "hostname": "www.google.com", + "port": "", + "pathname": "/foo", + "search": "", + "hash": "" + }, + { + "input": "http://foo:80/", + "base": null, + "href": "http://foo/", + "origin": "http://foo", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://foo:81/", + "base": null, + "href": "http://foo:81/", + "origin": "http://foo:81", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo:81", + "hostname": "foo", + "port": "81", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "httpa://foo:80/", + "base": null, + "href": "httpa://foo:80/", + "origin": "null", + "protocol": "httpa:", + "username": "", + "password": "", + "host": "foo:80", + "hostname": "foo", + "port": "80", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://foo:-80/", + "base": null, + "failure": true + }, + { + "input": "https://foo:443/", + "base": null, + "href": "https://foo/", + "origin": "https://foo", + "protocol": "https:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://foo:80/", + "base": null, + "href": "https://foo:80/", + "origin": "https://foo:80", + "protocol": "https:", + "username": "", + "password": "", + "host": "foo:80", + "hostname": "foo", + "port": "80", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ftp://foo:21/", + "base": null, + "href": "ftp://foo/", + "origin": "ftp://foo", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ftp://foo:80/", + "base": null, + "href": "ftp://foo:80/", + "origin": "ftp://foo:80", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "foo:80", + "hostname": "foo", + "port": "80", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "gopher://foo:70/", + "base": null, + "href": "gopher://foo:70/", + "origin": "null", + "protocol": "gopher:", + "username": "", + "password": "", + "host": "foo:70", + "hostname": "foo", + "port": "70", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "gopher://foo:443/", + "base": null, + "href": "gopher://foo:443/", + "origin": "null", + "protocol": "gopher:", + "username": "", + "password": "", + "host": "foo:443", + "hostname": "foo", + "port": "443", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ws://foo:80/", + "base": null, + "href": "ws://foo/", + "origin": "ws://foo", + "protocol": "ws:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ws://foo:81/", + "base": null, + "href": "ws://foo:81/", + "origin": "ws://foo:81", + "protocol": "ws:", + "username": "", + "password": "", + "host": "foo:81", + "hostname": "foo", + "port": "81", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ws://foo:443/", + "base": null, + "href": "ws://foo:443/", + "origin": "ws://foo:443", + "protocol": "ws:", + "username": "", + "password": "", + "host": "foo:443", + "hostname": "foo", + "port": "443", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ws://foo:815/", + "base": null, + "href": "ws://foo:815/", + "origin": "ws://foo:815", + "protocol": "ws:", + "username": "", + "password": "", + "host": "foo:815", + "hostname": "foo", + "port": "815", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss://foo:80/", + "base": null, + "href": "wss://foo:80/", + "origin": "wss://foo:80", + "protocol": "wss:", + "username": "", + "password": "", + "host": "foo:80", + "hostname": "foo", + "port": "80", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss://foo:81/", + "base": null, + "href": "wss://foo:81/", + "origin": "wss://foo:81", + "protocol": "wss:", + "username": "", + "password": "", + "host": "foo:81", + "hostname": "foo", + "port": "81", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss://foo:443/", + "base": null, + "href": "wss://foo/", + "origin": "wss://foo", + "protocol": "wss:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss://foo:815/", + "base": null, + "href": "wss://foo:815/", + "origin": "wss://foo:815", + "protocol": "wss:", + "username": "", + "password": "", + "host": "foo:815", + "hostname": "foo", + "port": "815", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/example.com/", + "base": null, + "href": "http://example.com/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ftp:/example.com/", + "base": null, + "href": "ftp://example.com/", + "origin": "ftp://example.com", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https:/example.com/", + "base": null, + "href": "https://example.com/", + "origin": "https://example.com", + "protocol": "https:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "madeupscheme:/example.com/", + "base": null, + "href": "madeupscheme:/example.com/", + "origin": "null", + "protocol": "madeupscheme:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "file:/example.com/", + "base": null, + "href": "file:///example.com/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "ftps:/example.com/", + "base": null, + "href": "ftps:/example.com/", + "origin": "null", + "protocol": "ftps:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "gopher:/example.com/", + "base": null, + "href": "gopher:/example.com/", + "origin": "null", + "protocol": "gopher:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "ws:/example.com/", + "base": null, + "href": "ws://example.com/", + "origin": "ws://example.com", + "protocol": "ws:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss:/example.com/", + "base": null, + "href": "wss://example.com/", + "origin": "wss://example.com", + "protocol": "wss:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "data:/example.com/", + "base": null, + "href": "data:/example.com/", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "javascript:/example.com/", + "base": null, + "href": "javascript:/example.com/", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "mailto:/example.com/", + "base": null, + "href": "mailto:/example.com/", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/example.com/", + "search": "", + "hash": "" + }, + { + "input": "http:example.com/", + "base": null, + "href": "http://example.com/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ftp:example.com/", + "base": null, + "href": "ftp://example.com/", + "origin": "ftp://example.com", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https:example.com/", + "base": null, + "href": "https://example.com/", + "origin": "https://example.com", + "protocol": "https:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "madeupscheme:example.com/", + "base": null, + "href": "madeupscheme:example.com/", + "origin": "null", + "protocol": "madeupscheme:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "ftps:example.com/", + "base": null, + "href": "ftps:example.com/", + "origin": "null", + "protocol": "ftps:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "gopher:example.com/", + "base": null, + "href": "gopher:example.com/", + "origin": "null", + "protocol": "gopher:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "ws:example.com/", + "base": null, + "href": "ws://example.com/", + "origin": "ws://example.com", + "protocol": "ws:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "wss:example.com/", + "base": null, + "href": "wss://example.com/", + "origin": "wss://example.com", + "protocol": "wss:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "data:example.com/", + "base": null, + "href": "data:example.com/", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "javascript:example.com/", + "base": null, + "href": "javascript:example.com/", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "mailto:example.com/", + "base": null, + "href": "mailto:example.com/", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "example.com/", + "search": "", + "hash": "" + }, + { + "input": "https://example.com/aaa/bbb/%2e%2e?query", + "base": null, + "href": "https://example.com/aaa/?query", + "origin": "https://example.com", + "protocol": "https:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/aaa/", + "search": "?query", + "hash": "" + }, + "# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/segments-userinfo-vs-host.html", + { + "input": "http:@www.example.com", + "base": null, + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/@www.example.com", + "base": null, + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://@www.example.com", + "base": null, + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:a:b@www.example.com", + "base": null, + "href": "http://a:b@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "a", + "password": "b", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/a:b@www.example.com", + "base": null, + "href": "http://a:b@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "a", + "password": "b", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://a:b@www.example.com", + "base": null, + "href": "http://a:b@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "a", + "password": "b", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://@pple.com", + "base": null, + "href": "http://pple.com/", + "origin": "http://pple.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "pple.com", + "hostname": "pple.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http::b@www.example.com", + "base": null, + "href": "http://:b@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "b", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/:b@www.example.com", + "base": null, + "href": "http://:b@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "b", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://:b@www.example.com", + "base": null, + "href": "http://:b@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "b", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/:@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http://user@/www.example.com", + "base": null, + "failure": true + }, + { + "input": "http:@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http:/@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http://@/www.example.com", + "base": null, + "failure": true + }, + { + "input": "https:@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http:a:b@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http:/a:b@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http://a:b@/www.example.com", + "base": null, + "failure": true + }, + { + "input": "http::@/www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http:a:@www.example.com", + "base": null, + "href": "http://a@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "a", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:/a:@www.example.com", + "base": null, + "href": "http://a@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "a", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://a:@www.example.com", + "base": null, + "href": "http://a@www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "a", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://www.@pple.com", + "base": null, + "href": "http://www.@pple.com/", + "origin": "http://pple.com", + "protocol": "http:", + "username": "www.", + "password": "", + "host": "pple.com", + "hostname": "pple.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http:@:www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http:/@:www.example.com", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "http://@:www.example.com", + "base": null, + "failure": true + }, + { + "input": "http://:@www.example.com", + "base": null, + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# Others", + { + "input": "/", + "base": "http://www.example.com/test", + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "/test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/test.txt", + "search": "", + "hash": "" + }, + { + "input": ".", + "base": "http://www.example.com/test", + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "..", + "base": "http://www.example.com/test", + "href": "http://www.example.com/", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/test.txt", + "search": "", + "hash": "" + }, + { + "input": "./test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/test.txt", + "search": "", + "hash": "" + }, + { + "input": "../test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/test.txt", + "search": "", + "hash": "" + }, + { + "input": "../aaa/test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/aaa/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/aaa/test.txt", + "search": "", + "hash": "" + }, + { + "input": "../../test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/test.txt", + "search": "", + "hash": "" + }, + { + "input": "中/test.txt", + "base": "http://www.example.com/test", + "href": "http://www.example.com/%E4%B8%AD/test.txt", + "origin": "http://www.example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example.com", + "hostname": "www.example.com", + "port": "", + "pathname": "/%E4%B8%AD/test.txt", + "search": "", + "hash": "" + }, + { + "input": "http://www.example2.com", + "base": "http://www.example.com/test", + "href": "http://www.example2.com/", + "origin": "http://www.example2.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example2.com", + "hostname": "www.example2.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "//www.example2.com", + "base": "http://www.example.com/test", + "href": "http://www.example2.com/", + "origin": "http://www.example2.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.example2.com", + "hostname": "www.example2.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file:...", + "base": "http://www.example.com/test", + "href": "file:///...", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/...", + "search": "", + "hash": "" + }, + { + "input": "file:..", + "base": "http://www.example.com/test", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file:a", + "base": "http://www.example.com/test", + "href": "file:///a", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/a", + "search": "", + "hash": "" + }, + { + "input": "file:.", + "base": null, + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file:.", + "base": "http://www.example.com/test", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/host.html", + "Basic canonicalization, uppercase should be converted to lowercase", + { + "input": "http://ExAmPlE.CoM", + "base": "http://other.com/", + "href": "http://example.com/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://example example.com", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://Goo%20 goo%7C|.com", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[:]", + "base": "http://other.com/", + "failure": true + }, + "U+3000 is mapped to U+0020 (space) which is disallowed", + { + "input": "http://GOO\u00a0\u3000goo.com", + "base": "http://other.com/", + "failure": true + }, + "Other types of space (no-break, zero-width, zero-width-no-break) are name-prepped away to nothing. U+200B, U+2060, and U+FEFF, are ignored", + { + "input": "http://GOO\u200b\u2060\ufeffgoo.com", + "base": "http://other.com/", + "href": "http://googoo.com/", + "origin": "http://googoo.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "googoo.com", + "hostname": "googoo.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Leading and trailing C0 control or space", + { + "input": "\u0000\u001b\u0004\u0012 http://example.com/\u001f \u000d ", + "base": null, + "href": "http://example.com/", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "non-special:opaque ", + "base": null, + "href": "non-special:opaque", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "opaque", + "search": "", + "hash": "" + }, + { + "input": "non-special:opaque ?hi", + "base": null, + "href": "non-special:opaque %20?hi", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "opaque %20", + "search": "?hi", + "hash": "" + }, + { + "input": "non-special:opaque #hi", + "base": null, + "href": "non-special:opaque %20#hi", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "opaque %20", + "search": "", + "hash": "#hi" + }, + { + "input": "non-special:opaque x?hi", + "base": null, + "href": "non-special:opaque x?hi", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "opaque x", + "search": "?hi", + "hash": "" + }, + { + "input": "non-special:opaque x#hi", + "base": null, + "href": "non-special:opaque x#hi", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "opaque x", + "search": "", + "hash": "#hi" + }, + { + "input": "non-special:opaque \t\t \t#hi", + "base": null, + "href": "non-special:opaque %20#hi", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "opaque %20", + "search": "", + "hash": "#hi" + }, + { + "input": "non-special:opaque \t\t #hi", + "base": null, + "href": "non-special:opaque %20#hi", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "opaque %20", + "search": "", + "hash": "#hi" + }, + { + "input": "non-special:opaque\t\t \r #hi", + "base": null, + "href": "non-special:opaque %20#hi", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "opaque %20", + "search": "", + "hash": "#hi" + }, + "Ideographic full stop (full-width period for Chinese, etc.) should be treated as a dot. U+3002 is mapped to U+002E (dot)", + { + "input": "http://www.foo。bar.com", + "base": "http://other.com/", + "href": "http://www.foo.bar.com/", + "origin": "http://www.foo.bar.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "www.foo.bar.com", + "hostname": "www.foo.bar.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Invalid unicode characters should fail... U+FDD0 is disallowed; %ef%b7%90 is U+FDD0", + { + "input": "http://\ufdd0zyx.com", + "base": "http://other.com/", + "failure": true + }, + "This is the same as previous but escaped", + { + "input": "http://%ef%b7%90zyx.com", + "base": "http://other.com/", + "failure": true + }, + "U+FFFD", + { + "input": "https://\ufffd", + "base": null, + "failure": true + }, + { + "input": "https://%EF%BF%BD", + "base": null, + "failure": true + }, + { + "input": "https://x/\ufffd?\ufffd#\ufffd", + "base": null, + "href": "https://x/%EF%BF%BD?%EF%BF%BD#%EF%BF%BD", + "origin": "https://x", + "protocol": "https:", + "username": "", + "password": "", + "host": "x", + "hostname": "x", + "port": "", + "pathname": "/%EF%BF%BD", + "search": "?%EF%BF%BD", + "hash": "#%EF%BF%BD" + }, + "Domain is ASCII, but a label is invalid IDNA", + { + "input": "http://a.b.c.xn--pokxncvks", + "base": null, + "href": "http://a.b.c.xn--pokxncvks/", + "origin": "http://a.b.c.xn--pokxncvks", + "protocol": "http:", + "username": "", + "password": "", + "host": "a.b.c.xn--pokxncvks", + "hostname": "a.b.c.xn--pokxncvks", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://10.0.0.xn--pokxncvks", + "base": null, + "href": "http://10.0.0.xn--pokxncvks/", + "origin": "http://10.0.0.xn--pokxncvks", + "protocol": "http:", + "username": "", + "password": "", + "host": "10.0.0.xn--pokxncvks", + "hostname": "10.0.0.xn--pokxncvks", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "IDNA labels should be matched case-insensitively", + { + "input": "http://a.b.c.XN--pokxncvks", + "base": null, + "href": "http://a.b.c.xn--pokxncvks/", + "origin": "http://a.b.c.xn--pokxncvks", + "protocol": "http:", + "username": "", + "password": "", + "host": "a.b.c.xn--pokxncvks", + "hostname": "a.b.c.xn--pokxncvks", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://a.b.c.Xn--pokxncvks", + "base": null, + "href": "http://a.b.c.xn--pokxncvks/", + "origin": "http://a.b.c.xn--pokxncvks", + "protocol": "http:", + "username": "", + "password": "", + "host": "a.b.c.xn--pokxncvks", + "hostname": "a.b.c.xn--pokxncvks", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://10.0.0.XN--pokxncvks", + "base": null, + "href": "http://10.0.0.xn--pokxncvks/", + "origin": "http://10.0.0.xn--pokxncvks", + "protocol": "http:", + "username": "", + "password": "", + "host": "10.0.0.xn--pokxncvks", + "hostname": "10.0.0.xn--pokxncvks", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://10.0.0.xN--pokxncvks", + "base": null, + "href": "http://10.0.0.xn--pokxncvks/", + "origin": "http://10.0.0.xn--pokxncvks", + "protocol": "http:", + "username": "", + "password": "", + "host": "10.0.0.xn--pokxncvks", + "hostname": "10.0.0.xn--pokxncvks", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Test name prepping, fullwidth input should be converted to ASCII and NOT IDN-ized. This is 'Go' in fullwidth UTF-8/UTF-16.", + { + "input": "http://Go.com", + "base": "http://other.com/", + "href": "http://go.com/", + "origin": "http://go.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "go.com", + "hostname": "go.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "URL spec forbids the following. https://www.w3.org/Bugs/Public/show_bug.cgi?id=24257", + { + "input": "http://%41.com", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://%ef%bc%85%ef%bc%94%ef%bc%91.com", + "base": "http://other.com/", + "failure": true + }, + "...%00 in fullwidth should fail (also as escaped UTF-8 input)", + { + "input": "http://%00.com", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://%ef%bc%85%ef%bc%90%ef%bc%90.com", + "base": "http://other.com/", + "failure": true + }, + "Basic IDN support, UTF-8 and UTF-16 input should be converted to IDN", + { + "input": "http://你好你好", + "base": "http://other.com/", + "href": "http://xn--6qqa088eba/", + "origin": "http://xn--6qqa088eba", + "protocol": "http:", + "username": "", + "password": "", + "host": "xn--6qqa088eba", + "hostname": "xn--6qqa088eba", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://faß.ExAmPlE/", + "base": null, + "href": "https://xn--fa-hia.example/", + "origin": "https://xn--fa-hia.example", + "protocol": "https:", + "username": "", + "password": "", + "host": "xn--fa-hia.example", + "hostname": "xn--fa-hia.example", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "sc://faß.ExAmPlE/", + "base": null, + "href": "sc://fa%C3%9F.ExAmPlE/", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "fa%C3%9F.ExAmPlE", + "hostname": "fa%C3%9F.ExAmPlE", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Invalid escaped characters should fail and the percents should be escaped. https://www.w3.org/Bugs/Public/show_bug.cgi?id=24191", + { + "input": "http://%zz%66%a.com", + "base": "http://other.com/", + "failure": true + }, + "If we get an invalid character that has been escaped.", + { + "input": "http://%25", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://hello%00", + "base": "http://other.com/", + "failure": true + }, + "Escaped numbers should be treated like IP addresses if they are.", + { + "input": "http://%30%78%63%30%2e%30%32%35%30.01", + "base": "http://other.com/", + "href": "http://192.168.0.1/", + "origin": "http://192.168.0.1", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.0.1", + "hostname": "192.168.0.1", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://%30%78%63%30%2e%30%32%35%30.01%2e", + "base": "http://other.com/", + "href": "http://192.168.0.1/", + "origin": "http://192.168.0.1", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.0.1", + "hostname": "192.168.0.1", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://192.168.0.257", + "base": "http://other.com/", + "failure": true + }, + "Invalid escaping in hosts causes failure", + { + "input": "http://%3g%78%63%30%2e%30%32%35%30%2E.01", + "base": "http://other.com/", + "failure": true + }, + "A space in a host causes failure", + { + "input": "http://192.168.0.1 hello", + "base": "http://other.com/", + "failure": true + }, + { + "input": "https://x x:12", + "base": null, + "failure": true + }, + "Fullwidth and escaped UTF-8 fullwidth should still be treated as IP", + { + "input": "http://0Xc0.0250.01", + "base": "http://other.com/", + "href": "http://192.168.0.1/", + "origin": "http://192.168.0.1", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.0.1", + "hostname": "192.168.0.1", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Domains with empty labels", + { + "input": "http://./", + "base": null, + "href": "http://./", + "origin": "http://.", + "protocol": "http:", + "username": "", + "password": "", + "host": ".", + "hostname": ".", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://../", + "base": null, + "href": "http://../", + "origin": "http://..", + "protocol": "http:", + "username": "", + "password": "", + "host": "..", + "hostname": "..", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Non-special domains with empty labels", + { + "input": "h://.", + "base": null, + "href": "h://.", + "origin": "null", + "protocol": "h:", + "username": "", + "password": "", + "host": ".", + "hostname": ".", + "port": "", + "pathname": "", + "search": "", + "hash": "" + }, + "Broken IPv6", + { + "input": "http://[www.google.com]/", + "base": null, + "failure": true + }, + { + "input": "http://[google.com]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::1.2.3.4x]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::1.2.3.]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::1.2.]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::.1.2]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::1.]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::.1]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://[::%31]", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://%5B::1]", + "base": "http://other.com/", + "failure": true + }, + "Misc Unicode", + { + "input": "http://foo:💩@example.com/bar", + "base": "http://other.com/", + "href": "http://foo:%F0%9F%92%A9@example.com/bar", + "origin": "http://example.com", + "protocol": "http:", + "username": "foo", + "password": "%F0%9F%92%A9", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/bar", + "search": "", + "hash": "" + }, + "Astral code point followed by a trailing character in the userinfo", + { + "input": "http://😀x@host/", + "base": null, + "href": "http://%F0%9F%98%80x@host/", + "origin": "http://host", + "protocol": "http:", + "username": "%F0%9F%98%80x", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://a:😀x@host/", + "base": null, + "href": "http://a:%F0%9F%98%80x@host/", + "origin": "http://host", + "protocol": "http:", + "username": "a", + "password": "%F0%9F%98%80x", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://😀@host/", + "base": null, + "href": "http://%F0%9F%98%80@host/", + "origin": "http://host", + "protocol": "http:", + "username": "%F0%9F%98%80", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://localhost?q=🔥", + "base": null, + "href": "https://localhost/?q=%F0%9F%94%A5", + "origin": "https://localhost", + "protocol": "https:", + "username": "", + "password": "", + "host": "localhost", + "hostname": "localhost", + "port": "", + "pathname": "/", + "search": "?q=%F0%9F%94%A5", + "hash": "" + }, + { + "input": "https://localhost#🔥", + "base": null, + "href": "https://localhost/#%F0%9F%94%A5", + "origin": "https://localhost", + "protocol": "https:", + "username": "", + "password": "", + "host": "localhost", + "hostname": "localhost", + "port": "", + "pathname": "/", + "search": "", + "hash": "#%F0%9F%94%A5" + }, + "# resolving a fragment against any scheme succeeds", + { + "input": "#", + "base": "test:test", + "href": "test:test#", + "origin": "null", + "protocol": "test:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "test", + "search": "", + "hash": "" + }, + { + "input": "#x", + "base": "mailto:x@x.com", + "href": "mailto:x@x.com#x", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "x@x.com", + "search": "", + "hash": "#x" + }, + { + "input": "#x", + "base": "data:,", + "href": "data:,#x", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": ",", + "search": "", + "hash": "#x" + }, + { + "input": "#x", + "base": "about:blank", + "href": "about:blank#x", + "origin": "null", + "protocol": "about:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "blank", + "search": "", + "hash": "#x" + }, + { + "input": "#x:y", + "base": "about:blank", + "href": "about:blank#x:y", + "origin": "null", + "protocol": "about:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "blank", + "search": "", + "hash": "#x:y" + }, + { + "input": "#", + "base": "test:test?test", + "href": "test:test?test#", + "origin": "null", + "protocol": "test:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "test", + "search": "?test", + "hash": "" + }, + "# multiple @ in authority state", + { + "input": "https://@test@test@example:800/", + "base": "http://doesnotmatter/", + "href": "https://%40test%40test@example:800/", + "origin": "https://example:800", + "protocol": "https:", + "username": "%40test%40test", + "password": "", + "host": "example:800", + "hostname": "example", + "port": "800", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://@@@example", + "base": "http://doesnotmatter/", + "href": "https://%40%40@example/", + "origin": "https://example", + "protocol": "https:", + "username": "%40%40", + "password": "", + "host": "example", + "hostname": "example", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "non-az-09 characters", + { + "input": "http://`{}:`{}@h/`{}?`{}", + "base": "http://doesnotmatter/", + "href": "http://%60%7B%7D:%60%7B%7D@h/%60%7B%7D?`{}", + "origin": "http://h", + "protocol": "http:", + "username": "%60%7B%7D", + "password": "%60%7B%7D", + "host": "h", + "hostname": "h", + "port": "", + "pathname": "/%60%7B%7D", + "search": "?`{}", + "hash": "" + }, + "byte is ' and url is special", + { + "input": "http://host/?'", + "base": null, + "href": "http://host/?%27", + "origin": "http://host", + "protocol": "http:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/", + "search": "?%27", + "hash": "" + }, + { + "input": "notspecial://host/?'", + "base": null, + "href": "notspecial://host/?'", + "origin": "null", + "protocol": "notspecial:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/", + "search": "?'", + "hash": "" + }, + "# Credentials in base", + { + "input": "/some/path", + "base": "http://user@example.org/smth", + "href": "http://user@example.org/some/path", + "origin": "http://example.org", + "protocol": "http:", + "username": "user", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/some/path", + "search": "", + "hash": "" + }, + { + "input": "", + "base": "http://user:pass@example.org:21/smth", + "href": "http://user:pass@example.org:21/smth", + "origin": "http://example.org:21", + "protocol": "http:", + "username": "user", + "password": "pass", + "host": "example.org:21", + "hostname": "example.org", + "port": "21", + "pathname": "/smth", + "search": "", + "hash": "" + }, + { + "input": "/some/path", + "base": "http://user:pass@example.org:21/smth", + "href": "http://user:pass@example.org:21/some/path", + "origin": "http://example.org:21", + "protocol": "http:", + "username": "user", + "password": "pass", + "host": "example.org:21", + "hostname": "example.org", + "port": "21", + "pathname": "/some/path", + "search": "", + "hash": "" + }, + "# a set of tests designed by zcorpan for relative URLs with unknown schemes", + { + "input": "i", + "base": "sc:sd", + "failure": true + }, + { + "input": "i", + "base": "sc:sd/sd", + "failure": true + }, + { + "input": "i", + "base": "sc:/pa/pa", + "href": "sc:/pa/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pa/i", + "search": "", + "hash": "" + }, + { + "input": "i", + "base": "sc://ho/pa", + "href": "sc://ho/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "ho", + "hostname": "ho", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "i", + "base": "sc:///pa/pa", + "href": "sc:///pa/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pa/i", + "search": "", + "hash": "" + }, + { + "input": "../i", + "base": "sc:sd", + "failure": true + }, + { + "input": "../i", + "base": "sc:sd/sd", + "failure": true + }, + { + "input": "../i", + "base": "sc:/pa/pa", + "href": "sc:/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "../i", + "base": "sc://ho/pa", + "href": "sc://ho/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "ho", + "hostname": "ho", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "../i", + "base": "sc:///pa/pa", + "href": "sc:///i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "/i", + "base": "sc:sd", + "failure": true + }, + { + "input": "/i", + "base": "sc:sd/sd", + "failure": true + }, + { + "input": "/i", + "base": "sc:/pa/pa", + "href": "sc:/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "/i", + "base": "sc://ho/pa", + "href": "sc://ho/i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "ho", + "hostname": "ho", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "/i", + "base": "sc:///pa/pa", + "href": "sc:///i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/i", + "search": "", + "hash": "" + }, + { + "input": "?i", + "base": "sc:sd", + "failure": true + }, + { + "input": "?i", + "base": "sc:sd/sd", + "failure": true + }, + { + "input": "?i", + "base": "sc:/pa/pa", + "href": "sc:/pa/pa?i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pa/pa", + "search": "?i", + "hash": "" + }, + { + "input": "?i", + "base": "sc://ho/pa", + "href": "sc://ho/pa?i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "ho", + "hostname": "ho", + "port": "", + "pathname": "/pa", + "search": "?i", + "hash": "" + }, + { + "input": "?i", + "base": "sc:///pa/pa", + "href": "sc:///pa/pa?i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pa/pa", + "search": "?i", + "hash": "" + }, + { + "input": "#i", + "base": "sc:sd", + "href": "sc:sd#i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "sd", + "search": "", + "hash": "#i" + }, + { + "input": "#i", + "base": "sc:sd/sd", + "href": "sc:sd/sd#i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "sd/sd", + "search": "", + "hash": "#i" + }, + { + "input": "#i", + "base": "sc:/pa/pa", + "href": "sc:/pa/pa#i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pa/pa", + "search": "", + "hash": "#i" + }, + { + "input": "#i", + "base": "sc://ho/pa", + "href": "sc://ho/pa#i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "ho", + "hostname": "ho", + "port": "", + "pathname": "/pa", + "search": "", + "hash": "#i" + }, + { + "input": "#i", + "base": "sc:///pa/pa", + "href": "sc:///pa/pa#i", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pa/pa", + "search": "", + "hash": "#i" + }, + "# make sure that relative URL logic works on known typically non-relative schemes too", + { + "input": "about:/../", + "base": null, + "href": "about:/", + "origin": "null", + "protocol": "about:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "data:/../", + "base": null, + "href": "data:/", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "javascript:/../", + "base": null, + "href": "javascript:/", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "mailto:/../", + "base": null, + "href": "mailto:/", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# unknown schemes and their hosts", + { + "input": "sc://ñ.test/", + "base": null, + "href": "sc://%C3%B1.test/", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1.test", + "hostname": "%C3%B1.test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "sc://%/", + "base": null, + "href": "sc://%/", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%", + "hostname": "%", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "sc://@/", + "base": null, + "failure": true + }, + { + "input": "sc://te@s:t@/", + "base": null, + "failure": true + }, + { + "input": "sc://:/", + "base": null, + "failure": true + }, + { + "input": "sc://:12/", + "base": null, + "failure": true + }, + { + "input": "x", + "base": "sc://ñ", + "href": "sc://%C3%B1/x", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1", + "hostname": "%C3%B1", + "port": "", + "pathname": "/x", + "search": "", + "hash": "" + }, + "# unknown schemes and backslashes", + { + "input": "sc:\\../", + "base": null, + "href": "sc:\\../", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "\\../", + "search": "", + "hash": "" + }, + "# unknown scheme with path looking like a password", + { + "input": "sc::a@example.net", + "base": null, + "href": "sc::a@example.net", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": ":a@example.net", + "search": "", + "hash": "" + }, + "# unknown scheme with bogus percent-encoding", + { + "input": "wow:%NBD", + "base": null, + "href": "wow:%NBD", + "origin": "null", + "protocol": "wow:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "%NBD", + "search": "", + "hash": "" + }, + { + "input": "wow:%1G", + "base": null, + "href": "wow:%1G", + "origin": "null", + "protocol": "wow:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "%1G", + "search": "", + "hash": "" + }, + "# unknown scheme with non-URL characters", + { + "input": "wow:\uFFFF", + "base": null, + "href": "wow:%EF%BF%BF", + "origin": "null", + "protocol": "wow:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "%EF%BF%BF", + "search": "", + "hash": "" + }, + "Forbidden host code points", + { + "input": "sc://a\u0000b/", + "base": null, + "failure": true + }, + { + "input": "sc://a b/", + "base": null, + "failure": true + }, + { + "input": "sc://ab", + "base": null, + "failure": true + }, + { + "input": "sc://a[b/", + "base": null, + "failure": true + }, + { + "input": "sc://a\\b/", + "base": null, + "failure": true + }, + { + "input": "sc://a]b/", + "base": null, + "failure": true + }, + { + "input": "sc://a^b", + "base": null, + "failure": true + }, + { + "input": "sc://a|b/", + "base": null, + "failure": true + }, + "Forbidden host codepoints: tabs and newlines are removed during preprocessing", + { + "input": "foo://ho\u0009st/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href":"foo://host/", + "password": "", + "pathname": "/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "" + }, + { + "input": "foo://ho\u000Ast/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href":"foo://host/", + "password": "", + "pathname": "/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "" + }, + { + "input": "foo://ho\u000Dst/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href":"foo://host/", + "password": "", + "pathname": "/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "" + }, + "Forbidden domain code-points", + { + "input": "http://a\u0000b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0001b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0002b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0003b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0004b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0005b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0006b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0007b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0008b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u000Bb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u000Cb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u000Eb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u000Fb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0010b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0011b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0012b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0013b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0014b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0015b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0016b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0017b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0018b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u0019b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u001Ab/", + "base": null, + "failure": true + }, + { + "input": "http://a\u001Bb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u001Cb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u001Db/", + "base": null, + "failure": true + }, + { + "input": "http://a\u001Eb/", + "base": null, + "failure": true + }, + { + "input": "http://a\u001Fb/", + "base": null, + "failure": true + }, + { + "input": "http://a b/", + "base": null, + "failure": true + }, + { + "input": "http://a%b/", + "base": null, + "failure": true + }, + { + "input": "http://ab", + "base": null, + "failure": true + }, + { + "input": "http://a[b/", + "base": null, + "failure": true + }, + { + "input": "http://a]b/", + "base": null, + "failure": true + }, + { + "input": "http://a^b", + "base": null, + "failure": true + }, + { + "input": "http://a|b/", + "base": null, + "failure": true + }, + { + "input": "http://a\u007Fb/", + "base": null, + "failure": true + }, + "Forbidden domain codepoints: tabs and newlines are removed during preprocessing", + { + "input": "http://ho\u0009st/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href":"http://host/", + "password": "", + "pathname": "/", + "port":"", + "protocol": "http:", + "search": "", + "username": "" + }, + { + "input": "http://ho\u000Ast/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href":"http://host/", + "password": "", + "pathname": "/", + "port":"", + "protocol": "http:", + "search": "", + "username": "" + }, + { + "input": "http://ho\u000Dst/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href":"http://host/", + "password": "", + "pathname": "/", + "port":"", + "protocol": "http:", + "search": "", + "username": "" + }, + "Encoded forbidden domain codepoints in special URLs", + { + "input": "http://ho%00st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%01st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%02st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%03st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%04st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%05st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%06st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%07st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%08st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%09st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%0Ast/", + "base": null, + "failure": true + }, + { + "input": "http://ho%0Bst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%0Cst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%0Dst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%0Est/", + "base": null, + "failure": true + }, + { + "input": "http://ho%0Fst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%10st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%11st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%12st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%13st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%14st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%15st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%16st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%17st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%18st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%19st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%1Ast/", + "base": null, + "failure": true + }, + { + "input": "http://ho%1Bst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%1Cst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%1Dst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%1Est/", + "base": null, + "failure": true + }, + { + "input": "http://ho%1Fst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%20st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%23st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%25st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%2Fst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%3Ast/", + "base": null, + "failure": true + }, + { + "input": "http://ho%3Cst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%3Est/", + "base": null, + "failure": true + }, + { + "input": "http://ho%3Fst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%40st/", + "base": null, + "failure": true + }, + { + "input": "http://ho%5Bst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%5Cst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%5Dst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%7Cst/", + "base": null, + "failure": true + }, + { + "input": "http://ho%7Fst/", + "base": null, + "failure": true + }, + "Allowed host/domain code points", + { + "input": "http://!\"$&'()*+,-.;=_`{}~/", + "base": null, + "href": "http://!\"$&'()*+,-.;=_`{}~/", + "origin": "http://!\"$&'()*+,-.;=_`{}~", + "protocol": "http:", + "username": "", + "password": "", + "host": "!\"$&'()*+,-.;=_`{}~", + "hostname": "!\"$&'()*+,-.;=_`{}~", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "sc://\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u000B\u000C\u000E\u000F\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001A\u001B\u001C\u001D\u001E\u001F\u007F!\"$%&'()*+,-.;=_`{}~/", + "base": null, + "href": "sc://%01%02%03%04%05%06%07%08%0B%0C%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%7F!\"$%&'()*+,-.;=_`{}~/", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%01%02%03%04%05%06%07%08%0B%0C%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%7F!\"$%&'()*+,-.;=_`{}~", + "hostname": "%01%02%03%04%05%06%07%08%0B%0C%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%7F!\"$%&'()*+,-.;=_`{}~", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# Hosts and percent-encoding", + { + "input": "ftp://example.com%80/", + "base": null, + "failure": true + }, + { + "input": "ftp://example.com%A0/", + "base": null, + "failure": true + }, + { + "input": "https://example.com%80/", + "base": null, + "failure": true + }, + { + "input": "https://example.com%A0/", + "base": null, + "failure": true + }, + { + "input": "ftp://%e2%98%83", + "base": null, + "href": "ftp://xn--n3h/", + "origin": "ftp://xn--n3h", + "protocol": "ftp:", + "username": "", + "password": "", + "host": "xn--n3h", + "hostname": "xn--n3h", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://%e2%98%83", + "base": null, + "href": "https://xn--n3h/", + "origin": "https://xn--n3h", + "protocol": "https:", + "username": "", + "password": "", + "host": "xn--n3h", + "hostname": "xn--n3h", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# tests from jsdom/whatwg-url designed for code coverage", + { + "input": "http://127.0.0.1:10100/relative_import.html", + "base": null, + "href": "http://127.0.0.1:10100/relative_import.html", + "origin": "http://127.0.0.1:10100", + "protocol": "http:", + "username": "", + "password": "", + "host": "127.0.0.1:10100", + "hostname": "127.0.0.1", + "port": "10100", + "pathname": "/relative_import.html", + "search": "", + "hash": "" + }, + { + "input": "http://facebook.com/?foo=%7B%22abc%22", + "base": null, + "href": "http://facebook.com/?foo=%7B%22abc%22", + "origin": "http://facebook.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "facebook.com", + "hostname": "facebook.com", + "port": "", + "pathname": "/", + "search": "?foo=%7B%22abc%22", + "hash": "" + }, + { + "input": "https://localhost:3000/jqueryui@1.2.3", + "base": null, + "href": "https://localhost:3000/jqueryui@1.2.3", + "origin": "https://localhost:3000", + "protocol": "https:", + "username": "", + "password": "", + "host": "localhost:3000", + "hostname": "localhost", + "port": "3000", + "pathname": "/jqueryui@1.2.3", + "search": "", + "hash": "" + }, + "# tab/LF/CR", + { + "input": "h\tt\nt\rp://h\to\ns\rt:9\t0\n0\r0/p\ta\nt\rh?q\tu\ne\rry#f\tr\na\rg", + "base": null, + "href": "http://host:9000/path?query#frag", + "origin": "http://host:9000", + "protocol": "http:", + "username": "", + "password": "", + "host": "host:9000", + "hostname": "host", + "port": "9000", + "pathname": "/path", + "search": "?query", + "hash": "#frag" + }, + "# Stringification of URL.searchParams", + { + "input": "?a=b&c=d", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar?a=b&c=d", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "?a=b&c=d", + "searchParams": "a=b&c=d", + "hash": "" + }, + { + "input": "??a=b&c=d", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar??a=b&c=d", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "??a=b&c=d", + "searchParams": "%3Fa=b&c=d", + "hash": "" + }, + "# Scheme only", + { + "input": "http:", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/bar", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/bar", + "search": "", + "searchParams": "", + "hash": "" + }, + { + "input": "http:", + "base": "https://example.org/foo/bar", + "failure": true + }, + { + "input": "sc:", + "base": "https://example.org/foo/bar", + "href": "sc:", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "", + "search": "", + "searchParams": "", + "hash": "" + }, + "# Percent encoding of fragments", + { + "input": "http://foo.bar/baz?qux#foo\bbar", + "base": null, + "href": "http://foo.bar/baz?qux#foo%08bar", + "origin": "http://foo.bar", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo.bar", + "hostname": "foo.bar", + "port": "", + "pathname": "/baz", + "search": "?qux", + "searchParams": "qux=", + "hash": "#foo%08bar" + }, + { + "input": "http://foo.bar/baz?qux#foo\"bar", + "base": null, + "href": "http://foo.bar/baz?qux#foo%22bar", + "origin": "http://foo.bar", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo.bar", + "hostname": "foo.bar", + "port": "", + "pathname": "/baz", + "search": "?qux", + "searchParams": "qux=", + "hash": "#foo%22bar" + }, + { + "input": "http://foo.bar/baz?qux#foobar", + "base": null, + "href": "http://foo.bar/baz?qux#foo%3Ebar", + "origin": "http://foo.bar", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo.bar", + "hostname": "foo.bar", + "port": "", + "pathname": "/baz", + "search": "?qux", + "searchParams": "qux=", + "hash": "#foo%3Ebar" + }, + { + "input": "http://foo.bar/baz?qux#foo`bar", + "base": null, + "href": "http://foo.bar/baz?qux#foo%60bar", + "origin": "http://foo.bar", + "protocol": "http:", + "username": "", + "password": "", + "host": "foo.bar", + "hostname": "foo.bar", + "port": "", + "pathname": "/baz", + "search": "?qux", + "searchParams": "qux=", + "hash": "#foo%60bar" + }, + "# IPv4 parsing (via https://github.com/nodejs/node/pull/10317)", + { + "input": "http://1.2.3.4/", + "base": "http://other.com/", + "href": "http://1.2.3.4/", + "origin": "http://1.2.3.4", + "protocol": "http:", + "username": "", + "password": "", + "host": "1.2.3.4", + "hostname": "1.2.3.4", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://1.2.3.4./", + "base": "http://other.com/", + "href": "http://1.2.3.4/", + "origin": "http://1.2.3.4", + "protocol": "http:", + "username": "", + "password": "", + "host": "1.2.3.4", + "hostname": "1.2.3.4", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://192.168.257", + "base": "http://other.com/", + "href": "http://192.168.1.1/", + "origin": "http://192.168.1.1", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.1.1", + "hostname": "192.168.1.1", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://192.168.257.", + "base": "http://other.com/", + "href": "http://192.168.1.1/", + "origin": "http://192.168.1.1", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.1.1", + "hostname": "192.168.1.1", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://192.168.257.com", + "base": "http://other.com/", + "href": "http://192.168.257.com/", + "origin": "http://192.168.257.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "192.168.257.com", + "hostname": "192.168.257.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://256", + "base": "http://other.com/", + "href": "http://0.0.1.0/", + "origin": "http://0.0.1.0", + "protocol": "http:", + "username": "", + "password": "", + "host": "0.0.1.0", + "hostname": "0.0.1.0", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://256.com", + "base": "http://other.com/", + "href": "http://256.com/", + "origin": "http://256.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "256.com", + "hostname": "256.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://999999999", + "base": "http://other.com/", + "href": "http://59.154.201.255/", + "origin": "http://59.154.201.255", + "protocol": "http:", + "username": "", + "password": "", + "host": "59.154.201.255", + "hostname": "59.154.201.255", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://999999999.", + "base": "http://other.com/", + "href": "http://59.154.201.255/", + "origin": "http://59.154.201.255", + "protocol": "http:", + "username": "", + "password": "", + "host": "59.154.201.255", + "hostname": "59.154.201.255", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://999999999.com", + "base": "http://other.com/", + "href": "http://999999999.com/", + "origin": "http://999999999.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "999999999.com", + "hostname": "999999999.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://10000000000", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://10000000000.com", + "base": "http://other.com/", + "href": "http://10000000000.com/", + "origin": "http://10000000000.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "10000000000.com", + "hostname": "10000000000.com", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://4294967295", + "base": "http://other.com/", + "href": "http://255.255.255.255/", + "origin": "http://255.255.255.255", + "protocol": "http:", + "username": "", + "password": "", + "host": "255.255.255.255", + "hostname": "255.255.255.255", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://4294967296", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://18446744073709551616", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://18446744075840258049", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://0xffffffff", + "base": "http://other.com/", + "href": "http://255.255.255.255/", + "origin": "http://255.255.255.255", + "protocol": "http:", + "username": "", + "password": "", + "host": "255.255.255.255", + "hostname": "255.255.255.255", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://0xffffffff1", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://256.256.256.256", + "base": "http://other.com/", + "failure": true + }, + { + "input": "https://0x.0x.0", + "base": null, + "href": "https://0.0.0.0/", + "origin": "https://0.0.0.0", + "protocol": "https:", + "username": "", + "password": "", + "host": "0.0.0.0", + "hostname": "0.0.0.0", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://0x.0x.0x.0x", + "base": null, + "href": "https://0.0.0.0/", + "origin": "https://0.0.0.0", + "protocol": "https:", + "username": "", + "password": "", + "host": "0.0.0.0", + "hostname": "0.0.0.0", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://00.00.00.00", + "base": null, + "href": "https://0.0.0.0/", + "origin": "https://0.0.0.0", + "protocol": "https:", + "username": "", + "password": "", + "host": "0.0.0.0", + "hostname": "0.0.0.0", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "https://0000000000000000000000000000000000000000177.0.0.1", + "base": null, + "href": "https://127.0.0.1/", + "origin": "https://127.0.0.1", + "protocol": "https:", + "username": "", + "password": "", + "host": "127.0.0.1", + "hostname": "127.0.0.1", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "More IPv4 parsing (via https://github.com/jsdom/whatwg-url/issues/92)", + { + "input": "https://0x100000000/test", + "base": null, + "failure": true + }, + { + "input": "https://256.0.0.1/test", + "base": null, + "failure": true + }, + "# file URLs containing percent-encoded Windows drive letters (shouldn't work)", + { + "input": "file:///C%3A/", + "base": null, + "href": "file:///C%3A/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C%3A/", + "search": "", + "hash": "" + }, + { + "input": "file:///C%7C/", + "base": null, + "href": "file:///C%7C/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C%7C/", + "search": "", + "hash": "" + }, + { + "input": "file://%43%3A", + "base": null, + "failure": true + }, + { + "input": "file://%43%7C", + "base": null, + "failure": true + }, + { + "input": "file://%43|", + "base": null, + "failure": true + }, + { + "input": "file://C%7C", + "base": null, + "failure": true + }, + { + "input": "file://%43%7C/", + "base": null, + "failure": true + }, + { + "input": "https://%43%7C/", + "base": null, + "failure": true + }, + { + "input": "asdf://%43|/", + "base": null, + "failure": true + }, + { + "input": "asdf://%43%7C/", + "base": null, + "href": "asdf://%43%7C/", + "origin": "null", + "protocol": "asdf:", + "username": "", + "password": "", + "host": "%43%7C", + "hostname": "%43%7C", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# file URLs relative to other file URLs (via https://github.com/jsdom/whatwg-url/pull/60)", + { + "input": "pix/submit.gif", + "base": "file:///C:/Users/Domenic/Dropbox/GitHub/tmpvar/jsdom/test/level2/html/files/anchor.html", + "href": "file:///C:/Users/Domenic/Dropbox/GitHub/tmpvar/jsdom/test/level2/html/files/pix/submit.gif", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/Users/Domenic/Dropbox/GitHub/tmpvar/jsdom/test/level2/html/files/pix/submit.gif", + "search": "", + "hash": "" + }, + { + "input": "..", + "base": "file:///C:/", + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "..", + "base": "file:///", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# More file URL tests by zcorpan and annevk", + { + "input": "/", + "base": "file:///C:/a/b", + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "/", + "base": "file://h/C:/a/b", + "href": "file://h/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "h", + "hostname": "h", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "/", + "base": "file://h/a/b", + "href": "file://h/", + "protocol": "file:", + "username": "", + "password": "", + "host": "h", + "hostname": "h", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "//d:", + "base": "file:///C:/a/b", + "href": "file:///d:", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/d:", + "search": "", + "hash": "" + }, + { + "input": "//d:/..", + "base": "file:///C:/a/b", + "href": "file:///d:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/d:/", + "search": "", + "hash": "" + }, + { + "input": "..", + "base": "file:///ab:/", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "..", + "base": "file:///1:/", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "", + "base": "file:///test?test#test", + "href": "file:///test?test", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?test", + "hash": "" + }, + { + "input": "file:", + "base": "file:///test?test#test", + "href": "file:///test?test", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?test", + "hash": "" + }, + { + "input": "?x", + "base": "file:///test?test#test", + "href": "file:///test?x", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?x", + "hash": "" + }, + { + "input": "file:?x", + "base": "file:///test?test#test", + "href": "file:///test?x", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?x", + "hash": "" + }, + { + "input": "#x", + "base": "file:///test?test#test", + "href": "file:///test?test#x", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?test", + "hash": "#x" + }, + { + "input": "file:#x", + "base": "file:///test?test#test", + "href": "file:///test?test#x", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?test", + "hash": "#x" + }, + "# File URLs and many (back)slashes", + { + "input": "file:\\\\//", + "base": null, + "href": "file:////", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "file:\\\\\\\\", + "base": null, + "href": "file:////", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "file:\\\\\\\\?fox", + "base": null, + "href": "file:////?fox", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "?fox", + "hash": "" + }, + { + "input": "file:\\\\\\\\#guppy", + "base": null, + "href": "file:////#guppy", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "#guppy" + }, + { + "input": "file://spider///", + "base": null, + "href": "file://spider///", + "protocol": "file:", + "username": "", + "password": "", + "host": "spider", + "hostname": "spider", + "port": "", + "pathname": "///", + "search": "", + "hash": "" + }, + { + "input": "file:\\\\localhost//", + "base": null, + "href": "file:////", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "file:///localhost//cat", + "base": null, + "href": "file:///localhost//cat", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/localhost//cat", + "search": "", + "hash": "" + }, + { + "input": "file://\\/localhost//cat", + "base": null, + "href": "file:////localhost//cat", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//localhost//cat", + "search": "", + "hash": "" + }, + { + "input": "file://localhost//a//../..//", + "base": null, + "href": "file://///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "///", + "search": "", + "hash": "" + }, + { + "input": "/////mouse", + "base": "file:///elephant", + "href": "file://///mouse", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "///mouse", + "search": "", + "hash": "" + }, + { + "input": "\\//pig", + "base": "file://lion/", + "href": "file:///pig", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/pig", + "search": "", + "hash": "" + }, + { + "input": "\\/localhost//pig", + "base": "file://lion/", + "href": "file:////pig", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//pig", + "search": "", + "hash": "" + }, + { + "input": "//localhost//pig", + "base": "file://lion/", + "href": "file:////pig", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//pig", + "search": "", + "hash": "" + }, + { + "input": "/..//localhost//pig", + "base": "file://lion/", + "href": "file://lion//localhost//pig", + "protocol": "file:", + "username": "", + "password": "", + "host": "lion", + "hostname": "lion", + "port": "", + "pathname": "//localhost//pig", + "search": "", + "hash": "" + }, + { + "input": "file://", + "base": "file://ape/", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# File URLs with non-empty hosts", + { + "input": "/rooibos", + "base": "file://tea/", + "href": "file://tea/rooibos", + "protocol": "file:", + "username": "", + "password": "", + "host": "tea", + "hostname": "tea", + "port": "", + "pathname": "/rooibos", + "search": "", + "hash": "" + }, + { + "input": "/?chai", + "base": "file://tea/", + "href": "file://tea/?chai", + "protocol": "file:", + "username": "", + "password": "", + "host": "tea", + "hostname": "tea", + "port": "", + "pathname": "/", + "search": "?chai", + "hash": "" + }, + "# Windows drive letter handling with the 'file:' base URL", + { + "input": "C|", + "base": "file://host/dir/file", + "href": "file://host/C:", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:", + "search": "", + "hash": "" + }, + { + "input": "C|", + "base": "file://host/D:/dir1/dir2/file", + "href": "file://host/C:", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:", + "search": "", + "hash": "" + }, + { + "input": "C|#", + "base": "file://host/dir/file", + "href": "file://host/C:#", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:", + "search": "", + "hash": "" + }, + { + "input": "C|?", + "base": "file://host/dir/file", + "href": "file://host/C:?", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:", + "search": "", + "hash": "" + }, + { + "input": "C|/", + "base": "file://host/dir/file", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "C|\n/", + "base": "file://host/dir/file", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "C|\\", + "base": "file://host/dir/file", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "C", + "base": "file://host/dir/file", + "href": "file://host/dir/C", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/dir/C", + "search": "", + "hash": "" + }, + { + "input": "C|a", + "base": "file://host/dir/file", + "href": "file://host/dir/C|a", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/dir/C|a", + "search": "", + "hash": "" + }, + "# Windows drive letter quirk in the file slash state", + { + "input": "/c:/foo/bar", + "base": "file:///c:/baz/qux", + "href": "file:///c:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/c:/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "/c|/foo/bar", + "base": "file:///c:/baz/qux", + "href": "file:///c:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/c:/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "file:\\c:\\foo\\bar", + "base": "file:///c:/baz/qux", + "href": "file:///c:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/c:/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "/c:/foo/bar", + "base": "file://host/path", + "href": "file://host/c:/foo/bar", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/c:/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "..", + "base": "abc://x/y/z/C:/", + "href": "abc://x/y/z/", + "protocol": "abc:", + "username": "", + "password": "", + "hostname": "x", + "port": "", + "host": "x", + "pathname": "/y/z/", + "search": "", + "hash": "" + }, + { + "input": "..", + "base": "file://x/C:/", + "href": "file://x/C:/", + "protocol": "file:", + "username": "", + "password": "", + "hostname": "x", + "port": "", + "host": "x", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + "# Do not drop the host in the presence of a drive letter", + { + "input": "file://example.net/C:/", + "base": null, + "href": "file://example.net/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "example.net", + "hostname": "example.net", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file://1.2.3.4/C:/", + "base": null, + "href": "file://1.2.3.4/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "1.2.3.4", + "hostname": "1.2.3.4", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file://[1::8]/C:/", + "base": null, + "href": "file://[1::8]/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "[1::8]", + "hostname": "[1::8]", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + "# Copy the host from the base URL in the following cases", + { + "input": "C|/", + "base": "file://host/", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "/C:/", + "base": "file://host/", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file:C:/", + "base": "file://host/", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file:/C:/", + "base": "file://host/", + "href": "file://host/C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + "# Copy the empty host from the input in the following cases", + { + "input": "//C:/", + "base": "file://host/", + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file://C:/", + "base": "file://host/", + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "///C:/", + "base": "file://host/", + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file:///C:/", + "base": "file://host/", + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + "# Windows drive letter quirk (no host)", + { + "input": "file:/C|/", + "base": null, + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + { + "input": "file://C|/", + "base": null, + "href": "file:///C:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/C:/", + "search": "", + "hash": "" + }, + "# file URLs without base URL by Rimas Misevičius", + { + "input": "file:", + "base": null, + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "file:?q=v", + "base": null, + "href": "file:///?q=v", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "?q=v", + "hash": "" + }, + { + "input": "file:#frag", + "base": null, + "href": "file:///#frag", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "#frag" + }, + "# file: drive letter cases from https://crbug.com/1078698", + { + "input": "file:///Y:", + "base": null, + "href": "file:///Y:", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/Y:", + "search": "", + "hash": "" + }, + { + "input": "file:///Y:/", + "base": null, + "href": "file:///Y:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/Y:/", + "search": "", + "hash": "" + }, + { + "input": "file:///./Y", + "base": null, + "href": "file:///Y", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/Y", + "search": "", + "hash": "" + }, + { + "input": "file:///./Y:", + "base": null, + "href": "file:///Y:", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/Y:", + "search": "", + "hash": "" + }, + { + "input": "\\\\\\.\\Y:", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + "# file: drive letter cases from https://crbug.com/1078698 but lowercased", + { + "input": "file:///y:", + "base": null, + "href": "file:///y:", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/y:", + "search": "", + "hash": "" + }, + { + "input": "file:///y:/", + "base": null, + "href": "file:///y:/", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/y:/", + "search": "", + "hash": "" + }, + { + "input": "file:///./y", + "base": null, + "href": "file:///y", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/y", + "search": "", + "hash": "" + }, + { + "input": "file:///./y:", + "base": null, + "href": "file:///y:", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/y:", + "search": "", + "hash": "" + }, + { + "input": "\\\\\\.\\y:", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + "# Additional file URL tests for (https://github.com/whatwg/url/issues/405)", + { + "input": "file://localhost//a//../..//foo", + "base": null, + "href": "file://///foo", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "///foo", + "search": "", + "hash": "" + }, + { + "input": "file://localhost////foo", + "base": null, + "href": "file://////foo", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "////foo", + "search": "", + "hash": "" + }, + { + "input": "file:////foo", + "base": null, + "href": "file:////foo", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//foo", + "search": "", + "hash": "" + }, + { + "input": "file:///one/two", + "base": "file:///", + "href": "file:///one/two", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/one/two", + "search": "", + "hash": "" + }, + { + "input": "file:////one/two", + "base": "file:///", + "href": "file:////one/two", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//one/two", + "search": "", + "hash": "" + }, + { + "input": "//one/two", + "base": "file:///", + "href": "file://one/two", + "protocol": "file:", + "username": "", + "password": "", + "host": "one", + "hostname": "one", + "port": "", + "pathname": "/two", + "search": "", + "hash": "" + }, + { + "input": "///one/two", + "base": "file:///", + "href": "file:///one/two", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/one/two", + "search": "", + "hash": "" + }, + { + "input": "////one/two", + "base": "file:///", + "href": "file:////one/two", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//one/two", + "search": "", + "hash": "" + }, + { + "input": "file:///.//", + "base": "file:////", + "href": "file:////", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + "File URL tests for https://github.com/whatwg/url/issues/549", + { + "input": "file:.//p", + "base": null, + "href": "file:////p", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//p", + "search": "", + "hash": "" + }, + { + "input": "file:/.//p", + "base": null, + "href": "file:////p", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//p", + "search": "", + "hash": "" + }, + "# IPv6 tests", + "IPv4 pieces embedded in IPv6 addresses must not have leading zeroes", + { + "input": "https://[0:1:2:3:4:5:192.0.02.1]/", + "base": null, + "failure": true + }, + "An embedded IPv4 address must end the IPv6 address", + { + "input": "https://[192.0.2.1::]/", + "base": null, + "failure": true + }, + { + "input": "http://[1:0::]", + "base": "http://example.net/", + "href": "http://[1::]/", + "origin": "http://[1::]", + "protocol": "http:", + "username": "", + "password": "", + "host": "[1::]", + "hostname": "[1::]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://[0:1:2:3:4:5:6:7:8]", + "base": "http://example.net/", + "failure": true + }, + { + "input": "https://[0::0::0]", + "base": null, + "failure": true + }, + { + "input": "https://[0:.0]", + "base": null, + "failure": true + }, + { + "input": "https://[0:0:]", + "base": null, + "failure": true + }, + { + "input": "https://[0:1:2:3:4:5:6:7.0.0.0.1]", + "base": null, + "failure": true + }, + { + "input": "https://[0:1.00.0.0.0]", + "base": null, + "failure": true + }, + { + "input": "https://[0:1.290.0.0.0]", + "base": null, + "failure": true + }, + { + "input": "https://[0:1.23.23]", + "base": null, + "failure": true + }, + "# Empty host", + { + "input": "http://?", + "base": null, + "failure": true + }, + { + "input": "http://#", + "base": null, + "failure": true + }, + "Port overflow (2^32 + 81)", + { + "input": "http://f:4294967377/c", + "base": "http://example.org/", + "failure": true + }, + "Port overflow (2^64 + 81)", + { + "input": "http://f:18446744073709551697/c", + "base": "http://example.org/", + "failure": true + }, + "Port overflow (2^128 + 81)", + { + "input": "http://f:340282366920938463463374607431768211537/c", + "base": "http://example.org/", + "failure": true + }, + "# Non-special-URL path tests", + { + "input": "sc://ñ", + "base": null, + "href": "sc://%C3%B1", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1", + "hostname": "%C3%B1", + "port": "", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "sc://ñ?x", + "base": null, + "href": "sc://%C3%B1?x", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1", + "hostname": "%C3%B1", + "port": "", + "pathname": "", + "search": "?x", + "hash": "" + }, + { + "input": "sc://ñ#x", + "base": null, + "href": "sc://%C3%B1#x", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1", + "hostname": "%C3%B1", + "port": "", + "pathname": "", + "search": "", + "hash": "#x" + }, + { + "input": "#x", + "base": "sc://ñ", + "href": "sc://%C3%B1#x", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1", + "hostname": "%C3%B1", + "port": "", + "pathname": "", + "search": "", + "hash": "#x" + }, + { + "input": "?x", + "base": "sc://ñ", + "href": "sc://%C3%B1?x", + "origin": "null", + "protocol": "sc:", + "username": "", + "password": "", + "host": "%C3%B1", + "hostname": "%C3%B1", + "port": "", + "pathname": "", + "search": "?x", + "hash": "" + }, + { + "input": "sc://?", + "base": null, + "href": "sc://?", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "sc://#", + "base": null, + "href": "sc://#", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "///", + "base": "sc://x/", + "href": "sc:///", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "////", + "base": "sc://x/", + "href": "sc:////", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "////x/", + "base": "sc://x/", + "href": "sc:////x/", + "protocol": "sc:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//x/", + "search": "", + "hash": "" + }, + { + "input": "tftp://foobar.com/someconfig;mode=netascii", + "base": null, + "href": "tftp://foobar.com/someconfig;mode=netascii", + "origin": "null", + "protocol": "tftp:", + "username": "", + "password": "", + "host": "foobar.com", + "hostname": "foobar.com", + "port": "", + "pathname": "/someconfig;mode=netascii", + "search": "", + "hash": "" + }, + { + "input": "telnet://user:pass@foobar.com:23/", + "base": null, + "href": "telnet://user:pass@foobar.com:23/", + "origin": "null", + "protocol": "telnet:", + "username": "user", + "password": "pass", + "host": "foobar.com:23", + "hostname": "foobar.com", + "port": "23", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "ut2004://10.10.10.10:7777/Index.ut2", + "base": null, + "href": "ut2004://10.10.10.10:7777/Index.ut2", + "origin": "null", + "protocol": "ut2004:", + "username": "", + "password": "", + "host": "10.10.10.10:7777", + "hostname": "10.10.10.10", + "port": "7777", + "pathname": "/Index.ut2", + "search": "", + "hash": "" + }, + { + "input": "redis://foo:bar@somehost:6379/0?baz=bam&qux=baz", + "base": null, + "href": "redis://foo:bar@somehost:6379/0?baz=bam&qux=baz", + "origin": "null", + "protocol": "redis:", + "username": "foo", + "password": "bar", + "host": "somehost:6379", + "hostname": "somehost", + "port": "6379", + "pathname": "/0", + "search": "?baz=bam&qux=baz", + "hash": "" + }, + { + "input": "rsync://foo@host:911/sup", + "base": null, + "href": "rsync://foo@host:911/sup", + "origin": "null", + "protocol": "rsync:", + "username": "foo", + "password": "", + "host": "host:911", + "hostname": "host", + "port": "911", + "pathname": "/sup", + "search": "", + "hash": "" + }, + { + "input": "git://github.com/foo/bar.git", + "base": null, + "href": "git://github.com/foo/bar.git", + "origin": "null", + "protocol": "git:", + "username": "", + "password": "", + "host": "github.com", + "hostname": "github.com", + "port": "", + "pathname": "/foo/bar.git", + "search": "", + "hash": "" + }, + { + "input": "irc://myserver.com:6999/channel?passwd", + "base": null, + "href": "irc://myserver.com:6999/channel?passwd", + "origin": "null", + "protocol": "irc:", + "username": "", + "password": "", + "host": "myserver.com:6999", + "hostname": "myserver.com", + "port": "6999", + "pathname": "/channel", + "search": "?passwd", + "hash": "" + }, + { + "input": "dns://fw.example.org:9999/foo.bar.org?type=TXT", + "base": null, + "href": "dns://fw.example.org:9999/foo.bar.org?type=TXT", + "origin": "null", + "protocol": "dns:", + "username": "", + "password": "", + "host": "fw.example.org:9999", + "hostname": "fw.example.org", + "port": "9999", + "pathname": "/foo.bar.org", + "search": "?type=TXT", + "hash": "" + }, + { + "input": "ldap://localhost:389/ou=People,o=JNDITutorial", + "base": null, + "href": "ldap://localhost:389/ou=People,o=JNDITutorial", + "origin": "null", + "protocol": "ldap:", + "username": "", + "password": "", + "host": "localhost:389", + "hostname": "localhost", + "port": "389", + "pathname": "/ou=People,o=JNDITutorial", + "search": "", + "hash": "" + }, + { + "input": "git+https://github.com/foo/bar", + "base": null, + "href": "git+https://github.com/foo/bar", + "origin": "null", + "protocol": "git+https:", + "username": "", + "password": "", + "host": "github.com", + "hostname": "github.com", + "port": "", + "pathname": "/foo/bar", + "search": "", + "hash": "" + }, + { + "input": "urn:ietf:rfc:2648", + "base": null, + "href": "urn:ietf:rfc:2648", + "origin": "null", + "protocol": "urn:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "ietf:rfc:2648", + "search": "", + "hash": "" + }, + { + "input": "tag:joe@example.org,2001:foo/bar", + "base": null, + "href": "tag:joe@example.org,2001:foo/bar", + "origin": "null", + "protocol": "tag:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "joe@example.org,2001:foo/bar", + "search": "", + "hash": "" + }, + "Serialize /. in path", + { + "input": "non-spec:/.//", + "base": null, + "href": "non-spec:/.//", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "non-spec:/..//", + "base": null, + "href": "non-spec:/.//", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "non-spec:/a/..//", + "base": null, + "href": "non-spec:/.//", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//", + "search": "", + "hash": "" + }, + { + "input": "non-spec:/.//path", + "base": null, + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "non-spec:/..//path", + "base": null, + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "non-spec:/a/..//path", + "base": null, + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "/.//path", + "base": "non-spec:/p", + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "/..//path", + "base": "non-spec:/p", + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "..//path", + "base": "non-spec:/p", + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "a/..//path", + "base": "non-spec:/p", + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + { + "input": "", + "base": "non-spec:/..//p", + "href": "non-spec:/.//p", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//p", + "search": "", + "hash": "" + }, + { + "input": "path", + "base": "non-spec:/..//p", + "href": "non-spec:/.//path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//path", + "search": "", + "hash": "" + }, + "Do not serialize /. in path", + { + "input": "../path", + "base": "non-spec:/.//p", + "href": "non-spec:/path", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/path", + "search": "", + "hash": "" + }, + "# percent encoded hosts in non-special-URLs", + { + "input": "non-special://%E2%80%A0/", + "base": null, + "href": "non-special://%E2%80%A0/", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "%E2%80%A0", + "hostname": "%E2%80%A0", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "non-special://H%4fSt/path", + "base": null, + "href": "non-special://H%4fSt/path", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "H%4fSt", + "hostname": "H%4fSt", + "port": "", + "pathname": "/path", + "search": "", + "hash": "" + }, + "# IPv6 in non-special-URLs", + { + "input": "non-special://[1:2:0:0:5:0:0:0]/", + "base": null, + "href": "non-special://[1:2:0:0:5::]/", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "[1:2:0:0:5::]", + "hostname": "[1:2:0:0:5::]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "non-special://[1:2:0:0:0:0:0:3]/", + "base": null, + "href": "non-special://[1:2::3]/", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "[1:2::3]", + "hostname": "[1:2::3]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "non-special://[1:2::3]:80/", + "base": null, + "href": "non-special://[1:2::3]:80/", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "[1:2::3]:80", + "hostname": "[1:2::3]", + "port": "80", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "non-special://[:80/", + "base": null, + "failure": true + }, + { + "input": "blob:https://example.com:443/", + "base": null, + "href": "blob:https://example.com:443/", + "origin": "https://example.com", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "https://example.com:443/", + "search": "", + "hash": "" + }, + { + "input": "blob:http://example.org:88/", + "base": null, + "href": "blob:http://example.org:88/", + "origin": "http://example.org:88", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "http://example.org:88/", + "search": "", + "hash": "" + }, + { + "input": "blob:d3958f5c-0777-0845-9dcf-2cb28783acaf", + "base": null, + "href": "blob:d3958f5c-0777-0845-9dcf-2cb28783acaf", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "d3958f5c-0777-0845-9dcf-2cb28783acaf", + "search": "", + "hash": "" + }, + { + "input": "blob:", + "base": null, + "href": "blob:", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "", + "search": "", + "hash": "" + }, + "blob: in blob:", + { + "input": "blob:blob:", + "base": null, + "href": "blob:blob:", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "blob:", + "search": "", + "hash": "" + }, + { + "input": "blob:blob:https://example.org/", + "base": null, + "href": "blob:blob:https://example.org/", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "blob:https://example.org/", + "search": "", + "hash": "" + }, + "Non-http(s): in blob:", + { + "input": "blob:about:blank", + "base": null, + "href": "blob:about:blank", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "about:blank", + "search": "", + "hash": "" + }, + { + "input": "blob:file://host/path", + "base": null, + "href": "blob:file://host/path", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "file://host/path", + "search": "", + "hash": "" + }, + { + "input": "blob:ftp://host/path", + "base": null, + "href": "blob:ftp://host/path", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "ftp://host/path", + "search": "", + "hash": "" + }, + { + "input": "blob:ws://example.org/", + "base": null, + "href": "blob:ws://example.org/", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "ws://example.org/", + "search": "", + "hash": "" + }, + { + "input": "blob:wss://example.org/", + "base": null, + "href": "blob:wss://example.org/", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "wss://example.org/", + "search": "", + "hash": "" + }, + "Percent-encoded http: in blob:", + { + "input": "blob:http%3a//example.org/", + "base": null, + "href": "blob:http%3a//example.org/", + "origin": "null", + "protocol": "blob:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "http%3a//example.org/", + "search": "", + "hash": "" + }, + "Invalid IPv4 radix digits", + { + "input": "http://0x7f.0.0.0x7g", + "base": null, + "href": "http://0x7f.0.0.0x7g/", + "protocol": "http:", + "username": "", + "password": "", + "host": "0x7f.0.0.0x7g", + "hostname": "0x7f.0.0.0x7g", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://0X7F.0.0.0X7G", + "base": null, + "href": "http://0x7f.0.0.0x7g/", + "protocol": "http:", + "username": "", + "password": "", + "host": "0x7f.0.0.0x7g", + "hostname": "0x7f.0.0.0x7g", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Invalid IPv4 portion of IPv6 address", + { + "input": "http://[::127.0.0.0.1]", + "base": null, + "failure": true + }, + "Uncompressed IPv6 addresses with 0", + { + "input": "http://[0:1:0:1:0:1:0:1]", + "base": null, + "href": "http://[0:1:0:1:0:1:0:1]/", + "protocol": "http:", + "username": "", + "password": "", + "host": "[0:1:0:1:0:1:0:1]", + "hostname": "[0:1:0:1:0:1:0:1]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "http://[1:0:1:0:1:0:1:0]", + "base": null, + "href": "http://[1:0:1:0:1:0:1:0]/", + "protocol": "http:", + "username": "", + "password": "", + "host": "[1:0:1:0:1:0:1:0]", + "hostname": "[1:0:1:0:1:0:1:0]", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Percent-encoded query and fragment", + { + "input": "http://example.org/test?\u0022", + "base": null, + "href": "http://example.org/test?%22", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?%22", + "hash": "" + }, + { + "input": "http://example.org/test?\u0023", + "base": null, + "href": "http://example.org/test?#", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "http://example.org/test?\u003C", + "base": null, + "href": "http://example.org/test?%3C", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?%3C", + "hash": "" + }, + { + "input": "http://example.org/test?\u003E", + "base": null, + "href": "http://example.org/test?%3E", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?%3E", + "hash": "" + }, + { + "input": "http://example.org/test?\u2323", + "base": null, + "href": "http://example.org/test?%E2%8C%A3", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?%E2%8C%A3", + "hash": "" + }, + { + "input": "http://example.org/test?%23%23", + "base": null, + "href": "http://example.org/test?%23%23", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?%23%23", + "hash": "" + }, + { + "input": "http://example.org/test?%GH", + "base": null, + "href": "http://example.org/test?%GH", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?%GH", + "hash": "" + }, + { + "input": "http://example.org/test?a#%EF", + "base": null, + "href": "http://example.org/test?a#%EF", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?a", + "hash": "#%EF" + }, + { + "input": "http://example.org/test?a#%GH", + "base": null, + "href": "http://example.org/test?a#%GH", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?a", + "hash": "#%GH" + }, + "URLs that require a non-about:blank base. (Also serve as invalid base tests.)", + { + "input": "a", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "a/", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "a//", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + "Bases that don't fail to parse but fail to be bases", + { + "input": "test-a-colon.html", + "base": "a:", + "failure": true + }, + { + "input": "test-a-colon-b.html", + "base": "a:b", + "failure": true + }, + "Other base URL tests, that must succeed", + { + "input": "test-a-colon-slash.html", + "base": "a:/", + "href": "a:/test-a-colon-slash.html", + "protocol": "a:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test-a-colon-slash.html", + "search": "", + "hash": "" + }, + { + "input": "test-a-colon-slash-slash.html", + "base": "a://", + "href": "a:///test-a-colon-slash-slash.html", + "protocol": "a:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test-a-colon-slash-slash.html", + "search": "", + "hash": "" + }, + { + "input": "test-a-colon-slash-b.html", + "base": "a:/b", + "href": "a:/test-a-colon-slash-b.html", + "protocol": "a:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test-a-colon-slash-b.html", + "search": "", + "hash": "" + }, + { + "input": "test-a-colon-slash-slash-b.html", + "base": "a://b", + "href": "a://b/test-a-colon-slash-slash-b.html", + "protocol": "a:", + "username": "", + "password": "", + "host": "b", + "hostname": "b", + "port": "", + "pathname": "/test-a-colon-slash-slash-b.html", + "search": "", + "hash": "" + }, + "Null code point in fragment", + { + "input": "http://example.org/test?a#b\u0000c", + "base": null, + "href": "http://example.org/test?a#b%00c", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?a", + "hash": "#b%00c" + }, + { + "input": "non-spec://example.org/test?a#b\u0000c", + "base": null, + "href": "non-spec://example.org/test?a#b%00c", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/test", + "search": "?a", + "hash": "#b%00c" + }, + { + "input": "non-spec:/test?a#b\u0000c", + "base": null, + "href": "non-spec:/test?a#b%00c", + "protocol": "non-spec:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "?a", + "hash": "#b%00c" + }, + "First scheme char - not allowed: https://github.com/whatwg/url/issues/464", + { + "input": "10.0.0.7:8080/foo.html", + "base": "file:///some/dir/bar.html", + "href": "file:///some/dir/10.0.0.7:8080/foo.html", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/some/dir/10.0.0.7:8080/foo.html", + "search": "", + "hash": "" + }, + "Subsequent scheme chars - not allowed", + { + "input": "a!@$*=/foo.html", + "base": "file:///some/dir/bar.html", + "href": "file:///some/dir/a!@$*=/foo.html", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/some/dir/a!@$*=/foo.html", + "search": "", + "hash": "" + }, + "First and subsequent scheme chars - allowed", + { + "input": "a1234567890-+.:foo/bar", + "base": "http://example.com/dir/file", + "href": "a1234567890-+.:foo/bar", + "protocol": "a1234567890-+.:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "foo/bar", + "search": "", + "hash": "" + }, + "IDNA ignored code points in file URLs hosts", + { + "input": "file://a\u00ADb/p", + "base": null, + "href": "file://ab/p", + "protocol": "file:", + "username": "", + "password": "", + "host": "ab", + "hostname": "ab", + "port": "", + "pathname": "/p", + "search": "", + "hash": "" + }, + { + "input": "file://a%C2%ADb/p", + "base": null, + "href": "file://ab/p", + "protocol": "file:", + "username": "", + "password": "", + "host": "ab", + "hostname": "ab", + "port": "", + "pathname": "/p", + "search": "", + "hash": "" + }, + "IDNA hostnames which get mapped to 'localhost'", + { + "input": "file://loC𝐀𝐋𝐇𝐨𝐬𝐭/usr/bin", + "base": null, + "href": "file:///usr/bin", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/usr/bin", + "search": "", + "hash": "" + }, + "Empty host after the domain to ASCII", + { + "input": "file://\u00ad/p", + "base": null, + "failure": true + }, + { + "input": "file://%C2%AD/p", + "base": null, + "failure": true + }, + { + "input": "file://xn--/p", + "base": null, + "href": "file://xn--/p", + "protocol": "file:", + "username": "", + "password": "", + "host": "xn--", + "hostname": "xn--", + "port": "", + "pathname": "/p", + "search": "", + "hash": "" + }, + "https://bugzilla.mozilla.org/show_bug.cgi?id=1647058", + { + "input": "#link", + "base": "https://example.org/##link", + "href": "https://example.org/#link", + "protocol": "https:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/", + "search": "", + "hash": "#link" + }, + "UTF-8 percent-encode of C0 control percent-encode set and supersets", + { + "input": "non-special:cannot-be-a-base-url-\u0000\u0001\u001F\u001E\u007E\u007F\u0080", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:cannot-be-a-base-url-%00%01%1F%1E~%7F%C2%80", + "origin": "null", + "password": "", + "pathname": "cannot-be-a-base-url-%00%01%1F%1E~%7F%C2%80", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "non-special:cannot-be-a-base-url-!\"$%&'()*+,-.;<=>@[\\]^_`{|}~@/", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:cannot-be-a-base-url-!\"$%&'()*+,-.;<=>@[\\]^_`{|}~@/", + "origin": "null", + "password": "", + "pathname": "cannot-be-a-base-url-!\"$%&'()*+,-.;<=>@[\\]^_`{|}~@/", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "https://www.example.com/path{\u007Fpath.html?query'\u007F=query#fragment<\u007Ffragment", + "base": null, + "hash": "#fragment%3C%7Ffragment", + "host": "www.example.com", + "hostname": "www.example.com", + "href": "https://www.example.com/path%7B%7Fpath.html?query%27%7F=query#fragment%3C%7Ffragment", + "origin": "https://www.example.com", + "password": "", + "pathname": "/path%7B%7Fpath.html", + "port": "", + "protocol": "https:", + "search": "?query%27%7F=query", + "username": "" + }, + { + "input": "https://user:pass[\u007F@foo/bar", + "base": "http://example.org", + "hash": "", + "host": "foo", + "hostname": "foo", + "href": "https://user:pass%5B%7F@foo/bar", + "origin": "https://foo", + "password": "pass%5B%7F", + "pathname": "/bar", + "port": "", + "protocol": "https:", + "search": "", + "username": "user" + }, + "Tests for the distinct percent-encode sets", + { + "input": "foo:// !\"$%&'()*+,-.;<=>@[\\]^_`{|}~@host/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "foo://%20!%22$%&'()*+,-.%3B%3C%3D%3E%40%5B%5C%5D%5E_%60%7B%7C%7D~@host/", + "origin": "null", + "password": "", + "pathname": "/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "%20!%22$%&'()*+,-.%3B%3C%3D%3E%40%5B%5C%5D%5E_%60%7B%7C%7D~" + }, + { + "input": "wss:// !\"$%&'()*+,-.;<=>@[]^_`{|}~@host/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "wss://%20!%22$%&'()*+,-.%3B%3C%3D%3E%40%5B%5D%5E_%60%7B%7C%7D~@host/", + "origin": "wss://host", + "password": "", + "pathname": "/", + "port":"", + "protocol": "wss:", + "search": "", + "username": "%20!%22$%&'()*+,-.%3B%3C%3D%3E%40%5B%5D%5E_%60%7B%7C%7D~" + }, + { + "input": "foo://joe: !\"$%&'()*+,-.:;<=>@[\\]^_`{|}~@host/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "foo://joe:%20!%22$%&'()*+,-.%3A%3B%3C%3D%3E%40%5B%5C%5D%5E_%60%7B%7C%7D~@host/", + "origin": "null", + "password": "%20!%22$%&'()*+,-.%3A%3B%3C%3D%3E%40%5B%5C%5D%5E_%60%7B%7C%7D~", + "pathname": "/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "joe" + }, + { + "input": "wss://joe: !\"$%&'()*+,-.:;<=>@[]^_`{|}~@host/", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "wss://joe:%20!%22$%&'()*+,-.%3A%3B%3C%3D%3E%40%5B%5D%5E_%60%7B%7C%7D~@host/", + "origin": "wss://host", + "password": "%20!%22$%&'()*+,-.%3A%3B%3C%3D%3E%40%5B%5D%5E_%60%7B%7C%7D~", + "pathname": "/", + "port":"", + "protocol": "wss:", + "search": "", + "username": "joe" + }, + { + "input": "foo://!\"$%&'()*+,-.;=_`{}~/", + "base": null, + "hash": "", + "host": "!\"$%&'()*+,-.;=_`{}~", + "hostname": "!\"$%&'()*+,-.;=_`{}~", + "href":"foo://!\"$%&'()*+,-.;=_`{}~/", + "origin": "null", + "password": "", + "pathname": "/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "" + }, + { + "input": "wss://!\"$&'()*+,-.;=_`{}~/", + "base": null, + "hash": "", + "host": "!\"$&'()*+,-.;=_`{}~", + "hostname": "!\"$&'()*+,-.;=_`{}~", + "href":"wss://!\"$&'()*+,-.;=_`{}~/", + "origin": "wss://!\"$&'()*+,-.;=_`{}~", + "password": "", + "pathname": "/", + "port":"", + "protocol": "wss:", + "search": "", + "username": "" + }, + { + "input": "foo://host/ !\"$%&'()*+,-./:;<=>@[\\]^_`{|}~", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "foo://host/%20!%22$%&'()*+,-./:;%3C=%3E@[\\]%5E_%60%7B|%7D~", + "origin": "null", + "password": "", + "pathname": "/%20!%22$%&'()*+,-./:;%3C=%3E@[\\]%5E_%60%7B|%7D~", + "port":"", + "protocol": "foo:", + "search": "", + "username": "" + }, + { + "input": "wss://host/ !\"$%&'()*+,-./:;<=>@[\\]^_`{|}~", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "wss://host/%20!%22$%&'()*+,-./:;%3C=%3E@[/]%5E_%60%7B|%7D~", + "origin": "wss://host", + "password": "", + "pathname": "/%20!%22$%&'()*+,-./:;%3C=%3E@[/]%5E_%60%7B|%7D~", + "port":"", + "protocol": "wss:", + "search": "", + "username": "" + }, + { + "input": "foo://host/dir/? !\"$%&'()*+,-./:;<=>?@[\\]^_`{|}~", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "foo://host/dir/?%20!%22$%&'()*+,-./:;%3C=%3E?@[\\]^_`{|}~", + "origin": "null", + "password": "", + "pathname": "/dir/", + "port":"", + "protocol": "foo:", + "search": "?%20!%22$%&'()*+,-./:;%3C=%3E?@[\\]^_`{|}~", + "username": "" + }, + { + "input": "wss://host/dir/? !\"$%&'()*+,-./:;<=>?@[\\]^_`{|}~", + "base": null, + "hash": "", + "host": "host", + "hostname": "host", + "href": "wss://host/dir/?%20!%22$%&%27()*+,-./:;%3C=%3E?@[\\]^_`{|}~", + "origin": "wss://host", + "password": "", + "pathname": "/dir/", + "port":"", + "protocol": "wss:", + "search": "?%20!%22$%&%27()*+,-./:;%3C=%3E?@[\\]^_`{|}~", + "username": "" + }, + { + "input": "foo://host/dir/# !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", + "base": null, + "hash": "#%20!%22#$%&'()*+,-./:;%3C=%3E?@[\\]^_%60{|}~", + "host": "host", + "hostname": "host", + "href": "foo://host/dir/#%20!%22#$%&'()*+,-./:;%3C=%3E?@[\\]^_%60{|}~", + "origin": "null", + "password": "", + "pathname": "/dir/", + "port":"", + "protocol": "foo:", + "search": "", + "username": "" + }, + { + "input": "wss://host/dir/# !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", + "base": null, + "hash": "#%20!%22#$%&'()*+,-./:;%3C=%3E?@[\\]^_%60{|}~", + "host": "host", + "hostname": "host", + "href": "wss://host/dir/#%20!%22#$%&'()*+,-./:;%3C=%3E?@[\\]^_%60{|}~", + "origin": "wss://host", + "password": "", + "pathname": "/dir/", + "port":"", + "protocol": "wss:", + "search": "", + "username": "" + }, + "Ensure that input schemes are not ignored when resolving non-special URLs", + { + "input": "abc:rootless", + "base": "abc://host/path", + "hash": "", + "host": "", + "hostname": "", + "href":"abc:rootless", + "password": "", + "pathname": "rootless", + "port":"", + "protocol": "abc:", + "search": "", + "username": "" + }, + { + "input": "abc:rootless", + "base": "abc:/path", + "hash": "", + "host": "", + "hostname": "", + "href":"abc:rootless", + "password": "", + "pathname": "rootless", + "port":"", + "protocol": "abc:", + "search": "", + "username": "" + }, + { + "input": "abc:rootless", + "base": "abc:path", + "hash": "", + "host": "", + "hostname": "", + "href":"abc:rootless", + "password": "", + "pathname": "rootless", + "port":"", + "protocol": "abc:", + "search": "", + "username": "" + }, + { + "input": "abc:/rooted", + "base": "abc://host/path", + "hash": "", + "host": "", + "hostname": "", + "href":"abc:/rooted", + "password": "", + "pathname": "/rooted", + "port":"", + "protocol": "abc:", + "search": "", + "username": "" + }, + "Empty query and fragment with blank should throw an error", + { + "input": "#", + "base": null, + "failure": true, + "relativeTo": "any-base" + }, + { + "input": "?", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + "Last component looks like a number, but not valid IPv4", + { + "input": "http://1.2.3.4.5", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://1.2.3.4.5.", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://0..0x300/", + "base": null, + "failure": true + }, + { + "input": "http://0..0x300./", + "base": null, + "failure": true + }, + { + "input": "http://256.256.256.256.256", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://256.256.256.256.256.", + "base": "http://other.com/", + "failure": true + }, + { + "input": "http://1.2.3.08", + "base": null, + "failure": true + }, + { + "input": "http://1.2.3.08.", + "base": null, + "failure": true + }, + { + "input": "http://1.2.3.09", + "base": null, + "failure": true + }, + { + "input": "http://09.2.3.4", + "base": null, + "failure": true + }, + { + "input": "http://09.2.3.4.", + "base": null, + "failure": true + }, + { + "input": "http://01.2.3.4.5", + "base": null, + "failure": true + }, + { + "input": "http://01.2.3.4.5.", + "base": null, + "failure": true + }, + { + "input": "http://0x100.2.3.4", + "base": null, + "failure": true + }, + { + "input": "http://0x100.2.3.4.", + "base": null, + "failure": true + }, + { + "input": "http://0x1.2.3.4.5", + "base": null, + "failure": true + }, + { + "input": "http://0x1.2.3.4.5.", + "base": null, + "failure": true + }, + { + "input": "http://foo.1.2.3.4", + "base": null, + "failure": true + }, + { + "input": "http://foo.1.2.3.4.", + "base": null, + "failure": true + }, + { + "input": "http://foo.2.3.4", + "base": null, + "failure": true + }, + { + "input": "http://foo.2.3.4.", + "base": null, + "failure": true + }, + { + "input": "http://foo.09", + "base": null, + "failure": true + }, + { + "input": "http://foo.09.", + "base": null, + "failure": true + }, + { + "input": "http://foo.0x4", + "base": null, + "failure": true + }, + { + "input": "http://foo.0x4.", + "base": null, + "failure": true + }, + { + "input": "http://foo.09..", + "base": null, + "hash": "", + "host": "foo.09..", + "hostname": "foo.09..", + "href":"http://foo.09../", + "password": "", + "pathname": "/", + "port":"", + "protocol": "http:", + "search": "", + "username": "" + }, + { + "input": "http://0999999999999999999/", + "base": null, + "failure": true + }, + { + "input": "http://foo.0x", + "base": null, + "failure": true + }, + { + "input": "http://foo.0XFfFfFfFfFfFfFfFfFfAcE123", + "base": null, + "failure": true + }, + { + "input": "http://💩.123/", + "base": null, + "failure": true + }, + "U+0000 and U+FFFF in various places", + { + "input": "https://\u0000y", + "base": null, + "failure": true + }, + { + "input": "https://x/\u0000y", + "base": null, + "hash": "", + "host": "x", + "hostname": "x", + "href": "https://x/%00y", + "password": "", + "pathname": "/%00y", + "port": "", + "protocol": "https:", + "search": "", + "username": "" + }, + { + "input": "https://x/?\u0000y", + "base": null, + "hash": "", + "host": "x", + "hostname": "x", + "href": "https://x/?%00y", + "password": "", + "pathname": "/", + "port": "", + "protocol": "https:", + "search": "?%00y", + "username": "" + }, + { + "input": "https://x/?#\u0000y", + "base": null, + "hash": "#%00y", + "host": "x", + "hostname": "x", + "href": "https://x/?#%00y", + "password": "", + "pathname": "/", + "port": "", + "protocol": "https:", + "search": "", + "username": "" + }, + { + "input": "https://\uFFFFy", + "base": null, + "failure": true + }, + { + "input": "https://x/\uFFFFy", + "base": null, + "hash": "", + "host": "x", + "hostname": "x", + "href": "https://x/%EF%BF%BFy", + "password": "", + "pathname": "/%EF%BF%BFy", + "port": "", + "protocol": "https:", + "search": "", + "username": "" + }, + { + "input": "https://x/?\uFFFFy", + "base": null, + "hash": "", + "host": "x", + "hostname": "x", + "href": "https://x/?%EF%BF%BFy", + "password": "", + "pathname": "/", + "port": "", + "protocol": "https:", + "search": "?%EF%BF%BFy", + "username": "" + }, + { + "input": "https://x/?#\uFFFFy", + "base": null, + "hash": "#%EF%BF%BFy", + "host": "x", + "hostname": "x", + "href": "https://x/?#%EF%BF%BFy", + "password": "", + "pathname": "/", + "port": "", + "protocol": "https:", + "search": "", + "username": "" + }, + { + "input": "non-special:\u0000y", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:%00y", + "password": "", + "pathname": "%00y", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "non-special:x/\u0000y", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:x/%00y", + "password": "", + "pathname": "x/%00y", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "non-special:x/?\u0000y", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:x/?%00y", + "password": "", + "pathname": "x/", + "port": "", + "protocol": "non-special:", + "search": "?%00y", + "username": "" + }, + { + "input": "non-special:x/?#\u0000y", + "base": null, + "hash": "#%00y", + "host": "", + "hostname": "", + "href": "non-special:x/?#%00y", + "password": "", + "pathname": "x/", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "non-special:\uFFFFy", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:%EF%BF%BFy", + "password": "", + "pathname": "%EF%BF%BFy", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "non-special:x/\uFFFFy", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:x/%EF%BF%BFy", + "password": "", + "pathname": "x/%EF%BF%BFy", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "non-special:x/?\uFFFFy", + "base": null, + "hash": "", + "host": "", + "hostname": "", + "href": "non-special:x/?%EF%BF%BFy", + "password": "", + "pathname": "x/", + "port": "", + "protocol": "non-special:", + "search": "?%EF%BF%BFy", + "username": "" + }, + { + "input": "non-special:x/?#\uFFFFy", + "base": null, + "hash": "#%EF%BF%BFy", + "host": "", + "hostname": "", + "href": "non-special:x/?#%EF%BF%BFy", + "password": "", + "pathname": "x/", + "port": "", + "protocol": "non-special:", + "search": "", + "username": "" + }, + { + "input": "", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "https://example.com/\"quoted\"", + "base": null, + "hash": "", + "host": "example.com", + "hostname": "example.com", + "href": "https://example.com/%22quoted%22", + "origin": "https://example.com", + "password": "", + "pathname": "/%22quoted%22", + "port": "", + "protocol": "https:", + "search": "", + "username": "" + }, + { + "input": "https://a%C2%ADb/", + "base": null, + "hash": "", + "host": "ab", + "hostname": "ab", + "href": "https://ab/", + "origin": "https://ab", + "password": "", + "pathname": "/", + "port": "", + "protocol": "https:", + "search": "", + "username": "" + }, + { + "comment": "Empty host after domain to ASCII", + "input": "https://\u00AD/", + "base": null, + "failure": true + }, + { + "input": "https://%C2%AD/", + "base": null, + "failure": true + }, + { + "input": "https://xn--/", + "base": null, + "href": "https://xn--/", + "origin": "https://xn--", + "protocol": "https:", + "username": "", + "password": "", + "host": "xn--", + "hostname": "xn--", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "Non-special schemes that some implementations might incorrectly treat as special", + { + "input": "data://example.com:8080/pathname?search#hash", + "base": null, + "href": "data://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "data:///test", + "base": null, + "href": "data:///test", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "data://test/a/../b", + "base": null, + "href": "data://test/b", + "origin": "null", + "protocol": "data:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "data://:443", + "base": null, + "failure": true + }, + { + "input": "data://test:test", + "base": null, + "failure": true + }, + { + "input": "data://[:1]", + "base": null, + "failure": true + }, + { + "input": "javascript://example.com:8080/pathname?search#hash", + "base": null, + "href": "javascript://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "javascript:///test", + "base": null, + "href": "javascript:///test", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "javascript://test/a/../b", + "base": null, + "href": "javascript://test/b", + "origin": "null", + "protocol": "javascript:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "javascript://:443", + "base": null, + "failure": true + }, + { + "input": "javascript://test:test", + "base": null, + "failure": true + }, + { + "input": "javascript://[:1]", + "base": null, + "failure": true + }, + { + "input": "mailto://example.com:8080/pathname?search#hash", + "base": null, + "href": "mailto://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "mailto:///test", + "base": null, + "href": "mailto:///test", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "mailto://test/a/../b", + "base": null, + "href": "mailto://test/b", + "origin": "null", + "protocol": "mailto:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "mailto://:443", + "base": null, + "failure": true + }, + { + "input": "mailto://test:test", + "base": null, + "failure": true + }, + { + "input": "mailto://[:1]", + "base": null, + "failure": true + }, + { + "input": "intent://example.com:8080/pathname?search#hash", + "base": null, + "href": "intent://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "intent:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "intent:///test", + "base": null, + "href": "intent:///test", + "origin": "null", + "protocol": "intent:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "intent://test/a/../b", + "base": null, + "href": "intent://test/b", + "origin": "null", + "protocol": "intent:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "intent://:443", + "base": null, + "failure": true + }, + { + "input": "intent://test:test", + "base": null, + "failure": true + }, + { + "input": "intent://[:1]", + "base": null, + "failure": true + }, + { + "input": "urn://example.com:8080/pathname?search#hash", + "base": null, + "href": "urn://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "urn:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "urn:///test", + "base": null, + "href": "urn:///test", + "origin": "null", + "protocol": "urn:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "urn://test/a/../b", + "base": null, + "href": "urn://test/b", + "origin": "null", + "protocol": "urn:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "urn://:443", + "base": null, + "failure": true + }, + { + "input": "urn://test:test", + "base": null, + "failure": true + }, + { + "input": "urn://[:1]", + "base": null, + "failure": true + }, + { + "input": "turn://example.com:8080/pathname?search#hash", + "base": null, + "href": "turn://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "turn:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "turn:///test", + "base": null, + "href": "turn:///test", + "origin": "null", + "protocol": "turn:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "turn://test/a/../b", + "base": null, + "href": "turn://test/b", + "origin": "null", + "protocol": "turn:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "turn://:443", + "base": null, + "failure": true + }, + { + "input": "turn://test:test", + "base": null, + "failure": true + }, + { + "input": "turn://[:1]", + "base": null, + "failure": true + }, + { + "input": "stun://example.com:8080/pathname?search#hash", + "base": null, + "href": "stun://example.com:8080/pathname?search#hash", + "origin": "null", + "protocol": "stun:", + "username": "", + "password": "", + "host": "example.com:8080", + "hostname": "example.com", + "port": "8080", + "pathname": "/pathname", + "search": "?search", + "hash": "#hash" + }, + { + "input": "stun:///test", + "base": null, + "href": "stun:///test", + "origin": "null", + "protocol": "stun:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test", + "search": "", + "hash": "" + }, + { + "input": "stun://test/a/../b", + "base": null, + "href": "stun://test/b", + "origin": "null", + "protocol": "stun:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/b", + "search": "", + "hash": "" + }, + { + "input": "stun://:443", + "base": null, + "failure": true + }, + { + "input": "stun://test:test", + "base": null, + "failure": true + }, + { + "input": "stun://[:1]", + "base": null, + "failure": true + }, + { + "input": "w://x:0", + "base": null, + "href": "w://x:0", + "origin": "null", + "protocol": "w:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "west://x:0", + "base": null, + "href": "west://x:0", + "origin": "null", + "protocol": "west:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "android://x:0/a", + "base": null, + "href": "android://x:0/a", + "origin": "null", + "protocol": "android:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "/a", + "search": "", + "hash": "" + }, + { + "input": "drivefs://x:0/a", + "base": null, + "href": "drivefs://x:0/a", + "origin": "null", + "protocol": "drivefs:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "/a", + "search": "", + "hash": "" + }, + { + "input": "chromeos-steam://x:0/a", + "base": null, + "href": "chromeos-steam://x:0/a", + "origin": "null", + "protocol": "chromeos-steam:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "/a", + "search": "", + "hash": "" + }, + { + "input": "steam://x:0/a", + "base": null, + "href": "steam://x:0/a", + "origin": "null", + "protocol": "steam:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "/a", + "search": "", + "hash": "" + }, + { + "input": "materialized-view://x:0/a", + "base": null, + "href": "materialized-view://x:0/a", + "origin": "null", + "protocol": "materialized-view:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "/a", + "search": "", + "hash": "" + }, + { + "input": "android-app://x:0", + "base": null, + "href": "android-app://x:0", + "origin": "null", + "protocol": "android-app:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "chrome-distiller://x:0", + "base": null, + "href": "chrome-distiller://x:0", + "origin": "null", + "protocol": "chrome-distiller:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "chrome-extension://x:0", + "base": null, + "href": "chrome-extension://x:0", + "origin": "null", + "protocol": "chrome-extension:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "chrome-native://x:0", + "base": null, + "href": "chrome-native://x:0", + "origin": "null", + "protocol": "chrome-native:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "chrome-resource://x:0", + "base": null, + "href": "chrome-resource://x:0", + "origin": "null", + "protocol": "chrome-resource:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "chrome-search://x:0", + "base": null, + "href": "chrome-search://x:0", + "origin": "null", + "protocol": "chrome-search:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "fuchsia-dir://x:0", + "base": null, + "href": "fuchsia-dir://x:0", + "origin": "null", + "protocol": "fuchsia-dir:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "", + "search": "", + "hash": "" + }, + { + "input": "isolated-app://x:0", + "base": null, + "href": "isolated-app://x:0", + "origin": "null", + "protocol": "isolated-app:", + "username": "", + "password": "", + "host": "x:0", + "hostname": "x", + "port": "0", + "pathname": "", + "search": "", + "hash": "" + }, + "Scheme relative path starting with multiple slashes", + { + "input": "///test", + "base": "http://example.org/", + "href": "http://test/", + "protocol": "http:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "///\\//\\//test", + "base": "http://example.org/", + "href": "http://test/", + "protocol": "http:", + "username": "", + "password": "", + "host": "test", + "hostname": "test", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "///example.org/path", + "base": "http://example.org/", + "href": "http://example.org/path", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/path", + "search": "", + "hash": "" + }, + { + "input": "///example.org/../path", + "base": "http://example.org/", + "href": "http://example.org/path", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/path", + "search": "", + "hash": "" + }, + { + "input": "///example.org/../../", + "base": "http://example.org/", + "href": "http://example.org/", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "///example.org/../path/../../", + "base": "http://example.org/", + "href": "http://example.org/", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "///example.org/../path/../../path", + "base": "http://example.org/", + "href": "http://example.org/path", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/path", + "search": "", + "hash": "" + }, + { + "input": "/\\/\\//example.org/../path", + "base": "http://example.org/", + "href": "http://example.org/path", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/path", + "search": "", + "hash": "" + }, + { + "input": "///abcdef/../", + "base": "file:///", + "href": "file:///", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + { + "input": "/\\//\\/a/../", + "base": "file:///", + "href": "file://////", + "protocol": "file:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "////", + "search": "", + "hash": "" + }, + { + "input": "//a/../", + "base": "file:///", + "href": "file://a/", + "protocol": "file:", + "username": "", + "password": "", + "host": "a", + "hostname": "a", + "port": "", + "pathname": "/", + "search": "", + "hash": "" + }, + "# Non-special URL and backslashes", + { + "input": "non-special:\\\\opaque", + "base": null, + "href": "non-special:\\\\opaque", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "\\\\opaque", + "search": "", + "hash": "" + }, + { + "input": "non-special:\\\\opaque/path", + "base": null, + "href": "non-special:\\\\opaque/path", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "\\\\opaque/path", + "search": "", + "hash": "" + }, + { + "input": "non-special:\\\\opaque\\path", + "base": null, + "href": "non-special:\\\\opaque\\path", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "\\\\opaque\\path", + "search": "", + "hash": "" + }, + { + "input": "non-special:\\/opaque", + "base": null, + "href": "non-special:\\/opaque", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "\\/opaque", + "search": "", + "hash": "" + }, + { + "input": "non-special:/\\path", + "base": null, + "href": "non-special:/\\path", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/\\path", + "search": "", + "hash": "" + }, + { + "input": "non-special://host\\a", + "base": null, + "failure": true + }, + { + "input": "non-special://host/a\\b", + "base": null, + "href": "non-special://host/a\\b", + "origin": "null", + "protocol": "non-special:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/a\\b", + "search": "", + "hash": "" + }, + "# Non-special relative URL and backslashes", + { + "comment": "Non-special relative: \\ should not enter RelativeSlash state", + "input": "\\a", + "base": "foo://foo/a", + "href": "foo://foo/\\a", + "protocol": "foo:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/\\a", + "search": "", + "hash": "" + }, + { + "comment": "Non-special relative: \\ should not enter RelativeSlash, so / is a path separator", + "input": "\\/a", + "base": "foo://foo/a", + "href": "foo://foo/\\/a", + "protocol": "foo:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/\\/a", + "search": "", + "hash": "" + }, + { + "comment": "Non-special relative: \\\\ should not trigger authority parsing", + "input": "\\\\a", + "base": "foo://foo/a", + "href": "foo://foo/\\\\a", + "protocol": "foo:", + "username": "", + "password": "", + "host": "foo", + "hostname": "foo", + "port": "", + "pathname": "/\\\\a", + "search": "", + "hash": "" + }, + { + "comment": "Fragment with <> on data: URI", + "input": "data:text/plain,test# ", + "base": null, + "href": "data:text/plain,test#%3Cfoo%3E%20%3Cbar%3E", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "text/plain,test", + "search": "", + "hash": "#%3Cfoo%3E%20%3Cbar%3E" + }, + { + "comment": "Fragment with <> on about:blank", + "input": "about:blank# ", + "base": null, + "href": "about:blank#%3Cfoo%3E%20%3Cbar%3E", + "protocol": "about:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "blank", + "search": "", + "hash": "#%3Cfoo%3E%20%3Cbar%3E" + }, + { + "comment": "Fragment percent-encode set on data: URI; tabs and newlines are removed", + "input":"data:text/plain,test#\u0000\u0001\t\n\r\u001f !\"#$%&'()*+,-./09:;<=>?@AZ[\\]^_`az{|}~\u007f\u0080\u0081Éé", + "base": null, + "href": "data:text/plain,test#%00%01%1F%20!%22#$%&'()*+,-./09:;%3C=%3E?@AZ[\\]^_%60az{|}~%7F%C2%80%C2%81%C3%89%C3%A9", + "protocol": "data:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "text/plain,test", + "search": "", + "hash": "#%00%01%1F%20!%22#$%&'()*+,-./09:;%3C=%3E?@AZ[\\]^_%60az{|}~%7F%C2%80%C2%81%C3%89%C3%A9" + }, + { + "comment": "Fragment percent-encode set on about:blank; tabs and newlines are removed", + "input": "about:blank#\u0000\u0001\t\n\r\u001f !\"#$%&'()*+,-./09:;<=>?@AZ[\\]^_`az{|}~\u007f\u0080\u0081Éé", + "base": null, + "href": "about:blank#%00%01%1F%20!%22#$%&'()*+,-./09:;%3C=%3E?@AZ[\\]^_%60az{|}~%7F%C2%80%C2%81%C3%89%C3%A9", + "protocol": "about:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "blank", + "search": "", + "hash": "#%00%01%1F%20!%22#$%&'()*+,-./09:;%3C=%3E?@AZ[\\]^_%60az{|}~%7F%C2%80%C2%81%C3%89%C3%A9" + } +] diff --git a/packages/router-core/tests/getNormalizedURL.test.ts b/packages/router-core/tests/getNormalizedURL.test.ts new file mode 100644 index 0000000000..89cca987b7 --- /dev/null +++ b/packages/router-core/tests/getNormalizedURL.test.ts @@ -0,0 +1,166 @@ +import { describe, expect, test } from 'vitest' +import { getNormalizedURL } from '../src/ssr/ssr-server' + +describe('getNormalizedURL', () => { + test('returns an independent URL that callers can modify', () => { + const input = new URL('https://example.com/path?query=value') + const { url } = getNormalizedURL(input) + url.pathname = '/changed' + expect(input.href).toBe('https://example.com/path?query=value') + }) + + test.each([ + 'https://user:password@example.com/path', + 'https://example.com/path?', + 'https://example.com/path#', + ])('normalizes the full URL consistently: %s', (input) => { + expect(getNormalizedURL(input).url.href).toBe('https://example.com/path') + }) + + test.each(['/%2Fdocs', '/%5Cdocs', '/%00/docs'])( + 'preserves encoded pathname data in a URL object: %s', + (pathname) => { + const input = new URL(pathname, 'https://app.example') + const { url, handledProtocolRelativeURL } = getNormalizedURL(input) + expect(url.href).toBe(input.href) + expect(handledProtocolRelativeURL).toBe(false) + }, + ) + + test.each(['//other.example/path', '///other.example/path'])( + 'keeps a request pathname %j on its original origin', + (pathname) => { + const { url, handledProtocolRelativeURL } = getNormalizedURL( + `https://example.com${pathname}?next=//other.example#//section`, + ) + expect(url.href).toBe( + 'https://example.com/other.example/path?next=%2F%2Fother.example#//section', + ) + expect(handledProtocolRelativeURL).toBe(true) + }, + ) + + test('should return URL that is in standardized format', () => { + const url1 = 'https://example.com/%EB%8C%80%7C/path?query=%EB%8C%80|#hash' + const url2 = 'https://example.com/%EB%8C%80|/path?query=%EB%8C%80%7C#hash' + + const normalizedUrl1 = getNormalizedURL(url1) + const normalizedUrl2 = getNormalizedURL(url2) + + expect(normalizedUrl1.url.pathname).toBe('/%EB%8C%80|/path') + expect(normalizedUrl1.url.pathname).toBe(normalizedUrl2.url.pathname) + expect(new URL(url1).pathname).not.toBe(new URL(url2).pathname) + + expect(normalizedUrl1.url.search).toBe(`?query=%EB%8C%80%7C`) + expect(normalizedUrl1.url.search).toBe(normalizedUrl2.url.search) + expect(new URL(url1).search).not.toBe(new URL(url2).search) + }) + + const testCases = [ + { + url: 'https://example.com/%3Fstart?query=value', + expectedPathName: '/%3Fstart', + expectedSearchParams: '?query=value', + expectedHash: '', + }, + { + url: 'https://example.com/end%3F?query=value', + expectedPathName: '/end%3F', + expectedSearchParams: '?query=value', + expectedHash: '', + }, + { + url: 'https://example.com/%23?query=value', + expectedPathName: '/%23', + expectedSearchParams: '?query=value', + expectedHash: '', + }, + { + url: 'https://example.com/a%3Fb%3Fc%23d?query=value', + expectedPathName: '/a%3Fb%3Fc%23d', + expectedSearchParams: '?query=value', + expectedHash: '', + }, + { + url: 'https://example.com/path?query=value#section%3Fpart', + expectedPathName: '/path', + expectedSearchParams: '?query=value', + expectedHash: '#section%3Fpart', + }, + { + url: 'https://example.com/start%3Fmiddle%23end?key=value%23part&other=%3Fdata#section%3Fpart', + expectedPathName: '/start%3Fmiddle%23end', + expectedSearchParams: '?key=value%23part&other=%3Fdata', + expectedHash: '#section%3Fpart', + }, + { + url: 'https://example.com/%E0%A4', + expectedPathName: '/%E0%A4', + expectedSearchParams: '', + expectedHash: '', + }, + { + url: 'https://example.com/%ZZ', + expectedPathName: '/%ZZ', + expectedSearchParams: '', + expectedHash: '', + }, + { + url: 'https://example.com/path?a=1&a=2', + expectedPathName: '/path', + expectedSearchParams: '?a=1&a=2', + expectedHash: '', + }, + { + url: 'https://example.com/path+a', + expectedPathName: '/path+a', + expectedSearchParams: '', + expectedHash: '', + }, + { + url: 'https://example.com/path a', + expectedPathName: '/path%20a', + expectedSearchParams: '', + expectedHash: '', + }, + { + url: 'https://example.com/path%20a', + expectedPathName: '/path%20a', + expectedSearchParams: '', + expectedHash: '', + }, + { + url: 'https://example.com/path%25a', + expectedPathName: '/path%25a', + expectedSearchParams: '', + expectedHash: '', + }, + { + url: 'https://example.com/path%25a', + expectedPathName: '/path%25a', + expectedSearchParams: '', + expectedHash: '', + }, + { + url: 'https://example.com/path\\a', + expectedPathName: '/path%5Ca', + expectedSearchParams: '', + expectedHash: '', + }, + { + url: 'https://example.com/path%5Ca', + expectedPathName: '/path%5Ca', + expectedSearchParams: '', + expectedHash: '', + }, + ] + test.each(testCases)( + 'should treat encoded URL specific characters correctly', + ({ url, expectedPathName, expectedHash, expectedSearchParams }) => { + const normalizedUrl = getNormalizedURL(url) + expect(normalizedUrl.url.pathname).toBe(expectedPathName) + expect(normalizedUrl.url.search).toBe(expectedSearchParams) + expect(normalizedUrl.url.hash).toBe(expectedHash) + }, + ) +}) diff --git a/packages/router-core/tests/getOrigin.test.ts b/packages/router-core/tests/getOrigin.test.ts new file mode 100644 index 0000000000..30047e35a8 --- /dev/null +++ b/packages/router-core/tests/getOrigin.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, test } from 'vitest' +import { getOrigin } from '../src/ssr/ssr-server' + +describe('getOrigin security', () => { + test('should not trust spoofed Origin header', () => { + // An attacker could send a malicious Origin header to try to manipulate + // the router's origin, which could affect redirect handling (CVE-2024-34351) + const maliciousRequest = new Request('https://legitimate.com/api/action', { + headers: { + Origin: 'https://evil.com', + }, + }) + + const origin = getOrigin(maliciousRequest) + + // The origin should come from request.url, not the spoofed Origin header + // This prevents SSRF-like attacks where an attacker tries to manipulate + // how redirects are processed by providing a malicious Origin header + expect(origin).toBe('https://legitimate.com') + expect(origin).not.toBe('https://evil.com') + }) + + test('should derive origin from request URL', () => { + const request = new Request('https://myapp.com/page') + const origin = getOrigin(request) + expect(origin).toBe('https://myapp.com') + }) + + test('should handle localhost requests', () => { + const request = new Request('http://localhost:3000/api') + const origin = getOrigin(request) + expect(origin).toBe('http://localhost:3000') + }) + + test('should return fallback for invalid request URL', () => { + // This should be rare, but handle gracefully + const request = { + url: 'not-a-valid-url', + headers: new Headers(), + } as unknown as Request + + const origin = getOrigin(request) + expect(origin).toBe('http://localhost') + }) + + test('should ignore Origin header even if request URL parse fails', () => { + // Even if the request URL is somehow invalid, we should not fall back + // to trusting the Origin header + const request = { + url: 'invalid-url', + headers: new Headers({ + Origin: 'https://evil.com', + }), + } as unknown as Request + + const origin = getOrigin(request) + + // Should fall back to localhost, not use the potentially malicious Origin + expect(origin).toBe('http://localhost') + expect(origin).not.toBe('https://evil.com') + }) +}) diff --git a/packages/router-core/tests/granular-stores.test.ts b/packages/router-core/tests/granular-stores.test.ts new file mode 100644 index 0000000000..8d5b98755a --- /dev/null +++ b/packages/router-core/tests/granular-stores.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +function createRouter() { + const rootRoute = new BaseRootRoute({}) + + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + + const postRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts/$postId', + }) + + const routeTree = rootRoute.addChildren([indexRoute, aboutRoute, postRoute]) + + return createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/'], + }), + }) +} + +describe('granular stores', () => { + test('keeps ordered route state current across match generations', async () => { + const router = createRouter() + await router.navigate({ to: '/posts/123' }) + + expect(router.state.location.pathname).toBe('/posts/123') + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + '__root__', + '/posts/$postId', + ]) + expect(router.state.matches.at(-1)?.params).toMatchObject({ postId: '123' }) + + await router.navigate({ to: '/posts/456' }) + + expect(router.state.location.pathname).toBe('/posts/456') + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + '__root__', + '/posts/$postId', + ]) + expect(router.state.matches.at(-1)?.params).toMatchObject({ postId: '456' }) + + await router.navigate({ to: '/about' }) + + expect(router.state.location.pathname).toBe('/about') + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + '__root__', + '/about', + ]) + }) +}) diff --git a/packages/router-core/tests/history-normalization.test.ts b/packages/router-core/tests/history-normalization.test.ts new file mode 100644 index 0000000000..b862a35b7d --- /dev/null +++ b/packages/router-core/tests/history-normalization.test.ts @@ -0,0 +1,215 @@ +import { createHashHistory, createMemoryHistory } from '@tanstack/history' +import { describe, expect, test } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +const fragments = ['//section', '/\\section', '\\/section', '\\\\section'] + +describe('history normalization boundaries', () => { + test.each([false, true])( + 'normalizes a pathname exposed by the basepath input rewrite (server=%s)', + async (isServer) => { + const root = new BaseRootRoute() + const target = new BaseRoute({ + getParentRoute: () => root, + path: '/target', + loader: () => 'target data', + }) + const router = createTestRouter({ + routeTree: root.addChildren([target]), + basepath: '/app', + isServer, + history: createMemoryHistory({ + initialEntries: ['/app//target#//section'], + }), + }) + + await router.load() + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.location.hash).toBe('//section') + if (isServer) { + expect(router._serverResult?.type).toBe('redirect') + if (router._serverResult?.type === 'redirect') { + expect(router._serverResult.redirect.headers.get('Location')).toBe( + '/app/target#//section', + ) + } + } else { + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: target.id, + status: 'success', + loaderData: 'target data', + }) + } + }, + ) + + test('preserves distinct logical and masked fragment data through a rewrite', async () => { + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: false, + rewrite: { input: ({ url }) => url }, + }) + await router.load() + await router.navigate({ + to: '/', + hash: '/\\logical', + mask: { to: '/', hash: '\\/public' }, + }) + expect(router.state.location.hash).toBe('/\\logical') + expect(router.state.location.maskedLocation?.hash).toBe('\\/public') + expect(router.history.location.hash).toBe('#\\/public') + }) + + test.each([ + { rewrite: false, isServer: false }, + { rewrite: true, isServer: false }, + { rewrite: false, isServer: true }, + { rewrite: true, isServer: true }, + ])( + 'normalizes a generated splat destination before output rewriting (%s)', + ({ rewrite, isServer }) => { + const root = new BaseRootRoute() + const splat = new BaseRoute({ getParentRoute: () => root, path: '$' }) + const rewrittenOrigins: Array = [] + const router = createTestRouter({ + routeTree: root.addChildren([splat]), + history: createMemoryHistory({ initialEntries: ['/'] }), + origin: 'https://app.example', + isServer, + rewrite: rewrite + ? { + output: ({ url }) => { + rewrittenOrigins.push(url.origin) + return url + }, + } + : undefined, + }) + const location = router.buildLocation({ + to: '/$', + params: { _splat: '/other.example/path' }, + }) + expect(location.pathname).toBe('/other.example/path') + expect(location.publicHref).toBe('/other.example/path') + expect(rewrittenOrigins).toEqual(rewrite ? ['https://app.example'] : []) + }, + ) + + test('normalizes protocol-relative paths from output rewrites', () => { + const origin = 'https://victim.example' + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history: createMemoryHistory({ initialEntries: ['/'] }), + origin, + rewrite: { + output: ({ url }) => + url.pathname === '/safe' + ? new URL(`${origin}//evil.example/path`) + : url, + }, + }) + + const location = router.buildLocation({ to: '/safe' }) + + expect(location.external).toBe(false) + expect(location.publicHref).toBe('/evil.example/path') + }) + + test.each(fragments)('preserves fragment data %j on initial load', (hash) => { + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history: createMemoryHistory({ initialEntries: [`/#${hash}`] }), + }) + + expect(router.state.location.hash).toBe(hash) + expect(router.state.location.href).toBe(`/#${hash}`) + }) + + test.each(fragments)( + 'preserves fragment data %j through navigation', + async (hash) => { + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: false, + }) + await router.load() + await router.navigate({ to: '/', hash }) + + expect(router.state.location.hash).toBe(hash) + expect(router.history.location.hash).toBe(`#${hash}`) + }, + ) + + test.each(fragments)( + 'preserves fragment data %j after an input rewrite', + (hash) => { + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history: createMemoryHistory({ initialEntries: ['/public'] }), + rewrite: { + input: ({ url }) => { + url.pathname = '/' + url.hash = hash + return url + }, + }, + }) + + expect(router.state.location.hash).toBe(hash) + }, + ) + + test.each(fragments)( + 'preserves nested fragment data %j with hash history', + async (hash) => { + window.history.replaceState(null, '', `/shell#/route#${hash}`) + const history = createHashHistory() + try { + const root = new BaseRootRoute() + const router = createTestRouter({ + routeTree: root.addChildren([ + new BaseRoute({ getParentRoute: () => root, path: '/route' }), + ]), + history, + isServer: false, + }) + expect(router.state.location.pathname).toBe('/route') + expect(router.state.location.hash).toBe(hash) + await router.load() + await router.navigate({ to: '/route', hash: `${hash}-next` }) + history.flush() + expect(router.state.location.hash).toBe(`${hash}-next`) + expect(window.location.hash).toBe(`#/route#${hash}-next`) + } finally { + history.destroy() + window.history.replaceState(null, '', '/') + } + }, + ) + + test('reads a hash route that starts with a query once', async () => { + window.history.replaceState(null, '', '/shell#?x=1') + const history = createHashHistory() + try { + const root = new BaseRootRoute() + const index = new BaseRoute({ getParentRoute: () => root, path: '/' }) + const router = createTestRouter({ + routeTree: root.addChildren([index]), + history, + isServer: false, + }) + await router.load() + expect(router.state.location.search).toEqual({ x: 1 }) + // The query must not also be read as part of the pathname. + expect(router.state.location.href).toMatch(/^\/?\?x=1$/) + expect(router.state.matches.at(-1)?.routeId).toBe(index.id) + } finally { + history.destroy() + window.history.replaceState(null, '', '/') + } + }) +}) diff --git a/packages/router-core/tests/hmr-refresh-lifecycle.test.ts b/packages/router-core/tests/hmr-refresh-lifecycle.test.ts new file mode 100644 index 0000000000..c115b8fff7 --- /dev/null +++ b/packages/router-core/tests/hmr-refresh-lifecycle.test.ts @@ -0,0 +1,411 @@ +import { + afterEach, + beforeEach, + describe, + expect, + onTestFinished, + test, + vi, +} from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + redirect, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +beforeEach(() => { + vi.spyOn(window, 'scrollTo').mockImplementation(() => {}) +}) + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('HMR route refresh', () => { + test('reloads retained routes with onStay lifecycle semantics', async () => { + let generation = 1 + const loader = vi.fn(() => generation) + const onEnter = vi.fn() + const onLeave = vi.fn() + const order: Array = [] + const onStay = vi.fn(() => order.push('onStay')) + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader, + onEnter, + onLeave, + onStay, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + const unsubLoad = router.subscribe('onLoad', () => order.push('onLoad')) + const unsubMount = router.subscribe('onBeforeRouteMount', () => + order.push('onBeforeRouteMount'), + ) + generation = 2 + await router._refreshRoute!() + + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.loaderData).toBe(2) + expect(onEnter).toHaveBeenCalledTimes(1) + expect(onLeave).not.toHaveBeenCalled() + expect(onStay).toHaveBeenCalledTimes(1) + expect(order).toEqual(['onStay', 'onLoad', 'onBeforeRouteMount']) + unsubLoad() + unsubMount() + }) + + test('retires refresh mode after an acknowledged publication', async () => { + const otherLoader = vi.fn(() => 'other data') + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + loader: otherLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + await router._refreshRoute!() + await router.preloadRoute({ to: '/other' }) + + expect(router._tx?.[6]).toBeUndefined() + expect(otherLoader).toHaveBeenCalledOnce() + }) + + test('passes rematerialization to a reentrant preflight load', async () => { + let generation = 1 + const loader = vi.fn(() => generation) + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + staleTime: Infinity, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + generation = 2 + let reenter = true + let reentrantLoad: Promise | undefined + const unsubscribe = router.subscribe('onBeforeNavigate', () => { + if (reenter) { + reenter = false + reentrantLoad = router.load({ sync: true }) + } + }) + onTestFinished(unsubscribe) + + await router._refreshRoute!() + await reentrantLoad + + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.loaderData).toBe(2) + }) + + test('passes rematerialization to a load that supersedes refresh work', async () => { + let generation = 1 + let reenter = false + let reentrantLoad: Promise | undefined + let router!: ReturnType + const loader = vi.fn(() => { + if (reenter) { + reenter = false + reentrantLoad = router.load({ sync: true }) + } + return generation + }) + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + staleTime: Infinity, + loader, + }) + router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + generation = 2 + reenter = true + await router._refreshRoute!() + await reentrantLoad + + expect(loader).toHaveBeenCalledTimes(3) + expect(router.state.matches.at(-1)?.loaderData).toBe(2) + }) + + test('passes rematerialization through a refresh redirect', async () => { + let generation = 1 + let shouldRedirect = false + const rootLoader = vi.fn(() => generation) + const rootRoute = new BaseRootRoute({ + staleTime: Infinity, + loader: rootLoader, + }) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + beforeLoad: () => { + if (shouldRedirect) { + throw redirect({ to: '/target' }) + } + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + }) + + await router.load() + generation = 2 + shouldRedirect = true + await router._refreshRoute!() + + expect(router.state.location.pathname).toBe('/target') + expect(rootLoader).toHaveBeenCalledTimes(2) + expect(router.state.matches[0]?.loaderData).toBe(2) + }) + + test('publishes refresh route errors without restoring the previous generation', async () => { + let generation = 1 + const boom = new Error('refreshed loader failed') + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => { + if (generation === 2) { + throw boom + } + return generation + }, + onError, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + generation = 2 + await router._refreshRoute!() + + expect(onError).toHaveBeenCalledWith(boom) + expect(router.state.status).toBe('idle') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'error', + error: boom, + }) + }) + + test('rapid refreshes release obsolete generations and converge on the successor', async () => { + let generation = 1 + const signals: Array = [] + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: ({ abortController }) => { + signals.push(abortController.signal) + return generation + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + const firstAck = createControlledPromise() + const firstPublished = createControlledPromise() + let transitions = 0 + router.startTransition = (fn) => { + transitions++ + if (transitions === 1) { + fn() + firstPublished.resolve() + return firstAck + } + firstAck.resolve(false) + fn() + return Promise.resolve(true) + } + + generation = 2 + const firstSettled = vi.fn() + const firstRefresh = router._refreshRoute!().then(firstSettled) + await firstPublished + + expect(firstSettled).not.toHaveBeenCalled() + expect(signals[0]?.aborted).toBe(true) + expect(signals[1]?.aborted).toBe(false) + expect(router.state.matches.at(-1)?.loaderData).toBe(2) + + generation = 3 + const secondRefresh = router._refreshRoute!() + await Promise.all([firstRefresh, secondRefresh]) + + expect(firstSettled).toHaveBeenCalledOnce() + expect(signals[1]?.aborted).toBe(true) + expect(signals[2]?.aborted).toBe(false) + expect(router.state.matches.at(-1)?.loaderData).toBe(3) + expect(router.state.status).toBe('idle') + expect(router._cache.size).toBe(0) + }) + + test('a published refresh waits for the navigation that supersedes it', async () => { + let generation = 1 + const destinationGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => generation, + }) + const destinationRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/destination', + loader: () => destinationGate, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute, destinationRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + const refreshAck = createControlledPromise() + const refreshPublished = createControlledPromise() + let transitionCount = 0 + router.startTransition = (fn) => { + transitionCount++ + if (transitionCount === 1) { + fn() + refreshPublished.resolve() + return refreshAck + } + refreshAck.resolve(false) + fn() + return Promise.resolve(true) + } + + generation = 2 + const refreshSettled = vi.fn() + const refresh = router._refreshRoute!().then(refreshSettled) + await refreshPublished + + const navigationSettled = vi.fn() + const navigation = router + .navigate({ to: '/destination' }) + .then(navigationSettled) + await vi.waitFor(() => + expect(router.state.location.pathname).toBe('/destination'), + ) + expect(refreshSettled).not.toHaveBeenCalled() + expect(navigationSettled).not.toHaveBeenCalled() + + destinationGate.resolve() + await Promise.all([refresh, navigation]) + expect(refreshSettled).toHaveBeenCalledOnce() + expect(navigationSettled).toHaveBeenCalledOnce() + expect(router.state.matches.at(-1)?.routeId).toBe(destinationRoute.id) + }) + + test('waits for an ordinary pending navigation before refreshing', async () => { + const destinationGate = createControlledPromise() + const destinationLoader = vi.fn(() => destinationGate) + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + }) + const destinationRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/destination', + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () => null, + loader: destinationLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute, destinationRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + const navigation = router.navigate({ to: '/destination' }) + await vi.waitFor(() => { + expect(router.state.status).toBe('pending') + expect(router.state.matches.at(-1)?.routeId).toBe(destinationRoute.id) + }) + const refreshSettled = vi.fn() + const refresh = router._refreshRoute!().then(refreshSettled) + await Promise.resolve() + expect(refreshSettled).not.toHaveBeenCalled() + + destinationGate.resolve() + await Promise.all([navigation, refresh]) + + expect(router.state.status).toBe('idle') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: destinationRoute.id, + status: 'success', + }) + expect(destinationLoader).toHaveBeenCalledTimes(2) + expect(refreshSettled).toHaveBeenCalledOnce() + }) + + test('does not adopt a preload created by HMR preflight hooks', async () => { + let generation = 1 + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => generation, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + generation = 2 + const unsubscribe = router.subscribe('onBeforeLoad', () => { + void router.preloadRoute({ to: '/page' }) + }) + onTestFinished(unsubscribe) + + await router._refreshRoute!() + + expect(router.state.matches.at(-1)?.loaderData).toBe(2) + }) +}) diff --git a/packages/router-core/tests/htmlBoundaryScanner.test.ts b/packages/router-core/tests/htmlBoundaryScanner.test.ts new file mode 100644 index 0000000000..05dfa5543e --- /dev/null +++ b/packages/router-core/tests/htmlBoundaryScanner.test.ts @@ -0,0 +1,256 @@ +import { describe, expect, test } from 'vitest' +import { + HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX, + HYDRATION_SCRIPT_BOUNDARY_BYTES, + createHydrationScripts, +} from '../src/ssr/hydrationScripts' +import { + DOCUMENT_CLOSE_ANCHOR_INDEX, + DOCUMENT_CLOSE_BYTES, + SCRIPT_CLOSE, + SCRIPT_CLOSE_ANCHOR_INDEX, + SCRIPT_CLOSE_BYTES, + advanceByteMatcher, + findExactBytes, + getExactBytesPrefixAtEnd, +} from '../src/ssr/htmlBoundaryScanner' +import type { ByteMatcherState } from '../src/ssr/htmlBoundaryScanner' + +const encoder = new TextEncoder() +const decoder = new TextDecoder() +const DOCUMENT_CLOSE = decoder.decode(DOCUMENT_CLOSE_BYTES) +const HYDRATION_SCRIPT_BOUNDARY_SUFFIX = decoder.decode( + HYDRATION_SCRIPT_BOUNDARY_BYTES, +) +const HYDRATION_SCRIPT_BOUNDARY_SOURCE = createHydrationScripts( + undefined, + [], +).takeInitialHydrationScriptTags()!.boundary.children! + +function chunksAtEverySplit(value: Uint8Array) { + return Array.from({ length: value.length + 1 }, (_, split) => [ + value.subarray(0, split), + value.subarray(split), + ]) +} + +function matcherFor(pattern: Uint8Array, anchorIndex = 0): ByteMatcherState { + return { pattern, anchorIndex, matched: 0 } +} + +describe('SSR exact byte matcher', () => { + test.each([ + [ + 'router boundary', + HYDRATION_SCRIPT_BOUNDARY_BYTES, + HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX, + ], + ['script close', SCRIPT_CLOSE_BYTES, SCRIPT_CLOSE_ANCHOR_INDEX], + ])('matches %s at every two-chunk split', (_, pattern, anchorIndex) => { + for (const chunks of chunksAtEverySplit(pattern)) { + const matcher = matcherFor(pattern, anchorIndex) + let matches = 0 + for (const chunk of chunks) { + if (advanceByteMatcher(matcher, chunk) !== undefined) { + matches++ + } + } + expect(matches).toBe(1) + } + }) + + test.each([ + [ + 'router boundary', + HYDRATION_SCRIPT_BOUNDARY_BYTES, + HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX, + ], + ['script close', SCRIPT_CLOSE_BYTES, SCRIPT_CLOSE_ANCHOR_INDEX], + ])('matches byte-at-a-time %s input', (_, pattern, anchorIndex) => { + const matcher = matcherFor(pattern, anchorIndex) + let matches = 0 + for (const byte of pattern) { + if (advanceByteMatcher(matcher, Uint8Array.of(byte)) !== undefined) { + matches++ + } + } + expect(matches).toBe(1) + }) + + test('returns the local end offset and keeps the unconsumed suffix', () => { + const matcher = matcherFor(SCRIPT_CLOSE_BYTES) + const prefix = encoder.encode('prefix') + const suffix = encoder.encode('') + const value = new Uint8Array( + prefix.length + SCRIPT_CLOSE_BYTES.length + suffix.length, + ) + value.set(prefix) + value.set(SCRIPT_CLOSE_BYTES, prefix.length) + value.set(suffix, prefix.length + SCRIPT_CLOSE_BYTES.length) + + const end = advanceByteMatcher(matcher, value) + expect(end).toBe(prefix.length + SCRIPT_CLOSE_BYTES.length) + expect(new TextDecoder().decode(value.subarray(end))).toBe('') + }) + + test('can find the last complete match without stopping at the first', () => { + const matcher = matcherFor(SCRIPT_CLOSE_BYTES, SCRIPT_CLOSE_ANCHOR_INDEX) + const value = encoder.encode('
    ') + + const end = advanceByteMatcher(matcher, value, 0, true) + expect(new TextDecoder().decode(value.subarray(0, end))).toBe( + '
    ', + ) + }) + + test.each([ + [ + 'router boundary', + HYDRATION_SCRIPT_BOUNDARY_BYTES, + HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX, + ], + ['script close', SCRIPT_CLOSE_BYTES, SCRIPT_CLOSE_ANCHOR_INDEX], + ])('%s satisfies the matcher invariants', (_, pattern, anchorIndex) => { + expect(pattern.length).toBeGreaterThan(0) + expect(pattern.indexOf(pattern[0]!, 1)).toBe(-1) + expect(anchorIndex).toBeGreaterThanOrEqual(0) + expect(anchorIndex).toBeLessThan(pattern.length) + }) + + test.each(['one chunk', 'split after the old overlapping prefix'])( + 'ignores marker text without the fixed semicolon in %s', + (shape) => { + const markerAndClose = HYDRATION_SCRIPT_BOUNDARY_BYTES.subarray(1) + const value = new Uint8Array(24 + markerAndClose.length - 1) + value.set(markerAndClose.subarray(0, 24)) + value.set(markerAndClose.subarray(1), 24) + const chunks = + shape === 'one chunk' + ? [value] + : [value.subarray(0, 24), value.subarray(24)] + const matcher = matcherFor( + HYDRATION_SCRIPT_BOUNDARY_BYTES, + HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX, + ) + + let consumed = 0 + let matchEnd: number | undefined + for (const chunk of chunks) { + const localEnd = advanceByteMatcher(matcher, chunk) + if (localEnd !== undefined) { + matchEnd = consumed + localEnd + } + consumed += chunk.length + } + + expect(matchEnd).toBeUndefined() + }, + ) + + test.each(['one chunk', 'split before the valid boundary'])( + 'restarts at a valid boundary after a near match in %s', + (shape) => { + const nearMatch = HYDRATION_SCRIPT_BOUNDARY_BYTES.subarray(0, 12) + const value = new Uint8Array( + nearMatch.length + HYDRATION_SCRIPT_BOUNDARY_BYTES.length, + ) + value.set(nearMatch) + value.set(HYDRATION_SCRIPT_BOUNDARY_BYTES, nearMatch.length) + const chunks = + shape === 'one chunk' + ? [value] + : [ + value.subarray(0, nearMatch.length), + value.subarray(nearMatch.length), + ] + const matcher = matcherFor( + HYDRATION_SCRIPT_BOUNDARY_BYTES, + HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX, + ) + + let consumed = 0 + let matchEnd: number | undefined + for (const chunk of chunks) { + const localEnd = advanceByteMatcher(matcher, chunk) + if (localEnd !== undefined) { + matchEnd = consumed + localEnd + } + consumed += chunk.length + } + + expect(matchEnd).toBe(value.length) + }, + ) + + test('reset drops an incomplete match', () => { + const matcher = matcherFor(SCRIPT_CLOSE_BYTES) + expect( + advanceByteMatcher(matcher, SCRIPT_CLOSE_BYTES.subarray(0, 5)), + ).toBeUndefined() + matcher.matched = 0 + expect( + advanceByteMatcher(matcher, SCRIPT_CLOSE_BYTES.subarray(5)), + ).toBeUndefined() + }) +}) + +describe('SSR exact byte helpers', () => { + test('scanner boundary is the exact end of the emitted script', () => { + expect(HYDRATION_SCRIPT_BOUNDARY_SUFFIX.endsWith(SCRIPT_CLOSE)).toBe(true) + expect( + HYDRATION_SCRIPT_BOUNDARY_SOURCE.endsWith( + HYDRATION_SCRIPT_BOUNDARY_SUFFIX.slice(0, -SCRIPT_CLOSE.length), + ), + ).toBe(true) + expect(HYDRATION_SCRIPT_BOUNDARY_BYTES).toEqual( + encoder.encode(HYDRATION_SCRIPT_BOUNDARY_SUFFIX), + ) + }) + + test('anchors document-close scans on the uncommon y byte', () => { + expect(DOCUMENT_CLOSE_ANCHOR_INDEX).toBe(DOCUMENT_CLOSE.indexOf('y')) + }) + + test('finds a complete sequence without decoding or copying', () => { + const prefix = encoder.encode('abc') + const value = new Uint8Array( + prefix.length + DOCUMENT_CLOSE_BYTES.length + 1, + ) + value.set(prefix) + value.set(DOCUMENT_CLOSE_BYTES, prefix.length) + value[value.length - 1] = 120 + + expect(findExactBytes(value, DOCUMENT_CLOSE_BYTES)).toBe(prefix.length) + expect(findExactBytes(value, DOCUMENT_CLOSE_BYTES, prefix.length + 1)).toBe( + -1, + ) + }) + + test('reports every incomplete document-close suffix', () => { + for (let length = 1; length < DOCUMENT_CLOSE_BYTES.length; length++) { + const prefix = encoder.encode('application') + const value = new Uint8Array(prefix.length + length) + value.set(prefix) + value.set(DOCUMENT_CLOSE_BYTES.subarray(0, length), prefix.length) + + expect(getExactBytesPrefixAtEnd(value, DOCUMENT_CLOSE_BYTES)).toBe( + prefix.length, + ) + } + }) + + test('uses the longest suffix when the pattern prefix overlaps', () => { + const pattern = encoder.encode('abab') + const value = encoder.encode('xxaba') + expect(getExactBytesPrefixAtEnd(value, pattern)).toBe(2) + }) + + test('returns no suffix for a final mismatch', () => { + expect( + getExactBytesPrefixAtEnd( + encoder.encode('application'), + SCRIPT_CLOSE_BYTES, + ), + ).toBeUndefined() + }) +}) diff --git a/packages/router-core/tests/hydrate.test.ts b/packages/router-core/tests/hydrate.test.ts index 3db2c1270f..37685b48ef 100644 --- a/packages/router-core/tests/hydrate.test.ts +++ b/packages/router-core/tests/hydrate.test.ts @@ -1,9 +1,38 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' -import { BaseRootRoute, BaseRoute, RouterCore, notFound } from '../src' +import { + BaseRootRoute, + BaseRoute, + _getAssetMatches, + createSerializationAdapter, + isNotFound, + notFound, +} from '../src' import { hydrate } from '../src/ssr/client' +import { dehydrateSsrMatchId } from '../src/ssr/ssr-match-id' +import { attachRouterServerSsrUtils } from '../src/ssr/ssr-server' +import { createTestRouter, dehydrateToBootstrap } from './routerTestUtils' +import type { AnyRouteMatch, AnyRouter, LocationRewrite } from '../src' +import type { ServerManifest } from '../src/manifest' import type { TsrSsrGlobal } from '../src/ssr/types' -import type { AnyRouteMatch } from '../src' + +const testManifest: ServerManifest = { + routes: {}, +} + +function createMockBootstrap( + router?: NonNullable, +): TsrSsrGlobal { + return { + router, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } +} describe('hydrate', () => { let mockWindow: { $_TSR?: TsrSsrGlobal } @@ -11,17 +40,13 @@ describe('hydrate', () => { let mockHead: any beforeEach(() => { - // Reset global window mock mockWindow = {} - ;(global as any).window = mockWindow + vi.stubGlobal('window', mockWindow) - // Reset mock head function mockHead = vi.fn() const history = createMemoryHistory({ initialEntries: ['/'] }) - const rootRoute = new BaseRootRoute({}) - const indexRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/', @@ -30,241 +55,782 @@ describe('hydrate', () => { head: mockHead, }) - const otherRoute = new BaseRoute({ - getParentRoute: () => indexRoute, - path: '/other', - component: () => 'Other', + mockRouter = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + isServer: false, }) - - const routeTree = rootRoute.addChildren([ - indexRoute.addChildren([otherRoute]), - ]) - - mockRouter = new RouterCore({ routeTree, history, isServer: true }) }) afterEach(() => { - vi.resetAllMocks() - delete (global as any).window + vi.restoreAllMocks() + vi.unstubAllGlobals() }) - it('should throw error if window.$_TSR is not available', async () => { - await expect(hydrate(mockRouter)).rejects.toThrow( + it.each([ + [ + 'window.$_TSR', + () => {}, 'Expected to find bootstrap data on window.$_TSR, but we did not. Please file an issue!', - ) - }) - - it('should throw error if window.$_TSR.router is not available', async () => { - mockWindow.$_TSR = { - c: vi.fn(), - p: vi.fn(), - buffer: [], - initialized: false, - // router is missing - } as any - - await expect(hydrate(mockRouter)).rejects.toThrow( + ], + [ + 'window.$_TSR.router', + () => { + mockWindow.$_TSR = createMockBootstrap() + }, 'Expected to find a dehydrated data on window.$_TSR.router, but we did not. Please file an issue!', - ) - }) + ], + ])( + 'throws a diagnostic when %s is unavailable', + async (_, setup, message) => { + setup() - it('should initialize serialization adapters when provided', async () => { - const mockSerializer = { - key: 'testAdapter', - fromSerializable: vi.fn(), - toSerializable: vi.fn(), - test: vi.fn().mockReturnValue(true), - '~types': { - input: {}, - output: {}, - extends: {}, - }, - } + await expect(hydrate(mockRouter)).rejects.toThrow(message) + }, + ) - mockRouter.options.serializationAdapters = [mockSerializer] - - const mockMatches = [{ id: '/', routeId: '/', index: 0, _nonReactive: {} }] - mockRouter.matchRoutes = vi.fn().mockReturnValue(mockMatches) - mockRouter.state.matches = mockMatches - - const mockBuffer = [vi.fn(), vi.fn()] - mockWindow.$_TSR = { - router: { - manifest: { routes: {} }, - dehydratedData: {}, - lastMatchId: '/', - matches: [], - }, - h: vi.fn(), - e: vi.fn(), - c: vi.fn(), - p: vi.fn(), - buffer: mockBuffer, - initialized: false, - } - - await hydrate(mockRouter) - - expect(mockWindow.$_TSR.t).toBeInstanceOf(Map) - expect(mockWindow.$_TSR.t?.get('testAdapter')).toBe( - mockSerializer.fromSerializable, - ) - expect(mockBuffer[0]).toHaveBeenCalled() - expect(mockBuffer[1]).toHaveBeenCalled() - expect(mockWindow.$_TSR.initialized).toBe(true) - }) - - it('should handle empty serialization adapters', async () => { - mockRouter.options.serializationAdapters = [] - - mockWindow.$_TSR = { - router: { - manifest: { routes: {} }, - dehydratedData: {}, - lastMatchId: '/', - matches: [], - }, - h: vi.fn(), - e: vi.fn(), - c: vi.fn(), - p: vi.fn(), - buffer: [], - initialized: false, - } - - await hydrate(mockRouter) - - expect(mockWindow.$_TSR.t).toBeUndefined() - expect(mockWindow.$_TSR.initialized).toBe(true) - }) - - it('should set manifest in router.ssr', async () => { - const testManifest = { routes: {} } - mockWindow.$_TSR = { - router: { - manifest: testManifest, - dehydratedData: {}, - lastMatchId: '/', - matches: [], - }, - h: vi.fn(), - e: vi.fn(), - c: vi.fn(), - p: vi.fn(), - buffer: [], - initialized: false, - } - - await hydrate(mockRouter) - - expect(mockRouter.ssr).toEqual({ + it('clears hydration preflight when the custom hydrate hook rejects', async () => { + const error = new Error('custom hydration failed') + mockWindow.$_TSR = createMockBootstrap({ manifest: testManifest, + dehydratedData: {}, + matches: [], + }) + mockRouter.options.hydrate = () => Promise.reject(error) + + await expect(hydrate(mockRouter)).rejects.toBe(error) + + expect(mockRouter._preflight).toBeUndefined() + }) + + it('clears hydration preflight when location reconstruction rejects', async () => { + const error = new Error('location parsing failed') + mockWindow.$_TSR = createMockBootstrap({ + manifest: testManifest, + dehydratedData: {}, + matches: [], + }) + mockRouter.options.hydrate = () => { + mockRouter.options.parseSearch = () => { + throw error + } + } + + await expect(hydrate(mockRouter)).rejects.toBe(error) + + expect(mockRouter._preflight).toBeUndefined() + }) + + it('round-trips the manifest and matches without running client loaders', async () => { + const serverRootRoute = new BaseRootRoute({}) + const serverProductRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/products/$productId', + loader: ({ params }) => ({ + productId: params.productId, + source: 'server', + }), + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([serverProductRoute]), + history: createMemoryHistory({ initialEntries: ['/products/42'] }), + isServer: true, + }) + const manifest: ServerManifest = { + routes: { + [serverRootRoute.id]: { preloads: ['/assets/root.js'] }, + [serverProductRoute.id]: { preloads: ['/assets/product.js'] }, + }, + } + + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter, manifest) + + const serverMatches = serverRouter.state.matches + const clientLoader = vi.fn(() => ({ + productId: 'client', + source: 'client', + })) + const clientRootRoute = new BaseRootRoute({}) + const clientProductRoute = new BaseRoute({ + getParentRoute: () => clientRootRoute, + path: '/products/$productId', + loader: clientLoader, + }) + const clientRouter = createTestRouter({ + routeTree: clientRootRoute.addChildren([clientProductRoute]), + history: createMemoryHistory({ initialEntries: ['/products/42'] }), + isServer: false, + }) + + await hydrate(clientRouter) + + expect(clientRouter.ssr?.manifest).toEqual(manifest) + expect( + clientRouter.state.matches.map((match) => ({ + id: match.id, + routeId: match.routeId, + status: match.status, + loaderData: match.loaderData, + ssr: match.ssr, + })), + ).toEqual( + serverMatches.map((match) => ({ + id: match.id, + routeId: match.routeId, + status: match.status, + loaderData: match.loaderData, + ssr: match.ssr, + })), + ) + expect(clientRouter.state.matches.at(-1)?.loaderData).toEqual({ + productId: '42', + source: 'server', + }) + expect(clientLoader).not.toHaveBeenCalled() + }) + + it('inlines match ids that are valid HTML and not path-like', async () => { + const rootRoute = new BaseRootRoute({}) + const productRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/products/$productId', + loader: () => 'product', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([productRoute]), + history: createMemoryHistory({ initialEntries: ['/products/42'] }), + isServer: true, + }) + attachRouterServerSsrUtils({ router, manifest: testManifest }) + + try { + await router.load() + await router.serverSsr!.dehydrate() + const html = router + .serverSsr!.takeInitialHydrationScriptTags()! + .before.map((script) => script.children) + .join('') + + // Control characters other than whitespace are parse errors in the HTML + // input stream. + // eslint-disable-next-line no-control-regex + expect(html).not.toMatch(/[\x00-\x08\x0b\x0e-\x1f\x7f-\x9f]/) + // A char above U+00FF would widen the whole HTML string to two bytes. + expect(html).not.toMatch(/[\u0100-\uffff]/) + expect(html).not.toContain('/products/42') + } finally { + router.serverSsr?.cleanup() + } + }) + + it('restores undefined loader data without serializing it', async () => { + const serverRootRoute = new BaseRootRoute({}) + const serverRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/page', + loader: () => undefined, + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([serverRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: true, + }) + + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter, testManifest) + expect(mockWindow.$_TSR.router?.matches[1]).not.toHaveProperty('l') + + const clientLoader = vi.fn(() => undefined) + const clientRootRoute = new BaseRootRoute({}) + const clientRoute = new BaseRoute({ + getParentRoute: () => clientRootRoute, + path: '/page', + loader: clientLoader, + }) + const clientRouter = createTestRouter({ + routeTree: clientRootRoute.addChildren([clientRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + + await hydrate(clientRouter) + + expect(clientLoader).not.toHaveBeenCalled() + const match = clientRouter.state.matches[1] + expect(match).toMatchObject({ + routeId: clientRoute.id, + status: 'success', + }) + expect(match).toHaveProperty('loaderData', undefined) + }) + + it('preserves successful undefined loader data when selecting a later failure', async () => { + const serverRootRoute = new BaseRootRoute({}) + const serverParentRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/parent', + loader: () => undefined, + }) + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverParentRoute, + path: '/child', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverParentRoute.addChildren([serverChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter, testManifest) + expect(mockWindow.$_TSR.router?.matches[1]).not.toHaveProperty('l') + + const parentError = new Error('parent reload failed') + const childError = new Error('child guard failed') + const clientRootRoute = new BaseRootRoute({}) + const clientParentRoute = new BaseRoute({ + getParentRoute: () => clientRootRoute, + path: '/parent', + loader: () => { + throw parentError + }, + errorComponent: () => null, + }) + const clientChildRoute = new BaseRoute({ + getParentRoute: () => clientParentRoute, + path: '/child', + beforeLoad: () => { + throw childError + }, + errorComponent: () => null, + }) + const clientRouter = createTestRouter({ + routeTree: clientRootRoute.addChildren([ + clientParentRoute.addChildren([clientChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: false, + }) + + await hydrate(clientRouter) + await clientRouter.invalidate() + + expect( + clientRouter.state.matches.find( + (match) => match.routeId === clientParentRoute.id, + ), + ).toMatchObject({ status: 'success', error: undefined }) + expect( + clientRouter.state.matches.find( + (match) => match.routeId === clientChildRoute.id, + ), + ).toMatchObject({ status: 'error', error: childError }) + }) + + it.each([ + ['mismatched', dehydrateSsrMatchId('/different-match')], + ['missing', undefined], + ['non-string', 42], + ])( + 'does not attach dehydrated data with a %s match identity', + async (_, identity) => { + const serverRootRoute = new BaseRootRoute({}) + const serverProductRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/products/$productId', + loader: () => 'server data', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([serverProductRoute]), + history: createMemoryHistory({ initialEntries: ['/products/42'] }), + isServer: true, + }) + + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter, testManifest) + mockWindow.$_TSR.router!.matches[1]!.i = identity as string + + const clientLoader = vi.fn(() => 'client data') + const clientRootRoute = new BaseRootRoute({}) + const clientProductRoute = new BaseRoute({ + getParentRoute: () => clientRootRoute, + path: '/products/$productId', + loader: clientLoader, + }) + const clientRouter = createTestRouter({ + routeTree: clientRootRoute.addChildren([clientProductRoute]), + history: createMemoryHistory({ initialEntries: ['/products/42'] }), + isServer: false, + }) + + await hydrate(clientRouter) + + const pendingMatch = clientRouter.state.matches.at(-1) + expect(pendingMatch).toMatchObject({ + routeId: clientProductRoute.id, + status: 'pending', + }) + expect(pendingMatch).not.toHaveProperty('loaderData') + expect(clientLoader).not.toHaveBeenCalled() + + await clientRouter.load() + + expect(clientRouter.state.matches.at(-1)).toMatchObject({ + routeId: clientProductRoute.id, + status: 'success', + loaderData: 'client data', + }) + expect(clientLoader).toHaveBeenCalledTimes(1) + }, + ) + + it('keeps an earlier data-only boundary when a descendant id mismatches', async () => { + const serverRootRoute = new BaseRootRoute({}) + const serverParentRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/parent', + ssr: 'data-only', + loader: () => 'server parent data', + }) + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverParentRoute, + path: '/child', + loader: () => 'server child data', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverParentRoute.addChildren([serverChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter, testManifest) + mockWindow.$_TSR.router!.matches[2]!.i = dehydrateSsrMatchId( + '/different-child-match', + ) + + const childContext = vi.fn(() => ({ source: 'client child context' })) + const clientRootRoute = new BaseRootRoute({}) + const clientParentLoader = vi.fn(() => 'client parent data') + const clientParentRoute = new BaseRoute({ + getParentRoute: () => clientRootRoute, + path: '/parent', + ssr: 'data-only', + loader: clientParentLoader, + }) + const clientChildRoute = new BaseRoute({ + getParentRoute: () => clientParentRoute, + path: '/child', + context: childContext, + loader: () => 'client child data', + }) + const clientRouter = createTestRouter({ + routeTree: clientRootRoute.addChildren([ + clientParentRoute.addChildren([clientChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: false, + }) + + await hydrate(clientRouter) + + expect(clientRouter.state.matches[1]).toMatchObject({ + routeId: clientParentRoute.id, + status: 'pending', + loaderData: 'server parent data', + }) + expect(childContext).not.toHaveBeenCalled() + expect(clientParentLoader).not.toHaveBeenCalled() + expect( + _getAssetMatches(clientRouter.state.matches).map( + (match) => match.routeId, + ), + ).toEqual([clientRootRoute.id, clientParentRoute.id]) + + await clientRouter.load() + + expect(childContext).toHaveBeenCalledTimes(1) + expect(clientParentLoader).not.toHaveBeenCalled() + expect(clientRouter.state.matches[1]).toMatchObject({ + routeId: clientParentRoute.id, + status: 'success', + loaderData: 'server parent data', + }) + expect(clientRouter.state.matches[2]).toMatchObject({ + routeId: clientChildRoute.id, + status: 'success', + loaderData: 'client child data', }) }) - it('should hydrate matches', async () => { - const mockMatches = [ - { - id: '/', - routeId: '/', - index: 0, - ssr: undefined, - _nonReactive: {}, - }, - { - id: '/other', - routeId: '/other', - index: 1, - ssr: undefined, - _nonReactive: {}, - }, - ] + it('rejects a longer non-terminal server lane before attaching its data', async () => { + const serverRootRoute = new BaseRootRoute({}) + const serverParentRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/parent', + loader: () => 'server data', + }) + const serverIndexRoute = new BaseRoute({ + getParentRoute: () => serverParentRoute, + path: '/', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverParentRoute.addChildren([serverIndexRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent'] }), + isServer: true, + }) - const dehydratedMatches = [ + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter, testManifest) + expect(mockWindow.$_TSR.router?.matches).toHaveLength(3) + + const clientLoader = vi.fn(() => 'client data') + const clientRootRoute = new BaseRootRoute({}) + const clientParentRoute = new BaseRoute({ + getParentRoute: () => clientRootRoute, + path: '/parent', + loader: clientLoader, + }) + const clientRouter = createTestRouter({ + routeTree: clientRootRoute.addChildren([clientParentRoute]), + history: createMemoryHistory({ initialEntries: ['/parent'] }), + isServer: false, + }) + + await hydrate(clientRouter) + + expect(clientRouter.state.resolvedLocation).toBeUndefined() + expect(clientRouter.state.matches.at(-1)).not.toHaveProperty('loaderData') + expect(clientLoader).not.toHaveBeenCalled() + + await clientRouter.load() + + expect(clientRouter.state.matches.at(-1)).toMatchObject({ + routeId: clientParentRoute.id, + status: 'success', + loaderData: 'client data', + }) + expect(clientLoader).toHaveBeenCalledTimes(1) + }) + + it('round-trips adapted loader data through the bootstrap protocol', async () => { + class AdaptedValue { + constructor(readonly value: string) {} + } + + const adapter = createSerializationAdapter({ + key: 'adapted-value', + test: (value: unknown): value is AdaptedValue => + value instanceof AdaptedValue, + toSerializable: (value: AdaptedValue) => value.value, + fromSerializable: (value: string) => new AdaptedValue(value), + }) + + const serverRootRoute = new BaseRootRoute({}) + const serverIndexRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/', + loader: () => new AdaptedValue('server loader data'), + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([serverIndexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + serverRouter.options.serializationAdapters = [adapter] + + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter, testManifest) + + const clientLoader = vi.fn(() => new AdaptedValue('client loader data')) + const clientRootRoute = new BaseRootRoute({}) + const clientIndexRoute = new BaseRoute({ + getParentRoute: () => clientRootRoute, + path: '/', + loader: clientLoader, + }) + const clientRouter = createTestRouter({ + routeTree: clientRootRoute.addChildren([clientIndexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: false, + }) + clientRouter.options.serializationAdapters = [adapter] + + await hydrate(clientRouter) + + const loaderData = clientRouter.state.matches.at(-1)?.loaderData + expect(loaderData).toBeInstanceOf(AdaptedValue) + expect(loaderData).toEqual(new AdaptedValue('server loader data')) + expect(clientLoader).not.toHaveBeenCalled() + }) + + it('round-trips a server root notFound lane as _notFound', async () => { + const serverRootRoute = new BaseRootRoute({ + notFoundComponent: () => 'Not Found', + }) + const serverMissingRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/missing', + loader: () => { + throw notFound({ data: { source: 'server loader' } }) + }, + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([serverMissingRoute]), + history: createMemoryHistory({ initialEntries: ['/missing'] }), + isServer: true, + }) + + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter, testManifest) + + expect(serverRouter.state.matches).toHaveLength(2) + expect(serverRouter.state.matches[0]).toMatchObject({ + routeId: serverRootRoute.id, + status: 'success', + _notFound: true, + }) + expect(isNotFound(serverRouter.state.matches[0]?.error)).toBe(true) + + const clientLoader = vi.fn(() => 'client data') + const clientRootRoute = new BaseRootRoute({ + notFoundComponent: () => 'Not Found', + }) + const clientMissingRoute = new BaseRoute({ + getParentRoute: () => clientRootRoute, + path: '/missing', + loader: clientLoader, + }) + const clientRouter = createTestRouter({ + routeTree: clientRootRoute.addChildren([clientMissingRoute]), + history: createMemoryHistory({ initialEntries: ['/missing'] }), + isServer: false, + }) + + await hydrate(clientRouter) + + expect(clientRouter.state.matches).toHaveLength(2) + expect(clientRouter.state.matches[0]).toMatchObject({ + routeId: clientRootRoute.id, + status: 'success', + _notFound: true, + }) + expect(clientRouter.state.matches[1]).toMatchObject({ + routeId: clientMissingRoute.id, + status: 'pending', + }) + expect(isNotFound(clientRouter.state.matches[0]?.error)).toBe(true) + expect(clientRouter.state.matches[0]?.error).toEqual( + expect.objectContaining({ data: { source: 'server loader' } }), + ) + expect(clientLoader).not.toHaveBeenCalled() + }) + + it('preserves a client-matched _notFound when a shell payload omits the flag', async () => { + const serverRootRoute = new BaseRootRoute({ + notFoundComponent: () => 'Not Found', + }) + const serverKnownRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/known', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([serverKnownRoute]), + history: createMemoryHistory({ initialEntries: ['/known'] }), + isServer: true, + isShell: true, + }) + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter, testManifest) + + const clientRootRoute = new BaseRootRoute({ + notFoundComponent: () => 'Not Found', + }) + const clientKnownRoute = new BaseRoute({ + getParentRoute: () => clientRootRoute, + path: '/known', + }) + const clientRouter = createTestRouter({ + routeTree: clientRootRoute.addChildren([clientKnownRoute]), + history: createMemoryHistory({ initialEntries: ['/does-not-exist'] }), + isServer: false, + }) + + await hydrate(clientRouter) + + expect(clientRouter.state.matches).toHaveLength(1) + expect(clientRouter.state.matches[0]).toMatchObject({ + routeId: clientRootRoute.id, + status: 'success', + _notFound: true, + }) + }) + + it('applies round-tripped custom hydration before matching a rewritten location', async () => { + const rewrite: LocationRewrite = { + input: ({ url }) => { + if (url.pathname === '/public') { + url.pathname = '/internal' + } + return url + }, + output: ({ url }) => { + if (url.pathname === '/internal') { + url.pathname = '/public' + } + return url + }, + } + + const serverRootRoute = new BaseRootRoute({}) + const serverInternalRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/internal', + loader: () => 'server internal data', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([serverInternalRoute]), + history: createMemoryHistory({ initialEntries: ['/public'] }), + rewrite, + dehydrate: () => ({ rewrite: true }), + isServer: true, + }) + + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter, testManifest) + + const clientLoader = vi.fn(() => 'client internal data') + const clientRootRoute = new BaseRootRoute({}) + const clientInternalRoute = new BaseRoute({ + getParentRoute: () => clientRootRoute, + path: '/internal', + loader: clientLoader, + }) + const customHydrate = vi.fn((dehydrated: { rewrite?: boolean }) => { + if (dehydrated.rewrite) { + clientRouter.update({ rewrite }) + } + }) + const clientRouter: AnyRouter = createTestRouter({ + routeTree: clientRootRoute.addChildren([clientInternalRoute]), + history: createMemoryHistory({ initialEntries: ['/public'] }), + hydrate: customHydrate, + isServer: false, + }) + + await hydrate(clientRouter) + + expect(customHydrate).toHaveBeenCalledOnce() + expect(customHydrate).toHaveBeenCalledWith({ rewrite: true }) + expect(clientRouter.state.location.pathname).toBe('/internal') + expect(clientRouter.state.location.publicHref).toBe('/public') + expect( + clientRouter.state.matches.map((match: AnyRouteMatch) => ({ + routeId: match.routeId, + status: match.status, + loaderData: match.loaderData, + })), + ).toEqual([ { - i: '/', - l: { indexData: 'server-data' }, + routeId: clientRootRoute.id, + status: 'success', + loaderData: undefined, + }, + { + routeId: clientInternalRoute.id, + status: 'success', + loaderData: 'server internal data', + }, + ]) + expect(clientLoader).not.toHaveBeenCalled() + }) + + it('logs and swallows a notFound thrown by a hydrated route head', async () => { + const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + mockHead.mockImplementation(() => { + throw notFound({ data: { source: 'index head' } }) + }) + const matched = mockRouter.matchRoutes(mockRouter.stores.location.get()) + + mockWindow.$_TSR = createMockBootstrap({ + manifest: testManifest, + dehydratedData: {}, + matches: matched.map((match: AnyRouteMatch) => ({ + i: dehydrateSsrMatchId(match.id), s: 'success' as const, ssr: true, u: Date.now(), - }, - ] - - mockRouter.matchRoutes = vi.fn().mockReturnValue(mockMatches) - mockRouter.state.matches = mockMatches - - mockWindow.$_TSR = { - router: { - manifest: { routes: {} }, - dehydratedData: {}, - lastMatchId: '/', - matches: dehydratedMatches, - }, - h: vi.fn(), - e: vi.fn(), - c: vi.fn(), - p: vi.fn(), - buffer: [], - initialized: false, - } - - await hydrate(mockRouter) - - const { id, loaderData, ssr, status } = mockMatches[0] as AnyRouteMatch - expect(id).toBe('/') - expect(loaderData).toEqual({ indexData: 'server-data' }) - expect(status).toBe('success') - expect(ssr).toBe(true) - }) - - it('should handle errors during route context hydration', async () => { - const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) - mockHead.mockImplementation(() => { - throw notFound() + })), }) - const mockMatches = [ - { id: '/', routeId: '/', index: 0, ssr: true, _nonReactive: {} }, - ] - - mockRouter.matchRoutes = vi.fn().mockReturnValue(mockMatches) - mockRouter.state.matches = mockMatches - - mockWindow.$_TSR = { - router: { - manifest: { routes: {} }, - dehydratedData: {}, - lastMatchId: '/', - matches: [ - { - i: '/', - l: { data: 'test' }, - s: 'success', - ssr: true, - u: Date.now(), - }, - ], - }, - h: vi.fn(), - e: vi.fn(), - c: vi.fn(), - p: vi.fn(), - buffer: [], - initialized: false, - } - await hydrate(mockRouter) - const match = mockRouter.state.matches[0] as AnyRouteMatch - expect(match.error).toEqual({ isNotFound: true }) - + const match = mockRouter.state.matches.find( + (candidate: AnyRouteMatch) => candidate.routeId === '/', + ) as AnyRouteMatch | undefined + expect(match).toBeDefined() + expect(match?.status).toBe('success') + expect(match?.error).toBeUndefined() + expect(mockHead).toHaveBeenCalledOnce() expect(consoleSpy).toHaveBeenCalledWith( - 'NotFound error during hydration for routeId: /', expect.objectContaining({ isNotFound: true, + data: { source: 'index head' }, }), ) + }) +}) - consoleSpy.mockRestore() +describe('createSerializationAdapter key validation', () => { + function createAdapter(key: string) { + return createSerializationAdapter({ + key, + test: (value): value is string => typeof value === 'string', + toSerializable: (value) => value, + fromSerializable: (value) => value, + }) + } + + it('throws in development for empty or unsupported keys', () => { + for (const key of [ + '', + 'nul\0key', + 'bad"key', + 'back\\slash', + 'lt createAdapter(key)).toThrowError( + /createSerializationAdapter: key .* is invalid/s, + ) + } + }) + + it('accepts a key that Seroval preserves verbatim', () => { + expect(() => createAdapter('safe-key/v1.0_$-')).not.toThrow() + }) + + it('does not inspect the key in production', () => { + vi.stubEnv('NODE_ENV', 'production') + try { + const options = { + get key(): string { + throw new Error('production key was inspected') + }, + test: (value: unknown): value is string => typeof value === 'string', + toSerializable: (value: string) => value, + fromSerializable: (value: string) => value, + } + + expect(createSerializationAdapter(options)).toBe(options) + } finally { + vi.unstubAllEnvs() + } }) }) diff --git a/packages/router-core/tests/hydrated-stay-match-data.test.ts b/packages/router-core/tests/hydrated-stay-match-data.test.ts new file mode 100644 index 0000000000..6e269e86c3 --- /dev/null +++ b/packages/router-core/tests/hydrated-stay-match-data.test.ts @@ -0,0 +1,135 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { hydrate } from '../src/ssr/client' +import { createTestRouter, dehydrateToBootstrap } from './routerTestUtils' +import type { TsrSsrGlobal } from '../src/ssr/types' +import type { ServerManifest } from '../src/manifest' + +const testManifest: ServerManifest = { routes: {} } + +describe('hydrated stay match data preservation', () => { + let mockWindow: { $_TSR?: TsrSsrGlobal } + + beforeEach(() => { + mockWindow = {} + vi.stubGlobal('window', mockWindow) + }) + + afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() + }) + + it('keeps server loader data while refreshing context on client navigation', async () => { + const serverRootBeforeLoad = vi.fn(() => ({ auth: 'server' })) + const serverRootLoader = vi.fn(() => ({ root: 'server' })) + const serverARouteLoader = vi.fn(() => 'a server data') + const serverRootRoute = new BaseRootRoute({ + beforeLoad: serverRootBeforeLoad, + loader: serverRootLoader, + }) + const serverARoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/a', + ssr: false, + loader: serverARouteLoader, + }) + const serverBRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/b', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([serverARoute, serverBRoute]), + history: createMemoryHistory({ initialEntries: ['/a'] }), + isServer: true, + }) + + const bootstrap = await dehydrateToBootstrap(serverRouter, testManifest) + + expect(serverRootBeforeLoad).toHaveBeenCalledTimes(1) + expect(serverRootLoader).toHaveBeenCalledTimes(1) + expect(serverARouteLoader).not.toHaveBeenCalled() + expect(serverRouter.state.matches[0]).toMatchObject({ + routeId: serverRootRoute.id, + status: 'success', + context: { auth: 'server' }, + loaderData: { root: 'server' }, + }) + const rootBeforeLoad = vi.fn(() => ({ auth: 'client' })) + const rootLoader = vi.fn(() => ({ root: 'client' })) + const history = createMemoryHistory({ initialEntries: ['/a'] }) + + const rootRoute = new BaseRootRoute({ + beforeLoad: rootBeforeLoad, + loader: rootLoader, + }) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + ssr: false, + loader: () => 'a client data', + }) + const bRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/b', + loader: () => 'b client data', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([aRoute, bRoute]), + history, + isServer: false, + }) + + mockWindow.$_TSR = bootstrap + + await hydrate(router) + + // Hydration adopts the server root before client loads can re-enter beforeLoad. + expect(rootBeforeLoad).not.toHaveBeenCalled() + expect(rootLoader).not.toHaveBeenCalled() + expect( + router.state.matches.find((m) => m.routeId === rootRoute.id), + ).toMatchObject({ + context: { auth: 'server' }, + loaderData: { root: 'server' }, + }) + + await router.load() + + expect( + router.state.matches.find((m) => m.routeId === aRoute.id)?.loaderData, + ).toBe('a client data') + expect(router.state.location.pathname).toBe('/a') + expect(router.state.resolvedLocation?.pathname).toBe('/a') + expect(rootLoader).not.toHaveBeenCalled() + expect( + router.state.matches.find((m) => m.routeId === rootRoute.id), + ).toMatchObject({ + context: { auth: 'server' }, + loaderData: { root: 'server' }, + }) + + // The root stay match refreshes beforeLoad context without rerunning its loader. + await router.navigate({ to: '/b' }) + + expect( + router.state.matches.find((m) => m.routeId === bRoute.id)?.loaderData, + ).toBe('b client data') + expect(router.state.location.pathname).toBe('/b') + expect(router.state.resolvedLocation?.pathname).toBe('/b') + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + bRoute.id, + ]) + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(rootLoader).not.toHaveBeenCalled() + expect( + router.state.matches.find((m) => m.routeId === rootRoute.id), + ).toMatchObject({ + context: { auth: 'client' }, + loaderData: { root: 'server' }, + }) + }) +}) diff --git a/packages/router-core/tests/hydration-asset-context-order.test.ts b/packages/router-core/tests/hydration-asset-context-order.test.ts new file mode 100644 index 0000000000..014e338b32 --- /dev/null +++ b/packages/router-core/tests/hydration-asset-context-order.test.ts @@ -0,0 +1,75 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { hydrate } from '../src/ssr/client' +import { createTestRouter, dehydrateToBootstrap } from './routerTestUtils' +import type { AnyRouteMatch } from '../src' +import type { ServerManifest } from '../src/manifest' +import type { TsrSsrGlobal } from '../src/ssr/types' + +const testManifest: ServerManifest = { routes: {} } + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +test('hydration reconstructs every match context before ancestor head reads the lane', async () => { + const serverBeforeLoad = vi.fn(() => ({ + user: 'server authenticated user', + })) + const serverRootRoute = new BaseRootRoute({}) + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/child', + beforeLoad: serverBeforeLoad, + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([serverChildRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: true, + }) + + const bootstrap = await dehydrateToBootstrap(serverRouter, testManifest) + + expect(serverBeforeLoad).toHaveBeenCalledTimes(1) + expect(serverRouter.state.matches.at(-1)?.context).toMatchObject({ + user: 'server authenticated user', + }) + let childContextSeenByRootHead: unknown + const rootHead = vi.fn(({ matches }: { matches: Array }) => { + childContextSeenByRootHead = matches[1]?.context + return { meta: [{ title: 'hydrated' }] } + }) + const clientBeforeLoad = vi.fn(() => ({ user: 'client fallback' })) + const rootRoute = new BaseRootRoute({ + head: rootHead, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + beforeLoad: clientBeforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: false, + }) + + vi.stubGlobal('window', { $_TSR: bootstrap }) + + await hydrate(router) + + expect(childContextSeenByRootHead).toMatchObject({ + user: 'server authenticated user', + }) + expect(clientBeforeLoad).not.toHaveBeenCalled() + expect(rootHead).toHaveBeenCalledTimes(1) + expect(router.state.location.pathname).toBe('/child') + expect(router.state.resolvedLocation?.pathname).toBe('/child') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: childRoute.id, + context: { user: 'server authenticated user' }, + }) + expect(router.state.matches[0]?.meta).toEqual([{ title: 'hydrated' }]) +}) diff --git a/packages/router-core/tests/hydration-boundary-chunks.test.ts b/packages/router-core/tests/hydration-boundary-chunks.test.ts new file mode 100644 index 0000000000..0d5c9a0af6 --- /dev/null +++ b/packages/router-core/tests/hydration-boundary-chunks.test.ts @@ -0,0 +1,210 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, isNotFound, notFound } from '../src' +import { hydrate } from '../src/ssr/client' +import { createTestRouter, dehydrateToBootstrap } from './routerTestUtils' +import type { TsrSsrGlobal } from '../src/ssr/types' +import type { ServerManifest } from '../src/manifest' + +const testManifest: ServerManifest = { routes: {} } + +describe('hydration route chunks below a server boundary', () => { + let mockWindow: { $_TSR?: TsrSsrGlobal } + + beforeEach(() => { + mockWindow = {} + vi.stubGlobal('window', mockWindow) + }) + + afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() + }) + + test('hydrates an error boundary without requiring its normal component chunk', async () => { + const serverError = new Error('server beforeLoad failed') + const serverBeforeLoad = vi.fn(() => { + throw serverError + }) + const serverRootRoute = new BaseRootRoute({}) + const serverAppRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/app', + beforeLoad: serverBeforeLoad, + errorComponent: () => null, + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([serverAppRoute]), + history: createMemoryHistory({ initialEntries: ['/app'] }), + isServer: true, + }) + + const bootstrap = await dehydrateToBootstrap(serverRouter, testManifest) + + expect(serverBeforeLoad).toHaveBeenCalledTimes(1) + expect(serverRouter.state.location.pathname).toBe('/app') + expect(serverRouter.state.matches.map((match) => match.routeId)).toEqual([ + serverRootRoute.id, + serverAppRoute.id, + ]) + expect(serverRouter.state.matches.at(-1)).toMatchObject({ + status: 'error', + error: serverError, + }) + const transportedError = bootstrap.router?.matches.at(-1)?.e + expect(transportedError).not.toBe(serverError) + expect(transportedError).toMatchObject({ + name: serverError.name, + message: serverError.message, + }) + + const normalChunkError = new Error('normal component chunk unavailable') + const normalComponentPreload = vi.fn(() => Promise.reject(normalChunkError)) + const errorComponentPreload = vi.fn(() => Promise.resolve()) + const clientBeforeLoad = vi.fn(() => { + throw new Error('client beforeLoad should not run') + }) + const NormalComponent = Object.assign(() => null, { + preload: normalComponentPreload, + }) + const ErrorComponent = Object.assign(() => null, { + preload: errorComponentPreload, + }) + + const rootRoute = new BaseRootRoute({}) + const appRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/app', + beforeLoad: clientBeforeLoad, + component: NormalComponent, + errorComponent: ErrorComponent, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([appRoute]), + history: createMemoryHistory({ initialEntries: ['/app'] }), + isServer: false, + }) + mockWindow.$_TSR = bootstrap + + await expect(hydrate(router)).resolves.toBeUndefined() + + const appMatch = router.state.matches.find( + (match) => match.routeId === appRoute.id, + ) + expect(appMatch?.status).toBe('error') + expect(appMatch?.error).toBe(transportedError) + expect(appMatch?.error).toMatchObject({ + name: serverError.name, + message: serverError.message, + }) + expect(router.state.location.pathname).toBe('/app') + expect(router.state.resolvedLocation?.pathname).toBe('/app') + expect(clientBeforeLoad).not.toHaveBeenCalled() + expect(normalComponentPreload).not.toHaveBeenCalled() + expect(errorComponentPreload).toHaveBeenCalledTimes(1) + }) + + test.each([ + { ssr: undefined, hydratedStatus: 'notFound', resolved: true }, + { + ssr: 'data-only' as const, + hydratedStatus: 'pending', + resolved: false, + }, + ])( + 'hydrates an ancestor notFound boundary with ssr=$ssr without loading an omitted descendant chunk', + async ({ ssr, hydratedStatus, resolved }) => { + const serverRootRoute = new BaseRootRoute({}) + const serverParentRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/parent', + ssr, + notFoundComponent: () => 'not found', + }) + const serverNotFound = notFound({ routeId: serverParentRoute.id }) + const serverChildLoader = vi.fn(() => { + throw serverNotFound + }) + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverParentRoute, + path: '/child', + loader: serverChildLoader, + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverParentRoute.addChildren([serverChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + + const bootstrap = await dehydrateToBootstrap(serverRouter, testManifest) + + expect(serverChildLoader).toHaveBeenCalledTimes(1) + expect(serverRouter.state.matches.map((match) => match.routeId)).toEqual([ + serverRootRoute.id, + serverParentRoute.id, + serverChildRoute.id, + ]) + expect(serverRouter.state.matches[1]?.status).toBe('notFound') + expect(isNotFound(serverRouter.state.matches[1]?.error)).toBe(true) + const childChunkError = new Error('omitted child chunk unavailable') + const childComponentPreload = vi.fn(() => Promise.reject(childChunkError)) + const ChildComponent = Object.assign(() => null, { + preload: childComponentPreload, + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + ssr, + notFoundComponent: () => 'not found', + }) + const childLoader = vi.fn(() => { + throw new Error('client child loader should not run') + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + component: ChildComponent, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: false, + }) + mockWindow.$_TSR = bootstrap + + await expect(hydrate(router)).resolves.toBeUndefined() + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]) + expect(router.state.matches[1]?.status).toBe(hydratedStatus) + expect(isNotFound(router.state.matches[1]?.error)).toBe(true) + expect(router.state.matches[2]?.status).toBe('pending') + expect(router.state.location.pathname).toBe('/parent/child') + expect(router.state.resolvedLocation?.pathname).toBe( + resolved ? '/parent/child' : undefined, + ) + expect(childComponentPreload).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + + if (ssr === 'data-only') { + await router.load() + + expect(router.state.resolvedLocation?.pathname).toBe('/parent/child') + expect(router.state.matches[1]?.status).toBe('notFound') + expect(isNotFound(router.state.matches[1]?.error)).toBe(true) + expect(childComponentPreload).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + } + }, + ) +}) diff --git a/packages/router-core/tests/hydration-currentness.test.ts b/packages/router-core/tests/hydration-currentness.test.ts new file mode 100644 index 0000000000..03ad11998b --- /dev/null +++ b/packages/router-core/tests/hydration-currentness.test.ts @@ -0,0 +1,662 @@ +import { + afterEach, + beforeEach, + describe, + expect, + onTestFinished, + test, + vi, +} from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + _getAssetMatches, + createControlledPromise, +} from '../src' +import { hydrate } from '../src/ssr/client' +import { dehydrateSsrMatchId } from '../src/ssr/ssr-match-id' +import { createTestRouter, dehydrateToBootstrap } from './routerTestUtils' +import type { AnyRouteMatch, AnyRouter, NavigateFn } from '../src' +import type { DehydratedRouter, TsrSsrGlobal } from '../src/ssr/types' +import type { ServerManifest } from '../src/manifest' + +const testManifest: ServerManifest = { routes: {} } + +// These tests install the hydration protocol directly so client-only hooks can +// be paused at deterministic ownership boundaries. +function installHydrationPayload( + mockWindow: { $_TSR?: TsrSsrGlobal }, + matches: DehydratedRouter['matches'], +) { + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + matches, + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } +} + +/** + * Hydration asset work is another private lane generation. If a public + * navigation commits while an old hydration head is pending, the hydration + * continuation must not execute more old-lane hooks or mark its captured + * location as resolved. + */ +describe('hydration asset currentness', () => { + let mockWindow: { $_TSR?: TsrSsrGlobal } + + beforeEach(() => { + mockWindow = {} + vi.stubGlobal('window', mockWindow) + }) + + afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() + }) + + test('shell hydration preserves the complete lane and its first pending boundary', async () => { + const childLoader = vi.fn(() => 'client data') + const rootRoute = new BaseRootRoute({}) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + ssr: false, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + ssr: true, + u: Date.now(), + }, + ]) + + await hydrate(router) + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + childRoute.id, + ]) + expect(router.state.matches[1]).toMatchObject({ + routeId: childRoute.id, + status: 'pending', + ssr: false, + }) + expect(router.state.resolvedLocation).toBeUndefined() + expect(childLoader).not.toHaveBeenCalled() + }) + + test('includes an identity-verified ssr:false boundary in a data-only asset prefix', async () => { + const serverChildLoader = vi.fn(() => 'server child data') + const serverRootRoute = new BaseRootRoute({}) + const serverParentRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/parent', + ssr: 'data-only', + }) + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverParentRoute, + path: '/child', + ssr: false, + loader: serverChildLoader, + }) + const serverTailRoute = new BaseRoute({ + getParentRoute: () => serverChildRoute, + path: '/tail', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverParentRoute.addChildren([ + serverChildRoute.addChildren([serverTailRoute]), + ]), + ]), + history: createMemoryHistory({ + initialEntries: ['/parent/child/tail'], + }), + isServer: true, + }) + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter, testManifest) + expect(serverChildLoader).not.toHaveBeenCalled() + + const childContext = vi.fn(() => ({ assetSource: 'child context' })) + const childHead = vi.fn(({ match }: { match: AnyRouteMatch }) => ({ + meta: [ + { + name: 'ssr-false-boundary', + content: (match.context as { assetSource?: string }).assetSource, + }, + ], + })) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + ssr: 'data-only', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + ssr: false, + loader: () => 'client child data', + context: childContext, + head: childHead, + }) + const tailRoute = new BaseRoute({ + getParentRoute: () => childRoute, + path: '/tail', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute.addChildren([tailRoute])]), + ]), + history: createMemoryHistory({ + initialEntries: ['/parent/child/tail'], + }), + isServer: false, + }) + + await hydrate(router) + + expect( + _getAssetMatches(router.state.matches).map((match) => match.routeId), + ).toEqual([rootRoute.id, parentRoute.id, childRoute.id]) + expect(childContext).toHaveBeenCalledOnce() + expect(childHead).toHaveBeenCalledOnce() + expect(router.state.matches[2]?.meta).toEqual([ + { name: 'ssr-false-boundary', content: 'child context' }, + ]) + }) + + test('preserves a verified data-only asset prefix through its client continuation', async () => { + const serverRootRoute = new BaseRootRoute({}) + const serverParentRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/parent', + ssr: 'data-only', + }) + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverParentRoute, + path: '/child', + ssr: false, + loader: () => 'server child data', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverParentRoute.addChildren([serverChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + mockWindow.$_TSR = await dehydrateToBootstrap(serverRouter, testManifest) + + const childLoaderResult = createControlledPromise() + let continuationAssetEnd: number | undefined + let router!: AnyRouter + const childLoader = vi.fn(() => { + continuationAssetEnd = router._tx?.[3][1]?._assetEnd + return childLoaderResult + }) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + ssr: 'data-only', + pendingComponent: () => null, + pendingMs: 0, + pendingMinMs: 0, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + ssr: false, + loader: childLoader, + }) + router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: false, + }) + + await hydrate(router) + const load = router.load() + + await vi.waitFor(() => { + expect(childLoader).toHaveBeenCalledOnce() + expect(router.state.status).toBe('pending') + }) + expect(continuationAssetEnd).toBe(3) + expect( + _getAssetMatches(router.state.matches).map((match) => match.routeId), + ).toEqual([rootRoute.id, parentRoute.id, childRoute.id]) + expect(router.state.matches[1]?._assetEnd).toBe(3) + + childLoaderResult.resolve('client child data') + await load + + expect(router.state.matches[1]?._assetEnd).toBeUndefined() + expect(router.state.matches[2]).toMatchObject({ + status: 'success', + loaderData: 'client child data', + }) + }) + + test('settles when navigation supersedes a pending custom hydrate hook', async () => { + const hydrateGate = createControlledPromise() + const hydrateStarted = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const oldRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/old', + }) + const newRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/new', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([oldRoute, newRoute]), + history: createMemoryHistory({ initialEntries: ['/old'] }), + isServer: false, + }) + router.options.hydrate = () => { + hydrateStarted.resolve() + return hydrateGate + } + const oldMatches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload( + mockWindow, + oldMatches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success' as const, + ssr: true, + u: Date.now(), + })), + ) + + const hydration = hydrate(router) + onTestFinished(async () => { + hydrateGate.resolve() + await hydration + }) + + await hydrateStarted + await router.navigate({ to: '/new' }) + await expect(hydration).resolves.toBeUndefined() + + expect(router.state.resolvedLocation?.pathname).toBe('/new') + expect(router.state.matches.at(-1)?.routeId).toBe(newRoute.id) + }) + + test('does not publish an old hydration lane after a newer navigation commits', async () => { + const oldChunkGate = createControlledPromise() + const oldChunkStarted = createControlledPromise() + const OldComponent = Object.assign(() => null, { + preload: () => { + oldChunkStarted.resolve() + return oldChunkGate + }, + }) + const rootRoute = new BaseRootRoute({}) + const oldRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/old', + component: OldComponent, + }) + const newRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/new', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([oldRoute, newRoute]), + history: createMemoryHistory({ initialEntries: ['/old'] }), + isServer: false, + }) + const oldMatches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload( + mockWindow, + oldMatches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success' as const, + ssr: true, + u: Date.now(), + })), + ) + + const hydration = hydrate(router) + onTestFinished(async () => { + oldChunkGate.resolve() + await hydration + }) + + await oldChunkStarted + await router.navigate({ to: '/new' }) + + expect(router.state.resolvedLocation?.pathname).toBe('/new') + expect(router.state.matches.at(-1)?.routeId).toBe(newRoute.id) + + await hydration + + expect(router.state.location.pathname).toBe('/new') + expect(router.state.resolvedLocation?.pathname).toBe('/new') + expect(router.state.matches.at(-1)?.routeId).toBe(newRoute.id) + }) + + test('an aborted hydration handoff falls back to a fresh client continuation', async () => { + let hydrationController: AbortController | undefined + const childLoader = vi.fn(() => 'client data') + const rootRoute = new BaseRootRoute({ + context: ({ abortController }: { abortController: AbortController }) => { + hydrationController ??= abortController + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + ssr: false, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'pending', + ssr: false, + u: Date.now(), + }, + ]) + + await hydrate(router) + expect(hydrationController).toBeDefined() + + const unsubscribe = router.subscribe('onBeforeLoad', () => { + hydrationController!.abort() + }) + onTestFinished(unsubscribe) + + await router.load() + + expect(router.state.resolvedLocation?.pathname).toBe('/child') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: childRoute.id, + status: 'success', + loaderData: 'client data', + }) + expect(childLoader).toHaveBeenCalledTimes(1) + }) + + test('published HMR consumes a partial hydration handoff before its successor converges', async () => { + let hydrationController: AbortController | undefined + let generation = 0 + const childLoader = vi.fn(() => `client child data ${++generation}`) + const rootRoute = new BaseRootRoute({ + context: ({ abortController }: { abortController: AbortController }) => { + hydrationController ??= abortController + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + ssr: false, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + ssr: true, + u: Date.now(), + }, + ]) + + await hydrate(router) + const handoff = router._handoff + const firstAck = createControlledPromise() + const firstPublished = createControlledPromise() + let transitions = 0 + router.startTransition = (fn) => { + transitions++ + if (transitions === 1) { + fn() + firstPublished.resolve() + return firstAck + } + firstAck.resolve(false) + fn() + return Promise.resolve(true) + } + + const firstRefresh = router._refreshRoute!() + await firstPublished + + expect(handoff).toBeDefined() + expect(router._handoff).toBeUndefined() + expect(hydrationController?.signal.aborted).toBe(true) + expect(router.state.matches[1]).toMatchObject({ + status: 'success', + ssr: false, + loaderData: 'client child data 1', + }) + + const secondRefresh = router._refreshRoute!() + await Promise.all([firstRefresh, secondRefresh]) + + expect(router._handoff).toBeUndefined() + expect(router.state.matches[1]).toMatchObject({ + status: 'success', + loaderData: 'client child data 2', + }) + expect(childLoader).toHaveBeenCalledTimes(2) + }) + + test('a synchronous context navigation prevents stale hydration assets from running', async () => { + const oldHead = vi.fn(() => ({ meta: [{ title: 'Old route' }] })) + const oldScripts = vi.fn(() => [ + { children: 'window.oldHydrationLaneRan = true' }, + ]) + const newHead = vi.fn(() => ({ meta: [{ title: 'New route' }] })) + + let navigation: Promise | undefined + let navigateDuringHydration = false + const navigationStarted = vi.fn() + const oldContext = vi.fn(({ navigate }: { navigate: NavigateFn }) => { + if (navigateDuringHydration) { + navigateDuringHydration = false + navigationStarted() + navigation = navigate({ to: '/new' }) + } + return { source: 'old' } + }) + const rootRoute = new BaseRootRoute({}) + const oldRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/old', + context: oldContext, + head: oldHead, + scripts: oldScripts, + }) + const newRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/new', + head: newHead, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([oldRoute, newRoute]), + history: createMemoryHistory({ initialEntries: ['/old'] }), + isServer: false, + }) + const oldMatches = router.matchRoutes(router.stores.location.get()) + + installHydrationPayload( + mockWindow, + oldMatches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success' as const, + ssr: true, + u: Date.now(), + })), + ) + + navigateDuringHydration = true + await hydrate(router) + expect(navigationStarted).toHaveBeenCalled() + expect(navigation).toBeDefined() + await navigation + + expect(router.state.location.pathname).toBe('/new') + expect(router.state.resolvedLocation?.pathname).toBe('/new') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: newRoute.id, + status: 'success', + meta: [{ title: 'New route' }], + }) + expect(oldContext).toHaveBeenCalled() + expect(oldHead).not.toHaveBeenCalled() + expect(oldScripts).not.toHaveBeenCalled() + expect(newHead).toHaveBeenCalled() + }) + + test('an adopted data-only error does not run its server-omitted descendants', async () => { + const serverError = new Error('server failed') + const serverBeforeLoad = vi.fn(() => { + throw serverError + }) + const serverRootRoute = new BaseRootRoute({}) + const serverParentRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/parent', + ssr: 'data-only', + beforeLoad: serverBeforeLoad, + }) + const serverChildLoader = vi.fn() + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverParentRoute, + path: '/child', + loader: serverChildLoader, + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverParentRoute.addChildren([serverChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + + const bootstrap = await dehydrateToBootstrap(serverRouter, testManifest) + + expect(serverBeforeLoad).toHaveBeenCalledTimes(1) + expect(serverChildLoader).not.toHaveBeenCalled() + expect(serverRouter.state.matches.map((match) => match.routeId)).toEqual([ + serverRootRoute.id, + serverParentRoute.id, + serverChildRoute.id, + ]) + expect(serverRouter.state.matches[1]).toMatchObject({ + routeId: serverParentRoute.id, + status: 'error', + ssr: 'data-only', + error: serverError, + }) + const transportedError = bootstrap.router?.matches.at(-1)?.e + expect(transportedError).not.toBe(serverError) + expect(transportedError).toMatchObject({ + name: serverError.name, + message: serverError.message, + }) + + const parentBeforeLoad = vi.fn() + const childBeforeLoad = vi.fn() + const childLoader = vi.fn() + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + ssr: 'data-only', + beforeLoad: parentBeforeLoad, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: childBeforeLoad, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: false, + }) + mockWindow.$_TSR = bootstrap + + await hydrate(router) + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + status: 'pending', + error: transportedError, + }) + expect(parentBeforeLoad).not.toHaveBeenCalled() + expect(childBeforeLoad).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + expect( + _getAssetMatches(router.state.matches).map((match) => match.routeId), + ).toEqual([rootRoute.id, parentRoute.id]) + + await router.load() + + expect(router.state.location.pathname).toBe('/parent/child') + expect(router.state.resolvedLocation?.pathname).toBe('/parent/child') + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]) + expect(router.state.matches[1]).toMatchObject({ + status: 'error', + error: transportedError, + }) + expect(router.state.matches[1]?.error).toMatchObject({ + name: serverError.name, + message: serverError.message, + }) + expect(parentBeforeLoad).not.toHaveBeenCalled() + expect(childBeforeLoad).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + }) +}) diff --git a/packages/router-core/tests/hydration-terminal-error-child-head.test.ts b/packages/router-core/tests/hydration-terminal-error-child-head.test.ts new file mode 100644 index 0000000000..e0acbd9780 --- /dev/null +++ b/packages/router-core/tests/hydration-terminal-error-child-head.test.ts @@ -0,0 +1,206 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, notFound } from '../src' +import { hydrate } from '../src/ssr/client' +import { createTestRouter, dehydrateToBootstrap } from './routerTestUtils' +import type { TsrSsrGlobal } from '../src/ssr/types' +import type { ServerManifest } from '../src/manifest' + +const testManifest: ServerManifest = { routes: {} } + +// This terminal-prefix case is an internal hydration protocol invariant, not +// an issue #7635 reproduction. The user-visible same-route navigation +// regression is covered in react-router, where the rendered boundary and +// document title can be observed directly. +describe('hydrated terminal error prefix', () => { + let mockWindow: { $_TSR?: TsrSsrGlobal } + + beforeEach(() => { + mockWindow = {} + vi.stubGlobal('window', mockWindow) + }) + + afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() + }) + + it('adopts the terminal prefix without running omitted child work', async () => { + const serverError = new Error('App beforeLoad failed') + const serverBeforeLoad = vi.fn(() => { + throw serverError + }) + const serverChildLoader = vi.fn(() => ({ child: 'server data' })) + const serverRootRoute = new BaseRootRoute({}) + const serverAppRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/app', + beforeLoad: serverBeforeLoad, + errorComponent: () => 'App error', + }) + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverAppRoute, + path: '/child', + loader: serverChildLoader, + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverAppRoute.addChildren([serverChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/app/child'] }), + isServer: true, + }) + + const bootstrap = await dehydrateToBootstrap(serverRouter, testManifest) + + expect(serverBeforeLoad).toHaveBeenCalledTimes(1) + expect(serverChildLoader).not.toHaveBeenCalled() + expect(serverRouter.state.matches.map((match) => match.routeId)).toEqual([ + serverRootRoute.id, + serverAppRoute.id, + serverChildRoute.id, + ]) + expect(serverRouter.state.matches[1]).toMatchObject({ + routeId: serverAppRoute.id, + status: 'error', + error: serverError, + }) + const transportedError = bootstrap.router?.matches.at(-1)?.e + expect(transportedError).not.toBe(serverError) + expect(transportedError).toMatchObject({ + name: serverError.name, + message: serverError.message, + }) + + const appHead = vi.fn(({ match }: any) => ({ + meta: [{ title: match.error ? 'App error title' : 'App success title' }], + })) + const childHead = vi.fn(() => ({ + meta: [{ title: 'Child success title' }], + })) + const childLoader = vi.fn(() => ({ child: 'data' })) + + const rootRoute = new BaseRootRoute({}) + const appRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/app', + head: appHead, + errorComponent: () => 'App error', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => appRoute, + path: '/child', + loader: childLoader, + head: childHead, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([appRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/app/child'] }), + isServer: false, + }) + + // Route matching confirms that the location has a child suffix which the + // terminal server payload omits. + const matches = router.matchRoutes(router.stores.location.get()) + expect(matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + appRoute.id, + childRoute.id, + ]) + mockWindow.$_TSR = bootstrap + + await hydrate(router) + + // Hydration reconstructs the full matched branch while adopting only the + // terminal prefix represented by the payload. + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + appRoute.id, + childRoute.id, + ]) + expect(router.state.matches[2]?.status).toBe('pending') + + const committedApp = router.state.matches.find( + (match) => match.routeId === appRoute.id, + ) + expect(router.state.location.pathname).toBe('/app/child') + expect(router.state.isLoading).toBe(false) + expect(committedApp?.status).toBe('error') + expect(committedApp?.error).toBe(transportedError) + + // No callback for the omitted suffix may run while adopting the prefix. + expect(childLoader).not.toHaveBeenCalled() + expect(childHead).not.toHaveBeenCalled() + + // Core projects the error match's metadata; document ownership is covered + // by the framework-level test. + expect(appHead).toHaveBeenCalledOnce() + expect(appHead).toHaveBeenCalledWith( + expect.objectContaining({ + match: expect.objectContaining({ + routeId: appRoute.id, + status: 'error', + error: transportedError, + }), + }), + ) + expect(committedApp?.meta).toEqual([{ title: 'App error title' }]) + }) + it.each(['error', 'notFound'] as const)( + 'preserves hydrated %s lifecycle membership through invalidation', + async (fallback) => { + let failed = true + const childEnter = vi.fn() + const childStay = vi.fn() + const childLeave = vi.fn() + const setup = (isServer: boolean) => { + const rootRoute = new BaseRootRoute({}) + const appRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/app', + errorComponent: () => null, + notFoundComponent: () => null, + beforeLoad: () => { + if (failed) { + throw fallback === 'error' ? new Error('unavailable') : notFound() + } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => appRoute, + path: 'child', + onEnter: childEnter, + onStay: childStay, + onLeave: childLeave, + }) + return createTestRouter({ + routeTree: rootRoute.addChildren([ + appRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/app/child'] }), + isServer, + }) + } + const server = setup(true) + const client = setup(false) + try { + mockWindow.$_TSR = await dehydrateToBootstrap(server, testManifest) + await hydrate(client) + expect(client.state.matches).toHaveLength(3) + await client.invalidate() + expect(childEnter).not.toHaveBeenCalled() + expect(childStay).not.toHaveBeenCalled() + expect(childLeave).not.toHaveBeenCalled() + failed = false + await client.invalidate() + expect(childEnter).toHaveBeenCalledOnce() + expect(childStay).not.toHaveBeenCalled() + expect(childLeave).not.toHaveBeenCalled() + } finally { + server.history.destroy() + client.history.destroy() + } + }, + ) +}) diff --git a/packages/router-core/tests/hydrationQueue.bench.ts b/packages/router-core/tests/hydrationQueue.bench.ts new file mode 100644 index 0000000000..04679b3c5c --- /dev/null +++ b/packages/router-core/tests/hydrationQueue.bench.ts @@ -0,0 +1,107 @@ +import { describe, test } from 'vitest' + +const MAX_DYNAMIC_RECORD_CODE_UNITS = 64 * 1024 +const SOURCE_SEPARATOR = ';' +const SCRIPT_OPENING_CODE_UNITS = '' + .length + +function getBatchLength( + values: ReadonlyArray, + head: number, +) { + let codeUnits = SCRIPT_OPENING_CODE_UNITS + DYNAMIC_CLOSE_CODE_UNITS + let batchLength = 0 + for (let index = head; index < values.length; index++) { + const nextCodeUnits = + codeUnits + SOURCE_SEPARATOR.length + values[index]!.length + if (batchLength > 0 && nextCodeUnits > MAX_DYNAMIC_RECORD_CODE_UNITS) { + break + } + codeUnits = nextCodeUnits + batchLength++ + if (codeUnits > MAX_DYNAMIC_RECORD_CODE_UNITS) { + break + } + } + return batchLength +} + +function drainWithSplice(values: Array) { + let drained = 0 + let consumedCodeUnits = 0 + while (values.length > 0) { + const batchLength = getBatchLength(values, 0) + const batch = values.splice(0, batchLength) + drained += batchLength + for (const part of batch) { + consumedCodeUnits += part.length + } + } + return { drained, consumedCodeUnits } +} + +function drainWithHead(values: Array) { + let head = 0 + let drained = 0 + let consumedCodeUnits = 0 + while (head < values.length) { + const batchLength = getBatchLength(values, head) + if (head === 0 && batchLength === values.length) { + const batch = values + drained += values.length + for (const part of batch) { + consumedCodeUnits += part!.length + } + values = [] + head = 0 + continue + } + const end = head + batchLength + const batch = values.slice(head, end) + for (let index = head; index < end; index++) { + values[index] = undefined + } + drained += batch.length + for (const part of batch) { + consumedCodeUnits += part!.length + } + head = end + if (head === values.length) { + values = [] + head = 0 + } else if (head >= 1024 && head >= values.length - head) { + values = values.slice(head) + head = 0 + } + } + return { drained, consumedCodeUnits } +} + +const source = 'x'.repeat(4 * 1024) +const sources = Array.from({ length: 4_095 }, () => source) +let benchmarkSink: { drained: number; consumedCodeUnits: number } | undefined + +const expected = drainWithSplice(sources.slice()) +const actual = drainWithHead(sources.slice()) +if ( + expected.drained !== sources.length || + actual.drained !== sources.length || + actual.consumedCodeUnits !== expected.consumedCodeUnits +) { + throw new Error('Hydration queue benchmark discarded a source') +} + +describe('maximum hydration source queue with 4 KiB sources', () => { + test('front splice', async ({ bench }) => { + await bench('front splice', () => { + return void (benchmarkSink = drainWithSplice(sources.slice())) + }).run() + }) + + test('head index with compaction', async ({ bench }) => { + await bench('head index with compaction', () => { + return void (benchmarkSink = drainWithHead(sources.slice())) + }).run() + }) +}) diff --git a/packages/router-core/tests/hydrationScripts.test.ts b/packages/router-core/tests/hydrationScripts.test.ts new file mode 100644 index 0000000000..911e7cd78d --- /dev/null +++ b/packages/router-core/tests/hydrationScripts.test.ts @@ -0,0 +1,808 @@ +import { createHash } from 'node:crypto' +import { describe, expect, test, vi } from 'vitest' +import { + HydrationScriptOutputState, + MAX_HYDRATION_OUTPUT_CHUNK_BYTES, + createHydrationScripts, +} from '../src/ssr/hydrationScripts' +import type { HydrationScriptOutput } from '../src/ssr/hydrationScripts' + +const decoder = new TextDecoder() +const encoder = new TextEncoder() + +function getBoundarySource() { + const scripts = createHydrationScripts(undefined, []) + const source = scripts.takeInitialHydrationScriptTags()!.boundary.children! + scripts.cleanup() + return source +} + +const HYDRATION_SCRIPT_BOUNDARY_SOURCE = getBoundarySource() + +function createReadyOutput(nonce?: string) { + const scripts = createHydrationScripts(nonce, ['boot()']) + const initial = scripts.takeInitialHydrationScriptTags()! + const output = scripts.claimOutput() + scripts.liftBarrier() + return { scripts, initial, output } +} + +function drainChunks(output: HydrationScriptOutput) { + const chunks: Array = [] + while ( + output.state === HydrationScriptOutputState.Ready || + output.state === HydrationScriptOutputState.Active + ) { + chunks.push(output.pullChunk()) + } + return chunks +} + +function decodeChunks(chunks: ReadonlyArray) { + let text = '' + for (const chunk of chunks) { + text += decoder.decode(chunk, { stream: true }) + } + return text + decoder.decode() +} + +async function flushMicrotasks() { + await Promise.resolve() +} + +describe('hydration script ownership', () => { + test('takes initial sources before the output is claimed', () => { + const scripts = createHydrationScripts(undefined, ['first()', 'second()']) + const initial = scripts.takeInitialHydrationScriptTags()! + + expect(initial.before[0]).toMatchObject({ + attrs: { 'data-tsr-stream-part': '' }, + }) + expect(initial.before[0]!.children).toMatch(/^first\(\);second\(\);/) + expect(initial.boundary.children).toBe(HYDRATION_SCRIPT_BOUNDARY_SOURCE) + expect(initial.boundary.attrs).not.toHaveProperty('id') + + const output = scripts.claimOutput() + expect(output.state).toBe(HydrationScriptOutputState.Waiting) + scripts.cleanup() + }) + + test('supports taking initial tags through the ServerSsr callback', () => { + const scripts = createHydrationScripts(undefined, ['boot()']) + const takeInitialHydrationScriptTags = + scripts.takeInitialHydrationScriptTags + + expect(takeInitialHydrationScriptTags()?.before[0]?.children).toMatch( + /^boot\(\);/, + ) + scripts.cleanup() + }) + + test('notifies the subscriber and pulls late records', () => { + const scripts = createHydrationScripts(undefined, []) + scripts.takeInitialHydrationScriptTags() + const output = scripts.claimOutput() + const onChange = vi.fn() + const unsubscribe = output.subscribe(onChange) + + scripts.liftBarrier() + scripts.pushSource('late()') + + expect(onChange).toHaveBeenCalledOnce() + expect(decoder.decode(output.pullChunk())).toContain('late()') + unsubscribe() + scripts.cleanup() + }) + + test('skipInitialTake releases initial sources as late records', () => { + const scripts = createHydrationScripts(undefined, ['boot()']) + const output = scripts.claimOutput() + scripts.pushSource('late()') + scripts.liftBarrier() + expect(output.state).toBe(HydrationScriptOutputState.Waiting) + + scripts.skipInitialTake() + + expect(output.state).toBe(HydrationScriptOutputState.Ready) + expect(decoder.decode(output.pullChunk())).toBe( + '', + ) + expect(scripts.takeInitialHydrationScriptTags()).toBeUndefined() + scripts.cleanup() + }) + + test('empty initial output keeps only the stream boundary', () => { + const scripts = createHydrationScripts(undefined, []) + const initial = scripts.takeInitialHydrationScriptTags()! + + expect(initial.before).toEqual([]) + expect(initial.boundary).toEqual({ + tag: 'script', + attrs: { nonce: undefined }, + children: HYDRATION_SCRIPT_BOUNDARY_SOURCE, + }) + scripts.cleanup() + }) + + test('does not append cleanup to a large initial source', () => { + const source = 'x'.repeat(20 * 1024) + const scripts = createHydrationScripts(undefined, [source]) + const initial = scripts.takeInitialHydrationScriptTags()! + + expect(initial.before).toHaveLength(2) + expect(initial.before[0]).toEqual({ + tag: 'script', + attrs: { nonce: undefined, 'data-tsr-stream-part': '' }, + children: source, + }) + expect(initial.before[1]).toMatchObject({ + tag: 'script', + attrs: { nonce: undefined, 'data-tsr-stream-part': '' }, + children: expect.stringContaining('document.currentScript'), + }) + scripts.cleanup() + }) + + test('does not move pending initial sources into an early claimant', () => { + const scripts = createHydrationScripts(undefined, ['boot()']) + const output = scripts.claimOutput() + + scripts.pushSource('beforeScripts()') + scripts.liftBarrier() + expect(output.state).toBe(HydrationScriptOutputState.Waiting) + + const initial = scripts.takeInitialHydrationScriptTags()! + expect( + initial.before.some((tag) => tag.children?.includes('beforeScripts()')), + ).toBe(true) + expect(output.state).toBe(HydrationScriptOutputState.Waiting) + scripts.cleanup() + }) + + test('releases initial source accounting when tags take ownership', () => { + const sources = Array.from({ length: 4_096 }, (_, index) => `${index}`) + const scripts = createHydrationScripts(undefined, sources) + expect(scripts.takeInitialHydrationScriptTags()).toBeDefined() + const output = scripts.claimOutput() + scripts.liftBarrier() + + for (const source of sources) { + scripts.pushSource(source) + } + + expect(output.state).toBe(HydrationScriptOutputState.Ready) + expect(output.error).toBeUndefined() + scripts.cleanup() + }) + + test('transfers buffered sources in order only after the barrier lifts', async () => { + const scripts = createHydrationScripts(undefined, ['boot()']) + scripts.takeInitialHydrationScriptTags() + const output = scripts.claimOutput() + + scripts.pushSource('first()') + scripts.pushSource('second()') + await flushMicrotasks() + expect(output.state).toBe(HydrationScriptOutputState.Waiting) + + scripts.liftBarrier() + expect(output.state).toBe(HydrationScriptOutputState.Ready) + expect(decodeChunks(drainChunks(output))).toBe( + '', + ) + scripts.cleanup() + }) + + test('emits exact nonce, separators, cleanup, boundary, and closing protocol', async () => { + const nonce = `a&"'<>` + const { scripts, initial, output } = createReadyOutput(nonce) + + expect(initial.before).toEqual([ + { + tag: 'script', + attrs: { nonce, 'data-tsr-stream-part': '' }, + children: + "boot();{let s=document.currentScript,p;while((p=s.previousElementSibling)&&p.hasAttribute('data-tsr-stream-part'))p.remove();s.remove()}", + }, + ]) + expect(initial.boundary).toEqual({ + tag: 'script', + attrs: { nonce }, + children: HYDRATION_SCRIPT_BOUNDARY_SOURCE, + }) + + scripts.pushSource('first()') + scripts.pushSource('second()') + await flushMicrotasks() + expect(decodeChunks(drainChunks(output))).toBe( + '', + ) + scripts.cleanup() + }) + + test.each([ + { + name: 'plain continuation', + initial: false, + wrap: false, + expected: 'value()', + }, + { + name: 'initial router value', + initial: true, + wrap: false, + expected: '$_TSR.router=value()', + }, + { + name: 'wrapped continuation', + initial: false, + wrap: true, + expected: '$_TSR.p(()=>value())', + }, + { + name: 'wrapped initial router value', + initial: true, + wrap: true, + expected: '$_TSR.p(()=>$_TSR.router=value())', + }, + ])('frames $name serialization exactly', ({ initial, wrap, expected }) => { + const { scripts, output } = createReadyOutput() + + scripts.pushSerializedSource('value()', initial, wrap) + + expect(decodeChunks(drainChunks(output))).toBe( + ``, + ) + scripts.cleanup() + }) +}) + +describe('hydration script encoding', () => { + test('uses one direct chunk for a small record', async () => { + const { scripts, output } = createReadyOutput() + scripts.pushSource('small()') + await flushMicrotasks() + + const chunks = drainChunks(output) + expect(chunks).toHaveLength(1) + expect(decodeChunks(chunks)).toBe( + '', + ) + scripts.cleanup() + }) + + test('can produce a record that is exactly one maximum-sized chunk', async () => { + const prefix = '' + const source = 'x'.repeat( + MAX_HYDRATION_OUTPUT_CHUNK_BYTES - prefix.length - suffix.length, + ) + const { scripts, output } = createReadyOutput() + scripts.pushSource(source) + await flushMicrotasks() + + const chunks = drainChunks(output) + expect(chunks).toHaveLength(1) + expect(chunks[0]).toHaveLength(MAX_HYDRATION_OUTPUT_CHUNK_BYTES) + expect(decodeChunks(chunks)).toBe(prefix + source + suffix) + scripts.cleanup() + }) + + test.each([ + ['CJK', '漢字語'.repeat(30_000)], + ['emoji', '🦄🚀'.repeat(30_000)], + ])( + 'encodes a large %s record without corrupting UTF-8', + async (_, source) => { + const { scripts, output } = createReadyOutput() + scripts.pushSource(source) + scripts.pushSource('tail()') + await flushMicrotasks() + + const chunks = drainChunks(output) + expect( + Math.max(...chunks.map((chunk) => chunk.byteLength)), + ).toBeLessThanOrEqual(MAX_HYDRATION_OUTPUT_CHUNK_BYTES) + expect(decodeChunks(chunks)).toBe( + `` + + '', + ) + scripts.cleanup() + }, + ) + + test('drains one 17 MiB record incrementally without retaining the response', async () => { + const source = 'x'.repeat(17 * 1024 * 1024) + const expectedHash = createHash('sha256') + .update('') + .digest('hex') + const { scripts, output } = createReadyOutput() + scripts.pushSource(source) + await flushMicrotasks() + + const actualHash = createHash('sha256') + let outputBytes = 0 + let maximumChunkBytes = 0 + while ( + output.state === HydrationScriptOutputState.Ready || + output.state === HydrationScriptOutputState.Active + ) { + const chunk = output.pullChunk() + actualHash.update(chunk) + outputBytes += chunk.byteLength + maximumChunkBytes = Math.max(maximumChunkBytes, chunk.byteLength) + } + + expect(outputBytes).toBe( + encoder.encode('').byteLength, + ) + expect(actualHash.digest('hex')).toBe(expectedHash) + expect(maximumChunkBytes).toBeLessThanOrEqual( + MAX_HYDRATION_OUTPUT_CHUNK_BYTES, + ) + expect(output.state).toBe(HydrationScriptOutputState.Waiting) + scripts.cleanup() + }) + + test('keeps a large record Active until its closing tag drains', async () => { + const { scripts, output } = createReadyOutput() + scripts.pushSource('x'.repeat(MAX_HYDRATION_OUTPUT_CHUNK_BYTES * 2)) + await flushMicrotasks() + + expect(output.state).toBe(HydrationScriptOutputState.Ready) + const first = output.pullChunk() + expect(first.byteLength).toBeLessThanOrEqual( + MAX_HYDRATION_OUTPUT_CHUNK_BYTES, + ) + expect(output.state).toBe(HydrationScriptOutputState.Active) + + drainChunks(output) + expect(output.state).toBe(HydrationScriptOutputState.Waiting) + scripts.cleanup() + }) + + test('closes one multi-chunk source before draining the next independent source', async () => { + const { scripts, output } = createReadyOutput() + const first = `first("${'a'.repeat(MAX_HYDRATION_OUTPUT_CHUNK_BYTES * 2)}")` + const second = `second("${'b'.repeat( + MAX_HYDRATION_OUTPUT_CHUNK_BYTES * 2, + )}")` + + try { + scripts.pushSource(first) + scripts.pushSource(second) + await flushMicrotasks() + + const recordDecoder = new TextDecoder() + let firstRecord = '' + while ( + (output.state === HydrationScriptOutputState.Ready || + output.state === HydrationScriptOutputState.Active) && + !firstRecord.includes('') + ) { + firstRecord += recordDecoder.decode(output.pullChunk(), { + stream: true, + }) + } + firstRecord += recordDecoder.decode() + + expect(firstRecord).toContain('first("') + expect(firstRecord).not.toContain('second("') + expect(output.state).toBe(HydrationScriptOutputState.Ready) + + const secondRecord = decodeChunks(drainChunks(output)) + expect(secondRecord).toContain('second("') + expect(secondRecord).not.toContain('first("') + expect(output.state).toBe(HydrationScriptOutputState.Waiting) + } finally { + scripts.cleanup() + } + }) + + test('splits sources whose combined framed record exceeds the record budget', async () => { + const { scripts, output } = createReadyOutput() + const first = `first("${'a'.repeat(40 * 1024)}")` + const second = `second("${'b'.repeat(40 * 1024)}")` + + try { + scripts.pushSource(first) + scripts.pushSource(second) + await flushMicrotasks() + + const firstRecord = decodeChunks([output.pullChunk()]) + expect(firstRecord).toContain(first) + expect(firstRecord).not.toContain(second) + expect(output.state).toBe(HydrationScriptOutputState.Ready) + + const secondRecord = decodeChunks([output.pullChunk()]) + expect(secondRecord).toContain(second) + expect(secondRecord).not.toContain(first) + expect(output.state).toBe(HydrationScriptOutputState.Waiting) + } finally { + scripts.cleanup() + } + }) + + test('preserves FIFO when sources append after queue compaction', () => { + const { scripts, output } = createReadyOutput() + const initialSources = Array.from({ length: 1_200 }, (_, index) => { + const prefix = `r${index.toString().padStart(4, '0')}:` + return prefix + 'x'.repeat(1024 - prefix.length) + }) + const appendedSources = Array.from({ length: 16 }, (_, offset) => { + const index = initialSources.length + offset + const prefix = `r${index.toString().padStart(4, '0')}:` + return prefix + 'x'.repeat(1024 - prefix.length) + }) + + try { + for (const source of initialSources) { + scripts.pushSource(source) + } + + const chunks = Array.from({ length: 17 }, () => output.pullChunk()) + expect(output.state).toBe(HydrationScriptOutputState.Ready) + + for (const source of appendedSources) { + scripts.pushSource(source) + } + scripts.finish() + chunks.push(...drainChunks(output)) + + const text = decodeChunks(chunks) + const markers = Array.from(text.matchAll(/r(\d{4}):/g), (match) => + Number(match[1]), + ) + expect(markers).toEqual( + [...initialSources, ...appendedSources].map((_, index) => index), + ) + expect(output.state).toBe(HydrationScriptOutputState.Done) + } finally { + scripts.cleanup() + } + }) + + test('reuses source-part capacity after queue compaction', () => { + const { scripts, output } = createReadyOutput() + const source = 'x'.repeat(1024) + + try { + for (let index = 0; index < 4_096; index++) { + scripts.pushSource(source) + } + + for (let record = 0; record < 33; record++) { + output.pullChunk() + } + expect(output.state).toBe(HydrationScriptOutputState.Ready) + + for (let index = 0; index < 2_079; index++) { + scripts.pushSource(source) + } + expect(output.state).toBe(HydrationScriptOutputState.Ready) + expect(output.error).toBeUndefined() + + scripts.pushSource(source) + expect(output.state).toBe(HydrationScriptOutputState.Failed) + expect((output.error as Error).message).toContain('source-part count') + } finally { + scripts.cleanup() + } + }) + + test('a mostly-empty final chunk does not pin the full output buffer', () => { + const { scripts, output } = createReadyOutput() + scripts.pushSource(`big("${'x'.repeat(80 * 1024)}")`) + scripts.finish() + + const chunks = drainChunks(output) + expect(chunks.length).toBeGreaterThan(1) + for (const chunk of chunks) { + // No chunk may retain more than twice its own bytes through its + // backing ArrayBuffer; small tails must be copied out of the 64 KiB + // output buffer. + expect(chunk.buffer.byteLength).toBeLessThanOrEqual(chunk.byteLength * 2) + } + }) +}) + +describe('disabled hydration', () => { + test('makes the fast path reservable without a take or a boundary', () => { + vi.useFakeTimers() + try { + const scripts = createHydrationScripts(undefined) + scripts.disableHydration() + + expect(scripts.isInitialTaken()).toBe(true) + expect(scripts.takeInitialHydrationScriptTags()).toBeUndefined() + expect(scripts.reserveFastPath()).toBe(true) + + // Late producer activity is inert: no sources, no timers. + scripts.pushSource('late()') + scripts.startSerializationTimeout(10) + scripts.finish() + expect(vi.getTimerCount()).toBe(0) + + scripts.cleanup() + } finally { + vi.useRealTimers() + } + }) + + test('is safe after cleanup', () => { + const scripts = createHydrationScripts(undefined) + scripts.disableHydration() + scripts.cleanup() + expect(() => scripts.disableHydration()).not.toThrow() + }) + + test('rejects disabling after the initial take', () => { + const scripts = createHydrationScripts(undefined, ['boot()']) + scripts.takeInitialHydrationScriptTags() + expect(() => scripts.disableHydration()).toThrow( + 'hydration output is already committed', + ) + scripts.cleanup() + }) + + test('rejects disabling after the output channel was claimed', () => { + const scripts = createHydrationScripts(undefined, ['boot()']) + scripts.claimOutput() + expect(() => scripts.disableHydration()).toThrow( + 'hydration output is already committed', + ) + scripts.cleanup() + }) +}) + +describe('hydration script completion and failure', () => { + test('enqueues $_TSR.e() before it reports Done', () => { + const { scripts, output } = createReadyOutput() + const observedStates: Array = [] + output.subscribe(() => observedStates.push(output.state)) + + scripts.pushSource('value()') + scripts.finish() + expect(output.state).toBe(HydrationScriptOutputState.Ready) + + const text = decodeChunks(drainChunks(output)) + expect(text).toBe( + '', + ) + expect(output.state).toBe(HydrationScriptOutputState.Done) + expect(observedStates).toContain(HydrationScriptOutputState.Ready) + scripts.cleanup() + }) + + test('reports the source-part guard synchronously', () => { + const { scripts, output } = createReadyOutput() + const notifications: Array = [] + output.subscribe(() => { + notifications.push(output.state) + }) + + let pushed = 0 + while ( + output.state !== HydrationScriptOutputState.Failed && + pushed < 10_000 + ) { + scripts.pushSource(`${pushed++}`) + } + + expect(pushed).toBeLessThan(10_000) + expect(output.state).toBe(HydrationScriptOutputState.Failed) + expect((output.error as Error).message).toContain('source-part count') + expect( + notifications.filter( + (value) => value === HydrationScriptOutputState.Failed, + ), + ).toHaveLength(1) + scripts.cleanup() + }) + + test('applies the source-part guard before the initial take', () => { + const scripts = createHydrationScripts(undefined, []) + + try { + for (let index = 0; index <= 4_096; index++) { + scripts.pushSource(`${index}`) + } + + const output = scripts.claimOutput() + expect(output.state).toBe(HydrationScriptOutputState.Failed) + expect((output.error as Error).message).toContain('source-part count') + expect(scripts.takeInitialHydrationScriptTags()).toBeUndefined() + } finally { + scripts.cleanup() + } + }) + + test('applies the source-part guard to constructor sources', () => { + const sources = Array.from({ length: 4_097 }, (_, index) => `${index}`) + const scripts = createHydrationScripts(undefined, sources) + + try { + const output = scripts.claimOutput() + expect(output.state).toBe(HydrationScriptOutputState.Failed) + expect((output.error as Error).message).toContain('source-part count') + expect(scripts.takeInitialHydrationScriptTags()).toBeUndefined() + } finally { + scripts.cleanup() + } + }) + + test('reports the regular backlog guard synchronously', () => { + const { scripts, output } = createReadyOutput() + const source = 'x'.repeat(1024 * 1024) + + let pushed = 0 + while (output.state !== HydrationScriptOutputState.Failed && pushed < 100) { + scripts.pushSource(source + pushed++) + } + + expect(pushed).toBeLessThan(100) + expect(output.state).toBe(HydrationScriptOutputState.Failed) + expect((output.error as Error).message).toContain('code-unit count') + scripts.cleanup() + }) + + test('applies the regular backlog guard before the initial take', () => { + const scripts = createHydrationScripts(undefined, []) + const source = 'x'.repeat(1024 * 1024) + + try { + for (let index = 0; index < 17; index++) { + scripts.pushSource(source + index) + } + + const output = scripts.claimOutput() + expect(output.state).toBe(HydrationScriptOutputState.Failed) + expect((output.error as Error).message).toContain('code-unit count') + } finally { + scripts.cleanup() + } + }) + + test('allows one oversized source but rejects a second one', () => { + const { scripts, output } = createReadyOutput() + const first = 'a'.repeat(17 * 1024 * 1024) + const second = 'b'.repeat(17 * 1024 * 1024) + + scripts.pushSource(first) + expect(output.state).not.toBe(HydrationScriptOutputState.Failed) + scripts.pushSource(second) + + expect(output.state).toBe(HydrationScriptOutputState.Failed) + expect((output.error as Error).message).toContain('code-unit count') + scripts.cleanup() + }) + + test('releases oversized-source accounting as soon as its source drains', () => { + const openingBytes = encoder.encode('', + ) + expect(output.state).toBe(HydrationScriptOutputState.Ready) + drainChunks(output) + expect(output.state).toBe(HydrationScriptOutputState.Waiting) + scripts.cleanup() + }) + + test('rejects a second consumer', () => { + const scripts = createHydrationScripts(undefined, ['boot()']) + scripts.claimOutput() + expect(() => scripts.claimOutput()).toThrow( + 'SSR hydration script output already has a consumer', + ) + scripts.cleanup() + }) + + test('rejects an output claim after the fast path owns the consumer', () => { + const scripts = createHydrationScripts(undefined) + scripts.disableHydration() + expect(scripts.reserveFastPath()).toBe(true) + expect(() => scripts.claimOutput()).toThrow( + 'SSR hydration script output already has a consumer', + ) + scripts.cleanup() + }) + + test('cleanup clears active state and does not retain a new subscriber', async () => { + const { scripts, output } = createReadyOutput() + scripts.pushSource('x'.repeat(MAX_HYDRATION_OUTPUT_CHUNK_BYTES * 2)) + await flushMicrotasks() + output.pullChunk() + expect(output.state).toBe(HydrationScriptOutputState.Active) + + scripts.cleanup() + + expect(output.state).toBe(HydrationScriptOutputState.Done) + expect(output.error).toBeUndefined() + expect(() => output.pullChunk()).toThrow('not ready') + const onChange = vi.fn() + const unsubscribe = output.subscribe(onChange) + scripts.pushSource('ignored()') + scripts.finish() + unsubscribe() + expect(onChange).not.toHaveBeenCalled() + }) + + test('a render timeout fails immediately while a record is Active', async () => { + vi.useFakeTimers() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const { scripts, output } = createReadyOutput() + const onChange = vi.fn() + output.subscribe(onChange) + + try { + scripts.pushSource('x'.repeat(MAX_HYDRATION_OUTPUT_CHUNK_BYTES * 2)) + await flushMicrotasks() + output.pullChunk() + expect(output.state).toBe(HydrationScriptOutputState.Active) + + scripts.startSerializationTimeout(10) + await vi.advanceTimersByTimeAsync(10) + + expect(output.state).toBe(HydrationScriptOutputState.Failed) + expect((output.error as Error).message).toContain('Serialization timeout') + expect(onChange).toHaveBeenCalled() + } finally { + scripts.cleanup() + errorSpy.mockRestore() + vi.useRealTimers() + } + }) + + test('serialization completion clears the timeout during a slow active drain', async () => { + vi.useFakeTimers() + const { scripts, output } = createReadyOutput() + + try { + scripts.pushSource('x'.repeat(MAX_HYDRATION_OUTPUT_CHUNK_BYTES * 2)) + await flushMicrotasks() + output.pullChunk() + expect(output.state).toBe(HydrationScriptOutputState.Active) + + scripts.startSerializationTimeout(10) + scripts.finish() + await vi.advanceTimersByTimeAsync(100) + + expect(output.state).toBe(HydrationScriptOutputState.Active) + expect(decodeChunks(drainChunks(output))).toContain('$_TSR.e()') + expect(output.state).toBe(HydrationScriptOutputState.Done) + } finally { + scripts.cleanup() + vi.useRealTimers() + } + }) +}) diff --git a/packages/router-core/tests/invalidate-pre-rematch-failure.test.ts b/packages/router-core/tests/invalidate-pre-rematch-failure.test.ts new file mode 100644 index 0000000000..084fbe8d31 --- /dev/null +++ b/packages/router-core/tests/invalidate-pre-rematch-failure.test.ts @@ -0,0 +1,63 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * A planning failure is a route error generation and leaves the router usable + * for a later retry. + */ +test('a fatal pre-rematch failure publishes an error and permits retry', async () => { + const boom = new Error('loaderDeps failed during invalidation rematch') + let failLoaderDeps = false + const loaderSignals: Array = [] + + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loaderDeps: () => { + if (failLoaderDeps) { + throw boom + } + return {} + }, + loader: ({ abortController }) => { + loaderSignals.push(abortController.signal) + return 'target data' + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + }) + + await router.load() + const activeSignal = loaderSignals[0] + expect(router.state.matches.at(-1)?.status).toBe('success') + + failLoaderDeps = true + await router.invalidate({ forcePending: true }) + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'error', + error: boom, + }) + expect(loaderSignals).toHaveLength(1) + expect(activeSignal?.aborted).toBe(true) + + failLoaderDeps = false + await router.invalidate() + const retrySignal = loaderSignals[1] + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + loaderData: 'target data', + }) + expect(loaderSignals).toHaveLength(2) + expect(retrySignal).not.toBe(activeSignal) + expect(activeSignal?.aborted).toBe(true) + expect(retrySignal?.aborted).toBe(false) +}) diff --git a/packages/router-core/tests/invalidation-reserved-flight.test.ts b/packages/router-core/tests/invalidation-reserved-flight.test.ts new file mode 100644 index 0000000000..d9f3aff105 --- /dev/null +++ b/packages/router-core/tests/invalidation-reserved-flight.test.ts @@ -0,0 +1,55 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('invalidation retires a zero-owner reservation before a blocked successor completes', async () => { + const started = createControlledPromise() + const data = createControlledPromise() + const entered = createControlledPromise() + const before = createControlledPromise() + let signal: AbortSignal | undefined + const root = new BaseRootRoute({}) + const home = new BaseRoute({ getParentRoute: () => root, path: '/' }) + const target = new BaseRoute({ + getParentRoute: () => root, + path: '/target', + validateSearch: (search: Record) => ({ + blocked: !!search.blocked, + }), + beforeLoad: ({ search }) => { + if (search.blocked) { + entered.resolve() + return before + } + return undefined + }, + loader: ({ abortController }) => { + signal = abortController.signal + started.resolve() + return data + }, + }) + const router = createTestRouter({ + routeTree: root.addChildren([home, target]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + const first = router.navigate({ to: '/target', search: { blocked: false } }) + await started + const second = router.navigate({ to: '/target', search: { blocked: true } }) + await entered + expect(signal?.aborted).toBe(false) + const aborted = vi.fn() + signal!.addEventListener('abort', aborted) + const invalidation = router.invalidate({ + filter: (match) => match.routeId === target.id, + }) + await router.navigate({ to: '/' }) + before.resolve() + data.resolve('obsolete data') + await Promise.all([first, second, invalidation]) + expect(signal?.aborted).toBe(true) + expect(aborted).toHaveBeenCalledOnce() + expect(router.state.location.pathname).toBe('/') +}) diff --git a/packages/router-core/tests/issue-3179-preload-cached-cause.test.ts b/packages/router-core/tests/issue-3179-preload-cached-cause.test.ts new file mode 100644 index 0000000000..c465961dc2 --- /dev/null +++ b/packages/router-core/tests/issue-3179-preload-cached-cause.test.ts @@ -0,0 +1,59 @@ +import { expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +// https://github.com/TanStack/router/issues/3179 +test('#3179: preloading the active route does not replay its load callbacks', async () => { + const calls: Array<{ + phase: 'beforeLoad' | 'loader' + cause: string + preload: boolean + }> = [] + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + staleTime: 0, + preloadStaleTime: 0, + beforeLoad: ({ cause, preload }) => { + calls.push({ phase: 'beforeLoad', cause, preload }) + }, + loader: ({ cause, preload }) => { + calls.push({ phase: 'loader', cause, preload }) + }, + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + history: createMemoryHistory({ initialEntries: ['/about'] }), + }) + + await router.load() + + // First hover Home from About, then click it. This is the sequence from + // the issue that used to cache the navigation's flags on the match. + await router.preloadRoute({ to: '/' }) + expect(calls).toEqual([ + { phase: 'beforeLoad', cause: 'preload', preload: true }, + { phase: 'loader', cause: 'preload', preload: true }, + ]) + + calls.length = 0 + await router.navigate({ to: '/' }) + expect(calls).toEqual([ + { phase: 'beforeLoad', cause: 'enter', preload: false }, + { phase: 'loader', cause: 'enter', preload: false }, + ]) + + // beforeLoad is contextualization, not loader cache data, so a later preload + // reruns it with fresh flags while retaining the accepted loader generation. + calls.length = 0 + await router.preloadRoute({ to: '/' }) + expect(calls).toEqual([ + { phase: 'beforeLoad', cause: 'preload', preload: true }, + ]) +}) diff --git a/packages/router-core/tests/issue-3293-on-enter-after-loader.test.ts b/packages/router-core/tests/issue-3293-on-enter-after-loader.test.ts new file mode 100644 index 0000000000..a1be910314 --- /dev/null +++ b/packages/router-core/tests/issue-3293-on-enter-after-loader.test.ts @@ -0,0 +1,108 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +// Existing-behavior controls for https://github.com/TanStack/router/issues/3293 +test('#3293 existing behavior: direct load runs onEnter after beforeLoad and loader', async () => { + const beforeLoadGate = createControlledPromise<{ ready: true }>() + const loaderGate = createControlledPromise<{ someData: 42 }>() + const beforeLoad = vi.fn(() => beforeLoadGate) + const loader = vi.fn(() => loaderGate) + const onEnter = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + beforeLoad, + loader, + onEnter, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([aboutRoute]), + history: createMemoryHistory({ initialEntries: ['/about'] }), + }) + + const load = router.load() + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) + expect(loader).not.toHaveBeenCalled() + expect(onEnter).not.toHaveBeenCalled() + + beforeLoadGate.resolve({ ready: true }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + expect(loader).toHaveBeenCalledWith( + expect.objectContaining({ + context: expect.objectContaining({ ready: true }), + }), + ) + expect(onEnter).not.toHaveBeenCalled() + + loaderGate.resolve({ someData: 42 }) + await load + + expect(onEnter).toHaveBeenCalledTimes(1) + expect(onEnter).toHaveBeenCalledWith( + expect.objectContaining({ + status: 'success', + context: expect.objectContaining({ ready: true }), + loaderData: { someData: 42 }, + }), + ) +}) + +test('#3293 existing behavior: uncached SPA navigation runs onEnter after beforeLoad and loader', async () => { + const beforeLoadGate = createControlledPromise<{ ready: true }>() + const loaderGate = createControlledPromise<{ someData: 42 }>() + const beforeLoad = vi.fn(() => beforeLoadGate) + const loader = vi.fn(() => loaderGate) + const onEnter = vi.fn() + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + beforeLoad, + loader, + onEnter, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + expect(beforeLoad).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + expect(onEnter).not.toHaveBeenCalled() + + const navigation = router.navigate({ to: '/about' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) + expect(loader).not.toHaveBeenCalled() + expect(onEnter).not.toHaveBeenCalled() + + beforeLoadGate.resolve({ ready: true }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + expect(loader).toHaveBeenCalledWith( + expect.objectContaining({ + context: expect.objectContaining({ ready: true }), + }), + ) + expect(onEnter).not.toHaveBeenCalled() + + loaderGate.resolve({ someData: 42 }) + await navigation + + expect(onEnter).toHaveBeenCalledTimes(1) + expect(onEnter).toHaveBeenCalledWith( + expect.objectContaining({ + status: 'success', + context: expect.objectContaining({ ready: true }), + loaderData: { someData: 42 }, + }), + ) +}) diff --git a/packages/router-core/tests/issue-3920-on-before-navigate-after-initial-redirect.test.ts b/packages/router-core/tests/issue-3920-on-before-navigate-after-initial-redirect.test.ts new file mode 100644 index 0000000000..6df66a08fa --- /dev/null +++ b/packages/router-core/tests/issue-3920-on-before-navigate-after-initial-redirect.test.ts @@ -0,0 +1,41 @@ +import { createMemoryHistory } from '@tanstack/history' +import { expect, onTestFinished, test } from 'vitest' +import { BaseRootRoute, BaseRoute, redirect } from '../src' +import { createTestRouter } from './routerTestUtils' + +// https://github.com/TanStack/router/issues/3920 +test('onBeforeNavigate fires after the initial load redirects', async () => { + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + beforeLoad: () => { + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const thirdRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/third', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute, thirdRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + }) + + await router.load() + expect(router.state.location.pathname).toBe('/target') + + const navigatedPaths: Array = [] + const unsub = router.subscribe('onBeforeNavigate', (event) => { + navigatedPaths.push(event.toLocation.pathname) + }) + onTestFinished(unsub) + + await router.navigate({ to: '/third' }) + + expect(navigatedPaths).toEqual(['/third']) +}) diff --git a/packages/router-core/tests/issue-3928-rapid-reload-abort.test.ts b/packages/router-core/tests/issue-3928-rapid-reload-abort.test.ts new file mode 100644 index 0000000000..a16258be0b --- /dev/null +++ b/packages/router-core/tests/issue-3928-rapid-reload-abort.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +type LoaderInvocation = { + resolve: (value: string) => void + signal: AbortSignal +} + +const createAbortableInvocation = ( + abortController: AbortController, + onAbort?: () => void, +) => { + let resolve!: (value: string) => void + const promise = new Promise((promiseResolve, reject) => { + const handleAbort = () => { + onAbort?.() + reject(new DOMException('signal is aborted without reason', 'AbortError')) + } + resolve = (value) => { + abortController.signal.removeEventListener('abort', handleAbort) + promiseResolve(value) + } + if (abortController.signal.aborted) { + handleAbort() + } else { + abortController.signal.addEventListener('abort', handleAbort, { + once: true, + }) + } + }) + return { + invocation: { resolve, signal: abortController.signal }, + promise, + } +} + +// https://github.com/TanStack/router/issues/3928 +describe('issue #3928: rapid reloads of a reused parent', () => { + test('one parent flight can serve rapid successors without clearing the latest child load', async () => { + const indexAbort = vi.fn() + const rootInvocations = new Map() + const indexInvocations = new Map() + + const rootRoute = new BaseRootRoute({ + shouldReload: true, + // Search is deliberately not part of this loader's key. Its active + // same-ID flight may serve successors while the child keys each filter. + loader: ({ abortController, location }) => { + const { invocation, promise } = + createAbortableInvocation(abortController) + const search = location.search as Record + const filter = typeof search.filter === 'string' ? search.filter : '' + rootInvocations.set(filter, invocation) + return promise + }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + validateSearch: (search: Record) => ({ + filter: typeof search.filter === 'string' ? search.filter : '', + }), + loaderDeps: ({ search }: { search: { filter: string } }) => ({ + filter: search.filter, + }), + loader: ({ + deps, + abortController, + }: { + deps: { filter: string } + abortController: AbortController + }) => { + const { invocation, promise } = createAbortableInvocation( + abortController, + indexAbort, + ) + indexInvocations.set(deps.filter, invocation) + return promise + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const initialLoad = router.load() + await vi.waitFor(() => { + expect(rootInvocations.has('')).toBe(true) + expect(indexInvocations.has('')).toBe(true) + }) + rootInvocations.get('')!.resolve('root:initial') + indexInvocations.get('')!.resolve('') + await initialLoad + + const navA = router.navigate({ to: '/', search: { filter: 'a' } }) + await vi.waitFor(() => { + expect(rootInvocations.has('a')).toBe(true) + expect(indexInvocations.has('a')).toBe(true) + }) + + const navAB = router.navigate({ to: '/', search: { filter: 'ab' } }) + await vi.waitFor(() => { + expect(indexInvocations.has('ab')).toBe(true) + expect(indexInvocations.get('a')!.signal.aborted).toBe(true) + expect(rootInvocations.get('a')!.signal.aborted).toBe(false) + }) + + const navABC = router.navigate({ to: '/', search: { filter: 'abc' } }) + await vi.waitFor(() => { + expect(indexInvocations.has('abc')).toBe(true) + expect(indexInvocations.get('ab')!.signal.aborted).toBe(true) + expect(rootInvocations.get('a')!.signal.aborted).toBe(false) + }) + + rootInvocations.get('a')!.resolve('root:a') + indexInvocations.get('abc')!.resolve('abc') + await Promise.all([navA, navAB, navABC]) + + expect(indexAbort).toHaveBeenCalledTimes(2) + expect(rootInvocations.size).toBe(2) + expect(rootInvocations.get('a')!.signal.aborted).toBe(false) + expect(indexInvocations.get('abc')!.signal.aborted).toBe(false) + expect(router.state.location.search).toEqual({ filter: 'abc' }) + expect(router.state.matches[0]).toMatchObject({ + status: 'success', + loaderData: 'root:a', + }) + expect(router.state.matches[1]).toMatchObject({ + status: 'success', + loaderData: 'abc', + }) + expect(router.state.matches.some((match) => match.status === 'error')).toBe( + false, + ) + }) +}) diff --git a/packages/router-core/tests/issue-4078-loader-notfound-root-boundary.test.ts b/packages/router-core/tests/issue-4078-loader-notfound-root-boundary.test.ts new file mode 100644 index 0000000000..c33521597b --- /dev/null +++ b/packages/router-core/tests/issue-4078-loader-notfound-root-boundary.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it, onTestFinished } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, + rootRouteId, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +// Existing Core attribution coverage related to: +// https://github.com/TanStack/router/issues/4078 +// https://github.com/TanStack/router/issues/2255 +// Throwing an untargeted notFound() in a child loader used to always render the +// defaultNotFoundComponent, even when __root__ defined a notFoundComponent +// (#4078). #2255 is the same asymmetry: a path-mismatch notFound renders the +// root component + notFoundComponent, but a loader-thrown notFound did not. +// +// At Router Core's boundary, root attribution is represented by the root match +// with _notFound. These assertions do not distinguish the +// configured root notFoundComponent from the router default; that reported +// rendering behavior requires framework-level coverage. +describe('#4078 / #2255 existing Core root-boundary attribution', () => { + const setup = (initialEntries: Array) => { + const loaderStarted = createControlledPromise() + const loaderResponse = createControlledPromise() + const rootRoute = new BaseRootRoute({ + component: () => 'Root', + notFoundComponent: () => 'Root not found', + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + loader: async () => { + loaderStarted.resolve() + await loaderResponse + throw notFound() + }, + component: () => 'About', + }) + + return { + router: createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + history: createMemoryHistory({ initialEntries }), + }), + loaderStarted, + loaderResponse, + } + } + + const getRootBoundaryProjection = ( + router: ReturnType['router'], + ) => { + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRouteId, + ) + + return { + routeId: rootMatch?.routeId, + _notFound: rootMatch?._notFound, + } + } + + it('an async loader notFound navigation selects the root boundary', async () => { + const { router, loaderStarted, loaderResponse } = setup(['/']) + await router.load() + + const navigation = router.navigate({ to: '/about' }) + onTestFinished(() => { + loaderResponse.resolve() + }) + await loaderStarted + expect(loaderResponse.status).toBe('pending') + loaderResponse.resolve() + + await navigation + + expect(router.state.location.pathname).toBe('/about') + expect(getRootBoundaryProjection(router)).toEqual({ + routeId: rootRouteId, + _notFound: true, + }) + }) + + it('matches the root-boundary projection of an unmatched URL (#2255 parity)', async () => { + const unmatched = setup(['/missing']) + await unmatched.router.load() + const unmatchedProjection = getRootBoundaryProjection(unmatched.router) + expect(unmatchedProjection).toEqual({ + routeId: rootRouteId, + _notFound: true, + }) + + const loaderNotFound = setup(['/']) + await loaderNotFound.router.load() + const navigation = loaderNotFound.router.navigate({ to: '/about' }) + await loaderNotFound.loaderStarted + loaderNotFound.loaderResponse.resolve() + await navigation + + expect(getRootBoundaryProjection(loaderNotFound.router)).toEqual( + unmatchedProjection, + ) + }) +}) diff --git a/packages/router-core/tests/issue-4444-param-parse-error-lazy-child.test.ts b/packages/router-core/tests/issue-4444-param-parse-error-lazy-child.test.ts new file mode 100644 index 0000000000..9a996f9e4a --- /dev/null +++ b/packages/router-core/tests/issue-4444-param-parse-error-lazy-child.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, PathParamError } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Issue #4444: when a route's params.parse throws and one of its children is + * lazily loaded, the router used to stay "pending" forever: the lazy child's + * chunk was never requested, its match never settled, and framework + * transitioners could never reach idle. + * + * Desired behavior: the param parse error is a serial failure — the failing + * route commits status 'error' for its error boundary, descendants below the + * boundary are trimmed out of the lane with their load promises settled, and + * router.load() resolves with no match left pending. + */ +describe('issue #4444: param parse error on a route with a lazy child', () => { + test('load settles, commits the error boundary, and leaves no match stuck pending', async () => { + const rootRoute = new BaseRootRoute({}) + const langRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/lang/$lang', + params: { + parse: ({ lang }: { lang: string }) => { + if (lang !== 'en') { + throw new Error(`Unsupported language: ${lang}`) + } + return { lang } + }, + stringify: ({ lang }: { lang: string }) => ({ lang }), + }, + errorComponent: () => null, + }) + const lazyChildRoute = new BaseRoute({ + getParentRoute: () => langRoute, + path: '/lazy', + }) + const lazyFn = vi.fn(() => + Promise.resolve({ + options: { + id: lazyChildRoute.id, + component: () => null, + }, + }), + ) + lazyChildRoute.lazy(lazyFn) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + langRoute.addChildren([lazyChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/lang/es/lazy'] }), + }) + + // The reported bug: this load never reached a settled render state. + await router.load() + expect(router.state.status).toBe('idle') + + // The failing route commits the parse error for its error boundary… + const langMatch = router.state.matches.find( + (match) => match.routeId === langRoute.id, + ) + expect(langMatch?.status).toBe('error') + expect(langMatch?.error).toBeInstanceOf(PathParamError) + + // …while the structurally matched lazy child remains unresolved and hidden + // below that boundary without starting its chunk. + expect( + router.state.matches.find((match) => match.routeId === lazyChildRoute.id), + ).toMatchObject({ status: 'pending', isFetching: false }) + expect(lazyFn).not.toHaveBeenCalled() + expect(router.state.isLoading).toBe(false) + }) +}) diff --git a/packages/router-core/tests/issue-4572-preload-root-beforeload-flags.test.ts b/packages/router-core/tests/issue-4572-preload-root-beforeload-flags.test.ts new file mode 100644 index 0000000000..23495e5001 --- /dev/null +++ b/packages/router-core/tests/issue-4572-preload-root-beforeload-flags.test.ts @@ -0,0 +1,173 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Issue #4572: an intent preload used to re-trigger active beforeLoad + * callbacks with stale navigation flags. Direct preloadRoute calls provide + * the core-level reduction of the reported Link hover behavior. + * + * A completed beforeLoad result is never cached. Every new preload therefore + * contextualizes its full route lane with fresh preload flags. + */ + +function createPreloadFixture() { + const rootBeforeLoad = vi.fn() + const indexBeforeLoad = vi.fn() + const aboutBeforeLoad = vi.fn() + const bagBeforeLoad = vi.fn() + const nestedBeforeLoad = vi.fn() + + const rootRoute = new BaseRootRoute({ beforeLoad: rootBeforeLoad }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + beforeLoad: indexBeforeLoad, + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + beforeLoad: aboutBeforeLoad, + }) + const bagRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '_bag', + beforeLoad: bagBeforeLoad, + }) + const nestedRoute = new BaseRoute({ + getParentRoute: () => bagRoute, + path: '/nested', + beforeLoad: nestedBeforeLoad, + }) + + return { + rootBeforeLoad, + indexBeforeLoad, + aboutBeforeLoad, + bagBeforeLoad, + nestedBeforeLoad, + nestedRoute, + router: createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + aboutRoute, + bagRoute.addChildren([nestedRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }), + } +} + +test('#4572: sibling preload contextualizes the full target lane with preload flags', async () => { + const { + rootBeforeLoad, + indexBeforeLoad, + aboutBeforeLoad, + bagBeforeLoad, + nestedBeforeLoad, + router, + } = createPreloadFixture() + + await router.load() + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(indexBeforeLoad).toHaveBeenCalledTimes(1) + expect(rootBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ cause: 'enter', preload: false }), + ) + + await router.preloadRoute({ to: '/about' }) + expect(rootBeforeLoad).toHaveBeenCalledTimes(2) + expect(indexBeforeLoad).toHaveBeenCalledTimes(1) + expect(aboutBeforeLoad).toHaveBeenCalledTimes(1) + expect(aboutBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ cause: 'preload', preload: true }), + ) + expect(rootBeforeLoad).toHaveBeenLastCalledWith( + expect.objectContaining({ cause: 'preload', preload: true }), + ) + expect(bagBeforeLoad).not.toHaveBeenCalled() + expect(nestedBeforeLoad).not.toHaveBeenCalled() +}) + +test('#4572: active-route preload reruns beforeLoad with preload flags', async () => { + const { + rootBeforeLoad, + indexBeforeLoad, + aboutBeforeLoad, + bagBeforeLoad, + nestedBeforeLoad, + router, + } = createPreloadFixture() + + await router.load() + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(indexBeforeLoad).toHaveBeenCalledTimes(1) + expect(rootBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ cause: 'enter', preload: false }), + ) + + rootBeforeLoad.mockClear() + indexBeforeLoad.mockClear() + await router.preloadRoute({ to: '/' }) + expect(rootBeforeLoad).toHaveBeenCalledOnce() + expect(indexBeforeLoad).toHaveBeenCalledOnce() + expect(rootBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ cause: 'preload', preload: true }), + ) + expect(indexBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ cause: 'preload', preload: true }), + ) + expect(aboutBeforeLoad).not.toHaveBeenCalled() + expect(bagBeforeLoad).not.toHaveBeenCalled() + expect(nestedBeforeLoad).not.toHaveBeenCalled() +}) + +test('#4572: active nested preload reruns its full pathless lane', async () => { + const { + rootBeforeLoad, + indexBeforeLoad, + aboutBeforeLoad, + bagBeforeLoad, + nestedBeforeLoad, + nestedRoute, + router, + } = createPreloadFixture() + + await router.load() + await router.navigate({ to: '/_bag/nested' }) + expect(rootBeforeLoad).toHaveBeenCalledTimes(2) + expect(rootBeforeLoad).toHaveBeenLastCalledWith( + expect.objectContaining({ cause: 'stay', preload: false }), + ) + expect(indexBeforeLoad).toHaveBeenCalledTimes(1) + expect(aboutBeforeLoad).not.toHaveBeenCalled() + expect(bagBeforeLoad).toHaveBeenCalledTimes(1) + expect(bagBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ cause: 'enter', preload: false }), + ) + expect(nestedBeforeLoad).toHaveBeenCalledTimes(1) + expect(nestedBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ cause: 'enter', preload: false }), + ) + expect( + router.state.matches.some((match) => match.routeId === nestedRoute.id), + ).toBe(true) + rootBeforeLoad.mockClear() + indexBeforeLoad.mockClear() + aboutBeforeLoad.mockClear() + bagBeforeLoad.mockClear() + nestedBeforeLoad.mockClear() + + await router.preloadRoute({ to: '/_bag/nested' }) + expect(rootBeforeLoad).toHaveBeenCalledOnce() + expect(indexBeforeLoad).not.toHaveBeenCalled() + expect(aboutBeforeLoad).not.toHaveBeenCalled() + expect(bagBeforeLoad).toHaveBeenCalledOnce() + expect(nestedBeforeLoad).toHaveBeenCalledOnce() + for (const beforeLoad of [rootBeforeLoad, bagBeforeLoad, nestedBeforeLoad]) { + expect(beforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ cause: 'preload', preload: true }), + ) + } +}) diff --git a/packages/router-core/tests/issue-4684-head-on-beforeload-error.test.ts b/packages/router-core/tests/issue-4684-head-on-beforeload-error.test.ts new file mode 100644 index 0000000000..6bf84e75ce --- /dev/null +++ b/packages/router-core/tests/issue-4684-head-on-beforeload-error.test.ts @@ -0,0 +1,84 @@ +import { createMemoryHistory } from '@tanstack/history' +import { describe, expect, test } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +// Existing Core projection coverage related to: +// https://github.com/TanStack/router/issues/4684 +// +// When beforeLoad throws, head() must still execute for the retained lane — +// the root head owns global stylesheets/title that the errorComponent page +// depends on, and the failing route's own head can provide error-specific +// head content. Rendering those projections through HeadContent is a framework +// concern; this suite asserts the Core-owned match projections. +describe('#4684 existing Core behavior: head executes when beforeLoad throws', () => { + const setup = (isServer: boolean) => { + const beforeLoadError = new Error('beforeLoad failed') + const rootHead = () => ({ + meta: [{ title: 'Root title' }], + links: [{ rel: 'stylesheet', href: '/global.css' }], + }) + const rootRoute = new BaseRootRoute({ head: rootHead }) + const failingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/fail', + beforeLoad: () => { + throw beforeLoadError + }, + head: ({ match }) => ({ + meta: [{ title: match.error ? 'Error title' : 'Success title' }], + }), + errorComponent: () => 'error', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([failingRoute]), + history: createMemoryHistory({ initialEntries: ['/fail'] }), + isServer, + }) + + return { router, rootRoute, failingRoute, beforeLoadError } + } + + test('server load projects root and failing-route heads for the error lane', async () => { + const { router, rootRoute, failingRoute, beforeLoadError } = setup(true) + + const response = await loadServerResponse(router, '/fail') + + expect(response.status).toBe(500) + + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRoute.id, + ) + const failingMatch = router.state.matches.find( + (match) => match.routeId === failingRoute.id, + ) + expect(rootMatch?.meta).toEqual([{ title: 'Root title' }]) + expect(rootMatch?.links).toEqual([ + { rel: 'stylesheet', href: '/global.css' }, + ]) + expect(failingMatch?.status).toBe('error') + expect(failingMatch?.error).toBe(beforeLoadError) + expect(failingMatch?.meta).toEqual([{ title: 'Error title' }]) + }) + + test('client load projects root and failing-route heads for the error lane', async () => { + const { router, rootRoute, failingRoute, beforeLoadError } = setup(false) + + await router.load() + + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRoute.id, + ) + const failingMatch = router.state.matches.find( + (match) => match.routeId === failingRoute.id, + ) + expect(rootMatch?.meta).toEqual([{ title: 'Root title' }]) + expect(rootMatch?.links).toEqual([ + { rel: 'stylesheet', href: '/global.css' }, + ]) + expect(failingMatch?.status).toBe('error') + expect(failingMatch?.error).toBe(beforeLoadError) + expect(failingMatch?.meta).toEqual([{ title: 'Error title' }]) + }) +}) diff --git a/packages/router-core/tests/issue-4696-parent-context-search-normalization.test.ts b/packages/router-core/tests/issue-4696-parent-context-search-normalization.test.ts new file mode 100644 index 0000000000..20ef368318 --- /dev/null +++ b/packages/router-core/tests/issue-4696-parent-context-search-normalization.test.ts @@ -0,0 +1,102 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +// Existing-behavior coverage for https://github.com/TanStack/router/issues/4696 +test('#4696 existing behavior: normalized child search keeps reused parent context', async () => { + const rootLoader = vi.fn( + ({ context }: { context: Record }) => context, + ) + const dashboardBeforeLoad = vi.fn( + ({ context }: { context: Record }) => { + if (!context.isAuthenticated) { + throw new Error('Authentication context was lost') + } + }, + ) + const rootRoute = new BaseRootRoute({ + beforeLoad: async () => { + await Promise.resolve() + return { + initialData: { + user: { email: 'mr.user@gmail.com', role: 'user' }, + }, + initializationError: undefined, + isAuthenticated: true, + isAdmin: false, + } + }, + loader: rootLoader, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const dashboardRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/dashboard', + validateSearch: () => ({ page: 0 }), + beforeLoad: dashboardBeforeLoad, + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, dashboardRoute]), + history, + }) + + await router.load() + expect(rootLoader).toHaveBeenCalledTimes(1) + expect(rootLoader.mock.calls[0]?.[0].context).toMatchObject({ + isAuthenticated: true, + }) + expect(router.state.location.pathname).toBe('/') + router.update({ + history: createMemoryHistory({ + initialEntries: ['/dashboard?page=0'], + }), + }) + await router.load() + expect(router.state.location.pathname).toBe('/dashboard') + expect(rootLoader).toHaveBeenCalledTimes(1) + expect(dashboardBeforeLoad).toHaveBeenCalledTimes(1) + expect(dashboardBeforeLoad).toHaveBeenLastCalledWith( + expect.objectContaining({ + context: expect.objectContaining({ isAuthenticated: true }), + }), + ) + expect( + router.state.matches.find((match) => match.routeId === rootRoute.id) + ?.loaderData, + ).toMatchObject({ isAuthenticated: true }) + + dashboardBeforeLoad.mockClear() + router.update({ + history: createMemoryHistory({ initialEntries: ['/dashboard'] }), + }) + await router.load() + + expect(dashboardBeforeLoad).toHaveBeenCalledTimes(1) + expect(dashboardBeforeLoad).toHaveBeenLastCalledWith( + expect.objectContaining({ + context: expect.objectContaining({ isAuthenticated: true }), + }), + ) + expect(rootLoader).toHaveBeenCalledTimes(1) + expect(router.state.location.pathname).toBe('/dashboard') + const rootMatch = router.state.matches.find( + (match) => match.routeId === rootRoute.id, + ) + const dashboardMatch = router.state.matches.find( + (match) => match.routeId === dashboardRoute.id, + ) + expect(rootMatch?.loaderData).toMatchObject({ + isAuthenticated: true, + isAdmin: false, + }) + expect(dashboardMatch).toMatchObject({ + status: 'success', + search: { page: 0 }, + searchError: undefined, + }) +}) diff --git a/packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts b/packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts new file mode 100644 index 0000000000..5ee450ee35 --- /dev/null +++ b/packages/router-core/tests/issue-5106-hydrated-notfound-boundary.test.ts @@ -0,0 +1,274 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, isNotFound } from '../src' +import { hydrate } from '../src/ssr/client' +import { dehydrateSsrMatchId } from '../src/ssr/ssr-match-id' +import { createTestRouter } from './routerTestUtils' +import type { TsrSsrGlobal } from '../src/ssr/types' +import type { Manifest } from '../src/manifest' + +const testManifest: Manifest = { routes: {} } + +// The child-owned case is supplemental Core state coverage for +// https://github.com/TanStack/router/issues/5106. The reported rendered React +// hydration symptom is not observable at this layer. The ancestor-owned case +// is a generic terminal-prefix invariant, not an issue #5106 reproduction. +describe('hydrated notFound boundary coverage', () => { + let mockWindow: { $_TSR?: TsrSsrGlobal } + + beforeEach(() => { + mockWindow = {} + ;(global as any).window = mockWindow + }) + + afterEach(() => { + delete (global as any).window + vi.restoreAllMocks() + }) + + it('#5106 existing behavior: adopts a child-owned boundary without invoking its loaders during hydration', async () => { + const postsLoader = vi.fn(() => 'posts-data') + const postLoader = vi.fn(() => 'post-data') + const history = createMemoryHistory({ + initialEntries: ['/posts/i-do-not-exist'], + }) + + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + loader: postsLoader, + component: () => 'Posts', + }) + const postRoute = new BaseRoute({ + getParentRoute: () => postsRoute, + path: '/$postId', + loader: postLoader, + component: () => 'Post', + notFoundComponent: () => 'Post not found', + }) + const safeLoader = vi.fn(() => 'safe-data') + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + loader: safeLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + postsRoute.addChildren([postRoute]), + safeRoute, + ]), + history, + isServer: false, + }) + + const matches = router.matchRoutes(router.stores.location.get()) + expect(matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + postsRoute.id, + postRoute.id, + ]) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + // This synthetic payload models a child-owned boundary, so its + // terminal prefix includes the child match. + matches: [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success' as const, + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'success' as const, + l: 'posts-data', + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[2]!.id), + s: 'notFound' as const, + e: { isNotFound: true }, + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + + const stateMatches = router.state.matches + expect(router.state.location.pathname).toBe('/posts/i-do-not-exist') + expect(router.state.isLoading).toBe(false) + expect(stateMatches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + postsRoute.id, + postRoute.id, + ]) + + // The parent keeps the data and status supplied by the payload. + expect(stateMatches[1]!.status).toBe('success') + expect(stateMatches[1]!.loaderData).toBe('posts-data') + + // The child is adopted as the notFound boundary. + expect(stateMatches[2]!.status).toBe('notFound') + expect(isNotFound(stateMatches[2]!.error)).toBe(true) + + // Hydration does not invoke either route loader represented by the + // payload. + expect(postsLoader).not.toHaveBeenCalled() + expect(postLoader).not.toHaveBeenCalled() + expect(safeLoader).not.toHaveBeenCalled() + + // Supplemental public liveness coverage: a later client navigation still + // completes. This does not exercise React's rendered hydration boundary. + await router.navigate({ to: '/safe' }) + expect(router.state.location.pathname).toBe('/safe') + expect(router.state.isLoading).toBe(false) + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + safeRoute.id, + ]) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: safeRoute.id, + status: 'success', + loaderData: 'safe-data', + }) + expect(safeLoader).toHaveBeenCalledTimes(1) + expect(postsLoader).not.toHaveBeenCalled() + expect(postLoader).not.toHaveBeenCalled() + }) + + it('generic terminal-prefix invariant: adopts an ancestor-owned boundary without presenting the omitted child', async () => { + const postsLoader = vi.fn(() => 'posts-data') + const postLoader = vi.fn(() => 'post-data') + const history = createMemoryHistory({ + initialEntries: ['/posts/i-do-not-exist'], + }) + + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + loader: postsLoader, + component: () => 'Posts', + notFoundComponent: () => 'Posts not found', + }) + // The child has no notFoundComponent, so the synthetic payload below + // represents the parent as the selected boundary and omits the child. + const postRoute = new BaseRoute({ + getParentRoute: () => postsRoute, + path: '/$postId', + loader: postLoader, + component: () => 'Post', + }) + const safeLoader = vi.fn(() => 'safe-data') + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + loader: safeLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + postsRoute.addChildren([postRoute]), + safeRoute, + ]), + history, + isServer: false, + }) + + const matches = router.matchRoutes(router.stores.location.get()) + expect(matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + postsRoute.id, + postRoute.id, + ]) + + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + // The represented terminal lane is capped at the parent boundary. + matches: [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success' as const, + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'notFound' as const, + l: 'posts-data', + e: { isNotFound: true }, + ssr: true, + u: Date.now(), + }, + ], + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + initialized: false, + } + + await hydrate(router) + + // Hydration reconstructs the complete branch but executes only the + // represented terminal prefix. + const stateMatches = router.state.matches + expect(router.state.location.pathname).toBe('/posts/i-do-not-exist') + expect(router.state.isLoading).toBe(false) + expect(stateMatches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + postsRoute.id, + postRoute.id, + ]) + expect(stateMatches[1]!.routeId).toBe(postsRoute.id) + expect(stateMatches[1]!.status).toBe('notFound') + expect(isNotFound(stateMatches[1]!.error)).toBe(true) + // The boundary keeps the parent loader data supplied by the payload. + expect(stateMatches[1]!.loaderData).toBe('posts-data') + expect(stateMatches[2]).toMatchObject({ + routeId: postRoute.id, + status: 'pending', + }) + + // Neither the omitted child nor the represented parent runs client-side. + expect(postLoader).not.toHaveBeenCalled() + expect(postsLoader).not.toHaveBeenCalled() + expect(safeLoader).not.toHaveBeenCalled() + + // A later client navigation remains usable after adopting the prefix. + await router.navigate({ to: '/safe' }) + expect(router.state.location.pathname).toBe('/safe') + expect(router.state.isLoading).toBe(false) + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + safeRoute.id, + ]) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: safeRoute.id, + status: 'success', + loaderData: 'safe-data', + }) + expect(safeLoader).toHaveBeenCalledTimes(1) + expect(postLoader).not.toHaveBeenCalled() + expect(postsLoader).not.toHaveBeenCalled() + }) +}) diff --git a/packages/router-core/tests/issue-5427-hydration-root-global-not-found.test.ts b/packages/router-core/tests/issue-5427-hydration-root-global-not-found.test.ts new file mode 100644 index 0000000000..0a6119b349 --- /dev/null +++ b/packages/router-core/tests/issue-5427-hydration-root-global-not-found.test.ts @@ -0,0 +1,136 @@ +import { createMemoryHistory } from '@tanstack/history' +import { describe, expect, onTestFinished, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { hydrate } from '../src/ssr/client' +import { dehydrateMatch } from '../src/ssr/ssr-server' +import { createTestRouter } from './routerTestUtils' +import type { TsrSsrGlobal } from '../src/ssr/types' + +function createRouter(initialEntry: string, isServer: boolean) { + const rootRoute = new BaseRootRoute({ + notFoundComponent: () => 'Root not found', + }) + const notFoundRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/404', + component: () => 'Not found route', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([notFoundRoute]), + history: createMemoryHistory({ initialEntries: [initialEntry] }), + isServer, + }) + + return { rootRoute, router } +} + +function createLayoutRouter(initialEntry: string, isServer: boolean) { + const rootRoute = new BaseRootRoute({}) + const layoutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + id: '_layout', + notFoundComponent: () => 'Layout not found', + }) + const notFoundRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '/404', + }) + const notFoundIndexRoute = new BaseRoute({ + getParentRoute: () => notFoundRoute, + path: '/', + }) + const agentsRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '/agents', + }) + const skillAgentRoute = new BaseRoute({ + getParentRoute: () => agentsRoute, + path: '/skill-agent', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + layoutRoute.addChildren([ + notFoundRoute.addChildren([notFoundIndexRoute]), + agentsRoute.addChildren([skillAgentRoute]), + ]), + ]), + history: createMemoryHistory({ initialEntries: [initialEntry] }), + isServer, + }) + + return { layoutRoute, router } +} + +describe('issue #5427: root-only global not-found hydration', () => { + test('resolves the client URL when the dehydrated /404 lane has a child match', async () => { + const { router: serverRouter } = createRouter('/404', true) + await serverRouter.load() + + const bootstrap: TsrSsrGlobal = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: serverRouter.state.matches.map(dehydrateMatch), + }, + h: () => {}, + e: () => {}, + c: () => {}, + p: () => {}, + buffer: [], + } + const previousBootstrap = window.$_TSR + window.$_TSR = bootstrap + onTestFinished(() => { + window.$_TSR = previousBootstrap + }) + + const { rootRoute, router } = createRouter('/missing', false) + + await hydrate(router) + await vi.waitFor(() => { + expect(router.state.resolvedLocation?.pathname).toBe('/missing') + }) + + expect(router.state.matches).toHaveLength(1) + expect(router.state.matches[0]).toMatchObject({ + routeId: rootRoute.id, + _notFound: true, + }) + }) + + test('resolves a fuzzy client URL capped by an ancestor layout boundary', async () => { + const { router: serverRouter } = createLayoutRouter('/404', true) + await serverRouter.load() + expect(serverRouter.state.matches).toHaveLength(4) + + const bootstrap: TsrSsrGlobal = { + router: { + manifest: { routes: {} }, + dehydratedData: {}, + matches: serverRouter.state.matches.map(dehydrateMatch), + }, + h: () => {}, + e: () => {}, + c: () => {}, + p: () => {}, + buffer: [], + } + const previousBootstrap = window.$_TSR + window.$_TSR = bootstrap + onTestFinished(() => { + window.$_TSR = previousBootstrap + }) + + const { layoutRoute, router } = createLayoutRouter('/agents/missing', false) + + await hydrate(router) + + expect(router.state.resolvedLocation?.pathname).toBe('/agents/missing') + expect(router.state.matches).toHaveLength(3) + expect(router.state.matches[1]).toMatchObject({ + routeId: layoutRoute.id, + _notFound: true, + }) + }) +}) diff --git a/packages/router-core/tests/issue-6107-preload-chunk-failure.test.ts b/packages/router-core/tests/issue-6107-preload-chunk-failure.test.ts new file mode 100644 index 0000000000..32539b3676 --- /dev/null +++ b/packages/router-core/tests/issue-6107-preload-chunk-failure.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Issue #6107: going offline and hovering a link (preload intent) made the + * failed dynamic import surface as an unhandled rejection in the console, and + * the error never reached the route's error component. + * + * Desired behavior: + * - a preload whose lazy chunk rejects resolves non-fatally, and + * - the failed chunk is evicted, so the subsequent real navigation retries + * the import and commits the chunk error onto the match (status 'error'), + * which is what framework error components render. + */ +describe('issue #6107: failed dynamic import of a lazy route chunk', () => { + test('preloadRoute failure is non-fatal and navigation retries and commits the chunk error', async () => { + const chunkError = new TypeError( + 'Failed to fetch dynamically imported module: /assets/posts.lazy-abc123.js', + ) + const lazyRoute = vi.fn(() => Promise.reject(chunkError)) + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }).lazy(lazyRoute) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([postsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + + await router.preloadRoute({ to: '/posts' }) + expect(lazyRoute).toHaveBeenCalled() + const lazyCallsAfterPreload = lazyRoute.mock.calls.length + + await router.navigate({ to: '/posts' }) + const postsMatch = router.state.matches.find( + (match) => match.routeId === postsRoute.id, + ) + expect(lazyRoute.mock.calls.length).toBeGreaterThan(lazyCallsAfterPreload) + expect(postsMatch?.status).toBe('error') + expect(postsMatch?.error).toBe(chunkError) + }) +}) diff --git a/packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts b/packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts new file mode 100644 index 0000000000..a9f56ba8d3 --- /dev/null +++ b/packages/router-core/tests/issue-6221-head-waits-for-loader.test.ts @@ -0,0 +1,162 @@ +import { createMemoryHistory } from '@tanstack/history' +import { describe, expect, onTestFinished, test, vi } from 'vitest' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +// https://github.com/TanStack/router/issues/6221 +// +// head() must never compute from loaderData older than the data the lane +// commits. Two reported shapes: +// 1. Revisiting a route whose previous visit ended in notFound — the head +// must see the fresh successful loaderData, not run before the loader. +// 2. Revisiting a cached success match that gets a stale reload — the head +// title must not lag one loaderData run behind. +describe('issue #6221: head does not run before loader data is ready', () => { + test('existing-behavior control: head sees fresh loaderData after a notFound visit', async () => { + let authed = false + const articleResponse = createControlledPromise<{ title: string }>() + const successfulLoadStarted = createControlledPromise() + + const articleLoader = async () => { + if (!authed) { + await Promise.resolve() + throw notFound() + } + + successfulLoadStarted.resolve() + return articleResponse + } + + const rootRoute = new BaseRootRoute({}) + const dashboardRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/dashboard', + }) + const articleRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/article', + loader: articleLoader, + notFoundComponent: () => 'Not found', + head: ({ loaderData }) => ({ + meta: [{ title: loaderData?.title ?? 'Generic title' }], + }), + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([dashboardRoute, articleRoute]), + history: createMemoryHistory({ initialEntries: ['/article'] }), + }) + const backLoadFinished = createControlledPromise() + let backLoadStarted = false + let unsubscribe: (() => void) | undefined + + try { + await router.load() + const notFoundMatch = router.state.matches.find( + (match) => match.routeId === articleRoute.id, + ) + expect(notFoundMatch?.status).toBe('notFound') + expect(notFoundMatch?.meta).toEqual([{ title: 'Generic title' }]) + + // Model the reported auth redirect and browser Back without relying on a + // wall-clock loader delay. + authed = true + await router.navigate({ to: '/dashboard' }) + unsubscribe = router.history.subscribe(() => { + backLoadStarted = true + void router.load().then( + () => backLoadFinished.resolve(), + (error) => backLoadFinished.reject(error), + ) + }) + router.history.back() + await successfulLoadStarted + expect(articleResponse.status).toBe('pending') + + articleResponse.resolve({ title: 'Article 123' }) + await backLoadFinished + + const articleMatch = router.state.matches.find( + (match) => match.routeId === articleRoute.id, + ) + expect(articleMatch?.status).toBe('success') + expect(articleMatch?.loaderData).toEqual({ title: 'Article 123' }) + expect(articleMatch?.meta).toEqual([{ title: 'Article 123' }]) + } finally { + articleResponse.resolve({ title: 'Article 123' }) + if (backLoadStarted) { + await backLoadFinished.catch(() => undefined) + } + unsubscribe?.() + } + }) + + test('head title does not lag one loaderData run behind on revisits', async () => { + const secondLoaderStarted = createControlledPromise() + const secondLoaderResponse = createControlledPromise<{ author: string }>() + let version = 0 + const quoteLoader = () => { + version += 1 + if (version === 2) { + secondLoaderStarted.resolve() + return secondLoaderResponse + } + + return { author: 'author-1' } + } + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const quoteRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/quote', + loader: quoteLoader, + staleTime: 0, + head: ({ loaderData }) => ({ + meta: [{ title: `Quote by ${loaderData?.author ?? '...'}` }], + }), + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, quoteRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const getQuoteMatch = () => + router.state.matches.find((match) => match.routeId === quoteRoute.id) + onTestFinished(() => { + secondLoaderResponse.resolve({ author: 'author-2' }) + }) + + await router.load() + + await router.navigate({ to: '/quote' }) + expect(getQuoteMatch()?.loaderData).toEqual({ author: 'author-1' }) + expect(getQuoteMatch()?.meta).toEqual([{ title: 'Quote by author-1' }]) + + await router.navigate({ to: '/' }) + const revisit = router.navigate({ to: '/quote' }) + await secondLoaderStarted + await revisit + + // The cached generation remains internally consistent while its stale + // loader is pending in the background. + expect(secondLoaderResponse.status).toBe('pending') + expect(getQuoteMatch()?.loaderData).toEqual({ author: 'author-1' }) + expect(getQuoteMatch()?.meta).toEqual([{ title: 'Quote by author-1' }]) + + secondLoaderResponse.resolve({ author: 'author-2' }) + await vi.waitFor(() => { + expect(getQuoteMatch()?.loaderData).toEqual({ author: 'author-2' }) + expect(getQuoteMatch()?.meta).toEqual([{ title: 'Quote by author-2' }]) + }) + }) +}) diff --git a/packages/router-core/tests/issue-6351-fuzzy-notfound-layout.test.ts b/packages/router-core/tests/issue-6351-fuzzy-notfound-layout.test.ts new file mode 100644 index 0000000000..9fec0992a4 --- /dev/null +++ b/packages/router-core/tests/issue-6351-fuzzy-notfound-layout.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * https://github.com/TanStack/router/issues/6351 + * + * A fuzzy (unmatched-URL) 404 must be attributed to the nearest matched + * ancestor that can actually render it: the deepest matched route with + * children that defines a `notFoundComponent`. Attributing it to the + * deepest matched route with children regardless of whether it has a + * `notFoundComponent` skips pathless-layout/ancestor `notFoundComponent`s + * and makes the framework fall back to `defaultNotFoundComponent`. + * + * When no matched route defines a `notFoundComponent`, the previous + * behavior (deepest matched route with children) is preserved, and + * `notFoundMode: 'root'` still attributes the 404 to the root route. + * This Core suite asserts boundary ownership; rendered fallback output needs + * framework-level coverage. + */ + +function setup(opts: { + layoutNotFoundComponent?: () => unknown + agentsNotFoundComponent?: () => unknown + agentsContext?: () => Record + agentsBeforeLoad?: () => Record + agentsLoader?: () => null + notFoundMode?: 'fuzzy' | 'root' + isServer?: boolean +}) { + const rootRoute = new BaseRootRoute({}) + const layoutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + id: '_authenticated', + notFoundComponent: opts.layoutNotFoundComponent, + }) + const agentsRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '/agents', + notFoundComponent: opts.agentsNotFoundComponent, + context: opts.agentsContext, + beforeLoad: opts.agentsBeforeLoad, + loader: opts.agentsLoader, + }) + const skillAgentRoute = new BaseRoute({ + getParentRoute: () => agentsRoute, + path: '/skill-agent', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + layoutRoute.addChildren([agentsRoute.addChildren([skillAgentRoute])]), + ]), + history: createMemoryHistory({ initialEntries: ['/agents/skill-agen'] }), + notFoundMode: opts.notFoundMode, + isServer: opts.isServer, + }) + + return { router, rootRoute, layoutRoute, agentsRoute } +} + +function _notFoundRouteIds(router: { + state: { matches: Array<{ routeId: string; _notFound?: boolean }> } +}) { + return router.state.matches + .filter((match) => match._notFound) + .map((match) => match.routeId) +} + +describe('issue #6351: fuzzy notFound honors pathless layout boundaries', () => { + test('lands on the pathless layout when the deeper route has no boundary', async () => { + const { router, rootRoute, layoutRoute, agentsRoute } = setup({ + layoutNotFoundComponent: () => 'layout not found', + }) + + await router.load() + + expect(router.state.location.pathname).toBe('/agents/skill-agen') + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + layoutRoute.id, + agentsRoute.id, + ]) + expect(_notFoundRouteIds(router)).toEqual([layoutRoute.id]) + }) + + test('boundary-enabled control: prefers the deeper matched route', async () => { + const { router, agentsRoute } = setup({ + layoutNotFoundComponent: () => 'layout not found', + agentsNotFoundComponent: () => 'agents not found', + }) + + await router.load() + + expect(_notFoundRouteIds(router)).toEqual([agentsRoute.id]) + }) + + test.each(['client', 'server'] as const)( + 'fuzzy ancestor 404 skips hidden descendant lifecycle callbacks on the %s', + async (environment) => { + const context = vi.fn(() => ({})) + const beforeLoad = vi.fn(() => ({})) + const loader = vi.fn(() => null) + const { router } = setup({ + layoutNotFoundComponent: () => 'layout not found', + agentsContext: context, + agentsBeforeLoad: beforeLoad, + agentsLoader: loader, + notFoundMode: 'fuzzy', + isServer: environment === 'server', + }) + + await router.load() + + expect(context).not.toHaveBeenCalled() + expect(beforeLoad).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + }, + ) +}) + +describe('generic global notFound attribution controls', () => { + test('fuzzy mode falls back to the deepest matched route with children when no boundary exists', async () => { + const { router, agentsRoute } = setup({}) + + await router.load() + + expect(_notFoundRouteIds(router)).toEqual([agentsRoute.id]) + }) + + test('root mode attributes the notFound to root even when a layout boundary exists', async () => { + const { router, rootRoute } = setup({ + layoutNotFoundComponent: () => 'layout not found', + notFoundMode: 'root', + }) + + await router.load() + + expect(_notFoundRouteIds(router)).toEqual([rootRoute.id]) + }) +}) diff --git a/packages/router-core/tests/issue-6371-search-default-normalization-abort.test.ts b/packages/router-core/tests/issue-6371-search-default-normalization-abort.test.ts new file mode 100644 index 0000000000..6f039b45da --- /dev/null +++ b/packages/router-core/tests/issue-6371-search-default-normalization-abort.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, trimPathRight } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Repro for https://github.com/TanStack/router/issues/6371 + * + * Entering a route directly via URL without search params, while + * validateSearch supplies defaults, makes the framework Transitioner commit a + * canonical replace-navigation (URL with the defaulted search) right after + * the mount load already started. The canonical pass may reuse that loader + * generation, and the URL-only replacement must not abort it or surface an + * AbortError. + */ + +describe('issue #6371: search default normalization aborts the mount load silently', () => { + test('canonical replace after validateSearch defaults does not surface AbortError', async () => { + const invocations: Array<{ resolve: () => void; signal: AbortSignal }> = [] + + const rootRoute = new BaseRootRoute({}) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + validateSearch: (search: Record) => ({ + page: typeof search.page === 'number' ? search.page : 1, + }), + loader: ({ abortController }: { abortController: AbortController }) => + new Promise((resolve, reject) => { + invocations.push({ + resolve: () => resolve('about data'), + signal: abortController.signal, + }) + abortController.signal.addEventListener('abort', () => { + const abortError = new Error('signal is aborted without reason') + abortError.name = 'AbortError' + reject(abortError) + }) + }), + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([aboutRoute]), + history: createMemoryHistory({ initialEntries: ['/about'] }), + }) + + // Mount load for the raw URL (no search params in the href yet). + const initialLoad = router.load() + await vi.waitFor(() => expect(invocations.length).toBe(1)) + + // What the framework Transitioner does on mount: rebuild the canonical + // location with validated search and replace if the public href differs. + const nextLocation = router.buildLocation({ + to: router.latestLocation.pathname, + search: true, + params: true, + hash: true, + state: true, + _includeValidateSearch: true, + } as any) + + expect(nextLocation.publicHref).toContain('page=1') + expect(trimPathRight(router.latestLocation.publicHref)).not.toBe( + trimPathRight(nextLocation.publicHref), + ) + + // In core (no history subscribers) commitLocation starts the second load. + void router.commitLocation({ ...nextLocation, replace: true } as any) + + await Promise.resolve() + expect(invocations).toHaveLength(1) + expect(invocations[0]!.signal.aborted).toBe(false) + + for (const match of router.state.matches) { + expect(match.status).not.toBe('error') + expect((match.error as Error | undefined)?.name).not.toBe('AbortError') + } + + invocations[0]!.resolve() + // Awaiting the superseded mount load also awaits the superseding chain. + await initialLoad + + expect(invocations).toHaveLength(1) + + const aboutMatch = router.state.matches.find( + (match) => match.routeId === aboutRoute.id, + )! + expect(aboutMatch.status).toBe('success') + expect(aboutMatch.error).toBeUndefined() + expect(aboutMatch.loaderData).toBe('about data') + expect(aboutMatch.search).toEqual({ page: 1 }) + + expect(router.state.location.search).toEqual({ page: 1 }) + expect(router.latestLocation.publicHref).toContain('page=1') + }) +}) diff --git a/packages/router-core/tests/issue-7379-head-matches-direct-load.test.ts b/packages/router-core/tests/issue-7379-head-matches-direct-load.test.ts new file mode 100644 index 0000000000..1768988e47 --- /dev/null +++ b/packages/router-core/tests/issue-7379-head-matches-direct-load.test.ts @@ -0,0 +1,81 @@ +import { createMemoryHistory } from '@tanstack/history' +import { describe, expect, test } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +// https://github.com/TanStack/router/issues/7379 +// +// On a direct (initial) load, head({ matches }) must observe loaderData and +// context on every ancestor match so a breadcrumb-style title can be built. +describe('issue #7379: head({ matches }) has loaderData and context on direct load', () => { + test('initial load executes head after loaders with populated matches', async () => { + const seenMatches: Array< + Array<{ routeId: string; loaderData: unknown; context: unknown }> + > = [] + + const rootRoute = new BaseRootRoute({}) + const nestedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/nested', + beforeLoad: async () => { + await Promise.resolve() + return { section: 'nested-section' } + }, + loader: async () => { + await Promise.resolve() + return { crumb: 'Nested' } + }, + }) + const evenRoute = new BaseRoute({ + getParentRoute: () => nestedRoute, + path: 'even', + loader: async () => { + await Promise.resolve() + return { crumb: 'Even' } + }, + head: ({ matches }) => { + seenMatches.push( + matches.map((match) => ({ + routeId: match.routeId, + loaderData: match.loaderData, + context: match.context, + })), + ) + const crumbs = matches + .map((match) => match.loaderData?.crumb) + .filter(Boolean) + return { + meta: [{ title: [...crumbs, 'Company Inc.'].join(' - ') }], + } + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([nestedRoute.addChildren([evenRoute])]), + history: createMemoryHistory({ initialEntries: ['/nested/even'] }), + }) + + // Direct load: this is the first and only load of the router. + await router.load() + + expect(seenMatches.length).toBeGreaterThan(0) + const seen = seenMatches.at(-1)! + + const seenNested = seen.find((entry) => entry.routeId === nestedRoute.id) + const seenEven = seen.find((entry) => entry.routeId === evenRoute.id) + + // loaderData is present on every match handed to head(). + expect(seenNested?.loaderData).toEqual({ crumb: 'Nested' }) + expect(seenEven?.loaderData).toEqual({ crumb: 'Even' }) + + // context (incl. beforeLoad context) is present as well. + expect(seenNested?.context).toMatchObject({ section: 'nested-section' }) + expect(seenEven?.context).toMatchObject({ section: 'nested-section' }) + + // The breadcrumb title is complete on the committed match. + const evenMatch = router.state.matches.find( + (match) => match.routeId === evenRoute.id, + ) + expect(evenMatch?.meta).toEqual([{ title: 'Nested - Even - Company Inc.' }]) + }) +}) diff --git a/packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts b/packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts new file mode 100644 index 0000000000..41549b58fd --- /dev/null +++ b/packages/router-core/tests/issue-7602-parent-beforeload-context-child-loader.test.ts @@ -0,0 +1,108 @@ +import { expect, onTestFinished, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +// https://github.com/TanStack/router/issues/7602 +test('#7602: browser Back republishes a cached child with fresh parent beforeLoad context', async () => { + const loaderContexts: Array<{ + number?: number + generation?: number + }> = [] + const reloadGate = createControlledPromise() + let loaderRuns = 0 + let beforeLoadRuns = 0 + + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const reproRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/repro', + beforeLoad: async () => { + await Promise.resolve() + return { number: 42, generation: ++beforeLoadRuns } + }, + }) + const reproIndexRoute = new BaseRoute({ + getParentRoute: () => reproRoute, + path: '/', + loader: async ({ + context, + }: { + context: { number?: number; generation?: number } + }) => { + loaderRuns++ + loaderContexts.push({ + number: context.number, + generation: context.generation, + }) + if (loaderRuns === 2) { + await reloadGate + } + return { visit: loaderRuns } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + homeRoute, + reproRoute.addChildren([reproIndexRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/repro'] }), + }) + const getChildMatch = () => + router.state.matches.find((match) => match.routeId === reproIndexRoute.id) + // RouterProvider's Transitioner installs this subscription in applications. + // It is what turns a browser Back history event into a router load. + const unsubscribe = router.history.subscribe(router.load) + onTestFinished(() => { + reloadGate.resolve() + unsubscribe() + }) + + await router.load() + expect(router.state.location.pathname).toBe('/repro') + expect(getChildMatch()).toMatchObject({ + routeId: reproIndexRoute.id, + status: 'success', + loaderData: { visit: 1 }, + context: { number: 42, generation: 1 }, + }) + expect(loaderContexts).toEqual([{ number: 42, generation: 1 }]) + + await router.navigate({ to: '/' }) + expect(router.state.location.pathname).toBe('/') + expect(router.state.isLoading).toBe(false) + expect(getChildMatch()).toBeUndefined() + + router.history.back() + await vi.waitFor(() => expect(loaderContexts).toHaveLength(2)) + + // The cached success is visible while its stale loader reloads. It must + // never be published with the parent's context contribution missing. + expect(router.state.location.pathname).toBe('/repro') + expect(getChildMatch()).toMatchObject({ + status: 'success', + loaderData: { visit: 1 }, + context: { number: 42, generation: 2 }, + }) + expect(loaderContexts).toEqual([ + { number: 42, generation: 1 }, + { number: 42, generation: 2 }, + ]) + + reloadGate.resolve() + await vi.waitFor(() => + expect(getChildMatch()?.loaderData).toEqual({ visit: 2 }), + ) + expect(router.state.location.pathname).toBe('/repro') + expect(router.state.isLoading).toBe(false) + expect(getChildMatch()?.context).toMatchObject({ + number: 42, + generation: 2, + }) + expect(beforeLoadRuns).toBe(2) + expect(loaderRuns).toBe(2) +}) diff --git a/packages/router-core/tests/issue-7759-in-flight-preload-eviction.test.ts b/packages/router-core/tests/issue-7759-in-flight-preload-eviction.test.ts new file mode 100644 index 0000000000..66f76aaa33 --- /dev/null +++ b/packages/router-core/tests/issue-7759-in-flight-preload-eviction.test.ts @@ -0,0 +1,43 @@ +import { expect, onTestFinished, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('issue #7759: evicting an in-flight preload finishes without an internal error', async () => { + let signalLoaderStarted!: () => void + let resolveLoader!: (value: string) => void + + const loaderStarted = new Promise((resolve) => { + signalLoaderStarted = resolve + }) + const loaderResult = new Promise((resolve) => { + resolveLoader = resolve + }) + + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: () => { + signalLoaderStarted() + return loaderResult + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory(), + }) + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { + consoleError.mockRestore() + }) + + const preload = router.preloadRoute({ to: '/target' }) + await loaderStarted + + router.clearCache() + resolveLoader('loaded') + + await preload + expect(consoleError).not.toHaveBeenCalled() +}) diff --git a/packages/router-core/tests/issue-7942-repro.test.ts b/packages/router-core/tests/issue-7942-repro.test.ts new file mode 100644 index 0000000000..116a527191 --- /dev/null +++ b/packages/router-core/tests/issue-7942-repro.test.ts @@ -0,0 +1,271 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { MAX_HYDRATION_OUTPUT_CHUNK_BYTES } from '../src/ssr/hydrationScripts' +import { attachRouterServerSsrUtils } from '../src/ssr/ssr-server' +import { transformReadableStreamWithRouter } from '../src/ssr/transformStreamWithRouter' +import { createTestRouter } from './routerTestUtils' +import type { RouterManagedTag } from '../src/manifest' +import type { InitialHydrationScriptTags } from '../src/ssr/hydrationScripts' + +function createDeferred() { + let resolve!: (value: T) => void + const promise = new Promise((res) => { + resolve = res + }) + return { promise, resolve } +} + +function createLoaderSsrRouter(loader: () => unknown) { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => null, + loader, + }) + + return createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) +} + +function createManualUpstream() { + let controllerRef: ReadableStreamDefaultController | undefined + const cancelled = { value: false } + const encoder = new TextEncoder() + const stream = new ReadableStream({ + start(controller) { + controllerRef = controller + }, + cancel() { + cancelled.value = true + }, + }) + + return { + stream, + cancelled, + push(value: string) { + controllerRef!.enqueue(encoder.encode(value)) + }, + close() { + controllerRef!.close() + }, + } +} + +function renderManagedScript(tag: RouterManagedTag) { + const id = tag.attrs?.id ? ` id="${tag.attrs.id}"` : '' + return `${tag.children ?? ''}` +} + +function renderManagedScripts(tags: Array) { + return tags.map(renderManagedScript).join('') +} + +function expectInitialScripts( + scripts: InitialHydrationScriptTags | undefined, +): InitialHydrationScriptTags { + expect(scripts?.boundary.children).toContain('$tsr-stream-boundary') + expect(scripts?.boundary.attrs).not.toHaveProperty('id') + expect(scripts?.before.length).toBeGreaterThan(0) + for (const script of scripts!.before) { + expect(script.attrs?.['data-tsr-stream-part']).toBe('') + } + return scripts! +} + +async function readAll(stream: ReadableStream) { + const reader = stream.getReader() + const decoder = new TextDecoder() + const chunks: Array = [] + const chunkSizes: Array = [] + for (;;) { + const { done, value } = await reader.read() + if (done) { + chunks.push(decoder.decode()) + return { + text: chunks.join(''), + chunkSizes, + } + } + chunkSizes.push(value.byteLength) + chunks.push(decoder.decode(value, { stream: true })) + } +} + +async function waitFor(check: () => boolean) { + for (let index = 0; index < 20; index++) { + if (check()) { + return + } + await Promise.resolve() + } + throw new Error('condition was not reached') +} + +describe('issue #7942', () => { + test('eager loader data stays in the segmented initial scripts', async () => { + const router = createLoaderSsrRouter(() => ({ value: 'eager-loader-data' })) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + + const initialScripts = expectInitialScripts( + router.serverSsr!.takeInitialHydrationScriptTags(), + ) + expect( + initialScripts.before.some((script) => + script.children?.includes('eager-loader-data'), + ), + ).toBe(true) + expect(router.serverSsr!.takeInitialHydrationScriptTags()).toBeUndefined() + + router.serverSsr!.cleanup() + }) + + test('keeps a large eager serialization part isolated from small initial scripts', async () => { + const payload = 'initial-large-value-'.repeat(2_000) + const router = createLoaderSsrRouter(() => ({ value: payload })) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + + const initialScripts = expectInitialScripts( + router.serverSsr!.takeInitialHydrationScriptTags(), + ) + const streamParts = initialScripts.before + const payloadScripts = streamParts.filter((script) => + script.children?.includes(payload), + ) + + expect(payloadScripts).toHaveLength(1) + expect(streamParts.indexOf(payloadScripts[0]!)).toBeGreaterThan(0) + expect( + streamParts + .filter((script) => script !== payloadScripts[0]) + .every((script) => !script.children?.includes(payload)), + ).toBe(true) + + router.serverSsr!.cleanup() + }) + + test('streams a large deferred loader result in bounded chunks after the next safe boundary', async () => { + const deferred = createDeferred() + const router = createLoaderSsrRouter(() => ({ value: deferred.promise })) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + + const initialScripts = expectInitialScripts( + router.serverSsr!.takeInitialHydrationScriptTags(), + ) + const liftBarrier = vi.spyOn( + router.serverSsr!.hydrationScripts, + 'liftBarrier', + ) + const upstream = createManualUpstream() + const output = transformReadableStreamWithRouter(router, upstream.stream) + const outputPromise = readAll(output) + + const appShell = + `${renderManagedScripts([ + ...initialScripts.before, + initialScripts.boundary, + ])}` + `
    app
    ` + expect(appShell.length).toBeLessThan(MAX_HYDRATION_OUTPUT_CHUNK_BYTES) + upstream.push(appShell) + await waitFor(() => liftBarrier.mock.calls.length === 1) + + const payload = 'x'.repeat(17 * 1024 * 1024) + deferred.resolve(payload) + + const tail = '' + upstream.push(tail) + upstream.close() + + const result = await outputPromise + const renderedInitialScripts = renderManagedScripts([ + ...initialScripts.before, + initialScripts.boundary, + ]) + const earliestInjectionOffset = + ''.length + renderedInitialScripts.length + const payloadOffset = result.text.indexOf(payload) + const injectedStart = result.text.lastIndexOf('' + const injectedEnd = + result.text.lastIndexOf(dynamicClose) + dynamicClose.length + expect(payloadOffset).toBeGreaterThan(injectedStart) + expect(injectedStart).toBeGreaterThanOrEqual(earliestInjectionOffset) + expect(injectedStart).toBeLessThanOrEqual(appShell.length) + expect(injectedEnd).toBeGreaterThan(payloadOffset) + expect( + result.text.slice(0, injectedStart) + result.text.slice(injectedEnd), + ).toBe(appShell + tail) + expect(result.text.endsWith(tail)).toBe(true) + expect(Math.max(...result.chunkSizes)).toBeLessThanOrEqual( + MAX_HYDRATION_OUTPUT_CHUNK_BYTES, + ) + expect(upstream.cancelled.value).toBe(false) + expect(router.serverSsr).toBeUndefined() + }) + + test('rejects multiple router fragments that genuinely accumulate past the guard', async () => { + const payloadCharsPerValue = 1024 * 1024 + const deferredValues = Array.from({ length: 17 }, () => + createDeferred(), + ) + const router = createLoaderSsrRouter(() => ({ + values: deferredValues.map((deferred) => deferred.promise), + })) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + + const initialScripts = expectInitialScripts( + router.serverSsr!.takeInitialHydrationScriptTags(), + ) + + const liftBarrier = vi.spyOn( + router.serverSsr!.hydrationScripts, + 'liftBarrier', + ) + const upstream = createManualUpstream() + const output = transformReadableStreamWithRouter(router, upstream.stream) + const outputResult = readAll(output).then( + (value) => ({ value, error: undefined }), + (error: unknown) => ({ value: undefined, error }), + ) + + upstream.push( + `${renderManagedScripts([ + ...initialScripts.before, + initialScripts.boundary, + ])}
    app
    `, + ) + await waitFor(() => liftBarrier.mock.calls.length === 1) + + for (let index = 0; index < deferredValues.length; index++) { + deferredValues[index]!.resolve( + `${index}:` + 'y'.repeat(payloadCharsPerValue), + ) + } + + const result = await outputResult + expect(result.value).toBeUndefined() + expect(result.error).toBeInstanceOf(Error) + expect((result.error as Error).message).toContain( + 'SSR hydration backlog exceeded maximum code-unit count', + ) + expect(upstream.cancelled.value).toBe(true) + expect(router.serverSsr).toBeUndefined() + }) +}) diff --git a/packages/router-core/tests/json.test.ts b/packages/router-core/tests/json.test.ts deleted file mode 100644 index 8d675212f8..0000000000 --- a/packages/router-core/tests/json.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { json } from '../src/ssr/json' - -describe('json', () => { - it('sets the content type to application/json and stringifies the data', async () => { - const data = { foo: 'bar' } - const response = json(data) - - expect(response.headers.get('Content-Type')).toBe('application/json') - - const responseClone = response.clone() - await expect(responseClone.text()).resolves.toEqual(JSON.stringify(data)) - - await expect(response.json()).resolves.toEqual(data) - }) - it("doesn't override the content type if it's already set", () => { - const response = json(null, { headers: { 'Content-Type': 'text/plain' } }) - - expect(response.headers.get('Content-Type')).toBe('text/plain') - }) - it('reflects passed status and statusText', () => { - const response = json(null, { status: 404, statusText: 'Not Found' }) - - expect(response.status).toBe(404) - expect(response.statusText).toBe('Not Found') - }) - it.each<[string, HeadersInit]>([ - ['plain object', { 'X-TYPE': 'example' }], - ['array', [['X-TYPE', 'example']]], - ['Headers', new Headers({ 'X-TYPE': 'example' })], - ])('merges headers from %s', (_, headers) => { - const response = json(null, { headers }) - - expect(response.headers.get('X-TYPE')).toBe('example') - expect(response.headers.get('Content-Type')).toBe('application/json') - }) -}) diff --git a/packages/router-core/tests/legacy-not-found-interpolation.test.ts b/packages/router-core/tests/legacy-not-found-interpolation.test.ts new file mode 100644 index 0000000000..4f524c68a3 --- /dev/null +++ b/packages/router-core/tests/legacy-not-found-interpolation.test.ts @@ -0,0 +1,105 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' +import type { AnyRoute } from '../src' + +afterEach(() => vi.restoreAllMocks()) + +function setup(isServer: boolean) { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const root = new BaseRootRoute({}) + const tenant = new BaseRoute({ + getParentRoute: () => root, + path: '/$tenant', + }) + const legacy = new BaseRoute({ + getParentRoute: () => tenant, + path: '/404', + loader: ({ params }) => params.tenant, + staleTime: Infinity, + }) + const history = createMemoryHistory({ initialEntries: ['/a/missing'] }) + const router = createTestRouter({ + routeTree: root.addChildren([tenant]), + notFoundRoute: legacy, + history, + isServer, + scrollRestoration: false, + }) + return { router, history, legacy } +} + +test.each([false, true])( + 'interpolates standalone fallback match IDs (server: %s)', + (isServer) => { + const { router, history, legacy } = setup(isServer) + try { + expect(legacy.originalIndex).toBe(99999999999) + const first = router.matchRoutes('/a/missing', {}).at(-1)! + const second = router.matchRoutes('/b/missing', {}).at(-1)! + expect(first.routeId).toBe(legacy.id) + expect(first.pathname).toBe('/a/404') + expect(second.pathname).toBe('/b/404') + expect(second.id).not.toBe(first.id) + expect(second._strictParams).toEqual({ tenant: 'b' }) + } finally { + history.destroy() + } + }, +) + +test('does not reuse fallback params or loader data across tenants', async () => { + const { router, history, legacy } = setup(false) + try { + await router.load() + const first = router.state.matches.find( + (match) => match.routeId === legacy.id, + )! + expect(first.params).toEqual({ tenant: 'a' }) + expect(first.loaderData).toBe('a') + await router.navigate({ href: '/b/missing' }) + const second = router.state.matches.find( + (match) => match.routeId === legacy.id, + )! + expect(second.id).not.toBe(first.id) + expect(second.params).toEqual({ tenant: 'b' }) + expect(second.loaderData).toBe('b') + } finally { + history.destroy() + } +}) + +test('refreshes fallback segments when the route tree is replaced', () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const root = new BaseRootRoute({}) + let parent: AnyRoute = new BaseRoute({ + getParentRoute: () => root, + path: '/$tenant', + }) + const legacy = new BaseRoute({ + getParentRoute: () => parent, + path: '/404', + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: root.addChildren([parent]), + notFoundRoute: legacy, + history, + scrollRestoration: false, + }) + try { + expect(router.matchRoutes('/a/missing', {}).at(-1)?.pathname).toBe('/a/404') + const nextRoot = new BaseRootRoute({}) + parent = new BaseRoute({ + getParentRoute: () => nextRoot, + path: '/$org', + }) + router.update({ routeTree: nextRoot.addChildren([parent]) }) + const match = router.matchRoutes('/b/missing', {}).at(-1)! + expect(match.pathname).toBe('/b/404') + expect(match._strictParams).toEqual({ org: 'b' }) + } finally { + history.destroy() + } +}) diff --git a/packages/router-core/tests/lifecycle-dispatch.test.ts b/packages/router-core/tests/lifecycle-dispatch.test.ts new file mode 100644 index 0000000000..12767c5a97 --- /dev/null +++ b/packages/router-core/tests/lifecycle-dispatch.test.ts @@ -0,0 +1,82 @@ +import { expect, test } from 'vitest' +import { lifecycleEnd, runRouteLifecycle } from '../src/router' +import type { AnyRouteMatch, AnyRouter } from '../src' +import type { LoadTransaction } from '../src/load-client' + +test.each(['onLeave', 'onEnter', 'onStay'] as const)( + '%s supersession stops remaining lifecycle callbacks', + (callback) => { + const events: Array = [] + const owner = {} as LoadTransaction + const matches = ['parent', 'child'].map((routeId) => ({ + routeId, + status: 'success', + })) as Array + const router = { + _tx: owner, + routesById: Object.fromEntries( + matches.map(({ routeId }) => [ + routeId, + { + options: { + [callback]: () => { + events.push(routeId) + router._tx = {} as LoadTransaction + }, + }, + }, + ]), + ), + } as unknown as AnyRouter + const previous = callback === 'onEnter' ? [] : matches + const next = callback === 'onLeave' ? [] : matches + runRouteLifecycle( + router, + previous, + next, + lifecycleEnd(previous), + lifecycleEnd(next), + owner, + ) + expect(events).toEqual(['parent']) + expect(matches).toHaveLength(2) + }, +) + +test('saved fallback membership survives statuses changing before dispatch', () => { + const events: Array = [] + const previous = [ + { routeId: 'parent', status: 'notFound' }, + { routeId: 'child', status: 'success' }, + ] as Array + const previousEnd = lifecycleEnd(previous) + previous[0]!.status = 'pending' + const matches = previous.map((match) => ({ + ...match, + status: 'success' as const, + })) + const router = { + routesById: Object.fromEntries( + matches.map(({ routeId }) => [ + routeId, + { + options: { + onEnter: () => events.push(`enter:${routeId}`), + onStay: () => events.push(`stay:${routeId}`), + onLeave: () => events.push(`leave:${routeId}`), + }, + }, + ]), + ), + } as unknown as AnyRouter + runRouteLifecycle( + router, + previous, + matches, + previousEnd, + lifecycleEnd(matches), + ) + expect(events).toEqual(['stay:parent', 'enter:child']) + expect(previous).toHaveLength(2) + expect(previous[0]!.status).toBe('pending') +}) diff --git a/packages/router-core/tests/lightweight-location.bench.ts b/packages/router-core/tests/lightweight-location.bench.ts new file mode 100644 index 0000000000..44f70c9d53 --- /dev/null +++ b/packages/router-core/tests/lightweight-location.bench.ts @@ -0,0 +1,66 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +describe.each([false, true])( + 'cold lightweight locations (server: %s)', + (isServer) => { + for (const count of [1, 8, 32]) { + const root = new BaseRootRoute({}) + const segments = Array.from({ length: count }, (_, index) => `$p${index}`) + const source = new BaseRoute({ + getParentRoute: () => root, + path: `/source/${segments.join('/')}`, + }) + const target = new BaseRoute({ + getParentRoute: () => root, + path: '/target', + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: root.addChildren([source, target]), + history, + isServer, + scrollRestoration: false, + }) + history.destroy() + const pathname = `/source/${segments.map((_, index) => String(index)).join('/')}` + const location = { + ...router.latestLocation, + pathname, + href: pathname, + publicHref: pathname, + } + let checksum = 0 + const iterations = 256 + function run() { + checksum = 0 + for (let index = 0; index < iterations; index++) { + checksum += router.buildLocation({ + to: '/target', + params: true, + _fromLocation: { ...location }, + }).pathname.length + } + } + run() + expect(checksum).toBe(iterations * '/target'.length) + test(`${count} source params`, async ({ bench }) => { + await bench( + `${count} source params`, + { + afterAll: () => { + expect(checksum).toBe(iterations * '/target'.length) + }, + }, + run, + ).run({ + time: 1000, + warmupTime: 200, + throws: true, + }) + }) + } + }, +) diff --git a/packages/router-core/tests/load-client-wait-for.test.ts b/packages/router-core/tests/load-client-wait-for.test.ts new file mode 100644 index 0000000000..fdf5397a16 --- /dev/null +++ b/packages/router-core/tests/load-client-wait-for.test.ts @@ -0,0 +1,377 @@ +import { describe, expect, test, vi } from 'vitest' +import { waitForReason } from '../src/await-signal' +import { waitFor } from '../src/load-client' +import { waitForRequest } from '../src/ssr/server' + +test('waitForRequest aliases waitForReason through the server barrel', () => { + expect(waitForRequest).toBe(waitForReason) +}) + +describe('waitFor', () => { + test.each(['resolve', 'reject'] as const)( + 'removes its abort listener after the value %ss', + async (outcome) => { + const controller = new AbortController() + const add = vi.spyOn(controller.signal, 'addEventListener') + const remove = vi.spyOn(controller.signal, 'removeEventListener') + const value = + outcome === 'resolve' ? Promise.resolve(42) : Promise.reject(42) + const result = waitFor(value, controller.signal) + if (outcome === 'resolve') { + await expect(result).resolves.toBe(42) + } else { + await expect(result).rejects.toBe(42) + } + expect(add).toHaveBeenCalledOnce() + expect(remove).toHaveBeenCalledExactlyOnceWith( + 'abort', + add.mock.calls[0]![1], + ) + }, + ) + + test('observes a late rejection and cleans up after an active wait is aborted', async () => { + const controller = new AbortController() + const add = vi.spyOn(controller.signal, 'addEventListener') + const remove = vi.spyOn(controller.signal, 'removeEventListener') + let rejectValue!: (error: Error) => void + const value = new Promise((_, reject) => { + rejectValue = reject + }) + const result = waitFor(value, controller.signal) + const canceled = expect(result).rejects.toBe(controller.signal) + + controller.abort() + await canceled + rejectValue(new Error('late failure')) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(add).toHaveBeenCalledOnce() + expect(remove).toHaveBeenCalledExactlyOnceWith( + 'abort', + add.mock.calls[0]![1], + ) + }) + + test('removes its abort listener when reading a thenable throws', async () => { + const controller = new AbortController() + const add = vi.spyOn(controller.signal, 'addEventListener') + const remove = vi.spyOn(controller.signal, 'removeEventListener') + const error = new Error('then getter failed') + const value: PromiseLike = { + get then(): never { + throw error + }, + } + + await expect(waitFor(value, controller.signal)).rejects.toBe(error) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(add).toHaveBeenCalledOnce() + expect(remove).toHaveBeenCalledExactlyOnceWith( + 'abort', + add.mock.calls[0]![1], + ) + }) + + test('observes a rejected value when the signal is already aborted', async () => { + const controller = new AbortController() + const error = new Error('late failure') + controller.abort() + + await expect(waitFor(undefined, controller.signal)).rejects.toBe( + controller.signal, + ) + await expect( + waitFor(Promise.reject(error), controller.signal), + ).rejects.toBe(controller.signal) + + await Promise.resolve() + }) + + test('preserves reason-based cancellation and observes a late value', async () => { + const controller = new AbortController() + const reason = new Error('request canceled') + const late = Promise.resolve('late response') + const onLate = vi.fn() + controller.abort(reason) + + await expect(waitForReason(late, controller.signal, onLate)).rejects.toBe( + reason, + ) + await vi.waitFor(() => expect(onLate).toHaveBeenCalledWith('late response')) + }) +}) + +describe('waitForReason', () => { + test('handles nested abort dispatch before its listener runs', async () => { + const source = new AbortController() + const nested = new AbortController() + const signal = AbortSignal.any([source.signal]) + signal.addEventListener('abort', () => nested.abort()) + + const reason = new Error('request canceled') + const result = waitForReason(Promise.resolve('late'), signal) + source.abort(reason) + + await expect(result).rejects.toBe(reason) + }) + + test('removes its abort listener once the wait settles', async () => { + const controller = new AbortController() + const addEventListener = vi.spyOn(controller.signal, 'addEventListener') + const removeEventListener = vi.spyOn( + controller.signal, + 'removeEventListener', + ) + let resolveFirst!: (value: string) => void + let rejectSecond!: (error: unknown) => void + const first = new Promise((resolve) => { + resolveFirst = resolve + }) + const second = new Promise((_resolve, reject) => { + rejectSecond = reject + }) + + const firstResult = waitForReason(first, controller.signal) + const secondResult = waitForReason(second, controller.signal) + expect(addEventListener).toHaveBeenCalledTimes(2) + + resolveFirst('first') + await expect(firstResult).resolves.toBe('first') + const failure = new Error('wait failed') + rejectSecond(failure) + await expect(secondResult).rejects.toBe(failure) + + for (const [, listener] of addEventListener.mock.calls) { + expect(removeEventListener).toHaveBeenCalledWith('abort', listener) + } + }) + + test('rejects all active waits and observes their late values', async () => { + const controller = new AbortController() + const reason = new Error('request canceled') + const onFirstLate = vi.fn() + const onSecondLate = vi.fn() + let resolveFirst!: (value: string) => void + let resolveSecond!: (value: string) => void + const first = new Promise((resolve) => { + resolveFirst = resolve + }) + const second = new Promise((resolve) => { + resolveSecond = resolve + }) + const firstResult = waitForReason(first, controller.signal, onFirstLate) + const secondResult = waitForReason(second, controller.signal, onSecondLate) + + controller.abort(reason) + await expect(firstResult).rejects.toBe(reason) + await expect(secondResult).rejects.toBe(reason) + + resolveFirst('first') + resolveSecond('second') + await vi.waitFor(() => { + expect(onFirstLate).toHaveBeenCalledWith('first') + expect(onSecondLate).toHaveBeenCalledWith('second') + }) + }) + + test('aborts remaining waits after an out-of-order rejection', async () => { + const controller = new AbortController() + const reason = new Error('request canceled') + const failure = new Error('wait failed') + const lateFailure = new Error('late failure') + const onLate = vi.fn() + const onLateError = vi.fn() + let resolveFirst!: (value: string) => void + let rejectSecond!: (error: Error) => void + let rejectThird!: (error: Error) => void + const first = new Promise((resolve) => { + resolveFirst = resolve + }) + const second = new Promise((_, reject) => { + rejectSecond = reject + }) + const third = new Promise((_, reject) => { + rejectThird = reject + }) + const firstResult = waitForReason(first, controller.signal, onLate) + const secondResult = waitForReason(second, controller.signal) + const thirdResult = waitForReason( + third, + controller.signal, + undefined, + onLateError, + ) + + rejectSecond(failure) + await expect(secondResult).rejects.toBe(failure) + + controller.abort(reason) + await expect(firstResult).rejects.toBe(reason) + await expect(thirdResult).rejects.toBe(reason) + + resolveFirst('late') + rejectThird(lateFailure) + await vi.waitFor(() => { + expect(onLate).toHaveBeenCalledWith('late') + expect(onLateError).toHaveBeenCalledWith(lateFailure) + }) + }) + + test('isolates waits for different signals', async () => { + const firstController = new AbortController() + const secondController = new AbortController() + const firstReason = new Error('first request canceled') + const firstAddEventListener = vi.spyOn( + firstController.signal, + 'addEventListener', + ) + const secondAddEventListener = vi.spyOn( + secondController.signal, + 'addEventListener', + ) + let resolveFirst!: (value: string) => void + let resolveSecond!: (value: string) => void + const first = new Promise((resolve) => { + resolveFirst = resolve + }) + const second = new Promise((resolve) => { + resolveSecond = resolve + }) + const firstResult = waitForReason(first, firstController.signal) + const secondResult = waitForReason(second, secondController.signal) + + expect(firstAddEventListener).toHaveBeenCalledOnce() + expect(secondAddEventListener).toHaveBeenCalledOnce() + + firstController.abort(firstReason) + await expect(firstResult).rejects.toBe(firstReason) + + resolveSecond('second result') + await expect(secondResult).resolves.toBe('second result') + resolveFirst('late first result') + await Promise.resolve() + }) + + test('observes fulfilled and rejected values when already aborted', async () => { + const controller = new AbortController() + const reason = new Error('request canceled') + const lateError = new Error('late failure') + const onLate = vi.fn() + const onLateError = vi.fn() + controller.abort(reason) + + await expect( + waitForReason(Promise.resolve('late'), controller.signal, onLate), + ).rejects.toBe(reason) + await expect( + waitForReason( + Promise.reject(lateError), + controller.signal, + undefined, + onLateError, + ), + ).rejects.toBe(reason) + + await vi.waitFor(() => { + expect(onLate).toHaveBeenCalledWith('late') + expect(onLateError).toHaveBeenCalledWith(lateError) + }) + }) + + test('handles an abort during listener registration', async () => { + const controller = new AbortController() + const reason = new Error('request canceled') + const onLate = vi.fn() + const addEventListener = controller.signal.addEventListener.bind( + controller.signal, + ) + vi.spyOn(controller.signal, 'addEventListener').mockImplementation( + (type, listener, options) => { + addEventListener(type, listener, options) + controller.abort(reason) + }, + ) + let resolve!: (value: string) => void + const value = new Promise((resolveValue) => { + resolve = resolveValue + }) + + const result = waitForReason(value, controller.signal, onLate) + await expect(result).rejects.toBe(reason) + + resolve('late') + await vi.waitFor(() => expect(onLate).toHaveBeenCalledWith('late')) + }) + + test('observes errors from late callbacks', async () => { + const unhandled: Array = [] + const onUnhandled = (error: unknown) => { + unhandled.push(error) + } + process.on('unhandledRejection', onUnhandled) + + try { + const reason = new Error('request canceled') + const thrownError = new Error('late callback threw') + const rejectedError = new Error('late callback rejected') + const throwLate = vi.fn(() => { + throw thrownError + }) + const rejectLate = vi.fn(() => { + return Promise.reject(rejectedError) + }) + const expectCanceled = (promise: Promise) => { + return expect(promise).rejects.toBe(reason) + } + const alreadyAborted = new AbortController() + alreadyAborted.abort(reason) + + await Promise.all([ + expectCanceled( + waitForReason( + Promise.resolve('late'), + alreadyAborted.signal, + throwLate, + ), + ), + expectCanceled( + waitForReason( + Promise.reject(new Error('late failure')), + alreadyAborted.signal, + undefined, + rejectLate, + ), + ), + ]) + + const controller = new AbortController() + const fulfilledWait = waitForReason( + Promise.resolve('late'), + controller.signal, + rejectLate, + ) + const rejectedWait = waitForReason( + Promise.reject(new Error('late failure')), + controller.signal, + undefined, + throwLate, + ) + controller.abort(reason) + + await Promise.all([ + expectCanceled(fulfilledWait), + expectCanceled(rejectedWait), + ]) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(throwLate).toHaveBeenCalledTimes(2) + expect(rejectLate).toHaveBeenCalledTimes(2) + expect(unhandled).not.toContain(thrownError) + expect(unhandled).not.toContain(rejectedError) + } finally { + process.off('unhandledRejection', onUnhandled) + } + }) +}) diff --git a/packages/router-core/tests/load-route-chunk.test.ts b/packages/router-core/tests/load-route-chunk.test.ts new file mode 100644 index 0000000000..73179f9f32 --- /dev/null +++ b/packages/router-core/tests/load-route-chunk.test.ts @@ -0,0 +1,30 @@ +import { expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('router.loadRouteChunk exposes a failed lazy import and remains retryable', async () => { + const chunkError = new TypeError('Failed to fetch lazy route') + const component = () => null + let fail = true + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/route', + }).lazy(() => { + if (fail) { + fail = false + return Promise.reject(chunkError) + } + return Promise.resolve({ options: { component } } as any) + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await expect(router.loadRouteChunk(route as any)).rejects.toBe(chunkError) + await router.loadRouteChunk(route as any) + + expect(route.options.component).toBe(component) +}) diff --git a/packages/router-core/tests/load.test.ts b/packages/router-core/tests/load.test.ts index d65d37cf74..484e8d0e71 100644 --- a/packages/router-core/tests/load.test.ts +++ b/packages/router-core/tests/load.test.ts @@ -1,17 +1,375 @@ -import { describe, expect, test, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' import { BaseRootRoute, BaseRoute, - RouterCore, + createControlledPromise, notFound, redirect, + rootRouteId, +} from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' +import type { + LoaderStaleReloadMode, + RootRouteOptions, + RouterCore, } from '../src' -import type { RootRouteOptions } from '../src' type AnyRouteOptions = RootRouteOptions type BeforeLoad = NonNullable type Loader = NonNullable +type LoaderEntry = Exclude + +describe('redirect resolution', () => { + test('resolveRedirect normalizes same-origin Location to path-only', async () => { + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + }) + + const routeTree = rootRoute.addChildren([fooRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['https://example.com/foo'], + }), + origin: 'https://example.com', + }) + + // This redirect already includes an absolute Location header (external-ish), + // but still represents an internal navigation. + const unresolved = redirect({ + to: '/foo', + headers: { Location: 'https://example.com/foo' }, + }) + + const resolved = router.resolveRedirect(unresolved) + + // Expect Location and stored href to be path-only (no origin). + expect(resolved.headers.get('Location')).toBe('/foo') + expect(resolved.options.href).toBe('/foo') + }) + + test.each(['/$a', '/$toString', '/$__proto__'])( + 'server startup redirects initial path %s to /undefined', + async (initialPath) => { + const rootRoute = new BaseRootRoute({}) + const slugRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/$slug', + }) + + const routeTree = rootRoute.addChildren([slugRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: [initialPath] }), + isServer: true, + }) + + const response = await loadServerResponse(router, initialPath) + + expect(response.status).toBe(307) + expect(response.headers.get('Location')).toBe('/undefined') + }, + ) + + test.each([ + '//evil.example', + '/\\evil.example', + '/\\\\evil.example', + '/\\/evil.example', + '\\/evil.example', + '\\\\evil.example', + ])('server loaders do not emit an unsafe Location for %j', async (href) => { + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => redirect({ href }), + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/source') + + expect(response.status).toBe(500) + expect(response.headers.get('Location')).toBeNull() + }) + + test.each([ + [ + 'preserves an explicit same-origin document redirect', + 'https://victim.example/target', + true, + '/target', + ], + [ + 'document-navigates an intentional external redirect', + 'https://other.example/target', + undefined, + 'https://other.example/target', + ], + ] as const)('%s', async (_name, href, reloadDocument, expectedHref) => { + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => redirect({ href, reloadDocument }), + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history, + origin: 'https://victim.example', + isServer: false, + }) + const windowLocation = { href: '', replace: vi.fn() } + vi.stubGlobal('window', { location: windowLocation }) + + void router.navigate({ to: '/source' }) + + await vi.waitFor(() => { + expect(windowLocation.replace).toHaveBeenCalledWith(expectedHref) + }) + }) + + test.each(['javascript:alert(1)', 'blob:https://victim.example/id'])( + 'client loaders block redirects made dangerous by output rewrite %j', + async (dangerousHref) => { + const unsafeRedirect = redirect({ to: '/target' }) + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => unsafeRedirect, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history, + isServer: false, + rewrite: { + input: ({ url }) => url, + output: ({ url }) => + url.pathname === '/target' ? new URL(dangerousHref) : url, + }, + }) + + await router.navigate({ to: '/source' }) + + expect(history.location.href).toBe('/source') + expect(unsafeRedirect.options.href).toBeUndefined() + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: '/source', + status: 'error', + error: expect.objectContaining({ + message: expect.stringMatching(/Redirect blocked: unsafe protocol/), + }), + }) + }, + ) + + test('client loaders block masked redirects made dangerous by output rewrites', async () => { + const unsafeRedirect = redirect({ + to: '/target', + mask: { to: '/pretty' }, + }) + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => unsafeRedirect, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history, + isServer: false, + rewrite: { + input: ({ url }) => url, + output: ({ url }) => + url.pathname === '/pretty' ? new URL('javascript:alert(1)') : url, + }, + }) + + await router.navigate({ to: '/source' }) + + expect(history.location.href).toBe('/source') + expect(unsafeRedirect.options.href).toBeUndefined() + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: '/source', + status: 'error', + error: expect.objectContaining({ + message: expect.stringMatching(/Redirect blocked: unsafe protocol/), + }), + }) + }) + + test('client loaders document-navigate an external output rewrite', async () => { + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => redirect({ to: '/target' }), + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + origin: 'https://victim.example', + isServer: false, + rewrite: { + input: ({ url }) => url, + output: ({ url }) => + url.pathname === '/target' + ? new URL('https://other.example/rewritten') + : url, + }, + }) + const windowLocation = { href: '', replace: vi.fn() } + vi.stubGlobal('window', { location: windowLocation }) + + try { + void router.navigate({ to: '/source' }) + + await vi.waitFor(() => { + expect(windowLocation.replace).toHaveBeenCalledWith( + 'https://other.example/rewritten', + ) + }) + } finally { + vi.unstubAllGlobals() + } + }) + + test('preloading stops at a redirect with an external output rewrite', async () => { + const targetLoader = vi.fn() + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => redirect({ to: '/target' }), + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: targetLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + origin: 'https://victim.example', + isServer: false, + rewrite: { + input: ({ url }) => url, + output: ({ url }) => + url.pathname === '/target' + ? new URL('https://other.example/rewritten') + : url, + }, + }) + + await router.preloadRoute({ to: '/source' }) + + expect(targetLoader).not.toHaveBeenCalled() + }) + + test('preloading follows an inferred same-origin absolute redirect', async () => { + const targetLoader = vi.fn() + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => redirect({ href: 'https://victim.example/app/pretty' }), + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: targetLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/app/'] }), + origin: 'https://victim.example', + basepath: '/app', + isServer: false, + rewrite: { + input: ({ url }) => { + if (url.pathname === '/pretty') { + url.pathname = '/target' + } + return url + }, + output: ({ url }) => { + if (url.pathname === '/target') { + url.pathname = '/pretty' + } + return url + }, + }, + }) + + await router.preloadRoute({ to: '/source' }) + + expect(targetLoader).toHaveBeenCalledOnce() + }) +}) + +describe('notFound detection', () => { + test('does not treat arbitrary proxy property access as notFound', async () => { + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader: () => + new Proxy( + {}, + { + get(_target, prop) { + if (prop === 'isNotFound') return 'truthy-but-not-true' + return undefined + }, + has() { + return true + }, + }, + ), + }) + + const routeTree = rootRoute.addChildren([fooRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/foo'] }), + isServer: true, + }) + + await router.load() + + expect(router.state.matches.at(-1)?.status).toBe('success') + expect(router.state.matches.at(-1)?.error).toBeUndefined() + }) +}) describe('beforeLoad skip or exec', () => { const setup = ({ beforeLoad }: { beforeLoad?: BeforeLoad }) => { @@ -30,7 +388,7 @@ describe('beforeLoad skip or exec', () => { const routeTree = rootRoute.addChildren([fooRoute, barRoute]) - const router = new RouterCore({ + const router = createTestRouter({ routeTree, history: createMemoryHistory(), }) @@ -48,12 +406,7 @@ describe('beforeLoad skip or exec', () => { test('exec on regular nav', async () => { const beforeLoad = vi.fn(() => Promise.resolve({ hello: 'world' })) const router = setup({ beforeLoad }) - const navigation = router.navigate({ to: '/foo' }) - expect(beforeLoad).toHaveBeenCalledTimes(1) - expect(router.state.pendingMatches).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) - await navigation + await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') expect(router.state.matches).toEqual( expect.arrayContaining([ @@ -68,16 +421,48 @@ describe('beforeLoad skip or exec', () => { expect(beforeLoad).toHaveBeenCalledTimes(1) }) + test('preserves primitive errors thrown from beforeLoad', async () => { + const beforeLoad = vi.fn(() => { + throw 'primitive error' + }) + const router = setup({ beforeLoad }) + + await router.navigate({ to: '/foo' }) + + expect(router.state.matches).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + id: '/foo/foo', + status: 'error', + error: 'primitive error', + }), + ]), + ) + }) + + test('does not mutate object errors thrown from beforeLoad', async () => { + const thrown = { type: 'domain-error' } + const beforeLoad = vi.fn(() => { + throw thrown + }) + const router = setup({ beforeLoad }) + + await router.navigate({ to: '/foo' }) + + const match = router.state.matches.find((d) => d.id === '/foo/foo') + expect(match?.status).toBe('error') + expect(match?.error).toBe(thrown) + expect(thrown).toEqual({ type: 'domain-error' }) + }) + test('exec if resolved preload (success)', async () => { const beforeLoad = vi.fn() const router = setup({ beforeLoad }) await router.preloadRoute({ to: '/foo' }) - expect(router.state.cachedMatches).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) await sleep(10) await router.navigate({ to: '/foo' }) + expect(router.state.location.pathname).toBe('/foo') expect(beforeLoad).toHaveBeenCalledTimes(2) }) @@ -86,11 +471,9 @@ describe('beforeLoad skip or exec', () => { const router = setup({ beforeLoad }) router.preloadRoute({ to: '/foo' }) await Promise.resolve() - expect(router.state.cachedMatches).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) await router.navigate({ to: '/foo' }) + expect(router.state.location.pathname).toBe('/foo') expect(beforeLoad).toHaveBeenCalledTimes(2) }) @@ -137,6 +520,7 @@ describe('beforeLoad skip or exec', () => { await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') + expect(router.state.matches.at(-1)?.status).toBe('success') expect(beforeLoad).toHaveBeenCalledTimes(2) }) @@ -153,6 +537,7 @@ describe('beforeLoad skip or exec', () => { await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') + expect(router.state.matches.at(-1)?.status).toBe('success') expect(beforeLoad).toHaveBeenCalledTimes(2) }) @@ -171,6 +556,41 @@ describe('beforeLoad skip or exec', () => { expect(beforeLoad).toHaveBeenCalledTimes(2) }) + test('skip child beforeLoad when parent beforeLoad throws during preload', async () => { + const parentBeforeLoad = vi.fn(async ({ preload }) => { + if (preload) throw new Error('parent error') + }) + const childBeforeLoad = vi.fn() + const parentHead = vi.fn(() => ({ meta: [{ title: 'Parent' }] })) + const childHead = vi.fn(() => ({ meta: [{ title: 'Child' }] })) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: parentBeforeLoad, + head: parentHead, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: childBeforeLoad, + head: childHead, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory(), + }) + + await router.preloadRoute({ to: '/parent/child' }) + + expect(parentBeforeLoad).toHaveBeenCalledTimes(1) + expect(childBeforeLoad).not.toHaveBeenCalled() + expect(parentHead).toHaveBeenCalledTimes(1) + expect(childHead).not.toHaveBeenCalled() + }) + test('exec if pending preload (error)', async () => { const beforeLoad = vi.fn(async ({ preload }) => { await sleep(100) @@ -191,9 +611,11 @@ describe('loader skip or exec', () => { const setup = ({ loader, staleTime, + defaultStaleReloadMode, }: { loader?: Loader staleTime?: number + defaultStaleReloadMode?: LoaderStaleReloadMode }) => { const rootRoute = new BaseRootRoute({}) @@ -212,8 +634,9 @@ describe('loader skip or exec', () => { const routeTree = rootRoute.addChildren([fooRoute, barRoute]) - const router = new RouterCore({ + const router = createTestRouter({ routeTree, + defaultStaleReloadMode, history: createMemoryHistory(), }) @@ -230,12 +653,7 @@ describe('loader skip or exec', () => { test('exec on regular nav', async () => { const loader = vi.fn(() => Promise.resolve({ hello: 'world' })) const router = setup({ loader }) - const navigation = router.navigate({ to: '/foo' }) - expect(loader).toHaveBeenCalledTimes(1) - expect(router.state.pendingMatches).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) - await navigation + await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') expect(router.state.matches).toEqual( expect.arrayContaining([ @@ -254,25 +672,21 @@ describe('loader skip or exec', () => { const loader = vi.fn() const router = setup({ loader }) await router.preloadRoute({ to: '/foo' }) - expect(router.state.cachedMatches).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) await sleep(10) await router.navigate({ to: '/foo' }) - expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.location.pathname).toBe('/foo') + expect(loader).toHaveBeenCalledTimes(1) }) test('skip if resolved preload (success) within staleTime duration', async () => { const loader = vi.fn() const router = setup({ loader, staleTime: 1000 }) await router.preloadRoute({ to: '/foo' }) - expect(router.state.cachedMatches).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) await sleep(10) await router.navigate({ to: '/foo' }) + expect(router.state.location.pathname).toBe('/foo') expect(loader).toHaveBeenCalledTimes(1) }) @@ -281,16 +695,14 @@ describe('loader skip or exec', () => { const router = setup({ loader }) router.preloadRoute({ to: '/foo' }) await Promise.resolve() - expect(router.state.cachedMatches).toEqual( - expect.arrayContaining([expect.objectContaining({ id: '/foo/foo' })]), - ) await router.navigate({ to: '/foo' }) + expect(router.state.location.pathname).toBe('/foo') expect(loader).toHaveBeenCalledTimes(1) }) test('exec if rejected preload (notFound)', async () => { - const loader = vi.fn(async ({ preload }) => { + const loader: Loader = vi.fn(async ({ preload }) => { if (preload) throw notFound() await Promise.resolve() }) @@ -304,23 +716,39 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(2) }) - test('skip if pending preload (notFound)', async () => { - const loader = vi.fn(async ({ preload }) => { - await sleep(100) + test('navigation shares a pending preload loader notFound', async () => { + const loaderGate = createControlledPromise() + const loader: Loader = vi.fn(async ({ preload }) => { + await loaderGate if (preload) throw notFound() }) const router = setup({ loader, }) - router.preloadRoute({ to: '/foo' }) - await Promise.resolve() - await router.navigate({ to: '/foo' }) + const preload = router.preloadRoute({ to: '/foo' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) - expect(loader).toHaveBeenCalledTimes(1) + const navigation = router.navigate({ to: '/foo' }) + await Promise.resolve() + expect(loader).toHaveBeenCalledOnce() + + loaderGate.resolve() + await Promise.all([preload, navigation]) + + expect(router.state.location.pathname).toBe('/foo') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: '/foo', + status: 'notFound', + error: { + isNotFound: true, + routeId: '/foo', + }, + }) + expect(loader).toHaveBeenCalledOnce() }) test('exec if rejected preload (redirect)', async () => { - const loader = vi.fn(async ({ preload }) => { + const loader: Loader = vi.fn(async ({ preload }) => { if (preload) throw redirect({ to: '/bar' }) await Promise.resolve() }) @@ -332,11 +760,12 @@ describe('loader skip or exec', () => { await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/foo') + expect(router.state.matches.at(-1)?.status).toBe('success') expect(loader).toHaveBeenCalledTimes(2) }) - test('skip if pending preload (redirect)', async () => { - const loader = vi.fn(async ({ preload }) => { + test('exec if pending preload redirects', async () => { + const loader: Loader = vi.fn(async ({ preload }) => { await sleep(100) if (preload) throw redirect({ to: '/bar' }) }) @@ -348,11 +777,12 @@ describe('loader skip or exec', () => { await router.navigate({ to: '/foo' }) expect(router.state.location.pathname).toBe('/bar') + expect(router.state.matches.at(-1)?.status).toBe('success') expect(loader).toHaveBeenCalledTimes(1) }) test('exec if rejected preload (error)', async () => { - const loader = vi.fn(async ({ preload }) => { + const loader: Loader = vi.fn(async ({ preload }) => { if (preload) throw new Error('error') await Promise.resolve() }) @@ -366,19 +796,33 @@ describe('loader skip or exec', () => { expect(loader).toHaveBeenCalledTimes(2) }) - test('skip if pending preload (error)', async () => { - const loader = vi.fn(async ({ preload }) => { - await sleep(100) - if (preload) throw new Error('error') + test('navigation shares a pending preload loader error', async () => { + const loaderGate = createControlledPromise() + const failure = new Error('preload failed') + const loader: Loader = vi.fn(async ({ preload }) => { + await loaderGate + if (preload) throw failure }) const router = setup({ loader, }) - router.preloadRoute({ to: '/foo' }) - await Promise.resolve() - await router.navigate({ to: '/foo' }) + const preload = router.preloadRoute({ to: '/foo' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) - expect(loader).toHaveBeenCalledTimes(1) + const navigation = router.navigate({ to: '/foo' }) + await Promise.resolve() + expect(loader).toHaveBeenCalledOnce() + + loaderGate.resolve() + await Promise.all([preload, navigation]) + + expect(router.state.location.pathname).toBe('/foo') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: '/foo', + status: 'error', + error: failure, + }) + expect(loader).toHaveBeenCalledOnce() }) }) @@ -420,7 +864,7 @@ test('exec on stay (beforeLoad & loader)', async () => { layoutRoute.addChildren([fooRoute, barRoute]), ]) - const router = new RouterCore({ + const router = createTestRouter({ routeTree, history: createMemoryHistory(), defaultStaleTime: 1000, @@ -460,24 +904,490 @@ test('exec on stay (beforeLoad & loader)', async () => { expect(layoutBeforeLoadResolved).toBe(true) }) -test('cancelMatches after pending timeout', async () => { - const WAIT_TIME = 5 - const onAbortMock = vi.fn() +describe('stale loader reload triggers', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(0) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + const getMatchById = ( + router: RouterCore, + id: string, + ) => router.state.matches.find((match) => match.id === id) + + const hasActiveMatch = ( + router: RouterCore, + id: string, + ) => router.state.matches.some((match) => match.id === id) + + const setup = ({ + loader, + staleTime, + defaultStaleReloadMode, + }: { + loader?: Loader + staleTime?: number + defaultStaleReloadMode?: LoaderStaleReloadMode + }) => { + const rootRoute = new BaseRootRoute({}) + + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + staleTime, + gcTime: 60_000, + }) + + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + }) + + const routeTree = rootRoute.addChildren([fooRoute, barRoute]) + + return createTestRouter({ + routeTree, + defaultStaleReloadMode, + history: createMemoryHistory(), + }) + } + + const createControlledStaleReload = () => { + let resolveStaleReload: (() => void) | undefined + let callCount = 0 + + const loader = vi.fn(() => { + callCount += 1 + if (callCount === 1) { + return { value: 'first' } + } + + return new Promise<{ value: string }>((resolve) => { + resolveStaleReload = () => resolve({ value: 'second' }) + }) + }) + + return { + loader, + resolveStaleReload: () => resolveStaleReload?.(), + } + } + + const expectBlockingStaleReloadBehavior = async ( + router: RouterCore, + loader: ReturnType, + resolveStaleReload: () => void, + ) => { + await router.navigate({ to: '/foo' }) + expect(loader).toHaveBeenCalledTimes(1) + expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ + value: 'first', + }) + + await vi.advanceTimersByTimeAsync(1) + await router.navigate({ to: '/bar' }) + await vi.advanceTimersByTimeAsync(1) + + let revisitSettled = false + const revisit = router.navigate({ to: '/foo' }).then(() => { + revisitSettled = true + }) + + await vi.waitFor(() => { + expect(loader).toHaveBeenCalledTimes(2) + }) + expect(revisitSettled).toBe(false) + expect(router.state.status).toBe('pending') + expect(router.state.isLoading).toBe(true) + expect(hasActiveMatch(router, '/bar/bar')).toBe(true) + expect(hasActiveMatch(router, '/foo/foo')).toBe(false) + + resolveStaleReload() + await revisit + + expect(revisitSettled).toBe(true) + expect(router.state.status).toBe('idle') + expect(router.state.isLoading).toBe(false) + expect(loader).toHaveBeenCalledTimes(2) + expect(hasActiveMatch(router, '/foo/foo')).toBe(true) + expect(router.state.location.pathname).toBe('/foo') + expect(router.state.resolvedLocation?.pathname).toBe('/foo') + expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ + value: 'second', + }) + } + + const expectBackgroundStaleReloadBehavior = async ( + router: RouterCore, + loader: ReturnType, + resolveStaleReload: () => void, + ) => { + await router.navigate({ to: '/foo' }) + expect(loader).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(1) + await router.navigate({ to: '/bar' }) + await vi.advanceTimersByTimeAsync(1) + + let revisitSettled = false + const revisit = router.navigate({ to: '/foo' }).then(() => { + revisitSettled = true + }) + await revisit + + expect(revisitSettled).toBe(true) + expect(router.state.status).toBe('idle') + expect(router.state.isLoading).toBe(false) + expect(loader).toHaveBeenCalledTimes(2) + expect(hasActiveMatch(router, '/foo/foo')).toBe(true) + expect(router.state.location.pathname).toBe('/foo') + expect(router.state.resolvedLocation?.pathname).toBe('/foo') + expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ + value: 'first', + }) + + resolveStaleReload() + await vi.waitFor(() => { + expect(getMatchById(router, '/foo/foo')?.loaderData).toEqual({ + value: 'second', + }) + }) + } + + test('skips stale loader when only unrelated search params change', async () => { + const rootRoute = new BaseRootRoute({}) + const loader = vi.fn(() => ({ ok: true })) + + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + staleTime: 0, + gcTime: 0, + loaderDeps: ({ search }: { search: Record }) => ({ + page: search['page'], + }), + }) + + const routeTree = rootRoute.addChildren([fooRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo', search: { page: '1', filter: 'a' } }) + expect(loader).toHaveBeenCalledTimes(1) + + await router.navigate({ to: '/foo', search: { page: '1', filter: 'b' } }) + + expect(loader).toHaveBeenCalledTimes(1) + }) + + test('reloads stale loader when loader deps change', async () => { + const rootRoute = new BaseRootRoute({}) + const loader = vi.fn(() => ({ ok: true })) + + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + staleTime: 0, + gcTime: 0, + loaderDeps: ({ search }: { search: Record }) => ({ + page: search['page'], + }), + }) + + const routeTree = rootRoute.addChildren([fooRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo', search: { page: '1' } }) + expect(loader).toHaveBeenCalledTimes(1) + + await router.navigate({ to: '/foo', search: { page: '2' } }) + + expect(loader).toHaveBeenCalledTimes(2) + }) + + test('reuses a fresh preloaded loader when switching to a different match id of the same route', async () => { + const rootRoute = new BaseRootRoute({}) + const rootLoader = vi.fn(() => ({ ok: true })) + const childLoader = vi.fn(() => ({ ok: true })) + + const rootChildRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + loader: rootLoader, + staleTime: 0, + gcTime: 0, + loaderDeps: ({ search }: { search: Record }) => ({ + page: search['page'], + }), + }) + + const leafRoute = new BaseRoute({ + getParentRoute: () => rootChildRoute, + path: '/$postId', + loader: childLoader, + staleTime: 0, + gcTime: 0, + }) + + const routeTree = rootRoute.addChildren([ + rootChildRoute.addChildren([leafRoute]), + ]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.navigate({ + to: '/posts/$postId', + params: { postId: '1' }, + search: { page: '1' }, + }) + + expect(rootLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenCalledTimes(1) + + await router.preloadRoute({ + to: '/posts/$postId', + params: { postId: '2' }, + search: { page: '2' }, + }) + + expect(rootLoader).toHaveBeenCalledTimes(2) + expect(childLoader).toHaveBeenCalledTimes(2) + + await vi.advanceTimersByTimeAsync(1) + + await router.navigate({ + to: '/posts/$postId', + params: { postId: '2' }, + search: { page: '2' }, + }) + + expect(rootLoader).toHaveBeenCalledTimes(2) + expect(childLoader).toHaveBeenCalledTimes(2) + }) + + test('skips stale ancestor loader when only a child path param changes', async () => { + const rootRoute = new BaseRootRoute({}) + const parentLoader = vi.fn(() => ({ ok: true })) + const childLoader = vi.fn(() => ({ ok: true })) + + const orgRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/orgs/$orgId', + loader: parentLoader, + staleTime: 0, + gcTime: 0, + }) + + const userRoute = new BaseRoute({ + getParentRoute: () => orgRoute, + path: '/users/$userId', + loader: childLoader, + staleTime: 0, + gcTime: 0, + }) + + const routeTree = rootRoute.addChildren([orgRoute.addChildren([userRoute])]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.navigate({ + to: '/orgs/$orgId/users/$userId', + params: { orgId: 'acme', userId: 'u1' }, + }) + expect(parentLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenCalledTimes(1) + + await router.navigate({ + to: '/orgs/$orgId/users/$userId', + params: { orgId: 'acme', userId: 'u2' }, + }) + + expect(parentLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenCalledTimes(2) + }) + + test('reloads stale ancestor loader when its own path param changes', async () => { + const rootRoute = new BaseRootRoute({}) + const parentLoader = vi.fn(() => ({ ok: true })) + const childLoader = vi.fn(() => ({ ok: true })) + + const orgRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/orgs/$orgId', + loader: parentLoader, + staleTime: 0, + gcTime: 0, + }) + + const userRoute = new BaseRoute({ + getParentRoute: () => orgRoute, + path: '/users/$userId', + loader: childLoader, + staleTime: 0, + gcTime: 0, + }) + + const routeTree = rootRoute.addChildren([orgRoute.addChildren([userRoute])]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.navigate({ + to: '/orgs/$orgId/users/$userId', + params: { orgId: 'acme', userId: 'u1' }, + }) + expect(parentLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenCalledTimes(1) + + await router.navigate({ + to: '/orgs/$orgId/users/$userId', + params: { orgId: 'beta', userId: 'u2' }, + }) + + expect(parentLoader).toHaveBeenCalledTimes(2) + expect(childLoader).toHaveBeenCalledTimes(2) + }) + + test('revalidates stale loaders on explicit same-location router.load()', async () => { + const rootRoute = new BaseRootRoute({}) + const loader = vi.fn(() => ({ ok: true })) + + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + loader, + staleTime: 0, + gcTime: 0, + loaderDeps: ({ search }: { search: Record }) => ({ + page: search['page'], + }), + }) + + const routeTree = rootRoute.addChildren([fooRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo', search: { page: '1', filter: 'a' } }) + expect(loader).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(1) + await router.load() + await Promise.resolve() + + expect(loader).toHaveBeenCalledTimes(2) + }) + + test('supports object-form loader handler', async () => { + const handler = vi.fn(() => ({ ok: true })) + const router = setup({ + loader: { + handler, + } satisfies LoaderEntry, + }) + + await router.navigate({ to: '/foo' }) + + expect(handler).toHaveBeenCalledTimes(1) + expect(router.state.matches).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + id: '/foo/foo', + loaderData: { ok: true }, + }), + ]), + ) + }) + + test('reloads stale loaders in the background by default', async () => { + const { loader, resolveStaleReload } = createControlledStaleReload() + const router = setup({ loader, staleTime: 0 }) + + await expectBackgroundStaleReloadBehavior( + router, + loader, + resolveStaleReload, + ) + }) + + test('blocks stale reloads when loader staleReloadMode is blocking', async () => { + const { loader, resolveStaleReload } = createControlledStaleReload() + const router = setup({ + staleTime: 0, + loader: { + handler: loader, + staleReloadMode: 'blocking', + } satisfies LoaderEntry, + }) + + await expectBlockingStaleReloadBehavior(router, loader, resolveStaleReload) + }) + + test('blocks stale reloads when defaultStaleReloadMode is blocking', async () => { + const { loader, resolveStaleReload } = createControlledStaleReload() + const router = setup({ + loader, + staleTime: 0, + defaultStaleReloadMode: 'blocking', + }) + + await expectBlockingStaleReloadBehavior(router, loader, resolveStaleReload) + }) + + test('loader staleReloadMode overrides defaultStaleReloadMode', async () => { + const { loader, resolveStaleReload } = createControlledStaleReload() + const router = setup({ + staleTime: 0, + defaultStaleReloadMode: 'blocking', + loader: { + handler: loader, + staleReloadMode: 'background', + } satisfies LoaderEntry, + }) + + await expectBackgroundStaleReloadBehavior( + router, + loader, + resolveStaleReload, + ) + }) +}) + +test('navigating away from a pending route aborts its loader', async () => { + let loaderSignal: AbortSignal | undefined const rootRoute = new BaseRootRoute({}) const fooRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/foo', - pendingMs: WAIT_TIME * 20, + pendingMs: 0, loader: async ({ abortController }) => { + loaderSignal = abortController.signal await new Promise((resolve) => { - const timer = setTimeout(() => { - resolve() - }, WAIT_TIME * 40) - abortController.signal.addEventListener('abort', () => { - onAbortMock() - clearTimeout(timer) - resolve() - }) + abortController.signal.addEventListener( + 'abort', + () => { + resolve() + }, + { once: true }, + ) }) }, pendingComponent: {}, @@ -487,26 +1397,658 @@ test('cancelMatches after pending timeout', async () => { path: '/bar', }) const routeTree = rootRoute.addChildren([fooRoute, barRoute]) - const router = new RouterCore({ routeTree, history: createMemoryHistory() }) + const router = createTestRouter({ routeTree, history: createMemoryHistory() }) await router.load() - router.navigate({ to: '/foo' }) - await sleep(WAIT_TIME * 30) + const fooNavigation = router.navigate({ to: '/foo' }) - // At this point, pending timeout should have triggered - const fooMatch = router.getMatch('/foo/foo') - expect(fooMatch).toBeDefined() + await vi.waitFor(() => { + expect(loaderSignal).toBeDefined() + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: fooRoute.id, + status: 'pending', + }) + }) - // Navigate away, which should cancel the pending match await router.navigate({ to: '/bar' }) - await router.latestLoadPromise + await fooNavigation expect(router.state.location.pathname).toBe('/bar') + expect(router.state.resolvedLocation?.pathname).toBe('/bar') + expect(router.state.status).toBe('idle') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: barRoute.id, + status: 'success', + }) + expect( + router.state.matches.some((match) => match.routeId === fooRoute.id), + ).toBe(false) + expect(loaderSignal?.aborted).toBe(true) +}) - // Verify that abort was called and pending timeout was cleared - expect(onAbortMock).toHaveBeenCalled() - const cancelledFooMatch = router.getMatch('/foo/foo') - expect(cancelledFooMatch?._nonReactive.pendingTimeout).toBeUndefined() +describe('head execution', () => { + const getTitle = (match: { meta?: unknown }) => + (match.meta as Array<{ title?: string }> | undefined)?.[0]?.title + + const setupBeforeLoadNotFoundHierarchy = (throwAtIndex: 1 | 2 | 3) => { + const loaderResolvers: Array<(() => void) | undefined> = [] + + const makeLoader = (index: number) => + vi.fn(async () => { + await new Promise((resolve) => { + loaderResolvers[index] = resolve + }) + return { level: index } + }) + + const makeHead = (label: string) => + vi.fn(() => ({ meta: [{ title: label }] })) + + const rootRoute = new BaseRootRoute({ + loader: makeLoader(0), + head: makeHead('Root'), + }) + + const level1Route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/level-1', + loader: makeLoader(1), + head: makeHead('Level 1'), + beforeLoad: + throwAtIndex === 1 + ? () => { + throw notFound() + } + : undefined, + }) + + const level2Route = new BaseRoute({ + getParentRoute: () => level1Route, + path: '/level-2', + loader: makeLoader(2), + head: makeHead('Level 2'), + beforeLoad: + throwAtIndex === 2 + ? () => { + throw notFound() + } + : undefined, + }) + + const level3Route = new BaseRoute({ + getParentRoute: () => level2Route, + path: '/level-3', + loader: makeLoader(3), + head: makeHead('Level 3'), + beforeLoad: + throwAtIndex === 3 + ? () => { + throw notFound() + } + : undefined, + }) + + const routeTree = rootRoute.addChildren([ + level1Route.addChildren([level2Route.addChildren([level3Route])]), + ]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/level-1/level-2/level-3'], + }), + }) + + const routes = [rootRoute, level1Route, level2Route, level3Route] as const + const loaders = routes.map( + (route) => route.options.loader as ReturnType, + ) + const heads = routes.map( + (route) => route.options.head as ReturnType, + ) + return { + router, + routes, + loaders, + heads, + loaderResolvers, + } + } + + const assertBeforeLoadNotFoundHierarchy = async (throwAtIndex: 1 | 2 | 3) => { + const { router, routes, loaders, heads, loaderResolvers } = + setupBeforeLoadNotFoundHierarchy(throwAtIndex) + + let loadResolved = false + const loadPromise = router.load().then(() => { + loadResolved = true + }) + + await Promise.resolve() + await Promise.resolve() + + expect(loadResolved).toBe(false) + + await vi.waitFor(() => { + loaders.forEach((loader, index) => { + expect(loader).toHaveBeenCalledTimes(index < throwAtIndex ? 1 : 0) + }) + }) + for (let i = 0; i < throwAtIndex; i++) { + loaderResolvers[i]!() + } + + await loadPromise + + const titles = router.state.matches.map(getTitle) + expect(titles.slice(0, throwAtIndex + 1)).toEqual( + ['Root', 'Level 1', 'Level 2', 'Level 3'].slice(0, throwAtIndex + 1), + ) + expect(titles.slice(throwAtIndex + 1).every((title) => !title)).toBe(true) + heads.forEach((head, index) => { + expect(head).toHaveBeenCalledTimes(index <= throwAtIndex ? 1 : 0) + }) + + for (let i = 0; i < throwAtIndex; i++) { + const route = routes[i]! + const match = router.state.matches.find((m) => m.routeId === route.id) + expect(match?.loaderData).toEqual({ level: i }) + } + + const thrownRoute = routes[throwAtIndex]! + const thrownMatch = router.state.matches.find( + (m) => m.routeId === thrownRoute.id, + ) + expect(thrownMatch?.status).toBe('notFound') + } + + ;([1, 2, 3] as const).forEach((throwAtIndex) => { + test(`beforeLoad notFound at hierarchy level ${throwAtIndex} waits for parent loader data and executes heads`, async () => { + await assertBeforeLoadNotFoundHierarchy(throwAtIndex) + }) + }) + + test('projects head when loader throws notFound', async () => { + const head = vi.fn(() => ({ meta: [{ title: 'Test' }] })) + const rootRoute = new BaseRootRoute({}) + const testRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/test', + loader: () => { + throw notFound() + }, + head, + }) + const routeTree = rootRoute.addChildren([testRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/test'] }), + }) + + await router.load() + + const match = router.state.matches.find((m) => m.routeId === testRoute.id) + expect(match?.status).toBe('notFound') + expect(match?.meta).toEqual([{ title: 'Test' }]) + expect(head).toHaveBeenCalledTimes(1) + }) + + test('propagates sync beforeLoad non-notFound error running ancestor loaders and heads', async () => { + const beforeLoadError = new Error('beforeLoad-sync-error') + const rootLoader = vi.fn(() => ({ level: 0 })) + const rootHead = vi.fn(() => ({ meta: [{ title: 'Root' }] })) + const rootRoute = new BaseRootRoute({ + loader: rootLoader, + head: rootHead, + }) + + const childLoader = vi.fn(() => ({ level: 1 })) + const childHead = vi.fn(() => ({ meta: [{ title: 'Child' }] })) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/test', + beforeLoad: () => { + throw beforeLoadError + }, + loader: childLoader, + head: childHead, + }) + + const routeTree = rootRoute.addChildren([childRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/test'] }), + }) + + await router.load() + + expect( + router.state.matches.find((match) => match.routeId === childRoute.id) + ?.error, + ).toBe(beforeLoadError) + + expect(router.state.matches[0]?.loaderData).toEqual({ level: 0 }) + expect(router.state.matches.map(getTitle)).toEqual(['Root', 'Child']) + expect(rootLoader).toHaveBeenCalledTimes(1) + expect(childLoader).not.toHaveBeenCalled() + expect(rootHead).toHaveBeenCalledTimes(1) + expect(childHead).toHaveBeenCalledTimes(1) + }) + + test('propagates async beforeLoad non-notFound error running ancestor loaders and heads', async () => { + const beforeLoadError = new Error('beforeLoad-async-error') + const rootLoader = vi.fn(() => ({ level: 0 })) + const rootHead = vi.fn(() => ({ meta: [{ title: 'Root' }] })) + const rootRoute = new BaseRootRoute({ + loader: rootLoader, + head: rootHead, + }) + + const childLoader = vi.fn(() => ({ level: 1 })) + const childHead = vi.fn(() => ({ meta: [{ title: 'Child' }] })) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/test', + beforeLoad: async () => { + await Promise.resolve() + throw beforeLoadError + }, + loader: childLoader, + head: childHead, + }) + + const routeTree = rootRoute.addChildren([childRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/test'] }), + }) + + await router.load() + + expect( + router.state.matches.find((match) => match.routeId === childRoute.id) + ?.error, + ).toBe(beforeLoadError) + + expect(router.state.matches[0]?.loaderData).toEqual({ level: 0 }) + expect(router.state.matches.map(getTitle)).toEqual(['Root', 'Child']) + expect(rootLoader).toHaveBeenCalledTimes(1) + expect(childLoader).not.toHaveBeenCalled() + expect(rootHead).toHaveBeenCalledTimes(1) + expect(childHead).toHaveBeenCalledTimes(1) + }) + + describe('beforeLoad notFound parent loader outcomes', () => { + type ThrowAtIndex = 1 | 2 | 3 + type ParentFailure = 'notFound' | 'redirect' | 'error' + type ParentFailureMap = Partial> + type Scenario = { + name: string + throwAtIndex: ThrowAtIndex + parentFailures: ParentFailureMap + expectedErrorKind: 'notFound' | 'redirect' + expectedErrorSource?: string + expectedBoundaryIndex?: 0 | 1 | 2 | 3 + expectedLoaderCount: number + expectedHeadTitles: Array + beforeLoadNotFoundFactory?: ( + routes: readonly [any, any, any, any], + ) => ReturnType + } + + const setupScenario = ({ + throwAtIndex, + parentFailures, + beforeLoadNotFoundFactory, + skipRootLoaderOnReload = false, + }: { + throwAtIndex: ThrowAtIndex + parentFailures: ParentFailureMap + beforeLoadNotFoundFactory?: Scenario['beforeLoadNotFoundFactory'] + skipRootLoaderOnReload?: boolean + }) => { + const makeHead = (label: string) => + vi.fn(() => ({ meta: [{ title: label }] })) + + const makeLoader = (index: number) => + vi.fn(({ location }: { location: { pathname: string } }) => { + // Keep failures scoped to the route under test. A root loader which + // redirects unconditionally would also redirect the destination and + // describe an infinite redirect loop rather than precedence between + // the original lane's settled outcomes. + if (location.pathname !== '/redirect-target') { + const failure = parentFailures[index as 0 | 1 | 2] + if (failure === 'notFound') { + throw notFound({ data: { source: `loader-${index}` } }) + } + if (failure === 'redirect') { + throw redirect({ to: '/redirect-target' }) + } + if (failure === 'error') { + throw new Error(`loader-${index}-error`) + } + } + return { level: index } + }) + + const rootRoute = new BaseRootRoute({ + loader: makeLoader(0), + head: makeHead('Root'), + ...(skipRootLoaderOnReload + ? { staleTime: Infinity, shouldReload: () => false } + : {}), + }) + + const level1Route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/level-1', + loader: makeLoader(1), + head: makeHead('Level 1'), + }) + + const level2Route = new BaseRoute({ + getParentRoute: () => level1Route, + path: '/level-2', + loader: makeLoader(2), + head: makeHead('Level 2'), + }) + + const level3Route = new BaseRoute({ + getParentRoute: () => level2Route, + path: '/level-3', + loader: makeLoader(3), + head: makeHead('Level 3'), + }) + + const redirectTargetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/redirect-target', + }) + + const routeTree = rootRoute.addChildren([ + level1Route.addChildren([level2Route.addChildren([level3Route])]), + redirectTargetRoute, + ]) + + const routes = [rootRoute, level1Route, level2Route, level3Route] as const + const loaders = routes.map( + (route) => route.options.loader as ReturnType, + ) + const heads = routes.map( + (route) => route.options.head as ReturnType, + ) + + const throwRoute = routes[throwAtIndex]! + throwRoute.options.beforeLoad = () => { + const beforeLoadNotFound = beforeLoadNotFoundFactory + ? beforeLoadNotFoundFactory(routes) + : notFound({ data: { source: `beforeLoad-${throwAtIndex}` } }) + throw beforeLoadNotFound + } + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/level-1/level-2/level-3'], + }), + }) + + return { + router, + routes, + loaders, + heads, + } + } + + const scenarios = [ + { + name: 'throws beforeLoad notFound when parent loaders succeed', + throwAtIndex: 3 as const, + parentFailures: {} as ParentFailureMap, + expectedErrorKind: 'notFound' as const, + expectedErrorSource: 'beforeLoad-3', + expectedBoundaryIndex: 3, + expectedLoaderCount: 3, + expectedHeadTitles: ['Root', 'Level 1', 'Level 2', 'Level 3'], + }, + { + name: 'promotes a fresh parent loader notFound above a serial child notFound', + throwAtIndex: 3 as const, + parentFailures: { 1: 'notFound' } as ParentFailureMap, + expectedErrorKind: 'notFound' as const, + expectedErrorSource: 'loader-1', + expectedBoundaryIndex: 1, + expectedLoaderCount: 3, + expectedHeadTitles: ['Root', 'Level 1'], + }, + { + name: 'promotes the first fresh parent loader failure above a serial child notFound', + throwAtIndex: 3 as const, + parentFailures: { 1: 'notFound', 2: 'notFound' } as ParentFailureMap, + expectedErrorKind: 'notFound' as const, + expectedErrorSource: 'loader-1', + expectedBoundaryIndex: 1, + expectedLoaderCount: 3, + expectedHeadTitles: ['Root', 'Level 1'], + }, + { + name: 'promotes a fresh root loader notFound above a serial child notFound', + throwAtIndex: 2 as const, + parentFailures: { 0: 'notFound' } as ParentFailureMap, + expectedErrorKind: 'notFound' as const, + expectedErrorSource: 'loader-0', + expectedBoundaryIndex: 0, + expectedLoaderCount: 2, + expectedHeadTitles: ['Root'], + }, + { + name: 'uses explicit routeId from beforeLoad notFound to target ancestor boundary', + throwAtIndex: 3 as const, + parentFailures: {} as ParentFailureMap, + expectedErrorKind: 'notFound' as const, + expectedErrorSource: 'beforeLoad-explicit-level1', + expectedBoundaryIndex: 1, + expectedLoaderCount: 2, + expectedHeadTitles: ['Root', 'Level 1'], + beforeLoadNotFoundFactory: (routes) => + notFound({ + routeId: routes[1].id as never, + data: { source: 'beforeLoad-explicit-level1' }, + }), + }, + { + name: 'falls back to root boundary when beforeLoad notFound uses unknown routeId', + throwAtIndex: 3 as const, + parentFailures: {} as ParentFailureMap, + expectedErrorKind: 'notFound' as const, + expectedErrorSource: 'beforeLoad-invalid-route', + expectedBoundaryIndex: 0, + expectedLoaderCount: 1, + expectedHeadTitles: ['Root'], + beforeLoadNotFoundFactory: () => + notFound({ + routeId: '/does-not-exist' as never, + data: { source: 'beforeLoad-invalid-route' }, + }), + }, + { + name: 'falls back to root boundary when beforeLoad notFound uses non-exact routeId', + throwAtIndex: 3 as const, + parentFailures: {} as ParentFailureMap, + expectedErrorKind: 'notFound' as const, + expectedErrorSource: 'beforeLoad-non-exact-route', + expectedBoundaryIndex: 0, + expectedLoaderCount: 1, + expectedHeadTitles: ['Root'], + beforeLoadNotFoundFactory: (routes) => + notFound({ + routeId: `${routes[1].id}/` as never, + data: { source: 'beforeLoad-non-exact-route' }, + }), + }, + { + name: 'prioritizes redirect when parent loader throws redirect', + throwAtIndex: 3 as const, + parentFailures: { 0: 'redirect' } as ParentFailureMap, + expectedErrorKind: 'redirect' as const, + expectedErrorSource: undefined, + expectedLoaderCount: 3, + expectedHeadTitles: ['Root'], + }, + { + name: 'prioritizes redirect over root-loader notFound when both appear in settled loaders', + throwAtIndex: 3 as const, + parentFailures: { 0: 'notFound', 1: 'redirect' } as ParentFailureMap, + expectedErrorKind: 'redirect' as const, + expectedErrorSource: undefined, + expectedLoaderCount: 3, + expectedHeadTitles: ['Root'], + }, + { + name: 'promotes the first fresh parent failure when later loaders fail differently', + throwAtIndex: 3 as const, + parentFailures: { 1: 'notFound', 2: 'error' } as ParentFailureMap, + expectedErrorKind: 'notFound' as const, + expectedErrorSource: 'loader-1', + expectedBoundaryIndex: 1, + expectedLoaderCount: 3, + expectedHeadTitles: ['Root', 'Level 1'], + }, + ] satisfies Array + + test.each(scenarios)('$name', async (scenario) => { + const { router, routes, loaders, heads } = setupScenario({ + throwAtIndex: scenario.throwAtIndex, + parentFailures: scenario.parentFailures, + beforeLoadNotFoundFactory: scenario.beforeLoadNotFoundFactory, + }) + + await router.load() + const matches = router.state.matches + + if (scenario.expectedErrorKind === 'redirect') { + expect(router.state.location.pathname).toBe('/redirect-target') + expect(matches.at(-1)).toEqual( + expect.objectContaining({ + pathname: '/redirect-target', + status: 'success', + }), + ) + expect(matches.some((match) => match.error !== undefined)).toBe(false) + expect(matches.some((match) => match._notFound)).toBe(false) + } else { + const boundary = matches.find( + (match) => match.status === 'notFound' || match._notFound, + )! + expect(boundary.routeId).toBe( + routes[scenario.expectedBoundaryIndex!]!.id, + ) + + expect(boundary.error).toEqual( + expect.objectContaining({ + isNotFound: true, + data: { source: scenario.expectedErrorSource }, + }), + ) + + if (scenario.expectedBoundaryIndex === 0) { + expect(boundary.status).toBe('success') + expect(boundary._notFound).toBe(true) + } else { + expect(boundary.status).toBe('notFound') + expect(boundary.error).toEqual( + expect.objectContaining({ routeId: boundary.routeId }), + ) + } + } + + loaders.forEach((loader, index) => { + const originalLaneCalls = loader.mock.calls.filter( + ([options]) => + options.location.pathname === '/level-1/level-2/level-3', + ) + expect(originalLaneCalls).toHaveLength( + index < scenario.expectedLoaderCount ? 1 : 0, + ) + }) + heads.forEach((head, index) => { + expect(head).toHaveBeenCalledTimes( + index < scenario.expectedHeadTitles.length ? 1 : 0, + ) + }) + expect( + matches.map(getTitle).filter((title) => title !== undefined), + ).toEqual(scenario.expectedHeadTitles) + expect(router.state.status).toBe('idle') + }) + + test('sets _notFound on root match when beforeLoad notFound targets root boundary', async () => { + const { router, routes } = setupScenario({ + throwAtIndex: 3, + parentFailures: {}, + beforeLoadNotFoundFactory: (innerRoutes) => + notFound({ + routeId: innerRoutes[0].id as never, + data: { source: 'beforeLoad-root-explicit' }, + }), + }) + + await router.load() + + const rootMatch = router.state.matches.find( + (m) => m.routeId === routes[0].id, + ) + + expect(rootMatch?._notFound).toBe(true) + expect(rootMatch?.status).toBe('success') + expect(rootMatch?.error).toEqual( + expect.objectContaining({ + isNotFound: true, + data: { source: 'beforeLoad-root-explicit' }, + }), + ) + }) + + test('clears stale root _notFound when the root loader is skipped on a successful reload', async () => { + const { router, routes, loaders } = setupScenario({ + throwAtIndex: 3, + parentFailures: {}, + skipRootLoaderOnReload: true, + beforeLoadNotFoundFactory: (innerRoutes) => + notFound({ + routeId: innerRoutes[0].id as never, + data: { source: 'beforeLoad-root-explicit' }, + }), + }) + + await router.load() + const initialRootMatch = router.state.matches.find( + (match) => match.routeId === routes[0].id, + ) + expect(initialRootMatch?._notFound).toBe(true) + expect(initialRootMatch?.error).toEqual( + expect.objectContaining({ + isNotFound: true, + data: { source: 'beforeLoad-root-explicit' }, + }), + ) + expect(loaders[0]).toHaveBeenCalledTimes(1) + + const throwingRoute = routes[3] + throwingRoute.options.beforeLoad = undefined + + await router.load() + + const rootMatch = router.state.matches.find( + (m) => m.routeId === routes[0].id, + ) + + expect(rootMatch?._notFound).toBe(false) + expect(rootMatch?.status).toBe('success') + expect(loaders[0]).toHaveBeenCalledTimes(1) + }) + }) }) describe('params.parse notFound', () => { @@ -526,16 +2068,16 @@ describe('params.parse notFound', () => { }, }) const routeTree = rootRoute.addChildren([testRoute]) - const router = new RouterCore({ + const router = createTestRouter({ routeTree, history: createMemoryHistory({ initialEntries: ['/test/invalid'] }), }) await router.load() - const match = router.state.pendingMatches?.find( - (m) => m.routeId === testRoute.id, - ) + const match = router.stores.matches + .get() + .find((m) => m.routeId === testRoute.id) expect(match?.status).toBe('notFound') }) @@ -556,7 +2098,7 @@ describe('params.parse notFound', () => { }, }) const routeTree = rootRoute.addChildren([testRoute]) - const router = new RouterCore({ + const router = createTestRouter({ routeTree, history: createMemoryHistory({ initialEntries: ['/test/123'] }), }) @@ -565,7 +2107,203 @@ describe('params.parse notFound', () => { const match = router.state.matches.find((m) => m.routeId === testRoute.id) expect(match?.status).toBe('success') - expect(router.state.statusCode).toBe(200) + }) +}) + +describe('routeId in context options', () => { + test('beforeLoad and context receive correct routeId for root route', async () => { + const beforeLoad = vi.fn() + const context = vi.fn() + const rootRoute = new BaseRootRoute({ + beforeLoad, + context, + }) + + const routeTree = rootRoute.addChildren([]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.load() + + expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(beforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ + routeId: rootRouteId, + }), + ) + + expect(context).toHaveBeenCalledTimes(1) + expect(context).toHaveBeenCalledWith( + expect.objectContaining({ + routeId: rootRouteId, + }), + ) + }) + + test('beforeLoad and context receive correct routeId for child route', async () => { + const beforeLoad = vi.fn() + const context = vi.fn() + const rootRoute = new BaseRootRoute({}) + + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad, + context, + }) + + const routeTree = rootRoute.addChildren([fooRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/foo' }) + + expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(beforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ + routeId: '/foo', + }), + ) + + expect(context).toHaveBeenCalledTimes(1) + expect(context).toHaveBeenCalledWith( + expect.objectContaining({ + routeId: '/foo', + }), + ) + }) + + test('beforeLoad and context receive correct routeId for nested route', async () => { + const parentBeforeLoad = vi.fn() + const parentContext = vi.fn() + const childBeforeLoad = vi.fn() + const childContext = vi.fn() + const rootRoute = new BaseRootRoute({}) + + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: parentBeforeLoad, + context: parentContext, + }) + + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: childBeforeLoad, + context: childContext, + }) + + const routeTree = rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/parent/child' }) + + expect(parentBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ + routeId: '/parent', + }), + ) + expect(parentContext).toHaveBeenCalledWith( + expect.objectContaining({ + routeId: '/parent', + }), + ) + expect(childBeforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ + routeId: '/parent/child', + }), + ) + expect(childContext).toHaveBeenCalledWith( + expect.objectContaining({ + routeId: '/parent/child', + }), + ) + }) + + test('beforeLoad and context receive correct routeId for route with dynamic params', async () => { + const beforeLoad = vi.fn() + const context = vi.fn() + const rootRoute = new BaseRootRoute({}) + + const postRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts/$postId', + beforeLoad, + context, + }) + + const routeTree = rootRoute.addChildren([postRoute]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.navigate({ to: '/posts/$postId', params: { postId: '123' } }) + + expect(beforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ + routeId: '/posts/$postId', + }), + ) + expect(context).toHaveBeenCalledWith( + expect.objectContaining({ + routeId: '/posts/$postId', + }), + ) + }) + + test('beforeLoad and context receive correct routeId for layout route', async () => { + const beforeLoad = vi.fn() + const context = vi.fn() + const rootRoute = new BaseRootRoute({}) + + const layoutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + id: '/_layout', + beforeLoad, + context, + }) + + const indexRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '/', + }) + + const routeTree = rootRoute.addChildren([ + layoutRoute.addChildren([indexRoute]), + ]) + + const router = createTestRouter({ + routeTree, + history: createMemoryHistory(), + }) + + await router.load() + + expect(beforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ + routeId: '/_layout', + }), + ) + expect(context).toHaveBeenCalledWith( + expect.objectContaining({ + routeId: '/_layout', + }), + ) }) }) diff --git a/packages/router-core/tests/loader-architecture-regressions.test.ts b/packages/router-core/tests/loader-architecture-regressions.test.ts new file mode 100644 index 0000000000..97561a9f72 --- /dev/null +++ b/packages/router-core/tests/loader-architecture-regressions.test.ts @@ -0,0 +1,1188 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, + redirect, +} from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +test.each([ + ['error', () => new Error('parent failed')], + ['notFound', () => notFound()], +] as const)( + 'a child can redirect after observing its parent loader %s', + async (expectedStatus, createFailure) => { + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw createFailure() + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async ({ parentMatchPromise }) => { + const parent = await parentMatchPromise + if (parent.status === expectedStatus) { + throw redirect({ to: '/target' }) + } + return parent.status + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ + initialEntries: ['/parent/child'], + }), + }) + + await router.load() + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + }, +) + +test.each(['client', 'server'] as const)( + 'a descendant self-abort cannot hide redirecting onError on the %s', + async (environment) => { + const parentGate = createControlledPromise() + const childGate = createControlledPromise() + const parentOnError = vi.fn() + const childOnError = vi.fn(() => { + throw redirect({ to: '/target' }) + }) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: async () => { + await parentGate + throw new Error('parent failed') + }, + onError: parentOnError, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async ({ abortController }) => { + await childGate + abortController.abort() + throw new Error('child failed') + }, + onError: childOnError, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: environment === 'server', + }) + + const loading = + environment === 'server' + ? loadServerResponse(router, '/parent/child') + : router.load() + parentGate.resolve() + await vi.waitFor(() => expect(parentOnError).toHaveBeenCalledOnce()) + childGate.resolve() + await vi.waitFor(() => expect(childOnError).toHaveBeenCalledOnce()) + + if (environment === 'server') { + const response = await loading + expect(response).toBeDefined() + if (!response) { + return + } + expect(response.status).toBe(307) + expect(response.headers.get('Location')).toBe('/target') + } else { + await loading + expect(router.state.location.pathname).toBe('/target') + } + }, +) + +test('superseding a load clears fetching state from the still-presented lane', async () => { + const firstGate = createControlledPromise() + const secondGate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + validateSearch: (search: Record) => ({ + revision: Number(search.revision ?? 0), + }), + beforeLoad: ({ search }) => (search.revision === 1 ? firstGate : undefined), + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + loader: () => secondGate, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + const firstNavigation = router.navigate({ + to: '/page', + search: { revision: 1 }, + }) + await vi.waitFor(() => + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'success', + isFetching: 'beforeLoad', + }), + ) + + const secondNavigation = router.navigate({ to: '/other' }) + await vi.waitFor(() => { + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + isFetching: false, + }) + }) + + firstGate.resolve() + secondGate.resolve() + await Promise.all([firstNavigation, secondNavigation]) +}) + +test('an ignored preload flight is released after a navigation has planned its loaders', async () => { + const preloadFailure = createControlledPromise() + const childGate = createControlledPromise() + let preloadSignal: AbortSignal | undefined + const parentLoader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + const generation = parentLoader.mock.calls.length + if (generation === 1) { + return 'initial parent data' + } + preloadSignal = abortController.signal + return preloadFailure + }, + ) + const childLoader = vi.fn(() => childGate) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + shouldReload: ({ preload }) => preload, + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + const siblingRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/sibling', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute, siblingRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/parent/sibling' }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(2)) + + const navigation = router.navigate({ to: '/parent/child' }) + await vi.waitFor(() => expect(childLoader).toHaveBeenCalledOnce()) + + preloadFailure.reject(new Error('discarded preload generation')) + await preload + expect(preloadSignal?.aborted).toBe(true) + + childGate.resolve('child data') + await navigation +}) + +test('an ordinary route-context failure still permits ancestor loaders', async () => { + const failure = new Error('child context failed') + const parentLoader = vi.fn(() => 'parent data') + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + context: () => { + throw failure + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + + expect(parentLoader).toHaveBeenCalledOnce() + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + status: 'success', + loaderData: 'parent data', + }) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: childRoute.id, + status: 'error', + error: failure, + }) +}) + +test('a failed route context is recomputed when the route is retried', async () => { + const failure = new Error('context failed') + let shouldFail = true + let generation = 0 + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + context: () => { + generation++ + if (shouldFail) { + throw failure + } + return { generation } + }, + loader: ({ context }) => context.generation, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: route.id, + status: 'error', + error: failure, + }) + + shouldFail = false + await router.invalidate() + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: route.id, + status: 'success', + loaderData: 2, + }) +}) + +test('invalidation reruns the loader with same-id route context', async () => { + let contextGeneration = 0 + let loaderGeneration = 0 + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + context: () => ({ generation: ++contextGeneration }), + loader: ({ context }) => ({ + loader: ++loaderGeneration, + context: context.generation, + }), + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + expect(router.state.matches.at(-1)?.loaderData).toEqual({ + loader: 1, + context: 1, + }) + + await router.invalidate() + + expect(router.state.matches.at(-1)?.loaderData).toEqual({ + loader: 2, + context: 1, + }) +}) + +test("a settled preload cannot abort a navigation's beforeLoad controller", async () => { + const suspended = createControlledPromise() + let navigationSignal: AbortSignal | undefined + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + beforeLoad: ({ abortController, preload }) => { + if (!preload) { + navigationSignal = abortController.signal + } + throw suspended + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/guarded' }) + const navigation = router.navigate({ to: '/guarded' }) + + await preload + expect(navigationSignal?.aborted).toBe(false) + + await navigation +}) + +test('a fast background candidate remains private when a reentrant navigation wins', async () => { + let parentLoads = 0 + let childLoads = 0 + let activeSignal: AbortSignal | undefined + let replacementSignal: AbortSignal | undefined + let reentrantNavigation: Promise | undefined + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + reload: Number(search.reload ?? 0), + }), + shouldReload: ({ location }) => + (location.search as { reload: number }).reload === 1, + loader: ({ abortController }) => { + parentLoads++ + if (parentLoads === 1) { + activeSignal = abortController.signal + } else { + replacementSignal = abortController.signal + } + return { revision: parentLoads } + }, + onStay: (match) => { + if (match.search.reload === 1 && !reentrantNavigation) { + reentrantNavigation = router.navigate({ + to: '/parent/child', + search: { reload: 2 }, + }) + } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + shouldReload: ({ location }) => + (location.search as { reload: number }).reload === 1, + loader: () => { + childLoads++ + if (childLoads === 2) { + throw redirect({ to: '/target' }) + } + return 'child data' + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ + initialEntries: ['/parent/child?reload=0'], + }), + }) + + await router.load() + await router.navigate({ + to: '/parent/child', + search: { reload: 1 }, + }) + await reentrantNavigation + + expect(router.state.location.search).toEqual({ reload: 2 }) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ loaderData: { revision: 1 } }) + expect(parentLoads).toBe(2) + expect(activeSignal?.aborted).toBe(false) + expect(replacementSignal?.aborted).toBe(true) +}) + +test('a superseding navigation reuses a pending background loader after async beforeLoad', async () => { + const backgroundResult = createControlledPromise() + const beforeLoadStarted = createControlledPromise() + const beforeLoadGate = createControlledPromise() + const signals: Array = [] + let generation = 0 + + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + validateSearch: (search: Record) => ({ + reload: Number(search.reload ?? 0), + }), + shouldReload: ({ location }) => + (location.search as { reload: number }).reload === 1 ? true : undefined, + beforeLoad: async ({ search }) => { + if (search.reload === 2) { + beforeLoadStarted.resolve() + await beforeLoadGate + } + }, + loader: { + staleReloadMode: 'background', + handler: ({ abortController }) => { + signals.push(abortController.signal) + generation++ + return generation === 2 ? backgroundResult : generation + }, + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ + initialEntries: ['/page?reload=0'], + }), + }) + + await router.load() + await router.navigate({ + to: '/page', + search: { reload: 1 }, + }) + await vi.waitFor(() => expect(generation).toBe(2)) + + const successor = router.navigate({ + to: '/page', + search: { reload: 2 }, + }) + await beforeLoadStarted + + backgroundResult.resolve(2) + beforeLoadGate.resolve() + await successor + + await vi.waitFor(() => { + expect(router.state.matches.at(-1)?.loaderData).toBe(2) + }) + expect(generation).toBe(2) + expect(signals[1]?.aborted).toBe(false) + expect(router.state.matches.at(-1)?.preload).toBe(false) +}) + +test('an ancestor beforeLoad failure releases an unconsumed background loader', async () => { + const backgroundResult = createControlledPromise() + const signals: Array = [] + let generation = 0 + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + phase: String(search.phase ?? 'initial'), + }), + beforeLoad: ({ search }) => { + if (search.phase === 'fail') { + throw new Error('parent failed') + } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + shouldReload: ({ location }) => + (location.search as { phase: string }).phase === 'refresh' + ? true + : undefined, + staleTime: Infinity, + loader: { + staleReloadMode: 'background', + handler: ({ abortController }) => { + signals.push(abortController.signal) + generation++ + return generation === 2 ? backgroundResult : generation + }, + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ + initialEntries: ['/parent/child?phase=initial'], + }), + }) + + await router.load() + await router.navigate({ + to: '/parent/child', + search: { phase: 'refresh' }, + }) + await vi.waitFor(() => expect(generation).toBe(2)) + + await router.navigate({ + to: '/parent/child', + search: { phase: 'fail' }, + }) + + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ status: 'error' }) + expect(signals[1]?.aborted).toBe(true) + + backgroundResult.resolve(2) + await router.navigate({ + to: '/parent/child', + search: { phase: 'recovered' }, + }) + + expect(generation).toBe(2) + expect(router.state.matches.at(-1)?.loaderData).toBe(1) +}) + +test('reentrant navigation from onError cancels stale serial work', async () => { + const failure = new Error('stale context failed') + const parentLoader = vi.fn(() => 'parent data') + let successor: Promise | undefined + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + context: () => { + throw failure + }, + onError: () => { + successor ??= router.navigate({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/parent/child' }) + await successor + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)?.routeId).toBe(targetRoute.id) + expect(router.state.matches.some((match) => match.error === failure)).toBe( + false, + ) + expect(parentLoader).not.toHaveBeenCalled() +}) + +test('a joined descendant loader redirect still wins after an ancestor loader fails', async () => { + const childStarted = createControlledPromise() + const childRedirect = createControlledPromise() + const ancestorFailure = new Error('navigation parent failed') + let childLoads = 0 + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + mode: String(search.mode ?? ''), + }), + loaderDeps: ({ search }) => ({ mode: search.mode }), + loader: ({ location }) => { + if ((location.search as { mode: string }).mode === 'navigation') { + throw ancestorFailure + } + return 'preload parent data' + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + childLoads++ + if (childLoads === 1) { + childStarted.resolve() + await childRedirect + throw redirect({ to: '/target' }) + } + return 'retried child data' + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ + to: '/parent/child', + search: { mode: 'preload' }, + }) + await childStarted + + const navigation = router.navigate({ + to: '/parent/child', + search: { mode: 'navigation' }, + }) + childRedirect.resolve() + await Promise.all([preload, navigation]) + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + expect(childLoads).toBe(1) +}) + +test('an unrelated preload redirect does not override a navigation error', async () => { + const preloadChildStarted = createControlledPromise() + const releasePreloadRedirect = createControlledPromise() + const navigationFailure = new Error('navigation parent failed') + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + mode: String(search.mode ?? ''), + }), + loaderDeps: ({ search }) => ({ mode: search.mode }), + loader: ({ deps }) => { + if (deps.mode === 'navigation') { + throw navigationFailure + } + return 'preload parent data' + }, + errorComponent: () => null, + }) + const childLoader = vi.fn(async ({ deps }: { deps: { mode: string } }) => { + if (deps.mode === 'preload') { + preloadChildStarted.resolve() + await releasePreloadRedirect + throw redirect({ to: '/target' }) + } + return 'navigation child data' + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loaderDeps: ({ search }) => ({ mode: search.mode }), + loader: childLoader, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ + to: '/parent/child', + search: { mode: 'preload' }, + }) + await preloadChildStarted + + await router.navigate({ + to: '/parent/child', + search: { mode: 'navigation' }, + }) + + expect(router.state.location).toMatchObject({ + pathname: '/parent/child', + search: { mode: 'navigation' }, + }) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + status: 'error', + error: navigationFailure, + }) + expect(childLoader).toHaveBeenCalledTimes(2) + + releasePreloadRedirect.resolve() + const preloaded = await preload + + expect(preloaded?.at(-1)?.routeId).toBe(targetRoute.id) + expect(router.state.location).toMatchObject({ + pathname: '/parent/child', + search: { mode: 'navigation' }, + }) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + status: 'error', + error: navigationFailure, + }) +}) + +test('a loaderDeps error is handled by the route error boundary', async () => { + const failure = new Error('loader deps failed') + const rootRoute = new BaseRootRoute({}) + const brokenRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/broken', + loaderDeps: (): Record => { + throw failure + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([brokenRoute]), + history: createMemoryHistory({ initialEntries: ['/broken'] }), + }) + + await router.load() + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: brokenRoute.id, + status: 'error', + error: failure, + }) +}) + +test('loaderDeps redirects use the bounded navigation redirect policy', async () => { + const rootRoute = new BaseRootRoute({}) + const routes = Array.from( + { length: 23 }, + (_, index) => + new BaseRoute({ + getParentRoute: () => rootRoute, + path: `/step-${index}`, + loaderDeps: + index === 22 + ? undefined + : () => { + throw redirect({ to: `/step-${index + 1}` }) + }, + }), + ) + const router = createTestRouter({ + routeTree: rootRoute.addChildren(routes as any) as any, + history: createMemoryHistory({ initialEntries: ['/step-0'] }), + }) + + await router.load() + + expect(router.state.location.pathname).toBe('/step-20') + expect( + router.state.matches.find((match) => match.status !== 'success'), + ).toMatchObject({ + routeId: rootRoute.id, + status: 'error', + error: expect.objectContaining({ + message: 'Too many redirects', + }), + }) +}) + +test('a reentrant user navigation starts a fresh redirect chain', async () => { + let navigateFresh: () => void + const rootRoute = new BaseRootRoute({}) + const chain = Array.from( + { length: 20 }, + (_, index) => + new BaseRoute({ + getParentRoute: () => rootRoute, + path: `/chain-${index}`, + beforeLoad: + index < 19 + ? () => { + throw redirect({ to: `/chain-${index + 1}` }) + } + : () => navigateFresh(), + }), + ) + const freshRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/fresh', + beforeLoad: () => { + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + ...(chain as any), + freshRoute, + targetRoute, + ]) as any, + history: createMemoryHistory({ initialEntries: ['/chain-0'] }), + }) + navigateFresh = () => { + void router.navigate({ to: '/fresh' }) + } + + await router.load() + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) +}) + +test('a superseded load settles without waiting for stale asset projection', async () => { + const slowHeadStarted = createControlledPromise() + const slowHead = createControlledPromise<{ + meta: Array<{ title: string }> + }>() + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const slowRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/slow', + head: () => { + slowHeadStarted.resolve() + return slowHead + }, + scripts: () => [{ children: 'window.route = "slow"' }], + headers: () => ({ 'x-route': 'slow' }), + }) + const fastRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/fast', + head: () => ({ meta: [{ title: 'fast' }] }), + scripts: () => [{ children: 'window.route = "fast"' }], + headers: () => ({ 'x-route': 'fast' }), + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, slowRoute, fastRoute]), + history, + }) + + await router.load() + history.push('/slow') + const slowLoad = router.load() + await slowHeadStarted + + history.push('/fast') + const fastLoad = router.load() + await fastLoad + + const settledBeforeProjection = await Promise.race([ + slowLoad.then(() => true), + new Promise((resolve) => setTimeout(() => resolve(false), 100)), + ]) + + slowHead.resolve({ meta: [{ title: 'slow' }] }) + await slowLoad + await Promise.resolve() + + expect(settledBeforeProjection).toBe(true) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: fastRoute.id, + meta: [{ title: 'fast' }], + scripts: [{ children: 'window.route = "fast"' }], + }) +}) + +test('server response headers stop at the terminal render boundary', async () => { + let failParent = false + const rootRoute = new BaseRootRoute({ + headers: () => ({ 'x-root': 'root' }), + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + if (failParent) { + throw new Error('parent failed') + } + }, + headers: () => ({ 'x-parent': 'parent' }), + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + headers: () => ({ 'x-child': 'child' }), + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + + await router.load() + expect(router.state.matches.at(-1)?.headers).toEqual({ 'x-child': 'child' }) + + failParent = true + const response = await loadServerResponse(router, '/parent/child') + + expect(router.state.matches).toHaveLength(3) + expect(router.state.matches[1]).toMatchObject({ + routeId: parentRoute.id, + status: 'error', + }) + expect(response.headers.get('x-root')).toBe('root') + expect(response.headers.get('x-parent')).toBe('parent') + expect(response.headers.get('x-child')).toBeNull() +}) + +test('a superseded load settles without waiting for its normal component chunk', async () => { + const chunkStarted = createControlledPromise() + const chunk = createControlledPromise() + const onError = vi.fn() + const component = Object.assign(() => null, { + preload: () => { + chunkStarted.resolve() + return chunk + }, + }) + const rootRoute = new BaseRootRoute({}) + const slowRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/slow', + component, + onError, + }) + const fastRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/fast', + }) + const history = createMemoryHistory({ initialEntries: ['/slow'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([slowRoute, fastRoute]), + history, + }) + + const slowLoad = router.load() + await chunkStarted + history.push('/fast') + await router.load() + + expect( + await Promise.race([ + slowLoad.then(() => true), + new Promise((resolve) => setTimeout(() => resolve(false), 100)), + ]), + ).toBe(true) + expect(router.state.matches.at(-1)?.routeId).toBe(fastRoute.id) + + chunk.reject(new Error('obsolete chunk failed')) + await Promise.resolve() + expect(onError).not.toHaveBeenCalled() +}) + +test('a superseded load settles without waiting for its terminal boundary chunk', async () => { + const chunkStarted = createControlledPromise() + const chunk = createControlledPromise() + const loaderError = new Error('loader failed') + const onError = vi.fn() + const errorComponent = Object.assign(() => null, { + preload: () => { + chunkStarted.resolve() + return chunk + }, + }) + const rootRoute = new BaseRootRoute({}) + const slowRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/slow', + loader: () => { + throw loaderError + }, + errorComponent, + onError, + }) + const fastRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/fast', + }) + const history = createMemoryHistory({ initialEntries: ['/slow'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([slowRoute, fastRoute]), + history, + }) + + const slowLoad = router.load() + await chunkStarted + history.push('/fast') + await router.load() + + expect( + await Promise.race([ + slowLoad.then(() => true), + new Promise((resolve) => setTimeout(() => resolve(false), 100)), + ]), + ).toBe(true) + expect(router.state.matches.at(-1)?.routeId).toBe(fastRoute.id) + + chunk.reject(new Error('obsolete boundary chunk failed')) + await Promise.resolve() + expect(onError).toHaveBeenCalledOnce() + expect(onError).toHaveBeenCalledWith(loaderError) +}) + +test('a stale shouldReload cannot continue a superseded preload', async () => { + const loader = vi.fn(() => 'cached') + const onError = vi.fn() + let reenter = false + let winner: Promise | undefined + let router: ReturnType + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const cachedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/cached', + preloadStaleTime: 0, + shouldReload: () => { + if (reenter) { + router.history.push('/winner') + winner = router.load() + throw new Error('obsolete shouldReload failure') + } + return true + }, + loader, + onError, + }) + const winnerRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/winner', + }) + router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, cachedRoute, winnerRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/cached' }) + reenter = true + await router.preloadRoute({ to: '/cached' }) + await winner + + expect(router.state.location.pathname).toBe('/winner') + expect(router.state.matches.at(-1)?.routeId).toBe(winnerRoute.id) + expect(loader).toHaveBeenCalledOnce() + // Preload lanes run to completion despite the navigation, so the stale + // shouldReload's failure surfaces through onError (matching pre-rewrite + // behavior for preload errors) — but it cannot restart the loader or + // disturb the winning navigation. + expect(onError).toHaveBeenCalledOnce() +}) + +test('an onLeave navigation to the in-flight destination runs a fresh lane', async () => { + const beforeLoad = vi.fn() + const firstEnter = vi.fn() + const firstStay = vi.fn() + let successor: Promise | undefined + let redirected = false + let router: ReturnType + + const rootRoute = new BaseRootRoute({}) + const fromRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/from', + onLeave: () => { + if (!redirected) { + redirected = true + successor = router.navigate({ to: '/first' }) + } + }, + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/first', + beforeLoad, + onEnter: firstEnter, + onStay: firstStay, + }) + router = createTestRouter({ + routeTree: rootRoute.addChildren([fromRoute, firstRoute]), + history: createMemoryHistory({ initialEntries: ['/from'] }), + }) + + await router.load() + await router.navigate({ to: '/first' }) + await successor + + expect(router.state.location.pathname).toBe('/first') + expect(router.state.matches.at(-1)?.routeId).toBe(firstRoute.id) + expect(beforeLoad).toHaveBeenCalledTimes(2) + expect(firstEnter.mock.calls.length + firstStay.mock.calls.length).toBe(1) +}) diff --git a/packages/router-core/tests/loader-self-abort.test.ts b/packages/router-core/tests/loader-self-abort.test.ts new file mode 100644 index 0000000000..68916b1d68 --- /dev/null +++ b/packages/router-core/tests/loader-self-abort.test.ts @@ -0,0 +1,73 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +test.each([false, true])( + 'a loader can fulfill after aborting its controller with isServer=%s', + async (isServer) => { + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: ({ abortController }) => { + abortController.abort() + return 'accepted data' + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer, + }) + + if (isServer) { + expect((await loadServerResponse(router, '/page')).status).toBe(200) + } else { + await router.load() + } + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'success', + loaderData: 'accepted data', + }) + }, +) + +test.each([false, true])( + 'a loader rejection remains an error after aborting its controller with isServer=%s', + async (isServer) => { + const failure = new Error('loader failed after aborting its controller') + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: ({ abortController }) => { + abortController.abort() + throw failure + }, + errorComponent: () => null, + onError, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer, + }) + + if (isServer) { + expect((await loadServerResponse(router, '/page')).status).toBe(500) + } else { + await router.load() + } + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'error', + error: failure, + }) + expect(onError).toHaveBeenCalledWith(failure) + }, +) diff --git a/packages/router-core/tests/loader-thrown-promise.test.ts b/packages/router-core/tests/loader-thrown-promise.test.ts new file mode 100644 index 0000000000..e45eede84f --- /dev/null +++ b/packages/router-core/tests/loader-thrown-promise.test.ts @@ -0,0 +1,57 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +test.each([ + ['beforeLoad', false], + ['beforeLoad', true], + ['loader', false], + ['loader', true], +] as const)( + 'a synchronously thrown %s Promise has the same meaning with isServer=%s', + async (hook, isServer) => { + const thrown = Promise.resolve('not loader data') + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + beforeLoad: + hook === 'beforeLoad' + ? () => { + throw thrown + } + : undefined, + loader: + hook === 'loader' + ? () => { + throw thrown + } + : undefined, + onError, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer, + }) + + if (isServer) { + const response = await loadServerResponse(router, '/target') + expect(response.status).toBe(500) + } else { + await router.load() + } + + const error = router.state.matches.at(-1)?.error + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'error', + }) + expect(error).toBeInstanceOf(Error) + expect((error as Error).cause).toBe(thrown) + expect(onError).toHaveBeenCalledWith(error) + }, +) diff --git a/packages/router-core/tests/lru.test.ts b/packages/router-core/tests/lru.test.ts deleted file mode 100644 index f601816596..0000000000 --- a/packages/router-core/tests/lru.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createLRUCache } from '../src/lru-cache' - -describe('LRU Cache', () => { - it('evicts oldest set', () => { - const cache = createLRUCache(3) - cache.set('a', 1) - cache.set('b', 2) - cache.set('c', 3) - cache.set('d', 4) // 'a' should be evicted - expect(cache.get('a')).toBeUndefined() - expect(cache.get('b')).toBe(2) - }) - it('evicts oldest used', () => { - const cache = createLRUCache(3) - cache.set('a', 1) - cache.set('b', 2) - cache.set('c', 3) - cache.get('a') // 'a' is now the most recently used - cache.set('d', 4) // 'b' should be evicted - expect(cache.get('b')).toBeUndefined() - expect(cache.get('a')).toBe(1) - }) -}) diff --git a/packages/router-core/tests/manifest.test.ts b/packages/router-core/tests/manifest.test.ts new file mode 100644 index 0000000000..f9d5d961df --- /dev/null +++ b/packages/router-core/tests/manifest.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it } from 'vitest' +import { appendUniqueUserTags } from '../src/manifest' +import type { RouterManagedTag } from '../src/manifest' + +describe('appendUniqueUserTags', () => { + it('does not modify the target for an empty category', () => { + const existing: RouterManagedTag = { + tag: 'meta', + attrs: { + name: 'description', + content: 'existing', + }, + } + const target = [existing] + + appendUniqueUserTags(target, []) + + expect(target).toEqual([existing]) + }) + + it('appends a single tag unchanged', () => { + const tag: RouterManagedTag = { + tag: 'title', + children: 'Home', + } + const target: Array = [] + + appendUniqueUserTags(target, [tag]) + + expect(target).toEqual([tag]) + expect(target[0]).toBe(tag) + }) + + it('dedupes equivalent tags within one appended category', () => { + const firstTag: RouterManagedTag = { + tag: 'link', + attrs: { + href: '/style.css', + rel: 'stylesheet', + }, + } + const duplicateTag: RouterManagedTag = { + tag: 'link', + attrs: { + href: '/style.css', + rel: 'stylesheet', + }, + } + const nextTag: RouterManagedTag = { + tag: 'link', + attrs: { + href: '/next.css', + rel: 'stylesheet', + }, + } + const target: Array = [] + + appendUniqueUserTags(target, [firstTag, duplicateTag, nextTag]) + + expect(target).toEqual([firstTag, nextTag]) + expect(target[0]).toBe(firstTag) + }) + + it('keeps tags that differ by attributes within one category', () => { + const target: Array = [] + + appendUniqueUserTags(target, [ + { + tag: 'meta', + attrs: { + name: 'description', + content: 'first', + }, + }, + { + tag: 'meta', + attrs: { + name: 'description', + content: 'second', + }, + }, + ]) + + expect(target).toEqual([ + { + tag: 'meta', + attrs: { + name: 'description', + content: 'first', + }, + }, + { + tag: 'meta', + attrs: { + name: 'description', + content: 'second', + }, + }, + ]) + }) + + it('dedupes only within the appended tag category', () => { + const tag: RouterManagedTag = { + tag: 'link', + attrs: { + href: '/style.css', + rel: 'stylesheet', + }, + } + const target: Array = [] + + appendUniqueUserTags(target, [tag, tag]) + appendUniqueUserTags(target, [tag]) + + expect(target).toEqual([tag, tag]) + }) +}) diff --git a/packages/router-core/tests/mask.test.ts b/packages/router-core/tests/mask.test.ts index 6b885d05f5..3722aa6a1b 100644 --- a/packages/router-core/tests/mask.test.ts +++ b/packages/router-core/tests/mask.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from 'vitest' import { createMemoryHistory } from '@tanstack/history' -import { BaseRootRoute, BaseRoute, RouterCore } from '../src' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' import type { RouteMask } from '../src' describe('buildLocation - route masks', () => { @@ -36,7 +37,7 @@ describe('buildLocation - route masks', () => { postsRoute.addChildren([postRoute.addChildren([infoRoute])]), ]) - const router = new RouterCore({ + const router = createTestRouter({ routeTree, history: createMemoryHistory(), routeMasks, @@ -91,6 +92,29 @@ describe('buildLocation - route masks', () => { expect(location.pathname).toBe('/photos/123/modal') }) + test('should prefer an explicit mask over a configured route mask', () => { + const routeMasks: Array> = [ + { + routeTree: null as any, + from: '/photos/$photoId/modal', + to: '/photos/$photoId', + params: () => { + throw new Error('Configured mask should not be applied') + }, + }, + ] + const router = setup(routeMasks) + + const location = router.buildLocation({ + to: '/photos/$photoId/modal', + params: { photoId: '123' }, + mask: { to: '/posts' }, + }) + + expect(location.pathname).toBe('/photos/123/modal') + expect(location.maskedLocation?.pathname).toBe('/posts') + }) + test('should set params to {} when maskParams is false', () => { const routeMasks: Array> = [ { @@ -412,7 +436,7 @@ describe('buildLocation - route masks', () => { }, ] - const router = new RouterCore({ + const router = createTestRouter({ routeTree, history: createMemoryHistory(), routeMasks, @@ -459,7 +483,7 @@ describe('buildLocation - route masks', () => { }, ] - const router = new RouterCore({ + const router = createTestRouter({ routeTree, history: createMemoryHistory(), routeMasks, @@ -509,7 +533,7 @@ describe('buildLocation - route masks', () => { }, ] - const router = new RouterCore({ + const router = createTestRouter({ routeTree, history: createMemoryHistory(), routeMasks, @@ -553,7 +577,7 @@ describe('buildLocation - route masks', () => { }, ] - const router = new RouterCore({ + const router = createTestRouter({ routeTree, history: createMemoryHistory(), routeMasks, @@ -604,7 +628,7 @@ describe('buildLocation - route masks', () => { }, ] - const router = new RouterCore({ + const router = createTestRouter({ routeTree, history: createMemoryHistory(), routeMasks, @@ -621,3 +645,201 @@ describe('buildLocation - route masks', () => { ) }) }) + +describe('buildLocation - masks and _fromLocation', () => { + test.each(['mask', 'routeMasks'] as const)( + 'the %s location builds from _fromLocation like the destination', + async (kind) => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + const photoRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/photo', + }) + const routeTree = rootRoute.addChildren([postsRoute, photoRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ + initialEntries: ['/posts?page=1#live'], + }), + routeMasks: + kind === 'routeMasks' + ? [ + { + routeTree: null as any, + from: '/photo', + to: '.', + search: true, + hash: true, + }, + ] + : undefined, + }) + await router.load() + const held = router.buildLocation({ + to: '/posts', + search: { page: 5 }, + hash: 'held', + }) + + const location = router.buildLocation({ + to: '/photo', + search: true, + mask: + kind === 'mask' ? { to: '.', search: true, hash: true } : undefined, + _fromLocation: held, + } as any) + + expect(location.href).toBe('/photo?page=5') + expect(location.maskedLocation?.href).toBe('/posts?page=5#held') + }, + ) +}) + +describe('buildLocation - masked locations and the static location cache', () => { + const setup = (routeMasks?: Array>) => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }) + const photoRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/photo', + }) + const photosRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/photos/$photoId', + }) + const routeTree = rootRoute.addChildren([ + postsRoute, + photoRoute, + photosRoute, + ]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts'] }), + routeMasks, + }) + // Two sources a Link can display, as the router builds them. + const sources = [1, 2].map((n) => + router.buildLocation({ + to: '/photos/$photoId', + params: { photoId: `${n}` }, + search: { page: n }, + hash: n === 1 ? 'one' : 'two', + state: { n } as any, + }), + ) + // Builds one options object from each source in turn, the way a Link + // rebuilds its destination when its displayed location changes. + const buildFromEachSource = (opts: Record) => + sources.map((source) => + router.buildLocation( + Object.assign(opts, { _fromLocation: source }) as any, + ), + ) + return { router, routeTree, buildFromEachSource } + } + + test('reuses the location of a fixed mask across sources', () => { + const { buildFromEachSource } = setup() + const [first, second] = buildFromEachSource({ + to: '/photo', + search: { id: 1 }, + mask: { to: '/posts', search: { from: 'photo' } }, + }) + expect(first!.maskedLocation!.href).toBe('/posts?from=photo') + expect(second).toBe(first) + }) + + test('reuses the location of a fixed route mask across sources', () => { + const { buildFromEachSource } = setup([ + { routeTree: null as any, from: '/photo', to: '/posts' }, + ]) + const [first, second] = buildFromEachSource({ to: '/photo' }) + expect(first!.maskedLocation!.href).toBe('/posts') + expect(second).toBe(first) + }) + + test.each([ + ['a relative target', { to: '.' }, ['/photos/1', '/photos/2']], + [ + 'inherited params', + { to: '/photos/$photoId' }, + ['/photos/1', '/photos/2'], + ], + [ + 'the current search', + { to: '/posts', search: true }, + ['/posts?page=1', '/posts?page=2'], + ], + [ + 'a search updater', + { to: '/posts', search: (prev: any) => ({ p: prev.page }) }, + ['/posts?p=1', '/posts?p=2'], + ], + [ + 'the current hash', + { to: '/posts', hash: true }, + ['/posts#one', '/posts#two'], + ], + ] as const)( + 'rebuilds a mask that reads %s for each source', + (_, mask, expected) => { + const { buildFromEachSource } = setup() + const locations = buildFromEachSource({ to: '/photo', mask }) + expect(locations[1]).not.toBe(locations[0]) + expect( + locations.map((location) => location.maskedLocation!.href), + ).toEqual(expected) + }, + ) + + test('rebuilds a mask that reads the current state for each source', () => { + const { buildFromEachSource } = setup() + const locations = buildFromEachSource({ + to: '/photo', + mask: { to: '/posts', state: true }, + }) + expect(locations[1]).not.toBe(locations[0]) + expect( + locations.map((location) => (location.maskedLocation!.state as any).n), + ).toEqual([1, 2]) + }) + + test('rebuilds a route mask that reads the current location for each source', () => { + const { buildFromEachSource } = setup([ + { + routeTree: null as any, + from: '/photo', + to: '/posts', + search: true, + hash: true, + }, + ]) + const locations = buildFromEachSource({ to: '/photo' }) + expect(locations[1]).not.toBe(locations[0]) + expect(locations.map((location) => location.maskedLocation!.href)).toEqual([ + '/posts?page=1#one', + '/posts?page=2#two', + ]) + }) + + test('drops a cached route mask when the router is updated', () => { + const { router, buildFromEachSource } = setup([ + { routeTree: null as any, from: '/photo', to: '/posts' }, + ]) + const opts = { to: '/photo' } + const [first] = buildFromEachSource(opts) + expect(first!.maskedLocation!.href).toBe('/posts') + + router.update({ ...router.options, routeMasks: undefined }) + const [afterUpdate] = buildFromEachSource(opts) + expect(afterUpdate).not.toBe(first) + expect(afterUpdate!.maskedLocation).toBeUndefined() + }) +}) diff --git a/packages/router-core/tests/masked-location-state-commit.test.ts b/packages/router-core/tests/masked-location-state-commit.test.ts new file mode 100644 index 0000000000..9738b42261 --- /dev/null +++ b/packages/router-core/tests/masked-location-state-commit.test.ts @@ -0,0 +1,55 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('masked location remnants in history state', () => { + test('a same-href navigation clears an expired mask from history state', async () => { + const makeRoutes = () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const realRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/real', + }) + const prettyRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/pretty', + }) + return rootRoute.addChildren([indexRoute, realRoute, prettyRoute]) + } + const history = createMemoryHistory({ initialEntries: ['/'] }) + + const router1 = createTestRouter({ + routeTree: makeRoutes(), + history, + unmaskOnReload: true, + }) + await router1.load() + await router1.navigate({ to: '/real', mask: { to: '/pretty' } }) + expect(history.location.state.__tempLocation).toBeDefined() + + // A fresh router over the same history models a page reload: the + // per-session temp key no longer matches, so the mask has expired and the + // literal URL resolves. + const router2 = createTestRouter({ + routeTree: makeRoutes(), + history, + unmaskOnReload: true, + }) + await router2.load() + expect(router2.state.location.pathname).toBe('/pretty') + + // Navigating to the same href must still commit so the expired mask + // payload is dropped from history state, matching pre-lane behavior. + await router2.navigate({ to: '/pretty' }) + expect(history.location.state.__tempLocation).toBeUndefined() + }) +}) diff --git a/packages/router-core/tests/match-by-path.test.ts b/packages/router-core/tests/match-by-path.test.ts index ad10808038..301eb846d0 100644 --- a/packages/router-core/tests/match-by-path.test.ts +++ b/packages/router-core/tests/match-by-path.test.ts @@ -1,8 +1,6 @@ import { describe, expect, it } from 'vitest' -import { - findSingleMatch, - processRouteTree, -} from '../src/new-process-route-tree' +import { findSingleMatch } from '../src/new-process-route-tree' +import { processTestRouteTree as processRouteTree } from './routerTestUtils' const { processedTree } = processRouteTree({ id: '__root__', @@ -26,7 +24,7 @@ describe('default path matching', () => { ['/b', '/a', undefined], ])('static %s %s => %s', (path, pattern, result) => { const res = findSingleMatch(pattern, true, false, path, processedTree) - expect(res?.params).toEqual(result) + expect(res?.rawParams).toEqual(result) }) it.each([ @@ -37,7 +35,7 @@ describe('default path matching', () => { ['/a/1/b/2', '/a/$id/b/$id', { id: '2' }], ])('params %s => %s', (path, pattern, result) => { const res = findSingleMatch(pattern, true, false, path, processedTree) - expect(res?.params).toEqual(result) + expect(res?.rawParams).toEqual(result) }) it('params support more than alphanumeric characters', () => { @@ -49,7 +47,7 @@ describe('default path matching', () => { '/a/@&é"\'(§è!çà)-_°^¨$*€£`ù=+:;.,?~<>|î©#0123456789\\😀}{', processedTree, ) - expect(anyValueResult?.params).toEqual({ + expect(anyValueResult?.rawParams).toEqual({ id: '@&é"\'(§è!çà)-_°^¨$*€£`ù=+:;.,?~<>|î©#0123456789\\😀}{', }) // in the key: basically everything except / and % and $ @@ -60,7 +58,7 @@ describe('default path matching', () => { '/a/1', processedTree, ) - expect(anyKeyResult?.params).toEqual({ + expect(anyKeyResult?.rawParams).toEqual({ '@&é"\'(§è!çà)-_°^¨*€£`ù=+:;.,?~<>|î©#0123456789\\😀}{': '1', }) }) @@ -77,7 +75,7 @@ describe('default path matching', () => { ['/a/1/b/2', '/a/{-$id}/b/{-$id}', { id: '2' }], ])('optional %s => %s', (path, pattern, result) => { const res = findSingleMatch(pattern, true, false, path, processedTree) - expect(res?.params).toEqual(result) + expect(res?.rawParams).toEqual(result) }) it.each([ @@ -87,7 +85,7 @@ describe('default path matching', () => { ['/a/b/c', '/a/$/foo', { _splat: 'b/c', '*': 'b/c' }], ])('wildcard %s => %s', (path, pattern, result) => { const res = findSingleMatch(pattern, true, false, path, processedTree) - expect(res?.params).toEqual(result) + expect(res?.rawParams).toEqual(result) }) }) @@ -106,7 +104,7 @@ describe('case insensitive path matching', () => { ['/', '/b', '/A', undefined], ])('static %s %s => %s', (base, path, pattern, result) => { const res = findSingleMatch(pattern, false, false, path, processedTree) - expect(res?.params).toEqual(result) + expect(res?.rawParams).toEqual(result) }) it.each([ @@ -116,7 +114,7 @@ describe('case insensitive path matching', () => { ['/a/1/b/2', '/A/$id/B/$id', { id: '2' }], ])('params %s => %s', (path, pattern, result) => { const res = findSingleMatch(pattern, false, false, path, processedTree) - expect(res?.params).toEqual(result) + expect(res?.rawParams).toEqual(result) }) it.each([ @@ -133,7 +131,7 @@ describe('case insensitive path matching', () => { ['/a/1/b/2_', '/A/{-$id}/B/{-$id}', { id: '2_' }], ])('optional %s => %s', (path, pattern, result) => { const res = findSingleMatch(pattern, false, false, path, processedTree) - expect(res?.params).toEqual(result) + expect(res?.rawParams).toEqual(result) }) it.each([ @@ -143,7 +141,7 @@ describe('case insensitive path matching', () => { ['/a/b/c', '/A/$/foo', { _splat: 'b/c', '*': 'b/c' }], ])('wildcard %s => %s', (path, pattern, result) => { const res = findSingleMatch(pattern, false, false, path, processedTree) - expect(res?.params).toEqual(result) + expect(res?.rawParams).toEqual(result) }) }) @@ -167,7 +165,7 @@ describe('fuzzy path matching', () => { ['/', '/a', '/b', undefined], ])('static %s %s => %s', (base, path, pattern, result) => { const res = findSingleMatch(pattern, true, true, path, processedTree) - expect(res?.params).toEqual(result) + expect(res?.rawParams).toEqual(result) }) it.each([ @@ -178,7 +176,7 @@ describe('fuzzy path matching', () => { ['/a/1/b/2/c', '/a/$id/b/$other', { id: '1', other: '2', '**': 'c' }], ])('params %s => %s', (path, pattern, result) => { const res = findSingleMatch(pattern, true, true, path, processedTree) - expect(res?.params).toEqual(result) + expect(res?.rawParams).toEqual(result) }) it.each([ @@ -193,7 +191,7 @@ describe('fuzzy path matching', () => { ['/a/1/b/2/c', '/a/{-$id}/b/{-$other}', { id: '1', other: '2', '**': 'c' }], ])('optional %s => %s', (path, pattern, result) => { const res = findSingleMatch(pattern, true, true, path, processedTree) - expect(res?.params).toEqual(result) + expect(res?.rawParams).toEqual(result) }) it.each([ @@ -203,6 +201,6 @@ describe('fuzzy path matching', () => { ['/a/b/c/d', '/a/$/foo', { _splat: 'b/c/d', '*': 'b/c/d' }], ])('wildcard %s => %s', (path, pattern, result) => { const res = findSingleMatch(pattern, true, true, path, processedTree) - expect(res?.params).toEqual(result) + expect(res?.rawParams).toEqual(result) }) }) diff --git a/packages/router-core/tests/match-params.test.ts b/packages/router-core/tests/match-params.test.ts new file mode 100644 index 0000000000..9b254834f9 --- /dev/null +++ b/packages/router-core/tests/match-params.test.ts @@ -0,0 +1,792 @@ +import { describe, expect, it, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { findRouteMatch } from '../src/new-process-route-tree' +import { BaseRootRoute, BaseRoute, PathParamError } from '../src' +import { + createTestRouter, + processTestRouteTree as processRouteTree, +} from './routerTestUtils' + +type TestRoute = { + id: string + fullPath: string + path?: string + isRoot?: boolean + options?: { + params?: { + parse?: (params: Record) => unknown + priority?: number + } + } + children?: Array +} + +const root = (children: Array): TestRoute => ({ + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children, +}) + +const parseWhen = (predicate: (params: Record) => boolean) => { + return (params: Record) => + predicate(params) ? params : false +} + +const integerParse = (key: string) => + parseWhen((params) => { + const value = Number(params[key]) + return Number.isInteger(value) + }) + +describe('params.parse route selection', () => { + describe('basic matching', () => { + it('matches route when params.parse returns params', () => { + const { processedTree } = processRouteTree( + root([ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: integerParse('id'), + }, + }, + }, + ]), + ) + + const result = findRouteMatch('/123', processedTree) + expect(result?.route.id).toBe('/$id') + expect(result?.rawParams).toEqual({ id: '123' }) + }) + + it('skips route when params.parse returns false and finds no alternative', () => { + const { processedTree } = processRouteTree( + root([ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: integerParse('id'), + }, + }, + }, + ]), + ) + + const result = findRouteMatch('/abc', processedTree) + expect(result).toBeNull() + }) + + it('skips route when params.parse returns false and finds an alternative', () => { + const { processedTree } = processRouteTree( + root([ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: integerParse('id'), + }, + }, + }, + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + }, + ]), + ) + + const result = findRouteMatch('/hello-world', processedTree) + expect(result?.route.id).toBe('/$slug') + expect(result?.rawParams).toEqual({ slug: 'hello-world' }) + }) + + it('does not skip route when params.parse throws', () => { + const { processedTree } = processRouteTree( + root([ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: () => { + throw 'invalid id' + }, + }, + }, + }, + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + }, + ]), + ) + + const result = findRouteMatch('/hello-world', processedTree) + expect(result?.route.id).toBe('/$id') + }) + + it('skips only false returns, not thrown params.parse errors', () => { + const parse = vi.fn(({ id }: Record) => { + if (id === 'skip') return false + if (id === 'boom') throw new Error('invalid id') + return { id } + }) + const { processedTree } = processRouteTree( + root([ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse, + }, + }, + }, + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + }, + ]), + ) + + expect(findRouteMatch('/ok', processedTree)?.route.id).toBe('/$id') + expect(findRouteMatch('/skip', processedTree)?.route.id).toBe('/$slug') + expect(findRouteMatch('/boom', processedTree)?.route.id).toBe('/$id') + }) + + it('surfaces thrown params.parse errors on the selected router match', () => { + const rootRoute = new BaseRootRoute({}) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/$id', + params: { + parse: ({ id }: { id: string }) => { + if (id === 'skip') return false + if (id === 'boom') throw new Error('invalid id') + return { id } + }, + }, + }) + const fallbackRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/$slug', + }) + const routeTree = rootRoute.addChildren([guardedRoute, fallbackRoute]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/ok'] }), + }) + + expect(router.matchRoutes('/skip', {}).at(-1)?.routeId).toBe('/$slug') + + const matches = router.matchRoutes('/boom', {}) + const match = matches.at(-1)! + expect(match.routeId).toBe('/$id') + expect(match.paramsError).toBeInstanceOf(PathParamError) + expect((match.paramsError as Error).message).toBe('invalid id') + + expect(() => + router.matchRoutes('/boom', {}, { throwOnError: true }), + ).toThrow(PathParamError) + }) + + it('calls params.parse during matching', () => { + const parse = vi.fn((params: Record) => params) + const { processedTree } = processRouteTree( + root([ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse, + }, + }, + }, + ]), + ) + + const result = findRouteMatch('/123', processedTree) + expect(result?.route.id).toBe('/$id') + expect(result?.rawParams).toEqual({ id: '123' }) + expect(parse).toHaveBeenCalledWith({ id: '123' }) + }) + }) + + describe('priority', () => { + it('params.parse routes take precedence over unguarded dynamic routes', () => { + const { processedTree } = processRouteTree( + root([ + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + }, + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: integerParse('id'), + }, + }, + }, + ]), + ) + + expect(findRouteMatch('/123', processedTree)?.route.id).toBe('/$id') + expect(findRouteMatch('/hello-world', processedTree)?.route.id).toBe( + '/$slug', + ) + }) + + it('static routes still take precedence over params.parse dynamic routes', () => { + const { processedTree } = processRouteTree( + root([ + { + id: '/settings', + fullPath: '/settings', + path: 'settings', + }, + { + id: '/$id', + fullPath: '/$id', + path: '$id', + options: { + params: { + parse: (params) => params, + priority: 999, + }, + }, + }, + ]), + ) + + expect(findRouteMatch('/settings', processedTree)?.route.id).toBe( + '/settings', + ) + }) + + it('deep params.parse routes can fall back to a sibling route', () => { + const { processedTree } = processRouteTree( + root([ + { + id: '/$a/$b/$c', + fullPath: '/$a/$b/$c', + path: '$a/$b/$c', + options: { + params: { + parse: parseWhen(({ c }) => c === 'three'), + }, + }, + }, + { + id: '/$x/$y/$z', + fullPath: '/$x/$y/$z', + path: '$x/$y/$z', + }, + ]), + ) + + expect(findRouteMatch('/one/two/three', processedTree)?.route.id).toBe( + '/$a/$b/$c', + ) + expect(findRouteMatch('/one/two/wrong', processedTree)?.route.id).toBe( + '/$x/$y/$z', + ) + }) + + it('params.priority breaks ties between params.parse routes', () => { + const { processedTree } = processRouteTree( + root([ + { + id: '/$a', + fullPath: '/$a', + path: '$a', + options: { + params: { + parse: (params) => params, + priority: -1, + }, + }, + }, + { + id: '/$z', + fullPath: '/$z', + path: '$z', + options: { + params: { + parse: (params) => params, + priority: 1, + }, + }, + }, + ]), + ) + + expect(findRouteMatch('/123', processedTree)?.route.id).toBe('/$z') + }) + + it('treats missing params.priority as 0', () => { + const priorityOneParse = vi.fn(() => false) + const defaultPriorityParse = vi.fn((params: Record) => { + return params + }) + const priorityNegativeOneParse = vi.fn( + (params: Record) => { + return params + }, + ) + + const { processedTree } = processRouteTree( + root([ + { + id: '/$default', + fullPath: '/$default', + path: '$default', + options: { + params: { + parse: defaultPriorityParse, + }, + }, + }, + { + id: '/$low', + fullPath: '/$low', + path: '$low', + options: { + params: { + parse: priorityNegativeOneParse, + priority: -1, + }, + }, + }, + { + id: '/$high', + fullPath: '/$high', + path: '$high', + options: { + params: { + parse: priorityOneParse, + priority: 1, + }, + }, + }, + ]), + ) + + expect(findRouteMatch('/123', processedTree)?.route.id).toBe('/$default') + expect(priorityOneParse).toHaveBeenCalledWith({ high: '123' }) + expect(defaultPriorityParse).toHaveBeenCalledWith({ default: '123' }) + expect(priorityNegativeOneParse).toHaveBeenCalledWith({ low: '123' }) + expect(priorityOneParse.mock.invocationCallOrder[0]!).toBeLessThan( + defaultPriorityParse.mock.invocationCallOrder[0]!, + ) + expect(defaultPriorityParse.mock.invocationCallOrder[0]!).toBeLessThan( + priorityNegativeOneParse.mock.invocationCallOrder[0]!, + ) + }) + + it('falls through to the next params.parse route by params.priority', () => { + const lowerPriorityParse = vi.fn((params: Record) => { + return params + }) + const higherPriorityParse = vi.fn(() => false) + + const { processedTree } = processRouteTree( + root([ + { + id: '/$number', + fullPath: '/$number', + path: '$number', + options: { + params: { + parse: lowerPriorityParse, + priority: 1, + }, + }, + }, + { + id: '/$uuid', + fullPath: '/$uuid', + path: '$uuid', + options: { + params: { + parse: higherPriorityParse, + priority: 10, + }, + }, + }, + ]), + ) + + expect(findRouteMatch('/42', processedTree)?.route.id).toBe('/$number') + expect(higherPriorityParse).toHaveBeenCalledWith({ uuid: '42' }) + expect(lowerPriorityParse).toHaveBeenCalledWith({ number: '42' }) + expect(higherPriorityParse.mock.invocationCallOrder[0]!).toBeLessThan( + lowerPriorityParse.mock.invocationCallOrder[0]!, + ) + }) + + it('declaration order breaks ties between params.parse routes', () => { + const routeTree = root([ + { + id: '/$a', + fullPath: '/$a', + path: '$a', + options: { + params: { + parse: (params) => params, + }, + }, + }, + { + id: '/$z', + fullPath: '/$z', + path: '$z', + options: { + params: { + parse: (params) => params, + }, + }, + }, + ]) + expect( + findRouteMatch('/123', processRouteTree(routeTree).processedTree)?.route + .id, + ).toBe('/$a') + }) + }) + + describe('regex-like match patterns', () => { + it('matches UUID values before falling back to a slug route', () => { + const uuidRegex = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + const { processedTree } = processRouteTree( + root([ + { + id: '/$uuid', + fullPath: '/$uuid', + path: '$uuid', + options: { + params: { + parse: parseWhen(({ uuid }) => uuidRegex.test(uuid!)), + }, + }, + }, + { + id: '/$slug', + fullPath: '/$slug', + path: '$slug', + }, + ]), + ) + + expect( + findRouteMatch('/550e8400-e29b-41d4-a716-446655440000', processedTree) + ?.route.id, + ).toBe('/$uuid') + expect(findRouteMatch('/my-blog-post', processedTree)?.route.id).toBe( + '/$slug', + ) + }) + + it('matches dates before falling back to a slug route', () => { + const isDate = (date: string | undefined) => { + if (!date) return false + return !Number.isNaN(new Date(date).getTime()) + } + const { processedTree } = processRouteTree( + root([ + { + id: '/posts/$date', + fullPath: '/posts/$date', + path: 'posts/$date', + options: { + params: { + parse: parseWhen(({ date }) => isDate(date)), + }, + }, + }, + { + id: '/posts/$slug', + fullPath: '/posts/$slug', + path: 'posts/$slug', + }, + ]), + ) + + const dateResult = findRouteMatch('/posts/2024-01-15', processedTree) + expect(dateResult?.route.id).toBe('/posts/$date') + expect(dateResult?.rawParams.date).toBe('2024-01-15') + expect( + findRouteMatch('/posts/my-first-post', processedTree)?.route.id, + ).toBe('/posts/$slug') + }) + }) + + describe('nested routes', () => { + it('parent params.parse failure prevents child matching', () => { + const { processedTree } = processRouteTree( + root([ + { + id: '/$orgId', + fullPath: '/$orgId', + path: '$orgId', + options: { + params: { + parse: integerParse('orgId'), + }, + }, + children: [ + { + id: '/$orgId/settings', + fullPath: '/$orgId/settings', + path: 'settings', + }, + ], + }, + { + id: '/$slug/about', + fullPath: '/$slug/about', + path: '$slug/about', + }, + ]), + ) + + expect(findRouteMatch('/123/settings', processedTree)?.route.id).toBe( + '/$orgId/settings', + ) + expect(findRouteMatch('/my-org/about', processedTree)?.route.id).toBe( + '/$slug/about', + ) + expect(findRouteMatch('/my-org/settings', processedTree)).toBeNull() + }) + + it('child params.parse failure falls back to sibling route', () => { + const { processedTree } = processRouteTree( + root([ + { + id: '/users', + fullPath: '/users', + path: 'users', + children: [ + { + id: '/users/$userId', + fullPath: '/users/$userId', + path: '$userId', + options: { + params: { + parse: integerParse('userId'), + }, + }, + }, + { + id: '/users/$username', + fullPath: '/users/$username', + path: '$username', + }, + ], + }, + ]), + ) + + const numericResult = findRouteMatch('/users/42', processedTree) + expect(numericResult?.route.id).toBe('/users/$userId') + expect(numericResult?.rawParams).toEqual({ userId: '42' }) + + const usernameResult = findRouteMatch('/users/johndoe', processedTree) + expect(usernameResult?.route.id).toBe('/users/$username') + expect(usernameResult?.rawParams).toEqual({ username: 'johndoe' }) + }) + }) + + describe('pathless routes', () => { + it('pathless layout with params.parse gates children', () => { + const { processedTree } = processRouteTree( + root([ + { + id: '/', + fullPath: '/', + path: '/', + }, + { + id: '/$foo/_layout', + fullPath: '/$foo', + path: '$foo', + options: { + params: { + parse: integerParse('foo'), + }, + }, + children: [ + { + id: '/$foo/_layout/bar', + fullPath: '/$foo/bar', + path: 'bar', + }, + { + id: '/$foo/_layout/', + fullPath: '/$foo/', + path: '/', + }, + ], + }, + { + id: '/$foo/hello', + fullPath: '/$foo/hello', + path: '$foo/hello', + }, + ]), + ) + + expect(findRouteMatch('/123/bar', processedTree)?.route.id).toBe( + '/$foo/_layout/bar', + ) + const indexResult = findRouteMatch('/123', processedTree) + expect(indexResult?.route.id).toBe('/$foo/_layout/') + expect(indexResult?.rawParams).toEqual({ foo: '123' }) + + expect(findRouteMatch('/abc/hello', processedTree)?.route.id).toBe( + '/$foo/hello', + ) + expect(findRouteMatch('/abc/bar', processedTree)).toBeNull() + }) + }) + + describe('optional params', () => { + it('optional param with static fallback', () => { + const validLangs = ['en', 'es', 'fr', 'de'] + const { processedTree } = processRouteTree( + root([ + { + id: '/{-$lang}/home', + fullPath: '/{-$lang}/home', + path: '{-$lang}/home', + options: { + params: { + parse: parseWhen( + ({ lang }) => !lang || validLangs.includes(lang), + ), + }, + }, + }, + { + id: '/home', + fullPath: '/home', + path: 'home', + }, + ]), + ) + + expect(findRouteMatch('/en/home', processedTree)?.route.id).toBe( + '/{-$lang}/home', + ) + expect(findRouteMatch('/home', processedTree)?.route.id).toBe( + '/{-$lang}/home', + ) + expect(findRouteMatch('/it/home', processedTree)).toBeNull() + }) + + it('optional param at root can match or skip the optional segment', () => { + const validLangs = ['en', 'es', 'fr', 'de'] + const { processedTree } = processRouteTree( + root([ + { + id: '/{-$lang}', + fullPath: '/{-$lang}', + path: '{-$lang}', + options: { + params: { + parse: parseWhen( + ({ lang }) => !lang || validLangs.includes(lang), + ), + }, + }, + }, + ]), + ) + + expect(findRouteMatch('/en', processedTree)?.route.id).toBe('/{-$lang}') + expect(findRouteMatch('/', processedTree)?.route.id).toBe('/{-$lang}') + expect(findRouteMatch('/about', processedTree)).toBeNull() + }) + }) + + describe('wildcard routes', () => { + it('wildcard with params.parse falls back in fuzzy mode', () => { + const { processedTree } = processRouteTree( + root([ + { + id: '/files/$', + fullPath: '/files/$', + path: 'files/$', + options: { + params: { + parse: parseWhen(({ _splat }) => !_splat!.includes('..')), + }, + }, + }, + { + id: '/files', + fullPath: '/files', + path: 'files', + }, + ]), + ) + + expect( + findRouteMatch('/files/docs/readme.txt', processedTree)?.route.id, + ).toBe('/files/$') + + const result = findRouteMatch( + '/files/../../secret/photo.jpg', + processedTree, + true, + ) + expect(result?.route.id).toBe('/files') + expect(result?.rawParams['**']).toBe('../../secret/photo.jpg') + }) + + it('index params.parse failure does not block wildcard sibling', () => { + const { processedTree } = processRouteTree( + root([ + { + id: '/a/', + fullPath: '/a/', + path: 'a/', + options: { + params: { + parse: () => false, + }, + }, + }, + { + id: '/a/$', + fullPath: '/a/$', + path: 'a/$', + }, + ]), + ) + + const result = findRouteMatch('/a', processedTree) + expect(result?.route.id).toBe('/a/$') + expect(result?.rawParams).toEqual({ '*': '', _splat: '' }) + }) + }) +}) diff --git a/packages/router-core/tests/matching-interpolation.bench.ts b/packages/router-core/tests/matching-interpolation.bench.ts new file mode 100644 index 0000000000..03fe060bfa --- /dev/null +++ b/packages/router-core/tests/matching-interpolation.bench.ts @@ -0,0 +1,121 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' +import type { AnyRoute } from '../src' + +const cases = [ + { + name: 'nested required params', + segments: ['/orgs/$org', '/items/$id'], + paths: Array.from( + { length: 32 }, + (_, id) => `/orgs/team%20one/items/item%20${id}`, + ), + }, + { + name: 'non-overlapping params', + segments: ['/items/$id'], + paths: Array.from({ length: 256 }, (_, id) => `/items/item%20${id}`), + misses: true, + }, + { + name: 'missing optional params', + segments: ['/items/{-$lang}/$id'], + paths: Array.from({ length: 32 }, (_, id) => `/items/item%20${id}`), + }, + { + name: 'present optional params', + segments: ['/items/{-$lang}/$id'], + paths: Array.from({ length: 32 }, (_, id) => `/items/en/item%20${id}`), + }, + { + name: 'affixed splats', + segments: ['/files/prefix{$}.txt'], + paths: Array.from( + { length: 32 }, + (_, id) => `/files/prefixdocs/file%20${id}.txt`, + ), + }, +] + +for (const server of [false, true]) { + for (const primeLinks of [false, true]) { + describe(`matching interpolation (server: ${server}, Link-primed: ${primeLinks})`, () => { + for (const scenario of cases) { + const root = new BaseRootRoute({}) + let parent: AnyRoute = root + for (const path of scenario.segments) { + const parentRoute = parent + const route = new BaseRoute({ + getParentRoute: () => parentRoute, + path, + }) + parent.addChildren([route]) + parent = route + } + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: root, + history, + isServer: server, + scrollRestoration: false, + }) + history.destroy() + const options = { _controller: new AbortController() } + + for (const path of scenario.paths) { + router.getMatchedRoutes(path) + } + if (primeLinks) { + const paths = scenario.misses + ? scenario.paths + .slice(0, 32) + .map((path) => path.replace('item%20', 'cached%20')) + : scenario.paths + for (const path of paths) { + const [routes, params] = router.getMatchedRoutes(path) + for (const route of routes) { + const to: string = route.fullPath + if (to.includes('$')) { + router.buildLocation({ to, params }) + } + } + } + } + + let expected = 0 + for (const path of scenario.paths) { + const matches = router.matchRoutes(path, {}, options) + expect(matches.at(-1)?.routeId).toBe(parent.id) + for (const match of matches) { + expect(match.paramsError).toBeUndefined() + expected += + match.id.length + Object.keys(match._strictParams).length + } + } + let checksum = 0 + test(scenario.name, async ({ bench }) => { + await bench( + scenario.name, + { afterAll: () => expect(checksum).toBe(expected) }, + () => { + let length = 0 + for (const path of scenario.paths) { + for (const match of router.matchRoutes(path, {}, options)) { + length += + match.id.length + Object.keys(match._strictParams).length + } + } + checksum = length + }, + ).run({ + time: 1000, + warmupTime: 300, + throws: true, + }) + }) + } + }) + } +} diff --git a/packages/router-core/tests/navigation-awaitable.test.ts b/packages/router-core/tests/navigation-awaitable.test.ts new file mode 100644 index 0000000000..1a0f165f93 --- /dev/null +++ b/packages/router-core/tests/navigation-awaitable.test.ts @@ -0,0 +1,200 @@ +import { runInNewContext } from 'node:vm' +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, notFound, redirect } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +describe.each([false, true])('awaitable hooks (server=%s)', (isServer) => { + test.each(['sync', 'promise', 'foreign promise'])( + 'inherits the result of a %s beforeLoad', + async (mode) => { + const value = { token: 'parent context' } + const root = new BaseRootRoute({ + beforeLoad: () => { + switch (mode) { + case 'promise': + return Promise.resolve(value) + case 'foreign promise': + return runInNewContext('Promise.resolve(value)', { value }) + default: + return value + } + }, + }) + const loader = vi.fn(({ context }) => context.token) + const child = new BaseRoute({ + getParentRoute: () => root, + path: '/', + loader, + }) + const router = createTestRouter({ + routeTree: root.addChildren([child]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer, + }) + if (isServer) { + expect((await loadServerResponse(router, '/')).status).toBe(200) + } else { + await router.load() + } + expect(loader).toHaveBeenCalledOnce() + expect(router.state.matches.at(-1)?.loaderData).toBe(value.token) + }, + ) +}) + +test.each(['immediate', 'microtask'] as const)( + 'a %s replacement from beforeLoad does not start its stale loader', + async (mode) => { + const root = new BaseRootRoute({}) + const loader = vi.fn() + const stale = new BaseRoute({ + getParentRoute: () => root, + path: '/stale', + beforeLoad: ({ navigate }) => { + const replace = () => { + void navigate({ to: '/current' }) + } + if (mode === 'microtask') { + queueMicrotask(replace) + } else { + replace() + } + return { stale: true } + }, + loader, + }) + const current = new BaseRoute({ + getParentRoute: () => root, + path: '/current', + }) + const router = createTestRouter({ + routeTree: root.addChildren([stale, current]), + history: createMemoryHistory({ initialEntries: ['/stale'] }), + }) + await router.load() + expect(router.state.location.pathname).toBe('/current') + expect(loader).not.toHaveBeenCalled() + }, +) + +test.each(['native', 'foreign'] as const)( + 'supersedes an unresolved %s Promise beforeLoad and observes its late rejection', + async (mode) => { + let rejectValue!: (error: Error) => void + const capture = (_resolve: unknown, reject: typeof rejectValue) => { + rejectValue = reject + } + const pending = + mode === 'native' + ? new Promise(capture) + : runInNewContext('new Promise(capture)', { capture }) + const beforeLoad = vi.fn(() => pending) + const loader = vi.fn() + const onError = vi.fn() + const root = new BaseRootRoute({}) + const stale = new BaseRoute({ + getParentRoute: () => root, + path: '/stale', + beforeLoad, + loader, + onError, + }) + const current = new BaseRoute({ + getParentRoute: () => root, + path: '/current', + }) + const router = createTestRouter({ + routeTree: root.addChildren([stale, current]), + history: createMemoryHistory({ initialEntries: ['/stale'] }), + }) + const staleLoad = router.load() + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledOnce()) + await router.navigate({ to: '/current' }) + await staleLoad + rejectValue(new Error('late failure')) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(router.state.location.pathname).toBe('/current') + expect(loader).not.toHaveBeenCalled() + expect(onError).not.toHaveBeenCalled() + }, +) + +test.each(['throw', 'reject'] as const)( + 'a normal component preload can %s a redirect', + async (mode) => { + const root = new BaseRootRoute({}) + const from = new BaseRoute({ + getParentRoute: () => root, + path: '/from', + component: Object.assign(() => null, { + preload: () => { + const result = redirect({ to: '/to' }) + if (mode === 'throw') { + throw result + } + return Promise.reject(result) + }, + }) as any, + }) + const to = new BaseRoute({ getParentRoute: () => root, path: '/to' }) + const router = createTestRouter({ + routeTree: root.addChildren([from, to]), + history: createMemoryHistory({ initialEntries: ['/from'] }), + }) + await router.load() + expect(router.state.location.pathname).toBe('/to') + expect(router.state.matches.at(-1)?.status).toBe('success') + }, +) + +test.each(['throw', 'reject'] as const)( + 'a chunk %s supports reentrant onError control flow', + async (mode) => { + for (const control of ['navigate', 'redirect', 'notFound'] as const) { + const error = new Error('chunk failed') + const root = new BaseRootRoute({}) + const onError = vi.fn(() => { + if (control === 'navigate') { + void router.navigate({ to: '/current' }) + } else if (control === 'redirect') { + throw redirect({ to: '/current' }) + } else { + throw notFound() + } + }) + const stale = new BaseRoute({ + getParentRoute: () => root, + path: '/stale', + component: Object.assign(() => null, { + preload: () => { + if (mode === 'throw') { + throw error + } + return Promise.reject(error) + }, + }) as any, + notFoundComponent: (() => null) as any, + loader: control === 'navigate' ? () => 'obsolete data' : undefined, + onError, + }) + const current = new BaseRoute({ + getParentRoute: () => root, + path: '/current', + }) + const router = createTestRouter({ + routeTree: root.addChildren([stale, current]), + history: createMemoryHistory({ initialEntries: ['/stale'] }), + }) + await router.load() + expect(onError).toHaveBeenCalledExactlyOnceWith(error) + if (control === 'notFound') { + expect(router.state.matches.at(-1)?.status).toBe('notFound') + } else { + expect(router.state.location.pathname).toBe('/current') + expect(router.state.matches.at(-1)?.status).toBe('success') + } + expect(router._flights?.size ?? 0).toBe(0) + } + }, +) diff --git a/packages/router-core/tests/navigation-burst-settle.test.ts b/packages/router-core/tests/navigation-burst-settle.test.ts new file mode 100644 index 0000000000..3ea034aa5a --- /dev/null +++ b/packages/router-core/tests/navigation-burst-settle.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * A superseded navigation resolves only once the router has settled on a + * transaction nobody replaced. A burst of same-tick navigations used to make + * every superseded waiter re-poll `router._tx` on each successor's + * completion, which was quadratic in microtask work and kept every + * superseded transaction alive until the router went idle. The waiters now + * share one memoized settle chain per transaction; this pins the observable + * contract that the chain preserves. + */ +describe('same-tick navigation burst', () => { + test('every superseded navigate() resolves after the router settles on the last one', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const itemRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, itemRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const unsubscribe = router.history.subscribe(router.load) + + try { + // Location and status observed by each navigation when it resolved. + const observed: Array<[pathname: string, status: string]> = [] + const burst = Array.from({ length: 25 }, (_, index) => + router + .navigate({ to: '/items/$id', params: { id: String(index) } }) + .then(() => { + observed.push([router.state.location.pathname, router.state.status]) + }), + ) + + await Promise.all(burst) + + expect(router.state.location.pathname).toBe('/items/24') + expect(router.state.status).toBe('idle') + // No navigation resolves before the router settled on the winner. + expect(observed).toHaveLength(25) + expect(new Set(observed.map(([pathname]) => pathname))).toEqual( + new Set(['/items/24']), + ) + expect(new Set(observed.map(([, status]) => status))).toEqual( + new Set(['idle']), + ) + expect(router.state.matches.map((m) => m.status)).toEqual([ + 'success', + 'success', + ]) + } finally { + unsubscribe() + } + }) +}) diff --git a/packages/router-core/tests/navigation-settled-cache.test.ts b/packages/router-core/tests/navigation-settled-cache.test.ts new file mode 100644 index 0000000000..b45a814349 --- /dev/null +++ b/packages/router-core/tests/navigation-settled-cache.test.ts @@ -0,0 +1,74 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('a settled loader result survives when its navigation is superseded', async () => { + const aLoader = vi.fn(() => 'a data') + let bSignal: AbortSignal | undefined + const bLoader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + bSignal = abortController.signal + return new Promise((_resolve, reject) => { + abortController.signal.addEventListener( + 'abort', + () => reject(abortController.signal), + { once: true }, + ) + }) + }, + ) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const aRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/a', + loader: aLoader, + staleTime: Infinity, + gcTime: Infinity, + }) + const bRoute = new BaseRoute({ + getParentRoute: () => aRoute, + path: '/b', + loader: bLoader, + }) + const cRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/c', + }) + const dRoute = new BaseRoute({ + getParentRoute: () => cRoute, + path: '/d', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + aRoute.addChildren([bRoute]), + cRoute.addChildren([dRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const abandoned = router.navigate({ to: '/a/b' }) + await vi.waitFor(() => { + expect(aLoader).toHaveBeenCalledOnce() + expect(bLoader).toHaveBeenCalledOnce() + }) + + await router.navigate({ to: '/c/d' }) + await abandoned + expect(bSignal?.aborted).toBe(true) + + await router.navigate({ to: '/a' }) + + expect(aLoader).toHaveBeenCalledOnce() + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: aRoute.id, + loaderData: 'a data', + }) +}) diff --git a/packages/router-core/tests/new-process-route-tree.test.ts b/packages/router-core/tests/new-process-route-tree.test.ts index 746cd47092..86a7c4e659 100644 --- a/packages/router-core/tests/new-process-route-tree.test.ts +++ b/packages/router-core/tests/new-process-route-tree.test.ts @@ -1,10 +1,10 @@ -import { describe, expect, it } from 'vitest' +import { beforeAll, describe, expect, it, vi } from 'vitest' import { findFlatMatch, findRouteMatch, processRouteMasks, - processRouteTree, } from '../src/new-process-route-tree' +import { processTestRouteTree as processRouteTree } from './routerTestUtils' import type { AnyRoute, RouteMask } from '../src' function makeTree(routes: Array) { @@ -22,6 +22,44 @@ function makeTree(routes: Array) { } describe('findRouteMatch', () => { + describe('routesByPath', () => { + it('uses exact route-template keys while matching duplicate bare aliases by insertion order', () => { + const routeTree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$id', + fullPath: '/$id', + path: '$id', + }, + { + id: '/{$id}', + fullPath: '/{$id}', + path: '{$id}', + }, + { + id: '/prefix{$id}', + fullPath: '/prefix{$id}', + path: 'prefix{$id}', + }, + ], + } + + const { processedTree, routesByPath } = processRouteTree(routeTree) + + expect(routesByPath['/$id']?.id).toBe('/$id') + expect(routesByPath['/{$id}']?.id).toBe('/{$id}') + expect(routesByPath['/prefix{$id}']?.id).toBe('/prefix{$id}') + expect(findRouteMatch('/value', processedTree)?.route.id).toBe('/$id') + expect(findRouteMatch('/prefixvalue', processedTree)?.route.id).toBe( + '/prefix{$id}', + ) + }) + }) + describe('priority', () => { describe('basic permutations priorities', () => { it('/static/static vs /static/dynamic', () => { @@ -76,6 +114,10 @@ describe('findRouteMatch', () => { const tree = makeTree(['/a/{-$b}b', '/a/{-$b}']) expect(findRouteMatch('/a/bbb', tree)?.route.id).toBe('/a/{-$b}b') }) + it('prefix+suffix optional wins when declared after plain optional', () => { + const tree = makeTree(['/a/{-$b}', '/a/b{-$b}b']) + expect(findRouteMatch('/a/bbb', tree)?.route.id).toBe('/a/b{-$b}b') + }) it('prefix+suffix wildcard wins over plain wildcard', () => { const tree = makeTree(['/a/b{$}b', '/a/$']) @@ -89,6 +131,90 @@ describe('findRouteMatch', () => { const tree = makeTree(['/a/{$}b', '/a/$']) expect(findRouteMatch('/a/bbb', tree)?.route.id).toBe('/a/{$}b') }) + it('sorts a third, more specific wildcard declared last', () => { + const tree = makeTree(['/a/$', '/a/b{$}', '/a/b{$}b']) + expect(findRouteMatch('/a/bbb', tree)?.route.id).toBe('/a/b{$}b') + }) + }) + + it('sorts parser priorities after building required, optional, and wildcard siblings', () => { + const cases = [ + ['pre{$value}suf', 'dynamic'], + ['pre{-$value}suf', 'optional'], + ['pre{$}suf', 'wildcard'], + ] as const + + for (const [segment, siblingKind] of cases) { + let acceptHigherPriority = true + const fullPath = `/a/${segment}` + const routeTree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: `low-${siblingKind}`, + fullPath, + path: fullPath.slice(1), + options: { + params: { + priority: 1, + parse: (params: Record) => params, + }, + }, + }, + { + id: `high-${siblingKind}`, + fullPath, + path: fullPath.slice(1), + options: { + params: { + priority: 2, + parse: (params: Record) => + acceptHigherPriority ? params : false, + }, + }, + }, + ], + } + const { processedTree } = processRouteTree(routeTree) + const branch = processedTree.segmentTree.staticInsensitive?.get('a') + + expect(branch?.[siblingKind]).toHaveLength(2) + expect(findRouteMatch('/a/prewinsuf', processedTree)?.route.id).toBe( + `high-${siblingKind}`, + ) + + acceptHigherPriority = false + expect( + findRouteMatch('/a/prefallbacksuf', processedTree)?.route.id, + ).toBe(`low-${siblingKind}`) + } + }) + + it('reuses optional nodes with the same shape when they have no parser', () => { + const tree = makeTree([ + '/a/{-$first}/first-child', + '/a/{-$second}/second-child', + ]) + const branch = tree.segmentTree.staticInsensitive?.get('a') + + expect(branch?.optional).toHaveLength(1) + expect(findRouteMatch('/a/value/first-child', tree)?.route.id).toBe( + '/a/{-$first}/first-child', + ) + expect(findRouteMatch('/a/value/second-child', tree)?.route.id).toBe( + '/a/{-$second}/second-child', + ) + }) + + it('keeps same-shaped wildcard aliases as separate match candidates', () => { + const tree = makeTree(['/a/$', '/a/{$}']) + const branch = tree.segmentTree.staticInsensitive?.get('a') + + expect(branch?.wildcard).toHaveLength(2) + expect(findRouteMatch('/a/value', tree)?.route.id).toBe('/a/$') }) describe('prefix / suffix lengths', () => { @@ -111,13 +237,13 @@ describe('findRouteMatch', () => { const tree = makeTree(['/{-$id}']) const res = findRouteMatch('/', tree) expect(res?.route.id).toBe('/{-$id}') - expect(res?.params).toEqual({}) + expect(res?.rawParams).toEqual({}) }) it('wildcard at the root matches /', () => { const tree = makeTree(['/$']) const res = findRouteMatch('/', tree) expect(res?.route.id).toBe('/$') - expect(res?.params).toEqual({ '*': '', _splat: '' }) + expect(res?.rawParams).toEqual({ '*': '', _splat: '' }) }) it('dynamic at the root DOES NOT match /', () => { const tree = makeTree(['/$id']) @@ -233,6 +359,64 @@ describe('findRouteMatch', () => { const treeWithIndex = makeTree(['/a/', '/a/{-$b}']) expect(findRouteMatch('/a', treeWithIndex)?.route.id).toBe('/a/') }) + it('optional+static vs static+wildcard', () => { + const tree = makeTree(['/{-$a}/b', '/a/$']) + expect(findRouteMatch('/a/b', tree)?.route.id).toBe('/a/$') + }) + it('dynamic+static vs static+wildcard', () => { + const tree = makeTree(['/$a/b', '/a/$']) + expect(findRouteMatch('/a/b', tree)?.route.id).toBe('/a/$') + }) + it('dynamic+static+static vs static+wildcard', () => { + const tree = makeTree(['/$a/b/c', '/a/$']) + expect(findRouteMatch('/a/b/c', tree)?.route.id).toBe('/a/$') + }) + it('case-insensitive static+wildcard beats optional+static', () => { + const tree = makeTree(['/{-$a}/bar', '/foo/$']) + expect(findRouteMatch('/FOO/bar', tree)?.route.id).toBe('/foo/$') + }) + it('static+optional+static vs static+static+wildcard', () => { + const tree = makeTree(['/a/{-$b}/c', '/a/b/$']) + expect(findRouteMatch('/a/b/c', tree)?.route.id).toBe('/a/b/$') + }) + it('static+optional+static vs static+static+dynamic', () => { + const tree = makeTree(['/a/{-$b}/c/d', '/a/b/c/$d']) + expect(findRouteMatch('/a/b/c/d', tree)?.route.id).toBe('/a/b/c/$d') + }) + it('static+optional+static+static beats static+dynamic+static+optional', () => { + const tree = makeTree(['/a/$b/c/{-$d}', '/a/{-$b}/c/d']) + expect(findRouteMatch('/a/b/c/d', tree)?.route.id).toBe('/a/{-$b}/c/d') + }) + it('static+dynamic+wildcard vs static+optional+static', () => { + const tree = makeTree(['/a/$b/$', '/a/{-$b}/c']) + expect(findRouteMatch('/a/b/c', tree)?.route.id).toBe('/a/{-$b}/c') + }) + it('static+dynamic+static vs static+dynamic+wildcard', () => { + const tree = makeTree(['/a/$b/c', '/a/$b/$']) + expect(findRouteMatch('/a/b/c', tree)?.route.id).toBe('/a/$b/c') + }) + it('prefix+suffix wildcard wins over prefix wildcard and plain wildcard', () => { + const tree = makeTree(['/a/foo{$}bar', '/a/foo{$}', '/a/$']) + expect(findRouteMatch('/a/fooxbar', tree)?.route.id).toBe( + '/a/foo{$}bar', + ) + }) + it('skipped optional keeps later static priority over wildcard', () => { + const tree = makeTree(['/{-$a}/b/c', '/b/$']) + expect(findRouteMatch('/b/c', tree)?.route.id).toBe('/{-$a}/b/c') + }) + it('skipped optional aligns later static priority with wildcard siblings', () => { + const tree = makeTree(['/{-$a}/b/{-$c}/d', '/b/c/$']) + expect(findRouteMatch('/b/c/d', tree)?.route.id).toBe('/b/c/$') + }) + it('optional child wins over empty wildcard at the same node', () => { + const tree = makeTree(['/a/{-$b}', '/a/$']) + expect(findRouteMatch('/a', tree)?.route.id).toBe('/a/{-$b}') + }) + it('optional+static vs static+optional', () => { + const tree = makeTree(['/{-$a}/b', '/a/{-$b}']) + expect(findRouteMatch('/a/b', tree)?.route.id).toBe('/a/{-$b}') + }) }) }) @@ -294,6 +478,63 @@ describe('findRouteMatch', () => { }) describe('case sensitivity competition', () => { + it('reuses an insensitive static node for differently cased siblings', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/Docs/API', + fullPath: '/Docs/API', + path: 'Docs/API', + }, + { + id: '/docs/guide', + fullPath: '/docs/guide', + path: 'docs/guide', + }, + ], + } + const { processedTree } = processRouteTree(tree) + const docs = processedTree.segmentTree.staticInsensitive?.get('docs') + + expect(processedTree.segmentTree.staticInsensitive?.size).toBe(1) + expect(docs?.staticInsensitive?.size).toBe(2) + expect(findRouteMatch('/DOCS/api', processedTree)?.route.id).toBe( + '/Docs/API', + ) + expect(findRouteMatch('/Docs/GUIDE', processedTree)?.route.id).toBe( + '/docs/guide', + ) + }) + it('allows a route to override a sensitive tree default', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/Strict', + fullPath: '/Strict', + path: 'Strict', + }, + { + id: '/loose', + fullPath: '/loose', + path: 'loose', + options: { caseSensitive: false }, + }, + ], + } + const { processedTree } = processRouteTree(tree, true) + + expect(findRouteMatch('/Strict', processedTree)?.route.id).toBe('/Strict') + expect(findRouteMatch('/strict', processedTree)).toBeNull() + expect(findRouteMatch('/LOOSE', processedTree)?.route.id).toBe('/loose') + }) it('a case sensitive segment early on should not prevent a case insensitive match', () => { const tree = { id: '__root__', @@ -386,6 +627,31 @@ describe('findRouteMatch', () => { '/A{$id}B', ) }) + it('case sensitivity does not distinguish plain dynamic segments', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$first', + fullPath: '/$first', + path: '$first', + options: { caseSensitive: false }, + }, + { + id: '/$second', + fullPath: '/$second', + path: '$second', + options: { caseSensitive: true }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + + expect(findRouteMatch('/value', processedTree)?.route.id).toBe('/$first') + }) }) describe('basic matching', () => { @@ -445,6 +711,22 @@ describe('findRouteMatch', () => { '/file{-$id}.txt', ) }) + it.each([ + ['/ab{$id}bc', '/abbc', { id: '' }], + ['/ab{-$id}bc', '/abbc', {}], + ['/ab{$}bc', '/abbc', { '*': '', _splat: '' }], + ['/ab{$}bc', '/abfoo/barbc', { '*': 'foo/bar', _splat: 'foo/bar' }], + ] as const)( + 'does not match overlapping affixes for %s', + (route, path, rawParams) => { + const tree = makeTree([route]) + expect(findRouteMatch('/abc', tree)).toBeNull() + expect(findRouteMatch(`${path}x`, tree)).toBeNull() + const match = findRouteMatch(path, tree) + expect(match?.route.id).toBe(route) + expect(match?.rawParams).toEqual(rawParams) + }, + ) }) it('optional at the end can still be omitted', () => { @@ -457,13 +739,16 @@ describe('findRouteMatch', () => { }) it('multiple optionals at the end -> favor earlier segments', () => { const tree = makeTree(['/a/{-$b}/{-$c}/{-$d}/{-$e}']) - expect(findRouteMatch('/a/b/c', tree)?.params).toEqual({ b: 'b', c: 'c' }) + expect(findRouteMatch('/a/b/c', tree)?.rawParams).toEqual({ + b: 'b', + c: 'c', + }) }) it('optional and wildcard at the end can still be omitted', () => { const tree = makeTree(['/a/{-$id}/$']) const result = findRouteMatch('/a', tree) expect(result?.route.id).toBe('/a/{-$id}/$') - expect(result?.params).toEqual({ '*': '', _splat: '' }) + expect(result?.rawParams).toEqual({ '*': '', _splat: '' }) }) it('multi-segment wildcard w/ prefix', () => { const tree = makeTree(['/file{$}']) @@ -473,6 +758,16 @@ describe('findRouteMatch', () => { const tree = makeTree(['/{$}/c/file']) expect(findRouteMatch('/a/b/c/file', tree)?.route.id).toBe('/{$}/c/file') }) + + it.fails('matches U+0130 wildcard suffixes case-insensitively', () => { + // U+0130 is currently the only character whose default lowercase mapping + // changes UTF-16 length, so its folded length cannot index the raw URL. + const tree = makeTree(['/{$}İ']) + expect(findRouteMatch('/valueİ', tree)?.rawParams).toEqual({ + '*': 'value', + _splat: 'value', + }) + }) it('multi-segment wildcard w/ prefix and suffix', () => { const tree = makeTree(['/file{$}end']) expect(findRouteMatch('/file/a/b/c/end', tree)?.route.id).toBe( @@ -544,7 +839,7 @@ describe('findRouteMatch', () => { const { processedTree } = processRouteTree(tree) const res = findRouteMatch('/a/b/foo', processedTree, true) expect(res?.route.id).toBe('/a/b/$') - expect(res?.params).toEqual({ _splat: 'foo', '*': 'foo' }) + expect(res?.rawParams).toEqual({ _splat: 'foo', '*': 'foo' }) }) describe('edge-case #5969: trailing empty wildcard should match', () => { it('basic', () => { @@ -636,7 +931,7 @@ describe('findRouteMatch', () => { const tree = makeTree(['/a/b/c', '/a/b', '/a']) const match = findRouteMatch('/a/b/x/y', tree, true) expect(match?.route?.id).toBe('/a/b') - expect(match?.params).toMatchInlineSnapshot(` + expect(match?.rawParams).toMatchInlineSnapshot(` { "**": "x/y", } @@ -697,7 +992,7 @@ describe('findRouteMatch', () => { true, ) expect(match?.route.id).toBe('/dashboard') - expect(match?.params).toEqual({ '**': 'foo' }) + expect(match?.rawParams).toEqual({ '**': 'foo' }) }) it('cannot use an index route as a fuzzy match', () => { @@ -718,7 +1013,7 @@ describe('findRouteMatch', () => { path: 'dashboard/', }, { - id: '/dashboard', + id: '/dashboard/invoices', fullPath: '/dashboard/invoices', path: 'invoices', }, @@ -769,10 +1064,81 @@ describe('findRouteMatch', () => { true, ) expect(match?.route.id).toBe('/dashboard') - expect(match?.params).toEqual({ '**': 'foo' }) + expect(match?.rawParams).toEqual({ '**': 'foo' }) const actualMatch = findRouteMatch('/dashboard', processed.processedTree) expect(actualMatch?.route.id).toBe('/dashboard/') }) + + it('uses an exact wildcard match instead of a fuzzy layout match', () => { + const tree = makeTree(['/a', '/a/$']) + const match = findRouteMatch('/a/b/c', tree, true) + expect(match?.route.id).toBe('/a/$') + expect(match?.rawParams).toEqual({ '*': 'b/c', _splat: 'b/c' }) + }) + + it('falls back to fuzzy layout matching when wildcard params.parse returns false', () => { + const tree = { + id: '__root__', + fullPath: '/', + path: '/', + isRoot: true, + options: {}, + children: [ + { + id: '/a', + fullPath: '/a', + path: 'a', + }, + { + id: '/a/$', + fullPath: '/a/$', + path: 'a/$', + options: { + params: { + parse: () => { + return false + }, + }, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const match = findRouteMatch('/a/b/c', processedTree, true) + expect(match?.route.id).toBe('/a') + expect(match?.rawParams).toEqual({ '**': 'b/c' }) + }) + + it('falls back to exact layout matching when empty wildcard params.parse returns false', () => { + const tree = { + id: '__root__', + fullPath: '/', + path: '/', + isRoot: true, + options: {}, + children: [ + { + id: '/a', + fullPath: '/a', + path: 'a', + }, + { + id: '/a/$', + fullPath: '/a/$', + path: 'a/$', + options: { + params: { + parse: () => { + return false + }, + }, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + expect(findRouteMatch('/a', processedTree)?.route.id).toBe('/a') + }) }) describe('param extraction', () => { @@ -797,7 +1163,7 @@ describe('findRouteMatch', () => { (char, encoded) => { const tree = makeTree([`/a/$id`]) const result = findRouteMatch(`/a/${encoded}`, tree) - expect(result?.params).toEqual({ id: char }) + expect(result?.rawParams).toEqual({ id: char }) }, ) it.each(URISyntaxCharacters)( @@ -805,7 +1171,7 @@ describe('findRouteMatch', () => { (char, encoded) => { const tree = makeTree([`/a/{-$id}`]) const result = findRouteMatch(`/a/${encoded}`, tree) - expect(result?.params).toEqual({ id: char }) + expect(result?.rawParams).toEqual({ id: char }) }, ) it.each(URISyntaxCharacters)( @@ -813,7 +1179,7 @@ describe('findRouteMatch', () => { (char, encoded) => { const tree = makeTree([`/a/$`]) const result = findRouteMatch(`/a/${encoded}`, tree) - expect(result?.params).toEqual({ '*': char, _splat: char }) + expect(result?.rawParams).toEqual({ '*': char, _splat: char }) }, ) it('wildcard splat supports multiple URI encoded characters in multiple URL segments', () => { @@ -821,14 +1187,14 @@ describe('findRouteMatch', () => { const path = URISyntaxCharacters.map(([, encoded]) => encoded).join('/') const decoded = URISyntaxCharacters.map(([char]) => char).join('/') const result = findRouteMatch(`/a/${path}`, tree) - expect(result?.params).toEqual({ '*': decoded, _splat: decoded }) + expect(result?.rawParams).toEqual({ '*': decoded, _splat: decoded }) }) it('fuzzy splat supports multiple URI encoded characters in multiple URL segments', () => { const tree = makeTree(['/a']) const path = URISyntaxCharacters.map(([, encoded]) => encoded).join('/') const decoded = URISyntaxCharacters.map(([char]) => char).join('/') const result = findRouteMatch(`/a/${path}`, tree, true) - expect(result?.params).toEqual({ '**': decoded }) + expect(result?.rawParams).toEqual({ '**': decoded }) }) }) describe('edge-cases', () => { @@ -859,28 +1225,770 @@ describe('findRouteMatch', () => { const { processedTree } = processRouteTree(tree) const result = findRouteMatch(`/sv`, processedTree) expect(result?.route.id).toBe('/_pathless/{-$language}/') - expect(result?.params).toEqual({ language: 'sv' }) + expect(result?.rawParams).toEqual({ language: 'sv' }) }) + it('skipped optional, ends with wildcard', () => { + const tree = { + id: '__root__', + fullPath: '/', + path: '/', + isRoot: true, + options: {}, + children: [ + { + id: '/{-$foo}/bar/$', + fullPath: '/{-$foo}/bar/$', + path: '{-$foo}/bar/$', + isRoot: false, + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch(`/bar/rest`, processedTree) + expect(result?.route.id).toBe('/{-$foo}/bar/$') + expect(result?.rawParams).toEqual({ '*': 'rest', _splat: 'rest' }) + }) + it('validates a stacked wildcard route once', () => { + let calls = 0 + const tree = { + id: '__root__', + fullPath: '/', + path: '/', + isRoot: true, + options: {}, + children: [ + { + id: '/a/$', + fullPath: '/a/$', + path: 'a/$', + isRoot: false, + options: { + params: { + parse: (params: Record) => { + calls++ + return params + }, + }, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/a/rest', processedTree) + expect(result?.route.id).toBe('/a/$') + expect(result?.rawParams).toEqual({ '*': 'rest', _splat: 'rest' }) + expect(calls).toBe(1) + }) + it('can fall back to a lower-priority wildcard when wildcard params.parse returns false', () => { + const tree = { + id: '__root__', + fullPath: '/', + path: '/', + isRoot: true, + options: {}, + children: [ + { + id: '/a/foo{$}', + fullPath: '/a/foo{$}', + path: 'a/foo{$}', + isRoot: false, + options: { + params: { + parse: () => { + return false + }, + }, + }, + }, + { + id: '/a/$', + fullPath: '/a/$', + path: 'a/$', + isRoot: false, + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/a/foobar', processedTree) + expect(result?.route.id).toBe('/a/$') + expect(result?.rawParams).toEqual({ '*': 'foobar', _splat: 'foobar' }) + }) + it('falls back to the next matching wildcard by priority when the best wildcard params.parse returns false', () => { + const tree = { + id: '__root__', + fullPath: '/', + path: '/', + isRoot: true, + options: {}, + children: [ + { + id: '/a/foo{$}bar', + fullPath: '/a/foo{$}bar', + path: 'a/foo{$}bar', + isRoot: false, + options: { + params: { + parse: () => { + return false + }, + }, + }, + }, + { + id: '/a/foo{$}', + fullPath: '/a/foo{$}', + path: 'a/foo{$}', + isRoot: false, + options: {}, + }, + { + id: '/a/$', + fullPath: '/a/$', + path: 'a/$', + isRoot: false, + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/a/fooxbar', processedTree) + expect(result?.route.id).toBe('/a/foo{$}') + expect(result?.rawParams).toEqual({ '*': 'xbar', _splat: 'xbar' }) + }) + it('does not validate a lower-priority wildcard after a better wildcard matches', () => { + let higherPriorityCalls = 0 + let lowerPriorityCalls = 0 + const tree = { + id: '__root__', + fullPath: '/', + path: '/', + isRoot: true, + options: {}, + children: [ + { + id: '/a/foo{$}', + fullPath: '/a/foo{$}', + path: 'a/foo{$}', + isRoot: false, + options: { + params: { + parse: (params: Record) => { + higherPriorityCalls++ + return params + }, + }, + }, + }, + { + id: '/a/$', + fullPath: '/a/$', + path: 'a/$', + isRoot: false, + options: { + params: { + parse: (params: Record) => { + lowerPriorityCalls++ + return params + }, + }, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/a/foobar', processedTree) + expect(result?.route.id).toBe('/a/foo{$}') + expect(result?.rawParams).toEqual({ '*': 'bar', _splat: 'bar' }) + expect(higherPriorityCalls).toBe(1) + expect(lowerPriorityCalls).toBe(0) + }) + it('does not validate wildcard fallback after a static sibling matches', () => { + let calls = 0 + const tree = { + id: '__root__', + fullPath: '/', + path: '/', + isRoot: true, + options: {}, + children: [ + { + id: '/a/b', + fullPath: '/a/b', + path: 'a/b', + isRoot: false, + options: {}, + }, + { + id: '/a/$', + fullPath: '/a/$', + path: 'a/$', + isRoot: false, + options: { + params: { + parse: (params: Record) => { + calls++ + return params + }, + }, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/a/b', processedTree) + expect(result?.route.id).toBe('/a/b') + expect(calls).toBe(0) + }) + it('does not validate empty wildcard fallback after an index sibling matches', () => { + let calls = 0 + const tree = { + id: '__root__', + fullPath: '/', + path: '/', + isRoot: true, + options: {}, + children: [ + { + id: '/a/', + fullPath: '/a/', + path: 'a/', + isRoot: false, + options: {}, + }, + { + id: '/a/$', + fullPath: '/a/$', + path: 'a/$', + isRoot: false, + options: { + params: { + parse: (params: Record) => { + calls++ + return params + }, + }, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/a', processedTree) + expect(result?.route.id).toBe('/a/') + expect(calls).toBe(0) + }) + it('passes wildcard raw params to params.parse', () => { + let parsedParams: Record | undefined + const tree = { + id: '__root__', + fullPath: '/', + path: '/', + isRoot: true, + options: {}, + children: [ + { + id: '/a/$', + fullPath: '/a/$', + path: 'a/$', + isRoot: false, + options: { + params: { + parse: (params: Record) => { + parsedParams = params + return { length: params._splat!.length } + }, + }, + }, + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/a/foo/bar', processedTree) + expect(result?.route.id).toBe('/a/$') + expect(result?.rawParams).toEqual({ '*': 'foo/bar', _splat: 'foo/bar' }) + expect(parsedParams).toEqual({ '*': 'foo/bar', _splat: 'foo/bar' }) + }) + }) + }) + describe('pathless routes', () => { + it('pathless nodes do not shift positional priority scores', () => { + const tree = { + id: '__root__', + fullPath: '/', + path: '/', + isRoot: true, + children: [ + { + id: '/_layout', + fullPath: '/', + children: [ + { + id: '/_layout/a/b', + fullPath: '/a/b', + path: 'a/b', + }, + ], + }, + { + id: '/a/$', + fullPath: '/a/$', + path: 'a/$', + }, + ], + } + const { processedTree } = processRouteTree(tree) + expect(findRouteMatch('/a/b', processedTree)?.route.id).toBe( + '/_layout/a/b', + ) + }) + it('uses trie depth to break equal-specificity pathless ties', () => { + const tree = { + id: '__root__', + fullPath: '/', + path: '/', + isRoot: true, + children: [ + { + id: '/a', + fullPath: '/a', + path: 'a', + }, + { + id: '/_layout', + fullPath: '/', + options: { + params: { + parse: (params: Record) => params, + }, + }, + children: [ + { + id: '/_layout/a', + fullPath: '/a', + path: 'a', + }, + ], + }, + ], + } + const { processedTree } = processRouteTree(tree) + + expect(findRouteMatch('/a', processedTree)?.route.id).toBe('/_layout/a') + }) + it('builds segment tree correctly', () => { + const tree = { + path: '/', + isRoot: true, + id: '__root__', + fullPath: '/', + children: [ + { + path: '/', + id: '/', + fullPath: '/', + options: {}, + }, + { + id: '/$foo/_layout', + path: '$foo', + fullPath: '/$foo', + options: { + params: { parse: (params: Record) => params }, + }, + children: [ + { + id: '/$foo/_layout/bar', + path: 'bar', + fullPath: '/$foo/bar', + options: {}, + }, + { + id: '/$foo/_layout/', + path: '/', + fullPath: '/$foo/', + options: {}, + }, + ], + }, + { + id: '/$foo/hello', + path: '$foo/hello', + fullPath: '/$foo/hello', + options: {}, + }, + ], + } + const { processedTree } = processRouteTree(tree) + expect(processedTree.segmentTree).toMatchInlineSnapshot(` + { + "caseSensitive": undefined, + "data": undefined, + "depth": 0, + "dynamic": [ + { + "caseSensitive": false, + "data": undefined, + "depth": 1, + "dynamic": null, + "index": null, + "kind": 1, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": [ + { + "caseSensitive": undefined, + "data": [ + [ + 1, + "foo", + "/", + "", + ], + ], + "depth": 2, + "dynamic": null, + "index": { + "caseSensitive": undefined, + "data": [ + [ + 1, + "foo", + "/", + "", + ], + ], + "depth": 3, + "dynamic": null, + "index": null, + "kind": 4, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": null, + "prefix": undefined, + "priority": 0, + "route": { + "_interpolation": [ + [ + 1, + "foo", + "/", + "", + ], + ], + "fullPath": "/$foo/", + "id": "/$foo/_layout/", + "options": {}, + "path": "/", + }, + "static": null, + "staticInsensitive": null, + "suffix": undefined, + "wildcard": null, + }, + "kind": 5, + "optional": null, + "parent": [Circular], + "parse": [Function], + "pathless": null, + "prefix": undefined, + "priority": 0, + "route": { + "_interpolation": [ + [ + 1, + "foo", + "/", + "", + ], + ], + "children": [ + { + "_interpolation": [ + [ + 1, + "foo", + "/", + "", + ], + "/bar", + ], + "fullPath": "/$foo/bar", + "id": "/$foo/_layout/bar", + "options": {}, + "path": "bar", + }, + { + "_interpolation": [ + [ + 1, + "foo", + "/", + "", + ], + ], + "fullPath": "/$foo/", + "id": "/$foo/_layout/", + "options": {}, + "path": "/", + }, + ], + "fullPath": "/$foo", + "id": "/$foo/_layout", + "options": { + "params": { + "parse": [Function], + }, + }, + "path": "$foo", + }, + "static": null, + "staticInsensitive": Map { + "bar" => { + "caseSensitive": undefined, + "data": [ + [ + 1, + "foo", + "/", + "", + ], + "/bar", + ], + "depth": 3, + "dynamic": null, + "index": null, + "kind": 0, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": null, + "prefix": undefined, + "priority": 0, + "route": { + "_interpolation": [ + [ + 1, + "foo", + "/", + "", + ], + "/bar", + ], + "fullPath": "/$foo/bar", + "id": "/$foo/_layout/bar", + "options": {}, + "path": "bar", + }, + "static": null, + "staticInsensitive": null, + "suffix": undefined, + "wildcard": null, + }, + }, + "suffix": undefined, + "wildcard": null, + }, + ], + "prefix": "", + "priority": 0, + "route": null, + "static": null, + "staticInsensitive": Map { + "hello" => { + "caseSensitive": undefined, + "data": [ + [ + 1, + "foo", + "/", + "", + ], + "/hello", + ], + "depth": 2, + "dynamic": null, + "index": null, + "kind": 0, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": null, + "prefix": undefined, + "priority": 0, + "route": { + "_interpolation": [ + [ + 1, + "foo", + "/", + "", + ], + "/hello", + ], + "fullPath": "/$foo/hello", + "id": "/$foo/hello", + "options": {}, + "path": "$foo/hello", + }, + "static": null, + "staticInsensitive": null, + "suffix": undefined, + "wildcard": null, + }, + }, + "suffix": "", + "wildcard": null, + }, + ], + "index": { + "caseSensitive": undefined, + "data": undefined, + "depth": 1, + "dynamic": null, + "index": null, + "kind": 4, + "optional": null, + "parent": [Circular], + "parse": null, + "pathless": null, + "prefix": undefined, + "priority": 0, + "route": { + "_interpolation": undefined, + "fullPath": "/", + "id": "/", + "options": {}, + "path": "/", + }, + "static": null, + "staticInsensitive": null, + "suffix": undefined, + "wildcard": null, + }, + "kind": 0, + "optional": null, + "parent": undefined, + "parse": null, + "pathless": null, + "prefix": undefined, + "priority": 0, + "route": null, + "static": null, + "staticInsensitive": null, + "suffix": undefined, + "wildcard": null, + } + `) + }) + it('does not consume a path segment during param extraction', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/$foo/_layout', + fullPath: '/$foo', + path: '$foo', + options: { + params: { + parse: (params: Record) => params, + }, + // force the creation of a pathless node + }, + children: [ + { + id: '/$foo/_layout/$bar', + fullPath: '/$foo/$bar', + path: '$bar', + options: {}, + }, + ], + }, + ], + } + const { processedTree } = processRouteTree(tree) + const result = findRouteMatch('/abc/def', processedTree) + expect(result?.route.id).toBe('/$foo/_layout/$bar') + expect(result?.rawParams).toEqual({ foo: 'abc', bar: 'def' }) + }) + it('skipped optional uses the correct node index with pathless nodes', () => { + const tree = { + id: '__root__', + isRoot: true, + fullPath: '/', + path: '/', + children: [ + { + id: '/one_{-$foo}/_layout', + fullPath: '/one_{-$foo}', + path: 'one_{-$foo}', + options: { + params: { + parse: (params: Record) => params, + }, + // force the creation of a pathless node + }, + children: [ + { + id: '/one_{-$foo}/_layout/two_{-$bar}/baz', + fullPath: '/one_{-$foo}/two_{-$bar}/baz', + path: 'two_{-$bar}/baz', + options: {}, + }, + ], + }, + ], + } + const { processedTree } = processRouteTree(tree) + // match first, skip second + { + const result = findRouteMatch('/one_value/baz', processedTree) + expect(result?.route.id).toBe('/one_{-$foo}/_layout/two_{-$bar}/baz') + expect(result?.rawParams).toEqual({ foo: 'value' }) + } + // skip first, match second + { + const result = findRouteMatch('/two_value/baz', processedTree) + expect(result?.route.id).toBe('/one_{-$foo}/_layout/two_{-$bar}/baz') + expect(result?.rawParams).toEqual({ bar: 'value' }) + } }) }) }) -describe('processRouteMasks', { sequential: true }, () => { +describe('processRouteMasks', { concurrent: false }, () => { const routeTree = { id: '__root__', isRoot: true, fullPath: '/', } as AnyRoute const { processedTree } = processRouteTree(routeTree) - it('processes a route masks list into a segment tree', () => { - const routeMasks: Array> = [ - { from: '/a/b/c', routeTree }, - { from: '/a/b/d', routeTree }, - { from: '/a/$param/d', routeTree }, - { from: '/a/{-$optional}/d', routeTree }, - { from: '/a/b/{$}.txt', routeTree }, - ] + const routeMasks: Array> = [ + { from: '/a/b/c', routeTree }, + { from: '/a/b/d', routeTree }, + { from: '/a/$param/d', routeTree }, + { from: '/a/{-$optional}/d', routeTree }, + { from: '/a/b/{$}.txt', routeTree }, + { from: '/a/$', routeTree }, + { from: '/a/foo{$}', routeTree }, + { from: '/a/foo{$}bar', routeTree }, + { from: '/required/$param', routeTree }, + { from: '/required/foo{$param}bar', routeTree }, + { from: '/optional/{-$param}', routeTree }, + { from: '/optional/foo{-$param}bar', routeTree }, + { from: '/Admin/Panel', routeTree }, + ] + + beforeAll(() => { processRouteMasks(routeMasks, processedTree) + }) + + it('processes a route masks list into a segment tree', () => { const aBranch = processedTree.masksTree?.staticInsensitive?.get('a') expect(aBranch).toBeDefined() expect(aBranch?.staticInsensitive?.get('b')).toBeDefined() @@ -891,19 +1999,73 @@ describe('processRouteMasks', { sequential: true }, () => { const res = findFlatMatch('/a/b/c', processedTree) expect(res?.route.from).toBe('/a/b/c') }) + it('caches route mask misses', () => { + const localTree = processRouteTree(routeTree).processedTree + processRouteMasks(routeMasks, localTree) + const cacheSet = vi.spyOn(localTree.flatCache!, 'set') + + expect(findFlatMatch('/missing', localTree)).toBeNull() + expect(findFlatMatch('/missing', localTree)).toBeNull() + expect(cacheSet).toHaveBeenCalledTimes(1) + cacheSet.mockRestore() + }) + it('matches uppercase static route masks case-insensitively', () => { + const res = findFlatMatch('/admin/panel', processedTree) + expect(res?.route.from).toBe('/Admin/Panel') + }) it('can match dynamic route masks w/ `findFlatMatch`', () => { const res = findFlatMatch('/a/123/d', processedTree) expect(res?.route.from).toBe('/a/$param/d') - expect(res?.params).toEqual({ param: '123' }) + expect(res?.rawParams).toEqual({ param: '123' }) }) it('can match optional route masks w/ `findFlatMatch`', () => { const res = findFlatMatch('/a/d', processedTree) expect(res?.route.from).toBe('/a/{-$optional}/d') - expect(res?.params).toEqual({}) + expect(res?.rawParams).toEqual({}) }) it('can match prefix/suffix wildcard route masks w/ `findFlatMatch`', () => { const res = findFlatMatch('/a/b/file/path.txt', processedTree) expect(res?.route.from).toBe('/a/b/{$}.txt') - expect(res?.params).toEqual({ '*': 'file/path', _splat: 'file/path' }) + expect(res?.rawParams).toEqual({ '*': 'file/path', _splat: 'file/path' }) + }) + it('sorts competing wildcard masks by specificity', () => { + const res = findFlatMatch('/a/fooxbar', processedTree) + expect(res?.route.from).toBe('/a/foo{$}bar') + expect(res?.rawParams).toEqual({ '*': 'x', _splat: 'x' }) + }) + it('sorts competing required masks by specificity', () => { + const res = findFlatMatch('/required/fooxbar', processedTree) + expect(res?.route.from).toBe('/required/foo{$param}bar') + expect(res?.rawParams).toEqual({ param: 'x' }) + }) + it('sorts competing optional masks by specificity', () => { + const res = findFlatMatch('/optional/fooxbar', processedTree) + expect(res?.route.from).toBe('/optional/foo{-$param}bar') + expect(res?.rawParams).toEqual({ param: 'x' }) + }) + it('sorts competing route masks declared least-specific first', () => { + const localTree = processRouteTree(routeTree).processedTree + processRouteMasks( + [ + { from: '/dynamic/$param', routeTree }, + { from: '/dynamic/prefix{$param}', routeTree }, + { from: '/optional/{-$param}', routeTree }, + { from: '/optional/prefix{-$param}', routeTree }, + { from: '/wildcard/$', routeTree }, + { from: '/wildcard/prefix{$}', routeTree }, + { from: '/wildcard/prefix{$}.txt', routeTree }, + ], + localTree, + ) + + expect(findFlatMatch('/dynamic/prefixvalue', localTree)?.route.from).toBe( + '/dynamic/prefix{$param}', + ) + expect(findFlatMatch('/optional/prefixvalue', localTree)?.route.from).toBe( + '/optional/prefix{-$param}', + ) + expect( + findFlatMatch('/wildcard/prefixvalue.txt', localTree)?.route.from, + ).toBe('/wildcard/prefix{$}.txt') }) }) diff --git a/packages/router-core/tests/not-found-navigation-lifecycle.test.ts b/packages/router-core/tests/not-found-navigation-lifecycle.test.ts new file mode 100644 index 0000000000..7fb50b6c89 --- /dev/null +++ b/packages/router-core/tests/not-found-navigation-lifecycle.test.ts @@ -0,0 +1,174 @@ +import { createMemoryHistory } from '@tanstack/history' +import { expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('retains the not-found owner while its hidden child loads again', async () => { + const ownerBeforeLoadStarted = createControlledPromise() + const ownerBeforeLoadGate = createControlledPromise() + const childBeforeLoadStarted = createControlledPromise() + const childBeforeLoadGate = createControlledPromise() + const layoutOnEnter = vi.fn() + const layoutOnStay = vi.fn() + const childOnEnter = vi.fn() + const childOnLeave = vi.fn() + const childOnStay = vi.fn() + let gateNextOwnerLoad = false + let gateNextChildLoad = false + const ownerBeforeLoad = vi.fn(() => { + if (gateNextOwnerLoad) { + ownerBeforeLoadStarted.resolve() + return ownerBeforeLoadGate + } + return undefined + }) + const childBeforeLoad = vi.fn(() => { + if (gateNextChildLoad) { + childBeforeLoadStarted.resolve() + return childBeforeLoadGate + } + return undefined + }) + + const rootRoute = new BaseRootRoute({ component: () => null }) + const layoutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + id: '_agents', + component: () => null, + notFoundComponent: () => null, + beforeLoad: ownerBeforeLoad, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () => null, + onEnter: layoutOnEnter, + onStay: layoutOnStay, + }) + const agentsRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '/agents', + beforeLoad: childBeforeLoad, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () => null, + component: () => null, + onEnter: childOnEnter, + onLeave: childOnLeave, + onStay: childOnStay, + }) + const history = createMemoryHistory({ + initialEntries: ['/agents'], + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([layoutRoute.addChildren([agentsRoute])]), + history, + }) + let navigation: Promise | undefined + + try { + await router.load() + await router.navigate({ to: '/agents/missing' } as any) + + expect(router.state.status).toBe('idle') + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + layoutRoute.id, + agentsRoute.id, + ]) + const sourceOwner = router.state.matches[1] + expect(sourceOwner).toMatchObject({ + routeId: layoutRoute.id, + status: 'success', + _notFound: true, + }) + expect(router.state.matches[2]).toMatchObject({ + routeId: agentsRoute.id, + status: 'success', + }) + expect(childBeforeLoad).toHaveBeenCalledTimes(1) + expect(layoutOnEnter).toHaveBeenCalledTimes(1) + expect(layoutOnStay).toHaveBeenCalledTimes(1) + expect(childOnEnter).toHaveBeenCalledTimes(1) + expect(childOnLeave).toHaveBeenCalledTimes(1) + expect(childOnStay).not.toHaveBeenCalled() + + ownerBeforeLoad.mockClear() + childBeforeLoad.mockClear() + layoutOnStay.mockClear() + childOnEnter.mockClear() + childOnLeave.mockClear() + gateNextOwnerLoad = true + gateNextChildLoad = true + navigation = router.navigate({ to: '/agents' }) + await ownerBeforeLoadStarted + + expect(router.state.status).toBe('pending') + expect(router.state.matches[1]).toMatchObject({ + id: sourceOwner?.id, + routeId: layoutRoute.id, + status: 'success', + _notFound: true, + }) + expect(childBeforeLoad).not.toHaveBeenCalled() + expect(layoutOnStay).not.toHaveBeenCalled() + expect(childOnEnter).not.toHaveBeenCalled() + expect(childOnLeave).not.toHaveBeenCalled() + expect(childOnStay).not.toHaveBeenCalled() + + ownerBeforeLoadGate.resolve() + await childBeforeLoadStarted + + await vi.waitFor(() => { + expect(router.state.matches[2]).toMatchObject({ + routeId: agentsRoute.id, + status: 'pending', + }) + }) + expect(router.state.status).toBe('pending') + expect(router.state.matches[1]).toMatchObject({ + id: sourceOwner?.id, + routeId: layoutRoute.id, + status: 'success', + }) + expect(router.state.matches[1]?._notFound).toBeFalsy() + expect(layoutOnStay).not.toHaveBeenCalled() + expect(childOnEnter).not.toHaveBeenCalled() + expect(childOnLeave).not.toHaveBeenCalled() + expect(childOnStay).not.toHaveBeenCalled() + + childBeforeLoadGate.resolve() + await navigation + + expect(router.state).toMatchObject({ + status: 'idle', + location: { pathname: '/agents' }, + resolvedLocation: { pathname: '/agents' }, + }) + expect(router.state.matches).toEqual([ + expect.objectContaining({ + routeId: rootRoute.id, + status: 'success', + }), + expect.objectContaining({ + id: sourceOwner?.id, + routeId: layoutRoute.id, + status: 'success', + }), + expect.objectContaining({ + routeId: agentsRoute.id, + status: 'success', + }), + ]) + expect(router.state.matches.some((match) => match._notFound)).toBe(false) + expect(ownerBeforeLoad).toHaveBeenCalledTimes(1) + expect(childBeforeLoad).toHaveBeenCalledTimes(1) + expect(layoutOnStay).toHaveBeenCalledTimes(1) + expect(childOnEnter).toHaveBeenCalledTimes(1) + expect(childOnLeave).not.toHaveBeenCalled() + expect(childOnStay).not.toHaveBeenCalled() + } finally { + ownerBeforeLoadGate.resolve() + childBeforeLoadGate.resolve() + await Promise.allSettled(navigation ? [navigation] : []) + history.destroy() + } +}) diff --git a/packages/router-core/tests/optional-path-params-clean.test.ts b/packages/router-core/tests/optional-path-params-clean.test.ts index d8c1411e96..36ed96f227 100644 --- a/packages/router-core/tests/optional-path-params-clean.test.ts +++ b/packages/router-core/tests/optional-path-params-clean.test.ts @@ -1,55 +1,20 @@ import { describe, expect, it } from 'vitest' import { interpolatePath } from '../src/path' +import { + parseTestPathname as parsePathname, + processTestRouteTree as processRouteTree, +} from './routerTestUtils' import { SEGMENT_TYPE_OPTIONAL_PARAM, SEGMENT_TYPE_PATHNAME, + SEGMENT_TYPE_WILDCARD, findSingleMatch, - parseSegment, - processRouteTree, + parseSegments, } from '../src/new-process-route-tree' -import type { SegmentKind } from '../src/new-process-route-tree' describe('Optional Path Parameters - Clean Comprehensive Tests', () => { describe('Optional Dynamic Parameters {-$param}', () => { describe('parsePathname', () => { - type PathSegment = { - type: SegmentKind - value: string - prefixSegment?: string - suffixSegment?: string - // Indicates if there is a static segment after this required/optional param - hasStaticAfter?: boolean - } - - const parsePathname = (to: string | undefined) => { - let cursor = 0 - let data - const path = to ?? '' - const segments: Array = [] - while (cursor < path.length) { - const start = cursor - data = parseSegment(path, start, data) - const end = data[5] - cursor = end + 1 - const type = data[0] - const value = path.substring(data[2], data[3]) - const prefix = path.substring(start, data[1]) - const suffix = path.substring(data[4], end) - const segment: PathSegment = { - type, - value, - } - if (prefix) { - segment.prefixSegment = prefix - } - if (suffix) { - segment.suffixSegment = suffix - } - segments.push(segment) - } - return segments - } - it('should parse single optional dynamic param', () => { const result = parsePathname('/posts/{-$category}') expect(result).toEqual([ @@ -87,53 +52,40 @@ describe('Optional Path Parameters - Clean Comprehensive Tests', () => { describe('interpolatePath', () => { it('should interpolate optional dynamic params when present', () => { - const result = interpolatePath({ - path: '/posts/{-$category}', - params: { category: 'tech' }, - }) - expect(result.interpolatedPath).toBe('/posts/tech') + const path = '/posts/{-$category}' + const segments = parseSegments(false, { fullPath: path }, 0) + expect(interpolatePath(path, segments, { category: 'tech' })).toBe( + '/posts/tech', + ) }) it('should omit optional dynamic params when missing', () => { - const result = interpolatePath({ - path: '/posts/{-$category}', - params: {}, - }) - expect(result.interpolatedPath).toBe('/posts') + const path = '/posts/{-$category}' + const segments = parseSegments(false, { fullPath: path }, 0) + expect(interpolatePath(path, segments, {})).toBe('/posts') }) it('should handle multiple optional dynamic params', () => { - const result1 = interpolatePath({ - path: '/posts/{-$category}/{-$slug}', - params: { category: 'tech', slug: 'hello' }, - }) - expect(result1.interpolatedPath).toBe('/posts/tech/hello') - - const result2 = interpolatePath({ - path: '/posts/{-$category}/{-$slug}', - params: { category: 'tech' }, - }) - expect(result2.interpolatedPath).toBe('/posts/tech') - - const result3 = interpolatePath({ - path: '/posts/{-$category}/{-$slug}', - params: {}, - }) - expect(result3.interpolatedPath).toBe('/posts') + const path = '/posts/{-$category}/{-$slug}' + const segments = parseSegments(false, { fullPath: path }, 0) + expect( + interpolatePath(path, segments, { category: 'tech', slug: 'hello' }), + ).toBe('/posts/tech/hello') + expect(interpolatePath(path, segments, { category: 'tech' })).toBe( + '/posts/tech', + ) + expect(interpolatePath(path, segments, {})).toBe('/posts') }) it('should handle mixed required and optional dynamic params', () => { - const result = interpolatePath({ - path: '/posts/{-$category}/user/$id', - params: { category: 'tech', id: '123' }, - }) - expect(result.interpolatedPath).toBe('/posts/tech/user/123') - - const result2 = interpolatePath({ - path: '/posts/{-$category}/user/$id', - params: { id: '123' }, - }) - expect(result2.interpolatedPath).toBe('/posts/user/123') + const path = '/posts/{-$category}/user/$id' + const segments = parseSegments(false, { fullPath: path }, 0) + expect( + interpolatePath(path, segments, { category: 'tech', id: '123' }), + ).toBe('/posts/tech/user/123') + expect(interpolatePath(path, segments, { id: '123' })).toBe( + '/posts/user/123', + ) }) }) @@ -155,7 +107,7 @@ describe('Optional Path Parameters - Clean Comprehensive Tests', () => { from, processedTree, ) - const result = match ? match.params : undefined + const result = match ? match.rawParams : undefined if (options.to && !result) return return result ?? {} } @@ -206,44 +158,46 @@ describe('Optional Path Parameters - Clean Comprehensive Tests', () => { describe('Edge Cases', () => { it('should handle optional params with wildcards', () => { - const result = interpolatePath({ - path: '/docs/{-$version}/$', - params: { version: 'v1', _splat: 'guide/intro' }, - }) - expect(result.interpolatedPath).toBe('/docs/v1/guide/intro') - - const result2 = interpolatePath({ - path: '/docs/{-$version}/$', - params: { _splat: 'guide/intro' }, - }) - expect(result2.interpolatedPath).toBe('/docs/guide/intro') + const path = '/docs/{-$version}/$' + const segments = parseSegments(false, { fullPath: path }, 0) + expect( + interpolatePath(path, segments, { + version: 'v1', + _splat: 'guide/intro', + }), + ).toBe('/docs/v1/guide/intro') + expect(interpolatePath(path, segments, { _splat: 'guide/intro' })).toBe( + '/docs/guide/intro', + ) }) it('should work with complex patterns', () => { const pattern = '/app/{-$env}/api/{-$version}/users/$id/{-$tab}' + const segments = parseSegments(false, { fullPath: pattern }, 0) // All params provided - const result1 = interpolatePath({ - path: pattern, - params: { env: 'prod', version: 'v2', id: '123', tab: 'settings' }, - }) - expect(result1.interpolatedPath).toBe( - '/app/prod/api/v2/users/123/settings', - ) + expect( + interpolatePath(pattern, segments, { + env: 'prod', + version: 'v2', + id: '123', + tab: 'settings', + }), + ).toBe('/app/prod/api/v2/users/123/settings') // Only required param - const result2 = interpolatePath({ - path: pattern, - params: { id: '123' }, - }) - expect(result2.interpolatedPath).toBe('/app/api/users/123') + expect(interpolatePath(pattern, segments, { id: '123' })).toBe( + '/app/api/users/123', + ) // Mix of optional and required - const result3 = interpolatePath({ - path: pattern, - params: { env: 'dev', id: '456', tab: 'profile' }, - }) - expect(result3.interpolatedPath).toBe('/app/dev/api/users/456/profile') + expect( + interpolatePath(pattern, segments, { + env: 'dev', + id: '456', + tab: 'profile', + }), + ).toBe('/app/dev/api/users/456/profile') }) }) }) diff --git a/packages/router-core/tests/optional-path-params.test.ts b/packages/router-core/tests/optional-path-params.test.ts index 304e9aebc0..4d3c2ee76e 100644 --- a/packages/router-core/tests/optional-path-params.test.ts +++ b/packages/router-core/tests/optional-path-params.test.ts @@ -1,13 +1,16 @@ import { describe, expect, it } from 'vitest' import { interpolatePath } from '../src/path' +import { + parseTestPathname as parsePathname, + processTestRouteTree as processRouteTree, +} from './routerTestUtils' import { SEGMENT_TYPE_OPTIONAL_PARAM, SEGMENT_TYPE_PARAM, SEGMENT_TYPE_PATHNAME, SEGMENT_TYPE_WILDCARD, findSingleMatch, - parseSegment, - processRouteTree, + parseSegments, } from '../src/new-process-route-tree' import type { SegmentKind } from '../src/new-process-route-tree' @@ -25,34 +28,6 @@ describe('Optional Path Parameters', () => { }> describe('parsePathname with optional params', () => { - const parsePathname = (to: string | undefined) => { - let cursor = 0 - let data - const path = to ?? '' - const segments: Array = [] - while (cursor < path.length) { - const start = cursor - data = parseSegment(path, start, data) - const end = data[5] - cursor = end + 1 - const type = data[0] - const value = path.substring(data[2], data[3]) - const prefix = path.substring(start, data[1]) - const suffix = path.substring(data[4], end) - const segment: PathSegment = { - type, - value, - } - if (prefix) { - segment.prefixSegment = prefix - } - if (suffix) { - segment.suffixSegment = suffix - } - segments.push(segment) - } - return segments - } it.each([ { name: 'regular optional param', @@ -169,6 +144,30 @@ describe('Optional Path Parameters', () => { { type: SEGMENT_TYPE_OPTIONAL_PARAM, value: 'day' }, ], }, + { + name: 'unclosed optional param is static', + to: '/{-$slug', + expected: [ + { type: SEGMENT_TYPE_PATHNAME, value: '' }, + { type: SEGMENT_TYPE_PATHNAME, value: '{-$slug' }, + ], + }, + { + name: 'empty optional param is static', + to: '/{-$}', + expected: [ + { type: SEGMENT_TYPE_PATHNAME, value: '' }, + { type: SEGMENT_TYPE_PATHNAME, value: '{-$}' }, + ], + }, + { + name: 'unmatched closing brace is static', + to: '/foo}bar$', + expected: [ + { type: SEGMENT_TYPE_PATHNAME, value: '' }, + { type: SEGMENT_TYPE_PATHNAME, value: 'foo}bar$' }, + ], + }, ] satisfies ParsePathnameTestScheme)('$name', ({ to, expected }) => { const result = parsePathname(to) expect(result).toEqual(expected) @@ -345,7 +344,8 @@ describe('Optional Path Parameters', () => { result: '/posts/42', }, ])('$name', ({ path, params, result }) => { - expect(interpolatePath({ path, params }).interpolatedPath).toBe(result) + const segments = parseSegments(false, { fullPath: path }, 0) + expect(interpolatePath(path, segments, params)).toBe(result) }) }) @@ -366,7 +366,7 @@ describe('Optional Path Parameters', () => { from, processedTree, ) - const result = match ? match.params : undefined + const result = match ? match.rawParams : undefined if (options.to && !result) return return result ?? {} } @@ -465,7 +465,7 @@ describe('Optional Path Parameters', () => { }, ])('$name', ({ input, matchingOptions, expectedMatchedParams }) => { expect(matchPathname(input, matchingOptions)).toStrictEqual( - expectedMatchedParams, + toNullObj(expectedMatchedParams), ) }) }) @@ -474,10 +474,9 @@ describe('Optional Path Parameters', () => { it('should handle optional parameters with validation', () => { // This test will be expanded when we implement params.parse for optional params const path = '/posts/{-$category}' + const segments = parseSegments(false, { fullPath: path }, 0) const params = { category: 'tech' } - expect(interpolatePath({ path, params }).interpolatedPath).toBe( - '/posts/tech', - ) + expect(interpolatePath(path, segments, params)).toBe('/posts/tech') }) it('should handle multiple consecutive optional parameters correctly', () => { @@ -527,3 +526,8 @@ describe('Optional Path Parameters', () => { }) }) }) + +function toNullObj(obj: T): T { + if (typeof obj === 'object') return Object.assign(Object.create(null), obj) + return obj +} diff --git a/packages/router-core/tests/original-param-names.test.ts b/packages/router-core/tests/original-param-names.test.ts new file mode 100644 index 0000000000..aca4c61ae4 --- /dev/null +++ b/packages/router-core/tests/original-param-names.test.ts @@ -0,0 +1,143 @@ +import { expect, test } from 'vitest' +import { + findFlatMatch, + findRouteMatch, + findSingleMatch, + processRouteMasks, +} from '../src/new-process-route-tree' +import { processTestRouteTree as processRouteTree } from './routerTestUtils' + +test('keeps original names when different templates share a trie prefix', () => { + const tree = processRouteTree({ + id: '__root__', + isRoot: true, + fullPath: '/', + children: [ + { id: '/$id/first', path: '$id/first', fullPath: '/$id/first' }, + { + id: '/{$name}/second', + path: '{$name}/second', + fullPath: '/{$name}/second', + }, + ], + }).processedTree + expect(findRouteMatch('/one/first', tree)?.rawParams).toEqual({ id: 'one' }) + expect(findRouteMatch('/two/second', tree)?.rawParams).toEqual({ + name: 'two', + }) +}) + +test("keeps a terminal route's names when a later alias adds a parser", () => { + const tree = processRouteTree({ + id: '__root__', + isRoot: true, + fullPath: '/', + children: [ + { id: '/$id/detail', path: '$id/detail', fullPath: '/$id/detail' }, + { + id: '/$name', + path: '$name', + fullPath: '/$name', + children: [ + { + id: '/$name/detail', + path: 'detail', + fullPath: '/$name/detail', + options: { + params: { parse: (params: Record) => params }, + }, + }, + ], + }, + ], + }).processedTree + const match = findRouteMatch('/abc/detail', tree) + expect(match?.route.id).toBe('/$id/detail') + expect(match?.rawParams).toEqual({ id: 'abc' }) +}) + +test('resumes through a route-less parse gate with skipped optional names', () => { + const seen: Array> = [] + const tree = processRouteTree({ + id: '__root__', + isRoot: true, + fullPath: '/', + children: [ + { + id: '/$id', + path: '$id', + fullPath: '/$id', + children: [ + { + id: '/$id/_layout', + fullPath: '/$id', + options: { + params: { + parse: (params: Record) => { + seen.push({ ...params }) + }, + }, + }, + children: [ + { + id: '/$id/_layout/{-$lang}/$slug', + path: '{-$lang}/$slug', + fullPath: '/$id/{-$lang}/$slug', + }, + ], + }, + ], + }, + ], + }).processedTree + expect(findRouteMatch('/one/post', tree)?.rawParams).toEqual({ + id: 'one', + slug: 'post', + }) + expect(findRouteMatch('/two/en/post', tree)?.rawParams).toEqual({ + id: 'two', + lang: 'en', + slug: 'post', + }) + expect(seen).toEqual([{ id: 'one' }, { id: 'two' }]) +}) + +test('retains nested mask branches without modifying their definitions', () => { + const tree = processRouteTree({ + id: '__root__', + fullPath: '/', + isRoot: true, + }).processedTree + const child = Object.freeze({ from: '/$id/detail' }) + const mask = Object.freeze({ from: '/$id', children: [child] }) + processRouteMasks([mask], tree) + const match = findFlatMatch('/one/detail', tree) + expect(match?.route).toBe(child) + expect(match?.rawParams).toEqual({ id: 'one' }) + expect(Object.keys(mask)).toEqual(['from', 'children']) + expect(Object.keys(child)).toEqual(['from']) +}) + +test('retains mask and single-match names without modifying frozen definitions', () => { + const tree = processRouteTree({ + id: '__root__', + isRoot: true, + fullPath: '/', + }).processedTree + const mask = Object.freeze({ from: '/pre{$code}/file' }) + processRouteMasks([mask], tree) + expect(findFlatMatch('/prea%20b/file', tree)?.rawParams).toEqual({ + code: 'a b', + }) + + expect(Object.keys(mask)).toEqual(['from']) + expect( + findSingleMatch( + '/{$first}/{-$middle}/$last', + false, + false, + '/one/two', + tree, + )?.rawParams, + ).toEqual({ first: 'one', last: 'two' }) +}) diff --git a/packages/router-core/tests/parent-match-promise.test.ts b/packages/router-core/tests/parent-match-promise.test.ts new file mode 100644 index 0000000000..5513067027 --- /dev/null +++ b/packages/router-core/tests/parent-match-promise.test.ts @@ -0,0 +1,121 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +test.each([false, true])( + 'parentMatchPromise exposes successful parent state during loading with isServer=%s', + async (isServer) => { + const seen: Array = [] + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => 'parent data', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async ({ parentMatchPromise }) => { + seen.push(await parentMatchPromise) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer, + }) + + await router.load() + + expect(seen).toHaveLength(1) + expect(seen[0]).toMatchObject({ + routeId: parentRoute.id, + loaderData: 'parent data', + status: 'success', + invalid: false, + preload: false, + isFetching: false, + }) + }, +) + +test('client preload=false parentMatchPromise exposes the skipped pending parent', async () => { + const seen: Array = [] + const parentLoader = vi.fn() + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + preload: false, + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async ({ parentMatchPromise }) => { + seen.push(await parentMatchPromise) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: false, + }) + + await router.preloadRoute({ to: '/parent/child' }) + + expect(parentLoader).not.toHaveBeenCalled() + expect(seen).toHaveLength(1) + expect(seen[0]).toMatchObject({ + routeId: parentRoute.id, + status: 'pending', + invalid: false, + preload: false, + isFetching: false, + }) +}) + +test('server parentMatchPromise exposes the error selected by onError', async () => { + const original = new Error('original') + const selected = new Error('selected') + let seen: unknown + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw original + }, + onError: () => { + throw selected + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async ({ parentMatchPromise }) => { + seen = await parentMatchPromise + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + + await router.load() + + expect(seen).toMatchObject({ + routeId: parentRoute.id, + status: 'error', + error: selected, + }) +}) diff --git a/packages/router-core/tests/parse-segment.test.ts b/packages/router-core/tests/parse-segment.test.ts new file mode 100644 index 0000000000..4b160f4644 --- /dev/null +++ b/packages/router-core/tests/parse-segment.test.ts @@ -0,0 +1,52 @@ +import { expect, test } from 'vitest' +import { + SEGMENT_TYPE_OPTIONAL_PARAM, + SEGMENT_TYPE_PARAM, + SEGMENT_TYPE_PATHNAME, + SEGMENT_TYPE_WILDCARD, + parseSegment, +} from '../src/new-process-route-tree' + +test('keeps offsets beyond the former 16-bit scratch buffer range', () => { + const path = `/${'x'.repeat(70_000)}/$id` + const literal = parseSegment(path, 1, 70_001) + expect(typeof literal).toBe('string') + expect(literal.length).toBe(70_000) + expect(parseSegment(path, 70_002, path.length)).toEqual([ + SEGMENT_TYPE_PARAM, + 'id', + '', + '', + ]) +}) + +test.each([ + [SEGMENT_TYPE_PATHNAME, 'pre{bad}{$id}', '', 'pre{bad}{$id}', ''], + [SEGMENT_TYPE_PATHNAME, '{-$}', '', '{-$}', ''], + [SEGMENT_TYPE_PATHNAME, '{--$id}', '', '{--$id}', ''], + [SEGMENT_TYPE_PARAM, '}pre{$a{b}.txt', '}pre', 'a{b', '.txt'], + [SEGMENT_TYPE_PARAM, '$id{suffix}', '', 'id{suffix}', ''], + [SEGMENT_TYPE_PARAM, '{$$}', '', '$', ''], + [SEGMENT_TYPE_OPTIONAL_PARAM, 'pre{-$a$b}suffix', 'pre', 'a$b', 'suffix'], + [SEGMENT_TYPE_WILDCARD, 'pre{$}suffix/tail', 'pre', '_splat', 'suffix/tail'], + [SEGMENT_TYPE_WILDCARD, '$/tail', '', '_splat', ''], +] as const)( + 'preserves the first segment grammar for %s: %s', + (kind, source, prefix, value, suffix) => { + const path = `/base/${source}` + const next = path.indexOf('/', 6) + const parsed = parseSegment(path, 6, next === -1 ? path.length : next) + expect( + typeof parsed === 'string' ? SEGMENT_TYPE_PATHNAME : parsed[0 /* kind */], + ).toBe(kind) + expect(typeof parsed === 'string' ? '' : parsed[2 /* prefix */]).toBe( + prefix, + ) + expect(typeof parsed === 'string' ? parsed : parsed[1 /* key */]).toBe( + value, + ) + expect( + typeof parsed === 'string' ? '' : (parsed[3 /* suffix */] ?? ''), + ).toBe(suffix) + }, +) diff --git a/packages/router-core/tests/path-decoder.bench.ts b/packages/router-core/tests/path-decoder.bench.ts new file mode 100644 index 0000000000..4c56a8aa76 --- /dev/null +++ b/packages/router-core/tests/path-decoder.bench.ts @@ -0,0 +1,66 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +describe.each(['stable', 'new-router', 'no-update'] as const)( + 'path decoder: %s configuration', + (mode) => { + const makeRouter = (allowed: ReadonlyArray<'@' | '+'>) => { + const root = new BaseRootRoute({}) + const item = new BaseRoute({ + getParentRoute: () => root, + path: '/items/$id', + }) + const router = createTestRouter({ + routeTree: root.addChildren([item]), + history: createMemoryHistory({ initialEntries: ['/'] }), + pathParamsAllowedCharacters: allowed, + scrollRestoration: false, + }) + router.history.destroy() + return router + } + let router = makeRouter(['@']) + const inputs = Array.from({ length: 200 }, (_, index) => ({ + to: '/items/$id', + params: { id: `item-${index % 40}@+` }, + })) + let count = 0 + let lastHref = '' + const run = () => { + count++ + if (mode === 'new-router') { + router = makeRouter(count % 2 === 0 ? ['+'] : ['@']) + } else if (mode === 'stable') { + router.update({ + ...router.options, + context: { count }, + }) + } + for (const input of inputs) { + lastHref = router.buildLocation(input).href + } + } + const verify = () => { + expect(lastHref).toBe( + mode === 'new-router' && count % 2 === 0 + ? '/items/item-39%40+' + : '/items/item-39@%2B', + ) + } + run() + verify() + test('update and build 200 locations', async ({ bench }) => { + await bench( + 'update and build 200 locations', + { afterAll: verify }, + run, + ).run({ + time: 1500, + warmupTime: 500, + throws: true, + }) + }) + }, +) diff --git a/packages/router-core/tests/path-decoder.test.ts b/packages/router-core/tests/path-decoder.test.ts new file mode 100644 index 0000000000..bf27b93134 --- /dev/null +++ b/packages/router-core/tests/path-decoder.test.ts @@ -0,0 +1,92 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import * as pathUtils from '../src/path' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => vi.restoreAllMocks()) + +test.each([ + { allowed: ['.', '@'], input: 'x%40.y', expected: 'x@.y' }, + { allowed: ['*', '@'], input: 'pre%40*post', expected: 'pre@*post' }, + { allowed: ['(', ')', '@'], input: '(%40)', expected: '(@)' }, + { allowed: ['|', '@'], input: '%7C%40%2F', expected: '|@%2F' }, + { allowed: ['12@', '1'], input: '12%40', expected: '12@' }, + { allowed: ['%', '/'], input: '%252F/%2F', expected: '%2F//' }, + { allowed: ['@', '@', '+'], input: '%40%2B', expected: '@+' }, + { allowed: [], input: '%40', expected: '%40' }, +])( + 'compiles literal decoder alternatives: $allowed', + ({ allowed, input, expected }) => { + expect(pathUtils.compileDecodeCharMap(allowed)(input)).toBe(expected) + }, +) + +function setup(allowed?: Array<'@' | '+'>) { + const root = new BaseRootRoute({}) + const item = new BaseRoute({ getParentRoute: () => root, path: '/items/$id' }) + const router = createTestRouter({ + routeTree: root.addChildren([item]), + history: createMemoryHistory({ initialEntries: ['/'] }), + pathParamsAllowedCharacters: allowed, + scrollRestoration: false, + }) + router.history.destroy() + const build = () => + router.buildLocation({ to: '/items/$id', params: { id: '@+' } }).href + return { router, build } +} + +test('keeps the decoder across provider option updates', () => { + const allowed: Array<'@' | '+'> = ['@'] + const { router, build } = setup(allowed) + const decoder = router.pathParamsDecoder + expect(build()).toBe('/items/@%2B') + const compile = vi.spyOn(pathUtils, 'compileDecodeCharMap') + for (let count = 0; count < 3; count++) { + router.update({ + ...router.options, + context: { count }, + }) + expect(build()).toBe('/items/@%2B') + expect(router.pathParamsDecoder).toBe(decoder) + } + expect(compile).not.toHaveBeenCalled() +}) + +test('requires a new router to apply changes to the original character array', () => { + const allowed: Array<'@' | '+'> = ['@'] + const { router, build } = setup(allowed) + const decoder = router.pathParamsDecoder + expect(build()).toBe('/items/@%2B') + allowed[0] = '+' + router.update({ context: {} }) + expect(router.pathParamsDecoder).toBe(decoder) + expect(build()).toBe('/items/@%2B') + expect( + router.buildLocation({ to: '/items/$id', params: { id: 'new@+' } }).href, + ).toBe('/items/new@%2B') + expect(setup(allowed).build()).toBe('/items/%40+') +}) + +test('does not change encoding through unsupported option updates', () => { + const { router, build } = setup(['@']) + const compile = vi.spyOn(pathUtils, 'compileDecodeCharMap') + expect(build()).toBe('/items/@%2B') + // @ts-expect-error Path encoding can only be configured at construction. + router.update({ pathParamsAllowedCharacters: undefined }) + expect( + router.buildLocation({ to: '/items/$id', params: { id: 'new@+' } }).href, + ).toBe('/items/new@%2B') + expect(compile).not.toHaveBeenCalled() +}) + +test('does not create a decoder for empty or omitted allowed characters', () => { + const compile = vi.spyOn(pathUtils, 'compileDecodeCharMap') + for (const allowed of [undefined, []]) { + const { router, build } = setup(allowed) + expect(router.pathParamsDecoder).toBeUndefined() + expect(build()).toBe('/items/%40%2B') + } + expect(compile).not.toHaveBeenCalled() +}) diff --git a/packages/router-core/tests/path-interpolation.bench.ts b/packages/router-core/tests/path-interpolation.bench.ts new file mode 100644 index 0000000000..80d3478594 --- /dev/null +++ b/packages/router-core/tests/path-interpolation.bench.ts @@ -0,0 +1,290 @@ +import { describe, expect, test } from 'vitest' +import { + createMemoryHistory, + normalizeProtocolRelative, +} from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { compileDecodeCharMap, interpolatePath } from '../src/path' +import { parseSegments } from '../src/new-process-route-tree' +import { decodePath } from '../src/utils' +import { createTestRouter } from './routerTestUtils' +import type { AnyRoute } from '../src' +import type { PathInterpolationTestOptions } from './routerTestUtils' + +const scenarios: Array<{ + name: string + inputs: Array + register?: boolean +}> = [ + { + name: 'single-param shared hits', + inputs: Array.from({ length: 200 }, (_, index) => ({ + path: '/items/$id', + params: { id: `item ${Math.floor(index / 5)}`, unrelated: index }, + })), + }, + { + name: 'multi-param shared hits', + inputs: Array.from({ length: 200 }, (_, index) => ({ + path: '/orgs/$orgId/items/$id', + params: { + orgId: `org:${Math.floor(index / 5) % 4}`, + id: `item/${Math.floor(index / 5)}`, + }, + })), + }, + { + name: 'result eviction', + inputs: Array.from({ length: 256 }, (_, index) => ({ + path: '/items/$id', + params: { id: `item ${index}` }, + })), + }, + { + name: '64-template working set', + inputs: Array.from({ length: 64 }, (_, index) => ({ + path: `/section-${index}/$id`, + params: { id: 'item one' }, + })), + }, + { + name: '256-template working set', + inputs: Array.from({ length: 256 }, (_, index) => ({ + path: `/section-${index}/$id`, + params: { id: 'item one' }, + })), + }, + { + name: 'unregistered template eviction', + register: false, + inputs: Array.from({ length: 64 }, (_, index) => ({ + path: `/section-${index}/$id`, + params: { id: 'item one' }, + })), + }, + { + name: 'mixed optional and splat params', + inputs: Array.from({ length: 200 }, (_, index) => { + switch (index % 5) { + case 0: + return { path: '/posts/{-$category}', params: {} } + case 1: + return { + path: '/posts/{-$category}', + params: { category: `news-${index % 10}` }, + } + case 2: + return { path: '/users/$id', params: { id: index } } + case 3: + return { path: '/files/$', params: { _splat: `docs/${index % 20}` } } + default: + return { path: '/about', params: {} } + } + }), + }, + { + name: 'missing required and splat params', + inputs: Array.from({ length: 200 }, (_, index) => { + switch (index % 5) { + case 0: + return { path: '/$first/$second', params: { second: 'two' } } + case 1: + return { + path: '/$first/$second', + params: { first: undefined, second: 'two' }, + } + case 2: + return { path: '/$first/{-$second}', params: {} } + case 3: + return { path: '/files/$', params: {} } + default: + return { path: '/files/prefix{$}suffix', params: { _splat: '' } } + } + }), + }, + { + name: 'affixed mixed segments', + inputs: Array.from({ length: 200 }, (_, index) => ({ + path: '/root/prefix{$id}suffix/{-$language}/files/{$}.txt', + params: { + id: `item ${index % 40}`, + language: index % 2 ? 'en' : undefined, + _splat: index % 3 ? `docs/file ${index % 20}` : '', + }, + })), + }, +] + +const decoder = compileDecodeCharMap(['@', '+']) +for (const { inputs } of scenarios) { + for (const input of inputs) { + input.decoder = decoder + input.server = false + } +} +scenarios.push( + ...scenarios.map(({ name, inputs, register }) => ({ + name: `server ${name}`, + inputs: inputs.map((input) => ({ ...input, server: true })), + register, + })), +) + +describe.each(scenarios)('$name', ({ inputs, register = true }) => { + const root = new BaseRootRoute({}) + const routes = new Map( + [...new Set(inputs.map((input) => input.path))].map((path) => [ + path, + new BaseRoute({ getParentRoute: () => root, path }), + ]), + ) + const router = createTestRouter({ + routeTree: register ? root.addChildren([...routes.values()]) : root, + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: inputs[0]?.server, + pathParamsAllowedCharacters: ['@', '+'], + scrollRestoration: false, + }) + router.history.destroy() + // Reference values come from a fresh standalone parse, independent of any + // route-owned segments under test. + const referencePathname = (input: PathInterpolationTestOptions) => + interpolatePath( + input.path, + parseSegments(false, { fullPath: input.path }, 0), + input.params, + input.decoder, + ) + // Mirrors how buildLocation turns a template into a canonical pathname. + const canonicalPathname = ( + path: string, + params: Record, + route: AnyRoute | undefined, + ) => + normalizeProtocolRelative( + decodePath( + interpolatePath( + path, + route?._interpolation ?? parseSegments(false, { fullPath: path }, 0), + params, + router.pathParamsDecoder, + ), + ), + ) + const calls = inputs + .filter((input) => input.path.includes('$')) + .map((input) => ({ + path: input.path, + params: input.params, + route: register ? routes.get(input.path) : undefined, + expected: decodePath(referencePathname(input)), + })) + let checksum = 0 + const expected = inputs.reduce( + (sum, input) => sum + referencePathname(input).length, + 0, + ) + const cachedExpected = calls.reduce((sum, call) => { + expect(canonicalPathname(call.path, call.params, call.route)).toBe( + call.expected, + ) + return sum + call.expected.length + }, 0) + for (const call of calls) { + expect(canonicalPathname(call.path, call.params, call.route)).toBe( + call.expected, + ) + } + + const preparedInputs = inputs.map((input) => ({ + ...input, + segments: register + ? routes.get(input.path)?._interpolation + : parseSegments(false, { fullPath: input.path }, 0), + })) + + test('interpolation and normalization batch', async ({ bench }) => { + await bench( + 'interpolation and normalization batch', + { + afterAll: () => { + expect(checksum).toBe(cachedExpected) + }, + }, + () => { + let length = 0 + for (const call of calls) { + length += canonicalPathname(call.path, call.params, call.route).length + } + checksum = length + }, + ).run({ + time: 1500, + warmupTime: 500, + throws: true, + }) + }) + + test('prepared pathname interpolation batch', async ({ bench }) => { + await bench( + 'prepared pathname interpolation batch', + { + afterAll: () => { + expect(checksum).toBe(expected) + }, + }, + () => { + let length = 0 + for (const input of preparedInputs) { + length += ( + input.segments + ? interpolatePath( + input.path, + input.segments, + input.params, + input.decoder, + ) + : input.path + ).length + } + checksum = length + }, + ).run({ + time: 1500, + warmupTime: 500, + throws: true, + }) + }) + + test('prepared metadata interpolation batch', async ({ bench }) => { + await bench( + 'prepared metadata interpolation batch', + { + afterAll: () => { + expect(checksum).toBe(expected) + }, + }, + () => { + let length = 0 + for (const input of preparedInputs) { + length += ( + input.segments + ? interpolatePath( + input.path, + input.segments, + input.params, + input.decoder, + Object.create(null), + ) + : input.path + ).length + } + checksum = length + }, + ).run({ + time: 1500, + warmupTime: 500, + throws: true, + }) + }) +}) diff --git a/packages/router-core/tests/path.test.ts b/packages/router-core/tests/path.test.ts index 6503eb0b75..dac91a80fa 100644 --- a/packages/router-core/tests/path.test.ts +++ b/packages/router-core/tests/path.test.ts @@ -1,6 +1,8 @@ -import { describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { + compileDecodeCharMap, exactPathTest, + hasMissingPathParams, interpolatePath, removeTrailingSlash, resolvePath, @@ -11,11 +13,372 @@ import { SEGMENT_TYPE_PATHNAME, SEGMENT_TYPE_WILDCARD, findSingleMatch, - parseSegment, - processRouteTree, + getParamNames, + parseSegments, } from '../src/new-process-route-tree' +import { createSieveCache } from '../src/sieve-cache' +import { + createTestPathInterpolator as createPathInterpolator, + parseTestPathname as parsePathname, + processTestRouteTree as processRouteTree, +} from './routerTestUtils' import type { SegmentKind } from '../src/new-process-route-tree' +afterEach(() => vi.restoreAllMocks()) + +describe.each([false, true])( + 'pathname interpolation (server: %s)', + (server) => { + it.each([ + { path: '/', params: {}, expected: '/' }, + { path: '/users/', params: {}, expected: '/users/' }, + { path: '/users/$id', params: { id: '123' }, expected: '/users/123' }, + { path: '/users/$id', params: { id: 0 }, expected: '/users/0' }, + { path: '/users/$id', params: {}, expected: '/users/undefined' }, + { + path: '/users/$id', + params: { id: 'a/b?#@+' }, + expected: '/users/a%2Fb%3F%23%40%2B', + }, + { + path: '/users/$id', + params: { id: 'cafe\u0301' }, + expected: '/users/cafe%CC%81', + normalized: '/users/cafe\u0301', + }, + { + path: '/users/{$id}.json', + params: { id: '123' }, + expected: '/users/123.json', + }, + { path: '/posts/{-$category}', params: {}, expected: '/posts' }, + { + path: '/posts/{-$category}', + params: { category: undefined }, + expected: '/posts', + }, + { + path: '/posts/{-$category}', + params: { category: '' }, + expected: '/posts/', + }, + { + path: '/posts/{-$category}', + params: { category: 'news' }, + expected: '/posts/news', + }, + { + path: '/posts/prefix{-$category}suffix', + params: { category: 'news' }, + expected: '/posts/prefixnewssuffix', + }, + { + path: '/files/$', + params: { _splat: 'a b/c+d' }, + expected: '/files/a%20b/c%2Bd', + normalized: '/files/a b/c%2Bd', + }, + { + path: '/files/prefix{$}suffix', + params: { _splat: 'a/b' }, + expected: '/files/prefixa/bsuffix', + }, + { path: '/files/$', params: { _splat: '' }, expected: '/files' }, + { path: '/files/$', params: { _splat: 0 }, expected: '/files/0' }, + { + path: '/files/prefix{$}.txt', + params: { _splat: 0 }, + expected: '/files/prefix0.txt', + }, + { + path: '/$id/$id/', + params: { id: '123' }, + expected: '/123/123/', + }, + ])( + 'interpolates $path with $params', + ({ path, params, expected, normalized }) => { + const interpolate = createPathInterpolator({ isServer: server }) + const options = { path, params, server } + const segments = parseSegments(false, { fullPath: path }, 0) + expect(interpolatePath(path, segments, params)).toBe(expected) + expect(interpolate(options)).toBe(normalized ?? expected) + expect(interpolate({ ...options, params: { ...params } })).toBe( + normalized ?? expected, + ) + }, + ) + + it('formats non-string values on every call', () => { + const interpolate = createPathInterpolator({ isServer: server }) + const toString = vi.fn(() => 'one two') + const options = { + path: '/users/$id', + params: { id: { toString } }, + server, + } + expect(interpolate(options)).toBe('/users/one two') + expect(toString).toHaveBeenCalledOnce() + toString.mockReturnValue('next value') + expect(interpolate(options)).toBe('/users/next value') + expect(toString).toHaveBeenCalledTimes(2) + }) + + it('separates results between fixed encoding configurations', () => { + const allowAt = createPathInterpolator({ + isServer: server, + pathParamsAllowedCharacters: ['@'], + }) + const allowPlus = createPathInterpolator({ + isServer: server, + pathParamsAllowedCharacters: ['+'], + }) + const standard = createPathInterpolator({ isServer: server }) + const options = { + path: '/users/$id', + params: { id: '@+' }, + server, + } + expect(allowAt(options)).toBe('/users/@%2B') + expect(allowPlus(options)).toBe('/users/%40+') + expect(standard(options)).toBe('/users/%40%2B') + expect(allowAt(options)).toBe('/users/@%2B') + }) + + it('keeps each router encoding independent across templates', () => { + const allowAt = createPathInterpolator({ + isServer: server, + pathParamsAllowedCharacters: ['@'], + }) + const allowPlus = createPathInterpolator({ + isServer: server, + pathParamsAllowedCharacters: ['+'], + }) + const standard = createPathInterpolator({ isServer: server }) + for (const [interpolate, encoded] of [ + [allowAt, '@%2B'], + [allowPlus, '%40+'], + [standard, '%40%2B'], + [allowAt, '@%2B'], + ] as const) { + for (const prefix of ['/users/', '/teams/']) { + const path = prefix + '$id' + const options = { path, params: { id: '@+' }, server } + expect(interpolate(options)).toBe(prefix + encoded) + } + } + }) + + it('does not confuse parameter boundaries', () => { + const interpolate = createPathInterpolator({ isServer: server }) + const options = { path: '/$first/$second', server } + const first = { first: 'a:b', second: 'c' } + const second = { first: 'a', second: 'b:c' } + + expect(interpolate({ ...options, params: first })).toBe('/a%3Ab/c') + expect(interpolate({ ...options, params: second })).toBe('/a/b%3Ac') + expect(interpolate({ ...options, params: first })).toBe('/a%3Ab/c') + }) + + it('keeps templates separate when parameter values are equal', () => { + const interpolate = createPathInterpolator({ isServer: server }) + const params = { id: '123' } + + expect(interpolate({ path: '/users/$id', params })).toBe('/users/123') + expect(interpolate({ path: '/posts/$id', params })).toBe('/posts/123') + expect(interpolate({ path: '/users/$id', params })).toBe('/users/123') + }) + + it('formats optional params from their current values', () => { + const interpolate = createPathInterpolator({ isServer: server }) + const path = '/posts/{-$category}/$id' + const inputs = [ + { params: { id: 'one' }, expected: '/posts/one' }, + { + params: { id: 'one', category: 'news' }, + expected: '/posts/news/one', + }, + { + params: { id: 'one', category: undefined }, + expected: '/posts/one', + }, + { params: { id: 'one', category: '' }, expected: '/posts//one' }, + { + params: { id: 'one', category: 'updates' }, + expected: '/posts/updates/one', + }, + ] + + for (const { params, expected } of [...inputs, ...inputs]) { + const options = { path, params, server } + expect(interpolate(options)).toBe(expected) + } + }) + + it('uses the canonical splat value instead of its legacy alias', () => { + const interpolate = createPathInterpolator({ + isServer: server, + pathParamsAllowedCharacters: ['@'], + }) + const options = { + path: '/files/$', + params: { _splat: 'docs/@guide', '*': 'ignored' }, + server, + } + + expect(interpolate(options)).toBe('/files/docs/@guide') + expect( + interpolate({ + ...options, + params: { _splat: 'docs/@guide', '*': 'changed' }, + }), + ).toBe('/files/docs/@guide') + }) + + it('collects used params for splats but not missing optionals', () => { + const usedParams: Record = Object.create(null) + interpolatePath( + '/posts/{-$category}', + parseSegments(false, { fullPath: '/posts/{-$category}' }, 0), + {}, + undefined, + usedParams, + ) + expect(usedParams).toEqual({}) + interpolatePath( + '/files/$', + parseSegments(false, { fullPath: '/files/$' }, 0), + { _splat: 'docs/guide' }, + undefined, + usedParams, + ) + expect(usedParams).toEqual({ + _splat: 'docs/guide', + '*': 'docs/guide', + }) + expect(Object.getPrototypeOf(usedParams)).toBeNull() + }) + + it.each([ + { + params: { id: 'one two', _splat: 'docs/file name' }, + path: '/root/prefixone%20twosuffix/files/docs/file%20name.txt', + used: { + id: 'one two', + _splat: 'docs/file name', + '*': 'docs/file name', + }, + missing: false, + }, + { + params: { id: '', language: '', _splat: '' }, + path: '/root/prefixsuffix//files/.txt', + used: { id: '', language: '', _splat: '', '*': '' }, + missing: true, + }, + { + params: {}, + path: '/root/prefixundefinedsuffix/files/.txt', + used: { id: undefined, _splat: undefined, '*': undefined }, + missing: true, + }, + ])( + 'keeps mixed segment metadata in one pass for $params', + ({ params, path, used, missing }) => { + const template = '/root/prefix{$id}suffix/{-$language}/files/{$}.txt' + const segments = parseSegments(false, { fullPath: template }, 0) + const usedParams: Record = Object.create(null) + expect( + interpolatePath(template, segments, params, undefined, usedParams), + ).toBe(path) + expect(getParamNames(segments)).toEqual(['id', 'language', '_splat']) + expect(usedParams).toEqual(used) + expect(hasMissingPathParams(segments, params)).toBe(missing) + expect(interpolatePath(template, segments, params)).toBe(path) + }, + ) + + it.each([ + { + path: '/$first/$second', + params: { second: 'two' }, + pathname: '/undefined/two', + usedParams: { first: undefined, second: 'two' }, + missing: true, + }, + { + path: '/$first/$second', + params: { first: undefined, second: 'two' }, + pathname: '/undefined/two', + usedParams: { first: undefined, second: 'two' }, + missing: false, + }, + { + path: '/{-$first}/$second', + params: { second: 'two' }, + pathname: '/two', + usedParams: { second: 'two' }, + missing: false, + }, + { + path: '/$first/{-$second}', + params: {}, + pathname: '/undefined', + usedParams: { first: undefined }, + missing: true, + }, + { + path: '/$first/prefix{$}suffix', + params: { first: 'one' }, + pathname: '/one/prefixsuffix', + usedParams: { first: 'one', _splat: undefined, '*': undefined }, + missing: true, + }, + ])( + 'preserves missing-param metadata for $path with $params', + ({ path, params, pathname, usedParams, missing }) => { + const segments = parseSegments(false, { fullPath: path }, 0) + const collectedParams: Record = Object.create(null) + expect( + interpolatePath(path, segments, params, undefined, collectedParams), + ).toBe(pathname) + expect(collectedParams).toEqual(usedParams) + expect(hasMissingPathParams(segments, params)).toBe(missing) + }, + ) + + it('tracks a splat that was empty when the template was first used', () => { + const interpolate = createPathInterpolator({ isServer: server }) + for (const _splat of ['', 'docs/guide', '', 'docs/reference']) { + const options = { + path: '/files/prefix{$}suffix', + params: { _splat }, + server, + } + expect(interpolate(options)).toBe(`/files/prefix${_splat}suffix`) + } + }) + + it('does not retain incomplete metadata when the first interpolation throws', () => { + const interpolate = createPathInterpolator({ isServer: server }) + const options = { path: '/$first/$second', server } + + expect(() => + interpolate({ + ...options, + params: { first: '\uD800', second: 'one' }, + }), + ).toThrow(URIError) + + for (const second of ['two', 'three', 'two']) { + expect( + interpolate({ ...options, params: { first: 'valid', second } }), + ).toBe(`/valid/${second}`) + } + }) + }, +) + describe.each([{ basepath: '/' }, { basepath: '/app' }, { basepath: '/app/' }])( 'removeTrailingSlash with basepath $basepath', ({ basepath }) => { @@ -92,6 +455,9 @@ describe('resolvePath', () => { ['/', 'a/', '/a'], ['/', '/a/b', '/a/b'], ['/a', 'b', '/a/b'], + ['/a', '', '/'], + ['/a', '.well-known', '/a/.well-known'], + ['/a', '/absolute', '/absolute'], ['/', 'a/b', '/a/b'], ['/', './a/b', '/a/b'], ['/a/b/c', 'd', '/a/b/c/d'], @@ -104,79 +470,62 @@ describe('resolvePath', () => { ['/a/b/c', '../..', '/a'], ['/a/b/c', '../../..', '/'], ['/a/b/c/', '../../..', '/'], + ['/a//b', '../../c', '/c'], + ['/a///b', '../c', '/a/c'], + ['/', '../javascript:alert(1)', '/javascript:alert(1)'], + ['/posts', '../../data:text/html,test', '/data:text/html,test'], ])('resolves correctly', (a, b, eq) => { it(`${a} to ${b} === ${eq}`, () => { - expect(resolvePath({ base: a, to: b })).toEqual(eq) + expect(resolvePath(a, b)).toEqual(eq) }) it(`${a}/ to ${b} === ${eq} (trailing slash)`, () => { - expect(resolvePath({ base: a + '/', to: b })).toEqual(eq) + expect(resolvePath(a + '/', b)).toEqual(eq) }) it(`${a}/ to ${b}/ === ${eq} (trailing slash + trailing slash)`, () => { - expect(resolvePath({ base: a + '/', to: b + '/' })).toEqual(eq) + expect(resolvePath(a + '/', b + '/')).toEqual(eq) }) }) + it('normalizes repeated slashes when resolving the base path', () => { + expect(resolvePath('/a//b', '.')).toBe('/a/b') + }) + describe('trailingSlash', () => { describe(`'always'`, () => { it('keeps trailing slash', () => { - expect( - resolvePath({ - base: '/a/b/c', - to: 'd/', - trailingSlash: 'always', - }), - ).toBe('/a/b/c/d/') + expect(resolvePath('/a/b/c', 'd/', 'always')).toBe('/a/b/c/d/') }) it('adds trailing slash', () => { - expect( - resolvePath({ - base: '/a/b/c', - to: 'd', - trailingSlash: 'always', - }), - ).toBe('/a/b/c/d/') + expect(resolvePath('/a/b/c', 'd', 'always')).toBe('/a/b/c/d/') }) }) describe(`'never'`, () => { it('removes trailing slash', () => { - expect( - resolvePath({ - base: '/a/b/c', - to: 'd/', - trailingSlash: 'never', - }), - ).toBe('/a/b/c/d') + expect(resolvePath('/a/b/c', 'd/', 'never')).toBe('/a/b/c/d') }) it('does not add trailing slash', () => { - expect( - resolvePath({ - base: '/a/b/c', - to: 'd', - trailingSlash: 'never', - }), - ).toBe('/a/b/c/d') + expect(resolvePath('/a/b/c', 'd', 'never')).toBe('/a/b/c/d') }) }) describe(`'preserve'`, () => { it('keeps trailing slash', () => { - expect( - resolvePath({ - base: '/a/b/c', - to: 'd/', - trailingSlash: 'preserve', - }), - ).toBe('/a/b/c/d/') + expect(resolvePath('/a/b/c', 'd/', 'preserve')).toBe('/a/b/c/d/') }) it('does not add trailing slash', () => { - expect( - resolvePath({ - base: '/a/b/c', - to: 'd', - trailingSlash: 'preserve', - }), - ).toBe('/a/b/c/d') + expect(resolvePath('/a/b/c', 'd', 'preserve')).toBe('/a/b/c/d') }) }) + + it.each([ + ['always', '/a//b', '/a/b/'], + ['never', '/a//b///', '/a/b'], + ['preserve', '/a//b///', '/a/b/'], + ] as const)( + "normalizes repeated slashes with trailingSlash '%s'", + (trailingSlash, to, expected) => { + expect(resolvePath('/', to, trailingSlash)).toBe(expected) + }, + ) }) describe.each([{ base: '/' }, { base: '/nested' }])( @@ -200,13 +549,7 @@ describe('resolvePath', () => { }, ])('$name', ({ to }) => { const candidate = base + trimPathLeft(to) - expect( - resolvePath({ - base, - to: candidate, - trailingSlash: 'never', - }), - ).toEqual(candidate) + expect(resolvePath(base, candidate, 'never')).toEqual(candidate) }) }) @@ -228,20 +571,106 @@ describe('resolvePath', () => { }, ])('$name', ({ to }) => { const candidate = base + trimPathLeft(to) - expect( - resolvePath({ - base, - to: candidate, - trailingSlash: 'never', - }), - ).toEqual(candidate) + expect(resolvePath(base, candidate, 'never')).toEqual(candidate) }) }) }, ) + + it('preserves explicit route-template param syntax', () => { + expect(resolvePath('/{$language}', '.')).toBe('/{$language}') + + expect(resolvePath('/{$language}/posts', '../{$language}')).toBe( + '/{$language}/{$language}', + ) + }) + + it('caches route-template paths without changing param syntax', () => { + const cache = createSieveCache(10) + const set = vi.spyOn(cache, 'set') + + expect(resolvePath('/', '{$id}', undefined, cache)).toBe('/{$id}') + expect(resolvePath('/', '$id', undefined, cache)).toBe('/$id') + expect(resolvePath('/', '{$id}', undefined, cache)).toBe('/{$id}') + expect(resolvePath('/', '$id', undefined, cache)).toBe('/$id') + expect(set).toHaveBeenCalledTimes(2) + }) }) describe('interpolatePath', () => { + it.each(['value', '', undefined])( + 'stops interpolation at a bare splat with value %s', + (_splat) => { + const params = { + _splat, + get ignored() { + throw new Error('A bare splat consumes the rest of the template') + }, + } + const segments = parseSegments( + false, + { fullPath: '/files/$/$ignored' }, + 0, + ) + const used: Record = Object.create(null) + expect( + interpolatePath('/files/$/$ignored', segments, params, undefined, used), + ).toBe(_splat ? '/files/value' : '/files') + expect(getParamNames(segments)).toEqual(['_splat']) + expect(used).toEqual({ _splat, '*': _splat }) + }, + ) + + it.each([ + { path: '/', expected: '/' }, + { path: '/about/', expected: '/about/' }, + ])('preserves static paths: $path', ({ path, expected }) => { + const params = { + get unused() { + throw new Error('Static paths must not read params') + }, + } + const segments = parseSegments(false, { fullPath: path }, 0) + const decoder = vi.fn() + const usedParams: Record = Object.create(null) + expect(interpolatePath(path, segments, params, decoder, usedParams)).toBe( + expected, + ) + expect(usedParams).toEqual({}) + expect(getParamNames(segments)).toEqual([]) + expect(hasMissingPathParams(segments, params)).toBe(false) + expect(decoder).not.toHaveBeenCalled() + }) + + it.each([ + { + path: '/users/$id', + params: {}, + expected: '/users/undefined', + missing: true, + }, + { + path: '/users/$id', + params: { id: 'one' }, + expected: '/users/one', + missing: false, + }, + { + path: '/posts/{-$category}', + params: {}, + expected: '/posts', + missing: false, + }, + { path: '/files/$', params: {}, expected: '/files', missing: true }, + ])( + 'collects only missing status for $path', + ({ path, params, expected, missing }) => { + const segments = parseSegments(false, { fullPath: path }, 0) + expect(interpolatePath(path, segments, params)).toBe(expected) + expect(hasMissingPathParams(segments, params)).toBe(missing) + }, + ) + describe('regular usage', () => { it.each([ { @@ -298,6 +727,12 @@ describe('interpolatePath', () => { params: { id: 0 }, result: '/users/0', }, + { + name: 'should interpolate the path with the splat param being a falsey number', + path: '/users/$', + params: { _splat: 0 }, + result: '/users/0', + }, { name: 'should interpolate the path with URI component encoding', path: '/users/$id', @@ -309,9 +744,7 @@ describe('interpolatePath', () => { path: '/users/$id', params: { id: '?#@john+smith' }, result: '/users/%3F%23@john+smith', - decodeCharMap: new Map( - ['@', '+'].map((char) => [encodeURIComponent(char), char]), - ), + decoder: compileDecodeCharMap(['@', '+']), }, { name: 'should interpolate the path with the splat param at the end', @@ -348,14 +781,9 @@ describe('interpolatePath', () => { params: { _splat: 'sean/cassiere' }, result: '/users/sean/cassiere', }, - ])('$name', ({ path, params, decodeCharMap, result }) => { - expect( - interpolatePath({ - path, - params, - decodeCharMap, - }).interpolatedPath, - ).toBe(result) + ])('$name', ({ path, params, decoder, result }) => { + const segments = parseSegments(false, { fullPath: path }, 0) + expect(interpolatePath(path, segments, params, decoder)).toBe(result) }) }) @@ -384,12 +812,8 @@ describe('interpolatePath', () => { ])( 'should preserve trailing slash for $path', ({ path, params, result }) => { - expect( - interpolatePath({ - path, - params, - }).interpolatedPath, - ).toBe(result) + const segments = parseSegments(false, { fullPath: path }, 0) + expect(interpolatePath(path, segments, params)).toBe(result) }, ) }) @@ -427,12 +851,70 @@ describe('interpolatePath', () => { result: '/prefixbar-suffix', }, ])('$name', ({ to, params, result }) => { - expect( - interpolatePath({ - path: to, - params, - }).interpolatedPath, - ).toBe(result) + const segments = parseSegments(false, { fullPath: to }, 0) + expect(interpolatePath(to, segments, params)).toBe(result) + }) + }) + + describe('splat params with special characters', () => { + it.each([ + { + name: 'should encode spaces in splat param', + path: '/$', + params: { _splat: 'file name.pdf' }, + result: '/file%20name.pdf', + }, + { + name: 'should preserve parentheses in splat param (RFC 3986 unreserved)', + path: '/$', + params: { _splat: 'file(1).pdf' }, + result: '/file(1).pdf', + }, + { + name: 'should encode brackets in splat param', + path: '/$', + params: { _splat: 'file[1].pdf' }, + result: '/file%5B1%5D.pdf', + }, + { + name: 'should encode spaces in nested splat param paths', + path: '/$', + params: { _splat: 'folder/sub folder/file name.pdf' }, + result: '/folder/sub%20folder/file%20name.pdf', + }, + { + name: 'should encode spaces and brackets but preserve parentheses', + path: '/$', + params: { _splat: 'docs/file (copy) [2].pdf' }, + result: '/docs/file%20(copy)%20%5B2%5D.pdf', + }, + { + name: 'should encode hash in splat param', + path: '/$', + params: { _splat: 'page#section' }, + result: '/page%23section', + }, + { + name: 'should handle splat param with prefix and special characters', + path: '/files/prefix{$}', + params: { _splat: 'my file.pdf' }, + result: '/files/prefixmy%20file.pdf', + }, + { + name: 'should encode plus signs in splat param', + path: '/$', + params: { _splat: 'file+name.pdf' }, + result: '/file%2Bname.pdf', + }, + { + name: 'should encode equals signs in splat param', + path: '/$', + params: { _splat: 'query=value' }, + result: '/query%3Dvalue', + }, + ])('$name', ({ path, params, result }) => { + const segments = parseSegments(false, { fullPath: path }, 0) + expect(interpolatePath(path, segments, params)).toBe(result) }) }) @@ -475,12 +957,8 @@ describe('interpolatePath', () => { result: '/prefixfoobar.suffix', }, ])('$name', ({ to, params, result }) => { - expect( - interpolatePath({ - path: to, - params, - }).interpolatedPath, - ).toBe(result) + const segments = parseSegments(false, { fullPath: to }, 0) + expect(interpolatePath(to, segments, params)).toBe(result) }) }) @@ -527,40 +1005,30 @@ describe('interpolatePath', () => { expectedResult: '/hello', }, ])('$name', ({ path, params, expectedResult }) => { - const result = interpolatePath({ - path, - params, - }) - expect(result.interpolatedPath).toBe(expectedResult) - expect(result.isMissingParams).toBe(true) + const segments = parseSegments(false, { fullPath: path }, 0) + expect(interpolatePath(path, segments, params)).toBe(expectedResult) + expect(hasMissingPathParams(segments, params)).toBe(true) }) }) -}) -describe('resolvePath + interpolatePath', () => { - it.each(['never', 'preserve', 'always'] as const)( - 'trailing slash: %s', - (trailingSlash) => { - const tail = trailingSlash === 'always' ? '/' : '' - const defaultedFromPath = '/' - const fromPath = resolvePath({ - base: defaultedFromPath, - to: '.', - trailingSlash, - }) - const nextTo = resolvePath({ - base: fromPath, - to: '/splat/$', - trailingSlash, - }) - const nextParams = { _splat: '' } - const interpolatedNextTo = interpolatePath({ - path: nextTo, - params: nextParams, - }).interpolatedPath - expect(interpolatedNextTo).toBe(`/splat${tail}`) - }, - ) + describe('resolvePath + interpolatePath', () => { + it.each(['never', 'preserve', 'always'] as const)( + 'trailing slash: %s', + (trailingSlash) => { + const tail = trailingSlash === 'always' ? '/' : '' + const defaultedFromPath = '/' + const fromPath = resolvePath(defaultedFromPath, '.', trailingSlash) + const nextTo = resolvePath(fromPath, '/splat/$', trailingSlash) + const nextParams = { _splat: '' } + const interpolatedNextTo = interpolatePath( + nextTo, + parseSegments(false, { fullPath: nextTo }, 0), + nextParams, + ) + expect(interpolatedNextTo).toBe(`/splat${tail}`) + }, + ) + }) }) describe('matchPathname', () => { @@ -581,7 +1049,7 @@ describe('matchPathname', () => { from, processedTree, ) - const result = match ? match.params : undefined + const result = match ? match.rawParams : undefined if (options.to && !result) return return result ?? {} } @@ -612,7 +1080,7 @@ describe('matchPathname', () => { expectedMatchedParams: { id: '123' }, }, { - name: 'should match and return the the splat param', + name: 'should match and return the splat param', input: '/users/123', matchingOptions: { to: '/users/$', @@ -661,7 +1129,7 @@ describe('matchPathname', () => { }, ])('$name', ({ input, matchingOptions, expectedMatchedParams }) => { expect(matchPathname(input, matchingOptions)).toStrictEqual( - expectedMatchedParams, + toNullObj(expectedMatchedParams), ) }) }) @@ -725,7 +1193,7 @@ describe('matchPathname', () => { }, ])('$name', ({ input, matchingOptions, expectedMatchedParams }) => { expect(matchPathname(input, matchingOptions)).toStrictEqual( - expectedMatchedParams, + toNullObj(expectedMatchedParams), ) }) }) @@ -804,7 +1272,7 @@ describe('matchPathname', () => { }, ])('$name', ({ input, matchingOptions, expectedMatchedParams }) => { expect(matchPathname(input, matchingOptions)).toStrictEqual( - expectedMatchedParams, + toNullObj(expectedMatchedParams), ) }) }) @@ -824,35 +1292,6 @@ describe('parsePathname', () => { suffixSegment?: string } - const parsePathname = (to: string | undefined) => { - let cursor = 0 - let data - const path = to ?? '' - const segments: Array = [] - while (cursor < path.length) { - const start = cursor - data = parseSegment(path, start, data) - const end = data[5] - cursor = end + 1 - const type = data[0] - const value = path.substring(data[2], data[3]) - const prefix = path.substring(start, data[1]) - const suffix = path.substring(data[4], end) - const segment: PathSegment = { - type, - value, - } - if (prefix) { - segment.prefixSegment = prefix - } - if (suffix) { - segment.suffixSegment = suffix - } - segments.push(segment) - } - return segments - } - describe('regular usage', () => { it.each([ { @@ -1142,3 +1581,8 @@ describe('parsePathname', () => { }) }) }) + +function toNullObj(obj: T): T { + if (typeof obj === 'object') return Object.assign(Object.create(null), obj) + return obj +} diff --git a/packages/router-core/tests/preflight-reentrant-context.test.ts b/packages/router-core/tests/preflight-reentrant-context.test.ts new file mode 100644 index 0000000000..415e5f0e50 --- /dev/null +++ b/packages/router-core/tests/preflight-reentrant-context.test.ts @@ -0,0 +1,101 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('synchronous navigation from route context stops abandoned descendant context work', async () => { + let redirected = false + let redirectNavigation: Promise | undefined + const childContext = vi.fn(() => ({ child: true })) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + context: ({ navigate }) => { + if (!redirected) { + redirected = true + redirectNavigation = navigate({ to: '/target' }) + } + return { parent: true } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + context: childContext, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/parent/child' }) + await redirectNavigation + + expect(router.state.location.pathname).toBe('/target') + expect(childContext).not.toHaveBeenCalled() +}) + +test('synchronous navigation from preloaded route context lets the preload finish quietly', async () => { + let redirected = false + let redirectNavigation: Promise | undefined + const childContext = vi.fn(() => ({ child: true })) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + context: ({ navigate, preload }) => { + if (preload && !redirected) { + redirected = true + redirectNavigation = navigate({ to: '/target' }) + } + return { parent: true } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + context: childContext, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/parent/child' }) + await redirectNavigation + + expect(router.state.location.pathname).toBe('/target') + // Preload lanes are not cancelled by navigations: the descendant context + // still computes (and may seed the cache), while the navigation wins the + // presented state. Only navigation lanes stop abandoned descendant work. + expect(childContext).toHaveBeenCalledOnce() +}) diff --git a/packages/router-core/tests/preflight-signal-currentness.test.ts b/packages/router-core/tests/preflight-signal-currentness.test.ts new file mode 100644 index 0000000000..23519edfec --- /dev/null +++ b/packages/router-core/tests/preflight-signal-currentness.test.ts @@ -0,0 +1,49 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, redirect } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('a route-context redirect retires its matching generation before following the redirect', async () => { + let sourceSignal: AbortSignal | undefined + const sourceBeforeLoad = vi.fn() + const sourceLoader = vi.fn() + const targetLoader = vi.fn(() => 'target') + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + context: ({ abortController }) => { + sourceSignal = abortController.signal + throw redirect({ to: '/target' }) + }, + beforeLoad: sourceBeforeLoad, + loader: sourceLoader, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: targetLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/source' }) + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + loaderData: 'target', + }) + expect(sourceSignal?.aborted).toBe(true) + expect(sourceBeforeLoad).not.toHaveBeenCalled() + expect(sourceLoader).not.toHaveBeenCalled() + expect(targetLoader).toHaveBeenCalledOnce() +}) diff --git a/packages/router-core/tests/preload-adoption.test.ts b/packages/router-core/tests/preload-adoption.test.ts new file mode 100644 index 0000000000..94d31e2e94 --- /dev/null +++ b/packages/router-core/tests/preload-adoption.test.ts @@ -0,0 +1,367 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.useRealTimers() +}) + +/** + * Preload adoption edge cases. The happy path (navigation adopts an + * in-flight preload's successful loader run) and the control-flow + * non-leakage path are pinned in load.test.ts; this file pins the + * adoption boundary: a donor must have its loader genuinely in flight. A + * preload still in its serial phase can itself be waiting on the navigation + * through the borrow protocol, while a stale successful donor can still have + * fresh loader work pending behind its cached snapshot. + */ + +describe('preload adoption', () => { + test('navigation waits for fresh data from an in-flight stale preload revalidation', async () => { + vi.useFakeTimers() + vi.setSystemTime(0) + + const revalidationGate = createControlledPromise<{ + notifications: Array + }>() + const revalidationStarted = createControlledPromise() + let loaderCalls = 0 + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const notificationsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/notifications', + staleTime: 0, + preloadStaleTime: 0, + gcTime: 60_000, + loader: { + staleReloadMode: 'blocking', + handler: () => { + loaderCalls++ + if (loaderCalls === 1) { + return { notifications: ['old'] } + } + + revalidationStarted.resolve() + return revalidationGate + }, + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, notificationsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/notifications' } as any) + + expect(loaderCalls).toBe(1) + + // The cached successful preload is now stale. A second hover starts a + // genuine revalidation while the user clicks the link. + vi.setSystemTime(1) + const revalidation = router.preloadRoute({ + to: '/notifications', + } as any) + await revalidationStarted + expect(loaderCalls).toBe(2) + + let navigationSettled = false + const navigation = router.navigate({ to: '/notifications' }).then(() => { + navigationSettled = true + }) + await Promise.resolve() + + // The navigation may share the revalidation, but it must not treat the + // stale cached snapshot as the completed result while fresh work runs. + expect(revalidationGate.status).toBe('pending') + expect(navigationSettled).toBe(false) + + revalidationGate.resolve({ notifications: ['fresh'] }) + await Promise.all([revalidation, navigation]) + + // A fix may either share the fresh revalidation or run a navigation + // loader of its own; correctness only requires publishing fresh data. + expect(loaderCalls).toBeGreaterThanOrEqual(2) + expect( + router.state.matches.find( + (match) => match.routeId === notificationsRoute.id, + )?.loaderData, + ).toEqual({ notifications: ['fresh'] }) + }) + + test('navigation runs beforeLoad independently of a preload serial phase', async () => { + const beforeLoadGate = createControlledPromise() + const preloadSerialStarted = createControlledPromise() + let beforeLoadCalls = 0 + const loader = vi.fn(() => 'data') + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad: async () => { + beforeLoadCalls++ + if (beforeLoadCalls === 1) { + // Keep the shared lane's serial phase in flight. + preloadSerialStarted.resolve() + await beforeLoadGate + } + }, + loader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fooRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + // Preload is stuck in its serial phase — its loader has NOT started. + const preload = router.preloadRoute({ to: '/foo' } as any) + await preloadSerialStarted + expect(beforeLoadCalls).toBe(1) + + const navigation = router.navigate({ to: '/foo' }) + await vi.waitFor(() => expect(beforeLoadCalls).toBe(2)) + expect(loader).toHaveBeenCalledTimes(1) + + beforeLoadGate.resolve() + await Promise.all([navigation, preload]) + expect(beforeLoadCalls).toBe(2) + expect(loader).toHaveBeenCalledTimes(1) + expect( + router.state.matches.find((match) => match.routeId === fooRoute.id) + ?.status, + ).toBe('success') + }) + + test("a sibling preload shares another preload lane's in-flight loader", async () => { + const loaderGate = createControlledPromise() + const loaderStarted = createControlledPromise() + let preloadBeforeLoadCalls = 0 + const loader = vi.fn(() => { + loaderStarted.resolve() + return loaderGate + }) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + preloadStaleTime: Infinity, + beforeLoad: ({ preload }) => { + if (preload) { + preloadBeforeLoadCalls++ + } + }, + loader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fooRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const first = router.preloadRoute({ to: '/foo' } as any) + await loaderStarted + + const second = router.preloadRoute({ to: '/foo' } as any) + await vi.waitFor(() => expect(preloadBeforeLoadCalls).toBe(2)) + expect(loader).toHaveBeenCalledTimes(1) + + loaderGate.resolve('once') + await Promise.all([first, second]) + expect(loader).toHaveBeenCalledTimes(1) + + await router.navigate({ to: '/foo' }) + + expect(loader).toHaveBeenCalledTimes(1) + expect( + router.state.matches.find((match) => match.routeId === fooRoute.id) + ?.loaderData, + ).toBe('once') + }) + + test('a fulfilled undefined loader result is adopted as success', async () => { + const loaderGate = createControlledPromise() + const loaderStarted = createControlledPromise() + const loader = vi.fn(() => { + loaderStarted.resolve() + return loaderGate + }) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad: vi.fn(), + loader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fooRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + const preload = router.preloadRoute({ to: '/foo' }) + await loaderStarted + const navigation = router.navigate({ to: '/foo' }) + await Promise.resolve() + expect(loaderGate.status).toBe('pending') + expect(loader).toHaveBeenCalledTimes(1) + + loaderGate.resolve(undefined) + await Promise.all([preload, navigation]) + + expect(loader).toHaveBeenCalledTimes(1) + const match = router.state.matches.find( + (candidate) => candidate.routeId === fooRoute.id, + ) + expect(match?.status).toBe('success') + expect(match?.loaderData).toBeUndefined() + }) + + test('navigation shares a failed pending preload without starving sibling work', async () => { + const preloadParentStarted = createControlledPromise() + const preloadFailureGate = createControlledPromise() + const childStarted = createControlledPromise() + const childGate = createControlledPromise() + const parentFailure = new Error('preload failed') + let parentLoads = 0 + let childLoads = 0 + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: async ({ preload }) => { + parentLoads++ + if (preload) { + preloadParentStarted.resolve() + await preloadFailureGate + throw parentFailure + } + return 'navigation data' + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + childLoads++ + childStarted.resolve() + return childGate + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/parent/child' } as any) + await Promise.all([preloadParentStarted, childStarted]) + expect(parentLoads).toBe(1) + expect(childLoads).toBe(1) + + const navigation = router.navigate({ to: '/parent/child' }) + await Promise.resolve() + expect(preloadFailureGate.status).toBe('pending') + expect(parentLoads).toBe(1) + expect(childLoads).toBe(1) + + preloadFailureGate.resolve() + childGate.resolve('child data') + await Promise.all([navigation, preload]) + + expect(parentLoads).toBe(1) + expect(childLoads).toBe(1) + expect(router.state.location.pathname).toBe('/parent/child') + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + status: 'error', + error: parentFailure, + }) + expect( + router.state.matches.find((match) => match.routeId === childRoute.id), + ).toMatchObject({ + status: 'success', + loaderData: 'child data', + }) + }) + + test('a route with preload disabled does not discard its preloaded ancestor', async () => { + const parentLoader = vi.fn(() => 'parent data') + const childLoader = vi.fn(() => 'child data') + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + preloadStaleTime: Infinity, + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + preload: false, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/parent/child' } as any) + await router.navigate({ to: '/parent/child' }) + + expect(parentLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenCalledTimes(1) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.loaderData, + ).toBe('parent data') + expect( + router.state.matches.find((match) => match.routeId === childRoute.id) + ?.loaderData, + ).toBe('child data') + }) +}) diff --git a/packages/router-core/tests/preload-background-parent-coherence.test.ts b/packages/router-core/tests/preload-background-parent-coherence.test.ts new file mode 100644 index 0000000000..3dcbb62824 --- /dev/null +++ b/packages/router-core/tests/preload-background-parent-coherence.test.ts @@ -0,0 +1,88 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('unrelated parent background work does not block a cacheable child preload', async () => { + const backgroundResponse = createControlledPromise<{ revision: number }>() + const childLoaderStarted = createControlledPromise() + let parentLoadCount = 0 + + const parentLoader = vi.fn(() => { + parentLoadCount++ + return parentLoadCount === 1 ? { revision: 1 } : backgroundResponse + }) + const childLoader = vi.fn(async ({ parentMatchPromise }) => { + childLoaderStarted.resolve() + const parentMatch = await parentMatchPromise + return { + parentRevision: (parentMatch.loaderData as { revision: number }).revision, + } + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: parentLoader, + staleTime: Infinity, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + staleTime: Infinity, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent'] }), + }) + + await router.load() + expect(parentLoader).toHaveBeenCalledTimes(1) + + // Invalidating a successful loader uses the default background revalidation + // mode. The public invalidate promise settles once that private reload has + // started; its network response can remain pending. + await router.invalidate({ + filter: (match) => match.routeId === parentRoute.id, + }) + expect(parentLoader).toHaveBeenCalledTimes(2) + + const childPreload = router.preloadRoute({ to: '/parent/child' }) + + await childLoaderStarted + expect(backgroundResponse.status).toBe('pending') + expect(parentLoader).toHaveBeenCalledTimes(2) + await childPreload + + // Loader data is deliberately reusable across context generations. The + // child preload may finish from the visible parent generation without + // waiting for unrelated background work to win publication. + expect(backgroundResponse.status).toBe('pending') + expect(childLoader).toHaveBeenCalledTimes(1) + + backgroundResponse.resolve({ revision: 2 }) + await vi.waitFor(() => + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.loaderData, + ).toEqual({ revision: 2 }), + ) + expect(parentLoader).toHaveBeenCalledTimes(2) + + await router.navigate({ to: '/parent/child' }) + + const parentMatch = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + ) + const childMatch = router.state.matches.find( + (match) => match.routeId === childRoute.id, + ) + + expect(parentLoader).toHaveBeenCalledTimes(2) + expect(childLoader).toHaveBeenCalledTimes(1) + expect(parentMatch?.loaderData).toEqual({ revision: 2 }) + expect(childMatch?.loaderData).toEqual({ parentRevision: 1 }) +}) diff --git a/packages/router-core/tests/preload-beforeload-reuse.test.ts b/packages/router-core/tests/preload-beforeload-reuse.test.ts new file mode 100644 index 0000000000..c9d70bae5d --- /dev/null +++ b/packages/router-core/tests/preload-beforeload-reuse.test.ts @@ -0,0 +1,669 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +afterEach(() => { + vi.useRealTimers() +}) + +describe('preloaded loader reuse with fresh beforeLoad context', () => { + test('reruns nested context for navigation while reusing loader data', async () => { + const parentBeforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + parent: preload ? 'preloaded parent' : 'loaded parent', + })) + const childBeforeLoad = vi.fn( + ({ + context, + preload, + }: { + context: { parent: string } + preload: boolean + }) => ({ + child: `${context.parent}:${preload}`, + }), + ) + const childLoader = vi.fn( + ({ + context, + preload, + }: { + context: { parent: string; child: string } + preload: boolean + }) => ({ context, preload }), + ) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + staleTime: Infinity, + beforeLoad: parentBeforeLoad, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + staleTime: Infinity, + beforeLoad: childBeforeLoad, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/parent/child' }) + await router.navigate({ to: '/parent/child' }) + + expect(parentBeforeLoad).toHaveBeenCalledTimes(2) + expect(parentBeforeLoad).toHaveBeenLastCalledWith( + expect.objectContaining({ preload: false }), + ) + expect(childBeforeLoad).toHaveBeenCalledTimes(2) + expect(childBeforeLoad).toHaveBeenLastCalledWith( + expect.objectContaining({ + context: expect.objectContaining({ parent: 'loaded parent' }), + preload: false, + }), + ) + expect(childLoader).toHaveBeenCalledTimes(1) + const match = router.state.matches.find( + (candidate) => candidate.routeId === childRoute.id, + ) + expect(match?.context).toEqual({ + parent: 'loaded parent', + child: 'loaded parent:false', + }) + expect(match?.loaderData).toEqual({ + context: { + parent: 'preloaded parent', + child: 'preloaded parent:true', + }, + preload: true, + }) + }) + + test('reruns beforeLoad while sharing an identical active preload loader', async () => { + const loaderGate = createControlledPromise() + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + guard: preload ? 'preloaded' : 'loaded', + })) + const loader = vi.fn(() => loaderGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + preloadStaleTime: Infinity, + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/guarded' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + const navigation = router.navigate({ to: '/guarded' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(loader).toHaveBeenCalledTimes(1) + + loaderGate.resolve('shared loader data') + await Promise.all([preload, navigation]) + + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.context).toEqual({ guard: 'loaded' }) + expect(router.state.matches.at(-1)?.loaderData).toBe('shared loader data') + }) + + test.each([ + { age: 50, expected: [false, true, false], guard: 'loaded' }, + { age: 100, expected: [false, true, false], guard: 'loaded' }, + ])( + 'reruns completed beforeLoad while retaining navigation-owned loader data at age $age', + async ({ age, expected, guard }) => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + guard: preload ? 'preloaded' : 'loaded', + })) + const loader = vi.fn(({ preload }: { preload: boolean }) => preload) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + staleTime: Infinity, + preloadStaleTime: 100, + beforeLoad, + shouldReload: false, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/guarded' }) + await router.navigate({ to: '/' }) + vi.setSystemTime(5_000) + await router.preloadRoute({ to: '/guarded' }) + vi.setSystemTime(5_000 + age) + await router.navigate({ to: '/guarded' }) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual( + expected, + ) + expect(loader.mock.calls.map(([context]) => context.preload)).toEqual([ + false, + ]) + expect(router.state.matches.at(-1)?.context).toEqual({ guard }) + }, + ) + + test('does not cache beforeLoad-only context across an unrelated navigation', async () => { + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + guard: preload ? 'preloaded' : 'loaded', + })) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + preloadStaleTime: Infinity, + preloadGcTime: Infinity, + beforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, otherRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/guarded' }) + await router.navigate({ to: '/other' }) + await router.navigate({ to: '/guarded' }) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(router.state.matches.at(-1)?.context).toEqual({ + guard: 'loaded', + }) + }) + + test('does not reuse child context under a different parent match', async () => { + const childBeforeLoad = vi.fn( + ({ + context, + preload, + }: { + context: { version: number } + preload: boolean + }) => ({ + childVersion: context.version, + }), + ) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + version: Number(search.version), + }), + loaderDeps: ({ search }) => ({ + version: search.version, + }), + context: ({ deps }: { deps: { version: number } }) => ({ + version: deps.version, + }), + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + preloadStaleTime: Infinity, + beforeLoad: childBeforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ + to: '/parent/child', + search: { version: 1 }, + }) + await router.navigate({ + to: '/parent/child', + search: { version: 2 }, + }) + + expect( + childBeforeLoad.mock.calls.map(([context]) => context.preload), + ).toEqual([true, false]) + expect(router.state.matches.at(-1)?.context).toEqual({ + version: 2, + childVersion: 2, + }) + }) + + test('reruns beforeLoad when the completed preload reaches its stale boundary', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const seen: Array = [] + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + staleTime: Infinity, + preloadStaleTime: 100, + beforeLoad: ({ preload }) => { + seen.push(preload) + return { generation: preload ? 'preload' : 'navigation' } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/guarded' }) + vi.setSystemTime(1_100) + await router.navigate({ to: '/guarded' }) + + expect(seen).toEqual([true, false]) + expect(router.state.matches.at(-1)?.context).toEqual({ + generation: 'navigation', + }) + }) + + test('reruns descendant context after an ancestor becomes stale', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const parentSeen: Array = [] + const childSeen: Array = [] + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + staleTime: Infinity, + preloadStaleTime: 100, + beforeLoad: ({ preload }) => { + parentSeen.push(preload) + return { parent: preload ? 'preloaded parent' : 'loaded parent' } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + staleTime: Infinity, + preloadStaleTime: 1_000, + beforeLoad: ({ context, preload }) => { + childSeen.push(preload) + return { child: `${context.parent}:${preload}` } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/parent/child' }) + vi.setSystemTime(1_100) + await router.navigate({ to: '/parent/child' }) + + expect(parentSeen).toEqual([true, false]) + expect(childSeen).toEqual([true, false]) + expect(router.state.matches.at(-1)?.context).toEqual({ + parent: 'loaded parent', + child: 'loaded parent:false', + }) + }) + + test('invalidation prevents reuse of completed preload context', async () => { + const seen: Array = [] + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + staleTime: Infinity, + beforeLoad: ({ preload }) => { + seen.push(preload) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/guarded' }) + await router.invalidate({ + filter: (match) => match.routeId === guardedRoute.id, + }) + await router.navigate({ to: '/guarded' }) + + expect(seen).toEqual([true, false]) + }) + + test('invalidation prevents adoption of context from an active preload', async () => { + const loaderGate = createControlledPromise() + let generation = 1 + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + generation, + preload, + })) + const loader = vi.fn(() => + loader.mock.calls.length === 1 ? loaderGate : 'new loader data', + ) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + staleTime: Infinity, + preloadStaleTime: Infinity, + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/guarded' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) + + generation = 2 + await router.invalidate() + const navigation = router.navigate({ to: '/guarded' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + loaderGate.resolve('shared loader data') + await Promise.all([preload, navigation]) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.context).toEqual({ + generation: 2, + preload: false, + }) + expect(router.state.matches.at(-1)?.loaderData).toBe('new loader data') + }) + + test('preload false does not cache beforeLoad context for navigation', async () => { + const seen: Array = [] + const loader = vi.fn() + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + preload: false, + staleTime: Infinity, + beforeLoad: ({ preload }) => { + seen.push(preload) + }, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/guarded' }) + + expect(seen).toEqual([true]) + expect(loader).not.toHaveBeenCalled() + + await router.navigate({ to: '/guarded' }) + + expect(seen).toEqual([true, false]) + expect(loader).toHaveBeenCalledTimes(1) + }) + + test('shouldReload remains scoped to loader data', async () => { + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + guard: preload ? 'preloaded' : 'loaded', + })) + const loader = vi.fn(({ preload }: { preload: boolean }) => preload) + const shouldReload = vi.fn(() => true) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + staleTime: Infinity, + beforeLoad, + shouldReload, + loader: { + staleReloadMode: 'blocking', + handler: loader, + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/guarded' }) + await router.navigate({ to: '/guarded' }) + + expect(beforeLoad).toHaveBeenCalledTimes(2) + expect(loader).toHaveBeenCalledTimes(2) + expect(loader.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(shouldReload).toHaveBeenCalledTimes(1) + expect(shouldReload).toHaveBeenCalledWith( + expect.objectContaining({ + context: expect.objectContaining({ guard: 'loaded' }), + preload: false, + }), + ) + }) + + test('shouldReload false does not keep stale beforeLoad context', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + guard: preload ? 'preloaded' : 'loaded', + })) + const loader = vi.fn(({ preload }: { preload: boolean }) => preload) + const shouldReload = vi.fn(() => false) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + staleTime: Infinity, + preloadStaleTime: 100, + beforeLoad, + shouldReload, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/guarded' }) + vi.setSystemTime(1_100) + await router.navigate({ to: '/guarded' }) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(loader.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + ]) + expect(shouldReload).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.context).toEqual({ guard: 'loaded' }) + }) + + test.each([false, true])( + 'a beforeLoad failure clears context from the previous generation with isServer=%s', + async (isServer) => { + const failure = new Error('guard failed') + let fail = false + const rootRoute = new BaseRootRoute({}) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + context: () => ({ routeContext: true }), + beforeLoad: () => { + if (fail) { + throw failure + } + return { guard: 'accepted' } + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/guarded'] }), + isServer, + }) + + await router.load() + expect(router.state.matches.at(-1)?.context).toEqual({ + routeContext: true, + guard: 'accepted', + }) + + fail = true + if (isServer) { + const response = await loadServerResponse(router, '/guarded') + expect(response.status).toBe(500) + } else { + await router.load() + } + + const failedMatch = router.state.matches.at(-1) + expect(failedMatch).toMatchObject({ + status: 'error', + error: failure, + }) + expect(failedMatch?.context).toEqual({ routeContext: true }) + }, + ) + + test.each([false, true])( + 'a validation failure clears context from the previous generation with isServer=%s', + async (isServer) => { + let fail = false + const rootRoute = new BaseRootRoute({}) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + validateSearch: () => { + if (fail) { + throw new Error('invalid search') + } + return {} + }, + context: () => ({ routeContext: true }), + beforeLoad: () => ({ guard: 'accepted' }), + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/guarded'] }), + isServer, + }) + + await router.load() + expect(router.state.matches.at(-1)?.context).toEqual({ + routeContext: true, + guard: 'accepted', + }) + fail = true + if (isServer) { + const response = await loadServerResponse(router, '/guarded') + expect(response.status).toBe(500) + } else { + await router.load() + } + + const failedMatch = router.state.matches.at(-1) + expect(failedMatch).toMatchObject({ + status: 'error', + }) + expect(failedMatch?.context).toEqual({ routeContext: true }) + }, + ) +}) diff --git a/packages/router-core/tests/preload-navigation-adoption.test.ts b/packages/router-core/tests/preload-navigation-adoption.test.ts new file mode 100644 index 0000000000..058c401f30 --- /dev/null +++ b/packages/router-core/tests/preload-navigation-adoption.test.ts @@ -0,0 +1,221 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +// A navigation that adopts an in-flight preload's loader run must reuse that +// run: it must not abort the preload's loader signal or rerun the loader. This +// is generic router adoption coverage; issue #4476 is covered separately with +// the React Query observer-unmount sequence from its reproduction. +describe('navigation adopting an in-flight preload', () => { + test('adopted preload loader runs once and its signal is not aborted', async () => { + const loaderGate = createControlledPromise() + const loaderStarted = createControlledPromise() + const beforeLoad = vi.fn() + let preloadSignal: AbortSignal | undefined + const loader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + preloadSignal = abortController.signal + loaderStarted.resolve() + return loaderGate + }, + ) + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad, + loader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, fooRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + + // Start the preload and wait until its loader is actually in flight. + const preload = router.preloadRoute({ to: '/foo' }) + await loaderStarted + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + ]) + expect(loader).toHaveBeenCalledTimes(1) + expect(preloadSignal).toBeDefined() + expect(preloadSignal?.aborted).toBe(false) + + // The navigation runs its own guard but shares the loader generation. + const navigation = router.navigate({ to: '/foo' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(loaderGate.status).toBe('pending') + expect(loader).toHaveBeenCalledTimes(1) + expect(preloadSignal?.aborted).toBe(false) + + // Resolve the shared loader and let both settle. + loaderGate.resolve('adopted') + await Promise.all([navigation, preload]) + + // Loader ran exactly once; the adopted run's signal was never aborted. + expect(loader).toHaveBeenCalledTimes(1) + expect(preloadSignal?.aborted).toBe(false) + + // Navigation committed with the adopted loaderData. + const committed = router.state.matches.find( + (match) => match.routeId === fooRoute.id, + ) + expect(committed?.status).toBe('success') + expect(committed?.loaderData).toBe('adopted') + + // Adoption transfers loader-data lifetime ownership to the active match. + // The shared request remains alive while rendered, then aborts on unload. + await router.navigate({ to: '/' }) + expect(preloadSignal?.aborted).toBe(true) + }) + + test('reruns beforeLoad when router context changes during an active preload', async () => { + const loaderGate = createControlledPromise() + const beforeLoad = vi.fn( + ({ + context, + preload, + }: { + context: { auth: boolean } + preload: boolean + }) => ({ authorization: `${context.auth}:${preload}` }), + ) + const loader = vi.fn(() => loaderGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + context: { auth: false }, + }) + + await router.load() + const preload = router.preloadRoute({ to: '/guarded' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + router.update({ ...router.options, context: { auth: true } }) + const navigation = router.navigate({ to: '/guarded' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(loader).toHaveBeenCalledTimes(1) + + loaderGate.resolve('shared') + await Promise.all([preload, navigation]) + expect(router.state.matches.at(-1)?.context).toEqual({ + auth: true, + authorization: 'true:false', + }) + }) + + test('reruns beforeLoad when user location state changes at the same href', async () => { + const loaderGate = createControlledPromise() + const beforeLoad = vi.fn( + ({ location, preload }: { location: any; preload: boolean }) => ({ + authorization: `${location.state.auth}:${preload}`, + }), + ) + const loader = vi.fn(() => loaderGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, guardedRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ + to: '/guarded', + state: { auth: 'old' } as any, + }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + const navigation = router.navigate({ + to: '/guarded', + state: { auth: 'new' } as any, + }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + + expect(beforeLoad.mock.results.map((result) => result.value)).toEqual([ + { authorization: 'old:true' }, + { authorization: 'new:false' }, + ]) + expect(loader).toHaveBeenCalledTimes(1) + + loaderGate.resolve('shared') + await Promise.all([preload, navigation]) + expect(router.state.matches.at(-1)?.context).toMatchObject({ + authorization: 'new:false', + }) + }) + + test('reruns beforeLoad when the route tree changes during an active preload', async () => { + const loaderGate = createControlledPromise() + const beforeLoad = vi.fn() + const loader = vi.fn(() => loaderGate) + const createRouteTree = () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const guardedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/guarded', + beforeLoad, + loader, + }) + return rootRoute.addChildren([indexRoute, guardedRoute]) + } + const router = createTestRouter({ + routeTree: createRouteTree(), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/guarded' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) + + router.update({ ...router.options, routeTree: createRouteTree() }) + const navigation = router.navigate({ to: '/guarded' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + + loaderGate.resolve('shared') + await Promise.all([preload, navigation]) + expect(loader).toHaveBeenCalledOnce() + }) +}) diff --git a/packages/router-core/tests/preload-public-cache-behavior.test.ts b/packages/router-core/tests/preload-public-cache-behavior.test.ts new file mode 100644 index 0000000000..2ad8017ee5 --- /dev/null +++ b/packages/router-core/tests/preload-public-cache-behavior.test.ts @@ -0,0 +1,785 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.restoreAllMocks() + vi.useRealTimers() +}) + +// https://github.com/TanStack/router/issues/2980 +// Repeated child preloads must borrow a stale active parent instead of rerunning +// its loader. +test('#2980: repeated child preloads do not rerun a stale active parent loader', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + + const layoutLoader = vi.fn(() => 'layout data') + const childLoader = vi.fn((childId: string) => `child ${childId}`) + const rootRoute = new BaseRootRoute({}) + const layoutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/layout', + staleTime: 10, + loader: layoutLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '$childId', + loader: ({ params }) => childLoader(params.childId), + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([layoutRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/layout'] }), + }) + + await router.load() + expect(layoutLoader).toHaveBeenCalledTimes(1) + vi.setSystemTime(2_000) + + await router.preloadRoute({ + to: '/layout/$childId', + params: { childId: 'one' }, + }) + expect(layoutLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenNthCalledWith(1, 'one') + + await router.preloadRoute({ + to: '/layout/$childId', + params: { childId: 'two' }, + }) + + expect(layoutLoader).toHaveBeenCalledTimes(1) + expect(childLoader).toHaveBeenCalledTimes(2) + expect(childLoader).toHaveBeenNthCalledWith(2, 'two') +}) + +// Public contract: the public stale/gc options determine whether user loader +// code runs. A read-only preload must not silently shorten a navigation-owned +// cache entry's lifetime. +test('fresh navigation data keeps its gc policy when a preload reuses it', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + + let revision = 0 + const loader = vi.fn(() => ++revision) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + gcTime: 30 * 60_000, + preloadGcTime: 30_000, + preloadStaleTime: 10 * 60_000, + staleTime: Infinity, + loader, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, reportsRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/reports' }) + await router.navigate({ to: '/' }) + expect(loader).toHaveBeenCalledTimes(1) + + vi.setSystemTime(61_000) + await router.preloadRoute({ to: '/reports' }) + await router.navigate({ to: '/other' }) + await router.navigate({ to: '/reports' }) + expect(loader).toHaveBeenCalledTimes(1) + expect( + router.state.matches.find((match) => match.routeId === reportsRoute.id) + ?.loaderData, + ).toBe(1) + + await router.navigate({ to: '/' }) + vi.setSystemTime(1_000 + 31 * 60_000) + await router.navigate({ to: '/other' }) + await router.navigate({ to: '/reports' }) + expect(loader).toHaveBeenCalledTimes(2) + expect( + router.state.matches.find((match) => match.routeId === reportsRoute.id) + ?.loaderData, + ).toBe(2) +}) + +// Public contract: clearCache must remain authoritative even if an older +// preload finishes unrelated asset work after the clear. +test('clearCache during an in-flight preload cannot resurrect its borrowed data', async () => { + const headGate = createControlledPromise<{ + meta: Array<{ title: string }> + }>() + let revision = 0 + let headCalls = 0 + const loader = vi.fn(() => ++revision) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + staleTime: Infinity, + preloadStaleTime: Infinity, + loader, + head: () => { + headCalls++ + return headCalls === 1 ? { meta: [{ title: 'Reports' }] } : headGate + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, reportsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/reports' }) + await router.navigate({ to: '/' }) + expect(loader).toHaveBeenCalledTimes(1) + + const preload = router.preloadRoute({ to: '/reports' }) + await vi.waitFor(() => expect(headCalls).toBe(2)) + expect(headGate.status).toBe('pending') + router.clearCache() + headGate.resolve({ meta: [{ title: 'Preloaded Reports' }] }) + await preload + + await router.navigate({ to: '/reports' }) + expect(loader).toHaveBeenCalledTimes(2) + expect( + router.state.matches.find((match) => match.routeId === reportsRoute.id) + ?.loaderData, + ).toBe(2) +}) + +test('clearCache cancels a brand-new in-flight preload before it can populate the cache', async () => { + const firstLoad = createControlledPromise() + const loader = vi + .fn<() => string | Promise>() + .mockImplementationOnce(() => firstLoad) + .mockReturnValue('navigation data') + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + preloadStaleTime: Infinity, + staleTime: Infinity, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, reportsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/reports' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + router.clearCache() + firstLoad.resolve('obsolete preload data') + await preload + await router.navigate({ to: '/reports' }) + + expect(loader).toHaveBeenCalledTimes(2) + expect( + router.state.matches.find((match) => match.routeId === reportsRoute.id) + ?.loaderData, + ).toBe('navigation data') +}) + +test('clearCache does not reserve a discarded preload for a navigation in beforeLoad', async () => { + const navigationBeforeLoad = createControlledPromise() + let preloadSignal: AbortSignal | undefined + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => + preload ? undefined : navigationBeforeLoad, + ) + const loader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + const generation = loader.mock.calls.length + if (generation !== 1) { + return 'fresh navigation data' + } + preloadSignal = abortController.signal + return new Promise((_resolve, reject) => { + abortController.signal.addEventListener( + 'abort', + () => reject(abortController.signal.reason), + { once: true }, + ) + }) + }, + ) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) + const navigation = router.navigate({ to: '/target' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + + router.clearCache({ + filter: (match) => match.routeId === targetRoute.id, + }) + await vi.waitFor(() => expect(preloadSignal?.aborted).toBe(true)) + await preload + + navigationBeforeLoad.resolve() + await navigation + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.loaderData).toBe('fresh navigation data') +}) + +test('clearCache does not abort loader work still used by a navigation', async () => { + const loaderGate = createControlledPromise() + let loaderSignal: AbortSignal | undefined + const beforeLoad = vi.fn() + const loader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + loaderSignal = abortController.signal + return loaderGate + }, + ) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) + const navigation = router.navigate({ to: '/target' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + + router.clearCache({ + filter: (match) => match.routeId === targetRoute.id, + }) + expect(loaderSignal?.aborted).toBe(false) + + loaderGate.resolve('shared loader data') + await Promise.all([preload, navigation]) + + expect(loader).toHaveBeenCalledOnce() + expect(router.state.matches.at(-1)?.loaderData).toBe('shared loader data') +}) + +test('clearCache leaves cache authority intact when its filter throws', async () => { + let firstSignal: AbortSignal | undefined + let secondSignal: AbortSignal | undefined + const rootRoute = new BaseRootRoute({}) + const firstRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/first', + loader: ({ abortController }) => { + firstSignal = abortController.signal + return 'first data' + }, + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/second', + loader: ({ abortController }) => { + secondSignal = abortController.signal + return 'second data' + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([firstRoute, secondRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/first' }) + await router.preloadRoute({ to: '/second' }) + const filterError = new Error('filter failed') + + expect(() => + router.clearCache({ + filter: (match) => { + if (match.routeId === firstRoute.id) { + return true + } + if (match.routeId === secondRoute.id) { + throw filterError + } + return false + }, + }), + ).toThrow(filterError) + expect(firstSignal?.aborted).toBe(false) + expect(secondSignal?.aborted).toBe(false) + + router.clearCache() + expect(firstSignal?.aborted).toBe(true) + expect(secondSignal?.aborted).toBe(true) +}) + +test('clearCache installs replacement authorities before abort listeners reenter', async () => { + let reentrantNavigation: Promise | undefined + let router: ReturnType + const loader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + const generation = loader.mock.calls.length + if (generation !== 2) { + return `generation ${generation}` + } + return new Promise((_resolve, reject) => { + abortController.signal.addEventListener( + 'abort', + () => { + reentrantNavigation = router.navigate({ to: '/target' }) + reject(abortController.signal.reason) + }, + { once: true }, + ) + }) + }, + ) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + staleTime: Infinity, + preloadStaleTime: 0, + loader, + }) + router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/target' }) + await router.navigate({ to: '/' }) + + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + router.clearCache() + + await reentrantNavigation + await preload + expect(loader).toHaveBeenCalledTimes(3) + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)?.loaderData).toBe('generation 3') +}) + +test('clearCache detaches every discarded flight before abort listeners reenter', async () => { + let reentrantNavigation: Promise | undefined + let router: ReturnType + const firstBeforeLoad = vi.fn( + ({ abortController }: { abortController: AbortController }) => + new Promise((_resolve, reject) => { + abortController.signal.addEventListener( + 'abort', + () => { + reentrantNavigation = router.navigate({ to: '/second' }) + reject(abortController.signal.reason) + }, + { once: true }, + ) + }), + ) + const secondLoader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + const generation = secondLoader.mock.calls.length + if (generation > 1) { + return `generation ${generation}` + } + return new Promise((_resolve, reject) => { + abortController.signal.addEventListener( + 'abort', + () => reject(abortController.signal.reason), + { once: true }, + ) + }) + }, + ) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/first', + beforeLoad: firstBeforeLoad, + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/second', + loader: secondLoader, + }) + router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, firstRoute, secondRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const firstPreload = router.preloadRoute({ to: '/first' }) + await vi.waitFor(() => expect(firstBeforeLoad).toHaveBeenCalledOnce()) + const secondPreload = router.preloadRoute({ to: '/second' }) + await vi.waitFor(() => expect(secondLoader).toHaveBeenCalledOnce()) + + router.clearCache() + + await reentrantNavigation + await Promise.all([firstPreload, secondPreload]) + expect(secondLoader).toHaveBeenCalledTimes(2) + expect(router.state.location.pathname).toBe('/second') + expect(router.state.matches.at(-1)?.loaderData).toBe('generation 2') +}) + +test('filtered clearCache keeps shared loader work discoverable through a retained preload', async () => { + const layoutGate = createControlledPromise() + const layoutLoader = vi.fn(() => layoutGate) + const rootRoute = new BaseRootRoute({}) + const layoutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/layout', + loader: layoutLoader, + }) + const firstBeforeLoad = vi.fn() + const firstRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '/first', + beforeLoad: firstBeforeLoad, + }) + const secondBeforeLoad = vi.fn() + const secondLoader = vi.fn(() => 'second data') + const secondRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '/second', + beforeLoad: secondBeforeLoad, + loader: secondLoader, + }) + const thirdBeforeLoad = vi.fn() + const thirdLoader = vi.fn(() => 'third data') + const thirdRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '/third', + beforeLoad: thirdBeforeLoad, + loader: thirdLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + layoutRoute.addChildren([firstRoute, secondRoute, thirdRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const firstPreload = router.preloadRoute({ to: '/layout/first' }) + const secondPreload = router.preloadRoute({ to: '/layout/second' }) + await vi.waitFor(() => { + expect(firstBeforeLoad).toHaveBeenCalledOnce() + expect(secondBeforeLoad).toHaveBeenCalledOnce() + expect(layoutLoader).toHaveBeenCalledOnce() + expect(secondLoader).toHaveBeenCalledOnce() + }) + + router.clearCache({ + filter: (match) => match.routeId === firstRoute.id, + }) + const thirdPreload = router.preloadRoute({ to: '/layout/third' }) + await vi.waitFor(() => { + expect(thirdBeforeLoad).toHaveBeenCalledOnce() + expect(thirdLoader).toHaveBeenCalledOnce() + }) + + expect(layoutLoader).toHaveBeenCalledOnce() + layoutGate.resolve('layout data') + await Promise.all([firstPreload, secondPreload, thirdPreload]) +}) + +test('independent concurrent preloads both populate the cache', async () => { + const firstGate = createControlledPromise() + const secondGate = createControlledPromise() + const firstLoader = vi.fn(() => firstGate) + const secondLoader = vi.fn(() => secondGate) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/first', + preloadStaleTime: Infinity, + loader: firstLoader, + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/second', + preloadStaleTime: Infinity, + loader: secondLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, firstRoute, secondRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const firstPreload = router.preloadRoute({ to: '/first' }) + const secondPreload = router.preloadRoute({ to: '/second' }) + await vi.waitFor(() => { + expect(firstLoader).toHaveBeenCalledOnce() + expect(secondLoader).toHaveBeenCalledOnce() + }) + + firstGate.resolve('first data') + await firstPreload + secondGate.resolve('second data') + await secondPreload + + await router.navigate({ to: '/first' }) + await router.navigate({ to: '/second' }) + expect(firstLoader).toHaveBeenCalledOnce() + expect(secondLoader).toHaveBeenCalledOnce() +}) + +test.each([ + ['unfiltered', undefined, true], + ['filtered affected', 'target', true], + ['filtered unaffected', 'home', false], +] as const)( + '%s invalidation preserves the correct preload generation', + async (_mode, selected, shouldReload) => { + const oldLoaderGate = createControlledPromise() + let generation = 1 + const loader = vi.fn(() => + loader.mock.calls.length === 1 + ? oldLoaderGate + : `generation ${generation}`, + ) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + preloadStaleTime: Infinity, + staleTime: Infinity, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) + + generation = 2 + await (selected + ? router.invalidate({ + filter: (match) => + match.routeId === + (selected === 'target' ? targetRoute.id : homeRoute.id), + }) + : router.invalidate()) + + oldLoaderGate.resolve('generation 1') + await preload + await router.navigate({ to: '/target' }) + + expect(loader).toHaveBeenCalledTimes(shouldReload ? 2 : 1) + expect(router.state.matches.at(-1)?.loaderData).toBe( + `generation ${shouldReload ? 2 : 1}`, + ) + }, +) + +test('filtering only an active preload invalidates seeded same-ID cache data', async () => { + const replacementGate = createControlledPromise() + const loader = vi.fn(() => { + const generation = loader.mock.calls.length + return generation === 2 ? replacementGate : `generation ${generation}` + }) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + validateSearch: (search: Record) => ({ + revision: Number(search.revision ?? 1), + }), + preloadStaleTime: 0, + staleTime: Infinity, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/target', search: { revision: 1 } }) + await router.navigate({ to: '/' }) + const preload = router.preloadRoute({ + to: '/target', + search: { revision: 2 }, + }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + await router.invalidate({ + filter: (match) => + match.routeId === targetRoute.id && + (match.search as { revision?: number }).revision === 2, + }) + replacementGate.resolve('obsolete generation 2') + await preload + await router.navigate({ to: '/target' }) + + await vi.waitFor(() => { + expect(loader).toHaveBeenCalledTimes(3) + expect(router.state.matches.at(-1)?.loaderData).toBe('generation 3') + }) +}) + +test('invalidation wins after a preload loader settles but before it publishes', async () => { + let invalidation: Promise | undefined + let generation = 0 + let router: ReturnType + const loader = vi.fn(() => { + const data = `generation ${++generation}` + if (generation === 1) { + // Schedule invalidation after the loader outcome has fulfilled while the + // preload lane's cache publication is still queued. + let turn = Promise.resolve() + for (let index = 0; index < 4; index++) { + turn = turn.then() + } + invalidation = turn.then(() => router.invalidate()) + } + return data + }) + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + preloadStaleTime: Infinity, + staleTime: Infinity, + loader, + }) + router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(invalidation).toBeDefined()) + await invalidation + await preload + await router.navigate({ to: '/target' }) + + await vi.waitFor(() => { + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.loaderData).toBe('generation 2') + }) +}) + +// Preload lanes are not cancelled by unrelated navigations: an in-flight +// async beforeLoad runs to completion, its loader still executes and seeds +// the cache, and a later navigation to the target reuses that work. +test('an unrelated navigation does not cancel an in-flight preload beforeLoad', async () => { + const beforeLoadGate = createControlledPromise<{ token: string }>() + const beforeLoad = vi.fn(() => beforeLoadGate) + const loader = vi.fn(() => 'target data') + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + preloadStaleTime: Infinity, + staleTime: Infinity, + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, otherRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) + + // Unrelated navigation commits while the preload's beforeLoad is pending. + await router.navigate({ to: '/other' }) + expect(router.state.location.pathname).toBe('/other') + + beforeLoadGate.resolve({ token: 'ctx' }) + await preload + // The preload completed its work despite the navigation. + expect(loader).toHaveBeenCalledTimes(1) + + // Navigating to the target consumes the seeded cache without a new load. + await router.navigate({ to: '/target' }) + expect(router.state.location.pathname).toBe('/target') + expect( + router.state.matches.find((match) => match.routeId === targetRoute.id) + ?.loaderData, + ).toBe('target data') + expect(loader).toHaveBeenCalledTimes(1) +}) diff --git a/packages/router-core/tests/preload-public-signal-lifetime.test.ts b/packages/router-core/tests/preload-public-signal-lifetime.test.ts new file mode 100644 index 0000000000..b884a3b9ad --- /dev/null +++ b/packages/router-core/tests/preload-public-signal-lifetime.test.ts @@ -0,0 +1,155 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +// Public contract: the AbortSignal supplied to loader code belongs to the +// accepted data generation. Adopting preloaded data keeps it alive; accepting +// replacement data aborts it; unloading aborts the replacement generation. +test('an adopted loader signal lives until public replacement and unload', async () => { + const replacementGate = createControlledPromise<{ generation: number }>() + let generation = 0 + let adoptedSignal: AbortSignal | undefined + let replacementSignal: AbortSignal | undefined + const loader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + generation++ + if (generation === 1) { + adoptedSignal = abortController.signal + return { generation } + } + + replacementSignal = abortController.signal + return replacementGate + }, + ) + + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + staleTime: Infinity, + preloadStaleTime: Infinity, + loader: { + staleReloadMode: 'blocking', + handler: loader, + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, reportsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/reports' }) + expect(adoptedSignal?.aborted).toBe(false) + + await router.navigate({ to: '/reports' }) + expect(loader).toHaveBeenCalledTimes(1) + expect( + router.state.matches.find((match) => match.routeId === reportsRoute.id) + ?.loaderData, + ).toEqual({ generation: 1 }) + expect(adoptedSignal?.aborted).toBe(false) + + const replacement = router.invalidate({ forcePending: true }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + expect(replacementGate.status).toBe('pending') + + // Until replacement data is accepted, the currently rendered data still + // owns the adopted signal. + expect(adoptedSignal?.aborted).toBe(false) + expect(replacementSignal?.aborted).toBe(false) + + replacementGate.resolve({ generation: 2 }) + await replacement + expect( + router.state.matches.find((match) => match.routeId === reportsRoute.id) + ?.loaderData, + ).toEqual({ generation: 2 }) + expect(adoptedSignal?.aborted).toBe(true) + expect(replacementSignal?.aborted).toBe(false) + + await router.navigate({ to: '/' }) + expect(replacementSignal?.aborted).toBe(true) +}) + +test('a superseded preload releases its borrowed loader signal lease', async () => { + let parentSignal: AbortSignal | undefined + let navigation!: Promise + + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: ({ abortController }) => { + parentSignal = abortController.signal + return 'parent data' + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: ({ navigate, preload }) => { + if (preload) { + navigation = navigate({ to: '/' }) + throw navigation + } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + homeRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent'] }), + }) + + await router.load() + expect(parentSignal?.aborted).toBe(false) + + await router.preloadRoute({ to: '/parent/child' }) + await navigation + + expect(router.state.location.pathname).toBe('/') + expect(parentSignal?.aborted).toBe(true) +}) + +test('a terminal preload aborts its loader generation', async () => { + const routeError = new Error('preload failed') + let signal: AbortSignal | undefined + + const rootRoute = new BaseRootRoute({}) + const homeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + loader: ({ abortController }) => { + signal = abortController.signal + throw routeError + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([homeRoute, reportsRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const matches = await router.preloadRoute({ to: '/reports' }) + + expect( + matches?.find((match) => match.routeId === reportsRoute.id), + ).toMatchObject({ status: 'error', error: routeError }) + expect(signal?.aborted).toBe(true) +}) diff --git a/packages/router-core/tests/public-client-loading-contract.test.ts b/packages/router-core/tests/public-client-loading-contract.test.ts new file mode 100644 index 0000000000..169f9e89dc --- /dev/null +++ b/packages/router-core/tests/public-client-loading-contract.test.ts @@ -0,0 +1,768 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + redirect, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('public client loading contracts', () => { + test('blocking loading is observable through match isFetching', async () => { + const loaderGate = createControlledPromise() + const loader = vi.fn(() => loaderGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + pendingMs: 0, + pendingComponent: () => null, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const navigation = router.navigate({ to: '/target' }) + + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => + expect( + router.state.matches.find((match) => match.routeId === targetRoute.id), + ).toMatchObject({ status: 'pending', isFetching: 'loader' }), + ) + + loaderGate.resolve('target data') + await navigation + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + isFetching: false, + loaderData: 'target data', + }) + }) + + test('a successor retains committed UI until its pending context is ready', async () => { + const initialPublished = createControlledPromise() + const initialRenderAck = createControlledPromise() + const successorStarted = createControlledPromise() + const successorLoader = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const initialRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const successorRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/successor', + context: () => ({ destinationContext: 'ready' }), + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () => null, + loader: () => { + successorStarted.resolve() + return successorLoader + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([initialRoute, successorRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const startTransition = router.startTransition + let waitForInitialRender = true + router.startTransition = (fn, expected) => { + fn() + if ( + waitForInitialRender && + expected?.at(-1)?.routeId === initialRoute.id && + expected.at(-1)?.status === 'success' + ) { + waitForInitialRender = false + initialPublished.resolve() + return initialRenderAck + } + return Promise.resolve(true) + } + + const initialLoad = router.load() + let navigation: Promise | undefined + try { + await initialPublished + expect(router._committed.at(-1)?.routeId).toBe(initialRoute.id) + expect(router.state.resolvedLocation).toBeUndefined() + expect(initialRenderAck.status).toBe('pending') + + navigation = router.navigate({ to: '/successor' }) + await successorStarted + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: successorRoute.id, + status: 'pending', + context: { destinationContext: 'ready' }, + }) + + successorLoader.resolve('successor data') + initialRenderAck.resolve(true) + await Promise.all([initialLoad, navigation]) + } finally { + successorLoader.resolve('successor data') + initialRenderAck.resolve(true) + await Promise.allSettled([initialLoad, navigation]) + router.startTransition = startTransition + } + }) + + test('background loading is observable while retaining committed data', async () => { + const reloadGate = createControlledPromise<{ generation: number }>() + let loaderCalls = 0 + const loader = vi.fn(() => + ++loaderCalls === 1 ? { generation: 1 } : reloadGate, + ) + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + staleTime: Infinity, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + const invalidation = router.invalidate() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'success', + isFetching: 'loader', + loaderData: { generation: 1 }, + }) + + reloadGate.resolve({ generation: 2 }) + await invalidation + await vi.waitFor(() => + expect(router.state.matches.at(-1)).toMatchObject({ + status: 'success', + isFetching: false, + loaderData: { generation: 2 }, + }), + ) + }) + + test('a successor does not fall back to older data while a background reload is in flight', async () => { + const backgroundResult = createControlledPromise() + const successorPlanned = createControlledPromise() + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls++ + if (loaderCalls === 1) { + return 'cached data' + } + if (loaderCalls === 2) { + return backgroundResult + } + return 'updated data' + }) + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + validateSearch: (search: Record) => ({ + phase: String(search.phase ?? 'initial'), + }), + shouldReload: ({ location }) => { + const phase = (location.search as { phase: string }).phase + if (phase === 'successor') { + successorPlanned.resolve() + } + return phase === 'reload' ? true : undefined + }, + staleTime: Infinity, + loader: { + staleReloadMode: 'background', + handler: loader, + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ + initialEntries: ['/page?phase=initial'], + }), + }) + + await router.load() + await router.navigate({ + to: '/page', + search: { phase: 'reload' }, + }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + const successor = router.navigate({ + to: '/page', + search: { phase: 'successor' }, + }) + await successorPlanned + backgroundResult.resolve('updated data') + await successor + + await vi.waitFor(() => { + expect(router.state.matches.at(-1)?.loaderData).toBe('updated data') + }) + }) + + test('a background loader can fulfill after aborting its controller', async () => { + let loaderCalls = 0 + const loader = vi.fn(({ abortController }) => { + loaderCalls++ + if (loaderCalls === 1) { + return { generation: 1 } + } + abortController.abort() + return { generation: 2 } + }) + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + staleTime: Infinity, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + await router.invalidate() + + expect(loader).toHaveBeenCalledTimes(2) + await vi.waitFor(() => + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'success', + isFetching: false, + loaderData: { generation: 2 }, + }), + ) + expect(router.state.status).toBe('idle') + }) + + test('a current loader can fulfill after aborting its controller', async () => { + const loader = vi.fn(({ abortController }) => { + abortController.abort() + return 'accepted data' + }) + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + staleTime: Infinity, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + await router.load() + + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.status).toBe('idle') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'success', + loaderData: 'accepted data', + }) + }) + + test('background redirects use the navigation redirect limit', async () => { + let loaderCalls = 0 + const loader = vi.fn(() => { + loaderCalls++ + if (loaderCalls === 1) { + return 'initial data' + } + if (loaderCalls < 30) { + throw redirect({ to: '/page' }) + } + return 'redirect limit was bypassed' + }) + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + shouldReload: true, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + await router.invalidate() + + expect(loader).toHaveBeenCalledTimes(22) + await vi.waitFor(() => + expect( + router.state.matches.find((match) => match.status !== 'success'), + ).toMatchObject({ + routeId: rootRoute.id, + status: 'error', + error: expect.objectContaining({ message: 'Too many redirects' }), + }), + ) + }) + + test('a blocking child observes the fresh semantic parent generation', async () => { + const parentReload = createControlledPromise<{ revision: number }>() + let parentCalls = 0 + const parentLoader = vi.fn(() => + ++parentCalls === 1 ? { revision: 1 } : parentReload, + ) + const childLoader = vi.fn(async ({ parentMatchPromise }) => { + const parent = await parentMatchPromise + return { + parentRevision: (parent.loaderData as { revision: number }).revision, + } + }) + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + staleTime: Infinity, + shouldReload: true, + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: { + staleReloadMode: 'blocking', + handler: childLoader, + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent'] }), + }) + + await router.load() + + let settled = false + const navigation = router.navigate({ to: '/parent/child' }).then(() => { + settled = true + }) + await vi.waitFor(() => expect(parentLoader).toHaveBeenCalledTimes(2)) + + expect(parentReload.status).toBe('pending') + expect(settled).toBe(false) + + parentReload.resolve({ revision: 2 }) + await navigation + + await vi.waitFor(() => + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ loaderData: { revision: 2 } }), + ) + expect( + router.state.matches.find((match) => match.routeId === childRoute.id), + ).toMatchObject({ loaderData: { parentRevision: 2 } }) + }) + + test('a background descendant redirect wins after a blocking ancestor loader fails', async () => { + const childStarted = createControlledPromise() + const childRedirect = createControlledPromise() + const parentError = new Error('parent failed') + let parentLoads = 0 + let childLoads = 0 + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: { + staleReloadMode: 'blocking', + handler: async () => { + if (++parentLoads === 1) { + return 'parent data' + } + await childStarted + throw parentError + }, + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + if (++childLoads === 1) { + return 'child data' + } + childStarted.resolve() + await childRedirect + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + const invalidation = router.invalidate() + await childStarted + childRedirect.resolve() + await invalidation + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + expect( + router.state.matches.some((match) => match.error === parentError), + ).toBe(false) + }) + + test('a hidden background descendant failure cannot replace an ancestor failure', async () => { + const childStarted = createControlledPromise() + const parentError = new Error('parent failed') + const childError = new Error('child failed') + let parentLoads = 0 + let childLoads = 0 + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: { + staleReloadMode: 'blocking', + handler: async () => { + if (++parentLoads === 1) { + return 'parent data' + } + await childStarted + throw parentError + }, + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => { + if (++childLoads === 1) { + return 'child data' + } + childStarted.resolve() + throw childError + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + await router.invalidate() + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ status: 'error', error: parentError }) + expect( + router.state.matches.find((match) => match.routeId === childRoute.id), + ).toMatchObject({ + status: 'success', + error: undefined, + isFetching: false, + loaderData: 'child data', + }) + expect( + router.state.matches.some((match) => match.error === childError), + ).toBe(false) + }) + + test('background projection stays private until its lane wins publication', async () => { + const reloadGate = createControlledPromise<{ title: string }>() + const headGate = createControlledPromise() + const freshHeadStarted = createControlledPromise() + let loaderCalls = 0 + let allowReload = true + const loader = vi.fn(() => + ++loaderCalls === 1 ? { title: 'old' } : reloadGate, + ) + const head = vi.fn(async ({ loaderData }) => { + if (loaderData?.title === 'fresh') { + freshHeadStarted.resolve() + await headGate + } + return { meta: [{ title: loaderData?.title }] } + }) + + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + staleTime: Infinity, + shouldReload: () => allowReload, + loader, + head, + }) + const otherRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/other', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + allowReload = false + await router.load() + expect(router.state.matches.at(-1)).toMatchObject({ + loaderData: { title: 'old' }, + meta: [{ title: 'old' }], + }) + + allowReload = true + const invalidation = router.invalidate() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + reloadGate.resolve({ title: 'fresh' }) + await freshHeadStarted + + expect(router.state.matches.at(-1)).toMatchObject({ + loaderData: { title: 'old' }, + meta: [{ title: 'old' }], + }) + + await router.navigate({ to: '/other' }) + allowReload = false + headGate.resolve() + await invalidation + await Promise.resolve() + + await router.navigate({ to: '/page' }) + expect(router.state.matches.at(-1)).toMatchObject({ + loaderData: { title: 'old' }, + meta: [{ title: 'old' }], + isFetching: false, + }) + }) + + test('redirect depth bookkeeping is cleared after a redirect chain settles', async () => { + const hopBeforeLoad = vi.fn(({ params }) => { + const hop = Number(params.hop) + if (hop < 20) { + throw redirect({ + to: '/hop/$hop', + params: { hop: String(hop + 1) }, + } as any) + } + }) + const rootRoute = new BaseRootRoute({}) + const hopRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/hop/$hop', + beforeLoad: hopBeforeLoad, + }) + const againRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/again', + beforeLoad: () => { + throw redirect({ to: '/final' }) + }, + }) + const finalRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/final', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([hopRoute, againRoute, finalRoute]), + history: createMemoryHistory({ initialEntries: ['/hop/0'] }), + }) + + await router.load() + expect(router.state.location.pathname).toBe('/hop/20') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: hopRoute.id, + status: 'success', + }) + + await router.navigate({ to: '/again' }) + expect(router.state.location.pathname).toBe('/final') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: finalRoute.id, + status: 'success', + }) + expect(router.state.status).toBe('idle') + }) + + test('a redirect-limit error aborts concurrent work in its final lane', async () => { + const finalRootAborted = createControlledPromise() + const finalRootData = createControlledPromise() + const errorComponentStarted = createControlledPromise() + const errorComponentGate = createControlledPromise() + let finalRootSignal: AbortSignal | undefined + const ErrorComponent = Object.assign(() => null, { + preload: () => { + errorComponentStarted.resolve() + return errorComponentGate + }, + }) + + const rootRoute = new BaseRootRoute({ + errorComponent: ErrorComponent as any, + loader: ({ location, abortController }) => { + if (location.pathname !== '/hop/20/child') { + return 'root data' + } + finalRootSignal = abortController.signal + finalRootSignal.addEventListener( + 'abort', + () => finalRootAborted.resolve(), + { once: true }, + ) + return finalRootData + }, + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/hop/$hop', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: ({ params }) => { + throw redirect({ + to: '/hop/$hop/child', + params: { hop: String(Number(params.hop) + 1) }, + } as any) + }, + }) + const cleanupRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/cleanup', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + cleanupRoute, + ]), + history: createMemoryHistory({ + initialEntries: ['/hop/0/child'], + }), + }) + const loading = router.load() + + try { + await errorComponentStarted + expect(finalRootData.status).toBe('pending') + errorComponentGate.resolve() + await finalRootAborted + await expect(loading).resolves.toBeUndefined() + + expect(router.state.location.pathname).toBe('/hop/20/child') + const firstTerminalMatch = router.state.matches.find( + (match) => match.status !== 'success', + ) + expect(firstTerminalMatch).toMatchObject({ + routeId: rootRoute.id, + status: 'error', + isFetching: false, + error: expect.objectContaining({ message: 'Too many redirects' }), + }) + expect(finalRootData.status).toBe('pending') + expect(finalRootSignal?.aborted).toBe(true) + expect( + router.state.matches.every((match) => match.isFetching === false), + ).toBe(true) + expect(router.state.status).toBe('idle') + expect(router.state.isLoading).toBe(false) + } finally { + finalRootData.resolve('late root data') + errorComponentGate.resolve() + await Promise.allSettled([loading]) + } + + await router.navigate({ to: '/cleanup' }) + expect(router.state.location.pathname).toBe('/cleanup') + expect( + router.state.matches.every((match) => match.status === 'success'), + ).toBe(true) + expect(router.state.status).toBe('idle') + }) + + test('a redirect is not blocked by an abort-ignoring sibling loader', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => new Promise(() => {}), + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => { + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.navigate({ to: '/source/child' }) + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + }) +}) diff --git a/packages/router-core/tests/public-hydration-contract.test.ts b/packages/router-core/tests/public-hydration-contract.test.ts new file mode 100644 index 0000000000..aea458b3f5 --- /dev/null +++ b/packages/router-core/tests/public-hydration-contract.test.ts @@ -0,0 +1,1607 @@ +import { + afterEach, + beforeEach, + describe, + expect, + onTestFinished, + test, + vi, +} from 'vitest' +import { createBrowserHistory, createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + redirect, +} from '../src' +import { hydrate } from '../src/ssr/client' +import { dehydrateSsrMatchId } from '../src/ssr/ssr-match-id' +import { createTestRouter, dehydrateToBootstrap } from './routerTestUtils' +import type { AnyRouteMatch, LocationRewrite } from '../src' +import type { DehydratedRouter, TsrSsrGlobal } from '../src/ssr/types' +import type { ServerManifest } from '../src/manifest' + +const testManifest: ServerManifest = { routes: {} } +const browserWindow = window + +function installHydrationPayload( + mockWindow: { $_TSR?: TsrSsrGlobal }, + matches: DehydratedRouter['matches'], +) { + mockWindow.$_TSR = { + router: { + manifest: testManifest, + dehydratedData: {}, + matches, + }, + h() {}, + e() {}, + c() {}, + p() {}, + buffer: [], + } +} + +describe('public hydration contracts', () => { + let mockWindow: { $_TSR?: TsrSsrGlobal } + + beforeEach(() => { + mockWindow = {} + vi.stubGlobal('window', mockWindow) + }) + + afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() + }) + + test('starts head and scripts together and swallows a head failure', async () => { + const error = new Error('head failed') + const headGate = createControlledPromise() + const head = vi.fn(async () => { + await headGate + throw error + }) + const scripts = vi.fn(() => [ + { children: 'window.hydrationScriptRan = true' }, + ]) + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => undefined) + + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + head, + scripts, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload( + mockWindow, + matches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success' as const, + ssr: true, + u: Date.now(), + })), + ) + + const hydration = hydrate(router) + await vi.waitFor(() => { + expect(head).toHaveBeenCalledTimes(1) + expect(scripts).toHaveBeenCalledTimes(1) + }) + + headGate.resolve() + await expect(hydration).resolves.toBeUndefined() + + expect(consoleError).toHaveBeenCalledWith(error) + expect(router.state.resolvedLocation?.pathname).toBe('/page') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'success', + }) + }) + + test('adopts a shorter selective-SSR prefix ending at a pending client-only match', async () => { + const serverLoader = vi.fn(() => 'server data') + const serverRootRoute = new BaseRootRoute({}) + const serverClientOnlyRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/client-only', + ssr: false, + loader: serverLoader, + }) + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverClientOnlyRoute, + path: '/child', + ssr: true, + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverClientOnlyRoute.addChildren([serverChildRoute]), + ]), + history: createMemoryHistory({ + initialEntries: ['/client-only/child'], + }), + isServer: true, + }) + const bootstrap = await dehydrateToBootstrap(serverRouter, testManifest) + expect(bootstrap.router?.matches).toHaveLength(2) + expect(bootstrap.router?.matches.at(-1)).toMatchObject({ + s: 'pending', + ssr: false, + }) + expect(serverLoader).not.toHaveBeenCalled() + + const routeContext = vi.fn(() => ({ routeContext: true })) + const beforeLoad = vi.fn(() => ({ clientContext: true })) + const loader = vi.fn( + ({ context }) => context.clientContext && context.routeContext, + ) + const rootRoute = new BaseRootRoute({}) + const clientOnlyRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/client-only', + ssr: false, + context: routeContext, + beforeLoad, + loader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => clientOnlyRoute, + path: '/child', + ssr: true, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + clientOnlyRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ + initialEntries: ['/client-only/child'], + }), + isServer: false, + }) + mockWindow.$_TSR = bootstrap + + await hydrate(router) + + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + clientOnlyRoute.id, + childRoute.id, + ]) + expect(router.state.matches.slice(1)).toMatchObject([ + { routeId: clientOnlyRoute.id, status: 'pending', ssr: false }, + { routeId: childRoute.id, ssr: true }, + ]) + expect(router.state.resolvedLocation).toBeUndefined() + expect(router.state.matches[1]?.context).toEqual({ routeContext: true }) + expect(routeContext).toHaveBeenCalledTimes(1) + expect(beforeLoad).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + + await router.load() + + expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(loader).toHaveBeenCalledTimes(1) + expect(routeContext).toHaveBeenCalledTimes(1) + expect(router.state.matches[1]).toMatchObject({ + routeId: clientOnlyRoute.id, + status: 'success', + loaderData: true, + }) + expect(router.state.resolvedLocation?.href).toBe('/client-only/child') + }) + + test('selective SSR exposes the complete accepted lane to route context and head hooks', async () => { + const serverRootRoute = new BaseRootRoute({}) + const serverClientOnlyRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/client-only', + ssr: false, + }) + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverClientOnlyRoute, + path: '/child', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverClientOnlyRoute.addChildren([serverChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/client-only/child'] }), + isServer: true, + }) + const bootstrap = await dehydrateToBootstrap(serverRouter, testManifest) + + const contextLanes: Array> = [] + const headLanes: Array> = [] + const rootRoute = new BaseRootRoute({ + context: ({ matches }) => { + contextLanes.push(matches.map((match) => match.routeId)) + return { hydrated: true } + }, + head: ({ matches }) => { + headLanes.push(matches.map((match) => match.routeId)) + return { + meta: [ + { + title: String(matches[1]?.loaderData), + }, + ], + } + }, + }) + const clientOnlyRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/client-only', + ssr: false, + loader: () => 'client data', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => clientOnlyRoute, + path: '/child', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + clientOnlyRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/client-only/child'] }), + isServer: false, + }) + mockWindow.$_TSR = bootstrap + + await hydrate(router) + + const fullLane = [rootRoute.id, clientOnlyRoute.id, childRoute.id] + expect(contextLanes).toEqual([fullLane]) + expect(headLanes).toEqual([fullLane]) + expect(router.state.matches.map((match) => match.routeId)).toEqual(fullLane) + expect(router.state.matches[0]?.context).toMatchObject({ hydrated: true }) + expect(router.state.matches[0]?.meta).toEqual([{ title: 'undefined' }]) + + await router.load() + + expect(router.state.matches[0]?.meta).toEqual([{ title: 'client data' }]) + }) + + test('shell hydration exposes the complete accepted lane to route context and head hooks', async () => { + const contextLanes: Array> = [] + const headLanes: Array> = [] + const rootRoute = new BaseRootRoute({ + context: ({ matches }) => { + contextLanes.push(matches.map((match) => match.routeId)) + return { hydrated: true } + }, + head: ({ matches }) => { + headLanes.push(matches.map((match) => match.routeId)) + return { meta: [{ title: 'Shell hydration' }] } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + ssr: false, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + ssr: true, + u: Date.now(), + }, + ]) + + await hydrate(router) + + const fullLane = [rootRoute.id, childRoute.id] + expect(contextLanes).toEqual([fullLane]) + expect(headLanes).toEqual([fullLane]) + expect(router.state.matches.map((match) => match.routeId)).toEqual(fullLane) + expect(router.state.matches[0]?.context).toMatchObject({ hydrated: true }) + expect(router.state.matches[0]?.meta).toEqual([ + { title: 'Shell hydration' }, + ]) + }) + + test('terminal hydration exposes the full structural lane to route context and head hooks', async () => { + const contextLanes: Array> = [] + const headLanes: Array> = [] + const observeContext = ({ matches }: { matches: Array }) => { + contextLanes.push(matches.map((match) => match.routeId)) + return {} + } + const observeHead = ({ matches }: { matches: Array }) => { + headLanes.push(matches.map((match) => match.routeId)) + return { meta: [{ title: 'Terminal hydration' }] } + } + const rootRoute = new BaseRootRoute({ + context: observeContext, + head: observeHead, + }) + const boundaryRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/app', + context: observeContext, + head: observeHead, + errorComponent: () => 'App error', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => boundaryRoute, + path: '/child', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + boundaryRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/app/child'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'error', + e: new Error('App failed on the server'), + ssr: true, + u: Date.now(), + }, + ]) + + await hydrate(router) + + const fullLane = [rootRoute.id, boundaryRoute.id, childRoute.id] + expect(contextLanes).toEqual([fullLane, fullLane]) + expect(headLanes).toEqual([fullLane, fullLane]) + expect(router.state.matches.map((match) => match.routeId)).toEqual(fullLane) + expect(router.state.matches[1]).toMatchObject({ + routeId: boundaryRoute.id, + status: 'error', + }) + expect(router.state.matches[2]?.status).toBe('success') + }) + + test('does not cache missing loader data when retrying a hydrated terminal boundary', async () => { + const serverError = new Error('Server boundary failed') + const chunkError = new Error('Boundary chunk failed during hydration') + const errorComponentPreload = vi + .fn<() => Promise>() + .mockRejectedValueOnce(chunkError) + .mockResolvedValue(undefined) + const ErrorComponent = Object.assign(() => 'App error', { + preload: errorComponentPreload, + }) + const beforeLoad = vi.fn() + const loader = vi.fn(() => 'client data') + const rootRoute = new BaseRootRoute({}) + const boundaryRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/app', + beforeLoad, + loader, + errorComponent: ErrorComponent, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => boundaryRoute, + path: '/child', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + boundaryRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/app/child'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'error', + e: serverError, + ssr: true, + u: Date.now(), + }, + ]) + + await hydrate(router) + + expect(errorComponentPreload).toHaveBeenCalledTimes(1) + expect(beforeLoad).not.toHaveBeenCalled() + expect(router.state.resolvedLocation).toBeUndefined() + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + boundaryRoute.id, + childRoute.id, + ]) + expect(router.state.matches[1]).toMatchObject({ + status: 'error', + error: serverError, + }) + + await router.load() + + expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.resolvedLocation?.href).toBe('/app/child') + expect(router.state.matches[1]).toMatchObject({ + status: 'success', + error: undefined, + loaderData: 'client data', + }) + }) + + test('retries a terminal lane after ancestor context reconstruction fails', async () => { + const serverError = new Error('Server boundary failed') + const clientError = new Error('Client boundary failed') + const contextError = new Error('Root context failed during hydration') + const context = vi + .fn<() => { clientContext: true }>() + .mockImplementationOnce(() => { + throw contextError + }) + .mockReturnValue({ clientContext: true }) + const beforeLoad = vi.fn(() => { + throw clientError + }) + const rootRoute = new BaseRootRoute({ context }) + const boundaryRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/app', + beforeLoad, + errorComponent: () => 'App error', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => boundaryRoute, + path: '/child', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + boundaryRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/app/child'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'error', + e: serverError, + ssr: true, + u: Date.now(), + }, + ]) + + await hydrate(router) + + expect(context).toHaveBeenCalledTimes(1) + expect(beforeLoad).not.toHaveBeenCalled() + expect(router.state.resolvedLocation).toBeUndefined() + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + boundaryRoute.id, + childRoute.id, + ]) + expect(router.state.matches[1]).toMatchObject({ + status: 'error', + error: serverError, + }) + + await router.load() + + expect(context).toHaveBeenCalledTimes(2) + expect(beforeLoad).toHaveBeenCalledTimes(1) + expect(router.state.resolvedLocation?.href).toBe('/app/child') + expect(router.state.matches[0]?.context).toMatchObject({ + clientContext: true, + }) + expect(router.state.matches[1]).toMatchObject({ + status: 'error', + error: clientError, + }) + }) + + test('does not repeat data-only assets during client continuation', async () => { + const serverRootRoute = new BaseRootRoute({}) + const serverPageRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/page', + ssr: 'data-only', + loader: () => 'server data', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([serverPageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: true, + }) + const bootstrap = await dehydrateToBootstrap(serverRouter, testManifest) + + const head = vi.fn(({ loaderData }) => ({ + meta: [{ title: String(loaderData) }], + })) + const scripts = vi.fn(({ loaderData }) => [ + { children: `window.pageData = ${JSON.stringify(loaderData)}` }, + ]) + const loader = vi.fn(() => 'client data') + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + ssr: 'data-only', + loader, + head, + scripts, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + mockWindow.$_TSR = bootstrap + + await hydrate(router) + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'pending', + loaderData: 'server data', + meta: [{ title: 'server data' }], + scripts: [{ children: 'window.pageData = "server data"' }], + }) + expect(head).toHaveBeenCalledTimes(1) + expect(scripts).toHaveBeenCalledTimes(1) + expect(loader).not.toHaveBeenCalled() + + await router.load() + + expect(router.state.resolvedLocation?.pathname).toBe('/page') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'success', + loaderData: 'server data', + meta: [{ title: 'server data' }], + scripts: [{ children: 'window.pageData = "server data"' }], + }) + expect(head).toHaveBeenCalledTimes(1) + expect(scripts).toHaveBeenCalledTimes(1) + expect(loader).not.toHaveBeenCalled() + }) + + test('adopts the complete nested data-only server prefix', async () => { + const serverParentBeforeLoad = vi.fn(() => ({ source: 'server' })) + const serverParentLoader = vi.fn(() => 'server parent') + const serverChildBeforeLoad = vi.fn() + const serverChildLoader = vi.fn(() => 'server child') + const serverRootRoute = new BaseRootRoute({}) + const serverParentRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/parent', + ssr: 'data-only', + beforeLoad: serverParentBeforeLoad, + loader: serverParentLoader, + }) + const serverChildRoute = new BaseRoute({ + getParentRoute: () => serverParentRoute, + path: '/child', + beforeLoad: serverChildBeforeLoad, + loader: serverChildLoader, + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([ + serverParentRoute.addChildren([serverChildRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + const bootstrap = await dehydrateToBootstrap(serverRouter, testManifest) + + expect(serverParentBeforeLoad).toHaveBeenCalledTimes(1) + expect(serverChildBeforeLoad).toHaveBeenCalledTimes(1) + expect(serverParentLoader).toHaveBeenCalledTimes(1) + expect(serverChildLoader).toHaveBeenCalledTimes(1) + + const parentBeforeLoad = vi.fn(() => ({ source: 'client' })) + const parentLoader = vi.fn(() => 'client parent') + const childBeforeLoad = vi.fn() + const childLoader = vi.fn(() => 'client child') + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + ssr: 'data-only', + beforeLoad: parentBeforeLoad, + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: childBeforeLoad, + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: false, + }) + mockWindow.$_TSR = bootstrap + + await hydrate(router) + + expect(router.state.matches[1]).toMatchObject({ + routeId: parentRoute.id, + status: 'pending', + loaderData: 'server parent', + }) + expect(router.state.matches[2]).toMatchObject({ + routeId: childRoute.id, + status: 'success', + loaderData: 'server child', + }) + expect(parentBeforeLoad).not.toHaveBeenCalled() + expect(childBeforeLoad).not.toHaveBeenCalled() + expect(parentLoader).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + + await router.load() + + expect(router.state.resolvedLocation?.pathname).toBe('/parent/child') + expect(router.state.matches[1]).toMatchObject({ + status: 'success', + context: { source: 'server' }, + loaderData: 'server parent', + }) + expect(router.state.matches[2]).toMatchObject({ + status: 'success', + loaderData: 'server child', + }) + expect(parentBeforeLoad).not.toHaveBeenCalled() + expect(childBeforeLoad).not.toHaveBeenCalled() + expect(parentLoader).not.toHaveBeenCalled() + expect(childLoader).not.toHaveBeenCalled() + }) + + test('keeps an ssr-false route-context error authoritative', async () => { + const serverError = new Error('server route context failed') + const serverRootRoute = new BaseRootRoute({}) + const serverPageRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/page', + ssr: false, + context: () => { + throw serverError + }, + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([serverPageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: true, + }) + const bootstrap = await dehydrateToBootstrap(serverRouter, testManifest) + const transportedError = bootstrap.router?.matches.at(-1)?.e + + expect(transportedError).toMatchObject({ + name: serverError.name, + message: serverError.message, + }) + + const context = vi.fn(() => ({ source: 'client' })) + const beforeLoad = vi.fn() + const loader = vi.fn() + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + ssr: false, + context, + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + mockWindow.$_TSR = bootstrap + + await hydrate(router) + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'pending', + error: transportedError, + }) + expect(context).toHaveBeenCalledTimes(1) + expect(beforeLoad).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + + await router.load() + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'error', + error: transportedError, + }) + expect(context).toHaveBeenCalledTimes(1) + expect(beforeLoad).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + }) + + test('aborts the hydrated route context generation when the route is later left', async () => { + const capturedSignals: Array = [] + const rootRoute = new BaseRootRoute({}) + const oldRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/old', + context: ({ abortController }) => { + capturedSignals.push(abortController.signal) + return { hydrated: true } + }, + }) + const newRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/new', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([oldRoute, newRoute]), + history: createMemoryHistory({ initialEntries: ['/old'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload( + mockWindow, + matches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success' as const, + ssr: true, + u: Date.now(), + })), + ) + + await hydrate(router) + const hydratedSignal = capturedSignals.at(-1)! + await router.load() + const reloadedSignal = router.state.matches.find( + (match) => match.routeId === oldRoute.id, + )!.abortController.signal + expect(hydratedSignal.aborted).toBe(true) + expect(reloadedSignal).not.toBe(hydratedSignal) + expect(reloadedSignal.aborted).toBe(false) + + await router.navigate({ to: '/new' }) + + expect(reloadedSignal.aborted).toBe(true) + expect(router.state.resolvedLocation?.pathname).toBe('/new') + }) + + test('keeps hydrated route context alive when the initial load is synchronously superseded', async () => { + let capturedSignal: AbortSignal | undefined + const beforeLoadGate = createControlledPromise() + const rootRoute = new BaseRootRoute({ + context: ({ abortController }) => { + capturedSignal = abortController.signal + return { hydrated: true } + }, + }) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + ssr: false, + beforeLoad: async () => { + await beforeLoadGate + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload( + mockWindow, + matches.map((match, index) => ({ + i: dehydrateSsrMatchId(match.id), + s: index ? ('pending' as const) : ('success' as const), + ssr: index ? false : true, + u: Date.now(), + })), + ) + + await hydrate(router) + expect(router.state.resolvedLocation).toBeUndefined() + let winningLoad: Promise | undefined + const unsubscribe = router.subscribe('onBeforeNavigate', () => { + unsubscribe() + winningLoad = router.load() + }) + + const supersededLoad = router.load() + await vi.waitFor(() => { + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'pending', + }) + }) + expect(router.state.matches.at(-1)!.abortController.signal.aborted).toBe( + false, + ) + + beforeLoadGate.resolve() + await supersededLoad + await winningLoad + + expect(capturedSignal?.aborted).toBe(false) + expect(router.state.resolvedLocation?.pathname).toBe('/page') + }) + + test('does not hand transported context to a reentrant navigation for another location', async () => { + const rootBeforeLoad = vi.fn(() => ({ source: 'client' })) + const newLoader = vi.fn( + ({ context }: { context: { source?: string } }) => context.source, + ) + const rootRoute = new BaseRootRoute({ beforeLoad: rootBeforeLoad }) + const oldRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/old', + ssr: false, + }) + const newRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/new', + loader: newLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([oldRoute, newRoute]), + history: createMemoryHistory({ initialEntries: ['/old'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + b: { source: 'server old' }, + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'pending', + ssr: false, + u: Date.now(), + }, + ]) + + await hydrate(router) + let winningNavigation: Promise | undefined + const unsubscribe = router.subscribe('onBeforeNavigate', () => { + unsubscribe() + winningNavigation = router.navigate({ to: '/new' }) + }) + + await router.load() + await winningNavigation + + expect(router.state.resolvedLocation?.pathname).toBe('/new') + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(newLoader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.loaderData).toBe('client') + }) + + test('does not hand transported context to a reentrant history-state change', async () => { + const rootBeforeLoad = vi.fn(({ location }: { location: any }) => ({ + auth: location.state.auth, + })) + const pageLoader = vi.fn( + ({ context }: { context: { auth?: string } }) => context.auth, + ) + const rootRoute = new BaseRootRoute({ beforeLoad: rootBeforeLoad }) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + ssr: false, + loader: pageLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + b: { auth: 'server old' }, + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'pending', + ssr: false, + u: Date.now(), + }, + ]) + + await hydrate(router) + let winningNavigation: Promise | undefined + const unsubscribe = router.subscribe('onBeforeNavigate', () => { + unsubscribe() + winningNavigation = router.navigate({ + to: '/page', + state: { auth: 'client new' } as any, + }) + }) + + await router.load() + await winningNavigation + + expect(router.state.resolvedLocation?.pathname).toBe('/page') + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(pageLoader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.loaderData).toBe('client new') + }) + + test('does not hand transported context to a replaced public URL generation', async () => { + vi.spyOn(browserWindow, 'scrollTo').mockImplementation(() => undefined) + browserWindow.history.replaceState({}, '', '/public-a') + const history = createBrowserHistory({ window: browserWindow }) + const rewrite: LocationRewrite = { + input: ({ url }) => { + if (url.pathname === '/public-a' || url.pathname === '/public-b') { + url.pathname = '/internal' + } + return url + }, + output: ({ url }) => url, + } + const beforeLoad = vi.fn(({ location }: { location: any }) => ({ + publicHref: location.publicHref, + })) + const loader = vi.fn( + ({ context: routeContext }: { context: { publicHref: string } }) => + routeContext.publicHref, + ) + const rootRoute = new BaseRootRoute({ beforeLoad }) + const internalRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/internal', + ssr: false, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([internalRoute]), + history, + rewrite, + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + b: { publicHref: '/public-a' }, + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'pending', + ssr: false, + u: Date.now(), + }, + ]) + onTestFinished(() => { + history.destroy() + browserWindow.history.replaceState({}, '', '/') + }) + + await hydrate(router) + browserWindow.history.replaceState( + browserWindow.history.state, + '', + '/public-b', + ) + + await router.load() + + expect( + beforeLoad.mock.calls.map(([options]) => options.location.publicHref), + ).toEqual(['/public-b']) + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.loaderData).toBe('/public-b') + }) + + test('keeps a hydration handoff when a provider initializes an empty context', async () => { + const rootBeforeLoad = vi.fn(() => ({ source: 'client' })) + const rootLoader = vi.fn(() => 'client root') + const pageLoader = vi.fn( + ({ context }: { context: { source?: string } }) => context.source, + ) + const rootRoute = new BaseRootRoute({ + beforeLoad: rootBeforeLoad, + loader: rootLoader, + }) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + ssr: false, + loader: pageLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + b: { source: 'server' }, + l: 'server root', + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'pending', + ssr: false, + u: Date.now(), + }, + ]) + + await hydrate(router) + router.update({ + ...router.options, + context: { ...router.options.context }, + }) + await router.load() + + expect(rootBeforeLoad).not.toHaveBeenCalled() + expect(rootLoader).not.toHaveBeenCalled() + expect(pageLoader).toHaveBeenCalledTimes(1) + expect(router.state.matches[0]).toMatchObject({ + context: { source: 'server' }, + loaderData: 'server root', + }) + expect(router.state.matches[1]).toMatchObject({ loaderData: 'server' }) + }) + + test('keeps transported hydration context across a cyclic router-context replacement', async () => { + const rootBeforeLoad = vi.fn(({ context }: { context: any }) => ({ + value: context.value, + })) + const rootLoader = vi.fn(() => 'client root') + const pageContext = vi.fn(({ context }: { context: any }) => ({ + value: context.value, + })) + const pageLoader = vi.fn(({ context }: { context: any }) => context.value) + const rootRoute = new BaseRootRoute({ + beforeLoad: rootBeforeLoad, + loader: rootLoader, + }) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + ssr: false, + context: pageContext, + loader: pageLoader, + }) + const initialValue: Record = {} + initialValue.self = initialValue + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + context: { value: initialValue }, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + b: { value: initialValue }, + l: 'server root', + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'pending', + ssr: false, + u: Date.now(), + }, + ]) + + await hydrate(router) + const nextValue: Record = {} + nextValue.self = nextValue + router.update({ + ...router.options, + context: { value: nextValue }, + }) + + await expect(router.load()).resolves.toBeUndefined() + + expect(rootBeforeLoad).not.toHaveBeenCalled() + expect(pageContext).toHaveBeenCalledTimes(1) + expect(rootLoader).not.toHaveBeenCalled() + expect(pageLoader).toHaveBeenCalledTimes(1) + expect(router.state.matches[0]?.loaderData).toBe('server root') + expect(router.state.matches[1]?.loaderData).toBe(initialValue) + }) + + test('does not hand transported context across an invalidation', async () => { + const rootBeforeLoad = vi.fn(({ context }: { context: any }) => ({ + auth: context.auth, + })) + const pageLoader = vi.fn( + ({ context }: { context: { auth?: string } }) => context.auth, + ) + const rootRoute = new BaseRootRoute({ beforeLoad: rootBeforeLoad }) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + ssr: false, + loader: pageLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + context: { auth: 'server old' }, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + b: { auth: 'server old' }, + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'pending', + ssr: false, + u: Date.now(), + }, + ]) + + await hydrate(router) + router.update({ + ...router.options, + context: { auth: 'client new' }, + }) + await router.invalidate() + + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(pageLoader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.loaderData).toBe('client new') + }) + + test('rejects a hydration handoff when its prefix identity changes before finish', async () => { + let generation = 'server' + const rootBeforeLoad = vi.fn(() => ({ source: 'client' })) + const pageLoader = vi.fn( + ({ context }: { context: { source?: string } }) => context.source, + ) + const rootRoute = new BaseRootRoute({ + loaderDeps: () => ({ generation }), + beforeLoad: rootBeforeLoad, + }) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + ssr: false, + loader: pageLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload(mockWindow, [ + { + i: dehydrateSsrMatchId(matches[0]!.id), + s: 'success', + b: { source: 'server' }, + ssr: true, + u: Date.now(), + }, + { + i: dehydrateSsrMatchId(matches[1]!.id), + s: 'pending', + ssr: false, + u: Date.now(), + }, + ]) + + await hydrate(router) + const unsubscribe = router.subscribe('onBeforeNavigate', () => { + unsubscribe() + generation = 'client' + }) + + await router.load() + + expect(rootBeforeLoad).toHaveBeenCalledTimes(1) + expect(pageLoader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.loaderData).toBe('client') + }) + + test('turns a client route-context reconstruction failure into a route error', async () => { + const contextError = new Error('client context failed') + const onError = vi.fn() + const loader = vi.fn(() => 'client data') + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + context: () => { + throw contextError + }, + loader, + onError, + errorComponent: () => 'Page error', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload( + mockWindow, + matches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success' as const, + l: match.routeId === pageRoute.id ? 'server data' : undefined, + ssr: true, + u: Date.now(), + })), + ) + + await expect(hydrate(router)).resolves.toBeUndefined() + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'pending', + ssr: false, + error: undefined, + loaderData: 'server data', + }) + expect(router.state.resolvedLocation).toBeUndefined() + expect(onError).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + + await router.load() + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'error', + error: contextError, + loaderData: 'server data', + }) + expect(onError).toHaveBeenCalledTimes(1) + expect(onError).toHaveBeenCalledWith(contextError) + expect(loader).not.toHaveBeenCalled() + }) + + test('preserves route-context redirect control during hydration reconstruction', async () => { + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + context: () => { + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload( + mockWindow, + matches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success' as const, + ssr: true, + u: Date.now(), + })), + ) + + await expect(hydrate(router)).resolves.toBeUndefined() + + expect(router.state.location.pathname).toBe('/source') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: sourceRoute.id, + status: 'pending', + ssr: false, + }) + expect(router.state.resolvedLocation).toBeUndefined() + + await router.load() + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.resolvedLocation?.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + }) + + test('keeps a transported terminal route-context error authoritative', async () => { + const serverError = new Error('server context failed') + const serverRootRoute = new BaseRootRoute({}) + const serverPageRoute = new BaseRoute({ + getParentRoute: () => serverRootRoute, + path: '/page', + context: () => { + throw serverError + }, + errorComponent: () => 'Page error', + }) + const serverRouter = createTestRouter({ + routeTree: serverRootRoute.addChildren([serverPageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: true, + }) + const bootstrap = await dehydrateToBootstrap(serverRouter, testManifest) + const transportedError = bootstrap.router?.matches.at(-1)?.e + + const clientContextError = new Error('client context failed') + const beforeLoad = vi.fn() + const loader = vi.fn( + ({ context }: { context: { recovered?: boolean } }) => context.recovered, + ) + const onError = vi.fn() + const clientContext = vi.fn((): { recovered: boolean } => { + throw clientContextError + }) + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + context: clientContext, + beforeLoad, + loader, + onError, + errorComponent: () => 'Page error', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + mockWindow.$_TSR = bootstrap + + await expect(hydrate(router)).resolves.toBeUndefined() + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'error', + error: transportedError, + }) + expect(router.state.matches.at(-1)?.error).not.toBe(clientContextError) + expect(router.state.resolvedLocation?.pathname).toBe('/page') + expect(onError).not.toHaveBeenCalled() + expect(beforeLoad).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + + clientContext.mockImplementation(() => ({ recovered: true })) + await router.invalidate() + + expect(clientContext).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)).toMatchObject({ + status: 'success', + context: { recovered: true }, + loaderData: true, + }) + }) + + test('turns a hydrated normal-component chunk failure into a route error without rerunning loader data', async () => { + const chunkError = new Error('page component failed to load') + const componentPreload = vi.fn(() => Promise.reject(chunkError)) + const Page = Object.assign(() => 'Page', { preload: componentPreload }) + const loader = vi.fn(() => 'client data') + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + errorComponent: () => 'Page error', + loader, + onError, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload( + mockWindow, + matches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success' as const, + l: match.routeId === pageRoute.id ? 'server data' : undefined, + ssr: true, + u: Date.now(), + })), + ) + + await expect(hydrate(router)).resolves.toBeUndefined() + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'success', + error: undefined, + loaderData: 'server data', + }) + expect(router.state.resolvedLocation).toBeUndefined() + expect(onError).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + + await router.load() + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'error', + error: chunkError, + loaderData: 'server data', + }) + expect(onError).toHaveBeenCalledTimes(1) + expect(onError).toHaveBeenCalledWith(chunkError) + expect(loader).not.toHaveBeenCalled() + }) + + test('retries from the earliest failed hydration chunk regardless of rejection order', async () => { + const rootChunkError = new Error('root component failed to load') + const childChunkError = new Error('child component failed to load') + const rootChunkGate = createControlledPromise() + const rootChunkStarted = createControlledPromise() + const RootComponent = Object.assign(() => 'Root', { + preload: () => { + rootChunkStarted.resolve() + return rootChunkGate + }, + }) + const childComponentPreload = vi.fn(() => Promise.reject(childChunkError)) + const ChildComponent = Object.assign(() => 'Child', { + preload: childComponentPreload, + }) + const rootContext = vi.fn(() => ({})) + const rootRoute = new BaseRootRoute({ + component: RootComponent, + context: rootContext, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + component: ChildComponent, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload( + mockWindow, + matches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success' as const, + ssr: true, + u: Date.now(), + })), + ) + + const hydration = hydrate(router) + await rootChunkStarted + await vi.waitFor(() => { + expect(childComponentPreload).toHaveBeenCalledTimes(1) + }) + rootChunkGate.reject(rootChunkError) + await expect(hydration).resolves.toBeUndefined() + + expect(rootContext).not.toHaveBeenCalled() + expect(router.state.resolvedLocation).toBeUndefined() + }) + + test('does not wait for descendant chunks after an earlier chunk fails', async () => { + const rootChunkError = new Error('root component failed to load') + const childChunkGate = createControlledPromise() + const childChunkStarted = createControlledPromise() + const RootComponent = Object.assign(() => 'Root', { + preload: () => Promise.reject(rootChunkError), + }) + const ChildComponent = Object.assign(() => 'Child', { + preload: () => { + childChunkStarted.resolve() + return childChunkGate + }, + }) + const rootContext = vi.fn(() => ({})) + const rootRoute = new BaseRootRoute({ + component: RootComponent, + context: rootContext, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + component: ChildComponent, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: false, + }) + const matches = router.matchRoutes(router.stores.location.get()) + installHydrationPayload( + mockWindow, + matches.map((match) => ({ + i: dehydrateSsrMatchId(match.id), + s: 'success' as const, + ssr: true, + u: Date.now(), + })), + ) + + let settled = false + const hydration = hydrate(router).then(() => { + settled = true + }) + try { + await childChunkStarted + await vi.waitFor(() => { + expect(settled).toBe(true) + }) + } finally { + childChunkGate.resolve() + await hydration + } + + expect(rootContext).not.toHaveBeenCalled() + expect(router.state.resolvedLocation).toBeUndefined() + }) +}) diff --git a/packages/router-core/tests/public-preload-lane-contract.test.ts b/packages/router-core/tests/public-preload-lane-contract.test.ts new file mode 100644 index 0000000000..a16c64b2dc --- /dev/null +++ b/packages/router-core/tests/public-preload-lane-contract.test.ts @@ -0,0 +1,1475 @@ +import { afterEach, describe, expect, onTestFinished, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, + redirect, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.useRealTimers() +}) + +describe('public preload lane contracts', () => { + test('completed preload matches retain context without caching beforeLoad context', async () => { + let beforeLoadGeneration = 0 + const loader = vi.fn(() => 'loader data') + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + context: () => ({ routeContext: true }), + beforeLoad: () => ({ generation: ++beforeLoadGeneration }), + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preloaded = await router.preloadRoute({ to: '/target' }) + + expect(preloaded?.at(-1)?.context).toEqual({ + routeContext: true, + generation: 1, + }) + + await router.navigate({ to: '/target' }) + + expect(router.state.matches.at(-1)?.context).toEqual({ + routeContext: true, + generation: 2, + }) + expect(loader).toHaveBeenCalledTimes(1) + }) + + test('every active preload runs beforeLoad even for an identical location', async () => { + const gates = new Map< + number, + ReturnType> + >() + const beforeLoad = vi.fn(({ search }: { search: { version: number } }) => { + let gate = gates.get(search.version) + if (!gate) { + gate = createControlledPromise() + gates.set(search.version, gate) + } + return gate + }) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + validateSearch: (search: Record) => ({ + version: Number(search.version), + }), + beforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + stringifySearch: () => '', + }) + + await router.load() + const first = router.preloadRoute({ + to: '/target', + search: { version: 1 }, + }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) + const second = router.preloadRoute({ + to: '/target', + search: { version: 2 }, + }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + gates.get(1)!.resolve(undefined) + gates.get(2)!.resolve(undefined) + await Promise.all([first, second]) + + const third = router.preloadRoute({ + to: '/target', + search: { version: 3 }, + }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(3)) + const identical = router.preloadRoute({ + to: '/target', + search: { version: 3 }, + }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(4)) + gates.get(3)!.resolve(undefined) + await Promise.all([third, identical]) + }) + + test('navigation reruns beforeLoad while sharing an identical preload loader', async () => { + const beforeLoadGate = createControlledPromise() + const beforeLoad = vi.fn(async ({ preload }: { preload: boolean }) => { + await beforeLoadGate + return { source: preload ? 'preload' : 'navigation' } + }) + const loader = vi.fn(() => 'loader data') + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) + + const navigation = router.navigate({ to: '/target' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + + beforeLoadGate.resolve() + await Promise.all([preload, navigation]) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)).toMatchObject({ + context: { source: 'navigation' }, + loaderData: 'loader data', + }) + }) + + test('a depth-20 navigation does not adopt a depth-0 active preload redirect', async () => { + const redirectGate = createControlledPromise() + const sharedBeforeLoad = vi.fn(async (_context: { preload: boolean }) => { + await redirectGate + throw redirect({ to: '/target' }) + }) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const hopRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/hop/$hop', + beforeLoad: ({ params }) => { + const hop = Number(params.hop) + if (hop < 19) { + throw redirect({ + to: '/hop/$hop', + params: { hop: String(hop + 1) }, + } as any) + } + throw redirect({ to: '/shared' }) + }, + }) + const sharedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/shared', + beforeLoad: sharedBeforeLoad, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + hopRoute, + sharedRoute, + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + let preload: Promise | undefined + let navigation: Promise | undefined + onTestFinished(async () => { + redirectGate.resolve() + const activeWork: Array> = [] + if (preload) { + activeWork.push(preload) + } + if (navigation) { + activeWork.push(navigation) + } + await Promise.allSettled(activeWork) + }) + + await router.load() + preload = router.preloadRoute({ to: '/shared' }) + await vi.waitFor(() => expect(sharedBeforeLoad).toHaveBeenCalledOnce()) + + navigation = router.navigate({ + to: '/hop/$hop', + params: { hop: '0' }, + } as any) + await vi.waitFor(() => expect(sharedBeforeLoad).toHaveBeenCalledTimes(2)) + + redirectGate.resolve() + await Promise.all([preload, navigation]) + + expect( + sharedBeforeLoad.mock.calls.map(([context]) => context.preload), + ).toEqual([true, false]) + expect(router.state.location.pathname).toBe('/shared') + expect( + router.state.matches.find((match) => match.status !== 'success'), + ).toMatchObject({ + routeId: rootRoute.id, + status: 'error', + error: expect.objectContaining({ message: 'Too many redirects' }), + }) + expect(router.state.status).toBe('idle') + }) + + test.each([ + { + difference: 'pathname', + preloadMask: { to: '/mask-a' }, + navigationMask: { to: '/mask-b' }, + preloadPathname: '/mask-a', + navigationPathname: '/mask-b', + }, + { + difference: 'unmaskOnReload', + preloadMask: { to: '/mask-a' }, + navigationMask: { to: '/mask-a', unmaskOnReload: true }, + preloadPathname: '/mask-a', + navigationPathname: '/mask-a', + }, + { + difference: 'search', + preloadMask: { to: '/mask-a', search: { source: 'preload' } }, + navigationMask: { to: '/mask-a', search: { source: 'navigation' } }, + preloadPathname: '/mask-a', + navigationPathname: '/mask-a', + }, + { + difference: 'state', + preloadMask: { to: '/mask-a', state: { source: 'preload' } }, + navigationMask: { to: '/mask-a', state: { source: 'navigation' } }, + preloadPathname: '/mask-a', + navigationPathname: '/mask-a', + }, + ])( + 'navigation reruns beforeLoad for a different explicit mask $difference on the same destination', + async ({ + preloadMask, + navigationMask, + preloadPathname, + navigationPathname, + }) => { + const beforeLoadGate = createControlledPromise() + const loaderGate = createControlledPromise() + const beforeLoad = vi.fn( + async (context: { + location: { maskedLocation?: { pathname: string } } + preload: boolean + }) => { + if (context.preload) { + await beforeLoadGate + } + return { source: context.preload ? 'preload' : 'navigation' } + }, + ) + const loader = vi.fn(() => loaderGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + beforeLoad, + loader, + }) + const maskARoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/mask-a', + }) + const maskBRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/mask-b', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + targetRoute, + maskARoute, + maskBRoute, + ]), + ...('search' in preloadMask ? { stringifySearch: () => '' } : {}), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + let preload: Promise | undefined + let navigation: Promise | undefined + try { + await router.load() + preload = router.preloadRoute({ + to: '/target', + mask: preloadMask as any, + }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) + + beforeLoadGate.resolve() + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + navigation = router.navigate({ + to: '/target', + mask: navigationMask as any, + }) + await vi.waitFor(() => + expect( + beforeLoad.mock.calls.map(([callContext]) => ({ + preload: callContext.preload, + pathname: callContext.location.maskedLocation?.pathname, + })), + ).toEqual([ + { preload: true, pathname: preloadPathname }, + { preload: false, pathname: navigationPathname }, + ]), + ) + + loaderGate.resolve('shared loader data') + await Promise.all([preload, navigation]) + + expect(router.state.matches.at(-1)?.context).toEqual({ + source: 'navigation', + }) + expect(router.history.location.pathname).toBe(navigationPathname) + expect(loader).toHaveBeenCalledTimes(1) + } finally { + beforeLoadGate.resolve() + loaderGate.resolve('shared loader data') + const activeWork: Array> = [] + if (preload) { + activeWork.push(preload) + } + if (navigation) { + activeWork.push(navigation) + } + await Promise.allSettled(activeWork) + } + }, + ) + + test('identical active preloads await the same redirect chain', async () => { + const redirectGate = createControlledPromise() + const loaderGate = createControlledPromise() + const redirectedLoader = vi.fn(() => loaderGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + beforeLoad: async () => { + await redirectGate + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader: redirectedLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const first = router.preloadRoute({ to: '/source' }) + const second = router.preloadRoute({ to: '/source' }) + let secondSettled = false + void second.then(() => { + secondSettled = true + }) + + redirectGate.resolve() + await vi.waitFor(() => expect(redirectedLoader).toHaveBeenCalledOnce()) + expect(secondSettled).toBe(false) + + loaderGate.resolve() + await Promise.all([first, second]) + expect(secondSettled).toBe(true) + }) + + test.each([ + { + name: 'route suffix', + preload: { to: '/items/one/first' }, + navigation: { to: '/items/one/second' }, + pathname: '/items/one/second', + search: {}, + }, + { + name: 'params', + preload: { to: '/items/one/first' }, + navigation: { to: '/items/two/first' }, + pathname: '/items/two/first', + search: {}, + }, + { + name: 'search', + preload: { + to: '/items/one/first', + search: { view: 'summary' }, + }, + navigation: { + to: '/items/one/first', + search: { view: 'detail' }, + }, + pathname: '/items/one/first', + search: { view: 'detail' }, + }, + ])( + 'navigation does not adopt beforeLoad from an active preload with different $name', + async ({ + preload: preloadOptions, + navigation: navigationOptions, + pathname, + search, + }) => { + const beforeLoadGate = createControlledPromise() + const beforeLoad = vi.fn(async ({ preload }: { preload: boolean }) => { + await beforeLoadGate + return { preload } + }) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const itemsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/items/$itemId', + beforeLoad, + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => itemsRoute, + path: '/first', + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => itemsRoute, + path: '/second', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + itemsRoute.addChildren([firstRoute, secondRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute(preloadOptions as any) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) + + const navigation = router.navigate(navigationOptions as any) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + + beforeLoadGate.resolve() + await Promise.all([preload, navigation]) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual( + [true, false], + ) + expect(router.state.location.pathname).toBe(pathname) + expect(router.state.location.search).toEqual(search) + expect(router.state.matches.at(-1)?.context).toEqual({ preload: false }) + }, + ) + + test('a different full navigation lane reruns beforeLoad but reuses active same-id loader work', async () => { + const loaderGate = createControlledPromise() + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + source: preload ? 'preload' : 'navigation', + })) + const loader = vi.fn(() => loaderGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad, + loader, + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/first', + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/second', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([firstRoute, secondRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/parent/first' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + const navigation = router.navigate({ to: '/parent/second' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + + expect(loader).toHaveBeenCalledTimes(1) + loaderGate.resolve('shared parent data') + await Promise.all([preload, navigation]) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.routeId).toBe(secondRoute.id) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + context: { source: 'navigation' }, + loaderData: 'shared parent data', + }) + }) + + test('reserved preload loader work survives preload completion while navigation beforeLoad is pending', async () => { + const loaderGate = createControlledPromise() + const navigationBeforeLoadGate = createControlledPromise() + const beforeLoad = vi.fn(async ({ preload }: { preload: boolean }) => { + if (!preload) { + await navigationBeforeLoadGate + } + return { source: preload ? 'preload' : 'navigation' } + }) + const loader = vi.fn(() => loaderGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad, + loader, + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/first', + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/second', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([firstRoute, secondRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/parent/first' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + + const navigation = router.navigate({ to: '/parent/second' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + + loaderGate.resolve('reserved parent data') + await preload + expect(loader).toHaveBeenCalledTimes(1) + + navigationBeforeLoadGate.resolve() + await navigation + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.routeId).toBe(secondRoute.id) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + context: { source: 'navigation' }, + loaderData: 'reserved parent data', + }) + }) + + test('a background refresh consumes reserved preload work after that preload completes', async () => { + const refreshGate = createControlledPromise() + const navigationBeforeLoadGate = createControlledPromise() + const beforeLoad = vi.fn( + async ({ + preload, + search, + }: { + preload: boolean + search: { revision: number } + }) => { + if (!preload && search.revision === 2) { + await navigationBeforeLoadGate + } + return { source: preload ? 'preload' : 'navigation' } + }, + ) + const loader = vi.fn(() => + loader.mock.calls.length === 1 ? 'initial data' : refreshGate, + ) + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + revision: Number(search.revision ?? 0), + }), + beforeLoad, + shouldReload: ({ location }) => + (location.search as { revision: number }).revision > 0, + loader: { + handler: loader, + staleReloadMode: 'background', + }, + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/first', + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/second', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([firstRoute, secondRoute]), + ]), + history: createMemoryHistory({ + initialEntries: ['/parent/first?revision=0'], + }), + }) + + await router.load() + const preload = router.preloadRoute({ + to: '/parent/first', + search: { revision: 1 }, + }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + let navigationSettled = false + const navigation = router + .navigate({ + to: '/parent/second', + search: { revision: 2 }, + }) + .then(() => { + navigationSettled = true + }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(3)) + + refreshGate.resolve('refreshed data') + await preload + expect(loader).toHaveBeenCalledTimes(2) + expect(navigationSettled).toBe(false) + + navigationBeforeLoadGate.resolve() + await navigation + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + false, + true, + false, + ]) + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.routeId).toBe(secondRoute.id) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + context: { source: 'navigation' }, + loaderData: 'refreshed data', + preload: false, + isFetching: false, + }) + }) + + test('different same-href preload lanes rerun beforeLoad but share loader work by match id', async () => { + const loaderGate = createControlledPromise() + const beforeLoad = vi.fn() + const loader = vi.fn(() => loaderGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + version: Number(search.version), + }), + beforeLoad, + loader, + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/first', + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/second', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([firstRoute, secondRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + stringifySearch: () => '', + }) + + await router.load() + const first = router.preloadRoute({ + to: '/parent/first', + search: { version: 1 }, + }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + const second = router.preloadRoute({ + to: '/parent/first', + search: { version: 2 }, + }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + + expect(loader).toHaveBeenCalledTimes(1) + loaderGate.resolve('parent data') + await Promise.all([first, second]) + + expect(beforeLoad).toHaveBeenCalledTimes(2) + expect(loader).toHaveBeenCalledTimes(1) + }) + + test('completed preloads cache loader data but not beforeLoad context', async () => { + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + source: preload ? 'preload' : 'navigation', + })) + const loader = vi.fn( + ({ context }: { context: { source: string } }) => context.source, + ) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + staleTime: Infinity, + preloadStaleTime: Infinity, + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/target' }) + await router.navigate({ to: '/target' }) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)).toMatchObject({ + context: { source: 'navigation' }, + loaderData: 'preload', + }) + }) + + test('completed preloads reuse same-id route context and loader data', async () => { + const context = ({ preload }: { preload: boolean }) => ({ + source: preload ? 'preload' : 'navigation', + }) + const loader = vi.fn( + ({ context: value }: { context: { source: string } }) => value.source, + ) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + staleTime: Infinity, + preloadStaleTime: Infinity, + context, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/target' }) + await router.navigate({ to: '/target' }) + + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)).toMatchObject({ + context: { source: 'preload' }, + loaderData: 'preload', + }) + }) + + test('navigation runs independently when an active preload fails', async () => { + const preloadGate = createControlledPromise() + const beforeLoad = vi.fn(async ({ preload }: { preload: boolean }) => { + if (preload) { + await preloadGate + throw new Error('preload failed') + } + return { source: 'navigation' } + }) + const loader = vi.fn(() => 'navigation data') + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(1)) + const navigation = router.navigate({ to: '/target' }) + + preloadGate.resolve() + await Promise.all([preload, navigation]) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + context: { source: 'navigation' }, + loaderData: 'navigation data', + }) + }) + + test('a later retry reuses successful loader data from the failed preload lane', async () => { + const childGate = createControlledPromise() + const childFailure = new Error('preload child failed') + const beforeLoad = vi.fn(({ preload }: { preload: boolean }) => ({ + source: preload ? 'preload' : 'navigation', + })) + let parentSignal: AbortSignal | undefined + const parentLoader = vi.fn(({ abortController }) => { + parentSignal = abortController.signal + return 'parent data' + }) + const childLoader = vi.fn(async ({ preload }: { preload: boolean }) => { + if (preload) { + await childGate + throw childFailure + } + return 'child data' + }) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad, + loader: parentLoader, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: childLoader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const preload = router.preloadRoute({ to: '/parent/child' }) + await vi.waitFor(() => expect(childLoader).toHaveBeenCalledTimes(1)) + + childGate.resolve() + const terminal = await preload + + expect( + terminal?.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + status: 'success', + loaderData: 'parent data', + }) + expect( + terminal?.find((match) => match.routeId === childRoute.id), + ).toMatchObject({ + status: 'error', + error: childFailure, + }) + + await router.navigate({ to: '/parent/child' }) + + expect(beforeLoad.mock.calls.map(([context]) => context.preload)).toEqual([ + true, + false, + ]) + expect(parentLoader).toHaveBeenCalledTimes(1) + expect(parentSignal?.aborted).toBe(false) + expect(childLoader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: childRoute.id, + status: 'success', + loaderData: 'child data', + }) + }) + + test('a terminal preload stays terminal publicly while caching its successful loader generation', async () => { + const loader = vi.fn( + ({ deps }: { deps: { version: number } }) => deps.version, + ) + const rootRoute = new BaseRootRoute({ + validateSearch: (search: Record) => ({ + version: Number(search.version ?? 0), + }), + loaderDeps: ({ search }) => ({ version: search.version }), + shouldReload: false, + loader, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + beforeLoad: () => { + throw notFound({ routeId: rootRoute.id as never }) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ + initialEntries: ['/?version=0'], + }), + }) + + await router.load() + const terminal = await router.preloadRoute({ + to: '/target', + search: { version: 1 }, + }) + + expect(loader).toHaveBeenCalledTimes(2) + expect(terminal).toHaveLength(2) + expect(terminal?.[0]).toMatchObject({ + routeId: rootRoute.id, + status: 'success', + _notFound: true, + error: { isNotFound: true }, + loaderData: 1, + }) + expect(terminal?.[1]).toMatchObject({ + routeId: targetRoute.id, + status: 'pending', + }) + + await router.navigate({ + to: '/target', + search: { version: 1 }, + }) + + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches[0]).toMatchObject({ + status: 'success', + _notFound: true, + loaderData: 1, + }) + expect(router.state.matches[1]).toMatchObject({ + routeId: targetRoute.id, + status: 'pending', + }) + }) + + test('a terminal preload started during navigation borrows its loader generation', async () => { + const loaderGate = createControlledPromise() + const loader = vi.fn(() => + loader.mock.calls.length === 1 ? 'initial data' : loaderGate, + ) + const rootRoute = new BaseRootRoute({ + shouldReload: true, + loader, + }) + const beforeLoad = vi.fn(() => { + throw notFound({ routeId: rootRoute.id as never }) + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + beforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const navigation = router.navigate({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + const preload = router.preloadRoute({ to: '/target' }) + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + + expect(loader).toHaveBeenCalledTimes(2) + loaderGate.resolve('navigation data') + const [, terminal] = await Promise.all([navigation, preload]) + + expect(loader).toHaveBeenCalledTimes(2) + expect(terminal?.[0]).toMatchObject({ + routeId: rootRoute.id, + _notFound: true, + loaderData: 'navigation data', + }) + }) + + test('leaving a route preserves its newer same-id preload generation', async () => { + const loader = vi.fn(() => `loader data ${loader.mock.calls.length}`) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + validateSearch: (search: Record) => ({ + revision: Number(search.revision ?? 1), + }), + shouldReload: ({ location }) => + (location.search as { revision: number }).revision === 2, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ + initialEntries: ['/target?revision=1'], + }), + }) + + await router.load() + await router.preloadRoute({ + to: '/target', + search: { revision: 2 }, + }) + await router.navigate({ to: '/' }) + await router.navigate({ + to: '/target', + search: { revision: 1 }, + }) + + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.loaderData).toBe('loader data 2') + }) + + test('an expired same-id preload does not displace fresh unloaded data', async () => { + const loader = vi.fn(() => `loader data ${loader.mock.calls.length}`) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + validateSearch: (search: Record) => ({ + revision: Number(search.revision ?? 1), + }), + shouldReload: ({ location }) => + (location.search as { revision: number }).revision === 2, + preloadGcTime: 0, + gcTime: Infinity, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ + initialEntries: ['/target?revision=1'], + }), + }) + + await router.load() + await router.preloadRoute({ + to: '/target', + search: { revision: 2 }, + }) + await router.navigate({ to: '/' }) + await router.navigate({ + to: '/target', + search: { revision: 1 }, + }) + + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)?.loaderData).toBe('loader data 1') + }) + + test('filtered invalidation reloads every generation of the selected match id', async () => { + const loader = vi.fn(() => `loader data ${loader.mock.calls.length}`) + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + validateSearch: (search: Record) => ({ + revision: Number(search.revision ?? 1), + }), + shouldReload: ({ location }) => + (location.search as { revision: number }).revision === 2 + ? true + : undefined, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ + initialEntries: ['/target?revision=1'], + }), + }) + + await router.load() + await router.preloadRoute({ + to: '/target', + search: { revision: 2 }, + }) + await router.invalidate({ + filter: (match) => (match.search as { revision?: number }).revision === 1, + }) + + expect(loader).toHaveBeenCalledTimes(3) + expect(router.state.matches.at(-1)?.loaderData).toBe('loader data 3') + }) + + test('a hidden terminal suffix does not evict a newer same-id preload', async () => { + const failingBeforeLoadStarted = createControlledPromise() + const failingBeforeLoadGate = createControlledPromise() + const loader = vi.fn(() => 'preloaded child data') + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + fail: search.fail === true, + }), + beforeLoad: async ({ search }) => { + if (search.fail) { + failingBeforeLoadStarted.resolve() + await failingBeforeLoadGate + throw new Error('parent failed') + } + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + staleTime: Infinity, + preloadStaleTime: Infinity, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + const failingNavigation = router.navigate({ + to: '/parent/child', + search: { fail: true }, + }) + await failingBeforeLoadStarted + + await router.preloadRoute({ + to: '/parent/child', + search: { fail: false }, + }) + expect(loader).toHaveBeenCalledTimes(1) + + failingBeforeLoadGate.resolve() + await failingNavigation + expect(router.state.matches).toHaveLength(3) + expect(router.state.matches[1]).toMatchObject({ + routeId: parentRoute.id, + status: 'error', + }) + + await router.navigate({ + to: '/parent/child', + search: { fail: false }, + }) + + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: childRoute.id, + loaderData: 'preloaded child data', + }) + }) + + test('preload false skips speculation but performs a blocking navigation load', async () => { + const loaderGate = createControlledPromise() + const loader = vi.fn(() => loaderGate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + preload: false, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await router.load() + await router.preloadRoute({ to: '/target' }) + expect(loader).not.toHaveBeenCalled() + + let settled = false + const navigation = router.navigate({ to: '/target' }).then(() => { + settled = true + }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + expect(settled).toBe(false) + + loaderGate.resolve('target data') + await navigation + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + loaderData: 'target data', + }) + }) + + test('preloads the target of a twenty-hop redirect chain', async () => { + const beforeLoad = vi.fn(({ params }) => { + const hop = Number(params.hop) + if (hop < 20) { + throw redirect({ + to: '/hop/$hop', + params: { hop: String(hop + 1) }, + } as any) + } + }) + const rootRoute = new BaseRootRoute({}) + const hopRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/hop/$hop', + beforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([hopRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const matches = await router.preloadRoute({ + to: '/hop/$hop', + params: { hop: '0' }, + } as any) + + expect(beforeLoad).toHaveBeenCalledTimes(21) + expect(matches?.at(-1)).toMatchObject({ + routeId: hopRoute.id, + status: 'success', + params: { hop: '20' }, + }) + }) + + test('stops a preload after the twenty-hop redirect limit', async () => { + const beforeLoad = vi.fn(({ params }) => { + const hop = Number(params.hop) + if (hop < 22) { + throw redirect({ + to: '/hop/$hop', + params: { hop: String(hop + 1) }, + } as any) + } + }) + const rootRoute = new BaseRootRoute({}) + const hopRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/hop/$hop', + beforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([hopRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const matches = await router.preloadRoute({ + to: '/hop/$hop', + params: { hop: '0' }, + } as any) + + expect(beforeLoad).toHaveBeenCalledTimes(21) + expect(matches?.find((match) => match.status !== 'success')).toMatchObject({ + routeId: rootRoute.id, + status: 'error', + error: expect.objectContaining({ + message: 'Too many redirects', + }), + }) + }) + + test('limits inferred same-origin absolute redirects during preload', async () => { + const origin = 'https://example.com' + const beforeLoad = vi.fn(({ params }) => { + const hop = Number(params.hop) + if (hop < 21) { + throw redirect({ href: `${origin}/hop/${hop + 1}` }) + } + }) + const rootRoute = new BaseRootRoute({}) + const hopRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/hop/$hop', + beforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([hopRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + origin, + isServer: false, + }) + + const matches = await router.preloadRoute({ + to: '/hop/$hop', + params: { hop: '0' }, + } as any) + + expect(beforeLoad).toHaveBeenCalledTimes(21) + expect(matches?.find((match) => match.status !== 'success')).toMatchObject({ + routeId: rootRoute.id, + status: 'error', + error: expect.objectContaining({ message: 'Too many redirects' }), + }) + }) + + test('forwards a document redirect at the redirect limit', async () => { + const beforeLoad = vi.fn(({ params }) => { + const hop = Number(params.hop) + throw redirect({ + to: '/hop/$hop', + params: { hop: String(hop + 1) }, + reloadDocument: hop === 20, + } as any) + }) + const rootRoute = new BaseRootRoute({}) + const hopRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/hop/$hop', + beforeLoad, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([hopRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const matches = await router.preloadRoute({ + to: '/hop/$hop', + params: { hop: '0' }, + } as any) + + expect(beforeLoad).toHaveBeenCalledTimes(21) + expect(matches).toBeUndefined() + }) + + test('reports a chunk redirect limit at root', async () => { + const chunkError = new Error('route chunk failed') + const rootRoute = new BaseRootRoute({}) + const loopRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/loop', + onError: () => { + throw redirect({ to: '/loop' }) + }, + }).lazy(() => Promise.reject(chunkError)) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([loopRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const matches = await router.preloadRoute({ to: '/loop' }) + + const terminal = matches?.find((match) => match.status !== 'success') + expect(terminal).toMatchObject({ + routeId: rootRoute.id, + status: 'error', + error: expect.objectContaining({ message: 'Too many redirects' }), + }) + }) +}) diff --git a/packages/router-core/tests/qss.test.ts b/packages/router-core/tests/qss.test.ts index ce92857ab5..3ced74266c 100644 --- a/packages/router-core/tests/qss.test.ts +++ b/packages/router-core/tests/qss.test.ts @@ -1,7 +1,74 @@ -import { describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { decode, encode } from '../src/qss' +afterEach(() => vi.unstubAllGlobals()) + describe('encode function', () => { + it.each([{}, { skipped: undefined }])( + 'does not allocate a native serializer for %j', + (input) => { + const Original = URLSearchParams + const constructor = vi.fn(function () { + return new Original() + }) + vi.stubGlobal('URLSearchParams', constructor) + expect(encode(input)).toBe('') + expect(constructor).not.toHaveBeenCalled() + }, + ) + + it('keeps getter and serializer order, including inherited values', () => { + const calls: Array = [] + const input = Object.create({ + get inherited() { + calls.push('get inherited') + return 'last' + }, + }) + Object.defineProperties(input, { + skipped: { + enumerable: true, + get() { + calls.push('get skipped') + return undefined + }, + }, + own: { + enumerable: true, + get() { + calls.push('get own') + return 'first' + }, + }, + }) + expect( + encode(input, (value) => { + calls.push(`stringify ${value}`) + return value + }), + ).toBe('own=first&inherited=last') + expect(calls).toEqual([ + 'get skipped', + 'get own', + 'stringify first', + 'get inherited', + 'stringify last', + ]) + }) + + it('preserves falsy values and empty serializer output', () => { + expect(encode({ zero: 0, false: false, null: null, empty: '' })).toBe( + 'zero=0&false=false&null=null&empty=', + ) + expect(encode({ value: 'present' }, () => '')).toBe('value=') + }) + + it('retains native set semantics for keys that normalize to the same string', () => { + expect(encode({ '\uD800': 'first', '\uD801': 'second' })).toBe( + '%EF%BF%BD=second', + ) + }) + it('should encode an object into a query string without a prefix', () => { const obj = { token: 'foo', key: 'value' } const queryString = encode(obj) diff --git a/packages/router-core/tests/ready-route-loading.test.ts b/packages/router-core/tests/ready-route-loading.test.ts new file mode 100644 index 0000000000..9d7f611b79 --- /dev/null +++ b/packages/router-core/tests/ready-route-loading.test.ts @@ -0,0 +1,136 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +test.each(['resolve', 'reject', 'supersede'] as const)( + 'a fresh cached loader still handles a new component chunk: %s', + async (outcome) => { + const data = { value: 'cached' } + const loader = vi.fn(() => data) + const root = new BaseRootRoute({}) + const cached = new BaseRoute({ + getParentRoute: () => root, + path: '/cached', + loader, + staleTime: Infinity, + gcTime: Infinity, + }) + const other = new BaseRoute({ + getParentRoute: () => root, + path: '/other', + }) + const router = createTestRouter({ + routeTree: root.addChildren([cached, other]), + history: createMemoryHistory({ initialEntries: ['/cached'] }), + }) + await router.load() + await router.navigate({ to: '/other' }) + + const chunk = createControlledPromise() + const started = createControlledPromise() + cached.update({ + component: Object.assign(() => null, { + preload: () => { + started.resolve() + return chunk + }, + }), + }) + let settled = false + const navigation = router.navigate({ to: '/cached' }).then(() => { + settled = true + }) + await started + expect(settled).toBe(false) + expect(loader).toHaveBeenCalledOnce() + + const error = new Error('Chunk failed') + if (outcome === 'supersede') { + await router.navigate({ to: '/other' }) + await navigation + expect(router.state.location.pathname).toBe('/other') + chunk.reject(error) + } else { + if (outcome === 'resolve') { + chunk.resolve() + } else { + chunk.reject(error) + } + await navigation + const match = router.state.matches.find( + (candidate) => candidate.routeId === cached.id, + )! + expect(match.status).toBe(outcome === 'resolve' ? 'success' : 'error') + if (outcome === 'resolve') { + expect(match.loaderData).toBe(data) + } else { + expect(match.error).toBe(error) + } + } + expect(loader).toHaveBeenCalledOnce() + }, +) + +test('a synchronous component preload failure is caught and can be retried', async () => { + const error = new Error('Synchronous preload failure') + const preload = vi.fn(() => { + throw error + }) + const root = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => root, + path: '/route', + component: Object.assign(() => null, { preload }), + }) + const router = createTestRouter({ + routeTree: root.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/route'] }), + }) + + await router.load() + expect(router.state.matches.at(-1)).toMatchObject({ + status: 'error', + error, + }) + + route.update({ component: () => null }) + await router.load() + expect(router.state.matches.at(-1)?.status).toBe('success') + expect(preload).toHaveBeenCalledOnce() +}) + +test('a synchronous loader failure takes precedence over a synchronous component preload failure', async () => { + const loaderError = new Error('Loader failed') + const chunkError = new Error('Component preload failed') + const loader = vi.fn(() => { + throw loaderError + }) + const preload = vi.fn(() => { + throw chunkError + }) + const root = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => root, + path: '/route', + loader, + component: Object.assign(() => null, { preload }), + errorComponent: () => null, + }) + const history = createMemoryHistory({ initialEntries: ['/route'] }) + const router = createTestRouter({ + routeTree: root.addChildren([route]), + history, + }) + try { + await router.load() + expect(loader).toHaveBeenCalledOnce() + expect(preload).toHaveBeenCalledOnce() + expect(router.state.matches.at(-1)).toMatchObject({ + status: 'error', + error: loaderError, + }) + } finally { + history.destroy() + } +}) diff --git a/packages/router-core/tests/ready-route-parent-snapshot.test.ts b/packages/router-core/tests/ready-route-parent-snapshot.test.ts new file mode 100644 index 0000000000..63d410352a --- /dev/null +++ b/packages/router-core/tests/ready-route-parent-snapshot.test.ts @@ -0,0 +1,103 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +test.each(['success', 'shouldReload error'] as const)( + 'a child immediately observes its fresh cached parent snapshot: %s', + async (outcome) => { + const originalError = new Error('shouldReload failed') + const selectedError = new Error('selected by onError') + const parentLoader = vi.fn(() => 'cached parent data') + const onError = vi.fn(() => { + throw selectedError + }) + const observed = createControlledPromise() + const childGate = createControlledPromise() + let shouldFail = false + let snapshot: unknown + const root = new BaseRootRoute({}) + const parent = new BaseRoute({ + getParentRoute: () => root, + path: '/parent', + staleTime: Infinity, + gcTime: Infinity, + loader: parentLoader, + shouldReload: + outcome === 'shouldReload error' + ? () => { + if (shouldFail) { + throw originalError + } + return false + } + : undefined, + onError, + errorComponent: () => null, + }) + const childLoader = vi.fn(async ({ parentMatchPromise }) => { + const match = await parentMatchPromise + snapshot = { + status: match.status, + loaderData: match.loaderData, + invalid: match.invalid, + isFetching: match.isFetching, + hasSelectedError: match.error === selectedError, + } + observed.resolve() + return childGate + }) + const child = new BaseRoute({ + getParentRoute: () => parent, + path: '/child', + loader: childLoader, + }) + const other = new BaseRoute({ + getParentRoute: () => root, + path: '/other', + }) + const router = createTestRouter({ + routeTree: root.addChildren([parent.addChildren([child]), other]), + history: createMemoryHistory({ initialEntries: ['/parent'] }), + isServer: false, + }) + + await router.load() + await router.navigate({ to: '/other' }) + shouldFail = true + let settled = false + const navigation = router.navigate({ to: '/parent/child' }).then(() => { + settled = true + }) + + await observed + expect(settled).toBe(false) + expect(parentLoader).toHaveBeenCalledOnce() + expect(childLoader).toHaveBeenCalledOnce() + expect(snapshot).toEqual({ + status: outcome === 'success' ? 'success' : 'error', + loaderData: 'cached parent data', + invalid: outcome !== 'success', + isFetching: false, + hasSelectedError: outcome !== 'success', + }) + + childGate.resolve('child data') + await navigation + + expect(parentLoader).toHaveBeenCalledOnce() + const parentMatch = router.state.matches.find( + (match) => match.routeId === parent.id, + ) + expect(parentMatch?.status).toBe( + outcome === 'success' ? 'success' : 'error', + ) + if (outcome === 'success') { + expect(onError).not.toHaveBeenCalled() + expect(router.state.matches.at(-1)?.loaderData).toBe('child data') + } else { + expect(onError).toHaveBeenCalledExactlyOnceWith(originalError) + expect(parentMatch?.error).toBe(selectedError) + } + }, +) diff --git a/packages/router-core/tests/redirect-resolution.test.ts b/packages/router-core/tests/redirect-resolution.test.ts new file mode 100644 index 0000000000..b8fa439609 --- /dev/null +++ b/packages/router-core/tests/redirect-resolution.test.ts @@ -0,0 +1,144 @@ +import { createMemoryHistory } from '@tanstack/history' +import { describe, expect, test } from 'vitest' +import { BaseRootRoute, redirect } from '../src' +import { createTestRouter } from './routerTestUtils' + +function createRouter(protocolAllowlist?: Array) { + return createTestRouter({ + routeTree: new BaseRootRoute(), + history: createMemoryHistory({ initialEntries: ['/'] }), + origin: 'https://app.example', + protocolAllowlist, + isServer: true, + }) +} + +describe('redirect destination classification', () => { + const cases = [ + [ + '/target?next=https://other.example#section', + '/target?next=https://other.example#section', + false, + ], + ['https://other.example/target', 'https://other.example/target', true], + ['http://app.example/target', 'http://app.example/target', true], + ['https://app.example:444/target', 'https://app.example:444/target', true], + ['mailto:person@example.com', 'mailto:person@example.com', true], + ['tel:+123456789', 'tel:+123456789', true], + [ + 'https://user@app.example/target', + 'https://user@app.example/target', + true, + ], + [ + 'https://:password@app.example/target', + 'https://:password@app.example/target', + true, + ], + [ + 'HTTPS://APP.EXAMPLE:443//other.example/path', + 'https://app.example//other.example/path', + true, + ], + ['HTTPS://OTHER.EXAMPLE:443//path', 'https://other.example//path', true], + ] as const + + const sameOriginDocumentCases = [ + ['https://app.example/target?q=1#section', '/target?q=1#section', false], + ['HTTPS://APP.EXAMPLE:443/a/../target', '/target', false], + ['h\tttps://app.example/target', '/target', false], + ['\x01H\tTtPs://app.example/a/../target', '/target', false], + ['https://@app.example/target', '/target', false], + ['https://app.example/%2Fpath', '/%2Fpath', false], + ['https://app.example/%5Cpath', '/%5Cpath', false], + ] as const + + for (const reloadDocument of [undefined, false, true]) { + test.each([...cases, ...sameOriginDocumentCases])( + `resolves %j with reloadDocument=${reloadDocument}`, + (href, expectedHref, external) => { + const router = createRouter() + const result = router.resolveRedirect( + redirect({ href, reloadDocument }), + ) + expect(result.options.href).toBe(expectedHref) + expect(result.headers.get('Location')).toBe(expectedHref) + expect(result.options.reloadDocument).toBe( + external ? true : reloadDocument, + ) + expect(router.resolveRedirect(result)).toBe(result) + expect(result.headers.get('Location')).toBe(expectedHref) + expect(result.options.href).toBe(expectedHref) + expect(result.options.reloadDocument).toBe( + external ? true : reloadDocument, + ) + }, + ) + } + + test.each([ + '//other.example/path', + '//other.example:443/path', + '/\\other.example/path', + '\\\\other.example/path', + '/\t/other.example/path', + 'javascript:alert(1)', + 'java\tscript:alert(1)', + 'custom:value', + '\x01Ja\tvaScript:alert(1)', + '\x01/\\other.example/path', + ])('rejects the unsafe destination %j', (href) => { + expect(() => createRouter().resolveRedirect(redirect({ href }))).toThrow( + 'Redirect blocked', + ) + }) + + test.each(['custom://[', 'blob:https://app.example/id'])( + 'keeps an explicitly allowed non-HTTP destination opaque: %s', + (href) => { + const router = createRouter(['custom:', 'blob:']) + const result = router.resolveRedirect(redirect({ href })) + expect(result.options.href).toBe(href) + expect(result.options.reloadDocument).toBe(true) + }, + ) + + test('does not implicitly allow HTTP when the configured allowlist excludes it', () => { + expect(() => + createRouter([]).resolveRedirect( + redirect({ href: 'https://app.example/target' }), + ), + ).toThrow('Redirect blocked') + }) + + test('classifies the Location header that takes precedence over options.href', () => { + const router = createRouter() + const result = router.resolveRedirect( + redirect({ + href: 'javascript:alert(1)', + headers: { Location: 'https://app.example/target' }, + }), + ) + expect(result.options.href).toBe('/target') + expect(result.options.reloadDocument).toBeUndefined() + expect(() => + router.resolveRedirect( + redirect({ + href: '/safe', + headers: { Location: '//other.example/path' }, + }), + ), + ).toThrow('Redirect blocked') + }) + + test('rejects an obfuscated scheme in the authoritative Location header', () => { + expect(() => + createRouter().resolveRedirect( + redirect({ + href: '/safe', + headers: { Location: '\x01Ja\tvaScript:alert(1)' }, + }), + ), + ).toThrow('Redirect blocked') + }) +}) diff --git a/packages/router-core/tests/redirect-target-error.test.ts b/packages/router-core/tests/redirect-target-error.test.ts new file mode 100644 index 0000000000..4a6f5cb8fd --- /dev/null +++ b/packages/router-core/tests/redirect-target-error.test.ts @@ -0,0 +1,635 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + redirect, +} from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +describe('redirect target errors', () => { + test.each([false, true])( + 'a client redirect target error becomes the originating route error (reloadDocument=%s)', + async (reloadDocument) => { + const boom = new Error('resolveRedirect failed') + const errorComponentGate = createControlledPromise() + const errorComponentStarted = createControlledPromise() + const errorComponentPreload = vi.fn(() => { + errorComponentStarted.resolve() + return errorComponentGate + }) + const ErrorComponent = Object.assign(() => null, { + preload: errorComponentPreload, + }) + + const rootLoader = vi.fn(() => 'root data') + const onError = vi.fn() + const rootRoute = new BaseRootRoute({ loader: rootLoader }) + const badRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bad', + beforeLoad: () => { + throw redirect({ + to: '/bad', + reloadDocument, + search: () => { + throw boom + }, + }) + }, + onError, + errorComponent: ErrorComponent, + }) + const safeLoader = vi.fn(() => 'safe data') + const safeRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/safe', + loader: safeLoader, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([badRoute, safeRoute]), + history: createMemoryHistory({ initialEntries: ['/bad'] }), + }) + + const load = router.load() + const outcome = await Promise.race([ + load.then(() => 'load-settled' as const), + errorComponentStarted.then(() => 'error-preload-started' as const), + ]) + expect(outcome).toBe('error-preload-started') + expect(rootLoader).toHaveBeenCalledOnce() + expect(onError).toHaveBeenCalledWith(boom) + + errorComponentGate.resolve() + await load + expect(errorComponentPreload).toHaveBeenCalledOnce() + expect(router.state.status).toBe('idle') + expect(router.state.location.pathname).toBe('/bad') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: badRoute.id, + status: 'error', + error: boom, + }) + + await router.navigate({ to: '/safe' }) + expect(router.state.location.pathname).toBe('/safe') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: safeRoute.id, + status: 'success', + loaderData: 'safe data', + }) + expect(safeLoader).toHaveBeenCalledTimes(1) + }, + ) + + test('a server redirect target error becomes the originating route error', async () => { + const boom = new Error('resolveRedirect failed') + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const badRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bad', + beforeLoad: () => { + throw redirect({ + to: '/bad', + search: () => { + throw boom + }, + }) + }, + onError, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([badRoute]), + history: createMemoryHistory({ initialEntries: ['/bad'] }), + }) + + const response = await loadServerResponse(router, '/bad') + + expect(response.status).toBe(500) + expect(response.headers.get('Location')).toBeNull() + expect(onError).toHaveBeenCalledWith(boom) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: badRoute.id, + status: 'error', + error: boom, + }) + }) + + test('a server loader redirect target error becomes the route error', async () => { + const boom = new Error('server loader redirect failed') + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const badRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bad', + loader: () => + redirect({ + to: '/target', + hash: () => { + throw boom + }, + }), + onError, + errorComponent: () => null, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([badRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/bad'] }), + }) + + const response = await loadServerResponse(router, '/bad') + + expect(response.status).toBe(500) + expect(onError).toHaveBeenCalledWith(boom) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: badRoute.id, + status: 'error', + error: boom, + }) + }) + + test.each([false, true])( + 'a loader redirect target error becomes the originating route error (reloadDocument=%s)', + async (reloadDocument) => { + const boom = new Error('redirect hash failed') + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const badRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bad', + loader: () => + redirect({ + to: '/target', + reloadDocument, + hash: () => { + throw boom + }, + }), + onError, + errorComponent: () => null, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([badRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/bad'] }), + }) + + await router.load() + + expect(onError).toHaveBeenCalledWith(boom) + expect(router.state.location.pathname).toBe('/bad') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: badRoute.id, + status: 'error', + error: boom, + }) + }, + ) + + test('an internal href parse error becomes the originating route error', async () => { + const boom = new Error('redirect search parse failed') + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + beforeLoad: () => { + throw redirect({ href: '/target?bad' }) + }, + onError, + errorComponent: () => null, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + parseSearch: (search) => { + if (search) { + throw boom + } + return {} + }, + }) + + await router.load() + + expect(onError).toHaveBeenCalledWith(boom) + expect(router.state.location.pathname).toBe('/source') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: sourceRoute.id, + status: 'error', + error: boom, + }) + }) + + test('an unsafe document href becomes the originating route error', async () => { + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => redirect({ href: 'javascript:alert(1)' }), + onError, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + }) + + await router.load() + + const error = onError.mock.calls[0]?.[0] + expect(error).toEqual( + expect.objectContaining({ + message: expect.stringContaining('unsafe protocol'), + }), + ) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: sourceRoute.id, + status: 'error', + error, + }) + }) + + test('a protocol-relative redirect becomes the originating route error', async () => { + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => redirect({ href: '/\\evil.example' }), + onError, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + }) + + await router.load() + + const error = onError.mock.calls[0]?.[0] + expect(error).toEqual( + expect.objectContaining({ + message: expect.stringContaining('unsafe protocol'), + }), + ) + expect(router.state.location.pathname).toBe('/source') + }) + + test('a preload does not build a document redirect target', async () => { + const search = vi.fn(() => ({ redirected: true })) + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + beforeLoad: () => + redirect({ + to: '/target', + search, + reloadDocument: true, + }), + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const matches = await router.preloadRoute({ to: '/source' }) + + expect(matches).toBeUndefined() + expect(search).not.toHaveBeenCalled() + }) + + test('request cancellation discards a late redirect without finalizing it', async () => { + const cancellation = new Error('request disconnected') + const boom = new Error('late redirect target failed') + const loaderStarted = createControlledPromise() + const loaderGate = createControlledPromise>() + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => { + loaderStarted.resolve() + return loaderGate + }, + onError, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + isServer: true, + }) + const controller = new AbortController() + const load = loadServerResponse(router, '/source', controller.signal) + await loaderStarted + + controller.abort(cancellation) + await expect(load).rejects.toBe(cancellation) + loaderGate.resolve( + redirect({ + to: '/target', + search: () => { + throw boom + }, + }), + ) + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(onError).not.toHaveBeenCalled() + }) + + test('a background redirect target error publishes after foreground commit', async () => { + const boom = new Error('background redirect target failed') + const reloadStarted = createControlledPromise() + const reloadGate = createControlledPromise>() + const onError = vi.fn() + let loads = 0 + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => { + if (++loads === 1) { + return 'initial data' + } + reloadStarted.resolve() + return reloadGate + }, + onError, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + await router.load() + const invalidation = router.invalidate() + await reloadStarted + await invalidation + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'success', + loaderData: 'initial data', + }) + + reloadGate.resolve( + redirect({ + to: '/page', + search: () => { + throw boom + }, + }), + ) + + await vi.waitFor(() => expect(onError).toHaveBeenCalledWith(boom)) + await vi.waitFor(() => + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'error', + error: boom, + }), + ) + }) + + test('a successful redirect target is built once', async () => { + const search = vi.fn(() => ({ redirected: true })) + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => redirect({ to: '/target', search }), + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + }) + + await router.load() + + expect(search).toHaveBeenCalledOnce() + expect(router.state.location).toMatchObject({ + pathname: '/target', + search: { redirected: true }, + }) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + }) + + test('a shared loader redirect is materialized for each preload lane', async () => { + const loaderStarted = createControlledPromise() + const loaderGate = createControlledPromise>() + const sourceLoader = vi.fn(() => { + loaderStarted.resolve() + return loaderGate + }) + const searchUpdater = vi.fn((search: { version?: number }) => ({ + version: search.version, + })) + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + validateSearch: (search: Record) => ({ + version: Number(search.version), + }), + loader: sourceLoader, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + validateSearch: (search: Record) => ({ + version: Number(search.version), + }), + loaderDeps: ({ search }) => ({ version: search.version }), + loader: ({ deps }) => deps.version, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const first = router.preloadRoute({ + to: '/source', + search: { version: 1 }, + }) + await loaderStarted + const second = router.preloadRoute({ + to: '/source', + search: { version: 2 }, + }) + await vi.waitFor(() => expect(sourceLoader).toHaveBeenCalledOnce()) + + loaderGate.resolve( + redirect({ to: '/target', search: searchUpdater } as any), + ) + const [firstMatches, secondMatches] = await Promise.all([first, second]) + + expect(sourceLoader).toHaveBeenCalledOnce() + expect(searchUpdater).toHaveBeenCalledTimes(2) + expect(firstMatches?.at(-1)).toMatchObject({ + routeId: targetRoute.id, + loaderData: 1, + }) + expect(secondMatches?.at(-1)).toMatchObject({ + routeId: targetRoute.id, + loaderData: 2, + }) + }) + + test.each([false, true])( + 'document redirects materialize the mask within route error handling (throws=%s)', + async (throws) => { + const boom = new Error('mask search failed') + const onError = vi.fn() + const maskSearch = vi.fn(() => { + if (throws) { + throw boom + } + return { masked: true } + }) + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => + redirect({ + to: '/target', + reloadDocument: true, + mask: { to: '/pretty', search: maskSearch }, + }), + onError, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + isServer: false, + }) + const windowLocation = { replace: vi.fn() } + vi.stubGlobal('window', { location: windowLocation }) + try { + await router.load() + expect(maskSearch).toHaveBeenCalledOnce() + if (throws) { + expect(onError).toHaveBeenCalledWith(boom) + expect(router.state.matches.at(-1)).toMatchObject({ + status: 'error', + error: boom, + }) + expect(windowLocation.replace).not.toHaveBeenCalled() + } else { + expect(onError).not.toHaveBeenCalled() + expect(windowLocation.replace).toHaveBeenCalledWith( + '/pretty?masked=true', + ) + } + } finally { + vi.unstubAllGlobals() + } + }, + ) + + test('an external rewrite does not bind a shared redirect to the preload location', async () => { + const loaderStarted = createControlledPromise() + const loaderGate = createControlledPromise>() + const beforeLoad = vi.fn() + const sourceLoader = vi.fn(() => { + loaderStarted.resolve() + return loaderGate + }) + const searchUpdater = vi.fn((search: { version?: number }) => ({ + version: search.version, + })) + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + validateSearch: (search: Record) => ({ + version: Number(search.version), + }), + beforeLoad, + loader: sourceLoader, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + rewrite: { + output: ({ url }) => + url.pathname === '/target' + ? new URL(url.pathname + url.search, 'https://other.example') + : url, + }, + }) + await router.load() + const matchRoutes = vi.spyOn(router, 'matchRoutes') + const navigate = vi.spyOn(router, 'navigate').mockResolvedValue() + const preload = router.preloadRoute({ + to: '/source', + search: { version: 1 }, + }) + await loaderStarted + router.history.push('/source?version=2') + const navigation = router.load() + await vi.waitFor(() => expect(beforeLoad).toHaveBeenCalledTimes(2)) + const rawRedirect = redirect({ + to: '/target', + search: searchUpdater, + } as any) + loaderGate.resolve(rawRedirect) + await Promise.all([preload, navigation]) + + expect(sourceLoader).toHaveBeenCalledOnce() + expect(searchUpdater).toHaveBeenCalledTimes(2) + expect(navigate).toHaveBeenCalledWith( + expect.objectContaining({ + href: 'https://other.example/target?version=2', + reloadDocument: true, + }), + ) + expect( + matchRoutes.mock.calls.every(([location]) => location !== undefined), + ).toBe(true) + expect(rawRedirect.options.href).toBeUndefined() + expect(rawRedirect.headers.has('Location')).toBe(false) + }) +}) diff --git a/packages/router-core/tests/redirect.test-d.ts b/packages/router-core/tests/redirect.test-d.ts new file mode 100644 index 0000000000..10221c59f4 --- /dev/null +++ b/packages/router-core/tests/redirect.test-d.ts @@ -0,0 +1,140 @@ +import { describe, expectTypeOf, test } from 'vitest' +import { + BaseRootRoute, + BaseRoute, + BaseRouteApi, + redirect, + type Redirect, + type RedirectFnRoute, + type RedirectOptionsRoute, +} from '../src' + +describe('RedirectFnRoute', () => { + test('should be callable with redirect options', () => { + type TestRedirectFn = RedirectFnRoute<'/users/$userId'> + + expectTypeOf().toBeCallableWith({ + to: '/' as const, + }) + }) + + test('should not require from option', () => { + type TestRedirectFn = RedirectFnRoute<'/users/$userId'> + + // from should not be in the options type + expectTypeOf[0]>().not.toHaveProperty('from') + }) + + test('should return Redirect type', () => { + type TestRedirectFn = RedirectFnRoute<'/users/$userId'> + + expectTypeOf>().toMatchTypeOf() + }) +}) + +describe('RedirectOptionsRoute', () => { + test('should not have from property', () => { + type TestOptions = RedirectOptionsRoute<'/users/$userId'> + + // from should be omitted + expectTypeOf().not.toHaveProperty('from') + }) + + test('should have to property', () => { + type TestOptions = RedirectOptionsRoute<'/users/$userId'> + + // Should be able to specify to + const optionsWithTo: TestOptions = { to: '/' } + expectTypeOf(optionsWithTo).toMatchTypeOf() + }) + + test('should allow statusCode option', () => { + type TestOptions = RedirectOptionsRoute<'/users/$userId'> + + const options: TestOptions = { to: '/', statusCode: 301 } + expectTypeOf(options).toMatchTypeOf() + }) + + test('should allow href option for external redirects', () => { + type TestOptions = RedirectOptionsRoute<'/users/$userId'> + + // href can be used with to + const options: TestOptions = { to: '/', href: 'http://example.com' } + expectTypeOf(options).toMatchTypeOf() + }) +}) + +describe('BaseRoute.redirect', () => { + test('should have redirect property on BaseRoute', () => { + const rootRoute = new BaseRootRoute({}) + const usersRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId', + }) + + expectTypeOf(usersRoute.redirect).toBeFunction() + }) + + test('should create redirect with to option', () => { + const rootRoute = new BaseRootRoute({}) + const usersRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId', + }) + + // Should be callable with to option + const result = usersRoute.redirect({ to: '/' }) + expectTypeOf(result).toMatchTypeOf() + }) +}) + +describe('BaseRouteApi.redirect', () => { + test('should have redirect property on BaseRouteApi', () => { + const routeApi = new BaseRouteApi({ id: '/users/$userId' }) + + expectTypeOf(routeApi.redirect).toBeFunction() + }) + + test('should create redirect with to option', () => { + const routeApi = new BaseRouteApi({ id: '/users/$userId' }) + + // Should be callable with to option + const result = routeApi.redirect({ to: '/' }) + expectTypeOf(result).toMatchTypeOf() + }) +}) + +describe('redirect vs Route.redirect comparison', () => { + test('regular redirect can use from for type inference', () => { + // Regular redirect - from is optional but helps with type inference + const regularRedirect = redirect({ + to: '/users' as const, + from: '/posts/$postId' as const, + }) + expectTypeOf(regularRedirect).toMatchTypeOf() + }) + + test('Route.redirect automatically sets from', () => { + const rootRoute = new BaseRootRoute({}) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts/$postId', + }) + + // Route.redirect - from is automatically set from fullPath + const routeRedirect = postsRoute.redirect({ + to: '/', + }) + expectTypeOf(routeRedirect).toMatchTypeOf() + }) + + test('RouteApi.redirect automatically sets from', () => { + const routeApi = new BaseRouteApi({ id: '/posts/$postId' }) + + // RouteApi.redirect - from is automatically set from route id + const routeApiRedirect = routeApi.redirect({ + to: '/', + }) + expectTypeOf(routeApiRedirect).toMatchTypeOf() + }) +}) diff --git a/packages/router-core/tests/rendered-matches.test.ts b/packages/router-core/tests/rendered-matches.test.ts new file mode 100644 index 0000000000..2a2ea362ae --- /dev/null +++ b/packages/router-core/tests/rendered-matches.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, test } from 'vitest' +import { _getAssetMatches } from '../src' +import type { AnyRouteMatch } from '../src' + +describe('_getAssetMatches', () => { + test('does not cross an ordinary data-only pending boundary', () => { + const matches = [ + { status: 'success' }, + { status: 'pending', ssr: 'data-only' }, + { status: 'success' }, + ] as Array + + expect(_getAssetMatches(matches)).toEqual(matches.slice(0, 2)) + }) + + test('limits a hydration handoff to its verified asset prefix', () => { + const matches = [ + { status: 'success' }, + { + status: 'pending', + ssr: 'data-only', + _assetEnd: 3, + }, + { status: 'success' }, + { status: 'success' }, + ] as Array + + expect(_getAssetMatches(matches)).toEqual(matches.slice(0, 3)) + }) +}) diff --git a/packages/router-core/tests/replace-equal-deep.bench.ts b/packages/router-core/tests/replace-equal-deep.bench.ts new file mode 100644 index 0000000000..044fbe38bc --- /dev/null +++ b/packages/router-core/tests/replace-equal-deep.bench.ts @@ -0,0 +1,665 @@ +import { describe, expect, test } from 'vitest' +import { + createNull, + deepEqual, + isPlainObject, + nullReplaceEqualDeep, + replaceEqualDeep, +} from '../src/utils' + +// Shapes the router feeds these helpers on every Link build / navigation. +const empty = {} +const emptyNull = createNull() +const search = { tab: 'specs', page: 2, sort: 'newest', filter: 'available' } +const searchCopy = { ...search } +const searchChanged = { ...search, page: 3 } +// parseSearch and path extraction produce null-prototype records. Exercise +// these separately from ordinary selector objects: their property storage differs. +const nullSearch = Object.assign(createNull(), search) +const nullSearchCopy = Object.assign(createNull(), searchCopy) +const nullSearchChanged = Object.assign(createNull(), searchChanged) +const decimalRecord = { x: 0.5, y: 1.5, width: 640.5, height: 480.5 } +const decimalRecordCopy = { ...decimalRecord } +const decimalRecordChanged = { ...decimalRecord, x: 1.5 } +// `?constructor=foo` decodes to an own `constructor` key on a null-proto record. +const searchWithConstructorKey = Object.assign(createNull(), { + constructor: 'foo', + page: 2, +}) +const searchWithConstructorKeyCopy = Object.assign(createNull(), { + constructor: 'foo', + page: 2, +}) +class Instance { + a = 1 +} +const instance = new Instance() +const nested = { + tab: 'specs', + filters: { category: 'hardware', available: true }, + ids: [1, 2, 3, 4], +} +const nestedCopy = { + tab: 'specs', + filters: { category: 'hardware', available: true }, + ids: [1, 2, 3, 4], +} +const nestedLeafChanged = { + tab: 'specs', + filters: { category: 'software', available: true }, + ids: [1, 2, 3, 4], +} +const list = Array.from({ length: 16 }, (_, index) => ({ id: index })) +const listCopy = list.map((item) => ({ ...item })) +const listChanged = list.map((item, index) => + index === 10 ? { id: -1 } : { ...item }, +) +const listShared = list.map((item, index) => (index === 10 ? { id: -1 } : item)) +const wide = Object.fromEntries( + Array.from({ length: 12 }, (_, index) => [`key${index}`, `value${index}`]), +) +const wideChanged = { ...wide, key7: 'changed' } +const searchAllChanged = { + tab: 'other', + page: 3, + sort: 'oldest', + filter: 'sold', +} +const searchReordered = { + filter: 'available', + sort: 'newest', + page: 2, + tab: 'specs', +} +const searchSubset = { tab: 'specs', page: 2, sort: 'newest' } +const wider = Object.fromEntries( + Array.from({ length: 64 }, (_, index) => [`key${index}`, `value${index}`]), +) +const widerChangedLast = { ...wider, key63: 'changed' } +const widerChangedFirst = { ...wider, key0: 'changed' } +const widerAllChanged = Object.fromEntries( + Object.keys(wider).map((key) => [key, 'changed']), +) +const widerSubset = Object.fromEntries(Object.entries(wider).slice(0, 8)) +const numbers = Array.from({ length: 1024 }, (_, index) => index) +const numbersCopy = [...numbers] +const numbersChangedLast = numbers.map((n, index) => (index === 1023 ? -1 : n)) +const numbersChangedFirst = numbers.map((n, index) => (index === 0 ? -1 : n)) +const numbersChangedMiddle = numbers.map((n, index) => (index === 512 ? -1 : n)) +const numbersAllChanged = numbers.map((n) => -n - 1) +const numbersShorter = numbers.slice(0, 512) +const numbersLonger = [...numbers, undefined, undefined] +const smallNumbers = [1, 2, 3, 4] +const smallNumbersChanged = [9, 2, 3, 4] +const consumedNumbers = replaceEqualDeep(numbers, numbersChangedLast) +const longList = Array.from({ length: 1024 }, (_, id) => ({ id })) +const longListCopy = [...longList] +const longListClonedLast = [...longList] +longListClonedLast[1023] = { id: 1023 } +const longListChangedLast = [...longList] +longListChangedLast[1023] = { id: -1 } +const longListClonedThenChanged = [...longListChangedLast] +longListClonedThenChanged[1022] = { id: 1022 } +const numericCases = [ + ['fractional', Array.from({ length: 1024 }, (_, index) => index + 0.5)], + [ + 'large integer', + Array.from({ length: 1024 }, (_, index) => 2 ** 40 + index), + ], +] as const +const numericResults = numericCases.map(([name, prev]) => { + const next = [...prev] + next[1023] = -1.5 + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + return { name, prev, next, result } +}) +const mixedPairs: Array<[unknown, unknown]> = [ + [search, search], + [search, searchCopy], + [search, searchChanged], + [search, searchSubset], + [searchSubset, search], + [nested, nestedCopy], + [list, listChanged], + [list, listShared], + [smallNumbers, smallNumbersChanged], + [emptyNull, createNull()], + [searchWithConstructorKey, searchWithConstructorKeyCopy], +] + +expect(replaceEqualDeep(empty, {})).toBe(empty) +expect(replaceEqualDeep(search, searchCopy)).toBe(search) +expect(replaceEqualDeep(search, searchChanged)).toStrictEqual(searchChanged) +expect(nullReplaceEqualDeep(nullSearch, nullSearchCopy)).toBe(nullSearch) +expect(nullReplaceEqualDeep(nullSearch, searchCopy)).toBe(nullSearch) +expect(replaceEqualDeep(decimalRecord, decimalRecordCopy)).toBe(decimalRecord) +expect(replaceEqualDeep(decimalRecord, decimalRecordChanged)).toStrictEqual( + decimalRecordChanged, +) +expect(nullReplaceEqualDeep(nullSearch, nullSearchChanged)).toStrictEqual( + nullSearchChanged, +) +expect(replaceEqualDeep(nested, nestedCopy)).toBe(nested) +expect(replaceEqualDeep(nested, nestedLeafChanged).ids).toBe(nested.ids) +const nullNestedResult = nullReplaceEqualDeep(nested, nestedLeafChanged) +expect(nullNestedResult).toEqual(nestedLeafChanged) +expect(nullNestedResult.ids).toBe(nested.ids) +expect(Object.getPrototypeOf(nullNestedResult)).toBeNull() +expect(replaceEqualDeep(list, listCopy)).toBe(list) +expect(replaceEqualDeep(list, listChanged)[3]).toBe(list[3]) +expect(replaceEqualDeep(wide, wideChanged)).toStrictEqual(wideChanged) +expect(replaceEqualDeep(list, listShared)[3]).toBe(list[3]) +expect(replaceEqualDeep(search, searchAllChanged)).toStrictEqual( + searchAllChanged, +) +expect(replaceEqualDeep(search, searchReordered)).toBe(search) +expect(replaceEqualDeep(search, searchSubset)).toStrictEqual(searchSubset) +expect(replaceEqualDeep(wider, widerChangedLast)).toStrictEqual( + widerChangedLast, +) +expect(replaceEqualDeep(numbers, numbersCopy)).toBe(numbers) +expect(replaceEqualDeep(longList, longListCopy)).toBe(longList) +expect(replaceEqualDeep(longList, longListClonedLast)).toBe(longList) +expect(replaceEqualDeep(longList, longListChangedLast)).toStrictEqual( + longListChangedLast, +) +const sharedLongList = replaceEqualDeep(longList, longListClonedThenChanged) +expect(sharedLongList).toStrictEqual(longListClonedThenChanged) +expect(sharedLongList[1022]).toBe(longList[1022]) +expect(replaceEqualDeep(widerSubset, wider)).toStrictEqual(wider) +expect(replaceEqualDeep(wider, widerChangedFirst)).toStrictEqual( + widerChangedFirst, +) +expect(replaceEqualDeep(wider, widerAllChanged)).toStrictEqual(widerAllChanged) +expect(replaceEqualDeep(numbers, numbersChangedLast)[1023]).toBe(-1) +for (const [prev, next] of mixedPairs) { + expect(replaceEqualDeep(prev, next)).toStrictEqual(next) +} +for (const next of [ + numbersChangedFirst, + numbersChangedMiddle, + numbersAllChanged, + numbersShorter, + numbersLonger, +]) { + expect(replaceEqualDeep(numbers, next)).toStrictEqual(next) +} +expect(nullReplaceEqualDeep(emptyNull, {})).toBe(emptyNull) +expect( + nullReplaceEqualDeep(searchWithConstructorKey, searchWithConstructorKeyCopy), +).toBe(searchWithConstructorKey) +expect(deepEqual(search, searchCopy, true)).toBe(true) +expect(isPlainObject(search)).toBe(true) +expect(isPlainObject(emptyNull)).toBe(true) +expect(isPlainObject(searchWithConstructorKey)).toBe(true) +expect(isPlainObject(instance)).toBe(false) + +const iterations = 1_000 +let sink: unknown + +describe('isPlainObject', () => { + test('literal', async ({ bench }) => { + await bench('literal', () => { + for (let i = 0; i < iterations; i++) { + sink = isPlainObject(search) + } + }).run() + }) + + test('null-proto record', async ({ bench }) => { + await bench('null-proto record', () => { + for (let i = 0; i < iterations; i++) { + sink = isPlainObject(emptyNull) + } + }).run() + }) + + test('null-proto record with a constructor key', async ({ bench }) => { + await bench('null-proto record with a constructor key', () => { + for (let i = 0; i < iterations; i++) { + sink = isPlainObject(searchWithConstructorKey) + } + }).run() + }) + + test('class instance', async ({ bench }) => { + await bench('class instance', () => { + for (let i = 0; i < iterations; i++) { + sink = isPlainObject(instance) + } + }).run() + }) +}) + +describe('replaceEqualDeep', () => { + test('equal empty objects', async ({ bench }) => { + await bench('equal empty objects', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(empty, {}) + } + }).run() + }) + + test('equal empty null-proto objects', async ({ bench }) => { + await bench('equal empty null-proto objects', () => { + for (let i = 0; i < iterations; i++) { + sink = nullReplaceEqualDeep(emptyNull, createNull()) + } + }).run() + }) + + test('equal null-proto search with a constructor key', async ({ bench }) => { + await bench('equal null-proto search with a constructor key', () => { + for (let i = 0; i < iterations; i++) { + sink = nullReplaceEqualDeep( + searchWithConstructorKey, + searchWithConstructorKeyCopy, + ) + } + }).run() + }) + + test('equal flat search', async ({ bench }) => { + await bench('equal flat search', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(search, searchCopy) + } + }).run() + }) + + test('flat search with one changed leaf', async ({ bench }) => { + await bench('flat search with one changed leaf', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(search, searchChanged) + } + }).run() + }) + + test('equal parsed null-proto search', async ({ bench }) => { + await bench('equal parsed null-proto search', () => { + for (let i = 0; i < iterations; i++) { + sink = nullReplaceEqualDeep(nullSearch, nullSearchCopy) + } + }).run() + }) + + test('equal ordinary search against a null-proto previous value', async ({ + bench, + }) => { + await bench( + 'equal ordinary search against a null-proto previous value', + () => { + for (let i = 0; i < iterations; i++) { + sink = nullReplaceEqualDeep(nullSearch, searchCopy) + } + }, + ).run() + }) + + test('parsed null-proto search with one changed leaf', async ({ bench }) => { + await bench('parsed null-proto search with one changed leaf', () => { + for (let i = 0; i < iterations; i++) { + sink = nullReplaceEqualDeep(nullSearch, nullSearchChanged) + } + }).run() + }) + + test('ordinary search update in null-proto mode', async ({ bench }) => { + await bench('ordinary search update in null-proto mode', () => { + for (let i = 0; i < iterations; i++) { + sink = nullReplaceEqualDeep(nullSearch, searchChanged) + } + }).run() + }) + + test('equal ordinary search in null-proto mode', async ({ bench }) => { + await bench('equal ordinary search in null-proto mode', () => { + for (let i = 0; i < iterations; i++) { + sink = nullReplaceEqualDeep(search, searchCopy) + } + }).run() + }) + + test('successive ordinary search update in null-proto mode', async ({ + bench, + }) => { + await bench('successive ordinary search update in null-proto mode', () => { + for (let i = 0; i < iterations; i++) { + sink = nullReplaceEqualDeep(search, searchChanged) + } + }).run() + }) + + test('changed selector followed by the same incoming reference', async ({ + bench, + }) => { + await bench( + 'changed selector followed by the same incoming reference', + () => { + for (let i = 0; i < iterations; i++) { + const current = replaceEqualDeep(search, searchChanged) + sink = replaceEqualDeep(current, searchChanged) + } + }, + ).run() + }) + + test('equal record with decimal values', async ({ bench }) => { + await bench('equal record with decimal values', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(decimalRecord, decimalRecordCopy) + } + }).run() + }) + + test('changed record with decimal values', async ({ bench }) => { + await bench('changed record with decimal values', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(decimalRecord, decimalRecordChanged) + } + }).run() + }) + + test('equal nested search', async ({ bench }) => { + await bench('equal nested search', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(nested, nestedCopy) + } + }).run() + }) + + test('nested search sharing unchanged subtrees', async ({ bench }) => { + await bench('nested search sharing unchanged subtrees', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(nested, nestedLeafChanged) + } + }).run() + }) + + test('nested search sharing unchanged subtrees in null-proto mode', async ({ + bench, + }) => { + await bench( + 'nested search sharing unchanged subtrees in null-proto mode', + () => { + for (let i = 0; i < iterations; i++) { + sink = nullReplaceEqualDeep(nested, nestedLeafChanged) + } + }, + ).run() + }) + + test('equal array of objects', async ({ bench }) => { + await bench('equal array of objects', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(list, listCopy) + } + }).run() + }) + + test('array of objects with one changed item', async ({ bench }) => { + await bench('array of objects with one changed item', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(list, listChanged) + } + }).run() + }) + + test('wide flat object with one changed leaf', async ({ bench }) => { + await bench('wide flat object with one changed leaf', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(wide, wideChanged) + } + }).run() + }) + + test('wide flat object with one changed leaf (null-proto)', async ({ + bench, + }) => { + await bench('wide flat object with one changed leaf (null-proto)', () => { + for (let i = 0; i < iterations; i++) { + sink = nullReplaceEqualDeep(wide, wideChanged) + } + }).run() + }) + + test('flat search with all leaves changed', async ({ bench }) => { + await bench('flat search with all leaves changed', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(search, searchAllChanged) + } + }).run() + }) + + test('equal flat search with reordered keys', async ({ bench }) => { + await bench('equal flat search with reordered keys', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(search, searchReordered) + } + }).run() + }) + + test('flat search with a key removed', async ({ bench }) => { + await bench('flat search with a key removed', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(search, searchSubset) + } + }).run() + }) + + test('array of shared objects with one changed item', async ({ bench }) => { + await bench('array of shared objects with one changed item', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(list, listShared) + } + }).run() + }) + + test('wider flat object (64 keys) with the last leaf changed', async ({ + bench, + }) => { + await bench( + 'wider flat object (64 keys) with the last leaf changed', + () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(wider, widerChangedLast) + } + }, + ).run() + }) + + test('flat object growing from 8 to 64 keys', async ({ bench }) => { + await bench('flat object growing from 8 to 64 keys', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(widerSubset, wider) + } + }).run() + }) + + for (const [name, next] of [ + ['first leaf changed', widerChangedFirst], + ['all leaves changed', widerAllChanged], + ] as const) { + test(`wider flat object (64 keys) with ${name}`, async ({ bench }) => { + await bench(`wider flat object (64 keys) with ${name}`, () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(wider, next) + } + }).run() + }) + } + + test('equal long array of shared objects', async ({ bench }) => { + await bench('equal long array of shared objects', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(longList, longListCopy) + } + }).run() + }) + + for (const [name, next] of [ + ['cloned but equal', longListClonedLast], + ['changed', longListChangedLast], + ['changed after a cloned but equal item', longListClonedThenChanged], + ] as const) { + test(`long array of shared objects with the last item ${name}`, async ({ + bench, + }) => { + await bench( + `long array of shared objects with the last item ${name}`, + () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(longList, next) + } + }, + ).run() + }) + } + + for (const length of [0, 1, 4]) { + const prev = Array.from({ length }, (_, index) => index) + const next = [...prev] + expect(replaceEqualDeep(prev, next)).toBe(prev) + test(`equal primitive array of length ${length}`, async ({ bench }) => { + await bench(`equal primitive array of length ${length}`, () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(prev, next) + } + }).run() + }) + } + + test('equal long primitive array', async ({ bench }) => { + await bench('equal long primitive array', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(numbers, numbersCopy) + } + }).run() + }) + + test('long primitive array with the last item changed', async ({ bench }) => { + await bench('long primitive array with the last item changed', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(numbers, numbersChangedLast) + } + }).run() + }) + + for (const [name, next] of [ + ['first item changed', numbersChangedFirst], + ['middle item changed', numbersChangedMiddle], + ['all items changed', numbersAllChanged], + ['shortened', numbersShorter], + ['appended undefined values', numbersLonger], + ] as const) { + test(`long primitive array with ${name}`, async ({ bench }) => { + await bench(`long primitive array with ${name}`, () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(numbers, next) + } + }).run() + }) + } + + test('small primitive array with the first item changed', async ({ + bench, + }) => { + await bench('small primitive array with the first item changed', () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(smallNumbers, smallNumbersChanged) + } + }).run() + }) + + test('mixed search and array updates', async ({ bench }) => { + await bench('mixed search and array updates', () => { + for (let i = 0; i < iterations; i++) { + const [prev, next] = mixedPairs[i % mixedPairs.length]! + sink = replaceEqualDeep(prev, next) + } + }).run() + }) + + for (const { name, prev, next } of numericResults) { + test(`long ${name} array with the last item changed`, async ({ bench }) => { + await bench(`long ${name} array with the last item changed`, () => { + for (let i = 0; i < iterations; i++) { + sink = replaceEqualDeep(prev, next) + } + }).run() + }) + } +}) + +describe('consume structurally shared arrays', () => { + test('sum changed primitive array by index', async ({ bench }) => { + await bench('sum changed primitive array by index', () => { + for (let i = 0; i < iterations; i++) { + let sum = 0 + for (let j = 0; j < consumedNumbers.length; j++) { + sum += consumedNumbers[j]! + } + sink = sum + } + }).run() + }) + + test('reduce changed primitive array', async ({ bench }) => { + await bench('reduce changed primitive array', () => { + for (let i = 0; i < iterations; i++) { + sink = consumedNumbers.reduce((sum, value) => sum + value, 0) + } + }).run() + }) + + for (const { name, result } of numericResults) { + test(`sum changed ${name} array by index`, async ({ bench }) => { + await bench(`sum changed ${name} array by index`, () => { + for (let i = 0; i < iterations; i++) { + let sum = 0 + for (let j = 0; j < result.length; j++) { + sum += result[j]! + } + sink = sum + } + }).run() + }) + + test(`reduce changed ${name} array`, async ({ bench }) => { + await bench(`reduce changed ${name} array`, () => { + for (let i = 0; i < iterations; i++) { + sink = result.reduce((sum, value) => sum + value, 0) + } + }).run() + }) + } +}) + +describe('deepEqual', () => { + test('equal empty objects', async ({ bench }) => { + await bench('equal empty objects', () => { + for (let i = 0; i < iterations; i++) { + sink = deepEqual(empty, {}) + } + }).run() + }) + + test('equal flat search (partial)', async ({ bench }) => { + await bench('equal flat search (partial)', () => { + for (let i = 0; i < iterations; i++) { + sink = deepEqual(search, searchCopy, true) + } + }).run() + }) + + test('nested search with one changed leaf', async ({ bench }) => { + await bench('nested search with one changed leaf', () => { + for (let i = 0; i < iterations; i++) { + sink = deepEqual(nested, nestedLeafChanged) + } + }).run() + }) +}) + +export { sink } diff --git a/packages/router-core/tests/rewrite.bench.ts b/packages/router-core/tests/rewrite.bench.ts new file mode 100644 index 0000000000..1f7b88d610 --- /dev/null +++ b/packages/router-core/tests/rewrite.bench.ts @@ -0,0 +1,180 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute } from '../src' +import { + composeRewrites, + executeRewriteInput, + executeRewriteOutput, + rewriteBasepath, +} from '../src/rewrite' +import { createTestRouter } from './routerTestUtils' +import type { LocationRewrite } from '../src' + +describe.each([ + 'basepath only', + 'missing handlers', + 'input only', + 'output only', + 'noop', + 'mutation', + 'URL', + 'string', + 'nested composer', +] as const)('basepath composition (%s)', (returnType) => { + const unchanged = [ + 'basepath only', + 'missing handlers', + 'input only', + 'output only', + 'noop', + ].includes(returnType) + const transform = (url: URL, input: boolean) => { + if (unchanged) { + return + } + const result = + returnType === 'mutation' || returnType === 'nested composer' + ? url + : new URL(url) + result.pathname = input ? '/internal' : '/public' + if (returnType === 'URL') { + return result + } + if (returnType === 'string') { + return result.href + } + return + } + let custom: LocationRewrite | undefined = { + input: ({ url }) => transform(url, true), + output: ({ url }) => transform(url, false), + } + if (returnType === 'basepath only') { + custom = undefined + } else if (returnType === 'missing handlers') { + custom = {} + } else if (returnType === 'input only') { + delete custom.output + } else if (returnType === 'output only') { + delete custom.input + } else if (returnType === 'nested composer') { + custom = composeRewrites([ + custom, + {}, + { input: ({ url }) => url, output: ({ url }) => url }, + ]) + } + const history = createMemoryHistory({ initialEntries: ['/app/public'] }) + const router = createTestRouter({ + routeTree: new BaseRootRoute({}), + history, + basepath: '/app', + rewrite: custom, + scrollRestoration: false, + }) + history.destroy() + + for (const [name, rewrite] of [ + [ + custom ? 'public composer' : 'standalone basepath', + custom + ? composeRewrites([rewriteBasepath('/app'), custom]) + : rewriteBasepath('/app'), + ], + ['router composition', router.rewrite], + ] as const) { + let url = new URL('https://example.com/app/public?sort=name#title') + url = executeRewriteInput(rewrite, url) + expect(url.pathname).toBe(unchanged ? '/public' : '/internal') + url = executeRewriteOutput(rewrite, url) + expect(url.href).toBe('https://example.com/app/public?sort=name#title') + + test(`${name} round trip`, async ({ bench }) => { + await bench( + `${name} round trip`, + { + afterAll: () => { + expect(url.href).toBe( + 'https://example.com/app/public?sort=name#title', + ) + }, + }, + () => { + // Reuse the round-trip URL so URL construction does not hide the + // composition cost for callbacks that mutate or leave it unchanged. + for (let index = 0; index < 64; index++) { + url = executeRewriteOutput( + rewrite, + executeRewriteInput(rewrite, url), + ) + } + }, + ).run({ + time: 1000, + warmupTime: 200, + throws: true, + }) + }) + } + + let trailingSlash = false + test('router update rebuilding the rewrite', async ({ bench }) => { + await bench( + 'router update rebuilding the rewrite', + { + afterAll: () => { + expect(router.latestLocation.pathname).toBe( + unchanged ? '/public' : '/internal', + ) + }, + }, + () => { + if (custom) { + router.update({ rewrite: { ...custom } }) + } else { + trailingSlash = !trailingSlash + router.update({ basepath: trailingSlash ? '/app/' : '/app' }) + } + }, + ).run({ + time: 1000, + warmupTime: 200, + throws: true, + }) + }) +}) + +describe.each(['/', '/app'])('unchanged rewrite options (%s)', (basepath) => { + const history = createMemoryHistory({ + initialEntries: [basepath === '/' ? '/public' : '/app/public'], + }) + const router = createTestRouter({ + routeTree: new BaseRootRoute({}), + history, + basepath, + rewrite: { input: ({ url }) => url }, + scrollRestoration: false, + }) + history.destroy() + const rewrite = router.rewrite + router.update({}) + expect(router.rewrite).toBe(rewrite) + expect(router.latestLocation.pathname).toBe('/public') + + test('router update without rebuilding the rewrite', async ({ bench }) => { + await bench( + 'router update without rebuilding the rewrite', + { + afterAll: () => { + expect(router.rewrite).toBe(rewrite) + expect(router.latestLocation.pathname).toBe('/public') + }, + }, + () => router.update({}), + ).run({ + time: 1000, + warmupTime: 200, + throws: true, + }) + }) +}) diff --git a/packages/router-core/tests/rewrite.test.ts b/packages/router-core/tests/rewrite.test.ts new file mode 100644 index 0000000000..2494f050e5 --- /dev/null +++ b/packages/router-core/tests/rewrite.test.ts @@ -0,0 +1,404 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, composeRewrites } from '../src' +import { + executeRewriteInput, + executeRewriteOutput, + rewriteBasepath, +} from '../src/rewrite' +import { createTestRouter } from './routerTestUtils' +import type { LocationRewrite } from '../src' + +describe('rewrite helpers', () => { + test('basepath rewrite strips input and restores output', () => { + const rewrite = rewriteBasepath('/app/') + const inputUrl = new URL('https://example.com/app/posts') + + expect(executeRewriteInput(rewrite, inputUrl).pathname).toBe('/posts') + + const outputUrl = new URL('https://example.com/posts') + expect(executeRewriteOutput(rewrite, outputUrl).pathname).toBe('/app/posts') + }) + + test('basepath rewrite handles root output', () => { + const rewrite = rewriteBasepath('/app') + const url = new URL('https://example.com/') + + expect(executeRewriteOutput(rewrite, url).pathname).toBe('/app/') + }) + + test('case-insensitive basepath input preserves original suffix casing', () => { + const rewrite = rewriteBasepath('/App') + const url = new URL('https://example.com/app/Users') + + expect(executeRewriteInput(rewrite, url).pathname).toBe('/Users') + }) + + test('case-sensitive basepath input only strips an exact-case basepath', () => { + const rewrite = rewriteBasepath('/App', true) + + expect( + executeRewriteInput(rewrite, new URL('https://example.com/app/users')) + .pathname, + ).toBe('/app/users') + expect( + executeRewriteInput(rewrite, new URL('https://example.com/App/users')) + .pathname, + ).toBe('/users') + }) + + test('basepath rewrite output collapses repeated slashes', () => { + const rewrite = rewriteBasepath('/app') + const url = new URL('https://example.com/') + url.pathname = '/posts//1' + + expect(executeRewriteOutput(rewrite, url).pathname).toBe('/app/posts/1') + }) + + test('composeRewrites applies input forward and output backward', () => { + const calls: Array = [] + const first: LocationRewrite = { + input: ({ url }) => { + calls.push('first-in') + url.pathname += 'a' + return url + }, + output: ({ url }) => { + calls.push('first-out') + url.pathname += 'd' + return url + }, + } + const second: LocationRewrite = { + input: ({ url }) => { + calls.push('second-in') + url.pathname += 'b' + return url + }, + output: ({ url }) => { + calls.push('second-out') + url.pathname += 'c' + return url + }, + } + + const rewrite = composeRewrites([first, second]) + + expect( + executeRewriteInput(rewrite, new URL('https://example.com/')).pathname, + ).toBe('/ab') + expect( + executeRewriteOutput(rewrite, new URL('https://example.com/')).pathname, + ).toBe('/cd') + expect(calls).toEqual(['first-in', 'second-in', 'second-out', 'first-out']) + }) + + test('composeRewrites supports arbitrary chains and mixed return types', () => { + const rewrite = composeRewrites([ + { + input: ({ url }): undefined => { + url.pathname += 'a' + }, + output: ({ url }): undefined => { + url.pathname += 'd' + }, + }, + {}, + { + input: ({ url }) => `${url.href}b`, + output: ({ url }) => `${url.href}c`, + }, + { + input: ({ url }) => new URL(`${url.href}c`), + output: ({ url }) => new URL(`${url.href}b`), + }, + { + output: ({ url }): undefined => { + url.pathname += 'a' + }, + }, + ]) + + expect( + executeRewriteInput(rewrite, new URL('https://example.com/')).pathname, + ).toBe('/abc') + expect( + executeRewriteOutput(rewrite, new URL('https://example.com/')).pathname, + ).toBe('/abcd') + }) + + test('composeRewrites accepts an empty chain', () => { + const rewrite = composeRewrites([]) + const url = new URL('https://example.com/posts') + + expect(executeRewriteInput(rewrite, url)).toBe(url) + expect(executeRewriteOutput(rewrite, url)).toBe(url) + }) +}) + +describe('router rewrites', () => { + test.each([undefined, '/', '', '///'])( + 'keeps the direct rewrite path for basepath %s', + (basepath) => { + const router = createTestRouter({ + routeTree: new BaseRootRoute({}), + history: createMemoryHistory({ initialEntries: ['/public'] }), + basepath, + }) + + expect(router.rewrite).toBeUndefined() + expect(router.latestLocation.pathname).toBe('/public') + expect(router.buildLocation({ to: '/public' }).publicHref).toBe('/public') + + const rewrite: LocationRewrite = { input: ({ url }) => url } + router.update({ rewrite }) + expect(router.rewrite).toBe(rewrite) + expect(router.state.location.pathname).toBe('/public') + }, + ) + + test.each([ + [undefined, '/app/Users', '/Users'], + [false, '/app/Users', '/Users'], + [true, '/app/Users', '/app/Users'], + [true, '/App/Users', '/Users'], + ] as const)( + 'initializes basepath with caseSensitive %s at %s', + (caseSensitive, pathname, expected) => { + const router = createTestRouter({ + routeTree: new BaseRootRoute({}), + history: createMemoryHistory({ initialEntries: [pathname] }), + basepath: '/App', + caseSensitive, + }) + + expect(router.latestLocation.pathname).toBe(expected) + expect(router.state.location.pathname).toBe(expected) + }, + ) + + test.each([false, true])( + 'updates basepath case sensitivity and stored location (custom rewrite: %s)', + (customRewrite) => { + const router = createTestRouter({ + routeTree: new BaseRootRoute({}), + history: createMemoryHistory({ initialEntries: ['/app/Users'] }), + basepath: '/App', + rewrite: customRewrite ? { input: ({ url }) => url } : undefined, + }) + + expect(router.state.location.pathname).toBe('/Users') + + router.update({ caseSensitive: true }) + expect(router.latestLocation.pathname).toBe('/app/Users') + expect(router.state.location.pathname).toBe('/app/Users') + + router.update({ caseSensitive: false }) + expect(router.latestLocation.pathname).toBe('/Users') + expect(router.state.location.pathname).toBe('/Users') + expect(router.buildLocation({ to: '/Users' }).publicHref).toBe( + '/App/Users', + ) + }, + ) + + test.each(['mutation', 'URL', 'string'] as const)( + 'composes basepath around custom rewrites returning %s', + (returnType) => { + const calls: Array = [] + const rewrite = (url: URL, direction: 'input' | 'output') => { + calls.push(`${direction}:${url.pathname}`) + const result = returnType === 'mutation' ? url : new URL(url) + result.pathname = direction === 'input' ? '/internal' : '/public' + if (returnType === 'URL') { + return result + } + if (returnType === 'string') { + return result.href + } + return + } + const router = createTestRouter({ + routeTree: new BaseRootRoute({}), + history: createMemoryHistory({ initialEntries: ['/app/public'] }), + basepath: '/app', + rewrite: { + input: ({ url }) => rewrite(url, 'input'), + output: ({ url }) => rewrite(url, 'output'), + }, + }) + + expect(router.latestLocation.pathname).toBe('/internal') + expect(calls).toEqual(['input:/public']) + expect(router.buildLocation({ to: '/internal' }).publicHref).toBe( + '/app/public', + ) + expect(calls).toEqual(['input:/public', 'output:/internal']) + }, + ) + + test('rebuilds rewrites and stored locations when basepath or custom rewrite changes', () => { + const router = createTestRouter({ + routeTree: new BaseRootRoute({}), + history: createMemoryHistory({ initialEntries: ['/app/public'] }), + basepath: '/app', + rewrite: { + input: ({ url }): undefined => { + url.pathname = url.pathname.replace('/public', '/internal') + }, + output: ({ url }): undefined => { + url.pathname = url.pathname.replace('/internal', '/public') + }, + }, + }) + const checkLocations = (pathname: string, outputHref: string) => { + expect(router.latestLocation).toMatchObject({ + pathname, + publicHref: '/app/public', + }) + expect(router.state.location).toMatchObject({ + pathname, + publicHref: '/app/public', + }) + expect(router.buildLocation({ to: '/internal' }).publicHref).toBe( + outputHref, + ) + } + + checkLocations('/internal', '/app/public') + router.update({ basepath: '/other' }) + checkLocations('/app/internal', '/other/public') + + router.update({ + rewrite: { + input: ({ url }) => new URL('/replacement', url), + output: ({ url }) => new URL('/updated', url), + }, + }) + checkLocations('/replacement', '/other/updated') + + router.update({ rewrite: undefined }) + checkLocations('/app/public', '/other/internal') + + router.update({ basepath: '/' }) + checkLocations('/app/public', '/internal') + expect(router.rewrite).toBeUndefined() + }) + + test.each(['URL', 'string'] as const)( + 'preserves query, hash, and external origin from a custom %s output', + (returnType) => { + const router = createTestRouter({ + routeTree: new BaseRootRoute({}), + history: createMemoryHistory({ initialEntries: ['/app/internal'] }), + origin: 'https://example.com', + basepath: '/app', + rewrite: { + output: ({ url }) => { + const rewritten = new URL(url) + rewritten.hostname = 'external.example' + rewritten.pathname = '/public' + return returnType === 'URL' ? rewritten : rewritten.href + }, + }, + }) + + expect( + router.buildLocation({ + to: '/internal', + search: { sort: 'name' }, + hash: 'section', + }), + ).toMatchObject({ + publicHref: 'https://external.example/app/public?sort=name#section', + external: true, + search: { sort: 'name' }, + hash: 'section', + }) + }, + ) + + test.each(['input', 'output'] as const)( + 'composes basepath with a custom rewrite providing only %s', + (direction) => { + const router = createTestRouter({ + routeTree: new BaseRootRoute({}), + history: createMemoryHistory({ initialEntries: ['/app/original'] }), + basepath: '/app', + rewrite: { + [direction]: ({ url }: { url: URL }): undefined => { + url.pathname = '/rewritten' + }, + }, + }) + + expect(router.latestLocation.pathname).toBe( + direction === 'input' ? '/rewritten' : '/original', + ) + expect(router.buildLocation({ to: '/original' }).publicHref).toBe( + direction === 'output' ? '/app/rewritten' : '/app/original', + ) + }, + ) + + test('reads custom handlers added, replaced, or removed after composition', () => { + const rewrite: LocationRewrite = {} + const router = createTestRouter({ + routeTree: new BaseRootRoute({}), + history: createMemoryHistory({ initialEntries: ['/app/public'] }), + basepath: '/app', + rewrite, + }) + const parse = () => router.parseLocation(router.history.location).pathname + + expect(parse()).toBe('/public') + rewrite.input = ({ url }): undefined => { + url.pathname = '/internal' + } + rewrite.output = ({ url }): undefined => { + url.pathname = '/public' + } + expect(parse()).toBe('/internal') + expect(router.buildLocation({ to: '/internal' }).publicHref).toBe( + '/app/public', + ) + + rewrite.input = ({ url }) => new URL('/replaced', url) + expect(parse()).toBe('/replaced') + + delete rewrite.input + delete rewrite.output + expect(parse()).toBe('/public') + expect(router.buildLocation({ to: '/internal' }).publicHref).toBe( + '/app/internal', + ) + }) + + test('composes a nested public rewrite chain inside the basepath', () => { + const router = createTestRouter({ + routeTree: new BaseRootRoute({}), + history: createMemoryHistory({ initialEntries: ['/app/public'] }), + basepath: '/app', + rewrite: composeRewrites([ + { + input: ({ url }): undefined => { + url.pathname = url.pathname.replace('/public', '/intermediate') + }, + output: ({ url }): undefined => { + url.pathname = url.pathname.replace('/intermediate', '/public') + }, + }, + { + input: ({ url }) => url.href.replace('/intermediate', '/internal'), + output: ({ url }) => + new URL(url.href.replace('/internal', '/intermediate')), + }, + ]), + }) + + expect(router.latestLocation.pathname).toBe('/internal') + expect(router.buildLocation({ to: '/internal' }).publicHref).toBe( + '/app/public', + ) + }) +}) diff --git a/packages/router-core/tests/route-initialization.test.ts b/packages/router-core/tests/route-initialization.test.ts new file mode 100644 index 0000000000..8d44447b43 --- /dev/null +++ b/packages/router-core/tests/route-initialization.test.ts @@ -0,0 +1,60 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { processRouteTree } from '../src/new-process-route-tree' +import type { AnyRoute } from '../src' + +afterEach(() => vi.restoreAllMocks()) + +test('initializes routes parent-first before reading their IDs and paths', () => { + const root = new BaseRootRoute({}) + const layout = new BaseRoute({ + getParentRoute: () => root, + path: '/layout', + }) + const child = new BaseRoute({ + getParentRoute: () => layout, + path: '/$id', + }) + const sibling = new BaseRoute({ + getParentRoute: () => root, + path: '/sibling', + }) + const routes = [root, layout, child, sibling] + const calls = routes.map((route) => vi.spyOn(route, 'init')) + const { routesById } = processRouteTree( + root.addChildren([layout.addChildren([child]), sibling]), + ) + for (const [originalIndex, init] of calls.entries()) { + expect(init).toHaveBeenCalledExactlyOnceWith(originalIndex) + expect(routes[originalIndex]!.originalIndex).toBe(originalIndex) + } + const order = calls.map((init) => init.mock.invocationCallOrder[0]!) + expect(order).toEqual([...order].sort((a, b) => a - b)) + expect(root.id).toBe('__root__') + expect(child.fullPath).toBe('/layout/$id') + for (const route of routes) { + expect(routesById[route.id]).toBe(route) + } +}) + +test('normalizes nested route IDs without changing pathless layout paths', () => { + const root = new BaseRootRoute({}) + const layout = new BaseRoute({ + getParentRoute: () => root, + id: '//_layout//', + }) + const item = new BaseRoute({ + getParentRoute: () => layout, + path: '//items//$id//', + }) + const { routesById } = processRouteTree( + root.addChildren([layout.addChildren([item])]), + ) + expect(root.id).toBe('__root__') + expect(layout.id).toBe('/_layout/') + expect(layout.fullPath).toBe('/') + expect(item.id).toBe('/_layout/items/$id/') + expect(item.fullPath).toBe('/items/$id/') + expect(item.to).toBe('/items/$id') + expect(routesById[item.id]).toBe(item) +}) diff --git a/packages/router-core/tests/route-interpolation.test.ts b/packages/router-core/tests/route-interpolation.test.ts new file mode 100644 index 0000000000..8743f8bc04 --- /dev/null +++ b/packages/router-core/tests/route-interpolation.test.ts @@ -0,0 +1,280 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { + cleanPath, + compileDecodeCharMap, + hasMissingPathParams, + interpolatePath, +} from '../src/path' +import * as routeTreeUtils from '../src/new-process-route-tree' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => vi.restoreAllMocks()) + +test.each([ + { path: '/static', params: {}, missing: false }, + { path: '/$id', params: {}, missing: true }, + { path: '/$id', params: { id: undefined }, missing: false }, + { path: '/$id', params: { id: '' }, missing: false }, + { path: '/{-$id}', params: {}, missing: false }, + { path: '/pre{-$id}suffix', params: { id: null }, missing: false }, + { path: '/files/$', params: {}, missing: true }, + { path: '/files/$', params: { _splat: null }, missing: true }, + { path: '/files/$', params: { _splat: '' }, missing: true }, + { path: '/files/{$}.txt', params: { _splat: 0 }, missing: false }, + { path: '/files/{$}.txt', params: { _splat: false }, missing: false }, + { path: '/files/$/ignored', params: { _splat: 'a/b' }, missing: false }, +])( + 'preserves navigation availability for $path: $params', + ({ path, params, missing }) => { + const segments = routeTreeUtils.parseSegments(false, { fullPath: path }, 0) + expect(hasMissingPathParams(segments, params)).toBe(missing) + }, +) + +test('encodes splats equivalently without interpreting literal encoded separators', () => { + const segments = routeTreeUtils.parseSegments( + false, + { fullPath: '/files/$' }, + 0, + ) + for (const allowed of [[], ['@', '+'], ['%'], ['/']]) { + const decoder = compileDecodeCharMap(allowed) + for (const value of [ + '/a//b/', + 'docs/a b/c+d?x#y', + 'literal%2F/100%/caf\u00e9', + 'folder/\u6f22\u5b57/file', + ]) { + const expected = value + .split('/') + .map((part) => decoder(encodeURIComponent(part))) + .join('/') + expect( + interpolatePath('/files/$', segments, { _splat: value }, decoder), + ).toBe(`/files/${expected}`) + } + } +}) + +describe.each([false, true])( + 'prepared route interpolation (server: %s)', + (server) => { + test.each([ + '/', + '/static/path/', + '/items/$id', + '/$id/$id/', + '/items/Pre{$id}Suffix/{-$lang}', + '/items/Pre{-$id}Suffix/$lang', + '/files/$', + '/files/Pre{$}Suffix/', + '/files/$/child', + '/{-$lang}/files/{$}.txt', + '//items//$id//', + '/literal$dollar/{$id}/', + ])('keeps substitution and metadata live for %s', (path) => { + const root = new BaseRootRoute({}) + const route = new BaseRoute({ getParentRoute: () => root, path }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + createTestRouter({ + routeTree: root.addChildren([route]), + history, + isServer: server, + scrollRestoration: false, + }) + history.destroy() + // The reference is the standalone parse buildLocation uses for templates + // without a processed route. + const template = routeTreeUtils.parseSegments( + false, + { fullPath: cleanPath(path) }, + 0, + ) + const decoder = compileDecodeCharMap(['@', '+']) + const inputs: Array> = [ + {}, + { id: '', lang: null, _splat: '' }, + { id: 'one /@+?', lang: 'en', _splat: 'docs/a b/100%' }, + { id: 0, lang: false, _splat: 0 }, + { id: 'next', lang: undefined, _splat: 'next/file' }, + ] + for (const params of [...inputs, ...inputs]) { + const expectedUsed = Object.create(null) + const actualUsed = Object.create(null) + const expected = interpolatePath( + path, + template, + params, + decoder, + expectedUsed, + ) + expect( + route._interpolation + ? interpolatePath( + path, + route._interpolation, + params, + decoder, + actualUsed, + ) + : path, + ).toBe(expected) + expect(actualUsed).toEqual(expectedUsed) + expect( + route._interpolation + ? routeTreeUtils.getParamNames(route._interpolation) + : [], + ).toEqual(routeTreeUtils.getParamNames(template)) + expect( + route._interpolation + ? hasMissingPathParams(route._interpolation, params) + : false, + ).toBe(hasMissingPathParams(template, params)) + } + }) + + test('does not change prepared segments when an encoder throws', () => { + const root = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => root, + path: '/$first/{-$second}', + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + createTestRouter({ + routeTree: root.addChildren([route]), + history, + isServer: server, + scrollRestoration: false, + }) + history.destroy() + const prepared = route._interpolation + expect(prepared).toBeDefined() + expect(() => + interpolatePath(route.fullPath, route._interpolation!, { + first: '\uD800', + second: 'two', + }), + ).toThrow(URIError) + expect(route._interpolation).toBe(prepared) + expect( + interpolatePath(route.fullPath, route._interpolation!, { + first: 'one', + second: 'two', + }), + ).toBe('/one/two') + }) + }, +) + +test('never reparses a processed route for first use, Link misses or match metadata', () => { + const root = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => root, + path: '/items/Pre{$id}Suffix/{-$lang}', + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: root.addChildren([route]), + history, + pathParamsAllowedCharacters: ['@'], + scrollRestoration: false, + }) + history.destroy() + const prepared = route._interpolation + expect(prepared).toBeDefined() + const parse = vi.spyOn(routeTreeUtils, 'parseSegments') + routeTreeUtils.parseSegments( + false, + { fullPath: '/unregistered-control/$id' }, + 0, + ) + expect(parse).toHaveBeenCalled() + parse.mockClear() + router.buildLocation({ + to: '/items/Pre{$id}Suffix/{-$lang}', + params: { id: 'first' }, + }) + for (let id = 0; id < 256; id++) { + expect( + router.buildLocation({ + to: '/items/Pre{$id}Suffix/{-$lang}', + params: { id: String(id), lang: 'en' }, + }).href, + ).toBe(`/items/Pre${id}Suffix/en`) + expect( + router.matchRoutes(`/items/Pre${id}Suffix/en`, {}).at(-1)?._strictParams, + ).toEqual({ id: String(id), lang: 'en' }) + } + expect( + router.buildLocation({ + to: '/items/Pre{$id}Suffix/{-$lang}', + params: { id: '@last' }, + }).href, + ).toBe('/items/Pre@lastSuffix') + expect(route._interpolation).toBe(prepared) + expect(parse).not.toHaveBeenCalled() +}) + +test.each([false, true])( + 'uses prepared segments for either trailing slash variant (server: %s)', + (server) => { + const root = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => root, + path: '/files/pre{$}.txt/', + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + createTestRouter({ + routeTree: root.addChildren([route]), + history, + isServer: server, + scrollRestoration: false, + }) + history.destroy() + const parse = vi.spyOn(routeTreeUtils, 'parseSegments') + for (const path of [ + '/files/pre{$}.txt', + '/files/pre{$}.txt/', + '/files/pre{$}.txt', + ]) { + expect( + interpolatePath(path, route._interpolation!, { _splat: 'a/b' }), + ).toBe(path.endsWith('/') ? '/files/prea/b.txt//' : '/files/prea/b.txt') + } + expect(parse).not.toHaveBeenCalled() + }, +) + +test.each([false, true])( + 'preserves inherited wildcard tails (server: %s)', + (server) => { + for (const path of ['/files/{$}.txt', '/{-$lang}/files/$', '/files/$']) { + const root = new BaseRootRoute({}) + const parent = new BaseRoute({ getParentRoute: () => root, path }) + const child = new BaseRoute({ + getParentRoute: () => parent, + path: '/child', + }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + createTestRouter({ + routeTree: root.addChildren([parent.addChildren([child])]), + history, + isServer: server, + scrollRestoration: false, + }) + history.destroy() + const params = { _splat: 'a/b', lang: 'en' } + expect( + interpolatePath(child.fullPath, child._interpolation!, params), + ).toBe( + interpolatePath( + child.fullPath, + routeTreeUtils.parseSegments(false, { fullPath: child.fullPath }, 0), + params, + ), + ) + } + }, +) diff --git a/packages/router-core/tests/route-tree-caches.test.ts b/packages/router-core/tests/route-tree-caches.test.ts new file mode 100644 index 0000000000..5f2f4721cf --- /dev/null +++ b/packages/router-core/tests/route-tree-caches.test.ts @@ -0,0 +1,415 @@ +import { afterEach, beforeEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import * as routeTreeUtils from '../src/new-process-route-tree' +import { createRequestHandler } from '../src/ssr/createRequestHandler' +import { createTestRouter } from './routerTestUtils' +import type { AnyRoute, AnyRouter } from '../src' + +const disposers: Array<() => void> = [] + +beforeEach(() => { + vi.stubEnv('NODE_ENV', 'production') + vi.stubGlobal('__TSR_CACHE__', undefined) +}) + +afterEach(() => { + for (const dispose of disposers.splice(0)) { + dispose() + } + vi.restoreAllMocks() + vi.unstubAllGlobals() + vi.unstubAllEnvs() +}) + +function createRoutes() { + const root = new BaseRootRoute({}) + const item = new BaseRoute({ + getParentRoute: () => root, + path: '/items/$id', + }) + return { root, item, routeTree: root.addChildren([item]) } +} + +function history() { + const result = createMemoryHistory({ initialEntries: ['/'] }) + disposers.push(result.destroy) + return result +} + +test.each([false, true])( + 'builds canonical pathnames and encoded hrefs (server: %s)', + (isServer) => { + const { routeTree } = createRoutes() + const router = createTestRouter({ routeTree, history: history(), isServer }) + for (const [id, pathname, href] of [ + ['one two', '/items/one two', '/items/one%20two'], + ['caf\u00e9', '/items/caf\u00e9', '/items/caf%C3%A9'], + ['a/b', '/items/a%2Fb', '/items/a%2Fb'], + ['%2F', '/items/%252F', '/items/%252F'], + ['a\\b', '/items/a%5Cb', '/items/a%5Cb'], + ['a?b#c', '/items/a%3Fb%23c', '/items/a%3Fb%23c'], + ['a\tb', '/items/a%09b', '/items/a%09b'], + ] as const) { + for (let repeat = 0; repeat < 2; repeat++) { + const result = router.buildLocation({ + to: '/items/$id', + params: { id }, + }) + expect(result.pathname).toBe(pathname) + expect(result.href).toBe(href) + } + } + }, +) + +test('reuses server caches after request cleanup without sharing match state', async () => { + const { routeTree, item, root } = createRoutes() + const routers: Array = [] + const request = () => + createRequestHandler({ + request: new Request('http://localhost/'), + createRouter: () => { + const router = createTestRouter({ routeTree, isServer: true }) + routers.push(router) + return router + }, + })(({ router }) => { + disposers.push(router.history.destroy) + return new Response( + router.buildLocation({ + to: '/items/$id', + params: { id: 'one two' }, + }).href, + ) + }) + + expect(await (await request()).text()).toBe('/items/one%20two') + const branch = item._branch + const firstLocation = routers[0]!.latestLocation + const lightweightResult = routers[0]!['lightweightCache'].get(firstLocation) + expect(branch).toEqual([root, item]) + expect(lightweightResult).toBeDefined() + + expect(await (await request()).text()).toBe('/items/one%20two') + expect(item._branch).toBe(branch) + expect(routers[0]).not.toBe(routers[1]) + expect(routers[0]!.resolvePathCache).toBe(routers[1]!.resolvePathCache) + expect(routers[0]!['lightweightCache']).not.toBe( + routers[1]!['lightweightCache'], + ) + expect(routers[1]!['lightweightCache'].get(firstLocation)).toBeUndefined() + expect(routers[1]!.latestLocation).not.toBe(firstLocation) + expect(routers[0]!._cache).not.toBe(routers[1]!._cache) +}) + +test.each([ + { mode: 'production', isServer: false }, + { mode: 'development', isServer: true }, +])( + 'does not share router cache groups in $mode (server: $isServer)', + ({ mode, isServer }) => { + vi.stubEnv('NODE_ENV', mode) + const first = createTestRouter({ + routeTree: createRoutes().routeTree, + history: history(), + isServer, + }) + const second = createTestRouter({ + routeTree: createRoutes().routeTree, + history: history(), + isServer, + }) + expect(first.resolvePathCache).not.toBe(second.resolvePathCache) + expect(first['lightweightCache']).not.toBe(second['lightweightCache']) + expect(globalThis.__TSR_CACHE__).toBeUndefined() + }, +) + +test.each(['production', 'development'])( + 'refreshes server matching caches when case sensitivity changes in %s', + (mode) => { + vi.stubEnv('NODE_ENV', mode) + const { root, item } = createRoutes() + const strict = new BaseRoute({ + getParentRoute: () => root, + path: '/strict', + caseSensitive: true, + }) + const relaxed = new BaseRoute({ + getParentRoute: () => root, + path: '/relaxed', + caseSensitive: false, + }) + const router = createTestRouter({ + routeTree: root.addChildren([item, strict, relaxed]), + history: history(), + isServer: true, + caseSensitive: false, + }) + expect(router.getMatchedRoutes('/ITEMS/one')[2]).toBe(item) + + for (const caseSensitive of [true, false]) { + router.buildLocation({ + to: '/items/$id', + params: { id: 'one' }, + search: true, + }) + const previousTree = router.processedTree + const previousResolve = router.resolvePathCache + const previousLightweight = router['lightweightCache'] + expect(previousTree.matchCache.get('/ITEMS/one')).toBeDefined() + expect(previousLightweight.get(router.latestLocation)).toBeDefined() + + router.update({ caseSensitive }) + + expect(router.processedTree).not.toBe(previousTree) + expect(router.resolvePathCache).not.toBe(previousResolve) + expect(router['lightweightCache']).not.toBe(previousLightweight) + expect(router.getMatchedRoutes('/ITEMS/one')[2] === item).toBe( + !caseSensitive, + ) + expect(router.getMatchedRoutes('/items/one')[2]).toBe(item) + expect(router.getMatchedRoutes('/STRICT')[2]).not.toBe(strict) + expect(router.getMatchedRoutes('/strict')[2]).toBe(strict) + expect(router.getMatchedRoutes('/RELAXED')[2]).toBe(relaxed) + + const currentTree = router.processedTree + router.update({ caseSensitive }) + expect(router.processedTree).toBe(currentTree) + } + }, +) + +test.each([false, true])( + 'only reuses a server route tree with matching case sensitivity (cached: %s)', + (caseSensitive) => { + const { routeTree, item } = createRoutes() + const createRouter = (sensitive: boolean) => + createTestRouter({ + routeTree, + history: history(), + isServer: true, + caseSensitive: sensitive, + }) + const first = createRouter(caseSensitive) + expect(first.getMatchedRoutes('/ITEMS/one')[2] === item).toBe( + !caseSensitive, + ) + + const same = createRouter(caseSensitive) + expect(same.processedTree).toBe(first.processedTree) + expect(same.resolvePathCache).toBe(first.resolvePathCache) + + const different = createRouter(!caseSensitive) + expect(different.processedTree).not.toBe(first.processedTree) + expect(different.resolvePathCache).not.toBe(first.resolvePathCache) + expect(different.getMatchedRoutes('/ITEMS/one')[2] === item).toBe( + caseSensitive, + ) + expect(different.getMatchedRoutes('/items/one')[2]).toBe(item) + + const reused = createRouter(caseSensitive) + expect(reused.processedTree).toBe(first.processedTree) + for (const router of [first, same, reused]) { + expect(router.getMatchedRoutes('/ITEMS/one')[2] === item).toBe( + !caseSensitive, + ) + expect(router.getMatchedRoutes('/items/one')[2]).toBe(item) + } + }, +) + +test('never accesses the server cache on the client', () => { + const getCache = vi.fn(() => { + throw new Error('Client read the server cache') + }) + const setCache = vi.fn(() => { + throw new Error('Client wrote the server cache') + }) + Object.defineProperty(globalThis, '__TSR_CACHE__', { + configurable: true, + get: getCache, + set: setCache, + }) + const router = createTestRouter({ + routeTree: createRoutes().routeTree, + history: history(), + isServer: false, + caseSensitive: false, + }) + const processedTree = router.processedTree + router.update({ caseSensitive: true }) + expect(router.processedTree).toBe(processedTree) + router.update({ routeTree: createRoutes().routeTree }) + expect(getCache).not.toHaveBeenCalled() + expect(setCache).not.toHaveBeenCalled() +}) + +test('keeps different route objects independent and resets derived caches when rebuilding', () => { + vi.stubEnv('NODE_ENV', 'development') + const firstTree = createRoutes() + const secondTree = createRoutes() + const first = createTestRouter({ + routeTree: firstTree.routeTree, + history: history(), + }) + const second = createTestRouter({ + routeTree: secondTree.routeTree, + history: history(), + }) + for (const router of [first, second]) { + expect( + router.buildLocation({ to: '/items/$id', params: { id: 'one' } }).href, + ).toBe('/items/one') + } + expect(firstTree.item._branch).not.toBe(secondTree.item._branch) + expect(firstTree.item._interpolation).not.toBe(secondTree.item._interpolation) + + const previousResolve = first.resolvePathCache + const previousLightweight = first['lightweightCache'] + const previousBranch = firstTree.item._branch + const previousInterpolation = firstTree.item._interpolation + first.setRoutes(first.buildRouteTree()) + expect(first.resolvePathCache).not.toBe(previousResolve) + expect(first['lightweightCache']).not.toBe(previousLightweight) + expect(firstTree.item._branch).toBeUndefined() + expect(firstTree.item._interpolation).not.toBe(previousInterpolation) + expect([...firstTree.item._interpolation!]).toEqual([ + ...previousInterpolation!, + ]) + expect( + first.buildLocation({ to: '/items/$id', params: { id: 'one' } }).href, + ).toBe('/items/one') + expect(firstTree.item._branch).not.toBe(previousBranch) +}) + +test('refreshes branches and segments when an existing route is reparented', () => { + vi.stubEnv('NODE_ENV', 'development') + const root = new BaseRootRoute({}) + const left = new BaseRoute({ getParentRoute: () => root, path: '/left' }) + const right = new BaseRoute({ getParentRoute: () => root, path: '/right' }) + let parent: AnyRoute = left + const child = new BaseRoute({ + getParentRoute: () => parent, + path: '/child/$id', + }) + const router = createTestRouter({ + routeTree: root.addChildren([left.addChildren([child]), right]), + history: history(), + }) + expect( + router.buildLocation({ to: '/left/child/$id', params: { id: 'one two' } }) + .href, + ).toBe('/left/child/one%20two') + expect(child._branch).toEqual([root, left, child]) + const previousInterpolation = child._interpolation + + parent = right + left.addChildren([]) + right.addChildren([child]) + router.setRoutes(router.buildRouteTree()) + expect(child._branch).toBeUndefined() + expect(child._interpolation).not.toBe(previousInterpolation) + expect(child.fullPath).toBe('/right/child/$id') + expect(child._interpolation?.[0]).toBe('/right/child') + const parse = vi.spyOn(routeTreeUtils, 'parseSegments') + expect( + router.buildLocation({ to: '/right/child/$id', params: { id: 'one two' } }) + .href, + ).toBe('/right/child/one%20two') + expect(child._branch).toEqual([root, right, child]) + expect(parse).not.toHaveBeenCalled() +}) + +test('uses updated callbacks with rebuilt segments in development', () => { + vi.stubEnv('NODE_ENV', 'development') + const { routeTree, item } = createRoutes() + const router = createTestRouter({ routeTree, history: history() }) + expect( + router.buildLocation({ to: '/items/$id', params: { id: 'one' } }).href, + ).toBe('/items/one') + const prepared = item._interpolation + item.options.params = { + stringify: ({ id }) => ({ id: `updated ${id}` }), + } + router.setRoutes(router.buildRouteTree()) + expect(item._interpolation).not.toBe(prepared) + const parse = vi.spyOn(routeTreeUtils, 'parseSegments') + expect( + router.buildLocation({ to: '/items/$id', params: { id: 'one' } }).href, + ).toBe('/items/updated%20one') + expect(parse).not.toHaveBeenCalled() +}) + +test('uses fixed encodings and trailing-slash policies on independent routes', () => { + const allowAt = createTestRouter({ + routeTree: createRoutes().routeTree, + history: history(), + isServer: true, + trailingSlash: 'never', + pathParamsAllowedCharacters: ['@'], + }) + const allowPlus = createTestRouter({ + routeTree: createRoutes().routeTree, + history: history(), + isServer: true, + trailingSlash: 'always', + pathParamsAllowedCharacters: ['+'], + }) + for (let round = 0; round < 3; round++) { + expect( + allowAt.buildLocation({ to: '/items/$id', params: { id: '@+' } }) + .pathname, + ).toBe('/items/@%2B') + expect( + allowPlus.buildLocation({ to: '/items/$id', params: { id: '@+' } }) + .pathname, + ).toBe('/items/%40+/') + } + const allowAtWithSlash = createTestRouter({ + routeTree: createRoutes().routeTree, + history: history(), + isServer: true, + trailingSlash: 'always', + pathParamsAllowedCharacters: ['@'], + }) + expect( + allowAtWithSlash.buildLocation({ to: '/items/$id', params: { id: '@+' } }) + .pathname, + ).toBe('/items/@%2B/') + expect( + allowAt.buildLocation({ to: '/items/$id', params: { id: '@+' } }).pathname, + ).toBe('/items/@%2B') +}) + +test('does not reparse a legacy fallback already registered in the tree', () => { + const { routeTree, item } = createRoutes() + const parse = vi.spyOn(routeTreeUtils, 'parseSegments') + const router = createTestRouter({ + routeTree, + notFoundRoute: item, + history: history(), + }) + expect(router.routesById[item.id]).toBe(item) + expect(item._interpolation).toBeDefined() + expect(parse).not.toHaveBeenCalled() +}) + +test('formats masked destinations without registered templates', () => { + const { routeTree } = createRoutes() + const router = createTestRouter({ + routeTree, + history: history(), + pathParamsAllowedCharacters: ['@'], + }) + const build = () => + router.buildLocation({ + to: '/items/$id', + params: { id: '@one' }, + mask: { to: '/pretty/$id', params: { id: '@one' } }, + }) + + expect(build().maskedLocation?.pathname).toBe('/pretty/@one') + expect(build().maskedLocation?.pathname).toBe('/pretty/@one') +}) diff --git a/packages/router-core/tests/route-tree-construction.bench.ts b/packages/router-core/tests/route-tree-construction.bench.ts new file mode 100644 index 0000000000..e567f06d36 --- /dev/null +++ b/packages/router-core/tests/route-tree-construction.bench.ts @@ -0,0 +1,103 @@ +import { describe, expect, test } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { findRouteMatch, processRouteTree } from '../src/new-process-route-tree' +import type { AnyRoute } from '../src' + +type Shape = 'static' | 'dynamic' | 'nested' | 'mixed' + +function createTree(count: number, shape: Shape) { + const root = new BaseRootRoute({}) + const child = (parent: AnyRoute, path: string) => + new BaseRoute({ getParentRoute: () => parent, path }) + if (shape === 'nested') { + return root.addChildren( + Array.from({ length: count / 10 }, (_, group) => { + const parent = child(root, `/orgs/group-${group}/$org`) + return parent.addChildren( + Array.from({ length: 9 }, (_, index) => + child(parent, `/items/section-${index}/$id`), + ), + ) + }), + ) + } + return root.addChildren( + Array.from({ length: count }, (_, index) => { + const path = + shape === 'static' + ? `/static-${index}/about` + : shape === 'dynamic' + ? `/section-${index}/$id` + : [ + `/mixed-${index}/$org/items/$id`, + `/mixed-${index}/{-$lang}/$id`, + `/mixed-${index}/pre{$id}suffix/{-$lang}`, + `/mixed-${index}/files/prefix{$}.txt`, + ][index % 4]! + return child(root, path) + }), + ) +} + +// Keep first-use interpolation and object allocation out of the processing-only case. +for (const count of [100, 1000, 10000]) { + describe.each(['static', 'dynamic', 'nested', 'mixed'])( + `route-tree construction (${count} routes, %s)`, + (shape) => { + let tree = createTree(count, shape) + let result = processRouteTree(tree) + const expectedPath = + shape === 'static' + ? '/static-0/about' + : shape === 'dynamic' + ? '/section-0/one' + : shape === 'nested' + ? '/orgs/group-0/one/items/section-0/two' + : '/mixed-0/one/items/two' + const verify = () => { + expect(Object.keys(result.routesById)).toHaveLength(count + 1) + expect( + findRouteMatch(expectedPath, result.processedTree), + ).not.toBeNull() + } + verify() + + test('processRouteTree + route.init on fresh objects', async ({ + bench, + }) => { + await bench( + 'processRouteTree + route.init on fresh objects', + { + beforeEach: () => { + tree = createTree(count, shape) + }, + afterAll: verify, + }, + () => { + result = processRouteTree(tree) + }, + ).run({ + time: 1500, + warmupTime: 500, + throws: true, + }) + }) + + test('route objects + processRouteTree + route.init', async ({ + bench, + }) => { + await bench( + 'route objects + processRouteTree + route.init', + { afterAll: verify }, + () => { + result = processRouteTree(createTree(count, shape)) + }, + ).run({ + time: 1500, + warmupTime: 500, + throws: true, + }) + }) + }, + ) +} diff --git a/packages/router-core/tests/router-origin.test.ts b/packages/router-core/tests/router-origin.test.ts new file mode 100644 index 0000000000..901dedad08 --- /dev/null +++ b/packages/router-core/tests/router-origin.test.ts @@ -0,0 +1,61 @@ +// @vitest-environment jsdom + +import { createMemoryHistory } from '@tanstack/history' +import { expect, test, vi } from 'vitest' +import { BaseRootRoute, redirect } from '../src' +import { createTestRouter } from './routerTestUtils' + +test.each( + [false, true].flatMap((isServer) => + ['https://app.example', 'http://app.example:8080'].map((origin) => ({ + isServer, + origin, + })), + ), +)( + 'preserves configured $origin through option updates (server=$isServer)', + ({ isServer, origin }) => { + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history: createMemoryHistory(), + isServer, + }) + const defaultOrigin = isServer ? 'http://localhost' : window.origin + expect(router.origin).toBe(defaultOrigin) + + router.update({ origin }) + expect(router.origin).toBe(origin) + router.update({ context: { updated: true } }) + expect(router.origin).toBe(origin) + expect( + router.resolveRedirect(redirect({ href: `${origin}/target` })).options + .href, + ).toBe('/target') + + router.update({ origin: undefined }) + expect(router.origin).toBe(defaultOrigin) + expect( + router.resolveRedirect(redirect({ href: `${origin}/target` })).options + .href, + ).toBe(`${origin}/target`) + router.update({ context: { updated: false } }) + expect(router.origin).toBe(defaultOrigin) + }, +) + +test('opaque browser origins use the fallback after clearing an explicit origin', () => { + vi.stubGlobal('origin', 'null') + try { + const router = createTestRouter({ + routeTree: new BaseRootRoute(), + history: createMemoryHistory(), + isServer: false, + }) + expect(router.origin).toBe('http://localhost') + router.update({ origin: 'https://app.example' }) + router.update({ origin: undefined }) + expect(router.origin).toBe('http://localhost') + } finally { + vi.unstubAllGlobals() + } +}) diff --git a/packages/router-core/tests/routerTestUtils.ts b/packages/router-core/tests/routerTestUtils.ts new file mode 100644 index 0000000000..79a4122c74 --- /dev/null +++ b/packages/router-core/tests/routerTestUtils.ts @@ -0,0 +1,221 @@ +import { runInNewContext } from 'node:vm' +import { expect } from 'vitest' +import { batch, createAtom } from '@tanstack/store' +import { createMemoryHistory } from '@tanstack/history' +import { isServer } from '@tanstack/router-core/isServer' +import { + BaseRootRoute, + RouterCore, + createNonReactiveMutableStore, + createNonReactiveReadonlyStore, +} from '../src' +import { createRequestHandler } from '../src/ssr/createRequestHandler' +import { + SEGMENT_TYPE_PATHNAME, + SEGMENT_TYPE_WILDCARD, + parseSegment, + processRouteTree, +} from '../src/new-process-route-tree' +import { attachRouterServerSsrUtils } from '../src/ssr/ssr-server' +import type { interpolatePath } from '../src/path' +import type { SegmentKind } from '../src/new-process-route-tree' +import type { ServerManifest } from '../src/manifest' +import type { TsrSsrGlobal } from '../src/ssr/types' +import type { RouterHistory } from '@tanstack/history' +import type { + AnyRoute, + AnyRouter, + GetStoreConfig, + RouterConstructorOptions, + RouterOptions, + TrailingSlashOption, +} from '../src' + +const getStoreConfig: GetStoreConfig = (opts) => { + if (isServer ?? opts.isServer) { + return { + createMutableStore: createNonReactiveMutableStore, + createReadonlyStore: createNonReactiveReadonlyStore, + batch: (fn) => fn(), + } + } + + return { + createMutableStore: createAtom, + createReadonlyStore: createAtom, + batch, + } +} + +export function createTestRouter< + TRouteTree extends AnyRoute, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, + TRouterHistory extends RouterHistory = RouterHistory, + TDehydrated extends Record = Record, +>( + options: RouterConstructorOptions< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated + >, +) { + return new RouterCore(options, getStoreConfig) +} + +type RouteTreeInput = Parameters[0] +type FixtureNode = { + init?: RouteTreeInput['init'] + children?: ReadonlyArray +} + +const fixtureInit = () => {} + +function prepareFixture( + route: T, +): asserts route is T & Pick { + if (!route.init) { + // Raw matcher fixtures already specify their derived paths and IDs. + Object.defineProperty(route, 'init', { value: fixtureInit }) + } + for (const child of route.children ?? []) { + prepareFixture(child) + } +} + +export function processTestRouteTree< + TRoute extends Omit, +>(routeTree: TRoute, caseSensitive = false) { + prepareFixture(routeTree) + return processRouteTree(routeTree, caseSensitive) +} + +export type PathInterpolationTestOptions = { + path: string + params: Record + decoder?: Parameters[3] + server?: boolean +} + +export function createTestPathInterpolator( + options: Pick< + RouterOptions, + 'isServer' | 'pathParamsAllowedCharacters' + > = {}, +) { + const router = createTestRouter({ + routeTree: new BaseRootRoute({}), + history: createMemoryHistory({ initialEntries: ['/'] }), + scrollRestoration: false, + trailingSlash: 'preserve', + ...options, + }) + router.history.destroy() + return ( + options: Pick, + ): string => { + return router.buildLocation({ to: options.path, params: options.params }) + .pathname + } +} + +export function parseTestPathname(to: string | undefined) { + const path = to ?? '' + const segments: Array<{ + type: SegmentKind + value: string + prefixSegment?: string + suffixSegment?: string + }> = [] + let cursor = 0 + while (cursor < path.length) { + const start = cursor + const next = path.indexOf('/', start) + const end = next === -1 ? path.length : next + const data = parseSegment(path, start, end) + cursor = end + 1 + if (typeof data === 'string') { + segments.push({ type: SEGMENT_TYPE_PATHNAME, value: data }) + } else { + const [type, key, prefix, suffix] = data + const splat = type === SEGMENT_TYPE_WILDCARD + if (splat) { + cursor = path.length + 1 + } + const segment: (typeof segments)[number] = { + type, + value: splat + ? suffix === undefined + ? path.substring(start) + : '$' + : key, + } + if (prefix) { + segment.prefixSegment = prefix + } + if (suffix) { + segment.suffixSegment = suffix + } + segments.push(segment) + } + } + return segments +} + +/** Materialize the request-local server result as the HTTP response users see. */ +export function loadServerResponse( + router: AnyRouter, + path: string, + signal?: AbortSignal, +) { + return createRequestHandler({ + createRouter: () => router, + request: new Request(`http://localhost${path}`, { signal }), + })(({ router: loadedRouter, responseHeaders }) => { + const result = loadedRouter._serverResult + return new Response(null, { + status: + result?.type === 'redirect' + ? result.redirect.status + : (result?.status ?? 500), + headers: responseHeaders, + }) + }) +} + +export async function dehydrateToBootstrap( + router: AnyRouter, + manifest: ServerManifest, +): Promise { + attachRouterServerSsrUtils({ router, manifest }) + try { + await router.load() + await router.serverSsr!.dehydrate() + + const scripts = router.serverSsr!.takeInitialHydrationScriptTags() + expect(scripts?.before.length).toBeGreaterThan(0) + expect(scripts?.boundary.children).toContain('$tsr-stream-boundary') + expect(scripts?.boundary.attrs).not.toHaveProperty('id') + + const context: Record = { + document: { + currentScript: { + remove() {}, + }, + }, + } + context.self = context + for (const script of scripts!.before) { + expect(script.attrs?.['data-tsr-stream-part']).toBe('') + expect(script.children).toBeTruthy() + runInNewContext(script.children!, context) + } + + expect(context.$_TSR).toBeDefined() + return context.$_TSR + } finally { + router.serverSsr?.cleanup() + } +} diff --git a/packages/router-core/tests/same-destination-navigation-join.test.ts b/packages/router-core/tests/same-destination-navigation-join.test.ts new file mode 100644 index 0000000000..c6d65fe525 --- /dev/null +++ b/packages/router-core/tests/same-destination-navigation-join.test.ts @@ -0,0 +1,331 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('same-destination navigation while one is in flight', () => { + function setup() { + const gate = createControlledPromise() + const beforeLoad = vi.fn() + const loader = vi.fn(() => gate) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + return { router, beforeLoad, loader, gate, targetRoute } + } + + test('a second navigation to the same destination joins the in-flight load', async () => { + const { router, beforeLoad, loader, gate, targetRoute } = setup() + await router.load() + + const first = router.navigate({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + const second = router.navigate({ to: '/target' }) + + gate.resolve('once') + await Promise.all([first, second]) + + expect(beforeLoad).toHaveBeenCalledTimes(2) + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + loaderData: 'once', + }) + }) + + test('a double navigation in the same tick joins the in-flight load', async () => { + const { router, loader, gate, targetRoute } = setup() + await router.load() + + const first = router.navigate({ to: '/target' }) + const second = router.navigate({ to: '/target' }) + + gate.resolve('once') + await Promise.all([first, second]) + + expect(loader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + loaderData: 'once', + }) + }) + + test('a successor joining a loader error normalizes the shared generation once', async () => { + const gate = createControlledPromise() + const failure = new Error('shared failure') + const loader = vi.fn(async () => { + await gate + throw failure + }) + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader, + onError, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + + const first = router.navigate({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) + const second = router.navigate({ to: '/target' }) + await Promise.resolve() + expect(loader).toHaveBeenCalledOnce() + + gate.resolve() + await Promise.all([first, second]) + + expect(loader).toHaveBeenCalledOnce() + expect(onError).toHaveBeenCalledOnce() + expect(onError).toHaveBeenCalledWith(failure) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'error', + error: failure, + }) + }) + + test('a navigation started by onError runs a fresh loader generation', async () => { + const gate = createControlledPromise() + const failure = new Error('first generation failed') + let successor: Promise | undefined + let router: ReturnType + const loader = vi.fn(async () => { + if (loader.mock.calls.length === 1) { + await gate + throw failure + } + return 'recovered' + }) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + loader, + onError: () => { + successor ??= router.navigate({ to: '/target' }) + }, + }) + router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + + const first = router.navigate({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) + gate.resolve() + await first + await successor + + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + loaderData: 'recovered', + }) + }) + + test('a superseded loader failure cannot poison a successor delayed in beforeLoad', async () => { + const firstResult = createControlledPromise() + const successorBeforeLoadStarted = createControlledPromise() + const successorBeforeLoadGate = createControlledPromise() + const failure = new Error('reserved generation failed') + const signals: Array = [] + const onError = vi.fn() + const loader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + signals.push(abortController.signal) + return loader.mock.calls.length === 1 ? firstResult : 'fresh' + }, + ) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + validateSearch: (search: Record) => ({ + phase: String(search.phase ?? ''), + }), + beforeLoad: async ({ search }) => { + if (search.phase === 'successor') { + successorBeforeLoadStarted.resolve() + await successorBeforeLoadGate + } + }, + loader, + onError, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + + const first = router.navigate({ + to: '/target', + search: { phase: 'predecessor' }, + }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledOnce()) + + const second = router.navigate({ + to: '/target', + search: { phase: 'successor' }, + }) + await successorBeforeLoadStarted + + expect(loader).toHaveBeenCalledOnce() + expect(signals[0]?.aborted).toBe(false) + + firstResult.reject(failure) + await vi.waitFor(() => expect(signals[0]?.aborted).toBe(true)) + + expect(onError).not.toHaveBeenCalled() + expect(loader).toHaveBeenCalledOnce() + + successorBeforeLoadGate.resolve() + await Promise.all([first, second]) + + expect(loader).toHaveBeenCalledTimes(2) + expect(onError).not.toHaveBeenCalled() + expect(signals[1]?.aborted).toBe(false) + expect(router.state.location).toMatchObject({ + pathname: '/target', + search: { phase: 'successor' }, + }) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + loaderData: 'fresh', + }) + }) + + test('invalidate reruns the loader after the navigation settles', async () => { + const { router, loader, gate } = setup() + gate.resolve('data') + await router.load() + await router.navigate({ to: '/target' }) + expect(loader).toHaveBeenCalledTimes(1) + + await router.invalidate() + + expect(loader).toHaveBeenCalledTimes(2) + }) + + test('invalidate during an in-flight navigation still reruns the loader', async () => { + const { router, loader, gate } = setup() + await router.load() + + const first = router.navigate({ to: '/target' }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1)) + const second = router.invalidate() + + gate.resolve('data') + await Promise.all([first, second]) + + expect(loader).toHaveBeenCalledTimes(2) + }) + + test('filtered invalidate does not adopt same-id work from an active preload', async () => { + const secondGate = createControlledPromise() + const loader = vi.fn( + ({ abortController }: { abortController: AbortController }) => { + const generation = loader.mock.calls.length + return generation === 2 + ? secondGate + : `generation ${generation}:${abortController.signal.aborted}` + }, + ) + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + validateSearch: (search: Record) => ({ + revision: Number(search.revision ?? 1), + }), + shouldReload: ({ preload }) => (preload ? true : undefined), + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ + initialEntries: ['/target?revision=1'], + }), + }) + + await router.load() + const preload = router.preloadRoute({ + to: '/target', + search: { revision: 2 }, + }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(2)) + + const invalidation = router.invalidate({ + filter: (match) => + match.routeId === targetRoute.id && + (match.search as { revision: number }).revision === 1, + }) + await vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(3)) + await invalidation + + expect(router.state.location.search).toEqual({ revision: 1 }) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + loaderData: 'generation 3:false', + }) + + secondGate.resolve('preload data') + await preload + }) + + test('a repeat navigation after settle reloads instead of joining', async () => { + const { router, loader, gate, targetRoute } = setup() + gate.resolve('data') + await router.load() + await router.navigate({ to: '/target' }) + + // Once the first navigation settles there is nothing to join: a repeat + // same-destination navigation keeps its refresh semantics. + await router.navigate({ to: '/target' }) + + expect(loader).toHaveBeenCalledTimes(2) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + }) +}) diff --git a/packages/router-core/tests/scroll-restoration-lifecycle.test.ts b/packages/router-core/tests/scroll-restoration-lifecycle.test.ts new file mode 100644 index 0000000000..e410d9aa55 --- /dev/null +++ b/packages/router-core/tests/scroll-restoration-lifecycle.test.ts @@ -0,0 +1,187 @@ +import { createMemoryHistory } from '@tanstack/history' +import { afterEach, beforeEach, expect, test, vi } from 'vitest' +import { + BaseRootRoute, + getElementScrollRestorationEntry, + setupScrollRestoration, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +let listeners: Array< + [ + Window | Document, + string, + EventListenerOrEventListenerObject, + boolean | AddEventListenerOptions | undefined, + ] +> + +beforeEach(() => { + listeners = [] + for (const target of [window, document]) { + const add = target.addEventListener.bind(target) + vi.spyOn(target, 'addEventListener').mockImplementation( + (type, listener, options) => { + listeners.push([target, type, listener, options]) + add(type, listener, options) + }, + ) + } +}) + +afterEach(() => { + for (const [target, type, listener, options] of listeners) { + target.removeEventListener(type, listener, options) + } + document.body.replaceChildren() + history.scrollRestoration = 'auto' + vi.restoreAllMocks() +}) + +function createRouter( + options: Parameters[0] = { + routeTree: new BaseRootRoute({}), + }, +) { + return createTestRouter({ + history: createMemoryHistory(), + scrollRestoration: true, + ...options, + }) +} + +test.each([false, true])( + 'hands off native restoration before taking a pagehide snapshot (persisted=%s)', + (persisted) => { + const modes: Array = [] + createRouter({ + routeTree: new BaseRootRoute({}), + getScrollRestorationKey: () => { + modes.push(history.scrollRestoration) + return `lifecycle-${persisted}` + }, + }) + dispatchEvent(new PageTransitionEvent('pagehide', { persisted })) + expect(modes).toEqual(['auto']) + expect(history.scrollRestoration).toBe('auto') + }, +) + +test.each([false, true])( + 'reclaims native restoration only for a persisted pageshow (persisted=%s)', + (persisted) => { + createRouter() + history.scrollRestoration = 'auto' + dispatchEvent(new PageTransitionEvent('pageshow', { persisted })) + expect(history.scrollRestoration).toBe(persisted ? 'manual' : 'auto') + }, +) + +test('still hands off native restoration when a custom key throws', () => { + const failure = new Error('custom scroll key failed') + const errors: Array = [] + addEventListener('error', (event) => { + errors.push(event.error) + event.preventDefault() + }) + createRouter({ + routeTree: new BaseRootRoute({}), + getScrollRestorationKey: () => { + throw failure + }, + }) + dispatchEvent(new PageTransitionEvent('pagehide')) + expect(errors).toEqual([failure]) + expect(history.scrollRestoration).toBe('auto') +}) + +test('hands off native restoration when storage persistence throws', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('storage unavailable') + }) + createRouter() + dispatchEvent(new PageTransitionEvent('pagehide')) + expect(history.scrollRestoration).toBe('auto') + expect(warn).toHaveBeenCalledOnce() +}) + +test('preserves live nested scroll snapshots across repeated hide/show cycles without repeated setup', () => { + const element = document.createElement('div') + element.dataset.scrollRestorationId = 'lifecycle-nested' + document.body.append(element) + const router = createRouter({ + routeTree: new BaseRootRoute({}), + getScrollRestorationKey: () => 'lifecycle-nested', + }) + setupScrollRestoration(router) + expect(listeners.filter(([, type]) => type === 'pageshow')).toHaveLength(1) + for (const scrollTop of [80, 120]) { + element.scrollTop = scrollTop + element.dispatchEvent(new Event('scroll', { bubbles: true })) + dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true })) + expect(history.scrollRestoration).toBe('auto') + expect( + getElementScrollRestorationEntry(router, { + id: 'lifecycle-nested', + getKey: router.options.getScrollRestorationKey, + }), + ).toEqual({ scrollX: 0, scrollY: scrollTop }) + dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true })) + expect(history.scrollRestoration).toBe('manual') + } +}) + +test('leaves native restoration alone when router restoration is disabled', () => { + history.scrollRestoration = 'auto' + createRouter({ routeTree: new BaseRootRoute({}), scrollRestoration: false }) + dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true })) + dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true })) + expect(history.scrollRestoration).toBe('auto') +}) + +test('can enable restoration after disabled setup without duplicate lifecycle listeners', () => { + history.scrollRestoration = 'auto' + const router = createRouter({ + routeTree: new BaseRootRoute({}), + scrollRestoration: false, + getScrollRestorationKey: () => 'lifecycle-forced', + }) + expect(history.scrollRestoration).toBe('auto') + setupScrollRestoration(router, true) + setupScrollRestoration(router, true) + expect(history.scrollRestoration).toBe('manual') + for (const event of ['pagehide', 'pageshow']) { + expect(listeners.filter(([, type]) => type === event)).toHaveLength(1) + } + const element = document.createElement('div') + element.dataset.scrollRestorationId = 'lifecycle-forced' + document.body.append(element) + element.scrollTop = 40 + element.dispatchEvent(new Event('scroll', { bubbles: true })) + dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true })) + expect(history.scrollRestoration).toBe('auto') + expect( + getElementScrollRestorationEntry(router, { + id: 'lifecycle-forced', + getKey: router.options.getScrollRestorationKey, + }), + ).toEqual({ scrollX: 0, scrollY: 40 }) + dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true })) + expect(history.scrollRestoration).toBe('manual') +}) + +test('does not take over browser restoration or register listeners on the server', () => { + history.scrollRestoration = 'auto' + const router = createRouter({ + routeTree: new BaseRootRoute({}), + isServer: true, + }) + setupScrollRestoration(router, true) + expect(history.scrollRestoration).toBe('auto') + expect( + listeners.filter(([, type]) => + ['pagehide', 'pageshow', 'scroll'].includes(type), + ), + ).toEqual([]) +}) diff --git a/packages/router-core/tests/scroll-restoration-script.test.ts b/packages/router-core/tests/scroll-restoration-script.test.ts new file mode 100644 index 0000000000..ed1f151562 --- /dev/null +++ b/packages/router-core/tests/scroll-restoration-script.test.ts @@ -0,0 +1,155 @@ +import { createMemoryHistory } from '@tanstack/history' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { getScrollRestorationScriptForRouter } from '../src/scroll-restoration-script/server' +import { BaseRootRoute, BaseRoute, storageKey } from '../src' +import { createTestRouter } from './routerTestUtils' + +function createScrollRestorationRouter(getScrollRestorationKey?: () => string) { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + + return createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + scrollRestoration: true, + getScrollRestorationKey, + }) +} + +function runScrollRestorationScript(script: string | null) { + expect(script).toBeTruthy() + new Function(script!)() +} + +afterEach(() => { + window.sessionStorage.clear() + window.history.replaceState({}, '', '/') + vi.unstubAllGlobals() +}) + +describe('getScrollRestorationScriptForRouter', () => { + test('restores SSR scroll entries for a user supplied key', () => { + const router = createScrollRestorationRouter(() => 'custom-key') + const script = getScrollRestorationScriptForRouter(router) + const scrollTo = vi.fn() + + window.history.replaceState({ __TSR_key: 'history-key' }, '', '/') + window.sessionStorage.setItem( + storageKey, + JSON.stringify({ + 'custom-key': { + window: { scrollX: 11, scrollY: 22 }, + }, + 'history-key': { + window: { scrollX: 33, scrollY: 44 }, + }, + }), + ) + + vi.stubGlobal('scrollTo', scrollTo) + + runScrollRestorationScript(script) + + expect(scrollTo).toHaveBeenCalledWith(11, 22) + }) + + test('restores SSR scroll entries for the default history key', () => { + const router = createScrollRestorationRouter() + const script = getScrollRestorationScriptForRouter(router) + const scrollTo = vi.fn() + + window.history.replaceState({ __TSR_key: 'history-key' }, '', '/') + window.sessionStorage.setItem( + storageKey, + JSON.stringify({ + 'history-key': { + window: { scrollX: 33, scrollY: 44 }, + }, + '/': { + window: { scrollX: 11, scrollY: 22 }, + }, + }), + ) + + vi.stubGlobal('scrollTo', scrollTo) + + runScrollRestorationScript(script) + + expect(scrollTo).toHaveBeenCalledWith(33, 44) + }) + + test('ignores invalid serialized scroll storage', () => { + const router = createScrollRestorationRouter() + const script = getScrollRestorationScriptForRouter(router) + const scrollTo = vi.fn() + + window.history.replaceState({ __TSR_key: 'history-key' }, '', '/') + window.sessionStorage.setItem(storageKey, '{') + vi.stubGlobal('scrollTo', scrollTo) + + expect(() => runScrollRestorationScript(script)).not.toThrow() + expect(scrollTo).not.toHaveBeenCalled() + }) + + test('ignores malformed scroll entries and falls back to top', () => { + const router = createScrollRestorationRouter() + const script = getScrollRestorationScriptForRouter(router) + const scrollTo = vi.fn() + + window.history.replaceState({ __TSR_key: 'history-key' }, '', '/') + window.sessionStorage.setItem( + storageKey, + JSON.stringify({ + 'history-key': { + window: { scrollX: 'bad', scrollY: 44 }, + '[': { scrollX: 11, scrollY: 22 }, + empty: null, + }, + }), + ) + vi.stubGlobal('scrollTo', scrollTo) + + expect(() => runScrollRestorationScript(script)).not.toThrow() + expect(scrollTo).toHaveBeenCalledWith(0, 0) + }) + + test('ignores a malformed restoration key payload and falls back to top', () => { + const router = createScrollRestorationRouter() + const script = getScrollRestorationScriptForRouter(router) + const scrollTo = vi.fn() + + window.history.replaceState({ __TSR_key: 'history-key' }, '', '/') + window.sessionStorage.setItem( + storageKey, + JSON.stringify({ + 'history-key': 'not an entry object', + }), + ) + vi.stubGlobal('scrollTo', scrollTo) + + expect(() => runScrollRestorationScript(script)).not.toThrow() + expect(scrollTo).toHaveBeenCalledWith(0, 0) + }) + + test('falls back safely when restoration key is missing from storage', () => { + const router = createScrollRestorationRouter() + const script = getScrollRestorationScriptForRouter(router) + const scrollTo = vi.fn() + + window.history.replaceState({ __TSR_key: 'history-key' }, '', '/') + window.sessionStorage.setItem( + storageKey, + JSON.stringify({ + 'other-key': { window: { scrollX: 1, scrollY: 2 } }, + }), + ) + vi.stubGlobal('scrollTo', scrollTo) + + expect(() => runScrollRestorationScript(script)).not.toThrow() + expect(scrollTo).toHaveBeenCalledWith(0, 0) + }) +}) diff --git a/packages/router-core/tests/scroll-restoration.test.ts b/packages/router-core/tests/scroll-restoration.test.ts new file mode 100644 index 0000000000..03e957e3da --- /dev/null +++ b/packages/router-core/tests/scroll-restoration.test.ts @@ -0,0 +1,322 @@ +import { createMemoryHistory } from '@tanstack/history' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' +import type { ParsedLocation } from '../src' + +function createRouter( + options: { + scrollRestoration?: boolean + scrollToTopSelectors?: Array Element | null | undefined)> + getScrollRestorationKey?: (location: ParsedLocation) => string + } = {}, +) { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + + return createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + ...options, + }) +} + +afterEach(() => { + document.body.replaceChildren() + window.sessionStorage.clear() + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +function getLocation( + router: ReturnType, + pathname: string, +) { + return { + ...router.latestLocation, + href: pathname, + pathname, + } +} + +function emitNavigation( + router: ReturnType, + type: 'onBeforeLoad' | 'onRendered', + fromLocation: ParsedLocation, + toLocation: ParsedLocation, +) { + router.emit({ + type, + fromLocation, + toLocation, + pathChanged: true, + hrefChanged: true, + hashChanged: false, + }) +} + +describe('setupScrollRestoration', () => { + test('sets up scroll restoration when scrollRestoration is true', () => { + const windowAddEventListener = vi.spyOn(window, 'addEventListener') + const documentAddEventListener = vi.spyOn(document, 'addEventListener') + const previousScrollRestoration = window.history.scrollRestoration + + window.history.scrollRestoration = 'auto' + + createRouter({ scrollRestoration: true }) + expect(window.history.scrollRestoration).toBe('manual') + expect( + windowAddEventListener.mock.calls.some(([event]) => event === 'pagehide'), + ).toBe(true) + expect( + documentAddEventListener.mock.calls.some( + ([event, _listener, options]) => event === 'scroll' && options === true, + ), + ).toBe(true) + + window.history.scrollRestoration = previousScrollRestoration + }) + + test('snapshots the live position when it changed after the latest scroll event', () => { + const element = document.createElement('div') + element.id = 'unit-live-snapshot-element' + document.body.append(element) + vi.stubGlobal('scrollTo', vi.fn()) + + const router = createRouter({ + scrollRestoration: true, + getScrollRestorationKey: (location) => location.pathname, + }) + const source = getLocation(router, '/unit-live-snapshot-source') + const destination = getLocation(router, '/unit-live-snapshot-destination') + + element.scrollTop = 80 + element.dispatchEvent(new Event('scroll', { bubbles: true })) + element.scrollTop = 120 + + emitNavigation(router, 'onBeforeLoad', source, destination) + element.scrollTop = 0 + emitNavigation(router, 'onRendered', source, destination) + + expect(element.scrollTop).toBe(120) + }) + + test('snapshots the live window position when it changed after the latest scroll event', () => { + const windowScrollTo = vi.fn() + vi.stubGlobal('scrollTo', windowScrollTo) + vi.stubGlobal('scrollX', 0) + vi.stubGlobal('scrollY', 80) + + const router = createRouter({ + scrollRestoration: true, + getScrollRestorationKey: (location) => location.pathname, + }) + const source = getLocation(router, '/unit-live-window-snapshot-source') + const destination = getLocation( + router, + '/unit-live-window-snapshot-destination', + ) + + document.dispatchEvent(new Event('scroll')) + vi.stubGlobal('scrollY', 120) + + emitNavigation(router, 'onBeforeLoad', source, destination) + emitNavigation(router, 'onRendered', source, destination) + windowScrollTo.mockClear() + + emitNavigation(router, 'onBeforeLoad', destination, source) + emitNavigation(router, 'onRendered', destination, source) + + expect(windowScrollTo).toHaveBeenCalledWith({ + top: 120, + left: 0, + behavior: undefined, + }) + }) + + test.each([ + ['omitted', undefined], + ['false', false], + ] as const)( + 'does not setup scroll restoration when scrollRestoration is %s', + (_name, scrollRestoration) => { + const windowAddEventListener = vi.spyOn(window, 'addEventListener') + const documentAddEventListener = vi.spyOn(document, 'addEventListener') + const previousScrollRestoration = window.history.scrollRestoration + + window.history.scrollRestoration = 'auto' + + createRouter(scrollRestoration === undefined ? {} : { scrollRestoration }) + expect(window.history.scrollRestoration).toBe('auto') + expect( + windowAddEventListener.mock.calls.some( + ([event]) => event === 'pagehide', + ), + ).toBe(false) + expect( + documentAddEventListener.mock.calls.some( + ([event, _listener, options]) => + event === 'scroll' && options === true, + ), + ).toBe(false) + + window.history.scrollRestoration = previousScrollRestoration + }, + ) + + test('restores a configured element independently from the window', () => { + const element = document.createElement('div') + element.id = 'unit-restored-element' + element.dataset.scrollRestorationId = 'unit-restored-element' + document.body.append(element) + + const elementScrollTo = vi.fn((options: ScrollToOptions) => { + element.scrollTop = options.top ?? element.scrollTop + }) + element.scrollTo = elementScrollTo as typeof element.scrollTo + const windowScrollTo = vi.fn() + vi.stubGlobal('scrollTo', windowScrollTo) + + const router = createRouter({ + scrollRestoration: true, + scrollToTopSelectors: ['#unit-restored-element'], + getScrollRestorationKey: (location) => location.pathname, + }) + const source = getLocation(router, '/unit-element-source') + const destination = getLocation(router, '/unit-element-destination') + + element.scrollTop = 80 + element.dispatchEvent(new Event('scroll', { bubbles: true })) + + emitNavigation(router, 'onBeforeLoad', source, destination) + emitNavigation(router, 'onRendered', source, destination) + expect(element.scrollTop).toBe(0) + + elementScrollTo.mockClear() + windowScrollTo.mockClear() + vi.stubGlobal('scrollX', 0) + vi.stubGlobal('scrollY', 120) + document.dispatchEvent(new Event('scroll')) + emitNavigation(router, 'onBeforeLoad', destination, source) + emitNavigation(router, 'onRendered', destination, source) + + expect(element.scrollTop).toBe(80) + expect(elementScrollTo).not.toHaveBeenCalled() + expect(windowScrollTo).toHaveBeenCalledWith({ + top: 0, + left: 0, + behavior: undefined, + }) + }) + + test('resets an uncached configured element when the window restores', () => { + const element = document.createElement('div') + element.id = 'unit-reset-element' + document.body.append(element) + + const elementScrollTo = vi.fn((options: ScrollToOptions) => { + element.scrollTop = options.top ?? element.scrollTop + }) + element.scrollTo = elementScrollTo as typeof element.scrollTo + + const windowScrollTo = vi.fn() + vi.stubGlobal('scrollX', 0) + vi.stubGlobal('scrollY', 120) + vi.stubGlobal('scrollTo', windowScrollTo) + + const router = createRouter({ + scrollRestoration: true, + scrollToTopSelectors: ['#unit-reset-element'], + getScrollRestorationKey: (location) => location.pathname, + }) + const source = getLocation(router, '/unit-window-source') + const destination = getLocation(router, '/unit-window-destination') + + document.dispatchEvent(new Event('scroll')) + emitNavigation(router, 'onBeforeLoad', source, destination) + emitNavigation(router, 'onRendered', source, destination) + + elementScrollTo.mockClear() + windowScrollTo.mockClear() + element.scrollTop = 80 + + emitNavigation(router, 'onBeforeLoad', destination, source) + emitNavigation(router, 'onRendered', destination, source) + + expect(windowScrollTo).toHaveBeenCalledWith({ + top: 120, + left: 0, + behavior: undefined, + }) + expect(element.scrollTop).toBe(0) + expect(elementScrollTo).toHaveBeenCalledWith({ + top: 0, + left: 0, + behavior: undefined, + }) + }) + + test('resets a configured element when its cached selector becomes stale', () => { + const element = document.createElement('div') + element.id = 'unit-stale-selector-element' + element.dataset.scrollRestorationId = 'unit-stale-selector-source' + document.body.append(element) + + const elementScrollTo = vi.fn((options: ScrollToOptions) => { + element.scrollTop = options.top ?? element.scrollTop + }) + element.scrollTo = elementScrollTo as typeof element.scrollTo + vi.stubGlobal('scrollTo', vi.fn()) + + const router = createRouter({ + scrollRestoration: true, + scrollToTopSelectors: [() => element], + getScrollRestorationKey: (location) => location.pathname, + }) + const source = getLocation(router, '/unit-stale-selector-source') + const destination = getLocation(router, '/unit-stale-selector-destination') + + element.scrollTop = 80 + element.dispatchEvent(new Event('scroll', { bubbles: true })) + emitNavigation(router, 'onBeforeLoad', source, destination) + emitNavigation(router, 'onRendered', source, destination) + expect(element.scrollTop).toBe(0) + + element.dataset.scrollRestorationId = 'unit-stale-selector-current' + element.scrollTop = 40 + elementScrollTo.mockClear() + emitNavigation(router, 'onBeforeLoad', destination, source) + emitNavigation(router, 'onRendered', destination, source) + + expect(element.scrollTop).toBe(0) + expect(elementScrollTo).toHaveBeenCalledWith({ + top: 0, + left: 0, + behavior: undefined, + }) + }) + + test('does not resolve configured selectors for hash navigation without source entries', () => { + const element = document.createElement('div') + document.body.append(element) + const getElement = vi.fn(() => element) + + const router = createRouter({ + scrollRestoration: true, + scrollToTopSelectors: [getElement], + getScrollRestorationKey: (location) => location.pathname, + }) + const source = getLocation(router, '/unit-hash-source') + const destination = { + ...getLocation(router, '/unit-hash-destination'), + hash: 'section', + } + + emitNavigation(router, 'onRendered', source, destination) + + expect(getElement).not.toHaveBeenCalled() + }) +}) diff --git a/packages/router-core/tests/search-context-boundaries.test.ts b/packages/router-core/tests/search-context-boundaries.test.ts new file mode 100644 index 0000000000..5daec53aaa --- /dev/null +++ b/packages/router-core/tests/search-context-boundaries.test.ts @@ -0,0 +1,57 @@ +import { expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +const path = '/parent/child?name=Alice&__proto__=%7B%22isAdmin%22%3Atrue%7D' + +function createRouteTree() { + const rootRoute = new BaseRootRoute() + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: ({ search }): Record => search, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: ({ context }) => ({ + name: context.name, + access: context.isAdmin ? 'admin' : 'visitor', + }), + }) + + return { + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + childRoute, + } +} + +test('search-derived ancestor context does not grant inherited properties to a client loader', async () => { + const { routeTree, childRoute } = createRouteTree() + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: [path] }), + isServer: false, + }) + + await router.load() + + expect( + router.state.matches.find((match) => match.routeId === childRoute.id) + ?.loaderData, + ).toEqual({ name: 'Alice', access: 'visitor' }) +}) + +test('search-derived ancestor context does not grant inherited properties to an SSR loader', async () => { + const { routeTree, childRoute } = createRouteTree() + const router = createTestRouter({ routeTree, isServer: true }) + + const response = await loadServerResponse(router, path) + + expect(response.status).toBe(200) + expect( + router.state.matches.find((match) => match.routeId === childRoute.id) + ?.loaderData, + ).toEqual({ name: 'Alice', access: 'visitor' }) +}) diff --git a/packages/router-core/tests/searchMiddleware.test-d.ts b/packages/router-core/tests/searchMiddleware.test-d.ts new file mode 100644 index 0000000000..8f68d91b21 --- /dev/null +++ b/packages/router-core/tests/searchMiddleware.test-d.ts @@ -0,0 +1,76 @@ +import { describe, expectTypeOf, test } from 'vitest' +import { + BaseRootRoute, + BaseRoute, + stripSearchParams, + type ValidatorAdapter, +} from '../src' + +describe('search middlewares', () => { + test('should use search validator output for middleware context', () => { + type SearchInput = { + page?: string + } + + type SearchOutput = { + page: number + } + + const searchValidator: ValidatorAdapter = { + types: undefined as never, + parse: () => ({ page: 1 }), + } + + const rootRoute = new BaseRootRoute({}) + + new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + validateSearch: searchValidator, + search: { + middlewares: [ + ({ search, next }) => { + expectTypeOf(search).toEqualTypeOf() + expectTypeOf(next).toBeCallableWith({ page: 2 }) + expectTypeOf(next).parameter(0).toEqualTypeOf() + expectTypeOf(next({ page: 2 })).toEqualTypeOf() + + return search + }, + ], + }, + }) + }) + + test('should allow stripping default-valued validator output keys', () => { + type RootSearch = { + root?: string + } + + type SearchInput = { + foo?: string + } + + type SearchOutput = { + foo: string + } + + const searchValidator: ValidatorAdapter = { + types: undefined as never, + parse: () => ({ foo: 'default' }), + } + + const rootRoute = new BaseRootRoute({ + validateSearch: (search: RootSearch): RootSearch => search, + }) + + new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + validateSearch: searchValidator, + search: { + middlewares: [stripSearchParams({ foo: 'default' })], + }, + }) + }) +}) diff --git a/packages/router-core/tests/searchMiddleware.test.ts b/packages/router-core/tests/searchMiddleware.test.ts new file mode 100644 index 0000000000..ee05ef8abc --- /dev/null +++ b/packages/router-core/tests/searchMiddleware.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, test } from 'vitest' +import { retainSearchParams, stripSearchParams } from '../src/searchMiddleware' + +describe('searchMiddleware - mutation prevention', () => { + describe('retainSearchParams', () => { + test('should not mutate original search object', () => { + const originalSearch = { id: '1', filter: 'active', page: '2' } + const originalCopy = { ...originalSearch } + + const middleware = retainSearchParams(['id', 'filter']) + + // next() returns object without 'id' and 'filter' keys + // so retainSearchParams should add them from search + const result = middleware({ + search: originalSearch, + next: () => + ({ + search: { page: 'new' }, + meta: {}, + }) as any, + }) + + expect(originalSearch).toEqual(originalCopy) + expect(originalSearch).toEqual({ id: '1', filter: 'active', page: '2' }) + expect(result).toEqual({ id: '1', filter: 'active', page: 'new' }) + expect(result).not.toBe(originalSearch) + }) + + test('should work correctly when same reference is reused', () => { + const sharedSearch = { id: '1', filter: 'active', page: '1' } + const middleware = retainSearchParams(['id', 'filter']) + + // next() returns object without 'id' and 'filter' keys + const result1 = middleware({ + search: sharedSearch, + next: () => + ({ + search: { page: '2' }, + meta: {}, + }) as any, + }) + + expect(sharedSearch).toEqual({ id: '1', filter: 'active', page: '1' }) + expect(result1).toEqual({ id: '1', filter: 'active', page: '2' }) + + const result2 = middleware({ + search: sharedSearch, + next: () => + ({ + search: { page: '3' }, + meta: {}, + }) as any, + }) + + expect(sharedSearch).toEqual({ id: '1', filter: 'active', page: '1' }) + expect(result2).toEqual({ id: '1', filter: 'active', page: '3' }) + }) + + test('should handle retainSearchParams(true) correctly', () => { + const originalSearch = { id: '1', filter: 'active' } + const originalCopy = { ...originalSearch } + + const middleware = retainSearchParams(true) + + const result = middleware({ + search: originalSearch, + next: () => + ({ + search: { id: '2' }, + meta: {}, + }) as any, + }) + + expect(originalSearch).toEqual(originalCopy) + expect(result).toEqual({ id: '2', filter: 'active' }) + }) + }) + + describe('stripSearchParams', () => { + test('should not mutate original search object (array input)', () => { + const originalSearch = { id: '1', filter: 'active', page: '1' } + const originalCopy = { ...originalSearch } + + const middleware = stripSearchParams(['filter', 'page']) + + const result = middleware({ + search: originalSearch, + next: (search) => search, + }) + + expect(originalSearch).toEqual(originalCopy) + expect(originalSearch).toEqual({ id: '1', filter: 'active', page: '1' }) + expect(result).toEqual({ id: '1' }) + expect(result).not.toBe(originalSearch) + }) + + test('should not mutate original search object (object input)', () => { + const originalSearch = { id: '1', filter: 'active', status: 'done' } + const originalCopy = { ...originalSearch } + + const middleware = stripSearchParams({ filter: 'active', status: 'done' }) + + const result = middleware({ + search: originalSearch, + next: (search) => search, + }) + + expect(originalSearch).toEqual(originalCopy) + expect(originalSearch).toEqual({ + id: '1', + filter: 'active', + status: 'done', + }) + expect(result).toEqual({ id: '1' }) + expect(result).not.toBe(originalSearch) + }) + + test('should work correctly when same reference is reused', () => { + const sharedSearch = { id: '1', filter: 'active', page: '1' } + const middleware = stripSearchParams(['filter', 'page']) + + const result1 = middleware({ + search: sharedSearch, + next: (search) => search, + }) + + expect(sharedSearch).toEqual({ id: '1', filter: 'active', page: '1' }) + expect(result1).toEqual({ id: '1' }) + + const result2 = middleware({ + search: sharedSearch, + next: (search) => search, + }) + + expect(sharedSearch).toEqual({ id: '1', filter: 'active', page: '1' }) + expect(result2).toEqual({ id: '1' }) + }) + + test('should handle stripSearchParams(true) correctly', () => { + const originalSearch = { id: '1', filter: 'active' } + const originalCopy = { ...originalSearch } + + const middleware = stripSearchParams(true) + + const result = middleware({ + search: originalSearch, + next: (search) => search, + }) + + expect(originalSearch).toEqual(originalCopy) + expect(result).toEqual({}) + }) + }) +}) diff --git a/packages/router-core/tests/searchParams-parse.bench.ts b/packages/router-core/tests/searchParams-parse.bench.ts new file mode 100644 index 0000000000..79f7e3e5ac --- /dev/null +++ b/packages/router-core/tests/searchParams-parse.bench.ts @@ -0,0 +1,328 @@ +import { describe, expect, test } from 'vitest' +import { defaultParseSearch, parseSearchWith } from '../src' + +const iterations = 1_000 + +const ordinaryStrings = { + tab: 'specs', + filter: 'available', + category: 'hardware', + sort: 'newest', +} +const nonLiteralInitialStrings = { + tab: 'specs', + filter: 'available', + category: 'hardware', + sort: 'descending', +} +const jsonInitialStrings = { + filter: 'foo', + notification: 'new', + tab: 'tabular', + empty: '', +} +const emptyStrings = { + first: '', + second: '', + third: '', + fourth: '', +} +const punctuationStrings = { + file: '.env', + path: '/products', + positive: '+1', + priority: '!important', +} +const nonLiteralPrefixStrings = { + first: 'future', + second: 'framework', + third: 'name', + fourth: 'table', +} +const jsonLiteralPrefixStrings = { + first: 'favorite', + second: 'number', + third: 'travel', + fourth: 'nullish', +} +const jsonLiteralWordStrings = { + truthy: 'true_value', + falsy: 'false_value', + nullable: 'null_value', +} +const jsonLiteralBoundaryStrings = { + truthy: 'true-value', + falsy: 'false/value', + nullable: 'null.value', +} +const jsonStrings = { + number: '123', + boolean: 'true', + object: '{"nested":true}', + array: '[1,2,3]', +} +const mixedValues = { + tab: 'specs', + page: '2', + filters: 'available', + exactPage: '2', +} + +function toSearchString(search: Record): string { + return new URLSearchParams(search).toString() +} + +let benchmarkSink = 0 + +// Correctness expectations for the parse side. +expect(defaultParseSearch(toSearchString(ordinaryStrings))).toEqual( + ordinaryStrings, +) +expect(defaultParseSearch(toSearchString(nonLiteralInitialStrings))).toEqual( + nonLiteralInitialStrings, +) +expect(defaultParseSearch(toSearchString(jsonInitialStrings))).toEqual( + jsonInitialStrings, +) +expect(defaultParseSearch(toSearchString(emptyStrings))).toEqual(emptyStrings) +expect(defaultParseSearch(toSearchString(punctuationStrings))).toEqual({ + ...punctuationStrings, + positive: '+1', +}) +expect(defaultParseSearch(toSearchString(nonLiteralPrefixStrings))).toEqual( + nonLiteralPrefixStrings, +) +expect(defaultParseSearch(toSearchString(jsonLiteralPrefixStrings))).toEqual( + jsonLiteralPrefixStrings, +) +expect(defaultParseSearch(toSearchString(jsonLiteralWordStrings))).toEqual( + jsonLiteralWordStrings, +) +expect(defaultParseSearch(toSearchString(jsonLiteralBoundaryStrings))).toEqual( + jsonLiteralBoundaryStrings, +) +expect(defaultParseSearch(toSearchString(jsonStrings))).toEqual({ + number: 123, + boolean: true, + object: { nested: true }, + array: [1, 2, 3], +}) + +function parseBatch(searchStr: string, parse = defaultParseSearch) { + let size = 0 + for (let index = 0; index < iterations; index++) { + size += Object.keys(parse(searchStr)).length + } + benchmarkSink = size +} + +const decodedPrimitives = { + number: '123', + negative: '-1', + yes: 'true', + no: 'false', +} +const parsedJson = { + nil: 'null', + quoted: '"hello"', + exponent: '1e2', + negativeZero: '-0', +} +const whitespaceJson = { + yes: ' true ', + nil: '\tnull', + array: '\n[1]', + object: '\r{}', +} +const malformedJson = { object: '{', array: '[', quoted: '"', number: '1e' } + +expect(defaultParseSearch(toSearchString(decodedPrimitives))).toEqual({ + number: 123, + negative: -1, + yes: true, + no: false, +}) +expect(defaultParseSearch(toSearchString(parsedJson))).toEqual({ + nil: null, + quoted: 'hello', + exponent: 100, + negativeZero: -0, +}) +expect(defaultParseSearch(toSearchString(whitespaceJson))).toEqual({ + yes: true, + nil: null, + array: [1], + object: {}, +}) +expect(defaultParseSearch(toSearchString(malformedJson))).toEqual(malformedJson) +expect(defaultParseSearch(toSearchString(mixedValues))).toEqual({ + tab: 'specs', + page: 2, + filters: 'available', + exactPage: 2, +}) + +// Encode fixtures before timing so the benchmark measures parsing alone. +const searches = Object.fromEntries( + Object.entries({ + ordinaryStrings, + nonLiteralInitialStrings, + jsonInitialStrings, + emptyStrings, + punctuationStrings, + nonLiteralPrefixStrings, + jsonLiteralPrefixStrings, + jsonLiteralWordStrings, + jsonLiteralBoundaryStrings, + jsonStrings, + mixedValues, + decodedPrimitives, + parsedJson, + whitespaceJson, + malformedJson, + }).map(([name, values]) => [name, toSearchString(values)]), +) + +describe('default search parsing', () => { + test('ordinary string values', async ({ bench }) => { + await bench('ordinary string values', () => { + parseBatch(searches.ordinaryStrings!) + }).run() + }) + + test('ordinary strings outside JSON-literal initials', async ({ bench }) => { + await bench('ordinary strings outside JSON-literal initials', () => { + parseBatch(searches.nonLiteralInitialStrings!) + }).run() + }) + + test('ordinary strings with JSON-literal initials', async ({ bench }) => { + await bench('ordinary strings with JSON-literal initials', () => { + parseBatch(searches.jsonInitialStrings!) + }).run() + }) + + test('empty string values', async ({ bench }) => { + await bench('empty string values', () => { + parseBatch(searches.emptyStrings!) + }).run() + }) + + test('ordinary strings with non-JSON punctuation starts', async ({ + bench, + }) => { + await bench('ordinary strings with non-JSON punctuation starts', () => { + parseBatch(searches.punctuationStrings!) + }).run() + }) + + test('ordinary f/n/t words outside JSON-literal prefixes', async ({ + bench, + }) => { + await bench('ordinary f/n/t words outside JSON-literal prefixes', () => { + parseBatch(searches.nonLiteralPrefixStrings!) + }).run() + }) + + test('application words with JSON-literal prefixes', async ({ bench }) => { + await bench('application words with JSON-literal prefixes', () => { + parseBatch(searches.jsonLiteralPrefixStrings!) + }).run() + }) + + test('application words with complete JSON-literal prefixes', async ({ + bench, + }) => { + await bench('application words with complete JSON-literal prefixes', () => { + parseBatch(searches.jsonLiteralWordStrings!) + }).run() + }) + + test('JSON-literal prefixes followed by punctuation', async ({ bench }) => { + await bench('JSON-literal prefixes followed by punctuation', () => { + parseBatch(searches.jsonLiteralBoundaryStrings!) + }).run() + }) + + test('JSON-compatible string values', async ({ bench }) => { + await bench('JSON-compatible string values', () => { + parseBatch(searches.jsonStrings!) + }).run() + }) + + test('mixed application values', async ({ bench }) => { + await bench('mixed application values', () => { + parseBatch(searches.mixedValues!) + }).run() + }) + test('primitives already converted by decode', async ({ bench }) => { + await bench('primitives already converted by decode', () => { + parseBatch(searches.decodedPrimitives!) + }).run() + }) + test('strings requiring JSON.parse', async ({ bench }) => { + await bench('strings requiring JSON.parse', () => { + parseBatch(searches.parsedJson!) + }).run() + }) + test('JSON with leading whitespace', async ({ bench }) => { + await bench('JSON with leading whitespace', () => { + parseBatch(searches.whitespaceJson!) + }).run() + }) + test('malformed JSON retains original strings', async ({ bench }) => { + await bench('malformed JSON retains original strings', () => { + parseBatch(searches.malformedJson!) + }).run() + }) +}) + +const customParse = parseSearchWith((value) => value.toUpperCase()) +expect(customParse(searches.ordinaryStrings!)).toEqual({ + tab: 'SPECS', + filter: 'AVAILABLE', + category: 'HARDWARE', + sort: 'NEWEST', +}) +test('custom search parser ordinary strings', async ({ bench }) => { + await bench('custom search parser ordinary strings', () => { + parseBatch(searches.ordinaryStrings!, customParse) + }).run() +}) + +const throwingParse = parseSearchWith(() => { + throw new Error('not parseable') +}) +expect(throwingParse(searches.ordinaryStrings!)).toEqual(ordinaryStrings) +test('custom search parser rejected strings', async ({ bench }) => { + await bench('custom search parser rejected strings', () => { + parseBatch(searches.ordinaryStrings!, throwingParse) + }).run() +}) + +const encodedMixed = new URLSearchParams([ + ['tab', 'specs'], + ['page', '2'], + ['quoted', '"2"'], + ['filters', '{"available":true}'], + ['q', 'hello world'], + ['category', 'favorite'], + ['tag', 'one'], + ['tag', 'two'], +]).toString() +expect(defaultParseSearch(encodedMixed)).toEqual({ + tab: 'specs', + page: 2, + quoted: '2', + filters: { available: true }, + q: 'hello world', + category: 'favorite', + tag: ['one', 'two'], +}) +test('encoded mixed search with repeated keys', async ({ bench }) => { + await bench('encoded mixed search with repeated keys', () => { + parseBatch(encodedMixed) + }).run() +}) + +void benchmarkSink diff --git a/packages/router-core/tests/searchParams.bench.ts b/packages/router-core/tests/searchParams.bench.ts new file mode 100644 index 0000000000..32d42b96fd --- /dev/null +++ b/packages/router-core/tests/searchParams.bench.ts @@ -0,0 +1,200 @@ +import { describe, expect, test } from 'vitest' +import { defaultStringifySearch } from '../src' + +const iterations = 1_000 + +const ordinaryStrings = { + tab: 'specs', + filter: 'available', + category: 'hardware', + sort: 'newest', +} +const nonLiteralInitialStrings = { + tab: 'specs', + filter: 'available', + category: 'hardware', + sort: 'descending', +} +const jsonInitialStrings = { + filter: 'foo', + notification: 'new', + tab: 'tabular', + empty: '', +} +const emptyStrings = { + first: '', + second: '', + third: '', + fourth: '', +} +const punctuationStrings = { + file: '.env', + path: '/products', + positive: '+1', + priority: '!important', +} +const nonLiteralPrefixStrings = { + first: 'future', + second: 'framework', + third: 'name', + fourth: 'table', +} +const jsonLiteralPrefixStrings = { + first: 'favorite', + second: 'number', + third: 'travel', + fourth: 'nullish', +} +const jsonLiteralWordStrings = { + truthy: 'true_value', + falsy: 'false_value', + nullable: 'null_value', +} +const jsonLiteralBoundaryStrings = { + truthy: 'true-value', + falsy: 'false/value', + nullable: 'null.value', +} +const jsonStrings = { + number: '123', + boolean: 'true', + object: '{"nested":true}', + array: '[1,2,3]', +} +const mixedValues = { + tab: 'specs', + page: 2, + filters: ['available', 'featured'], + exactPage: '2', +} +let benchmarkSink = 0 + +expect(defaultStringifySearch(ordinaryStrings)).toBe( + '?tab=specs&filter=available&category=hardware&sort=newest', +) +expect(defaultStringifySearch(nonLiteralInitialStrings)).toBe( + '?tab=specs&filter=available&category=hardware&sort=descending', +) +expect(defaultStringifySearch(jsonInitialStrings)).toBe( + '?filter=foo¬ification=new&tab=tabular&empty=', +) +expect(defaultStringifySearch(emptyStrings)).toBe( + '?first=&second=&third=&fourth=', +) +expect(defaultStringifySearch(punctuationStrings)).toBe( + '?file=.env&path=%2Fproducts&positive=%2B1&priority=%21important', +) +expect(defaultStringifySearch(nonLiteralPrefixStrings)).toBe( + '?first=future&second=framework&third=name&fourth=table', +) +expect(defaultStringifySearch(jsonLiteralPrefixStrings)).toBe( + '?first=favorite&second=number&third=travel&fourth=nullish', +) +expect(defaultStringifySearch(jsonLiteralWordStrings)).toBe( + '?truthy=true_value&falsy=false_value&nullable=null_value', +) +expect(defaultStringifySearch(jsonLiteralBoundaryStrings)).toBe( + '?truthy=true-value&falsy=false%2Fvalue&nullable=null.value', +) +expect(defaultStringifySearch(jsonStrings)).toBe( + '?number=%22123%22&boolean=%22true%22&object=%22%7B%5C%22nested%5C%22%3Atrue%7D%22&array=%22%5B1%2C2%2C3%5D%22', +) +expect(defaultStringifySearch(mixedValues)).toBe( + '?tab=specs&page=2&filters=%5B%22available%22%2C%22featured%22%5D&exactPage=%222%22', +) + +function stringifyBatch(search: Record) { + let size = 0 + for (let index = 0; index < iterations; index++) { + size += defaultStringifySearch(search).length + } + benchmarkSink = size +} + +describe('default search serialization', () => { + test('empty object', async ({ bench }) => { + await bench('empty object', () => { + stringifyBatch({}) + }).run() + }) + + test('only undefined values', async ({ bench }) => { + await bench('only undefined values', () => { + stringifyBatch({ first: undefined, second: undefined }) + }).run() + }) + + test('ordinary string values', async ({ bench }) => { + await bench('ordinary string values', () => { + stringifyBatch(ordinaryStrings) + }).run() + }) + + test('ordinary strings outside JSON-literal initials', async ({ bench }) => { + await bench('ordinary strings outside JSON-literal initials', () => { + stringifyBatch(nonLiteralInitialStrings) + }).run() + }) + + test('ordinary strings with JSON-literal initials', async ({ bench }) => { + await bench('ordinary strings with JSON-literal initials', () => { + stringifyBatch(jsonInitialStrings) + }).run() + }) + + test('empty string values', async ({ bench }) => { + await bench('empty string values', () => { + stringifyBatch(emptyStrings) + }).run() + }) + + test('ordinary strings with non-JSON punctuation starts', async ({ + bench, + }) => { + await bench('ordinary strings with non-JSON punctuation starts', () => { + stringifyBatch(punctuationStrings) + }).run() + }) + + test('ordinary f/n/t words outside JSON-literal prefixes', async ({ + bench, + }) => { + await bench('ordinary f/n/t words outside JSON-literal prefixes', () => { + stringifyBatch(nonLiteralPrefixStrings) + }).run() + }) + + test('application words with JSON-literal prefixes', async ({ bench }) => { + await bench('application words with JSON-literal prefixes', () => { + stringifyBatch(jsonLiteralPrefixStrings) + }).run() + }) + + test('application words with complete JSON-literal prefixes', async ({ + bench, + }) => { + await bench('application words with complete JSON-literal prefixes', () => { + stringifyBatch(jsonLiteralWordStrings) + }).run() + }) + + test('JSON-literal prefixes followed by punctuation', async ({ bench }) => { + await bench('JSON-literal prefixes followed by punctuation', () => { + stringifyBatch(jsonLiteralBoundaryStrings) + }).run() + }) + + test('JSON-compatible string values', async ({ bench }) => { + await bench('JSON-compatible string values', () => { + stringifyBatch(jsonStrings) + }).run() + }) + + test('mixed application values', async ({ bench }) => { + await bench('mixed application values', () => { + stringifyBatch(mixedValues) + }).run() + }) +}) + +void benchmarkSink diff --git a/packages/router-core/tests/searchParams.test.ts b/packages/router-core/tests/searchParams.test.ts index 006e119be5..ab63e6ce3b 100644 --- a/packages/router-core/tests/searchParams.test.ts +++ b/packages/router-core/tests/searchParams.test.ts @@ -1,5 +1,10 @@ -import { describe, expect, test } from 'vitest' -import { defaultParseSearch, defaultStringifySearch } from '../src' +import { describe, expect, test, vi } from 'vitest' +import { + defaultParseSearch, + defaultStringifySearch, + parseSearchWith, + stringifySearchWith, +} from '../src' describe('Search Params serialization and deserialization', () => { /* @@ -47,6 +52,176 @@ describe('Search Params serialization and deserialization', () => { expect(defaultParseSearch(str)).toEqual({ foo: 'bar' }) }) + test.each([ + 'false', + '-1', + '"quoted"', + ' true ', + 'true ', + 'false\t', + 'null\r\n', + '\tfalse', + '\nnull', + '\r1', + ' ', + '雪', + '"雪"', + ])('preserves JSON-compatible string %j as a string', (value) => { + const str = defaultStringifySearch({ value }) + expect(defaultParseSearch(str)).toEqual({ value }) + }) + + test('uses custom parsers for ordinary strings', () => { + const stringify = stringifySearchWith(JSON.stringify, (value) => { + if (value === 'word') { + return value + } + throw new Error('not parseable') + }) + + expect(stringify({ value: 'word' })).toEqual('?value=%22word%22') + }) + + test('skips JSON.parse for strings that cannot be JSON', () => { + const parseSpy = vi.spyOn(JSON, 'parse') + try { + const stringify = stringifySearchWith(JSON.stringify, JSON.parse) + + expect( + stringify({ + empty: '', + filter: 'foo', + future: 'future', + name: 'name', + notification: 'new', + tab: 'tabular', + topic: 'topic', + unicode: '雪', + }), + ).toEqual( + '?empty=&filter=foo&future=future&name=name¬ification=new&tab=tabular&topic=topic&unicode=%E9%9B%AA', + ) + expect( + stringify({ file: '.env', path: '/products', positive: '+1' }), + ).toEqual('?file=.env&path=%2Fproducts&positive=%2B1') + expect(parseSpy).not.toHaveBeenCalled() + } finally { + parseSpy.mockRestore() + } + }) + + test('parse skips JSON.parse for strings that cannot begin valid JSON', () => { + const parseSpy = vi.spyOn(JSON, 'parse') + try { + const parse = parseSearchWith(JSON.parse) + expect(parse('?empty=&filter=foo&tab=specs&sort=newest')).toEqual({ + empty: '', + filter: 'foo', + tab: 'specs', + sort: 'newest', + }) + expect(parse('?file=.env&path=/products')).toEqual({ + file: '.env', + path: '/products', + }) + expect(parseSpy).not.toHaveBeenCalled() + expect(parse('?value=%7B%7D')).toEqual({ value: {} }) + expect(parseSpy).toHaveBeenCalledExactlyOnceWith('{}') + } finally { + parseSpy.mockRestore() + } + }) + + test('parse still parses strings that pass the jsonStart guard', () => { + expect(defaultParseSearch('?n=123&flag=true&obj={"a":1}&arr=[1]')).toEqual({ + n: 123, + flag: true, + obj: { a: 1 }, + arr: [1], + }) + }) + + test('parse applies the guard only when the parser is JSON.parse', () => { + const upperCaseParser = (str: string) => str.toUpperCase() + const parse = parseSearchWith(upperCaseParser) + + // A non-JSON parser is invoked even for values the jsonStart + // regex would reject. + expect(parse('?foo=bar&filter=available')).toEqual({ + foo: 'BAR', + filter: 'AVAILABLE', + }) + }) + + test.each([ + ['null', null], + [' true ', true], + ['\tfalse', false], + ['\nnull', null], + ['\r1', 1], + ['1e2', 100], + ['-0', -0], + ['0.0', 0], + ['"雪"', '雪'], + [' {"nested":[true,null]} ', { nested: [true, null] }], + [' [1,"two"] ', [1, 'two']], + ['', ''], + [' \t\r\n', ' \t\r\n'], + ['favorite', 'favorite'], + ['nullish', 'nullish'], + ['travel', 'travel'], + ['true_value', 'true_value'], + ['{', '{'], + ['[', '['], + ['"', '"'], + ['-', '-'], + ['01', '01'], + ['1e', '1e'], + ['+1', '+1'], + ['雪', '雪'], + ['\u00a0null', '\u00a0null'], + ['\ufefftrue', '\ufefftrue'], + ])( + 'parses decoded value %j without changing fallback behavior', + (value, expected) => { + const search = new URLSearchParams({ value }).toString() + expect(defaultParseSearch(search)).toEqual({ value: expected }) + expect(defaultParseSearch(`?${search}`)).toEqual({ value: expected }) + }, + ) + + test('custom parsers receive every string, preserve failures, and skip decoded non-strings', () => { + const parser = vi.fn((value: string) => { + if (value === 'invalid') { + throw new Error('not parseable') + } + return { parsed: value } + }) + const parse = parseSearchWith(parser) + expect( + parse( + '?empty=&word=hello&bad=invalid&json=null&n=1&b=true&tag=foo&tag=%7B%7D', + ), + ).toEqual({ + empty: { parsed: '' }, + word: { parsed: 'hello' }, + bad: 'invalid', + json: { parsed: 'null' }, + n: 1, + b: true, + tag: ['foo', '{}'], + }) + expect(parser.mock.calls).toEqual([[''], ['hello'], ['invalid'], ['null']]) + }) + + test('preserves repeated JSON-looking values as decoded arrays', () => { + expect( + defaultParseSearch('?value=null&value=%7B%7D&value=%5B%5D&value=1'), + ).toEqual({ + value: ['null', '{}', '[]', 1], + }) + }) + test('[edge case] self-reference serializes to "object Object"', () => { const obj = {} as any obj.self = obj diff --git a/packages/router-core/tests/serial-failure-foreground-prefix.test.ts b/packages/router-core/tests/serial-failure-foreground-prefix.test.ts new file mode 100644 index 0000000000..ef57474288 --- /dev/null +++ b/packages/router-core/tests/serial-failure-foreground-prefix.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * When the serial beforeLoad phase records a failure, retained ancestor + * prefix loaders belong to the foreground failure lane: a stale ancestor + * must reload in the foreground commit rather than being deferred into a + * background batch that the boundary trim would discard. + */ + +describe('serial failure keeps ancestor reloads in the foreground lane', () => { + test('a stale ancestor reloads with fresh data when a child beforeLoad fails', async () => { + let parentRuns = 0 + let shouldFail = false + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + staleTime: 0, + loader: () => `parent run ${++parentRuns}`, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + errorComponent: {}, + beforeLoad: () => { + if (shouldFail) { + throw new Error('child beforeLoad failed') + } + }, + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + await router.load() + expect(parentRuns).toBe(1) + + await router.navigate({ to: '/' }) + shouldFail = true + await router.navigate({ to: '/parent/child' }) + + const parentMatch = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + ) + const childMatch = router.state.matches.find( + (match) => match.routeId === childRoute.id, + ) + + // The child committed its serial failure... + expect(childMatch?.status).toBe('error') + // ...and the stale parent reloaded in the SAME foreground lane: fresh + // loaderData is committed with the failure, not deferred to a discarded + // background batch. + expect(parentRuns).toBe(2) + expect(parentMatch?.loaderData).toBe('parent run 2') + expect(parentMatch?.status).toBe('success') + }) +}) diff --git a/packages/router-core/tests/serializer-recursion.test-d.ts b/packages/router-core/tests/serializer-recursion.test-d.ts index 4df82d5b73..a688ed3b4a 100644 --- a/packages/router-core/tests/serializer-recursion.test-d.ts +++ b/packages/router-core/tests/serializer-recursion.test-d.ts @@ -3,7 +3,6 @@ import { describe, expectTypeOf, it } from 'vitest' import type { Serializable, ValidateSerializable, - ValidateSerializableResult, } from '../src/ssr/serializer/transformer' describe('ValidateSerializable array handling', () => { @@ -51,30 +50,4 @@ describe('ValidateSerializable array handling', () => { ValidateSerializable >().branded.toEqualTypeOf() }) - - it('should preserve recursive payload without infinite expansion', () => { - type Result = Array | { [key: string]: Result } - expectTypeOf< - ValidateSerializableResult - >().branded.toEqualTypeOf() - }) - - it('should preserve recursive tuples without infinite expansion', () => { - type ResultTuple = readonly [ - ReadonlyArray, - { [key: string]: ResultTuple }, - ] - expectTypeOf< - ValidateSerializableResult - >().branded.toEqualTypeOf() - }) - - it('should preserve readonly recursive arrays without infinite expansion', () => { - type ResultReadonlyArray = ReadonlyArray< - ResultReadonlyArray | { [key: string]: ResultReadonlyArray } - > - expectTypeOf< - ValidateSerializableResult - >().branded.toEqualTypeOf() - }) }) diff --git a/packages/router-core/tests/serializer.test-d.ts b/packages/router-core/tests/serializer.test-d.ts index 4fd2c69faa..5ef3e3964b 100644 --- a/packages/router-core/tests/serializer.test-d.ts +++ b/packages/router-core/tests/serializer.test-d.ts @@ -1,68 +1,18 @@ import { describe, expectTypeOf, it } from 'vitest' -import { +import type { Serializable, + SerializationError, TsrSerializable, ValidateSerializable, - ValidateSerializableResult, } from '../src/ssr/serializer/transformer' describe('Serializer', () => { - describe('Default types are serializable: $name', () => { - it('string', () => { - const value: string = 'hello' - expectTypeOf< - ValidateSerializableResult - >().toBeString() - }) - it('number', () => { - const value: number = 123 - - expectTypeOf< - ValidateSerializableResult - >().toBeNumber() - }) - it('boolean', () => { - const value: boolean = true - - expectTypeOf< - ValidateSerializableResult - >().toBeBoolean() - }) - it('null', () => { - const value = null - - expectTypeOf< - ValidateSerializableResult - >().toBeNull() - }) - it('undefined', () => { - const value = undefined - - expectTypeOf< - ValidateSerializableResult - >().toBeUndefined() - }) - it('bigint', () => { - const value = BigInt(123) - - expectTypeOf< - ValidateSerializableResult - >().toBeBigInt() - }) - it('Date', () => { - const value = new Date() - - expectTypeOf< - ValidateSerializableResult - >().toEqualTypeOf() - }) - }) it('fails for non-serializable types', () => { const value = () => {} expectTypeOf< ValidateSerializable - >().toEqualTypeOf<'Function is not serializable'>() + >().toEqualTypeOf>() }) it('works for types extending TsrSerializable', () => { diff --git a/packages/router-core/tests/server-async-headers-decorative-hang.test.ts b/packages/router-core/tests/server-async-headers-decorative-hang.test.ts new file mode 100644 index 0000000000..454e6a6bb8 --- /dev/null +++ b/packages/router-core/tests/server-async-headers-decorative-hang.test.ts @@ -0,0 +1,52 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +afterEach(() => { + vi.restoreAllMocks() +}) + +test('a rejected projection hook is logged without failing the response', async () => { + const projectionError = new Error('scripts failed') + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const headGate = createControlledPromise<{ + meta: Array<{ title: string }> + }>() + const headersGate = createControlledPromise>() + const head = vi.fn(() => headGate) + const scripts = vi.fn(async () => { + throw projectionError + }) + const headers = vi.fn(() => headersGate) + + const rootRoute = new BaseRootRoute({}) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + head, + scripts, + headers, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([targetRoute]), + history: createMemoryHistory({ initialEntries: ['/target'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/target') + + expect(headGate.status).toBe('pending') + expect(headersGate.status).toBe('pending') + expect(response.status).toBe(200) + expect(response.headers.get('x-response-header')).toBeNull() + expect(head).toHaveBeenCalledTimes(1) + expect(scripts).toHaveBeenCalledTimes(1) + expect(headers).toHaveBeenCalledTimes(1) + expect(log).toHaveBeenCalledTimes(1) + expect(log).toHaveBeenCalledWith(projectionError) + + headGate.resolve({ meta: [{ title: 'discarded' }] }) + headersGate.resolve({ 'x-response-header': 'discarded' }) + await Promise.all([headGate, headersGate]) +}) diff --git a/packages/router-core/tests/server-beforeload-preload-flag.test.ts b/packages/router-core/tests/server-beforeload-preload-flag.test.ts new file mode 100644 index 0000000000..4779001305 --- /dev/null +++ b/packages/router-core/tests/server-beforeload-preload-flag.test.ts @@ -0,0 +1,88 @@ +import { createMemoryHistory } from '@tanstack/history' +import { expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +test('server beforeLoad receives preload false', async () => { + const seen: Array = [] + const rootRoute = new BaseRootRoute({}) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + beforeLoad: ({ preload }) => { + seen.push(preload) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: true, + }) + + await router.load() + + expect(seen).toEqual([false]) +}) + +test('server preloadRoute stays speculative and receives preload true', async () => { + const beforeLoad = vi.fn() + const loader = vi.fn(() => 'preloaded data') + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + beforeLoad, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, childRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + + await router.load() + const matches = await router.preloadRoute({ to: '/child' }) + + expect(beforeLoad).toHaveBeenCalledWith( + expect.objectContaining({ preload: true }), + ) + expect(loader).toHaveBeenCalledOnce() + expect(matches?.at(-1)).toMatchObject({ + routeId: childRoute.id, + loaderData: 'preloaded data', + }) + expect(router.state.location.pathname).toBe('/') + expect(router.state.matches.at(-1)?.routeId).toBe(indexRoute.id) +}) + +test('server child context receives its parent beforeLoad context', async () => { + const rootRoute = new BaseRootRoute({ + beforeLoad: () => ({ parent: 'ready' }), + }) + const childContext = vi.fn(({ context }) => ({ + child: `${context.parent}:child`, + })) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + context: childContext, + loader: ({ context }) => context.child, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: true, + }) + + await router.load() + + expect(router.state.matches.at(-1)).toMatchObject({ + context: { parent: 'ready', child: 'ready:child' }, + loaderData: 'ready:child', + }) + expect(childContext).toHaveBeenCalledTimes(1) +}) diff --git a/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts b/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts new file mode 100644 index 0000000000..662fab95f9 --- /dev/null +++ b/packages/router-core/tests/server-chunk-failure-lifecycle.test.ts @@ -0,0 +1,238 @@ +import { describe, expect, onTestFinished, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, + redirect, +} from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +/** + * A primary route chunk failure observed by the server loader phase (a route + * component preload or lazyFn rejection) must go through the same route + * failure lifecycle as loader failures: the route's onError runs, + * redirect/notFound conversion applies, and the errorComponent boundary + * chunk is loaded. Only boundary component chunk failures commit directly + * without recursing into another boundary chunk. + * + * These tests use real server router loads and public component preload/lazy + * route APIs. + */ + +describe('server route chunk failure lifecycle', () => { + test('calls route onError once and loads the errorComponent chunk when the route component chunk rejects', async () => { + const chunkError = new Error('component chunk failed') + const capturedErrors: Array = [] + const events: Array = [] + + const FailingComponent = Object.assign(() => null, { + preload: () => Promise.reject(chunkError), + }) + const ErrorBoundary = Object.assign(() => null, { + preload: () => { + events.push('errorComponent-preload') + return Promise.resolve() + }, + }) + + const rootRoute = new BaseRootRoute({}) + const chunkedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/chunked', + onError: (error: unknown) => { + capturedErrors.push(error) + events.push('onError') + }, + component: FailingComponent as any, + errorComponent: ErrorBoundary as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([chunkedRoute]), + history: createMemoryHistory({ initialEntries: ['/chunked'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/chunked') + + const match = router.state.matches.find( + (item) => item.routeId === chunkedRoute.id, + ) + expect(capturedErrors).toEqual([chunkError]) + expect(match?.status).toBe('error') + expect(match?.error).toBe(chunkError) + expect(events).toEqual(['onError', 'errorComponent-preload']) + expect(response.status).toBe(500) + }) + + test('a notFound thrown from onError for a route chunk failure sets 404 instead of 500', async () => { + const chunkError = new Error('component chunk failed') + + const FailingComponent = Object.assign(() => null, { + preload: () => Promise.reject(chunkError), + }) + + const rootRoute = new BaseRootRoute({}) + const chunkedRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/chunked', + onError: () => { + throw notFound() + }, + component: FailingComponent as any, + notFoundComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([chunkedRoute]), + history: createMemoryHistory({ initialEntries: ['/chunked'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/chunked') + + const match = router.state.matches.find( + (item) => item.routeId === chunkedRoute.id, + ) + expect(response.status).toBe(404) + expect(match?.status).toBe('notFound') + expect(match?.error).toEqual(expect.objectContaining({ isNotFound: true })) + }) + + test('the first route-order chunk failure determines the response', async () => { + const rootError = new Error('root component failed') + const rootChunkGate = createControlledPromise() + const childConverted = createControlledPromise() + const RootComponent = Object.assign(() => null, { + preload: () => rootChunkGate, + }) + const ChildComponent = Object.assign(() => null, { + preload: () => Promise.reject(new Error('child component failed')), + }) + + const rootRoute = new BaseRootRoute({ + component: RootComponent as any, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + component: ChildComponent as any, + onError: () => { + childConverted.resolve() + throw redirect({ to: '/elsewhere' }) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: true, + }) + + const responsePromise = loadServerResponse(router, '/child') + await childConverted + rootChunkGate.reject(rootError) + const response = await responsePromise + + expect(response.status).toBe(500) + expect(response.headers.get('Location')).toBeNull() + expect(router.state.matches).toHaveLength(2) + expect(router.state.matches[0]).toMatchObject({ + routeId: rootRoute.id, + status: 'error', + error: rootError, + }) + }) + + test('does not leave later chunk rejections unhandled after request abort', async () => { + const rootError = new Error('root component failed') + const abortError = new Error('request closed') + const rootChunkGate = createControlledPromise() + const childChunkGate = createControlledPromise() + const rootChunkStarted = createControlledPromise() + const childChunkStarted = createControlledPromise() + const RootComponent = Object.assign(() => null, { + preload: () => { + rootChunkStarted.resolve() + return rootChunkGate + }, + }) + const ChildComponent = Object.assign(() => null, { + preload: () => { + childChunkStarted.resolve() + return childChunkGate + }, + }) + const rootRoute = new BaseRootRoute({ + component: RootComponent as any, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + component: ChildComponent as any, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: true, + }) + const controller = new AbortController() + const unhandled: Array = [] + const onUnhandled = (error: unknown) => { + unhandled.push(error) + } + process.on('unhandledRejection', onUnhandled) + onTestFinished(() => { + process.off('unhandledRejection', onUnhandled) + }) + + const responsePromise = loadServerResponse( + router, + '/child', + controller.signal, + ) + await Promise.all([rootChunkStarted, childChunkStarted]) + + rootChunkGate.reject(rootError) + await expect(responsePromise).resolves.toMatchObject({ status: 500 }) + + controller.abort(abortError) + childChunkGate.resolve() + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(unhandled).not.toContain(abortError) + }) + + test('a required ancestor lazy chunk failure wins over a deeper loader notFound', async () => { + const chunkError = new Error('ancestor lazy chunk failed') + const rootRoute = new BaseRootRoute({}) + const ancestorRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/ancestor', + errorComponent: () => null, + }).lazy(() => Promise.reject(chunkError)) + const childRoute = new BaseRoute({ + getParentRoute: () => ancestorRoute, + path: '/child', + loader: () => { + throw notFound() + }, + notFoundComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + ancestorRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/ancestor/child'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/ancestor/child') + + expect(response.status).toBe(500) + expect( + router.state.matches.find((match) => match.routeId === ancestorRoute.id), + ).toMatchObject({ status: 'error', error: chunkError }) + }) +}) diff --git a/packages/router-core/tests/server-concurrent-error-notfound.test.ts b/packages/router-core/tests/server-concurrent-error-notfound.test.ts new file mode 100644 index 0000000000..5fc3cc63f9 --- /dev/null +++ b/packages/router-core/tests/server-concurrent-error-notfound.test.ts @@ -0,0 +1,467 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, + redirect, +} from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +const requiredPrefixModes = [ + ['fresh', 'error', false, 'child-first'], + ['fresh', 'error', true, 'child-first'], + ['fresh', 'notFound', false, 'child-first'], + ['fresh', 'notFound', true, 'child-first'], + ['retained', 'error', false, 'child-first'], + ['retained', 'notFound', false, 'child-first'], + ['retained', 'error', false, 'parent-first'], +] as const + +describe('concurrent route failure ordering', () => { + test.each(requiredPrefixModes)( + 'selects the reachable failure (parentData=%s, parent=%s, isServer=%s, order=%s)', + async (parentData, parentOutcome, isServer, settlementOrder) => { + const parentFailure = + parentOutcome === 'error' + ? new Error('parent loader failed') + : notFound() + const childFailure = + parentOutcome === 'error' + ? notFound() + : new Error('child loader failed') + const childOutcome = parentOutcome === 'error' ? 'notFound' : 'error' + const parentGate = createControlledPromise() + const childGate = createControlledPromise() + const parentStarted = createControlledPromise() + const childStarted = createControlledPromise() + const parentSettled = createControlledPromise() + const childSettled = createControlledPromise() + const settlements: Array = [] + let failing = parentData === 'fresh' + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + ssr: 'data-only', + loader: async () => { + if (!failing) { + return undefined + } + parentStarted.resolve() + await parentGate + settlements.push('parent') + parentSettled.resolve() + throw parentFailure + }, + errorComponent: () => null, + notFoundComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + if (!failing) { + return 'child data' + } + childStarted.resolve() + await childGate + settlements.push('child') + childSettled.resolve() + throw childFailure + }, + errorComponent: () => null, + notFoundComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer, + defaultStaleReloadMode: 'blocking', + }) + + if (parentData === 'retained') { + await router.load() + const parentMatch = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + ) + expect(parentMatch).toMatchObject({ + routeId: parentRoute.id, + status: 'success', + loaderData: undefined, + }) + failing = true + } + + const responsePromise = isServer + ? loadServerResponse(router, '/parent/child') + : (parentData === 'retained' + ? router.invalidate() + : router.load() + ).then(() => undefined) + await Promise.all([parentStarted, childStarted]) + if (settlementOrder === 'child-first') { + childGate.resolve() + await childSettled + parentGate.resolve() + await parentSettled + } else { + parentGate.resolve() + await parentSettled + childGate.resolve() + await childSettled + } + const response = await responsePromise + + const parentWon = + parentData === 'fresh' || settlementOrder === 'parent-first' + const selectedOutcome = parentWon ? parentOutcome : childOutcome + const selectedFailure = parentWon ? parentFailure : childFailure + if (isServer) { + expect(response?.status).toBe(selectedOutcome === 'error' ? 500 : 404) + } + expect(settlements).toEqual( + settlementOrder === 'child-first' + ? ['child', 'parent'] + : ['parent', 'child'], + ) + const terminalMatch = router.state.matches.find( + (match) => match.status === 'error' || match.status === 'notFound', + ) + expect(terminalMatch).toMatchObject({ + routeId: parentWon ? parentRoute.id : childRoute.id, + status: selectedOutcome, + error: selectedFailure, + }) + expect(router.state.status).toBe('idle') + }, + ) + + test.each([false, true])( + 'recomputes chunk readiness after a notFound ancestor promotes to root (isServer=%s)', + async (isServer) => { + const chunkError = new Error('intermediate lazy chunk failed') + const childError = new Error('child loader failed') + const rootNotFound = notFound() + const ancestorGate = createControlledPromise() + const childGate = createControlledPromise() + const ancestorStarted = createControlledPromise() + const childStarted = createControlledPromise() + const ancestorSettled = createControlledPromise() + const childSettled = createControlledPromise() + const settlements: Array = [] + const intermediateLazy = vi.fn(() => Promise.reject(chunkError)) + const rootRoute = new BaseRootRoute({ + notFoundComponent: () => null, + }) + const intermediateRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/intermediate', + errorComponent: () => null, + }).lazy(intermediateLazy) + const ancestorRoute = new BaseRoute({ + getParentRoute: () => intermediateRoute, + path: '/ancestor', + loader: async () => { + ancestorStarted.resolve() + await ancestorGate + settlements.push('ancestor') + ancestorSettled.resolve() + throw rootNotFound + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => ancestorRoute, + path: '/child', + loader: async () => { + childStarted.resolve() + await childGate + settlements.push('child') + childSettled.resolve() + throw childError + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + intermediateRoute.addChildren([ + ancestorRoute.addChildren([childRoute]), + ]), + ]), + history: createMemoryHistory({ + initialEntries: ['/intermediate/ancestor/child'], + }), + isServer, + }) + + const responsePromise = isServer + ? loadServerResponse(router, '/intermediate/ancestor/child') + : router.load().then(() => undefined) + await Promise.all([ancestorStarted, childStarted]) + childGate.resolve() + await childSettled + ancestorGate.resolve() + await ancestorSettled + const response = await responsePromise + + if (isServer) { + expect(response?.status).toBe(404) + } + expect(settlements).toEqual(['child', 'ancestor']) + expect(intermediateLazy).toHaveBeenCalled() + expect( + router.state.matches.find((match) => match.routeId === rootRoute.id), + ).toMatchObject({ + status: 'success', + error: rootNotFound, + }) + expect( + router.state.matches.some((match) => match.error === chunkError), + ).toBe(false) + }, + ) + + test.each([ + [false, 'beforeLoad'], + [false, 'loader'], + [true, 'beforeLoad'], + [true, 'loader'], + ] as const)( + 'keeps a resolved notFound boundary stable within one load (isServer=%s, phase=%s)', + async (isServer, phase) => { + const lazyError = new Error('lazy boundary lookup failed') + const notFoundError = notFound() + const resolveAt = phase === 'beforeLoad' ? 2 : 3 + let lazyCalls = 0 + const rootRoute = new BaseRootRoute({ + notFoundComponent: () => null, + }) + const intermediateRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/intermediate', + }).lazy(() => { + lazyCalls++ + if (lazyCalls < resolveAt) { + return Promise.reject(lazyError) + } + return Promise.resolve({ + options: { notFoundComponent: () => null }, + } as any) + }) + function throwNotFound() { + throw notFoundError + } + const childRoute = new BaseRoute({ + getParentRoute: () => intermediateRoute, + path: '/child', + beforeLoad: phase === 'beforeLoad' ? throwNotFound : undefined, + loader: phase === 'loader' ? throwNotFound : undefined, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + intermediateRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ + initialEntries: ['/intermediate/child'], + }), + isServer, + }) + + const response = isServer + ? await loadServerResponse(router, '/intermediate/child') + : await router.load().then(() => undefined) + + if (isServer) { + expect(response?.status).toBe(404) + } + expect(lazyCalls).toBe(!isServer && phase === 'loader' ? 2 : 1) + expect( + router.state.matches.find((match) => match.error === notFoundError) + ?.routeId, + ).toBe(rootRoute.id) + }, + ) + + test('a redirect aborts every generation in its discarded server lane', async () => { + const signals: Array = [] + const rootRoute = new BaseRootRoute({ + loader: ({ abortController }) => { + signals.push(abortController.signal) + return 'root data' + }, + }) + const redirectRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/redirect', + loader: ({ abortController }) => { + signals.push(abortController.signal) + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([redirectRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/redirect'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/redirect') + + expect(response.status).toBe(307) + expect(response.headers.get('Location')).toBe('/target') + expect(signals).toHaveLength(2) + expect(signals.every((signal) => signal.aborted)).toBe(true) + }) + + test('a started descendant can redirect after its ancestor fails', async () => { + const childStarted = createControlledPromise() + const childRedirect = createControlledPromise() + const parentError = new Error('parent failed') + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: async () => { + await childStarted + throw parentError + }, + errorComponent: () => null, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: async () => { + childStarted.resolve() + await childRedirect + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + + const responsePromise = loadServerResponse(router, '/parent/child') + await childStarted + childRedirect.resolve() + const response = await responsePromise + + expect(response.status).toBe(307) + expect(response.headers.get('Location')).toBe('/target') + }) + + test('a redirect does not abort a later server generation on the same router', async () => { + let generation = 0 + const rootRoute = new BaseRootRoute({}) + const pageRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => { + generation++ + if (generation === 2) { + throw redirect({ to: '/target' }) + } + return `data ${generation}` + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([pageRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + isServer: true, + }) + + expect((await loadServerResponse(router, '/page')).status).toBe(200) + expect((await loadServerResponse(router, '/page')).status).toBe(307) + expect((await loadServerResponse(router, '/page')).status).toBe(200) + + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: pageRoute.id, + status: 'success', + loaderData: 'data 3', + }) + }) + + test.each([false, true])( + 'an aborted child does not report its cancellation through onError (isServer=%s)', + async (isServer) => { + const childStarted = createControlledPromise() + const childLoader = createControlledPromise() + const cancellation = new Error('discarded request aborted') + const childOnError = vi.fn() + let childSignal: AbortSignal | undefined + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: async () => { + await childStarted + throw redirect({ to: '/target' }) + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => sourceRoute, + path: '/child', + loader: ({ abortController }) => { + childSignal = abortController.signal + abortController.signal.addEventListener( + 'abort', + () => childLoader.reject(cancellation), + { once: true }, + ) + childStarted.resolve() + return childLoader + }, + onError: childOnError, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + sourceRoute.addChildren([childRoute]), + targetRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/source/child'] }), + isServer, + }) + + const childCancellation = expect(childLoader).rejects.toBe(cancellation) + const loadPromise = isServer + ? loadServerResponse(router, '/source/child') + : router.load().then(() => undefined) + const [response] = await Promise.all([loadPromise, childCancellation]) + + expect(childSignal?.aborted).toBe(true) + expect(childOnError).not.toHaveBeenCalled() + if (isServer) { + expect(response?.status).toBe(307) + expect(response?.headers.get('Location')).toBe('/target') + } else { + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + } + }, + ) +}) diff --git a/packages/router-core/tests/server-history.test.ts b/packages/router-core/tests/server-history.test.ts new file mode 100644 index 0000000000..6343a08cd2 --- /dev/null +++ b/packages/router-core/tests/server-history.test.ts @@ -0,0 +1,246 @@ +import { createMemoryHistory, createServerHistory } from '@tanstack/history' +import { expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute, redirect } from '../src' +import { createRequestHandler } from '../src/ssr/server' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +test.each([ + { basepath: '', origin: undefined }, + { basepath: '/app', origin: undefined }, + { basepath: '/app', origin: 'https://canonical.example' }, +])( + 'request handling rewrites once with basepath $basepath and origin $origin', + async ({ basepath, origin }) => { + const root = new BaseRootRoute() + const input = vi.fn(({ url }: { url: URL }) => { + url.pathname = url.pathname.replace('/public/', '/posts/') + return url + }) + const router = createTestRouter({ + isServer: true, + basepath, + origin, + rewrite: { + input, + output: ({ url }) => { + url.pathname = url.pathname.replace('/posts/', '/public/') + return url + }, + }, + routeTree: root.addChildren([ + new BaseRoute({ + getParentRoute: () => root, + path: '/posts/$postId', + loader: ({ params }) => params.postId, + }), + ]), + }) + input.mockClear() + + const response = await createRequestHandler({ + createRouter: () => router, + request: new Request( + `https://example.com${basepath}/public/caf%C3%A9?view=full`, + ), + })(({ router: loadedRouter }) => { + return Response.json({ + postId: loadedRouter.state.matches.at(-1)?.loaderData, + pathname: loadedRouter.state.location.pathname, + search: loadedRouter.state.location.search, + }) + }) + + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ + postId: 'café', + pathname: '/posts/café', + search: { view: 'full' }, + }) + expect(input).toHaveBeenCalledTimes(1) + expect(input.mock.calls[0]?.[0].url.origin).toBe( + origin ?? 'https://example.com', + ) + }, +) + +test.each([ + { isServer: false, action: 'push' }, + { isServer: false, action: 'replace' }, + { isServer: true, action: 'push' }, + { isServer: true, action: 'replace' }, +] as const)( + 'loads refresh memory history after $action with isServer=$isServer by default', + async ({ isServer, action }) => { + const root = new BaseRootRoute() + const targetLoader = vi.fn(() => 'target') + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + isServer, + history, + routeTree: root.addChildren([ + new BaseRoute({ getParentRoute: () => root, path: '/' }), + new BaseRoute({ + getParentRoute: () => root, + path: '/target', + loader: targetLoader, + }), + ]), + }) + await router.load() + + history[action]('/target') + await router.load() + + expect(router.state.location.pathname).toBe('/target') + expect(targetLoader).toHaveBeenCalledTimes(1) + expect(router.state.matches.at(-1)?.loaderData).toBe('target') + }, +) + +test('server loads reuse a location prepared with updated router options', async () => { + const root = new BaseRootRoute() + const input = vi.fn(({ url }: { url: URL }) => { + url.pathname = url.pathname.replace('/public', '/target') + return url + }) + const router = createTestRouter({ + isServer: true, + basepath: '/old', + history: createMemoryHistory({ initialEntries: ['/old/'] }), + routeTree: root.addChildren([ + new BaseRoute({ getParentRoute: () => root, path: '/' }), + new BaseRoute({ + getParentRoute: () => root, + path: '/target', + loader: () => 'target', + }), + ]), + }) + router.update({ + history: createServerHistory('/app/public'), + basepath: '/app', + rewrite: { + input, + output: ({ url }) => { + url.pathname = url.pathname.replace('/target', '/public') + return url + }, + }, + }) + input.mockClear() + + await router.load({ _skipLocationUpdate: true }) + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.location.publicHref).toBe('/app/public') + expect(router.state.matches.at(-1)?.loaderData).toBe('target') + expect(input).not.toHaveBeenCalled() +}) + +test.each([false, true])( + 'router navigation respects isServer=%s with memory history', + async (isServer) => { + const root = new BaseRootRoute() + const targetLoader = vi.fn(() => 'target') + const router = createTestRouter({ + isServer, + history: createMemoryHistory({ initialEntries: ['/'] }), + routeTree: root.addChildren([ + new BaseRoute({ getParentRoute: () => root, path: '/' }), + new BaseRoute({ + getParentRoute: () => root, + path: '/target', + loader: targetLoader, + }), + ]), + }) + await router.load() + const load = vi.spyOn(router, 'load') + + await router.navigate({ to: '/target' }) + expect(router.history.length).toBe(isServer ? 1 : 2) + expect(router.state.location.pathname).toBe(isServer ? '/' : '/target') + await router.navigate({ to: '/', replace: true }) + expect(router.history.length).toBe(isServer ? 1 : 2) + expect(router.history.location.pathname).toBe('/') + expect(targetLoader).toHaveBeenCalledTimes(isServer ? 0 : 1) + expect(load).toHaveBeenCalledTimes(isServer ? 0 : 2) + }, +) + +test('server navigation entry points resolve without building or loading', async () => { + const router = createTestRouter({ + isServer: true, + history: createServerHistory('/'), + routeTree: new BaseRootRoute(), + }) + const location = router.buildLocation({ to: '/' }) + const build = vi.spyOn(router, 'buildLocation') + const load = vi.spyOn(router, 'load') + await router.navigate({ to: '/' }) + await router.navigate({ href: 'https://example.com', reloadDocument: true }) + await router.navigate({ to: '/', reloadDocument: true, replace: true }) + await router.buildAndCommitLocation({ to: '/' }) + await router.commitLocation(location) + + expect(build).not.toHaveBeenCalled() + expect(load).not.toHaveBeenCalled() + expect(router._pendingLocation).toBeUndefined() + expect(router._commitPromise).toBeUndefined() +}) + +test.each(['beforeLoad', 'loader'] as const)( + 'navigation during %s leaves the request load intact', + async (hook) => { + const targetLoader = vi.fn() + const root = new BaseRootRoute() + const router = createTestRouter({ + isServer: true, + routeTree: root.addChildren([ + new BaseRoute({ + getParentRoute: () => root, + path: '/', + [hook]: async ({ + navigate, + }: { + navigate: (opts: { to: string }) => Promise + }) => { + await navigate({ to: '/target' }) + return { value: 'request data' } + }, + }), + new BaseRoute({ + getParentRoute: () => root, + path: '/target', + loader: targetLoader, + }), + ]), + }) + const load = vi.spyOn(router, 'load') + const response = await loadServerResponse(router, '/') + + expect(response.status).toBe(200) + expect(load).toHaveBeenCalledTimes(1) + expect(targetLoader).not.toHaveBeenCalled() + expect(router.state.location.pathname).toBe('/') + expect(router.history.location.pathname).toBe('/') + expect(router.state.matches.at(-1)?.status).toBe('success') + router.history.push('/target') + expect(router.history.location.pathname).toBe('/') + }, +) + +test('server redirects still produce HTTP redirect responses', async () => { + const router = createTestRouter({ + isServer: true, + routeTree: new BaseRootRoute({ + beforeLoad: () => { + throw redirect({ href: '/login', statusCode: 307 }) + }, + }), + }) + const response = await loadServerResponse(router, '/') + expect(response.status).toBe(307) + expect(response.headers.get('Location')).toBe('/login') + expect(router.history.location.pathname).toBe('/') +}) diff --git a/packages/router-core/tests/server-loader-abort-error.test.ts b/packages/router-core/tests/server-loader-abort-error.test.ts new file mode 100644 index 0000000000..e3b5d3c3ef --- /dev/null +++ b/packages/router-core/tests/server-loader-abort-error.test.ts @@ -0,0 +1,390 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + redirect, +} from '../src' +import { createRequestHandler } from '../src/ssr/server' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +describe('loader user-thrown abort values', () => { + test.each([ + { + isServer: false, + thrownType: 'AbortSignal', + createThrownValue: (signal: AbortSignal) => signal, + }, + { + isServer: false, + thrownType: 'AbortError', + createThrownValue: () => + new DOMException('The operation was aborted.', 'AbortError'), + }, + { + isServer: true, + thrownType: 'AbortError', + createThrownValue: () => + Object.assign(new Error('The operation was aborted.'), { + name: 'AbortError', + }), + }, + ])( + 'treats a user-thrown $thrownType as an ordinary route error (isServer=$isServer)', + async ({ isServer, createThrownValue }) => { + let matchSignal: AbortSignal | undefined + let thrownValue: unknown + const rootRoute = new BaseRootRoute({}) + const abortingRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/aborting', + loader: ({ abortController }) => { + matchSignal = abortController.signal + thrownValue = createThrownValue(matchSignal) + throw thrownValue + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([abortingRoute]), + history: createMemoryHistory({ initialEntries: ['/aborting'] }), + isServer, + }) + + if (isServer) { + const response = await loadServerResponse(router, '/aborting') + expect(response.status).toBe(500) + } else { + await router.load() + } + + const match = router.state.matches.find( + (item) => item.routeId === abortingRoute.id, + ) + // A server match remains ordinary route failure during reduction. Its + // controller is left alone: the payload finished, so nothing is pending. + expect(matchSignal?.aborted).toBe(false) + expect(match?.status).toBe('error') + expect(match?.error).toBe(thrownValue) + }, + ) + + test('request cancellation reaches the controller shared by route hooks', async () => { + const loaderStarted = createControlledPromise() + const controllers: Array = [] + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/work', + context: ({ abortController }) => { + controllers.push(abortController) + }, + beforeLoad: ({ abortController }) => { + controllers.push(abortController) + }, + loader: ({ abortController }) => { + controllers.push(abortController) + loaderStarted.resolve() + return new Promise((_, reject) => { + abortController.signal.addEventListener( + 'abort', + () => reject(abortController.signal.reason), + { once: true }, + ) + }) + }, + onError, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/work'] }), + isServer: true, + }) + const requestController = new AbortController() + const render = vi.fn(() => new Response('must not render')) + const handler = createRequestHandler({ + createRouter: () => router, + request: new Request('http://localhost/work', { + signal: requestController.signal, + }), + }) + const response = handler(render) + await loaderStarted + + const cancellation = new Error('request disconnected') + requestController.abort(cancellation) + + await expect(response).rejects.toBe(cancellation) + expect(controllers).toHaveLength(3) + expect( + controllers.every((controller) => controller === controllers[0]), + ).toBe(true) + expect(controllers[0]?.signal.aborted).toBe(true) + expect(controllers[0]?.signal.reason).toBe(cancellation) + expect(onError).not.toHaveBeenCalled() + expect(render).not.toHaveBeenCalled() + }) + + test('response cleanup aborts deferred loader data with a shared AbortError reason', async () => { + const deferred = createControlledPromise() + let loaderSignal: AbortSignal | undefined + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/work', + loader: ({ abortController }) => { + loaderSignal = abortController.signal + return { deferred } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/work'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/work') + + expect(response.status).toBe(200) + expect(loaderSignal?.aborted).toBe(true) + const firstReason = loaderSignal?.reason + expect(firstReason).toMatchObject({ + name: 'AbortError', + message: expect.stringContaining('settled'), + }) + expect(firstReason).not.toBeInstanceOf(DOMException) + + const nextDeferred = createControlledPromise() + const nextRootRoute = new BaseRootRoute({}) + const nextRouter = createTestRouter({ + routeTree: nextRootRoute.addChildren([ + new BaseRoute({ + getParentRoute: () => nextRootRoute, + path: '/next', + loader: ({ abortController }) => { + loaderSignal = abortController.signal + return { deferred: nextDeferred } + }, + }), + ]), + history: createMemoryHistory({ initialEntries: ['/next'] }), + isServer: true, + }) + + const nextResponse = await loadServerResponse(nextRouter, '/next') + + expect(nextResponse.status).toBe(200) + expect(loaderSignal?.reason).toBe(firstReason) + deferred.resolve('late data') + nextDeferred.resolve('late data') + }) + + test('redirect aborts match controllers with an AbortError-shaped reason', async () => { + let loaderSignal: AbortSignal | undefined + const rootRoute = new BaseRootRoute() + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: ({ abortController }) => { + loaderSignal = abortController.signal + return redirect({ + href: 'https://other.example/ignored', + headers: { Location: '/target' }, + }) + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute]), + isServer: true, + }) + + const response = await loadServerResponse(router, '/source') + + expect(response.status).toBe(307) + expect(loaderSignal?.aborted).toBe(true) + expect(loaderSignal?.reason).toMatchObject({ + name: 'AbortError', + message: expect.stringContaining('redirect'), + }) + expect(loaderSignal?.reason).not.toHaveProperty('matches') + }) + + test('request cancellation thrown from route context does not call onError', async () => { + const cancellation = new Error('request disconnected in context') + const requestController = new AbortController() + const beforeLoad = vi.fn() + const loader = vi.fn() + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/work', + context: ({ abortController }) => { + requestController.abort(cancellation) + abortController.signal.throwIfAborted() + }, + beforeLoad, + loader, + onError, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/work'] }), + isServer: true, + }) + const render = vi.fn(() => new Response('must not render')) + const handler = createRequestHandler({ + createRouter: () => router, + request: new Request('http://localhost/work', { + signal: requestController.signal, + }), + }) + + await expect(handler(render)).rejects.toBe(cancellation) + + expect(onError).not.toHaveBeenCalled() + expect(beforeLoad).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + expect(render).not.toHaveBeenCalled() + }) + + test('request cancellation during beforeLoad does not start loaders', async () => { + const beforeLoadStarted = createControlledPromise() + const loader = vi.fn() + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/work', + beforeLoad: ({ abortController }) => { + beforeLoadStarted.resolve() + return new Promise((resolve) => { + abortController.signal.addEventListener('abort', () => resolve(), { + once: true, + }) + }) + }, + loader, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/work'] }), + isServer: true, + }) + const requestController = new AbortController() + const handler = createRequestHandler({ + createRouter: () => router, + request: new Request('http://localhost/work', { + signal: requestController.signal, + }), + }) + const response = handler(() => new Response('must not render')) + await beforeLoadStarted + + const cancellation = new Error('request disconnected') + requestController.abort(cancellation) + + await expect(response).rejects.toBe(cancellation) + expect(loader).not.toHaveBeenCalled() + }) + + test('request cancellation does not wait for manifest lookup', async () => { + const manifestStarted = createControlledPromise() + const manifest = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const loader = vi.fn() + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/work', + loader, + }) + const createRouter = vi.fn(() => + createTestRouter({ + routeTree: rootRoute.addChildren([route]), + history: createMemoryHistory({ initialEntries: ['/work'] }), + isServer: true, + }), + ) + const requestController = new AbortController() + const render = vi.fn(() => new Response('must not render')) + const handler = createRequestHandler({ + createRouter, + request: new Request('http://localhost/work', { + signal: requestController.signal, + }), + getRouterManifest: () => { + manifestStarted.resolve() + return manifest + }, + }) + + const response = handler(render) + await manifestStarted + const cancellation = new Error('request disconnected') + requestController.abort(cancellation) + + await expect(response).rejects.toBe(cancellation) + expect(createRouter).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + expect(render).not.toHaveBeenCalled() + }) + + test('request cancellation wins after manifest lookup resolves', async () => { + const rootRoute = new BaseRootRoute({}) + const createRouter = vi.fn(() => + createTestRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }), + ) + const requestController = new AbortController() + const render = vi.fn(() => new Response('must not render')) + const handler = createRequestHandler({ + createRouter, + request: new Request('http://localhost/', { + signal: requestController.signal, + }), + getRouterManifest: () => Promise.resolve({ routes: {} }), + }) + + const response = handler(render) + const cancellation = new Error('request disconnected') + queueMicrotask(() => requestController.abort(cancellation)) + + await expect(response).rejects.toBe(cancellation) + expect(createRouter).not.toHaveBeenCalled() + expect(render).not.toHaveBeenCalled() + }) + + test('request cancellation does not wait for custom dehydration', async () => { + const dehydrateStarted = createControlledPromise() + const dehydrate = createControlledPromise() + const rootRoute = new BaseRootRoute({}) + const router = createTestRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + dehydrate: () => { + dehydrateStarted.resolve() + return dehydrate + }, + }) + const requestController = new AbortController() + const render = vi.fn(() => new Response('must not render')) + const handler = createRequestHandler({ + createRouter: () => router, + request: new Request('http://localhost/', { + signal: requestController.signal, + }), + }) + + const response = handler(render) + await dehydrateStarted + const cancellation = new Error('request disconnected') + requestController.abort(cancellation) + + await expect(response).rejects.toBe(cancellation) + expect(render).not.toHaveBeenCalled() + }) +}) diff --git a/packages/router-core/tests/server-planning-redirect.test.ts b/packages/router-core/tests/server-planning-redirect.test.ts new file mode 100644 index 0000000000..95a3a50317 --- /dev/null +++ b/packages/router-core/tests/server-planning-redirect.test.ts @@ -0,0 +1,79 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, redirect } from '../src' +import { createRequestHandler } from '../src/ssr/server' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +test.each([false, true])( + 'a route-context planning redirect is control with isServer=%s', + async (isServer) => { + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + context: () => { + throw redirect({ to: '/target' }) + }, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + isServer, + }) + + if (isServer) { + const response = await loadServerResponse(router, '/source') + + expect(response.status).toBe(307) + expect(response.headers.get('Location')).toBe('/target') + } else { + await router.load() + + expect(router.state.location.pathname).toBe('/target') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: targetRoute.id, + status: 'success', + }) + } + }, +) + +test('the generic request handler returns a redirect without rendering', async () => { + const rootRoute = new BaseRootRoute({}) + const sourceRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/source', + loader: () => + redirect({ + to: '/target', + statusCode: 308, + headers: { 'x-redirect': 'route' }, + }), + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([sourceRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + isServer: true, + }) + const render = vi.fn(() => new Response('must not render')) + const handler = createRequestHandler({ + createRouter: () => router, + request: new Request('http://localhost/source'), + }) + + const response = await handler(render) + + expect(response.status).toBe(308) + expect(response.headers.get('Location')).toBe('/target') + expect(response.headers.get('x-redirect')).toBe('route') + expect(await response.text()).toBe('') + expect(render).not.toHaveBeenCalled() +}) diff --git a/packages/router-core/tests/server-route-lifecycle.test.ts b/packages/router-core/tests/server-route-lifecycle.test.ts new file mode 100644 index 0000000000..7c90f87b60 --- /dev/null +++ b/packages/router-core/tests/server-route-lifecycle.test.ts @@ -0,0 +1,76 @@ +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +test('server route lifecycle callbacks run after loaded matches are published', async () => { + const events: Array = [] + const onEnter = vi.fn((match) => { + events.push(`enter:${match.routeId}:${match.loaderData}`) + }) + const onStay = vi.fn((match) => { + events.push(`stay:${match.routeId}:${match.search.step}`) + }) + const onLeave = vi.fn((match) => { + events.push(`leave:${match.routeId}`) + }) + const barEnter = vi.fn((match) => { + events.push(`enter:${match.routeId}`) + }) + + const rootRoute = new BaseRootRoute({}) + const fooRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/foo', + beforeLoad: () => { + events.push('beforeLoad:/foo') + return { ready: true } + }, + loader: ({ context }) => { + events.push(`loader:/foo:${context.ready}`) + return 'foo data' + }, + onEnter, + onStay, + onLeave, + }) + const barRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/bar', + onEnter: barEnter, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([fooRoute, barRoute]), + history: createMemoryHistory(), + isServer: true, + }) + + expect((await loadServerResponse(router, '/foo?step=one')).status).toBe(200) + expect(events).toEqual([ + 'beforeLoad:/foo', + 'loader:/foo:true', + `enter:${fooRoute.id}:foo data`, + ]) + expect(onEnter).toHaveBeenCalledWith( + expect.objectContaining({ + routeId: fooRoute.id, + status: 'success', + loaderData: 'foo data', + context: expect.objectContaining({ ready: true }), + }), + ) + + events.length = 0 + expect((await loadServerResponse(router, '/foo?step=two')).status).toBe(200) + expect(events).toEqual([ + 'beforeLoad:/foo', + 'loader:/foo:true', + `stay:${fooRoute.id}:two`, + ]) + + events.length = 0 + expect((await loadServerResponse(router, '/bar')).status).toBe(200) + expect(events).toEqual([`leave:${fooRoute.id}`, `enter:${barRoute.id}`]) + expect(onLeave).toHaveBeenCalledTimes(1) + expect(barEnter).toHaveBeenCalledTimes(1) +}) diff --git a/packages/router-core/tests/server-serial-ssr-notfound.test.ts b/packages/router-core/tests/server-serial-ssr-notfound.test.ts new file mode 100644 index 0000000000..6f8c92b6ca --- /dev/null +++ b/packages/router-core/tests/server-serial-ssr-notfound.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, notFound } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +/** + * A notFound thrown from a route's ssr() option happens during the serial + * phase, before beforeLoad has run for that route and its descendants. It + * must cap the loader prefix like a beforeLoad notFound: the throwing route + * and its descendants must not run their loaders (their context is + * incomplete and their ssr status unresolved), and the response must be a + * 404 — a descendant loader failure must not be able to turn the outcome + * into a 200/500. + */ + +function setupRouter() { + const loaderCalls: Array = [] + + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + notFoundComponent: () => null, + ssr: () => { + throw notFound() + }, + loader: () => { + loaderCalls.push('parent') + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loader: () => { + loaderCalls.push('child') + throw new Error('child loader failed') + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + + return { router, rootRoute, parentRoute, childRoute, loaderCalls } +} + +describe('server serial ssr() notFound', () => { + test('caps the loader prefix at the boundary and sets 404', async () => { + const { router, rootRoute, parentRoute, childRoute, loaderCalls } = + setupRouter() + + const response = await loadServerResponse(router, '/parent/child') + + const parentMatch = router.state.matches.find( + (item) => item.routeId === parentRoute.id, + ) + expect(loaderCalls).toEqual([]) + expect(response.status).toBe(404) + expect(parentMatch?.status).toBe('notFound') + expect(parentMatch?.error).toEqual( + expect.objectContaining({ isNotFound: true }), + ) + expect(router.state.matches.map((match) => match.routeId)).toEqual([ + rootRoute.id, + parentRoute.id, + childRoute.id, + ]) + expect(router.state.matches[1]?.status).toBe('notFound') + }) +}) diff --git a/packages/router-core/tests/server-ssr-false-assets.test.ts b/packages/router-core/tests/server-ssr-false-assets.test.ts new file mode 100644 index 0000000000..5ee27fa232 --- /dev/null +++ b/packages/router-core/tests/server-ssr-false-assets.test.ts @@ -0,0 +1,192 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +/** + * The first `ssr: false` route contributes the assets needed for its server + * shell. Descendants inherit the client-only restriction and do not execute + * their route asset callbacks, even if they request `ssr: true` themselves. + */ +describe('server assets for ssr:false routes', () => { + test('executes assets at the client-only boundary but not below it', async () => { + const rootHead = vi.fn(() => ({ meta: [{ title: 'server root' }] })) + const rootScripts = vi.fn(() => [ + { + children: 'window.rootAssetRan = true', + }, + ]) + const rootHeaders = vi.fn(() => ({ + 'x-server-root': 'projected', + })) + const parentHead = vi.fn(() => ({ + meta: [{ title: 'client-only parent' }], + })) + const parentScripts = vi.fn(() => [ + { + children: 'window.parentAssetRan = true', + }, + ]) + const parentHeaders = vi.fn(() => ({ + 'x-client-only-parent': 'projected', + })) + const parentBeforeLoad = vi.fn(() => ({})) + const parentLoader = vi.fn(() => 'unexpected') + const childHead = vi.fn(() => ({ + meta: [{ title: 'client-only child' }], + })) + const childScripts = vi.fn(() => [ + { + children: 'window.childAssetRan = true', + }, + ]) + const childHeaders = vi.fn(() => ({ + 'x-client-only-child': 'unexpected', + })) + + const rootRoute = new BaseRootRoute({ + head: rootHead, + scripts: rootScripts, + headers: rootHeaders, + }) + const clientOnlyRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/client-only', + ssr: false, + beforeLoad: parentBeforeLoad, + loader: parentLoader, + head: parentHead, + scripts: parentScripts, + headers: parentHeaders, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => clientOnlyRoute, + path: '/child', + // A child cannot relax its parent's client-only restriction. + ssr: true, + head: childHead, + scripts: childScripts, + headers: childHeaders, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + clientOnlyRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ + initialEntries: ['/client-only/child'], + }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/client-only/child') + + expect(response.status).toBe(200) + expect(rootHead).toHaveBeenCalledTimes(1) + expect(rootScripts).toHaveBeenCalledTimes(1) + expect(rootHeaders).toHaveBeenCalledTimes(1) + expect(response.headers.get('x-server-root')).toBe('projected') + expect(parentHead).toHaveBeenCalledTimes(1) + expect(parentScripts).toHaveBeenCalledTimes(1) + expect(parentHeaders).toHaveBeenCalledTimes(1) + expect(parentBeforeLoad).not.toHaveBeenCalled() + expect(parentLoader).not.toHaveBeenCalled() + expect(response.headers.get('x-client-only-parent')).toBe('projected') + expect( + router.state.matches.find( + (match) => match.routeId === clientOnlyRoute.id, + ), + ).toMatchObject({ + meta: [{ title: 'client-only parent' }], + scripts: [{ children: 'window.parentAssetRan = true' }], + headers: { 'x-client-only-parent': 'projected' }, + }) + expect(childHead).not.toHaveBeenCalled() + expect(childScripts).not.toHaveBeenCalled() + expect(childHeaders).not.toHaveBeenCalled() + expect(response.headers.get('x-client-only-child')).toBeNull() + }) + + test('executes assets when the root route is client-only', async () => { + const rootHead = vi.fn(() => ({ meta: [{ title: 'root shell' }] })) + const rootScripts = vi.fn(() => [ + { children: 'window.rootShellRan = true' }, + ]) + const rootHeaders = vi.fn(() => ({ 'x-root-shell': 'projected' })) + const childHead = vi.fn(() => ({ meta: [{ title: 'child' }] })) + const childScripts = vi.fn(() => [{ children: 'window.childRan = true' }]) + const childHeaders = vi.fn(() => ({ 'x-child': 'unexpected' })) + const rootRoute = new BaseRootRoute({ + ssr: false, + head: rootHead, + scripts: rootScripts, + headers: rootHeaders, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/child', + ssr: true, + head: childHead, + scripts: childScripts, + headers: childHeaders, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/child'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/child') + + expect(response.status).toBe(200) + expect(rootHead).toHaveBeenCalledTimes(1) + expect(rootScripts).toHaveBeenCalledTimes(1) + expect(rootHeaders).toHaveBeenCalledTimes(1) + expect(response.headers.get('x-root-shell')).toBe('projected') + expect(childHead).not.toHaveBeenCalled() + expect(childScripts).not.toHaveBeenCalled() + expect(childHeaders).not.toHaveBeenCalled() + expect(response.headers.get('x-child')).toBeNull() + }) + + test('projects assets for a data-only branch', async () => { + const head = vi.fn(({ loaderData }) => ({ + meta: [{ title: `report: ${loaderData}` }], + })) + const scripts = vi.fn(({ loaderData }) => [ + { children: `window.report = ${JSON.stringify(loaderData)}` }, + ]) + const headers = vi.fn(({ loaderData }) => ({ + 'x-report': String(loaderData), + })) + const rootRoute = new BaseRootRoute({}) + const reportRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/report', + ssr: 'data-only', + loader: () => 'server data', + head, + scripts, + headers, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([reportRoute]), + history: createMemoryHistory({ initialEntries: ['/report'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/report') + const match = router.state.matches.at(-1) + + expect(response.status).toBe(200) + expect(response.headers.get('x-report')).toBe('server data') + expect(match).toMatchObject({ + ssr: 'data-only', + meta: [{ title: 'report: server data' }], + scripts: [{ children: 'window.report = "server data"' }], + headers: { 'x-report': 'server data' }, + }) + expect(head).toHaveBeenCalledTimes(1) + expect(scripts).toHaveBeenCalledTimes(1) + expect(headers).toHaveBeenCalledTimes(1) + }) +}) diff --git a/packages/router-core/tests/server-ssr-option-error.test.ts b/packages/router-core/tests/server-ssr-option-error.test.ts new file mode 100644 index 0000000000..f1dcf64e14 --- /dev/null +++ b/packages/router-core/tests/server-ssr-option-error.test.ts @@ -0,0 +1,178 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, redirect } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +/** + * A functional ssr() option is user route code in the server serial phase. + * If it throws an ordinary error, the route must not be committed as a + * successful 200 response with missing loader data. It follows the same + * renderable route-error lifecycle as beforeLoad and loader failures. + */ +describe('server functional ssr() errors', () => { + test.each(['sync', 'async'] as const)( + 'commits a %s failure with route context and returns 500', + async (failureMode) => { + const boom = new Error('feature flag lookup failed') + const loader = vi.fn(() => 'reports data') + const onError = vi.fn() + const beforeLoad = vi.fn() + + const rootRoute = new BaseRootRoute({ + context: () => ({ rootContext: true }), + beforeLoad: () => ({ rootBeforeLoadContext: true }), + }) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + context: ({ context }) => ({ + reportsContext: context.rootBeforeLoadContext, + }), + ssr: () => { + if (failureMode === 'sync') { + throw boom + } + return Promise.reject(boom) + }, + beforeLoad, + loader, + onError, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([reportsRoute]), + history: createMemoryHistory({ initialEntries: ['/reports'] }), + isServer: true, + context: { routerContext: true }, + }) + + const response = await loadServerResponse(router, '/reports') + + const reportsMatch = router.state.matches.find( + (match) => match.routeId === reportsRoute.id, + ) + expect(loader).not.toHaveBeenCalled() + expect(beforeLoad).not.toHaveBeenCalled() + expect(response.status).toBe(500) + expect(onError).toHaveBeenCalledTimes(1) + expect(onError).toHaveBeenCalledWith(boom) + expect(reportsMatch).toMatchObject({ + status: 'error', + error: boom, + context: { + routerContext: true, + rootContext: true, + rootBeforeLoadContext: true, + reportsContext: true, + }, + }) + }, + ) + + test('retains inherited renderability and loads the lazy error boundary', async () => { + const boom = new Error('SSR policy failed') + const errorBoundaryPreload = vi.fn(() => Promise.resolve()) + const ErrorBoundary = Object.assign(() => null, { + preload: errorBoundaryPreload, + }) + const rootRoute = new BaseRootRoute({}) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + ssr: async () => { + await Promise.resolve() + throw boom + }, + }) + const lazy = vi.fn(() => + Promise.resolve({ + options: { + id: reportsRoute.id, + errorComponent: ErrorBoundary, + }, + }), + ) + reportsRoute.lazy(lazy as any) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([reportsRoute]), + history: createMemoryHistory({ initialEntries: ['/reports'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/reports') + + expect(response.status).toBe(500) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: reportsRoute.id, + status: 'error', + error: boom, + ssr: true, + }) + expect(lazy).toHaveBeenCalledTimes(1) + expect(errorBoundaryPreload).toHaveBeenCalledTimes(1) + }) + + test('does not run route context after an SSR policy redirect', async () => { + const context = vi.fn(() => ({ reportsContext: true })) + const loader = vi.fn(() => 'reports data') + const rootRoute = new BaseRootRoute({}) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + ssr: () => { + throw redirect({ to: '/target' }) + }, + context, + loader, + }) + const targetRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/target', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([reportsRoute, targetRoute]), + history: createMemoryHistory({ initialEntries: ['/reports'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/reports') + + expect(response.status).toBe(307) + expect(response.headers.get('Location')).toBe('/target') + expect(context).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + }) + + test('preserves the SSR policy failure when route context also throws', async () => { + const policyError = new Error('SSR policy failed') + const contextError = new Error('route context failed') + const onError = vi.fn() + const rootRoute = new BaseRootRoute({}) + const reportsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/reports', + ssr: () => { + throw policyError + }, + context: () => { + throw contextError + }, + onError, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([reportsRoute]), + history: createMemoryHistory({ initialEntries: ['/reports'] }), + isServer: true, + }) + + const response = await loadServerResponse(router, '/reports') + + expect(response.status).toBe(500) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: reportsRoute.id, + status: 'error', + error: policyError, + }) + expect(onError).toHaveBeenCalledWith(policyError) + expect(onError).not.toHaveBeenCalledWith(contextError) + }) +}) diff --git a/packages/router-core/tests/server-static-ssr.test.ts b/packages/router-core/tests/server-static-ssr.test.ts new file mode 100644 index 0000000000..21c1b8775a --- /dev/null +++ b/packages/router-core/tests/server-static-ssr.test.ts @@ -0,0 +1,97 @@ +import { runInNewContext } from 'node:vm' +import { expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +test.each(['false', 'data-only', 'default'] as const)( + 'inherits %s SSR through static and functional children', + async (policy) => { + for (const mode of [ + 'undefined', + 'true', + 'sync', + 'promise', + 'foreign', + 'thenable', + ]) { + const loader = vi.fn() + const root = new BaseRootRoute({ + ssr: + policy === 'default' + ? undefined + : policy === 'false' + ? false + : 'data-only', + }) + const child = new BaseRoute({ + getParentRoute: () => root, + path: '/', + ssr: + mode === 'undefined' + ? undefined + : mode === 'true' + ? true + : () => { + if (mode === 'foreign') { + return runInNewContext('Promise.resolve(true)') + } + if (mode === 'thenable') { + return { then: (resolve: any) => resolve(true) } as any + } + return mode === 'sync' ? true : Promise.resolve(true) + }, + loader, + }) + const router = createTestRouter({ + routeTree: root.addChildren([child]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + router.options.defaultSsr = policy === 'default' ? 'data-only' : true + expect((await loadServerResponse(router, '/')).status).toBe(200) + expect(router.state.matches.map((match) => match.ssr)).toEqual( + policy === 'false' ? [false, false] : ['data-only', 'data-only'], + ) + expect(loader).toHaveBeenCalledTimes(policy === 'false' ? 0 : 1) + } + }, +) + +test.each(['return', 'throw', 'microtask throw'] as const)( + 'request cancellation wins when an SSR callback aborts then %ss', + async (mode) => { + const controller = new AbortController() + const cancellation = new Error('disconnected') + const context = vi.fn() + const loader = vi.fn() + const onError = vi.fn() + const root = new BaseRootRoute({ + ssr: () => { + if (mode === 'microtask throw') { + queueMicrotask(() => controller.abort(cancellation)) + } else { + controller.abort(cancellation) + } + if (mode !== 'return') { + throw new Error('obsolete policy error') + } + return true + }, + context, + loader, + onError, + }) + const router = createTestRouter({ + routeTree: root, + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + await expect( + loadServerResponse(router, '/', controller.signal), + ).rejects.toBe(cancellation) + expect(context).not.toHaveBeenCalled() + expect(loader).not.toHaveBeenCalled() + expect(onError).not.toHaveBeenCalled() + }, +) diff --git a/packages/router-core/tests/server-url-encoding.test.ts b/packages/router-core/tests/server-url-encoding.test.ts new file mode 100644 index 0000000000..7ba4dbbba0 --- /dev/null +++ b/packages/router-core/tests/server-url-encoding.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, test } from 'vitest' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter, loadServerResponse } from './routerTestUtils' + +const asciiControls = [...Array.from({ length: 32 }, (_, code) => code), 127] +const staticPaths = ['/', '/admin', '/profile'] as const +const parameterCases = [ + '{{app_name}}', + '', + '"quoted"', + "apostrophe's", + 'back`tick', + 'file name', + 'a\\b', + 'a%b', + '대한민국', + '😀', + ...asciiControls.map((code) => `a${String.fromCharCode(code)}b`), +].map((value) => ({ value, path: `/params/${encodeURIComponent(value)}` })) +const encodedControls = [ + ...asciiControls.map( + (code) => `%${code.toString(16).padStart(2, '0').toUpperCase()}`, + ), + '%0D%0A', +] + +describe.each([false, true])('SSR URL encoding (rewrite: %s)', (rewrite) => { + function setupRouter() { + const loaderCalls: Array = [] + const rootRoute = new BaseRootRoute() + const staticRoutes = staticPaths.map( + (path) => + new BaseRoute({ + getParentRoute: () => rootRoute, + path, + loader: () => { + loaderCalls.push(path) + return path + }, + }), + ) + const paramRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/params/$value', + loader: ({ params }) => params.value, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([...staticRoutes, paramRoute]), + isServer: true, + rewrite: rewrite + ? { input: ({ url }) => url, output: ({ url }) => url } + : undefined, + }) + return { router, paramRoute, loaderCalls } + } + + test.each(parameterCases)( + 'serves and rebuilds $path without redirecting', + async ({ value, path }) => { + const { router, paramRoute } = setupRouter() + + const response = await loadServerResponse(router, path) + + expect(response.status).toBe(200) + expect(response.headers.get('Location')).toBeNull() + const match = router.state.matches.find( + (item) => item.routeId === paramRoute.id, + ) + expect(match?.params).toEqual({ value }) + expect(match?.loaderData).toBe(value) + expect( + router.buildLocation({ to: '/params/$value', params: { value } }) + .publicHref, + ).toBe(path) + }, + ) + + test.each(staticPaths)('loads the ordinary route %s', async (path) => { + const { router, loaderCalls } = setupRouter() + + const response = await loadServerResponse(router, path) + + expect(response.status).toBe(200) + expect(response.headers.get('Location')).toBeNull() + expect(loaderCalls).toEqual([path]) + }) + + test.each(encodedControls)( + 'preserves %s when resolving routes and canonicalizing trailing slashes', + async (encoded) => { + for (const variant of new Set([encoded, encoded.toLowerCase()])) { + for (const path of [ + `/${variant}admin`, + `/assets/..${variant}/profile`, + `/assets/..${variant}/`, + ]) { + const normalizedPath = path.replace(variant, encoded) + const { router, loaderCalls } = setupRouter() + + const response = await loadServerResponse(router, path) + + expect(loaderCalls, path).toEqual([]) + expect(router.state.location.pathname, path).toBe(normalizedPath) + if (path.endsWith('/')) { + const destination = normalizedPath.slice(0, -1) + expect(response.status, path).toBe(307) + expect(response.headers.get('Location'), path).toBe(destination) + + // Removing the trailing slash must preserve the encoded segment + // and end at a 404, rather than redirecting again or loading '/'. + const followUp = setupRouter() + const finalResponse = await loadServerResponse( + followUp.router, + destination, + ) + expect(finalResponse.status, path).toBe(404) + expect(finalResponse.headers.get('Location'), path).toBeNull() + expect(followUp.loaderCalls, path).toEqual([]) + expect(followUp.router.state.location.pathname, path).toBe( + destination, + ) + } else { + expect(response.status, path).toBe(404) + expect(response.headers.get('Location'), path).toBeNull() + } + } + } + }, + ) +}) diff --git a/packages/router-core/tests/sieve.test.ts b/packages/router-core/tests/sieve.test.ts new file mode 100644 index 0000000000..5987b056a8 --- /dev/null +++ b/packages/router-core/tests/sieve.test.ts @@ -0,0 +1,163 @@ +import { describe, expect, it } from 'vitest' +import { createSieveCache } from '../src/sieve-cache' + +describe('Sieve Cache', () => { + it('stores and reads back values', () => { + const cache = createSieveCache(3) + cache.set('a', 1) + cache.set('b', 2) + expect(cache.get('a')).toBe(1) + expect(cache.get('b')).toBe(2) + expect(cache.get('c')).toBeUndefined() + }) + + it('evicts the oldest unvisited entry', () => { + const cache = createSieveCache(3) + cache.set('a', 1) + cache.set('b', 2) + cache.set('c', 3) + cache.set('d', 4) // nothing was visited, 'a' is evicted + expect(cache.get('a')).toBeUndefined() + expect(cache.get('b')).toBe(2) + expect(cache.get('c')).toBe(3) + expect(cache.get('d')).toBe(4) + }) + + it('keeps visited entries for one more sweep', () => { + const cache = createSieveCache(3) + cache.set('a', 1) + cache.set('b', 2) + cache.set('c', 3) + cache.get('a') // 'a' is now visited + cache.set('d', 4) // hand clears 'a', evicts 'b' + expect(cache.get('b')).toBeUndefined() + expect(cache.get('a')).toBe(1) + expect(cache.get('c')).toBe(3) + expect(cache.get('d')).toBe(4) + }) + + it('drops a previously visited entry on the next sweep', () => { + const cache = createSieveCache(3) + cache.set('a', 1) + cache.set('b', 2) + cache.set('c', 3) + cache.get('a') + cache.get('a') + cache.set('d', 4) // 'a' visited bit cleared, 'b' evicted, hand at 'c' + cache.get('c') + cache.get('d') + cache.set('e', 5) // clears 'c' and 'd', wraps, then evicts unvisited 'a' + expect(cache.get('a')).toBeUndefined() + expect(cache.get('c')).toBe(3) + expect(cache.get('d')).toBe(4) + expect(cache.get('e')).toBe(5) + }) + + it('wraps the hand around to the oldest entry', () => { + const cache = createSieveCache(3) + cache.set('a', 1) + cache.set('b', 2) + cache.set('c', 3) + // everything is visited: the sweep clears every bit, wraps around, and + // evicts the oldest entry + cache.get('a') + cache.get('b') + cache.get('c') + cache.set('d', 4) + expect(cache.get('a')).toBeUndefined() + expect(cache.get('b')).toBe(2) + expect(cache.get('c')).toBe(3) + expect(cache.get('d')).toBe(4) + }) + + it('keeps evicting correctly once the hand reaches the newest entry', () => { + const cache = createSieveCache(3) + cache.set('a', 1) + cache.set('b', 2) + cache.set('c', 3) + cache.set('d', 4) // evicts 'a', hand -> 'b' + cache.set('e', 5) // evicts 'b', hand -> 'c' + cache.set('f', 6) // evicts 'c', hand -> 'd' + cache.set('g', 7) // evicts 'd', hand -> 'e' + expect(cache.get('d')).toBeUndefined() + expect(cache.get('e')).toBe(5) + expect(cache.get('f')).toBe(6) + expect(cache.get('g')).toBe(7) + }) + + it('wraps after evicting newest instead of visiting its replacement', () => { + const cache = createSieveCache(3) + cache.set('a', 1) + cache.set('b', 2) + cache.set('c', 3) + cache.get('a') + cache.get('b') + cache.set('d', 4) // clears 'a' and 'b', then evicts newest 'c' + cache.set('e', 5) // wraps and evicts oldest 'a', not replacement 'd' + expect(cache.get('a')).toBeUndefined() + expect(cache.get('b')).toBe(2) + expect(cache.get('c')).toBeUndefined() + expect(cache.get('d')).toBe(4) + expect(cache.get('e')).toBe(5) + }) + + it('works with a capacity of one', () => { + const cache = createSieveCache(1) + cache.set('a', 1) + cache.set('b', 2) + expect(cache.get('a')).toBeUndefined() + expect(cache.get('b')).toBe(2) + cache.set('c', 3) + expect(cache.get('b')).toBeUndefined() + expect(cache.get('c')).toBe(3) + }) + + it('overwrites an existing key without evicting', () => { + const cache = createSieveCache(3) + cache.set('a', 1) + cache.set('b', 2) + cache.set('c', 3) + cache.set('b', 20) + expect(cache.get('a')).toBe(1) + expect(cache.get('b')).toBe(20) + expect(cache.get('c')).toBe(3) + }) + + it('clears entries and resets an active hand', () => { + const cache = createSieveCache(3) + cache.set('a', 1) + cache.set('b', 2) + cache.set('c', 3) + cache.set('d', 4) + cache.clear() + expect(cache.get('a')).toBeUndefined() + expect(cache.get('b')).toBeUndefined() + expect(cache.get('c')).toBeUndefined() + expect(cache.get('d')).toBeUndefined() + // the cache is usable again, and the hand starts over + cache.set('e', 5) + cache.set('f', 6) + cache.set('g', 7) + cache.set('h', 8) + expect(cache.get('e')).toBeUndefined() + expect(cache.get('f')).toBe(6) + expect(cache.get('g')).toBe(7) + expect(cache.get('h')).toBe(8) + }) + + it('keeps only its capacity during insertion churn', () => { + const max = 8 + const cache = createSieveCache(max) + for (let i = 0; i < 500; i++) { + cache.set(i, i) + } + + const present: Array = [] + for (let i = 0; i < 500; i++) { + if (cache.get(i) !== undefined) { + present.push(i) + } + } + expect(present).toEqual([492, 493, 494, 495, 496, 497, 498, 499]) + }) +}) diff --git a/packages/router-core/tests/ssr-match-id.bench.ts b/packages/router-core/tests/ssr-match-id.bench.ts new file mode 100644 index 0000000000..33e0bb5945 --- /dev/null +++ b/packages/router-core/tests/ssr-match-id.bench.ts @@ -0,0 +1,38 @@ +import { describe, test } from 'vitest' +import { dehydrateSsrMatchId } from '../src/ssr/ssr-match-id' + +const typicalIds = Array.from( + { length: 100 }, + (_, index) => + `/$orgId/projects/$projectId/acme/projects/project-${index}{"page":${index}}`, +) +const deepIds = Array.from( + { length: 100 }, + (_, index) => + `${Array.from({ length: 32 }, (__, depth) => `/route-${depth}`).join('')}/${index}`, +) +let benchmarkSink = 0 + +describe('SSR match ID codec', () => { + test('encode 100 typical match IDs', async ({ bench }) => { + await bench('encode 100 typical match IDs', () => { + let size = 0 + for (const id of typicalIds) { + size += dehydrateSsrMatchId(id).length + } + benchmarkSink = size + }).run() + }) + + test('encode 100 deep match IDs', async ({ bench }) => { + await bench('encode 100 deep match IDs', () => { + let size = 0 + for (const id of deepIds) { + size += dehydrateSsrMatchId(id).length + } + benchmarkSink = size + }).run() + }) +}) + +void benchmarkSink diff --git a/packages/router-core/tests/ssr-match-id.test.ts b/packages/router-core/tests/ssr-match-id.test.ts new file mode 100644 index 0000000000..221b15c3e6 --- /dev/null +++ b/packages/router-core/tests/ssr-match-id.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' +import { dehydrateSsrMatchId } from '../src/ssr/ssr-match-id' + +describe('ssr match id codec', () => { + it('removes forward slashes in dehydrated ids', () => { + const dehydratedId = dehydrateSsrMatchId( + '/$orgId/projects/$projectId//acme/projects/dashboard/{}', + ) + + expect(dehydratedId).not.toContain('/') + expect(dehydratedId).not.toContain('\0') + }) + + it('leaves ids without slashes unchanged', () => { + expect(dehydrateSsrMatchId('plain-id')).toBe('plain-id') + }) + + it('keeps distinct slash-delimited ids distinct', () => { + expect(dehydrateSsrMatchId('/posts/1')).not.toBe( + dehydrateSsrMatchId('/posts1'), + ) + }) +}) diff --git a/packages/router-core/tests/ssr-server-cleanup.test.ts b/packages/router-core/tests/ssr-server-cleanup.test.ts new file mode 100644 index 0000000000..84e718812c --- /dev/null +++ b/packages/router-core/tests/ssr-server-cleanup.test.ts @@ -0,0 +1,1383 @@ +import { runInNewContext } from 'node:vm' +import { createMemoryHistory } from '@tanstack/history' +import { createStream } from 'seroval' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { BaseRootRoute, BaseRoute, RawStream } from '../src' +import { createRequestHandler } from '../src/ssr/createRequestHandler' +import { + bindSsrResponseToRequest, + createSsrStreamResponse, +} from '../src/ssr/handlerCallback' +import { + HYDRATION_SCRIPT_BOUNDARY_BYTES, + HydrationScriptOutputState, + createHydrationScripts, +} from '../src/ssr/hydrationScripts' +import { attachRouterServerSsrUtils } from '../src/ssr/ssr-server' +import { + transformHtmlStringWithRouter, + transformReadableStreamWithRouter, +} from '../src/ssr/transformStreamWithRouter' +import { createTestRouter } from './routerTestUtils' +import type { + HydrationScriptOutput, + InitialHydrationScriptTags, +} from '../src/ssr/hydrationScripts' + +type HydrationScripts = ReturnType +const HYDRATION_SCRIPT_BOUNDARY_SUFFIX = new TextDecoder().decode( + HYDRATION_SCRIPT_BOUNDARY_BYTES, +) +const HYDRATION_SCRIPT_BOUNDARY_SOURCE = + `document.currentScript.remove()` + + HYDRATION_SCRIPT_BOUNDARY_SUFFIX.slice(0, -''.length) + +/** + * CI-stable tests for the SSR cleanup contract. These do not rely on GC + * timing; they exercise the observable behavior: + * - onCleanup listeners run exactly once + * - cleanup is reentrancy-safe (listener calling cleanup again is a no-op) + * - cleanup is idempotent (second cleanup() call is a no-op) + */ + +function buildRouter(dehydratedData?: Record) { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => null, + }) + return createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + dehydrate: dehydratedData ? () => dehydratedData : undefined, + }) +} + +function deferred() { + let resolve!: (value: T) => void + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +afterEach(() => { + vi.restoreAllMocks() +}) + +function renderInitialScripts(scripts: InitialHydrationScriptTags) { + return [...scripts.before, scripts.boundary] + .map((script) => { + const id = script.attrs?.id ? ` id="${script.attrs.id}"` : '' + return `${script.children ?? ''}` + }) + .join('') +} + +async function waitFor(check: () => boolean) { + for (let index = 0; index < 20; index++) { + if (check()) { + return + } + await Promise.resolve() + } + throw new Error('condition was not reached') +} + +function drainHydrationOutput(output: HydrationScriptOutput) { + const decoder = new TextDecoder() + let text = '' + while ( + output.state === HydrationScriptOutputState.Ready || + output.state === HydrationScriptOutputState.Active + ) { + text += decoder.decode(output.pullChunk(), { stream: true }) + } + return text + decoder.decode() +} + +describe('serverSsr.cleanup', () => { + test('onCleanup listeners run exactly once', () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const serverSsr = router.serverSsr! + + let calls = 0 + serverSsr.onCleanup(() => { + calls++ + }) + + serverSsr.cleanup() + serverSsr.cleanup() + expect(calls).toBe(1) + expect(router.ssr).toBeUndefined() + expect(router.serverSsr).toBeUndefined() + }) + + test('listener that re-enters cleanup() does not re-fire siblings', () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + + const order: Array = [] + router.serverSsr!.onCleanup(() => { + order.push('a') + // Reentry: must be a no-op. + router.serverSsr?.cleanup() + }) + router.serverSsr!.onCleanup(() => { + order.push('b') + }) + + router.serverSsr!.cleanup() + expect(order).toEqual(['a', 'b']) + }) + + test('listener errors are swallowed and do not stop subsequent listeners', () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + + const order: Array = [] + router.serverSsr!.onCleanup(() => { + order.push('a') + throw new Error('boom') + }) + router.serverSsr!.onCleanup(() => { + order.push('b') + }) + + // Should not throw. + router.serverSsr!.cleanup() + expect(order).toEqual(['a', 'b']) + }) + + test('cleanup before pending serialization resolves drops late scripts safely', async () => { + const value = deferred() + const router = buildRouter({ value: value.promise }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + router.serverSsr!.cleanup() + + value.resolve('done') + await Promise.resolve() + await Promise.resolve() + + expect(router.serverSsr).toBeUndefined() + }) + + test('cleanup cancels and unlocks a pending RawStream reader', async () => { + const pullStarted = deferred() + let cancelCalls = 0 + const stream = new ReadableStream( + { + pull() { + pullStarted.resolve() + return new Promise(() => {}) + }, + cancel() { + cancelCalls++ + return new Promise(() => {}) + }, + }, + { highWaterMark: 0 }, + ) + const router = buildRouter({ value: new RawStream(stream) }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + const serverSsr = router.serverSsr! + await serverSsr.dehydrate() + await pullStarted.promise + expect(stream.locked).toBe(true) + + serverSsr.cleanup() + expect(cancelCalls).toBe(1) + expect(stream.locked).toBe(false) + + serverSsr.cleanup() + expect(cancelCalls).toBe(1) + expect(router.ssr).toBeUndefined() + expect(router.serverSsr).toBeUndefined() + }) + + test('hydration output notifies once before cleanup', async () => { + const value = deferred() + const router = buildRouter({ value: value.promise }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + await router.load() + const serverSsr = router.serverSsr! + await serverSsr.dehydrate() + serverSsr.takeInitialHydrationScriptTags() + const output = serverSsr.hydrationScripts.claimOutput() + let calls = 0 + output.subscribe(() => { + calls++ + }) + + serverSsr.hydrationScripts.liftBarrier() + value.resolve('done') + await waitFor(() => output.state === HydrationScriptOutputState.Ready) + expect(calls).toBe(1) + serverSsr.cleanup() + await Promise.resolve() + + expect(calls).toBe(1) + expect(output.state).toBe(HydrationScriptOutputState.Done) + expect(router.serverSsr).toBeUndefined() + }) + + test('cleanup stops work from late serialization values', async () => { + const value = deferred() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const router = buildRouter({ value: value.promise }) + + try { + attachRouterServerSsrUtils({ router, manifest: undefined }) + await router.load() + await router.serverSsr!.dehydrate() + router.serverSsr!.cleanup() + + value.resolve(() => {}) + await Promise.resolve() + await Promise.resolve() + + expect(errorSpy).not.toHaveBeenCalled() + } finally { + router.serverSsr?.cleanup() + errorSpy.mockRestore() + } + }) + + test('cleanup while custom dehydration waits does not start serialization', async () => { + const dehydratedData = deferred>() + const router = buildRouter() + router.options.dehydrate = () => dehydratedData.promise + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + const serverSsr = router.serverSsr! + const dehydration = serverSsr.dehydrate() + + serverSsr.cleanup() + dehydratedData.resolve({ late: 'ignored' }) + await dehydration + + expect(router.serverSsr).toBeUndefined() + }) + + test('request abort unwinds an argument-free custom dehydration hook', async () => { + const abortController = new AbortController() + const reason = new Error('request-aborted') + const dehydratedData = deferred>() + const router = buildRouter() + const dehydrate = vi.fn(() => dehydratedData.promise) + router.options.dehydrate = dehydrate + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + const dehydration = router.serverSsr!.dehydrate({ + signal: abortController.signal, + }) + expect(dehydrate).toHaveBeenCalledWith() + abortController.abort(reason) + + await expect(dehydration).rejects.toBe(reason) + router.serverSsr?.cleanup() + dehydratedData.resolve({ late: 'ignored' }) + }) + + test('request abort stops dehydration after an already-settled custom hook', async () => { + const abortController = new AbortController() + const reason = new Error('request-aborted') + const router = buildRouter() + router.options.dehydrate = () => Promise.resolve({ ready: true }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + const serverSsr = router.serverSsr! + const scripts = serverSsr.hydrationScripts as HydrationScripts + const pushSerializedSource = vi.spyOn(scripts, 'pushSerializedSource') + const dehydration = serverSsr.dehydrate({ + signal: abortController.signal, + }) + queueMicrotask(() => abortController.abort(reason)) + + await expect(dehydration).rejects.toBe(reason) + expect(pushSerializedSource).not.toHaveBeenCalled() + serverSsr.cleanup() + }) + + test('serialization completion does not clear render-finished listeners', async () => { + const value = deferred() + const router = buildRouter({ value: value.promise }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + + let renderFinishedCalls = 0 + router.serverSsr!.onRenderFinished(() => { + renderFinishedCalls++ + }) + + router.serverSsr!.takeInitialHydrationScriptTags() + const output = router.serverSsr!.hydrationScripts.claimOutput() + router.serverSsr!.hydrationScripts.liftBarrier() + + value.resolve('done') + await waitFor(() => output.state === HydrationScriptOutputState.Ready) + drainHydrationOutput(output) + expect(output.state).toBe(HydrationScriptOutputState.Done) + + expect(renderFinishedCalls).toBe(0) + router.serverSsr!.setRenderFinished() + expect(renderFinishedCalls).toBe(1) + + router.serverSsr?.cleanup() + }) + + test('waits for the initial record after a completed Seroval stream', async () => { + const completedStream = createStream() + completedStream.next('stream value') + completedStream.return('stream done') + const lateValue = deferred() + const router = buildRouter({ + completedStream, + lateValue: lateValue.promise, + }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + const serverSsr = router.serverSsr! + await serverSsr.dehydrate() + const initialHydration = renderInitialScripts( + serverSsr.takeInitialHydrationScriptTags()!, + ) + expect(initialHydration).toContain('stream value') + + const output = serverSsr.hydrationScripts.claimOutput() + serverSsr.setRenderFinished() + expect(output.state).toBe(HydrationScriptOutputState.Waiting) + + lateValue.resolve('late value') + await waitFor(() => output.state === HydrationScriptOutputState.Ready) + const hydration = drainHydrationOutput(output) + expect(hydration).toContain('late value') + expect(hydration).toContain('$_TSR.e()') + expect(output.state).toBe(HydrationScriptOutputState.Done) + + serverSsr.cleanup() + }) + + test('render-finished listeners can synchronously finish serialization', async () => { + const value = deferred() + const router = buildRouter({ value: value.promise }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + router.serverSsr!.takeInitialHydrationScriptTags() + const output = router.serverSsr!.hydrationScripts.claimOutput() + + router.serverSsr!.onRenderFinished(() => { + value.resolve('done') + }) + + router.serverSsr!.setRenderFinished() + await waitFor(() => output.state === HydrationScriptOutputState.Ready) + + expect(drainHydrationOutput(output)).toContain('$_TSR.e()') + expect(output.state).toBe(HydrationScriptOutputState.Done) + + router.serverSsr?.cleanup() + }) + + test('render-finished is one-shot and invokes late listeners immediately', () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const serverSsr = router.serverSsr! + const earlyListener = vi.fn() + const lateListener = vi.fn() + + serverSsr.onRenderFinished(earlyListener) + serverSsr.setRenderFinished() + serverSsr.setRenderFinished() + serverSsr.onRenderFinished(lateListener) + serverSsr.setRenderFinished() + + expect(earlyListener).toHaveBeenCalledOnce() + expect(lateListener).toHaveBeenCalledOnce() + serverSsr.cleanup() + }) + + test('a late output claim exposes completed serialization', async () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + + router.serverSsr!.takeInitialHydrationScriptTags() + const output = router.serverSsr!.hydrationScripts.claimOutput() + let calls = 0 + const unsubscribe = output.subscribe(() => { + calls++ + }) + + expect(output.state).toBe(HydrationScriptOutputState.Done) + expect(calls).toBe(0) + expect(() => unsubscribe()).not.toThrow() + router.serverSsr?.cleanup() + }) + + test('stream pass-through only reserves when no SSR work is pending', async () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + const initialScripts = router.serverSsr!.takeInitialHydrationScriptTags() + expect(initialScripts?.boundary.children).toBe( + HYDRATION_SCRIPT_BOUNDARY_SOURCE, + ) + expect(initialScripts?.boundary.attrs).not.toHaveProperty('id') + + expect(router.serverSsr!.hydrationScripts.reserveFastPath()).toBe(true) + let renderFinishedCalls = 0 + router.serverSsr!.onRenderFinished(() => { + renderFinishedCalls++ + }) + router.serverSsr!.setRenderFinished() + expect(renderFinishedCalls).toBe(1) + expect(router.serverSsr!.hydrationScripts.reserveFastPath()).toBe(false) + + router.serverSsr?.cleanup() + }) + + test('initial boundary ends with the exact scanner suffix', async () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + const scripts = router.serverSsr!.takeInitialHydrationScriptTags()! + const boundaryHtml = renderInitialScripts({ + before: [], + boundary: scripts.boundary, + }) + + expect(boundaryHtml).toBe( + ``, + ) + expect(boundaryHtml.endsWith(HYDRATION_SCRIPT_BOUNDARY_SUFFIX)).toBe(true) + + router.serverSsr?.cleanup() + }) + + test('the final hydration tag cleans adjacent parts before adapter scripts', () => { + const hydrationScripts = createHydrationScripts(undefined, ['void 0']) + const scripts = hydrationScripts.takeInitialHydrationScriptTags()! + const cleanupTag = scripts.before.at(-1)! + const nodes: Array = [] + const createNode = (marked: boolean) => { + const node = { + hasAttribute(name: string) { + return marked && name === 'data-tsr-stream-part' + }, + remove() { + nodes.splice(nodes.indexOf(this), 1) + }, + } + Object.defineProperty(node, 'previousElementSibling', { + get() { + return nodes[nodes.indexOf(node) - 1] ?? null + }, + }) + return node + } + const olderPart = createNode(true) + const unrelated = createNode(false) + const firstPart = createNode(true) + const cleanup = createNode(true) + nodes.push(olderPart, unrelated, firstPart, cleanup) + + runInNewContext(cleanupTag.children!, { + document: { currentScript: cleanup }, + }) + + const routeScript = createNode(false) + const assetScript = createNode(false) + nodes.push(routeScript, assetScript) + + expect(nodes).toEqual([olderPart, unrelated, routeScript, assetScript]) + hydrationScripts.cleanup() + }) + + test('a failed hydration tag leaves its transport node', () => { + for (const brokenSource of [ + 'throw new Error("runtime failure")', + 'const = "syntax failure"', + ]) { + const hydrationScripts = createHydrationScripts(undefined, [brokenSource]) + const scripts = hydrationScripts.takeInitialHydrationScriptTags()! + const nodes: Array<{ remove: () => void }> = [] + const part = { + previousElementSibling: null, + hasAttribute: () => true, + remove() { + nodes.splice(nodes.indexOf(this), 1) + }, + } + nodes.push(part) + + expect(() => + runInNewContext(scripts.before[0]!.children!, { + document: { currentScript: part }, + }), + ).toThrow() + expect(nodes).toEqual([part]) + hydrationScripts.cleanup() + } + }) + + test('the boundary removes only itself when there are no initial parts', () => { + const hydrationScripts = createHydrationScripts(undefined, []) + const scripts = hydrationScripts.takeInitialHydrationScriptTags()! + const nodes: Array<{ remove: () => void }> = [] + const boundary = { + remove() { + nodes.splice(nodes.indexOf(this), 1) + }, + } + nodes.push(boundary) + + runInNewContext(scripts.boundary.children!, { + document: { currentScript: boundary }, + }) + + expect(nodes).toEqual([]) + hydrationScripts.cleanup() + }) + + test('stream pass-through rejects while SSR work is pending', async () => { + const value = deferred() + const router = buildRouter({ value: value.promise }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + + expect(router.serverSsr!.hydrationScripts.reserveFastPath()).toBe(false) + const initialScripts = router.serverSsr!.takeInitialHydrationScriptTags() + expect(initialScripts?.boundary.children).toBe( + HYDRATION_SCRIPT_BOUNDARY_SOURCE, + ) + expect(initialScripts?.boundary.attrs).not.toHaveProperty('id') + expect(router.serverSsr!.hydrationScripts.reserveFastPath()).toBe(false) + + value.resolve('done') + await Promise.resolve() + await Promise.resolve() + + expect(router.serverSsr!.hydrationScripts.reserveFastPath()).toBe(false) + const output = router.serverSsr!.hydrationScripts.claimOutput() + router.serverSsr!.setRenderFinished() + await waitFor(() => output.state === HydrationScriptOutputState.Ready) + const hydration = drainHydrationOutput(output) + expect(hydration).toContain('done') + expect(output.state).toBe(HydrationScriptOutputState.Done) + expect(router.serverSsr!.hydrationScripts.reserveFastPath(output)).toBe( + true, + ) + expect(router.serverSsr!.hydrationScripts.reserveFastPath(output)).toBe( + false, + ) + + router.serverSsr?.cleanup() + }) + + test('an initial serialization error fails hydration output', async () => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const router = buildRouter({ unsupported: () => {} }) + + try { + attachRouterServerSsrUtils({ router, manifest: undefined }) + await router.load() + await expect(router.serverSsr!.dehydrate()).rejects.toBeInstanceOf(Error) + + expect(errorSpy).toHaveBeenCalledWith( + 'Serialization error:', + expect.any(Error), + ) + } finally { + router.serverSsr?.cleanup() + errorSpy.mockRestore() + } + }) + + test('an invalid deferred value fails instead of leaving hydration pending', async () => { + const invalidValue = deferred() + const validValue = deferred() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const router = buildRouter({ + invalidValue: invalidValue.promise, + validValue: validValue.promise, + }) + + try { + attachRouterServerSsrUtils({ router, manifest: undefined }) + await router.load() + await router.serverSsr!.dehydrate() + router.serverSsr!.takeInitialHydrationScriptTags() + const output = router.serverSsr!.hydrationScripts.claimOutput() + router.serverSsr!.hydrationScripts.liftBarrier() + invalidValue.resolve(() => {}) + await waitFor(() => output.state === HydrationScriptOutputState.Failed) + + expect(output.error).toBeInstanceOf(Error) + expect(errorSpy).toHaveBeenCalledWith( + 'Serialization error:', + output.error, + ) + + validValue.resolve('ignored') + await Promise.resolve() + await Promise.resolve() + expect(output.state).toBe(HydrationScriptOutputState.Failed) + expect(router.serverSsr!.hydrationScripts.reserveFastPath(output)).toBe( + false, + ) + } finally { + router.serverSsr?.cleanup() + errorSpy.mockRestore() + } + }) + + test('a rejected hydration source stops serialization before stream creation', async () => { + const lateValue = deferred() + const router = buildRouter({ lateValue: lateValue.promise }) + const onCleanup = vi.fn() + + try { + attachRouterServerSsrUtils({ router, manifest: undefined }) + router.serverSsr!.onCleanup(onCleanup) + await router.load() + const scripts = router.serverSsr!.hydrationScripts as HydrationScripts + const backlogError = new Error('hydration backlog full') + const pushSerializedSource = vi + .spyOn(scripts, 'pushSerializedSource') + .mockImplementation(() => { + scripts.fail(backlogError) + return false + }) + + await router.serverSsr!.dehydrate() + + const output = scripts.claimOutput() + expect(output.state).toBe(HydrationScriptOutputState.Failed) + expect(output.error).toBe(backlogError) + expect(pushSerializedSource).toHaveBeenCalledOnce() + + lateValue.resolve('ignored') + await Promise.resolve() + await Promise.resolve() + expect(pushSerializedSource).toHaveBeenCalledOnce() + router.serverSsr!.cleanup() + expect(onCleanup).toHaveBeenCalledExactlyOnceWith(false) + } finally { + router.serverSsr?.cleanup() + } + }) + + test('a hydration backlog failure aborts pending loader work during cleanup', async () => { + const pending = deferred() + const onCleanup = vi.fn() + const cancelSource = vi.fn() + let loaderSignal: AbortSignal | undefined + let chunks = 0 + const source = new ReadableStream( + { + pull(controller) { + // Bound the producer even if backlog protection regresses. + if (chunks++ < 5_000) { + controller.enqueue(Uint8Array.of(1)) + } + }, + cancel: cancelSource, + }, + { highWaterMark: 0 }, + ) + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: ({ abortController }) => { + loaderSignal = abortController.signal + return { pending: pending.promise, stream: new RawStream(source) } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + const serverSsr = router.serverSsr! + serverSsr.onCleanup(onCleanup) + + try { + await router.load() + await serverSsr.dehydrate() + // The renderer has not returned its stream, so nothing drains the backlog. + const output = serverSsr.hydrationScripts.claimOutput() + await vi.waitFor(() => { + expect(output.state).toBe(HydrationScriptOutputState.Failed) + expect(cancelSource).toHaveBeenCalledOnce() + }) + expect(String(output.error)).toContain( + 'backlog exceeded maximum source-part count', + ) + expect(loaderSignal?.aborted).toBe(false) + + serverSsr.cleanup() + + expect(onCleanup).toHaveBeenCalledExactlyOnceWith(false) + expect(loaderSignal?.aborted).toBe(true) + expect(source.locked).toBe(false) + expect(router.serverSsr).toBeUndefined() + expect(router.ssr).toBeUndefined() + } finally { + serverSsr.cleanup() + pending.resolve('done') + if (!source.locked) { + await source.cancel() + } + } + }) + + test('the hydration channel permits only one subscriber', () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const output = router.serverSsr!.hydrationScripts.claimOutput() + const unsubscribe = output.subscribe(() => {}) + + expect(() => output.subscribe(() => {})).toThrow('already has a subscriber') + unsubscribe() + expect(() => output.subscribe(() => {})).not.toThrow() + router.serverSsr!.cleanup() + }) + + test('the claimed output receives scripts buffered before the claim', async () => { + const value = deferred() + const router = buildRouter({ value: value.promise }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + await router.load() + await router.serverSsr!.dehydrate() + router.serverSsr!.takeInitialHydrationScriptTags() + + router.serverSsr!.hydrationScripts.liftBarrier() + value.resolve('buffered') + await Promise.resolve() + await Promise.resolve() + + const output = router.serverSsr!.hydrationScripts.claimOutput() + + expect(output.state).toBe(HydrationScriptOutputState.Ready) + const hydration = drainHydrationOutput(output) + expect(hydration).toContain('buffered') + expect(hydration).toContain('$_TSR.e()') + router.serverSsr!.cleanup() + }) + + test('server SSR attach lifecycle runs listeners at attach time', () => { + const router = buildRouter() + const calls: Array = [] + router.serverSsrLifecycle = { + onServerSsrAttach: [ + (serverSsr) => { + calls.push('attach') + serverSsr.onCleanup(() => calls.push('cleanup')) + }, + ], + } + + attachRouterServerSsrUtils({ router, manifest: undefined }) + expect(calls).toEqual(['attach']) + + router.serverSsr!.cleanup() + expect(calls).toEqual(['attach', 'cleanup']) + }) + + test('request handler cleans SSR state before returning a plain body', async () => { + const router = buildRouter() + let cleanupEffects = 0 + const handler = createRequestHandler({ + createRouter: () => router, + request: new Request('http://localhost/'), + }) + + const response = await handler(({ router: requestRouter }) => { + const serverSsr = requestRouter.serverSsr! + serverSsr.onCleanup(() => { + cleanupEffects++ + }) + return Promise.resolve(new Response('plain')) + }) + + expect(cleanupEffects).toBe(1) + await response.text() + expect(cleanupEffects).toBe(1) + expect(router.serverSsr).toBeUndefined() + }) + + test('request handler cleans SSR state before returning a plain stream', async () => { + const router = buildRouter() + let cleanupCalls = 0 + const handler = createRequestHandler({ + createRouter: () => router, + request: new Request('http://localhost/'), + }) + + const response = await handler(({ router: requestRouter }) => { + const serverSsr = requestRouter.serverSsr! + const cleanup = serverSsr.cleanup + serverSsr.cleanup = () => { + cleanupCalls++ + cleanup() + } + return Promise.resolve( + new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('plain')) + }, + }), + ), + ) + }) + + expect(cleanupCalls).toBe(1) + await response.body!.cancel('done') + expect(cleanupCalls).toBe(1) + expect(router.serverSsr).toBeUndefined() + }) + + test('request handler cleans bodyless response immediately', async () => { + const router = buildRouter() + let cleanupCalls = 0 + const handler = createRequestHandler({ + createRouter: () => router, + request: new Request('http://localhost/'), + }) + + await handler(({ router: requestRouter }) => { + const serverSsr = requestRouter.serverSsr! + const cleanup = serverSsr.cleanup + serverSsr.cleanup = () => { + cleanupCalls++ + cleanup() + } + return Promise.resolve(new Response(null, { status: 204 })) + }) + + expect(cleanupCalls).toBe(1) + expect(router.serverSsr).toBeUndefined() + }) + + test('request abort settles while the render callback is still pending', async () => { + const router = buildRouter() + const requestController = new AbortController() + const renderStarted = deferred() + const renderResult = deferred>() + let cleanupEffects = 0 + let cancelCalls = 0 + let lateStreamResponse!: ReturnType + const handler = createRequestHandler({ + createRouter: () => router, + request: new Request('http://localhost/', { + signal: requestController.signal, + }), + }) + + const response = handler(({ router: requestRouter }) => { + const serverSsr = requestRouter.serverSsr! + serverSsr.onCleanup(() => { + cleanupEffects++ + }) + lateStreamResponse = createSsrStreamResponse( + requestRouter, + new Response( + new ReadableStream({ + cancel() { + cancelCalls++ + return new Promise(() => {}) + }, + }), + ), + ) + renderStarted.resolve() + return renderResult.promise + }) + + await renderStarted.promise + const cancellation = new Error('request disconnected') + requestController.abort(cancellation) + + await expect(response).rejects.toBe(cancellation) + expect(cleanupEffects).toBe(1) + expect(router.serverSsr).toBeUndefined() + + renderResult.resolve(lateStreamResponse) + await Promise.resolve() + await Promise.resolve() + expect(cleanupEffects).toBe(1) + expect(cancelCalls).toBe(1) + expect(router.serverSsr).toBeUndefined() + }) + + test('request abort cancels a plain response resolved by the callback later', async () => { + const router = buildRouter() + const requestController = new AbortController() + const callbackStarted = deferred() + const callbackResult = deferred() + const cancel = vi.fn((_reason: unknown) => new Promise(() => {})) + const handler = createRequestHandler({ + createRouter: () => router, + request: new Request('http://localhost/', { + signal: requestController.signal, + }), + }) + + const response = handler(() => { + callbackStarted.resolve() + return callbackResult.promise + }) + + await callbackStarted.promise + const cancellation = new Error('request disconnected') + requestController.abort(cancellation) + + await expect(response).rejects.toBe(cancellation) + callbackResult.resolve(new Response(new ReadableStream({ cancel }))) + await vi.waitFor(() => { + expect(cancel).toHaveBeenCalledTimes(1) + expect(cancel).toHaveBeenCalledWith(cancellation) + }) + }) + + test('request abort disposes a stream after response handoff', async () => { + const router = buildRouter() + const requestController = new AbortController() + let cleanupCalls = 0 + let cancelCalls = 0 + const handler = createRequestHandler({ + createRouter: () => router, + request: new Request('http://localhost/', { + signal: requestController.signal, + }), + }) + + const response = await handler(({ router: requestRouter }) => { + const serverSsr = requestRouter.serverSsr! + const cleanup = serverSsr.cleanup + serverSsr.cleanup = () => { + cleanupCalls++ + cleanup() + } + return createSsrStreamResponse( + requestRouter, + new Response( + new ReadableStream({ + cancel() { + cancelCalls++ + return new Promise(() => {}) + }, + }), + ), + ) + }) + + expect(response.body).not.toBeNull() + expect(cleanupCalls).toBe(0) + requestController.abort(new Error('request disconnected')) + await Promise.resolve() + + expect(cleanupCalls).toBe(1) + expect(cancelCalls).toBe(1) + expect(router.serverSsr).toBeUndefined() + }) + + test('request handler defers cleanup for stream response metadata', async () => { + const router = buildRouter() + let cleanupCalls = 0 + let controller!: ReadableStreamDefaultController + let initialScriptHtml = '' + const handler = createRequestHandler({ + createRouter: () => router, + request: new Request('http://localhost/'), + }) + + const response = await handler(({ router: requestRouter }) => { + const serverSsr = requestRouter.serverSsr! + const cleanup = serverSsr.cleanup + serverSsr.cleanup = () => { + cleanupCalls++ + cleanup() + } + const initialScripts = serverSsr.takeInitialHydrationScriptTags() + expect(initialScripts?.boundary.children).toBe( + HYDRATION_SCRIPT_BOUNDARY_SOURCE, + ) + expect(initialScripts?.boundary.attrs).not.toHaveProperty('id') + initialScriptHtml = renderInitialScripts(initialScripts!) + const appStream = new ReadableStream({ + start(c) { + controller = c + }, + }) + const responseStream = transformReadableStreamWithRouter( + requestRouter, + appStream as any, + ) + + return createSsrStreamResponse( + requestRouter, + new Response(responseStream as any), + ) + }) + + expect(cleanupCalls).toBe(0) + controller.enqueue( + new TextEncoder().encode( + `${initialScriptHtml}ok`, + ), + ) + controller.close() + await response.text() + expect(cleanupCalls).toBe(1) + expect(router.serverSsr).toBeUndefined() + }) + + test('external cleanup releases a discarded stream transform immediately', async () => { + // Mirrors a request handler that discards a stream response (for example a + // middleware throwing after the handler returned): the bare cleanup() in + // its finally block must tear the transform down at once instead of + // leaving the renderer pinned until the lifetime timer. + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const serverSsr = router.serverSsr! + serverSsr.takeInitialHydrationScriptTags() + + const upstreamCancelled = { value: false, reason: undefined as unknown } + const appStream = new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode('')) + }, + cancel(reason) { + upstreamCancelled.value = true + upstreamCancelled.reason = reason + }, + }) + const aborts: Array = [] + const responseStream = transformReadableStreamWithRouter( + router, + appStream as any, + { + onAbort: (reason) => aborts.push(reason), + }, + ) + + // The response is never read and never cancelled. + serverSsr.cleanup() + + expect(upstreamCancelled.value).toBe(true) + expect((upstreamCancelled.reason as Error).name).toBe('AbortError') + expect(aborts).toHaveLength(1) + expect(router.serverSsr).toBeUndefined() + await expect(responseStream.getReader().read()).rejects.toMatchObject({ + name: 'AbortError', + }) + }) + + test('concurrent dehydrate calls throw instead of double-serializing', async () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const serverSsr = router.serverSsr! + + const first = serverSsr.dehydrate() + await expect(serverSsr.dehydrate()).rejects.toThrow( + 'router is already dehydrated', + ) + await first + await expect(serverSsr.dehydrate()).rejects.toThrow( + 'router is already dehydrated', + ) + serverSsr.cleanup() + }) + + test('onCleanup after cleanup invokes the listener immediately', () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const serverSsr = router.serverSsr! + serverSsr.cleanup() + + const listener = vi.fn() + serverSsr.onCleanup(listener) + expect(listener).toHaveBeenCalledTimes(1) + }) + + test('a late onCleanup listener that throws is contained', () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const serverSsr = router.serverSsr! + serverSsr.cleanup() + + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + expect(() => + serverSsr.onCleanup(() => { + throw new Error('late-listener-boom') + }), + ).not.toThrow() + expect(errorSpy).toHaveBeenCalledWith( + 'Error in SSR cleanup listener:', + expect.objectContaining({ message: 'late-listener-boom' }), + ) + } finally { + errorSpy.mockRestore() + } + }) + + test('binding a stream response after cleanup still observes request abort', async () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const cancel = vi.fn() + const streamResponse = createSsrStreamResponse( + router, + new Response(new ReadableStream({ cancel })), + ) + const dispose = vi.spyOn(streamResponse, 'dispose') + router.serverSsr!.cleanup() + + const controller = new AbortController() + const addSpy = vi.spyOn(controller.signal, 'addEventListener') + const result = bindSsrResponseToRequest( + router, + streamResponse, + controller.signal, + ) + + expect(result.serverSsrCleanup).toBe('stream') + expect(addSpy).toHaveBeenCalledOnce() + + const reason = new Error('request disconnected') + controller.abort(reason) + await Promise.resolve() + + expect(dispose).toHaveBeenCalledExactlyOnceWith(reason) + expect(cancel).toHaveBeenCalledExactlyOnceWith(reason) + }) + + test.each(['pass-through', 'merge'])( + 'shares the %s transform abort listener with final response disposal', + async (mode) => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const serverSsr = router.serverSsr! + if (mode === 'pass-through') { + serverSsr.disableHydration() + } + const cleanup = vi.fn() + serverSsr.onCleanup(cleanup) + const requestAbort = new AbortController() + const add = vi.spyOn(requestAbort.signal, 'addEventListener') + const remove = vi.spyOn(requestAbort.signal, 'removeEventListener') + const cancelSource = vi.fn(() => new Promise(() => {})) + const source = new ReadableStream({ cancel: cancelSource }) + const transformed = transformReadableStreamWithRouter(router, source, { + signal: requestAbort.signal, + }) + const original = createSsrStreamResponse( + router, + new Response(transformed), + ) + const cancelFinal = vi.fn(() => new Promise(() => {})) + const response = new Response(new ReadableStream({ cancel: cancelFinal })) + const dispose = vi.fn((reason?: unknown): undefined => { + original.dispose(reason) + void response.body!.cancel(reason).catch(() => {}) + }) + bindSsrResponseToRequest( + router, + { ...original, response, dispose }, + requestAbort.signal, + ) + + expect(add).toHaveBeenCalledOnce() + const reason = new Error('request disconnected') + const reader = transformed.getReader() + const rejected = expect(reader.read()).rejects.toBe(reason) + requestAbort.abort(reason) + await rejected + + expect(dispose).toHaveBeenCalledExactlyOnceWith(reason) + expect(cancelFinal).toHaveBeenCalledExactlyOnceWith(reason) + expect(cancelSource).toHaveBeenCalledExactlyOnceWith(reason) + expect(source.locked).toBe(false) + expect(cleanup).toHaveBeenCalledOnce() + expect(remove).toHaveBeenCalledOnce() + expect(router.serverSsr).toBeUndefined() + reader.releaseLock() + }, + ) + + test('successful transform completion removes abort handling without disposing the response', async () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + router.serverSsr!.disableHydration() + const requestAbort = new AbortController() + const add = vi.spyOn(requestAbort.signal, 'addEventListener') + const remove = vi.spyOn(requestAbort.signal, 'removeEventListener') + const cancel = vi.fn() + const source = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('done')) + controller.close() + }, + cancel, + }) + const transformed = transformReadableStreamWithRouter(router, source, { + signal: requestAbort.signal, + }) + const result = createSsrStreamResponse(router, new Response(transformed)) + const dispose = vi.spyOn(result, 'dispose') + bindSsrResponseToRequest(router, result, requestAbort.signal) + + expect(await result.response.text()).toBe('done') + requestAbort.abort(new Error('request ended after completion')) + expect(add).toHaveBeenCalledOnce() + expect(remove).toHaveBeenCalledOnce() + expect(dispose).not.toHaveBeenCalled() + expect(cancel).not.toHaveBeenCalled() + expect(source.locked).toBe(false) + expect(router.serverSsr).toBeUndefined() + }) + + test.each(['custom response', 'no signal', 'different signal'])( + 'keeps request binding for a %s', + async (mode) => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + router.serverSsr!.disableHydration() + const requestAbort = new AbortController() + const add = vi.spyOn(requestAbort.signal, 'addEventListener') + const cancel = vi.fn() + const source = new ReadableStream({ cancel }) + const body = + mode === 'custom response' + ? source + : transformReadableStreamWithRouter(router, source, { + signal: + mode === 'different signal' + ? new AbortController().signal + : undefined, + }) + const result = createSsrStreamResponse(router, new Response(body)) + const dispose = vi.spyOn(result, 'dispose') + bindSsrResponseToRequest(router, result, requestAbort.signal) + const reason = new Error('request disconnected') + requestAbort.abort(reason) + await Promise.resolve() + + expect(add).toHaveBeenCalledOnce() + expect(dispose).toHaveBeenCalledExactlyOnceWith(reason) + expect(cancel).toHaveBeenCalledOnce() + expect(source.locked).toBe(false) + expect(router.serverSsr).toBeUndefined() + }, + ) + + test('already-aborted response handoff disposes immediately without adding a listener', async () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const cancel = vi.fn() + const result = createSsrStreamResponse( + router, + new Response(new ReadableStream({ cancel })), + ) + const dispose = vi.spyOn(result, 'dispose') + const requestAbort = new AbortController() + const reason = new Error('request already disconnected') + requestAbort.abort(reason) + const add = vi.spyOn(requestAbort.signal, 'addEventListener') + bindSsrResponseToRequest(router, result, requestAbort.signal) + await Promise.resolve() + + expect(add).not.toHaveBeenCalled() + expect(dispose).toHaveBeenCalledExactlyOnceWith(reason) + expect(cancel).toHaveBeenCalledExactlyOnceWith(reason) + expect(router.serverSsr).toBeUndefined() + }) + + test('disabled hydration streams through pass-through without a boundary', async () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + const serverSsr = router.serverSsr! + serverSsr.disableHydration() + + // No boundary anywhere in the document. + const html = '
    static page
    ' + const appStream = new ReadableStream({ + start(c) { + c.enqueue(new TextEncoder().encode(html)) + c.close() + }, + }) + + const responseStream = transformReadableStreamWithRouter( + router, + appStream as any, + ) + const text = await new Response(responseStream as any).text() + + expect(text).toBe(html) + expect(text).not.toContain('$tsr-stream-boundary') + expect(text).not.toContain('data-tsr-stream-part') + expect(router.serverSsr).toBeUndefined() + }) + + test('disabled hydration renders strings through the eager fast path', async () => { + const router = buildRouter() + attachRouterServerSsrUtils({ router, manifest: undefined }) + router.serverSsr!.disableHydration() + + const html = 'no hydration' + const text = await transformHtmlStringWithRouter(router, html) + + expect(text).toBe('' + html) + expect(router.serverSsr).toBeUndefined() + }) + + test('disableHydration and dehydrate are mutually exclusive', async () => { + const disabledFirst = buildRouter() + attachRouterServerSsrUtils({ router: disabledFirst, manifest: undefined }) + disabledFirst.serverSsr!.disableHydration() + // Idempotent second call. + expect(() => disabledFirst.serverSsr!.disableHydration()).not.toThrow() + await expect(disabledFirst.serverSsr!.dehydrate()).rejects.toThrow( + 'hydration is disabled for this request', + ) + disabledFirst.serverSsr!.cleanup() + + const dehydratedFirst = buildRouter() + attachRouterServerSsrUtils({ router: dehydratedFirst, manifest: undefined }) + await dehydratedFirst.serverSsr!.dehydrate() + expect(() => dehydratedFirst.serverSsr!.disableHydration()).toThrow( + 'cannot disable hydration after dehydrate()', + ) + dehydratedFirst.serverSsr!.cleanup() + }) +}) diff --git a/packages/router-core/tests/ssr-server-manifest.test.ts b/packages/router-core/tests/ssr-server-manifest.test.ts new file mode 100644 index 0000000000..95b7588e87 --- /dev/null +++ b/packages/router-core/tests/ssr-server-manifest.test.ts @@ -0,0 +1,557 @@ +import { runInNewContext } from 'node:vm' +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { GLOBAL_TSR } from '../src/ssr/constants' + +import { attachRouterServerSsrUtils } from '../src/ssr/ssr-server' +import { createTestRouter } from './routerTestUtils' +import type { AnyRouter } from '../src' +import type { + ManifestCssLink, + ManifestRouteAssets, + ServerManifest, +} from '../src/manifest' +import type { InitialHydrationScriptTags } from '../src/ssr/hydrationScripts' +import type { DehydratedRouter } from '../src/ssr/types' + +function buildRouter() { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => null, + }) + const postsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + component: () => null, + }) + + const routeTree = rootRoute.addChildren([indexRoute, postsRoute]) + + return createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) +} + +function buildManifest(): ServerManifest { + const sharedAsset: ManifestCssLink = '/assets/shared.css' + + return { + routes: { + __root__: { + css: [sharedAsset], + preloads: ['/assets/root.js'], + }, + '/': { + css: [sharedAsset], + preloads: ['/assets/index.js'], + }, + '/posts': { + css: [sharedAsset], + preloads: ['/assets/posts.js'], + }, + }, + } +} + +function buildInlineManifest(): ServerManifest { + const manifest = buildManifest() + return { + ...manifest, + inlineCss: { + styles: { + '/assets/shared.css': '.shared{color:red}', + }, + }, + } +} + +async function dehydrateManifest() { + const router = buildRouter() + const manifest = buildManifest() + + attachRouterServerSsrUtils({ + router, + manifest, + }) + + await router.load() + await router.serverSsr!.dehydrate() + + const scripts = router.serverSsr!.takeInitialHydrationScriptTags() + expect(scripts?.boundary.children).toContain('$tsr-stream-boundary') + expect(scripts?.boundary.attrs).not.toHaveProperty('id') + + return parseSerializedRouter(scripts!).manifest! +} + +function parseSerializedRouter( + scripts: InitialHydrationScriptTags, +): DehydratedRouter { + const context: Record = { + document: { + currentScript: { + remove() {}, + }, + }, + } + context.self = context + + expect(scripts.boundary.children).toContain('$tsr-stream-boundary') + expect(scripts.boundary.attrs).not.toHaveProperty('id') + + const streamParts = scripts.before + expect(streamParts.length).toBeGreaterThan(0) + for (const script of streamParts) { + expect(script.tag).toBe('script') + expect(script.attrs?.['data-tsr-stream-part']).toBe('') + expect(script.children).toBeTruthy() + runInNewContext(script.children!, context) + } + + const router = context[GLOBAL_TSR]?.router + expect(router).toBeDefined() + return router +} + +describe('attachRouterServerSsrUtils manifest dehydration', () => { + test.each([ + { label: 'false', value: false, expectedProperty: true }, + { label: 'zero', value: 0, expectedProperty: true }, + { label: 'an empty string', value: '', expectedProperty: true }, + { label: 'null', value: null, expectedProperty: true }, + { label: 'undefined', value: undefined, expectedProperty: false }, + ])( + 'preserves $label custom dehydration values', + async ({ value, expectedProperty }) => { + const router: AnyRouter = buildRouter() + router.options.dehydrate = () => value + attachRouterServerSsrUtils({ router, manifest: undefined }) + + try { + await router.load() + await router.serverSsr!.dehydrate() + const scripts = router.serverSsr!.takeInitialHydrationScriptTags() + const dehydratedRouter = parseSerializedRouter(scripts!) + + expect( + Object.prototype.hasOwnProperty.call( + dehydratedRouter, + 'dehydratedData', + ), + ).toBe(expectedProperty) + if (expectedProperty) { + expect(dehydratedRouter.dehydratedData).toBe(value) + } + } finally { + router.serverSsr?.cleanup() + } + }, + ) + + test('omits unmatched route assets by default', async () => { + const manifest = await dehydrateManifest() + + expect(manifest.routes['/posts']).toBeUndefined() + expect(manifest.routes['/']?.preloads).toEqual(['/assets/index.js']) + }) + + test('preserves script format when dehydrating the manifest', async () => { + const router = buildRouter() + const manifest: ServerManifest = { + ...buildManifest(), + scriptFormat: 'iife', + } + + attachRouterServerSsrUtils({ + router, + manifest, + }) + + await router.load() + await router.serverSsr!.dehydrate() + + const scripts = router.serverSsr!.takeInitialHydrationScriptTags() + const dehydratedManifest = parseSerializedRouter(scripts!).manifest! + + expect(dehydratedManifest.scriptFormat).toBe('iife') + }) + + test('maps request-scoped preload links into SSR manifest data', async () => { + const router = buildRouter() + const manifest = buildManifest() + const requestAssets: ManifestRouteAssets = { + preloads: [{ href: '/assets/rsc-client.js', crossOrigin: 'anonymous' }], + scripts: [ + { + attrs: { + src: '/assets/request-script.js', + type: 'module', + }, + children: 'console.log("request")', + }, + ], + css: [{ href: '/assets/rsc-client.css', crossOrigin: 'use-credentials' }], + } + + attachRouterServerSsrUtils({ + router, + manifest, + getRequestAssets: () => requestAssets, + }) + + await router.load() + + expect(router.ssr!.manifest?.routes.__root__).toMatchObject({ + preloads: [ + { href: '/assets/rsc-client.js', crossOrigin: 'anonymous' }, + '/assets/root.js', + ], + scripts: [ + { + attrs: { + src: '/assets/request-script.js', + type: 'module', + }, + children: 'console.log("request")', + }, + ], + css: [ + { href: '/assets/rsc-client.css', crossOrigin: 'use-credentials' }, + '/assets/shared.css', + ], + }) + }) + + test('maps preloads-only request assets into SSR manifest data', async () => { + const router = buildRouter() + const manifest = buildManifest() + const requestAssets: ManifestRouteAssets = { + preloads: [{ href: '/assets/rsc-client.js', crossOrigin: 'anonymous' }], + } + + attachRouterServerSsrUtils({ + router, + manifest, + getRequestAssets: () => requestAssets, + }) + + await router.load() + + expect(router.ssr!.manifest?.routes.__root__?.preloads).toEqual([ + { href: '/assets/rsc-client.js', crossOrigin: 'anonymous' }, + '/assets/root.js', + ]) + }) + + test('dehydrates request-scoped preload links into manifest data', async () => { + const router = buildRouter() + const manifest = buildManifest() + + attachRouterServerSsrUtils({ + router, + manifest, + }) + + await router.load() + await router.serverSsr!.dehydrate({ + requestAssets: { + preloads: [{ href: '/assets/rsc-client.js', crossOrigin: 'anonymous' }], + scripts: [ + { + attrs: { + src: '/assets/request-script.js', + type: 'module', + }, + children: 'console.log("request")', + }, + ], + css: [ + { + href: '/assets/rsc-client.css', + crossOrigin: 'use-credentials', + }, + ], + }, + }) + + const scripts = router.serverSsr!.takeInitialHydrationScriptTags() + const dehydratedManifest = parseSerializedRouter(scripts!).manifest! + + expect(dehydratedManifest.routes.__root__).toMatchObject({ + preloads: [ + { href: '/assets/rsc-client.js', crossOrigin: 'anonymous' }, + '/assets/root.js', + ], + scripts: [ + { + attrs: { + src: '/assets/request-script.js', + type: 'module', + }, + children: 'console.log("request")', + }, + ], + css: [ + { href: '/assets/rsc-client.css', crossOrigin: 'use-credentials' }, + '/assets/shared.css', + ], + }) + expect(Array.isArray(dehydratedManifest.routes.__root__?.css)).toBe(true) + expect((dehydratedManifest.routes.__root__?.css as any).links).toBe( + undefined, + ) + }) + + test('dehydrates preloads-only request assets into manifest data', async () => { + const router = buildRouter() + const manifest = buildManifest() + + attachRouterServerSsrUtils({ + router, + manifest, + }) + + await router.load() + await router.serverSsr!.dehydrate({ + requestAssets: { + preloads: [{ href: '/assets/rsc-client.js', crossOrigin: 'anonymous' }], + }, + }) + + const scripts = router.serverSsr!.takeInitialHydrationScriptTags() + const dehydratedManifest = parseSerializedRouter(scripts!).manifest! + + expect(dehydratedManifest.routes.__root__?.preloads).toEqual([ + { href: '/assets/rsc-client.js', crossOrigin: 'anonymous' }, + '/assets/root.js', + ]) + }) + + test('inlines stylesheet assets for SSR and strips stylesheet links from dehydration', async () => { + const router = buildRouter() + const manifest = buildInlineManifest() + + attachRouterServerSsrUtils({ + router, + manifest, + }) + + await router.load() + + const ssrInlineCss = router.ssr!.manifest?.inlineStyle + expect(ssrInlineCss).toMatchObject({ + children: '.shared{color:red}', + }) + + await router.serverSsr!.dehydrate() + + const scripts = router.serverSsr!.takeInitialHydrationScriptTags() + const dehydratedRouter = parseSerializedRouter(scripts!) + const dehydratedManifest = dehydratedRouter.manifest! + const rootInlineCss = dehydratedManifest.inlineStyle + const allLinks = Object.values(dehydratedManifest.routes).flatMap( + (route) => route.css ?? [], + ) + + expect(rootInlineCss).toEqual({ + attrs: { + suppressHydrationWarning: true, + }, + }) + expect('inlineCss' in dehydratedManifest).toBe(false) + expect( + allLinks.some((asset) => + typeof asset === 'string' + ? asset === '/assets/shared.css' + : asset.href === '/assets/shared.css', + ), + ).toBe(false) + expect(dehydratedManifest.routes['/']?.preloads).toEqual([ + '/assets/index.js', + ]) + }) + + test('memoizes prepared inline CSS while composing request assets freshly', async () => { + const router = buildRouter() + const manifest = buildInlineManifest() + const requestAssets: ManifestRouteAssets = { + preloads: ['/assets/request.js'], + } + + attachRouterServerSsrUtils({ + router, + manifest, + getRequestAssets: () => requestAssets, + }) + + await router.load() + + const first = router.ssr!.manifest + const second = router.ssr!.manifest + // The composed manifest is fresh because request assets are mutable, while + // the immutable inline CSS preparation is reused for this route set. + expect(second).not.toBe(first) + expect(second?.inlineStyle).toBe(first?.inlineStyle) + expect(first?.inlineStyle).toMatchObject({ + children: '.shared{color:red}', + }) + expect(first?.routes.__root__?.preloads).toEqual([ + '/assets/request.js', + '/assets/root.js', + ]) + }) + + test('refreshes the composed manifest when a stable request-assets object changes', async () => { + const router = buildRouter() + const manifest = buildManifest() + const requestAssets: ManifestRouteAssets = { + preloads: ['/assets/discovered-early.js'], + } + + attachRouterServerSsrUtils({ + router, + manifest, + getRequestAssets: () => requestAssets, + }) + + try { + await router.load() + + const beforeDiscovery = router.ssr!.manifest + expect(beforeDiscovery?.routes.__root__?.preloads).toEqual([ + '/assets/discovered-early.js', + '/assets/root.js', + ]) + + // React Start RSC retains this object and replaces these members as it + // discovers client references during the request. + requestAssets.preloads = ['/assets/discovered-late.js'] + + const afterDiscovery = router.ssr!.manifest + expect(afterDiscovery).not.toBe(beforeDiscovery) + expect(afterDiscovery?.routes.__root__?.preloads).toEqual([ + '/assets/discovered-late.js', + '/assets/root.js', + ]) + } finally { + router.serverSsr?.cleanup() + } + }) + + test('strips only inlinable stylesheet links from dehydrated manifest data', async () => { + const router = buildRouter() + const manifest: ServerManifest = { + inlineCss: { + styles: { + '/assets/root-inline.css': '.root{color:red}', + '/assets/index-inline.css': '.index{color:blue}', + }, + }, + routes: { + __root__: { + css: [ + '/assets/root-inline.css', + { + href: '/assets/root-linked.css', + crossOrigin: 'anonymous', + }, + ], + }, + '/': { + css: [ + { + href: '/assets/index-inline.css', + crossOrigin: 'use-credentials', + }, + '/assets/index-linked.css', + ], + preloads: ['/assets/index.js'], + }, + }, + } + + attachRouterServerSsrUtils({ + router, + manifest, + }) + + await router.load() + + expect(router.ssr!.manifest?.inlineStyle).toMatchObject({ + children: '.root{color:red}.index{color:blue}', + }) + + await router.serverSsr!.dehydrate() + + const scripts = router.serverSsr!.takeInitialHydrationScriptTags() + const dehydratedManifest = parseSerializedRouter(scripts!).manifest! + + expect(dehydratedManifest.routes.__root__?.css).toEqual([ + { + href: '/assets/root-linked.css', + crossOrigin: 'anonymous', + }, + ]) + expect(dehydratedManifest.routes['/']?.css).toEqual([ + '/assets/index-linked.css', + ]) + expect(dehydratedManifest.routes['/']?.preloads).toEqual([ + '/assets/index.js', + ]) + }) + + test('omits descendant assets past a terminal parent boundary', async () => { + const rootRoute = new BaseRootRoute({}) + const parentRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => { + throw new Error('parent failed') + }, + }) + const childRoute = new BaseRoute({ + getParentRoute: () => parentRoute, + path: '/child', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + isServer: true, + }) + const manifest: ServerManifest = { + inlineCss: { + styles: { + '/assets/root.css': '.root{}', + '/assets/parent.css': '.parent{}', + '/assets/child.css': '.child{}', + }, + }, + routes: { + [rootRoute.id]: { css: ['/assets/root.css'] }, + [parentRoute.id]: { css: ['/assets/parent.css'] }, + [childRoute.id]: { + css: ['/assets/child.css'], + preloads: ['/assets/child.js'], + }, + }, + } + + attachRouterServerSsrUtils({ router, manifest }) + await router.load() + + expect(router.state.matches).toHaveLength(3) + expect(router.ssr!.manifest?.inlineStyle?.children).toBe('.root{}.parent{}') + + await router.serverSsr!.dehydrate() + const scripts = router.serverSsr!.takeInitialHydrationScriptTags() + expect(scripts).toBeDefined() + const dehydratedManifest = parseSerializedRouter(scripts!).manifest! + + expect(dehydratedManifest.routes[childRoute.id]).toBeUndefined() + }) +}) diff --git a/packages/router-core/tests/stay-match-abort.test.ts b/packages/router-core/tests/stay-match-abort.test.ts new file mode 100644 index 0000000000..a389d2be76 --- /dev/null +++ b/packages/router-core/tests/stay-match-abort.test.ts @@ -0,0 +1,247 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + BaseRoute, + createControlledPromise, + notFound, +} from '../src' +import { createTestRouter } from './routerTestUtils' + +afterEach(() => { + vi.restoreAllMocks() +}) + +/** + * A settled success stay-match must keep its abortController un-aborted + * across navigations and invalidations: loaders can hand that signal to + * still-streaming deferred data (fetch(url, { signal }) consumed via + * ), and the documented contract only cancels the signal when the + * route unloads or the loader call becomes outdated. Only pending or + * actively-fetching matches are cancelled at load start. + */ + +function setup(reloadGate?: Promise) { + let capturedSignal: AbortSignal | undefined + let deferredRequestAbortCount = 0 + let loaderCalls = 0 + + const rootRoute = new BaseRootRoute({}) + const dashboardRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/dashboard', + staleTime: Infinity, + loader: ({ abortController }: { abortController: AbortController }) => { + loaderCalls++ + capturedSignal = abortController.signal + + // A common streaming pattern is to return immediately-available data + // alongside a request consumed later by . That request must stay + // alive while this layout is reused, then be cancelled when it unloads. + const deferredRequest = new Promise<'aborted'>((resolve) => { + abortController.signal.addEventListener( + 'abort', + () => { + deferredRequestAbortCount++ + resolve('aborted') + }, + { once: true }, + ) + }) + + const data = { critical: 'dashboard data', deferredRequest } + return reloadGate && loaderCalls > 1 ? reloadGate.then(() => data) : data + }, + }) + const settingsRoute = new BaseRoute({ + getParentRoute: () => dashboardRoute, + path: '/settings', + }) + const loginRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/login', + }) + + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + dashboardRoute.addChildren([settingsRoute]), + loginRoute, + ]), + history: createMemoryHistory({ initialEntries: ['/dashboard'] }), + }) + + return { + router, + dashboardRoute, + getSignal: () => capturedSignal, + getDeferredRequestAbortCount: () => deferredRequestAbortCount, + } +} + +describe('stay-match abort scope', () => { + test('unloading a reused match aborts the signal exposed to its loader', async () => { + const { router, getSignal, getDeferredRequestAbortCount } = setup() + + await router.load() + const dashboardLoaderSignal = getSignal() + + // Reusing the dashboard layout for a child must preserve the lifetime of + // its loader's deferred request. + await router.navigate({ to: '/dashboard/settings' }) + expect(dashboardLoaderSignal?.aborted).toBe(false) + expect(getDeferredRequestAbortCount()).toBe(0) + + // Leaving the layout altogether must now cancel that same request. + await router.navigate({ to: '/login' }) + expect(dashboardLoaderSignal?.aborted).toBe(true) + expect(getDeferredRequestAbortCount()).toBe(1) + }) + + test('background invalidation keeps the old loader signal until fresh data commits', async () => { + const reloadGate = createControlledPromise() + const { router, dashboardRoute, getSignal } = setup(reloadGate) + + await router.load() + const firstSignal = getSignal() + expect(firstSignal?.aborted).toBe(false) + + const invalidation = router.invalidate() + await vi.waitFor(() => expect(getSignal()).not.toBe(firstSignal)) + const replacementSignal = getSignal() + + // The old loader data is still the published generation while the + // background replacement is private. + expect(firstSignal?.aborted).toBe(false) + expect(replacementSignal?.aborted).toBe(false) + + reloadGate.resolve() + await invalidation + await vi.waitFor(() => expect(firstSignal?.aborted).toBe(true)) + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: dashboardRoute.id, + status: 'success', + }) + expect(replacementSignal?.aborted).toBe(false) + }) + + test.each(['beforeLoad', 'shouldReload'] as const)( + '%s failure replacing a successful stay aborts its loader signal', + async (failureStage) => { + const failure = new Error(`${failureStage} failed`) + const onAbort = vi.fn() + let shouldFail = false + let loaderSignal: AbortSignal | undefined + + const rootRoute = new BaseRootRoute({}) + const accountRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/account', + staleTime: Infinity, + beforeLoad: () => { + if (shouldFail && failureStage === 'beforeLoad') { + throw failure + } + }, + shouldReload: () => { + if (shouldFail && failureStage === 'shouldReload') { + throw failure + } + return false + }, + loader: ({ abortController }: { abortController: AbortController }) => { + loaderSignal = abortController.signal + loaderSignal.addEventListener('abort', onAbort, { once: true }) + return { user: 'Flo' } + }, + errorComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([accountRoute]), + history: createMemoryHistory({ initialEntries: ['/account'] }), + }) + + await router.load() + expect(loaderSignal?.aborted).toBe(false) + + shouldFail = true + await router.load() + + const match = router.state.matches.find( + (candidate) => candidate.routeId === accountRoute.id, + ) + expect(match?.status).toBe('error') + expect(match?.error).toBe(failure) + expect(loaderSignal?.aborted).toBe(true) + expect(onAbort).toHaveBeenCalledTimes(1) + }, + ) + + test('background notFound replacing successful data aborts its old loader signal', async () => { + let loaderCalls = 0 + let initialSignal: AbortSignal | undefined + + const rootRoute = new BaseRootRoute({}) + const accountRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/account', + staleTime: Infinity, + loader: ({ abortController }: { abortController: AbortController }) => { + loaderCalls++ + if (loaderCalls === 1) { + initialSignal = abortController.signal + return { user: 'Flo' } + } + throw notFound() + }, + notFoundComponent: () => null, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([accountRoute]), + history: createMemoryHistory({ initialEntries: ['/account'] }), + }) + + await router.load() + expect(initialSignal?.aborted).toBe(false) + + await router.invalidate() + await vi.waitFor(() => + expect(router.state.matches.at(-1)?.status).toBe('notFound'), + ) + expect(initialSignal?.aborted).toBe(true) + }) + + test('decorative background asset failure still transfers loader signal ownership', async () => { + vi.spyOn(console, 'error').mockImplementation(() => undefined) + let loaderCalls = 0 + const loaderSignals: Array = [] + + const rootRoute = new BaseRootRoute({}) + const accountRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/account', + staleTime: Infinity, + loader: ({ abortController }: { abortController: AbortController }) => { + loaderSignals.push(abortController.signal) + return { revision: ++loaderCalls } + }, + head: ({ loaderData }) => { + if (loaderData?.revision === 2) { + throw new Error('fresh head failed') + } + return { meta: [{ title: 'account' }] } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([accountRoute]), + history: createMemoryHistory({ initialEntries: ['/account'] }), + }) + + await router.load() + await router.invalidate() + + expect(router.state.matches.at(-1)?.loaderData).toEqual({ revision: 2 }) + expect(loaderSignals).toHaveLength(2) + expect(loaderSignals[0]?.aborted).toBe(true) + expect(loaderSignals[1]?.aborted).toBe(false) + }) +}) diff --git a/packages/router-core/tests/superseded-load-await.test.ts b/packages/router-core/tests/superseded-load-await.test.ts new file mode 100644 index 0000000000..38fe3115c4 --- /dev/null +++ b/packages/router-core/tests/superseded-load-await.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, createControlledPromise } from '../src' +import { createTestRouter } from './routerTestUtils' + +/** + * Awaiting router.load() should remain a reliable synchronization point even + * when that load is superseded. If the abandoned load resolves immediately, + * callers can observe router state before the newer load has settled. + * + * This test starts a real public router.load() for /one, supersedes it with a + * real navigation to /two, and resolves only the abandoned /one loader. The + * original await should not settle until the superseding /two loader settles. + */ + +const waitForMacrotask = () => + new Promise((resolve) => { + setTimeout(resolve, 0) + }) + +describe('superseded load await', () => { + test('router.load waits for a superseding navigation load to settle', async () => { + const firstLoaderGate = createControlledPromise() + const secondLoaderGate = createControlledPromise() + let firstLoaderCalls = 0 + let secondLoaderCalls = 0 + let secondLoaderSettled = false + let supersededLoadSettled = false + + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const firstRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/one', + loader: async () => { + firstLoaderCalls++ + await firstLoaderGate + return 'one' + }, + }) + const secondRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/two', + loader: async () => { + secondLoaderCalls++ + await secondLoaderGate + secondLoaderSettled = true + return 'two' + }, + }) + + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, firstRoute, secondRoute]), + history, + }) + + await router.load() + + history.push('/one') + const supersededLoad = router.load().then(() => { + supersededLoadSettled = true + }) + await vi.waitFor(() => expect(firstLoaderCalls).toBe(1)) + + const latestNavigation = router.navigate({ to: '/two' }) + await vi.waitFor(() => expect(secondLoaderCalls).toBe(1)) + + firstLoaderGate.resolve() + await waitForMacrotask() + + expect(secondLoaderSettled).toBe(false) + expect(supersededLoadSettled).toBe(false) + + secondLoaderGate.resolve() + await Promise.all([supersededLoad, latestNavigation]) + + expect(secondLoaderSettled).toBe(true) + expect(supersededLoadSettled).toBe(true) + expect(router.state.location.pathname).toBe('/two') + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: secondRoute.id, + status: 'success', + loaderData: 'two', + }) + }) +}) diff --git a/packages/router-core/tests/transformStreamBackpressure.perf.test.ts b/packages/router-core/tests/transformStreamBackpressure.perf.test.ts new file mode 100644 index 0000000000..12531988c0 --- /dev/null +++ b/packages/router-core/tests/transformStreamBackpressure.perf.test.ts @@ -0,0 +1,264 @@ +// On-demand backpressure test for transformReadableStreamWithRouter. +// +// NOT run in CI by default. To execute: +// RUN_BACKPRESSURE_PERF=1 pnpm --filter @tanstack/router-core test:unit -- transformStreamBackpressure +// +// Validates fix for TanStack/router#7402 +// without a backpressure gate the read loop in +// transformReadableStreamWithRouter calls controller.enqueue unconditionally, +// allowing controller.[[queue]] to accumulate Uint8Array chunks (external +// memory) when the consumer drains slower than the producer. +import { describe, expect, it } from 'vitest' +import { + HYDRATION_SCRIPT_BOUNDARY_BYTES, + HydrationScriptOutputState, +} from '../src/ssr/hydrationScripts' +import { transformReadableStreamWithRouter } from '../src/ssr/transformStreamWithRouter' +import type { HydrationScriptOutput } from '../src/ssr/hydrationScripts' + +const enabled = process.env.RUN_BACKPRESSURE_PERF === '1' +const requiresGc = typeof (globalThis as any).gc === 'function' +const SCRIPT_BARRIER_HTML = `'.length)}` + +function createFastProducer( + chunkCount: number, + chunkBytes: number, + opts: { freshChunks?: boolean } = {}, +) { + let pulls = 0 + let produced = 0 + const reusable = opts.freshChunks + ? null + : new Uint8Array(chunkBytes).fill(0x61) + const stream = new ReadableStream({ + pull(controller) { + pulls++ + if (produced >= chunkCount) { + controller.close() + return + } + produced++ + // Fresh allocation for external-memory tests: reusing one Uint8Array + // means the upstream queue never actually retains additional native + // memory even if our transform held arbitrarily many references. + controller.enqueue( + opts.freshChunks ? new Uint8Array(chunkBytes).fill(0x61) : reusable!, + ) + }, + }) + return { + stream, + getPulls: () => pulls, + getProduced: () => produced, + } +} + +function makeRouter() { + const output: HydrationScriptOutput = { + state: HydrationScriptOutputState.Done, + error: undefined, + pullChunk() { + throw new Error('Finished hydration output cannot be pulled') + }, + subscribe() { + return () => {} + }, + } + return { + serverSsr: { + hydrationScripts: { + reserveFastPath: () => true, + claimOutput: () => output, + liftBarrier: () => {}, + isInitialTaken: () => true, + startSerializationTimeout: () => {}, + }, + setRenderFinished: () => {}, + onCleanup: () => {}, + cleanup: () => {}, + }, + } as any +} + +// Main-path router fake: serialization NOT finished synchronously, so the +// transform runs the full scanner + script merger path. Exposes hooks to +// emit router script batches and signal serialization finished. +function makeMainPathRouter(): { + router: any + finishSerialization: () => void +} { + let state: HydrationScriptOutput['state'] = HydrationScriptOutputState.Waiting + let listener: (() => void) | undefined + const output: HydrationScriptOutput = { + get state() { + return state + }, + error: undefined, + pullChunk() { + throw new Error('No hydration output is ready') + }, + subscribe(onChange) { + listener = onChange + return () => { + if (listener === onChange) { + listener = undefined + } + } + }, + } + const router: any = { + serverSsr: { + hydrationScripts: { + reserveFastPath: () => false, + claimOutput: () => output, + liftBarrier: () => {}, + isInitialTaken: () => true, + startSerializationTimeout: () => {}, + }, + setRenderFinished: () => {}, + onCleanup: () => {}, + cleanup: () => {}, + }, + } + return { + router, + finishSerialization: () => { + state = HydrationScriptOutputState.Done + listener?.() + }, + } +} + +describe.runIf(enabled)( + 'transformReadableStreamWithRouter backpressure', + () => { + it('does not run producer arbitrarily ahead of slow consumer', async () => { + const CHUNKS = 200 + const CHUNK_BYTES = 8 * 1024 // 8KB per chunk + const producer = createFastProducer(CHUNKS, CHUNK_BYTES) + const router = makeRouter() + + const out = transformReadableStreamWithRouter(router, producer.stream) + + const reader = out.getReader() + let consumed = 0 + let maxLead = 0 + for (;;) { + // Throttled consumer: ~5ms per chunk. + await new Promise((r) => setTimeout(r, 5)) + const { done } = await reader.read() + if (done) { + break + } + consumed++ + const lead = producer.getProduced() - consumed + if (lead > maxLead) { + maxLead = lead + } + } + + // Producer should never be more than a small constant number of chunks + // ahead of the consumer. ReadableStream default HWM is 1 for byte + // streams; allow generous slack for scheduling jitter. + expect(maxLead).toBeLessThanOrEqual(8) + expect(consumed).toBe(CHUNKS) + }) + + it('bounded external memory under sustained load', async () => { + expect(requiresGc, 'Run with node --expose-gc').toBe(true) + const CHUNKS = 1000 + const CHUNK_BYTES = 16 * 1024 + const producer = createFastProducer(CHUNKS, CHUNK_BYTES, { + freshChunks: true, + }) + const router = makeRouter() + + const out = transformReadableStreamWithRouter(router, producer.stream) + const reader = out.getReader() + + ;(globalThis as any).gc() + ;(globalThis as any).gc() + let consumed = 0 + let peakExternal = 0 + const baseline = process.memoryUsage().external + for (;;) { + await new Promise((r) => setTimeout(r, 2)) + const { done } = await reader.read() + if (done) { + break + } + consumed++ + if (consumed % 50 === 0) { + ;(globalThis as any).gc() + const ext = process.memoryUsage().external - baseline + if (ext > peakExternal) { + peakExternal = ext + } + } + } + + // Without backpressure, peak external memory scales w/ CHUNKS*CHUNK_BYTES + // (~16MB). With backpressure, only a few chunks worth. + expect(peakExternal).toBeLessThan(2 * 1024 * 1024) // 2MB ceiling + expect(consumed).toBe(CHUNKS) + }) + + it('main path: scanner+inject path also honors backpressure', async () => { + // Same shape as fast-path test but with a router that forces the + // scanner+inject code path. Producer emits valid HTML fragments + // (ending at closing tags) so the scanner can release them. + const CHUNKS = 200 + const CHUNK_BYTES = 8 * 1024 + const filler = 'a'.repeat(CHUNK_BYTES - '

    '.length) + const chunkStr = `

    ${filler}

    ` + const encoded = new TextEncoder().encode(chunkStr) + const firstFiller = 'a'.repeat( + CHUNK_BYTES - '

    '.length - SCRIPT_BARRIER_HTML.length, + ) + const firstEncoded = new TextEncoder().encode( + `

    ${firstFiller}${SCRIPT_BARRIER_HTML}

    `, + ) + + let produced = 0 + const stream = new ReadableStream({ + pull(controller) { + if (produced >= CHUNKS) { + controller.close() + return + } + produced++ + controller.enqueue(produced === 1 ? firstEncoded : encoded) + }, + }) + + const { router, finishSerialization } = makeMainPathRouter() + const out = transformReadableStreamWithRouter(router, stream) + // Mark serialization finished immediately so tryFinish() proceeds once + // upstream closes. + finishSerialization() + + const reader = out.getReader() + let consumed = 0 + let bytes = 0 + let maxLead = 0 + for (;;) { + await new Promise((r) => setTimeout(r, 5)) + const { done, value } = await reader.read() + if (done) { + break + } + consumed++ + bytes += value.byteLength + const lead = produced - consumed + if (lead > maxLead) { + maxLead = lead + } + } + + expect(maxLead).toBeLessThanOrEqual(8) + // The merger splits the first renderer record at the router boundary. + expect(consumed).toBe(CHUNKS + 1) + expect(bytes).toBe(CHUNKS * encoded.byteLength) + }) + }, +) diff --git a/packages/router-core/tests/transformStreamWithRouter.test.ts b/packages/router-core/tests/transformStreamWithRouter.test.ts new file mode 100644 index 0000000000..e5ce1d8d50 --- /dev/null +++ b/packages/router-core/tests/transformStreamWithRouter.test.ts @@ -0,0 +1,2877 @@ +// CI-stable tests for transformReadableStreamWithRouter behavior. +// +// These exercise the deterministic side-effects of the SSR memory fix +// (TanStack/router#7402) without relying on GC, timing of real I/O, or +// process.memoryUsage(). On-demand backpressure/external-memory +// assertions live in transformStreamBackpressure.perf.test.ts. +import { PassThrough, Readable } from 'node:stream' +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { GLOBAL_TSR } from '../src/ssr/constants' +import { + HYDRATION_SCRIPT_BOUNDARY_BYTES, + HydrationScriptOutputState, + MAX_HYDRATION_OUTPUT_CHUNK_BYTES, +} from '../src/ssr/hydrationScripts' +import { + createSsrStreamResponse, + replaceSsrResponse, +} from '../src/ssr/handlerCallback' +import { attachRouterServerSsrUtils } from '../src/ssr/ssr-server' +import { + transformHtmlStringWithRouter, + transformPipeableStreamWithRouter, + transformReadableStreamWithRouter, +} from '../src/ssr/transformStreamWithRouter' +import { + DOCUMENT_CLOSE_BYTES, + SCRIPT_CLOSE, +} from '../src/ssr/htmlBoundaryScanner' +import { createTestRouter } from './routerTestUtils' +import type { RouterManagedTag } from '../src/manifest' +import type { HydrationScriptOutput } from '../src/ssr/hydrationScripts' + +const decoder = new TextDecoder() +const DOCUMENT_CLOSE = decoder.decode(DOCUMENT_CLOSE_BYTES) +const HYDRATION_SCRIPT_BOUNDARY_SUFFIX = decoder.decode( + HYDRATION_SCRIPT_BOUNDARY_BYTES, +) +const HYDRATION_SCRIPT_BOUNDARY_SOURCE = + `document.currentScript.remove()` + + HYDRATION_SCRIPT_BOUNDARY_SUFFIX.slice(0, -SCRIPT_CLOSE.length) +const SCRIPT_BARRIER_HTML = `` + +function internalSplitOffsets(value: string) { + return Array.from({ length: value.length - 1 }, (_, index) => index + 1) +} + +type FakeHydrationScripts = { + reserveFastPath: (output?: HydrationScriptOutput) => boolean + claimOutput: () => HydrationScriptOutput + liftBarrier: () => void + isInitialTaken: () => boolean + startSerializationTimeout: (timeoutMs: number) => void +} + +type FakeServerSsr = { + hydrationScripts: FakeHydrationScripts + setRenderFinished: () => void + onCleanup: (listener: () => void) => void + cleanup: () => void +} + +type MakeRouterOptions = Partial> & + Partial + +type FakeRouter = { + serverSsr?: FakeServerSsr +} + +type FakeHydrationRecord = { + bytes: Uint8Array + offset: number +} + +function makeRouter(opts: MakeRouterOptions = {}): { + router: FakeRouter + cleanupCalls: { count: number } + claimCalls: { count: number } + emitHydrationRecord: (record: string) => void + emitScriptBatch: (parts: ReadonlyArray) => void + finishSerialization: () => void + failHydrationOutput: (error: unknown) => void +} { + const cleanupCalls = { count: 0 } + const claimCalls = { count: 0 } + const cleanupListeners: Array<() => void> = [] + let cleanedUp = false + let producerDone = false + let claimed = false + let failure: unknown + let activeRecord: FakeHydrationRecord | undefined + const records: Array = [] + let listener: (() => void) | undefined + let state: HydrationScriptOutput['state'] = HydrationScriptOutputState.Waiting + let serializationTimeout: ReturnType | undefined + const encoder = new TextEncoder() + + function updateState() { + const nextState = + failure !== undefined + ? HydrationScriptOutputState.Failed + : activeRecord + ? HydrationScriptOutputState.Active + : records.length > 0 + ? HydrationScriptOutputState.Ready + : producerDone + ? HydrationScriptOutputState.Done + : HydrationScriptOutputState.Waiting + if (state !== nextState) { + state = nextState + listener?.() + } + } + + const output: HydrationScriptOutput = { + get state() { + return state + }, + get error() { + return failure + }, + pullChunk() { + if (state === HydrationScriptOutputState.Ready) { + activeRecord = records.shift()! + } else if (state !== HydrationScriptOutputState.Active) { + throw new Error('Fake hydration output is not ready') + } + + const record = activeRecord! + const end = Math.min( + record.offset + MAX_HYDRATION_OUTPUT_CHUNK_BYTES, + record.bytes.length, + ) + const chunk = record.bytes.subarray(record.offset, end) + record.offset = end + if (end === record.bytes.length) { + activeRecord = undefined + } + updateState() + return chunk + }, + subscribe(onChange) { + if (listener) { + throw new Error('Fake hydration output already has a subscriber') + } + listener = onChange + return () => { + if (listener === onChange) { + listener = undefined + } + } + }, + } + + const { + reserveFastPath = () => false, + claimOutput = () => { + claimCalls.count++ + if (claimed) { + throw new Error('Fake hydration output already has a consumer') + } + claimed = true + return output + }, + liftBarrier = () => {}, + isInitialTaken = () => true, + startSerializationTimeout = (timeoutMs: number) => { + if ( + producerDone || + failure !== undefined || + serializationTimeout !== undefined + ) { + return + } + serializationTimeout = setTimeout(() => { + serializationTimeout = undefined + failure = new Error('Serialization timeout after app render finished') + console.error('Serialization timeout after app render finished') + updateState() + }, timeoutMs) + }, + ...serverSsrOverrides + } = opts + + const router: FakeRouter = { + serverSsr: { + hydrationScripts: { + reserveFastPath, + claimOutput, + liftBarrier, + isInitialTaken, + startSerializationTimeout, + }, + setRenderFinished: () => {}, + onCleanup: (cleanupListener: () => void) => { + if (cleanedUp) { + return + } + cleanupListeners.push(cleanupListener) + }, + cleanup: () => { + if (cleanedUp) { + return + } + cleanedUp = true + cleanupCalls.count++ + if (serializationTimeout !== undefined) { + clearTimeout(serializationTimeout) + serializationTimeout = undefined + } + records.length = 0 + activeRecord = undefined + failure = undefined + listener = undefined + state = HydrationScriptOutputState.Done + // Mirror the real implementation: snapshot + clear, then notify. + const pendingCleanupListeners = cleanupListeners.slice() + cleanupListeners.length = 0 + for (const cleanupListener of pendingCleanupListeners) { + cleanupListener() + } + router.serverSsr = undefined + }, + ...serverSsrOverrides, + }, + } + + function emitHydrationRecord(record: string) { + records.push({ + bytes: encoder.encode(record), + offset: 0, + }) + updateState() + } + + return { + router, + cleanupCalls, + claimCalls, + emitHydrationRecord, + emitScriptBatch: (parts) => emitHydrationRecord(renderScriptBatch(parts)), + finishSerialization: () => { + producerDone = true + if (serializationTimeout !== undefined) { + clearTimeout(serializationTimeout) + serializationTimeout = undefined + } + updateState() + }, + failHydrationOutput: (error) => { + failure = error + updateState() + }, + } +} + +function makeManualUpstream(): { + stream: ReadableStream + push: (s: string) => void + close: () => void + error: (reason: unknown) => void + cancelled: { value: boolean; reason: unknown } +} { + let controllerRef: ReadableStreamDefaultController | undefined + const cancelled = { value: false, reason: undefined as unknown } + const encoder = new TextEncoder() + const stream = new ReadableStream({ + start(c) { + controllerRef = c + }, + cancel(reason) { + cancelled.value = true + cancelled.reason = reason + }, + }) + return { + stream, + push: (s) => controllerRef!.enqueue(encoder.encode(s)), + close: () => controllerRef!.close(), + error: (reason) => controllerRef!.error(reason), + cancelled, + } +} + +async function readAll(s: ReadableStream): Promise { + const reader = s.getReader() + const decoder = new TextDecoder() + let out = '' + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + out += decoder.decode(value, { stream: true }) + } + return out + decoder.decode() +} + +async function readAllBytes( + stream: ReadableStream, +): Promise { + const reader = stream.getReader() + const chunks: Array = [] + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + chunks.push(Buffer.from(value)) + } + return Buffer.concat(chunks) +} + +async function readAllPipeableChunks(stream: Readable): Promise> { + const chunks: Array = [] + for await (const chunk of stream) { + chunks.push(Buffer.from(chunk)) + } + return chunks +} + +async function readAllPipeableBytes(stream: Readable): Promise { + return Buffer.concat(await readAllPipeableChunks(stream)) +} + +function makeLargeStringRecord(prefix: string, suffix: string) { + return ( + prefix + + 'x'.repeat( + MAX_HYDRATION_OUTPUT_CHUNK_BYTES - 1 - Buffer.byteLength(prefix), + ) + + '😀' + + '漢x'.repeat(20_000) + + suffix + ) +} + +// Yield to the microtask queue a few times so async stream operations can +// drain. Avoids reliance on real timers. +async function flush(n = 5) { + for (let i = 0; i < n; i++) { + await Promise.resolve() + } +} + +function createIssuePayload() { + return 'x'.repeat(17 * 1024 * 1024) +} + +function createDeferred() { + let resolve!: (value: T) => void + let reject!: (reason?: unknown) => void + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return { promise, resolve, reject } +} + +function createControlledStream() { + let controller!: ReadableStreamDefaultController + const stream = new ReadableStream({ + start(c) { + controller = c + }, + }) + return { stream, controller } +} + +function renderManagedScript(tag: RouterManagedTag) { + const attrs = tag.attrs ?? {} + const id = attrs.id ? ` id="${attrs.id}"` : '' + const className = attrs.className ? ` class="${attrs.className}"` : '' + const nonce = attrs.nonce ? ` nonce="${attrs.nonce}"` : '' + const streamPart = + 'data-tsr-stream-part' in attrs ? ' data-tsr-stream-part=""' : '' + return `${tag.children ?? ''}` +} + +function renderManagedScripts(tags: Array) { + return tags.map(renderManagedScript).join('') +} + +function renderInitialScripts(scripts: { + before: Array + boundary: RouterManagedTag +}) { + return renderManagedScripts([...scripts.before, scripts.boundary]) +} + +function renderScriptBatch(parts: ReadonlyArray) { + return `` +} + +function createRealSsrRouter(dehydratedData: Record) { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => null, + }) + + return createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + dehydrate: () => dehydratedData, + }) +} + +describe('transformReadableStreamWithRouter — real SSR scripts', () => { + test('uses pass-through after Scripts takes all eager hydration scripts', async () => { + const router = createRealSsrRouter({ eager: 'loader-data' }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + + // This is the server-side work performed by during rendering. + const initialScripts = router.serverSsr!.takeInitialHydrationScriptTags() + expect(initialScripts).toBeDefined() + + const serverSsr = router.serverSsr! + const setRenderFinished = vi.spyOn(serverSsr, 'setRenderFinished') + const upstream = makeManualUpstream() + const html = `
    app
    ${renderInitialScripts( + initialScripts!, + )}` + + const output = transformReadableStreamWithRouter(router, upstream.stream) + + // Pass-through reservation must not require render completion in advance. + expect(setRenderFinished).not.toHaveBeenCalled() + upstream.push(html) + upstream.close() + + await expect(readAll(output)).resolves.toBe(html) + expect(setRenderFinished).toHaveBeenCalledOnce() + expect(router.serverSsr).toBeUndefined() + }) + + test('flushes stream-end scripts before body close when serialization finishes before transform starts', async () => { + const streamed = createDeferred() + const router = createRealSsrRouter({ streamed: streamed.promise }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + + const initialScripts = router.serverSsr!.takeInitialHydrationScriptTags() + expect(initialScripts).toBeDefined() + const barrierScript = initialScripts!.boundary + expect(barrierScript.attrs).not.toHaveProperty('id') + expect(barrierScript).toBeDefined() + const initialHtml = renderInitialScripts(initialScripts!) + expect(initialHtml).toContain(`${GLOBAL_TSR}.router=`) + expect(initialHtml).not.toContain(`${GLOBAL_TSR}.e()`) + + streamed.resolve('done') + await flush(20) + + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + upstream.push(`
    app
    ${initialHtml}`) + upstream.close() + + const html = await readAll(output as any) + + expect(html).toContain(`${GLOBAL_TSR}.router=`) + expect(html).toContain(`${GLOBAL_TSR}.e()`) + expect(html.indexOf(`${GLOBAL_TSR}.e()`)).toBeLessThan( + html.indexOf(''), + ) + }) + + test('fuses the final resolver and stream-end scripts', async () => { + const streamed = createControlledStream() + const router = createRealSsrRouter({ streamed: streamed.stream }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + + const initialScripts = router.serverSsr!.takeInitialHydrationScriptTags() + expect(initialScripts).toBeDefined() + + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + upstream.push( + `
    app
    ${renderInitialScripts( + initialScripts!, + )}`, + ) + + streamed.controller.close() + await flush(20) + upstream.close() + + const html = await readAll(output as any) + const resolverIndex = html.indexOf('.return(void 0)') + const endIndex = html.indexOf(`${GLOBAL_TSR}.e()`) + + expect(resolverIndex).toBeGreaterThan(-1) + expect(endIndex).toBeGreaterThan(resolverIndex) + expect(html.slice(resolverIndex, endIndex)).not.toContain('') + expect(endIndex).toBeLessThan(html.indexOf('')) + }) + + test.each([ + ['completes', false], + ['is cancelled before the payload finishes', true], + ] as const)( + 'loader controllers are aborted only when the response %s', + async (_name, cancelled) => { + let loaderSignal: AbortSignal | undefined + const deferred = createDeferred() + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => null, + loader: ({ abortController }) => { + loaderSignal = abortController.signal + return { deferred: deferred.promise } + }, + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + await router.load() + await router.serverSsr!.dehydrate() + const initialScripts = router.serverSsr!.takeInitialHydrationScriptTags()! + + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter(router, upstream.stream) + upstream.push( + `${renderInitialScripts(initialScripts)}`, + ) + upstream.close() + expect(loaderSignal?.aborted).toBe(false) + + if (cancelled) { + await output.cancel(new Error('client gone')) + } else { + deferred.resolve('late') + await readAll(output as any) + } + + expect(router.serverSsr).toBeUndefined() + expect(loaderSignal?.aborted).toBe(cancelled) + }, + ) + + test('emits router scripts after the document when no Scripts barrier was rendered', async () => { + const streamed = createDeferred() + const router = createRealSsrRouter({ streamed: streamed.promise }) + attachRouterServerSsrUtils({ router, manifest: undefined }) + + await router.load() + await router.serverSsr!.dehydrate() + + streamed.resolve('done') + await flush(20) + + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + upstream.push('
    app
    ') + upstream.close() + + const html = await readAll(output as any) + const documentEnd = html.indexOf('') + ''.length + expect(html.slice(0, documentEnd)).toBe( + '
    app
    ', + ) + const tail = html.slice(documentEnd) + expect(tail).toContain(`${GLOBAL_TSR}.router=`) + expect(tail).toContain(`${GLOBAL_TSR}.e()`) + expect(tail).toMatch(/<\/script>$/) + expect(router.serverSsr).toBeUndefined() + }) + + test('detects a barrier marker split across chunks', async () => { + let liftCalls = 0 + const { router, finishSerialization } = makeRouter({ + liftBarrier: () => { + liftCalls++ + }, + }) + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const markerStart = SCRIPT_BARRIER_HTML.indexOf( + HYDRATION_SCRIPT_BOUNDARY_SUFFIX, + ) + const splitAt = + markerStart + Math.floor(HYDRATION_SCRIPT_BOUNDARY_SUFFIX.length / 2) + + upstream.push(`${SCRIPT_BARRIER_HTML.slice(0, splitAt)}`) + upstream.push(`${SCRIPT_BARRIER_HTML.slice(splitAt)}
    app
    `) + upstream.push('') + upstream.close() + finishSerialization() + + await readAll(output as any) + expect(liftCalls).toBe(1) + }) + + test('does not inject stream scripts inside a split barrier script', async () => { + const { router, emitScriptBatch, finishSerialization } = makeRouter({ + liftBarrier: () => { + emitScriptBatch(['streamed()']) + }, + }) + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + + const splitAt = + SCRIPT_BARRIER_HTML.indexOf(HYDRATION_SCRIPT_BOUNDARY_SUFFIX) + 4 + upstream.push( + `
    app
    ${SCRIPT_BARRIER_HTML.slice(0, splitAt)}`, + ) + upstream.push( + `${SCRIPT_BARRIER_HTML.slice(splitAt)}
    after
    `, + ) + finishSerialization() + upstream.push('') + upstream.close() + + const html = await readAll(output as any) + + expect(html.indexOf(renderScriptBatch(['streamed()']))).toBeGreaterThan( + html.indexOf(SCRIPT_BARRIER_HTML), + ) + expect(html.indexOf(renderScriptBatch(['streamed()']))).toBeLessThan( + html.indexOf('
    after
    '), + ) + expect(html.indexOf(renderScriptBatch(['streamed()']))).toBeLessThan( + html.indexOf(''), + ) + }) + + test('uses a complete renderer record as an insertion boundary', async () => { + const { router, emitScriptBatch, finishSerialization } = makeRouter() + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { + rendererSafePoint: 'record-end', + }, + ) + const reader = output.getReader() + const decoder = new TextDecoder() + let html = '' + + const rendererRecord = 'content' + upstream.push(`${SCRIPT_BARRIER_HTML}${rendererRecord}`) + for (let index = 0; index < 2; index++) { + const { value } = await reader.read() + html += decoder.decode(value, { stream: true }) + } + + emitScriptBatch(['streamed()']) + upstream.push('
    after
    ') + upstream.close() + finishSerialization() + + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + html += decoder.decode(value, { stream: true }) + } + html += decoder.decode() + + expect(html).toBe( + `${SCRIPT_BARRIER_HTML}${rendererRecord}${renderScriptBatch([ + 'streamed()', + ])}
    after
    `, + ) + }) + + test('does not split a held document close at a record-end safe point', async () => { + const { router, emitScriptBatch, finishSerialization } = makeRouter() + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { + rendererSafePoint: 'record-end', + }, + ) + const reader = output.getReader() + const splitAt = 5 + const prefix = `${SCRIPT_BARRIER_HTML}` + + upstream.push(prefix + DOCUMENT_CLOSE.slice(0, splitAt)) + expect(Buffer.from((await reader.read()).value!).toString()).toBe(prefix) + + const nextRead = reader.read() + await flush() + emitScriptBatch(['streamed()']) + upstream.push(DOCUMENT_CLOSE.slice(splitAt)) + finishSerialization() + upstream.close() + + const chunks = [(await nextRead).value!] + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + chunks.push(value) + } + + expect( + Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString(), + ).toBe(renderScriptBatch(['streamed()']) + DOCUMENT_CLOSE) + }) + + test('conservative mode waits for EOF instead of using record ends', async () => { + const { router, emitScriptBatch, finishSerialization } = makeRouter() + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const reader = output.getReader() + + upstream.push(`${SCRIPT_BARRIER_HTML}
    first
    `) + expect(Buffer.from((await reader.read()).value!).toString()).toBe( + SCRIPT_BARRIER_HTML, + ) + expect(Buffer.from((await reader.read()).value!).toString()).toBe( + '
    first
    ', + ) + + emitScriptBatch(['streamed()']) + upstream.push('
    second
    ') + expect(Buffer.from((await reader.read()).value!).toString()).toBe( + '
    second
    ', + ) + + let pendingReadSettled = false + const pendingRead = reader.read().then((result) => { + pendingReadSettled = true + return result + }) + await flush() + expect(pendingReadSettled).toBe(false) + + finishSerialization() + upstream.close() + expect(Buffer.from((await pendingRead).value!).toString()).toBe( + renderScriptBatch(['streamed()']), + ) + expect((await reader.read()).done).toBe(true) + }) +}) + +describe('transformReadableStreamWithRouter — cleanup side-effects', () => { + test('unrefs Node-style lifecycle timer handles', () => { + const nativeSetTimeout = globalThis.setTimeout + const { router } = makeRouter() + const upstream = makeManualUpstream() + const timerHandle = nativeSetTimeout(() => undefined, 60_000) + const unref = vi.spyOn(timerHandle, 'unref') + let output: ReadableStream | undefined + + vi.stubGlobal( + 'setTimeout', + ((_callback: () => void, _delay?: number) => + timerHandle) as typeof setTimeout, + ) + try { + output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + expect(unref).toHaveBeenCalledOnce() + } finally { + void output?.cancel() + router.serverSsr?.cleanup() + vi.stubGlobal('setTimeout', nativeSetTimeout) + clearTimeout(timerHandle) + unref.mockRestore() + } + }) + + test('supports runtimes whose timer handles are numeric', () => { + const nativeSetTimeout = globalThis.setTimeout + const nativeClearTimeout = globalThis.clearTimeout + const { router } = makeRouter() + const upstream = makeManualUpstream() + let output: ReadableStream | undefined + + vi.stubGlobal( + 'setTimeout', + ((_callback: () => void, _delay?: number) => 1) as typeof setTimeout, + ) + vi.stubGlobal( + 'clearTimeout', + ((_handle?: number) => undefined) as typeof clearTimeout, + ) + try { + expect(() => { + output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + }).not.toThrow() + } finally { + void output?.cancel() + router.serverSsr?.cleanup() + vi.stubGlobal('setTimeout', nativeSetTimeout) + vi.stubGlobal('clearTimeout', nativeClearTimeout) + } + }) + + test.each([ + ['fast', true], + ['merge', false], + ] as const)( + 'request abort cleans the %s path without consuming its response body', + async (_path, reserveStreamFastPath) => { + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => reserveStreamFastPath, + }) + const upstream = makeManualUpstream() + const request = new AbortController() + + const responseBody = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { + signal: request.signal, + }, + ) + + expect(responseBody.locked).toBe(false) + + const reason = new Error('request-gone') + request.abort(reason) + await flush() + + expect(responseBody.locked).toBe(false) + expect(upstream.cancelled).toEqual({ value: true, reason }) + expect(cleanupCalls.count).toBe(1) + }, + ) + + test('string rendering uses the eager pass-through path', async () => { + const setRenderFinished = vi.fn() + const { router, cleanupCalls, claimCalls } = makeRouter({ + reserveFastPath: () => true, + setRenderFinished, + }) + + await expect( + transformHtmlStringWithRouter( + router as any, + 'ready', + ), + ).resolves.toBe('ready') + expect(setRenderFinished).toHaveBeenCalledOnce() + expect(claimCalls.count).toBe(0) + expect(cleanupCalls.count).toBe(1) + }) + + test('string rendering drains merged output without Response byte buffering', async () => { + const { router, cleanupCalls, emitScriptBatch, finishSerialization } = + makeRouter() + const parts = ['streamed("hydration π 🚀")'] + emitScriptBatch(parts) + finishSerialization() + const responseText = vi + .spyOn(Response.prototype, 'text') + .mockRejectedValue(new Error('Response.text must not be used')) + + try { + const rendererHtml = makeLargeStringRecord( + '
    eager ', + `
    ${SCRIPT_BARRIER_HTML}`, + ) + expect(rendererHtml.indexOf('😀')).toBe( + MAX_HYDRATION_OUTPUT_CHUNK_BYTES - 1, + ) + await expect( + transformHtmlStringWithRouter(router as any, rendererHtml), + ).resolves.toBe( + '' + + rendererHtml.replace( + SCRIPT_BARRIER_HTML, + SCRIPT_BARRIER_HTML + renderScriptBatch(parts), + ), + ) + expect(responseText).not.toHaveBeenCalled() + expect(cleanupCalls.count).toBe(1) + } finally { + responseText.mockRestore() + } + }) + + test('byte-0 pass-through preserves renderer bytes after document closes', async () => { + const { router, cleanupCalls, claimCalls } = makeRouter({ + reserveFastPath: () => true, + }) + const upstream = createControlledStream() + const rendererBytes = new TextEncoder().encode( + 'shell', + ) + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + + upstream.controller.enqueue(rendererBytes) + upstream.controller.close() + + await expect(readAllBytes(output)).resolves.toEqual( + Buffer.from(rendererBytes), + ) + expect(claimCalls.count).toBe(0) + expect(cleanupCalls.count).toBe(1) + }) + + test('dynamic pass-through preserves renderer bytes after document closes', async () => { + let allowFastPath = false + let reserveCalls = 0 + const { router, cleanupCalls, claimCalls, finishSerialization } = + makeRouter({ + reserveFastPath: () => { + reserveCalls++ + return allowFastPath + }, + }) + finishSerialization() + const upstream = createControlledStream() + const encoder = new TextEncoder() + const prefix = '
    shell
    ' + const suffix = '' + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const reader = output.getReader() + + expect(reserveCalls).toBe(1) + allowFastPath = true + upstream.controller.enqueue(encoder.encode(prefix)) + expect(Buffer.from((await reader.read()).value!).toString()).toBe(prefix) + + // Finishing serialization alone cannot bypass the rendered boundary. + expect(reserveCalls).toBe(1) + upstream.controller.enqueue(encoder.encode(SCRIPT_BARRIER_HTML + suffix)) + expect(Buffer.from((await reader.read()).value!).toString()).toBe( + SCRIPT_BARRIER_HTML, + ) + expect(reserveCalls).toBe(1) + + // The next pull enters the scanner-free post-boundary pass-through phase. + expect(Buffer.from((await reader.read()).value!).toString()).toBe(suffix) + expect(reserveCalls).toBe(2) + expect(claimCalls.count).toBe(1) + upstream.controller.close() + + expect((await reader.read()).done).toBe(true) + expect(cleanupCalls.count).toBe(1) + }) + + test('generic streams wait for the document close before a late batch', async () => { + const { router, emitScriptBatch, cleanupCalls, finishSerialization } = + makeRouter() + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const reader = output.getReader() + const firstAppChunk = '
    first
    ' + + upstream.push(`${SCRIPT_BARRIER_HTML}${firstAppChunk}`) + const barrier = await reader.read() + const first = await reader.read() + expect(Buffer.from(barrier.value!).toString()).toBe(SCRIPT_BARRIER_HTML) + expect(Buffer.from(first.value!).toString()).toBe(firstAppChunk) + + const parts = ['lateBatch()'] + emitScriptBatch(parts) + upstream.push('next') + finishSerialization() + upstream.close() + + const remaining: Array = [] + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + remaining.push(value) + } + + expect( + Buffer.concat([barrier.value!, first.value!, ...remaining]).toString(), + ).toBe( + `${SCRIPT_BARRIER_HTML}${firstAppChunk}next${renderScriptBatch( + parts, + )}`, + ) + expect(cleanupCalls.count).toBe(1) + }) + + test.each([ + ['record-end safe points', { rendererSafePoint: 'record-end' }], + ['conservative safe points', undefined], + ] as const)( + '%s preserve a non-canonical document close when a batch arrives later', + async (_, options) => { + const { router, emitScriptBatch, cleanupCalls, finishSerialization } = + makeRouter() + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + options, + ) + const reader = output.getReader() + const rendererHtml = + `
    app
    ${SCRIPT_BARRIER_HTML}` + + '\n' + + upstream.push(rendererHtml) + let received = '' + while (received.length < rendererHtml.length) { + const result = await reader.read() + expect(result.done).toBe(false) + received += Buffer.from(result.value!).toString() + } + expect(received).toBe(rendererHtml) + + const parts = ['lateBatch()'] + emitScriptBatch(parts) + finishSerialization() + upstream.close() + + let remaining = '' + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + remaining += Buffer.from(value).toString() + } + + expect(received + remaining).toBe(rendererHtml + renderScriptBatch(parts)) + expect(cleanupCalls.count).toBe(1) + }, + ) + + test('an aborted request stops eager string rendering', async () => { + const reason = new Error('request aborted') + const abortController = new AbortController() + abortController.abort(reason) + const onAbort = vi.fn() + const setRenderFinished = vi.fn() + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => true, + setRenderFinished, + }) + + await expect( + transformHtmlStringWithRouter( + router as any, + 'ready', + { signal: abortController.signal, onAbort }, + ), + ).rejects.toBe(reason) + expect(setRenderFinished).not.toHaveBeenCalled() + expect(onAbort).toHaveBeenCalledOnce() + expect(onAbort).toHaveBeenCalledWith(reason) + expect(cleanupCalls.count).toBe(1) + }) + + test('a locked input stream fails synchronously and cleans SSR state', () => { + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => true, + }) + const upstream = new ReadableStream() + const upstreamReader = upstream.getReader() + const onAbort = vi.fn() + + expect(() => + transformReadableStreamWithRouter(router as any, upstream as any, { + onAbort, + }), + ).toThrow() + expect(onAbort).toHaveBeenCalledOnce() + expect(cleanupCalls.count).toBe(1) + + upstreamReader.releaseLock() + }) + + test('a setup failure cancels an acquired input stream', async () => { + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => { + throw new Error('setup failed') + }, + }) + const upstream = makeManualUpstream() + const onAbort = vi.fn() + + expect(() => + transformReadableStreamWithRouter(router as any, upstream.stream as any, { + onAbort, + }), + ).toThrow('setup failed') + await flush() + + expect(upstream.cancelled.value).toBe(true) + expect(onAbort).toHaveBeenCalledOnce() + expect(cleanupCalls.count).toBe(1) + }) + + test('a pre-aborted request fails setup before selecting a stream path', async () => { + const reserveFastPath = vi.fn(() => true) + const { router, cleanupCalls } = makeRouter({ reserveFastPath }) + const upstream = makeManualUpstream() + const requestAbort = new AbortController() + const reason = new Error('request already ended') + const onAbort = vi.fn() + requestAbort.abort(reason) + + expect(() => + transformReadableStreamWithRouter(router as any, upstream.stream as any, { + signal: requestAbort.signal, + onAbort, + }), + ).toThrow(reason) + await flush() + + expect(reserveFastPath).not.toHaveBeenCalled() + expect(upstream.cancelled).toEqual({ value: true, reason }) + expect(onAbort).toHaveBeenCalledOnce() + expect(cleanupCalls.count).toBe(1) + }) + + test('an already-failed hydration channel fails stream setup', async () => { + const state = makeRouter() + const upstream = makeManualUpstream() + const reason = new Error('hydration already failed') + const onAbort = vi.fn() + state.failHydrationOutput(reason) + + expect(() => + transformReadableStreamWithRouter( + state.router as any, + upstream.stream as any, + { + onAbort, + }, + ), + ).toThrow(reason) + await flush() + + expect(upstream.cancelled).toEqual({ value: true, reason }) + expect(onAbort).toHaveBeenCalledOnce() + expect(state.cleanupCalls.count).toBe(1) + }) + + test.each([ + ['fast', true], + ['merge', false], + ] as const)( + 'request abort immediately closes the %s path', + async (_, reserveFastPath) => { + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => reserveFastPath, + }) + const upstream = makeManualUpstream() + const requestAbort = new AbortController() + const onAbort = vi.fn() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { + signal: requestAbort.signal, + onAbort, + }, + ) + const reader = output.getReader() + const pendingRead = reader.read() + const reason = new Error('request ended') + + requestAbort.abort(reason) + + await expect(pendingRead).rejects.toBe(reason) + await flush() + expect(upstream.cancelled).toEqual({ value: true, reason }) + expect(onAbort).toHaveBeenCalledOnce() + expect(cleanupCalls.count).toBe(1) + }, + ) + + test('downstream cancel propagates upstream and calls serverSsr.cleanup once', async () => { + // Fast path: simpler, no scanner. Verifies cancel + cleanup contract. + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => true, + }) + const upstream = makeManualUpstream() + + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const reader = ( + out as any + ).getReader() as ReadableStreamDefaultReader + + // Cancel before any data flows. Should still trigger upstream cancel + // and exactly one cleanup invocation. + await reader.cancel('consumer-gone') + await flush() + + expect(upstream.cancelled.value).toBe(true) + expect(cleanupCalls.count).toBe(1) + }) + + test('downstream cancel releases the upstream reader while cancellation settles', async () => { + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => true, + }) + + let resolveCancel!: () => void + const upstream = new ReadableStream({ + pull() { + // Keep the transform's upstream read pending until cancellation. + }, + cancel() { + return new Promise((resolve) => { + resolveCancel = resolve + }) + }, + }) + + const out = transformReadableStreamWithRouter( + router as any, + upstream as any, + ) + const reader = ( + out as any + ).getReader() as ReadableStreamDefaultReader + + let cancelSettled = false + const cancelPromise = reader.cancel('consumer-gone').then(() => { + cancelSettled = true + }) + + await flush() + expect(cancelSettled).toBe(false) + expect(upstream.locked).toBe(false) + expect(cleanupCalls.count).toBe(1) + + resolveCancel() + await cancelPromise + expect(cancelSettled).toBe(true) + }) + + test('stream response metadata defers cleanup until body drains', async () => { + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => true, + }) + const upstream = makeManualUpstream() + + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const response = new Response(out as any) + const result = createSsrStreamResponse(router as any, response) + + expect(result.serverSsrCleanup).toBe('stream') + expect(cleanupCalls.count).toBe(0) + + upstream.push('done') + upstream.close() + + await result.response.text() + expect(cleanupCalls.count).toBe(1) + }) + + test('stream response dispose cancels body and cleans once', async () => { + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => true, + }) + const upstream = makeManualUpstream() + + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const result = createSsrStreamResponse( + router as any, + new Response(out as any), + ) + expect(result.serverSsrCleanup).toBe('stream') + + await result.dispose('dropped') + await result.dispose('dropped-again') + + expect(upstream.cancelled.value).toBe(true) + expect(cleanupCalls.count).toBe(1) + }) + + test('stream response replacement does not wait for cancellation', async () => { + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => true, + }) + let cancelCalls = 0 + const stream = new ReadableStream({ + cancel() { + cancelCalls++ + return new Promise(() => {}) + }, + }) + const result = createSsrStreamResponse( + router as any, + new Response(stream as any), + ) + const replacement = new Response('replacement') + + const next = replaceSsrResponse(result, replacement, 'replaced') + + expect(next.response).toBe(replacement) + expect(cancelCalls).toBe(1) + expect(cleanupCalls.count).toBe(1) + }) + + test('external serverSsr cleanup releases a never-read merge transform immediately', async () => { + vi.useFakeTimers() + try { + const { router, cleanupCalls } = makeRouter() + const upstream = makeManualUpstream() + const aborts: Array = [] + + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { + onAbort: (reason) => aborts.push(reason), + }, + ) + expect(vi.getTimerCount()).toBe(1) + + // A discarded response is never read and never cancelled; external + // cleanup must not leave the transform pinned until the lifetime timer. + router.serverSsr!.cleanup() + + expect(cleanupCalls.count).toBe(1) + expect(aborts).toHaveLength(1) + expect((aborts[0] as Error).name).toBe('AbortError') + expect(upstream.cancelled.value).toBe(true) + expect(vi.getTimerCount()).toBe(0) + await expect(out.getReader().read()).rejects.toMatchObject({ + name: 'AbortError', + }) + } finally { + vi.useRealTimers() + } + }) + + test('external serverSsr cleanup releases a never-read fast-path transform immediately', async () => { + vi.useFakeTimers() + try { + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => true, + }) + const upstream = makeManualUpstream() + const aborts: Array = [] + + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { + onAbort: (reason) => aborts.push(reason), + }, + ) + expect(vi.getTimerCount()).toBe(1) + + router.serverSsr!.cleanup() + + expect(cleanupCalls.count).toBe(1) + expect(aborts).toHaveLength(1) + expect(upstream.cancelled.value).toBe(true) + expect(vi.getTimerCount()).toBe(0) + await expect(out.getReader().read()).rejects.toMatchObject({ + name: 'AbortError', + }) + } finally { + vi.useRealTimers() + } + }) + + test('external serverSsr cleanup promptly fails a merge stream parked on hydration output', async () => { + const { router, cleanupCalls } = makeRouter() + const upstream = makeManualUpstream() + const aborts: Array = [] + + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { + onAbort: (reason) => aborts.push(reason), + }, + ) + const reader = out.getReader() + + upstream.push(`${SCRIPT_BARRIER_HTML}`) + const first = await reader.read() + expect(first.done).toBe(false) + + // Renderer EOF with hydration output still Waiting parks the pump. + upstream.close() + const parked = reader.read() + await new Promise((resolve) => setTimeout(resolve, 0)) + + router.serverSsr!.cleanup() + + await expect(parked).rejects.toMatchObject({ name: 'AbortError' }) + expect(cleanupCalls.count).toBe(1) + expect(aborts).toHaveLength(1) + }) + + test('SSR byte-0 pass-through is used when explicitly safe', async () => { + let setRenderFinishedCalls = 0 + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => true, + setRenderFinished: () => { + setRenderFinishedCalls++ + }, + }) + const upstream = makeManualUpstream() + + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + upstream.push('done') + upstream.close() + + const text = await readAll(out as any) + expect(text).toBe('done') + expect(setRenderFinishedCalls).toBe(1) + expect(cleanupCalls.count).toBe(1) + }) + + test('SSR pass-through is bypassed when not explicitly safe', async () => { + const { router, emitScriptBatch, finishSerialization } = makeRouter({ + reserveFastPath: () => false, + }) + const upstream = makeManualUpstream() + + emitScriptBatch(['pending()']) + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + upstream.push(`done${SCRIPT_BARRIER_HTML}`) + upstream.close() + finishSerialization() + + const text = await readAll(out as any) + expect(text).toContain(renderScriptBatch(['pending()'])) + expect(text.indexOf(renderScriptBatch(['pending()']))).toBeLessThan( + text.indexOf(''), + ) + }) + + const lifetimeTimeoutCases = [ + { + name: 'pass-through with an active reader', + reserveFastPath: true, + activeReader: true, + }, + { + name: 'pass-through without an active reader', + reserveFastPath: true, + activeReader: false, + }, + { + name: 'main path with an active reader', + reserveFastPath: false, + activeReader: true, + }, + { + name: 'main path without an active reader', + reserveFastPath: false, + activeReader: false, + }, + ] as const + + test.each(lifetimeTimeoutCases)( + 'lifetime timeout errors $name and cleans up', + async ({ reserveFastPath, activeReader }) => { + vi.useFakeTimers() + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => reserveFastPath, + }) + const upstream = makeManualUpstream() + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { + lifetimeMs: 10, + }, + ) + + if (activeReader) { + const reader = out.getReader() + const pendingRead = reader.read() + const readError = expect(pendingRead).rejects.toThrow( + 'Stream lifetime exceeded', + ) + + await vi.advanceTimersByTimeAsync(15) + + await readError + reader.releaseLock() + } else { + await vi.advanceTimersByTimeAsync(15) + + const reader = out.getReader() + await expect(reader.read()).rejects.toThrow( + 'Stream lifetime exceeded', + ) + reader.releaseLock() + } + + expect(upstream.cancelled.value).toBe(true) + expect(upstream.cancelled.reason).toEqual( + new Error('Stream lifetime exceeded'), + ) + expect(cleanupCalls.count).toBe(1) + expect(warnSpy).toHaveBeenCalledOnce() + } finally { + warnSpy.mockRestore() + vi.useRealTimers() + } + }, + ) + + test('serialization timeout fails a completed render exactly once', async () => { + vi.useFakeTimers() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + const onAbort = vi.fn() + const { router, cleanupCalls } = makeRouter() + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { + timeoutMs: 10, + lifetimeMs: 1_000, + onAbort, + }, + ) + const outputPromise = readAll(output) + const outputError = expect(outputPromise).rejects.toThrow( + 'Serialization timeout after app render finished', + ) + + upstream.push(`${SCRIPT_BARRIER_HTML}${DOCUMENT_CLOSE}`) + upstream.close() + await flush(10) + await vi.advanceTimersByTimeAsync(15) + + await outputError + expect(onAbort).toHaveBeenCalledOnce() + expect(onAbort.mock.calls[0]![0]).toEqual( + new Error('Serialization timeout after app render finished'), + ) + expect(cleanupCalls.count).toBe(1) + expect(errorSpy).toHaveBeenCalledOnce() + expect(vi.getTimerCount()).toBe(0) + } finally { + errorSpy.mockRestore() + vi.useRealTimers() + } + }) + + test('upstream cancel() that rejects does not produce an unhandled rejection', async () => { + // Some upstream sources may reject when cancel() is called (e.g. their + // own underlying source.cancel throws). safeCancelReader must swallow. + const unhandled: Array = [] + const onUnhandled = (e: PromiseRejectionEvent | any) => { + unhandled.push(e?.reason ?? e) + } + process.on('unhandledRejection', onUnhandled) + try { + const { router, cleanupCalls } = makeRouter() + + const stream = new ReadableStream({ + start() {}, + cancel() { + // Simulate a misbehaving upstream whose cancel rejects. + throw new Error('boom-cancel') + }, + }) + + const out = transformReadableStreamWithRouter( + router as any, + stream as any, + ) + const reader = ( + out as any + ).getReader() as ReadableStreamDefaultReader + + // Consumer goes away → triggers cancelUpstream → upstream cancel throws. + await reader.cancel('consumer-gone').catch(() => {}) + // Allow microtasks for any rejection to surface. + await flush(10) + + expect(cleanupCalls.count).toBe(1) + expect( + unhandled.find( + (e: any) => e && String(e.message || e).includes('boom-cancel'), + ), + ).toBeUndefined() + } finally { + process.off('unhandledRejection', onUnhandled) + } + }) + + test('an output-channel failure terminates without another downstream pull', async () => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + const { router, cleanupCalls, failHydrationOutput } = makeRouter() + const upstream = makeManualUpstream() + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const reason = new Error('hydration-output-failed') + + failHydrationOutput(reason) + await flush() + + await expect(readAll(out as any)).rejects.toBe(reason) + expect(upstream.cancelled.value).toBe(true) + expect(cleanupCalls.count).toBe(1) + } finally { + errorSpy.mockRestore() + } + }) + + test('places a late router batch after a post-document script patch and before the relocated close', async () => { + const { router, emitScriptBatch, cleanupCalls, finishSerialization } = + makeRouter() + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { + rendererSafePoint: 'script-close', + }, + ) + const reader = output.getReader() + const shell = `

    loading

    ${SCRIPT_BARRIER_HTML}` + // Minimal resolved segment and replacement call. The runtime helper can be + // installed by the shell. + const rendererPatch = + '' + + '' + const appHtml = `${shell}${rendererPatch}` + + upstream.push(appHtml) + + const shellChunk = await reader.read() + expect(shellChunk.done).toBe(false) + expect(Buffer.from(shellChunk.value!).toString('utf8')).toBe(shell) + + const patchChunk = await reader.read() + expect(patchChunk.done).toBe(false) + expect(Buffer.from(patchChunk.value!).toString('utf8')).toBe(rendererPatch) + + // The original close suffix has now been scanned and held. This batch is + // deliberately emitted afterward to cover the late-arrival ordering. + const routerParts = ['routerPayload()'] + emitScriptBatch(routerParts) + finishSerialization() + + const routerChunk = await reader.read() + expect(routerChunk.done).toBe(false) + expect(Buffer.from(routerChunk.value!).toString('utf8')).toBe( + renderScriptBatch(routerParts), + ) + + upstream.close() + + const chunks = [shellChunk.value!, patchChunk.value!, routerChunk.value!] + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + chunks.push(value) + } + + const actual = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))) + const routerScript = renderScriptBatch(routerParts) + const expected = Buffer.from( + `${shell}${rendererPatch}${routerScript}`, + ) + + expect(actual).toEqual(expected) + expect(actual.indexOf(Buffer.from(rendererPatch))).toBeLessThan( + actual.indexOf(Buffer.from(routerScript)), + ) + expect(actual.indexOf(Buffer.from(routerScript))).toBeLessThan( + actual.indexOf(Buffer.from('')), + ) + expect(cleanupCalls.count).toBe(1) + }) + + test.each(internalSplitOffsets(SCRIPT_CLOSE))( + 'waits for a script-close safe point split at byte %s before a router batch', + async (splitAt) => { + const { router, emitScriptBatch, finishSerialization } = makeRouter() + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { + rendererSafePoint: 'script-close', + }, + ) + const reader = output.getReader() + const patchPrefix = + '' + + upstream.push(`${SCRIPT_BARRIER_HTML}${patchPrefix}`) + expect(Buffer.from((await reader.read()).value!).toString()).toBe( + SCRIPT_BARRIER_HTML, + ) + expect(Buffer.from((await reader.read()).value!).toString()).toBe( + patchPrefix.slice(0, -1), + ) + + const parts = ['streamed()'] + emitScriptBatch(parts) + upstream.push(`${patchSuffix}${DOCUMENT_CLOSE}`) + upstream.close() + finishSerialization() + + let remaining = '' + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + remaining += Buffer.from(value).toString() + } + + expect(remaining).toBe( + `<${patchSuffix}${renderScriptBatch(parts)}${DOCUMENT_CLOSE}`, + ) + }) + + test('places a router batch after a script-terminated patch and before its final close', async () => { + const { router, emitScriptBatch, cleanupCalls, finishSerialization } = + makeRouter() + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { + rendererSafePoint: 'script-close', + }, + ) + const reader = output.getReader() + const shell = + `` + + `

    loading

    ${SCRIPT_BARRIER_HTML}` + + '' + const rendererPatch = + '' + + '' + + upstream.push(shell) + const shellChunks = [await reader.read(), await reader.read()] + expect( + Buffer.concat( + shellChunks.map((chunk) => Buffer.from(chunk.value!)), + ).toString(), + ).toBe(shell) + + upstream.push(rendererPatch) + const patchChunk = await reader.read() + expect(Buffer.from(patchChunk.value!).toString()).toBe(rendererPatch) + + const routerParts = ['routerPayload()'] + emitScriptBatch(routerParts) + finishSerialization() + const routerChunk = await reader.read() + expect(Buffer.from(routerChunk.value!).toString()).toBe( + renderScriptBatch(routerParts), + ) + + upstream.push(DOCUMENT_CLOSE) + upstream.close() + + const closeChunk = await reader.read() + expect(Buffer.from(closeChunk.value!).toString()).toBe(DOCUMENT_CLOSE) + expect((await reader.read()).done).toBe(true) + expect(cleanupCalls.count).toBe(1) + }) + + test.each(['one byte chunk', 'byte chunks', 'one string record'] as const)( + 'relocates the document close after script safe points in %s', + async (input) => { + const { router, finishSerialization, cleanupCalls } = makeRouter() + const upstream = createControlledStream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream, + { rendererSafePoint: 'script-close' }, + ) + const reader = output.getReader() + const patch = '' + const prefix = SCRIPT_BARRIER_HTML + patch + const filler = 'x'.repeat( + MAX_HYDRATION_OUTPUT_CHUNK_BYTES - prefix.length, + ) + const afterClose = '' + const first = prefix + filler + const last = DOCUMENT_CLOSE + afterClose + const encoder = new TextEncoder() + + if (input === 'one string record') { + upstream.controller.enqueue(first + last) + } else if (input === 'byte chunks') { + upstream.controller.enqueue(encoder.encode(first)) + upstream.controller.enqueue(encoder.encode(last)) + } else { + upstream.controller.enqueue(encoder.encode(first + last)) + } + upstream.controller.close() + + expect(Buffer.from((await reader.read()).value!).toString()).toBe( + SCRIPT_BARRIER_HTML, + ) + // Keep hydration waiting until a script safe point has interrupted the + // document-close search. The byte/string variants then advance chunks. + expect(Buffer.from((await reader.read()).value!).toString()).toBe(patch) + finishSerialization() + reader.releaseLock() + + await expect(readAll(output)).resolves.toBe( + filler + afterClose + DOCUMENT_CLOSE, + ) + expect(cleanupCalls.count).toBe(1) + }, + ) + + test.each( + ['', ''].flatMap((prefix) => + internalSplitOffsets(prefix + DOCUMENT_CLOSE).map((splitAt) => ({ + prefix, + splitAt, + })), + ), + )( + 'relocates the structural document close after "$prefix" split at byte $splitAt', + async ({ prefix, splitAt }) => { + const { router, finishSerialization } = makeRouter() + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { rendererSafePoint: 'script-close' }, + ) + const shell = `${SCRIPT_BARRIER_HTML}` + const patch = '' + const beforeClose = `${shell}${patch}
    app
    ` + const afterClose = '' + const close = prefix + DOCUMENT_CLOSE + + upstream.push(beforeClose + close.slice(0, splitAt)) + upstream.push(close.slice(splitAt) + afterClose) + upstream.close() + const reader = output.getReader() + expect(Buffer.from((await reader.read()).value!).toString()).toBe(shell) + expect(Buffer.from((await reader.read()).value!).toString()).toBe(patch) + finishSerialization() + reader.releaseLock() + + await expect(readAll(output)).resolves.toBe( + '
    app
    ' + prefix + afterClose + DOCUMENT_CLOSE, + ) + }, + ) + + test('reconstructs one emoji split across upstream UTF-8 byte chunks', async () => { + const { router, finishSerialization } = makeRouter() + const upstream = createControlledStream() + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const encoder = new TextEncoder() + const emoji = encoder.encode('😀') + const html = `

    😀

    ${SCRIPT_BARRIER_HTML}` + + upstream.controller.enqueue(encoder.encode('

    ')) + upstream.controller.enqueue(emoji.slice(0, 2)) + upstream.controller.enqueue(emoji.slice(2)) + upstream.controller.enqueue( + encoder.encode(`

    ${SCRIPT_BARRIER_HTML}`), + ) + upstream.controller.close() + finishSerialization() + + await expect(readAll(out)).resolves.toBe(html) + }) + + test('does not interleave application bytes while an opaque record is active', async () => { + const { router, emitHydrationRecord, finishSerialization } = makeRouter() + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const reader = output.getReader() + const record = 'R'.repeat(MAX_HYDRATION_OUTPUT_CHUNK_BYTES * 2 + 1) + const patch = '' + + upstream.push(`${SCRIPT_BARRIER_HTML}`) + expect(Buffer.from((await reader.read()).value!).toString()).toBe( + `${SCRIPT_BARRIER_HTML}`, + ) + + emitHydrationRecord(record) + upstream.push(patch + DOCUMENT_CLOSE) + upstream.close() + finishSerialization() + + let rest = '' + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + rest += Buffer.from(value).toString() + } + + expect(rest).toBe(record + patch + DOCUMENT_CLOSE) + }) + + test('drains an active opaque record after prefetched renderer EOF', async () => { + const setRenderFinished = vi.fn() + const startSerializationTimeout = vi.fn() + const { router, emitHydrationRecord, finishSerialization } = makeRouter({ + setRenderFinished, + startSerializationTimeout, + }) + const upstream = makeManualUpstream() + const output = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const reader = output.getReader() + const record = 'R'.repeat(MAX_HYDRATION_OUTPUT_CHUNK_BYTES + 1) + + upstream.push(SCRIPT_BARRIER_HTML) + expect(Buffer.from((await reader.read()).value!).toString()).toBe( + SCRIPT_BARRIER_HTML, + ) + emitHydrationRecord(record) + finishSerialization() + upstream.close() + await flush() + + expect(startSerializationTimeout).toHaveBeenCalledOnce() + expect(startSerializationTimeout).toHaveBeenCalledWith(60_000) + expect(setRenderFinished).toHaveBeenCalledOnce() + + const first = await reader.read() + expect(first.done).toBe(false) + + let received = Buffer.from(first.value!).toString() + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + received += Buffer.from(value).toString() + } + expect(received).toBe(record) + }) + + test('draining a large source does not read more app chunks per transport slice', async () => { + const { router, emitScriptBatch } = makeRouter() + const encoder = new TextEncoder() + let produced = 0 + const appStream = new ReadableStream({ + pull(controller) { + produced++ + controller.enqueue( + encoder.encode( + produced === 1 + ? `
    app
    ${SCRIPT_BARRIER_HTML}` + : `

    app-${produced}

    `, + ), + ) + }, + }) + const out = transformReadableStreamWithRouter( + router as any, + appStream as any, + ) + emitScriptBatch([createIssuePayload()]) + const reader = out.getReader() + + const first = await reader.read() + expect(first.done).toBe(false) + await flush() + const producedBeforeRouterDrain = produced + + for (let index = 0; index < 8; index++) { + const next = await reader.read() + expect(next.done).toBe(false) + } + await flush() + + expect(produced).toBe(producedBeforeRouterDrain) + await reader.cancel() + }) + + test('a prefetched upstream error immediately stops an active large-source drain', async () => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + const { router, emitScriptBatch, cleanupCalls } = makeRouter() + const upstream = makeManualUpstream() + const onAbort = vi.fn() + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { onAbort }, + ) + const reader = out.getReader() + const upstreamError = new Error('renderer-failed') + + emitScriptBatch([createIssuePayload()]) + upstream.push(`${SCRIPT_BARRIER_HTML}`) + expect((await reader.read()).done).toBe(false) + expect((await reader.read()).done).toBe(false) + + upstream.error(upstreamError) + await flush() + + expect(cleanupCalls.count).toBe(1) + expect(onAbort).toHaveBeenCalledOnce() + expect(onAbort).toHaveBeenCalledWith(upstreamError) + await expect(reader.read()).rejects.toBe(upstreamError) + } finally { + errorSpy.mockRestore() + } + }) + + test('cancellation tears down an active large-source drain', async () => { + const { router, emitScriptBatch, cleanupCalls } = makeRouter() + const upstream = makeManualUpstream() + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const reader = out.getReader() + + emitScriptBatch([createIssuePayload()]) + upstream.push(`
    app
    ${SCRIPT_BARRIER_HTML}`) + + expect((await reader.read()).done).toBe(false) + expect((await reader.read()).done).toBe(false) + expect(cleanupCalls.count).toBe(0) + + await reader.cancel('consumer-gone') + + expect(upstream.cancelled.value).toBe(true) + expect(cleanupCalls.count).toBe(1) + }) + + test('lifetime timeout errors an active large-source drain', async () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.useFakeTimers() + try { + const { router, emitScriptBatch, cleanupCalls } = makeRouter() + const upstream = makeManualUpstream() + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + { + lifetimeMs: 10, + }, + ) + const reader = out.getReader() + + emitScriptBatch([createIssuePayload()]) + upstream.push(`
    app
    ${SCRIPT_BARRIER_HTML}`) + + expect((await reader.read()).done).toBe(false) + expect((await reader.read()).done).toBe(false) + + await vi.advanceTimersByTimeAsync(15) + + await expect(reader.read()).rejects.toThrow('Stream lifetime exceeded') + expect(upstream.cancelled.value).toBe(true) + expect(upstream.cancelled.reason).toEqual( + new Error('Stream lifetime exceeded'), + ) + expect(cleanupCalls.count).toBe(1) + expect(warnSpy).toHaveBeenCalledOnce() + } finally { + vi.useRealTimers() + warnSpy.mockRestore() + } + }) + + test('forwards a large application byte chunk unchanged', async () => { + const { router, finishSerialization } = makeRouter() + const upstream = makeManualUpstream() + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const reader = (out as any).getReader() + const text = '😀a'.repeat(50_000) + + upstream.push(text) + + const first = await reader.read() + expect(first.done).toBe(false) + const firstText = Buffer.from(first.value).toString('utf8') + expect(firstText).toBe(text) + + upstream.push(SCRIPT_BARRIER_HTML) + upstream.close() + finishSerialization() + + let rest = '' + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + rest += Buffer.from(value).toString('utf8') + } + + expect(firstText + rest).toBe(text + SCRIPT_BARRIER_HTML) + }) + + test('forwards an incomplete document close and drains pending router scripts', async () => { + const { router, emitScriptBatch, finishSerialization, cleanupCalls } = + makeRouter() + const upstream = makeManualUpstream() + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const reader = out.getReader() + + upstream.push(`${SCRIPT_BARRIER_HTML}${SCRIPT_BARRIER_HTML}`, + ) + + const pendingRead = reader.read() + await flush() + emitScriptBatch(['pending()']) + finishSerialization() + upstream.close() + + expect(Buffer.from((await pendingRead).value!).toString()).toBe( + 'pending();document.currentScript.remove()', + ) + expect(cleanupCalls.count).toBe(1) + }) + + test('downstream backpressure delays close; no chunks are lost', async () => { + // Consumer reads slowly: all router scripts and relocated closing tags + // must arrive before the stream ends. + const { router, emitScriptBatch, finishSerialization } = makeRouter() + const upstream = makeManualUpstream() + + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + + upstream.push(`
    a
    ${SCRIPT_BARRIER_HTML}`) + // Queue many script batches while app is still rendering. + for (let i = 0; i < 50; i++) { + emitScriptBatch([`S${i}`]) + } + upstream.push('') + upstream.close() + finishSerialization() + + const full = await readAll(out as any) + + expect(full).toContain('
    a
    ') + expect(full).toContain('') + for (let i = 0; i < 50; i++) { + expect(full).toContain(renderScriptBatch([`S${i}`])) + } + // All scripts must appear before . + expect(full.indexOf(renderScriptBatch(['S49']))).toBeLessThan( + full.indexOf(''), + ) + }) +}) + +describe('transformReadableStreamWithRouter — hydration output ordering', () => { + test('does not scan or lift the barrier before the initial script take', async () => { + let taken = false + const { router, emitScriptBatch, finishSerialization } = makeRouter({ + isInitialTaken: () => taken, + }) + const upstream = makeManualUpstream() + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const reader = out.getReader() + const injected = 'late()' + const rendered = renderScriptBatch([injected]) + const decoder = new TextDecoder() + + // A Ready record plus barrier-lookalike bytes rendered before + // ran (initial take pending) must pass through without lifting. + emitScriptBatch([injected]) + upstream.push(`${SCRIPT_BARRIER_HTML}`) + const first = await reader.read() + expect(first.done).toBe(false) + expect(decoder.decode(first.value)).toBe( + `${SCRIPT_BARRIER_HTML}`, + ) + + // After the take, the real boundary lifts the barrier and the queued + // record is injected after it. + taken = true + upstream.push(`
    x
    ${SCRIPT_BARRIER_HTML}${DOCUMENT_CLOSE}`) + upstream.close() + finishSerialization() + + let rest = '' + for (;;) { + const result = await reader.read() + if (result.done) { + break + } + rest += decoder.decode(result.value, { stream: true }) + } + const barrierEnd = + rest.indexOf(SCRIPT_BARRIER_HTML) + SCRIPT_BARRIER_HTML.length + expect(rest.indexOf(SCRIPT_BARRIER_HTML)).toBeGreaterThanOrEqual(0) + expect(rest.indexOf(rendered)).toBeGreaterThanOrEqual(barrierEnd) + expect(rest.endsWith(DOCUMENT_CLOSE)).toBe(true) + }) + + test('does not interpret close-looking bytes before the router boundary', async () => { + const { router, emitScriptBatch, finishSerialization } = makeRouter() + const upstream = makeManualUpstream() + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + const injected = 'pending()' + const rendered = renderScriptBatch([injected]) + const inlineScript = '' + + emitScriptBatch([injected]) + upstream.push( + `${inlineScript}
    x
    ${SCRIPT_BARRIER_HTML}`, + ) + upstream.close() + finishSerialization() + + const full = await readAll(out as any) + expect(full).toContain(inlineScript) + expect(full.indexOf(rendered)).toBeGreaterThan(full.indexOf('')) + expect(full.indexOf(rendered)).toBeLessThan(full.lastIndexOf('')) + }) + + test('keeps queued script batches ordered when lifting the barrier emits synchronously', async () => { + const beforeLift = 'beforeLift()' + const duringLift = 'duringLift()' + const duringLiftEmitter: { + current?: (html: string) => void + } = {} + const { router, emitScriptBatch, finishSerialization } = makeRouter({ + liftBarrier: () => { + duringLiftEmitter.current!(duringLift) + }, + }) + duringLiftEmitter.current = (script) => emitScriptBatch([script]) + const upstream = makeManualUpstream() + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + + emitScriptBatch([beforeLift]) + upstream.push(`${SCRIPT_BARRIER_HTML}`) + upstream.close() + finishSerialization() + + const full = await readAll(out as any) + expect(full.indexOf(renderScriptBatch([beforeLift]))).toBeGreaterThan( + full.indexOf(SCRIPT_BARRIER_HTML), + ) + expect(full.indexOf(renderScriptBatch([beforeLift]))).toBeLessThan( + full.indexOf(renderScriptBatch([duringLift])), + ) + expect(full.indexOf(renderScriptBatch([duringLift]))).toBeLessThan( + full.indexOf(''), + ) + }) + + test('drains queued batches after the exact boundary and before the close', async () => { + const { router, emitScriptBatch, finishSerialization } = makeRouter() + const upstream = makeManualUpstream() + + const out = transformReadableStreamWithRouter( + router as any, + upstream.stream as any, + ) + + upstream.push(`
    app
    ${SCRIPT_BARRIER_HTML}`) + // Router parts must not move ahead of pending application bytes. + emitScriptBatch(['X']) + emitScriptBatch(['Y']) + + // The structural close is held until all router scripts finish. + upstream.push('') + upstream.close() + finishSerialization() + + const full = await readAll(out as any) + + // Order: app div → scripts → body close. + expect(full).toContain('
    app
    ') + expect(full).toContain(renderScriptBatch(['X'])) + expect(full).toContain(renderScriptBatch(['Y'])) + expect(full.indexOf('
    app
    ')).toBeLessThan( + full.indexOf(renderScriptBatch(['X'])), + ) + expect(full.indexOf(renderScriptBatch(['Y']))).toBeLessThan( + full.indexOf(''), + ) + }) + + test('onAbort: fires once when downstream cancels (readable wrapper)', async () => { + const { router, finishSerialization } = makeRouter() + finishSerialization() + + let produced = 0 + const upstream = new ReadableStream({ + pull(controller) { + produced++ + controller.enqueue(new TextEncoder().encode('

    x

    ')) + }, + }) + + let aborts = 0 + const out = transformReadableStreamWithRouter( + router as any, + upstream as any, + { + onAbort: () => aborts++, + }, + ) + + const reader = (out as any).getReader() + await reader.read() + await reader.cancel(new Error('client disconnect')) + // Allow microtasks to flush. + await Promise.resolve() + await Promise.resolve() + + expect(aborts).toBe(1) + expect(produced).toBeGreaterThan(0) + }) + + test('onAbort: NOT called on natural successful completion', async () => { + const { router, finishSerialization } = makeRouter({ + reserveFastPath: () => true, + }) + + const upstream = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('

    done

    ')) + controller.close() + }, + }) + + let aborts = 0 + const out = transformReadableStreamWithRouter( + router as any, + upstream as any, + { + onAbort: () => aborts++, + }, + ) + + finishSerialization() + + // Drain to completion. + const reader = (out as any).getReader() + for (;;) { + const { done } = await reader.read() + if (done) { + break + } + } + + expect(aborts).toBe(0) + }) + + test('readable wrapper accepts string chunks', async () => { + const { router } = makeRouter({ reserveFastPath: () => true }) + const source = 'string record' + const upstream = new ReadableStream({ + start(controller) { + controller.enqueue(source) + controller.close() + }, + }) + + const out = transformReadableStreamWithRouter(router as any, upstream) + + await expect(readAll(out)).resolves.toBe(source) + }) + + test('pipeable byte-0 pass-through encodes string records independently', async () => { + const { router } = makeRouter({ + reserveFastPath: () => true, + }) + const highSurrogate = String.fromCharCode(0xd83d) + const lowSurrogate = String.fromCharCode(0xde00) + const records = [ + '', + highSurrogate, + lowSurrogate, + '', + ] + const upstream = Readable.from(records) + const out = transformPipeableStreamWithRouter(router as any, upstream) + const actual = await readAllPipeableBytes(out) + const expected = Buffer.concat(records.map((record) => Buffer.from(record))) + + expect(actual).toEqual(expected) + expect(actual.includes(Buffer.from('😀'))).toBe(false) + }) + + test('pipeable byte-0 pass-through bounds one large string record', async () => { + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => true, + }) + const source = makeLargeStringRecord('', '') + const upstream = Readable.from([source]) + const out = transformPipeableStreamWithRouter(router as any, upstream) + const chunks = await readAllPipeableChunks(out) + const actual = Buffer.concat(chunks) + + expect(source.indexOf('😀')).toBe(MAX_HYDRATION_OUTPUT_CHUNK_BYTES - 1) + expect(actual).toEqual(Buffer.from(source)) + expect( + Math.max(...chunks.map((chunk) => chunk.byteLength)), + ).toBeLessThanOrEqual(MAX_HYDRATION_OUTPUT_CHUNK_BYTES) + expect(cleanupCalls.count).toBe(1) + }) + + test('pipeable pass-through handles an encoding set during the first read', async () => { + const { router } = makeRouter({ + reserveFastPath: () => true, + }) + const source = 'français' + const upstream = new Readable({ + read() { + this.setEncoding('utf8') + this.push(Buffer.from(source)) + this.push(null) + }, + }) + + const out = transformPipeableStreamWithRouter(router as any, upstream) + const actual = await readAllPipeableBytes(out) + + expect(actual).toEqual(Buffer.from(source)) + }) + + test('pipeable merge path encodes string records independently', async () => { + const { router, emitScriptBatch, finishSerialization } = makeRouter() + const highSurrogate = String.fromCharCode(0xd83d) + const lowSurrogate = String.fromCharCode(0xde00) + const prefix = `${SCRIPT_BARRIER_HTML}` + const records = [prefix, highSurrogate, lowSurrogate, DOCUMENT_CLOSE] + const upstream = Readable.from(records) + const out = transformPipeableStreamWithRouter(router as any, upstream) + const parts = ['streamed()'] + + emitScriptBatch(parts) + finishSerialization() + + const actual = await readAllPipeableBytes(out) + const expected = Buffer.concat( + [ + prefix, + renderScriptBatch(parts), + highSurrogate, + lowSurrogate, + DOCUMENT_CLOSE, + ].map((record) => Buffer.from(record)), + ) + + expect(actual).toEqual(expected) + expect(actual.includes(Buffer.from('😀'))).toBe(false) + }) + + test('pipeable merge path bounds one large string record', async () => { + const { router, cleanupCalls, emitScriptBatch, finishSerialization } = + makeRouter() + const source = makeLargeStringRecord( + '
    ', + `
    ${SCRIPT_BARRIER_HTML}${DOCUMENT_CLOSE}`, + ) + const parts = ['streamed()'] + const routerScript = renderScriptBatch(parts) + const expected = + source.slice(0, -DOCUMENT_CLOSE.length) + routerScript + DOCUMENT_CLOSE + const upstream = Readable.from([source]) + const out = transformPipeableStreamWithRouter(router as any, upstream) + + emitScriptBatch(parts) + finishSerialization() + + const chunks = await readAllPipeableChunks(out) + const actual = Buffer.concat(chunks) + + expect(source.indexOf('😀')).toBe(MAX_HYDRATION_OUTPUT_CHUNK_BYTES - 1) + expect(actual).toEqual(Buffer.from(expected)) + expect(actual.indexOf(Buffer.from(routerScript))).toBeGreaterThan( + actual.indexOf(Buffer.from(SCRIPT_BARRIER_HTML)), + ) + expect(actual.indexOf(Buffer.from(routerScript))).toBeLessThan( + actual.lastIndexOf(Buffer.from(DOCUMENT_CLOSE)), + ) + expect( + Math.max(...chunks.map((chunk) => chunk.byteLength)), + ).toBeLessThanOrEqual(MAX_HYDRATION_OUTPUT_CHUNK_BYTES) + expect(cleanupCalls.count).toBe(1) + }) + + test('record-end does not split one large Node string record', async () => { + const { router, emitScriptBatch, finishSerialization, cleanupCalls } = + makeRouter() + const prefix = `${SCRIPT_BARRIER_HTML}` + const largeRecord = 'x'.repeat(MAX_HYDRATION_OUTPUT_CHUNK_BYTES * 2) + const parts = ['streamed()'] + const routerScript = renderScriptBatch(parts) + const upstream = Readable.from([prefix, largeRecord, DOCUMENT_CLOSE]) + const out = transformPipeableStreamWithRouter(router as any, upstream, { + rendererSafePoint: 'record-end', + }) + const iterator = out[Symbol.asyncIterator]() + const chunks = [Buffer.from((await iterator.next()).value)] + + chunks.push(Buffer.from((await iterator.next()).value)) + expect(chunks[0]).toEqual(Buffer.from(prefix)) + expect(chunks[1]).toEqual( + Buffer.alloc(MAX_HYDRATION_OUTPUT_CHUNK_BYTES, 'x'), + ) + + emitScriptBatch(parts) + finishSerialization() + + for (;;) { + const { done, value } = await iterator.next() + if (done) { + break + } + chunks.push(Buffer.from(value)) + } + + const actual = Buffer.concat(chunks) + const expected = Buffer.from( + prefix + largeRecord + routerScript + DOCUMENT_CLOSE, + ) + + expect(actual).toEqual(expected) + expect(actual.indexOf(Buffer.from(routerScript))).toBe( + Buffer.byteLength(prefix + largeRecord), + ) + expect(cleanupCalls.count).toBe(1) + }) + + test('cancelling a large Node string drain tears down once', async () => { + const { router, cleanupCalls } = makeRouter({ + reserveFastPath: () => true, + }) + const source = makeLargeStringRecord('', '') + let upstreamCancellations = 0 + let pushed = false + const upstream = new Readable({ + objectMode: true, + read() { + if (!pushed) { + pushed = true + this.push(source) + } + }, + destroy(_error, callback) { + upstreamCancellations++ + callback() + }, + }) + const upstreamClosed = new Promise((resolve) => { + upstream.once('close', resolve) + }) + const onAbort = vi.fn() + const out = transformReadableStreamWithRouter( + router as any, + Readable.toWeb(upstream) as any, + { + onAbort, + }, + ) + const reader = out.getReader() + const first = await reader.read() + + expect(first.value!.byteLength).toBe(MAX_HYDRATION_OUTPUT_CHUNK_BYTES - 1) + + const reason = new Error('consumer stopped') + await reader.cancel(reason) + await upstreamClosed + await flush() + + expect(upstreamCancellations).toBe(1) + expect(onAbort).toHaveBeenCalledOnce() + expect(cleanupCalls.count).toBe(1) + }) + + test('onAbort: fires when pipeable wrapper consumer destroys', async () => { + const { router, finishSerialization } = makeRouter() + finishSerialization() + + const pass = new PassThrough() + let aborts = 0 + const out = transformPipeableStreamWithRouter(router as any, pass, { + onAbort: () => aborts++, + }) + // Swallow expected error emission from destroy(). + out.on('error', () => {}) + + // Push something so the read loop is engaged. + pass.write('

    x

    ') + // Wait a tick to let reader start. + await new Promise((r) => setImmediate(r)) + + // Destroy downstream — simulates Node response being closed by client. + out.destroy(new Error('client gone')) + // Allow microtasks + readable webstream cancel propagation. + await new Promise((r) => setImmediate(r)) + await Promise.resolve() + + expect(aborts).toBe(1) + + // Cleanup: destroy upstream so we don't leak. + if (!pass.destroyed) { + pass.destroy() + } + }) + + test('onAbort: lifetime timeout triggers abort exactly once', async () => { + vi.useFakeTimers() + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + const { router, finishSerialization } = makeRouter() + finishSerialization() + + // Upstream that never produces or closes. + const upstream = new ReadableStream({ + pull() { + // never enqueue, never close + }, + }) + + let aborts = 0 + + const out = transformReadableStreamWithRouter( + router as any, + upstream as any, + { + onAbort: () => aborts++, + lifetimeMs: 1000, + }, + ) + + // Start reading before the lifetime watchdog errors the stream. + const reader = (out as any).getReader() + const readP = reader.read() + const readError = expect(readP).rejects.toThrow( + 'Stream lifetime exceeded', + ) + + await vi.advanceTimersByTimeAsync(1500) + await readError + + expect(aborts).toBe(1) + } finally { + warnSpy.mockRestore() + vi.useRealTimers() + } + }) + + test('default lifetime is derived from timeoutMs', async () => { + vi.useFakeTimers() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + const { router, finishSerialization } = makeRouter() + finishSerialization() + const upstream = new ReadableStream({ + pull() { + // never enqueue, never close + }, + }) + + let aborts = 0 + const out = transformReadableStreamWithRouter( + router as any, + upstream as any, + { + onAbort: () => aborts++, + timeoutMs: 10, + }, + ) + + const reader = (out as any).getReader() + const readP = reader.read() + const readError = expect(readP).rejects.toThrow( + 'Stream lifetime exceeded', + ) + + await vi.advanceTimersByTimeAsync(15) + expect(aborts).toBe(0) + + await vi.advanceTimersByTimeAsync(6) + await readError + expect(aborts).toBe(1) + } finally { + errorSpy.mockRestore() + warnSpy.mockRestore() + vi.useRealTimers() + } + }) + + test('upstream writable abort surfaces; readable does not hang', async () => { + const { router, finishSerialization } = makeRouter() + finishSerialization() + + // Simulate a synchronous producer setup failure: a TransformStream is + // handed to the router transform, and the producer never writes before + // aborting the writable side. The router transform's readable must resolve + // (with done or an error) rather than wait for lifetimeMs. + const ts = new TransformStream() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + let aborts = 0 + const out = transformReadableStreamWithRouter( + router as any, + ts.readable as any, + { + onAbort: () => aborts++, + }, + ) + + void ts.writable.abort(new Error('setup-throw')).catch(() => {}) + + const reader = (out as any).getReader() + // Either the read resolves with done, or it rejects with the abort + // reason. Both prove non-hang behavior; we just require it terminates. + const terminated = await reader + .read() + .then(() => true) + .catch(() => true) + + expect(terminated).toBe(true) + expect(aborts).toBe(1) + } finally { + errorSpy.mockRestore() + } + }) +}) diff --git a/packages/router-core/tests/tsr-script-teardown.test.ts b/packages/router-core/tests/tsr-script-teardown.test.ts new file mode 100644 index 0000000000..2355e1c99a --- /dev/null +++ b/packages/router-core/tests/tsr-script-teardown.test.ts @@ -0,0 +1,46 @@ +import { afterEach, beforeEach, describe, expect, test } from 'vitest' +import minifiedTsrBootStrapScript from '../src/ssr/tsrScript?script-string' + +type TsrBootstrap = { + h: () => void + e: () => void + c: () => void +} + +// Assign `self.$_TSR`. +function installBootstrap(): TsrBootstrap { + new Function(minifiedTsrBootStrapScript)() + return (window as any).$_TSR +} + +describe('$_TSR client teardown', () => { + beforeEach(() => { + ;(window as any).$R = { tsr: [] } + delete (window as any).$_TSR + }) + + afterEach(() => { + delete (window as any).$_TSR + delete (window as any).$R + }) + + test('does not tear down until both hydrated and streamEnded', () => { + const tsr = installBootstrap() + + tsr.h() + expect((window as any).$_TSR).toBeDefined() + + tsr.e() + expect((window as any).$_TSR).toBeUndefined() + }) + + test('removes both $_TSR and $R[tsr] on teardown', () => { + const tsr = installBootstrap() + + tsr.h() + tsr.e() + + expect((window as any).$_TSR).toBeUndefined() + expect((window as any).$R.tsr).toBeUndefined() + }) +}) diff --git a/packages/router-core/tests/url-standard.test.ts b/packages/router-core/tests/url-standard.test.ts new file mode 100644 index 0000000000..4be6c0dfd6 --- /dev/null +++ b/packages/router-core/tests/url-standard.test.ts @@ -0,0 +1,96 @@ +import { createHash } from 'node:crypto' +import { readFileSync } from 'node:fs' +import { URL as NodeURL } from 'node:url' +import { describe, expect, it } from 'vitest' +import { + DEFAULT_PROTOCOL_ALLOWLIST, + getUrlScheme, + isDangerousProtocol, +} from '../src/utils' + +type UrlFixture = { + input: string + protocol?: string +} + +const sources = [ + { + file: 'urltestdata.json', + sha256: 'b8767904d25029a46e0d297e1320ded3a733322f489caa5a482c886fb11e9238', + }, + { + file: 'urltestdata-javascript-only.json', + sha256: '74eaf2f3b8246b1fe44c388e3ecf8eb8442e01f229418b634acecb9595caddfa', + }, +] +const allowlists = [ + { name: 'default', protocols: new Set(DEFAULT_PROTOCOL_ALLOWLIST) }, + { name: 'empty', protocols: new Set() }, + { + name: 'custom', + protocols: new Set([ + 'https:', + 'javascript:', + 'non-special:', + 'intent:', + 'a1234567890-+.:', + ]), + }, +] + +// These WPT inputs have a protocol-relative prefix but no valid HTTP(S) host. +const malformedProtocolRelative = new Set(['//', '///', '////', '//C|/foo/bar']) + +function getNativeScheme(input: string): string | undefined { + const colon = input.indexOf(':') + if (colon === -1) { + return undefined + } + + // A valid replacement body lets URL recognize the scheme even when the + // original host or port is invalid. No base is supplied, so relative prefixes fail. + try { + return new NodeURL(`${input.slice(0, colon + 1)}//example.com`).protocol + } catch { + return undefined + } +} + +describe.each(sources)('WPT $file', ({ file, sha256 }) => { + const contents = readFileSync( + new NodeURL(`./fixtures/wpt-url/${file}`, import.meta.url), + 'utf8', + ) + // JSON.parse preserves the unpaired surrogates in the JavaScript-only file. + const entries = JSON.parse(contents) as Array + const cases = entries.flatMap((fixture, index) => + typeof fixture === 'string' ? [] : [{ ...fixture, index }], + ) + + it('preserves the complete pinned upstream file', () => { + expect(createHash('sha256').update(contents).digest('hex')).toBe(sha256) + }) + + it.each(cases)('case $index: $input', ({ input, protocol }) => { + const scheme = getNativeScheme(input) + if (scheme !== undefined && protocol !== undefined) { + expect(scheme).toBe(protocol) + } + expect(getUrlScheme(input)).toBe(scheme) + + // Ordinary relative paths inherit the two different base hosts; a + // protocol-relative input supplies its own host, producing the same hostname. + const protocolRelative = + scheme === undefined && + (malformedProtocolRelative.has(input) || + new NodeURL(input, 'https://one.example/').hostname === + new NodeURL(input, 'https://two.example/').hostname) + + for (const { name, protocols } of allowlists) { + // The allowlist and blanket protocol-relative rejection are Router policy. + const blocked = + protocolRelative || (scheme !== undefined && !protocols.has(scheme)) + expect(isDangerousProtocol(input, protocols), name).toBe(blocked) + } + }) +}) diff --git a/packages/router-core/tests/utils.test.ts b/packages/router-core/tests/utils.test.ts index 932d368ca8..baeb751e8f 100644 --- a/packages/router-core/tests/utils.test.ts +++ b/packages/router-core/tests/utils.test.ts @@ -2,11 +2,237 @@ import { afterEach, describe, expect, it } from 'vitest' import { decodePath, deepEqual, + encodePathLikeUrl, + escapeHtml, + hasOwn, isPlainArray, + isPlainObject, + nullReplaceEqualDeep, replaceEqualDeep, } from '../src/utils' +import { decode } from '../src/qss' describe('replaceEqualDeep', () => { + it('reuses the next object when its children need no replacements', () => { + const shared = Object.freeze({ id: 1 }) + const prev = Object.freeze({ shared, page: 1 }) + const next = Object.freeze({ shared, page: 2 }) + + expect(replaceEqualDeep(prev, next)).toBe(next) + }) + + it('reuses a changed null-prototype search record', () => { + const prev = decode('page=1&sort=newest') + const next = decode('page=2&sort=newest') + + expect(nullReplaceEqualDeep(prev, next)).toBe(next) + }) + + it('reuses a changed ordinary object in null-prototype mode', () => { + const prev = decode('page=1&sort=newest') + const next = { page: '2', sort: 'newest' } + const result = nullReplaceEqualDeep(prev, next) + + expect(result).toBe(next) + expect(Object.getPrototypeOf(result)).toBe(Object.prototype) + }) + + it('returns the previous signed zero when strict equality matches', () => { + expect(replaceEqualDeep(-0, 0)).toBe(-0) + expect(replaceEqualDeep(0, -0)).toBe(0) + }) + + it.each([false, true])( + 'uses the same signed-zero sharing rule for every child (nullProto=%s)', + (nullProto) => { + const prev = { first: -0, changed: 1, last: -0 } + const next = { first: 0, changed: 2, last: 0 } + const result = replaceEqualDeep(prev, next, nullProto) + expect(result).not.toBe(next) + expect(Object.getPrototypeOf(result)).toBe( + nullProto ? null : Object.prototype, + ) + expect(result.first).toBe(-0) + expect(result.changed).toBe(2) + expect(result.last).toBe(-0) + expect(replaceEqualDeep([-0, 1, -0], [0, 2, 0], nullProto)).toStrictEqual( + [-0, 2, -0], + ) + }, + ) + + // Known unsupported edge case for ordinary object copies. + it.skip('copies an own __proto__ property as data in the incoming key order', () => { + const prev = JSON.parse('{"first":1,"__proto__":{"shared":1},"last":1}') + const next = JSON.parse('{"first":2,"__proto__":{"shared":1},"last":1}') + const result = replaceEqualDeep(prev, next) + expect(Object.getPrototypeOf(result)).toBe(Object.prototype) + expect(hasOwn.call(result, '__proto__')).toBe(true) + expect(result.__proto__).toBe(prev.__proto__) + expect(Object.keys(result)).toEqual(Object.keys(next)) + expect(result).toStrictEqual(next) + }) + + it.skip.each([undefined, { shared: 1 }])( + 'preserves a newly added own __proto__ property with value %j', + (value) => { + const prev = { first: 1, last: 1 } + const next = { first: 1, ['__proto__']: value, last: 1 } + const result = replaceEqualDeep(prev, next) + expect(Object.getPrototypeOf(result)).toBe(Object.prototype) + expect(hasOwn.call(result, '__proto__')).toBe(true) + expect(result.__proto__).toBe(value) + expect(Object.keys(result)).toEqual(Object.keys(next)) + expect(result).toStrictEqual(next) + }, + ) + + it('shares children without changing recursively frozen inputs', () => { + const prev = Object.freeze({ + items: Object.freeze([ + Object.freeze({ id: 1 }), + Object.freeze({ id: 2 }), + ]), + page: 1, + }) + const next = Object.freeze({ + items: Object.freeze([ + Object.freeze({ id: 1 }), + Object.freeze({ id: 3 }), + ]), + page: 2, + }) + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result.items[0]).toBe(prev.items[0]) + expect(next.items[0]).not.toBe(prev.items[0]) + expect(prev.items[1]?.id).toBe(2) + expect(next.items[1]?.id).toBe(3) + }) + + it('preserves special numbers and explicit undefined in changed frozen arrays', () => { + const prev = Object.freeze([-0, NaN, Infinity, 2 ** 40, 1.5, undefined, 1]) + const next = Object.freeze([0, NaN, Infinity, 2 ** 40, 1.5, undefined, 2]) + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual([ + -0, + NaN, + Infinity, + 2 ** 40, + 1.5, + undefined, + 2, + ]) + expect(hasOwn.call(result, 5)).toBe(true) + expect(next[0]).toBe(0) + expect(prev[6]).toBe(1) + }) + + it('ignores auxiliary array metadata without using its constructor or iterator', () => { + const fail = () => { + throw new Error('array metadata must not be invoked') + } + const decorate = (values: Array) => + Object.freeze( + Object.defineProperties(values, { + metadata: { value: 'ignored' }, + constructor: { value: { [Symbol.species]: fail } }, + [Symbol.iterator]: { value: fail }, + }), + ) + const child = Object.freeze({ id: 1 }) + const prev = decorate([child, 1]) + const equal = decorate([{ id: 1 }, 1]) + const next = decorate([{ id: 1 }, 2]) + + expect(replaceEqualDeep(prev, equal)).toBe(prev) + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual([child, 2]) + expect(result[0]).toBe(child) + expect(Object.keys(result)).toEqual(['0', '1']) + expect(Object.getOwnPropertySymbols(result)).toEqual([]) + expect(prev[1]).toBe(1) + expect(next[0]).not.toBe(child) + }) + + it.each(['prev', 'next'])( + 'preserves incoming values with a non-enumerable array index on %s', + (side) => { + const prev = [{ id: 1 }, 1] + const next = [{ id: 1 }, 2] + Object.defineProperty(side === 'prev' ? prev : next, '1', { + enumerable: false, + }) + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(Object.getOwnPropertyDescriptor(result, '1')?.enumerable).toBe( + Object.getOwnPropertyDescriptor(next, '1')?.enumerable, + ) + }, + ) + + it('does not consider separate NaN children strictly equal', () => { + const prev = { value: NaN } + const next = { value: NaN } + const result = replaceEqualDeep(prev, next) + expect(result).not.toBe(prev) + expect(result).toStrictEqual(next) + }) + + it.each([0, 1, 8, 16])( + 'resolves deeply equal children after %i identical array entries', + (length) => { + const prefix = Array.from({ length }, (_, index) => index) + const shared = { child: { value: 1 } } + const prev = [...prefix, shared, { version: 1 }] + const equal = [...prefix, { child: { value: 1 } }, { version: 1 }] + expect(replaceEqualDeep(prev, equal)).toBe(prev) + + const next = [...prefix, { child: { value: 1 } }, { version: 2 }] + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result).not.toBe(prev) + expect(result).not.toBe(next) + expect(result[length]).toBe(shared) + }, + ) + + it('bounds recursion for cyclic records', () => { + const prev: any = { value: 1 } + const next: any = { value: 2 } + prev.self = prev + next.self = next + const result = replaceEqualDeep(prev, next) + expect(result.value).toBe(2) + expect(result.self).toBe(next) + }) + + it.each([0, 1])( + 'bounds recursion for cyclic arrays with %s preceding values', + (index) => { + const prev: Array = index ? [1] : [] + const next: Array = index ? [2] : [] + prev.push(prev) + next.push(next) + const result = replaceEqualDeep(prev, next) + let tail = result + for (let i = 0; i < 1000 && tail !== next; i++) { + tail = tail[index] + } + expect(tail).toBe(next) + if (index) { + expect(result[0]).toBe(2) + } + expect(prev[index]).toBe(prev) + expect(next[index]).toBe(next) + }, + ) + + it('preserves identity even when the recursion budget is exhausted', () => { + const value = [{ id: 1 }] + expect(replaceEqualDeep(value, value, false, 10_000)).toBe(value) + }) + it('should return the same object if the input objects are equal', () => { const obj = { a: 1, b: 2 } const result = replaceEqualDeep(obj, obj) @@ -35,20 +261,20 @@ describe('replaceEqualDeep', () => { }) describe('symbol properties', () => { - it('should look at symbol properties in the object comparison', () => { + it('passes objects with differing symbol values through untouched', () => { const propertyKey = Symbol('property') const obj1 = { a: 1, [propertyKey]: 2 } const obj2 = { a: 1, [propertyKey]: 3 } const result = replaceEqualDeep(obj1, obj2) - expect(result).toStrictEqual(obj2) + expect(result).toBe(obj2) }) - it('should copy over symbol properties when creating a new object', () => { + it('never copies an object with symbol properties partially', () => { const propertyKey = Symbol('property') const obj1 = { a: 1, [propertyKey]: 2 } const obj2 = { a: 3, [propertyKey]: 2 } const result = replaceEqualDeep(obj1, obj2) - expect(result).toStrictEqual(obj2) + expect(result).toBe(obj2) }) }) @@ -132,7 +358,6 @@ describe('replaceEqualDeep', () => { const result = replaceEqualDeep(prev, next) expect(result).toEqual(next) expect(result).not.toBe(prev) - expect(result).not.toBe(next) }) it('should return a copy when the previous value is a different array superset', () => { @@ -141,7 +366,6 @@ describe('replaceEqualDeep', () => { const result = replaceEqualDeep(prev, next) expect(result).toEqual(next) expect(result).not.toBe(prev) - expect(result).not.toBe(next) }) it('should return the previous value when the next value is an equal empty array', () => { @@ -182,7 +406,6 @@ describe('replaceEqualDeep', () => { expect(result).not.toBe(next) expect(result[0]).toBe(prev[0]) expect(result[1]).toBe(prev[1]) - expect(result[2]).not.toBe(next[2]) expect(result[2].b.b).toBe(next[2].b.b) expect(result[3]).toBe(prev[3]) }) @@ -250,6 +473,35 @@ describe('replaceEqualDeep', () => { expect(result).toBe(next) }) + // A hole and an extra key cancel out in `Object.keys(array).length`, so the + // key count alone would admit such an array and the copy would drop the key + // and fill the hole. + describe('non-dense arrays', () => { + it('passes a sparse array with an extra key through untouched', () => { + const next = Object.assign([1, ,], { extra: 'x' }) as Array + expect(Object.keys(next)).toHaveLength(next.length) + expect(replaceEqualDeep([1, 3], next)).toBe(next) + expect(replaceEqualDeep([1, undefined], next)).toBe(next) + }) + + it('does not reuse a sparse previous array with a compensating extra key', () => { + const prev = Object.assign([1, ,], { extra: 'old' }) + const next = [1, undefined] + expect(Object.keys(prev)).toHaveLength(prev.length) + expect(replaceEqualDeep(prev, next)).toBe(next) + }) + + it('still shares dense arrays', () => { + const prev = [1, 2, undefined] + expect(replaceEqualDeep(prev, [1, 2, undefined])).toBe(prev) + expect(replaceEqualDeep(prev, [1, 3, undefined])).toStrictEqual([ + 1, + 3, + undefined, + ]) + }) + }) + it('should replace all parent objects if some nested value changes', () => { const prev = { todo: { id: '1', meta: { createdAt: 0 }, state: { done: false } }, @@ -267,7 +519,6 @@ describe('replaceEqualDeep', () => { expect(result.todo).not.toBe(next.todo) expect(result.todo.id).toBe(next.todo.id) expect(result.todo.meta).toBe(prev.todo.meta) - expect(result.todo.state).not.toBe(next.todo.state) expect(result.todo.state.done).toBe(next.todo.state.done) expect(result.otherTodo).toBe(prev.otherTodo) }) @@ -295,7 +546,6 @@ describe('replaceEqualDeep', () => { expect(result.todos[0]).not.toBe(next.todos[0]) expect(result.todos[0]?.id).toBe(next.todos[0]?.id) expect(result.todos[0]?.meta).toBe(prev.todos[0]?.meta) - expect(result.todos[0]?.state).not.toBe(next.todos[0]?.state) expect(result.todos[0]?.state.done).toBe(next.todos[0]?.state.done) expect(result.todos[1]).toBe(prev.todos[1]) }) @@ -343,6 +593,447 @@ describe('replaceEqualDeep', () => { next.foo = 'baz' expect(replaceEqualDeep(current, next)).toEqual(next) }) + + describe('sharing children in changed containers', () => { + it('keeps earlier equal entries, including explicit undefined, when a later key differs', () => { + const prev = { a: { x: 1 }, b: undefined, c: 1 } + const next = { a: { x: 1 }, b: undefined, c: 2 } + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result).not.toBe(prev) + expect(result).not.toBe(next) + expect(result.a).toBe(prev.a) + expect('b' in result).toBe(true) + }) + + it('includes keys that only exist in next before the first difference', () => { + const prev: Record = { a: 1 } + const next = { b: undefined, a: 2 } + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect('b' in result).toBe(true) + }) + + it('keeps the key order of next', () => { + const prev = { a: 1, b: 2, c: 3 } + expect(Object.keys(replaceEqualDeep(prev, { c: 3, b: 2, a: 9 }))).toEqual( + ['c', 'b', 'a'], + ) + expect(Object.keys(replaceEqualDeep(prev, { b: 9, a: 1, c: 3 }))).toEqual( + ['b', 'a', 'c'], + ) + }) + + it('copies when only the key sets differ', () => { + const prev = { a: 1, b: 2 } + const next = { a: 1 } + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result).not.toBe(prev) + }) + + it('returns a longer array when next appends an explicit undefined', () => { + const prev = [1] + const next = [1, undefined] + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result).toHaveLength(2) + expect(result).not.toBe(prev) + }) + + it('shares equal array entries before and after the first difference', () => { + const prev = [{ a: 1 }, { b: 1 }, { c: 1 }] + const next = [{ a: 1 }, { b: 2 }, { c: 1 }] + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result[0]).toBe(prev[0]) + expect(result[1]).not.toBe(prev[1]) + expect(result[2]).toBe(prev[2]) + }) + }) + + describe('changed keys and recursive sharing', () => { + it('copies an empty array after a nonempty array', () => { + const prev = [1] + const result = replaceEqualDeep(prev, []) + expect(result).toStrictEqual([]) + expect(result).not.toBe(prev) + }) + + it('appends multiple explicit undefined array entries', () => { + const result = replaceEqualDeep([1], [1, undefined, undefined]) + expect(result).toStrictEqual([1, undefined, undefined]) + expect(hasOwn.call(result, 1)).toBe(true) + expect(hasOwn.call(result, 2)).toBe(true) + }) + it('returns prev for equal objects whose keys are ordered differently', () => { + const prev = { a: 1, b: { x: 1 }, c: 3 } + const next = { c: 3, a: 1, b: { x: 1 } } + expect(replaceEqualDeep(prev, next)).toBe(prev) + }) + + it('copies when a reordered next has a key that prev lacks', () => { + const prev: Record = { a: 1, b: 2 } + const next = { b: 2, c: undefined } + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result).not.toBe(prev) + expect('c' in result).toBe(true) + expect('a' in result).toBe(false) + }) + + it('includes keys that only exist in next after the first difference', () => { + const prev: Record = { a: 1, b: 2, d: 4 } + const next = { a: 9, b: 2, c: undefined } + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect('c' in result).toBe(true) + expect('d' in result).toBe(false) + }) + + it('shares equal children that come after the first difference', () => { + const prev = { a: 1, b: { x: 1 }, c: [1, 2], d: 'same' } + const next = { a: 2, b: { x: 1 }, c: [1, 2], d: 'same' } + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result.b).toBe(prev.b) + expect(result.c).toBe(prev.c) + }) + + it('recurses into changed children that come after the first difference', () => { + const prev = { a: 1, b: { x: 1, y: { z: 1 } } } + const next = { a: 2, b: { x: 2, y: { z: 1 } } } + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result.b).not.toBe(prev.b) + expect(result.b).not.toBe(next.b) + expect(result.b.y).toBe(prev.b.y) + }) + + it('takes the next value when an entry changes between object and primitive', () => { + const prev = { a: { x: 1 }, b: null, c: 's', d: [1], e: 0 } + const next = { a: null, b: { x: 1 }, c: {}, d: 's', e: [1] } + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result.b).toBe(next.b) + expect(result.c).toBe(next.c) + expect(result.e).toBe(next.e) + }) + + it('takes the next value when a later entry changes between object and primitive', () => { + const prev = { k: 0, a: { x: 1 }, b: undefined, c: [1] } + const next = { k: 1, a: undefined, b: { x: 1 }, c: 's' } + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result.b).toBe(next.b) + }) + + it('copies a shorter next array, sharing its equal prefix', () => { + const prev = [{ a: 1 }, { b: 1 }, { c: 1 }] + const next = [{ a: 1 }, { b: 1 }] + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result).not.toBe(prev) + expect(result).not.toBe(next) + expect(result[0]).toBe(prev[0]) + expect(result[1]).toBe(prev[1]) + }) + + it('copies a longer next array, sharing the equal prefix', () => { + const prev = [{ a: 1 }] + const next = [{ a: 1 }, { b: 1 }] + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result[0]).toBe(prev[0]) + expect(result[1]).toBe(next[1]) + }) + + it('copies a next object whose entries all match a larger prev', () => { + const prev = { a: { x: 1 }, b: 2 } + const next = { a: { x: 1 } } + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result).not.toBe(prev) + expect(result).not.toBe(next) + expect(result.a).toBe(prev.a) + }) + + it('handles a change in the last entry of a long array', () => { + const prev = Array.from({ length: 1024 }, (_, index) => ({ index })) + const next = prev.map((item, index) => + index === 1023 ? { index: -1 } : item, + ) + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result).not.toBe(prev) + expect(result[0]).toBe(prev[0]) + expect(result[1022]).toBe(prev[1022]) + expect(result[1023]).not.toBe(prev[1023]) + expect(result[1023]).toStrictEqual(next[1023]) + }) + + it('stops sharing beyond the depth limit', () => { + const nest = (depth: number) => { + let value: any = { leaf: true } + for (let i = 0; i < depth; i++) { + value = { child: value } + } + return value + } + const prev = nest(510) + const next = nest(510) + const result = replaceEqualDeep(prev, next) + expect(result).not.toBe(prev) + expect(result).toStrictEqual(next) + }) + }) +}) + +describe('nullReplaceEqualDeep', () => { + it('keeps a shared array prefix and reuses unchanged child results', () => { + const shared = { id: 1 } + const prev = [shared, { id: 2 }] + const next = [shared, { id: 3 }] + const result = nullReplaceEqualDeep(prev, next) + expect(Array.isArray(result)).toBe(true) + expect(result[0]).toBe(shared) + expect(Object.getPrototypeOf(result[0])).toBe(Object.prototype) + expect(result[1]).toBe(next[1]) + expect(Object.getPrototypeOf(result[1])).toBe(Object.prototype) + }) + + it('creates null-prototype copies on the first difference', () => { + const prev = { a: { x: 1 }, b: 2 } + const result = nullReplaceEqualDeep(prev, { a: { x: 1 }, b: 3 }) + expect(Object.getPrototypeOf(result)).toBeNull() + expect(result.a).toBe(prev.a) + expect(result.b).toBe(3) + }) + + it('creates null-prototype copies when only the key sets differ', () => { + const prev = { a: { x: 1 } } + const result = nullReplaceEqualDeep(prev, { a: { x: 1 }, b: undefined }) + expect(Object.getPrototypeOf(result)).toBeNull() + expect(result.a).toBe(prev.a) + expect('b' in result).toBe(true) + }) + + it('reuses a changed child when only the root needs a null-prototype copy', () => { + const prev = { shared: { x: 1 }, changed: { y: 1 } } + const next = { shared: { x: 1 }, changed: { y: 2 } } + const result = nullReplaceEqualDeep(prev, next) + expect(Object.getPrototypeOf(result)).toBeNull() + expect(result.changed).toBe(next.changed) + expect(result.shared).toBe(prev.shared) + }) + + it('creates null-prototype copies at every level that needs replacements', () => { + const prev = { outer: { shared: { id: 1 }, page: 1 } } + const next = { outer: { shared: { id: 1 }, page: 2 } } + const result = nullReplaceEqualDeep(prev, next) + expect(Object.getPrototypeOf(result)).toBeNull() + expect(Object.getPrototypeOf(result.outer)).toBeNull() + expect(result.outer.shared).toBe(prev.outer.shared) + expect(result.outer.page).toBe(2) + expect(prev).toStrictEqual({ outer: { shared: { id: 1 }, page: 1 } }) + expect(next).toStrictEqual({ outer: { shared: { id: 1 }, page: 2 } }) + }) + + it('stores an own __proto__ key instead of changing the prototype', () => { + const prev = { name: 'Bob', shared: { id: 1 } } + const next = JSON.parse( + '{"__proto__":{"isAdmin":true},"name":"Alice","shared":{"id":1}}', + ) + const result = nullReplaceEqualDeep(prev, next) + expect(result.shared).toBe(prev.shared) + expect(Object.getPrototypeOf(result)).toBeNull() + expect(hasOwn.call(result, '__proto__')).toBe(true) + expect(result['__proto__']).toEqual({ isAdmin: true }) + expect(result.name).toBe('Alice') + expect(({} as any).isAdmin).toBeUndefined() + }) + + it('returns prev when a plain next equals a null-prototype prev', () => { + const prev = Object.assign(Object.create(null), { a: 1, b: { c: 2 } }) + expect(nullReplaceEqualDeep(prev, { a: 1, b: { c: 2 } })).toBe(prev) + }) +}) + +describe('isPlainObject', () => { + it.each([ + [ + 'null-prototype record', + Object.assign(Object.create(null), { inherited: 1 }), + ], + ['null constructor', { constructor: null }], + ['undefined constructor', { constructor: undefined }], + ])('shares records inheriting from a %s', (_name, proto) => { + const prev = Object.assign(Object.create(proto), { + child: { id: 1 }, + page: 1, + }) + const equal = Object.assign(Object.create(proto), { + child: { id: 1 }, + page: 1, + }) + const next = Object.assign(Object.create(proto), { + child: { id: 1 }, + page: 2, + }) + + expect(isPlainObject(prev)).toBe(true) + expect(deepEqual(prev, equal)).toBe(true) + expect(replaceEqualDeep(prev, equal)).toBe(prev) + const result = replaceEqualDeep(prev, next) + expect(result.child).toBe(prev.child) + expect(result.page).toBe(2) + expect(Object.keys(result)).toEqual(['child', 'page']) + }) + + it.each([ + ['object literal', {}], + ['object literal with keys', { a: 1 }], + ['Object.create(null)', Object.create(null)], + ['object inheriting from a literal', Object.create({ inherited: 1 })], + ['JSON.parse result', JSON.parse('{"a":1}')], + ['frozen literal', Object.freeze({ a: 1 })], + ['new Object()', new Object()], + ['literal with an own constructor key', { constructor: 'foo' }], + [ + 'null-prototype object with an own constructor key', + Object.assign(Object.create(null), { constructor: 'foo' }), + ], + ['decoded search with a constructor key', decode('constructor=foo&page=1')], + ])('returns true for %s', (_name, value) => { + expect(isPlainObject(value)).toBe(true) + }) + + class Foo { + a = 1 + } + + it.each([ + ['null', null], + ['undefined', undefined], + ['number', 1], + ['string', 'a'], + ['boolean', true], + ['symbol', Symbol('s')], + ['function', () => {}], + ['empty array', []], + ['array', [1]], + ['Map', new Map()], + ['Set', new Set()], + ['Date', new Date()], + ['RegExp', /x/], + ['Promise', Promise.resolve()], + ['class instance', new Foo()], + ['Object.create(class prototype)', Object.create(Foo.prototype)], + [ + 'class instance with an own constructor key', + Object.assign(new Foo(), { constructor: 'foo' }), + ], + ])('returns false for %s', (_name, value) => { + expect(isPlainObject(value)).toBe(false) + }) + + it.each([ + ['string', 'foo'], + ['number', 1], + ['boolean', false], + ['null', null], + ['undefined', undefined], + ['array', ['a', 'b']], + ['object', { nested: 1 }], + ])('stays plain with a %s-valued constructor key', (_name, value) => { + expect(isPlainObject({ constructor: value })).toBe(true) + expect( + isPlainObject(Object.assign(Object.create(null), { constructor: value })), + ).toBe(true) + }) + + it.each([ + ['literal', Object.prototype], + ['null-prototype', null], + ])( + 'treats a constructor key as data in %s search records', + (_name, proto) => { + const makeSearch = (constructor: string) => + Object.assign(Object.create(proto), { + constructor, + filters: { status: 'open' }, + }) + const share = proto === null ? nullReplaceEqualDeep : replaceEqualDeep + + const prev = makeSearch('foo') + const equal = makeSearch('foo') + const changed = makeSearch('bar') + + expect(isPlainObject(prev)).toBe(true) + expect(deepEqual(prev, equal)).toBe(true) + expect(share(prev, equal)).toBe(prev) + + expect(deepEqual(prev, changed)).toBe(false) + const result = share(prev, changed) + expect(result).not.toBe(prev) + expect(result.constructor).toBe('bar') + expect(result.filters).toBe(prev.filters) + expect(Object.getPrototypeOf(result)).toBe(proto) + }, + ) + + it('shares decoded search records that carry a constructor key', () => { + const prev = decode('constructor=foo&page=1') + expect(prev.constructor).toBe('foo') + + expect(nullReplaceEqualDeep(prev, decode('constructor=foo&page=1'))).toBe( + prev, + ) + expect(deepEqual(prev, decode('page=1&constructor=foo'))).toBe(true) + + const changed = nullReplaceEqualDeep(prev, decode('constructor=bar&page=1')) + expect(changed).not.toBe(prev) + expect(changed.constructor).toBe('bar') + expect(changed.page).toBe(1) + + const repeated = decode('constructor=a&constructor=b') + expect(repeated.constructor).toStrictEqual(['a', 'b']) + expect(deepEqual(repeated, decode('constructor=a&constructor=b'))).toBe( + true, + ) + }) + + it('keeps class instances opaque for structural sharing and equality', () => { + const prev = new Foo() + const next = new Foo() + expect(replaceEqualDeep(prev, next)).toBe(next) + expect(deepEqual(prev, next)).toBe(false) + expect(deepEqual({ foo: prev }, { foo: prev })).toBe(true) + }) + + it.each([null, undefined])( + 'keeps built-ins opaque with an own constructor valued %s', + (constructor) => { + for (const [prev, next] of [ + [new Date(0), new Date(1)], + [new Map([['value', 0]]), new Map([['value', 1]])], + [/before/, /after/], + ]) { + Object.assign(prev!, { constructor }) + Object.assign(next!, { constructor }) + expect(isPlainObject(prev)).toBe(false) + expect(deepEqual(prev, next)).toBe(false) + expect(replaceEqualDeep(prev, next)).toBe(next) + } + }, + ) + + it('treats null-prototype and literal objects alike', () => { + const nullProto = Object.assign(Object.create(null), { a: 1 }) + expect(deepEqual(nullProto, { a: 1 })).toBe(true) + expect(deepEqual({ a: 1 }, nullProto)).toBe(true) + expect(replaceEqualDeep(nullProto, { a: 1 })).toBe(nullProto) + }) }) describe('isPlainArray', () => { @@ -360,43 +1051,43 @@ describe('deepEqual', () => { it('should return `true` for equal objects', () => { const a = { a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] } const b = { a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] } - expect(deepEqual(a, b, { partial })).toEqual(true) - expect(deepEqual(b, a, { partial })).toEqual(true) + expect(deepEqual(a, b, partial)).toEqual(true) + expect(deepEqual(b, a, partial)).toEqual(true) }) it('should return `false` for non equal objects', () => { const a = { a: { b: 'b' }, c: 'c' } const b = { a: { b: 'c' }, c: 'c' } - expect(deepEqual(a, b, { partial })).toEqual(false) - expect(deepEqual(b, a, { partial })).toEqual(false) + expect(deepEqual(a, b, partial)).toEqual(false) + expect(deepEqual(b, a, partial)).toEqual(false) }) it('should return `true` for equal objects and ignore `undefined` properties', () => { const a = { a: 'a', b: undefined, c: 'c' } const b = { a: 'a', c: 'c' } - expect(deepEqual(a, b, { partial })).toEqual(true) - expect(deepEqual(b, a, { partial })).toEqual(true) + expect(deepEqual(a, b, partial)).toEqual(true) + expect(deepEqual(b, a, partial)).toEqual(true) }) it('should return `true` for equal objects and ignore `undefined` nested properties', () => { const a = { a: { b: 'b', x: undefined }, c: 'c' } const b = { a: { b: 'b' }, c: 'c', d: undefined } - expect(deepEqual(a, b, { partial })).toEqual(true) - expect(deepEqual(b, a, { partial })).toEqual(true) + expect(deepEqual(a, b, partial)).toEqual(true) + expect(deepEqual(b, a, partial)).toEqual(true) }) it('should return `true` for equal arrays and ignore `undefined` object properties', () => { const a = { a: { b: 'b' }, c: undefined } const b = { a: { b: 'b' } } - expect(deepEqual([a], [b], { partial })).toEqual(true) - expect(deepEqual([b], [a], { partial })).toEqual(true) + expect(deepEqual([a], [b], partial)).toEqual(true) + expect(deepEqual([b], [a], partial)).toEqual(true) }) it('should return `true` for equal arrays and ignore nested `undefined` object properties', () => { const a = { a: { b: 'b', x: undefined }, c: 'c' } const b = { a: { b: 'b' }, c: 'c' } - expect(deepEqual([a], [b], { partial })).toEqual(true) - expect(deepEqual([b], [a], { partial })).toEqual(true) + expect(deepEqual([a], [b], partial)).toEqual(true) + expect(deepEqual([b], [a], partial)).toEqual(true) }) }) @@ -407,15 +1098,15 @@ describe('deepEqual', () => { it('should return `false` for objects', () => { const a = { a: { b: 'b', x: undefined }, c: 'c' } const b = { a: { b: 'b' }, c: 'c', d: undefined } - expect(deepEqual(a, b, { partial, ignoreUndefined })).toEqual(false) - expect(deepEqual(b, a, { partial, ignoreUndefined })).toEqual(false) + expect(deepEqual(a, b, partial, !ignoreUndefined)).toEqual(false) + expect(deepEqual(b, a, partial, !ignoreUndefined)).toEqual(false) }) it('should return `false` for arrays', () => { const a = { a: { b: 'b', x: undefined }, c: 'c' } const b = { a: { b: 'b' }, c: 'c' } - expect(deepEqual([a], [b], { partial, ignoreUndefined })).toEqual(false) - expect(deepEqual([b], [a], { partial, ignoreUndefined })).toEqual(false) + expect(deepEqual([a], [b], partial, !ignoreUndefined)).toEqual(false) + expect(deepEqual([b], [a], partial, !ignoreUndefined)).toEqual(false) }) }) describe('partial = true', () => { @@ -423,15 +1114,15 @@ describe('deepEqual', () => { it('should return `true` for objects', () => { const a = { a: { b: 'b' }, c: 'c' } const b = { a: { b: 'b' }, c: 'c', d: undefined } - expect(deepEqual(a, b, { partial, ignoreUndefined })).toEqual(true) - expect(deepEqual(b, a, { partial, ignoreUndefined })).toEqual(true) + expect(deepEqual(a, b, partial, !ignoreUndefined)).toEqual(true) + expect(deepEqual(b, a, partial, !ignoreUndefined)).toEqual(true) }) it('should return `true` for arrays', () => { const a = { a: { b: 'b', x: undefined }, c: 'c' } const b = { a: { b: 'b' }, c: 'c' } - expect(deepEqual([a], [b], { partial, ignoreUndefined })).toEqual(true) - expect(deepEqual([b], [a], { partial, ignoreUndefined })).toEqual(true) + expect(deepEqual([a], [b], partial, !ignoreUndefined)).toEqual(true) + expect(deepEqual([b], [a], partial, !ignoreUndefined)).toEqual(true) }) }) }) @@ -440,15 +1131,15 @@ describe('deepEqual', () => { it('correctly compares partially equal objects', () => { const a = { a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }] } const b = { a: { b: 'b' }, c: 'c' } - expect(deepEqual(a, b, { partial: true })).toEqual(true) - expect(deepEqual(b, a, { partial: true })).toEqual(false) + expect(deepEqual(a, b, true)).toEqual(true) + expect(deepEqual(b, a, true)).toEqual(false) }) it('correctly compares partially equal objects and ignores `undefined` object properties', () => { const a = { a: { b: 'b' }, c: 'c', d: [{ d: 'd ' }], e: undefined } const b = { a: { b: 'b' }, c: 'c', d: undefined } - expect(deepEqual(a, b, { partial: true })).toEqual(true) - expect(deepEqual(b, a, { partial: true })).toEqual(false) + expect(deepEqual(a, b, true)).toEqual(true) + expect(deepEqual(b, a, true)).toEqual(false) }) }) @@ -485,7 +1176,7 @@ describe('deepEqual', () => { Object.prototype.x = 'x' const a = { a: 1 } const b = { a: 1 } - expect(deepEqual(a, b, { ignoreUndefined: false })).toEqual(true) + expect(deepEqual(a, b, false, true)).toEqual(true) }, ) @@ -499,75 +1190,6 @@ describe('deepEqual', () => { }) describe('decodePath', () => { - it('should decode a path segment with no ignored items existing', () => { - const itemsToCheck = ['%25', '%5C'] - const stringToCheck = - 'https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B' - const expectedResult = 'https://mozilla.org/?x=шеллы' - - const result = decodePath(stringToCheck, itemsToCheck) - - expect(result).toBe(expectedResult) - }) - - it('should decode a path segment with one ignored character and one ignored item existing', () => { - const itemsToCheck = ['%25'] - const stringToCheck = - 'https://mozilla.org/?x=%25%D1%88%D0%B5%5C%D0%BB%D0%BB%D1%8B' - const expectedResult = 'https://mozilla.org/?x=%25ше\\ллы' - - const result = decodePath(stringToCheck, itemsToCheck) - - expect(result).toBe(expectedResult) - }) - - it('should decode a path segment with multiple ignored characters and first ignored item existing', () => { - const itemsToCheck = ['%25', '%5C'] - let stringToCheck = - 'https://mozilla.org/?x=%25%D1%88%D0%B5%D0%BB%D0%BB%D1%8B' - let expectedResult = 'https://mozilla.org/?x=%25шеллы' - - let result = decodePath(stringToCheck, itemsToCheck) - - expect(result).toBe(expectedResult) - - stringToCheck = 'https://mozilla.org/?x=%D1%88%D0%B5%5C%D0%BB%D0%BB%D1%8B' - expectedResult = 'https://mozilla.org/?x=ше%5Cллы' - - result = decodePath(stringToCheck, itemsToCheck) - - expect(result).toBe(expectedResult) - }) - - it('should decode a path segment with multiple ignored characters and other ignored item existing', () => { - const itemsToCheck = ['%25', '%5C'] - let stringToCheck = - 'https://mozilla.org/?x=%5C%D1%88%D0%B5%D0%BB%D0%BB%D1%8B' - let expectedResult = 'https://mozilla.org/?x=%5Cшеллы' - - let result = decodePath(stringToCheck, itemsToCheck) - - expect(result).toBe(expectedResult) - - stringToCheck = 'https://mozilla.org/?x=%D1%88%D0%B5%5C%D0%BB%D0%BB%D1%8B' - expectedResult = 'https://mozilla.org/?x=ше%5Cллы' - - result = decodePath(stringToCheck, itemsToCheck) - - expect(result).toBe(expectedResult) - }) - - it('should decode a path segment with multiple ignored characters and multiple ignored items existing', () => { - const itemsToCheck = ['%25', '%5C'] - const stringToCheck = - 'https://mozilla.org/?x=%25%D1%88%D0%B5%5C%D0%BB%D0%BB%D1%8B' - const expectedResult = 'https://mozilla.org/?x=%25ше%5Cллы' - - const result = decodePath(stringToCheck, itemsToCheck) - - expect(result).toBe(expectedResult) - }) - it('should decode a path segment, ignoring `%` and `\\` by default, with multiple ignored items existing', () => { const stringToCheck = 'https://mozilla.org/?x=%25%D1%88%D0%B5%5C%D0%BB%D0%BB%D1%8B%2F' @@ -612,4 +1234,613 @@ describe('decodePath', () => { expectedResultWithLowerCase, ) }) + + describe('open redirect prevention', () => { + it('should keep CR (%0d) encoded to prevent open redirect', () => { + // %0d stays encoded — no decoding, no stripping, no path mismatch + // Output is uppercase hex per RFC 3986 + const result = decodePath('/%0d/google.com/') + expect(result).toBe('/%0D/google.com/') + expect(result).not.toMatch(/^\/\//) + }) + + it('should keep LF (%0a) encoded to prevent open redirect', () => { + const result = decodePath('/%0a/evil.com/') + expect(result).toBe('/%0A/evil.com/') + expect(result).not.toMatch(/^\/\//) + }) + + it('should keep CRLF (%0d%0a) encoded to prevent open redirect', () => { + const result = decodePath('/%0d%0a/evil.com/') + expect(result).toBe('/%0D%0A/evil.com/') + expect(result).not.toMatch(/^\/\//) + }) + + it('should keep multiple control characters encoded', () => { + const result = decodePath('/%0d%0d%0d/evil.com/') + expect(result).toBe('/%0D%0D%0D/evil.com/') + expect(result).not.toMatch(/^\/\//) + }) + + it('should keep null bytes encoded', () => { + const result = decodePath('/%00/test/') + expect(result).toBe('/%00/test/') + }) + + it('should handle normal paths unchanged', () => { + expect(decodePath('/users/profile/')).toBe('/users/profile/') + expect(decodePath('/api/v1/data')).toBe('/api/v1/data') + }) + }) + + describe('WHATWG path percent-encode set preserved', () => { + it('should keep curly braces encoded', () => { + const result = decodePath('/%7B%7Bapp_name%7D%7D/Makefile') + expect(result).toBe('/%7B%7Bapp_name%7D%7D/Makefile') + }) + + it('should keep angle brackets encoded', () => { + expect(decodePath('/%3Ctest%3E')).toBe('/%3Ctest%3E') + }) + + it('should keep double quotes encoded', () => { + expect(decodePath('/foo%22bar')).toBe('/foo%22bar') + }) + + it('should keep backticks encoded', () => { + expect(decodePath('/back%60tick')).toBe('/back%60tick') + }) + + it('should decode space (handled by encodePathLikeUrl for outgoing URLs)', () => { + expect(decodePath('/file%20name')).toBe('/file name') + }) + + it('should still decode safe characters', () => { + // Regular letters/unicode should still be decoded + expect(decodePath('/%D1%88%D0%B5%D0%BB%D0%BB%D1%8B')).toBe('/шеллы') + }) + }) +}) + +/** + * Tests for the key handling of replaceEqualDeep. + * + * Plain objects are compared and copied by their enumerable own string keys. + * Objects with symbol keys (checked on `next`) or non-enumerable keys are opaque: + * `next` passes through untouched, so no data is dropped and no stale object is + * reused (Apollo's preloadQuery refs carry symbol keys, see #4237). + */ +describe('key handling (via replaceEqualDeep)', () => { + describe('plain objects with string keys only', () => { + it('should handle empty objects', () => { + const prev = {} + const next = {} + expect(replaceEqualDeep(prev, next)).toBe(prev) + }) + + it('should handle objects with single key', () => { + const prev = { a: 1 } + const next = { a: 1 } + expect(replaceEqualDeep(prev, next)).toBe(prev) + }) + + it('should handle objects with many keys', () => { + const prev = { + a: 1, + b: 2, + c: 3, + d: 4, + e: 5, + f: 6, + g: 7, + h: 8, + i: 9, + j: 10, + } + const next = { + a: 1, + b: 2, + c: 3, + d: 4, + e: 5, + f: 6, + g: 7, + h: 8, + i: 9, + j: 10, + } + expect(replaceEqualDeep(prev, next)).toBe(prev) + }) + + it('should handle objects with numeric string keys', () => { + const prev = { '0': 'a', '1': 'b', '2': 'c' } + const next = { '0': 'a', '1': 'b', '2': 'c' } + expect(replaceEqualDeep(prev, next)).toBe(prev) + }) + + it('should handle objects with special string keys', () => { + const prev = { + 'key-with-dash': 1, + 'key.with.dot': 2, + 'key with space': 3, + } + const next = { + 'key-with-dash': 1, + 'key.with.dot': 2, + 'key with space': 3, + } + expect(replaceEqualDeep(prev, next)).toBe(prev) + }) + + it('should detect differences in objects with string keys', () => { + const prev = { a: 1, b: 2, c: 3 } + const next = { a: 1, b: 99, c: 3 } + const result = replaceEqualDeep(prev, next) + expect(result).not.toBe(prev) + expect(result).toEqual(next) + }) + }) + + describe('objects with symbol keys pass through untouched', () => { + it('returns next for a single symbol key', () => { + const sym = Symbol('test') + const prev = { [sym]: 1 } + const next = { [sym]: 1 } + expect(replaceEqualDeep(prev, next)).toBe(next) + }) + + it('returns next for multiple symbol keys', () => { + const sym1 = Symbol('a') + const sym2 = Symbol('b') + const sym3 = Symbol('c') + const prev = { [sym1]: 1, [sym2]: 2, [sym3]: 3 } + const next = { [sym1]: 1, [sym2]: 2, [sym3]: 3 } + expect(replaceEqualDeep(prev, next)).toBe(next) + }) + + it('keeps differing symbol values', () => { + const sym = Symbol('test') + const prev = { [sym]: 1 } + const next = { [sym]: 2 } + const result = replaceEqualDeep(prev, next) + expect(result).not.toBe(prev) + expect(result[sym]).toBe(2) + }) + + it('returns next for global symbols', () => { + const sym = Symbol.for('global.test.key') + const prev = { [sym]: 'value' } + const next = { [sym]: 'value' } + expect(replaceEqualDeep(prev, next)).toBe(next) + }) + + it('does not share a symbol-keyed prev when next has no symbols', () => { + const sym = Symbol('test') + const prev = { a: 1, [sym]: 1 } + const next = { a: 1 } + expect(replaceEqualDeep(prev, next)).toBe(next) + }) + + it('removes a previous non-enumerable symbol', () => { + const sym = Symbol('hidden') + const prev = Object.defineProperty({ a: 1 }, sym, { value: 'old' }) + const next = { a: 1 } + expect(replaceEqualDeep(prev, next)).toBe(next) + }) + + it.each(['first', 'last'])( + 'removes nested symbols in the %s entry', + (position) => { + const sym = Symbol('metadata') + const removed = { a: 1, [sym]: 'old' } + const shared = { b: 2 } + const prev = + position === 'first' + ? { removed, shared, changed: 0 } + : { changed: 0, shared, removed } + const next = + position === 'first' + ? { removed: { a: 1 }, shared: { b: 2 }, changed: 1 } + : { changed: 1, shared: { b: 2 }, removed: { a: 1 } } + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(result.removed).toBe(next.removed) + expect(result.shared).toBe(shared) + }, + ) + + it('removes symbols by reusing a null-prototype next object', () => { + const sym = Symbol('metadata') + const prev = Object.assign(Object.create(null), { a: 1, [sym]: 'old' }) + const next = Object.assign(Object.create(null), { a: 1 }) + expect(nullReplaceEqualDeep(prev, next)).toBe(next) + }) + + it('preserves incoming values when previous symbols exist in null-prototype mode', () => { + const sym = Symbol('metadata') + const prev = { child: { a: 1 }, page: 1, [sym]: 'old' } + const next = { child: { a: 1 }, page: 2 } + const result = nullReplaceEqualDeep(prev, next) + expect({ ...result }).toStrictEqual(next) + expect(Object.getOwnPropertySymbols(result)).toEqual([]) + expect(result.page).toBe(2) + }) + + it('keeps an opaque next object unchanged in null-prototype mode', () => { + const next = { child: { a: 1 }, [Symbol('metadata')]: 'kept' } + const result = nullReplaceEqualDeep({ child: { a: 1 } }, next) + expect(result).toBe(next) + expect(Object.getPrototypeOf(result)).toBe(Object.prototype) + }) + + it('preserves incoming values when previous symbols accompany changed string keys', () => { + const sym = Symbol('metadata') + const prev = { changed: 0, child: { a: 1 }, [sym]: 'old' } + const next = { changed: 1, child: { a: 1 } } + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(prev[sym]).toBe('old') + }) + + it('preserves incoming values when previous symbols accompany removed string keys', () => { + const sym = Symbol('metadata') + const prev = { removed: 0, child: { a: 1 }, [sym]: 'old' } + const next = { child: { a: 1 } } + const result = replaceEqualDeep(prev, next) + expect(result).toStrictEqual(next) + expect(prev[sym]).toBe('old') + }) + }) + + describe('objects with mixed string and symbol keys', () => { + it('returns next when both string and symbol keys are present', () => { + const sym = Symbol('test') + const prev = { a: 1, b: 2, [sym]: 3 } + const next = { a: 1, b: 2, [sym]: 3 } + expect(replaceEqualDeep(prev, next)).toBe(next) + }) + + it('keeps string differences when symbols present', () => { + const sym = Symbol('test') + const prev = { a: 1, b: 2, [sym]: 3 } + const next = { a: 1, b: 99, [sym]: 3 } + const result = replaceEqualDeep(prev, next) + expect(result).not.toBe(prev) + expect(result.b).toBe(99) + expect(result[sym]).toBe(3) + }) + + it('keeps symbol differences when strings present', () => { + const sym = Symbol('test') + const prev = { a: 1, b: 2, [sym]: 3 } + const next = { a: 1, b: 2, [sym]: 99 } + const result = replaceEqualDeep(prev, next) + expect(result).not.toBe(prev) + expect(result.a).toBe(1) + expect(result[sym]).toBe(99) + }) + + it('shares plain siblings around a nested symbol-keyed object', () => { + const sym = Symbol('nested') + const prev = { + outer: { inner: 1, [sym]: { deep: 'value' } }, + plain: { x: 1 }, + } + const next = { + outer: { inner: 1, [sym]: { deep: 'value' } }, + plain: { x: 1 }, + } + const result = replaceEqualDeep(prev, next) + expect(result).not.toBe(prev) + expect(result.outer).toBe(next.outer) + expect(result.plain).toBe(prev.plain) + }) + }) + + describe('non-enumerable properties', () => { + it('should treat objects with non-enumerable string property as non-plain', () => { + const prev: Record = { a: 1 } + Object.defineProperty(prev, 'hidden', { value: 2, enumerable: false }) + const next: Record = { a: 1 } + Object.defineProperty(next, 'hidden', { value: 2, enumerable: false }) + + // Non-plain objects should return next, not prev (no structural sharing) + const result = replaceEqualDeep(prev, next) + expect(result).toBe(next) + }) + + it('should treat objects with non-enumerable symbol property as non-plain', () => { + const sym = Symbol('hidden') + const prev: Record = { a: 1 } + Object.defineProperty(prev, sym, { value: 2, enumerable: false }) + const next: Record = { a: 1 } + Object.defineProperty(next, sym, { value: 2, enumerable: false }) + + // Non-plain objects should return next, not prev + const result = replaceEqualDeep(prev, next) + expect(result).toBe(next) + }) + + it('should handle mix of enumerable and non-enumerable properties', () => { + const prev: Record = { visible: 1 } + Object.defineProperty(prev, 'hidden', { value: 2, enumerable: false }) + const next = { visible: 1 } + + // prev is non-plain (has non-enumerable), next is plain + const result = replaceEqualDeep(prev, next) + expect(result).toBe(next) + }) + + it('should handle non-enumerable property that shadows a string key', () => { + const prev = Object.create(null) + prev.a = 1 + Object.defineProperty(prev, 'b', { value: 2, enumerable: false }) + + const next = Object.create(null) + next.a = 1 + next.b = 2 // enumerable version + + const result = replaceEqualDeep(prev, next) + expect(result).toBe(next) + }) + }) + + describe('edge cases for key enumeration', () => { + it('should handle frozen objects as non-plain (configurable is false)', () => { + const prev = Object.freeze({ a: 1, b: 2 }) + const next = Object.freeze({ a: 1, b: 2 }) + + // Frozen objects have all properties as non-configurable but still enumerable + // They should still work with replaceEqualDeep + const result = replaceEqualDeep(prev, next) + expect(result).toBe(prev) + }) + + it('should handle sealed objects', () => { + const prev = Object.seal({ a: 1, b: 2 }) + const next = Object.seal({ a: 1, b: 2 }) + + const result = replaceEqualDeep(prev, next) + expect(result).toBe(prev) + }) + + it('should handle objects created with Object.create(null)', () => { + const prev = Object.create(null) + prev.a = 1 + prev.b = 2 + + const next = Object.create(null) + next.a = 1 + next.b = 2 + + const result = replaceEqualDeep(prev, next) + expect(result).toBe(prev) + }) + + it('should handle objects with inherited properties (only own props checked)', () => { + const proto = { inherited: 'value' } + const prev = Object.create(proto) + prev.own = 1 + + const next = Object.create(proto) + next.own = 1 + + const result = replaceEqualDeep(prev, next) + expect(result).toBe(prev) + }) + + it('should not be confused by Object.prototype properties', () => { + // Ensure hasOwnProperty, toString, etc. don't interfere + const prev = { hasOwnProperty: 1, toString: 2, valueOf: 3 } + const next = { hasOwnProperty: 1, toString: 2, valueOf: 3 } + const result = replaceEqualDeep(prev, next) + expect(result).toBe(prev) + }) + }) + + describe('performance-critical scenarios (typical router state)', () => { + it('should efficiently handle typical router location object', () => { + const prev = { + pathname: '/users/123', + search: '?tab=settings', + hash: '#section', + state: { key: 'abc123' }, + } + const next = { + pathname: '/users/123', + search: '?tab=settings', + hash: '#section', + state: { key: 'abc123' }, + } + expect(replaceEqualDeep(prev, next)).toBe(prev) + }) + + it('should efficiently handle typical router match object', () => { + const prev = { + id: 'route-1', + routeId: '/users/$userId', + pathname: '/users/123', + params: { userId: '123' }, + search: {}, + fullPath: '/users/$userId', + loaderData: { user: { name: 'John' } }, + } + const next = { + id: 'route-1', + routeId: '/users/$userId', + pathname: '/users/123', + params: { userId: '123' }, + search: {}, + fullPath: '/users/$userId', + loaderData: { user: { name: 'John' } }, + } + expect(replaceEqualDeep(prev, next)).toBe(prev) + }) + + it('should efficiently handle array of matches', () => { + const prev = [ + { id: '1', routeId: '__root__', pathname: '/', params: {} }, + { id: '2', routeId: '/users', pathname: '/users', params: {} }, + { + id: '3', + routeId: '/users/$userId', + pathname: '/users/123', + params: { userId: '123' }, + }, + ] + const next = [ + { id: '1', routeId: '__root__', pathname: '/', params: {} }, + { id: '2', routeId: '/users', pathname: '/users', params: {} }, + { + id: '3', + routeId: '/users/$userId', + pathname: '/users/123', + params: { userId: '123' }, + }, + ] + expect(replaceEqualDeep(prev, next)).toBe(prev) + }) + + it('preserves identity of unchanged nested subtrees when one leaf changes', () => { + const prev = { + search: { q: 'hello', f: 'live' }, + params: { username: 'elonmusk', tweetId: '123' }, + loaderData: { + user: { id: '44196397', name: 'Elon' }, + tabs: ['a', 'b'], + }, + } + const next = { + search: { q: 'hello', f: 'live' }, + params: { username: 'elonmusk', tweetId: '123' }, + loaderData: { + user: { id: '44196397', name: 'Musk' }, + tabs: ['a', 'b'], + }, + } + const result = replaceEqualDeep(prev, next) + // user.name changed -> top object is new, but every unchanged subtree + // (including the array) keeps its previous reference for cheap memo checks. + expect(result).not.toBe(prev) + expect(result.search).toBe(prev.search) + expect(result.params).toBe(prev.params) + expect(result.loaderData.tabs).toBe(prev.loaderData.tabs) + expect(result.loaderData.user).not.toBe(prev.loaderData.user) + expect(result.loaderData.user.name).toBe('Musk') + }) + + it('bails to next for a nested object carrying a non-enumerable prop', () => { + const prevInner: Record = { a: 1 } + Object.defineProperty(prevInner, 'hidden', { + value: 2, + enumerable: false, + }) + const nextInner: Record = { a: 1 } + Object.defineProperty(nextInner, 'hidden', { + value: 2, + enumerable: false, + }) + const prev = { shared: { x: 1 }, inner: prevInner } + const next = { shared: { x: 1 }, inner: nextInner } + const result = replaceEqualDeep(prev, next) + // inner is not clone-friendly -> returns nextInner; sibling subtree shared. + expect(result.inner).toBe(nextInner) + expect(result.shared).toBe(prev.shared) + }) + }) +}) + +describe('escapeHtml', () => { + it('should escape less-than sign', () => { + expect(escapeHtml('<')).toBe('\\u003c') + }) + + it('should escape greater-than sign', () => { + expect(escapeHtml('>')).toBe('\\u003e') + }) + + it('should escape ampersand', () => { + expect(escapeHtml('&')).toBe('\\u0026') + }) + + it('should escape line separator (U+2028)', () => { + expect(escapeHtml('\u2028')).toBe('\\u2028') + }) + + it('should escape paragraph separator (U+2029)', () => { + expect(escapeHtml('\u2029')).toBe('\\u2029') + }) + + it('should escape multiple characters', () => { + expect(escapeHtml('')).toBe( + '\\u003cscript\\u003ealert("XSS")\\u003c/script\\u003e', + ) + }) + + it('should handle script tag injection attempt in JSON', () => { + const maliciousKey = '' + const json = JSON.stringify({ key: maliciousKey }) + const escaped = escapeHtml(json) + + // The escaped version should not contain literal < or > characters + expect(escaped).not.toContain('<') + expect(escaped).not.toContain('>') + + // The escaped version should still be valid JSON when evaluated + // (the escape sequences are valid in JavaScript strings) + expect(escaped).toContain('\\u003c') + expect(escaped).toContain('\\u003e') + }) + + it('should return strings without special characters unchanged', () => { + const safe = 'hello world 123' + expect(escapeHtml(safe)).toBe(safe) + }) + + it('should handle empty string', () => { + expect(escapeHtml('')).toBe('') + }) + + it('should handle mixed content', () => { + expect(escapeHtml('ac&d\u2028e\u2029f')).toBe( + 'a\\u003cb\\u003ec\\u0026d\\u2028e\\u2029f', + ) + }) +}) + +describe('encodePathLikeUrl', () => { + it('should return path unchanged if no non-ASCII characters', () => { + expect(encodePathLikeUrl('/foo/bar/baz')).toBe('/foo/bar/baz') + }) + + it('should encode non-ASCII characters', () => { + expect(encodePathLikeUrl('/path/caf\u00e9')).toBe('/path/caf%C3%A9') + }) + + it('should encode unicode characters in path segments', () => { + expect(encodePathLikeUrl('/users/\u4e2d\u6587/profile')).toBe( + '/users/%E4%B8%AD%E6%96%87/profile', + ) + }) + + it('should encode spaces but preserve other ASCII special characters', () => { + // encodePathLikeUrl encodes whitespace and non-ASCII, but not other ASCII special chars + expect(encodePathLikeUrl('/path/file name.pdf')).toBe( + '/path/file%20name.pdf', + ) + expect(encodePathLikeUrl('/path/file[1].pdf')).toBe('/path/file[1].pdf') + expect(encodePathLikeUrl('/path#section')).toBe('/path#section') + }) + + it('should handle mixed ASCII and non-ASCII characters', () => { + expect(encodePathLikeUrl('/path/caf\u00e9 (copy).pdf')).toBe( + '/path/caf%C3%A9%20(copy).pdf', + ) + }) + + it('should handle emoji characters', () => { + expect(encodePathLikeUrl('/path/\u{1F600}/file')).toBe( + '/path/%F0%9F%98%80/file', + ) + }) }) diff --git a/packages/router-core/tsconfig.build.json b/packages/router-core/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/router-core/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/router-core/tsconfig.json b/packages/router-core/tsconfig.json index e99dc8130a..34cb3c4dc9 100644 --- a/packages/router-core/tsconfig.json +++ b/packages/router-core/tsconfig.json @@ -1,4 +1,16 @@ { "extends": "../../tsconfig.json", - "include": ["src", "vite.config.ts", "tests", "vite-minify-plugin.ts"] + "compilerOptions": { + "types": ["node"], + "paths": { + "@tanstack/router-core/isServer": ["./src/isServer/development.ts"] + } + }, + "include": [ + "src", + "vite.config.ts", + "tests", + "vite-minify-plugin.ts", + "benchmarks/ssr-streaming/worker.ts" + ] } diff --git a/packages/router-core/vite-minify-plugin.ts b/packages/router-core/vite-minify-plugin.ts index e379f16ea4..adeb8fb5c2 100644 --- a/packages/router-core/vite-minify-plugin.ts +++ b/packages/router-core/vite-minify-plugin.ts @@ -14,8 +14,16 @@ export default function minifyScriptPlugin(): Plugin { target: 'esnext', }) + // Source files may use `export default …`. esbuild preserves that, + // but we need a bare expression so it can be embedded in inline + // scripts (e.g. as an IIFE: `(function(…){…})(args)`). + // Strip `export default` and any trailing semicolon/whitespace. + const normalizedCode = result.code + .replace(/^export default /, '') + .replace(/;?\s*$/, '') + return { - code: `export default ${JSON.stringify(result.code)};`, + code: `export default ${JSON.stringify(normalizedCode)};`, map: null, } }, diff --git a/packages/router-core/vite.config.ts b/packages/router-core/vite.config.ts index a27d8d3535..97859dda97 100644 --- a/packages/router-core/vite.config.ts +++ b/packages/router-core/vite.config.ts @@ -1,24 +1,57 @@ +import path from 'node:path' import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' import minifyScriptPlugin from './vite-minify-plugin' import packageJson from './package.json' import type { ViteUserConfig } from 'vitest/config' const config = defineConfig({ plugins: [minifyScriptPlugin()] as ViteUserConfig['plugins'], + build: { + rolldownOptions: { + output: { + topLevelVar: false, + }, + }, + }, test: { name: packageJson.name, dir: './tests', watch: false, environment: 'jsdom', typecheck: { enabled: true }, + // Perf tests are gated by env var and excluded from default runs. + // To run: RUN_BACKPRESSURE_PERF=1 pnpm vitest run transformStreamBackpressure + exclude: + process.env.RUN_BACKPRESSURE_PERF === '1' + ? ['**/node_modules/**'] + : ['**/*.perf.test.ts', '**/node_modules/**'], + alias: { + // For tests only, resolve to development.ts which returns undefined + // so that router.isServer fallback is used + '@tanstack/router-core/isServer': path.resolve( + __dirname, + 'src/isServer/development.ts', + ), + }, }, }) export default mergeConfig( config, tanstackViteConfig({ - entry: ['./src/index.ts', './src/ssr/client.ts', './src/ssr/server.ts'], + entry: [ + './src/index.ts', + './src/ssr/client.ts', + './src/ssr/server.ts', + './src/scroll-restoration-script/client.ts', + './src/scroll-restoration-script/server.ts', + './src/isServer/server.ts', + './src/isServer/client.ts', + './src/isServer/development.ts', + ], srcDir: './src', + externalDeps: ['@tanstack/router-core/isServer'], + tsconfigPath: './tsconfig.build.json', }), ) diff --git a/packages/router-devtools-core/CHANGELOG.md b/packages/router-devtools-core/CHANGELOG.md new file mode 100644 index 0000000000..63eb2961dd --- /dev/null +++ b/packages/router-devtools-core/CHANGELOG.md @@ -0,0 +1,122 @@ +# @tanstack/router-devtools-core + +## 1.168.3 + +### Patch Changes + +- [#8888](https://github.com/TanStack/router/pull/8888) [`bbf9b75`](https://github.com/TanStack/router/commit/bbf9b75808d8eee497a6dd1663f0cf08426512e0) - Fix broken styling of the embedded `TanStackRouterDevtoolsPanel` (including inside shadow DOM) by giving the devtools size tokens a `1rem` fallback when `--tsrd-font-size` is not set. + +## 1.168.2 + +### Patch Changes + +- [#8321](https://github.com/TanStack/router/pull/8321) [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6) - Consolidate internal path interpolation into `interpolatePath`, returning a pathname directly and collecting metadata only when requested. Update router and devtools callers without changing route parsing or interpolation caching. + +- [#8327](https://github.com/TanStack/router/pull/8327) [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef) - Reuse parsed route segments when generating paths for navigation, Links, and Devtools. Preserve interpolation metadata and refresh segments when the route tree is rebuilt, without reparsing templates for new parameter values. + +- [#8327](https://github.com/TanStack/router/pull/8327) [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef) - Share compact parsed route segments between matching and interpolation, preserve original parameter names, and avoid reparsing templates while building paths. Simplify route-tree traversal, reuse existing path helpers, and keep Devtools-only navigation validation out of the production formatter. Preserve dynamic match identity for standalone legacy fallback routes. + +- Updated dependencies [[`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776), [`6cfb1e8`](https://github.com/TanStack/router/commit/6cfb1e8b564be282584765352250bf61747895ed), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`873c830`](https://github.com/TanStack/router/commit/873c830ccb2610a864ee697250e10fcc99772ffa), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`f151ab0`](https://github.com/TanStack/router/commit/f151ab018eede64ae849b77e68f3cdf31cb95cc5), [`bc57fa3`](https://github.com/TanStack/router/commit/bc57fa3f12450cf34c731450947c7c8f1ea05e58), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9448caa`](https://github.com/TanStack/router/commit/9448caa03a89076b9770631c356c0cc502802c09), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef)]: + - @tanstack/router-core@1.171.30 + +## 1.168.1 + +### Patch Changes + +- [#7805](https://github.com/TanStack/router/pull/7805) [`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd) - Rewrite match loading around a lane-based scheduler that tracks each navigation, preload, and background reload as an ordered unit of work. This fixes pending/redirect/retry state leaking between overlapping navigations, restores correct SSR status codes for redirects, errors, and not-found responses, and closes hydration gaps where the client re-ran work the server had already completed. + - Invalidation now retires matching active preloads so older speculative loader results cannot become fresh cache data after invalidation. + - Route `headers()` now only runs on the server, matching the documented behavior — it is no longer invoked during client-side asset projection. + - The documented default `gcTime` and `preloadGcTime` now match the existing runtime default of 5 minutes (`300_000`). + + **Removed / changed exported internals** + - `RouterState` no longer includes `loadedAt`, `isTransitioning`, `statusCode`, or `redirect`. Use `match.updatedAt` in place of `loadedAt`; subscribe to `router.state.status` / `router.state.isLoading` in place of `isTransitioning`; server response status and redirect handling are now internal to the server loader and are no longer exposed on `router.state`. + - `RouteMatch.fetchCount` has been removed, with no replacement — it was purely informational. + - `RouteMatch.status` no longer includes `'redirected'` (it remains `'pending' | 'success' | 'error' | 'notFound'`) — redirected matches are dropped from the match list instead of being rendered. + - `RouteMatch.globalNotFound` has been renamed and privatized to the internal `_notFound` field. Use `match.status === 'notFound'` instead. + - The exported React, Solid, and Vue `Match` components now accept `routeId` instead of `matchId`. + - The exported `RouterStores` adapter contract now uses route-keyed presentation stores: `matchesId` is replaced by `ids`, `matchStores` by `byRoute`, and `getRouteMatchStore()` by `getMatchStore()`. The separate `loadedAt`, `isLoading`, `isTransitioning`, `statusCode`, and `redirect` stores have been removed, along with the pending/cache stores and their setters. `StoreConfig.init` has also been removed. Read application-facing state from `router.state`; preload and cache coordination are now internal. + - Removed `RouterCore` members `getMatch()`, `updateMatch()`, `cancelMatch()`, and `cancelMatches()` — read matches from `router.state.matches` (e.g. `router.state.matches.find((m) => m.id === id)`); there is no replacement for mutating or cancelling an individual in-flight match from outside the router. + - Removed `RouterCore.hasNotFoundMatch()` — use `router.state.matches.some((m) => m.status === 'notFound')`. + - Removed `RouterCore.looseRoutesById` — use `routesById`. + - Removed `RouterCore.isPrerendering()`, `RouterCore.isViewTransitionTypesSupported`, and `RouterCore.viewTransitionPromise`, with no replacement. + - Removed `RouterCore.getParsedLocationHref()` and `RouterCore.clearExpiredCache()`, with no replacement — expired cache entries are now reconciled automatically as part of match commit. + - Removed `RouterCore.latestLoadPromise` and `RouterCore.beforeLoad()`, with no replacement. + - `RouterCore.commitLocationPromise` and `RouterCore.pendingBuiltLocation` have been replaced by the internal `_commitPromise` and `_pendingLocation` fields. + - Removed the exported `GetMatchFn` and `UpdateMatchFn` types, along with the methods they typed. + - Removed the standalone `getMatchedRoutes()` export from `@tanstack/router-core` — use the `router.getMatchedRoutes()` instance method instead. + - `RouterCore.loadRouteChunk()` no longer accepts an array of component types as its second argument. One-argument usage is unchanged; the optional second argument is now `'errorComponent'`, `'notFoundComponent'`, or `false` for internal boundary loading. + - Removed `Redirect.redirectHandled`, which was internal redirect bookkeeping. + - `MatchRoutesOpts.preload` and `MatchRoutesOpts.dest` have been removed. + - `StartTransitionFn` is now `(fn, expected) => Promise` (previously `(fn) => void`). This only affects custom framework adapters that implement `startTransition`. + +- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: + - @tanstack/router-core@1.171.16 + +## 1.168.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +### Patch Changes + +- Updated dependencies [[`b1c061a`](https://github.com/TanStack/router/commit/b1c061aff9185cdf5fdc08c0136382a9dce0302f), [`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14)]: + - @tanstack/router-core@1.170.0 + +## 1.167.3 + +### Patch Changes + +- shorten internal non-minifiable store names for byte shaving ([#7152](https://github.com/TanStack/router/pull/7152)) + +- Updated dependencies [[`6355bb7`](https://github.com/TanStack/router/commit/6355bb75f7637ba77f06a923c18fdaf37720bb48)]: + - @tanstack/router-core@1.168.11 + +## 1.167.2 + +### Patch Changes + +- migrate createStore > createAtom for simpler API ([#7150](https://github.com/TanStack/router/pull/7150)) + +- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: + - @tanstack/router-core@1.168.10 + +## 1.167.1 + +### Patch Changes + +- Replace tiny-invariant and tiny-warning with in-house solution for bundle-size ([#7007](https://github.com/TanStack/router/pull/7007)) + +- Updated dependencies [[`c9e1855`](https://github.com/TanStack/router/commit/c9e18555f3a5531e96de8f574cfca9edcdb18e5c)]: + - @tanstack/router-core@1.168.2 + +## 1.167.0 + +### Minor Changes + +- remove pendingMatches, cachedMatches ([#6704](https://github.com/TanStack/router/pull/6704)) + move to signal-based reactivity + solid uses its own native signals + +### Patch Changes + +- Updated dependencies [[`0545239`](https://github.com/TanStack/router/commit/054523900b2ee19308e5a88417dadfc6923afe30)]: + - @tanstack/router-core@1.168.0 + +## 1.166.9 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +- Updated dependencies [[`838b0eb`](https://github.com/TanStack/router/commit/838b0eb9a8bbbb987a0a6972c1446e01423bbd7b)]: + - @tanstack/router-core@1.167.2 + +## 1.166.8 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) + +- Updated dependencies [[`ef9b241`](https://github.com/TanStack/router/commit/ef9b241f3cfe95cee40daa96da669f0ffd4a971a)]: + - @tanstack/router-core@1.167.1 diff --git a/packages/router-devtools-core/package.json b/packages/router-devtools-core/package.json index 95de2ac7f0..24db637cc7 100644 --- a/packages/router-devtools-core/package.json +++ b/packages/router-devtools-core/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/router-devtools-core", - "version": "1.141.8", + "version": "1.168.3", "description": "Modern and scalable routing for Web applications", "author": "Tanner Linsley", "license": "MIT", @@ -25,14 +25,15 @@ ], "scripts": { "clean": "rimraf ./dist && rimraf ./coverage", - "test:eslint": "eslint ./src", + "test:eslint": "eslint ./src ./tests", + "test:unit": "vitest", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -59,22 +60,27 @@ "src" ], "engines": { - "node": ">=12" + "node": ">=20.19" }, "dependencies": { "clsx": "^2.1.1", - "goober": "^2.1.16", - "tiny-invariant": "^1.3.3" + "goober": "^2.1.16" }, "devDependencies": { - "solid-js": "^1.9.10", - "vite": "^7.1.7", - "vite-plugin-solid": "^2.11.10" + "@testing-library/jest-dom": "catalog:", + "solid-js": "catalog:", + "vite": "*", + "vite-plugin-solid": "catalog:", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "@tanstack/router-core": "workspace:^", - "csstype": "^3.0.10", - "solid-js": ">=1.9.5" + "csstype": "^3.0.10" }, "peerDependenciesMeta": { "csstype": { diff --git a/packages/router-devtools-core/src/AgeTicker.tsx b/packages/router-devtools-core/src/AgeTicker.tsx index 27d179fda1..5a615be54f 100644 --- a/packages/router-devtools-core/src/AgeTicker.tsx +++ b/packages/router-devtools-core/src/AgeTicker.tsx @@ -1,6 +1,6 @@ import { clsx as cx } from 'clsx' import { useStyles } from './useStyles' -import type { AnyRouteMatch, AnyRouter } from '@tanstack/router-core' +import type { AnyRoute, AnyRouteMatch, AnyRouter } from '@tanstack/router-core' import type { Accessor } from 'solid-js' function formatTime(ms: number) { @@ -35,7 +35,9 @@ export function AgeTicker({ return null } - const route = router().looseRoutesById[match.routeId]! + const route = (router().routesById as Record)[ + match.routeId + ]! if (!route.options.loader) { return null @@ -45,7 +47,7 @@ export function AgeTicker({ const staleTime = route.options.staleTime ?? router().options.defaultStaleTime ?? 0 const gcTime = - route.options.gcTime ?? router().options.defaultGcTime ?? 30 * 60 * 1000 + route.options.gcTime ?? router().options.defaultGcTime ?? 300_000 return (
    staleTime))}> diff --git a/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx b/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx index 67e67877d3..7efcaffca2 100644 --- a/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx +++ b/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx @@ -1,6 +1,12 @@ import { clsx as cx } from 'clsx' -import { default as invariant } from 'tiny-invariant' -import { interpolatePath, rootRouteId, trimPath } from '@tanstack/router-core' +import { + getRouteSegments, + hasKeys, + hasMissingPathParams, + interpolatePath, + rootRouteId, + trimPath, +} from '@tanstack/router-core' import { For, Match, @@ -102,6 +108,7 @@ function NavigateLink(props: { function RouteComp({ routerState, + pendingMatches, router, route, isRoot, @@ -133,6 +140,7 @@ function RouteComp({ MakeRouteMatchUnion > > + pendingMatches: Accessor> router: Accessor route: AnyRoute isRoot?: boolean @@ -140,8 +148,8 @@ function RouteComp({ setActiveId: (id: string) => void }) { const styles = useStyles() - const matches = createMemo( - () => routerState().pendingMatches || routerState().matches, + const matches = createMemo(() => + pendingMatches().length ? pendingMatches() : routerState().matches, ) const match = createMemo(() => routerState().matches.find((d) => d.routeId === route.id), @@ -173,19 +181,19 @@ function RouteComp({ // flatten all params in the router state, into a single object const allParams = Object.assign({}, ...matches().map((m) => m.params)) - // interpolatePath is used by router-core to generate the `to` - // path for the navigate function in the router - const interpolated = interpolatePath({ - path: route.fullPath, - params: allParams, - decodeCharMap: router().pathParamsDecodeCharMap, - }) + const segments = getRouteSegments(route) + const pathname = segments + ? interpolatePath( + route.fullPath, + segments, + allParams, + router().pathParamsDecoder, + ) + : route.fullPath - // only if `interpolated` is not missing params, return the path since this - // means that all the params are present for a successful navigation - return !interpolated.isMissingParams - ? interpolated.interpolatedPath - : undefined + return segments && hasMissingPathParams(segments, allParams) + ? undefined + : pathname }) return ( @@ -231,6 +239,7 @@ function RouteComp({ .map((r) => ( component tree or pass the router instance to the devtools manually.', - ) - - // useStore(router.__store) + // useStore(router.stores.__store) const [currentTab, setCurrentTab] = useLocalStorage< 'routes' | 'matches' | 'history' @@ -280,6 +284,41 @@ export const BaseTanStackRouterDevtoolsPanel = const [history, setHistory] = createSignal>([]) const [hasHistoryOverflowed, setHasHistoryOverflowed] = createSignal(false) + const pendingMatches = () => { + const matches = routerState().matches + return matches.some((match: AnyRouteMatch) => match.status === 'pending') + ? matches + : [] + } + let cache = router()._cache + let cacheMatches = [...cache.values()] + const [cachedMatches, setCachedMatches] = createSignal(cacheMatches) + + createEffect(() => { + const refreshCache = () => { + const next = router()._cache + let valuesChanged = next.size !== cacheMatches.length + if (!valuesChanged) { + let index = 0 + for (const match of next.values()) { + if (match !== cacheMatches[index++]) { + valuesChanged = true + break + } + } + } + + if (next !== cache || valuesChanged) { + cache = next + cacheMatches = [...next.values()] + setCachedMatches(cacheMatches) + } + } + refreshCache() + const interval = setInterval(refreshCache, 500) + onCleanup(() => clearInterval(interval)) + }) + createEffect(() => { const matches = routerState().matches const currentMatch = matches[matches.length - 1] @@ -309,18 +348,16 @@ export const BaseTanStackRouterDevtoolsPanel = const activeMatch = createMemo(() => { const matches = [ - ...(routerState().pendingMatches ?? []), + ...pendingMatches(), ...routerState().matches, - ...routerState().cachedMatches, + ...cachedMatches(), ] return matches.find( (d) => d.routeId === activeId() || d.id === activeId(), ) }) - const hasSearch = createMemo( - () => Object.keys(routerState().location.search).length, - ) + const hasSearch = createMemo(() => hasKeys(routerState().location.search)) const explorerState = createMemo(() => { return { @@ -348,13 +385,10 @@ export const BaseTanStackRouterDevtoolsPanel = (d) => typeof d[1] !== 'function' && ![ - '__store', + 'stores', 'basepath', - 'injectedHtml', 'subscribers', - 'latestLoadPromise', - 'navigateTimeout', - 'resetNextScroll', + '_scroll', 'tempLocationKey', 'latestLocation', 'routeTree', @@ -512,6 +546,7 @@ export const BaseTanStackRouterDevtoolsPanel =
    - {(routerState().pendingMatches?.length - ? routerState().pendingMatches + {(pendingMatches().length + ? pendingMatches() : routerState().matches - )?.map((match: any, _i: any) => { + ).map((match: any, _i: any) => { return (
    - {routerState().cachedMatches.length ? ( + {cachedMatches().length ? (
    Cached Matches
    @@ -617,7 +652,7 @@ export const BaseTanStackRouterDevtoolsPanel =
    - {routerState().cachedMatches.map((match: any) => { + {cachedMatches().map((match: any) => { return (
    State:
    - {routerState().pendingMatches?.find( - (d: any) => d.id === activeMatch()?.id, + {pendingMatches().find( + (d: AnyRouteMatch) => d.id === activeMatch()?.id, ) ? 'Pending' : routerState().matches.find( diff --git a/packages/router-devtools-core/src/Explorer.tsx b/packages/router-devtools-core/src/Explorer.tsx index a43cb9c95c..1862ecbd16 100644 --- a/packages/router-devtools-core/src/Explorer.tsx +++ b/packages/router-devtools-core/src/Explorer.tsx @@ -3,7 +3,12 @@ import { clsx as cx } from 'clsx' import * as goober from 'goober' import { createMemo, createSignal, useContext } from 'solid-js' import { tokens } from './tokens' -import { displayValue } from './utils' +import { + displayValue, + getServerComponentSlotUsageSummary, + getServerComponentSlots, + getServerComponentType, +} from './utils' import { ShadowDomTargetContext } from './context' import type { Accessor, JSX } from 'solid-js' @@ -12,7 +17,7 @@ type ExpanderProps = { style?: JSX.CSSProperties } -export const Expander = ({ expanded, style = {} }: ExpanderProps) => { +export const Expander = ({ expanded, style: _style = {} }: ExpanderProps) => { const styles = useStyles() return ( @@ -90,6 +95,12 @@ function isIterable(x: any): x is Iterable { return Symbol.iterator in x } +function isPlainObject(value: unknown): value is Record { + if (!value || typeof value !== 'object') return false + const proto = Object.getPrototypeOf(value) + return proto === Object.prototype || proto === null +} + export function Explorer({ value, defaultExpanded, @@ -116,7 +127,22 @@ export function Explorer({ } } - if (Array.isArray(value())) { + if ( + Array.isArray(value()) && + (value() as Array).length === 2 && + (value() as Array)[0] === 'React element' && + isPlainObject((value() as Array)[1]) + ) { + // Special case: treat `["React element", { ...meta }]` as sibling entries + // to avoid the meta object being rendered as a deeper nested tree. + const v = value() as ['React element', Record] + entries = [ + makeProperty({ label: '0', value: v[0] }), + ...Object.entries(v[1]).map(([key, val]) => + makeProperty({ label: key, value: val }), + ), + ] + } else if (Array.isArray(value())) { // any[] entries = (value() as Array).map((d, i) => makeProperty({ @@ -169,9 +195,72 @@ export function Explorer({ /> ) + const serverComponentType = createMemo(() => getServerComponentType(value())) + const serverComponentSlots = createMemo(() => + getServerComponentSlots(value()), + ) + const serverComponentSlotUsageSummary = createMemo(() => + getServerComponentSlotUsageSummary(value()), + ) + + const isCompositeWithSlots = createMemo( + () => + serverComponentType() === 'compositeSource' && + serverComponentSlots().length > 0, + ) + return (
    - {subEntryPages().length ? ( + {serverComponentType() !== null ? ( + isCompositeWithSlots() ? ( + <> + + {(expanded() ?? false) ? ( +
    + slots +
    + {serverComponentSlots().map((name) => { + const usage = serverComponentSlotUsageSummary()[name] + if (!usage) return null + return ( + + usage.invocations.map((args) => + args.length === 1 ? args[0] : args, + ) + } + /> + ) + })} +
    +
    + ) : null} + + ) : ( + <> + {rest.label}:{' '} + + {displayValue(value())} + + + ) + ) : subEntryPages().length ? ( <> + + + ) + }, + }) + + const indexRoute = createRoute({ + path: '/', + getParentRoute: () => rootRoute, + component: () =>
    Index
    , + }) + + const router = createRouter({ + history, + routeTree: rootRoute.addChildren([indexRoute]), + }) + + router.ssr = { + manifest: createTestManifest(rootRoute.id), + } + + await router.load() + + render(() => ) + + const getStylesheetLink = () => + Array.from(document.head.querySelectorAll('link[rel="stylesheet"]')).find( + (link) => link.getAttribute('href') === '/main.css', + ) + + await waitFor(() => { + expect(getStylesheetLink()).toBeInstanceOf(HTMLLinkElement) + }) + + const initialLink = getStylesheetLink() + expect(initialLink).toBeInstanceOf(HTMLLinkElement) + + fireEvent.click(screen.getByRole('button', { name: 'Replace state' })) + + await waitFor(() => { + expect(router.state.location.state).toMatchObject({ + slideId: 'slide-2', + }) + }) + + expect(getStylesheetLink()).toBe(initialLink) + expect( + Array.from( + document.head.querySelectorAll('link[rel="stylesheet"]'), + ).filter((link) => link.getAttribute('href') === '/main.css'), + ).toHaveLength(1) + }) }) diff --git a/packages/solid-router/tests/Transitioner.test.tsx b/packages/solid-router/tests/Transitioner.test.tsx index dffe2bd4fd..26fa0da5b4 100644 --- a/packages/solid-router/tests/Transitioner.test.tsx +++ b/packages/solid-router/tests/Transitioner.test.tsx @@ -31,7 +31,6 @@ describe('Transitioner', () => { const loadSpy = vi.spyOn(router, 'load') render(() => ) - await router.latestLoadPromise // Wait for the createRenderEffect to run and call router.load() await waitFor(() => { diff --git a/packages/solid-router/tests/blocker.test.tsx b/packages/solid-router/tests/blocker.test.tsx index be10c91ac6..ac27b633e5 100644 --- a/packages/solid-router/tests/blocker.test.tsx +++ b/packages/solid-router/tests/blocker.test.tsx @@ -1,4 +1,3 @@ -import '@testing-library/jest-dom/vitest' import { afterEach, describe, expect, test, vi } from 'vitest' import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library' import combinate from 'combinate' diff --git a/packages/solid-router/tests/component-preload-retry.test.tsx b/packages/solid-router/tests/component-preload-retry.test.tsx new file mode 100644 index 0000000000..fda9f2ca3b --- /dev/null +++ b/packages/solid-router/tests/component-preload-retry.test.tsx @@ -0,0 +1,249 @@ +import { ErrorBoundary, Suspense } from 'solid-js' +import { afterEach, expect, onTestFinished, test, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library' +import { createControlledPromise } from '@tanstack/router-core' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + lazyRouteComponent, + useRouter, +} from '../src' +import type { ErrorComponentProps } from '../src' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +test('a successful server component download is reused', async () => { + vi.stubGlobal('window', undefined) + const importer = vi.fn().mockResolvedValue({ default: () => null }) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload?.() + await preload + + expect(Page.preload?.()).toBe(preload) + expect(importer).toHaveBeenCalledTimes(1) +}) + +test('a component loads when rendered before preload', async () => { + const importer = vi.fn().mockResolvedValue({ + default: () =>
    Page content
    , + }) + const Page = lazyRouteComponent(importer) + + render(() => ) + + expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(1) +}) + +test('a resolved client component preload is reused', async () => { + const importer = vi.fn().mockResolvedValue({ default: () => null }) + const Page = lazyRouteComponent(importer) + + await Page.preload?.() + expect(Page.preload).toBeUndefined() + expect(importer).toHaveBeenCalledTimes(1) +}) + +test('revisiting a resolved lazy component skips pending UI', async () => { + const PageContent = () =>
    Page content
    + const componentImport = createControlledPromise<{ + default: typeof PageContent + }>() + const repeatedImport = createControlledPromise<{ + default: typeof PageContent + }>() + const importer = vi + .fn() + .mockImplementationOnce(() => componentImport) + .mockImplementationOnce(() => repeatedImport) + const Page = lazyRouteComponent(importer) + const PendingComponent = vi.fn(() => ( +
    Loading page
    + )) + const rootRoute = createRootRoute({ + component: () => ( + <> + Home link + Page link + + + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home content
    , + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 0, + defaultPendingComponent: PendingComponent, + }) + + render(() => ) + expect(await screen.findByText('Home content')).toBeInTheDocument() + + fireEvent.click(screen.getByRole('link', { name: 'Page link' })) + expect(await screen.findByTestId('pending-component')).toHaveTextContent( + 'Loading page', + ) + componentImport.resolve({ default: PageContent }) + expect(await screen.findByText('Page content')).toBeInTheDocument() + + fireEvent.click(screen.getByRole('link', { name: 'Home link' })) + expect(await screen.findByText('Home content')).toBeInTheDocument() + PendingComponent.mockClear() + fireEvent.click(screen.getByRole('link', { name: 'Page link' })) + await new Promise((resolve) => setTimeout(resolve, 10)) + + expect(screen.queryByText('Page content')).toBeInTheDocument() + expect(screen.queryByTestId('pending-component')).not.toBeInTheDocument() + expect(PendingComponent).not.toHaveBeenCalled() + expect(importer).toHaveBeenCalledOnce() +}) + +test('a missing export fails through the route error UI instead of recursing', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const importer = vi.fn().mockResolvedValue({ Other: () => null }) + const Page = lazyRouteComponent(importer, 'Missing' as never) + const rootRoute = createRootRoute() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + errorComponent: (props: ErrorComponentProps) => ( +
    {props.error.message}
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render(() => ) + + expect( + await screen.findByText('lazyRouteComponent: export "Missing" not found'), + ).toBeInTheDocument() +}) + +test('a failed component download is retried from the route error UI', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + + const PageContent = () =>
    Page content
    + const retryImport = createControlledPromise<{ default: typeof PageContent }>() + onTestFinished(() => retryImport.resolve({ default: PageContent })) + const importer = vi + .fn<() => Promise<{ default: typeof PageContent }>>() + .mockRejectedValueOnce(new Error('component download failed')) + .mockImplementation(() => retryImport) + const Page = lazyRouteComponent(importer) + + function RouteError(props: ErrorComponentProps) { + const router = useRouter() + return ( + + ) + } + + const rootRoute = createRootRoute() + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: Page, + errorComponent: RouteError, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render(() => ) + + fireEvent.click(await screen.findByRole('button', { name: 'Retry' })) + + await vi.waitFor(() => expect(importer).toHaveBeenCalledTimes(2)) + expect(screen.queryByText('Page content')).not.toBeInTheDocument() + retryImport.resolve({ default: PageContent }) + + expect(await screen.findByText('Page content')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(Page.preload).toBeUndefined() +}) + +test('a component first loaded during render recovers after an awaited preload retry', async () => { + const PageContent = () =>
    Recovered component
    + const retryImport = createControlledPromise<{ default: typeof PageContent }>() + onTestFinished(() => retryImport.resolve({ default: PageContent })) + const importer = vi + .fn<() => Promise<{ default: typeof PageContent }>>() + .mockRejectedValueOnce(new Error('component download failed')) + .mockImplementation(() => retryImport) + const Page = lazyRouteComponent(importer) + let retry: Promise | undefined + + render(() => ( + ( + + )} + > + Loading component}> + + + + )) + + const button = await screen.findByRole('button', { + name: 'Retry component download failed', + }) + expect(importer).toHaveBeenCalledOnce() + fireEvent.click(button) + + expect(importer).toHaveBeenCalledTimes(2) + expect(retry).toBeDefined() + expect(Page.preload?.()).toBe(retry) + expect(button).toBeInTheDocument() + expect(screen.queryByText('Recovered component')).not.toBeInTheDocument() + + retryImport.resolve({ default: PageContent }) + await retry + + expect(await screen.findByText('Recovered component')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(Page.preload).toBeUndefined() +}) diff --git a/packages/solid-router/tests/createLazyRoute.test.tsx b/packages/solid-router/tests/createLazyRoute.test.tsx index ddee828467..4dcbbbfc2c 100644 --- a/packages/solid-router/tests/createLazyRoute.test.tsx +++ b/packages/solid-router/tests/createLazyRoute.test.tsx @@ -1,9 +1,12 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library' import { Link, + Outlet, RouterProvider, createBrowserHistory, + createControlledPromise, + createLazyRoute, createMemoryHistory, createRootRoute, createRoute, @@ -93,3 +96,135 @@ describe('preload: matched routes', { timeout: 20000 }, () => { expect(lazyRoute.options.component).toBeDefined() }) }) + +// https://github.com/TanStack/router/issues/4467 +it('replaces default pending UI when delayed lazy options provide pending UI', async () => { + const loader = createControlledPromise() + const componentPreload = createControlledPromise() + const pendingComponentPreload = createControlledPromise() + const preloadComponent = vi.fn(() => componentPreload) + const preloadPendingComponent = vi.fn(() => pendingComponentPreload) + const Page = Object.assign(() =>

    Page

    , { + preload: preloadComponent, + }) + const Pending = Object.assign(() =>

    Loading lazy page

    , { + preload: preloadPendingComponent, + }) + const lazyPageOptions = createLazyRoute('/page')({ + pendingComponent: Pending, + component: Page, + }) + const lazyOptions = createControlledPromise() + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>

    Index page

    , + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => loader, + }).lazy(() => lazyOptions) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 0, + defaultPendingComponent: () =>

    Loading default

    , + }) + render(() => ) + expect(await screen.findByText('Index page')).toBeInTheDocument() + + const navigation = router.navigate({ to: '/page' }) + onTestFinished(async () => { + lazyOptions.resolve(lazyPageOptions) + pendingComponentPreload.resolve() + componentPreload.resolve() + loader.resolve() + await Promise.allSettled([navigation]) + }) + + expect(await screen.findByRole('status')).toHaveTextContent('Loading default') + + lazyOptions.resolve(lazyPageOptions) + await vi.waitFor(() => { + expect(preloadComponent).toHaveBeenCalledOnce() + expect(preloadPendingComponent).toHaveBeenCalledOnce() + }) + expect(screen.getByRole('status')).toHaveTextContent('Loading default') + expect(pendingComponentPreload.status).toBe('pending') + + pendingComponentPreload.resolve() + await vi.waitFor(() => + expect(screen.getByRole('status')).toHaveTextContent('Loading lazy page'), + ) + expect(componentPreload.status).toBe('pending') + expect(screen.queryByText('Page')).not.toBeInTheDocument() + + componentPreload.resolve() + loader.resolve() + await navigation + + expect(await screen.findByText('Page')).toBeInTheDocument() +}) + +it('renders an eager loader error with a delayed lazy errorComponent', async () => { + const loader = createControlledPromise() + const loaderErrorHandled = createControlledPromise() + const loaderError = new Error('loader failed') + const lazyPageOptions = createLazyRoute('/page')({ + component: () =>

    Page

    , + errorComponent: ({ error }) => ( +

    Lazy error: {error.message}

    + ), + }) + const lazyOptions = createControlledPromise() + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>

    Index page

    , + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: async () => { + await loader + throw loaderError + }, + onError: () => loaderErrorHandled.resolve(), + }).lazy(() => lazyOptions) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 0, + defaultPendingComponent: () =>

    Loading default

    , + }) + let navigation: Promise | undefined + + try { + render(() => ) + expect(await screen.findByText('Index page')).toBeInTheDocument() + + navigation = router.navigate({ to: '/page' }) + expect(await screen.findByText('Loading default')).toBeInTheDocument() + + loader.resolve() + await loaderErrorHandled + lazyOptions.resolve(lazyPageOptions) + await navigation + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Lazy error: loader failed', + ) + } finally { + lazyOptions.resolve(lazyPageOptions) + loader.resolve() + loaderErrorHandled.resolve() + if (navigation) { + await Promise.allSettled([navigation]) + } + } +}) diff --git a/packages/solid-router/tests/errorBoundary.test-d.tsx b/packages/solid-router/tests/errorBoundary.test-d.tsx new file mode 100644 index 0000000000..026437d757 --- /dev/null +++ b/packages/solid-router/tests/errorBoundary.test-d.tsx @@ -0,0 +1,42 @@ +import { expectTypeOf, test } from 'vitest' +import { CatchBoundary, createRootRoute, createRouter } from '../src' +import type { ErrorComponentProps } from '../src' + +test('Solid boundary errors default to Error', () => { + expectTypeOf().toEqualTypeOf() + expectTypeOf['error']>().toEqualTypeOf() + ; 0} + onCatch={(error) => { + expectTypeOf(error).toEqualTypeOf() + }} + errorComponent={({ error }) => { + expectTypeOf(error).toEqualTypeOf() + return null + }} + > +
    + + const routeTree = createRootRoute({ + errorComponent: ({ error }) => { + expectTypeOf(error).toEqualTypeOf() + return null + }, + onCatch: (error) => { + expectTypeOf(error).toEqualTypeOf() + }, + onError: (error) => { + expectTypeOf(error).toBeAny() + }, + }) + createRouter({ + routeTree, + defaultErrorComponent: ({ error }) => { + expectTypeOf(error).toEqualTypeOf() + return null + }, + defaultOnCatch: (error) => { + expectTypeOf(error).toEqualTypeOf() + }, + }) +}) diff --git a/packages/solid-router/tests/errorComponent.test.tsx b/packages/solid-router/tests/errorComponent.test.tsx index b9ccd941a6..af7898c121 100644 --- a/packages/solid-router/tests/errorComponent.test.tsx +++ b/packages/solid-router/tests/errorComponent.test.tsx @@ -1,9 +1,14 @@ -import { afterEach, describe, expect, test, vi } from 'vitest' +import { afterEach, describe, expect, onTestFinished, test, vi } from 'vitest' import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library' +import { createControlledPromise } from '@tanstack/router-core' import { + CatchBoundary, + ErrorComponent, Link, + Outlet, RouterProvider, + createLazyRoute, createRootRoute, createRoute, createRouter, @@ -11,7 +16,11 @@ import { import type { ErrorComponentProps } from '../src' function MyErrorComponent(props: ErrorComponentProps) { - return
    Error: {props.error.message}
    + return
    Error: {getErrorMessage(props.error)}
    +} + +function getErrorMessage(error: unknown) { + return error instanceof Error ? error.message : String(error) } async function asyncToThrowFn() { @@ -29,108 +38,285 @@ afterEach(() => { cleanup() }) -describe.each([{ preload: false }, { preload: 'intent' }] as const)( - 'errorComponent is rendered when the preload=$preload', - (options) => { - describe.each([true, false])('with async=%s', (isAsync) => { - const throwableFn = isAsync ? asyncToThrowFn : throwFn +describe.each([true, false])( + 'with lazy errorComponent=%s', + (isUsingLazyError) => { + describe.each([{ preload: false }, { preload: 'intent' }] as const)( + 'errorComponent is rendered when the preload=$preload', + (options) => { + describe.each([true, false])('with async=%s', (isAsync) => { + const throwableFn = isAsync ? asyncToThrowFn : throwFn - const callers = [ - { caller: 'beforeLoad', testFn: throwableFn }, - { caller: 'loader', testFn: throwableFn }, - ] + const callers = [ + { caller: 'beforeLoad', testFn: throwableFn }, + { caller: 'loader', testFn: throwableFn }, + ] - test.each(callers)( - 'an Error is thrown on navigate in the route $caller function', - async ({ caller, testFn }) => { - const rootRoute = createRootRoute() - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: function Home() { - return ( -
    - link to about -
    + test.each(callers)( + 'an Error is thrown on navigate in the route $caller function', + async ({ caller, testFn }) => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: function Home() { + return ( +
    + link to about +
    + ) + }, + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + beforeLoad: caller === 'beforeLoad' ? testFn : undefined, + loader: caller === 'loader' ? testFn : undefined, + component: function Home() { + return
    About route content
    + }, + errorComponent: isUsingLazyError ? undefined : MyErrorComponent, + }) + + if (isUsingLazyError) { + aboutRoute.lazy(() => + Promise.resolve( + createLazyRoute('/about')({ + errorComponent: MyErrorComponent, + }), + ), + ) + } + + const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]) + + const router = createRouter({ + routeTree, + defaultPreload: options.preload, + }) + + render(() => ) + + const linkToAbout = await screen.findByRole('link', { + name: 'link to about', + }) + + expect(linkToAbout).toBeInTheDocument() + fireEvent.mouseOver(linkToAbout) + fireEvent.focus(linkToAbout) + fireEvent.click(linkToAbout) + + const errorComponent = await screen.findByText( + `Error: error thrown`, + undefined, + { timeout: 1500 }, ) + await expect( + screen.findByText('About route content'), + ).rejects.toThrow() + expect(errorComponent).toBeInTheDocument() }, - }) - const aboutRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/about', - beforeLoad: caller === 'beforeLoad' ? testFn : undefined, - loader: caller === 'loader' ? testFn : undefined, - component: function Home() { - return
    About route content
    - }, - errorComponent: MyErrorComponent, - }) - - const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]) - - const router = createRouter({ - routeTree, - defaultPreload: options.preload, - }) - - render(() => ) - - const linkToAbout = await screen.findByRole('link', { - name: 'link to about', - }) - - expect(linkToAbout).toBeInTheDocument() - fireEvent.mouseOver(linkToAbout) - fireEvent.focus(linkToAbout) - fireEvent.click(linkToAbout) - - const errorComponent = await screen.findByText( - `Error: error thrown`, - undefined, - { timeout: 1500 }, ) - await expect( - screen.findByText('About route content'), - ).rejects.toThrow() - expect(errorComponent).toBeInTheDocument() - }, - ) - test.each(callers)( - 'an Error is thrown on first load in the route $caller function', - async ({ caller, testFn }) => { - const rootRoute = createRootRoute() - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - beforeLoad: caller === 'beforeLoad' ? testFn : undefined, - loader: caller === 'loader' ? testFn : undefined, - component: function Home() { - return
    Index route content
    + test.each(callers)( + 'an Error is thrown on first load in the route $caller function', + async ({ caller, testFn }) => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + beforeLoad: caller === 'beforeLoad' ? testFn : undefined, + loader: caller === 'loader' ? testFn : undefined, + component: function Home() { + return
    Index route content
    + }, + errorComponent: isUsingLazyError ? undefined : MyErrorComponent, + }) + + if (isUsingLazyError) { + indexRoute.lazy(() => + Promise.resolve( + createLazyRoute('/')({ + errorComponent: MyErrorComponent, + }), + ), + ) + } + + const routeTree = rootRoute.addChildren([indexRoute]) + + const router = createRouter({ + routeTree, + defaultPreload: options.preload, + }) + + render(() => ) + + const errorComponent = await screen.findByText( + `Error: error thrown`, + undefined, + { timeout: 750 }, + ) + await expect( + screen.findByText('Index route content'), + ).rejects.toThrow() + expect(errorComponent).toBeInTheDocument() }, - errorComponent: MyErrorComponent, - }) - - const routeTree = rootRoute.addChildren([indexRoute]) - - const router = createRouter({ - routeTree, - defaultPreload: options.preload, - }) - - render(() => ) - - const errorComponent = await screen.findByText( - `Error: error thrown`, - undefined, - { timeout: 750 }, ) - await expect( - screen.findByText('Index route content'), - ).rejects.toThrow() - expect(errorComponent).toBeInTheDocument() - }, - ) - }) + }) + }, + ) }, ) + +test('global catch boundary resets when a background child generation recovers', async () => { + const refresh = createControlledPromise() + let loaderCalls = 0 + const rootRoute = createRootRoute({ component: Outlet }) + const childRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: { + staleReloadMode: 'background', + handler: () => (++loaderCalls === 1 ? 1 : refresh), + }, + component: () => { + const revision = childRoute.useLoaderData() + if (revision() === 1) { + throw new Error('stale child render failed') + } + return
    Recovered child revision {revision()}
    + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([childRoute]), + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + render(() => ) + expect( + await screen.findByText('stale child render failed'), + ).toBeInTheDocument() + + const invalidation = router.invalidate() + await vi.waitFor(() => expect(loaderCalls).toBe(2)) + expect(screen.getByText('stale child render failed')).toBeInTheDocument() + expect(screen.queryByText(/Recovered child revision/)).not.toBeInTheDocument() + refresh.resolve(2) + await invalidation + + expect( + await screen.findByText('Recovered child revision 2'), + ).toBeInTheDocument() + expect( + screen.queryByText('stale child render failed'), + ).not.toBeInTheDocument() +}) + +test('ancestor route errorComponent resets when a background child generation recovers', async () => { + const refresh = createControlledPromise() + let loaderCalls = 0 + const rootRoute = createRootRoute({ + component: Outlet, + errorComponent: ({ error }) => ( +
    Ancestor error: {getErrorMessage(error)}
    + ), + }) + const childRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: { + staleReloadMode: 'background', + handler: () => (++loaderCalls === 1 ? 1 : refresh), + }, + component: () => { + const revision = childRoute.useLoaderData() + if (revision() === 1) { + throw new Error('stale child render failed') + } + return
    Recovered child revision {revision()}
    + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([childRoute]), + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + + render(() => ) + expect( + await screen.findByText('Ancestor error: stale child render failed'), + ).toBeInTheDocument() + + const invalidation = router.invalidate({ + filter: (match) => match.routeId === childRoute.id, + }) + onTestFinished(async () => { + refresh.resolve(2) + await Promise.allSettled([invalidation]) + }) + + await vi.waitFor(() => expect(loaderCalls).toBe(2)) + expect( + screen.getByText('Ancestor error: stale child render failed'), + ).toBeInTheDocument() + refresh.resolve(2) + await invalidation + + expect( + await screen.findByText('Recovered child revision 2'), + ).toBeInTheDocument() +}) + +test.each([ + ['false', false], + ['zero', 0], + ['negative zero', -0], + ['bigint zero', 0n], + ['empty string', ''], + ['null', null], + ['undefined', undefined], + ['NaN', NaN], +] as const)('CatchBoundary renders falsy thrown value %s', (_, thrown) => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + let caught: unknown + + function ThrowFalsy(): never { + throw thrown + } + + render(() => ( + 0} + errorComponent={({ error }) => ( +
    + {error instanceof Error && Object.is(error.cause, thrown) + ? 'Caught value' + : 'Wrong value'} +
    + )} + onCatch={(error) => { + caught = error + }} + > + +
    + )) + + expect(screen.getByText('Caught value')).toBeInTheDocument() + expect(screen.queryByText('Wrong value')).not.toBeInTheDocument() + expect(caught).toBeInstanceOf(Error) + expect(Object.is((caught as Error).cause, thrown)).toBe(true) +}) + +test.each([ + [new Error('Error message'), 'Error message'], + [new Error('Wrapped error', { cause: false }), 'Wrapped error'], + [new Error(''), undefined], +])('default error details render %s', (error, expected) => { + const { container } = render(() => ) + + expect(screen.getByText('Something went wrong!')).toBeInTheDocument() + expect(container.querySelector('code')?.textContent).toBe(expected) +}) diff --git a/packages/solid-router/tests/fileRoute.test-d.tsx b/packages/solid-router/tests/fileRoute.test-d.tsx index c97d932325..6c32156b2d 100644 --- a/packages/solid-router/tests/fileRoute.test-d.tsx +++ b/packages/solid-router/tests/fileRoute.test-d.tsx @@ -1,5 +1,53 @@ import { expectTypeOf, test } from 'vitest' import { createFileRoute, createRootRoute } from '../src' +import type { Route } from '@tanstack/router-core' + +declare module '@tanstack/router-core' { + interface FilebaseRouteOptionsInterface< + TRegister, + TParentRoute, + TId, + TPath, + TSearchValidator, + TParams, + TLoaderDeps, + TLoaderFn, + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TRemountDepsFn, + TSSR, + TServerMiddlewares, + THandlers, + > { + server?: { + middleware?: TServerMiddlewares + } + } + + interface RouteTypes< + TRegister, + TParentRoute, + TPath, + TFullPath, + TCustomId, + TId, + TSearchValidator, + TParams, + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TLoaderDeps, + TLoaderFn, + TChildren, + TFileRouteTypes, + TSSR, + TServerMiddlewares, + THandlers, + > { + middleware: TServerMiddlewares + } +} const rootRoute = createRootRoute() @@ -100,3 +148,42 @@ test('when creating a folder group', () => { expectTypeOf<'(auth)/protected'>(protectedRoute.path) expectTypeOf<'/protected'>(protectedRoute.id) }) + +test('when creating a file route with middleware options', () => { + type Middleware = { readonly middleware: 'middleware' } + const middleware = { middleware: 'middleware' } as const + + const route = createFileRoute('/invoices')({ + server: { + middleware: [middleware], + }, + }) + + type ExtractMiddlewares = + TRoute extends Route< + any, + any, + any, + any, + any, + any, + any, + any, + any, + any, + any, + any, + any, + any, + any, + any, + infer TMiddlewares, + any + > + ? TMiddlewares + : never + + expectTypeOf>().toEqualTypeOf< + readonly [Middleware] + >() +}) diff --git a/packages/solid-router/tests/fileRoute.test.ts b/packages/solid-router/tests/fileRoute.test.ts index f6b92298c8..5d459d1b7e 100644 --- a/packages/solid-router/tests/fileRoute.test.ts +++ b/packages/solid-router/tests/fileRoute.test.ts @@ -1,13 +1,38 @@ /* eslint-disable */ -import { describe, it, expect } from 'vitest' +import { afterEach, describe, it, expect, vi } from 'vitest' import { getRouteApi, createFileRoute, createLazyRoute, createLazyFileRoute, LazyRoute, + FileRoute, } from '../src' +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('createFileRoute', () => { + it('creates a non-root route without a deprecation warning', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + // @ts-expect-error + const route = createFileRoute('')({}) + + expect(route.isRoot).toBe(false) + expect(warn).not.toHaveBeenCalled() + }) + + it('keeps the deprecation warning for direct FileRoute usage', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + // @ts-expect-error + const route = new FileRoute('').createRoute({}) + + expect(route.isRoot).toBe(false) + expect(warn).toHaveBeenCalledOnce() + }) +}) + describe('createFileRoute has the same hooks as getRouteApi', () => { const routeApi = getRouteApi('foo') const hookNames = Object.keys(routeApi).filter((key) => key.startsWith('use')) diff --git a/packages/solid-router/tests/hydration-terminal-lane.test.tsx b/packages/solid-router/tests/hydration-terminal-lane.test.tsx new file mode 100644 index 0000000000..e7ee9b0f4d --- /dev/null +++ b/packages/solid-router/tests/hydration-terminal-lane.test.tsx @@ -0,0 +1,87 @@ +import { cleanup, render, screen } from '@solidjs/testing-library' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { hydrate } from '@tanstack/router-core/ssr/client' +import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id' +import { + RouterProvider, + createMemoryHistory, + createRootRoute, + createRouter, +} from '../src' +import type { AnyRouteMatch } from '@tanstack/router-core' +import type { TsrSsrGlobal } from '@tanstack/router-core/ssr/client' + +function bootstrap( + matches: Array<{ + match: AnyRouteMatch + status: AnyRouteMatch['status'] + ssr: AnyRouteMatch['ssr'] + data?: unknown + error?: unknown + notFound?: boolean + }>, +): void { + window.$_TSR = { + router: { + manifest: undefined, + matches: matches.map(({ match, status, ssr, data, error, notFound }) => ({ + i: dehydrateSsrMatchId(match.id), + l: data, + e: error, + s: status, + ssr, + u: Date.now(), + ...(notFound ? { g: true } : {}), + })), + }, + h: vi.fn(), + e: vi.fn(), + c: vi.fn(), + p: vi.fn(), + buffer: [], + } as TsrSsrGlobal +} + +afterEach(() => { + cleanup() + vi.useRealTimers() + delete window.$_TSR +}) + +describe('hydration terminal lane', () => { + test('keeps a hydrated pending fallback through its minimum before a terminal result', async () => { + vi.useFakeTimers() + vi.setSystemTime(0) + const rootRoute = createRootRoute({ + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    Missing page pending
    , + notFoundComponent: () =>
    Missing page
    , + }) + const router = createRouter({ + history: createMemoryHistory({ initialEntries: ['/missing'] }), + routeTree: rootRoute, + }) + const matches = router.matchRoutes(router.state.location) + expect(matches[0]?._notFound).toBe(true) + bootstrap([ + { + match: matches[0]!, + status: 'pending', + ssr: false, + notFound: true, + }, + ]) + + await hydrate(router) + render(() => ) + expect(screen.getByRole('status')).toHaveTextContent('Missing page pending') + + await vi.advanceTimersByTimeAsync(99) + expect(screen.getByRole('status')).toHaveTextContent('Missing page pending') + expect(screen.queryByText('Missing page')).not.toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(5) + expect(screen.getByText('Missing page')).toBeInTheDocument() + }) +}) diff --git a/packages/solid-router/tests/issue-4467-lazy-route-pending.test.tsx b/packages/solid-router/tests/issue-4467-lazy-route-pending.test.tsx new file mode 100644 index 0000000000..b49de23a58 --- /dev/null +++ b/packages/solid-router/tests/issue-4467-lazy-route-pending.test.tsx @@ -0,0 +1,82 @@ +import { cleanup, render, screen } from '@solidjs/testing-library' +import { afterEach, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { + Outlet, + RouterProvider, + createLazyRoute, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +test('a lazy pending component does not restart an acknowledged minimum', async () => { + const loader = createControlledPromise() + const lazyPageOptions = createLazyRoute('/page')({ + pendingComponent: () =>

    Loading lazy page

    , + component: () =>

    Page

    , + }) + const lazyOptions = createControlledPromise() + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>

    Index page

    , + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + loader: () => loader, + }).lazy(() => lazyOptions) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 100, + defaultPendingComponent: () =>

    Loading default

    , + }) + + render(() => ) + expect( + await screen.findByRole('heading', { name: 'Index page' }), + ).toBeInTheDocument() + vi.useFakeTimers() + vi.setSystemTime(0) + + const navigation = router.navigate({ to: '/page' }) + let settled = false + void navigation.then(() => { + settled = true + }) + try { + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByRole('status')).toHaveTextContent('Loading default') + + await vi.advanceTimersByTimeAsync(25) + lazyOptions.resolve(lazyPageOptions) + loader.resolve() + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByRole('status')).toHaveTextContent('Loading lazy page') + + await vi.advanceTimersByTimeAsync(74) + expect(screen.getByRole('status')).toHaveTextContent('Loading lazy page') + + await vi.advanceTimersByTimeAsync(5) + await Promise.resolve() + expect(settled).toBe(true) + await navigation + expect(screen.getByRole('heading', { name: 'Page' })).toBeInTheDocument() + expect(Date.now()).toBeLessThan(125) + } finally { + lazyOptions.resolve(lazyPageOptions) + loader.resolve() + await vi.advanceTimersByTimeAsync(1_000) + await navigation + } +}) diff --git a/packages/solid-router/tests/issue-7367-pending-min-redirect.test.tsx b/packages/solid-router/tests/issue-7367-pending-min-redirect.test.tsx new file mode 100644 index 0000000000..d96b01352f --- /dev/null +++ b/packages/solid-router/tests/issue-7367-pending-min-redirect.test.tsx @@ -0,0 +1,127 @@ +import { cleanup, render, screen } from '@solidjs/testing-library' +import { createControlledPromise } from '@tanstack/router-core' +import { afterEach, expect, test, vi } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + redirect, +} from '../src' + +afterEach(() => { + vi.restoreAllMocks() + cleanup() + vi.useRealTimers() +}) + +test('a compatible SPA redirect preserves the acknowledged pending minimum', async () => { + vi.useFakeTimers() + vi.setSystemTime(0) + const redirectReady = createControlledPromise() + let shouldRedirect = true + + const rootRoute = createRootRoute({ + component: () => , + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    loading
    , + beforeLoad: async () => { + if (shouldRedirect) { + shouldRedirect = false + await redirectReady + throw redirect({ to: '/welcome', replace: true }) + } + }, + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Index
    , + }) + const welcomeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/welcome', + component: () =>
    Welcome
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, welcomeRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + try { + render(() => ) + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(25) + redirectReady.resolve() + await vi.advanceTimersByTimeAsync(74) + expect(screen.getByTestId('pending')).toBeInTheDocument() + expect(screen.queryByTestId('welcome-page')).not.toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(5) + expect(screen.getByTestId('welcome-page')).toBeInTheDocument() + } finally { + redirectReady.resolve() + await vi.advanceTimersByTimeAsync(1_000) + vi.useRealTimers() + } +}) + +test('an incompatible SPA redirect does not inherit the pending minimum', async () => { + const redirectReady = createControlledPromise() + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Index
    , + }) + const sourceRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/source', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    loading
    , + beforeLoad: async () => { + await redirectReady + throw redirect({ to: '/welcome', replace: true }) + }, + }) + const welcomeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/welcome', + component: () =>
    Welcome
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, sourceRoute, welcomeRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + expect(await screen.findByTestId('index-page')).toBeVisible() + vi.useFakeTimers() + vi.setSystemTime(0) + + const navigation = router.navigate({ to: '/source' }) + try { + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByTestId('pending')).toBeVisible() + + await vi.advanceTimersByTimeAsync(25) + redirectReady.resolve() + await vi.advanceTimersByTimeAsync(5) + await navigation + + expect(Date.now()).toBeLessThan(100) + expect(screen.getByTestId('welcome-page')).toBeVisible() + expect(screen.queryByTestId('index-page')).not.toBeInTheDocument() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + } finally { + redirectReady.resolve() + await vi.advanceTimersByTimeAsync(1_000) + await navigation + } +}) diff --git a/packages/solid-router/tests/issue-7964-param-parsing-loader.test.tsx b/packages/solid-router/tests/issue-7964-param-parsing-loader.test.tsx new file mode 100644 index 0000000000..ca49ad1dc7 --- /dev/null +++ b/packages/solid-router/tests/issue-7964-param-parsing-loader.test.tsx @@ -0,0 +1,102 @@ +import { cleanup, render, screen, waitFor } from '@solidjs/testing-library' +import { afterEach, expect, test } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +// https://github.com/TanStack/router/issues/7964 +test('#7964: a child loader receives fresh structured params after revisiting its route', async () => { + const rootRoute = createRootRoute({ + component: Outlet, + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home page
    , + }) + const parsedParamRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/$parsedParam', + params: { + parse: ({ parsedParam }) => { + const [recordName, revisionNumber] = parsedParam.split('-') + return { + parsedParam: { + recordName: recordName!, + revisionNumber: Number(revisionNumber), + }, + } + }, + stringify: ({ parsedParam }) => ({ + parsedParam: `${parsedParam.recordName}-${parsedParam.revisionNumber}`, + }), + }, + component: Outlet, + }) + const parsedParamIndexRoute = createRoute({ + getParentRoute: () => parsedParamRoute, + path: '/', + loader: ({ params }) => params.parsedParam.revisionNumber * 100, + component: () => { + const params = parsedParamIndexRoute.useParams() + const loaderData = parsedParamIndexRoute.useLoaderData() + + return ( + <> +
    + Params have {params().parsedParam.recordName} with revision{' '} + {params().parsedParam.revisionNumber} +
    +
    Loader data is {loaderData()}
    + + ) + }, + }) + const routeTree = rootRoute.addChildren([ + indexRoute, + parsedParamRoute.addChildren([parsedParamIndexRoute]), + ]) + const router = createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + + await router.navigate({ + to: '/$parsedParam', + params: { parsedParam: { recordName: 'blue', revisionNumber: 1 } }, + }) + expect( + await screen.findByText('Params have blue with revision 1'), + ).toBeInTheDocument() + expect(await screen.findByText('Loader data is 100')).toBeInTheDocument() + + await router.navigate({ to: '/' }) + expect(await screen.findByText('Home page')).toBeInTheDocument() + + await router.navigate({ + to: '/$parsedParam', + params: { parsedParam: { recordName: 'red', revisionNumber: 2 } }, + }) + expect(router.state.location.pathname).toBe('/red-2') + + await waitFor(() => { + expect({ + params: screen.getByTestId('params').textContent, + loaderData: screen.getByTestId('loader-data').textContent, + }).toEqual({ + params: 'Params have red with revision 2', + loaderData: 'Loader data is 200', + }) + }) +}) diff --git a/packages/solid-router/tests/issue-7986-retained-pending.test.tsx b/packages/solid-router/tests/issue-7986-retained-pending.test.tsx new file mode 100644 index 0000000000..e4051afbbf --- /dev/null +++ b/packages/solid-router/tests/issue-7986-retained-pending.test.tsx @@ -0,0 +1,1055 @@ +import { cleanup, render, screen, waitFor } from '@solidjs/testing-library' +import { afterEach, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { + Outlet, + RouterProvider, + createLazyRoute, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' +import type { ControlledPromise } from '@tanstack/router-core' + +const controlledPromises = new Set>() +const pendingOperations = new Set>() + +afterEach(async () => { + try { + for (const promise of controlledPromises) { + if (promise.status === 'pending') { + promise.resolve() + } + } + if (vi.isFakeTimers()) { + await vi.runAllTimersAsync() + } + await Promise.allSettled(pendingOperations) + } finally { + controlledPromises.clear() + pendingOperations.clear() + cleanup() + vi.useRealTimers() + vi.restoreAllMocks() + } +}) + +const navigationDelay = 100 + +function delayNavigation() { + return new Promise((resolve) => setTimeout(resolve, navigationDelay)) +} + +function controlled() { + const promise = createControlledPromise() + controlledPromises.add(promise) + return promise +} + +function track(operation: Promise) { + pendingOperations.add(operation) + return operation +} + +function setup() { + const navigationBeforeLoadStarted = controlled() + let beforeLoadCalls = 0 + + const rootRoute = createRootRoute({ component: () => }) + const layoutRoute = createRoute({ + getParentRoute: () => rootRoute, + id: 'app', + beforeLoad: async () => { + if (++beforeLoadCalls > 1) { + navigationBeforeLoadStarted.resolve() + await delayNavigation() + } + return { user: 'test' } + }, + component: () => , + }) + const projectRoute = createRoute({ + getParentRoute: () => layoutRoute, + path: '/projects/$projectId', + validateSearch: (search: Record): { tab?: string } => + typeof search.tab === 'string' ? { tab: search.tab } : {}, + component: Project, + }) + + function Project() { + const params = projectRoute.useParams() + const search = projectRoute.useSearch() + return ( +
    + project={params().projectId} tab={search().tab ?? 'default'} +
    + ) + } + + const router = createRouter({ + routeTree: rootRoute.addChildren([layoutRoute.addChildren([projectRoute])]), + history: createMemoryHistory({ initialEntries: ['/projects/p1'] }), + defaultPendingComponent: () =>
    Pending
    , + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + return { router, navigationBeforeLoadStarted } +} + +test('a search-only navigation retains successful UI while beforeLoad reruns', async () => { + const { router, navigationBeforeLoadStarted } = setup() + render(() => ) + expect(await screen.findByTestId('content')).toHaveTextContent( + 'project=p1 tab=default', + ) + + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const navigation = track( + router.navigate({ + to: '/projects/$projectId', + params: { projectId: 'p1' }, + search: { tab: 'files' }, + }), + ) + await navigationBeforeLoadStarted + + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent( + 'project=p1 tab=default', + ) + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent( + 'project=p1 tab=default', + ) + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(navigationDelay) + await navigation + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toHaveTextContent( + 'project=p1 tab=files', + ) +}) + +test('a path-param navigation retains successful UI while beforeLoad reruns', async () => { + const { router, navigationBeforeLoadStarted } = setup() + render(() => ) + expect(await screen.findByTestId('content')).toHaveTextContent( + 'project=p1 tab=default', + ) + + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const navigation = track( + router.navigate({ + to: '/projects/$projectId', + params: { projectId: 'p2' }, + }), + ) + await navigationBeforeLoadStarted + + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent( + 'project=p1 tab=default', + ) + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent( + 'project=p1 tab=default', + ) + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(navigationDelay) + await navigation + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toHaveTextContent( + 'project=p2 tab=default', + ) +}) + +test('a blocking reload retains the exact successful match', async () => { + const reloadStarted = controlled() + let loaderCalls = 0 + + const rootRoute = createRootRoute({ component: () => }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + validateSearch: (search: Record): { tab?: string } => + typeof search.tab === 'string' ? { tab: search.tab } : {}, + shouldReload: true, + loader: { + staleReloadMode: 'blocking', + handler: () => { + if (++loaderCalls === 1) { + return 'initial' + } + reloadStarted.resolve() + return delayNavigation().then(() => 'reloaded') + }, + }, + component: () => ( +
    + {pageRoute.useLoaderData()()} tab= + {pageRoute.useSearch()().tab ?? 'default'} +
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + defaultPendingComponent: () =>
    Pending
    , + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render(() => ) + expect(await screen.findByTestId('content')).toHaveTextContent( + 'initial tab=default', + ) + + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const navigation = track( + router.navigate({ + to: '/page', + search: { tab: 'files' }, + }), + ) + await reloadStarted + + const contentWhileLoading = screen.getByTestId('content') + expect(contentWhileLoading).toBeVisible() + expect(contentWhileLoading).toHaveTextContent('initial tab=default') + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent('initial tab=default') + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(navigationDelay) + await navigation + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toHaveTextContent('reloaded tab=files') +}) + +test('a cached success retries through pending UI when an error is mounted', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const retryStarted = controlled() + const retry = controlled() + let loaderCalls = 0 + + const rootRoute = createRootRoute({ component: () => }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + shouldReload: true, + loader: { + staleReloadMode: 'blocking', + handler: () => { + loaderCalls++ + if (loaderCalls === 1) { + throw new Error('initial load failed') + } + if (loaderCalls === 2) { + return 'preloaded' + } + retryStarted.resolve() + return retry.then(() => 'retried') + }, + }, + component: () => ( +
    {pageRoute.useLoaderData()()}
    + ), + pendingComponent: () =>
    Pending
    , + errorComponent: () =>
    Failed
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render(() => ) + expect(await screen.findByTestId('error')).toBeInTheDocument() + + await router.preloadRoute({ to: '/page' }) + expect(loaderCalls).toBe(2) + expect(screen.getByTestId('error')).toBeInTheDocument() + + const navigation = track(router.navigate({ to: '/page' })) + await retryStarted + + expect(await screen.findByTestId('pending')).toBeVisible() + expect(screen.queryByTestId('error')).not.toBeInTheDocument() + + retry.resolve() + await navigation + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent('retried') +}) + +test('a cache-only success retries through pending UI over mounted success', async () => { + const retryStarted = controlled() + const retry = controlled() + let loaderCalls = 0 + + const rootRoute = createRootRoute({ component: () => }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + shouldReload: true, + loader: { + staleReloadMode: 'blocking', + handler: () => { + const generation = ++loaderCalls + if (generation === 3) { + retryStarted.resolve() + return retry.then(() => `generation ${generation}`) + } + return `generation ${generation}` + }, + }, + component: () => ( +
    {pageRoute.useLoaderData()()}
    + ), + pendingComponent: () =>
    Pending
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render(() => ) + expect(await screen.findByTestId('content')).toHaveTextContent('generation 1') + + await router.preloadRoute({ to: '/page' }) + expect(loaderCalls).toBe(2) + expect(screen.getByTestId('content')).toHaveTextContent('generation 1') + + const navigation = track(router.navigate({ to: '/page' })) + await retryStarted + + expect(await screen.findByTestId('pending')).toBeVisible() + expect(screen.queryByTestId('content')).not.toBeInTheDocument() + + retry.resolve() + await navigation + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toHaveTextContent('generation 3') +}) + +test('a success hidden below an error boundary retries through pending UI', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const childReloadStarted = controlled() + const childReload = controlled() + let parentFails = false + let childReloads = false + + const rootRoute = createRootRoute({ component: () => }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + shouldReload: true, + loader: () => { + if (parentFails) { + throw new Error('parent failed') + } + return 'parent data' + }, + component: () => , + errorComponent: () =>
    Parent failed
    , + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + shouldReload: () => childReloads, + loader: { + staleReloadMode: 'blocking', + handler: () => { + if (childReloads) { + childReloadStarted.resolve() + return childReload.then(() => 'reloaded child') + } + return 'initial child' + }, + }, + component: () => ( +
    {childRoute.useLoaderData()()}
    + ), + pendingComponent: () =>
    Pending child
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render(() => ) + expect(await screen.findByTestId('content')).toHaveTextContent( + 'initial child', + ) + + parentFails = true + await track(router.navigate({ to: '/parent/child' })) + expect(await screen.findByTestId('error')).toBeInTheDocument() + + parentFails = false + childReloads = true + const navigation = track(router.navigate({ to: '/parent/child' })) + await childReloadStarted + + expect(await screen.findByTestId('pending')).toBeVisible() + expect(screen.queryByTestId('error')).not.toBeInTheDocument() + + childReload.resolve() + await navigation + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent('reloaded child') +}) + +test('a global not-found destination keeps pending until its terminal component is ready', async () => { + const missingStarted = controlled() + const missingLoader = controlled() + const terminalStarted = controlled() + const terminalReady = controlled() + let loaderCalls = 0 + const Missing = Object.assign( + () =>
    Missing
    , + { + preload: () => { + terminalStarted.resolve() + return terminalReady + }, + }, + ) + + const rootRoute = createRootRoute({ + shouldReload: true, + loader: { + staleReloadMode: 'blocking', + handler: () => { + if (++loaderCalls === 1) { + return 'initial root' + } + missingStarted.resolve() + return missingLoader + }, + }, + component: () => , + pendingComponent: () =>
    Pending root
    , + notFoundComponent: Missing, + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + component: () =>
    Page
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render(() => ) + expect(await screen.findByTestId('content')).toBeInTheDocument() + + const navigation = track(router.navigate({ to: '/missing' } as any)) + await missingStarted + + expect(await screen.findByTestId('pending')).toBeVisible() + expect(screen.queryByTestId('content')).not.toBeInTheDocument() + + let settled = false + void navigation.then(() => { + settled = true + }) + missingLoader.resolve() + await terminalStarted + expect(screen.getByTestId('pending')).toBeVisible() + expect(screen.queryByTestId('missing')).not.toBeInTheDocument() + expect(settled).toBe(false) + + terminalReady.resolve() + await navigation + + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.getByTestId('missing')).toBeVisible() +}) + +test('a cold global not-found presents pending only while its terminal component loads', async () => { + const terminalStarted = controlled() + const terminalReady = controlled() + const Missing = Object.assign( + () =>
    Missing
    , + { + preload: () => { + terminalStarted.resolve() + return terminalReady + }, + }, + ) + const rootRoute = createRootRoute({ + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>
    Pending root
    , + notFoundComponent: Missing, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/missing'] }), + }) + + render(() => ) + await terminalStarted + expect(await screen.findByTestId('pending')).toBeVisible() + expect(screen.queryByTestId('missing')).not.toBeInTheDocument() + + terminalReady.resolve() + expect(await screen.findByTestId('missing')).toBeVisible() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() +}) + +test('lazy fuzzy-boundary relocation retains the mounted parent', async () => { + const lazyStarted = controlled() + const lazyRoute = controlled() + const parentReloadStarted = controlled() + const parentReload = controlled() + let parentLoads = 0 + + const rootRoute = createRootRoute({ + component: () => , + notFoundComponent: () =>
    Root missing
    , + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: async () => { + if (++parentLoads > 1) { + parentReloadStarted.resolve() + await parentReload + } + }, + component: () => ( +
    +
    Parent content
    + +
    + ), + pendingComponent: () => ( +
    Parent pending
    + ), + notFoundComponent: () => ( +
    Parent missing
    + ), + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + }).lazy(async () => { + lazyStarted.resolve() + await lazyRoute + return createLazyRoute('/parent/child')({ + notFoundComponent: () => ( +
    Child missing
    + ), + }) + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent'] }), + defaultPendingComponent: () => ( +
    Pending
    + ), + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render(() => ) + expect(await screen.findByTestId('parent-content')).toBeVisible() + + const navigation = track( + router.navigate({ to: '/parent/child/missing' as any }), + ) + await lazyStarted + + expect(screen.getByTestId('parent-content')).toBeVisible() + expect(screen.queryByTestId('parent-pending')).not.toBeInTheDocument() + expect(screen.queryByTestId('parent-missing')).not.toBeInTheDocument() + + lazyRoute.resolve() + await parentReloadStarted + + expect(screen.getByTestId('parent-content')).toBeVisible() + expect(screen.queryByTestId('parent-pending')).not.toBeInTheDocument() + expect(screen.queryByTestId('parent-missing')).not.toBeInTheDocument() + + parentReload.resolve() + await navigation + + expect(screen.getByTestId('child-missing')).toBeVisible() + expect(screen.queryByTestId('root-missing')).not.toBeInTheDocument() + expect(screen.queryByTestId('parent-missing')).not.toBeInTheDocument() +}) + +test('a superseding navigation replaces an unrelated pending presentation', async () => { + const otherStarted = controlled() + const otherLoader = controlled() + const pageReloadStarted = controlled() + const pageReload = controlled() + let pageLoads = 0 + + const rootRoute = createRootRoute({ component: () => }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + shouldReload: true, + loader: { + staleReloadMode: 'blocking', + handler: () => { + if (++pageLoads === 1) { + return 'initial page' + } + pageReloadStarted.resolve() + return pageReload.then(() => 'reloaded page') + }, + }, + component: () => ( +
    {pageRoute.useLoaderData()()}
    + ), + pendingComponent: () =>
    Page pending
    , + }) + const otherRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/other', + loader: async () => { + otherStarted.resolve() + await otherLoader + }, + pendingComponent: () => ( +
    Other pending
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute, otherRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 1, + }) + + render(() => ) + expect(await screen.findByTestId('content')).toHaveTextContent('initial page') + + const otherNavigation = track(router.navigate({ to: '/other' })) + await otherStarted + expect(await screen.findByTestId('other-pending')).toBeVisible() + + const navigation = track(router.navigate({ to: '/page' })) + await pageReloadStarted + + await waitFor(() => { + expect(screen.getByTestId('page-pending')).toBeVisible() + expect(screen.queryByTestId('other-pending')).not.toBeInTheDocument() + }) + + pageReload.resolve() + await navigation + otherLoader.resolve() + await otherNavigation + + expect(screen.queryByTestId('page-pending')).not.toBeInTheDocument() + expect(screen.getByTestId('content')).toBeVisible() + expect(screen.getByTestId('content')).toHaveTextContent('reloaded page') +}) + +test('a retained root publishes fresh context with a child fallback', async () => { + const retainedStarted = controlled() + const retainedReady = controlled() + const childStarted = controlled() + const childReady = controlled() + let retainedLoads = 0 + + const rootRoute = createRootRoute({ + validateSearch: (search: Record): { user: string } => ({ + user: typeof search.user === 'string' ? search.user : 'unknown', + }), + beforeLoad: async ({ search }) => { + if (++retainedLoads > 1) { + retainedStarted.resolve() + await retainedReady + } + return { user: search.user } + }, + component: () => ( +
    +
    {rootRoute.useRouteContext()().user}
    + +
    + ), + }) + const sourceRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/source', + component: () =>
    Source
    , + }) + const childRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/child', + loader: async () => { + childStarted.resolve() + await childReady + }, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>
    Pending
    , + component: () =>
    Child
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([sourceRoute, childRoute]), + history: createMemoryHistory({ initialEntries: ['/source?user=Ada'] }), + }) + + render(() => ) + expect(await screen.findByTestId('source')).toBeVisible() + expect(screen.getByTestId('user')).toHaveTextContent('Ada') + await waitFor(() => expect(router.state.status).toBe('idle')) + + const navigation = track( + router.navigate({ to: '/child', search: { user: 'Grace' } }), + ) + await retainedStarted + expect(screen.getByTestId('source')).toBeVisible() + expect(screen.getByTestId('user')).toHaveTextContent('Ada') + expect(screen.queryByTestId('child-pending')).not.toBeInTheDocument() + + retainedReady.resolve() + await childStarted + expect(await screen.findByTestId('child-pending')).toBeVisible() + expect(screen.getByTestId('user')).toHaveTextContent('Grace') + + childReady.resolve() + await navigation + expect(screen.getByTestId('child')).toBeVisible() +}) + +test('a retained prefix exposes one fresh context chain before descendant pending', async () => { + const retainedStarted = controlled() + const retainedReady = controlled() + const pendingStarted = controlled() + const pendingReady = controlled() + let retainedLoads = 0 + + const rootRoute = createRootRoute({ + beforeLoad: () => ({ rootReady: true }), + component: () => , + }) + const aRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'a', + validateSearch: (search: Record): { user: string } => ({ + user: typeof search.user === 'string' ? search.user : 'unknown', + }), + beforeLoad: async ({ search }) => { + if (++retainedLoads > 1) { + retainedStarted.resolve() + await retainedReady + } + return { user: search.user } + }, + component: () => { + const user = aRoute.useRouteContext({ + select: (context) => context.user, + }) + return ( +
    +
    {user()}
    + +
    + ) + }, + }) + const bRoute = createRoute({ + getParentRoute: () => aRoute, + path: 'b', + component: () => , + }) + const cRoute = createRoute({ + getParentRoute: () => bRoute, + path: 'c', + component: () => , + }) + const dRoute = createRoute({ + getParentRoute: () => cRoute, + path: 'd', + component: () =>
    Source
    , + }) + const eRoute = createRoute({ + getParentRoute: () => aRoute, + path: 'e', + component: () => { + const user = eRoute.useRouteContext({ + select: (context) => context.user, + }) + return ( +
    +
    {user()}
    + +
    + ) + }, + }) + const fRoute = createRoute({ + getParentRoute: () => eRoute, + path: 'f', + loader: async () => { + pendingStarted.resolve() + await pendingReady + }, + pendingComponent: () => { + const user = fRoute.useRouteContext({ + select: (context) => context.user, + }) + return
    F pending for {user()}
    + }, + component: () => , + }) + const gRoute = createRoute({ + getParentRoute: () => fRoute, + path: 'g', + component: () =>
    G
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + aRoute.addChildren([ + bRoute.addChildren([cRoute.addChildren([dRoute])]), + eRoute.addChildren([fRoute.addChildren([gRoute])]), + ]), + ]), + history: createMemoryHistory({ initialEntries: ['/a/b/c/d?user=Ada'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 0, + }) + + render(() => ) + expect(await screen.findByTestId('source')).toBeVisible() + expect(screen.getByTestId('user')).toHaveTextContent('Ada') + + const navigation = track( + router.navigate({ + to: '/a/e/f/g', + search: { user: 'Grace' }, + }), + ) + await retainedStarted + + expect(screen.getByTestId('source')).toBeVisible() + expect(screen.getByTestId('user')).toHaveTextContent('Ada') + expect(screen.queryByTestId('f-pending')).not.toBeInTheDocument() + + retainedReady.resolve() + await pendingStarted + + expect(await screen.findByTestId('f-pending')).toBeVisible() + expect(screen.getByTestId('user')).toHaveTextContent('Grace') + expect(screen.getByTestId('e-user')).toHaveTextContent('Grace') + expect(screen.getByTestId('f-pending')).toHaveTextContent('Grace') + expect(screen.queryByTestId('source')).not.toBeInTheDocument() + expect(screen.queryByTestId('hidden-g')).not.toBeInTheDocument() + expect(router.state.matches.map((match) => match.routeId)).toContain( + gRoute.id, + ) + + pendingReady.resolve() + await navigation +}) + +test.each([false, true])( + 'retained loader and component work does not own the child fallback (parent pending: %s)', + async (parentHasPending) => { + const parentReloadStarted = controlled() + const parentReload = controlled() + const parentComponent = controlled() + const childLoader = controlled() + let parentLoads = 0 + let parentPreloads = 0 + + const rootRoute = createRootRoute({ component: () => }) + const Parent = Object.assign( + () => ( +
    + {parentRoute.useLoaderData()()} + +
    + ), + { + preload: () => (++parentPreloads === 1 ? undefined : parentComponent), + }, + ) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'parent', + shouldReload: true, + loader: { + staleReloadMode: 'blocking', + handler: async () => { + if (++parentLoads === 1) { + return 'initial parent' + } + parentReloadStarted.resolve() + await parentReload + return 'reloaded parent' + }, + }, + component: Parent, + ...(parentHasPending + ? { + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () => ( +
    Parent pending
    + ), + } + : {}), + }) + const sourceRoute = createRoute({ + getParentRoute: () => parentRoute, + path: 'source', + component: () =>
    Source
    , + }) + const childOptions = createLazyRoute('/parent/child')({ + pendingComponent: () => ( +
    Child pending
    + ), + component: () =>
    Child
    , + }) + const childLazy = createControlledPromise() + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: 'child', + pendingMs: 0, + pendingMinMs: 0, + loader: () => childLoader, + }).lazy(() => childLazy) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + parentRoute.addChildren([sourceRoute, childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/parent/source'] }), + }) + + render(() => ) + expect(await screen.findByTestId('source')).toBeVisible() + await waitFor(() => expect(router.state.status).toBe('idle')) + + const navigation = track(router.navigate({ to: '/parent/child' })) + try { + await parentReloadStarted + parentReload.resolve() + await waitFor(() => { + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id) + ?.isFetching, + ).toBe(false) + }) + + childLazy.resolve(childOptions) + expect(await screen.findByTestId('child-pending')).toBeVisible() + expect(screen.getByTestId('parent-content')).toBeVisible() + expect(screen.queryByTestId('parent-pending')).not.toBeInTheDocument() + expect(screen.queryByTestId('source')).not.toBeInTheDocument() + } finally { + parentReload.resolve() + parentComponent.resolve() + childLazy.resolve(childOptions) + childLoader.resolve() + await navigation + } + + expect(screen.getByTestId('child')).toBeVisible() + }, +) + +test('a failure in the last retained guard suppresses descendant pending', async () => { + const guardStarted = controlled() + const guardReady = controlled() + const childReady = controlled() + let guardLoads = 0 + let childLoads = 0 + + const rootRoute = createRootRoute({ + beforeLoad: () => ({ rootReady: true }), + component: () => , + }) + const layoutRoute = createRoute({ + getParentRoute: () => rootRoute, + id: 'layout', + beforeLoad: async () => { + if (++guardLoads > 1) { + guardStarted.resolve() + await guardReady + throw new Error('blocked') + } + }, + component: () => , + errorComponent: () =>
    Guard error
    , + }) + const sourceRoute = createRoute({ + getParentRoute: () => layoutRoute, + path: '/source', + component: () =>
    Source
    , + }) + const childRoute = createRoute({ + getParentRoute: () => layoutRoute, + path: '/child', + loader: async () => { + childLoads++ + await childReady + }, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>
    Pending
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + layoutRoute.addChildren([sourceRoute, childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/source'] }), + }) + + render(() => ) + expect(await screen.findByTestId('source')).toBeVisible() + await waitFor(() => expect(router.state.status).toBe('idle')) + + const navigation = track(router.navigate({ to: '/child' })) + await guardStarted + expect(screen.getByTestId('source')).toBeVisible() + expect(screen.queryByTestId('child-pending')).not.toBeInTheDocument() + expect(childLoads).toBe(0) + + guardReady.resolve() + await navigation + expect(await screen.findByTestId('guard-error')).toBeVisible() + expect(screen.queryByTestId('child-pending')).not.toBeInTheDocument() + expect(childLoads).toBe(0) +}) diff --git a/packages/solid-router/tests/issue-8115-context.test.tsx b/packages/solid-router/tests/issue-8115-context.test.tsx new file mode 100644 index 0000000000..114935549c --- /dev/null +++ b/packages/solid-router/tests/issue-8115-context.test.tsx @@ -0,0 +1,771 @@ +import { Show, createMemo, createSignal } from 'solid-js' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@solidjs/testing-library' +import { afterEach, expect, test, vi } from 'vitest' +import { hydrate } from '@tanstack/router-core/ssr/client' +import { attachRouterServerSsrUtils } from '@tanstack/router-core/ssr/server' +import { + Outlet, + RouterProvider, + Scripts, + createControlledPromise, + createMemoryHistory, + createRootRoute, + createRootRouteWithContext, + createRoute, + createRouter, + useLocation, +} from '../src' + +declare module '@tanstack/history' { + interface HistoryState { + issue8115Revision?: 'old' | 'new' + } +} + +afterEach(() => { + cleanup() + vi.restoreAllMocks() + delete window.$_TSR + delete (window as Window & { $R?: unknown }).$R + document.body.innerHTML = '' +}) + +test('invalidate merges fresh parent beforeLoad context with cached child context', async () => { + let generation = 0 + let childContextCalls = 0 + + const rootRoute = createRootRoute({ + beforeLoad: () => { + generation++ + return { + parentGeneration: generation, + collision: `parent-${generation}`, + } + }, + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + context: ({ context }) => { + childContextCalls++ + return { + childSnapshotOfParent: context.parentGeneration, + collision: `child-snapshot-${context.parentGeneration}`, + } + }, + component: () => { + const context = childRoute.useRouteContext() + + return ( +
    +
    + {context().parentGeneration} +
    +
    + {context().childSnapshotOfParent} +
    +
    {context().collision}
    +
    + ) + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + + expect(await screen.findByTestId('parent-generation')).toHaveTextContent('1') + expect(screen.getByTestId('child-snapshot')).toHaveTextContent('1') + expect(screen.getByTestId('collision')).toHaveTextContent('child-snapshot-1') + expect(generation).toBe(1) + expect(childContextCalls).toBe(1) + const childMatchId = router.state.matches[1]!.id + + await router.invalidate() + + // The fresh parent contribution is merged under the cached child contribution. + expect(router.state.matches[1]!.id).toBe(childMatchId) + expect(generation).toBe(2) + expect(childContextCalls).toBe(1) + await waitFor(() => { + expect(screen.getByTestId('parent-generation')).toHaveTextContent('2') + expect(screen.getByTestId('child-snapshot')).toHaveTextContent('1') + expect(screen.getByTestId('collision')).toHaveTextContent( + 'child-snapshot-1', + ) + }) +}) + +test('a same-id child beforeLoad error observes fresh inherited context', async () => { + const childError = new Error('child beforeLoad failed') + let parentGeneration = 0 + let renderedError: unknown + + const rootRoute = createRootRoute({ component: Outlet }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loaderDeps: () => ({ stable: true }), + beforeLoad: () => ({ generation: ++parentGeneration }), + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loaderDeps: () => ({ stable: true }), + beforeLoad: ({ context }) => { + if (context.generation === 2) { + throw childError + } + }, + component: () => { + const context = childRoute.useRouteContext() + return
    {context().generation}
    + }, + errorComponent: ({ error }) => { + renderedError = error + const context = childRoute.useRouteContext() + + return ( +
    {context().generation}
    + ) + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + render(() => ) + + expect(await screen.findByTestId('child-generation')).toHaveTextContent('1') + await waitFor(() => expect(router.state.status).toBe('idle')) + const initialChildMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )?.id + expect(initialChildMatchId).toBeDefined() + + await router.invalidate() + + expect( + await screen.findByTestId('child-error-generation'), + ).toBeInTheDocument() + expect(renderedError).toBe(childError) + expect( + router.state.matches.find((match) => match.routeId === childRoute.id)?.id, + ).toBe(initialChildMatchId) + expect(screen.getByTestId('child-error-generation')).toHaveTextContent('2') +}) + +test('a same-match reload merges new provider context with cached route context', async () => { + type ProviderContext = { + providerValue: string + collision: string + } + + const providerA: ProviderContext = { + providerValue: 'A', + collision: 'provider:A', + } + const providerB: ProviderContext = { + providerValue: 'B', + collision: 'provider:B', + } + const rootRoute = createRootRouteWithContext()() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + context: ({ context }) => ({ + derivedFromProvider: `derived:${context.providerValue}`, + collision: `route-cached:${context.providerValue}`, + }), + component: () => { + const context = indexRoute.useRouteContext() + return
    {JSON.stringify(context())}
    + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + context: providerA, + }) + const [provider, setProvider] = createSignal(providerA) + + render(() => ( + + {(context) => } + + )) + expect(await screen.findByTestId('full-context')).toHaveTextContent( + JSON.stringify({ + providerValue: 'A', + collision: 'route-cached:A', + derivedFromProvider: 'derived:A', + }), + ) + + setProvider(providerB) + await Promise.resolve() + await router.invalidate() + + await waitFor(() => { + expect(screen.getByTestId('full-context')).toHaveTextContent( + JSON.stringify({ + providerValue: 'B', + collision: 'route-cached:A', + derivedFromProvider: 'derived:A', + }), + ) + }) +}) + +test('navigation merges fresh parent context with cached child preload context', async () => { + let parentBeforeLoadRuns = 0 + let childContextRuns = 0 + let childLoaderRuns = 0 + + const rootRoute = createRootRoute({ component: Outlet }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: ({ preload }) => { + parentBeforeLoadRuns++ + return { + parentValue: preload ? 'parent-preload' : 'parent-navigation', + } + }, + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + context: ({ context, preload }) => { + childContextRuns++ + return { + childValue: `${preload ? 'child-preload' : 'child-navigation'}:${context.parentValue}`, + } + }, + loader: () => { + childLoaderRuns++ + return 'child data' + }, + preloadStaleTime: Infinity, + component: () => { + const context = childRoute.useRouteContext() + return ( +
    + {JSON.stringify({ + parentValue: context().parentValue, + childValue: context().childValue, + })} +
    + ) + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + parentRoute.addChildren([childRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + expect(await screen.findByText('Home')).toBeInTheDocument() + + await router.preloadRoute({ to: '/parent/child' }) + expect(parentBeforeLoadRuns).toBe(1) + expect(childContextRuns).toBe(1) + expect(childLoaderRuns).toBe(1) + + await router.navigate({ to: '/parent/child' }) + + expect(await screen.findByTestId('context')).toHaveTextContent( + JSON.stringify({ + parentValue: 'parent-navigation', + childValue: 'child-preload:parent-preload', + }), + ) + expect(parentBeforeLoadRuns).toBe(2) + expect(childContextRuns).toBe(1) + expect(childLoaderRuns).toBe(1) +}) + +test('a cached child context contribution is merged with fresh parent context', async () => { + const rootRoute = createRootRoute({ component: Outlet }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + version: Number(search.version), + }), + loaderDeps: ({ search }) => ({ version: search.version }), + context: ({ deps }) => ({ parentVersion: `version-${deps.version}` }), + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loaderDeps: () => ({ stable: true }), + context: ({ context }) => ({ + childSnapshot: `derived-from-${context.parentVersion}`, + }), + component: () => { + const context = childRoute.useRouteContext() + return ( +
    + Parent: {context().parentVersion}; cached child:{' '} + {context().childSnapshot} +
    + ) + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ + initialEntries: ['/parent/child?version=1'], + }), + }) + + render(() => ) + + expect( + await screen.findByText( + 'Parent: version-1; cached child: derived-from-version-1', + ), + ).toBeInTheDocument() + + const initialParentMatchId = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )?.id + const initialChildMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )?.id + + expect(initialParentMatchId).toBeDefined() + expect(initialChildMatchId).toBeDefined() + + await router.navigate({ + to: '/parent/child', + search: { version: 2 }, + }) + + await waitFor(() => { + expect( + screen.getByText( + 'Parent: version-2; cached child: derived-from-version-1', + ), + ).toBeInTheDocument() + }) + + const nextParentMatchId = router.state.matches.find( + (match) => match.routeId === parentRoute.id, + )?.id + const nextChildMatchId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )?.id + + expect(nextParentMatchId).not.toBe(initialParentMatchId) + expect(nextChildMatchId).toBe(initialChildMatchId) +}) + +test('#8115: hydration does not render a successful route with missing context when context reconstruction fails', async () => { + const contextError = new Error('client context reconstruction failed') + const clientSuccessRenderValues: Array = [] + let clientContextAttempts = 0 + let serverPhase = true + + const createRouteTree = () => { + const rootRoute = createRootRoute({ + component: () => ( + <> + + + + ), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + context: (): { locale: string } => { + if (serverPhase) { + return { locale: 'en' } + } + clientContextAttempts++ + throw contextError + }, + component: () => { + const context = indexRoute.useRouteContext() + const locale = createMemo(() => { + const value: string | undefined = context().locale + if (!serverPhase) { + clientSuccessRenderValues.push(value) + } + return value + }) + return ( +
    Locale: {locale() ?? 'missing'}
    + ) + }, + errorComponent: ({ error }) => ( +
    + {error instanceof Error ? error.message : String(error)} +
    + ), + }) + + return rootRoute.addChildren([indexRoute]) + } + + const serverRouter = createRouter({ + routeTree: createRouteTree(), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + attachRouterServerSsrUtils({ router: serverRouter, manifest: undefined }) + const currentScriptSpy = vi.spyOn(document, 'currentScript', 'get') + try { + await serverRouter.load() + expect(serverRouter.state.matches.at(-1)?.context).toMatchObject({ + locale: 'en', + }) + expect(serverRouter.state.matches.at(-1)?.status).toBe('success') + + await serverRouter.serverSsr!.dehydrate() + const scripts = serverRouter.serverSsr!.takeInitialHydrationScriptTags() + expect(scripts?.before.length).toBeGreaterThan(0) + // These scripts come exclusively from the router's production SSR serializer. + for (const script of scripts!.before) { + expect(script.children).toBeTruthy() + currentScriptSpy.mockReturnValue(document.createElement('script')) + new Function(script.children!)() + } + } finally { + currentScriptSpy.mockRestore() + serverRouter.serverSsr?.cleanup() + } + expect(window.$_TSR?.router?.matches.at(-1)?.s).toBe('success') + + serverPhase = false + const clientRouter = createRouter({ + routeTree: createRouteTree(), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + await hydrate(clientRouter) + render(() => ) + + expect(await screen.findByTestId('route-error')).toHaveTextContent( + contextError.message, + ) + expect(clientContextAttempts).toBeGreaterThan(0) + expect(screen.queryByTestId('route-success')).not.toBeInTheDocument() + expect(clientSuccessRenderValues).not.toContain(undefined) +}) + +test('a same-id child retry presents one coherent beforeLoad context generation', async () => { + const childReloadStarted = createControlledPromise() + const childReload = createControlledPromise() + let parentGeneration = 0 + let childLoads = 0 + + const rootRoute = createRootRoute({ component: Outlet }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + beforeLoad: () => ({ generation: ++parentGeneration }), + component: () => { + const context = parentRoute.useRouteContext() + return ( +
    +
    + Parent generation {context().generation} +
    + +
    + ) + }, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: ({ context }) => ({ + inheritedGeneration: context.generation, + }), + loader: async () => { + if (++childLoads > 1) { + childReloadStarted.resolve() + await childReload + } + }, + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () => { + const context = childRoute.useRouteContext() + return ( +
    + Child generation {context().inheritedGeneration} +
    + ) + }, + component: () => { + const context = childRoute.useRouteContext() + return ( +
    + Child generation {context().inheritedGeneration} +
    + ) + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ initialEntries: ['/parent/child'] }), + }) + + render(() => ) + expect(await screen.findByTestId('parent-generation')).toHaveTextContent( + 'Parent generation 1', + ) + expect(await screen.findByTestId('child-generation')).toHaveTextContent( + 'Child generation 1', + ) + await waitFor(() => expect(router.state.status).toBe('idle')) + const initialChildId = router.state.matches.find( + (match) => match.routeId === childRoute.id, + )?.id + expect(initialChildId).toBeDefined() + + let invalidation: Promise | undefined + try { + invalidation = router.invalidate({ + filter: (match) => + match.routeId === parentRoute.id || match.routeId === childRoute.id, + forcePending: true, + }) + await childReloadStarted + + await waitFor(() => { + expect(screen.getByTestId('parent-generation')).toHaveTextContent( + 'Parent generation 2', + ) + expect(screen.getByTestId('child-pending-generation')).toHaveTextContent( + 'Child generation 2', + ) + }) + expect( + router.state.matches.find((match) => match.routeId === parentRoute.id), + ).toMatchObject({ + status: 'success', + context: { generation: 2 }, + }) + expect( + router.state.matches.find((match) => match.routeId === childRoute.id), + ).toMatchObject({ + id: initialChildId, + status: 'pending', + context: { generation: 2, inheritedGeneration: 2 }, + }) + } finally { + childReload.resolve() + await Promise.allSettled(invalidation ? [invalidation] : []) + } +}) + +test('a same-id navigation merges new inherited context with cached route context', async () => { + const history = createMemoryHistory({ initialEntries: ['/'] }) + history.replace('/', { issue8115Revision: 'old' }) + + const rootRoute = createRootRoute({ + beforeLoad: ({ location }) => ({ + inheritedRevision: location.state.issue8115Revision, + }), + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + context: ({ location }) => ({ + selfRevision: location.state.issue8115Revision, + }), + component: () => { + const location = useLocation() + const context = indexRoute.useRouteContext() + const matchId = indexRoute.useMatch({ select: (match) => match.id }) + const navigate = indexRoute.useNavigate() + + return ( + <> + {matchId()} + + location: {location().state.issue8115Revision}; inherited:{' '} + {context().inheritedRevision}; self: {context().selfRevision} + + + + ) + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render(() => ) + + expect(await screen.findByTestId('snapshot')).toHaveTextContent( + 'location: old; inherited: old; self: old', + ) + const initialMatchId = screen.getByTestId('match-id').textContent + + fireEvent.click(screen.getByRole('button', { name: 'Update state' })) + + await waitFor(() => { + expect(screen.getByTestId('match-id').textContent).toBe(initialMatchId) + expect(screen.getByTestId('snapshot')).toHaveTextContent( + 'location: new; inherited: new; self: old', + ) + }) +}) + +test('#8115: a successful root never renders without its context while a child is pending on cold load', async () => { + let resolveChildLoader!: () => void + const childLoader = new Promise((resolve) => { + resolveChildLoader = resolve + }) + const rootRenderValues: Array = [] + + const rootRoute = createRootRoute({ + context: () => ({ locale: 'en' }), + component: () => { + const context = rootRoute.useRouteContext() + const locale = createMemo(() => { + const value: string | undefined = context().locale + rootRenderValues.push(value) + return value + }) + + return ( +
    +

    Locale: {locale() ?? 'missing'}

    + +
    + ) + }, + }) + const childRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: () => childLoader, + pendingMs: 0, + pendingComponent: () =>

    Loading child

    , + component: () =>

    Child content

    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([childRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + + try { + expect(await screen.findByRole('status')).toHaveTextContent('Loading child') + expect(screen.getByTestId('root-locale')).toHaveTextContent('Locale: en') + expect(rootRenderValues.length).toBeGreaterThan(0) + expect(rootRenderValues.every((locale) => locale === 'en')).toBe(true) + } finally { + resolveChildLoader() + await childLoader + } +}) + +test('a same-id search navigation merges fresh inherited context with cached route context', async () => { + const rootRoute = createRootRoute({ component: Outlet }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + validateSearch: (search: Record) => ({ + revision: typeof search.revision === 'string' ? search.revision : 'one', + }), + loaderDeps: ({ search }) => ({ revision: search.revision }), + context: ({ deps }) => ({ inheritedRevision: deps.revision }), + component: Outlet, + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + loaderDeps: () => ({}), + context: ({ context, location }) => { + const search = location.search as Record + return { + cachedSelfRevision: `${context.inheritedRevision}:${String(search.revision)}`, + } + }, + component: () => { + const context = childRoute.useRouteContext() + const search = childRoute.useSearch() + const matchId = childRoute.useMatch({ select: (match) => match.id }) + + return ( + <> +
    {matchId()}
    +
    {search().revision}
    +
    + {context().inheritedRevision} +
    +
    + {context().cachedSelfRevision} +
    + + ) + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ + initialEntries: ['/parent/child?revision=one'], + }), + }) + + render(() => ) + + expect(await screen.findByTestId('current-search')).toHaveTextContent('one') + expect(screen.getByTestId('inherited-context')).toHaveTextContent('one') + expect(screen.getByTestId('cached-self-context')).toHaveTextContent('one:one') + const initialMatchId = screen.getByTestId('match-id').textContent + + await router.navigate({ + to: '/parent/child', + search: { revision: 'two' }, + }) + + await waitFor(() => { + expect(screen.getByTestId('current-search')).toHaveTextContent('two') + expect(screen.getByTestId('match-id').textContent).toBe(initialMatchId) + expect(screen.getByTestId('inherited-context')).toHaveTextContent('two') + expect(screen.getByTestId('cached-self-context')).toHaveTextContent( + 'one:one', + ) + }) +}) diff --git a/packages/solid-router/tests/jest-dom.setup.ts b/packages/solid-router/tests/jest-dom.setup.ts new file mode 100644 index 0000000000..8f7cbf15be --- /dev/null +++ b/packages/solid-router/tests/jest-dom.setup.ts @@ -0,0 +1,18 @@ +import * as jestDomMatchers from '@testing-library/jest-dom/matchers' +import { expect } from 'vitest' +import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' + +// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged +// and released, and go back to `import '@testing-library/jest-dom/vitest'`. +// That entry imports `vitest` from its own install location, which can resolve +// a different Vitest copy than the one running these tests, and its types +// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. +// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting +// `@testing-library/jest-dom/vitest` when a setup file path contains it. +expect.extend(jestDomMatchers) + +declare module 'vitest' { + // Type parameter names must match Vitest's declaration for the interfaces to merge. + // eslint-disable-next-line @typescript-eslint/naming-convention + interface Matchers extends TestingLibraryMatchers {} +} diff --git a/packages/solid-router/tests/lazy/normal.tsx b/packages/solid-router/tests/lazy/normal.tsx index 5b0f169da4..61eba8ab02 100644 --- a/packages/solid-router/tests/lazy/normal.tsx +++ b/packages/solid-router/tests/lazy/normal.tsx @@ -2,7 +2,7 @@ import { createLazyFileRoute, createLazyRoute } from '../../src' export function Route(id: string) { return createLazyRoute(id)({ - component: () =>

    I'm a normal route

    , + component: () =>

    I'm a normal route

    , }) } diff --git a/packages/solid-router/tests/lazyRouteComponent.production.test.tsx b/packages/solid-router/tests/lazyRouteComponent.production.test.tsx new file mode 100644 index 0000000000..34ccb97102 --- /dev/null +++ b/packages/solid-router/tests/lazyRouteComponent.production.test.tsx @@ -0,0 +1,135 @@ +import { resolve } from 'node:path' +import { setImmediate } from 'node:timers/promises' +import * as Solid from 'solid-js' +import * as SolidWeb from 'solid-js/web' +import { afterEach, beforeAll, expect, test, vi } from 'vitest' +import { cleanup, render, screen, waitFor } from '@solidjs/testing-library' +import { build } from 'vite' +import solid from 'vite-plugin-solid' +import type { lazyRouteComponent } from '../src/lazyRouteComponent' + +let productionLazyRouteComponent: typeof lazyRouteComponent + +beforeAll(async () => { + const result = await build({ + configFile: false, + logLevel: 'silent', + plugins: [solid({ dev: false, hot: false })], + define: { 'process.env.NODE_ENV': JSON.stringify('production') }, + build: { + write: false, + minify: true, + lib: { + entry: resolve(import.meta.dirname, '../src/lazyRouteComponent.tsx'), + formats: ['cjs'], + }, + rollupOptions: { external: ['solid-js', 'solid-js/web'] }, + }, + }) + const outputs = Array.isArray(result) ? result : [result] + const code = outputs + .flatMap((output) => { + if (!('output' in output)) { + throw new Error('Expected an in-memory build result') + } + return output.output.flatMap((chunk) => + chunk.type === 'chunk' ? [chunk.code] : [], + ) + }) + .join('\n') + const exports: { lazyRouteComponent?: typeof lazyRouteComponent } = {} + + // Use the test's Solid owner graph with the production-compiled router code. + new Function('require', 'exports', code)((id: string) => { + if (id === 'solid-js') { + return Solid + } + if (id === 'solid-js/web') { + return SolidWeb + } + throw new Error(`Unexpected external module: ${id}`) + }, exports) + + expect(exports.lazyRouteComponent).toBeTypeOf('function') + productionLazyRouteComponent = exports.lazyRouteComponent! +}, 60_000) + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +test.each([ + { exportName: undefined, preload: false }, + { exportName: 'Missing', preload: false }, + { exportName: undefined, preload: true }, + { exportName: 'Missing', preload: true }, +])( + 'a missing $exportName export renders blank with preload=$preload in production', + async ({ exportName, preload }) => { + const importer = vi.fn().mockResolvedValue({ Other: () => null }) + const Page = productionLazyRouteComponent(importer, exportName as never) + const onError = vi.fn(() => Render failed) + if (preload) { + await Page.preload?.() + } + + const { container } = render(() => ( + + Loading component}> + + + + )) + + await waitFor(() => + expect(screen.queryByText('Loading component')).not.toBeInTheDocument(), + ) + // Finish queued lazy-import continuations before checking for render errors. + await setImmediate() + expect(importer).toHaveBeenCalled() + expect(onError).not.toHaveBeenCalled() + expect(container).toBeEmptyDOMElement() + }, +) + +test('a preloaded production component renders synchronously with its props', async () => { + const importer = vi.fn(() => + Promise.resolve({ + Page: (props: { label: string }) => {props.label}, + }), + ) + const Page = productionLazyRouteComponent(importer, 'Page') + await Page.preload?.() + + render(() => ( + Loading component}> + + + )) + + expect(screen.getByText('Ready component')).toBeInTheDocument() + expect(screen.queryByText('Loading component')).not.toBeInTheDocument() + expect(importer).toHaveBeenCalledOnce() + expect(Page.preload).toBeUndefined() +}) + +test('a rejected production import reaches the error boundary', async () => { + const importer = vi + .fn() + .mockRejectedValue(new Error('component download failed')) + const Page = productionLazyRouteComponent(importer) + + render(() => ( + {error.message}}> + Loading component}> + + + + )) + + expect( + await screen.findByText('component download failed'), + ).toBeInTheDocument() + expect(importer).toHaveBeenCalledOnce() +}) diff --git a/packages/solid-router/tests/link-departing-scope.test.tsx b/packages/solid-router/tests/link-departing-scope.test.tsx new file mode 100644 index 0000000000..6e130f361b --- /dev/null +++ b/packages/solid-router/tests/link-departing-scope.test.tsx @@ -0,0 +1,1225 @@ +import { setFlagsFromString } from 'node:v8' +import { runInNewContext } from 'node:vm' +import * as Solid from 'solid-js' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@solidjs/testing-library' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouteMask, + createRouter, + redirect, + useMatch, +} from '../src' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +type Deferred = { + promise: Promise + resolve: () => void +} + +function deferred(): Deferred { + let resolve!: () => void + const promise = new Promise((r) => (resolve = r)) + return { promise, resolve } +} + +// Lets the router run its microtask-driven load steps. +const tick = () => new Promise((resolve) => setTimeout(resolve, 0)) + +type Gates = Partial> + +function setup({ + initial = '/a', + bAfterGate, + beforeRender, +}: { + initial?: string + bAfterGate?: () => void + beforeRender?: (router: any) => void +} = {}) { + const gates: Gates = {} + const counts = { + aUpdater: 0, + aRenders: 0, + goneUpdater: 0, + listUpdater: 0, + } + // The `x` dependency of every `/a` load, preloads included. + const aLoads: Array = [] + // The `x` of every location the `a-next` link derives from. + const nextFrom: Array = [] + const controls: { + setHash?: (hash: string | undefined) => void + setExtra?: (extra: boolean) => void + setGone?: (gone: boolean) => void + setRenderPreload?: (renderPreload: boolean) => void + setList?: (list: Array) => void + } = {} + + const root = createRootRoute({ + component: () => ( + <> + + root b + + + + ), + }) + const layout = createRoute({ + getParentRoute: () => root, + id: '_layout', + component: () => ( + <> + + layout b + + + + ), + }) + function AComponent() { + const [hash, setHash] = Solid.createSignal(undefined) + const [extra, setExtra] = Solid.createSignal(false) + const [gone, setGone] = Solid.createSignal(false) + const [renderPreload, setRenderPreload] = Solid.createSignal(false) + const [list, setList] = Solid.createSignal(['one', 'two']) + controls.setHash = setHash + controls.setExtra = setExtra + controls.setGone = setGone + controls.setRenderPreload = setRenderPreload + controls.setList = setList + return ( + <> +

    A page

    + { + counts.aUpdater++ + return prev + }} + > + {(state: { isActive: boolean }) => { + counts.aRenders++ + return state.isActive ? 'a self' : 'a self (inactive)' + }} + + + a dot + + { + nextFrom.push(prev.x) + return { x: `${prev.x}-next` } + }} + preload="intent" + preloadDelay={0} + data-testid="a-next" + > + a next + + + ({ x: `${prev.x}-render` })} + preload="render" + data-testid="a-render" + > + a render + + + + prev} data-testid="a-extra"> + a extra + + + + { + counts.goneUpdater++ + return prev + }} + > + a gone + + + + {(item) => ( + { + counts.listUpdater++ + return { ...prev, item } + }} + > + {item} + + )} + + + ) + } + const a = createRoute({ + getParentRoute: () => layout, + path: '/a', + loaderDeps: ({ search }: { search: any }) => ({ x: search.x }), + loader: ({ deps }: { deps: { x: unknown } }) => { + aLoads.push(deps.x) + return gates.a?.promise + }, + component: AComponent, + }) + const b = createRoute({ + getParentRoute: () => layout, + path: '/b', + loader: async () => { + await gates.b?.promise + bAfterGate?.() + }, + component: () =>

    B page

    , + }) + const c = createRoute({ + getParentRoute: () => root, + path: '/c', + component: () =>

    C page

    , + }) + const items = createRoute({ + getParentRoute: () => root, + path: '/items/$id', + loader: () => gates.items?.promise, + component: () => ( + <> +

    Items page

    + + item 1 + + + item 2 + + + ), + }) + + const router = createRouter({ + routeTree: root.addChildren([layout.addChildren([a, b]), c, items]), + history: createMemoryHistory({ initialEntries: [initial] }), + }) + + beforeRender?.(router) + render(() => ) + + const link = (id: string) => screen.getByTestId(id) + const isActive = (id: string) => + link(id).getAttribute('aria-current') === 'page' + const href = (id: string) => link(id).getAttribute('href') + + async function start(options: any) { + void router.navigate(options) + await tick() + } + + async function settle() { + await waitFor(() => expect(router.state.status).toBe('idle')) + } + + async function release(name: keyof Gates) { + const gate = gates[name]! + gates[name] = undefined + gate.resolve() + await gate.promise + await tick() + } + + return { + router, + gates, + counts, + aLoads, + nextFrom, + controls, + link, + isActive, + href, + start, + settle, + release, + } +} + +describe('links in a departing match', () => { + test('skip work at navigation start while staying links update urgently', async () => { + const t = setup() + await screen.findByText('A page') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(false) + expect(t.isActive('layout-b')).toBe(false) + + const updater = t.counts.aUpdater + const renders = t.counts.aRenders + const list = t.counts.listUpdater + t.gates.b = deferred() + await t.start({ to: '/b' }) + + expect(t.router.state.status).toBe('pending') + expect(t.router.state.location.pathname).toBe('/b') + expect(screen.getByText('A page')).toBeInTheDocument() + // Staying root and layout links update while the loader is pending. + expect(t.isActive('root-b')).toBe(true) + expect(t.isActive('layout-b')).toBe(true) + // The departing route's links do no work. + expect(t.counts.aUpdater).toBe(updater) + expect(t.counts.aRenders).toBe(renders) + expect(t.counts.listUpdater).toBe(list) + expect(t.isActive('a-self')).toBe(true) + + await t.release('b') + await screen.findByText('B page') + expect(t.isActive('root-b')).toBe(true) + expect(t.router.state.status).toBe('idle') + }) + + test('staying route with changed params updates its links while pending', async () => { + const t = setup({ initial: '/items/1' }) + await screen.findByText('Items page') + expect(t.isActive('item-1')).toBe(true) + expect(t.isActive('item-2')).toBe(false) + + t.gates.items = deferred() + await t.start({ to: '/items/$id', params: { id: '2' } }) + expect(t.router.state.status).toBe('pending') + expect(t.isActive('item-1')).toBe(false) + expect(t.isActive('item-2')).toBe(true) + + await t.release('items') + await t.settle() + expect(t.isActive('item-2')).toBe(true) + }) + + test('a pending departure redirected back to the owner ends consistent', async () => { + const t = setup({ + bAfterGate: () => { + throw redirect({ to: '/a', search: { x: 'back' } } as any) + }, + }) + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + expect(t.isActive('a-self')).toBe(true) + expect(t.href('a-self')).toBe('/a') + + await t.release('b') + await t.settle() + expect(t.router.state.location.href).toBe('/a?x=back') + expect(screen.getByText('A page')).toBeInTheDocument() + expect(t.href('a-self')).toBe('/a?x=back') + expect(t.isActive('a-self')).toBe(true) + expect(t.href('a-dot')).toBe('/a') + expect(t.isActive('root-b')).toBe(false) + }) + + test('a pending departure superseded by a location that keeps the owner ends consistent', async () => { + const t = setup() + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + const updater = t.counts.aUpdater + await t.start({ to: '/a', search: { x: 'two' } }) + expect(t.counts.aUpdater).toBeGreaterThan(updater) + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(false) + t.gates.b.resolve() + await t.settle() + expect(t.router.state.location.href).toBe('/a?x=two') + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('a-self')).toBe(true) + }) + + test('links changing in a departing match keep its held location, links mounting in it read the pending one', async () => { + const t = setup() + await screen.findByText('A page') + expect(t.href('a-dot')).toBe('/a') + t.gates.b = deferred() + await t.start({ to: '/b' }) + + t.controls.setHash!('h') + t.controls.setExtra!(true) + // A changing link builds from the location it held; a link mounting in a + // departing match has nothing to hold and reads the pending location. + expect(t.href('a-dot')).toBe('/a#h') + expect(t.href('a-extra')).toBe('/b') + expect(t.isActive('a-self')).toBe(true) + + await t.start({ to: '/a', search: { x: 'one' } }) + expect(t.href('a-dot')).toBe('/a#h') + expect(t.href('a-extra')).toBe('/a?x=one') + expect(t.href('a-self')).toBe('/a?x=one') + t.gates.b.resolve() + await t.settle() + expect(t.href('a-extra')).toBe('/a?x=one') + expect(t.isActive('a-extra')).toBe(true) + }) + + test('For churn in a departing match derives only the new link, from the pending location', async () => { + const t = setup({ initial: '/a?x=one' }) + await screen.findByText('A page') + expect(t.href('a-list-one')).toBe('/a?x=one&item=one') + t.gates.b = deferred() + await t.start({ to: '/b' }) + + const list = t.counts.listUpdater + t.controls.setList!(['two', 'three']) + expect(screen.queryByTestId('a-list-one')).toBeNull() + // Only the new link derives; it mounts without a held location. + expect(t.counts.listUpdater).toBe(list + 1) + expect(t.href('a-list-two')).toBe('/a?x=one&item=two') + expect(t.href('a-list-three')).toBe('/a?item=three') + + await t.release('b') + await screen.findByText('B page') + expect(t.counts.listUpdater).toBe(list + 1) + }) + + test('a pending navigation within the owner, then a departure, then back', async () => { + const t = setup() + await screen.findByText('A page') + + t.gates.a = deferred() + const firstA = t.gates.a + await t.start({ to: '/a', search: { x: 'one' } }) + expect(t.router.state.status).toBe('pending') + // Staying: updates while the owner's own loader is pending. + expect(t.href('a-self')).toBe('/a?x=one') + + t.gates.b = deferred() + const updater = t.counts.aUpdater + const renders = t.counts.aRenders + await t.start({ to: '/b' }) + expect(t.counts.aUpdater).toBe(updater) + expect(t.counts.aRenders).toBe(renders) + expect(t.href('a-self')).toBe('/a?x=one') + expect(t.isActive('root-b')).toBe(true) + + await t.start({ to: '/a', search: { x: 'two' } }) + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('root-b')).toBe(false) + + firstA.resolve() + t.gates.b.resolve() + await t.settle() + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('a-self')).toBe(true) + }) + + test('a departing link unmounted while pending does no further work', async () => { + const error = vi.spyOn(console, 'error') + const warn = vi.spyOn(console, 'warn') + const t = setup() + await screen.findByText('A page') + t.gates.b = deferred() + const gone = t.counts.goneUpdater + await t.start({ to: '/b' }) + t.controls.setGone!(true) + expect(screen.queryByTestId('a-gone')).toBeNull() + await t.release('b') + await screen.findByText('B page') + expect(t.counts.goneUpdater).toBe(gone) + expect(error).not.toHaveBeenCalled() + expect(warn).not.toHaveBeenCalled() + }) + + test.each([ + ['a-dot', '/a'], + ['a-next', '/a?x=one-next'], + ])( + 'clicking held link %s navigates to the href it displays', + async (id, displayed) => { + const t = setup({ initial: '/a?x=one' }) + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + expect(t.router.state.status).toBe('pending') + expect(t.href(id)).toBe(displayed) + + fireEvent.click(t.link(id)) + await tick() + expect(t.router.latestLocation.href).toBe(displayed) + t.gates.b.resolve() + await t.settle() + expect(t.router.state.location.href).toBe(displayed) + expect(screen.getByText('A page')).toBeInTheDocument() + }, + ) + + test.each(['mouseEnter', 'focus', 'touchStart'] as const)( + 'a %s preload of a held link loads the location it displays', + async (event) => { + const t = setup({ initial: '/a?x=one' }) + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + expect(t.href('a-next')).toBe('/a?x=one-next') + t.aLoads.length = 0 + + fireEvent[event](t.link('a-next')) + await tick() + expect(t.aLoads).toEqual(['one-next']) + await t.release('b') + await screen.findByText('B page') + }, + ) + + test('a render preload of a link mounting in a departing match loads the location it displays', async () => { + // A link mounting in a departing match displays the pending location. + const t = setup({ initial: '/a?x=one' }) + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + t.aLoads.length = 0 + + t.controls.setRenderPreload!(true) + await tick() + expect(t.href('a-render')).toBe('/a?x=undefined-render') + expect(t.aLoads).toEqual(['undefined-render']) + await t.release('b') + await screen.findByText('B page') + }) + + test('staying links click and preload from the live location', async () => { + const t = setup({ initial: '/a?x=one' }) + await screen.findByText('A page') + t.gates.a = deferred() + await t.start({ to: '/a', search: { x: 'two' } }) + expect(t.router.state.status).toBe('pending') + expect(t.href('a-next')).toBe('/a?x=two-next') + t.aLoads.length = 0 + + fireEvent.mouseEnter(t.link('a-next')) + await tick() + expect(t.aLoads).toEqual(['two-next']) + fireEvent.click(t.link('a-next')) + await tick() + expect(t.router.latestLocation.href).toBe('/a?x=two-next') + await t.release('a') + await t.settle() + expect(t.router.state.location.href).toBe('/a?x=two-next') + expect(t.href('a-next')).toBe('/a?x=two-next-next') + }) + + test('a revisited route starts with fresh links, also ones mounting during its next departure', async () => { + const t = setup({ initial: '/a?x=one' }) + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + expect(t.href('a-next')).toBe('/a?x=one-next') + await t.release('b') + await screen.findByText('B page') + await t.settle() + + t.nextFrom.length = 0 + await t.router.navigate({ to: '/a', search: { x: 'two' } }) + await screen.findByText('A page') + await t.settle() + // The remounted links never derive from the previous visit's location. + expect(t.nextFrom).not.toContain('one') + expect(t.href('a-next')).toBe('/a?x=two-next') + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(false) + + // B is cached now: depart to a route that has not loaded yet. + t.gates.items = deferred() + const updater = t.counts.aUpdater + await t.start({ to: '/items/$id', params: { id: '1' } }) + expect(t.router.state.status).toBe('pending') + expect(t.counts.aUpdater).toBe(updater) + t.controls.setExtra!(true) + // The new link reads the pending location, never the previous visit's, + // while the mounted links keep this visit's. + expect(t.href('a-extra')).toBe('/items/1') + expect(t.href('a-next')).toBe('/a?x=two-next') + expect(t.isActive('root-b')).toBe(false) + + fireEvent.click(t.link('a-next')) + await tick() + expect(t.router.latestLocation.href).toBe('/a?x=two-next') + t.gates.items.resolve() + await t.settle() + expect(t.router.state.location.href).toBe('/a?x=two-next') + expect(t.href('a-next')).toBe('/a?x=two-next-next') + }) + + test('a document redirect from the destination does not break later navigations', async () => { + // jsdom reports the attempted document navigation as not implemented. + vi.spyOn(console, 'error').mockImplementation(() => {}) + const t = setup({ + bAfterGate: () => { + throw redirect({ to: '/c', reloadDocument: true }) + }, + }) + await screen.findByText('A page') + t.gates.b = deferred() + await t.start({ to: '/b' }) + await t.release('b') + await tick() + + await t.router.navigate({ to: '/a', search: { x: 'two' } }) + await t.settle() + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(false) + }) + + test('a departure superseded by a history traversal back to the owner updates its links', async () => { + const t = setup({ initial: '/a?x=one' }) + await screen.findByText('A page') + await t.router.navigate({ to: '/a', search: { x: 'two' } }) + await t.settle() + expect(t.href('a-self')).toBe('/a?x=two') + + t.gates.b = deferred() + const updater = t.counts.aUpdater + await t.start({ to: '/b' }) + expect(t.counts.aUpdater).toBe(updater) + t.router.history.go(-2) + await tick() + await t.settle() + expect(t.router.state.location.href).toBe('/a?x=one') + expect(t.href('a-self')).toBe('/a?x=one') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(false) + t.gates.b.resolve() + await tick() + expect(screen.getByText('A page')).toBeInTheDocument() + expect(t.href('a-self')).toBe('/a?x=one') + }) + + test('invalidating a pending departure keeps holding until it commits', async () => { + const t = setup() + await screen.findByText('A page') + t.gates.b = deferred() + const updater = t.counts.aUpdater + const renders = t.counts.aRenders + await t.start({ to: '/b' }) + void t.router.invalidate() + await tick() + expect(t.router.state.status).toBe('pending') + expect(t.router.state.location.pathname).toBe('/b') + expect(t.counts.aUpdater).toBe(updater) + expect(t.counts.aRenders).toBe(renders) + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(true) + await t.release('b') + await screen.findByText('B page') + expect(t.counts.aUpdater).toBe(updater) + }) + + test('a departure redirected or superseded to another departing location does no work', async () => { + const t = setup({ + bAfterGate: () => { + throw redirect({ to: '/c' }) + }, + }) + await screen.findByText('A page') + const updater = t.counts.aUpdater + const renders = t.counts.aRenders + t.gates.b = deferred() + await t.start({ to: '/b' }) + t.gates.items = deferred() + await t.start({ to: '/items/$id', params: { id: '1' } }) + // B redirects to C after being superseded; neither keeps A. + await t.release('b') + expect(t.counts.aUpdater).toBe(updater) + expect(t.counts.aRenders).toBe(renders) + await t.release('items') + await screen.findByText('Items page') + expect(t.router.state.location.pathname).toBe('/items/1') + + await t.router.navigate({ to: '/a' }) + await screen.findByText('A page') + const again = t.counts.aUpdater + t.gates.b = deferred() + await t.start({ to: '/b' }) + await t.release('b') + await screen.findByText('C page') + expect(t.counts.aUpdater).toBe(again) + }) + + test('a view transition callback that throws does not break later navigations', async () => { + vi.stubGlobal('CSS', { supports: () => true }) + ;(document as any).startViewTransition = (update: () => unknown) => { + update() + return { + updateCallbackDone: Promise.resolve(), + finished: Promise.resolve(), + } + } + const failures: Array = [] + const t = setup({ + // The history listener's load rejects with the callback's error. Record + // it instead of leaving it unhandled. + beforeRender: (router) => { + const load = router.load + router.load = (opts: any) => + load(opts).catch((error: unknown) => failures.push(error)) + }, + }) + await screen.findByText('A page') + await t.start({ + to: '/b', + viewTransition: { + types: () => { + throw new Error('types failed') + }, + }, + }) + await tick() + expect(failures.length).toBeGreaterThan(0) + delete (document as any).startViewTransition + vi.unstubAllGlobals() + + // A navigation that keeps the page updates its links. + await t.router.navigate({ to: '/a', search: { x: 'two' } }) + await t.settle() + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(false) + }) + + test('navigations published inside a Solid batch leave staying links on the latest location', async () => { + const t = setup({ initial: '/items/1' }) + await screen.findByText('Items page') + t.gates.items = deferred() + Solid.batch(() => { + void t.router.navigate({ to: '/items/$id', params: { id: '2' } }) + void t.router.navigate({ to: '/a', search: { x: 'one' } }) + }) + await t.settle() + await screen.findByText('A page') + expect(t.router.state.location.href).toBe('/a?x=one') + expect(t.href('a-self')).toBe('/a?x=one') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('root-b')).toBe(false) + + t.gates.b = deferred() + Solid.batch(() => { + void t.router.navigate({ to: '/b' }) + void t.router.navigate({ to: '/a', search: { x: 'two' } }) + }) + await tick() + t.gates.b.resolve() + await t.settle() + expect(t.router.state.location.href).toBe('/a?x=two') + expect(t.href('a-self')).toBe('/a?x=two') + expect(t.isActive('a-self')).toBe(true) + expect(t.isActive('layout-b')).toBe(false) + }) + + test('links outside every match follow a pending navigation', async () => { + const t = setup() + await screen.findByText('A page') + cleanup() + const router = t.router + const InnerWrap = (props: { children: Solid.JSX.Element }) => ( + <> + + wrap b + + {props.children} + + ) + router.update({ ...router.options, InnerWrap }) + render(() => ) + await screen.findByText('A page') + expect(t.isActive('wrap-b')).toBe(false) + t.gates.b = deferred() + await t.start({ to: '/b' }) + expect(router.state.status).toBe('pending') + expect(t.isActive('wrap-b')).toBe(true) + await t.release('b') + await screen.findByText('B page') + expect(t.isActive('wrap-b')).toBe(true) + }) +}) + +describe('pending and failing destinations', () => { + function setupPending(options: { throwFromP?: boolean } = {}) { + const gate: { p?: Deferred } = {} + const counts = { aUpdater: 0 } + const root = createRootRoute({ + component: () => ( + <> + + root p + + + + ), + errorComponent: () => ( + + error a + + ), + }) + const a = createRoute({ + getParentRoute: () => root, + path: '/a', + component: () => ( + <> +

    A page

    + { + counts.aUpdater++ + return { x: `${prev.x}-next` } + }} + data-testid="a-next" + > + a next + + + ), + }) + const pRoute = createRoute({ + getParentRoute: () => root, + path: '/p', + validateSearch: (search: Record) => + search as { y?: string }, + loader: async () => { + await gate.p?.promise + if (options.throwFromP) { + throw new Error('p failed') + } + }, + pendingComponent: () => ( + ({ y: `${prev.y}-pending` })} + data-testid="p-pending" + > + p pending + + ), + component: () =>

    P page

    , + }) + const router = createRouter({ + routeTree: root.addChildren([a, pRoute]), + history: createMemoryHistory({ initialEntries: ['/a?x=one'] }), + defaultPendingMs: 0, + defaultPendingMinMs: 0, + }) + render(() => ) + return { router, gate, counts } + } + + test('links in a pending component build from the destination and a return remounts fresh links', async () => { + const t = setupPending() + await screen.findByText('A page') + const updater = t.counts.aUpdater + t.gate.p = deferred() + void t.router.navigate({ to: '/p', search: { y: 'one' } }) + const pending = await screen.findByTestId('p-pending') + expect(t.counts.aUpdater).toBe(updater) + expect(pending).toHaveAttribute('href', '/p?y=one-pending') + expect(screen.getByTestId('root-p')).toHaveAttribute('aria-current', 'page') + + void t.router.navigate({ to: '/a', search: { x: 'two' } }) + await screen.findByText('A page') + await waitFor(() => expect(t.router.state.status).toBe('idle')) + expect(screen.getByTestId('a-next')).toHaveAttribute( + 'href', + '/a?x=two-next', + ) + expect(screen.getByTestId('root-p')).not.toHaveAttribute('aria-current') + t.gate.p.resolve() + await tick() + expect(screen.getByText('A page')).toBeInTheDocument() + }) + + test('a departure that ends in an error leaves live links', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const t = setupPending({ throwFromP: true }) + await screen.findByText('A page') + const updater = t.counts.aUpdater + t.gate.p = deferred() + void t.router.navigate({ to: '/p' }) + await tick() + expect(t.counts.aUpdater).toBe(updater) + t.gate.p.resolve() + const errorLink = await screen.findByTestId('error-a') + await waitFor(() => expect(t.router.state.status).toBe('idle')) + expect(t.router.state.location.pathname).toBe('/p') + expect(errorLink).toHaveAttribute('href', '/a') + expect(errorLink).not.toHaveAttribute('aria-current') + }) +}) + +describe('links in a page kept on screen by a suspended transition', () => { + // The root suspends on the destination's match inside the commit's Solid + // transition, which keeps the departing page on screen until it resolves. + function setupTransition() { + const gate = deferred() + const counts = { updater: 0 } + const root = createRootRoute({ + component: () => { + const viewing = useMatch({ + from: '/view', + shouldThrow: false, + select: (match) => !!match, + }) + const [label] = Solid.createResource( + () => (viewing() ? 'viewing' : 'other'), + (key) => (key === 'viewing' ? gate.promise.then(() => key) : key), + ) + return ( + <> + root {label()} + + root view + + + + ) + }, + }) + const a = createRoute({ + getParentRoute: () => root, + path: '/a', + component: () => ( + <> +

    A page

    + { + counts.updater++ + return { x: `${prev.x}-next` } + }} + data-testid="a-next" + > + a next + + + ), + }) + const view = createRoute({ + getParentRoute: () => root, + path: '/view', + component: () =>

    View page

    , + }) + const router = createRouter({ + routeTree: root.addChildren([a, view]), + history: createMemoryHistory({ initialEntries: ['/a?x=one'] }), + }) + render(() => ) + const link = (id: string) => screen.getByTestId(id) + return { router, gate, counts, link } + } + + async function departToView(t: ReturnType) { + await screen.findByText('A page') + expect(t.link('a-next')).toHaveAttribute('href', '/a?x=one-next') + const updater = t.counts.updater + void t.router.navigate({ to: '/view' }) + await tick() + await tick() + expect(t.router.state.location.pathname).toBe('/view') + expect(screen.getByText('A page')).toBeInTheDocument() + expect(screen.queryByText('View page')).toBeNull() + expect(t.counts.updater).toBe(updater) + expect(t.link('a-next')).toHaveAttribute('href', '/a?x=one-next') + } + + test('held links update when the navigation returns to their page', async () => { + const t = setupTransition() + await departToView(t) + + void t.router.navigate({ to: '/a', search: { x: 'two' } }) + await waitFor(() => expect(t.router.state.status).toBe('idle')) + await waitFor(() => + expect(t.link('a-next')).toHaveAttribute('href', '/a?x=two-next'), + ) + expect(t.link('root-view')).not.toHaveAttribute('aria-current') + t.gate.resolve() + await tick() + expect(screen.getByText('A page')).toBeInTheDocument() + expect(t.link('a-next')).toHaveAttribute('href', '/a?x=two-next') + }) + + test('a held link navigates to the href it displays', async () => { + const t = setupTransition() + await departToView(t) + + fireEvent.click(t.link('a-next')) + await waitFor(() => expect(t.router.state.status).toBe('idle')) + expect(t.router.state.location.href).toBe('/a?x=one-next') + await waitFor(() => + expect(t.link('a-next')).toHaveAttribute('href', '/a?x=one-next-next'), + ) + t.gate.resolve() + await tick() + expect(screen.getByText('A page')).toBeInTheDocument() + }) +}) + +describe('masked links in a departing match', () => { + test.each(['mask', 'routeMasks'] as const)( + 'clicking a held link with a location-dependent %s pushes the masked href it displays', + async (kind) => { + const root = createRootRoute() + const gate: { b?: Deferred } = {} + const a = createRoute({ + getParentRoute: () => root, + path: '/a', + component: () => ( + ({ id: prev.x })} + hash + mask={ + kind === 'mask' + ? ({ to: '.', search: true, hash: true } as any) + : undefined + } + data-testid="masked" + > + masked + + ), + }) + const b = createRoute({ + getParentRoute: () => root, + path: '/b', + loader: () => gate.b?.promise, + component: () =>

    B page

    , + }) + const photo = createRoute({ + getParentRoute: () => root, + path: '/photo', + component: () =>

    Photo page

    , + }) + const routeTree = root.addChildren([a, b, photo]) + const router = createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/a?x=one#h'] }), + routeMasks: + kind === 'routeMasks' + ? [ + createRouteMask({ + routeTree, + from: '/photo', + to: '/a', + search: true, + hash: true, + } as any), + ] + : undefined, + }) + render(() => ) + const link = await screen.findByTestId('masked') + expect(link).toHaveAttribute('href', '/a?x=one#h') + + gate.b = deferred() + void router.navigate({ to: '/b' }) + await tick() + expect(router.state.status).toBe('pending') + expect(link).toHaveAttribute('href', '/a?x=one#h') + + fireEvent.click(link) + await tick() + // The URL bar shows the masked href the link displayed. + expect(router.history.location.href).toBe('/a?x=one#h') + expect(router.latestLocation.pathname).toBe('/photo') + expect(router.latestLocation.search).toEqual({ id: 'one' }) + gate.b.resolve() + await screen.findByText('Photo page') + expect(router.history.location.href).toBe('/a?x=one#h') + }, + ) +}) + +describe('link location retention', () => { + setFlagsFromString('--expose-gc') + const gc: () => void = runInNewContext('gc') + async function collect() { + for (let round = 0; round < 3; round++) { + await tick() + gc() + } + } + const alive = (refs: Array>) => + refs.flatMap((ref, index) => (ref.deref() ? [index] : [])) + + // Builds and renders a router whose route `/a` and root render Links, and + // returns a function that visits a location with a large history state. + function renderApp() { + const root = createRootRoute({ + component: () => ( + <> + + root b + + + + ), + }) + const a = createRoute({ + getParentRoute: () => root, + path: '/a', + component: () => ( + <> +

    A page

    + prev} data-testid="a-self"> + a self + + + ), + }) + const b = createRoute({ + getParentRoute: () => root, + path: '/b', + component: () =>

    B page

    , + }) + const router = createRouter({ + routeTree: root.addChildren([a, b]), + history: createMemoryHistory({ initialEntries: ['/a'] }), + }) + render(() => ) + return async (to: string, index: number) => { + await router.navigate({ + to, + search: { i: index }, + state: { payload: new Array(100_000).fill(index) } as any, + replace: true, + } as any) + await waitFor(() => expect(router.state.status).toBe('idle')) + const location: any = router.state.location + return [new WeakRef(location), new WeakRef(location.state.payload)] + } + } + + test( + 'locations with large history state are collectable after their route is left', + { timeout: 20_000 }, + async () => { + const visit = renderApp() + await screen.findByText('A page') + // The router may keep its first navigation's state (also on main). + await visit('/a', 0) + const left: Array> = [] + for (let index = 1; index < 5; index++) { + left.push(...(await visit('/a', index))) + } + for (let index = 5; index < 9; index++) { + left.push(...(await visit('/b', index))) + } + await visit('/b', 9) + await screen.findByText('B page') + await collect() + // Only the current location (and its payload) stays reachable. + expect(alive(left)).toEqual([]) + }, + ) +}) + +describe('links after a same-href navigation that changes history state', () => { + function renderStateApp() { + // The `tag` state of every `/b` load, preloads included. + const bLoads: Array = [] + const root = createRootRoute({ component: () => }) + const a = createRoute({ + getParentRoute: () => root, + path: '/a', + component: () => ( + <> +

    A page

    + + inherit + + ({ tag: `${prev.tag}-updated` }) as any} + data-testid="updater" + > + updater + + + ), + }) + const b = createRoute({ + getParentRoute: () => root, + path: '/b', + loader: ({ location }) => { + bLoads.push((location.state as any).tag) + }, + component: () =>

    B page

    , + }) + const router = createRouter({ + routeTree: root.addChildren([a, b]), + history: createMemoryHistory({ initialEntries: ['/a'] }), + }) + render(() => ) + return { router, bLoads } + } + + async function changeState(router: any) { + await screen.findByText('A page') + await router.navigate({ + to: '/a', + state: { tag: 'latest' } as any, + replace: true, + }) + expect(router.state.location.href).toBe('/a') + expect(router.state.location.state.tag).toBe('latest') + } + + test.each([ + ['inherit', 'latest'], + ['updater', 'latest-updated'], + ])( + 'clicking link %s derives its state from the latest location', + async (id, tag) => { + const { router } = renderStateApp() + await changeState(router) + + fireEvent.click(screen.getByTestId(id)) + await screen.findByText('B page') + expect(router.state.location.pathname).toBe('/b') + expect((router.state.location.state as any).tag).toBe(tag) + }, + ) + + test('preloading derives its state from the latest location', async () => { + const { router, bLoads } = renderStateApp() + await changeState(router) + + fireEvent.mouseEnter(screen.getByTestId('inherit')) + await waitFor(() => expect(bLoads).toEqual(['latest'])) + }) +}) diff --git a/packages/solid-router/tests/link-destination.test.tsx b/packages/solid-router/tests/link-destination.test.tsx new file mode 100644 index 0000000000..bfddf1da25 --- /dev/null +++ b/packages/solid-router/tests/link-destination.test.tsx @@ -0,0 +1,396 @@ +import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library' +import { afterEach, expect, test, vi } from 'vitest' +import { createSignal } from 'solid-js' +import { createStore } from 'solid-js/store' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + defaultStringifySearch, + useLinkProps, +} from '../src' +import type { JSX } from 'solid-js' + +afterEach(cleanup) + +/** + * Renders `links` in the root route next to `/source/$id`, `/target/$id` and + * `/visible/$id`. `builds()` counts the destination builds that stringify a + * search carrying a `build` key, so a reused location does not count. + */ +function setup(links: () => JSX.Element, initial = '/source/one') { + const counted = vi.fn(defaultStringifySearch) + const root = createRootRoute({ + component: () => ( + <> + {links()} + + + ), + }) + const routes = ['/source/$id', '/target/$id', '/visible/$id'].map((path) => + createRoute({ getParentRoute: () => root, path }), + ) + const router = createRouter({ + routeTree: root.addChildren(routes), + history: createMemoryHistory({ initialEntries: [initial] }), + stringifySearch: (search) => + 'build' in search ? counted(search) : defaultStringifySearch(search), + }) + render(() => ) + const go = (id: string, extra?: object) => + router.navigate({ to: '/source/$id', params: { id }, ...extra } as any) + return { router, go, builds: () => counted.mock.calls.length } +} + +test('reuses a fixed destination across navigations', async () => { + const { go, builds } = setup(() => ( + + )) + const link = await screen.findByTestId('link') + expect(link).toHaveAttribute('href', '/target/fixed?build=1#details') + const initial = builds() + + await go('two') + await go('three', { hash: 'x' }) + expect(link).toHaveAttribute('href', '/target/fixed?build=1#details') + expect(builds()).toBe(initial) + + fireEvent.click(link) + await screen.findByTestId('link') + await vi.waitFor(() => expect(link).toHaveAttribute('data-status', 'active')) + expect(link).toHaveAttribute('href', '/target/fixed?build=1#details') +}) + +test('rebuilds on a destination prop change, not a presentation prop change', async () => { + const [id, setId] = createSignal('one') + const [search, setSearch] = createSignal>({ + build: 1, + }) + const [hash, setHash] = createSignal('first') + const [to, setTo] = createSignal('/target/$id') + const [cls, setCls] = createSignal('a') + const { go, builds } = setup(() => ( + + )) + const link = await screen.findByTestId('link') + expect(link).toHaveAttribute('href', '/target/one?build=1#first') + + setId('two') + expect(link).toHaveAttribute('href', '/target/two?build=1#first') + setSearch({ build: 2 }) + expect(link).toHaveAttribute('href', '/target/two?build=2#first') + setHash('second') + expect(link).toHaveAttribute('href', '/target/two?build=2#second') + setTo('/visible/$id') + expect(link).toHaveAttribute('href', '/visible/two?build=2#second') + + const settled = builds() + setCls('b') + expect(link).toHaveClass('b') + await go('three') + expect(builds()).toBe(settled) + expect(link).toHaveAttribute('href', '/visible/two?build=2#second') +}) + +test('store-backed params and search follow in-place mutations at the next navigation', async () => { + const [params, setParams] = createStore({ id: 'one' }) + const [search, setSearch] = createStore({ build: 1 }) + const { go } = setup(() => ( + + )) + const link = await screen.findByTestId('link') + expect(link).toHaveAttribute('href', '/target/one?build=1') + + setParams('id', 'two') + setSearch('build', 2) + // As before: a store read during a build is not tracked. + expect(link).toHaveAttribute('href', '/target/one?build=1') + await go('two') + expect(link).toHaveAttribute('href', '/target/two?build=2') + + setParams('id', 'three') + await go('three') + expect(link).toHaveAttribute('href', '/target/three?build=2') + + // Clicks and preloads read the store as it is now. + setParams('id', 'four') + fireEvent.click(link) + await vi.waitFor(() => + expect(screen.getByTestId('link')).toHaveAttribute('data-status', 'active'), + ) + expect(link).toHaveAttribute('href', '/target/four?build=2') +}) + +test('does not re-read a store nested inside a plain object', async () => { + // Only the prop value itself is checked for a store (one level). A store + // nested inside a plain object is like any other object mutated in place: + // pass a new object, or the store itself, to change the destination. + const [filters, setFilters] = createStore({ page: 1 }) + const { go } = setup(() => ( + + )) + const link = await screen.findByTestId('link') + const href = link.getAttribute('href') + setFilters('page', 2) + await go('two') + expect(link).toHaveAttribute('href', href!) +}) + +test('state store values are not reused either', async () => { + const [state, setState] = createStore({ label: 'one' }) + const seen: Array = [] + const { router } = setup(() => ( + + )) + const link = await screen.findByTestId('link') + router.subscribe('onResolved', ({ toLocation }) => { + seen.push((toLocation.state as any).label) + }) + setState('label', 'two') + fireEvent.click(link) + await vi.waitFor(() => expect(seen).toEqual(['two'])) +}) + +test('inherited params and search rebuild on every navigation', async () => { + const { go } = setup(() => ( + + )) + const link = await screen.findByTestId('link') + expect(link).toHaveAttribute('href', '/target/one') + await go('two', { search: { page: 2 } }) + expect(link).toHaveAttribute('href', '/target/two?page=2') + await go('three', { search: { page: 3 } }) + expect(link).toHaveAttribute('href', '/target/three?page=3') +}) + +test('masked destinations follow their inputs', async () => { + const [params, setParams] = createStore({ id: 'one' }) + const [hash, setHash] = createSignal('a') + const { go } = setup(() => ( + <> + + + + )) + const storeMask = await screen.findByTestId('store-mask') + const inheritedMask = screen.getByTestId('inherited-mask') + expect(storeMask).toHaveAttribute('href', '/visible/one') + expect(inheritedMask).toHaveAttribute('href', '/visible/one#a') + setParams('id', 'two') + await go('two') + expect(storeMask).toHaveAttribute('href', '/visible/two') + expect(inheritedMask).toHaveAttribute('href', '/visible/two#a') + setHash('b') + expect(inheritedMask).toHaveAttribute('href', '/visible/two#b') +}) + +test('switches a mounted Link between plain and store-backed inputs', async () => { + const [live, setLive] = createSignal(false) + const [params, setParams] = createStore({ id: 'one' }) + const [search, setSearch] = createStore({ build: 1 }) + const plainParams = { id: 'fixed' } + const plainSearch = { build: 0 } + const { go, builds } = setup(() => ( + + )) + const link = await screen.findByTestId('link') + expect(link).toHaveAttribute('href', '/target/fixed?build=0') + + setLive(true) + expect(link).toHaveAttribute('href', '/target/one?build=1') + setParams('id', 'two') + setSearch('build', 2) + await go('two') + expect(link).toHaveAttribute('href', '/target/two?build=2') + + setLive(false) + expect(link).toHaveAttribute('href', '/target/fixed?build=0') + const plain = builds() + await go('three') + expect(builds()).toBe(plain) + + setLive(true) + setParams('id', 'three') + await go('four') + expect(link).toHaveAttribute('href', '/target/three?build=2') +}) + +test('never mutates frozen caller options', async () => { + const params = Object.freeze({ id: 'fixed' }) + const options = Object.freeze({ + to: '/target/$id', + params, + search: Object.freeze({ build: 1 }), + 'data-testid': 'frozen', + }) + const Links = () => { + const frozen = useLinkProps(options as any) + return + } + const result = setup(() => ) + const frozen = await screen.findByTestId('frozen') + expect(frozen).toHaveAttribute('href', '/target/fixed?build=1') + await result.go('two') + expect(frozen).toHaveAttribute('href', '/target/fixed?build=1') + expect(Object.keys(options)).toEqual([ + 'to', + 'params', + 'search', + 'data-testid', + ]) + expect(Object.keys(params)).toEqual(['id']) + + fireEvent.click(frozen) + await vi.waitFor(() => + expect(result.router.state.location.pathname).toBe('/target/fixed'), + ) +}) + +test.each([ + ['inherited state', true], + ['a state updater', (prev: any) => ({ label: `${prev.label}!` })], +])( + 'a click after a same-href, state-only navigation uses the new state (%s)', + async (_, state) => { + const { router, go } = setup(() => ( + + )) + const link = await screen.findByTestId('link') + await go('one', { state: { label: 'next' } }) + expect(router.state.location.state).toMatchObject({ label: 'next' }) + fireEvent.click(link) + await vi.waitFor(() => + expect(router.state.location.pathname).toBe('/target/fixed'), + ) + expect(router.state.location.state).toMatchObject({ + label: state === true ? 'next' : 'next!', + }) + }, +) + +test('function children render once per active state change', async () => { + const calls: Array = [] + const { go } = setup(() => ( + + {({ isActive }) => { + calls.push(isActive) + return isActive ? 'active' : 'inactive' + }} + + )) + const link = await screen.findByTestId('link') + expect(link).toHaveTextContent('inactive') + await go('two') + await go('three') + expect(calls).toEqual([false]) + fireEvent.click(link) + await vi.waitFor(() => expect(link).toHaveTextContent(/^active$/)) + expect(calls).toEqual([false, true]) +}) + +test('calls a user ref once per element across state changes', async () => { + const refs: Array = [] + const [id, setId] = createSignal('one') + const { go } = setup(() => ( + refs.push(el)} + data-testid="link" + /> + )) + const link = await screen.findByTestId('link') + setId('two') + expect(link).toHaveAttribute('href', '/target/two') + await go('two') + fireEvent.click(link) + await vi.waitFor(() => expect(link).toHaveAttribute('data-status', 'active')) + expect(refs).toEqual([link]) +}) + +test('refreshes history formatting even when the destination is reused', async () => { + let suffix = 'old' + const root = createRootRoute({ + component: () => ( + <> + + + + ), + }) + const source = createRoute({ + getParentRoute: () => root, + path: '/source/$id', + }) + const target = createRoute({ getParentRoute: () => root, path: '/target' }) + const history = createMemoryHistory({ initialEntries: ['/source/one'] }) + const router = createRouter({ + routeTree: root.addChildren([source, target]), + history: { + ...history, + get location() { + return history.location + }, + createHref: (href) => `${href}#${suffix}`, + }, + }) + render(() => ) + const link = await screen.findByTestId('formatted') + expect(link).toHaveAttribute('href', '/target#old') + suffix = 'new' + await router.navigate({ to: '/source/$id', params: { id: 'two' } }) + expect(link).toHaveAttribute('href', '/target#new') +}) diff --git a/packages/solid-router/tests/link-element-props.test.tsx b/packages/solid-router/tests/link-element-props.test.tsx new file mode 100644 index 0000000000..7b3364ead4 --- /dev/null +++ b/packages/solid-router/tests/link-element-props.test.tsx @@ -0,0 +1,442 @@ +import * as Solid from 'solid-js' +import { afterEach, expect, test, vi } from 'vitest' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@solidjs/testing-library' +import { + Link, + Outlet, + RouterProvider, + createLink, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' +import type { RegisteredRouter } from '../src' + +const disposers: Array<() => void> = [] +afterEach(() => { + cleanup() + for (const dispose of disposers.splice(0)) { + dispose() + } +}) + +function renderLinks( + Links: Solid.Component, + options: { preload?: 'intent'; preloadDelay?: number } = {}, +) { + const history = createMemoryHistory({ initialEntries: ['/'] }) + disposers.push(history.destroy) + const root = createRootRoute({ + component: () => ( + <> + + + + ), + }) + const router = createRouter({ + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: '/' }), + createRoute({ getParentRoute: () => root, path: '/target' }), + createRoute({ getParentRoute: () => root, path: '/other' }), + ]), + history, + scrollRestoration: false, + defaultPreload: options.preload ?? false, + defaultPreloadDelay: options.preloadDelay ?? 0, + }) + render(() => ) + return router as unknown as RegisteredRouter +} + +test('static and reactive element props reach the anchor', async () => { + const [title, setTitle] = Solid.createSignal('first') + const [label, setLabel] = Solid.createSignal('Go to target') + const onKeyDown = vi.fn() + renderLinks(() => ( + <> + + Static + + + Reactive + + + )) + + const staticLink = await screen.findByTestId('static') + expect(staticLink.tagName).toBe('A') + expect(staticLink).toHaveAttribute('href', '/target') + expect(staticLink).toHaveAttribute('data-flag') + expect(staticLink).toHaveAttribute('aria-label', 'Static target') + expect(staticLink).toHaveAttribute('id', 'static-link') + expect(staticLink).toHaveAttribute('rel', 'noopener') + expect(staticLink).toHaveAttribute('target', '_blank') + expect(staticLink).toHaveAttribute('tabindex', '3') + fireEvent.keyDown(staticLink, { key: 'Enter' }) + expect(onKeyDown).toHaveBeenCalledOnce() + + const reactiveLink = screen.getByTestId('reactive') + expect(reactiveLink).toHaveAttribute('title', 'first') + expect(reactiveLink).toHaveAttribute('aria-label', 'Go to target') + setTitle('second') + setLabel('Target') + await waitFor(() => { + expect(reactiveLink).toHaveAttribute('title', 'second') + expect(reactiveLink).toHaveAttribute('aria-label', 'Target') + }) + setTitle(undefined) + await waitFor(() => expect(reactiveLink).not.toHaveAttribute('title')) + expect(reactiveLink).toHaveAttribute('href', '/target') +}) + +test('element props spread into a Link apply, also when their keys change', async () => { + const [extra, setExtra] = Solid.createSignal>({ + 'data-a': 'a', + }) + renderLinks(() => ( + + Spread + + )) + const link = await screen.findByTestId('spread') + expect(link).toHaveAttribute('data-a', 'a') + setExtra({ 'data-b': 'b' }) + await waitFor(() => { + expect(link).not.toHaveAttribute('data-a') + expect(link).toHaveAttribute('data-b', 'b') + }) + expect(link).toHaveAttribute('href', '/target') +}) + +test('element state attributes apply where the Link leaves them unset', async () => { + const router = renderLinks(() => ( + + {(state) => (state.isActive ? 'Active' : 'Inactive')} + + )) + const link = await screen.findByTestId('attributes') + expect(link).toHaveAttribute('aria-current', 'step') + expect(link).toHaveAttribute('data-status', 'custom') + expect(link).toHaveAttribute('role', 'button') + expect(link).toHaveTextContent('Inactive') + + await router.navigate({ to: '/target' }) + await waitFor(() => { + expect(link).toHaveAttribute('aria-current', 'page') + expect(link).toHaveAttribute('data-status', 'active') + expect(link).toHaveTextContent('Active') + }) + expect(link).toHaveAttribute('role', 'button') + + await router.navigate({ to: '/' }) + await waitFor(() => { + expect(link).toHaveAttribute('aria-current', 'step') + expect(link).toHaveAttribute('data-status', 'custom') + expect(link).toHaveTextContent('Inactive') + }) +}) + +test('state props add and remove arbitrary props, over element props of the same name', async () => { + const router = renderLinks(() => ( + + State + + )) + const link = await screen.findByTestId('state') + expect(link).toHaveClass('off') + expect(link).toHaveAttribute('data-inactive', '') + expect(link).toHaveAttribute('title', 'base') + expect(link).not.toHaveAttribute('data-active') + expect(link).not.toHaveAttribute('aria-current') + + await router.navigate({ to: '/target' }) + await waitFor(() => { + expect(link).toHaveClass('on') + expect(link).not.toHaveClass('off') + expect(link.style.color).toBe('red') + expect(link).toHaveAttribute('title', 'active title') + expect(link).toHaveAttribute('data-active', 'yes') + expect(link).toHaveAttribute('aria-label', 'Current target') + expect(link).toHaveAttribute('aria-current', 'page') + expect(link).not.toHaveAttribute('data-inactive') + }) + + await router.navigate({ to: '/' }) + await waitFor(() => { + expect(link).toHaveClass('off') + expect(link).not.toHaveClass('on') + expect(link.style.color).toBe('') + expect(link).toHaveAttribute('title', 'base') + expect(link).not.toHaveAttribute('data-active') + expect(link).not.toHaveAttribute('aria-label') + expect(link).not.toHaveAttribute('aria-current') + expect(link).toHaveAttribute('data-inactive', '') + }) +}) + +test('user handlers run before the Link and can prevent its navigation', async () => { + const calls: Array = [] + const [prevent, setPrevent] = Solid.createSignal(true) + const router = renderLinks(() => ( + { + calls.push(`click:${router.state.location.pathname}`) + if (prevent()) { + event.preventDefault() + } + }} + > + Target + + )) + const link = await screen.findByRole('link', { name: 'Target' }) + fireEvent.click(link) + expect(calls).toEqual(['click:/']) + await Promise.resolve() + expect(router.state.location.pathname).toBe('/') + + setPrevent(false) + fireEvent.click(link) + expect(calls).toEqual(['click:/', 'click:/']) + await waitFor(() => expect(router.state.location.pathname).toBe('/target')) +}) + +test('intent preloading follows the user handlers of each event', async () => { + const onMouseEnter = vi.fn() + const onFocus = vi.fn() + const onTouchStart = vi.fn() + // `mouseover` is cancelable: preventing it skips the Link's preload. + const onMouseOver = vi.fn((event: MouseEvent) => event.preventDefault()) + const router = renderLinks( + () => ( + + Target + + ), + { preload: 'intent' }, + ) + const preloadRoute = vi.spyOn(router, 'preloadRoute') + const link = await screen.findByRole('link', { name: 'Target' }) + + fireEvent.mouseOver(link) + expect(onMouseOver).toHaveBeenCalledOnce() + expect(preloadRoute).not.toHaveBeenCalled() + + fireEvent.mouseEnter(link) + expect(onMouseEnter).toHaveBeenCalledOnce() + expect(preloadRoute).toHaveBeenCalledOnce() + expect(preloadRoute.mock.calls[0]?.[0]).toMatchObject({ to: '/target' }) + + fireEvent.focus(link) + expect(onFocus).toHaveBeenCalledOnce() + expect(preloadRoute).toHaveBeenCalledTimes(2) + + fireEvent.touchStart(link) + expect(onTouchStart).toHaveBeenCalledOnce() + expect(preloadRoute).toHaveBeenCalledTimes(3) +}) + +test('leaving a Link cancels a delayed intent preload after the user handlers', async () => { + vi.useFakeTimers() + try { + const onMouseLeave = vi.fn() + const onBlur = vi.fn() + const router = renderLinks( + () => ( + + Target + + ), + { preload: 'intent', preloadDelay: 50 }, + ) + const preloadRoute = vi.spyOn(router, 'preloadRoute') + await vi.runAllTimersAsync() + const link = screen.getByRole('link', { name: 'Target' }) + + fireEvent.mouseEnter(link) + fireEvent.mouseLeave(link) + expect(onMouseLeave).toHaveBeenCalledOnce() + fireEvent.focus(link) + fireEvent.blur(link) + expect(onBlur).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(100) + expect(preloadRoute).not.toHaveBeenCalled() + + fireEvent.mouseEnter(link) + await vi.advanceTimersByTimeAsync(100) + expect(preloadRoute).toHaveBeenCalledOnce() + } finally { + vi.useRealTimers() + } +}) + +test('a user ref receives the anchor once', async () => { + const ref = vi.fn() + const router = renderLinks(() => ( + + Ref + + )) + const link = await screen.findByTestId('ref') + expect(ref).toHaveBeenCalledOnce() + expect(ref).toHaveBeenCalledWith(link) + await router.navigate({ to: '/target' }) + await waitFor(() => expect(link).toHaveAttribute('data-status', 'active')) + await router.navigate({ to: '/other' }) + await waitFor(() => expect(link).not.toHaveAttribute('data-status')) + expect(ref).toHaveBeenCalledOnce() +}) + +test('a disabled Link renders no href and does not navigate', async () => { + const onClick = vi.fn() + const [disabled, setDisabled] = Solid.createSignal(true) + const router = renderLinks(() => ( + + Disabled + + )) + const link = await screen.findByTestId('disabled') + expect(link).not.toHaveAttribute('href') + expect(link).toHaveAttribute('role', 'link') + expect(link).toHaveAttribute('aria-disabled', 'true') + expect((link as any).disabled).toBe(true) + // Solid skips delegated handlers of a disabled element, the user's too. + fireEvent.click(link) + expect(onClick).not.toHaveBeenCalled() + await Promise.resolve() + expect(router.state.location.pathname).toBe('/') + + setDisabled(false) + await waitFor(() => expect(link).toHaveAttribute('href', '/target')) + expect(link).not.toHaveAttribute('role') + expect(link).not.toHaveAttribute('aria-disabled') + expect((link as any).disabled).toBe(false) + fireEvent.click(link) + expect(onClick).toHaveBeenCalledOnce() + await waitFor(() => expect(router.state.location.pathname).toBe('/target')) +}) + +test('a custom component receives the element props, state and handlers', async () => { + const ref = vi.fn() + const onClick = vi.fn() + const CustomLink = createLink((props: Solid.ComponentProps<'a'>) => ( + + )) + const router = renderLinks(() => ( + + Custom + + )) + const link = await screen.findByRole('link', { name: 'Custom' }) + expect(link).toHaveAttribute('data-custom') + expect(link).toHaveAttribute('href', '/target') + expect(link).toHaveAttribute('title', 'custom') + expect(link).not.toHaveAttribute('data-on') + expect(ref).toHaveBeenCalledOnce() + expect(ref).toHaveBeenCalledWith(link) + fireEvent.click(link) + expect(onClick).toHaveBeenCalledOnce() + await waitFor(() => expect(router.state.location.pathname).toBe('/target')) + await waitFor(() => { + expect(link).toHaveAttribute('data-status', 'active') + expect(link).toHaveAttribute('data-on', '') + }) +}) + +test('state props added later through a spread apply their extra props', async () => { + const [extra, setExtra] = Solid.createSignal>({}) + const router = renderLinks(() => ( + + Late + + )) + const link = await screen.findByTestId('late') + await router.navigate({ to: '/target' }) + await waitFor(() => expect(link).toHaveAttribute('data-status', 'active')) + setExtra({ activeProps: { title: 'active title', 'data-active': 'yes' } }) + await waitFor(() => { + expect(link).toHaveAttribute('title', 'active title') + expect(link).toHaveAttribute('data-active', 'yes') + }) +}) + +test("the Link's handlers follow the element's own listeners", async () => { + const log: Array = [] + const onclick = vi.fn() + const router = renderLinks(() => ( + log.push('link')} + on:focus={() => log.push('element')} + onclick={onclick} + > + Target + + )) + const link = await screen.findByRole('link', { name: 'Target' }) + fireEvent.focus(link) + expect(log).toEqual(['element', 'link']) + // A lowercase delegated handler is replaced by the Link's own. + fireEvent.click(link) + await waitFor(() => expect(router.state.location.pathname).toBe('/target')) + expect(onclick).not.toHaveBeenCalled() +}) diff --git a/packages/solid-router/tests/link-href-cases.ts b/packages/solid-router/tests/link-href-cases.ts new file mode 100644 index 0000000000..3e47ac9956 --- /dev/null +++ b/packages/solid-router/tests/link-href-cases.ts @@ -0,0 +1,21 @@ +// kind, final href, blocked, active +export const linkHrefCases: Array< + readonly [ + kind: 'history' | 'rewrite' | 'to', + href: string, + blocked: boolean, + active: boolean, + ] +> = [ + ['history', '//evil.example/path', true, false], + ['history', '/\\evil.example/path', true, false], + ['history', '\\/evil.example/path', true, false], + ['history', '\x01 \t//evil.example/path', true, false], + ['history', 'javascript:blocked()', true, false], + ['history', '/formatted', false, true], + ['rewrite', 'javascript:blocked()', true, false], + ['rewrite', 'https://other.example/', false, false], + ['rewrite', '/safe', false, true], + ['to', 'myapp:open', false, false], + ['to', 'mailto:person@example.com', true, false], +] diff --git a/packages/solid-router/tests/link-href-safety.test.tsx b/packages/solid-router/tests/link-href-safety.test.tsx new file mode 100644 index 0000000000..c02d626f19 --- /dev/null +++ b/packages/solid-router/tests/link-href-safety.test.tsx @@ -0,0 +1,76 @@ +import { cleanup, fireEvent, render } from '@solidjs/testing-library' +import { afterEach, expect, test, vi } from 'vitest' +import { + Link, + RouterContextProvider, + createMemoryHistory, + createRootRoute, + createRouter, +} from '../src' +import { linkHrefCases } from './link-href-cases' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +test.each(linkHrefCases)( + 'validates %s href %j and its active state', + (kind, href, blocked, active) => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const history = createMemoryHistory({ initialEntries: ['/safe'] }) + // Keep custom history output raw so Link must validate it itself. + history.createHref = vi.fn((path) => (kind === 'history' ? href : path)) + const router = createRouter({ + routeTree: createRootRoute(), + history, + isServer: false, + protocolAllowlist: ['http:', 'https:', 'myapp:'], + rewrite: + kind === 'rewrite' + ? { + output: ({ url }) => new URL(href, url), + } + : undefined, + }) + const navigate = vi.spyOn(router, 'navigate').mockResolvedValue() + const preload = vi + .spyOn(router, 'preloadRoute') + .mockResolvedValue(undefined) + // Runtime state props can contain href even though the typings exclude it. + const activeProps = { class: 'active', href: 'javascript:active()' } + const inactiveProps = { class: 'inactive', href: 'javascript:inactive()' } + const { container } = render(() => ( + + {() => ( + + {({ isActive }) => String(isActive)} + + )} + + )) + const anchor = container.querySelector('a')! + if (kind === 'history') { + expect(history.createHref).toHaveBeenCalledWith('/safe') + } + expect(anchor.getAttribute('href')).toBe(blocked ? null : href) + expect(anchor.textContent).toBe(String(active)) + expect(anchor.getAttribute('aria-current')).toBe(active ? 'page' : null) + expect(anchor.getAttribute('aria-disabled')).toBe(blocked ? 'true' : null) + expect(anchor.className.trim()).toBe(active ? 'active' : 'inactive') + if (blocked) { + expect(fireEvent.click(anchor)).toBe(true) + fireEvent.focus(anchor) + fireEvent.mouseEnter(anchor) + fireEvent.touchStart(anchor) + expect(navigate).not.toHaveBeenCalled() + expect(preload).not.toHaveBeenCalled() + } + }, +) diff --git a/packages/solid-router/tests/link-path-cases.ts b/packages/solid-router/tests/link-path-cases.ts new file mode 100644 index 0000000000..c34f464c06 --- /dev/null +++ b/packages/solid-router/tests/link-path-cases.ts @@ -0,0 +1,9 @@ +export const linkPathCases = [ + { current: '/', to: '/', exact: true, active: true }, + { current: '/posts', to: '/posts/', exact: true, active: true }, + { current: '/posts/', to: '/posts', exact: true, active: true }, + { current: '/posts/item', to: '/posts', exact: true, active: false }, + { current: '/posts/item', to: '/posts', exact: false, active: true }, + { current: '/posts/item', to: '/posts/', exact: false, active: true }, + { current: '/posts-other', to: '/posts', exact: false, active: false }, +] diff --git a/packages/solid-router/tests/link-path-matching.test.tsx b/packages/solid-router/tests/link-path-matching.test.tsx new file mode 100644 index 0000000000..e49205ebbb --- /dev/null +++ b/packages/solid-router/tests/link-path-matching.test.tsx @@ -0,0 +1,74 @@ +import { createSignal } from 'solid-js' +import { cleanup, render } from '@solidjs/testing-library' +import { afterEach, expect, test } from 'vitest' +import { + Link, + RouterContextProvider, + createMemoryHistory, + createRootRoute, + createRouter, +} from '../src' +import { linkPathCases } from './link-path-cases' + +afterEach(cleanup) + +for (const basepath of ['', '/app']) { + test.each(linkPathCases)( + `pathname matching with basepath "${basepath}": $current -> $to, exact=$exact`, + ({ current, to, exact, active }) => { + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory({ initialEntries: [basepath + current] }), + basepath, + trailingSlash: 'preserve', + isServer: false, + }) + const { container } = render(() => ( + + {() => ( + + {({ isActive }) => String(isActive)} + + )} + + )) + const anchor = container.querySelector('a')! + expect(anchor.textContent).toBe(String(active)) + expect(anchor.getAttribute('aria-current')).toBe(active ? 'page' : null) + expect(anchor.className).toBe(active ? 'active' : 'inactive') + }, + ) +} + +test('pathname matching reacts when exact mode changes', () => { + const [exact, setExact] = createSignal(true) + const router = createRouter({ + routeTree: createRootRoute(), + history: createMemoryHistory({ initialEntries: ['/posts/item'] }), + isServer: false, + }) + const { container } = render(() => ( + + {() => ( + + {({ isActive }) => String(isActive)} + + )} + + )) + const anchor = container.querySelector('a')! + for (const mode of [true, false, true]) { + setExact(mode) + expect(anchor.textContent).toBe(String(!mode)) + expect(anchor.getAttribute('aria-current')).toBe(mode ? null : 'page') + expect(anchor.className).toBe(mode ? 'inactive' : 'active') + } +}) diff --git a/packages/solid-router/tests/link-style.test.tsx b/packages/solid-router/tests/link-style.test.tsx new file mode 100644 index 0000000000..5f7aacdbb1 --- /dev/null +++ b/packages/solid-router/tests/link-style.test.tsx @@ -0,0 +1,218 @@ +import * as Solid from 'solid-js' +import { createStore } from 'solid-js/store' +import { afterEach, expect, test, vi } from 'vitest' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@solidjs/testing-library' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +const disposers: Array<() => void> = [] +afterEach(() => { + cleanup() + for (const dispose of disposers.splice(0)) { + dispose() + } +}) + +function renderLinks(Links: Solid.Component) { + const history = createMemoryHistory({ initialEntries: ['/target'] }) + disposers.push(history.destroy) + const root = createRootRoute({ + component: () => ( + <> + + + + ), + }) + const router = createRouter({ + routeTree: root.addChildren([ + createRoute({ getParentRoute: () => root, path: '/' }), + createRoute({ getParentRoute: () => root, path: '/target' }), + ]), + history, + scrollRestoration: false, + defaultPreload: false, + }) + render(() => ) + return router +} + +test.each([true, false])( + 'selected state props override element props but not routing options (active: %s)', + async (active) => { + const baseClick = vi.fn() + const selectedClick = vi.fn((event: MouseEvent) => event.preventDefault()) + const unusedClick = vi.fn() + const selectedRef = vi.fn() + const stateProps = { + ref: selectedRef, + title: 'state title', + onClick: selectedClick, + class: 'state-class', + style: { color: 'blue' }, + href: '/state-href', + target: '_self', + disabled: true, + } + renderLinks(() => ( + + Override + + )) + const link = await screen.findByRole('link', { name: 'Override' }) + expect(selectedRef).toHaveBeenCalledOnce() + expect(selectedRef.mock.calls[0]?.[0]).toBe(link) + expect(link).toHaveAttribute('title', 'state title') + expect(link).toHaveAttribute('href', active ? '/target' : '/') + expect(link).toHaveAttribute('target', '_blank') + expect(link).not.toHaveAttribute('disabled') + expect(link).toHaveClass('base', 'state-class') + expect(link.style).toMatchObject({ color: 'blue', marginTop: '2px' }) + fireEvent.click(link) + expect(selectedClick).toHaveBeenCalledOnce() + expect(baseClick).not.toHaveBeenCalled() + expect(unusedClick).not.toHaveBeenCalled() + }, +) + +test('tracks additions to an initially empty state-only style store', async () => { + const [style, setStyle] = createStore({}) + renderLinks(() => ( + ({ style })}> + Reactive + + )) + const link = await screen.findByRole('link', { name: 'Reactive' }) + expect(link.style.color).toBe('') + setStyle('color', 'red') + await waitFor(() => expect(link.style.color).toBe('red')) + setStyle('color', undefined) + await waitFor(() => expect(link.style.color).toBe('')) +}) + +test('merges only the selected state and tracks reactive style properties', async () => { + const [base, setBase] = createStore({ + color: 'red', + 'margin-top': '2px', + }) + const [stateStyle, setStateStyle] = createStore({ + 'background-color': 'white', + }) + const [stateClass, setStateClass] = Solid.createSignal('selected') + const active = vi.fn(() => ({ + class: stateClass(), + style: stateStyle, + title: 'selected', + })) + const inactive = vi.fn(() => ({ + class: 'idle', + style: { color: 'gray' }, + title: 'idle', + })) + const router = renderLinks(() => ( + + Styled + + )) + const link = await screen.findByRole('link', { name: 'Styled' }) + expect(link).toHaveClass('base', 'selected') + expect(link.style).toMatchObject({ + color: 'red', + marginTop: '2px', + backgroundColor: 'white', + }) + expect(link).toHaveAttribute('href', '/target') + expect(inactive).not.toHaveBeenCalled() + + setBase('color', 'blue') + setStateStyle('background-color', 'black') + setStateClass('updated') + await waitFor(() => { + expect(link).toHaveClass('base', 'updated') + expect(link.style).toMatchObject({ + color: 'blue', + backgroundColor: 'black', + }) + }) + + await router.navigate({ to: '/' }) + await waitFor(() => { + expect(link).toHaveClass('base', 'idle') + expect(link).toHaveAttribute('title', 'idle') + expect(link.style).toMatchObject({ color: 'gray', marginTop: '2px' }) + expect(link.style.backgroundColor).toBe('') + }) + active.mockClear() + inactive.mockClear() + setBase('margin-top', '3px') + await waitFor(() => expect(link.style).toMatchObject({ marginTop: '3px' })) + expect(active).not.toHaveBeenCalled() + expect(inactive).toHaveBeenCalled() + + await router.navigate({ to: '/target' }) + await waitFor(() => { + expect(link).toHaveClass('base', 'updated') + expect(link.style).toMatchObject({ + color: 'blue', + backgroundColor: 'black', + }) + }) +}) + +test('switches between default and custom state props without stale attributes', async () => { + const [custom, setCustom] = Solid.createSignal(false) + const router = renderLinks(() => ( + + Defaults + + )) + const link = await screen.findByRole('link', { name: 'Defaults' }) + expect(link).toHaveClass('active') + setCustom(true) + await waitFor(() => { + expect(link).not.toHaveClass('active') + expect(link).toHaveAttribute('title', 'custom') + expect(link.style).toMatchObject({ color: 'red' }) + }) + setCustom(false) + await waitFor(() => { + expect(link).toHaveClass('active') + expect(link).not.toHaveAttribute('title') + expect(link.style.color).toBe('') + }) + await router.navigate({ to: '/' }) + await waitFor(() => expect(link).not.toHaveClass('active')) +}) diff --git a/packages/solid-router/tests/link.bench.tsx b/packages/solid-router/tests/link.bench.tsx index 7d60d9ebd5..30c2585d08 100644 --- a/packages/solid-router/tests/link.bench.tsx +++ b/packages/solid-router/tests/link.bench.tsx @@ -1,5 +1,6 @@ import { render } from '@solidjs/testing-library' -import { bench, describe } from 'vitest' +import { describe, test } from 'vitest' +import { getRouteSegments } from '@tanstack/router-core' import { Link, RouterProvider, @@ -38,8 +39,16 @@ const InterpolatePathLink = ({ to, params, children, -}: Solid.PropsWithChildren) => { - const href = interpolatePath({ path: to, params }).interpolatedPath +}: Solid.PropsWithChildren<{ + to: string + params: Record +}>) => { + const router = useRouter() + const href = interpolatePath( + to, + getRouteSegments(router.routesByPath[to])!, + params, + ) return {children} } @@ -74,22 +83,21 @@ describe.each([ ])('$name', ({ numberOfRoutes, numberOfLinks, matchedParamId }) => { const renderRouter = createRouterRenderer(numberOfRoutes) - bench( - 'hardcoded href', - () => { + test('hardcoded href', async ({ bench }) => { + await bench('hardcoded href', () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( {i} )), ) render(() => ) - }, - { warmupIterations: 1 }, - ) + }).run({ + warmupIterations: 1, + }) + }) - bench( - 'interpolate path', - () => { + test('interpolate path', async ({ bench }) => { + await bench('interpolate path', () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( ) - }, - { warmupIterations: 1 }, - ) + }).run({ + warmupIterations: 1, + }) + }) - bench( - 'build location', - () => { + test('build location', async ({ bench }) => { + await bench('build location', () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( ) - }, - { warmupIterations: 1 }, - ) + }).run({ + warmupIterations: 1, + }) + }) - bench( - 'link to absolute path', - () => { + test('link to absolute path', async ({ bench }) => { + await bench('link to absolute path', () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( ) - }, - { warmupIterations: 1 }, - ) + }).run({ + warmupIterations: 1, + }) + }) - bench( - 'link to relative path', - () => { + test('link to relative path', async ({ bench }) => { + await bench('link to relative path', () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => { const to = `./params/$param${Math.min(i, matchedParamId)}` @@ -160,13 +168,13 @@ describe.each([ }), ) render(() => ) - }, - { warmupIterations: 1 }, - ) + }).run({ + warmupIterations: 1, + }) + }) - bench( - 'link to current path', - () => { + test('link to current path', async ({ bench }) => { + await bench('link to current path', () => { const router = renderRouter( Array.from({ length: numberOfLinks }).map((_, i) => ( @@ -175,7 +183,8 @@ describe.each([ )), ) render(() => ) - }, - { warmupIterations: 1 }, - ) + }).run({ + warmupIterations: 1, + }) + }) }) diff --git a/packages/solid-router/tests/link.test.tsx b/packages/solid-router/tests/link.test.tsx index 8d9f36374d..136e358b39 100644 --- a/packages/solid-router/tests/link.test.tsx +++ b/packages/solid-router/tests/link.test.tsx @@ -34,6 +34,7 @@ import { useRouteContext, useSearch, } from '../src' +import { useIntersectionObserver } from '../src/utils' import { getIntersectionObserverMock, getSearchParamsFromURI, @@ -43,12 +44,16 @@ import type { RouterHistory } from '../src' const ioObserveMock = vi.fn() const ioDisconnectMock = vi.fn() +let ioCallback: IntersectionObserverCallback let history: RouterHistory beforeEach(() => { const io = getIntersectionObserverMock({ observe: ioObserveMock, disconnect: ioDisconnectMock, + onCreate: (callback) => { + ioCallback = callback + }, }) vi.stubGlobal('IntersectionObserver', io) history = createBrowserHistory() @@ -56,6 +61,7 @@ beforeEach(() => { }) afterEach(() => { + vi.useRealTimers() history.destroy?.() window.history.replaceState(null, 'root', '/') vi.resetAllMocks() @@ -65,6 +71,295 @@ afterEach(() => { const WAIT_TIME = 300 describe('Link', () => { + test('custom state props follow external, internal and blocked destination changes', async () => { + const [to, setTo] = Solid.createSignal('https://example.com/') + const root = createRootRoute() + const activeProps = () => ({ + class: 'active-state', + style: { color: 'red' }, + }) + const inactiveProps = () => ({ + class: 'inactive-state', + style: { color: 'blue' }, + href: 'javascript:inactive()', + }) + const index = createRoute({ + getParentRoute: () => root, + path: '/', + component: () => ( + + ), + }) + const router = createRouter({ + routeTree: root.addChildren([index]), + history, + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + render(() => ) + const link = await screen.findByTestId('transition-link') + for (const destination of [ + 'https://example.com/', + '/', + 'javascript:blocked()', + '/', + ]) { + setTo(destination) + const active = destination === '/' + await waitFor(() => { + expect(link.getAttribute('href')).toBe( + destination.startsWith('javascript:') ? null : destination, + ) + expect(link.getAttribute('class')?.trim()).toBe( + `base ${active ? 'active-state' : 'inactive-state'}`, + ) + expect(link).toHaveStyle({ + color: active ? 'rgb(255, 0, 0)' : 'rgb(0, 0, 255)', + 'font-weight': '700', + }) + }) + } + }) + + test('keeps protocol-relative Link paths on the router origin', async () => { + const inputs = [ + '//evil.example', + '/\\evil.example', + '\\/evil.example', + ' \t/\\evil.example', + ] + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + <> + {inputs.map((to, index) => ( + + ))} + + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render(() => ) + + for (let index = 0; index < inputs.length; index++) { + const link = await screen.findByTestId(`unsafe-link-${index}`) + const href = link.getAttribute('href') + expect(href).not.toBeNull() + expect(new URL(href!, window.location.href).origin).toBe( + window.location.origin, + ) + } + }) + + test('blocks a dangerous final href produced by an output rewrite', async () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + rewrite: { + output: ({ url }) => + url.pathname === '/safe' ? new URL('javascript:alert(1)') : url, + }, + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + render(() => ) + const link = await screen.findByTestId('rewritten-link') + + expect(link).not.toHaveAttribute('href') + expect(link).toHaveAttribute('role', 'link') + expect(link).toHaveAttribute('aria-disabled', 'true') + expect(fireEvent.click(link)).toBe(true) + }) + + test('blocks a dangerous final href produced by custom history', async () => { + const customHistory = createBrowserHistory({ + createHref: () => 'javascript:alert(1)', + }) + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: customHistory, + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + render(() => ) + const link = await screen.findByTestId('custom-history-link') + + expect(link).not.toHaveAttribute('href') + expect(link).toHaveAttribute('role', 'link') + expect(link).toHaveAttribute('aria-disabled', 'true') + expect(fireEvent.click(link)).toBe(true) + customHistory.destroy() + }) + + test('does not transform a direct HTTPS link through custom history', async () => { + const customHistory = createBrowserHistory({ + createHref: () => 'https://other.example/', + }) + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: customHistory, + }) + try { + render(() => ) + const link = await screen.findByTestId('direct-https-link') + + expect(link).toHaveAttribute('href', 'https://intended.example/') + expect(fireEvent.click(link)).toBe(true) + } finally { + customHistory.destroy() + } + }) + + test('keeps a scheme-bearing custom-history href native', async () => { + const customHistory = createBrowserHistory({ + createHref: () => 'https://other.example/path', + }) + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: customHistory, + }) + + try { + render(() => ) + const link = await screen.findByTestId('custom-history-link') + + expect(link).toHaveAttribute('href', 'https://other.example/path') + expect(fireEvent.click(link)).toBe(true) + } finally { + customHistory.destroy() + } + }) + + test('reactively stops intercepting when a destination becomes external', async () => { + let setTo!: (to: string) => void + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => { + const [to, _setTo] = Solid.createSignal('/safe') + setTo = _setTo + return + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + render(() => ) + const link = await screen.findByTestId('reactive-external-link') + setTo('https://other.example/path') + await waitFor(() => + expect(link).toHaveAttribute('href', 'https://other.example/path'), + ) + + expect(fireEvent.click(link)).toBe(true) + }) + + test('blocks a custom protocol that is not in the allowlist', async () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + protocolAllowlist: [], + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + render(() => ) + const link = await screen.findByTestId('custom-protocol-link') + + expect(link).not.toHaveAttribute('href') + }) + + test('a blocked link stays inactive and cannot regain an href', async () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + + {({ isActive }) => String(isActive)} + + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + rewrite: { + output: ({ url }) => + url.pathname === '/blocked' ? new URL('javascript:alert(1)') : url, + }, + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + render(() => ) + + expect( + await screen.findByTestId('blocked-caller-href'), + ).not.toHaveAttribute('href') + expect(screen.getByTestId('blocked-caller-href')).toHaveAttribute( + 'data-inactive', + 'true', + ) + expect(screen.getByTestId('blocked-caller-href')).toHaveTextContent('false') + expect(fireEvent.click(screen.getByTestId('blocked-caller-href'))).toBe( + true, + ) + }) + // rerender doesn't exist in solid // test('when using renderHook it returns a hook with same content to prove rerender works', async () => { @@ -174,6 +469,90 @@ describe('Link', () => { ).rejects.toThrow() }) + test('does not forward internal Link props to the DOM', async () => { + const internalPropNames = [ + 'activeProps', + 'inactiveProps', + 'activeOptions', + 'to', + 'from', + 'preload', + 'preloadDelay', + 'preloadIntentProximity', + 'hashScrollIntoView', + 'replace', + 'startTransition', + 'resetScroll', + 'viewTransition', + 'ignoreBlocker', + 'params', + 'search', + 'hash', + 'state', + 'mask', + 'reloadDocument', + 'unsafeRelative', + ].map((propName) => propName.toLowerCase()) + + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + + Posts + + ), + }) + + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + component: () =>

    Posts

    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, postsRoute]), + }) + + render(() => ) + + const postsLink = await screen.findByRole('link', { name: 'Posts' }) + const renderedAttributeNames = postsLink + .getAttributeNames() + .map((attributeName) => attributeName.toLowerCase()) + + for (const propName of internalPropNames) { + expect(renderedAttributeNames).not.toContain(propName) + } + }) + test('when a Link has children', async () => { const ChildComponent = vi.fn().mockReturnValue() const rootRoute = createRootRoute() @@ -454,6 +833,479 @@ describe('Link', () => { }) }) + describe('active and href updates', () => { + const createControlledPromise = () => { + let resolve!: () => void + const promise = new Promise((r) => { + resolve = r + }) + + return { promise, resolve } + } + + test('always reports external links as inactive', async () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + + {({ isActive }) => ( + {String(isActive)} + )} + + ), + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history, + }) + + render(() => ) + + expect( + await screen.findByTestId('external-link-active'), + ).toHaveTextContent('false') + }) + + test('updates href when link options change reactively', async () => { + const [to, setTo] = Solid.createSignal<'/a' | '/b'>('/a') + const rootRoute = createRootRoute({ + component: () => ( + <> + + + Destination + + + ), + }) + const aRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/a', + }) + const bRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/b', + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([aRoute, bRoute]), + history, + }) + + render(() => ) + + const link = await screen.findByTestId('dynamic-link') + expect(link).toHaveAttribute('href', '/a') + + fireEvent.click( + screen.getByRole('button', { name: 'Change destination' }), + ) + + await waitFor(() => { + expect(link).toHaveAttribute('href', '/b') + }) + }) + + test('updates exact and fuzzy active state before the next route renders', async () => { + const postLoader = createControlledPromise() + + const rootRoute = createRootRoute({ + component: () => ( + <> + + Posts exact + + + Posts fuzzy + + + Post exact + + + + ), + }) + + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'posts', + component: () => ( + <> +

    Posts

    + + Open post + + + + ), + }) + + const postRoute = createRoute({ + getParentRoute: () => postsRoute, + path: '$postId', + loader: () => postLoader.promise, + component: () =>

    Post detail

    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([postsRoute.addChildren([postRoute])]), + history: createMemoryHistory({ initialEntries: ['/posts'] }), + defaultPendingMs: 0, + defaultPendingComponent: () =>

    Loading...

    , + }) + + render(() => ) + + const postsExact = await screen.findByTestId('posts-exact') + const postsFuzzy = await screen.findByTestId('posts-fuzzy') + const postExact = await screen.findByTestId('post-exact') + + expect(postsExact).toHaveClass('active') + expect(postsFuzzy).toHaveClass('active') + expect(postExact).toHaveClass('inactive') + + fireEvent.click(screen.getByTestId('open-post')) + + expect(await screen.findByText('Loading...')).toBeInTheDocument() + expect(screen.queryByText('Post detail')).not.toBeInTheDocument() + expect(router.state.location.pathname).toBe('/posts/1') + expect(postsExact).toHaveClass('inactive') + expect(postsFuzzy).toHaveClass('active') + expect(postExact).toHaveClass('active') + + postLoader.resolve() + + expect(await screen.findByText('Post detail')).toBeInTheDocument() + }) + + test('updates exact active state and href when only params change with params=true', async () => { + const postLoader = createControlledPromise() + let postLoadCount = 0 + + const rootRoute = createRootRoute({ + component: () => { + const params = useParams({ strict: false }) + const nextPostId = params().postId === '1' ? '2' : '1' + + return ( + <> + + Current post + + + Switch post + + + + ) + }, + }) + + const postRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts/$postId', + loader: () => { + postLoadCount += 1 + return postLoadCount === 1 ? Promise.resolve() : postLoader.promise + }, + component: () => { + const params = useParams({ strict: false }) + return

    {`Post ${params().postId}`}

    + }, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([postRoute]), + history: createMemoryHistory({ initialEntries: ['/posts/1'] }), + defaultPendingMs: 0, + defaultPendingComponent: () =>

    Loading...

    , + }) + + render(() => ) + + const currentPost = await screen.findByTestId('current-post') + expect(await screen.findByText('Post 1')).toBeInTheDocument() + expect(currentPost).toHaveClass('active') + expect(currentPost).toHaveAttribute('href', '/posts/1') + + fireEvent.click(screen.getByTestId('switch-post')) + + expect(await screen.findByText('Loading...')).toBeInTheDocument() + expect(screen.queryByText('Post 2')).not.toBeInTheDocument() + expect(router.state.location.pathname).toBe('/posts/2') + expect(currentPost).toHaveClass('active') + + await waitFor(() => { + expect(currentPost).toHaveAttribute('href', '/posts/2') + }) + + postLoader.resolve() + + expect(await screen.findByText('Post 2')).toBeInTheDocument() + }) + + test('updates search-sensitive active state immediately with and without search=true', async () => { + const postsLoader = createControlledPromise() + let postsLoadCount = 0 + + const rootRoute = createRootRoute({ + component: () => { + const search = useSearch({ strict: false }) + const nextPage = Number(search().page ?? 1) === 1 ? 2 : 1 + + return ( + <> + + Static search + + + Current search + + + Switch search + + + + ) + }, + }) + + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + validateSearch: (input: Record) => ({ + page: Number(input.page ?? 1), + }), + loaderDeps: ({ search }) => ({ page: search.page }), + loader: () => { + postsLoadCount += 1 + return postsLoadCount === 1 ? Promise.resolve() : postsLoader.promise + }, + component: () => { + const search = useSearch({ strict: false }) + return

    {`Posts ${search().page}`}

    + }, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([postsRoute]), + history: createMemoryHistory({ initialEntries: ['/posts?page=1'] }), + defaultPendingMs: 0, + defaultPendingComponent: () =>

    Loading...

    , + }) + + render(() => ) + + const staticSearch = await screen.findByTestId('static-search') + const currentSearch = await screen.findByTestId('current-search') + + expect(await screen.findByText('Posts 1')).toBeInTheDocument() + expect(staticSearch).toHaveClass('active') + expect(currentSearch).toHaveClass('active') + expect(currentSearch).toHaveAttribute('href', '/posts?page=1') + + fireEvent.click(screen.getByTestId('switch-search')) + + expect(await screen.findByText('Loading...')).toBeInTheDocument() + expect(screen.queryByText('Posts 2')).not.toBeInTheDocument() + expect(router.state.location.search).toEqual({ page: 2 }) + expect(staticSearch).toHaveClass('inactive') + expect(currentSearch).toHaveClass('active') + + await waitFor(() => { + expect(currentSearch).toHaveAttribute('href', '/posts?page=2') + }) + + postsLoader.resolve() + + expect(await screen.findByText('Posts 2')).toBeInTheDocument() + }) + + test('updates hash-sensitive active state immediately with and without hash=true', async () => { + const rootRoute = createRootRoute({ + component: () => ( + <> + + Static hash + + + Current hash + + + Switch hash + + + + ), + }) + + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + component: () =>

    Posts

    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([postsRoute]), + history: createMemoryHistory({ initialEntries: ['/posts#first'] }), + }) + + render(() => ) + + const staticHash = await screen.findByTestId('static-hash') + const currentHash = await screen.findByTestId('current-hash') + + expect(staticHash).toHaveClass('active') + expect(currentHash).toHaveClass('active') + expect(currentHash).toHaveAttribute('href', '/posts#first') + + await fireEvent.click(screen.getByTestId('switch-hash')) + + expect(router.state.location.hash).toBe('second') + expect(staticHash).toHaveClass('inactive') + expect(currentHash).toHaveClass('active') + + await waitFor(() => { + expect(currentHash).toHaveAttribute('href', '/posts#second') + }) + }) + + test('eventually updates relative hrefs when the current route changes', async () => { + const rootRoute = createRootRoute({ + component: () => ( + <> + + Relative foo + + + To posts + + + To invoices + + + + ), + }) + + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + component: () =>

    Posts

    , + }) + + const postsFooRoute = createRoute({ + getParentRoute: () => postsRoute, + path: 'foo', + component: () =>

    Posts foo

    , + }) + + const invoicesRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/invoices', + component: () =>

    Invoices

    , + }) + + const invoicesFooRoute = createRoute({ + getParentRoute: () => invoicesRoute, + path: 'foo', + component: () =>

    Invoices foo

    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([ + postsRoute.addChildren([postsFooRoute]), + invoicesRoute.addChildren([invoicesFooRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/posts'] }), + }) + + render(() => ) + + const relativeFoo = await screen.findByTestId('relative-foo') + expect(await screen.findByText('Posts')).toBeInTheDocument() + expect(relativeFoo).toHaveAttribute('href', '/posts/foo') + + fireEvent.click(screen.getByTestId('to-invoices')) + + expect(await screen.findByText('Invoices')).toBeInTheDocument() + + await waitFor(() => { + expect(relativeFoo).toHaveAttribute('href', '/invoices/foo') + }) + }) + }) + test('when the current route is the root with beforeLoad that throws', async () => { const onError = vi.fn() const rootRoute = createRootRoute({ @@ -554,10 +1406,13 @@ describe('Link', () => { expect(indexLink).not.toHaveAttribute('data-status', 'active') expect(indexLink).toHaveAttribute('href', '/') - expect(postsLink).toHaveAttribute('data-status', 'active') - expect(postsLink).toHaveAttribute('aria-current', 'page') - expect(postsLink).toHaveClass('active') - expect(postsLink).toHaveAttribute('href', '/posts') + // The clicked link left with the index page; check the posts page's own. + const activePostsLink = await screen.findByRole('link', { name: 'Posts' }) + expect(activePostsLink).not.toBe(postsLink) + expect(activePostsLink).toHaveAttribute('data-status', 'active') + expect(activePostsLink).toHaveAttribute('aria-current', 'page') + expect(activePostsLink).toHaveClass('active') + expect(activePostsLink).toHaveAttribute('href', '/posts') }) test('when navigating to /posts with a base url', async () => { @@ -613,10 +1468,13 @@ describe('Link', () => { expect(indexLink).not.toHaveAttribute('data-status', 'active') expect(indexLink).toHaveAttribute('href', '/app/') - expect(postsLink).toHaveAttribute('data-status', 'active') - expect(postsLink).toHaveAttribute('aria-current', 'page') - expect(postsLink).toHaveClass('active') - expect(postsLink).toHaveAttribute('href', '/app/posts') + // The clicked link left with the index page; check the posts page's own. + const activePostsLink = await screen.findByRole('link', { name: 'Posts' }) + expect(activePostsLink).not.toBe(postsLink) + expect(activePostsLink).toHaveAttribute('data-status', 'active') + expect(activePostsLink).toHaveAttribute('aria-current', 'page') + expect(activePostsLink).toHaveClass('active') + expect(activePostsLink).toHaveAttribute('href', '/app/posts') }) test('when navigating to /posts with search', async () => { @@ -775,7 +1633,7 @@ describe('Link', () => { '/posts?page=2&filter=inactive', ) - await fireEvent.click(updateSearchLink) + fireEvent.click(updateSearchLink) // Wait for navigation to complete and search params to update await waitFor(() => { @@ -786,8 +1644,11 @@ describe('Link', () => { const updatedFilter = await screen.findByTestId('current-filter') // Verify search was updated - expect(window.location.pathname).toBe('/posts') - expect(window.location.search).toBe('?page=2&filter=inactive') + // Wait for navigation to complete and search params to update + await waitFor(() => { + expect(window.location.pathname).toBe('/posts') + expect(window.location.search).toBe('?page=2&filter=inactive') + }) expect(updatedPage).toHaveTextContent('Page: 2') expect(updatedFilter).toHaveTextContent('Filter: inactive') @@ -893,22 +1754,17 @@ describe('Link', () => { '/Dashboard/posts?page=2&filter=inactive', ) - await fireEvent.click(updateSearchLink) + fireEvent.click(updateSearchLink) - // Wait for navigation to complete and search params to update await waitFor(() => { + expect(window.location.pathname).toBe('/Dashboard/posts') expect(window.location.search).toBe('?page=2&filter=inactive') + expect(screen.getByTestId('current-page')).toHaveTextContent('Page: 2') + expect(screen.getByTestId('current-filter')).toHaveTextContent( + 'Filter: inactive', + ) }) - - await screen.findByTestId('current-page') - // Verify search was updated - expect(window.location.pathname).toBe('/Dashboard/posts') - expect(window.location.search).toBe('?page=2&filter=inactive') - - const updatedPage = await screen.findByTestId('current-page') - const updatedFilter = await screen.findByTestId('current-filter') - expect(updatedPage).toHaveTextContent('Page: 2') - expect(updatedFilter).toHaveTextContent('Filter: inactive') + await vi.waitFor(() => expect(router.state.status).toBe('idle')) }) test('when navigating to /posts with invalid search', async () => { @@ -1487,7 +2343,11 @@ describe('Link', () => { return ( <>

    Index

    - + To first post @@ -1543,6 +2403,118 @@ describe('Link', () => { expect(paramText).toBeInTheDocument() }) + test('keeps a relative link active when changing inherited params (issue #5655)', async () => { + const rootRoute = createRootRoute() + + const postRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/post/$postId', + component: () => { + const params = useParams({ strict: false }) + const postId = () => params().postId + + return ( + <> + + Step 1 + + + Step 2 + + + + ) + }, + }) + + const step1Route = createRoute({ + getParentRoute: () => postRoute, + path: 'step1', + component: () => { + const params = useParams({ strict: false }) + const postId = () => params().postId + const otherPostId = () => (postId() === '1' ? '2' : '1') + + return ( + <> + {`Post ${postId()} step1`} + {`Go to post ${otherPostId()}`} + + ) + }, + }) + + const step2Route = createRoute({ + getParentRoute: () => postRoute, + path: 'step2', + component: () => { + const params = useParams({ strict: false }) + const postId = () => params().postId + const otherPostId = () => (postId() === '1' ? '2' : '1') + + return ( + <> + {`Post ${postId()} step2`} + {`Go to post ${otherPostId()}`} + + ) + }, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([ + postRoute.addChildren([step1Route, step2Route]), + ]), + history: createMemoryHistory({ + initialEntries: ['/post/1/step1'], + }), + }) + + render(() => ) + + expect(await screen.findByText('Post 1 step1')).toBeInTheDocument() + expect(screen.getByTestId('step1-link')).toHaveClass('active') + + fireEvent.click(screen.getByTestId('switch-post-link')) + + expect(await screen.findByText('Post 2 step1')).toBeInTheDocument() + expect(router.state.location.pathname).toBe('/post/2/step1') + expect(screen.getByTestId('step1-link')).toHaveClass('active') + + fireEvent.click(screen.getByTestId('step2-link')) + + expect(await screen.findByText('Post 2 step2')).toBeInTheDocument() + expect(router.state.location.pathname).toBe('/post/2/step2') + expect(screen.getByTestId('step2-link')).toHaveClass('active') + + fireEvent.click(screen.getByTestId('switch-post-link')) + + expect(await screen.findByText('Post 1 step2')).toBeInTheDocument() + expect(router.state.location.pathname).toBe('/post/1/step2') + expect(screen.getByTestId('step2-link')).toHaveClass('active') + }) + test('when navigating from /posts to ./$postId', async () => { const rootRoute = createRootRoute() const indexRoute = createRoute({ @@ -2064,10 +3036,16 @@ describe('Link', () => { const postRoute = createRoute({ getParentRoute: () => postsRoute, - path: '$postId/', + path: '$postId', component: PostComponent, }) + const postIndexRoute = createRoute({ + getParentRoute: () => postRoute, + path: '/', + component: () =>
    Post Index
    , + }) + const DetailsComponent = () => { return ( <> @@ -2100,7 +3078,11 @@ describe('Link', () => { indexRoute, layoutRoute.addChildren([ postsRoute.addChildren([ - postRoute.addChildren([detailsRoute, informationRoute]), + postRoute.addChildren([ + postIndexRoute, + detailsRoute, + informationRoute, + ]), ]), ]), ]), @@ -4316,6 +5298,234 @@ describe('Link', () => { expect(ioDisconnectMock).not.toHaveBeenCalled() // it should not disconnect again }) + test.each([ + ['intent', true], + [false, false], + ] as const)( + 'observers without viewport preloading clean up only while preloading (%s)', + (mode, cleansUp) => { + const callback = vi.fn() + const view = render(() => { + const [element, setElement] = Solid.createSignal(null) + useIntersectionObserver(element, callback, () => mode) + return
    + }) + callback.mockClear() + view.unmount() + if (cleansUp) { + expect(callback).toHaveBeenCalledWith() + } else { + expect(callback).not.toHaveBeenCalled() + } + }, + ) + + test.each(['intent', 'viewport'] as const)( + 'preserves %s timer cleanup across mode changes and unmount', + async (mode) => { + const [preload, setPreload] = Solid.createSignal< + false | 'intent' | 'viewport' + >() + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + + Preload Link + + ), + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + history, + }) + const preloadRouteSpy = vi.spyOn(router, 'preloadRoute') + const view = render(() => ) + const link = await screen.findByRole('link', { name: 'Preload Link' }) + const notify = (callback: IntersectionObserverCallback) => { + callback( + [ + { + isIntersecting: true, + target: link, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + } + const trigger = () => { + if (mode === 'intent') { + fireEvent.mouseEnter(link) + } else { + notify(ioCallback) + } + } + vi.useFakeTimers() + + setPreload(mode) + await Promise.resolve() + const oldObserver = mode === 'viewport' ? ioCallback : undefined + trigger() + await vi.advanceTimersByTimeAsync(49) + setPreload(false) + await Promise.resolve() + if (oldObserver) { + notify(oldObserver) + } + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).not.toHaveBeenCalled() + + setPreload(mode) + await Promise.resolve() + if (oldObserver) { + // The mode matches again, but the previous observer is still obsolete. + notify(oldObserver) + } + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).not.toHaveBeenCalled() + trigger() + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).toHaveBeenCalledOnce() + + preloadRouteSpy.mockClear() + trigger() + const lastObserver = mode === 'viewport' ? ioCallback : undefined + view.unmount() + if (lastObserver) { + notify(lastObserver) + } + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).not.toHaveBeenCalled() + }, + ) + + test('Link.preload="viewport" should respect preloadDelay', async () => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + <> + + Viewport Link + + + Intent Link + + + ), + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + history, + }) + const preloadRouteSpy = vi.spyOn(router, 'preloadRoute') + + render(() => ) + + const viewportLink = await screen.findByRole('link', { + name: 'Viewport Link', + }) + const intentLink = await screen.findByRole('link', { name: 'Intent Link' }) + vi.useFakeTimers() + + ioCallback([], {} as IntersectionObserver) + ioCallback( + [ + { + isIntersecting: false, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).not.toHaveBeenCalled() + + ioCallback( + [ + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + ioCallback( + [ + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + fireEvent.mouseLeave(viewportLink) + + expect(preloadRouteSpy).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(49) + expect(preloadRouteSpy).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + expect(preloadRouteSpy).toHaveBeenCalledOnce() + + ioCallback( + [ + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + { + isIntersecting: false, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).toHaveBeenCalledOnce() + + ioCallback( + [ + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + await vi.advanceTimersByTimeAsync(49) + + ioCallback( + [ + { + isIntersecting: false, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + { + isIntersecting: true, + target: viewportLink, + } as unknown as IntersectionObserverEntry, + ], + {} as IntersectionObserver, + ) + await vi.advanceTimersByTimeAsync(1) + expect(preloadRouteSpy).toHaveBeenCalledTimes(2) + + fireEvent.mouseEnter(intentLink) + fireEvent.mouseLeave(intentLink) + await vi.advanceTimersByTimeAsync(50) + expect(preloadRouteSpy).toHaveBeenCalledTimes(2) + }) + test("Router.preload='render', should trigger the route loader on render", async () => { const mock = vi.fn() @@ -4356,6 +5566,121 @@ describe('Link', () => { expect(mock).toHaveBeenCalledTimes(1) }) + test.each([undefined, false, 'render', 'viewport'] as const)( + 'Link.preload="%s" should not preload on focus, hover, or touchstart', + async (preloadMode) => { + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + <> +

    Index Heading

    + + About Link + + + ), + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + component: () =>

    About Heading

    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([aboutRoute, indexRoute]), + defaultPreload: false, + defaultPreloadDelay: 0, + history, + }) + + const preloadRouteSpy = vi.spyOn(router, 'preloadRoute') + + render(() => ) + + const aboutLink = await screen.findByRole('link', { name: 'About Link' }) + expect(aboutLink).toBeInTheDocument() + + if (preloadMode === 'render') { + await waitFor(() => + expect(preloadRouteSpy.mock.calls.length).toBeGreaterThan(0), + ) + } + + const baselineCalls = preloadRouteSpy.mock.calls.length + + fireEvent.focus(aboutLink) + fireEvent.mouseOver(aboutLink) + fireEvent.touchStart(aboutLink) + + await sleep(100) + expect(preloadRouteSpy).toHaveBeenCalledTimes(baselineCalls) + }, + ) + + test('Link.preload="intent" should preload on focus, hover, and touchstart', async () => { + const updateSearch = vi.fn((search) => search) + const rootRoute = createRootRoute() + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => ( + <> +

    Index Heading

    + + About Link + + + ), + }) + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + component: () =>

    About Heading

    , + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([aboutRoute, indexRoute]), + defaultPreload: false, + defaultPreloadDelay: 0, + history, + }) + + const preloadRouteSpy = vi.spyOn(router, 'preloadRoute') + + render(() => ) + + const aboutLink = await screen.findByRole('link', { name: 'About Link' }) + expect(aboutLink).toBeInTheDocument() + + const baselineCalls = preloadRouteSpy.mock.calls.length + const baselineSearchCalls = updateSearch.mock.calls.length + expect(baselineSearchCalls).toBeGreaterThan(0) + + fireEvent.focus(aboutLink) + await waitFor(() => + expect(preloadRouteSpy).toHaveBeenCalledTimes(baselineCalls + 1), + ) + + fireEvent.mouseOver(aboutLink) + await waitFor(() => + expect(preloadRouteSpy).toHaveBeenCalledTimes(baselineCalls + 2), + ) + + fireEvent.touchStart(aboutLink) + await waitFor(() => + expect(preloadRouteSpy).toHaveBeenCalledTimes(baselineCalls + 3), + ) + expect(updateSearch).toHaveBeenCalledTimes(baselineSearchCalls + 3) + for (const call of preloadRouteSpy.mock.calls.slice(baselineCalls)) { + expect(call).toHaveLength(1) + } + }) + test('Router.preload="intent", pendingComponent renders during unresolved route loader', async () => { const rootRoute = createRootRoute() const indexRoute = createRoute({ @@ -5529,14 +6854,12 @@ describe('splat routes with empty splat', () => { async (trailingSlash) => { const tail = trailingSlash === 'always' ? '/' : '' - const rootRoute = createRootRoute() - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', + // The links stay mounted across the navigation so they can turn active. + const rootRoute = createRootRoute({ component: () => { return ( <> -

    Index Route

    + { ) }, }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () => { + return

    Index Route

    + }, + }) const splatRoute = createRoute({ getParentRoute: () => rootRoute, @@ -6496,8 +7826,8 @@ describe('encoded and unicode paths', () => { name: 'with prefix', path: '/foo/prefix@대{$}', expectedPath: - '/foo/prefix@%EB%8C%80test[s%5C/.%5C/parameter%25!%F0%9F%9A%80@]', - expectedLocation: '/foo/prefix@대test[s%5C/.%5C/parameter%25!🚀@]', + '/foo/prefix@%EB%8C%80test[s%5C/.%5C/parameter%25!%F0%9F%9A%80%40]', + expectedLocation: '/foo/prefix@대test[s%5C/.%5C/parameter%25!🚀%40]', params: { _splat: 'test[s\\/.\\/parameter%!🚀@]', '*': 'test[s\\/.\\/parameter%!🚀@]', @@ -6507,8 +7837,8 @@ describe('encoded and unicode paths', () => { name: 'with suffix', path: '/foo/{$}대suffix@', expectedPath: - '/foo/test[s%5C/.%5C/parameter%25!%F0%9F%9A%80@]%EB%8C%80suffix@', - expectedLocation: '/foo/test[s%5C/.%5C/parameter%25!🚀@]대suffix@', + '/foo/test[s%5C/.%5C/parameter%25!%F0%9F%9A%80%40]%EB%8C%80suffix@', + expectedLocation: '/foo/test[s%5C/.%5C/parameter%25!🚀%40]대suffix@', params: { _splat: 'test[s\\/.\\/parameter%!🚀@]', '*': 'test[s\\/.\\/parameter%!🚀@]', diff --git a/packages/solid-router/tests/loaders.test.tsx b/packages/solid-router/tests/loaders.test.tsx index c0e5253219..63ac8e3e2e 100644 --- a/packages/solid-router/tests/loaders.test.tsx +++ b/packages/solid-router/tests/loaders.test.tsx @@ -17,9 +17,10 @@ import { import { sleep } from './utils' afterEach(() => { + cleanup() + vi.useRealTimers() vi.resetAllMocks() window.history.replaceState(null, 'root', '/') - cleanup() }) const WAIT_TIME = 100 @@ -320,6 +321,66 @@ test('throw error from beforeLoad when navigating to route', async () => { expect(indexElement).toBeInTheDocument() }) +// https://github.com/TanStack/router/pull/7673 +test('#7673: a spontaneous loader AbortError renders the boundary without executing the route component', async () => { + window.history.replaceState(null, 'root', '/app') + const rootRoute = createRootRoute({}) + const abortError = new DOMException('Aborted', 'AbortError') + const routeComponentRendered = vi.fn() + const renderedError = vi.fn() + let routeSignal: AbortSignal | undefined + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: async ({ abortController }): Promise<{ value: string }> => { + routeSignal = abortController.signal + return Promise.reject(abortError) + }, + component: () => { + routeComponentRendered() + const data = indexRoute.useLoaderData() + return
    {data().value}
    + }, + errorComponent: ({ error }) => { + renderedError(error) + return
    indexErrorComponent
    + }, + }) + + const routeTree = rootRoute.addChildren([indexRoute]) + const router = createRouter({ routeTree, basepath: '/app' }) + const rendered = new Promise((resolve) => { + const unsubscribe = router.subscribe('onRendered', () => { + unsubscribe() + resolve() + }) + }) + + render(() => ) + + expect(await screen.findByTestId('index-error')).toBeInTheDocument() + await rendered + expect(screen.queryByTestId('index-content')).not.toBeInTheDocument() + expect(routeComponentRendered).not.toHaveBeenCalled() + // jsdom creates DOMException in another realm, so Solid wraps the error. + expect(renderedError).toHaveBeenCalledWith( + expect.objectContaining({ + message: 'Unknown error', + cause: abortError, + }), + ) + expect(routeSignal?.aborted).toBe(false) + expect( + router.state.matches.find((match) => match.routeId === indexRoute.id), + ).toMatchObject({ + status: 'error', + error: abortError, + }) + expect(window.location.pathname).toBe('/app') + expect(router.state.status).toBe('idle') +}) + test('reproducer #4245', async () => { const LOADER_WAIT_TIME = 500 const rootRoute = createRootRoute({}) @@ -589,7 +650,8 @@ test('reproducer #4546', async () => { fireEvent.click(indexLink) { - // Wait for navigation to complete before checking values + // beforeLoad is fresh for this navigation, while the cached loader data is + // allowed to remain visible until its background reload completes. await screen.findByText('Index route') const headerCounter = await screen.findByTestId('header-counter') expect(headerCounter).toHaveTextContent('3') @@ -598,7 +660,7 @@ test('reproducer #4546', async () => { expect(routeContext).toHaveTextContent('3') const loaderData = await screen.findByTestId('index-loader-data') - expect(loaderData).toHaveTextContent('3') + await vi.waitFor(() => expect(loaderData).toHaveTextContent('3')) } fireEvent.click(invalidateRouterButton) @@ -619,7 +681,7 @@ test('reproducer #4546', async () => { fireEvent.click(idLink) { - // Wait for navigation to complete before checking values + // This loader generation can likewise begin with reusable cached data. await screen.findByText('$id route') const headerCounter = await screen.findByTestId('header-counter') expect(headerCounter).toHaveTextContent('5') @@ -628,11 +690,11 @@ test('reproducer #4546', async () => { expect(routeContext).toHaveTextContent('5') const loaderData = await screen.findByTestId('id-loader-data') - expect(loaderData).toHaveTextContent('5') + await vi.waitFor(() => expect(loaderData).toHaveTextContent('5')) } }) -test('clears pendingTimeout when match resolves', async () => { +test('does not show pending UI when loaders finish before their pending delays', async () => { const defaultPendingComponentOnMountMock = vi.fn() const nestedPendingComponentOnMountMock = vi.fn() const fooPendingComponentOnMountMock = vi.fn() @@ -700,13 +762,16 @@ test('clears pendingTimeout when match resolves', async () => { }) render(() => ) - await router.latestLoadPromise - const linkToFoo = await screen.findByTestId('link-to-foo') - fireEvent.click(linkToFoo) - const fooElement = await screen.findByText('Nested Foo page') + await screen.findByTestId('link-to-foo') + vi.useFakeTimers() + const navigation = router.navigate({ to: '/nested/foo' }) + await vi.advanceTimersByTimeAsync(WAIT_TIME * 5) + await navigation + const fooElement = screen.getByText('Nested Foo page') expect(fooElement).toBeInTheDocument() expect(router.state.location.href).toBe('/nested/foo') + expect(router.state.status).toBe('idle') // none of the pending components should have been called expect(defaultPendingComponentOnMountMock).not.toHaveBeenCalled() @@ -714,7 +779,7 @@ test('clears pendingTimeout when match resolves', async () => { expect(fooPendingComponentOnMountMock).not.toHaveBeenCalled() }) -test('cancelMatches after pending timeout', async () => { +test('navigating away from a pending route aborts its loader', async () => { function getPendingComponent(onMount: () => void) { const PendingComponent = () => { onMount() @@ -724,6 +789,7 @@ test('cancelMatches after pending timeout', async () => { } const onAbortMock = vi.fn() const fooPendingComponentOnMountMock = vi.fn() + let fooSignal: AbortSignal | undefined const history = createMemoryHistory({ initialEntries: ['/'] }) const rootRoute = createRootRoute({ component: () => ( @@ -742,17 +808,18 @@ test('cancelMatches after pending timeout', async () => { const fooRoute = createRoute({ getParentRoute: () => rootRoute, path: '/foo', - pendingMs: WAIT_TIME * 20, + pendingMs: 0, loader: async ({ abortController }) => { + fooSignal = abortController.signal await new Promise((resolve) => { - const timer = setTimeout(() => { - resolve() - }, WAIT_TIME * 40) - abortController.signal.addEventListener('abort', () => { - onAbortMock() - clearTimeout(timer) - resolve() - }) + abortController.signal.addEventListener( + 'abort', + () => { + onAbortMock() + resolve() + }, + { once: true }, + ) }) }, pendingComponent: getPendingComponent(fooPendingComponentOnMountMock), @@ -766,16 +833,20 @@ test('cancelMatches after pending timeout', async () => { const routeTree = rootRoute.addChildren([fooRoute, barRoute]) const router = createRouter({ routeTree, history }) render(() => ) - await router.latestLoadPromise const fooLink = await screen.findByTestId('link-to-foo') fireEvent.click(fooLink) - await sleep(WAIT_TIME * 30) const pendingElement = await screen.findByText('Pending...') expect(pendingElement).toBeInTheDocument() - const barLink = await screen.findByTestId('link-to-bar') - fireEvent.click(barLink) - const barElement = await screen.findByText('Bar page') + expect(fooSignal?.aborted).toBe(false) + await router.navigate({ to: '/bar' }) + const barElement = screen.getByText('Bar page') expect(barElement).toBeInTheDocument() + expect(fooPendingComponentOnMountMock).toHaveBeenCalled() - expect(onAbortMock).toHaveBeenCalled() + expect(onAbortMock).toHaveBeenCalledTimes(1) + expect(fooSignal?.aborted).toBe(true) + expect(screen.queryByText('Pending...')).not.toBeInTheDocument() + expect(screen.queryByText('Foo page')).not.toBeInTheDocument() + expect(router.state.location.href).toBe('/bar') + expect(router.state.status).toBe('idle') }) diff --git a/packages/solid-router/tests/navigate.test.tsx b/packages/solid-router/tests/navigate.test.tsx index 4aaacc8674..fdc85abb62 100644 --- a/packages/solid-router/tests/navigate.test.tsx +++ b/packages/solid-router/tests/navigate.test.tsx @@ -480,17 +480,26 @@ describe('router.navigate navigation using layout routes resolves correctly', () await router.load() expect(router.state.location.pathname).toBe('/search') - expect(router.state.location.search).toStrictEqual({ 'foo=bar': 2 }) + expect(router.state.location.search).toStrictEqual( + toNullObj({ 'foo=bar': 2 }), + ) await router.navigate({ search: { 'foo=bar': 3 }, } as any) await router.invalidate() - expect(router.state.location.search).toStrictEqual({ 'foo=bar': 3 }) + expect(router.state.location.search).toStrictEqual( + toNullObj({ 'foo=bar': 3 }), + ) }) }) +function toNullObj(obj: T): T { + if (typeof obj === 'object') return Object.assign(Object.create(null), obj) + return obj +} + describe('relative navigation', () => { it('should navigate to a child route', async () => { const { router } = createTestRouter( @@ -1270,8 +1279,8 @@ describe('encoded and unicode paths', () => { name: 'with prefix', path: '/foo/prefix@대{$}', expectedPath: - '/foo/prefix@%EB%8C%80test[s%5C/.%5C/parameter%25!%F0%9F%9A%80@]', - expectedLocation: '/foo/prefix@대test[s%5C/.%5C/parameter%25!🚀@]', + '/foo/prefix@%EB%8C%80test[s%5C/.%5C/parameter%25!%F0%9F%9A%80%40]', + expectedLocation: '/foo/prefix@대test[s%5C/.%5C/parameter%25!🚀%40]', params: { _splat: 'test[s\\/.\\/parameter%!🚀@]', '*': 'test[s\\/.\\/parameter%!🚀@]', @@ -1281,8 +1290,8 @@ describe('encoded and unicode paths', () => { name: 'with suffix', path: '/foo/{$}대suffix@', expectedPath: - '/foo/test[s%5C/.%5C/parameter%25!%F0%9F%9A%80@]%EB%8C%80suffix@', - expectedLocation: '/foo/test[s%5C/.%5C/parameter%25!🚀@]대suffix@', + '/foo/test[s%5C/.%5C/parameter%25!%F0%9F%9A%80%40]%EB%8C%80suffix@', + expectedLocation: '/foo/test[s%5C/.%5C/parameter%25!🚀%40]대suffix@', params: { _splat: 'test[s\\/.\\/parameter%!🚀@]', '*': 'test[s\\/.\\/parameter%!🚀@]', diff --git a/packages/solid-router/tests/not-found.test.tsx b/packages/solid-router/tests/not-found.test.tsx index 38a3e63944..36b08a3718 100644 --- a/packages/solid-router/tests/not-found.test.tsx +++ b/packages/solid-router/tests/not-found.test.tsx @@ -10,6 +10,7 @@ import { createRoute, createRouter, notFound, + rootRouteId, } from '../src' import type { NotFoundRouteProps, RouterHistory } from '../src' @@ -245,3 +246,241 @@ test('defaultNotFoundComponent and notFoundComponent receives data props via spr const errorMessageComponent = await screen.findByTestId('message') expect(errorMessageComponent).toHaveTextContent(customData.message) }) + +test('component-thrown bare notFound renders current route notFoundComponent', async () => { + const rootRoute = createRootRoute({ + component: () => , + notFoundComponent: () => Root, + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: () => , + notFoundComponent: () => ( + Parent not found + ), + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + notFoundComponent: () => ( + Child not found + ), + component: () => { + throw notFound() + }, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + notFoundMode: 'fuzzy', + }) + + render(() => ) + await router.navigate({ to: '/parent/child' }) + + expect(await screen.findByTestId('child-not-found')).toBeInTheDocument() + expect(screen.queryByTestId('parent-not-found')).not.toBeInTheDocument() + expect(screen.queryByTestId('root-not-found')).not.toBeInTheDocument() +}) + +test('component-thrown bare notFound falls back to nearest ancestor notFoundComponent', async () => { + const rootRoute = createRootRoute({ + component: () => , + notFoundComponent: () => Root, + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: () => , + notFoundComponent: () => ( + Parent not found + ), + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + component: () => { + throw notFound() + }, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + notFoundMode: 'fuzzy', + }) + + render(() => ) + await router.navigate({ to: '/parent/child' }) + + expect(await screen.findByTestId('parent-not-found')).toBeInTheDocument() + expect(screen.queryByTestId('root-not-found')).not.toBeInTheDocument() +}) + +test('beforeLoad notFound with routeId targets parent notFoundComponent', async () => { + const rootRoute = createRootRoute({ + component: () => , + notFoundComponent: () => ( + Root not found + ), + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: () => , + notFoundComponent: () => ( + Parent not found + ), + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: () => { + throw notFound({ routeId: parentRoute.id }) + }, + component: () => Child, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + }) + + render(() => ) + await router.navigate({ to: '/parent/child' }) + + expect(await screen.findByTestId('parent-not-found')).toBeInTheDocument() + expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() +}) + +test('beforeLoad notFound with routeId targets parent boundary and preserves parent loader data', async () => { + const rootRoute = createRootRoute({ + component: () => , + notFoundComponent: () => ( + Root not found + ), + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loader: () => ({ message: 'ready' }), + component: () => , + notFoundComponent: () => { + const loaderData = parentRoute.useLoaderData() + return ( + + {loaderData().message} + + ) + }, + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: () => { + throw notFound({ routeId: parentRoute.id }) + }, + component: () => Child, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + }) + + render(() => ) + await router.navigate({ to: '/parent/child' }) + + expect( + await screen.findByTestId('parent-not-found-with-loader-data'), + ).toHaveTextContent('ready') + expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() +}) + +test('beforeLoad notFound with routeId targets root notFoundComponent', async () => { + const rootRoute = createRootRoute({ + component: () => , + notFoundComponent: () => ( + Root not found + ), + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: () => , + notFoundComponent: () => ( + Parent not found + ), + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: () => { + throw notFound({ routeId: rootRouteId }) + }, + component: () => Child, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + }) + + render(() => ) + await router.navigate({ to: '/parent/child' }) + + expect(await screen.findByTestId('root-not-found')).toBeInTheDocument() + expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() +}) + +test('beforeLoad notFound with non-exact routeId falls back to root notFoundComponent', async () => { + const rootRoute = createRootRoute({ + component: () => , + notFoundComponent: () => ( + Root not found + ), + }) + + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + component: () => , + notFoundComponent: () => ( + Parent not found + ), + }) + + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + beforeLoad: () => { + throw notFound({ routeId: `${parentRoute.id}/` as never }) + }, + component: () => Child, + }) + + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history, + notFoundMode: 'fuzzy', + }) + + render(() => ) + await router.navigate({ to: '/parent/child' }) + + expect(await screen.findByTestId('root-not-found')).toBeInTheDocument() + expect(screen.queryByTestId('parent-not-found')).not.toBeInTheDocument() + expect(screen.queryByTestId('child-component')).not.toBeInTheDocument() +}) diff --git a/packages/solid-router/tests/pending-fallback-promise-replacement.test.tsx b/packages/solid-router/tests/pending-fallback-promise-replacement.test.tsx new file mode 100644 index 0000000000..1b1ac2268c --- /dev/null +++ b/packages/solid-router/tests/pending-fallback-promise-replacement.test.tsx @@ -0,0 +1,179 @@ +import { cleanup, render, screen } from '@solidjs/testing-library' +import { afterEach, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' +import type { AnyRouter } from '../src' + +const testCleanups: Array<() => void | Promise> = [] + +afterEach(async () => { + const pendingCleanups = testCleanups + .splice(0) + .reverse() + .map((testCleanup) => testCleanup()) + if (vi.isFakeTimers()) { + await vi.runAllTimersAsync() + } + await Promise.allSettled(pendingCleanups) + cleanup() + vi.useRealTimers() +}) + +test.each(['child', 'root'] as const)( + 'a mounted %s pending fallback follows an overlapping load generation', + async (routeLevel) => { + const firstReload = createControlledPromise() + const secondReload = createControlledPromise() + const reloads = [firstReload, secondReload] + let loaderCall = 0 + + const routeOptions = { + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    Pending
    , + loader: () => { + const generation = ++loaderCall + const gate = reloads[generation - 2] + return gate ? gate.then(() => generation) : generation + }, + } + + const makeRouter = (): AnyRouter => { + if (routeLevel === 'root') { + const rootRoute = createRootRoute({ + ...routeOptions, + component: () =>
    Generation {rootRoute.useLoaderData()()}
    , + }) + return createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + } + + const rootRoute = createRootRoute({ component: () => }) + const pageRoute = createRoute({ + ...routeOptions, + getParentRoute: () => rootRoute, + path: '/page', + component: () =>
    Generation {pageRoute.useLoaderData()()}
    , + }) + return createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + } + const router = makeRouter() + + render(() => ) + expect(await screen.findByText('Generation 1')).toBeInTheDocument() + + vi.useFakeTimers() + const firstInvalidation = router.invalidate({ forcePending: true }) + const invalidations = [firstInvalidation] + testCleanups.push(async () => { + firstReload.resolve() + secondReload.resolve() + await Promise.allSettled(invalidations) + }) + await vi.advanceTimersByTimeAsync(0) + expect(loaderCall).toBe(2) + expect(screen.getByTestId('pending')).toBeInTheDocument() + expect(screen.queryByText('Generation 1')).not.toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(25) + const secondInvalidation = router.invalidate({ forcePending: true }) + invalidations.push(secondInvalidation) + await vi.advanceTimersByTimeAsync(0) + expect(loaderCall).toBe(3) + + firstReload.resolve() + await vi.advanceTimersByTimeAsync(0) + + expect(screen.getByTestId('pending')).toBeInTheDocument() + expect(screen.queryByText('Generation 2')).not.toBeInTheDocument() + + let secondSettled = false + void secondInvalidation.then(() => { + secondSettled = true + }) + secondReload.resolve() + await vi.advanceTimersByTimeAsync(0) + + expect(secondSettled).toBe(false) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(74) + expect(secondSettled).toBe(false) + expect(screen.getByTestId('pending')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(1) + await Promise.all(invalidations) + expect(screen.getByText('Generation 3')).toBeInTheDocument() + expect(screen.queryByText('Generation 1')).not.toBeInTheDocument() + expect(screen.queryByText('Generation 2')).not.toBeInTheDocument() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(router.state.status).toBe('idle') + }, +) + +test('forcePending honors pendingMinMs when the reload settles before pendingMs', async () => { + const reload = createControlledPromise() + let loaderCall = 0 + + const rootRoute = createRootRoute({ component: () => }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + pendingMinMs: 100, + pendingComponent: () =>
    Pending
    , + loader: async () => { + if (++loaderCall > 1) { + await reload + } + return loaderCall + }, + component: () =>
    Generation {pageRoute.useLoaderData()()}
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + + render(() => ) + expect(await screen.findByText('Generation 1')).toBeInTheDocument() + + vi.useFakeTimers() + const invalidation = router.invalidate({ forcePending: true }) + testCleanups.push(async () => { + reload.resolve() + await Promise.allSettled([invalidation]) + }) + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByTestId('fast-pending')).toBeInTheDocument() + + let settled = false + void invalidation.then(() => { + settled = true + }) + reload.resolve() + await vi.advanceTimersByTimeAsync(0) + + await vi.advanceTimersByTimeAsync(99) + expect(settled).toBe(false) + expect(screen.getByTestId('fast-pending')).toBeInTheDocument() + expect(screen.queryByText('Generation 2')).not.toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(1) + await invalidation + expect(screen.getByText('Generation 2')).toBeInTheDocument() + expect(screen.queryByText('Generation 1')).not.toBeInTheDocument() + expect(screen.queryByTestId('fast-pending')).not.toBeInTheDocument() + expect(router.state.status).toBe('idle') +}) diff --git a/packages/solid-router/tests/public-presentation-lane-contract.test.tsx b/packages/solid-router/tests/public-presentation-lane-contract.test.tsx new file mode 100644 index 0000000000..267f0049c8 --- /dev/null +++ b/packages/solid-router/tests/public-presentation-lane-contract.test.tsx @@ -0,0 +1,459 @@ +import * as Solid from 'solid-js' +import { cleanup, render, screen, waitFor } from '@solidjs/testing-library' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +describe('public presentation lane contracts', () => { + test('a plain load retry presents pending UI over a committed error', async () => { + const retryStarted = createControlledPromise() + const retry = createControlledPromise() + let attempt = 0 + + const rootRoute = createRootRoute({ component: () => }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: () =>
    Retrying page
    , + loader: () => { + if (!attempt++) { + throw new Error('Initial failure') + } + retryStarted.resolve() + return retry + }, + errorComponent: () =>
    Page failed
    , + component: () =>
    {pageRoute.useLoaderData()()}
    , + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([pageRoute]), + history: createMemoryHistory({ initialEntries: ['/page'] }), + }) + const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + render(() => ) + expect(await screen.findByText('Page failed')).toBeInTheDocument() + + let retryLoad!: Promise + try { + retryLoad = router.load() + await retryStarted + expect(await screen.findByText('Retrying page')).toBeInTheDocument() + expect(screen.queryByText('Page failed')).not.toBeInTheDocument() + + retry.resolve('Page recovered') + await retryLoad + expect(screen.getByText('Page recovered')).toBeInTheDocument() + } finally { + retry.resolve('Page recovered') + await retryLoad + consoleWarn.mockRestore() + } + }) + + test('same-boundary takeover republishes successor search without restarting pendingMinMs', async () => { + const firstGate = createControlledPromise() + const secondGate = createControlledPromise() + + const rootRoute = createRootRoute({ component: () => }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + validateSearch: (search: Record) => ({ + revision: Number(search.revision), + }), + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    Loading page
    , + beforeLoad: ({ search }) => + search.revision === 1 ? firstGate : secondGate, + component: () => { + const search = pageRoute.useSearch() + return
    Page revision {search().revision}
    + }, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + expect(await screen.findByText('Home')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + + vi.useFakeTimers() + vi.setSystemTime(0) + + let successorSettled = false + let settledAtOriginalDeadline = false + let renderedAtOriginalDeadline = false + try { + void router.navigate({ + to: '/page', + search: { revision: 1 }, + }) + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByText('Loading page')).toBeInTheDocument() + expect(router.state.matches.at(-1)?.search).toMatchObject({ revision: 1 }) + + await vi.advanceTimersByTimeAsync(25) + + const secondNavigation = router.navigate({ + to: '/page', + search: { revision: 2 }, + }) + await vi.advanceTimersByTimeAsync(0) + + expect(screen.getByText('Loading page')).toBeInTheDocument() + expect(router.state.location.search).toMatchObject({ revision: 2 }) + expect(router.state.matches.at(-1)?.search).toMatchObject({ revision: 2 }) + + void secondNavigation.then(() => { + successorSettled = true + }) + secondGate.resolve() + await Promise.resolve() + + await vi.advanceTimersByTimeAsync(74) + expect(successorSettled).toBe(false) + expect(screen.getByText('Loading page')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(5) + await Promise.resolve() + + settledAtOriginalDeadline = successorSettled + renderedAtOriginalDeadline = + screen.queryByText('Page revision 2') !== null + } finally { + firstGate.resolve() + secondGate.resolve() + await vi.advanceTimersByTimeAsync(1_000) + await Promise.resolve() + } + + expect({ + settled: settledAtOriginalDeadline, + rendered: renderedAtOriginalDeadline, + }).toEqual({ settled: true, rendered: true }) + expect(screen.getByText('Page revision 2')).toBeInTheDocument() + expect(screen.queryByText('Loading page')).not.toBeInTheDocument() + }) + + test('an earlier pending-ineligible boundary retires a deeper pending minimum', async () => { + const childReloadStarted = createControlledPromise() + const childReload = createControlledPromise() + const parentReloadStarted = createControlledPromise() + const parentReload = createControlledPromise() + let childLoads = 0 + + const rootRoute = createRootRoute({ + validateSearch: (search: Record) => ({ + revision: Number(search.revision), + }), + component: () => , + }) + const parentRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/parent', + loaderDeps: ({ search }) => ({ revision: search.revision }), + beforeLoad: ({ search }) => { + if (search.revision === 2) { + parentReloadStarted.resolve() + return parentReload + } + return undefined + }, + component: () => , + }) + const childRoute = createRoute({ + getParentRoute: () => parentRoute, + path: '/child', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    Loading child
    , + loader: { + staleReloadMode: 'blocking', + handler: () => { + if (childLoads++) { + childReloadStarted.resolve() + return childReload + } + return undefined + }, + }, + component: () => ( +
    Child revision {childRoute.useSearch()().revision}
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([parentRoute.addChildren([childRoute])]), + history: createMemoryHistory({ + initialEntries: ['/parent/child?revision=1'], + }), + }) + + render(() => ) + expect(await screen.findByText('Child revision 1')).toBeInTheDocument() + await waitFor(() => expect(router.state.status).toBe('idle')) + vi.useFakeTimers() + vi.setSystemTime(0) + + let firstNavigation: Promise | undefined + let secondNavigation: Promise | undefined + let settledBeforeOldMinimum = false + let renderedBeforeOldMinimum = false + try { + firstNavigation = router.invalidate({ + filter: (match) => match.routeId === childRoute.id, + forcePending: true, + }) + await childReloadStarted + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByText('Loading child')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(25) + secondNavigation = router.navigate({ + to: '/parent/child', + search: { revision: 2 }, + }) + await parentReloadStarted + expect(screen.getByText('Loading child')).toBeInTheDocument() + + childReload.resolve() + + const successor = secondNavigation + void successor.then(() => { + settledBeforeOldMinimum = true + }) + parentReload.resolve() + await vi.advanceTimersByTimeAsync(5) + renderedBeforeOldMinimum = screen.queryByText('Child revision 2') !== null + } finally { + childReload.resolve() + parentReload.resolve() + await vi.advanceTimersByTimeAsync(1_000) + await Promise.allSettled( + [firstNavigation, secondNavigation].filter( + (navigation): navigation is Promise => !!navigation, + ), + ) + } + + expect({ + settled: settledBeforeOldMinimum, + rendered: renderedBeforeOldMinimum, + }).toEqual({ settled: true, rendered: true }) + }) + + test('same-boundary timing survives a private retained-context barrier', async () => { + const retainedStarted = createControlledPromise() + const retainedReady = createControlledPromise() + const firstPage = createControlledPromise() + const secondPageStarted = createControlledPromise() + const secondPage = createControlledPromise() + + const rootRoute = createRootRoute({ + validateSearch: (search: Record) => ({ + revision: Number(search.revision) || 0, + }), + beforeLoad: ({ search }) => { + if (search.revision === 2) { + retainedStarted.resolve() + return retainedReady.then(() => ({ rootRevision: 2 })) + } + return { rootRevision: search.revision } + }, + component: () => { + const rootRevision = rootRoute.useRouteContext({ + select: (context) => context.rootRevision, + }) + return ( +
    +
    Root revision {rootRevision()}
    + +
    + ) + }, + }) + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Home
    , + }) + const pageRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/page', + pendingMs: 0, + pendingMinMs: 100, + pendingComponent: () =>
    Loading page
    , + beforeLoad: ({ search }) => { + if (search.revision === 1) { + return firstPage + } + secondPageStarted.resolve() + return secondPage + }, + component: () => ( +
    Page revision {pageRoute.useSearch()().revision}
    + ), + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, pageRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + expect(await screen.findByText('Home')).toBeInTheDocument() + vi.useFakeTimers() + vi.setSystemTime(0) + + let firstNavigation: Promise | undefined + let secondNavigation: Promise | undefined + try { + firstNavigation = router.navigate({ + to: '/page', + search: { revision: 1 }, + }) + await vi.advanceTimersByTimeAsync(0) + expect(screen.getByText('Loading page')).toBeInTheDocument() + expect(screen.getByText('Root revision 1')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(25) + secondNavigation = router.navigate({ + to: '/page', + search: { revision: 2 }, + }) + await retainedStarted + + expect(screen.getByText('Loading page')).toBeInTheDocument() + expect(screen.getByText('Root revision 1')).toBeInTheDocument() + + retainedReady.resolve() + await secondPageStarted + expect(screen.getByText('Loading page')).toBeInTheDocument() + expect(screen.getByText('Root revision 2')).toBeInTheDocument() + + let settled = false + const successor = secondNavigation + void successor.then(() => { + settled = true + }) + secondPage.resolve() + await vi.advanceTimersByTimeAsync(74) + expect(settled).toBe(false) + expect(screen.getByText('Loading page')).toBeInTheDocument() + + await vi.advanceTimersByTimeAsync(5) + await Promise.all([firstNavigation, successor]) + expect(screen.getByText('Page revision 2')).toBeInTheDocument() + } finally { + retainedReady.resolve() + firstPage.resolve() + secondPage.resolve() + await vi.advanceTimersByTimeAsync(1_000) + await Promise.allSettled( + [firstNavigation, secondNavigation].filter( + (navigation): navigation is Promise => !!navigation, + ), + ) + } + }) + + test('a successor supersedes the previous receipt while joining its transition', async () => { + const firstRenderStarted = createControlledPromise() + const firstRender = createControlledPromise() + const secondRenderStarted = createControlledPromise() + const secondRender = createControlledPromise() + let setRevision!: Solid.Setter + + const Revision = (props: { revision: number }) => { + const [rendered] = Solid.createResource(async () => { + if (props.revision === 2) { + firstRenderStarted.resolve() + await firstRender + } else if (props.revision === 3) { + secondRenderStarted.resolve() + await secondRender + } + return props.revision + }) + return
    Revision {rendered()}
    + } + const rootRoute = createRootRoute({ + component: () => { + const [revision, set] = Solid.createSignal(1) + setRevision = set + return ( + + {(value) => } + + ) + }, + }) + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + render(() => ) + expect(await screen.findByText('Revision 1')).toBeInTheDocument() + + const expected = router.state.matches + const firstAcknowledgement = router.startTransition( + () => setRevision(2), + expected, + ) + const acknowledgements = [firstAcknowledgement] + try { + await firstRenderStarted + const secondAcknowledgement = router.startTransition( + () => setRevision(3), + expected, + ) + acknowledgements.push(secondAcknowledgement) + + await expect(firstAcknowledgement).resolves.toBe(false) + await secondRenderStarted + expect(screen.getByText('Revision 1')).toBeInTheDocument() + + let secondSettled = false + void secondAcknowledgement.then(() => { + secondSettled = true + }) + secondRender.resolve() + await Promise.resolve() + await Promise.resolve() + + expect(secondSettled).toBe(false) + expect(screen.queryByText('Revision 3')).not.toBeInTheDocument() + + firstRender.resolve() + await expect(secondAcknowledgement).resolves.toBe(true) + expect(await screen.findByText('Revision 3')).toBeInTheDocument() + expect(screen.queryByText('Revision 2')).not.toBeInTheDocument() + } finally { + firstRender.resolve() + secondRender.resolve() + await Promise.allSettled(acknowledgements) + } + }) +}) diff --git a/packages/solid-router/tests/redirect.test.tsx b/packages/solid-router/tests/redirect.test.tsx index f9f7c28085..2192f4f962 100644 --- a/packages/solid-router/tests/redirect.test.tsx +++ b/packages/solid-router/tests/redirect.test.tsx @@ -1,13 +1,13 @@ import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library' import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' -import invariant from 'tiny-invariant' import { Link, + Outlet, RouterProvider, createBrowserHistory, - createMemoryHistory, createRootRoute, createRoute, createRouter, @@ -105,6 +105,61 @@ describe('redirect', () => { expect(nestedFooLoaderMock).toHaveBeenCalled() }) + test('when root `beforeLoad` redirects while root pendingComponent is showing and the target route is lazy', async () => { + let hasRedirected = false + const beforeLoad = createControlledPromise() + const consoleError = vi + .spyOn(console, 'error') + .mockImplementation(() => {}) + + const rootRoute = createRootRoute({ + component: () => , + pendingMs: 0, + pendingComponent: () =>
    loading
    , + beforeLoad: async () => { + await beforeLoad + if (!hasRedirected) { + hasRedirected = true + throw redirect({ to: '/posts' }) + } + }, + }) + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>
    Index page
    , + }) + + const postsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/posts', + }).lazy(() => import('./lazy/normal').then((d) => d.Route('/posts'))) + + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, postsRoute]), + history, + }) + + render(() => ) + + try { + expect(await screen.findByTestId('pending')).toBeInTheDocument() + expect(screen.queryByTestId('index-page')).not.toBeInTheDocument() + } finally { + beforeLoad.resolve() + } + + // The lazy target route adds the async boundary that exposes the stale + // redirected-match render path this regression is guarding. + expect(await screen.findByTestId('lazy-route-page')).toBeInTheDocument() + expect(screen.queryByTestId('pending')).not.toBeInTheDocument() + expect(screen.queryByTestId('index-page')).not.toBeInTheDocument() + expect(router.state.location.href).toBe('/posts') + await vi.waitFor(() => expect(router.state.status).toBe('idle')) + expect(consoleError).not.toHaveBeenCalled() + }) + test('when `redirect` is thrown in `loader`', async () => { const nestedLoaderMock = vi.fn() const nestedFooLoaderMock = vi.fn() @@ -257,116 +312,4 @@ describe('redirect', () => { expect(window.location.pathname).toBe('/final') }) }) - - describe('SSR', () => { - test('when `redirect` is thrown in `beforeLoad`', async () => { - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - beforeLoad: () => { - throw redirect({ - to: '/about', - }) - }, - }) - - const aboutRoute = createRoute({ - path: '/about', - getParentRoute: () => rootRoute, - component: () => { - return 'About' - }, - }) - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), - // Mock server mode - isServer: true, - history: createMemoryHistory({ - initialEntries: ['/'], - }), - }) - - await router.load() - - expect(router.state.redirect).toBeDefined() - expect(router.state.redirect).toBeInstanceOf(Response) - invariant(router.state.redirect) - - expect(router.state.redirect.options).toEqual({ - _fromLocation: expect.objectContaining({ - hash: '', - href: '/', - pathname: '/', - search: {}, - searchStr: '', - }), - to: '/about', - href: '/about', - statusCode: 307, - }) - }) - }) - - test('when `redirect` is thrown in `loader`', async () => { - const rootRoute = createRootRoute() - - const indexRoute = createRoute({ - path: '/', - getParentRoute: () => rootRoute, - loader: () => { - throw redirect({ - to: '/about', - }) - }, - }) - - const aboutRoute = createRoute({ - path: '/about', - getParentRoute: () => rootRoute, - component: () => { - return 'About' - }, - }) - - const router = createRouter({ - history: createMemoryHistory({ - initialEntries: ['/'], - }), - routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), - // Mock server mode - isServer: true, - }) - - await router.load() - - const currentRedirect = router.state.redirect - - expect(currentRedirect).toBeDefined() - expect(currentRedirect).toBeInstanceOf(Response) - invariant(currentRedirect) - expect(currentRedirect.status).toEqual(307) - expect(currentRedirect.headers.get('Location')).toEqual('/about') - expect(currentRedirect.options).toEqual({ - _fromLocation: { - publicHref: '/', - url: new URL('http://localhost/'), - hash: '', - href: '/', - pathname: '/', - search: {}, - searchStr: '', - state: { - __TSR_index: 0, - __TSR_key: currentRedirect.options._fromLocation!.state.__TSR_key, - key: currentRedirect.options._fromLocation!.state.key, - }, - }, - href: '/about', - to: '/about', - statusCode: 307, - }) - }) }) diff --git a/packages/solid-router/tests/remountDeps.test.tsx b/packages/solid-router/tests/remountDeps.test.tsx new file mode 100644 index 0000000000..991ee786f3 --- /dev/null +++ b/packages/solid-router/tests/remountDeps.test.tsx @@ -0,0 +1,99 @@ +import * as Solid from 'solid-js' +import { cleanup, render, screen } from '@solidjs/testing-library' +import { afterEach, expect, test, vi } from 'vitest' +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(() => { + cleanup() +}) + +function setup(remountOnParams: boolean | 'falsy' = false) { + const mounted = vi.fn() + const unmounted = vi.fn() + const rootRoute = createRootRoute({ component: () => }) + + function ItemComponent() { + const params = itemRoute.useParams() + + Solid.onMount(mounted) + Solid.onCleanup(unmounted) + + return
    Item {params().itemId}
    + } + + const itemRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/items/$itemId', + component: ItemComponent, + remountDeps: + remountOnParams === 'falsy' + ? ({ params }) => (params.itemId === 'one' ? false : 0) + : remountOnParams + ? ({ params }) => params + : undefined, + }) + const router = createRouter({ + routeTree: rootRoute.addChildren([itemRoute]), + history: createMemoryHistory({ initialEntries: ['/items/one'] }), + }) + + render(() => ) + + return { mounted, router, unmounted } +} + +async function navigateToSecondItem( + router: ReturnType['router'], +) { + await router.navigate({ + to: '/items/$itemId', + params: { itemId: 'two' }, + }) +} + +test('keeps an active route component mounted when params change by default', async () => { + const { mounted, router, unmounted } = setup() + + expect(await screen.findByText('Item one')).toBeInTheDocument() + expect(mounted).toHaveBeenCalledTimes(1) + expect(unmounted).not.toHaveBeenCalled() + + await navigateToSecondItem(router) + + expect(await screen.findByText('Item two')).toBeInTheDocument() + expect(mounted).toHaveBeenCalledTimes(1) + expect(unmounted).not.toHaveBeenCalled() +}) + +test('remounts an active route component when params are remount deps', async () => { + const { mounted, router, unmounted } = setup(true) + + expect(await screen.findByText('Item one')).toBeInTheDocument() + expect(mounted).toHaveBeenCalledTimes(1) + + await navigateToSecondItem(router) + + expect(await screen.findByText('Item two')).toBeInTheDocument() + expect(mounted).toHaveBeenCalledTimes(2) + expect(unmounted).toHaveBeenCalledTimes(1) +}) + +test('remounts when remount deps change between falsy values', async () => { + const { mounted, router, unmounted } = setup('falsy') + + expect(await screen.findByText('Item one')).toBeInTheDocument() + expect(mounted).toHaveBeenCalledTimes(1) + + await navigateToSecondItem(router) + + expect(await screen.findByText('Item two')).toBeInTheDocument() + expect(mounted).toHaveBeenCalledTimes(2) + expect(unmounted).toHaveBeenCalledTimes(1) +}) diff --git a/packages/solid-router/tests/renderRouterToStream.test.tsx b/packages/solid-router/tests/renderRouterToStream.test.tsx new file mode 100644 index 0000000000..5986fea88b --- /dev/null +++ b/packages/solid-router/tests/renderRouterToStream.test.tsx @@ -0,0 +1,432 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { attachRouterServerSsrUtils } from '@tanstack/router-core/ssr/server' +import { createMemoryHistory, createRootRoute, createRouter } from '../src' +import type * as RouterSsrServer from '@tanstack/router-core/ssr/server' +import type * as SolidWeb from 'solid-js/web' + +const solidMocks = vi.hoisted(() => ({ + renderToStream: vi.fn(), + pipeTo: vi.fn(), +})) +const routerTransformMocks = vi.hoisted(() => ({ + readableOptions: vi.fn(), +})) + +vi.mock('@tanstack/router-core/ssr/server', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + transformReadableStreamWithRouter: ( + ...args: Parameters + ) => { + routerTransformMocks.readableOptions(args[2]) + return actual.transformReadableStreamWithRouter(...args) + }, + } +}) + +vi.mock('solid-js/web', async () => { + const actual = await vi.importActual('solid-js/web') + return { + ...actual, + renderToStream: solidMocks.renderToStream, + } +}) + +// Imported after mock so the wrapper picks up the mocked binding. +const { renderRouterToStream } = await import('../src/ssr/renderRouterToStream') + +function unwrapResponse( + result: Awaited>, +) { + return result.response +} + +afterEach(() => { + solidMocks.renderToStream.mockReset() + solidMocks.pipeTo.mockReset() + routerTransformMocks.readableOptions.mockReset() + vi.restoreAllMocks() +}) + +async function buildRouter() { + const rootRoute = createRootRoute({ + component: () => null, + }) + const router = createRouter({ + history: createMemoryHistory({ initialEntries: ['/'] }), + routeTree: rootRoute, + }) + router.isServer = true + attachRouterServerSsrUtils({ router, manifest: undefined }) + await router.load() + return router +} + +function drainBody(response: Response) { + const reader = response.body!.getReader() + return (async () => { + for (;;) { + const { done } = await reader.read() + if (done) { + return true + } + } + })().catch(() => true) +} + +describe('renderRouterToStream', () => { + test('already-aborted requests do not start the Solid producer', async () => { + const abortController = new AbortController() + abortController.abort(new Error('already-gone')) + const router = await buildRouter() + + await expect( + renderRouterToStream({ + request: new Request('http://localhost/', { + signal: abortController.signal, + }), + router, + responseHeaders: new Headers(), + children: () => null, + }), + ).rejects.toThrow('already-gone') + + expect(solidMocks.renderToStream).not.toHaveBeenCalled() + expect(router.serverSsr).toBeUndefined() + }) + + test('request abort during bot wait terminates before piping starts', async () => { + const neverReady = new Promise(() => {}) + solidMocks.renderToStream.mockImplementationOnce( + () => + ({ + then: neverReady.then.bind(neverReady), + pipeTo: solidMocks.pipeTo, + }) as any, + ) + + const router = await buildRouter() + const abortController = new AbortController() + const reason = new Error('client-gone') + try { + const responsePromise = renderRouterToStream({ + request: new Request('http://localhost/', { + headers: { 'User-Agent': 'Googlebot' }, + signal: abortController.signal, + }), + router, + responseHeaders: new Headers(), + children: () => null, + }) + + await Promise.resolve() + abortController.abort(reason) + + await expect(responsePromise).rejects.toBe(reason) + expect(solidMocks.pipeTo).not.toHaveBeenCalled() + expect(router.serverSsr).toBeUndefined() + } finally { + router.serverSsr?.cleanup() + } + }) + + test.each(['lifetime expiry', 'external cleanup'] as const)( + '%s rejects the bot wait and prevents late piping', + async (termination) => { + let resolveReady!: () => void + const ready = new Promise((resolve) => { + resolveReady = resolve + }) + solidMocks.renderToStream.mockImplementationOnce( + () => + ({ + then: ready.then.bind(ready), + pipeTo: solidMocks.pipeTo, + }) as any, + ) + const router = await buildRouter() + const owner = router.serverSsr! + const cleanup = vi.fn() + owner.onCleanup(cleanup) + const request = new Request('http://localhost/', { + headers: { 'User-Agent': 'Googlebot' }, + }) + const resolved = vi.fn() + const rejected = vi.fn() + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.useFakeTimers() + const pending = renderRouterToStream({ + request, + router, + responseHeaders: new Headers(), + children: () => null, + }).then(resolved, rejected) + + try { + await Promise.resolve() + expect(rejected).not.toHaveBeenCalled() + if (termination === 'lifetime expiry') { + await vi.advanceTimersByTimeAsync(120_000) + } else { + owner.cleanup() + await vi.advanceTimersByTimeAsync(0) + } + + expect(rejected).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + message: + termination === 'lifetime expiry' + ? 'Stream lifetime exceeded' + : 'SSR stream transform aborted by router SSR cleanup', + }), + ) + expect(request.signal.aborted).toBe(false) + expect(cleanup).toHaveBeenCalledOnce() + expect(router.serverSsr).toBeUndefined() + expect(solidMocks.pipeTo).not.toHaveBeenCalled() + + resolveReady() + await vi.advanceTimersByTimeAsync(0) + expect(resolved).not.toHaveBeenCalled() + expect(solidMocks.pipeTo).not.toHaveBeenCalled() + } finally { + resolveReady() + await pending + owner.cleanup() + vi.useRealTimers() + warn.mockRestore() + } + }, + ) + + test('bots wait for renderer readiness before piping', async () => { + let resolveReady!: () => void + const ready = new Promise((resolve) => { + resolveReady = resolve + }) + solidMocks.renderToStream.mockImplementationOnce( + () => + ({ + then: ready.then.bind(ready), + pipeTo: solidMocks.pipeTo.mockImplementation( + () => new Promise(() => {}), + ), + }) as any, + ) + const router = await buildRouter() + try { + let settled = false + const responsePromise = renderRouterToStream({ + request: new Request('http://localhost/', { + headers: { 'User-Agent': 'Googlebot' }, + }), + router, + responseHeaders: new Headers(), + children: () => null, + }).then((result) => { + settled = true + return result + }) + + await Promise.resolve() + expect(settled).toBe(false) + expect(solidMocks.pipeTo).not.toHaveBeenCalled() + + resolveReady() + const result = await responsePromise + expect(unwrapResponse(result)).toBeInstanceOf(Response) + expect(solidMocks.pipeTo).toHaveBeenCalledOnce() + } finally { + router.serverSsr?.cleanup() + } + }) + + test('bot response does not wait for a backpressured pipe', async () => { + const html = new TextEncoder().encode( + 'solid', + ) + let pipeCompletion: Promise | undefined + solidMocks.renderToStream.mockImplementationOnce( + () => + ({ + then(resolve: () => void) { + resolve() + }, + pipeTo(writable: WritableStream) { + const writer = writable.getWriter() + pipeCompletion = writer.write(html).then(() => writer.close()) + return pipeCompletion + }, + }) as any, + ) + + const router = await buildRouter() + router.serverSsr!.disableHydration() + try { + const result = await renderRouterToStream({ + request: new Request('http://localhost/', { + headers: { 'User-Agent': 'Googlebot' }, + }), + router, + responseHeaders: new Headers(), + children: () => null, + }) + + expect(pipeCompletion).toBeDefined() + const response = unwrapResponse(result) + await expect(response.text()).resolves.toBe( + new TextDecoder().decode(html), + ) + await expect(pipeCompletion).resolves.toBeUndefined() + } finally { + router.serverSsr?.cleanup() + } + }) + + test.each([ + ['ordinary', new Error('solid-pipe-failed')], + [ + 'named AbortError', + Object.assign(new Error('solid-pipe-aborted'), { name: 'AbortError' }), + ], + ] as const)( + '%s pipeTo rejection logs, aborts the writer, and terminates the response', + async (_kind, pipeError) => { + solidMocks.renderToStream.mockImplementationOnce( + () => + ({ + pipeTo: () => Promise.reject(pipeError), + }) as any, + ) + + const router = await buildRouter() + const request = new Request('http://localhost/') + const addEventListener = vi.spyOn(request.signal, 'addEventListener') + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + const response = unwrapResponse( + await renderRouterToStream({ + request, + router, + responseHeaders: new Headers(), + children: () => null, + }), + ) + expect(routerTransformMocks.readableOptions).toHaveBeenCalledWith( + expect.objectContaining({ rendererSafePoint: 'record-end' }), + ) + expect( + addEventListener.mock.calls.filter(([type]) => type === 'abort'), + ).toHaveLength(1) + + expect(await drainBody(response)).toBe(true) + expect(errorSpy).toHaveBeenCalledWith( + 'Error in Solid render stream:', + pipeError, + ) + } finally { + errorSpy.mockRestore() + router.serverSsr?.cleanup() + } + }, + ) + + test('async pipe failure cleans an unread response immediately', async () => { + let rejectPipe!: (reason: unknown) => void + const pipeCompletion = new Promise((_resolve, reject) => { + rejectPipe = reject + }) + solidMocks.renderToStream.mockImplementationOnce( + () => ({ pipeTo: () => pipeCompletion }) as any, + ) + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const router = await buildRouter() + try { + const result = await renderRouterToStream({ + request: new Request('http://localhost/'), + router, + responseHeaders: new Headers(), + children: () => null, + }) + expect(unwrapResponse(result).body).not.toBeNull() + + rejectPipe(new Error('solid-pipe-failed-unread')) + await vi.waitFor(() => expect(router.serverSsr).toBeUndefined()) + } finally { + errorSpy.mockRestore() + router.serverSsr?.cleanup() + } + }) + + test('request abort after attachment stops outgoing Solid writes', async () => { + let outboundWriter!: WritableStreamDefaultWriter + solidMocks.pipeTo.mockImplementationOnce( + (writable: WritableStream) => { + outboundWriter = writable.getWriter() + return new Promise(() => {}) + }, + ) + solidMocks.renderToStream.mockImplementationOnce( + () => ({ pipeTo: solidMocks.pipeTo }) as any, + ) + + const router = await buildRouter() + const abortController = new AbortController() + const request = new Request('http://localhost/', { + signal: abortController.signal, + }) + const addEventListener = vi.spyOn(request.signal, 'addEventListener') + try { + const response = unwrapResponse( + await renderRouterToStream({ + request, + router, + responseHeaders: new Headers(), + children: () => null, + }), + ) + + expect(solidMocks.pipeTo).toHaveBeenCalledOnce() + expect( + addEventListener.mock.calls.filter(([type]) => type === 'abort'), + ).toHaveLength(1) + abortController.abort(new Error('solid-request-gone')) + + await expect( + outboundWriter.write(new TextEncoder().encode('late Solid chunk')), + ).rejects.toBeDefined() + + expect(await drainBody(response)).toBe(true) + } finally { + router.serverSsr?.cleanup() + } + }) + + test('request abort during renderer setup is caught before transform attachment', async () => { + const abortController = new AbortController() + solidMocks.renderToStream.mockImplementationOnce(() => { + abortController.abort(new Error('solid-setup-request-gone')) + return { pipeTo: solidMocks.pipeTo } as any + }) + + const router = await buildRouter() + try { + await expect( + renderRouterToStream({ + request: new Request('http://localhost/', { + signal: abortController.signal, + }), + router, + responseHeaders: new Headers(), + children: () => null, + }), + ).rejects.toThrow('solid-setup-request-gone') + + expect(solidMocks.pipeTo).not.toHaveBeenCalled() + expect(router.serverSsr).toBeUndefined() + } finally { + router.serverSsr?.cleanup() + } + }) +}) diff --git a/packages/solid-router/tests/route.test-d.tsx b/packages/solid-router/tests/route.test-d.tsx index 3cdc65bb1d..f2dfcada86 100644 --- a/packages/solid-router/tests/route.test-d.tsx +++ b/packages/solid-router/tests/route.test-d.tsx @@ -44,6 +44,7 @@ test('when creating the root with routeContext', () => { context: {} deps: {} matches: Array + routeId: '__root__' }>() }, }) @@ -67,6 +68,7 @@ test('when creating the root with beforeLoad', () => { context: {} search: {} matches: Array + routeId: '__root__' }>() }, }) @@ -114,6 +116,7 @@ test('when creating the root route with context and routeContext', () => { context: { userId: string } deps: {} matches: Array + routeId: '__root__' }>() }, }) @@ -156,6 +159,7 @@ test('when creating the root route with context and beforeLoad', () => { context: { userId: string } search: {} matches: Array + routeId: '__root__' }>() }, }) @@ -240,6 +244,7 @@ test('when creating the root route with context, routeContext, beforeLoad and a context: { userId: string } deps: {} matches: Array + routeId: '__root__' }>() return { @@ -258,6 +263,7 @@ test('when creating the root route with context, routeContext, beforeLoad and a context: { userId: string; env: 'env1' } search: {} matches: Array + routeId: '__root__' }>() return { permission: 'view' as const } }, @@ -365,6 +371,7 @@ test('when creating a child route with routeContext from the root route with con context: { userId: string } deps: {} matches: Array + routeId: '/invoices' }>() return { @@ -392,6 +399,7 @@ test('when creating a child route with beforeLoad from the root route with conte context: { userId: string } search: {} matches: Array + routeId: '/invoices' }>() }, }) @@ -727,6 +735,7 @@ test('when creating a child route with params, search with routeContext from the context: { userId: string } deps: {} matches: Array + routeId: '/invoices/$invoiceId' }>() }, }) @@ -775,6 +784,7 @@ test('when creating a child route with params, search with routeContext, beforeL context: { userId: string } deps: {} matches: Array + routeId: '/invoices/$invoiceId' }>() return { env: 'env1', @@ -792,6 +802,7 @@ test('when creating a child route with params, search with routeContext, beforeL context: { userId: string; env: string } search: { page: number } matches: Array + routeId: '/invoices/$invoiceId' }>() return { permission: 'view' } as const }, @@ -903,6 +914,7 @@ test('when creating a child route with routeContext from a parent with routeCont context: { userId: string } deps: {} matches: Array + routeId: '/invoices' }>() return { invoiceId: 'invoiceId1' } @@ -924,6 +936,7 @@ test('when creating a child route with routeContext from a parent with routeCont context: { userId: string; invoiceId: string } deps: {} matches: Array + routeId: '/invoices/details' }>() return { detailId: 'detailId1' } @@ -977,6 +990,7 @@ test('when creating a child route with beforeLoad from a parent with beforeLoad' context: { userId: string } search: {} matches: Array + routeId: '/invoices' }>() return { invoiceId: 'invoiceId1' } }, @@ -997,6 +1011,7 @@ test('when creating a child route with beforeLoad from a parent with beforeLoad' context: { userId: string; invoiceId: string } search: {} matches: Array + routeId: '/invoices/details' }>() return { detailId: 'detailId1' } }, @@ -1050,6 +1065,7 @@ test('when creating a child route with routeContext, beforeLoad, search, params, context: { userId: string } deps: {} matches: Array + routeId: '/invoices' }>() return { env: 'env1' } }, @@ -1065,6 +1081,7 @@ test('when creating a child route with routeContext, beforeLoad, search, params, context: { userId: string; env: string } search: { page: number } matches: Array + routeId: '/invoices' }>() return { invoicePermissions: ['view'] as const } }, @@ -1095,6 +1112,7 @@ test('when creating a child route with routeContext, beforeLoad, search, params, } deps: {} matches: Array + routeId: '/invoices/$invoiceId/details' }>() return { detailEnv: 'detailEnv' } }, @@ -1115,6 +1133,7 @@ test('when creating a child route with routeContext, beforeLoad, search, params, } search: { page: number; detailPage: number } matches: Array + routeId: '/invoices/$invoiceId/details' }>() return { detailsPermissions: ['view'] as const } }, @@ -1145,6 +1164,7 @@ test('when creating a child route with routeContext, beforeLoad, search, params, } deps: { detailPage: number; invoicePage: number } matches: Array + routeId: '/invoices/$invoiceId/details/$detailId' }>() return { detailEnv: 'detailEnv' } }, diff --git a/packages/solid-router/tests/routeApi.test-d.tsx b/packages/solid-router/tests/routeApi.test-d.tsx index 2a1095ccd4..e6770e2652 100644 --- a/packages/solid-router/tests/routeApi.test-d.tsx +++ b/packages/solid-router/tests/routeApi.test-d.tsx @@ -63,6 +63,12 @@ describe('getRouteApi', () => { invoiceId: string }> >() + + expectTypeOf( + invoiceRouteApi.useParams({ + shouldThrow: false, + }), + ).toEqualTypeOf>() }) test('useContext', () => { expectTypeOf( @@ -79,6 +85,12 @@ describe('getRouteApi', () => { page: number }> >() + + expectTypeOf( + invoiceRouteApi.useSearch({ + shouldThrow: false, + }), + ).toEqualTypeOf>() }) test('useLoaderData', () => { expectTypeOf(invoiceRouteApi.useLoaderData()).toEqualTypeOf< @@ -98,6 +110,16 @@ describe('getRouteApi', () => { expectTypeOf(invoiceRouteApi.useMatch()).toEqualTypeOf< Accessor> >() + + expectTypeOf( + invoiceRouteApi.useMatch({ + shouldThrow: false, + }), + ).toEqualTypeOf< + Accessor< + MakeRouteMatch | undefined + > + >() }) test('Link', () => { const Link = invoiceRouteApi.Link diff --git a/packages/solid-router/tests/routeContext.test.tsx b/packages/solid-router/tests/routeContext.test.tsx index b7e0a902a9..fdee696bf8 100644 --- a/packages/solid-router/tests/routeContext.test.tsx +++ b/packages/solid-router/tests/routeContext.test.tsx @@ -133,7 +133,7 @@ describe('context function', () => { }) test('when loader deps change', async () => { - const mockContextFn = vi.fn() + let generation = 0 const rootRoute = createRootRoute() const indexRoute = createRoute({ @@ -145,14 +145,21 @@ describe('context function', () => { path: '/', loaderDeps: ({ search }) => ({ foo: search.foo }), context: ({ deps }) => { - mockContextFn(deps) + return { + generation: ++generation, + deps: JSON.stringify(deps), + } }, component: () => { const navigate = indexRoute.useNavigate() + const context = indexRoute.useRouteContext() return (

    Index page

    search: {JSON.stringify(indexRoute.useSearch()())}

    +

    + context: {context().generation}:{context().deps} +

    + + ) +} +``` + +Unlike the React version, `useServerFn` does NOT wrap the returned function in any memoization (no `useCallback` equivalent needed — Solid's `setup` runs once). + +## Solid-Specific Components + +All routing components from `@tanstack/solid-router` work in Start: + +- `` — renders matched child route +- `` — type-safe navigation +- `` — declarative redirect +- `` — renders head tags via `@solidjs/meta` (must be in `` — uses portals to inject into ``) +- `` — renders body scripts (must be in ``) +- `` — renders deferred data with `` +- `` — renders children only after hydration +- `` — error boundary wrapping `Solid.ErrorBoundary` + +## Hooks Reference + +All hooks from `@tanstack/solid-router` work in Start. Most return `Accessor` — call the accessor to read: + +- `useRouter()` — router instance (NOT an Accessor) +- `useRouterState()` — `Accessor`, subscribe to router state +- `useNavigate()` — navigation function (NOT an Accessor) +- `useSearch({ from })` — `Accessor`, validated search params +- `useParams({ from })` — `Accessor`, path params +- `useLoaderData({ from })` — `Accessor`, loader data +- `useMatch({ from })` — `Accessor`, full route match +- `useRouteContext({ from })` — `Accessor`, route context +- `Route.useLoaderData()` — `Accessor`, typed loader data (preferred in route files) +- `Route.useSearch()` — `Accessor`, typed search params (preferred in route files) + +## Common Mistakes + +### 1. CRITICAL: Importing from wrong package + +```tsx +// WRONG — this is the SPA router, NOT Start +import { createServerFn } from '@tanstack/solid-router' + +// CORRECT — server functions come from solid-start +import { createServerFn } from '@tanstack/solid-start' + +// CORRECT — routing APIs come from solid-router (re-exported by Start too) +import { createFileRoute, Link } from '@tanstack/solid-router' +``` + +### 2. CRITICAL: Forgetting to call Accessor + +Most hooks return `Accessor`. Must call to read the value. + +```tsx +// WRONG +const data = Route.useLoaderData() +return

    {data.message}

    + +// CORRECT +const data = Route.useLoaderData() +return

    {data().message}

    +``` + +### 3. HIGH: Missing Scripts component + +Without `` in the root route's ``, client JavaScript doesn't load and the app won't hydrate. + +### 4. HIGH: Solid plugin before Start plugin in Vite config + +```ts +// WRONG +plugins: [solidPlugin(), tanstackStart()] + +// CORRECT +plugins: [tanstackStart(), solidPlugin()] +``` + +## Cross-References + +- `@tanstack/start-client-core#start-core` — core Start concepts +- `@tanstack/router-core#router-core` — routing fundamentals +- `@tanstack/solid-router#solid-router` — Solid Router hooks and components diff --git a/packages/solid-start/src/client-only.ts b/packages/solid-start/src/client-only.ts new file mode 100644 index 0000000000..336ce12bb9 --- /dev/null +++ b/packages/solid-start/src/client-only.ts @@ -0,0 +1 @@ +export {} diff --git a/packages/solid-start/src/default-entry/server.ts b/packages/solid-start/src/default-entry/server.ts index b8f3105c6a..ae38924363 100644 --- a/packages/solid-start/src/default-entry/server.ts +++ b/packages/solid-start/src/default-entry/server.ts @@ -1,6 +1,7 @@ import { createStartHandler, defaultStreamHandler, + createServerEntry as createCoreServerEntry, } from '@tanstack/solid-start/server' import type { Register } from '@tanstack/solid-router' import type { RequestHandler } from '@tanstack/solid-start/server' @@ -10,12 +11,8 @@ const fetch = createStartHandler(defaultStreamHandler) // Providing `RequestHandler` from `@tanstack/solid-start/server` is required so that the output types don't import it from `@tanstack/start-server-core` export type ServerEntry = { fetch: RequestHandler } -export function createServerEntry(entry: ServerEntry): ServerEntry { - return { - async fetch(...args) { - return await entry.fetch(...args) - }, - } -} +// Bind the shared request context and fallback error handling to Solid's Register. +export const createServerEntry: (entry: ServerEntry) => ServerEntry = + createCoreServerEntry export default createServerEntry({ fetch }) diff --git a/packages/solid-start/src/hydration.ts b/packages/solid-start/src/hydration.ts new file mode 100644 index 0000000000..fc660e9dc5 --- /dev/null +++ b/packages/solid-start/src/hydration.ts @@ -0,0 +1,18 @@ +export { + condition, + idle, + interaction, + load, + media, + never, + visible, +} from '@tanstack/solid-start-client/hydration' +export type { + HydrationCondition, + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationPrefetchStrategy, + HydrationStrategy, + HydrationWhen, + VisibleHydrationOptions, +} from '@tanstack/solid-start-client/hydration' diff --git a/packages/solid-start/src/index.ts b/packages/solid-start/src/index.ts index 8b51b6c783..bc5560978d 100644 --- a/packages/solid-start/src/index.ts +++ b/packages/solid-start/src/index.ts @@ -1,2 +1,34 @@ export { useServerFn } from './useServerFn' export * from '@tanstack/start-client-core' +// Explicit re-exports shadow `export *` above so these public-API names are +// registered on the namespace at link time (via Vite SSR's `defineExport` +// at fileStartIndex), surviving the cold-start SSR cycle through user +// middleware. See vitejs/vite#22491 / #22493. Trim list to genuine public +// API only; internals fall through `export *` and are safe because they +// aren't imported at top level in the cycle path. +export { + createClientOnlyFn, + createCsrfMiddleware, + createIsomorphicFn, + createMiddleware, + createServerFn, + createServerOnlyFn, + createStart, +} from '@tanstack/start-client-core' + +// Keep root `@tanstack/solid-start` imports from evaluating the client barrel. +// The barrel also exports `hydrateStart`, which imports the virtual client +// entry. That virtual entry imports the user's router module, so route modules +// that import the root package can be pulled back into the same graph and +// create circular HMR updates. Re-exporting from the Hydrate-only subpath +// preserves the public API without introducing that import edge. +export { Hydrate } from '@tanstack/solid-start-client/Hydrate' +export type { + HydrateOptions, + HydrateProps, + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationPrefetchStrategy, + HydrationStrategy, + HydrationWhen, +} from '@tanstack/solid-start-client/Hydrate' diff --git a/packages/solid-start/src/plugin/rsbuild.ts b/packages/solid-start/src/plugin/rsbuild.ts new file mode 100644 index 0000000000..4df2f77d36 --- /dev/null +++ b/packages/solid-start/src/plugin/rsbuild.ts @@ -0,0 +1,84 @@ +import { + RSBUILD_ENVIRONMENT_NAMES, + tanStackStartRsbuild, +} from '@tanstack/start-plugin-core/rsbuild' +import { solidStartDefaultEntryPaths } from './shared' +import type { + TanStackStartRsbuildInputConfig, + TanStackStartRsbuildPluginCoreOptions, +} from '@tanstack/start-plugin-core/rsbuild' +import type { RsbuildPlugin } from '@rsbuild/core' + +export function tanstackStart( + options?: TanStackStartRsbuildInputConfig, +): RsbuildPlugin { + const corePluginOpts: TanStackStartRsbuildPluginCoreOptions = { + framework: 'solid', + defaultEntryPaths: solidStartDefaultEntryPaths, + providerEnvironmentName: RSBUILD_ENVIRONMENT_NAMES.server, + ssrIsProvider: true, + rsbuild: { + environments: { + all: { + resolve: { + conditionNames: ['solid', '...'], + }, + }, + }, + }, + } + + const basePlugin = tanStackStartRsbuild(corePluginOpts, options) + + return { + name: 'tanstack-solid-start-rsbuild', + setup(api) { + basePlugin.setup(api) + + api.modifyBundlerChain(async (chain, { CHAIN_ID, target }) => { + for (const ruleId of [ + CHAIN_ID.RULE.JS, + CHAIN_ID.RULE.JS_DATA_URI, + 'babel-js', + ]) { + if (!chain.module.rules.has(ruleId)) { + continue + } + + const rule = chain.module.rule(ruleId) + if (!rule.uses.has(CHAIN_ID.USE.BABEL)) { + continue + } + + rule.use(CHAIN_ID.USE.BABEL).tap((babelOptions) => { + if (typeof babelOptions === 'string') { + return babelOptions + } + babelOptions.presets = (babelOptions.presets ?? []).map( + (preset: unknown) => { + if ( + Array.isArray(preset) && + typeof preset[0] === 'string' && + preset[0].includes('babel-preset-solid') + ) { + return [ + preset[0], + { + ...(preset[1] ?? {}), + hydratable: true, + generate: target === 'node' ? 'ssr' : 'dom', + }, + ] + } + + return preset + }, + ) + + return babelOptions + }) + } + }) + }, + } +} diff --git a/packages/solid-start/src/plugin/shared.ts b/packages/solid-start/src/plugin/shared.ts new file mode 100644 index 0000000000..f3e09591f4 --- /dev/null +++ b/packages/solid-start/src/plugin/shared.ts @@ -0,0 +1,17 @@ +import { fileURLToPath } from 'node:url' +import path from 'pathe' + +const currentDir = path.dirname(fileURLToPath(import.meta.url)) +const defaultEntryDir = path.resolve( + currentDir, + '..', + '..', + 'plugin', + 'default-entry', +) + +export const solidStartDefaultEntryPaths = { + client: path.resolve(defaultEntryDir, 'client.tsx'), + server: path.resolve(defaultEntryDir, 'server.ts'), + start: path.resolve(defaultEntryDir, 'start.ts'), +} diff --git a/packages/solid-start/src/plugin/vite.ts b/packages/solid-start/src/plugin/vite.ts index d56ff2d5a2..6319c75d0e 100644 --- a/packages/solid-start/src/plugin/vite.ts +++ b/packages/solid-start/src/plugin/vite.ts @@ -1,37 +1,46 @@ -import { fileURLToPath } from 'node:url' import { - TanStackStartVitePluginCore, - VITE_ENVIRONMENT_NAMES, -} from '@tanstack/start-plugin-core' -import path from 'pathe' -import type { TanStackStartInputConfig } from '@tanstack/start-plugin-core' + START_ENVIRONMENT_NAMES, + tanStackStartVite, +} from '@tanstack/start-plugin-core/vite' +import type { + TanStackStartViteInputConfig, + TanStackStartVitePluginCoreOptions, +} from '@tanstack/start-plugin-core/vite' +import { solidStartDefaultEntryPaths } from './shared' import type { PluginOption } from 'vite' -const currentDir = path.dirname(fileURLToPath(import.meta.url)) -const defaultEntryDir = path.resolve( - currentDir, - '..', - '..', - 'plugin', - 'default-entry', -) -const defaultEntryPaths = { - client: path.resolve(defaultEntryDir, 'client.tsx'), - server: path.resolve(defaultEntryDir, 'server.ts'), - start: path.resolve(defaultEntryDir, 'start.ts'), -} - export function tanstackStart( - options?: TanStackStartInputConfig, + options?: TanStackStartViteInputConfig, ): Array { + const corePluginOpts: TanStackStartVitePluginCoreOptions = { + framework: 'solid', + defaultEntryPaths: solidStartDefaultEntryPaths, + providerEnvironmentName: START_ENVIRONMENT_NAMES.server, + ssrIsProvider: true, + ssrResolverStrategy: { + type: 'default', + }, + } + return [ { name: 'tanstack-solid-start:config', + config() { + return { + ssr: { + noExternal: [ + '@tanstack/solid-router-ssr-query', + '@tanstack/solid-query', + '@tanstack/solid-query-devtools', + ], + }, + } + }, configEnvironment(environmentName, options) { return { optimizeDeps: - environmentName === VITE_ENVIRONMENT_NAMES.client || - (environmentName === VITE_ENVIRONMENT_NAMES.server && + environmentName === START_ENVIRONMENT_NAMES.client || + (environmentName === START_ENVIRONMENT_NAMES.server && // This indicates that the server environment has opted in to dependency optimization options.optimizeDeps?.noDiscovery === false) ? { @@ -46,12 +55,6 @@ export function tanstackStart( } }, }, - TanStackStartVitePluginCore( - { - framework: 'solid', - defaultEntryPaths, - }, - options, - ), + tanStackStartVite(corePluginOpts, options), ] } diff --git a/packages/solid-start/src/server-only.ts b/packages/solid-start/src/server-only.ts new file mode 100644 index 0000000000..336ce12bb9 --- /dev/null +++ b/packages/solid-start/src/server-only.ts @@ -0,0 +1 @@ +export {} diff --git a/packages/solid-start/src/useServerFn.ts b/packages/solid-start/src/useServerFn.ts index b0949121b4..c91c643a33 100644 --- a/packages/solid-start/src/useServerFn.ts +++ b/packages/solid-start/src/useServerFn.ts @@ -16,7 +16,7 @@ export function useServerFn) => Promise>( return res } catch (err) { if (isRedirect(err)) { - err.options._fromLocation = router.state.location + err.options._fromLocation = router.stores.location.get() return router.navigate(router.resolveRedirect(err).options) } diff --git a/packages/solid-start/tests/rsbuild.test.ts b/packages/solid-start/tests/rsbuild.test.ts new file mode 100644 index 0000000000..3ab029ad07 --- /dev/null +++ b/packages/solid-start/tests/rsbuild.test.ts @@ -0,0 +1,107 @@ +// @vitest-environment node +import { createRsbuild } from '@rsbuild/core' +import { describe, expect, test, vi } from 'vitest' +import { tanstackStart } from '../src/plugin/rsbuild' + +// Exercise the Solid-specific hook with Rsbuild's real chain, independently of +// route generation and the core Start plugin's filesystem setup. +vi.mock('@tanstack/start-plugin-core/rsbuild', () => ({ + RSBUILD_ENVIRONMENT_NAMES: { server: 'server' }, + tanStackStartRsbuild: () => ({ setup() {} }), +})) + +async function configureBabel( + target: 'web' | 'node', + options: string | { presets: Array }, +) { + const results: Array = [] + const rsbuild = await createRsbuild({ + rsbuildConfig: { + source: { entry: { index: './src/index.ts' } }, + output: { target }, + plugins: [ + { + name: 'test-babel-options', + setup(api) { + api.modifyBundlerChain((chain, { CHAIN_ID }) => { + for (const id of [ + CHAIN_ID.RULE.JS, + CHAIN_ID.RULE.JS_DATA_URI, + 'babel-js', + ]) { + chain.module + .rule(id) + .use(CHAIN_ID.USE.BABEL) + .loader('babel-loader') + .options(structuredClone(options)) + } + }) + }, + }, + tanstackStart(), + { + name: 'test-read-babel-options', + setup(api) { + api.modifyBundlerChain((chain, { CHAIN_ID }) => { + for (const id of [ + CHAIN_ID.RULE.JS, + CHAIN_ID.RULE.JS_DATA_URI, + 'babel-js', + ]) { + results.push( + chain.module.rule(id).use(CHAIN_ID.USE.BABEL).get('options'), + ) + } + }) + }, + }, + ], + }, + }) + await rsbuild.initConfigs() + return results +} + +describe('Solid Start Rsbuild Babel options', () => { + test.each(['web', 'node'] as const)( + 'preserves string loader options for %s', + async (target) => { + const options = 'babelrc=true&configFile=./babel.config.json' + expect(await configureBabel(target, options)).toEqual([ + options, + options, + options, + ]) + }, + ) + + test.each(['web', 'node'] as const)( + 'retains Solid hydration and target selection for %s', + async (target) => { + const options = { + presets: [ + ['babel-preset-solid', { custom: true, hydratable: false }], + ['another-preset', { untouched: true }], + ], + } + const expected = { + presets: [ + [ + 'babel-preset-solid', + { + custom: true, + hydratable: true, + generate: target === 'node' ? 'ssr' : 'dom', + }, + ], + ['another-preset', { untouched: true }], + ], + } + expect(await configureBabel(target, options)).toEqual([ + expected, + expected, + expected, + ]) + }, + ) +}) diff --git a/packages/solid-start/tsconfig.build.json b/packages/solid-start/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/solid-start/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/solid-start/tsconfig.json b/packages/solid-start/tsconfig.json index e4523c7a5a..61fa4599cf 100644 --- a/packages/solid-start/tsconfig.json +++ b/packages/solid-start/tsconfig.json @@ -3,7 +3,8 @@ "compilerOptions": { "jsx": "preserve", "jsxImportSource": "solid-js", - "module": "esnext" + "module": "esnext", + "types": ["node"] }, "include": ["src", "vite.config.ts", "vite.config.server-entry.ts"] } diff --git a/packages/solid-start/tsconfig.server-entry.json b/packages/solid-start/tsconfig.server-entry.json new file mode 100644 index 0000000000..a73a0fc5ae --- /dev/null +++ b/packages/solid-start/tsconfig.server-entry.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src", + "paths": { + "@tanstack/solid-start/server": ["./src/server.tsx"] + } + }, + "include": ["src/default-entry"] +} diff --git a/packages/solid-start/vite.config.server-entry.ts b/packages/solid-start/vite.config.server-entry.ts index e5f7f61767..6ba821babd 100644 --- a/packages/solid-start/vite.config.server-entry.ts +++ b/packages/solid-start/vite.config.server-entry.ts @@ -1,6 +1,7 @@ -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' export default tanstackViteConfig({ + tsconfigPath: './tsconfig.server-entry.json', srcDir: './src/default-entry', exclude: ['./src/default-entry/client.tsx'], entry: ['./src/default-entry/server.ts'], diff --git a/packages/solid-start/vite.config.ts b/packages/solid-start/vite.config.ts index 4004316d91..2c1a42d0e4 100644 --- a/packages/solid-start/vite.config.ts +++ b/packages/solid-start/vite.config.ts @@ -1,5 +1,5 @@ import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' import { copyFilesPlugin } from '@tanstack/router-utils' import packageJson from './package.json' @@ -21,16 +21,21 @@ const config = defineConfig({ export default mergeConfig( config, tanstackViteConfig({ + tsconfigPath: './tsconfig.build.json', srcDir: './src', exclude: ['./src/default-entry'], entry: [ './src/index.ts', './src/client.tsx', + './src/hydration.ts', './src/client-rpc.ts', './src/ssr-rpc.ts', './src/server-rpc.ts', './src/server.tsx', + './src/plugin/rsbuild.ts', './src/plugin/vite.ts', + './src/server-only.ts', + './src/client-only.ts', ], externalDeps: [ '@tanstack/solid-start-client', diff --git a/packages/start-client-core/AGENTS.md b/packages/start-client-core/AGENTS.md new file mode 100644 index 0000000000..1e45453ddf --- /dev/null +++ b/packages/start-client-core/AGENTS.md @@ -0,0 +1,5 @@ +# Start shared/client runtime + +- RawStream RPC responses use binary frames; request arguments/static responses use JSON/base64; SSR uses injected script factories. Pair framing changes in `src/client-rpc/frame-decoder.ts` with `../start-server-core/src/frame-protocol.ts`. For API/serialization changes, validate affected paths through RawStream e2e and encoder/decoder tests. +- Preserve decoder limits and cancellation scopes: canceling one raw stream must leave sibling streams usable; canceling the JSON stream cancels the whole response. Keep malformed/truncated-frame, unread-stream, and split-header coverage in `tests/frame-decoder.test.ts`. +- Context crosses a trust boundary. Use `safeObjectMerge`/`createNullProtoObject`; preserve trusted server middleware context over client-sent context, including SSR and FormData calls. The `server-functions-global-middleware` e2e suite covers that precedence. diff --git a/packages/start-client-core/CHANGELOG.md b/packages/start-client-core/CHANGELOG.md new file mode 100644 index 0000000000..521960c1ac --- /dev/null +++ b/packages/start-client-core/CHANGELOG.md @@ -0,0 +1,680 @@ +# @tanstack/start-client-core + +## 1.170.39 + +### Patch Changes + +- [#8670](https://github.com/TanStack/router/pull/8670) [`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c) - Reference agent skills in other packages by their `intent load` identifier (`@tanstack/#`) instead of relative file links that break once packages are installed. + +- Updated dependencies [[`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c)]: + - @tanstack/router-core@1.171.39 + - @tanstack/start-storage-context@1.167.41 + +## 1.170.38 + +### Patch Changes + +- Updated dependencies [[`18154b1`](https://github.com/TanStack/router/commit/18154b1c45454a70aa77e9d6d27c8a6e0733d031)]: + - @tanstack/router-core@1.171.38 + - @tanstack/start-storage-context@1.167.40 + +## 1.170.37 + +### Patch Changes + +- Updated dependencies [[`740b0ce`](https://github.com/TanStack/router/commit/740b0ce17737d1f7398740136acdbeabe80df7d8), [`d6ba115`](https://github.com/TanStack/router/commit/d6ba115d5751c75e20943f0062577cf17b446d82)]: + - @tanstack/start-storage-context@1.167.39 + - @tanstack/router-core@1.171.37 + +## 1.170.36 + +### Patch Changes + +- [#8694](https://github.com/TanStack/router/pull/8694) [`550f478`](https://github.com/TanStack/router/commit/550f47881070c0558a87e1acce7f38fbc85b9549) - Remove the deprecated `.inputValidator()` from `createServerFn` and `createMiddleware`. Use `.validator()`, which takes the same validator. + +- [#7588](https://github.com/TanStack/router/pull/7588) [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5) - Reduce request middleware overhead, reuse loaded entries and transport header requirements, and avoid unnecessary URL normalization for server functions. Preserve response helper writes made during body cancellation and SSR cleanup. + + Avoid allocating absent middleware headers and reply context, and construct RPC redirects with their final response state. Preserve middleware accessor evaluation and the documented undefined value for absent `sendContext`. + + Reduce synchronous server-function response overhead while preserving cancellation cleanup and middleware response mutations. + +- Updated dependencies [[`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5)]: + - @tanstack/router-core@1.171.36 + - @tanstack/start-storage-context@1.167.38 + +## 1.170.35 + +### Patch Changes + +- Updated dependencies [[`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`663282b`](https://github.com/TanStack/router/commit/663282b0ebbc494aee3595ed95867ee29d01938e)]: + - @tanstack/router-core@1.171.35 + - @tanstack/start-storage-context@1.167.37 + +## 1.170.34 + +### Patch Changes + +- Updated dependencies [[`d521abd`](https://github.com/TanStack/router/commit/d521abd71c69f1ff010bb3def4d417cb5fa058cb)]: + - @tanstack/router-core@1.171.34 + - @tanstack/start-storage-context@1.167.36 + +## 1.170.33 + +### Patch Changes + +- [#8297](https://github.com/TanStack/router/pull/8297) [`488d046`](https://github.com/TanStack/router/commit/488d046a907d330429e2c807ef95326dad87480f) - Update `seroval` and `seroval-plugins` from 1.6.2 to 1.6.7. This picks up the typed array length guard, the `maxBase64Length` and `compactArrayBufferViews` options, and the `isStream` export. + +- [#8353](https://github.com/TanStack/router/pull/8353) [`76a7c0b`](https://github.com/TanStack/router/commit/76a7c0bfadb42d5f7fe7b9e1748acc7333178c91) - Avoid an unused array when registering server-function middleware. + +- Updated dependencies [[`488d046`](https://github.com/TanStack/router/commit/488d046a907d330429e2c807ef95326dad87480f), [`0c1b5e3`](https://github.com/TanStack/router/commit/0c1b5e38de71b7e81bbf1fd81c73ee0cd68ffe47), [`3cdd1af`](https://github.com/TanStack/router/commit/3cdd1af04b3e2d6f777797ee7bddf285318dd9d2)]: + - @tanstack/router-core@1.171.33 + - @tanstack/start-storage-context@1.167.35 + +## 1.170.32 + +### Patch Changes + +- Updated dependencies [[`cecae54`](https://github.com/TanStack/router/commit/cecae5440b8edaea77c5448fe3d74bbd20fe10a4), [`0103578`](https://github.com/TanStack/router/commit/01035782e53af9b929c784b94ddd64b95efb89c7), [`ce10dcd`](https://github.com/TanStack/router/commit/ce10dcd4d9d3d23738744e453205aad5c6dbd716), [`84936cc`](https://github.com/TanStack/router/commit/84936cc04530bba11059c57b293a794922bbc5aa), [`bbd2336`](https://github.com/TanStack/router/commit/bbd2336b8446de3f7dd85070895e7cf43980183e)]: + - @tanstack/router-core@1.171.32 + - @tanstack/start-storage-context@1.167.34 + +## 1.170.31 + +### Patch Changes + +- [#8204](https://github.com/TanStack/router/pull/8204) [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26) - Stream large deferred SSR hydration payloads through a backpressure-aware router transport, fail known setup errors before response creation, and close cancelled or expired transforms safely. + + Start now cancels discarded middleware and HEAD response bodies, including plain streams and derived branches. + + Server-function raw streams share one ordered response. Arbitrary or sequential consumption can require potentially unbounded buffering of unread data on the client. Cancelling one raw stream discards it locally, while aborting the whole call cancels the response and server work. Consume streams concurrently, cancel unused streams promptly, or use separate calls when independent backpressure is required. A raw stream that exceeds its unread-byte limit now fails alone; sibling streams and the JSON result keep flowing. + + The JSON wire shape of a `RawStream` server-function argument changed. Clients and servers must run matching versions for requests that pass a `RawStream`. + + The frame-protocol constants (`FRAME_TYPE_*`, `MAX_FRAME_PAYLOAD_SIZE`, `MAX_FRAMED_STREAMS`) moved from the `@tanstack/start-client-core` root to the `@tanstack/start-client-core/client-rpc` subpath. + + Router requests whose `Accept` header allows neither `text/html` nor `*/*` now receive `406 Not Acceptable` instead of `500`. + + Framework adapters share the body `` composition (`getSsrBodyScriptParts`, `composeSsrBodyScripts`) and the eager HTML response wrapper (`renderSsrHtmlResponse`) from `@tanstack/router-core`. + + Solid SSR now emits one document type and renders late lazy errors through route boundaries. A Solid `` without a `fallback` no longer holds the streamed shell; it renders inside the nearest `` boundary like React and Vue, and now renders falsy resolved values. + + Static server functions decode cached `RawStream` values with the client deserializer plugins. + + SSR Query integrations now keep request cleanup and stream ownership aligned with the router lifecycle. + +- Updated dependencies [[`bc80866`](https://github.com/TanStack/router/commit/bc80866f6d6eb3e6f152ee3682eb783c96403e83), [`e561fa1`](https://github.com/TanStack/router/commit/e561fa1d7118e3d29267cc3b6ce1130d6581f387), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a1c8d1a`](https://github.com/TanStack/router/commit/a1c8d1aa759c227eae9601a030321ac4c53c24bd), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a0b2ad9`](https://github.com/TanStack/router/commit/a0b2ad99aee64af08d16b0e4ff26b3ba42a99f0a), [`1ca361b`](https://github.com/TanStack/router/commit/1ca361ba52a627d2f76ab33323bd83d1d0aa65a3)]: + - @tanstack/router-core@1.171.31 + - @tanstack/start-storage-context@1.167.33 + +## 1.170.30 + +### Patch Changes + +- Updated dependencies [[`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776), [`6cfb1e8`](https://github.com/TanStack/router/commit/6cfb1e8b564be282584765352250bf61747895ed), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`873c830`](https://github.com/TanStack/router/commit/873c830ccb2610a864ee697250e10fcc99772ffa), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`f151ab0`](https://github.com/TanStack/router/commit/f151ab018eede64ae849b77e68f3cdf31cb95cc5), [`bc57fa3`](https://github.com/TanStack/router/commit/bc57fa3f12450cf34c731450947c7c8f1ea05e58), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9448caa`](https://github.com/TanStack/router/commit/9448caa03a89076b9770631c356c0cc502802c09), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef)]: + - @tanstack/router-core@1.171.30 + - @tanstack/start-storage-context@1.167.32 + +## 1.170.29 + +### Patch Changes + +- Updated dependencies [[`f9836f1`](https://github.com/TanStack/router/commit/f9836f16f0e25b0a8495f5e01e3f303b1cbc8725), [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8), [`9871c06`](https://github.com/TanStack/router/commit/9871c0625806001d6bf373524821a00303438a91), [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9)]: + - @tanstack/router-core@1.171.29 + - @tanstack/start-storage-context@1.167.31 + +## 1.170.28 + +### Patch Changes + +- Updated dependencies [[`edf0e16`](https://github.com/TanStack/router/commit/edf0e16ebfe82ec6e8f68f403a1fda8de9e28889), [`2f20c00`](https://github.com/TanStack/router/commit/2f20c00224c5ba63467551914e0c37012588c4c2), [`28a5e45`](https://github.com/TanStack/router/commit/28a5e4504e4ea5cb1480667a4bea2588a53e110f), [`08eff50`](https://github.com/TanStack/router/commit/08eff50c447a154a3373909009e9e4375cea17ce), [`216c0c4`](https://github.com/TanStack/router/commit/216c0c48036fd1a33163b70dcabfed2b893808b0), [`2f91503`](https://github.com/TanStack/router/commit/2f9150309bc472f4a75cbe98adcdb50c76b12c7a), [`f0b5eda`](https://github.com/TanStack/router/commit/f0b5eda544606686a8a8d675a686ca1366428b96), [`50eafca`](https://github.com/TanStack/router/commit/50eafcaebbbedb6fde3b2816de7a0ace8cde4832), [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b), [`ee28348`](https://github.com/TanStack/router/commit/ee283480dfa51150a2e0b096a6eff94a89ff8b3f), [`c18e690`](https://github.com/TanStack/router/commit/c18e69081475a7c98f9d40bd0fe6da78ccb84598)]: + - @tanstack/router-core@1.171.28 + - @tanstack/start-storage-context@1.167.30 + +## 1.170.27 + +### Patch Changes + +- Updated dependencies [[`fa65287`](https://github.com/TanStack/router/commit/fa652872812c9433ba8b9d9a285e51b535e7367c), [`cb281d7`](https://github.com/TanStack/router/commit/cb281d70c1f5fe780f9d07bc500ea3a284a4e04b)]: + - @tanstack/router-core@1.171.27 + - @tanstack/start-storage-context@1.167.29 + +## 1.170.26 + +### Patch Changes + +- Updated dependencies [[`3e016ac`](https://github.com/TanStack/router/commit/3e016ac84ffec8119f0c25cfdd1fb17e5292bd34)]: + - @tanstack/router-core@1.171.26 + - @tanstack/start-storage-context@1.167.28 + +## 1.170.25 + +### Patch Changes + +- Updated dependencies [[`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175), [`63d2cc9`](https://github.com/TanStack/router/commit/63d2cc9155ff5374112f7d067d0b278bafeb8486)]: + - @tanstack/router-core@1.171.25 + - @tanstack/start-storage-context@1.167.27 + +## 1.170.24 + +### Patch Changes + +- Updated dependencies [[`4c89b15`](https://github.com/TanStack/router/commit/4c89b15dd2b46491ee5e57985559bae8e31d62c2), [`cf6ab17`](https://github.com/TanStack/router/commit/cf6ab178b39e7628bf784759f384e0f4230e6d9e), [`bdaf73a`](https://github.com/TanStack/router/commit/bdaf73a4063ee2b02e3c9cc105ad10ce82a5a0ff)]: + - @tanstack/router-core@1.171.24 + - @tanstack/start-storage-context@1.167.26 + +## 1.170.23 + +### Patch Changes + +- Updated dependencies [[`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90)]: + - @tanstack/router-core@1.171.23 + - @tanstack/start-storage-context@1.167.25 + +## 1.170.22 + +### Patch Changes + +- Updated dependencies [[`7e93431`](https://github.com/TanStack/router/commit/7e93431ae9ff58c91c3c5ca10ffcb8414c1d0b13)]: + - @tanstack/router-core@1.171.22 + - @tanstack/start-storage-context@1.167.24 + +## 1.170.21 + +### Patch Changes + +- Updated dependencies [[`51138a8`](https://github.com/TanStack/router/commit/51138a824cea053738f125c4c95073bd6286ff05)]: + - @tanstack/router-core@1.171.21 + - @tanstack/start-storage-context@1.167.23 + +## 1.170.20 + +### Patch Changes + +- [#8009](https://github.com/TanStack/router/pull/8009) [`c59788c`](https://github.com/TanStack/router/commit/c59788ca20f2d2e7f264a859ebe01b7646ba3154) - perf: drop consumed chunks from the client frame decoder buffer with an O(1) head pointer instead of `Array.prototype.shift()` (O(n)). The previous approach degraded to O(n^2) when a single large frame (e.g. a big `RawStream` payload) was assembled from many small network reads. + +- Updated dependencies [[`44a8c3e`](https://github.com/TanStack/router/commit/44a8c3e1d2af305064b2363d97fc7847c6f1a246), [`5253e70`](https://github.com/TanStack/router/commit/5253e70db2083d68a788fb7c9a043bb0c5518f2a)]: + - @tanstack/router-core@1.171.20 + - @tanstack/start-storage-context@1.167.22 + +## 1.170.19 + +### Patch Changes + +- [#7978](https://github.com/TanStack/router/pull/7978) [`2fbc99f`](https://github.com/TanStack/router/commit/2fbc99f2c262b057cb957e6ebba1ee073c655186) - compact private frame decoder result keys + +- [#7980](https://github.com/TanStack/router/pull/7980) [`6bede65`](https://github.com/TanStack/router/commit/6bede65d7074dcd83455151b66b4574268bc782c) - compact deferred hydration private state + +## 1.170.18 + +### Patch Changes + +- Updated dependencies [[`ea3a665`](https://github.com/TanStack/router/commit/ea3a665d81cbb5074c2d77ec953255ab534e7db9)]: + - @tanstack/router-core@1.171.19 + - @tanstack/start-storage-context@1.167.21 + +## 1.170.17 + +### Patch Changes + +- [#7985](https://github.com/TanStack/router/pull/7985) [`9cac62a`](https://github.com/TanStack/router/commit/9cac62a5c7f99ef070991ea6f1fa7e42c746d46b) - perf: compact private bundle boundaries- [#7975](https://github.com/TanStack/router/issues/7975) + +- Updated dependencies [[`84db4a8`](https://github.com/TanStack/router/commit/84db4a842311df3f7e58073f6f12aaf371aeb5c7), [`9cac62a`](https://github.com/TanStack/router/commit/9cac62a5c7f99ef070991ea6f1fa7e42c746d46b), [`6aefb33`](https://github.com/TanStack/router/commit/6aefb3392595a07a93f89301d7b5e3558ff9190c)]: + - @tanstack/router-core@1.171.18 + - @tanstack/start-storage-context@1.167.20 + +## 1.170.16 + +### Patch Changes + +- [#7962](https://github.com/TanStack/router/pull/7962) [`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5) - Update Seroval dependencies to version 1.6.2. + +- Updated dependencies [[`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5)]: + - @tanstack/router-core@1.171.17 + - @tanstack/start-storage-context@1.167.19 + +## 1.170.15 + +### Patch Changes + +- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: + - @tanstack/router-core@1.171.16 + - @tanstack/start-storage-context@1.167.18 + +## 1.170.14 + +### Patch Changes + +- Updated dependencies [[`e2dd204`](https://github.com/TanStack/router/commit/e2dd2049cb42eb219d3b447b8605066d19d9c1fa)]: + - @tanstack/router-core@1.171.15 + - @tanstack/start-storage-context@1.167.17 + +## 1.170.13 + +### Patch Changes + +- [#7662](https://github.com/TanStack/router/pull/7662) [`ba52d2b`](https://github.com/TanStack/router/commit/ba52d2b8f9e95d6becd1be14c020b35f3231e02c) - perf: zero-copy frame payload extraction in the client frame decoder. When a frame's bytes are fully contained in the first buffered chunk (the common case), return a subarray view instead of allocating a new buffer and copying. This is on the hot path for decoding streamed server-function responses and `RawStream` payloads. + +- Updated dependencies [[`9809a06`](https://github.com/TanStack/router/commit/9809a0619d4ed3fe8c2a393af5b9eca4b6c7695b)]: + - @tanstack/router-core@1.171.14 + - @tanstack/start-storage-context@1.167.16 + +## 1.170.12 + +### Patch Changes + +- [#7566](https://github.com/TanStack/router/pull/7566) [`9bebf8d`](https://github.com/TanStack/router/commit/9bebf8dc9f2bf74b680c065a5aa63d03b9622825) - Add `validator()` as the canonical server function and middleware validator method. Deprecate `inputValidator()` and emit compiler warnings for remaining uses. + +## 1.170.11 + +### Patch Changes + +- Updated dependencies [[`776d8ef`](https://github.com/TanStack/router/commit/776d8ef283e5bd9ffe97d43bc3a7f58064cd7e03)]: + - @tanstack/router-core@1.171.13 + - @tanstack/start-storage-context@1.167.15 + +## 1.170.10 + +### Patch Changes + +- Updated dependencies [[`df1076c`](https://github.com/TanStack/router/commit/df1076c03ae5a51ab384bebd4d6afda20fb6f107)]: + - @tanstack/router-core@1.171.12 + - @tanstack/start-storage-context@1.167.14 + +## 1.170.9 + +### Patch Changes + +- Updated dependencies [[`ac10815`](https://github.com/TanStack/router/commit/ac10815f387d25b15163ff711b4049e8f8482d01)]: + - @tanstack/router-core@1.171.11 + - @tanstack/start-storage-context@1.167.13 + +## 1.170.8 + +### Patch Changes + +- Updated dependencies [[`2cca73c`](https://github.com/TanStack/router/commit/2cca73c92262ffd96dac4e283c9f69fb37f4b43a), [`7a83e67`](https://github.com/TanStack/router/commit/7a83e67e6596fbef21cb0a88a7127f5935bed2ba), [`76b3d3b`](https://github.com/TanStack/router/commit/76b3d3b24522bd3d1d216674c441252c9b8f184c)]: + - @tanstack/router-core@1.171.10 + - @tanstack/start-storage-context@1.167.12 + +## 1.170.7 + +### Patch Changes + +- Updated dependencies [[`b4cd5af`](https://github.com/TanStack/router/commit/b4cd5af8d0f9d4aaa2d29095e6a261b9181bc778)]: + - @tanstack/router-core@1.171.9 + - @tanstack/start-storage-context@1.167.11 + +## 1.170.6 + +### Patch Changes + +- Updated dependencies [[`2f53749`](https://github.com/TanStack/router/commit/2f5374945e2138559a51464f45a5152eae67e1dd)]: + - @tanstack/router-core@1.171.8 + - @tanstack/start-storage-context@1.167.10 + +## 1.170.5 + +### Patch Changes + +- Updated dependencies [[`d1997b6`](https://github.com/TanStack/router/commit/d1997b66d7c24c1d64772bb8bab5caf9c6d9cc48)]: + - @tanstack/router-core@1.171.7 + - @tanstack/start-storage-context@1.167.9 + +## 1.170.4 + +### Patch Changes + +- Fix serialization adapter module resolution in TanStack Start. Vite dev now uses clean runtime-specific virtual module IDs instead of browser requests containing encoded null-byte virtual IDs, which avoids reverse proxy failures. When no serialization adapters are configured, Vite and Rsbuild now resolve `#tanstack-start-plugin-adapters` through the package empty-adapter fallback. ([#7484](https://github.com/TanStack/router/pull/7484)) + +## 1.170.3 + +### Patch Changes + +- Updated dependencies [[`51a97a1`](https://github.com/TanStack/router/commit/51a97a167fb3ef1b8ca70fbb63db635158f43509)]: + - @tanstack/router-core@1.171.6 + - @tanstack/start-storage-context@1.167.8 + +## 1.170.2 + +### Patch Changes + +- Updated dependencies [[`5268ba4`](https://github.com/TanStack/router/commit/5268ba4566233ea58880df85f167ad0401a93a46)]: + - @tanstack/router-core@1.171.5 + - @tanstack/start-storage-context@1.167.7 + +## 1.170.1 + +### Patch Changes + +- Updated dependencies [[`0300f87`](https://github.com/TanStack/router/commit/0300f87ec5a7f878ffbe0b181acf84cba9139960), [`0300f87`](https://github.com/TanStack/router/commit/0300f87ec5a7f878ffbe0b181acf84cba9139960)]: + - @tanstack/router-core@1.171.4 + - @tanstack/start-storage-context@1.167.6 + +## 1.170.0 + +### Minor Changes + +- Add deferred Hydrate boundary support for TanStack Start. ([#7362](https://github.com/TanStack/router/pull/7362)) + + Hydrate boundaries can now be code-split by the Start compiler, preload their generated client chunks, preserve server-rendered fallback HTML, and replay interaction-triggered events after hydration. The compiler integration now uses a Start-owned compiler plugin for Hydrate virtual modules across Vite and Rsbuild, with dev invalidation for generated virtual modules. + + Shared AST utilities used by the router code-splitter and Hydrate virtual modules were moved into `@tanstack/router-utils` so both pipelines can retain referenced top-level declarations, unwrap local exports, and let dead-code elimination remove unused route module code. + +### Patch Changes + +- Updated dependencies [[`5fa9e55`](https://github.com/TanStack/router/commit/5fa9e555f3a2edb5e45586623e6bcbfa7f7c7a6b)]: + - @tanstack/router-core@1.171.3 + - @tanstack/start-storage-context@1.167.5 + +## 1.169.4 + +### Patch Changes + +- Updated dependencies [[`b60eb36`](https://github.com/TanStack/router/commit/b60eb36e59e8a468ee0742cbcf7f47aca1ff1c67)]: + - @tanstack/router-core@1.171.2 + - @tanstack/start-storage-context@1.167.4 + +## 1.169.3 + +### Patch Changes + +- Updated dependencies [[`d9cf933`](https://github.com/TanStack/router/commit/d9cf9331b83fcbd2abfee75d839d862f9bb18e6b)]: + - @tanstack/router-core@1.171.1 + - @tanstack/start-storage-context@1.167.3 + +## 1.169.2 + +### Patch Changes + +- Updated dependencies [[`d533f87`](https://github.com/TanStack/router/commit/d533f87976704098a40b48f160b37c28c8182806)]: + - @tanstack/router-core@1.171.0 + - @tanstack/start-storage-context@1.167.2 + +## 1.169.1 + +### Patch Changes + +- Updated dependencies [[`2387a2e`](https://github.com/TanStack/router/commit/2387a2eea0683004cc400b9f71bed5944eb60110)]: + - @tanstack/router-core@1.170.1 + - @tanstack/start-storage-context@1.167.1 + +## 1.169.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +### Patch Changes + +- Updated dependencies [[`b1c061a`](https://github.com/TanStack/router/commit/b1c061aff9185cdf5fdc08c0136382a9dce0302f), [`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14), [`5ae2ae5`](https://github.com/TanStack/router/commit/5ae2ae5e0f8ce32e02667a482ea9be52a6150240)]: + - @tanstack/router-core@1.170.0 + - @tanstack/start-fn-stubs@1.162.0 + - @tanstack/start-storage-context@1.167.0 + +## 1.168.2 + +### Patch Changes + +- Update seroval dependencies to version 1.5.4. ([#7340](https://github.com/TanStack/router/pull/7340)) + +- Updated dependencies [[`35e88f0`](https://github.com/TanStack/router/commit/35e88f04996d71019a1868b7b06ecb4ddbc9df9e)]: + - @tanstack/router-core@1.169.2 + - @tanstack/start-storage-context@1.166.35 + +## 1.168.1 + +### Patch Changes + +- Updated dependencies [[`4a1e63f`](https://github.com/TanStack/router/commit/4a1e63f1d1230b1ed8234609acad4639d8982c13)]: + - @tanstack/router-core@1.169.1 + - @tanstack/start-storage-context@1.166.34 + +## 1.168.0 + +### Minor Changes + +- Add a `strict` option to `createServerFn` for type-level server function serialization checks. Use `strict: false` to opt out for input and output values, or `strict: { output: false }` to opt out for return values only. ([#7277](https://github.com/TanStack/router/pull/7277)) + +## 1.167.22 + +### Patch Changes + +- Updated dependencies [[`c992495`](https://github.com/TanStack/router/commit/c992495bf4010ff4c3597bb1f3b1ba02594e857e)]: + - @tanstack/router-core@1.169.0 + - @tanstack/start-storage-context@1.166.33 + +## 1.167.21 + +### Patch Changes + +- Updated dependencies [[`b5c4183`](https://github.com/TanStack/router/commit/b5c4183ab8b44be8a75647b7f7b588ad7c146ece)]: + - @tanstack/router-core@1.168.18 + - @tanstack/start-storage-context@1.166.32 + +## 1.167.20 + +### Patch Changes + +- Updated dependencies [[`493148b`](https://github.com/TanStack/router/commit/493148bc5378b7f9de1544d87f6aaa425c12eb34)]: + - @tanstack/router-core@1.168.17 + - @tanstack/start-storage-context@1.166.31 + +## 1.167.19 + +### Patch Changes + +- refactor(start-client-core): use a more explicit typing to `CustomFetch` type ([#7258](https://github.com/TanStack/router/pull/7258)) + +## 1.167.18 + +### Patch Changes + +- Updated dependencies [[`4d864ee`](https://github.com/TanStack/router/commit/4d864eebbd184265eabb563d326ab409c93feb17)]: + - @tanstack/router-core@1.168.16 + - @tanstack/start-storage-context@1.166.30 + +## 1.167.17 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/start-storage-context@1.166.29 + +## 1.167.16 + +### Patch Changes + +- Updated dependencies [[`0e2c900`](https://github.com/TanStack/router/commit/0e2c9003c18ae07c09969189c028f277ea562a7a)]: + - @tanstack/router-core@1.168.14 + - @tanstack/start-storage-context@1.166.28 + +## 1.167.15 + +### Patch Changes + +- Updated dependencies [[`812792f`](https://github.com/TanStack/router/commit/812792fbda3caf97b300770855cf5641252f413b)]: + - @tanstack/router-core@1.168.13 + - @tanstack/start-storage-context@1.166.27 + +## 1.167.14 + +### Patch Changes + +- Updated dependencies [[`8ec9ca9`](https://github.com/TanStack/router/commit/8ec9ca97b472779de878c2a6510f21deb24d386c)]: + - @tanstack/router-core@1.168.12 + - @tanstack/start-storage-context@1.166.26 + +## 1.167.13 + +### Patch Changes + +- Updated dependencies [[`6355bb7`](https://github.com/TanStack/router/commit/6355bb75f7637ba77f06a923c18fdaf37720bb48)]: + - @tanstack/router-core@1.168.11 + - @tanstack/start-storage-context@1.166.25 + +## 1.167.12 + +### Patch Changes + +- migrate createStore > createAtom for simpler API ([#7150](https://github.com/TanStack/router/pull/7150)) + +- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: + - @tanstack/router-core@1.168.10 + - @tanstack/start-storage-context@1.166.24 + +## 1.167.11 + +### Patch Changes + +- fix publishing ([`f8ac427`](https://github.com/TanStack/router/commit/f8ac427000c3fec99225926e72f9f2fc7a37231f)) + +## 1.167.10 + +### Patch Changes + +- Ensure request middleware context wins over colliding client-provided context in server function execution paths, including SSR, GET, and FormData requests. ([#7135](https://github.com/TanStack/router/pull/7135)) + +## 1.167.9 + +### Patch Changes + +- Updated dependencies [[`796406d`](https://github.com/TanStack/router/commit/796406da66cfb12b518bb3ca326c9d541368fb06)]: + - @tanstack/router-core@1.168.9 + - @tanstack/start-storage-context@1.166.23 + +## 1.167.8 + +### Patch Changes + +- Updated dependencies [[`2d1ec86`](https://github.com/TanStack/router/commit/2d1ec865a446926f7db6e29dbbde82d265de6d36)]: + - @tanstack/router-core@1.168.8 + - @tanstack/start-storage-context@1.166.22 + +## 1.167.7 + +### Patch Changes + +- Updated dependencies [[`6ee0e79`](https://github.com/TanStack/router/commit/6ee0e795b085651beb2f1ac6503cdbd7eaffedd1)]: + - @tanstack/router-core@1.168.7 + - @tanstack/start-storage-context@1.166.21 + +## 1.167.6 + +### Patch Changes + +- Updated dependencies [[`42c3f3b`](https://github.com/TanStack/router/commit/42c3f3b3a3a478fd6d6894310ef94b2d23794b8e)]: + - @tanstack/router-core@1.168.6 + - @tanstack/start-storage-context@1.166.20 + +## 1.167.5 + +### Patch Changes + +- Updated dependencies [[`cf5f554`](https://github.com/TanStack/router/commit/cf5f5542476137a81515099ad740747e84512f9a)]: + - @tanstack/router-core@1.168.5 + - @tanstack/start-storage-context@1.166.19 + +## 1.167.4 + +### Patch Changes + +- Updated dependencies [[`71a8b68`](https://github.com/TanStack/router/commit/71a8b684c87c37fd4a033d99f5ba4a05c7a179f5)]: + - @tanstack/router-core@1.168.4 + - @tanstack/start-storage-context@1.166.18 + +## 1.167.3 + +### Patch Changes + +- Updated dependencies [[`d81d21a`](https://github.com/TanStack/router/commit/d81d21ad05c9401bf54b24acd29401e1e4fd624c)]: + - @tanstack/router-core@1.168.3 + - @tanstack/start-storage-context@1.166.17 + +## 1.167.2 + +### Patch Changes + +- Replace tiny-invariant and tiny-warning with in-house solution for bundle-size ([#7007](https://github.com/TanStack/router/pull/7007)) + +- Updated dependencies [[`c9e1855`](https://github.com/TanStack/router/commit/c9e18555f3a5531e96de8f574cfca9edcdb18e5c)]: + - @tanstack/router-core@1.168.2 + - @tanstack/start-storage-context@1.166.16 + +## 1.167.1 + +### Patch Changes + +- Updated dependencies [[`91cc628`](https://github.com/TanStack/router/commit/91cc62899b75ca920fe83c5ee7f3dbb5c71a523f)]: + - @tanstack/router-core@1.168.1 + - @tanstack/start-storage-context@1.166.15 + +## 1.167.0 + +### Minor Changes + +- remove pendingMatches, cachedMatches ([#6704](https://github.com/TanStack/router/pull/6704)) + move to signal-based reactivity + solid uses its own native signals + +### Patch Changes + +- Updated dependencies [[`0545239`](https://github.com/TanStack/router/commit/054523900b2ee19308e5a88417dadfc6923afe30)]: + - @tanstack/router-core@1.168.0 + - @tanstack/start-storage-context@1.166.14 + +## 1.166.13 + +### Patch Changes + +- Updated dependencies [[`5ff4f0b`](https://github.com/TanStack/router/commit/5ff4f0b8dce1fac2bb0b0bfe2684fc677a8ee505)]: + - @tanstack/router-core@1.167.5 + - @tanstack/start-storage-context@1.166.13 + +## 1.166.12 + +### Patch Changes + +- Add @tanstack/intent AI agent skills and CLI entry points for Router and Start packages ([#6866](https://github.com/TanStack/router/pull/6866)) + +- Updated dependencies [[`940151c`](https://github.com/TanStack/router/commit/940151cbed0c76c92a5cf196c0905b17a956ca7e)]: + - @tanstack/router-core@1.167.4 + - @tanstack/start-storage-context@1.166.12 + +## 1.166.11 + +### Patch Changes + +- Updated dependencies [[`32fcba7`](https://github.com/TanStack/router/commit/32fcba7b044b03f5901308b870f70b0b4910c220)]: + - @tanstack/router-core@1.167.3 + - @tanstack/start-storage-context@1.166.11 + +## 1.166.10 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +- Updated dependencies [[`838b0eb`](https://github.com/TanStack/router/commit/838b0eb9a8bbbb987a0a6972c1446e01423bbd7b)]: + - @tanstack/router-core@1.167.2 + - @tanstack/start-fn-stubs@1.161.6 + - @tanstack/start-storage-context@1.166.10 + +## 1.166.9 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) + +- Updated dependencies [[`ef9b241`](https://github.com/TanStack/router/commit/ef9b241f3cfe95cee40daa96da669f0ffd4a971a)]: + - @tanstack/start-storage-context@1.166.9 + - @tanstack/start-fn-stubs@1.161.5 + - @tanstack/router-core@1.167.1 + +## 1.166.8 + +### Patch Changes + +- Updated dependencies [[`6f297a2`](https://github.com/TanStack/router/commit/6f297a249424c0fd1c1a56aa4fc12c8217be7b6a)]: + - @tanstack/router-core@1.167.0 + - @tanstack/start-storage-context@1.166.8 diff --git a/packages/start-client-core/package.json b/packages/start-client-core/package.json index 3f473c26a9..c74dce13aa 100644 --- a/packages/start-client-core/package.json +++ b/packages/start-client-core/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/start-client-core", - "version": "1.141.8", + "version": "1.170.39", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -30,12 +30,12 @@ "test:unit:dev": "vitest --watch", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -60,29 +60,65 @@ "default": "./dist/esm/client-rpc/index.js" } }, + "./hydration": { + "import": { + "types": "./dist/esm/hydration.d.ts", + "default": "./dist/esm/hydration.js" + } + }, + "./hydration/constants": { + "import": { + "types": "./dist/esm/hydration/constants.d.ts", + "default": "./dist/esm/hydration/constants.js" + } + }, + "./hydration/runtime": { + "import": { + "types": "./dist/esm/hydration/runtime.d.ts", + "default": "./dist/esm/hydration/runtime.js" + } + }, "./package.json": "./package.json" }, "imports": { "#tanstack-start-entry": { - "default": "./dist/esm/fake-start-entry.js" + "types": "./src/start-entry.d.ts", + "default": "./dist/esm/fake-entries/start.js" }, "#tanstack-router-entry": { - "default": "./dist/esm/fake-start-entry.js" + "types": "./src/start-entry.d.ts", + "default": "./dist/esm/fake-entries/router.js" + }, + "#tanstack-start-plugin-adapters": { + "types": "./src/start-entry.d.ts", + "default": "./dist/esm/empty-plugin-adapters.js" } }, "sideEffects": false, "files": [ "dist", - "src" + "src", + "skills", + "bin", + "!skills/_artifacts" ], "engines": { "node": ">=22.12.0" }, "dependencies": { "@tanstack/router-core": "workspace:*", + "@tanstack/start-fn-stubs": "workspace:*", "@tanstack/start-storage-context": "workspace:*", - "seroval": "^1.4.1", - "tiny-invariant": "^1.3.3", - "tiny-warning": "^1.0.3" + "seroval": "^1.6.7" + }, + "devDependencies": { + "vite": "*", + "@types/node": ">=20", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" } } diff --git a/packages/start-client-core/skills/_artifacts/domain_map.yaml b/packages/start-client-core/skills/_artifacts/domain_map.yaml new file mode 100644 index 0000000000..ac17d49f56 --- /dev/null +++ b/packages/start-client-core/skills/_artifacts/domain_map.yaml @@ -0,0 +1,574 @@ +# domain_map.yaml +# Generated by skill-domain-discovery +# Library: TanStack Start +# Version: 1.170.14 +# Date: 2026-03-07 +# Status: reviewed + +library: + name: '@tanstack/react-start' + version: '1.170.14' + repository: 'https://github.com/TanStack/router' + description: >- + Full-stack React framework built on TanStack Router and Vite. Adds + SSR, streaming, server functions (type-safe RPCs), middleware, + server routes, and universal deployment. Isomorphic by default — + all code runs in both environments unless explicitly constrained. + primary_framework: 'React' + +domains: + - name: 'Project Setup' + slug: 'project-setup' + description: >- + Scaffolding a Start project, configuring Vite plugin, router + setup with getRouter(), root route with document shell, client + and server entry points. + + - name: 'Server Functions' + slug: 'server-functions' + description: >- + Creating type-safe RPCs with createServerFn, input validation, + calling from loaders/components/other server functions, error + handling, streaming responses. + + - name: 'Middleware and Context' + slug: 'middleware-and-context' + description: >- + Request middleware, server function middleware, context passing + with sendContext, global middleware via createStart, middleware + factories, fetch override precedence. + + - name: 'Execution Model' + slug: 'execution-model' + description: >- + Isomorphic code execution, environment functions + (createServerFn, createServerOnlyFn, createClientOnlyFn, + createIsomorphicFn), import protection, dead code elimination, + environment variable safety. + + - name: 'Server Routes' + slug: 'server-routes' + description: >- + Server-side API endpoints defined in routes, HTTP method + handlers, handler middleware, request/response patterns. + + - name: 'Deployment and Rendering' + slug: 'deployment-and-rendering' + description: >- + Hosting providers (Cloudflare, Netlify, Vercel, Node/Docker), + selective SSR, SPA mode, static prerendering, ISR with + Cache-Control headers, SEO and head management. + +skills: + # ── Project Setup ──────────────────────────────────────────────── + - name: 'Start Core' + slug: 'start-core' + domain: 'project-setup' + description: >- + Scaffold a TanStack Start project, configure Vite plugin with + tanstackStart(), set up router with getRouter(), create root + route with document shell (HeadContent, Scripts, Outlet), + configure client and server entry points. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-plugin-core' + covers: + - tanstackStart Vite plugin + - getRouter() factory pattern + - Root route document shell + - HeadContent / Scripts / Outlet + - Client entry point (optional) + - Server entry point (optional) + - routeTree.gen.ts + - tsconfig configuration + tasks: + - 'Scaffold a new TanStack Start project' + - 'Configure the Vite plugin' + - 'Set up the router factory' + - 'Customize client/server entry points' + failure_modes: + - mistake: 'React plugin before Start plugin in Vite config' + mechanism: >- + Start's Vite plugin must come before React's plugin. + Wrong order causes route generation and server function + compilation to fail. + wrong_pattern: | + plugins: [react(), tanstackStart()] + correct_pattern: | + plugins: [tanstackStart(), react()] + source: 'docs/start/framework/react/build-from-scratch.md' + priority: CRITICAL + status: active + + - mistake: 'Enabling verbatimModuleSyntax in tsconfig' + mechanism: >- + verbatimModuleSyntax causes server bundles to leak into + client bundles. Must be disabled. + source: 'docs/start/framework/react/build-from-scratch.md' + priority: HIGH + status: active + + - mistake: 'Missing Scripts component in root route' + mechanism: >- + The Scripts component must be rendered in the body of + the root route for proper hydration and functionality. + Without it, client-side JavaScript does not load. + source: 'docs/start/framework/react/guide/routing.md' + priority: HIGH + status: active + + # ── Server Functions ───────────────────────────────────────────── + - name: 'Server Functions' + slug: 'server-functions' + domain: 'server-functions' + description: >- + Create type-safe RPCs with createServerFn, validate inputs + with Zod or plain functions, call from loaders/components/ + event handlers, handle errors/redirects/notFound, stream + responses with ReadableStream or async generators. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-client-core' + - '@tanstack/start-server-core' + covers: + - createServerFn (GET/POST) + - validator (Zod or function) + - useServerFn hook + - Server context utilities (getRequest, getRequestHeader, setResponseHeader, setResponseStatus) + - Error handling (throw errors, redirect, notFound) + - Streaming (ReadableStream, async generators) + - File organization (.functions.ts, .server.ts) + - FormData handling + tasks: + - 'Create a server function for data fetching' + - 'Validate server function inputs' + - 'Call server functions from components' + - 'Stream data from server functions' + - 'Handle errors in server functions' + failure_modes: + - mistake: 'Putting server-only code in loaders instead of server functions' + mechanism: >- + Loaders are ISOMORPHIC — they run on both client and server. + Database queries, file system access, and secret API keys + in loaders will either fail on the client or leak to the + client bundle. Use createServerFn for server-only logic. + wrong_pattern: | + export const Route = createFileRoute('/posts')({ + loader: async () => { + const posts = await db.query('SELECT * FROM posts') + return { posts } + }, + }) + correct_pattern: | + const getPosts = createServerFn({ method: 'GET' }) + .handler(async () => { + const posts = await db.query('SELECT * FROM posts') + return { posts } + }) + + export const Route = createFileRoute('/posts')({ + loader: () => getPosts(), + }) + source: 'maintainer interview' + priority: CRITICAL + status: active + skills: ['server-functions', 'execution-model'] + + - mistake: 'Using dynamic imports for server functions' + mechanism: >- + Dynamic imports of server functions can cause bundler + issues. Static imports are safe — the build process + replaces server implementations with RPC stubs. + wrong_pattern: | + const { getUser } = await import('~/utils/users.functions') + correct_pattern: | + import { getUser } from '~/utils/users.functions' + source: 'docs/start/framework/react/guide/server-functions.md' + priority: HIGH + status: active + + - mistake: 'Not using useServerFn for component calls' + mechanism: >- + Component calls need useServerFn so redirects and not-found + responses use the active router instead of falling through as + ordinary function results. + source: 'docs/start/framework/react/guide/server-functions.md' + priority: MEDIUM + status: active + + - mistake: 'Generating Next.js or Remix server patterns' + mechanism: >- + Agents generate getServerSideProps, "use server" directives, + or Remix-style loader exports. TanStack Start uses + createServerFn for server-only code. + wrong_pattern: | + 'use server' + export async function getUser() { ... } + correct_pattern: | + const getUser = createServerFn({ method: 'GET' }) + .handler(async () => { ... }) + source: 'maintainer interview' + priority: CRITICAL + status: active + + - mistake: 'Relying on a route guard to protect a server function' + mechanism: >- + beforeLoad protects route UX, but createServerFn exposes an + independently callable endpoint. Private handlers must enforce + authentication and authorization themselves or through middleware. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + - mistake: 'Self-fetching a relative API URL from an SSR loader' + mechanism: >- + Loaders also run on the server, where relative URLs may not have a + base. App-internal loaders should call a server function directly. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + - mistake: 'Mutating without invalidating cached loader data' + mechanism: >- + Local state can show a write that was not persisted or leave route + cache stale. Await the write, invalidate, and verify a fresh reload. + source: 'protocol-v4 evaluation' + priority: HIGH + status: active + + - mistake: 'Treating typecheck as proof of output schema propagation' + mechanism: >- + A typed model can still be projected or serialized without the new + field. Assert the actual handler or HTTP payload at runtime. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + # ── Middleware and Context ─────────────────────────────────────── + - name: 'Middleware' + slug: 'middleware' + domain: 'middleware-and-context' + description: >- + Request middleware and server function middleware with + createMiddleware, context passing via next(), sendContext + for client-server transfer, global middleware via createStart + in src/start.ts, middleware factories, fetch override + precedence, header merging. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-client-core' + - '@tanstack/start-server-core' + covers: + - createMiddleware + - Request middleware (.server only) + - Server function middleware (.client + .server) + - Context passing via next({ context }) + - sendContext for client-server transfer + - Global middleware (createStart in src/start.ts) + - Middleware factories + - Fetch override precedence + - Header merging + - Method order enforcement (middleware → validator → client → server) + tasks: + - 'Add authentication middleware' + - 'Pass context through middleware chain' + - 'Configure global request middleware' + - 'Create reusable middleware factories' + failure_modes: + - mistake: 'Trusting client context without server validation' + mechanism: >- + Client context via sendContext is NOT validated by default. + Dynamic user-generated data must be validated in server-side + middleware before use. + source: 'docs/start/framework/react/guide/middleware.md' + priority: HIGH + status: active + + - mistake: 'Wrong middleware method order' + mechanism: >- + TypeScript enforces method order: middleware → validator + → client → server. Wrong order causes type errors and + runtime failures. + source: 'docs/start/framework/react/guide/middleware.md' + priority: MEDIUM + status: active + + - mistake: 'Confusing request vs server function middleware' + mechanism: >- + Request middleware runs on ALL server requests (SSR, server + routes, server functions). Server function middleware runs + only for server functions and has .client() method. Using + the wrong type causes unexpected scope. + source: 'docs/start/framework/react/guide/middleware.md' + priority: MEDIUM + status: active + + # ── Execution Model ────────────────────────────────────────────── + - name: 'Execution Model' + slug: 'execution-model' + domain: 'execution-model' + description: >- + Isomorphic code execution model, environment boundary functions + (createServerFn, createServerOnlyFn, createClientOnlyFn, + createIsomorphicFn), import protection, dead code elimination, + environment variable safety (VITE_ prefix), useHydrated hook. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-client-core' + - '@tanstack/start-server-core' + covers: + - Isomorphic-by-default principle + - createServerFn (RPC boundary) + - createServerOnlyFn (throws on client) + - createClientOnlyFn (throws on server) + - createIsomorphicFn (different impl per env) + - ClientOnly component + - useHydrated hook + - Import protection (experimental) + - Environment variables (VITE_ prefix, process.env) + - Dead code elimination / tree shaking + tasks: + - 'Protect server-only code from client bundles' + - 'Use environment-specific implementations' + - 'Handle environment variables safely' + - 'Debug import protection violations' + failure_modes: + - mistake: 'Assuming loaders are server-only' + mechanism: >- + ALL code in TanStack Start is isomorphic by default. + Loaders run on BOTH server and client. Server-only + operations must use createServerFn, createServerOnlyFn, + or server routes. + wrong_pattern: | + export const Route = createFileRoute('/dashboard')({ + loader: async () => { + const secret = process.env.API_SECRET + return fetch(`https://api.example.com/data`, { + headers: { Authorization: secret } + }) + }, + }) + correct_pattern: | + const getData = createServerFn({ method: 'GET' }) + .handler(async () => { + const secret = process.env.API_SECRET + return fetch(`https://api.example.com/data`, { + headers: { Authorization: secret } + }) + }) + + export const Route = createFileRoute('/dashboard')({ + loader: () => getData(), + }) + source: 'docs/start/framework/react/guide/execution-model.md' + priority: CRITICAL + status: active + skills: ['execution-model', 'server-functions'] + + - mistake: 'Exposing secrets via module-level process.env' + mechanism: >- + Module-level process.env access runs in both environments. + The variable value leaks into the client bundle. Access + secrets only inside createServerFn or createServerOnlyFn. + wrong_pattern: | + const apiKey = process.env.SECRET_KEY + export function fetchData() { ... } + correct_pattern: | + const fetchData = createServerFn({ method: 'GET' }) + .handler(async () => { + const apiKey = process.env.SECRET_KEY + return fetch(url, { headers: { Authorization: apiKey } }) + }) + source: 'docs/start/framework/react/guide/execution-model.md' + priority: CRITICAL + status: active + + - mistake: 'Using VITE_ prefix for server secrets' + mechanism: >- + VITE_ prefixed variables are exposed to the client bundle. + Server secrets must NOT have the VITE_ prefix. Access + them via process.env inside server functions only. + source: 'docs/start/framework/react/guide/environment-variables.md' + priority: CRITICAL + status: active + + - mistake: 'Hydration mismatches from env-dependent rendering' + mechanism: >- + Rendering different output from server-only environment state + causes the client hydration pass to disagree with the SSR HTML. + Transfer stable data or defer environment-dependent UI. + source: 'docs/start/framework/react/guide/execution-model.md' + priority: HIGH + status: active + + - mistake: 'Using a relative URL in an isomorphic loader' + mechanism: >- + Browser fetch resolves relative URLs against the document, while an + SSR runtime may have no base URL. Use a server function boundary. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + # ── Server Routes ──────────────────────────────────────────────── + - name: 'Server Routes' + slug: 'server-routes' + domain: 'server-routes' + description: >- + Define server-side API endpoints alongside app routes using + the server property with HTTP method handlers, per-handler + middleware via createHandlers, request/response patterns. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-server-core' + covers: + - server property on createFileRoute + - handlers object (GET, POST, PUT, DELETE) + - createHandlers for per-handler middleware + - Handler context (request, params, context) + - Request body parsing (json, text, formData) + - Response helpers (Response.json) + - File naming for API routes + tasks: + - 'Create a REST API endpoint' + - 'Add middleware to server route handlers' + - 'Handle different HTTP methods' + failure_modes: + - mistake: 'Duplicate path resolution for server routes' + mechanism: >- + Each route can only have a single handler file. Having + both users.ts and users/index.ts causes errors. + source: 'docs/start/framework/react/guide/server-routes.md' + priority: MEDIUM + status: active + + - mistake: 'Forgetting to await request body methods' + mechanism: >- + Request body readers return promises. Using request.json(), + request.text(), or request.formData() without await passes a promise + instead of the parsed request body. + source: 'docs/start/framework/react/guide/server-routes.md' + priority: MEDIUM + status: active + + - mistake: 'Relying on page auth to protect a server route' + mechanism: >- + API handlers are directly callable and must authenticate and + authorize private reads and writes at the handler boundary. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + - mistake: 'Self-fetching a server route from an SSR loader' + mechanism: >- + A relative API URL can fail during SSR. Share one server-side service + between a server function and server route instead. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + - mistake: 'Omitting a field from serialized response output' + mechanism: >- + Typechecking does not inspect the runtime Response payload. Test the + serialized output when a schema changes. + source: 'protocol-v4 evaluation' + priority: CRITICAL + status: active + + # ── Deployment and Rendering ───────────────────────────────────── + - name: 'Deployment' + slug: 'deployment' + domain: 'deployment-and-rendering' + description: >- + Deploy TanStack Start to Cloudflare Workers, Netlify, Vercel, + Node.js/Docker, Bun, Railway. Configure selective SSR, SPA + mode, static prerendering, ISR with Cache-Control headers. + type: core + packages: + - '@tanstack/react-start' + - '@tanstack/start-plugin-core' + covers: + - Cloudflare Workers deployment + - Netlify deployment + - Vercel / Railway deployment + - Node.js / Docker deployment + - Bun deployment + - Selective SSR (ssr option per route) + - SPA mode configuration + - Static prerendering (prerender option) + - ISR with Cache-Control headers + - SEO (head property, structured data) + tasks: + - 'Deploy to Cloudflare Workers' + - 'Deploy to Netlify' + - 'Configure selective SSR per route' + - 'Enable SPA mode' + - 'Set up static prerendering' + - 'Configure ISR with cache headers' + failure_modes: + - mistake: 'Bun deployment with React 18' + mechanism: >- + Bun-specific deployment only works with React 19. + For React 18, use Node.js deployment guidelines. + source: 'docs/start/framework/react/guide/hosting.md' + priority: MEDIUM + status: active + + - mistake: 'Missing nodejs_compat flag for Cloudflare Workers' + mechanism: >- + Cloudflare Workers requires compatibility_flags: + ["nodejs_compat"] in wrangler config. Without it, + Node.js APIs used by Start fail at runtime. + source: 'docs/start/framework/react/guide/hosting.md' + priority: HIGH + status: active + + - mistake: 'Child route loosening parent SSR config' + mechanism: >- + SSR config inherits from parent and can only become MORE + restrictive (true → data-only → false). A child cannot + set ssr: true if parent has ssr: false. + source: 'docs/start/framework/react/guide/selective-ssr.md' + priority: MEDIUM + status: active + +tensions: + - name: 'Isomorphic defaults vs server-only expectations' + skills: ['execution-model', 'server-functions'] + description: >- + All code runs everywhere by default. Agents trained on + Next.js/Remix assume loaders and route code are server-only. + implication: >- + Agents put secrets, DB queries, and file system access in + loaders instead of server functions, causing client-side + failures or security leaks. + + - name: 'Simplicity of isomorphic code vs security boundaries' + skills: ['execution-model', 'middleware'] + description: >- + The isomorphic model makes code easy to write but requires + explicit boundaries for security. Agents don't realize they + need to actively constrain execution environment. + implication: >- + Agents expose secrets via module-level process.env or + forget to validate sendContext data in middleware. + +cross_references: + - from: 'server-functions' + to: 'execution-model' + reason: 'Server functions ARE the isomorphic boundary — understanding the execution model is prerequisite' + - from: 'server-functions' + to: 'middleware' + reason: 'Server function middleware chains compose with server functions' + - from: 'middleware' + to: 'server-routes' + reason: 'Server routes use the same middleware system' + - from: 'deployment' + to: 'execution-model' + reason: 'Deployment target affects which environment code runs in' + +gaps: [] diff --git a/packages/start-client-core/skills/_artifacts/skill_spec.md b/packages/start-client-core/skills/_artifacts/skill_spec.md new file mode 100644 index 0000000000..841105ee17 --- /dev/null +++ b/packages/start-client-core/skills/_artifacts/skill_spec.md @@ -0,0 +1,103 @@ +# TanStack Start — Skill Spec + +TanStack Start is a full-stack React framework built on TanStack Router and Vite. It adds SSR, streaming, server functions (type-safe RPCs), middleware, server routes, and universal deployment. All code is isomorphic by default — it runs in both server and client environments unless explicitly constrained. + +## Domains + +| Domain | Description | Skills | +| ------------------------ | ------------------------------------------------------------- | ---------------- | +| Project Setup | Scaffolding, Vite plugin, router factory, root route, entries | start-core | +| Server Functions | Type-safe RPCs with createServerFn, validation, streaming | server-functions | +| Middleware and Context | Request/function middleware, context, global middleware | middleware | +| Execution Model | Isomorphic defaults, environment boundaries, env vars | execution-model | +| Server Routes | API endpoints, HTTP handlers, handler middleware | server-routes | +| Deployment and Rendering | Hosting, selective SSR, prerendering, SEO | deployment | + +## Skill Inventory + +| Skill | Type | Domain | What it covers | Failure modes | +| ------------------- | --------- | ------------------------ | ------------------------------------------------------- | ------------- | +| start-core | core | project-setup | tanstackStart(), getRouter(), root route, entries | 4 | +| server-functions | core | server-functions | createServerFn, validation, useServerFn, streaming | 8 | +| middleware | core | middleware-and-context | createMiddleware, context, global middleware, factories | 3 | +| execution-model | core | execution-model | Isomorphic defaults, environment functions, env vars | 5 | +| server-routes | core | server-routes | server property, HTTP handlers, createHandlers | 5 | +| deployment | core | deployment-and-rendering | Hosting, SSR modes, prerendering, SEO | 3 | +| react-start | framework | project-setup | React bindings, useServerFn, full setup | 3 | +| migrate-from-nextjs | lifecycle | project-setup | Next.js App Router migration checklist | 3 | + +## Failure Mode Inventory + +### start-core (4 failure modes) + +| # | Mistake | Priority | Source | +| --- | ----------------------------------------------- | -------- | ----------------------- | +| 1 | React plugin before Start plugin in Vite config | CRITICAL | docs/build-from-scratch | +| 2 | Enabling verbatimModuleSyntax in tsconfig | HIGH | docs/build-from-scratch | +| 3 | Missing Scripts component in root route | HIGH | docs/guide/routing | +| 4 | Loading every overlapping Start skill | HIGH | protocol-v4 evaluation | + +### server-functions (8 failure modes) + +| # | Mistake | Priority | Source | +| --- | --------------------------------------------------------------- | -------- | --------------------------- | +| 1 | Putting server-only code in loaders instead of server functions | CRITICAL | maintainer interview | +| 2 | Using dynamic imports for server functions | HIGH | docs/guide/server-functions | +| 3 | Not using useServerFn for component calls | MEDIUM | docs/guide/server-functions | +| 4 | Generating Next.js or Remix server patterns | CRITICAL | maintainer interview | +| 5 | Relying on a route guard to protect a server function | CRITICAL | protocol-v4 evaluation | +| 6 | Self-fetching a relative API URL from an SSR loader | CRITICAL | protocol-v4 evaluation | +| 7 | Mutating without invalidating cached loader data | HIGH | protocol-v4 evaluation | +| 8 | Treating typecheck as proof of output schema propagation | CRITICAL | protocol-v4 evaluation | + +### middleware (3 failure modes) + +| # | Mistake | Priority | Source | +| --- | ----------------------------------------------------- | -------- | --------------------- | +| 1 | Trusting client sendContext without server validation | HIGH | docs/guide/middleware | +| 2 | Confusing request vs server function middleware | MEDIUM | docs/guide/middleware | +| 3 | Wrong middleware method order | MEDIUM | docs/guide/middleware | + +### execution-model (5 failure modes) + +| # | Mistake | Priority | Source | +| --- | ------------------------------------------------- | -------- | -------------------------------- | +| 1 | Assuming loaders are server-only | CRITICAL | docs/guide/execution-model | +| 2 | Exposing secrets via module-level process.env | CRITICAL | docs/guide/execution-model | +| 3 | Using VITE\_ prefix for server secrets | CRITICAL | docs/guide/environment-variables | +| 4 | Hydration mismatches from env-dependent rendering | HIGH | docs/guide/execution-model | +| 5 | Using a relative URL in an isomorphic loader | CRITICAL | protocol-v4 evaluation | + +### server-routes (5 failure modes) + +| # | Mistake | Priority | Source | +| --- | ------------------------------------------------ | -------- | ------------------------ | +| 1 | Duplicate path resolution for server routes | MEDIUM | docs/guide/server-routes | +| 2 | Forgetting to await request body methods | MEDIUM | docs/guide/server-routes | +| 3 | Relying on page auth to protect a server route | CRITICAL | protocol-v4 evaluation | +| 4 | Self-fetching a server route from an SSR loader | CRITICAL | protocol-v4 evaluation | +| 5 | Omitting a field from serialized response output | CRITICAL | protocol-v4 evaluation | + +### deployment (3 failure modes) + +| # | Mistake | Priority | Source | +| --- | ------------------------------------------------- | -------- | ------------------------ | +| 1 | Missing nodejs_compat flag for Cloudflare Workers | HIGH | docs/guide/hosting | +| 2 | Bun deployment with React 18 | MEDIUM | docs/guide/hosting | +| 3 | Child route loosening parent SSR config | MEDIUM | docs/guide/selective-ssr | + +## Tensions + +| Tension | Skills | Agent implication | +| ---------------------------------------------------- | ---------------------------------- | ----------------------------------------------------------------------------- | +| Isomorphic defaults vs server-only expectations | execution-model ↔ server-functions | Agents put secrets/DB queries in loaders instead of server functions | +| Simplicity of isomorphic code vs security boundaries | execution-model ↔ middleware | Agents expose secrets via module-level process.env or skip context validation | + +## Cross-References + +| From | To | Reason | +| ---------------- | --------------- | ----------------------------------------------- | +| server-functions | execution-model | Server functions ARE the isomorphic boundary | +| server-functions | middleware | Middleware chains compose with server functions | +| middleware | server-routes | Server routes use the same middleware system | +| deployment | execution-model | Deployment target affects where code runs | diff --git a/packages/start-client-core/skills/_artifacts/skill_tree.yaml b/packages/start-client-core/skills/_artifacts/skill_tree.yaml new file mode 100644 index 0000000000..673f7ab543 --- /dev/null +++ b/packages/start-client-core/skills/_artifacts/skill_tree.yaml @@ -0,0 +1,120 @@ +# packages/start-client-core/skills/_artifacts/skill_tree.yaml +library: + name: '@tanstack/start-client-core' + version: '1.170.14' + repository: 'https://github.com/TanStack/router' + description: >- + Framework-agnostic client-side core for TanStack Start. + Provides server functions, middleware, execution model, + server routes, and deployment configuration. +generated_from: + domain_map: 'skills/_artifacts/domain_map.yaml' +generated_at: '2026-03-08' + +skills: + # ── Start Core Skills ─────────────────────────────────────────── + - name: 'Start Core' + slug: 'start-core' + type: 'core' + domain: 'project-setup' + path: 'skills/start-core/SKILL.md' + package: 'packages/start-client-core' + description: >- + Core overview for TanStack Start: tanstackStart() Vite plugin, + getRouter() factory, root route document shell (HeadContent, + Scripts, Outlet), client/server entry points, routeTree.gen.ts, + tsconfig configuration. Entry point for all Start skills. + sources: + - 'TanStack/router:docs/start/framework/react/build-from-scratch.md' + - 'TanStack/router:docs/start/framework/react/quick-start.md' + - 'TanStack/router:docs/start/framework/react/guide/routing.md' + + - name: 'Server Functions' + slug: 'start-core/server-functions' + type: 'sub-skill' + domain: 'server-functions' + path: 'skills/start-core/server-functions/SKILL.md' + package: 'packages/start-client-core' + description: >- + createServerFn (GET/POST), validator (Zod or function), + useServerFn hook, server context utilities (getRequest, + getRequestHeader, setResponseHeader, setResponseStatus), error + handling (throw errors, redirect, notFound), streaming + (ReadableStream, async generators), FormData handling, file + organization (.functions.ts, .server.ts). + requires: + - 'start-core' + sources: + - 'TanStack/router:docs/start/framework/react/guide/server-functions.md' + + - name: 'Middleware' + slug: 'start-core/middleware' + type: 'sub-skill' + domain: 'middleware-and-context' + path: 'skills/start-core/middleware/SKILL.md' + package: 'packages/start-client-core' + description: >- + createMiddleware, request middleware (.server only), server + function middleware (.client + .server), context passing via + next({ context }), sendContext for client-server transfer, + global middleware via createStart in src/start.ts, middleware + factories, method order enforcement. + requires: + - 'start-core' + - 'start-core/server-functions' + sources: + - 'TanStack/router:docs/start/framework/react/guide/middleware.md' + + - name: 'Execution Model' + slug: 'start-core/execution-model' + type: 'sub-skill' + domain: 'execution-model' + path: 'skills/start-core/execution-model/SKILL.md' + package: 'packages/start-client-core' + description: >- + Isomorphic-by-default principle, environment boundary functions + (createServerFn, createServerOnlyFn, createClientOnlyFn, + createIsomorphicFn), ClientOnly component, useHydrated hook, + import protection, dead code elimination, environment variable + safety (VITE_ prefix, process.env). + requires: + - 'start-core' + sources: + - 'TanStack/router:docs/start/framework/react/guide/execution-model.md' + - 'TanStack/router:docs/start/framework/react/guide/environment-variables.md' + + - name: 'Server Routes' + slug: 'start-core/server-routes' + type: 'sub-skill' + domain: 'server-routes' + path: 'skills/start-core/server-routes/SKILL.md' + package: 'packages/start-client-core' + description: >- + Server-side API endpoints using the server property on + createFileRoute, HTTP method handlers (GET, POST, PUT, DELETE), + createHandlers for per-handler middleware, handler context + (request, params, context), request body parsing, response + helpers, file naming for API routes. + requires: + - 'start-core' + sources: + - 'TanStack/router:docs/start/framework/react/guide/server-routes.md' + + - name: 'Deployment' + slug: 'start-core/deployment' + type: 'sub-skill' + domain: 'deployment-and-rendering' + path: 'skills/start-core/deployment/SKILL.md' + package: 'packages/start-client-core' + description: >- + Deploy to Cloudflare Workers, Netlify, Vercel, Node.js/Docker, + Bun, Railway. Selective SSR (ssr option per route), SPA mode, + static prerendering, ISR with Cache-Control headers, SEO and + head management. + requires: + - 'start-core' + sources: + - 'TanStack/router:docs/start/framework/react/guide/hosting.md' + - 'TanStack/router:docs/start/framework/react/guide/selective-ssr.md' + - 'TanStack/router:docs/start/framework/react/guide/static-prerendering.md' + - 'TanStack/router:docs/start/framework/react/guide/full-stack-seo.md' diff --git a/packages/start-client-core/skills/start-core/SKILL.md b/packages/start-client-core/skills/start-core/SKILL.md new file mode 100644 index 0000000000..60d9f3fcd1 --- /dev/null +++ b/packages/start-client-core/skills/start-core/SKILL.md @@ -0,0 +1,231 @@ +--- +name: start-core +description: >- + Core overview for TanStack Start: tanstackStart() Vite plugin, + getRouter() factory, root route document shell (HeadContent, + Scripts, Outlet), client/server entry points, routeTree.gen.ts, + tsconfig configuration. Entry point for all Start skills. +metadata: + type: core + library: tanstack-start + library_version: '1.170.14' +sources: + - TanStack/router:docs/start/framework/react/build-from-scratch.md + - TanStack/router:docs/start/framework/react/quick-start.md + - TanStack/router:docs/start/framework/react/guide/routing.md +--- + +# TanStack Start Core + +TanStack Start is a full-stack React framework built on TanStack Router and Vite. It adds SSR, streaming, server functions (type-safe RPCs), middleware, server routes, and universal deployment. + +> **CRITICAL**: All code in TanStack Start is ISOMORPHIC by default — it runs in BOTH server and client environments. Loaders run on both server AND client. To run code exclusively on the server, use `createServerFn`. This is the #1 AI agent mistake. +> **CRITICAL**: TanStack Start is NOT Next.js. Do not generate `getServerSideProps`, `"use server"` directives, `app/layout.tsx`, or any Next.js/Remix patterns. Use `createServerFn` for server-only code. +> **CRITICAL**: Types are FULLY INFERRED. Never cast, never annotate inferred values. + +Use this entry skill to pick one primary workflow. Do not load every Start sub-skill. Add another only when the implementation crosses that boundary; for example, a protected mutation needs `server-functions` plus `auth-server-primitives`, while a public REST endpoint needs `server-routes` alone. + +## Sub-Skills + +| Task | Sub-Skill | +| ------------------------------------------------ | ------------------------------------------------------------------------------- | +| Type-safe RPCs, data fetching, mutations | [start-core/server-functions/SKILL.md](./server-functions/SKILL.md) | +| Request/function middleware, context, auth | [start-core/middleware/SKILL.md](./middleware/SKILL.md) | +| Server-side auth: sessions, cookies, OAuth, CSRF | [start-core/auth-server-primitives/SKILL.md](./auth-server-primitives/SKILL.md) | +| Isomorphic execution, environment boundaries | [start-core/execution-model/SKILL.md](./execution-model/SKILL.md) | +| REST API endpoints alongside app routes | [start-core/server-routes/SKILL.md](./server-routes/SKILL.md) | +| Hosting, SSR modes, prerendering, SEO | [start-core/deployment/SKILL.md](./deployment/SKILL.md) | + +## Quick Decision Tree + +```text +Need to run code exclusively on the server (DB, secrets)? + → start-core/server-functions + +Need auth checks, logging, or shared logic across server functions? + → start-core/middleware + +Need to add login, sessions, OAuth, CSRF, password reset? + → start-core/auth-server-primitives + +Need to understand where code runs (server vs client)? + → start-core/execution-model + +Need a REST API endpoint (GET/POST/PUT/DELETE)? + → start-core/server-routes + +Need to deploy, configure SSR, or prerender? + → start-core/deployment +``` + +## Full-Stack Delivery Workflow + +For application data loaded by a Start route: + +1. Put database, filesystem, secrets, and persistence code behind `createServerFn`. +2. Call the server function directly from the route loader. Do not self-fetch a relative `/api/...` URL from an SSR loader. +3. Validate every input and enforce auth in the server function or middleware. `beforeLoad` only protects route UX. +4. After a mutation resolves, invalidate the router or the external query cache and await the refresh when the UI must be current before continuing. +5. For schema changes, update storage, validation, handler serialization, loader, and UI. Assert the actual runtime payload; typechecking alone cannot detect an omitted serialized field. + +Use a server route when the raw HTTP contract is the product: webhooks, third-party clients, feeds, file responses, or a public REST API. When the Start UI and a server route share data, call one server-side service from both instead of making the SSR loader fetch its own API route. + +Before finishing, test the initial SSR request, client navigation, mutation followed by refresh, and a direct anonymous request to every protected endpoint. + +## Project Setup + +### 1. Install Dependencies + +```bash +npm i @tanstack/react-start @tanstack/react-router react react-dom +npm i -D vite @vitejs/plugin-react typescript +``` + +### 2. Configure Vite + +```ts +// 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: [ + // MUST come before react() + tanstackStart(), + viteReact(), + ], +}) +``` + +### 3. Create Router Factory + +```tsx +// src/router.tsx +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + const router = createRouter({ + routeTree, + scrollRestoration: true, + }) + + return router +} +``` + +### 4. Create Root Route with Document Shell + +```tsx +// src/routes/__root.tsx +import type { ReactNode } from 'react' +import { + Outlet, + createRootRoute, + HeadContent, + Scripts, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'My App' }, + ], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} +``` + +### 5. Create Index Route with Server Function + +```tsx +// src/routes/index.tsx +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' + +const getGreeting = createServerFn({ method: 'GET' }).handler(async () => { + return { message: 'Hello from the server!' } +}) + +export const Route = createFileRoute('/')({ + loader: () => getGreeting(), + component: HomePage, +}) + +function HomePage() { + const data = Route.useLoaderData() + return

    {data.message}

    +} +``` + +## Common Mistakes + +### 1. CRITICAL: React plugin before Start plugin in Vite config + +```ts +// WRONG — route generation and server function compilation fail +plugins: [react(), tanstackStart()] + +// CORRECT — Start plugin must come first +plugins: [tanstackStart(), react()] +``` + +### 2. HIGH: Enabling verbatimModuleSyntax in tsconfig + +`verbatimModuleSyntax` causes server bundles to leak into client bundles. Keep it disabled. + +### 3. HIGH: Missing Scripts component in root route + +The `` component must be rendered in the `` of the root route. Without it, client-side JavaScript does not load and hydration fails. + +```tsx +// WRONG — no Scripts +function RootComponent() { + return ( + + + + + + + + + ) +} + +// CORRECT — Scripts in body +function RootComponent() { + return ( + + + + + + + + + + ) +} +``` + +## Version Note + +This skill targets `@tanstack/start-client-core` v1.170.14. diff --git a/packages/start-client-core/skills/start-core/auth-server-primitives/SKILL.md b/packages/start-client-core/skills/start-core/auth-server-primitives/SKILL.md new file mode 100644 index 0000000000..eb50266b00 --- /dev/null +++ b/packages/start-client-core/skills/start-core/auth-server-primitives/SKILL.md @@ -0,0 +1,415 @@ +--- +name: auth-server-primitives +description: >- + Server-side authentication primitives for TanStack Start: session + cookies (HttpOnly, Secure, SameSite, __Host- prefix), session + read/issue/destroy via createServerFn and middleware, OAuth + authorization-code flow with state and PKCE, password-reset + enumeration defense, CSRF for non-GET RPCs, rate limiting auth + endpoints, session rotation on privilege change. Pairs with + router-core/auth-and-guards for the routing side. +metadata: + type: sub-skill + library: tanstack-start + library_version: '1.170.14' +requires: + - start-core + - start-core/server-functions + - start-core/middleware +sources: + - TanStack/router:docs/start/framework/react/guide/authentication-overview.md + - TanStack/router:docs/start/framework/react/guide/authentication-server-primitives.md +--- + +# Auth Server Primitives + +This skill covers the **server half** of authentication: session storage, cookie issuance, OAuth flow, password-reset hardening, CSRF, rate limiting. For the **routing half** (`_authenticated` layout, `beforeLoad` redirects, RBAC checks), see `@tanstack/router-core#router-core/auth-and-guards`. + +> **CRITICAL**: Protect the data/API boundary first. Server functions, server routes, and other API endpoints that touch private data must enforce auth **inside the handler** or middleware. Route guards are route UX, not the data security boundary. +> **CRITICAL**: Validating the _shape_ of a client-supplied identifier (`z.string().uuid().parse(...)`) is not authorization. A parsed UUID is still _some_ tenant — re-check membership against the session principal before using it. +> **CRITICAL**: Read session/cookies inside `.handler()` or middleware `.server()`, not at module scope. Module-level reads run before requests exist (and are also undefined on Cloudflare Workers). + +## Production Checklist + +- Enforce auth in every server function, server route, or API endpoint that reads or writes private user, tenant, or account data. Use route `beforeLoad` for page UX, not as the data boundary. +- Use `.validator()` on every server function that accepts input. +- Store sessions in `HttpOnly`, `Secure`, `SameSite` cookies. Do not store session tokens in `localStorage` or `sessionStorage`. +- Hash passwords with bcrypt, scrypt, or Argon2. For missing users, verify against a dummy hash and return the same login/reset message. +- Rate limit login, registration, and password-reset endpoints. +- Use CSRF or same-origin protections for non-GET server functions and server routes. +- Log authentication events and monitor failures. +- Test direct unauthenticated calls to protected server functions; they should reject before returning data. +- Follow the anonymous redirect and inspect its HTML and serialized state. Login and unauthorized pages must not name the protected user, tenant, or record. + +## Session Cookies + +The recommended session storage is an HTTP-only cookie holding either an opaque session ID (with server-side lookup) or a signed/encrypted token. The cookie flags matter — set them all. + +```tsx +// src/server/session.ts +import { + deleteCookie, + getCookie, + setCookie, +} from '@tanstack/react-start/server' + +const SESSION_COOKIE = '__Host-session' // __Host- prefix binds to the exact origin + path '/' +const ONE_DAY = 60 * 60 * 24 + +const sessionCookieOptions = { + httpOnly: true, // not readable from JS — defeats XSS exfiltration + secure: true, // HTTPS only (required for __Host- prefix) + sameSite: 'lax', // sent on top-level navigations, blocks most CSRF + path: '/', // required for __Host- prefix +} as const + +export function setSessionCookie(token: string) { + setCookie(SESSION_COOKIE, token, { + ...sessionCookieOptions, + maxAge: ONE_DAY, + }) +} + +export function clearSessionCookie() { + deleteCookie(SESSION_COOKIE, sessionCookieOptions) +} + +export function readSessionToken(): string | null { + return getCookie(SESSION_COOKIE) ?? null +} +``` + +Write cookies with `setCookie` (or `appendResponseHeader('set-cookie', serialized)` for a cookie that a library already serialized). Do not use `setResponseHeader('Set-Cookie', ...)` for this: it replaces every cookie on the outgoing response, including cookies set by other middleware or returned by a handler. + +Flag rationale: + +- `HttpOnly` — JavaScript can't read the cookie, so an XSS bug can't steal the session. +- `Secure` — HTTPS only. Required when using `__Host-` prefix. +- `SameSite=Lax` — blocks CSRF on most cross-origin POST/PUT/DELETE. Use `Strict` for highest-security flows where loss of cross-site GET navigation is acceptable. +- `__Host-` prefix — binds the cookie to the exact origin (no Domain attribute, Path must be `/`, Secure must be set). Prevents subdomain takeover from forging a session cookie. +- `Path=/` — required by `__Host-`. +- `Max-Age` — finite lifetime so a stolen cookie isn't useful forever. Pair with server-side session rotation. + +## Session Lookup as Middleware + +Use middleware to centralize session loading so every protected handler sees a typed session: + +```tsx +// src/server/auth-middleware.ts +import { createMiddleware } from '@tanstack/react-start' +import { readSessionToken } from './session' + +export const authMiddleware = createMiddleware({ type: 'function' }).server( + async ({ next }) => { + const token = readSessionToken() + const session = token ? await db.sessions.findValid(token) : null + if (!session) throw new Error('Unauthorized') + return next({ context: { session } }) + }, +) +``` + +Attach it to every server function that needs a logged-in user: + +```tsx +import { createServerFn } from '@tanstack/react-start' +import { authMiddleware } from '~/server/auth-middleware' + +export const getMyOrders = createServerFn({ method: 'GET' }) + .middleware([authMiddleware]) + .handler(async ({ context }) => { + return db.orders.findMany({ where: { userId: context.session.userId } }) + }) +``` + +> **Route guards do not cover this.** A `createFileRoute('/_authenticated/orders')` with a `beforeLoad` redirect does NOT protect `getMyOrders` — the RPC is reachable directly whether or not the user ever hits the route. Apply `authMiddleware` (or re-check inside `.handler()`) on every server function that needs auth. + +## Issuing a Session on Login + +```tsx +// src/server/login.functions.ts +import { createServerFn } from '@tanstack/react-start' +import { z } from 'zod' +import { setSessionCookie } from './session' + +export const login = createServerFn({ method: 'POST' }) + .validator(z.object({ email: z.string().email(), password: z.string() })) + .handler(async ({ data }) => { + const user = await db.users.findByEmail(data.email) + // Always run verifyPasswordHash — even when the user doesn't exist — + // so the user-not-found branch takes the same time as wrong-password. + // DUMMY_PASSWORD_HASH is a hash of any throwaway password computed once + // at startup with the same algorithm/cost as real password hashes. + const hashToCheck = user?.passwordHash ?? DUMMY_PASSWORD_HASH + const passwordMatches = await verifyPasswordHash(hashToCheck, data.password) + const ok = user != null && passwordMatches + if (!ok) throw new Error('Invalid email or password') + + // ROTATE on privilege change: destroy any existing session, then issue fresh. + await db.sessions.revokeAllForUser(user.id) + const token = await db.sessions.create({ userId: user.id }) + setSessionCookie(token) + return { ok: true } + }) +``` + +## Logout + +```tsx +import { createServerFn } from '@tanstack/react-start' +import { authMiddleware } from '~/server/auth-middleware' +import { clearSessionCookie } from '~/server/session' + +export const logout = createServerFn({ method: 'POST' }) + .middleware([authMiddleware]) + .handler(async ({ context }) => { + await db.sessions.revoke(context.session.id) + clearSessionCookie() + return { ok: true } + }) +``` + +## OAuth: state + PKCE + +For OAuth authorization-code flow, generate a one-time `state` (CSRF defense) and a PKCE verifier (defense against authorization-code interception). Store both in a short-lived signed cookie keyed to this exact login attempt. + +```tsx +// 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 crypto from 'node:crypto' + +const OAUTH_STATE_COOKIE = '__Host-oauth' // expires fast; one-shot + +function base64url(buf: Buffer) { + return buf + .toString('base64') + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_') +} + +export const startOAuth = createServerFn({ method: 'GET' }).handler( + async () => { + const state = base64url(crypto.randomBytes(32)) + const verifier = base64url(crypto.randomBytes(32)) + const challenge = base64url( + crypto.createHash('sha256').update(verifier).digest(), + ) + + setCookie(OAUTH_STATE_COOKIE, signed({ state, verifier }), { + httpOnly: true, + secure: true, + sameSite: 'lax', + path: '/', + maxAge: 600, + }) + + throw redirect({ + href: + `https://provider.example/authorize` + + `?response_type=code` + + `&client_id=${process.env.OAUTH_CLIENT_ID}` + + `&redirect_uri=${encodeURIComponent(process.env.OAUTH_REDIRECT_URI!)}` + + `&state=${state}` + + `&code_challenge=${challenge}` + + `&code_challenge_method=S256`, + }) + }, +) +``` + +In the callback handler, **verify the cookie state matches the returned state** and exchange the code with the verifier. If state is missing or doesn't match, abort — the request did not originate from your `startOAuth`. + +## Password Reset: defeat user enumeration + +When a user requests a reset, do not let the response shape or timing reveal whether the email is registered. + +```tsx +import { createServerFn } from '@tanstack/react-start' +import { z } from 'zod' + +export const requestPasswordReset = createServerFn({ method: 'POST' }) + .validator(z.object({ email: z.string().email() })) + .handler(async ({ data }) => { + const user = await db.users.findByEmail(data.email) + if (user) { + const token = await db.passwordResets.issue(user.id) + await sendResetEmail(user.email, token) + } + // Always 200, always the same body, regardless of whether the user exists. + // The user is told to check their inbox; no confirmation either way. + return { ok: true } + }) +``` + +Do NOT: + +- Return 200 if exists, 404 if not. +- Use a different message ("we sent you a link" vs "no account found"). +- Skip the work when the user doesn't exist (timing leak — measurable from the wire). + +## CSRF for non-GET RPCs + +`SameSite=Lax` on the session cookie blocks most cross-site CSRF for POST/PUT/DELETE. Two cases need extra defense: + +1. **Top-level GET navigation that mutates** — never do this. Always use POST/PUT/DELETE for mutations. +2. **POST from a page on a sibling subdomain** — `SameSite=Lax` does NOT block this; verify the `Origin` header matches your app's origin in middleware. + +```tsx +import { createMiddleware } from '@tanstack/react-start' +import { getRequest } from '@tanstack/react-start/server' + +export const csrfMiddleware = createMiddleware().server(async ({ next }) => { + const request = getRequest() + if (request.method !== 'GET' && request.method !== 'HEAD') { + const origin = request.headers.get('origin') + // Compare the FULL origin (scheme + host + port) — host alone lets + // http://example.com pass a check meant for https://example.com. + if (!origin || new URL(origin).origin !== process.env.APP_ORIGIN) { + throw new Error('Origin check failed') + } + } + return next() +}) +``` + +Attach this to global request middleware in `src/start.ts` so it covers every non-GET request, including server routes and SSR. + +## Rate Limiting Auth Endpoints + +A login endpoint without rate limiting is a credential-stuffing target. Limit per-IP (and ideally per-account) with a sliding window. + +```tsx +import { createMiddleware } from '@tanstack/react-start' +import { getRequest } from '@tanstack/react-start/server' + +function rateLimitMiddleware(opts: { + key: string + max: number + windowMs: number +}) { + return createMiddleware().server(async ({ next }) => { + const request = getRequest() + const ip = + request.headers.get('cf-connecting-ip') ?? + request.headers.get('x-forwarded-for')?.split(',')[0] ?? + 'unknown' + const bucketKey = `rl:${opts.key}:${ip}` + const allowed = await rateLimiter.consume( + bucketKey, + opts.max, + opts.windowMs, + ) + if (!allowed) throw new Error('Too many requests') + return next() + }) +} + +// On the login server function: +export const login = createServerFn({ method: 'POST' }).middleware([ + rateLimitMiddleware({ key: 'login', max: 5, windowMs: 60_000 }), +]) +// ... +``` + +## Session Rotation on Privilege Change + +Whenever the user's privileges change — login, logout, role change, password change — **destroy the old session and issue a new one**. This neutralizes session-fixation attacks where an attacker plants their own session ID in the victim's browser before login. + +```tsx +// In the login handler (already shown above): destroy any pre-login session, then create a fresh one. +await db.sessions.revokeAllForUser(user.id) +const token = await db.sessions.create({ userId: user.id }) +setSessionCookie(token) +``` + +```tsx +// On password change / role grant: +await db.sessions.revokeAllForUser(user.id) // destroy existing +const token = await db.sessions.create({ userId: user.id }) // issue fresh +setSessionCookie(token) +``` + +## Common Mistakes + +### CRITICAL: Trusting the route guard for server-function auth + +```tsx +// WRONG — the RPC is callable directly via POST regardless of the route +export const Route = createFileRoute('/_authenticated/orders')({ + beforeLoad: ({ context }) => { + if (!context.auth.isAuthenticated) throw redirect({ to: '/login' }) + }, +}) +const getMyOrders = createServerFn({ method: 'GET' }).handler(async () => { + return db.orders.findMany() // ← anyone can hit the RPC and get all orders +}) + +// CORRECT — auth enforced on the handler itself +const getMyOrders = createServerFn({ method: 'GET' }) + .middleware([authMiddleware]) + .handler(async ({ context }) => { + return db.orders.findMany({ where: { userId: context.session.userId } }) + }) +``` + +### CRITICAL: Treating shape validation as authorization + +A parsed UUID is _some_ workspace, not an _authorized_ workspace. + +```tsx +// WRONG — UUID is well-formed but the user may not be a member +const getWorkspaceData = createServerFn({ method: 'GET' }) + .middleware([authMiddleware]) + .validator(z.object({ workspaceId: z.string().uuid() })) + .handler(async ({ context, data }) => { + return db.workspaces.findById(data.workspaceId) // missing membership check! + }) + +// CORRECT — verify the session principal has access to that workspace +const getWorkspaceData = createServerFn({ method: 'GET' }) + .middleware([authMiddleware]) + .validator(z.object({ workspaceId: z.string().uuid() })) + .handler(async ({ context, data }) => { + const member = await db.memberships.find({ + userId: context.session.userId, + workspaceId: data.workspaceId, + }) + if (!member) throw new Error('Not a member of this workspace') + return db.workspaces.findById(data.workspaceId) + }) +``` + +### HIGH: Returning different responses based on email existence + +Already covered above — `requestPasswordReset` must return the same body regardless of whether the email matches a user. + +### HIGH: Reading cookies/env at module scope + +```tsx +// WRONG — module-load time, before any request exists +const SESSION_SECRET = process.env.SESSION_SECRET +export function signSession(payload) { + return sign(payload, SESSION_SECRET) +} + +// CORRECT — read inside per-request callback +export function signSession(payload) { + return sign(payload, process.env.SESSION_SECRET) +} +``` + +On Cloudflare Workers and other edge runtimes, the module-level read evaluates to `undefined` even on the server because env is injected per-request. See [start-core/execution-model](../execution-model/SKILL.md). + +### MEDIUM: Long-lived sessions with no rotation + +A session token that never rotates is functionally a long-lived credential. Rotate on login, logout, password change, and role/permission change. + +## Cross-References + +- `@tanstack/router-core#router-core/auth-and-guards` — the routing side: `_authenticated` layout, `beforeLoad`, `redirect`, RBAC checks. +- [start-core/server-functions](../server-functions/SKILL.md) — how to expose RPCs (and how the route guard does NOT cover them). +- [start-core/middleware](../middleware/SKILL.md) — composing `authMiddleware` and others. +- [start-core/execution-model](../execution-model/SKILL.md) — why module-level env/secret reads are wrong. diff --git a/packages/start-client-core/skills/start-core/deployment/SKILL.md b/packages/start-client-core/skills/start-core/deployment/SKILL.md new file mode 100644 index 0000000000..39939ea5e7 --- /dev/null +++ b/packages/start-client-core/skills/start-core/deployment/SKILL.md @@ -0,0 +1,316 @@ +--- +name: deployment +description: >- + Deploy to Cloudflare Workers, Netlify, Vercel, Node.js/Docker, + Bun, Railway. Selective SSR (ssr option per route), SPA mode, + static prerendering, ISR with Cache-Control headers, SEO and + head management. +metadata: + type: sub-skill + library: tanstack-start + library_version: '1.170.14' +requires: + - start-core +sources: + - TanStack/router:docs/start/framework/react/guide/hosting.md + - TanStack/router:docs/start/framework/react/guide/selective-ssr.md + - TanStack/router:docs/start/framework/react/guide/static-prerendering.md + - TanStack/router:docs/start/framework/react/guide/seo.md +--- + +# Deployment and Rendering + +TanStack Start deploys to any hosting provider via Vite and Nitro. This skill covers hosting setup, SSR configuration, prerendering, and SEO. + +## Hosting Providers + +### Cloudflare Workers + +```bash +pnpm add -D @cloudflare/vite-plugin wrangler +``` + +```ts +// vite.config.ts +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { cloudflare } from '@cloudflare/vite-plugin' +import viteReact from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [ + cloudflare({ viteEnvironment: { name: 'ssr' } }), + tanstackStart(), + viteReact(), + ], +}) +``` + +```jsonc +// wrangler.jsonc +{ + "name": "my-app", + "compatibility_date": "2025-09-02", + "compatibility_flags": ["nodejs_compat"], + "main": "@tanstack/react-start/server-entry", +} +``` + +Deploy: `npx wrangler login && pnpm run deploy` + +> **Worker env is per-request.** Cloudflare Workers inject env vars at request time. `process.env.X` at module scope evaluates to `undefined` even on the server. The Cloudflare-canonical way to read env (including from module scope) is the `cloudflare:workers` env binding: +> +> ```ts +> import { env } from 'cloudflare:workers' +> const apiHost = env.API_HOST +> ``` +> +> Or read `process.env.X` per-request inside `.handler()` / middleware `.server()`. See [Cloudflare's environment-variables docs](https://developers.cloudflare.com/workers/configuration/environment-variables/) and [start-core/execution-model](../execution-model/SKILL.md). + +### Netlify + +```bash +pnpm add -D @netlify/vite-plugin-tanstack-start +``` + +```ts +// vite.config.ts +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import netlify from '@netlify/vite-plugin-tanstack-start' +import viteReact from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [tanstackStart(), netlify(), viteReact()], +}) +``` + +Deploy: `npx netlify deploy` + +### Nitro (Vercel, Railway, Node.js, Docker) + +```bash +npm install nitro@npm:nitro-nightly@latest +``` + +```ts +// vite.config.ts +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { nitro } from 'nitro/vite' +import viteReact from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [tanstackStart(), nitro(), viteReact()], +}) +``` + +Build and start: `npm run build && node .output/server/index.mjs` + +### Bun + +Bun deployment requires React 19. For React 18, use Node.js deployment. + +```ts +// vite.config.ts — add bun preset to nitro +plugins: [tanstackStart(), nitro({ preset: 'bun' }), viteReact()] +``` + +## Selective SSR + +Control SSR per route with the `ssr` property. + +### `ssr: true` (default) + +Runs `beforeLoad` and `loader` on server, renders component on server: + +```tsx +export const Route = createFileRoute('/posts/$postId')({ + ssr: true, // default + loader: () => fetchPost(), // runs on server during SSR + component: PostPage, // rendered on server +}) +``` + +### `ssr: false` + +Disables server execution of `beforeLoad`/`loader` and server rendering: + +```tsx +export const Route = createFileRoute('/dashboard')({ + ssr: false, + loader: () => fetchDashboard(), // runs on client only + component: DashboardPage, // rendered on client only +}) +``` + +### `ssr: 'data-only'` + +Runs `beforeLoad`/`loader` on server but renders component on client only: + +```tsx +export const Route = createFileRoute('/canvas')({ + ssr: 'data-only', + loader: () => fetchCanvasData(), // runs on server + component: CanvasPage, // rendered on client only +}) +``` + +### Functional Form + +Decide SSR at runtime based on params/search: + +```tsx +export const Route = createFileRoute('/docs/$docType/$docId')({ + ssr: ({ params }) => { + if (params.status === 'success' && params.value.docType === 'sheet') { + return false + } + }, +}) +``` + +### SSR Inheritance + +Children inherit parent SSR config and can only be MORE restrictive: + +- `true` → `data-only` or `false` (allowed) +- `false` → `true` (NOT allowed — parent `false` wins) + +### Default SSR + +Change the default for all routes in `src/start.ts`: + +```tsx +import { createStart } from '@tanstack/react-start' + +export const startInstance = createStart(() => ({ + defaultSsr: false, +})) +``` + +## Static Prerendering + +Generate static HTML at build time: + +```ts +// vite.config.ts +tanstackStart({ + prerender: { + enabled: true, + crawlLinks: true, + concurrency: 14, + failOnError: true, + }, +}) +``` + +Static routes are auto-discovered. Dynamic routes (e.g. `/users/$userId`) require `crawlLinks` or explicit `pages` config. + +## SEO and Head Management + +### Basic Meta Tags + +```tsx +export const Route = createFileRoute('/')({ + head: () => ({ + meta: [ + { title: 'My App - Home' }, + { name: 'description', content: 'Welcome to My App' }, + ], + }), +}) +``` + +### Dynamic Meta from Loader Data + +```tsx +export const Route = createFileRoute('/posts/$postId')({ + loader: async ({ params }) => fetchPost(params.postId), + head: ({ loaderData }) => ({ + meta: [ + { title: loaderData.title }, + { name: 'description', content: loaderData.excerpt }, + { property: 'og:title', content: loaderData.title }, + { property: 'og:image', content: loaderData.coverImage }, + ], + }), +}) +``` + +### Structured Data (JSON-LD) + +```tsx +head: ({ loaderData }) => ({ + scripts: [ + { + type: 'application/ld+json', + children: JSON.stringify({ + '@context': 'https://schema.org', + '@type': 'Article', + headline: loaderData.title, + }), + }, + ], +}) +``` + +### Dynamic Sitemap via Server Route + +```ts +// src/routes/sitemap[.]xml.ts +export const Route = createFileRoute('/sitemap.xml')({ + server: { + handlers: { + GET: async () => { + const posts = await fetchAllPosts() + const sitemap = ` + + ${posts.map((p) => `https://myapp.com/posts/${p.id}`).join('')} +` + return new Response(sitemap, { + headers: { 'Content-Type': 'application/xml' }, + }) + }, + }, + }, +}) +``` + +## Common Mistakes + +### 1. HIGH: Missing nodejs_compat flag for Cloudflare Workers + +```jsonc +// WRONG — Node.js APIs fail at runtime +{ "compatibility_flags": [] } + +// CORRECT +{ "compatibility_flags": ["nodejs_compat"] } +``` + +### 2. MEDIUM: Bun deployment with React 18 + +Bun-specific deployment only works with React 19. Use Node.js deployment for React 18. + +### 3. MEDIUM: Child route loosening parent SSR config + +```tsx +// Parent sets ssr: false +// WRONG — child cannot upgrade to ssr: true +const parentRoute = createFileRoute('/dashboard')({ ssr: false }) +const childRoute = createFileRoute('/dashboard/stats')({ + ssr: true, // IGNORED — parent false wins +}) + +// CORRECT — children can only be MORE restrictive +const parentRoute = createFileRoute('/dashboard')({ ssr: 'data-only' }) +const childRoute = createFileRoute('/dashboard/stats')({ + ssr: false, // OK — more restrictive than parent +}) +``` + +## Cross-References + +- [start-core/server-routes](../server-routes/SKILL.md) — API endpoints for sitemaps, robots.txt +- [start-core/execution-model](../execution-model/SKILL.md) — SSR affects where code runs diff --git a/packages/start-client-core/skills/start-core/execution-model/SKILL.md b/packages/start-client-core/skills/start-core/execution-model/SKILL.md new file mode 100644 index 0000000000..271efe6bf1 --- /dev/null +++ b/packages/start-client-core/skills/start-core/execution-model/SKILL.md @@ -0,0 +1,353 @@ +--- +name: execution-model +description: >- + Isomorphic-by-default principle, environment boundary functions + (createServerFn, createServerOnlyFn, createClientOnlyFn, + createIsomorphicFn), ClientOnly component, useHydrated hook, + import protection, dead code elimination, environment variable + safety (VITE_ prefix, process.env). +metadata: + type: sub-skill + library: tanstack-start + library_version: '1.170.14' +requires: + - start-core +sources: + - TanStack/router:docs/start/framework/react/guide/execution-model.md + - TanStack/router:docs/start/framework/react/guide/environment-variables.md + - TanStack/router:docs/start/framework/react/guide/import-protection.md +--- + +# Execution Model + +Understanding where code runs is fundamental to TanStack Start. This skill covers the isomorphic execution model and how to control environment boundaries. + +> **CRITICAL**: ALL code in TanStack Start is isomorphic by default — it runs in BOTH server and client bundles. Route loaders run on BOTH server (during SSR) AND client (during navigation). Server-only operations MUST use `createServerFn`. +> **CRITICAL**: Module-level `process.env` access is wrong on **two** axes — security (values leak into the client bundle) AND runtime correctness (on Cloudflare Workers and other edge runtimes, env is injected per-request, so module-level reads evaluate to `undefined` even on the server). Read env inside `.handler()` or another per-request function, never at module scope. +> **CRITICAL**: `VITE_` prefixed environment variables are exposed to the client bundle. Server secrets must NOT have the `VITE_` prefix. +> **CRITICAL**: Relative URLs belong to browser-only code. An isomorphic loader also runs during SSR, where `fetch('/api/...')` may have no base URL. Call a server function from the loader, or keep the fetch inside an explicit environment boundary. + +## Execution Control APIs + +| API | Use Case | Client Behavior | Server Behavior | +| ------------------------------------------- | --------------------------- | ------------------------- | --------------------- | +| `createServerFn()` | RPC calls, data mutations | Network request to server | Direct execution | +| `createServerOnlyFn(fn)` | Utility functions | Throws error | Direct execution | +| `createClientOnlyFn(fn)` | Browser utilities | Direct execution | Throws error | +| `createIsomorphicFn()` | Different impl per env | Uses `.client()` impl | Uses `.server()` impl | +| `` | Browser-only components | Renders children | Renders fallback | +| `useHydrated()` | Hydration-dependent logic | `true` after hydration | `false` | +| `import '@tanstack/-start/server-only'` | Mark whole file server-only | Import denied | Allowed | +| `import '@tanstack/-start/client-only'` | Mark whole file client-only | Allowed | Import denied | + +## Server-Only Execution + +### createServerFn (RPC pattern) + +The primary way to run server-only code. On the client, calls become fetch requests: + +```tsx +// Use @tanstack/-start for your framework (react, solid, vue) +import { createServerFn } from '@tanstack/react-start' + +const fetchUser = createServerFn().handler(async () => { + const secret = process.env.API_SECRET // safe — server only + return await db.users.find() +}) + +// Client calls this via network request +const user = await fetchUser() +``` + +### createServerOnlyFn (throws on client) + +For utility functions that must never run on client: + +```tsx +// Use @tanstack/-start for your framework (react, solid, vue) +import { createServerOnlyFn } from '@tanstack/react-start' + +const getSecret = createServerOnlyFn(() => process.env.DATABASE_URL) + +// Server: returns the value +// Client: THROWS an error +``` + +## Client-Only Execution + +### createClientOnlyFn + +```tsx +// Use @tanstack/-start for your framework (react, solid, vue) +import { createClientOnlyFn } from '@tanstack/react-start' + +const saveToStorage = createClientOnlyFn((key: string, value: string) => { + localStorage.setItem(key, value) +}) +``` + +### ClientOnly Component + +```tsx +// Use @tanstack/-router for your framework (react, solid, vue) +import { ClientOnly } from '@tanstack/react-router' + +function Analytics() { + return ( + + + + ) +} +``` + +### useHydrated Hook + +```tsx +// Use @tanstack/-router for your framework (react, solid, vue) +import { useHydrated } from '@tanstack/react-router' + +function TimeZoneDisplay() { + const hydrated = useHydrated() + const timeZone = hydrated + ? Intl.DateTimeFormat().resolvedOptions().timeZone + : 'UTC' + + return
    Your timezone: {timeZone}
    +} +``` + +Behavior: SSR → `false`, first client render → `false`, after hydration → `true` (stays `true`). + +## Environment-Specific Implementations + +```tsx +// Use @tanstack/-start for your framework (react, solid, vue) +import { createIsomorphicFn } from '@tanstack/react-start' + +const getDeviceInfo = createIsomorphicFn() + .server(() => ({ type: 'server', platform: process.platform })) + .client(() => ({ type: 'client', userAgent: navigator.userAgent })) +``` + +## Import Protection: File Markers + +> Experimental. + +The `.server.*` and `.client.*` filename suffixes (e.g. `db.server.ts`) opt a file into Start's import protection — it can't be imported from the wrong environment. When you can't or don't want to rename the file, add a side-effect import at the top of the file to apply the same protection by marker: + +```ts +// src/lib/secrets.ts (filename can't be *.server.ts) +import '@tanstack/react-start/server-only' +// (or @tanstack/solid-start/server-only, @tanstack/vue-start/server-only) + +export function getApiKey() { + return process.env.API_KEY +} +``` + +```ts +// src/lib/storage.ts +import '@tanstack/react-start/client-only' +// (or @tanstack/solid-start/client-only, @tanstack/vue-start/client-only) + +export function savePreferences(prefs: Record) { + localStorage.setItem('prefs', JSON.stringify(prefs)) +} +``` + +Rules: + +- Both markers in the same file is an error. +- Type-only imports are ignored (they erase to nothing at runtime). +- Default behavior is `error` in production builds and `mock` in dev. The mock returns a recursive Proxy so dev keeps running while you fix the import graph. + +Pick the right tool: + +- File should never run on the wrong side **and** has no client API → `*.server.ts` filename or `import '@tanstack/-start/server-only'`. +- One symbol needs to behave differently per environment → `createIsomorphicFn().client(...).server(...)`. +- One function should error if called from the wrong side → `createServerOnlyFn` / `createClientOnlyFn`. +- Component renders only after hydration → `` or `useHydrated()`. + +## Environment Variables + +### Server-Side (inside createServerFn) + +Access any variable via `process.env`: + +```tsx +const connectDb = createServerFn().handler(async () => { + const url = process.env.DATABASE_URL // no prefix needed + return createConnection(url) +}) +``` + +### Client-Side (components) + +Only `VITE_` prefixed variables are available: + +```tsx +// Framework-specific component type (React.ReactNode, JSX.Element, etc.) +function ApiProvider({ children }: { children: React.ReactNode }) { + const apiUrl = import.meta.env.VITE_API_URL // available + // import.meta.env.DATABASE_URL → undefined (security) + return ( + {children} + ) +} +``` + +### Runtime Client Variables + +If you need server-side variables on the client without `VITE_` prefix, pass them through a server function: + +```tsx +const getRuntimeVar = createServerFn({ method: 'GET' }).handler(() => { + return process.env.MY_RUNTIME_VAR +}) + +export const Route = createFileRoute('/')({ + loader: async () => { + const foo = await getRuntimeVar() + return { foo } + }, + component: () => { + const { foo } = Route.useLoaderData() + return
    {foo}
    + }, +}) +``` + +### Type Safety for Environment Variables + +```tsx +// src/env.d.ts +/// + +interface ImportMetaEnv { + readonly VITE_APP_NAME: string + readonly VITE_API_URL: string +} + +interface ImportMeta { + readonly env: ImportMetaEnv +} + +declare global { + namespace NodeJS { + interface ProcessEnv { + readonly DATABASE_URL: string + readonly JWT_SECRET: string + } + } +} + +export {} +``` + +## Common Mistakes + +### 1. CRITICAL: Assuming loaders are server-only + +```tsx +// WRONG — loader runs on BOTH server and client +export const Route = createFileRoute('/dashboard')({ + loader: async () => { + const secret = process.env.API_SECRET // LEAKED to client + return fetch(`https://api.example.com/data`, { + headers: { Authorization: secret }, + }) + }, +}) + +// CORRECT — use createServerFn +const getData = createServerFn({ method: 'GET' }).handler(async () => { + const secret = process.env.API_SECRET + return fetch(`https://api.example.com/data`, { + headers: { Authorization: secret }, + }) +}) + +export const Route = createFileRoute('/dashboard')({ + loader: () => getData(), +}) +``` + +### 2. CRITICAL: Reading process.env at module scope + +Module-level `process.env` reads are wrong for **two** reasons, not one: + +1. **Security:** the value can be inlined into the client bundle, leaking secrets. +2. **Runtime correctness (edge runtimes):** Cloudflare Workers and other edge SSR runtimes inject env at request time. Module-level code runs at module load, before the env exists, so the read evaluates to `undefined` even on the server. The bug only surfaces at deploy time. + +```tsx +// WRONG — leaks to client AND is undefined on Workers +const apiKey = process.env.SECRET_KEY +export function fetchData() { + /* uses apiKey, which is undefined under Worker SSR */ +} + +// CORRECT — read per-request, inside the handler +const fetchData = createServerFn({ method: 'GET' }).handler(async () => { + const apiKey = process.env.SECRET_KEY + return fetch(url, { headers: { Authorization: apiKey } }) +}) +``` + +The same rule applies to middleware `.server()` callbacks, server-route handlers, and any function that runs per request — read env there, not at the top of the file. + +### 3. CRITICAL: Using VITE\_ prefix for server secrets + +```bash +# WRONG — exposed to client bundle +VITE_SECRET_API_KEY=sk_live_xxx + +# CORRECT — no prefix for server secrets +SECRET_API_KEY=sk_live_xxx + +# CORRECT — VITE_ only for public client values +VITE_APP_NAME=My App +``` + +### 4. HIGH: Hydration mismatches + +```tsx +// WRONG — different content server vs client +function CurrentTime() { + return
    {new Date().toLocaleString()}
    +} + +// CORRECT — consistent rendering +function CurrentTime() { + const [time, setTime] = useState() + useEffect(() => { + setTime(new Date().toLocaleString()) + }, []) + return
    {time || 'Loading...'}
    +} +``` + +## Architecture Decision Framework + +**Server-Only** (`createServerFn` / `createServerOnlyFn`): + +- Sensitive data (env vars, secrets) +- Database connections, file system +- External API keys + +**Client-Only** (`createClientOnlyFn` / ``): + +- DOM manipulation, browser APIs +- localStorage, geolocation +- Analytics/tracking + +**Isomorphic** (default / `createIsomorphicFn`): + +- Data formatting, business logic +- Shared utilities +- Route loaders (they're isomorphic by nature) + +## Cross-References + +- [start-core/server-functions](../server-functions/SKILL.md) — the primary server boundary +- [start-core/deployment](../deployment/SKILL.md) — deployment target affects execution diff --git a/packages/start-client-core/skills/start-core/middleware/SKILL.md b/packages/start-client-core/skills/start-core/middleware/SKILL.md new file mode 100644 index 0000000000..f98d8b1852 --- /dev/null +++ b/packages/start-client-core/skills/start-core/middleware/SKILL.md @@ -0,0 +1,399 @@ +--- +name: middleware +description: >- + createMiddleware, request middleware (.server only), server function + middleware (.client + .server), context passing via next({ context }), + sendContext for client-server transfer, global middleware via + createStart in src/start.ts, middleware factories, method order + enforcement, fetch override precedence. +metadata: + type: sub-skill + library: tanstack-start + library_version: '1.170.14' +requires: + - start-core + - start-core/server-functions +sources: + - TanStack/router:docs/start/framework/react/guide/middleware.md +--- + +# Middleware + +Middleware customizes the behavior of server functions and server routes. It is composable — middleware can depend on other middleware to form a chain. + +> **CRITICAL**: TypeScript enforces method order: `middleware()` → `validator()` → `client()` → `server()`. Wrong order causes type errors. +> **CRITICAL**: Validating the _shape_ of `sendContext` (e.g. `z.string().uuid().parse(...)`) is NOT authorization. A parsed identifier is a well-formed identifier, not an authorized one. Always re-check access against the session principal before using a client-sent ID as a query key, filter, or path parameter. + +## Two Types of Middleware + +| Feature | Request Middleware | Server Function Middleware | +| ----------------- | -------------------------------------------- | ---------------------------------------- | +| Scope | All server requests (SSR, routes, functions) | Server functions only | +| Methods | `.server()` | `.client()`, `.server()` | +| Input validation | No | Yes (`.validator()`) | +| Client-side logic | No | Yes | +| Created with | `createMiddleware()` | `createMiddleware({ type: 'function' })` | + +Request middleware cannot depend on server function middleware. Server function middleware can depend on both types. + +## Request Middleware + +Runs on ALL server requests (SSR, server routes, server functions): + +```tsx +// Use @tanstack/-start for your framework (react, solid, vue) +import { createMiddleware } from '@tanstack/react-start' + +const loggingMiddleware = createMiddleware().server( + async ({ next, context, request }) => { + console.log('Request:', request.url) + const result = await next() + return result + }, +) +``` + +## Server Function Middleware + +Has both client and server phases: + +```tsx +// Use @tanstack/-start for your framework (react, solid, vue) +import { createMiddleware } from '@tanstack/react-start' + +const authMiddleware = createMiddleware({ type: 'function' }) + .client(async ({ next }) => { + // Runs on client BEFORE the RPC call + const result = await next() + // Runs on client AFTER the RPC response + return result + }) + .server(async ({ next, context }) => { + // Runs on server BEFORE the handler + const result = await next() + // Runs on server AFTER the handler + return result + }) +``` + +## Attaching Middleware to Server Functions + +```tsx +// Use @tanstack/-start for your framework (react, solid, vue) +import { createServerFn } from '@tanstack/react-start' + +const fn = createServerFn() + .middleware([authMiddleware]) + .handler(async ({ context }) => { + // context contains data from middleware + return { user: context.user } + }) +``` + +## Context Passing via next() + +Pass context down the middleware chain: + +```tsx +const authMiddleware = createMiddleware().server(async ({ next, request }) => { + const session = await getSession(request.headers) + if (!session) throw new Error('Unauthorized') + + return next({ + context: { session }, + }) +}) + +const roleMiddleware = createMiddleware() + .middleware([authMiddleware]) + .server(async ({ next, context }) => { + console.log('Session:', context.session) // typed! + return next() + }) +``` + +## Sending Context Between Client and Server + +### Client → Server (sendContext) + +```tsx +const workspaceMiddleware = createMiddleware({ type: 'function' }) + .client(async ({ next, context }) => { + return next({ + sendContext: { + workspaceId: context.workspaceId, + }, + }) + }) + .server(async ({ next, context }) => { + // workspaceId available here, but VALIDATE IT + console.log('Workspace:', context.workspaceId) + return next() + }) +``` + +### Server → Client (sendContext in server) + +```tsx +const serverTimer = createMiddleware({ type: 'function' }).server( + async ({ next }) => { + return next({ + sendContext: { + timeFromServer: new Date(), + }, + }) + }, +) + +const clientLogger = createMiddleware({ type: 'function' }) + .middleware([serverTimer]) + .client(async ({ next }) => { + const result = await next() + console.log('Server time:', result.context.timeFromServer) + return result + }) +``` + +## Input Validation in Middleware + +```tsx +import { z } from 'zod' +import { zodValidator } from '@tanstack/zod-adapter' + +const workspaceMiddleware = createMiddleware({ type: 'function' }) + .validator(zodValidator(z.object({ workspaceId: z.string() }))) + .server(async ({ next, data }) => { + console.log('Workspace:', data.workspaceId) + return next() + }) +``` + +## Global Middleware + +Create `src/start.ts` to configure global middleware: + +```tsx +// src/start.ts +// Use @tanstack/-start for your framework (react, solid, vue) +import { createStart, createMiddleware } from '@tanstack/react-start' + +const requestLogger = createMiddleware().server(async ({ next, request }) => { + console.log(`${request.method} ${request.url}`) + return next() +}) + +const functionAuth = createMiddleware({ type: 'function' }).server( + async ({ next }) => { + // runs for every server function + return next() + }, +) + +export const startInstance = createStart(() => ({ + requestMiddleware: [requestLogger], + functionMiddleware: [functionAuth], +})) +``` + +## Using Middleware with Server Routes + +### All handlers in a route + +```tsx +export const Route = createFileRoute('/api/users')({ + server: { + middleware: [authMiddleware], + handlers: { + GET: async ({ context }) => Response.json(context.user), + POST: async ({ request }) => { + /* ... */ + }, + }, + }, +}) +``` + +### Specific handlers only + +```tsx +export const Route = createFileRoute('/api/users')({ + server: { + handlers: ({ createHandlers }) => + createHandlers({ + GET: async () => Response.json({ public: true }), + POST: { + middleware: [authMiddleware], + handler: async ({ context }) => { + return Response.json({ user: context.session.user }) + }, + }, + }), + }, +}) +``` + +## Middleware Factories + +Create parameterized middleware for reusable patterns like authorization: + +```tsx +const authMiddleware = createMiddleware().server(async ({ next, request }) => { + const session = await auth.getSession({ headers: request.headers }) + if (!session) throw new Error('Unauthorized') + return next({ context: { session } }) +}) +``` + +> **Attach `authMiddleware` to every `createServerFn` that needs auth.** Server functions are API endpoints; a route `beforeLoad` does not protect their data, only the route's UI. Protect the endpoint that reads or mutates private data. See `@tanstack/router-core#router-core/auth-and-guards` and [start-core/auth-server-primitives](../auth-server-primitives/SKILL.md). + +```tsx +type Permissions = Record + +function authorizationMiddleware(permissions: Permissions) { + return createMiddleware({ type: 'function' }) + .middleware([authMiddleware]) + .server(async ({ next, context }) => { + const granted = await auth.hasPermission(context.session, permissions) + if (!granted) throw new Error('Forbidden') + return next() + }) +} + +// Usage +const getClients = createServerFn() + .middleware([authorizationMiddleware({ client: ['read'] })]) + .handler(async () => { + return { message: 'The user can read clients.' } + }) +``` + +## Custom Headers and Fetch + +### Setting headers from client middleware + +```tsx +const authMiddleware = createMiddleware({ type: 'function' }).client( + async ({ next }) => { + return next({ + headers: { Authorization: `Bearer ${getToken()}` }, + }) + }, +) +``` + +Headers merge across middleware. Later middleware overrides earlier. Call-site headers override all middleware headers. + +### Custom fetch + +```tsx +// Use @tanstack/-start for your framework (react, solid, vue) +import type { CustomFetch } from '@tanstack/react-start' + +const loggingMiddleware = createMiddleware({ type: 'function' }).client( + async ({ next }) => { + const customFetch: CustomFetch = async (url, init) => { + console.log('Request:', url) + return fetch(url, init) + } + return next({ fetch: customFetch }) + }, +) +``` + +Fetch precedence (highest to lowest): call site → later middleware → earlier middleware → createStart global → default fetch. + +## Common Mistakes + +### 1. CRITICAL: Trusting client sendContext — shape check is not access check + +`sendContext` from a client middleware arrives on the server as untrusted client input. Most agents stop after parsing the shape with Zod and assume the value is safe. It isn't: a parsed UUID is _some_ workspace, not the requesting user's workspace. Without a membership check against the session principal, you've built a tenant-walking endpoint. + +**Layer 1 — WRONG (no validation):** + +```tsx +.server(async ({ next, context }) => { + // SQL-injectable AND tenant-walkable + await db.query(`SELECT * FROM workspace_${context.workspaceId}`) + return next() +}) +``` + +**Layer 2 — STILL WRONG (shape only):** + +```tsx +.server(async ({ next, context }) => { + // Looks safe, isn't. UUID is well-formed but the user may not be a member. + const workspaceId = z.string().uuid().parse(context.workspaceId) + await db.query('SELECT * FROM workspaces WHERE id = $1', [workspaceId]) + return next() +}) +``` + +**Layer 3 — CORRECT (shape AND access):** + +```tsx +.middleware([authMiddleware]) // session loaded from cookie, NOT from sendContext +.server(async ({ next, context }) => { + const workspaceId = z.string().uuid().parse(context.workspaceId) + // Verify the session principal can access this workspace. + const member = await db.memberships.find({ + userId: context.session.userId, + workspaceId, + }) + if (!member) throw new Error('Not a member of this workspace') + await db.query('SELECT * FROM workspaces WHERE id = $1', [workspaceId]) + return next({ context: { workspaceId } }) +}) +``` + +The session itself must come from a server-trusted source (the cookie + DB lookup in `authMiddleware`), never from `sendContext` — anything the client can send, the client can lie about. See [start-core/auth-server-primitives](../auth-server-primitives/SKILL.md). + +### 2. MEDIUM: Confusing request vs server function middleware + +Request middleware runs on ALL requests (SSR, routes, functions). Server function middleware runs only for `createServerFn` calls and has `.client()` method. + +### 3. HIGH: Browser APIs in .client() crash during SSR + +During SSR, `.client()` callbacks run on the server. Browser-only APIs like `localStorage` or `window` will throw `ReferenceError`: + +```tsx +// WRONG — localStorage doesn't exist on the server during SSR +const middleware = createMiddleware({ type: 'function' }).client( + async ({ next }) => { + const token = localStorage.getItem('token') + return next({ sendContext: { token } }) + }, +) + +// CORRECT — use cookies/headers or guard with typeof window check +const middleware = createMiddleware({ type: 'function' }).client( + async ({ next }) => { + const token = + typeof window !== 'undefined' ? localStorage.getItem('token') : null + return next({ sendContext: { token } }) + }, +) +``` + +### 4. MEDIUM: Wrong method order + +```tsx +// WRONG — type error +createMiddleware({ type: 'function' }) + .server(() => { ... }) + .client(() => { ... }) + +// CORRECT — middleware → validator → client → server +createMiddleware({ type: 'function' }) + .middleware([dep]) + .validator(schema) + .client(({ next }) => next()) + .server(({ next }) => next()) +``` + +## Cross-References + +- [start-core/server-functions](../server-functions/SKILL.md) — what middleware wraps +- [start-core/server-routes](../server-routes/SKILL.md) — middleware on API endpoints +- [start-core/auth-server-primitives](../auth-server-primitives/SKILL.md) — building the `authMiddleware` factory itself: session cookie reads, OAuth state, CSRF +- `@tanstack/router-core#router-core/auth-and-guards` — routing-side UX guards; data auth belongs in the server function, server route, or API endpoint handler/middleware diff --git a/packages/start-client-core/skills/start-core/server-functions/SKILL.md b/packages/start-client-core/skills/start-core/server-functions/SKILL.md new file mode 100644 index 0000000000..881e76b873 --- /dev/null +++ b/packages/start-client-core/skills/start-core/server-functions/SKILL.md @@ -0,0 +1,498 @@ +--- +name: server-functions +description: >- + createServerFn (GET/POST), validator (Zod or function), + useServerFn hook, server context utilities (getRequest, + getRequestHeader, setResponseHeader, setResponseStatus), error + handling (throw errors, redirect, notFound), streaming, FormData + handling, file organization (.functions.ts, .server.ts). +metadata: + type: sub-skill + library: tanstack-start + library_version: '1.170.14' +requires: + - start-core +sources: + - TanStack/router:docs/start/framework/react/guide/server-functions.md +--- + +# Server Functions + +Server functions are type-safe RPCs created with `createServerFn`. They run exclusively on the server but can be called from anywhere — loaders, components, hooks, event handlers, or other server functions. + +> **CRITICAL**: Server functions are API endpoints. They are reachable independently of whichever route renders the calling UI. **Auth must be enforced inside the handler (or via middleware) for any server function that touches private data.** Route `beforeLoad` is UX, not the data boundary. See [start-core/auth-server-primitives](../auth-server-primitives/SKILL.md) for the session/middleware pattern. +> **CRITICAL**: Loaders are ISOMORPHIC — they run on BOTH client and server. Database queries, file system access, and secret API keys MUST go inside `createServerFn`, NOT in loaders directly. +> **CRITICAL**: Do not use `"use server"` directives, `getServerSideProps`, or any Next.js/Remix server patterns. TanStack Start uses `createServerFn` exclusively. + +## Basic Usage + +```tsx +import { createServerFn } from '@tanstack/react-start' + +// GET (default) +const getData = createServerFn().handler(async () => { + return { message: 'Hello from server!' } +}) + +// POST +const saveData = createServerFn({ method: 'POST' }).handler(async () => { + return { success: true } +}) +``` + +## Calling from Loaders + +```tsx +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' + +const getPosts = createServerFn({ method: 'GET' }).handler(async () => { + const posts = await db.query('SELECT * FROM posts') + return { posts } +}) + +export const Route = createFileRoute('/posts')({ + loader: () => getPosts(), + component: PostList, +}) + +function PostList() { + const { posts } = Route.useLoaderData() + return ( +
      + {posts.map((p) => ( +
    • {p.title}
    • + ))} +
    + ) +} +``` + +## Calling from Components + +Use the `useServerFn` hook to call server functions from event handlers: + +```tsx +import { useServerFn } from '@tanstack/react-start' + +const deletePost = createServerFn({ method: 'POST' }) + .validator((data: { id: string }) => data) + .handler(async ({ data }) => { + await db.delete('posts').where({ id: data.id }) + return { success: true } + }) + +function DeleteButton({ postId }: { postId: string }) { + const deletePostFn = useServerFn(deletePost) + + return ( + + ) +} +``` + +## Cache-Coherent Mutations + +Keep reads and writes behind server functions that use the same authoritative store. Await the write, then invalidate the route cache so its loader reads the persisted result: + +```tsx +const listIssues = createServerFn({ method: 'GET' }).handler(() => { + return db.issues.findMany() +}) + +const createIssue = createServerFn({ method: 'POST' }) + .validator((data: unknown) => { + if ( + typeof data !== 'object' || + data === null || + !('title' in data) || + typeof data.title !== 'string' || + data.title.trim().length === 0 + ) { + throw new Error('Title is required') + } + return { title: data.title.trim() } + }) + .handler(async ({ data }) => { + return db.issues.create({ data }) + }) + +export const Route = createFileRoute('/issues')({ + loader: () => listIssues(), + component: IssuesPage, +}) + +function IssuesPage() { + const router = useRouter() + const createIssueFn = useServerFn(createIssue) + + const handleCreate = async (title: string) => { + await createIssueFn({ data: { title } }) + await router.invalidate({ sync: true }) + } + + // render Route.useLoaderData() and call handleCreate from the form +} +``` + +Do not update only local component state after a persistent mutation. Verify the rendered list after create, update, delete, and a fresh page load. + +## Input Validation + +### Basic Validator + +```tsx +const greetUser = createServerFn({ method: 'GET' }) + .validator((data: { name: string }) => data) + .handler(async ({ data }) => { + return `Hello, ${data.name}!` + }) + +await greetUser({ data: { name: 'John' } }) +``` + +### Zod Validator + +```tsx +import { z } from 'zod' + +const createUser = createServerFn({ method: 'POST' }) + .validator( + z.object({ + name: z.string().min(1), + age: z.number().min(0), + }), + ) + .handler(async ({ data }) => { + return `Created user: ${data.name}, age ${data.age}` + }) +``` + +Input validation does not validate output serialization. When a response schema changes, update the database selection, service return value, server-function result, loader consumer, and UI. Add a runtime test that calls the handler or HTTP boundary and asserts the new field in the returned payload. + +### FormData + +```tsx +const submitForm = createServerFn({ method: 'POST' }) + .validator((data) => { + if (!(data instanceof FormData)) { + throw new Error('Expected FormData') + } + return { + name: data.get('name')?.toString() || '', + email: data.get('email')?.toString() || '', + } + }) + .handler(async ({ data }) => { + return { success: true } + }) +``` + +## Error Handling + +### Errors + +```tsx +const riskyFunction = createServerFn().handler(async () => { + throw new Error('Something went wrong!') +}) + +try { + await riskyFunction() +} catch (error) { + console.log(error.message) // "Something went wrong!" +} +``` + +### Redirects + +```tsx +import { redirect } from '@tanstack/react-router' + +const requireAuth = createServerFn().handler(async () => { + const user = await getCurrentUser() + if (!user) { + throw redirect({ to: '/login' }) + } + return user +}) +``` + +### Not Found + +```tsx +import { notFound } from '@tanstack/react-router' + +const getPost = createServerFn() + .validator((data: { id: string }) => data) + .handler(async ({ data }) => { + const post = await db.findPost(data.id) + if (!post) { + throw notFound() + } + return post + }) +``` + +## Server Context Utilities + +Access request/response details inside server function handlers: + +```tsx +import { createServerFn } from '@tanstack/react-start' +import { + getRequest, + getRequestHeader, + setResponseHeaders, + setResponseStatus, +} from '@tanstack/react-start/server' + +// Public, non-personalized data — safe to cache shared across users. +const getPublicData = createServerFn({ method: 'GET' }).handler(async () => { + setResponseHeaders({ + // 'public' is correct ONLY when the response does not depend on identity. + // For anything tied to a session/user/tenant, use 'private' or 'no-store'. + 'Cache-Control': 'public, max-age=300', + }) + setResponseStatus(200) + return fetchPublicData() +}) + +// Authenticated data — must NOT be 'public'. +const getMyData = createServerFn({ method: 'GET' }).handler(async () => { + const authHeader = getRequestHeader('Authorization') + // ... auth check ... + + setResponseHeaders({ + // 'private' = only the user-agent may cache. Vary by Cookie/Authorization + // so any intermediary that does cache keys by identity, not URL alone. + 'Cache-Control': 'private, max-age=60', + Vary: 'Cookie, Authorization', + }) + return fetchPersonalizedData() +}) +``` + +Available utilities: + +- `getRequest()` — full Request object +- `getRequestHeader(name)` — single request header +- `setResponseHeader(name, value)` — single response header +- `setResponseHeaders(headers)` — multiple response headers +- `setResponseStatus(code)` — HTTP status code + +## File Organization + +```text +src/utils/ +├── users.functions.ts # createServerFn wrappers (safe to import anywhere) +├── users.server.ts # Server-only helpers (DB queries, internal logic) +└── schemas.ts # Shared validation schemas (client-safe) +``` + +```tsx +// users.server.ts — server-only helpers +import { db } from '~/db' + +export async function findUserById(id: string) { + return db.query.users.findFirst({ where: eq(users.id, id) }) +} +``` + +```tsx +// users.functions.ts — server functions +import { createServerFn } from '@tanstack/react-start' +import { findUserById } from './users.server' + +export const getUser = createServerFn({ method: 'GET' }) + .validator((data: { id: string }) => data) + .handler(async ({ data }) => { + return findUserById(data.id) + }) +``` + +Static imports of server functions are safe — the build replaces implementations with RPC stubs in client bundles. + +## Common Mistakes + +### 1. CRITICAL: Relying on a route guard to protect a server function + +A `beforeLoad` redirect protects the **route's UI**, not the **data endpoint**. `createServerFn` exposes a callable endpoint that an attacker can hit directly — no need to load the route at all. Auth on the endpoint is the security boundary; auth on the route is UX. + +```tsx +// WRONG — the route guard doesn't reach the handler +const getMyOrders = createServerFn({ method: 'GET' }).handler(async () => { + return db.orders.findMany() // ← anyone can call the RPC +}) +export const Route = createFileRoute('/_authenticated/orders')({ + beforeLoad: ({ context }) => { + if (!context.auth.isAuthenticated) throw redirect({ to: '/login' }) + }, + loader: () => getMyOrders(), +}) + +// CORRECT — auth enforced on the handler itself +const getMyOrders = createServerFn({ method: 'GET' }) + .middleware([authMiddleware]) + .handler(async ({ context }) => { + return db.orders.findMany({ where: { userId: context.session.userId } }) + }) +``` + +Apply `authMiddleware` (or an equivalent in-handler check) to **every** `createServerFn` that needs auth. See [start-core/auth-server-primitives](../auth-server-primitives/SKILL.md) for the full session/middleware pattern and [start-core/middleware](../middleware/SKILL.md) for composing the factory. + +### 2. CRITICAL: Putting server-only code in loaders + +```tsx +// WRONG — loader is ISOMORPHIC, runs on BOTH client and server +export const Route = createFileRoute('/posts')({ + loader: async () => { + const posts = await db.query('SELECT * FROM posts') + return { posts } + }, +}) + +// CORRECT — use createServerFn for server-only logic +const getPosts = createServerFn({ method: 'GET' }).handler(async () => { + const posts = await db.query('SELECT * FROM posts') + return { posts } +}) + +export const Route = createFileRoute('/posts')({ + loader: () => getPosts(), +}) +``` + +### 3. CRITICAL: Using Next.js / Remix / React Router DOM patterns + +If the file lives at `src/pages/`, `app/layout.tsx`, `_app/`, or imports anything from `react-router-dom` or `next/`, it is wrong-framework code. TanStack Start uses `src/routes/` + `createFileRoute` + `createServerFn`. + +```tsx +// WRONG — "use server" is a React directive, not used in TanStack Start +'use server' +export async function getUser() { ... } + +// WRONG — getServerSideProps is Next.js Pages Router +export async function getServerSideProps() { ... } + +// WRONG — Next.js App Router server component data fetching +export default async function Page() { + const data = await fetch(...).then(r => r.json()) + return
    {data}
    +} + +// WRONG — Remix +export async function loader({ request }) { ... } +export async function action({ request }) { ... } + +// WRONG — react-router-dom (a different library) +import { Link, useNavigate } from 'react-router-dom' + +// CORRECT — TanStack Start +import { createServerFn } from '@tanstack/react-start' +import { Link, useNavigate, createFileRoute } from '@tanstack/react-router' + +const getUser = createServerFn({ method: 'GET' }) + .handler(async () => { ... }) + +export const Route = createFileRoute('/users/$id')({ + loader: ({ params }) => getUser({ data: { id: params.id } }), + component: UserPage, +}) +``` + +If you see `src/pages/`, `app/layout.tsx`, or `react-router-dom` in agent output, the agent is generating for the wrong framework. Build will fail or routes will conflict at runtime. + +### 4. HIGH: Dynamic imports for server functions + +```tsx +// WRONG — can cause bundler issues +const { getUser } = await import('~/utils/users.functions') + +// CORRECT — static imports are safe, build handles environment shaking +import { getUser } from '~/utils/users.functions' +``` + +### 5. HIGH: Awaiting server function without calling it + +`createServerFn` returns a function — it must be invoked with `()`: + +```tsx +// WRONG — getItems is a function, not a Promise +const data = await getItems + +// CORRECT — call the function +const data = await getItems() + +// With validated input +const data = await getItems({ data: { id: '1' } }) +``` + +### 6. CRITICAL: Caching authenticated responses with `Cache-Control: public` + +`Cache-Control: public, max-age=N` tells every CDN, proxy, and shared cache between you and the user that this response can be served to anyone. If the response depends on the session (user, tenant, role), the first user's response gets cached and replayed to the next user — a cross-tenant data leak. + +```tsx +// WRONG — auth'd response, public cache, leaks to next user via CDN +const getMyOrders = createServerFn({ method: 'GET' }).handler(async () => { + const session = await requireSession() // identity-dependent + setResponseHeaders({ 'Cache-Control': 'public, max-age=300' }) + return db.orders.findMany({ where: { userId: session.userId } }) +}) + +// CORRECT — private + Vary so any cache that does store it keys by identity +const getMyOrders = createServerFn({ method: 'GET' }).handler(async () => { + const session = await requireSession() + setResponseHeaders({ + 'Cache-Control': 'private, max-age=60', + Vary: 'Cookie, Authorization', + }) + return db.orders.findMany({ where: { userId: session.userId } }) +}) + +// ALSO CORRECT — opt out entirely for sensitive data +setResponseHeaders({ 'Cache-Control': 'no-store' }) +``` + +Rule of thumb: if the handler reads a session/cookie/auth header or branches on identity, the response is **not** `public`. Default to `private` (or `no-store` for sensitive data); reach for `public` only on responses that are byte-for-byte identical regardless of who asks. See also [start-core/deployment](../deployment/SKILL.md) for ISR/Cache-Control on full pages. + +### 7. MEDIUM: When to wrap with `useServerFn` + +`useServerFn` is **required** when the server function uses `throw redirect()` or `throw notFound()` — the hook wires the throw into the router so the redirect actually navigates. For server functions that just return data (call them directly or via `useMutation`/`useQuery`), the hook is optional. + +```tsx +// Plain data — direct call is fine (also fine to pass to useMutation/useQuery) + +useMutation({ mutationFn: deletePost }) + +// Throws redirect/notFound — MUST wrap with useServerFn so the router handles the throw +const signupFn = useServerFn(signup) // signup throws redirect on success + +``` + +If in doubt: wrap with `useServerFn`. It's a no-op for plain-data functions and the safe default when a function might later add a redirect. + +### 8. CRITICAL: Self-fetching a relative API URL from a loader + +```tsx +// WRONG — this loader also runs during SSR, where a relative URL may fail +export const Route = createFileRoute('/issues')({ + loader: () => fetch('/api/issues').then((response) => response.json()), +}) + +// CORRECT — call the server function; the client build gets an RPC stub +export const Route = createFileRoute('/issues')({ + loader: () => listIssues(), +}) +``` + +Relative `fetch` is fine in a browser-only event handler. It is not a universal loader data strategy. + +## Cross-References + +- [start-core/execution-model](../execution-model/SKILL.md) — understanding where code runs +- [start-core/middleware](../middleware/SKILL.md) — composing server functions with middleware +- [start-core/auth-server-primitives](../auth-server-primitives/SKILL.md) — sessions, cookies, OAuth, CSRF, rate limiting (the server-side half of auth; `getCurrentUser` and external session helpers belong here, not at module scope) +- `@tanstack/router-core#router-core/auth-and-guards` — routing-side UX guards; data auth belongs in the server function, server route, or API endpoint handler/middleware diff --git a/packages/start-client-core/skills/start-core/server-routes/SKILL.md b/packages/start-client-core/skills/start-core/server-routes/SKILL.md new file mode 100644 index 0000000000..9655f243ed --- /dev/null +++ b/packages/start-client-core/skills/start-core/server-routes/SKILL.md @@ -0,0 +1,324 @@ +--- +name: server-routes +description: >- + Server-side API endpoints using the server property on + createFileRoute, HTTP method handlers (GET, POST, PUT, DELETE), + createHandlers for per-handler middleware, handler context + (request, params, context), request body parsing, response + helpers, file naming for API routes. +metadata: + type: sub-skill + library: tanstack-start + library_version: '1.170.14' +requires: + - start-core +sources: + - TanStack/router:docs/start/framework/react/guide/server-routes.md +--- + +# Server Routes + +Server routes are API endpoints defined alongside app routes in the `src/routes` directory. They use the `server` property on `createFileRoute` and handle raw HTTP requests. + +Use server routes when callers need an HTTP contract. For data used only by the Start application, prefer a server function and call it directly from the loader. A route loader runs during SSR and client navigation, so `fetch('/api/...')` is not a portable loader pattern. + +## Basic Server Route + +```ts +// src/routes/api/hello.ts +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/api/hello')({ + server: { + handlers: { + GET: async ({ request }) => { + return new Response('Hello, World!') + }, + }, + }, +}) +``` + +## Combining Server Route and App Route + +The same file can define both a server route and a UI route: + +```tsx +// src/routes/hello.tsx +import { createFileRoute } from '@tanstack/react-router' +import { useState } from 'react' + +export const Route = createFileRoute('/hello')({ + server: { + handlers: { + POST: async ({ request }) => { + const body = await request.json() + return Response.json({ message: `Hello, ${body.name}!` }) + }, + }, + }, + component: HelloComponent, +}) + +function HelloComponent() { + const [reply, setReply] = useState('') + return ( + + ) +} +``` + +The relative `fetch('/hello')` above is safe because it runs only in a browser click handler. + +## Sharing Data with a Start Route + +Do not make the SSR loader call its own server route. Put the business operation in a server-only service, then expose it through both boundaries when both are required: + +```tsx +// src/server/issues.server.ts +export function listIssues() { + return db.issues.findMany() +} + +// src/routes/api/issues.ts +export const Route = createFileRoute('/api/issues')({ + server: { + handlers: { + GET: async () => Response.json(await listIssues()), + }, + }, +}) + +// src/routes/issues.tsx +const getIssues = createServerFn({ method: 'GET' }).handler(() => { + return listIssues() +}) + +export const Route = createFileRoute('/issues')({ + loader: () => getIssues(), +}) +``` + +This keeps SSR independent of URL resolution and keeps one source of business logic. + +## File Route Conventions + +Server routes follow TanStack Router file-based routing conventions: + +| File | Route | +| --------------------------- | ----------------------------- | +| `routes/users.ts` | `/users` | +| `routes/users/$id.ts` | `/users/$id` | +| `routes/users/$id/posts.ts` | `/users/$id/posts` | +| `routes/api/file/$.ts` | `/api/file/$` (splat) | +| `routes/my-script[.]js.ts` | `/my-script.js` (escaped dot) | + +## Unique Route Paths + +Each route can only have a single handler file. These would conflict: + +- `routes/users.ts` +- `routes/users.index.ts` +- `routes/users/index.ts` + +## Handler Context + +Each handler receives: + +- `request` — the incoming [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object +- `params` — dynamic path parameters +- `context` — context from middleware +- `pathname` — the matched pathname +- `next` — call to fall through to SSR (returns a `Response`) + +## Dynamic Path Params + +```ts +// routes/users/$id.ts +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/users/$id')({ + server: { + handlers: { + GET: async ({ params }) => { + return new Response(`User ID: ${params.id}`) + }, + }, + }, +}) +``` + +## Splat/Wildcard Params + +```ts +// routes/file/$.ts +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/file/$')({ + server: { + handlers: { + GET: async ({ params }) => { + return new Response(`File: ${params._splat}`) + }, + }, + }, +}) +``` + +## Request Body Handling + +```ts +export const Route = createFileRoute('/api/users')({ + server: { + handlers: { + POST: async ({ request }) => { + const body = await request.json() + return Response.json({ created: body.name }) + }, + }, + }, +}) +``` + +Other body methods: `request.text()`, `request.formData()`. + +## JSON Responses + +```ts +// Using Response.json helper +handlers: { + GET: async () => { + return Response.json({ message: 'Hello!' }) + }, +} +``` + +## Status Codes and Headers + +```ts +handlers: { + GET: async ({ params }) => { + const user = await findUser(params.id) + if (!user) { + return new Response('Not found', { status: 404 }) + } + return Response.json(user) + }, +} +``` + +```ts +handlers: { + GET: async () => { + return new Response('Hello', { + headers: { 'Content-Type': 'text/plain' }, + }) + }, +} +``` + +## Middleware on Server Routes + +### All handlers + +```tsx +export const Route = createFileRoute('/api/admin')({ + server: { + middleware: [authMiddleware, loggerMiddleware], + handlers: { + GET: async ({ context }) => Response.json(context.user), + POST: async ({ request, context }) => { + /* ... */ + }, + }, + }, +}) +``` + +### Specific handlers with createHandlers + +```tsx +export const Route = createFileRoute('/api/data')({ + server: { + handlers: ({ createHandlers }) => + createHandlers({ + GET: async () => Response.json({ public: true }), + POST: { + middleware: [authMiddleware], + handler: async ({ context }) => { + return Response.json({ user: context.session.user }) + }, + }, + }), + }, +}) +``` + +### Combined route-level and handler-specific + +```tsx +export const Route = createFileRoute('/api/posts')({ + server: { + middleware: [authMiddleware], // runs first for all + handlers: ({ createHandlers }) => + createHandlers({ + GET: async () => Response.json([]), + POST: { + middleware: [validationMiddleware], // runs after auth, POST only + handler: async ({ request }) => { + const body = await request.json() + return Response.json({ created: true }) + }, + }, + }), + }, +}) +``` + +## Common Mistakes + +### 1. CRITICAL: Protecting the page but not the server route + +Every handler that reads or writes private data must authenticate and authorize the request through route middleware, handler middleware, or an in-handler check. A router `beforeLoad` redirect does not protect `/api/...`. Test the handler directly without cookies and assert that no private payload is returned. + +### 2. MEDIUM: Duplicate route paths + +```text +# WRONG — both resolve to /users, causes error +routes/users.ts +routes/users/index.ts + +# CORRECT — pick one +routes/users.ts +``` + +### 3. MEDIUM: Forgetting to await request body methods + +```ts +// WRONG — body is a Promise, not the actual data +const body = request.json() + +// CORRECT — await the promise +const body = await request.json() +``` + +### 4. HIGH: Trusting TypeScript as response-schema validation + +Validate request input and test the serialized `Response` output. A typed service can still be projected or serialized without a newly added field. For schema changes, assert `await response.json()` at the server-route boundary. + +## Cross-References + +- [start-core/middleware](../middleware/SKILL.md) — middleware for server routes +- [start-core/server-functions](../server-functions/SKILL.md) — alternative for RPC-style calls diff --git a/packages/start-client-core/src/client-rpc/createClientRpc.ts b/packages/start-client-core/src/client-rpc/createClientRpc.ts index aed2cf62e9..0ab3c73e76 100644 --- a/packages/start-client-core/src/client-rpc/createClientRpc.ts +++ b/packages/start-client-core/src/client-rpc/createClientRpc.ts @@ -1,16 +1,20 @@ import { TSS_SERVER_FUNCTION } from '../constants' +import { getStartOptions } from '../getStartOptions' import { serverFnFetcher } from './serverFnFetcher' +import type { ClientFnMeta } from '../constants' export function createClientRpc(functionId: string) { const url = process.env.TSS_SERVER_FN_BASE + functionId + const serverFnMeta: ClientFnMeta = { id: functionId } const clientFn = (...args: Array) => { - return serverFnFetcher(url, args, fetch) + const startFetch = getStartOptions()?.serverFns?.fetch + return serverFnFetcher(url, args, startFetch ?? fetch) } return Object.assign(clientFn, { url, - functionId, + serverFnMeta, [TSS_SERVER_FUNCTION]: true, }) } diff --git a/packages/start-client-core/src/client-rpc/frame-decoder.ts b/packages/start-client-core/src/client-rpc/frame-decoder.ts new file mode 100644 index 0000000000..dd33dcb55a --- /dev/null +++ b/packages/start-client-core/src/client-rpc/frame-decoder.ts @@ -0,0 +1,281 @@ +import { + FRAME_HEADER_SIZE, + FRAME_TYPE_CHUNK, + FRAME_TYPE_END, + FRAME_TYPE_ERROR, + FRAME_TYPE_JSON, + MAX_FRAMED_STREAMS, + MAX_FRAME_PAYLOAD_SIZE, + MAX_UNREAD_RAW_STREAM_BYTES, +} from '../constants' + +const decoder = new TextDecoder() +const empty: Uint8Array = new Uint8Array() +// With a zero high-water mark, `-desiredSize` is the unread byte count. +const rawStreamQueue = new ByteLengthQueuingStrategy({ highWaterMark: 0 }) + +type Closed = 1 +type Failed = readonly [unknown] +type State = 0 | Closed | Failed +type RawController = + | ReadableStreamDefaultController + | null // canceled by its consumer + | false // ended by the wire or decoder +type RawEntry = [ReadableStream, RawController] + +export function createFrameDecoder(input: ReadableStream) { + const reader = input.getReader() + const rawStreams = new Map() + let state = 0 as State + let resume: (() => void) | undefined + let jsonController!: ReadableStreamDefaultController + + const wake = () => { + resume?.() + resume = undefined + } + + const settleRaw = (entry: RawEntry, terminal: Closed | Failed) => { + const controller = entry[1] + entry[1] = false + if (controller) { + if (terminal === 1) { + controller.close() + } else { + controller.error(terminal[0]) + } + } + } + + const chunks = new ReadableStream({ + start(controller) { + jsonController = controller + }, + pull: wake, + cancel(reason) { + // Every raw stream, including one requested later, ends with this reason. + const failed: Failed = [ + reason === undefined ? new Error('Framed response cancelled') : reason, + ] + state = failed + wake() + void reader.cancel(reason).catch(() => {}) + for (const entry of rawStreams.values()) { + settleRaw(entry, failed) + } + }, + }) + + function getRaw(id: number): RawEntry { + const existing = rawStreams.get(id) + if (existing) { + return existing + } + if (rawStreams.size >= MAX_FRAMED_STREAMS) { + throw new Error('Too many raw streams') + } + + let controller!: ReadableStreamDefaultController + const stream = new ReadableStream( + { + start(value) { + controller = value + }, + cancel() { + if (entry[1] !== false) { + entry[1] = null + } + }, + }, + rawStreamQueue, + ) + const entry: RawEntry = [stream, controller] + rawStreams.set(id, entry) + if (state !== 0) { + settleRaw(entry, state) + } + return entry + } + + function getStream(id: number): ReadableStream { + if (id === 0 || id >>> 0 !== id) { + throw new RangeError('Invalid raw stream ID') + } + return getRaw(id)[0] + } + + void (async () => { + let inputChunk = empty + let inputOffset = 0 + + async function more(): Promise { + while (inputOffset === inputChunk.byteLength) { + inputChunk = empty + inputOffset = 0 + const next = await reader.read() + if (state !== 0 || next.done) { + return false + } + inputChunk = next.value + } + return true + } + + async function read( + length: number, + cleanEof?: boolean, + ): Promise { + if (length === 0) { + return empty + } + if (!(await more())) { + if (cleanEof) { + return + } + throw new Error('Incomplete frame') + } + + const available = inputChunk.byteLength - inputOffset + if (available >= length) { + const result = inputChunk.subarray(inputOffset, inputOffset + length) + inputOffset += length + if (inputOffset === inputChunk.byteLength) { + inputChunk = empty + inputOffset = 0 + } + return result + } + + const result = new Uint8Array(length) + let offset = 0 + while (offset < length) { + if (!(await more())) { + throw new Error('Incomplete frame') + } + const size = Math.min( + length - offset, + inputChunk.byteLength - inputOffset, + ) + result.set(inputChunk.subarray(inputOffset, inputOffset + size), offset) + inputOffset += size + offset += size + } + if (inputOffset === inputChunk.byteLength) { + inputChunk = empty + inputOffset = 0 + } + return result + } + + try { + while (state === 0) { + let header = await read(FRAME_HEADER_SIZE, true) + // Cancellation can run while the read is suspended. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (state !== 0) { + return + } + if (!header) { + for (const entry of rawStreams.values()) { + if (entry[1]) { + throw new Error('Incomplete raw stream') + } + } + state = 1 + jsonController.close() + return + } + + const type = header[0]! + const streamId = + ((header[1]! << 24) | + (header[2]! << 16) | + (header[3]! << 8) | + header[4]!) >>> + 0 + const length = + ((header[5]! << 24) | + (header[6]! << 16) | + (header[7]! << 8) | + header[8]!) >>> + 0 + header = empty + + if ( + type > FRAME_TYPE_ERROR || + (type === FRAME_TYPE_JSON) !== (streamId === 0) || + length > MAX_FRAME_PAYLOAD_SIZE || + (type === FRAME_TYPE_END && length !== 0) + ) { + throw new Error('Invalid frame') + } + + const entry = type === FRAME_TYPE_JSON ? undefined : getRaw(streamId) + if (entry?.[1] === false) { + throw new Error('Raw stream already ended') + } + + let payload = (await read(length))! + // Cancellation can run while the read is suspended. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (state !== 0) { + return + } + if (!entry) { + const value = decoder.decode(payload) + payload = empty + jsonController.enqueue(value) + // Cancellation wakes this wait even when JSON demand stays at zero. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (state === 0 && jsonController.desiredSize! <= 0) { + await new Promise((resolve) => { + resume = resolve + }) + } + continue + } + + if (type === FRAME_TYPE_CHUNK) { + const controller = entry[1] + if (controller) { + if (-controller.desiredSize! > MAX_UNREAD_RAW_STREAM_BYTES) { + controller.error( + new Error(`Raw stream ${streamId} has too many unread bytes`), + ) + entry[1] = null + payload = empty + continue + } + // A small view would pin its whole network buffer; copy those. + const chunk = + payload.byteLength * 4 < payload.buffer.byteLength + ? payload.slice() + : payload + payload = empty + controller.enqueue(chunk) + } + } else { + settleRaw( + entry, + type === FRAME_TYPE_END ? 1 : [new Error(decoder.decode(payload))], + ) + } + } + } catch (error) { + if (state === 0) { + const failed: Failed = [error] + state = failed + void reader.cancel(error).catch(() => {}) + jsonController.error(error) + for (const entry of rawStreams.values()) { + settleRaw(entry, failed) + } + } + } finally { + inputChunk = empty + reader.releaseLock() + } + })() + + return [chunks, getStream] as const +} diff --git a/packages/start-client-core/src/client-rpc/index.ts b/packages/start-client-core/src/client-rpc/index.ts index a50dc46635..b12e671307 100644 --- a/packages/start-client-core/src/client-rpc/index.ts +++ b/packages/start-client-core/src/client-rpc/index.ts @@ -1 +1,11 @@ export { createClientRpc } from './createClientRpc' +export { + FRAME_HEADER_SIZE, + FRAME_TYPE_CHUNK, + FRAME_TYPE_END, + FRAME_TYPE_ERROR, + FRAME_TYPE_JSON, + MAX_FRAMED_STREAMS, + MAX_FRAME_PAYLOAD_SIZE, + MAX_UNREAD_RAW_STREAM_BYTES, +} from '../constants' diff --git a/packages/start-client-core/src/client-rpc/serverFnFetcher.ts b/packages/start-client-core/src/client-rpc/serverFnFetcher.ts index 5511bdc517..1d15747f95 100644 --- a/packages/start-client-core/src/client-rpc/serverFnFetcher.ts +++ b/packages/start-client-core/src/client-rpc/serverFnFetcher.ts @@ -1,21 +1,117 @@ import { encode, + invariant, isNotFound, - isPlainObject, parseRedirect, } from '@tanstack/router-core' +import { createRawStreamDeserializePlugin } from '@tanstack/router-core/ssr/client' import { fromCrossJSON, toJSONAsync } from 'seroval' -import invariant from 'tiny-invariant' import { getDefaultSerovalPlugins } from '../getDefaultSerovalPlugins' import { + TSS_CONTENT_TYPE_FRAMED, TSS_FORMDATA_CONTEXT, + TSS_FRAMED_PROTOCOL_VERSION, X_TSS_RAW_RESPONSE, X_TSS_SERIALIZED, } from '../constants' +import { createFrameDecoder } from './frame-decoder' import type { FunctionMiddlewareClientFnOptions } from '../createMiddleware' import type { Plugin as SerovalPlugin } from 'seroval' -let serovalPlugins: Array> | null = null +let serovalPlugins: Array> | undefined + +/** + * Current async post-processing context for deserialization. + * + * Some deserializers need to perform async work after synchronous deserialization + * (e.g., decoding RSC payloads, fetching remote data). This context allows them + * to register promises that must complete before the deserialized value is used. + * + * This uses a synchronous execution context pattern: + * - Each call to `fromCrossJSON` is synchronous + * - Within that synchronous execution, all `fromSerializable` calls happen + * - We set the context before `fromCrossJSON`, then clear it afterward + * + * Even with concurrent server function calls, each individual deserialization + * is atomic (synchronous), so promises are correctly scoped to their call. + */ +let currentPostProcessContext: Array> | null = null + +/** + * Track an async post-processing promise in the current deserialization context. + * Called by deserializers that need to perform async work after sync deserialization. + * + * If no context is active (e.g., on server), this is a no-op. + * + * @param promise - The async work promise to track + */ +export function trackPostProcessPromise(promise: Promise): void { + if (currentPostProcessContext) { + currentPostProcessContext.push(promise) + } +} + +function deserialize( + value: any, + options: { + refs?: Map + plugins: Array> + }, + promises: Array>, +) { + currentPostProcessContext = promises + try { + return fromCrossJSON(value, options) + } catch (error) { + observePostProcessPromises(promises) + throw error + } finally { + currentPostProcessContext = null + } +} + +/** + * Helper to await all post-processing promises. + * Uses Promise.allSettled to ensure all promises complete even if some reject. + */ +async function awaitPostProcessPromises( + promises: Array>, +): Promise { + if (promises.length > 0) { + await Promise.allSettled(promises) + promises.length = 0 + } +} + +function observePostProcessPromises(promises: Array>): void { + for (const promise of promises) { + void promise.catch(() => {}) + } + promises.length = 0 +} + +/** + * Checks if an object has at least one own enumerable property. + * More efficient than Object.keys(obj).length > 0 as it short-circuits on first property. + */ +const hop = Object.prototype.hasOwnProperty +function hasOwnProperties(obj: object): boolean { + for (const _ in obj) { + if (hop.call(obj, _)) { + return true + } + } + return false +} +// caller => +// serverFnFetcher => +// client => +// server => +// fn => +// seroval => +// client middleware => +// serverFnFetcher => +// caller export async function serverFnFetcher( url: string, @@ -25,82 +121,58 @@ export async function serverFnFetcher( if (!serovalPlugins) { serovalPlugins = getDefaultSerovalPlugins() } - const _first = args[0] + const first = args[0] as FunctionMiddlewareClientFnOptions & { + headers?: HeadersInit + } - // If createServerFn was used to wrap the fetcher, - // We need to handle the arguments differently - if (isPlainObject(_first) && _first.method) { - const first = _first as FunctionMiddlewareClientFnOptions & { - headers: HeadersInit - } - const type = first.data instanceof FormData ? 'formData' : 'payload' + // Use custom fetch if provided, otherwise fall back to the passed handler (global fetch) + const fetchImpl = first.fetch ?? handler - // Arrange the headers - const headers = new Headers({ - 'x-tsr-redirect': 'manual', - ...(first.headers instanceof Headers - ? Object.fromEntries(first.headers.entries()) - : first.headers), - }) + const isFormData = first.data instanceof FormData - if (type === 'payload') { - headers.set('accept', 'application/x-ndjson, application/json') - } + // Arrange the headers + const headers = new Headers(first.headers) + headers.set('x-tsr-serverFn', 'true') - // If the method is GET, we need to move the payload to the query string - if (first.method === 'GET') { - if (type === 'formData') { - throw new Error('FormData is not supported with GET requests') - } - const serializedPayload = await serializePayload(first) - if (serializedPayload !== undefined) { - const encodedPayload = encode({ - payload: await serializePayload(first), - }) - if (url.includes('?')) { - url += `&${encodedPayload}` - } else { - url += `?${encodedPayload}` - } - } - } - - if (url.includes('?')) { - url += `&createServerFn` - } else { - url += `?createServerFn` - } - - let body = undefined - if (first.method === 'POST') { - const fetchBody = await getFetchBody(first) - if (fetchBody?.contentType) { - headers.set('content-type', fetchBody.contentType) - } - body = fetchBody?.body - } - - return await getResponse(async () => - handler(url, { - method: first.method, - headers, - signal: first.signal, - body, - }), + if (!isFormData) { + headers.set( + 'accept', + `${TSS_CONTENT_TYPE_FRAMED}, application/x-ndjson, application/json`, ) } - // If not a custom fetcher, it was probably - // a `use server` function, so just proxy the arguments - // through as a POST request - return await getResponse(() => - handler(url, { - method: 'POST', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - }, - body: JSON.stringify(args), + // If the method is GET, we need to move the payload to the query string + if (first.method === 'GET') { + if (isFormData) { + throw new Error('FormData is not supported with GET requests') + } + const serializedPayload = await serializePayload(first) + if (serializedPayload !== undefined) { + const encodedPayload = encode({ + payload: serializedPayload, + }) + if (url.includes('?')) { + url += `&${encodedPayload}` + } else { + url += `?${encodedPayload}` + } + } + } + + let body = undefined + if (first.method === 'POST') { + body = await getFetchBody(first) + if (typeof body === 'string') { + headers.set('content-type', 'application/json') + } + } + + return getResponse(() => + fetchImpl(url, { + method: first.method, + headers, + signal: first.signal, + body, }), ) } @@ -108,50 +180,47 @@ export async function serverFnFetcher( async function serializePayload( opts: FunctionMiddlewareClientFnOptions, ): Promise { - let payloadAvailable = false - const payloadToSerialize: any = {} + let payload: any if (opts.data !== undefined) { - payloadAvailable = true - payloadToSerialize['data'] = opts.data + payload = { data: opts.data } } // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (opts.context && Object.keys(opts.context).length > 0) { - payloadAvailable = true - payloadToSerialize['context'] = opts.context + if (opts.context && hasOwnProperties(opts.context)) { + ;(payload ??= {}).context = opts.context } - if (payloadAvailable) { - return serialize(payloadToSerialize) - } - return undefined + return payload ? serialize(payload, opts.signal) : undefined } -async function serialize(data: any) { - return JSON.stringify( - await Promise.resolve(toJSONAsync(data, { plugins: serovalPlugins! })), - ) +async function serialize(data: any, signal?: AbortSignal) { + signal?.throwIfAborted() + let value + try { + value = await toJSONAsync(data, { + plugins: signal ? getDefaultSerovalPlugins(signal) : serovalPlugins!, + }) + } finally { + signal?.throwIfAborted() + } + return JSON.stringify(value) } async function getFetchBody( opts: FunctionMiddlewareClientFnOptions, -): Promise<{ body: FormData | string; contentType?: string } | undefined> { +): Promise { if (opts.data instanceof FormData) { let serializedContext = undefined // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (opts.context && Object.keys(opts.context).length > 0) { - serializedContext = await serialize(opts.context) + if (opts.context && hasOwnProperties(opts.context)) { + serializedContext = await serialize(opts.context, opts.signal) } if (serializedContext !== undefined) { opts.data.set(TSS_FORMDATA_CONTEXT, serializedContext) } - return { body: opts.data } + return opts.data } - const serializedBody = await serializePayload(opts) - if (serializedBody) { - return { body: serializedBody, contentType: 'application/json' } - } - return undefined + return serializePayload(opts) } /** @@ -163,60 +232,89 @@ async function getFetchBody( * @throws If the response is invalid or an error occurs during processing. */ async function getResponse(fn: () => Promise) { - const response = await (async () => { - try { - return await fn() - } catch (error) { - if (error instanceof Response) { - return error - } - console.log(error) + let response: Response + try { + response = await fn() // client => server => fn => server => client + } catch (error) { + if (error instanceof Response) { + response = error + } else { throw error } - })() + } - if (response.headers.get(X_TSS_RAW_RESPONSE) === 'true') { + const raw = response.headers.get(X_TSS_RAW_RESPONSE) + if (raw === 'true') { return response } - const contentType = response.headers.get('content-type') - invariant(contentType, 'expected content-type header to be set') - const serializedByStart = !!response.headers.get(X_TSS_SERIALIZED) - // If the response is not ok, throw an error - if (!response.ok) { - if (serializedByStart && contentType.includes('application/json')) { - const jsonPayload = await response.json() - const result = fromCrossJSON(jsonPayload, { plugins: serovalPlugins! }) - throw result - } - - throw new Error(await response.text()) + // The server function threw this Response, so the call rejects with it. + if (raw === 'thrown') { + throw response } + const contentType = response.headers.get('content-type') + if (!contentType) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + 'Invariant failed: expected content-type header to be set', + ) + } + + invariant() + } + const serializedByStart = !!response.headers.get(X_TSS_SERIALIZED) + + // If the response is serialized by the start server, we need to process it + // differently than a normal response. if (serializedByStart) { let result - if (contentType.includes('application/x-ndjson')) { - const refs = new Map() - result = await processServerFnResponse({ - response, - onMessage: (msg) => - fromCrossJSON(msg, { refs, plugins: serovalPlugins! }), - onError(msg, error) { - // TODO how could we notify consumer that an error occurred? - console.error(msg, error) - }, - }) + + // If it's a framed response (contains RawStream), use frame decoder + if (contentType.includes(TSS_CONTENT_TYPE_FRAMED)) { + // A server without a version parameter predates versioning. + const version = /;\s*v=(\d+)/.exec(contentType)?.[1] + if (version && +version !== TSS_FRAMED_PROTOCOL_VERSION) { + throw new Error(`Unsupported framed protocol version ${version}`) + } + if (!response.body) { + throw new Error('No response body for framed response') + } + + const [chunks, getStream] = createFrameDecoder(response.body) + + // Create deserialize plugin that wires up the raw streams + const rawStreamPlugin = createRawStreamDeserializePlugin(getStream) + const plugins = [rawStreamPlugin, ...serovalPlugins!] + + result = await processFramedResponse(chunks, plugins) } - if (contentType.includes('application/json')) { + // If it's a JSON response, it can be simpler + else if (contentType.includes('application/json')) { const jsonPayload = await response.json() - result = fromCrossJSON(jsonPayload, { plugins: serovalPlugins! }) + // Track async post-processing work for this deserialization + const postProcessPromises: Array> = [] + result = deserialize( + jsonPayload, + { plugins: serovalPlugins! }, + postProcessPromises, + ) + // Await any async post-processing before returning + await awaitPostProcessPromises(postProcessPromises) } - invariant(result, 'expected result to be resolved') - if (result instanceof Error) { - throw result + + if (!result) { + if (process.env.NODE_ENV !== 'production') { + throw new Error('Invariant failed: expected result to be resolved') + } + + invariant() } + return result } + // If it wasn't processed by the start serializer, check + // if it's JSON if (contentType.includes('application/json')) { const jsonPayload = await response.json() const redirect = parseRedirect(jsonPayload) @@ -229,89 +327,75 @@ async function getResponse(fn: () => Promise) { return jsonPayload } + // Otherwise, if it's not OK, throw the content + if (!response.ok) { + throw new Error(await response.text()) + } + + // Or return the response itself return response } -async function processServerFnResponse({ - response, - onMessage, - onError, -}: { - response: Response - onMessage: (msg: any) => any - onError?: (msg: string, error?: any) => void -}) { - if (!response.body) { - throw new Error('No response body') +/** Processes the complete JSON values emitted by the frame decoder. */ +async function processFramedResponse( + jsonStream: ReadableStream, + plugins: Array>, +) { + const reader = jsonStream.getReader() + const options = { refs: new Map(), plugins } + + // TODO: promises and streams that Seroval created from earlier records stay + // pending after a transport failure. Rejecting them needs a Seroval API for + // aborting a cross-JSON deserialization session; do not reach into + // Seroval's refs to do it here. + const fail = (error: unknown) => { + void reader.cancel(error).catch(() => {}) } - const reader = response.body.pipeThrough(new TextDecoderStream()).getReader() - - let buffer = '' - let firstRead = false - let firstObject - - while (!firstRead) { - const { value, done } = await reader.read() - if (value) buffer += value - - if (buffer.length === 0 && done) { + let result: any + const initialPostProcessPromises: Array> = [] + try { + const first = await reader.read() + if (first.done) { throw new Error('Stream ended before first object') } - // common case: buffer ends with newline - if (buffer.endsWith('\n')) { - const lines = buffer.split('\n').filter(Boolean) - const firstLine = lines[0] - if (!firstLine) throw new Error('No JSON line in the first chunk') - firstObject = JSON.parse(firstLine) - firstRead = true - buffer = lines.slice(1).join('\n') - } else { - // fallback: wait for a newline to parse first object safely - const newlineIndex = buffer.indexOf('\n') - if (newlineIndex >= 0) { - const line = buffer.slice(0, newlineIndex).trim() - buffer = buffer.slice(newlineIndex + 1) - if (line.length > 0) { - firstObject = JSON.parse(line) - firstRead = true - } - } - } + result = deserialize( + JSON.parse(first.value), + options, + initialPostProcessPromises, + ) + } catch (error) { + fail(error) + reader.releaseLock() + throw error } - // process rest of the stream asynchronously - ;(async () => { + // Keep consuming patches before awaiting root post-processing: that work may + // itself depend on raw frames which follow later JSON frames on the wire. + void (async () => { + const postProcessPromises: Array> = [] try { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - while (true) { - const { value, done } = await reader.read() - if (value) buffer += value - - const lastNewline = buffer.lastIndexOf('\n') - if (lastNewline >= 0) { - const chunk = buffer.slice(0, lastNewline) - buffer = buffer.slice(lastNewline + 1) - const lines = chunk.split('\n').filter(Boolean) - - for (const line of lines) { - try { - onMessage(JSON.parse(line)) - } catch (e) { - onError?.(`Invalid JSON line: ${line}`, e) - } - } + for (;;) { + const next = await reader.read() + if (next.done) { + return } - if (done) { - break - } + deserialize(JSON.parse(next.value), options, postProcessPromises) + // Later patches publish their promise/stream values synchronously. + // Observe auxiliary work without blocking frames those values need. + observePostProcessPromises(postProcessPromises) } - } catch (err) { - onError?.('Stream processing error:', err) + } catch (error) { + fail(error) + console.error('Stream processing error:', error) + } finally { + reader.releaseLock() } })() - return onMessage(firstObject) + await awaitPostProcessPromises(initialPostProcessPromises) + + return result } diff --git a/packages/start-client-core/src/client/ServerFunctionSerializationAdapter.ts b/packages/start-client-core/src/client/ServerFunctionSerializationAdapter.ts index 6df1f4fa6d..743673a8c2 100644 --- a/packages/start-client-core/src/client/ServerFunctionSerializationAdapter.ts +++ b/packages/start-client-core/src/client/ServerFunctionSerializationAdapter.ts @@ -4,13 +4,13 @@ import { createClientRpc } from '../client-rpc/createClientRpc' export const ServerFunctionSerializationAdapter = createSerializationAdapter({ key: '$TSS/serverfn', - test: (v): v is { functionId: string } => { + test: (v): v is { serverFnMeta: { id: string } } => { if (typeof v !== 'function') return false if (!(TSS_SERVER_FUNCTION in v)) return false return !!v[TSS_SERVER_FUNCTION] }, - toSerializable: ({ functionId }) => ({ functionId }), + toSerializable: ({ serverFnMeta }) => ({ functionId: serverFnMeta.id }), fromSerializable: ({ functionId }) => createClientRpc(functionId), }) diff --git a/packages/start-client-core/src/client/hydrateStart.ts b/packages/start-client-core/src/client/hydrateStart.ts index 4377aa4b3b..d3742e5ff6 100644 --- a/packages/start-client-core/src/client/hydrateStart.ts +++ b/packages/start-client-core/src/client/hydrateStart.ts @@ -1,14 +1,27 @@ import { hydrate } from '@tanstack/router-core/ssr/client' - -import { ServerFunctionSerializationAdapter } from './ServerFunctionSerializationAdapter' -import type { AnyStartInstanceOptions } from '../createStart' -import type { AnyRouter, AnySerializationAdapter } from '@tanstack/router-core' -// eslint-disable-next-line import/no-duplicates,import/order -import { getRouter } from '#tanstack-router-entry' -// eslint-disable-next-line import/no-duplicates,import/order import { startInstance } from '#tanstack-start-entry' +import { + hasPluginAdapters, + pluginSerializationAdapters, +} from '#tanstack-start-plugin-adapters' +import { getRouter } from '#tanstack-router-entry' +import { ServerFunctionSerializationAdapter } from './ServerFunctionSerializationAdapter' +import type { AnyRouter, AnySerializationAdapter } from '@tanstack/router-core' +import type { AnyStartInstanceOptions } from '../createStart' -export async function hydrateStart(): Promise { +type HotContext = { + data?: Record + dispose?: (cb: (data: Record) => void) => void +} + +declare global { + interface ImportMeta { + hot?: HotContext + webpackHot?: HotContext + } +} + +async function hydrateStart(): Promise { const router = await getRouter() let serializationAdapters: Array @@ -26,6 +39,10 @@ export async function hydrateStart(): Promise { } as AnyStartInstanceOptions } + // Only spread plugin adapters if any are configured (this will tree-shake away otherwise) + if (hasPluginAdapters) { + serializationAdapters.push(...pluginSerializationAdapters) + } serializationAdapters.push(ServerFunctionSerializationAdapter) if (router.options.serializationAdapters) { serializationAdapters.push(...router.options.serializationAdapters) @@ -35,9 +52,44 @@ export async function hydrateStart(): Promise { basepath: process.env.TSS_ROUTER_BASEPATH, ...{ serializationAdapters }, }) - if (!router.state.matches.length) { + if (!router.stores.ids.get().length) { await hydrate(router) } return router } + +function hydrateStartWithHmr(): Promise { + const hot = import.meta.hot ?? import.meta.webpackHot + + if (!hot) { + return hydrateStart() + } + + const key = 'tss-hydrate-start-promise' + const hotData = (hot.data ??= {}) + let hydrationPromise = hotData[key] as Promise | undefined + + if (!hydrationPromise) { + hydrationPromise = hydrateStart().catch((error) => { + if (hotData[key] === hydrationPromise) { + hotData[key] = undefined + } + + throw error + }) + + hotData[key] = hydrationPromise + } + + hot.dispose?.((data) => { + data[key] = hotData[key] + }) + + return hydrationPromise +} + +const exportedHydrateStart = + process.env.NODE_ENV !== 'production' ? hydrateStartWithHmr : hydrateStart + +export { exportedHydrateStart as hydrateStart } diff --git a/packages/start-client-core/src/constants.ts b/packages/start-client-core/src/constants.ts index 1e541af323..1b7bd1077e 100644 --- a/packages/start-client-core/src/constants.ts +++ b/packages/start-client-core/src/constants.ts @@ -6,4 +6,59 @@ export const TSS_SERVER_FUNCTION_FACTORY = Symbol.for( export const X_TSS_SERIALIZED = 'x-tss-serialized' export const X_TSS_RAW_RESPONSE = 'x-tss-raw' +export const X_TSS_CONTEXT = 'x-tss-context' + +/** Content-Type for multiplexed framed responses (RawStream support) */ +export const TSS_CONTENT_TYPE_FRAMED = 'application/x-tss-framed' + +/** + * Frame types for binary multiplexing protocol. + */ +export const FRAME_TYPE_JSON = 0 +export const FRAME_TYPE_CHUNK = 1 +export const FRAME_TYPE_END = 2 +export const FRAME_TYPE_ERROR = 3 + +/** Header size in bytes: type(1) + streamId(4) + length(4) */ +export const FRAME_HEADER_SIZE = 9 + +/** Largest payload accepted by one framed-protocol record. */ +export const MAX_FRAME_PAYLOAD_SIZE = 16 * 1024 * 1024 + +/** Largest number of raw streams accepted in one framed response. */ +export const MAX_FRAMED_STREAMS = 1024 + +/** + * Largest number of bytes one raw stream may hold unread. Raw streams share + * one ordered response, so an unread stream would otherwise buffer without + * bound while later frames arrive. + */ +export const MAX_UNREAD_RAW_STREAM_BYTES = 128 * 1024 * 1024 + +/** Current protocol version for framed responses */ +export const TSS_FRAMED_PROTOCOL_VERSION = 1 + +/** Full Content-Type header value with version parameter */ +export const TSS_CONTENT_TYPE_FRAMED_VERSIONED = `${TSS_CONTENT_TYPE_FRAMED}; v=${TSS_FRAMED_PROTOCOL_VERSION}` + +/** + * Minimal metadata about a server function, available to client middleware. + * Only contains the function ID since name/filename may expose server internals. + */ +export interface ClientFnMeta { + /** The unique identifier for this server function */ + id: string +} + +/** + * Full metadata about a server function, available to server middleware and server functions. + * This information is embedded at compile time by the TanStack Start compiler. + */ +export interface ServerFnMeta extends ClientFnMeta { + /** The original variable name of the server function (e.g., "myServerFn") */ + name: string + /** The source file path relative to the project root (e.g., "src/routes/api.ts") */ + filename: string +} + export {} diff --git a/packages/start-client-core/src/createCsrfMiddleware.ts b/packages/start-client-core/src/createCsrfMiddleware.ts new file mode 100644 index 0000000000..75cf65c81e --- /dev/null +++ b/packages/start-client-core/src/createCsrfMiddleware.ts @@ -0,0 +1,241 @@ +import { createIsomorphicFn } from '@tanstack/start-fn-stubs' +import { isPromise } from '@tanstack/router-core' +import { createMiddleware } from './createMiddleware' +import type { + RequestMiddlewareAfterServer, + RequestServerOptions, +} from './createMiddleware' +import type { Register } from '@tanstack/router-core' + +export const csrfSymbol = Symbol.for('tanstack-start:csrf-middleware') + +export type CsrfSecFetchSite = + | 'same-origin' + | 'same-site' + | 'cross-site' + | 'none' + +export type CsrfMatcher = + | TValue + | Array + | (( + value: TValue | (string & {}), + ctx: RequestServerOptions, + ) => boolean | Promise) + +export interface CsrfMiddlewareOptions< + TRegister = Register, + TMiddlewares = unknown, +> { + /** + * Return `true` to validate this request, or `false` to skip validation. + * + * @default undefined, which validates every request handled by this middleware. + */ + filter?: ( + ctx: RequestServerOptions, + ) => boolean | Promise + /** + * Allowed Origin values. Defaults to the trusted request origin. + */ + origin?: CsrfMatcher + /** + * Allowed Sec-Fetch-Site values. + * + * @default 'same-origin' + */ + secFetchSite?: CsrfMatcher + /** + * Whether to use Referer as a fallback when Sec-Fetch-Site and Origin are absent. + * + * @default true + */ + referer?: + | boolean + | (( + referer: string, + ctx: RequestServerOptions, + ) => boolean | Promise) + /** + * Allow requests when Sec-Fetch-Site, Origin, and Referer are all missing. + * + * @default false + */ + allowRequestsWithoutOriginCheck?: boolean + /** + * Optional response returned when CSRF validation fails. + * + * @default new Response('Forbidden', { status: 403 }) + */ + failureResponse?: + | Response + | (( + ctx: RequestServerOptions, + ) => Response | Promise) +} + +type CreateCsrfMiddleware = ( + opts?: CsrfMiddlewareOptions, +) => RequestMiddlewareAfterServer<{}, undefined, undefined> + +const innerCreateCsrfMiddleware: CreateCsrfMiddleware = (opts = {}) => { + const continueRequest = ( + result: boolean | undefined, + ctx: RequestServerOptions, + ) => { + return isValidationResultAllowed(result, opts) + ? ctx.next() + : getFailureResponse(opts, ctx) + } + + const validateRequest = (ctx: RequestServerOptions) => { + const result = validateCsrfRequest(opts, ctx) + if (isPromise(result)) { + return result.then((result) => continueRequest(result, ctx)) + } + return continueRequest(result, ctx) + } + + // Synchronous checks can pass through next() without another promise chain. + const middleware = createMiddleware().server((ctx) => { + const csrfCtx = ctx as RequestServerOptions + try { + if (opts.filter) { + const shouldValidate = opts.filter(csrfCtx) + if (isPromise(shouldValidate)) { + return shouldValidate.then((shouldValidate) => + shouldValidate ? validateRequest(csrfCtx) : ctx.next(), + ) + } + if (!shouldValidate) { + return ctx.next() + } + } + return validateRequest(csrfCtx) + } catch (error) { + return Promise.reject(error) + } + }) + + if (process.env.NODE_ENV !== 'production') { + Object.defineProperty(middleware, csrfSymbol, { value: true }) + } + + return middleware +} + +export const createCsrfMiddleware: CreateCsrfMiddleware = + createIsomorphicFn().server(innerCreateCsrfMiddleware) as CreateCsrfMiddleware + +export async function isCsrfRequestAllowed( + opts: CsrfMiddlewareOptions, + ctx: RequestServerOptions, +): Promise { + return isValidationResultAllowed(await validateCsrfRequest(opts, ctx), opts) +} + +function isValidationResultAllowed( + result: boolean | undefined, + opts: CsrfMiddlewareOptions, +): boolean { + return ( + result === true || + (result === undefined && opts.allowRequestsWithoutOriginCheck === true) + ) +} + +export async function getCsrfRequestValidationResult( + opts: CsrfMiddlewareOptions, + ctx: RequestServerOptions, +): Promise { + return validateCsrfRequest(opts, ctx) +} + +function validateCsrfRequest( + opts: CsrfMiddlewareOptions, + ctx: RequestServerOptions, +): boolean | undefined | Promise { + const fetchSite = ctx.request.headers.get('Sec-Fetch-Site') + if (fetchSite !== null) { + return matchValue(opts.secFetchSite ?? 'same-origin', fetchSite, ctx) + } + + const origin = ctx.request.headers.get('Origin') + if (origin !== null) { + if (opts.origin) { + return matchValue(opts.origin, origin, ctx) + } + + return origin === new URL(ctx.request.url).origin + } + + const referer = ctx.request.headers.get('Referer') + if (referer === null || opts.referer === false) { + return undefined + } + + if (typeof opts.referer === 'function') { + return opts.referer(referer, ctx) + } + + if (opts.origin) { + const refererOrigin = getOriginFromUrl(referer) + return ( + refererOrigin !== undefined && matchValue(opts.origin, refererOrigin, ctx) + ) + } + + return isRefererSameOrigin(referer, new URL(ctx.request.url).origin) +} + +function matchValue( + matcher: CsrfMatcher, + value: string, + ctx: RequestServerOptions, +): boolean | Promise { + if (typeof matcher === 'function') { + return matcher(value, ctx) + } + + if (Array.isArray(matcher)) { + // typescript is dumb for array.includes() + return matcher.includes(value as TValue) + } + + return value === matcher +} + +function getOriginFromUrl(url: string): string | undefined { + try { + return new URL(url).origin + } catch { + return undefined + } +} + +function isRefererSameOrigin(referer: string, requestOrigin: string): boolean { + if (referer === requestOrigin) { + return true + } + if (!referer.startsWith(requestOrigin)) { + return false + } + if (referer.length === requestOrigin.length) { + return true + } + const code = referer.charCodeAt(requestOrigin.length) + return code === 47 /* '/' */ || code === 63 /* '?' */ || code === 35 /* '#' */ +} + +function getFailureResponse( + opts: CsrfMiddlewareOptions, + ctx: RequestServerOptions, +): Response | Promise { + if (typeof opts.failureResponse === 'function') { + return opts.failureResponse(ctx) + } + + return ( + opts.failureResponse?.clone() ?? new Response('Forbidden', { status: 403 }) + ) +} diff --git a/packages/start-client-core/src/createIsomorphicFn.ts b/packages/start-client-core/src/createIsomorphicFn.ts deleted file mode 100644 index 09a1be9ec1..0000000000 --- a/packages/start-client-core/src/createIsomorphicFn.ts +++ /dev/null @@ -1,41 +0,0 @@ -// a function that can have different implementations on the client and server. -// implementations not provided will default to a no-op function. - -export type IsomorphicFn< - TArgs extends Array = [], - TServer = undefined, - TClient = undefined, -> = (...args: TArgs) => TServer | TClient - -export interface ServerOnlyFn, TServer> - extends IsomorphicFn { - client: ( - clientImpl: (...args: TArgs) => TClient, - ) => IsomorphicFn -} - -export interface ClientOnlyFn, TClient> - extends IsomorphicFn { - server: ( - serverImpl: (...args: TArgs) => TServer, - ) => IsomorphicFn -} - -export interface IsomorphicFnBase extends IsomorphicFn { - server: , TServer>( - serverImpl: (...args: TArgs) => TServer, - ) => ServerOnlyFn - client: , TClient>( - clientImpl: (...args: TArgs) => TClient, - ) => ClientOnlyFn -} - -// this is a dummy function, it will be replaced by the transformer -// if we use `createIsomorphicFn` in this library itself, vite tries to execute it before the transformer runs -// therefore we must return a dummy function that allows calling `server` and `client` method chains. -export function createIsomorphicFn(): IsomorphicFnBase { - return { - server: () => ({ client: () => () => {} }), - client: () => ({ server: () => () => {} }), - } as any -} diff --git a/packages/start-client-core/src/createMiddleware.ts b/packages/start-client-core/src/createMiddleware.ts index c47c3aa1b4..9b19833d09 100644 --- a/packages/start-client-core/src/createMiddleware.ts +++ b/packages/start-client-core/src/createMiddleware.ts @@ -1,5 +1,11 @@ import type { StartInstanceOptions } from './createStart' -import type { AnyServerFn, ConstrainValidator, Method } from './createServerFn' +import type { + AnyServerFn, + ConstrainValidator, + CustomFetch, + Method, +} from './createServerFn' +import type { ClientFnMeta, ServerFnMeta } from './constants' import type { AnyContext, Assign, @@ -30,32 +36,22 @@ export const createMiddleware: CreateMiddlewareFn<{}> = (options, __opts) => { type: 'request', ...(__opts || options), } - return { options: resolvedOptions, middleware: (middleware: any) => { return createMiddleware( - {} as any, + {}, Object.assign(resolvedOptions, { middleware }), - ) as any + ) }, - inputValidator: (inputValidator: any) => { - return createMiddleware( - {} as any, - Object.assign(resolvedOptions, { inputValidator }), - ) as any + validator: (validator: any) => { + return createMiddleware({}, Object.assign(resolvedOptions, { validator })) }, client: (client: any) => { - return createMiddleware( - {} as any, - Object.assign(resolvedOptions, { client }), - ) as any + return createMiddleware({}, Object.assign(resolvedOptions, { client })) }, server: (server: any) => { - return createMiddleware( - {} as any, - Object.assign(resolvedOptions, { server }), - ) as any + return createMiddleware({}, Object.assign(resolvedOptions, { server })) }, } as any } @@ -69,8 +65,9 @@ export type CreateMiddlewareResult< ? RequestMiddleware : FunctionMiddleware -export interface FunctionMiddleware - extends FunctionMiddlewareAfterMiddleware { +export interface FunctionMiddleware< + TRegister, +> extends FunctionMiddlewareAfterMiddleware { middleware: ( middlewares: Constrain< TNewMiddlewares, @@ -80,7 +77,8 @@ export interface FunctionMiddleware } export interface FunctionMiddlewareAfterMiddleware - extends FunctionMiddlewareWithTypes< + extends + FunctionMiddlewareWithTypes< TRegister, TMiddlewares, undefined, @@ -168,7 +166,7 @@ export interface FunctionMiddlewareTypes< TMiddlewares, TClientSendContext > - inputValidator: TInputValidator + validator: TInputValidator } /** @@ -227,7 +225,7 @@ export type IntersectAllValidatorOutputs = ? IntersectAllMiddleware : IntersectAssign< IntersectAllMiddleware, - ResolveValidatorOutput + Awaited> > /** @@ -377,7 +375,7 @@ export interface FunctionMiddlewareOptions< in out TClientContext, > { middleware?: TMiddlewares - inputValidator?: ConstrainValidator + validator?: ConstrainValidator client?: FunctionMiddlewareClientFn< TRegister, TMiddlewares, @@ -402,6 +400,7 @@ export type FunctionMiddlewareClientNextFn = < context?: TNewClientContext sendContext?: ValidateSerializableInput headers?: HeadersInit + fetch?: CustomFetch }) => Promise< FunctionClientResultWithContext > @@ -511,8 +510,7 @@ export interface FunctionMiddlewareServerFnOptions< TServerSendContext > method: Method - filename: string - functionId: string + serverFnMeta: ServerFnMeta signal: AbortSignal } @@ -549,14 +547,14 @@ export interface FunctionMiddlewareAfterServer< TClientContext, TClientSendContext, > extends FunctionMiddlewareWithTypes< - TRegister, - TMiddlewares, - TInputValidator, - TServerContext, - TServerSendContext, - TClientContext, - TClientSendContext - > {} + TRegister, + TMiddlewares, + TInputValidator, + TServerContext, + TServerSendContext, + TClientContext, + TClientSendContext +> {} export interface FunctionMiddlewareClient< TRegister, @@ -608,9 +606,10 @@ export interface FunctionMiddlewareClientFnOptions< sendContext: Expand> method: Method signal: AbortSignal + serverFnMeta: ClientFnMeta next: FunctionMiddlewareClientNextFn filename: string - functionId: string + fetch?: CustomFetch } export type FunctionMiddlewareClientFnResult< @@ -636,6 +635,7 @@ export type FunctionClientResultWithContext< context: Expand> sendContext: Expand> headers: HeadersInit + fetch?: CustomFetch } export interface FunctionMiddlewareAfterClient< @@ -644,7 +644,9 @@ export interface FunctionMiddlewareAfterClient< TInputValidator, TServerSendContext, TClientContext, -> extends FunctionMiddlewareWithTypes< +> + extends + FunctionMiddlewareWithTypes< TRegister, TMiddlewares, TInputValidator, @@ -662,8 +664,8 @@ export interface FunctionMiddlewareAfterClient< > {} export interface FunctionMiddlewareValidator { - inputValidator: ( - inputValidator: ConstrainValidator, + validator: ( + validator: ConstrainValidator, ) => FunctionMiddlewareAfterValidator } @@ -671,7 +673,9 @@ export interface FunctionMiddlewareAfterValidator< TRegister, TMiddlewares, TInputValidator, -> extends FunctionMiddlewareWithTypes< +> + extends + FunctionMiddlewareWithTypes< TRegister, TMiddlewares, TInputValidator, @@ -689,8 +693,9 @@ export interface FunctionMiddlewareAfterValidator< >, FunctionMiddlewareClient {} -export interface RequestMiddleware - extends RequestMiddlewareAfterMiddleware { +export interface RequestMiddleware< + TRegister, +> extends RequestMiddlewareAfterMiddleware { middleware: ( middlewares: Constrain>, ) => RequestMiddlewareAfterMiddleware @@ -736,7 +741,8 @@ export interface RequestMiddlewareTypes< } export interface RequestMiddlewareAfterMiddleware - extends RequestMiddlewareWithTypes, + extends + RequestMiddlewareWithTypes, RequestMiddlewareServer {} export interface RequestMiddlewareServer { @@ -754,6 +760,16 @@ export interface RequestServerOptions { pathname: string context: Expand> next: RequestServerNextFn + /** + * Type of Start handler currently processing this request. + */ + handlerType: 'serverFn' | 'router' + /** + * Metadata about the server function being invoked. + * This is only present when the request is handling a server function call. + * For regular page requests, this will be undefined. + */ + serverFnMeta?: ServerFnMeta } export type RequestServerNextFn = < @@ -767,9 +783,8 @@ export interface RequestServerNextFnOptions { } export type RequestServerNextFnResult = - - | Promise> - | RequestServerResult + | Promise> + | RequestServerResult export type RequestMiddlewareServerFnResult< TRegister, diff --git a/packages/start-client-core/src/createServerFn.ts b/packages/start-client-core/src/createServerFn.ts index 3307d4b7ce..ea1566aa37 100644 --- a/packages/start-client-core/src/createServerFn.ts +++ b/packages/start-client-core/src/createServerFn.ts @@ -1,10 +1,16 @@ -import { isNotFound, isRedirect } from '@tanstack/router-core' import { mergeHeaders } from '@tanstack/router-core/ssr/client' +import { isRedirect, parseRedirect } from '@tanstack/router-core' +import { isServer } from '@tanstack/router-core/isServer' import { TSS_SERVER_FUNCTION_FACTORY } from './constants' import { getStartOptions } from './getStartOptions' import { getStartContextServerOnly } from './getStartContextServerOnly' -import type { TSS_SERVER_FUNCTION } from './constants' +import { createNullProtoObject, safeObjectMerge } from './safeObjectMerge' +import type { + ClientFnMeta, + ServerFnMeta, + TSS_SERVER_FUNCTION, +} from './constants' import type { AnyValidator, Constrain, @@ -20,31 +26,51 @@ import type { AnyFunctionMiddleware, AnyRequestMiddleware, AssignAllServerFnContext, - FunctionMiddlewareClientFnResult, - FunctionMiddlewareServerFnResult, IntersectAllValidatorInputs, IntersectAllValidatorOutputs, } from './createMiddleware' -type TODO = any +export type ServerFnStrict = boolean | { input?: boolean; output?: boolean } + +export interface ServerFnOptions< + TMethod extends Method = Method, + TStrict extends ServerFnStrict = true, +> { + method?: TMethod + strict?: TStrict +} + +export type ServerFnStrictInput = + TStrict extends false + ? false + : TStrict extends { input: infer TInput extends boolean } + ? TInput + : true + +export type ServerFnStrictOutput = + TStrict extends false + ? false + : TStrict extends { output: infer TOutput extends boolean } + ? TOutput + : true export type CreateServerFn = < TMethod extends Method, + TStrict extends ServerFnStrict = true, TResponse = unknown, TMiddlewares = undefined, TInputValidator = undefined, >( - options?: { - method?: TMethod - }, + options?: ServerFnOptions, __opts?: ServerFnBaseOptions< TRegister, TMethod, TResponse, TMiddlewares, - TInputValidator + TInputValidator, + TStrict >, -) => ServerFnBuilder +) => ServerFnBuilder export const createServerFn: CreateServerFn = (options, __opts) => { const resolvedOptions = (__opts || options || {}) as ServerFnBaseOptions< @@ -52,6 +78,7 @@ export const createServerFn: CreateServerFn = (options, __opts) => { any, any, any, + any, any > @@ -59,20 +86,21 @@ export const createServerFn: CreateServerFn = (options, __opts) => { resolvedOptions.method = 'GET' as Method } - const res: ServerFnBuilder = { - options: resolvedOptions as any, + const res: ServerFnBuilder = { + options: resolvedOptions, middleware: (middleware) => { // multiple calls to `middleware()` merge the middlewares with the previously supplied ones // this is primarily useful for letting users create their own abstractions on top of `createServerFn` const newMiddleware = [...(resolvedOptions.middleware || [])] - middleware.map((m) => { - if (TSS_SERVER_FUNCTION_FACTORY in m) { - if (m.options.middleware) { - newMiddleware.push(...m.options.middleware) + // forEach skips holes and ignores items appended during iteration + middleware.forEach((item) => { + if (TSS_SERVER_FUNCTION_FACTORY in item) { + if (item.options.middleware) { + newMiddleware.push(...item.options.middleware) } } else { - newMiddleware.push(m) + newMiddleware.push(item) } }) @@ -80,12 +108,15 @@ export const createServerFn: CreateServerFn = (options, __opts) => { ...resolvedOptions, middleware: newMiddleware, } - const res = createServerFn(undefined, newOptions) as any + const res = createServerFn(undefined, newOptions) res[TSS_SERVER_FUNCTION_FACTORY] = true return res }, - inputValidator: (inputValidator) => { - const newOptions = { ...resolvedOptions, inputValidator } + validator: (validator) => { + const newOptions = { + ...resolvedOptions, + validator, + } return createServerFn(undefined, newOptions) as any }, handler: (...args) => { @@ -109,133 +140,222 @@ export const createServerFn: CreateServerFn = (options, __opts) => { // We want to make sure the new function has the same // properties as the original function + // Propagate the declared HTTP method onto the extracted handler + // so the manifest-exported symbol (resolved by getServerFnById) + // carries `method`, enabling the server handler to reject + // mismatched HTTP methods before parsing request payloads. + ;(extractedFn as any).method = resolvedOptions.method + return Object.assign( async (opts?: CompiledFetcherFnOptions) => { // Start by executing the client-side middleware chain - return executeMiddleware(resolvedMiddleware, 'client', { + const result = await executeMiddleware(resolvedMiddleware, 'client', { ...extractedFn, ...newOptions, - data: opts?.data as any, + data: opts?.data, headers: opts?.headers, signal: opts?.signal, - context: {}, - }).then((d) => { - if (d.error) throw d.error - return d.result + fetch: opts?.fetch, + context: createNullProtoObject(), }) + + // Only a failed call has an `error` key. Its value is whatever was + // thrown, so a thrown undefined or 0 still rejects the call. + if ('error' in result) { + throw parseRedirect(result.error) ?? result.error + } + return result.result }, { // This copies over the URL, function ID ...extractedFn, + // Expose the declared HTTP method so the server handler + // can reject mismatched methods before parsing payloads + method: resolvedOptions.method, // The extracted function on the server-side calls - // this function - __executeServer: async (opts: any, signal: AbortSignal) => { - const startContext = getStartContextServerOnly() - const serverContextAfterGlobalMiddlewares = - startContext.contextAfterGlobalMiddlewares - const ctx = { - ...extractedFn, - ...opts, - context: { - ...serverContextAfterGlobalMiddlewares, - ...opts.context, - }, - signal, - request: startContext.request, - } + // this function. Browsers never execute a server function. + __executeServer: + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- isServer is only known outside development + (isServer ?? typeof window === 'undefined') + ? async (opts: any) => { + const startContext = getStartContextServerOnly() + const serverContextAfterGlobalMiddlewares = + startContext.contextAfterGlobalMiddlewares + const ctx = { + ...extractedFn, + data: opts.data, + method: opts.method ?? resolvedOptions.method, + // Ensure we use the full serverFnMeta from the provider file's extractedFn + // (which has id, name, filename) rather than the partial one from SSR/client + // callers (which only has id) + serverFnMeta: extractedFn.serverFnMeta, + // Merge client context first so trusted server middleware context wins. + context: safeObjectMerge( + opts.context, + serverContextAfterGlobalMiddlewares, + ), + request: startContext.request, + } - return executeMiddleware(resolvedMiddleware, 'server', ctx).then( - (d) => ({ - // Only send the result and sendContext back to the client - result: d.result, - error: d.error, - context: d.sendContext, - }), - ) - }, + const result = await executeMiddleware( + resolvedMiddleware, + 'server', + ctx, + ) + + // Only send the result and sendContext back to the client. A + // failed call sends only its thrown value, under an `error` key. + if ('error' in result) { + return { error: result.error } + } + return result.sendContext === undefined + ? { result: result.result } + : { result: result.result, context: result.sendContext } + } + : undefined, }, ) as any }, - } as ServerFnBuilder - const fun = (options?: { method?: Method }) => { + } as ServerFnBuilder + const fun = (options?: ServerFnOptions) => { const newOptions = { ...resolvedOptions, ...options, } - return createServerFn(undefined, newOptions) as any + return createServerFn(undefined, newOptions) } return Object.assign(fun, res) as any } +function mergeOptionalSendContext( + target: Record | undefined, + source: Record | null | undefined, +) { + return target === undefined && source === undefined + ? undefined + : safeObjectMerge(target, source) +} + +function mergeOptionalHeaders( + target: HeadersInit | undefined, + source: HeadersInit | undefined, +) { + return target || source ? mergeHeaders(target, source) : undefined +} + export async function executeMiddleware( middlewares: Array, env: 'client' | 'server', opts: ServerFnMiddlewareOptions, ): Promise { - const globalMiddlewares = getStartOptions()?.functionMiddleware || [] - const flattenedMiddlewares = flattenMiddlewares([ - ...globalMiddlewares, - ...middlewares, - ]) + const globalMiddlewares: Array = + getStartOptions()?.functionMiddleware || [] + // On the server, flattening skips middlewares that already executed in the + // request phase to prevent duplicate execution (issue #5239) + const flattenedMiddlewares = flattenMiddlewares( + globalMiddlewares.concat(middlewares), + undefined, + env === 'server' + ? new Set( + getStartContextServerOnly({ throwIfNotFound: false }) + ?.executedRequestMiddlewares, + ) + : undefined, + ) - const next: NextFn = async (ctx) => { - // Get the next middleware - const nextMiddleware = flattenedMiddlewares.shift() + let index = 0 - // If there are no more middlewares, return the context - if (!nextMiddleware) { - return ctx - } - - if ( - 'inputValidator' in nextMiddleware.options && - nextMiddleware.options.inputValidator && - env === 'server' - ) { - // Execute the middleware's input function - ctx.data = await execValidator( - nextMiddleware.options.inputValidator, - ctx.data, + // Runs the remaining middlewares. A middleware's next() continues with its + // context merged with what it passed. Failures reject every pending next() + // up to the top, where they become `{ error }`. + const callNextMiddleware = async ( + callerCtx: ServerFnMiddlewareResult, + userCtx?: ServerFnMiddlewareResult, + ): Promise => { + let ctx = callerCtx + if (userCtx !== undefined) { + // Assign after the spreads: an object literal with properties after a + // second spread defines each of them through a slow runtime call. + ctx = { ...callerCtx, ...userCtx } + // Use safeObjectMerge for context objects to prevent prototype pollution + ctx.context = safeObjectMerge(callerCtx.context, userCtx.context) + ctx.sendContext = mergeOptionalSendContext( + callerCtx.sendContext, + userCtx.sendContext, ) + ctx.headers = mergeOptionalHeaders(callerCtx.headers, userCtx.headers) + ctx._callSiteFetch = callerCtx._callSiteFetch + ctx.fetch = callerCtx._callSiteFetch ?? userCtx.fetch ?? callerCtx.fetch + ctx.result = + userCtx.result !== undefined + ? userCtx.result + : userCtx instanceof Response + ? userCtx + : callerCtx.result } - let middlewareFn: MiddlewareFn | undefined = undefined - if (env === 'client') { - if ('client' in nextMiddleware.options) { - middlewareFn = nextMiddleware.options.client as MiddlewareFn | undefined + let result = ctx + // Middleware without a function for this environment only validates. + while (index < flattenedMiddlewares.length) { + const options = flattenedMiddlewares[index++]!.options as { + validator?: AnyValidator + client?: MiddlewareFn + server?: MiddlewareFn + } + const validator = options.validator + if (validator && env === 'server') { + // Execute the middleware's input function + ctx.data = await execValidator(validator, ctx.data) + } + + const middlewareFn = env === 'client' ? options.client : options.server + if (middlewareFn) { + result = await middlewareFn({ + ...ctx, + next: (nextCtx = {} as ServerFnMiddlewareResult) => + callNextMiddleware(ctx, nextCtx), + }) + + if (result instanceof Response) { + // A returned redirect fails the call; any other Response is its + // result. + if (isRedirect(result)) { + throw result + } + result = { ...ctx, result } + } else if (!(result as any)) { + throw new Error( + 'User middleware returned undefined. You must call next() or return a result in your middlewares.', + ) + } + break } } - // env === 'server' - else if ('server' in nextMiddleware.options) { - middlewareFn = nextMiddleware.options.server as MiddlewareFn | undefined + + if ('error' in result) { + throw result.error } - - if (middlewareFn) { - // Execute the middleware - return applyMiddleware(middlewareFn, ctx, async (newCtx) => { - return next(newCtx).catch((error: any) => { - if (isRedirect(error) || isNotFound(error)) { - return { - ...newCtx, - error, - } - } - - throw error - }) - }) - } - - return next(ctx) + return result } // Start the middleware chain - return next({ + const initialCtx = { ...opts, - headers: opts.headers || {}, - sendContext: opts.sendContext || {}, - context: opts.context || {}, - }) + // Client next() results always expose HeadersInit. Server middleware does + // not require a headers value unless one was explicitly supplied. + headers: opts.headers || (env === 'client' ? {} : undefined), + sendContext: opts.sendContext, + context: opts.context || createNullProtoObject(), + _callSiteFetch: opts.fetch, + } + if (initialCtx.sendContext !== undefined) { + initialCtx.sendContext ||= {} + } + try { + return await callNextMiddleware(initialCtx) + } catch (error) { + return { ...initialCtx, error } + } } export type CompiledFetcherFnOptions = { @@ -243,6 +363,7 @@ export type CompiledFetcherFnOptions = { data: unknown headers?: HeadersInit signal?: AbortSignal + fetch?: CustomFetch context?: any } @@ -254,41 +375,60 @@ export type Fetcher = export interface FetcherBase { [TSS_SERVER_FUNCTION]: true url: string + method: Method __executeServer: (opts: { method: Method data: unknown headers?: HeadersInit context?: any - signal: AbortSignal }) => Promise } -export interface OptionalFetcher - extends FetcherBase { +export interface OptionalFetcher< + TMiddlewares, + TInputValidator, + TResponse, +> extends FetcherBase { ( options?: OptionalFetcherDataOptions, ): Promise> } -export interface RequiredFetcher - extends FetcherBase { +export interface RequiredFetcher< + TMiddlewares, + TInputValidator, + TResponse, +> extends FetcherBase { ( opts: RequiredFetcherDataOptions, ): Promise> } +// Ideally, this type should just be `export type CustomFetch = typeof globalThis.fetch`, but that conflicts with the type overrides the `bun-types` package - a dependency of unplugin. +// Relevant bun issues: +// - https://github.com/oven-sh/bun/issues/23500 +// - https://github.com/oven-sh/bun/issues/23741 +export type CustomFetch = typeof fetch extends (...args: infer A) => infer R + ? (...args: A) => R + : never + export type FetcherBaseOptions = { headers?: HeadersInit signal?: AbortSignal + fetch?: CustomFetch } -export interface OptionalFetcherDataOptions - extends FetcherBaseOptions { +export interface OptionalFetcherDataOptions< + TMiddlewares, + TInputValidator, +> extends FetcherBaseOptions { data?: Expand> } -export interface RequiredFetcherDataOptions - extends FetcherBaseOptions { +export interface RequiredFetcherDataOptions< + TMiddlewares, + TInputValidator, +> extends FetcherBaseOptions { data: Expand> } @@ -298,12 +438,18 @@ export type RscStream = { export type Method = 'GET' | 'POST' -export type ServerFnReturnType = - TResponse extends PromiseLike - ? Promise> - : TResponse extends Response - ? TResponse - : ValidateSerializableInput +export type ServerFnReturnType< + TRegister, + TResponse, + TStrict extends ServerFnStrict = true, +> = + ServerFnStrictOutput extends false + ? TResponse + : TResponse extends PromiseLike + ? Promise> + : TResponse extends Response + ? TResponse + : ValidateSerializableInput export type ServerFn< TRegister, @@ -311,14 +457,21 @@ export type ServerFn< TMiddlewares, TInputValidator, TResponse, + TStrict extends ServerFnStrict = true, > = ( - ctx: ServerFnCtx, -) => ServerFnReturnType + ctx: ServerFnCtx, +) => ServerFnReturnType -export interface ServerFnCtx { +export interface ServerFnCtx< + TRegister, + TMethod, + TMiddlewares, + TInputValidator, +> { data: Expand> + serverFnMeta: ServerFnMeta context: Expand> - signal: AbortSignal + method: TMethod } export type CompiledFetcherFn = { @@ -326,6 +479,7 @@ export type CompiledFetcherFn = { opts: CompiledFetcherFnOptions & ServerFnBaseOptions, ): Promise url: string + serverFnMeta: ServerFnMeta } export type ServerFnBaseOptions< @@ -334,49 +488,57 @@ export type ServerFnBaseOptions< TResponse = unknown, TMiddlewares = unknown, TInputValidator = unknown, + TStrict extends ServerFnStrict = true, > = { method: TMethod + strict?: TStrict middleware?: Constrain< TMiddlewares, ReadonlyArray > - inputValidator?: ConstrainValidator + validator?: ConstrainValidator extractedFn?: CompiledFetcherFn serverFn?: ServerFn< TRegister, TMethod, TMiddlewares, TInputValidator, - TResponse + TResponse, + TStrict > - functionId: string } export type ValidateValidatorInput< TRegister, TMethod extends Method, TInputValidator, -> = TMethod extends 'POST' - ? ResolveValidatorInput extends FormData + TStrict extends ServerFnStrict = true, +> = + ServerFnStrictInput extends false ? ResolveValidatorInput - : ValidateSerializable< - ResolveValidatorInput, - RegisteredSerializableInput - > - : ValidateSerializable< - ResolveValidatorInput, - RegisteredSerializableInput - > + : TMethod extends 'POST' + ? ResolveValidatorInput extends FormData + ? ResolveValidatorInput + : ValidateSerializable< + ResolveValidatorInput, + RegisteredSerializableInput + > + : ValidateSerializable< + ResolveValidatorInput, + RegisteredSerializableInput + > export type ValidateValidator< TRegister, TMethod extends Method, TInputValidator, + TStrict extends ServerFnStrict = true, > = ValidateValidatorInput< TRegister, TMethod, - TInputValidator + TInputValidator, + TStrict > extends infer TInput ? Validator : never @@ -385,17 +547,19 @@ export type ConstrainValidator< TRegister, TMethod extends Method, TInputValidator, + TStrict extends ServerFnStrict = true, > = | (unknown extends TInputValidator ? TInputValidator : ResolveValidatorInput extends ValidateValidator< TRegister, TMethod, - TInputValidator + TInputValidator, + TStrict > ? TInputValidator : never) - | ValidateValidator + | ValidateValidator export type AppendMiddlewares = TMiddlewares extends ReadonlyArray @@ -409,6 +573,7 @@ export interface ServerFnMiddleware< TMethod extends Method, TMiddlewares, TInputValidator, + TStrict extends ServerFnStrict, > { middleware: ( middlewares: Constrain< @@ -419,7 +584,8 @@ export interface ServerFnMiddleware< TRegister, TMethod, AppendMiddlewares, - TInputValidator + TInputValidator, + TStrict > } @@ -428,38 +594,62 @@ export interface ServerFnAfterMiddleware< TMethod extends Method, TMiddlewares, TInputValidator, -> extends ServerFnWithTypes< + TStrict extends ServerFnStrict, +> + extends + ServerFnWithTypes< TRegister, TMethod, TMiddlewares, TInputValidator, - undefined + undefined, + TStrict >, - ServerFnMiddleware, - ServerFnValidator, - ServerFnHandler { - (options?: { - method?: TNewMethod - }): ServerFnAfterMiddleware< + ServerFnMiddleware, + ServerFnValidator, + ServerFnHandler< + TRegister, + TMethod, + TMiddlewares, + TInputValidator, + TStrict + > { + < + TNewMethod extends Method = TMethod, + TNewStrict extends ServerFnStrict = TStrict, + >( + options?: ServerFnOptions, + ): ServerFnAfterMiddleware< TRegister, TNewMethod, TMiddlewares, - TInputValidator + TInputValidator, + TNewStrict > } -export type ValidatorFn = < +export type ValidatorFn< + TRegister, + TMethod extends Method, + TMiddlewares, + TStrict extends ServerFnStrict, +> = ( + validator: ConstrainValidator, +) => ServerFnAfterValidator< + TRegister, + TMethod, + TMiddlewares, TInputValidator, ->( - inputValidator: ConstrainValidator, -) => ServerFnAfterValidator + TStrict +> export interface ServerFnValidator< TRegister, TMethod extends Method, TMiddlewares, + TStrict extends ServerFnStrict, > { - inputValidator: ValidatorFn + validator: ValidatorFn } export interface ServerFnAfterValidator< @@ -467,29 +657,55 @@ export interface ServerFnAfterValidator< TMethod extends Method, TMiddlewares, TInputValidator, -> extends ServerFnWithTypes< + TStrict extends ServerFnStrict, +> + extends + ServerFnWithTypes< TRegister, TMethod, TMiddlewares, TInputValidator, - undefined + undefined, + TStrict >, - ServerFnMiddleware, - ServerFnHandler {} + ServerFnMiddleware< + TRegister, + TMethod, + TMiddlewares, + TInputValidator, + TStrict + >, + ServerFnHandler< + TRegister, + TMethod, + TMiddlewares, + TInputValidator, + TStrict + > {} export interface ServerFnAfterTyper< TRegister, TMethod extends Method, TMiddlewares, TInputValidator, -> extends ServerFnWithTypes< + TStrict extends ServerFnStrict, +> + extends + ServerFnWithTypes< TRegister, TMethod, TMiddlewares, TInputValidator, - undefined + undefined, + TStrict >, - ServerFnHandler {} + ServerFnHandler< + TRegister, + TMethod, + TMiddlewares, + TInputValidator, + TStrict + > {} // Handler export interface ServerFnHandler< @@ -497,6 +713,7 @@ export interface ServerFnHandler< TMethod extends Method, TMiddlewares, TInputValidator, + TStrict extends ServerFnStrict, > { handler: ( fn?: ServerFn< @@ -504,28 +721,42 @@ export interface ServerFnHandler< TMethod, TMiddlewares, TInputValidator, - TNewResponse + TNewResponse, + TStrict >, ) => Fetcher } -export interface ServerFnBuilder - extends ServerFnWithTypes< +export interface ServerFnBuilder< + TRegister, + TMethod extends Method = 'GET', + TStrict extends ServerFnStrict = true, +> + extends + ServerFnWithTypes< TRegister, TMethod, undefined, undefined, - undefined + undefined, + TStrict >, - ServerFnMiddleware, - ServerFnValidator, - ServerFnHandler { + ServerFnMiddleware, + ServerFnValidator, + ServerFnHandler { + < + TNewMethod extends Method = TMethod, + TNewStrict extends ServerFnStrict = TStrict, + >( + options?: ServerFnOptions, + ): ServerFnBuilder options: ServerFnBaseOptions< TRegister, TMethod, unknown, undefined, - undefined + undefined, + TStrict > } @@ -535,25 +766,28 @@ export interface ServerFnWithTypes< in out TMiddlewares, in out TInputValidator, in out TResponse, + in out TStrict extends ServerFnStrict, > { '~types': ServerFnTypes< TRegister, TMethod, TMiddlewares, TInputValidator, - TResponse + TResponse, + TStrict > options: ServerFnBaseOptions< TRegister, TMethod, unknown, undefined, - undefined + undefined, + TStrict > [TSS_SERVER_FUNCTION_FACTORY]: true } -export type AnyServerFn = ServerFnWithTypes +export type AnyServerFn = ServerFnWithTypes export interface ServerFnTypes< in out TRegister, @@ -561,28 +795,38 @@ export interface ServerFnTypes< in out TMiddlewares, in out TInputValidator, in out TResponse, + in out TStrict extends ServerFnStrict, > { method: TMethod + strict: TStrict middlewares: TMiddlewares - inputValidator: TInputValidator + validator: TInputValidator response: TResponse allServerContext: AssignAllServerFnContext allInput: IntersectAllValidatorInputs allOutput: IntersectAllValidatorOutputs } -export function flattenMiddlewares( - middlewares: Array, -): Array { - const seen = new Set() - const flattened: Array = [] +export function flattenMiddlewares< + T extends AnyFunctionMiddleware | AnyRequestMiddleware, +>( + middlewares: Array, + maxDepth: number = 100, + seen: Set = new Set(), +): Array { + const flattened: Array = [] - const recurse = ( - middleware: Array, - ) => { + // forEach skips holes, and a list that is not an array throws instead of + // silently dropping its middleware. + const recurse = (middleware: Array, depth: number) => { + if (depth > maxDepth) { + throw new Error( + `Middleware nesting depth exceeded maximum of ${maxDepth}. Check for circular references.`, + ) + } middleware.forEach((m) => { if (m.options.middleware) { - recurse(m.options.middleware) + recurse(m.options.middleware as Array, depth + 1) } if (!seen.has(m)) { @@ -592,7 +836,7 @@ export function flattenMiddlewares( }) } - recurse(middlewares) + recurse(middlewares, 0) return flattened } @@ -604,11 +848,15 @@ export type ServerFnMiddlewareOptions = { signal?: AbortSignal sendContext?: any context?: any - functionId: string + serverFnMeta: ClientFnMeta + fetch?: CustomFetch + /** @internal - Preserves the call-site fetch to ensure it has highest priority over middleware */ + _callSiteFetch?: CustomFetch } export type ServerFnMiddlewareResult = ServerFnMiddlewareOptions & { result?: unknown + /** Present only when the call failed. Holds the thrown value, even `undefined`. */ error?: unknown } @@ -622,52 +870,14 @@ export type MiddlewareFn = ( }, ) => Promise -export const applyMiddleware = async ( - middlewareFn: MiddlewareFn, - ctx: ServerFnMiddlewareOptions, - nextFn: NextFn, -) => { - return middlewareFn({ - ...ctx, - next: (async ( - userCtx: ServerFnMiddlewareResult | undefined = {} as any, - ) => { - // Return the next middleware - return nextFn({ - ...ctx, - ...userCtx, - context: { - ...ctx.context, - ...userCtx.context, - }, - sendContext: { - ...ctx.sendContext, - ...(userCtx.sendContext ?? {}), - }, - headers: mergeHeaders(ctx.headers, userCtx.headers), - result: - userCtx.result !== undefined - ? userCtx.result - : userCtx instanceof Response - ? userCtx - : (ctx as any).result, - error: userCtx.error ?? (ctx as any).error, - }) - }) as any, - } as any) -} - -export function execValidator( +export async function execValidator( validator: AnyValidator, input: unknown, -): unknown { +): Promise { if (validator == null) return {} if ('~standard' in validator) { - const result = validator['~standard'].validate(input) - - if (result instanceof Promise) - throw new Error('Async validation not supported') + const result = await validator['~standard'].validate(input) if (result.issues) throw new Error(JSON.stringify(result.issues, undefined, 2)) @@ -692,39 +902,33 @@ function serverFnBaseToMiddleware( return { '~types': undefined!, options: { - inputValidator: options.inputValidator, - client: async ({ next, sendContext, ...ctx }) => { + validator: options.validator, + client: async ({ next, sendContext, fetch, ...ctx }) => { const payload = { ...ctx, // switch the sendContext over to context context: sendContext, - } as any + fetch, + } // Execute the extracted function // but not before serializing the context const res = await options.extractedFn?.(payload) - return next(res) as unknown as FunctionMiddlewareClientFnResult< - any, - any, - any - > + return next(res) }, - server: async ({ next, ...ctx }) => { - // Execute the server function - const result = await options.serverFn?.(ctx as TODO) + // Always the last middleware, so it returns the result instead of + // passing it through next(). Browsers never execute a server function. + server: + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- isServer is only known outside development + (isServer ?? typeof window === 'undefined') + ? async ({ next: _next, ...ctx }) => { + // Execute the server function + const result = await options.serverFn?.(ctx) - return next({ - ...ctx, - result, - } as any) as unknown as FunctionMiddlewareServerFnResult< - any, - any, - any, - any, - any - > - }, + return { ...ctx, result } as any + } + : undefined, }, } } diff --git a/packages/start-client-core/src/createStart.ts b/packages/start-client-core/src/createStart.ts index 7fc0ddba87..0929bc3b31 100644 --- a/packages/start-client-core/src/createStart.ts +++ b/packages/start-client-core/src/createStart.ts @@ -1,3 +1,4 @@ +import { isPromise } from '@tanstack/router-core' import { createMiddleware } from './createMiddleware' import type { TSS_SERVER_FUNCTION } from './constants' import type { @@ -5,6 +6,7 @@ import type { AnyRequestMiddleware, CreateMiddlewareFn, } from './createMiddleware' +import type { CustomFetch } from './createServerFn' import type { AnySerializationAdapter, Register, @@ -27,6 +29,25 @@ export interface StartInstanceOptions< defaultSsr?: TDefaultSsr requestMiddleware?: TRequestMiddlewares functionMiddleware?: TFunctionMiddlewares + /** + * Configuration options for server functions. + */ + serverFns?: { + /** + * A custom fetch implementation to use for all server function calls. + * This can be overridden by middleware or at the call site. + * + * Precedence (highest to lowest): + * 1. Call site: `serverFn({ fetch: customFetch })` + * 2. Later middleware: Last middleware in chain that provides `fetch` + * 3. Earlier middleware: First middleware in chain that provides `fetch` + * 4. createStart: `createStart({ serverFns: { fetch: customFetch } })` + * 5. Default: Global `fetch` function + * + * @note Only applies on the client side. During SSR, server functions are called directly. + */ + fetch?: CustomFetch + } } export interface StartInstance< @@ -80,9 +101,23 @@ function dedupeSerializationAdapters( } } +function dedupeOptions< + T extends { serializationAdapters?: ReadonlyArray }, +>(options: T): T { + if (options.serializationAdapters) { + const deduped = new Set() + dedupeSerializationAdapters( + deduped, + options.serializationAdapters as Array, + ) + options.serializationAdapters = Array.from(deduped) + } + return options +} + export const createStart = < - const TSerializationAdapters extends - ReadonlyArray = [], + const TSerializationAdapters extends ReadonlyArray = + [], TDefaultSsr extends SSROption = SSROption, const TRequestMiddlewares extends ReadonlyArray = [], const TFunctionMiddlewares extends ReadonlyArray = [], @@ -115,19 +150,16 @@ export const createStart = < TFunctionMiddlewares > => { return { - getOptions: async () => { - const options = await getOptions() - if (options.serializationAdapters) { - const deduped = new Set() - dedupeSerializationAdapters( - deduped, - options.serializationAdapters as unknown as Array, - ) - options.serializationAdapters = Array.from(deduped) as any - } - return options + // A synchronous factory returns synchronously so callers can skip a + // microtask per request. + getOptions: () => { + const options = getOptions() + // Promise.resolve adopts any thenable and returns a native promise as is. + return isPromise(options) + ? Promise.resolve(options).then(dedupeOptions) + : dedupeOptions(options) }, - createMiddleware: createMiddleware as any, + createMiddleware: createMiddleware, } as StartInstance< TSerializationAdapters, TDefaultSsr, diff --git a/packages/start-client-core/src/empty-plugin-adapters.ts b/packages/start-client-core/src/empty-plugin-adapters.ts new file mode 100644 index 0000000000..579643cb86 --- /dev/null +++ b/packages/start-client-core/src/empty-plugin-adapters.ts @@ -0,0 +1,4 @@ +import type { AnySerializationAdapter } from '@tanstack/router-core' + +export const pluginSerializationAdapters: Array = [] +export const hasPluginAdapters = false diff --git a/packages/start-client-core/src/fake-entries/router.ts b/packages/start-client-core/src/fake-entries/router.ts new file mode 100644 index 0000000000..4fea94521d --- /dev/null +++ b/packages/start-client-core/src/fake-entries/router.ts @@ -0,0 +1 @@ +export function getRouter() {} diff --git a/packages/start-client-core/src/fake-entries/start.ts b/packages/start-client-core/src/fake-entries/start.ts new file mode 100644 index 0000000000..087859454d --- /dev/null +++ b/packages/start-client-core/src/fake-entries/start.ts @@ -0,0 +1 @@ +export const startInstance = undefined diff --git a/packages/start-client-core/src/fake-start-entry.ts b/packages/start-client-core/src/fake-start-entry.ts deleted file mode 100644 index cb81fb0df0..0000000000 --- a/packages/start-client-core/src/fake-start-entry.ts +++ /dev/null @@ -1,2 +0,0 @@ -export const startInstance = undefined -export const getRouter = () => {} diff --git a/packages/start-client-core/src/getDefaultSerovalPlugins.ts b/packages/start-client-core/src/getDefaultSerovalPlugins.ts index 61e48b9d89..3071e9924f 100644 --- a/packages/start-client-core/src/getDefaultSerovalPlugins.ts +++ b/packages/start-client-core/src/getDefaultSerovalPlugins.ts @@ -1,17 +1,27 @@ import { + createDefaultSerovalPlugins, makeSerovalPlugin, - defaultSerovalPlugins as routerDefaultSerovalPlugins, -} from '@tanstack/router-core' +} from '@tanstack/router-core/ssr/client' import { getStartOptions } from './getStartOptions' -import type { AnySerializationAdapter } from '@tanstack/router-core' +import type { AnySerializationAdapter } from '@tanstack/router-core/ssr/client' +import type { Plugin } from 'seroval' -export function getDefaultSerovalPlugins() { - const start = getStartOptions() - const adapters = start?.serializationAdapters as +/** Start's serialization adapters followed by `routerPlugins`. */ +export function getSerovalPlugins( + routerPlugins: Array>, +): Array> { + const adapters = getStartOptions()?.serializationAdapters as | Array | undefined - return [ - ...(adapters?.map(makeSerovalPlugin) ?? []), - ...routerDefaultSerovalPlugins, - ] + return [...(adapters?.map(makeSerovalPlugin) ?? []), ...routerPlugins] +} + +/** + * Plugins for client JSON transport. The optional signal stops RawStream + * pumps when the request is aborted. + */ +export function getDefaultSerovalPlugins( + signal?: AbortSignal, +): Array> { + return getSerovalPlugins(createDefaultSerovalPlugins(signal)) } diff --git a/packages/start-client-core/src/getGlobalStartContext.ts b/packages/start-client-core/src/getGlobalStartContext.ts index 20c1bcd6da..3e1af51361 100644 --- a/packages/start-client-core/src/getGlobalStartContext.ts +++ b/packages/start-client-core/src/getGlobalStartContext.ts @@ -1,5 +1,5 @@ import { getStartContext } from '@tanstack/start-storage-context' -import { createIsomorphicFn } from './createIsomorphicFn' +import { createIsomorphicFn } from '@tanstack/start-fn-stubs' import type { AssignAllServerRequestContext } from './createMiddleware' import type { Expand, Register } from '@tanstack/router-core' diff --git a/packages/start-client-core/src/getRouterInstance.ts b/packages/start-client-core/src/getRouterInstance.ts index 501970ed0b..d1fc9d6301 100644 --- a/packages/start-client-core/src/getRouterInstance.ts +++ b/packages/start-client-core/src/getRouterInstance.ts @@ -1,5 +1,5 @@ import { getStartContext } from '@tanstack/start-storage-context' -import { createIsomorphicFn } from './createIsomorphicFn' +import { createIsomorphicFn } from '@tanstack/start-fn-stubs' import type { Awaitable, RegisteredRouter } from '@tanstack/router-core' export const getRouterInstance: () => Awaitable = diff --git a/packages/start-client-core/src/getStartContextServerOnly.ts b/packages/start-client-core/src/getStartContextServerOnly.ts index 78787a4982..4b1ec43c04 100644 --- a/packages/start-client-core/src/getStartContextServerOnly.ts +++ b/packages/start-client-core/src/getStartContextServerOnly.ts @@ -1,4 +1,4 @@ import { getStartContext } from '@tanstack/start-storage-context' -import { createServerOnlyFn } from './envOnly' +import { createServerOnlyFn } from '@tanstack/start-fn-stubs' export const getStartContextServerOnly = createServerOnlyFn(getStartContext) diff --git a/packages/start-client-core/src/getStartOptions.ts b/packages/start-client-core/src/getStartOptions.ts index 7c08e1f49a..d290934b5f 100644 --- a/packages/start-client-core/src/getStartOptions.ts +++ b/packages/start-client-core/src/getStartOptions.ts @@ -1,5 +1,5 @@ import { getStartContext } from '@tanstack/start-storage-context' -import { createIsomorphicFn } from './createIsomorphicFn' +import { createIsomorphicFn } from '@tanstack/start-fn-stubs' import type { AnyStartInstanceOptions } from './createStart' export const getStartOptions: () => AnyStartInstanceOptions | undefined = diff --git a/packages/start-client-core/src/hydration.ts b/packages/start-client-core/src/hydration.ts new file mode 100644 index 0000000000..934b73116f --- /dev/null +++ b/packages/start-client-core/src/hydration.ts @@ -0,0 +1,50 @@ +import { hydrateIdAttribute } from './hydration/constants' + +export { condition } from './hydration/condition' +export type { HydrationCondition } from './hydration/condition' +export { + hydrateIdAttribute, + hydrateInteractionEventsAttribute, + hydrateWhenAttribute, +} from './hydration/constants' +export const hydrateIdSelector = `[${hydrateIdAttribute}]` +export { idle } from './hydration/idle' +export type { IdleHydrationOptions } from './hydration/idle' +export { interaction } from './hydration/interaction' +export { load } from './hydration/load' +export { media } from './hydration/media' +export { never } from './hydration/never' +export { + clearResolvedGateIdsInMarker, + createResolvedGate, + getFallbackHtml, + getMarkerGate, + getOrCreateGate, + onGateResolve, + releaseGate, + resolveHydrationMarker, + runHydrationStrategyCleanup, + saveFallbackHtml, + waitForHydrationPrefetchStrategy, +} from './hydration/runtime' +export { withHydrationRenderer } from './hydration/renderer' +export { visible } from './hydration/visible' +export { listenForDelegatedHydrationIntent } from './hydration/interaction' +export type { VisibleHydrationOptions } from './hydration/visible' +export type { HydrationGateRecord } from './hydration/runtime' +export type { HydrationStrategyWithRenderer } from './hydration/renderer' +export type { + HydrationInteractionEvent, + HydrationInteractionEvents, + HydrationMarkerAttributes, + HydrationPrefetchContext, + HydrationPrefetchFunction, + HydrationPrefetchWhen, + HydrationPrefetchStrategy, + HydrationPrefetchWaitReason, + HydrationRuntimeContext, + HydrationRuntimeGate, + HydrationStrategy, + HydrationStrategyTypes, + HydrationWhen, +} from './hydration/types' diff --git a/packages/start-client-core/src/hydration/condition.ts b/packages/start-client-core/src/hydration/condition.ts new file mode 100644 index 0000000000..6e640cc3ae --- /dev/null +++ b/packages/start-client-core/src/hydration/condition.ts @@ -0,0 +1,20 @@ +import type { HydrationStrategy } from './types' + +const conditionType = 'condition' + +export type HydrationCondition = boolean | (() => boolean) + +/* @__NO_SIDE_EFFECTS__ */ +export function condition( + condition: HydrationCondition, +): HydrationStrategy { + return { + _t: conditionType, + _d: () => !(typeof condition === 'function' ? condition() : condition), + _s: ({ gate }) => { + if (typeof condition === 'function' ? condition() : condition) { + gate!.resolve() + } + }, + } +} diff --git a/packages/start-client-core/src/hydration/constants.ts b/packages/start-client-core/src/hydration/constants.ts new file mode 100644 index 0000000000..4b7a29313d --- /dev/null +++ b/packages/start-client-core/src/hydration/constants.ts @@ -0,0 +1,4 @@ +export const hydrateIdAttribute = 'data-ts-hydrate-id' +export const hydrateWhenAttribute = 'data-ts-hydrate-when' +export const hydrateInteractionEventsAttribute = + 'data-ts-hydrate-interaction-events' diff --git a/packages/start-client-core/src/hydration/idle.ts b/packages/start-client-core/src/hydration/idle.ts new file mode 100644 index 0000000000..bf0dc71131 --- /dev/null +++ b/packages/start-client-core/src/hydration/idle.ts @@ -0,0 +1,35 @@ +import type { HydrationPrefetchStrategy } from './types' + +const idleType = 'idle' + +export type IdleHydrationOptions = { + timeout?: number +} + +export function idle( + options: IdleHydrationOptions = {}, +): HydrationPrefetchStrategy { + const timeout = options.timeout ?? 2000 + + return { + _t: idleType, + _s: ({ gate, prefetch }) => { + const schedule = globalThis as unknown as { + requestIdleCallback?: ( + callback: IdleRequestCallback, + options?: IdleRequestOptions, + ) => number + cancelIdleCallback?: (handle: number) => void + } + const callback = prefetch ?? gate!.resolve + + if (schedule.requestIdleCallback) { + const handle = schedule.requestIdleCallback(callback, { timeout }) + return () => schedule.cancelIdleCallback?.(handle) + } + + const timeoutId = globalThis.setTimeout(callback, timeout) + return () => globalThis.clearTimeout(timeoutId) + }, + } +} diff --git a/packages/start-client-core/src/hydration/interaction.ts b/packages/start-client-core/src/hydration/interaction.ts new file mode 100644 index 0000000000..d5d6886d36 --- /dev/null +++ b/packages/start-client-core/src/hydration/interaction.ts @@ -0,0 +1,342 @@ +import { + hydrateIdAttribute, + hydrateInteractionEventsAttribute, + hydrateWhenAttribute, +} from './constants' +import { + clearResolvedGateIdsInMarker, + getMarkerGate, + resolveHydrationMarker, +} from './runtime' +import type { + HydrationInteractionEvents, + HydrationPrefetchStrategy, + HydrationRuntimeContext, +} from './types' + +export type InteractionHydrationOptions = { + events?: HydrationInteractionEvents +} + +const hydrateIdSelector = `[${hydrateIdAttribute}]` + +type PendingReplayEvent = { + marker: Element + targetPath: Array + type: string + event: Event +} + +const defaultInteractionEvents = [ + 'pointerenter', + 'focusin', + 'pointerdown', + 'click', +] as const +const supportedInteractionEvents = [ + 'auxclick', + 'click', + 'contextmenu', + 'dblclick', + 'focusin', + 'keydown', + 'keyup', + 'mousedown', + 'mouseenter', + 'mouseover', + 'mouseup', + 'pointerdown', + 'pointerenter', + 'pointerover', + 'pointerup', +] as const +const interactionType = 'interaction' +const dynamicType = 'dynamic' +const interactionHydrateSelector = `[${hydrateWhenAttribute}="${interactionType}"]` +const delegatedHydrateSelector = `${interactionHydrateSelector},[${hydrateWhenAttribute}="${dynamicType}"]` +const replayEventsByGateId = /* @__PURE__ */ new Map< + string, + Array +>() + +function getIntentListenerEvents( + marker: Element, + events: ReadonlyArray, +) { + const listenerEvents = new Set(events) + + marker.querySelectorAll(delegatedHydrateSelector).forEach((childMarker) => { + if (childMarker.getAttribute(hydrateWhenAttribute) === dynamicType) { + supportedInteractionEvents.forEach((eventName) => { + listenerEvents.add(eventName) + }) + return + } + + const attr = childMarker.getAttribute(hydrateInteractionEventsAttribute) + for (const eventName of attr === null + ? defaultInteractionEvents + : attr.split(/\s+/).filter(Boolean)) { + listenerEvents.add(eventName) + } + }) + + return [...listenerEvents] +} + +function queueHydrationReplayEvent(marker: Element, event: Event) { + if (!event.bubbles) return + + const id = marker.getAttribute(hydrateIdAttribute) + const when = marker.getAttribute(hydrateWhenAttribute) + if (!id || !when || when === 'never') return + + const target = event.target + if (!target) return + + const gate = getMarkerGate(marker) + if (gate?.resolved) return + + event.preventDefault() + event.stopPropagation() + event.stopImmediatePropagation() + + let targetPath: Array = [] + if (target instanceof Node && marker.contains(target)) { + let node: Element | null = + target instanceof Element ? target : target.parentElement + + while (node && node !== marker) { + const parent = node.parentElement + if (!parent) { + targetPath = [] + break + } + targetPath.push(Array.prototype.indexOf.call(parent.children, node)) + node = parent + } + targetPath.reverse() + } + + const pendingEvents = replayEventsByGateId.get(id) ?? [] + pendingEvents.push({ + marker, + targetPath, + type: event.type, + event, + }) + replayEventsByGateId.set(id, pendingEvents) +} + +if (typeof document !== 'undefined') { + const onIntent = (event: Event) => { + const target = event.target + if (!(target instanceof Element)) return + + let marker: Element | null = target.closest(hydrateIdSelector) + const markers: Array = [] + let shouldHandle = false + + while (marker) { + markers.push(marker) + + const when = marker.getAttribute(hydrateWhenAttribute) + if (when === dynamicType) { + shouldHandle ||= event.type === 'click' + } else if (when === interactionType) { + const attr = marker.getAttribute(hydrateInteractionEventsAttribute) + const events: ReadonlyArray = + attr === null + ? defaultInteractionEvents + : attr.split(/\s+/).filter(Boolean) + shouldHandle ||= events.includes(event.type) + } + + marker = marker.parentElement?.closest(hydrateIdSelector) ?? null + } + + if (!shouldHandle) return + + markers.reverse() + if (markers.every((marker) => getMarkerGate(marker))) return + + markers.forEach((marker) => { + queueHydrationReplayEvent(marker, event) + resolveHydrationMarker(marker) + }) + } + + supportedInteractionEvents.forEach((eventName) => { + document.addEventListener(eventName, onIntent, true) + }) +} + +function listenForIntent( + element: Element, + events: ReadonlyArray, + context: HydrationRuntimeContext, +) { + const onIntent = (event: Event) => { + const target = event.target + let marker: Element | null + if (target instanceof Element) { + const closestMarker = target.closest(hydrateIdSelector) + marker = + closestMarker && element.contains(closestMarker) + ? closestMarker + : element + } else { + marker = element + } + + const markers: Array = [] + while (marker) { + if (marker.hasAttribute(hydrateIdAttribute)) { + markers.push(marker) + } + if (marker === element) break + marker = marker.parentElement + } + + if (!markers.includes(element)) { + markers.push(element) + } + + markers.reverse() + + if ( + context.delegated && + !markers.some( + (marker) => + marker.getAttribute(hydrateWhenAttribute) === interactionType || + marker.getAttribute(hydrateWhenAttribute) === dynamicType, + ) + ) { + return + } + + markers.forEach((marker) => { + queueHydrationReplayEvent(marker, event) + resolveHydrationMarker(marker) + }) + } + let disposed = false + + events.forEach((eventName) => { + element.addEventListener(eventName, onIntent, true) + }) + + return () => { + if (disposed) return + disposed = true + events.forEach((eventName) => { + element.removeEventListener(eventName, onIntent, true) + }) + } +} + +export function listenForDelegatedHydrationIntent( + element: Element, + context: HydrationRuntimeContext, +) { + const listenerEvents = getIntentListenerEvents(element, []) + if (!listenerEvents.length) return + + const cleanupIntent = listenForIntent(element, listenerEvents, { + ...context, + delegated: true, + }) + return () => { + cleanupIntent() + clearResolvedGateIdsInMarker(element) + } +} + +/* @__NO_SIDE_EFFECTS__ */ +export function interaction( + options: InteractionHydrationOptions = {}, +): HydrationPrefetchStrategy { + let events: ReadonlyArray = defaultInteractionEvents + if (options.events !== undefined) { + const eventList: ReadonlyArray = + typeof options.events === 'string' ? [options.events] : options.events + const normalizedEvents: Array = [] + const seen = new Set() + + for (const eventName of eventList) { + if (!eventName || seen.has(eventName)) continue + seen.add(eventName) + normalizedEvents.push(eventName) + } + + events = normalizedEvents + } + + const eventKey = events.join(' ') + + return { + _t: interactionType, + _s: (context) => { + const element = context.element + if (!element) return + const prefetch = context.prefetch + if (prefetch) { + if (!events.length) return + let disposed = false + + events.forEach((eventName) => { + element.addEventListener(eventName, prefetch, true) + }) + + return () => { + if (disposed) return + disposed = true + events.forEach((eventName) => { + element.removeEventListener(eventName, prefetch, true) + }) + } + } + + const listenerEvents = getIntentListenerEvents(element, events) + const cleanupIntent = listenerEvents.length + ? listenForIntent(element, listenerEvents, context) + : undefined + return () => { + cleanupIntent?.() + clearResolvedGateIdsInMarker(element) + } + }, + _o: (id) => { + globalThis.requestAnimationFrame(() => { + const pendingEvents = replayEventsByGateId.get(id) + if (!pendingEvents?.length) return + + replayEventsByGateId.delete(id) + + for (const pendingEvent of pendingEvents) { + let replayTarget: Element | null = pendingEvent.marker + for (const index of pendingEvent.targetPath) { + replayTarget = replayTarget.children[index] ?? null + if (!replayTarget) break + } + + const event = pendingEvent.event + replayTarget ??= pendingEvent.marker + replayTarget.dispatchEvent( + event instanceof MouseEvent + ? new MouseEvent(event.type, event) + : event instanceof FocusEvent + ? new FocusEvent(event.type, event) + : new Event(event.type, event), + ) + } + }) + }, + _a: () => + options.events === undefined + ? undefined + : { + [hydrateInteractionEventsAttribute]: eventKey, + }, + } +} diff --git a/packages/start-client-core/src/hydration/load.ts b/packages/start-client-core/src/hydration/load.ts new file mode 100644 index 0000000000..b78d6d6a42 --- /dev/null +++ b/packages/start-client-core/src/hydration/load.ts @@ -0,0 +1,16 @@ +import type { HydrationPrefetchStrategy } from './types' + +const loadType = 'load' + +const loadStrategy: HydrationPrefetchStrategy = { + _t: loadType, + _d: () => false, + _s: ({ gate, prefetch }) => { + ;(prefetch ?? gate!.resolve)() + }, +} + +/* @__NO_SIDE_EFFECTS__ */ +export function load(): HydrationPrefetchStrategy { + return loadStrategy +} diff --git a/packages/start-client-core/src/hydration/media.ts b/packages/start-client-core/src/hydration/media.ts new file mode 100644 index 0000000000..c2335b7e2f --- /dev/null +++ b/packages/start-client-core/src/hydration/media.ts @@ -0,0 +1,25 @@ +import type { HydrationPrefetchStrategy } from './types' + +const mediaType = 'media' + +/* @__NO_SIDE_EFFECTS__ */ +export function media( + query: string, +): HydrationPrefetchStrategy { + return { + _t: mediaType, + _s: ({ gate, prefetch }) => { + if (!query) return + + const callback = prefetch ?? gate!.resolve + const mediaQuery = window.matchMedia(query) + const onChange = () => { + if (mediaQuery.matches) callback() + } + mediaQuery.addEventListener('change', onChange) + onChange() + + return () => mediaQuery.removeEventListener('change', onChange) + }, + } +} diff --git a/packages/start-client-core/src/hydration/never.ts b/packages/start-client-core/src/hydration/never.ts new file mode 100644 index 0000000000..8ace129b5e --- /dev/null +++ b/packages/start-client-core/src/hydration/never.ts @@ -0,0 +1,13 @@ +import type { HydrationStrategy } from './types' + +const neverType = 'never' + +const neverStrategy: HydrationStrategy = { + _t: neverType, + _d: () => true, +} + +/* @__NO_SIDE_EFFECTS__ */ +export function never(): HydrationStrategy { + return neverStrategy +} diff --git a/packages/start-client-core/src/hydration/renderer.ts b/packages/start-client-core/src/hydration/renderer.ts new file mode 100644 index 0000000000..1a14ef9b46 --- /dev/null +++ b/packages/start-client-core/src/hydration/renderer.ts @@ -0,0 +1,21 @@ +import type { HydrationStrategy } from './types' + +export type HydrationStrategyWithRenderer< + TStrategy extends HydrationStrategy, + TRenderer, +> = TStrategy & { + _h: TRenderer +} + +/* @__NO_SIDE_EFFECTS__ */ +export function withHydrationRenderer< + TStrategy extends HydrationStrategy, + TRenderer, +>( + strategy: TStrategy, + renderer: TRenderer, +): HydrationStrategyWithRenderer { + return /* @__PURE__ */ Object.assign(strategy, { + _h: renderer, + }) +} diff --git a/packages/start-client-core/src/hydration/runtime.ts b/packages/start-client-core/src/hydration/runtime.ts new file mode 100644 index 0000000000..307487c4f9 --- /dev/null +++ b/packages/start-client-core/src/hydration/runtime.ts @@ -0,0 +1,193 @@ +import { hydrateIdAttribute, hydrateWhenAttribute } from './constants' +import type { + HydrationPrefetchStrategy, + HydrationPrefetchWaitReason, + HydrationRuntimeGate, + HydrationWhen, +} from './types' + +const hydrateIdSelector = `[${hydrateIdAttribute}]` + +export type HydrationGateRecord = HydrationRuntimeGate & { + id: string + when: HydrationWhen + promise: Promise + consumers: number + resolveListeners: Set<() => void> +} + +const gateRegistry = /* @__PURE__ */ new Map() +const resolvedGateIds = /* @__PURE__ */ new Set() +const fallbackHtmlByGateId = /* @__PURE__ */ new Map() + +export function createResolvedGate( + id: string, + when: HydrationWhen, +): HydrationGateRecord { + return { + id, + when, + promise: Promise.resolve(), + resolve: () => {}, + resolved: true, + consumers: 0, + resolveListeners: new Set<() => void>(), + } +} + +export function getOrCreateGate( + id: string, + when: HydrationWhen, +): HydrationGateRecord { + const existing = gateRegistry.get(id) + if (existing?.when === when) { + existing.consumers++ + return existing + } + + let resolvePromise!: () => void + const promise = new Promise((resolve) => { + resolvePromise = resolve + }) + + const gate: HydrationGateRecord = { + id, + promise, + resolved: false, + consumers: 1, + when, + resolveListeners: new Set(), + resolve: () => { + if (gate.resolved) return + gate.resolved = true + resolvePromise() + gate.resolveListeners.forEach((listener) => listener()) + gate.resolveListeners.clear() + }, + } + + gateRegistry.set(id, gate) + if (when !== 'never' && resolvedGateIds.has(id)) { + resolvedGateIds.delete(id) + gate.resolve() + } + return gate +} + +export function releaseGate(gate: HydrationGateRecord) { + resolvedGateIds.delete(gate.id) + gate.consumers-- + if (gate.consumers > 0) return + if (gateRegistry.get(gate.id) === gate) { + gateRegistry.delete(gate.id) + fallbackHtmlByGateId.delete(gate.id) + gate.resolveListeners.clear() + } +} + +export function onGateResolve(gate: HydrationGateRecord, listener: () => void) { + if (gate.resolved) { + listener() + return () => {} + } + + gate.resolveListeners.add(listener) + return () => { + gate.resolveListeners.delete(listener) + } +} + +export function runHydrationStrategyCleanup(cleanup: void | (() => void)) { + if (typeof cleanup === 'function') return cleanup + return undefined +} + +export function waitForHydrationPrefetchStrategy( + strategy: HydrationPrefetchStrategy, + options: { + element: Element | null + signal: AbortSignal + onHydrate: (listener: () => void) => () => void + }, +): Promise { + if (options.signal.aborted) { + return Promise.resolve('abort') + } + + return new Promise((resolve) => { + let disposed = false + // The strategy may finish synchronously before returning its cleanup. + let cleanupStrategy: void | (() => void) = undefined + let cleanupHydrate = () => {} + + const finish = (reason: HydrationPrefetchWaitReason) => { + if (disposed) { + return + } + disposed = true + options.signal.removeEventListener('abort', onAbort) + cleanupHydrate() + runHydrationStrategyCleanup(cleanupStrategy)?.() + resolve(reason) + } + + const onAbort = () => finish('abort') + + options.signal.addEventListener('abort', onAbort, { once: true }) + cleanupHydrate = options.onHydrate(() => finish('hydrate')) + cleanupStrategy = strategy._s?.({ + element: options.element, + prefetch: () => finish('prefetch'), + }) + // A synchronous finish must immediately run the cleanup just returned. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (disposed) { + runHydrationStrategyCleanup(cleanupStrategy)?.() + } + }) +} + +export function getMarkerGate(marker: Element) { + const id = marker.getAttribute(hydrateIdAttribute) + return id ? gateRegistry.get(id) : undefined +} + +export function resolveHydrationMarker(marker: Element) { + const id = marker.getAttribute(hydrateIdAttribute) + const when = marker.getAttribute(hydrateWhenAttribute) + if (!id || !when || when === 'never') { + return + } + + const gate = gateRegistry.get(id) + if (gate) { + if (gate.when !== 'never') gate.resolve() + return + } + + resolvedGateIds.add(id) +} + +export function clearResolvedGateIdsInMarker(marker: Element) { + const ownId = marker.getAttribute(hydrateIdAttribute) + if (ownId) { + resolvedGateIds.delete(ownId) + } + + marker.querySelectorAll(hydrateIdSelector).forEach((childMarker) => { + const childId = childMarker.getAttribute(hydrateIdAttribute) + if (childId) { + resolvedGateIds.delete(childId) + } + }) +} + +export function saveFallbackHtml(id: string, element: Element) { + if (!fallbackHtmlByGateId.has(id)) { + fallbackHtmlByGateId.set(id, element.innerHTML) + } +} + +export function getFallbackHtml(id: string) { + return fallbackHtmlByGateId.get(id) +} diff --git a/packages/start-client-core/src/hydration/types.ts b/packages/start-client-core/src/hydration/types.ts new file mode 100644 index 0000000000..f4250067d6 --- /dev/null +++ b/packages/start-client-core/src/hydration/types.ts @@ -0,0 +1,90 @@ +export type HydrationWhen = + | 'load' + | 'idle' + | 'visible' + | 'media' + | 'interaction' + | 'condition' + | 'never' + | 'dynamic' + +export type HydrationInteractionEvent = + | 'auxclick' + | 'click' + | 'contextmenu' + | 'dblclick' + | 'focusin' + | 'keydown' + | 'keyup' + | 'mousedown' + | 'mouseenter' + | 'mouseover' + | 'mouseup' + | 'pointerdown' + | 'pointerenter' + | 'pointerover' + | 'pointerup' + +export type HydrationInteractionEvents = + | HydrationInteractionEvent + | ReadonlyArray + +export type HydrationMarkerAttributes = Record + +export type HydrationRuntimeGate = { + id?: string + when?: HydrationWhen + resolved: boolean + resolve: () => void +} + +export type HydrationRuntimeContext = { + element: Element | null + gate?: HydrationRuntimeGate + prefetch?: () => void + delegated?: boolean +} + +export type HydrationStrategyTypes< + TWhen extends HydrationWhen = HydrationWhen, + TCanPrefetch extends boolean = boolean, +> = { + when: TWhen + canPrefetch: TCanPrefetch +} + +export type HydrationStrategy< + TWhen extends HydrationWhen = HydrationWhen, + TCanPrefetch extends boolean = boolean, +> = { + _t?: TWhen + readonly '~types'?: HydrationStrategyTypes + _d?: () => boolean + _s?: (context: HydrationRuntimeContext) => void | (() => void) + _o?: (id: string) => void + _a?: () => HydrationMarkerAttributes | undefined +} + +export type HydrationPrefetchWhen = Exclude< + HydrationWhen, + 'condition' | 'never' | 'dynamic' +> + +export type HydrationPrefetchStrategy< + TWhen extends HydrationPrefetchWhen = HydrationPrefetchWhen, +> = HydrationStrategy + +export type HydrationPrefetchWaitReason = 'prefetch' | 'hydrate' | 'abort' + +export type HydrationPrefetchContext = { + element: Element | null + signal: AbortSignal + preload: () => Promise + waitFor: ( + strategy: HydrationPrefetchStrategy, + ) => Promise +} + +export type HydrationPrefetchFunction = ( + context: HydrationPrefetchContext, +) => void | Promise diff --git a/packages/start-client-core/src/hydration/visible.ts b/packages/start-client-core/src/hydration/visible.ts new file mode 100644 index 0000000000..27855c6d68 --- /dev/null +++ b/packages/start-client-core/src/hydration/visible.ts @@ -0,0 +1,97 @@ +import type { HydrationPrefetchStrategy } from './types' + +const visibleType = 'visible' + +export type VisibleHydrationOptions = { + rootMargin?: string + threshold?: number | Array +} + +type VisibleObserverEntry = [ + observer: IntersectionObserver, + elements: Map void>>, +] + +const observerRegistry = /* @__PURE__ */ new Map() + +function cleanupVisibleObserverEntry( + key: string, + observer: IntersectionObserver, + elements: Map void>>, +) { + if (elements.size > 0) { + return + } + observer.disconnect() + observerRegistry.delete(key) +} + +/* @__NO_SIDE_EFFECTS__ */ +export function visible( + options: VisibleHydrationOptions = {}, +): HydrationPrefetchStrategy { + const rootMargin = options.rootMargin ?? '600px' + const threshold = options.threshold ?? 0 + + return { + _t: visibleType, + _s: ({ element, gate, prefetch }) => { + const callback = prefetch ?? gate!.resolve + + if (!element) { + callback() + return + } + + const key = `${rootMargin}|${ + Array.isArray(threshold) ? threshold.join(',') : String(threshold) + }` + let observerEntry = observerRegistry.get(key) + + if (!observerEntry) { + const elements = new Map void>>() + const observer = new IntersectionObserver( + (entries) => { + for (const intersectingEntry of entries) { + if (!intersectingEntry.isIntersecting) { + continue + } + + const callbacks = elements.get(intersectingEntry.target) + if (!callbacks) { + continue + } + + callbacks.forEach((callback) => callback()) + elements.delete(intersectingEntry.target) + observer.unobserve(intersectingEntry.target) + cleanupVisibleObserverEntry(key, observer, elements) + } + }, + { rootMargin, threshold }, + ) + observerEntry = [observer, elements] + observerRegistry.set(key, observerEntry) + } + + const [observer, elements] = observerEntry + let callbacks = elements.get(element) + if (!callbacks) { + callbacks = new Set() + elements.set(element, callbacks) + observer.observe(element) + } + callbacks.add(callback) + + return () => { + const currentCallbacks = elements.get(element) + currentCallbacks?.delete(callback) + if (currentCallbacks?.size === 0) { + elements.delete(element) + observer.unobserve(element) + } + cleanupVisibleObserverEntry(key, observer, elements) + } + }, + } +} diff --git a/packages/start-client-core/src/index.tsx b/packages/start-client-core/src/index.tsx index 015ef25987..e9a8b92d85 100644 --- a/packages/start-client-core/src/index.tsx +++ b/packages/start-client-core/src/index.tsx @@ -1,15 +1,24 @@ export type { JsonResponse } from '@tanstack/router-core/ssr/client' -export { hydrate, json, mergeHeaders } from '@tanstack/router-core/ssr/client' +export { + defaultSerovalDeserializerPlugins, + hydrate, + json, + mergeHeaders, +} from '@tanstack/router-core/ssr/client' + +export { RawStream } from '@tanstack/router-core' +export type { OnRawStreamCallback } from '@tanstack/router-core' export { createIsomorphicFn, + createServerOnlyFn, + createClientOnlyFn, type IsomorphicFn, type ServerOnlyFn, type ClientOnlyFn, type IsomorphicFnBase, -} from './createIsomorphicFn' -export { createServerOnlyFn, createClientOnlyFn } from './envOnly' +} from '@tanstack/start-fn-stubs' export { createServerFn } from './createServerFn' export { createMiddleware, @@ -55,11 +64,16 @@ export { export type { CompiledFetcherFnOptions, CompiledFetcherFn, + CustomFetch, Fetcher, RscStream, FetcherBaseOptions, ServerFn, ServerFnCtx, + ServerFnOptions, + ServerFnStrict, + ServerFnStrictInput, + ServerFnStrictOutput, MiddlewareFn, ServerFnMiddlewareOptions, ServerFnMiddlewareResult, @@ -71,18 +85,34 @@ export type { RequiredFetcher, } from './createServerFn' export { - applyMiddleware, execValidator, flattenMiddlewares, executeMiddleware, } from './createServerFn' +export { + createCsrfMiddleware, + csrfSymbol, + getCsrfRequestValidationResult, + isCsrfRequestAllowed, +} from './createCsrfMiddleware' +export type { + CsrfMatcher, + CsrfMiddlewareOptions, + CsrfSecFetchSite, +} from './createCsrfMiddleware' export { TSS_FORMDATA_CONTEXT, TSS_SERVER_FUNCTION, + TSS_CONTENT_TYPE_FRAMED, + TSS_CONTENT_TYPE_FRAMED_VERSIONED, + TSS_FRAMED_PROTOCOL_VERSION, + FRAME_HEADER_SIZE, X_TSS_SERIALIZED, X_TSS_RAW_RESPONSE, + X_TSS_CONTEXT, } from './constants' +export type { ClientFnMeta, ServerFnMeta } from './constants' export type * from './serverRoute' @@ -93,9 +123,15 @@ export type { AnyStartInstance, AnyStartInstanceOptions, StartInstance, + StartInstanceOptions, } from './createStart' export type { Register } from '@tanstack/router-core' export { getRouterInstance } from './getRouterInstance' -export { getDefaultSerovalPlugins } from './getDefaultSerovalPlugins' +export { + getDefaultSerovalPlugins, + getSerovalPlugins, +} from './getDefaultSerovalPlugins' export { getGlobalStartContext } from './getGlobalStartContext' +export { safeObjectMerge, createNullProtoObject } from './safeObjectMerge' +export { trackPostProcessPromise } from './client-rpc/serverFnFetcher' diff --git a/packages/start-client-core/src/safeObjectMerge.ts b/packages/start-client-core/src/safeObjectMerge.ts new file mode 100644 index 0000000000..133a104324 --- /dev/null +++ b/packages/start-client-core/src/safeObjectMerge.ts @@ -0,0 +1,46 @@ +/* eslint-disable @typescript-eslint/prefer-for-of -- indexed loops avoid the iterator protocol on every merge */ +function isSafeKey(key: string): boolean { + return key !== '__proto__' && key !== 'constructor' && key !== 'prototype' +} + +/** + * Merge target and source into a new null-proto object, filtering dangerous keys. + */ +export function safeObjectMerge>( + target: T | undefined, + source: Record | null | undefined, +): T { + const result: Record = Object.create(null) + if (target) { + const keys = Object.keys(target) + for (let i = 0; i < keys.length; i++) { + const key = keys[i]! + if (isSafeKey(key)) { + result[key] = target[key] + } + } + } + if (source && typeof source === 'object') { + const keys = Object.keys(source) + for (let i = 0; i < keys.length; i++) { + const key = keys[i]! + if (isSafeKey(key)) { + result[key] = source[key] + } + } + } + return result as T +} + +/** + * Create a null-prototype object, optionally copying from source. + */ +export function createNullProtoObject( + source?: T, +): { [K in keyof T]: T[K] } { + return ( + source + ? safeObjectMerge(source as Record, undefined) + : Object.create(null) + ) as { [K in keyof T]: T[K] } +} diff --git a/packages/start-client-core/src/serverRoute.ts b/packages/start-client-core/src/serverRoute.ts index 17c129aa3a..511412683e 100644 --- a/packages/start-client-core/src/serverRoute.ts +++ b/packages/start-client-core/src/serverRoute.ts @@ -80,6 +80,7 @@ declare module '@tanstack/router-core' { in out TParams, in out TRouterContext, in out TRouteContextFn, + in out TRouteId, in out TServerMiddlewares, in out THandlers, > { diff --git a/packages/start-client-core/src/start-entry.d.ts b/packages/start-client-core/src/start-entry.d.ts index ceb8c96aa7..9fb8e08638 100644 --- a/packages/start-client-core/src/start-entry.d.ts +++ b/packages/start-client-core/src/start-entry.d.ts @@ -1,11 +1,18 @@ declare module '#tanstack-start-entry' { - import type { StartEntry } from '@tanstack/start-client-core' + import type { StartEntry } from './startEntry' export const startInstance: StartEntry['startInstance'] } declare module '#tanstack-router-entry' { - import type { RouterEntry } from '@tanstack/start-client-core' + import type { RouterEntry } from './startEntry' export const getRouter: RouterEntry['getRouter'] } + +declare module '#tanstack-start-plugin-adapters' { + import type { AnySerializationAdapter } from '@tanstack/router-core' + + export const pluginSerializationAdapters: Array + export const hasPluginAdapters: boolean +} diff --git a/packages/start-client-core/src/tests/createServerFn.test-d.ts b/packages/start-client-core/src/tests/createServerFn.test-d.ts index 9d2f74b538..f4defe813e 100644 --- a/packages/start-client-core/src/tests/createServerFn.test-d.ts +++ b/packages/start-client-core/src/tests/createServerFn.test-d.ts @@ -2,39 +2,46 @@ import { describe, expectTypeOf, test } from 'vitest' import { createMiddleware } from '../createMiddleware' import { createServerFn } from '../createServerFn' import { TSS_SERVER_FUNCTION } from '../constants' +import type { ServerFnMeta } from '../constants' import type { Constrain, Register, + SerializationError, TsrSerializable, ValidateSerializableInput, Validator, } from '@tanstack/router-core' -import type { ConstrainValidator, ServerFnReturnType } from '../createServerFn' +import type { + ConstrainValidator, + CustomFetch, + ServerFnReturnType, +} from '../createServerFn' test('createServerFn without middleware', () => { expectTypeOf(createServerFn()).toHaveProperty('handler') expectTypeOf(createServerFn()).toHaveProperty('middleware') - expectTypeOf(createServerFn()).toHaveProperty('inputValidator') + expectTypeOf(createServerFn()).toHaveProperty('validator') createServerFn({ method: 'GET' }).handler((options) => { expectTypeOf(options).toEqualTypeOf<{ context: undefined data: undefined - signal: AbortSignal + method: 'GET' + serverFnMeta: ServerFnMeta }>() }) }) -test('createServerFn with validator', () => { +test('createServerFn with validator function', () => { const fnAfterValidator = createServerFn({ method: 'GET', - }).inputValidator((input: { input: string }) => ({ + }).validator((input: { input: string }) => ({ a: input.input, })) expectTypeOf(fnAfterValidator).toHaveProperty('handler') expectTypeOf(fnAfterValidator).toHaveProperty('middleware') - expectTypeOf(fnAfterValidator).not.toHaveProperty('inputValidator') + expectTypeOf(fnAfterValidator).not.toHaveProperty('validator') const fn = fnAfterValidator.handler((options) => { expectTypeOf(options).toEqualTypeOf<{ @@ -42,7 +49,8 @@ test('createServerFn with validator', () => { data: { a: string } - signal: AbortSignal + method: 'GET' + serverFnMeta: ServerFnMeta }>() }) @@ -50,6 +58,190 @@ test('createServerFn with validator', () => { data: { input: string } headers?: HeadersInit signal?: AbortSignal + fetch?: CustomFetch + }>() + + expectTypeOf>().resolves.toEqualTypeOf() +}) + +test('createServerFn with async validator function', () => { + const fnAfterValidator = createServerFn({ + method: 'GET', + }).validator((input: string) => Promise.resolve(input)) + + expectTypeOf(fnAfterValidator).toHaveProperty('handler') + expectTypeOf(fnAfterValidator).toHaveProperty('middleware') + expectTypeOf(fnAfterValidator).not.toHaveProperty('validator') + + const fn = fnAfterValidator.handler((options) => { + expectTypeOf(options).toEqualTypeOf<{ + context: undefined + data: string + method: 'GET' + serverFnMeta: ServerFnMeta + }>() + }) + + expectTypeOf(fn).parameter(0).toEqualTypeOf<{ + data: string + headers?: HeadersInit + signal?: AbortSignal + fetch?: CustomFetch + }>() + + expectTypeOf>().resolves.toEqualTypeOf() +}) + +test('createServerFn with validator with parse method', () => { + const fnAfterValidator = createServerFn({ + method: 'GET', + }).validator({ + parse: (input: string) => input, + }) + + expectTypeOf(fnAfterValidator).toHaveProperty('handler') + expectTypeOf(fnAfterValidator).toHaveProperty('middleware') + expectTypeOf(fnAfterValidator).not.toHaveProperty('validator') + + const fn = fnAfterValidator.handler((options) => { + expectTypeOf(options).toEqualTypeOf<{ + context: undefined + data: string + method: 'GET' + serverFnMeta: ServerFnMeta + }>() + }) + + expectTypeOf(fn).parameter(0).toEqualTypeOf<{ + data: string + headers?: HeadersInit + signal?: AbortSignal + fetch?: CustomFetch + }>() + + expectTypeOf>().resolves.toEqualTypeOf() +}) + +test('createServerFn with async validator with parse method', () => { + const fnAfterValidator = createServerFn({ + method: 'GET', + }).validator({ + parse: (input: string) => Promise.resolve(input), + }) + + expectTypeOf(fnAfterValidator).toHaveProperty('handler') + expectTypeOf(fnAfterValidator).toHaveProperty('middleware') + expectTypeOf(fnAfterValidator).not.toHaveProperty('validator') + + const fn = fnAfterValidator.handler((options) => { + expectTypeOf(options).toEqualTypeOf<{ + context: undefined + data: string + method: 'GET' + serverFnMeta: ServerFnMeta + }>() + }) + + expectTypeOf(fn).parameter(0).toEqualTypeOf<{ + data: string + headers?: HeadersInit + signal?: AbortSignal + fetch?: CustomFetch + }>() + + expectTypeOf>().resolves.toEqualTypeOf() +}) + +test('createServerFn with standard validator', () => { + interface SyncValidator { + readonly '~standard': { + types?: { + input: string + output: string + } + validate: (input: unknown) => { + value: string + } + } + } + const validator: SyncValidator = { + ['~standard']: { + validate: (input: unknown) => ({ + value: input as string, + }), + }, + } + + const fnAfterValidator = createServerFn({ + method: 'GET', + }).validator(validator) + + expectTypeOf(fnAfterValidator).toHaveProperty('handler') + expectTypeOf(fnAfterValidator).toHaveProperty('middleware') + expectTypeOf(fnAfterValidator).not.toHaveProperty('validator') + + const fn = fnAfterValidator.handler((options) => { + expectTypeOf(options).toEqualTypeOf<{ + context: undefined + data: string + method: 'GET' + serverFnMeta: ServerFnMeta + }>() + }) + + expectTypeOf(fn).parameter(0).toEqualTypeOf<{ + data: string + headers?: HeadersInit + signal?: AbortSignal + fetch?: CustomFetch + }>() + + expectTypeOf>().resolves.toEqualTypeOf() +}) + +test('createServerFn with async standard validator', () => { + interface AsyncValidator { + readonly '~standard': { + types?: { + input: string + output: string + } + validate: (input: unknown) => Promise<{ + value: string + }> + } + } + const validator: AsyncValidator = { + ['~standard']: { + validate: (input: unknown) => + Promise.resolve({ + value: input as string, + }), + }, + } + + const fnAfterValidator = createServerFn({ + method: 'GET', + }).validator(validator) + + expectTypeOf(fnAfterValidator).toHaveProperty('handler') + expectTypeOf(fnAfterValidator).toHaveProperty('middleware') + expectTypeOf(fnAfterValidator).not.toHaveProperty('validator') + + const fn = fnAfterValidator.handler((options) => { + expectTypeOf(options).toEqualTypeOf<{ + context: undefined + data: string + method: 'GET' + serverFnMeta: ServerFnMeta + }>() + }) + + expectTypeOf(fn).parameter(0).toEqualTypeOf<{ + data: string + headers?: HeadersInit + signal?: AbortSignal + fetch?: CustomFetch }>() expectTypeOf>().resolves.toEqualTypeOf() @@ -93,7 +285,7 @@ test('createServerFn with middleware and context', () => { ]) expectTypeOf(fnWithMiddleware).toHaveProperty('handler') - expectTypeOf(fnWithMiddleware).toHaveProperty('inputValidator') + expectTypeOf(fnWithMiddleware).toHaveProperty('validator') fnWithMiddleware.handler((options) => { expectTypeOf(options).toEqualTypeOf<{ @@ -104,20 +296,21 @@ test('createServerFn with middleware and context', () => { readonly d: 'd' } data: undefined - signal: AbortSignal + method: 'GET' + serverFnMeta: ServerFnMeta }>() }) }) describe('createServerFn with middleware and validator', () => { - const middleware1 = createMiddleware({ type: 'function' }).inputValidator( + const middleware1 = createMiddleware({ type: 'function' }).validator( (input: { readonly inputA: 'inputA' }) => ({ outputA: 'outputA', }) as const, ) - const middleware2 = createMiddleware({ type: 'function' }).inputValidator( + const middleware2 = createMiddleware({ type: 'function' }).validator( (input: { readonly inputB: 'inputB' }) => ({ outputB: 'outputB', @@ -132,7 +325,7 @@ describe('createServerFn with middleware and validator', () => { test(`response`, () => { const fn = createServerFn({ method: 'GET' }) .middleware([middleware3]) - .inputValidator( + .validator( (input: { readonly inputC: 'inputC' }) => ({ outputC: 'outputC', @@ -146,7 +339,8 @@ describe('createServerFn with middleware and validator', () => { readonly outputB: 'outputB' readonly outputC: 'outputC' } - signal: AbortSignal + method: 'GET' + serverFnMeta: ServerFnMeta }>() return 'some-data' as const @@ -160,6 +354,7 @@ describe('createServerFn with middleware and validator', () => { } headers?: HeadersInit signal?: AbortSignal + fetch?: CustomFetch }>() expectTypeOf(fn).returns.resolves.toEqualTypeOf<'some-data'>() @@ -173,7 +368,7 @@ describe('createServerFn with middleware and validator', () => { test('createServerFn overrides properties', () => { const middleware1 = createMiddleware({ type: 'function' }) - .inputValidator( + .validator( () => ({ input: 'a' as 'a' | 'b' | 'c', @@ -198,7 +393,7 @@ test('createServerFn overrides properties', () => { const middleware2 = createMiddleware({ type: 'function' }) .middleware([middleware1]) - .inputValidator( + .validator( () => ({ input: 'b' as 'b' | 'c', @@ -221,7 +416,7 @@ test('createServerFn overrides properties', () => { createServerFn() .middleware([middleware2]) - .inputValidator( + .validator( () => ({ input: 'c', @@ -237,24 +432,26 @@ test('createServerFn overrides properties', () => { test('createServerFn where validator is a primitive', () => { createServerFn({ method: 'GET' }) - .inputValidator(() => 'c' as const) + .validator(() => 'c' as const) .handler((options) => { expectTypeOf(options).toEqualTypeOf<{ context: undefined data: 'c' - signal: AbortSignal + method: 'GET' + serverFnMeta: ServerFnMeta }>() }) }) test('createServerFn where validator is optional if object is optional', () => { const fn = createServerFn({ method: 'GET' }) - .inputValidator((input: 'c' | undefined) => input) + .validator((input: 'c' | undefined) => input) .handler((options) => { expectTypeOf(options).toEqualTypeOf<{ context: undefined data: 'c' | undefined - signal: AbortSignal + method: 'GET' + serverFnMeta: ServerFnMeta }>() }) @@ -263,6 +460,7 @@ test('createServerFn where validator is optional if object is optional', () => { data?: 'c' | undefined headers?: HeadersInit signal?: AbortSignal + fetch?: CustomFetch } | undefined >() @@ -275,7 +473,8 @@ test('createServerFn where data is optional if there is no validator', () => { expectTypeOf(options).toEqualTypeOf<{ context: undefined data: undefined - signal: AbortSignal + method: 'GET' + serverFnMeta: ServerFnMeta }>() }) @@ -284,6 +483,7 @@ test('createServerFn where data is optional if there is no validator', () => { data?: undefined headers?: HeadersInit signal?: AbortSignal + fetch?: CustomFetch } | undefined >() @@ -313,11 +513,138 @@ test('createServerFn returns undefined', () => { test('createServerFn cannot return function', () => { expectTypeOf(createServerFn().handler<{ func: () => 'func' }>) .parameter(0) - .returns.toEqualTypeOf<{ func: 'Function is not serializable' }>() + .returns.toEqualTypeOf<{ + func: SerializationError<'Function may not be serializable'> + }>() +}) + +test('createServerFn strict false can validate and return function', () => { + const fn = createServerFn({ method: 'GET', strict: false }) + .validator((input: { func: () => 'input' }) => ({ + output: input.func(), + })) + .handler(({ data }) => { + expectTypeOf(data).toEqualTypeOf<{ output: 'input' }>() + + return { + func: () => 'func' as const, + } + }) + + expectTypeOf(fn).parameter(0).toEqualTypeOf<{ + data: { func: () => 'input' } + headers?: HeadersInit + signal?: AbortSignal + fetch?: CustomFetch + }>() + + expectTypeOf(fn({ data: { func: () => 'input' } })).toEqualTypeOf< + Promise<{ + func: () => 'func' + }> + >() +}) + +test('createServerFn strict false factory preserves strictness', () => { + const createServerFnWithoutSerializationCheck = createServerFn({ + strict: false, + }) + + const myServerFn = createServerFnWithoutSerializationCheck() + .validator((input: { func: () => 'input' }) => ({ + output: input.func(), + })) + .handler(({ data }) => { + expectTypeOf(data).toEqualTypeOf<{ output: 'input' }>() + + return { + func: () => 'func' as const, + } + }) + + expectTypeOf(myServerFn).parameter(0).toEqualTypeOf<{ + data: { func: () => 'input' } + headers?: HeadersInit + signal?: AbortSignal + fetch?: CustomFetch + }>() + + expectTypeOf(myServerFn({ data: { func: () => 'input' } })).toEqualTypeOf< + Promise<{ + func: () => 'func' + }> + >() +}) + +test('createServerFn strict input false can validate function', () => { + const fn = createServerFn({ strict: { input: false } }) + .validator((input: { func: () => 'input' }) => ({ + output: input.func(), + })) + .handler(({ data }) => { + expectTypeOf(data).toEqualTypeOf<{ output: 'input' }>() + + return { + value: 'serializable' as const, + } + }) + + expectTypeOf(fn).parameter(0).toEqualTypeOf<{ + data: { func: () => 'input' } + headers?: HeadersInit + signal?: AbortSignal + fetch?: CustomFetch + }>() + + expectTypeOf(fn({ data: { func: () => 'input' } })).toEqualTypeOf< + Promise<{ + value: 'serializable' + }> + >() +}) + +test('createServerFn strict output false can return function', () => { + const fn = createServerFn({ strict: { output: false } }).handler(() => ({ + func: () => 'func' as const, + })) + + expectTypeOf(fn()).toEqualTypeOf< + Promise<{ + func: () => 'func' + }> + >() + + const promiseFn = createServerFn({ strict: { output: false } }).handler(() => + Promise.resolve({ + func: () => 'func' as const, + }), + ) + + expectTypeOf(promiseFn()).toEqualTypeOf< + Promise<{ + func: () => 'func' + }> + >() +}) + +test('ServerFnReturnType skips serialization when strict is false', () => { + expectTypeOf< + ServerFnReturnType 'func' }, false> + >().toEqualTypeOf<{ + func: () => 'func' + }>() +}) + +test('ServerFnReturnType skips serialization when strict output is false', () => { + expectTypeOf< + ServerFnReturnType 'func' }, { output: false }> + >().toEqualTypeOf<{ + func: () => 'func' + }>() }) test('createServerFn cannot validate function', () => { - const validator = createServerFn().inputValidator< + const validator = createServerFn().validator< (input: { func: () => 'string' }) => { output: 'string' } > @@ -326,13 +653,35 @@ test('createServerFn cannot validate function', () => { .toEqualTypeOf< Constrain< (input: { func: () => 'string' }) => { output: 'string' }, - Validator<{ func: 'Function is not serializable' }, any> + Validator< + { func: SerializationError<'Function may not be serializable'> }, + any + > + > + >() +}) + +test('createServerFn strict output false still checks input', () => { + const validator = createServerFn({ + method: 'GET', + strict: { output: false }, + }).validator<(input: { func: () => 'string' }) => { output: 'string' }> + + expectTypeOf(validator) + .parameter(0) + .toEqualTypeOf< + Constrain< + (input: { func: () => 'string' }) => { output: 'string' }, + Validator< + { func: SerializationError<'Function may not be serializable'> }, + any + > > >() }) test('createServerFn can validate Date', () => { - const validator = createServerFn().inputValidator< + const validator = createServerFn().validator< (input: Date) => { output: 'string' } > @@ -344,7 +693,7 @@ test('createServerFn can validate Date', () => { }) test('createServerFn can validate FormData', () => { - const validator = createServerFn({ method: 'POST' }).inputValidator< + const validator = createServerFn({ method: 'POST' }).validator< (input: FormData) => { output: 'string' } > @@ -352,7 +701,7 @@ test('createServerFn can validate FormData', () => { }) test('createServerFn cannot validate FormData for GET', () => { - const validator = createServerFn({ method: 'GET' }).inputValidator< + const validator = createServerFn({ method: 'GET' }).validator< (input: FormData) => { output: 'string' } > @@ -391,7 +740,7 @@ test('ServerFnReturnType distributes Response union', () => { test('createServerFn can be used as a mutation function', () => { const serverFn = createServerFn() - .inputValidator((data: number) => data) + .validator((data: number) => data) .handler(() => 'foo') type MutationFunction = ( @@ -408,7 +757,7 @@ test('createServerFn can be used as a mutation function', () => { test('createServerFn validator infers unknown for default input type', () => { const fn = createServerFn() - .inputValidator((input) => { + .validator((input) => { expectTypeOf(input).toEqualTypeOf() if (typeof input === 'number') return 'success' as const @@ -426,6 +775,7 @@ test('createServerFn validator infers unknown for default input type', () => { data?: unknown | undefined headers?: HeadersInit signal?: AbortSignal + fetch?: CustomFetch } | undefined >() @@ -457,7 +807,7 @@ test('incrementally building createServerFn with multiple middleware calls', () ]) expectTypeOf(builderWithMw1).toHaveProperty('handler') - expectTypeOf(builderWithMw1).toHaveProperty('inputValidator') + expectTypeOf(builderWithMw1).toHaveProperty('validator') expectTypeOf(builderWithMw1).toHaveProperty('middleware') builderWithMw1.handler((options) => { @@ -466,7 +816,8 @@ test('incrementally building createServerFn with multiple middleware calls', () readonly a: 'a' } data: undefined - signal: AbortSignal + method: 'GET' + serverFnMeta: ServerFnMeta }>() }) @@ -476,7 +827,7 @@ test('incrementally building createServerFn with multiple middleware calls', () ]) expectTypeOf(builderWithMw2).toHaveProperty('handler') - expectTypeOf(builderWithMw2).toHaveProperty('inputValidator') + expectTypeOf(builderWithMw2).toHaveProperty('validator') expectTypeOf(builderWithMw2).toHaveProperty('middleware') builderWithMw2.handler((options) => { @@ -486,7 +837,8 @@ test('incrementally building createServerFn with multiple middleware calls', () readonly b: 'b' } data: undefined - signal: AbortSignal + method: 'POST' + serverFnMeta: ServerFnMeta }>() }) @@ -496,7 +848,7 @@ test('incrementally building createServerFn with multiple middleware calls', () ]) expectTypeOf(builderWithMw3).toHaveProperty('handler') - expectTypeOf(builderWithMw3).toHaveProperty('inputValidator') + expectTypeOf(builderWithMw3).toHaveProperty('validator') expectTypeOf(builderWithMw3).toHaveProperty('middleware') builderWithMw3.handler((options) => { @@ -507,7 +859,9 @@ test('incrementally building createServerFn with multiple middleware calls', () readonly c: 'c' } data: undefined - signal: AbortSignal + method: 'GET' + + serverFnMeta: ServerFnMeta }>() }) }) @@ -539,7 +893,8 @@ test('compose middlewares and server function factories', () => { readonly b: 'b' } data: undefined - signal: AbortSignal + method: 'GET' + serverFnMeta: ServerFnMeta }>() }) }) @@ -561,7 +916,7 @@ test('createServerFn with request middleware and function middleware', () => { }) const funMw = createMiddleware({ type: 'function' }) - .inputValidator((x: string) => x) + .validator((x: string) => x) .server(({ next }) => { return next({ context: { a: 'a' } as const }) }) @@ -572,7 +927,7 @@ test('createServerFn with request middleware and function middleware', () => { expectTypeOf(fn({ data: 'a' })).toEqualTypeOf>() }) -test('createServerFn with inputValidator and request middleware', () => { +test('createServerFn with validator and request middleware', () => { const loggingMiddleware = createMiddleware().server(async ({ next }) => { console.log('Logging middleware executed on the server') const result = await next() @@ -581,7 +936,7 @@ test('createServerFn with inputValidator and request middleware', () => { const fn = createServerFn() .middleware([loggingMiddleware]) - .inputValidator(({ userName }: { userName: string }) => { + .validator(({ userName }: { userName: string }) => { return { userName } }) .handler(async ({ data }) => { diff --git a/packages/start-client-core/src/tests/createServerMiddleware.test-d.ts b/packages/start-client-core/src/tests/createServerMiddleware.test-d.ts index 11bfb6598c..f7bc33cb8a 100644 --- a/packages/start-client-core/src/tests/createServerMiddleware.test-d.ts +++ b/packages/start-client-core/src/tests/createServerMiddleware.test-d.ts @@ -1,25 +1,27 @@ import { expectTypeOf, test } from 'vitest' import { createMiddleware } from '../createMiddleware' import type { RequestServerNextFn } from '../createMiddleware' -import type { ConstrainValidator } from '../createServerFn' -import type { Register } from '@tanstack/router-core' +import type { ConstrainValidator, CustomFetch } from '../createServerFn' +import type { Register, SerializationError } from '@tanstack/router-core' +import type { ServerFnMeta } from '../constants' test('createServeMiddleware removes middleware after middleware,', () => { const middleware = createMiddleware({ type: 'function' }) expectTypeOf(middleware).toHaveProperty('middleware') expectTypeOf(middleware).toHaveProperty('server') - expectTypeOf(middleware).toHaveProperty('inputValidator') + expectTypeOf(middleware).toHaveProperty('validator') const middlewareAfterMiddleware = middleware.middleware([]) - expectTypeOf(middlewareAfterMiddleware).toHaveProperty('inputValidator') + expectTypeOf(middlewareAfterMiddleware).toHaveProperty('validator') expectTypeOf(middlewareAfterMiddleware).toHaveProperty('server') expectTypeOf(middlewareAfterMiddleware).not.toHaveProperty('middleware') - const middlewareAfterInput = middleware.inputValidator(() => {}) + const middlewareAfterInput = middleware.validator(() => {}) expectTypeOf(middlewareAfterInput).toHaveProperty('server') + expectTypeOf(middlewareAfterInput).not.toHaveProperty('validator') expectTypeOf(middlewareAfterInput).not.toHaveProperty('middleware') const middlewareAfterServer = middleware.server(async (options) => { @@ -42,6 +44,7 @@ test('createServeMiddleware removes middleware after middleware,', () => { expectTypeOf(middlewareAfterServer).not.toHaveProperty('server') expectTypeOf(middlewareAfterServer).not.toHaveProperty('input') + expectTypeOf(middlewareAfterServer).not.toHaveProperty('validator') expectTypeOf(middlewareAfterServer).not.toHaveProperty('middleware') }) @@ -155,6 +158,7 @@ test('createMiddleware merges client context and sends to the server', () => { context: { a: boolean } sendContext: undefined headers: HeadersInit + fetch?: CustomFetch }>() return result @@ -172,6 +176,7 @@ test('createMiddleware merges client context and sends to the server', () => { context: { b: string } sendContext: undefined headers: HeadersInit + fetch?: CustomFetch }>() return result @@ -190,6 +195,7 @@ test('createMiddleware merges client context and sends to the server', () => { context: { a: boolean; b: string; c: number } sendContext: undefined headers: HeadersInit + fetch?: CustomFetch }>() return result @@ -213,6 +219,7 @@ test('createMiddleware merges client context and sends to the server', () => { context: { a: boolean; b: string; c: number } sendContext: { a: boolean; b: string; c: number; d: 5 } headers: HeadersInit + fetch?: CustomFetch }>() return result @@ -252,7 +259,7 @@ test('createMiddleware merges client context and sends to the server', () => { test('createMiddleware merges input', () => { const middleware1 = createMiddleware({ type: 'function' }) - .inputValidator(() => { + .validator(() => { return { a: 'a', } as const @@ -264,7 +271,7 @@ test('createMiddleware merges input', () => { const middleware2 = createMiddleware({ type: 'function' }) .middleware([middleware1]) - .inputValidator(() => { + .validator(() => { return { b: 'b', } as const @@ -276,7 +283,7 @@ test('createMiddleware merges input', () => { createMiddleware({ type: 'function' }) .middleware([middleware2]) - .inputValidator(() => ({ c: 'c' }) as const) + .validator(() => ({ c: 'c' }) as const) .server(({ next, data }) => { expectTypeOf(data).toEqualTypeOf<{ readonly a: 'a' @@ -301,6 +308,7 @@ test('createMiddleware merges server context and client context, sends server co context: { fromClient1: string } sendContext: undefined headers: HeadersInit + fetch?: CustomFetch }>() return result @@ -340,6 +348,7 @@ test('createMiddleware merges server context and client context, sends server co context: { fromClient2: string } sendContext: undefined headers: HeadersInit + fetch?: CustomFetch }>() return result @@ -387,6 +396,7 @@ test('createMiddleware merges server context and client context, sends server co } sendContext: undefined headers: HeadersInit + fetch?: CustomFetch }>() return result @@ -444,6 +454,7 @@ test('createMiddleware merges server context and client context, sends server co } sendContext: { toServer1: 'toServer1' } headers: HeadersInit + fetch?: CustomFetch }>() return result @@ -511,6 +522,7 @@ test('createMiddleware merges server context and client context, sends server co } sendContext: { toServer1: 'toServer1'; toServer2: 'toServer2' } headers: HeadersInit + fetch?: CustomFetch }>() return result @@ -563,7 +575,10 @@ test('createMiddleware sendContext cannot send a function', () => { .parameter(0) .exclude() .toHaveProperty('sendContext') - .toEqualTypeOf<{ func: 'Function is not serializable' } | undefined>() + .toEqualTypeOf< + | { func: SerializationError<'Function may not be serializable'> } + | undefined + >() return next() }) @@ -572,14 +587,17 @@ test('createMiddleware sendContext cannot send a function', () => { .parameter(0) .exclude() .toHaveProperty('sendContext') - .toEqualTypeOf<{ func: 'Function is not serializable' } | undefined>() + .toEqualTypeOf< + | { func: SerializationError<'Function may not be serializable'> } + | undefined + >() return next() }) }) test('createMiddleware cannot validate function', () => { - const validator = createMiddleware({ type: 'function' }).inputValidator< + const validator = createMiddleware({ type: 'function' }).validator< (input: { func: () => 'string' }) => { output: 'string' } > @@ -595,7 +613,7 @@ test('createMiddleware cannot validate function', () => { }) test('createMiddleware can validate Date', () => { - const validator = createMiddleware({ type: 'function' }).inputValidator< + const validator = createMiddleware({ type: 'function' }).validator< (input: Date) => { output: 'string' } > @@ -607,7 +625,7 @@ test('createMiddleware can validate Date', () => { }) test('createMiddleware can validate FormData', () => { - const validator = createMiddleware({ type: 'function' }).inputValidator< + const validator = createMiddleware({ type: 'function' }).validator< (input: FormData) => { output: 'string' } > @@ -623,7 +641,7 @@ test('createMiddleware can validate FormData', () => { }) test('createMiddleware merging from parent with undefined validator', () => { - const middleware1 = createMiddleware({ type: 'function' }).inputValidator( + const middleware1 = createMiddleware({ type: 'function' }).validator( (input: { test: string }) => input.test, ) @@ -638,7 +656,7 @@ test('createMiddleware merging from parent with undefined validator', () => { test('createMiddleware validator infers unknown for default input type', () => { createMiddleware({ type: 'function' }) - .inputValidator((input) => { + .validator((input) => { expectTypeOf(input).toEqualTypeOf() if (typeof input === 'number') return 'success' as const @@ -659,6 +677,8 @@ test('createMiddleware with type request, no middleware or context', () => { next: RequestServerNextFn<{}, undefined> pathname: string context: undefined + handlerType: 'serverFn' | 'router' + serverFnMeta?: ServerFnMeta }>() const result = await options.next() @@ -681,6 +701,8 @@ test('createMiddleware with type request, no middleware with context', () => { next: RequestServerNextFn<{}, undefined> pathname: string context: undefined + handlerType: 'serverFn' | 'router' + serverFnMeta?: ServerFnMeta }>() const result = await options.next({ context: { a: 'a' } }) @@ -704,6 +726,8 @@ test('createMiddleware with type request, middleware and context', () => { next: RequestServerNextFn<{}, undefined> pathname: string context: undefined + handlerType: 'serverFn' | 'router' + serverFnMeta?: ServerFnMeta }>() const result = await options.next({ context: { a: 'a' } }) @@ -727,6 +751,8 @@ test('createMiddleware with type request, middleware and context', () => { next: RequestServerNextFn<{}, undefined> pathname: string context: { a: string } + handlerType: 'serverFn' | 'router' + serverFnMeta?: ServerFnMeta }>() const result = await options.next({ context: { b: 'b' } }) @@ -749,6 +775,8 @@ test('createMiddleware with type request can return Response directly', () => { next: RequestServerNextFn<{}, undefined> pathname: string context: undefined + handlerType: 'serverFn' | 'router' + serverFnMeta?: ServerFnMeta }>() // Should be able to return a Response directly @@ -768,6 +796,8 @@ test('createMiddleware with type request can return Promise', () => { next: RequestServerNextFn<{}, undefined> pathname: string context: undefined + handlerType: 'serverFn' | 'router' + serverFnMeta?: ServerFnMeta }>() // Should be able to return a Promise @@ -782,6 +812,8 @@ test('createMiddleware with type request can return sync Response', () => { next: RequestServerNextFn<{}, undefined> pathname: string context: undefined + handlerType: 'serverFn' | 'router' + serverFnMeta?: ServerFnMeta }>() // Should be able to return a synchronous Response diff --git a/packages/start-client-core/tests/createServerFn.test.ts b/packages/start-client-core/tests/createServerFn.test.ts new file mode 100644 index 0000000000..69f756a8ac --- /dev/null +++ b/packages/start-client-core/tests/createServerFn.test.ts @@ -0,0 +1,171 @@ +import { describe, expect, test } from 'vitest' +import { runWithStartContext } from '@tanstack/start-storage-context' +import { createMiddleware } from '../src/createMiddleware' +import { createServerFn, flattenMiddlewares } from '../src/createServerFn' + +test('appends factory middleware in order without changing source builders', () => { + const first = createMiddleware({ type: 'function' }) + const second = createMiddleware({ type: 'function' }) + const third = createMiddleware({ type: 'function' }) + const factory = createServerFn().middleware([second]) + const base = createServerFn({ method: 'POST' }).middleware([first]) + const middlewares = Object.freeze([factory, third, second]) + + const combined = base.middleware(middlewares) + + expect(combined.options.middleware).toEqual([first, second, third, second]) + expect(combined.options.method).toBe('POST') + expect(base.options.middleware).toEqual([first]) + expect(factory.options.middleware).toEqual([second]) + expect(middlewares).toEqual([factory, third, second]) + expect(combined.middleware([]).options.middleware).toEqual([ + first, + second, + third, + second, + ]) +}) + +test('ignores empty slots in a middleware array', () => { + const middleware = createMiddleware({ type: 'function' }) + const middlewares: Array = [] + middlewares[1] = middleware + + expect(createServerFn().middleware(middlewares).options.middleware).toEqual([ + middleware, + ]) + expect(0 in middlewares).toBe(false) +}) + +test('does not register middleware appended while reading the input', () => { + const first = createMiddleware({ type: 'function' }) + const second = createMiddleware({ type: 'function' }) + const middlewares = [first] + Object.defineProperty(middlewares, 0, { + get() { + middlewares.push(second) + return first + }, + }) + + expect(createServerFn().middleware(middlewares).options.middleware).toEqual([ + first, + ]) + expect(middlewares).toHaveLength(2) +}) + +describe('client-side throws', () => { + function runOnClient(fn: () => Promise) { + return runWithStartContext( + { + getRouter() { + throw new Error('Client middleware does not need a router') + }, + request: new Request('http://localhost/'), + startOptions: {}, + contextAfterGlobalMiddlewares: {}, + executedRequestMiddlewares: new Set(), + handlerType: 'serverFn', + }, + fn, + ) + } + + test.each([undefined, null, 0, '', false])( + 'rejects when client middleware throws %s', + async (value) => { + let fetched = false + const extractedFn = Object.assign( + async () => { + fetched = true + return { result: 'fetched' } + }, + { + url: '/_serverFn/client-throw', + serverFnMeta: { id: 'client-throw' }, + }, + ) + const fn = ( + createServerFn().middleware([ + createMiddleware({ type: 'function' }).client(() => { + throw value + }), + ]).handler as unknown as ( + extractedFn: unknown, + ) => () => Promise + )(extractedFn) + + const outcome = await runOnClient(() => + fn().then( + (resolved) => ({ resolved }), + (rejected: unknown) => ({ rejected }), + ), + ) + + expect(outcome).toStrictEqual({ rejected: value }) + expect(fetched).toBe(false) + }, + ) +}) + +describe('flattenMiddlewares', () => { + const inner = createMiddleware({ type: 'function' }) + const middle = createMiddleware({ type: 'function' }).middleware([inner]) + const outer = createMiddleware({ type: 'function' }).middleware([ + inner, + middle, + ]) + const sibling = createMiddleware({ type: 'function' }) + const names = new Map([ + [inner, 'inner'], + [middle, 'middle'], + [outer, 'outer'], + [sibling, 'sibling'], + ]) + const nameAll = (middlewares: Array) => + middlewares.map((middleware) => names.get(middleware)) + + test('lists nested middleware before its parent and keeps first occurrences', () => { + expect(nameAll(flattenMiddlewares([outer, sibling, middle]))).toEqual([ + 'inner', + 'middle', + 'outer', + 'sibling', + ]) + }) + + test('skips middleware in the seen set but still lists its children', () => { + expect( + nameAll( + flattenMiddlewares([outer, sibling], undefined, new Set([middle])), + ), + ).toEqual(['inner', 'outer', 'sibling']) + }) + + test('skips empty slots in nested middleware arrays', () => { + const sparse: Array = [] + sparse[1] = inner + const parent = createMiddleware({ type: 'function' }).middleware(sparse) + names.set(parent, 'parent') + + expect(nameAll(flattenMiddlewares([parent]))).toEqual(['inner', 'parent']) + }) + + test('throws for a nested middleware list that is not an array', () => { + const guard = createMiddleware({ type: 'function' }) + const parent = createMiddleware({ type: 'function' }).middleware( + guard as never, + ) + + expect(() => flattenMiddlewares([parent])).toThrow(TypeError) + }) + + test('throws for nesting deeper than the limit', () => { + const looped = createMiddleware({ type: 'function' }) + looped.middleware([looped]) + + expect(() => flattenMiddlewares([looped], 3)).toThrow( + 'Middleware nesting depth exceeded maximum of 3. Check for circular references.', + ) + }) +}) diff --git a/packages/start-client-core/tests/createStart.test.ts b/packages/start-client-core/tests/createStart.test.ts new file mode 100644 index 0000000000..79a4994281 --- /dev/null +++ b/packages/start-client-core/tests/createStart.test.ts @@ -0,0 +1,62 @@ +import { expect, test } from 'vitest' +import { createSerializationAdapter } from '@tanstack/router-core' +import { createStart } from '../src/createStart' + +const base = createSerializationAdapter({ + key: 'base', + test: (value): value is 'base' => value === 'base', + toSerializable: () => 'base', + fromSerializable: () => 'base' as const, +}) +const extended = createSerializationAdapter({ + key: 'extended', + extends: [base], + test: (value): value is 'extended' => value === 'extended', + toSerializable: () => 'extended', + fromSerializable: () => 'extended' as const, +}) + +test('getOptions returns the options of a synchronous factory synchronously', () => { + const options = createStart(() => ({ + serializationAdapters: [extended, base, extended], + })).getOptions() + + expect(options).not.toBeInstanceOf(Promise) + expect( + (options as { serializationAdapters: Array }) + .serializationAdapters, + ).toEqual([extended, base]) +}) + +test('getOptions resolves the options of an asynchronous factory', async () => { + const options = await createStart(async () => ({ + serializationAdapters: [extended, base, extended], + })).getOptions() + + expect(options.serializationAdapters).toEqual([extended, base]) +}) + +test('getOptions adopts a thenable that a factory returns', async () => { + const error = new Error('boom') + const resolving = createStart( + () => + ({ + then(resolve: (value: unknown) => void) { + resolve({ serializationAdapters: [extended, base, extended] }) + }, + }) as never, + ) + const rejecting = createStart( + () => + ({ + then(_: unknown, reject: (reason: unknown) => void) { + reject(error) + }, + }) as never, + ) + + await expect(resolving.getOptions()).resolves.toEqual({ + serializationAdapters: [extended, base], + }) + await expect(rejecting.getOptions()).rejects.toBe(error) +}) diff --git a/packages/start-client-core/tests/frame-decoder.test.ts b/packages/start-client-core/tests/frame-decoder.test.ts new file mode 100644 index 0000000000..0b330c2884 --- /dev/null +++ b/packages/start-client-core/tests/frame-decoder.test.ts @@ -0,0 +1,1628 @@ +import { describe, expect, it, vi } from 'vitest' +import { RawStream, createControlledPromise } from '@tanstack/router-core' +import { createRawStreamRPCPlugin } from '@tanstack/router-core/ssr/server' +import { runWithStartContext } from '@tanstack/start-storage-context' +import { SerovalDeserializationError, toCrossJSONStream } from 'seroval' +import { createFrameDecoder } from '../src/client-rpc/frame-decoder' +import { + serverFnFetcher, + trackPostProcessPromise, +} from '../src/client-rpc/serverFnFetcher' +import { + FRAME_HEADER_SIZE, + FRAME_TYPE_CHUNK, + FRAME_TYPE_END, + FRAME_TYPE_ERROR, + FRAME_TYPE_JSON, + MAX_FRAME_PAYLOAD_SIZE, + MAX_UNREAD_RAW_STREAM_BYTES, + TSS_CONTENT_TYPE_FRAMED_VERSIONED, + X_TSS_SERIALIZED, +} from '../src/constants' +import type * as Seroval from 'seroval' + +const serovalMocks = vi.hoisted(() => ({ + fromCrossJSON: vi.fn(), +})) + +vi.mock('seroval', async (importOriginal) => { + const actual = await importOriginal() + serovalMocks.fromCrossJSON.mockImplementation(actual.fromCrossJSON) + return { ...actual, fromCrossJSON: serovalMocks.fromCrossJSON } +}) + +/** + * Helper to encode a frame for testing + */ +function encodeFrame( + type: number, + streamId: number, + payload: Uint8Array, +): Uint8Array { + const frame = new Uint8Array(FRAME_HEADER_SIZE + payload.length) + const view = new DataView(frame.buffer) + view.setUint8(0, type) + view.setUint32(1, streamId, false) + view.setUint32(5, payload.length, false) + frame.set(payload, FRAME_HEADER_SIZE) + return frame +} + +function encodeJSONFrame(json: string): Uint8Array { + return encodeFrame(FRAME_TYPE_JSON, 0, new TextEncoder().encode(json)) +} + +function encodeChunkFrame(streamId: number, data: Uint8Array): Uint8Array { + return encodeFrame(FRAME_TYPE_CHUNK, streamId, data) +} + +function encodeEndFrame(streamId: number): Uint8Array { + return encodeFrame(FRAME_TYPE_END, streamId, new Uint8Array(0)) +} + +function encodeErrorFrame(streamId: number, message: string): Uint8Array { + return encodeFrame( + FRAME_TYPE_ERROR, + streamId, + new TextEncoder().encode(message), + ) +} + +async function readBytes( + reader: ReadableStreamDefaultReader, +): Promise { + const chunks: Array = [] + let length = 0 + for (;;) { + const next = await reader.read() + if (next.done) { + break + } + chunks.push(next.value) + length += next.value.byteLength + } + const result = new Uint8Array(length) + let offset = 0 + for (const chunk of chunks) { + result.set(chunk, offset) + offset += chunk.byteLength + } + return result +} + +describe('frame-decoder', () => { + it('cancels RawStream request serialization when the request is aborted', async () => { + const cancel = vi.fn(() => new Promise(() => {})) + const stream = new ReadableStream({ + pull: () => new Promise(() => {}), + cancel, + }) + const controller = new AbortController() + const reason = new Error('request aborted') + const handler = vi.fn() + + const request = runWithStartContext( + { startOptions: undefined } as any, + async () => + serverFnFetcher( + 'http://localhost/_serverFn/test', + [ + { + method: 'POST', + data: new RawStream(stream), + signal: controller.signal, + }, + ], + handler, + ), + ) + + await vi.waitFor(() => expect(stream.locked).toBe(true)) + controller.abort(reason) + + await expect(request).rejects.toBe(reason) + expect(cancel).toHaveBeenCalledExactlyOnceWith(reason) + expect(handler).not.toHaveBeenCalled() + expect(stream.locked).toBe(false) + }) + + it('cancels a framed response whose first JSON value is invalid', async () => { + const cancel = vi.fn() + const body = new ReadableStream({ + start(controller) { + controller.enqueue(encodeJSONFrame('{')) + }, + cancel, + }) + + await expect( + runWithStartContext({ startOptions: undefined } as any, async () => + serverFnFetcher( + 'http://localhost/_serverFn/test', + [{ method: 'POST' }], + () => + new Response(body, { + headers: { + 'content-type': TSS_CONTENT_TYPE_FRAMED_VERSIONED, + [X_TSS_SERIALIZED]: 'true', + }, + }), + ), + ), + ).rejects.toBeInstanceOf(SyntaxError) + + expect(cancel).toHaveBeenCalledOnce() + await vi.waitFor(() => expect(body.locked).toBe(false)) + }) + + it.each([ + ['JSON', 'application/json', false], + ['framed', TSS_CONTENT_TYPE_FRAMED_VERSIONED, true], + ])( + 'observes tracked post-processing when initial %s deserialization throws', + async (_name, contentType, framed) => { + const observe = vi.fn(() => Promise.resolve()) + const tracked = { catch: observe } as unknown as Promise + const error = new Error('deserialization failed') + serovalMocks.fromCrossJSON.mockImplementationOnce(() => { + trackPostProcessPromise(tracked) + throw error + }) + + const cancel = vi.fn() + const body = framed + ? new ReadableStream({ + start(controller) { + controller.enqueue(encodeJSONFrame('{}')) + }, + cancel, + }) + : '{}' + + await expect( + runWithStartContext({ startOptions: undefined } as any, async () => + serverFnFetcher( + 'http://localhost/_serverFn/test', + [{ method: 'POST' }], + () => + new Response(body, { + headers: { + 'content-type': contentType, + [X_TSS_SERIALIZED]: 'true', + }, + }), + ), + ), + ).rejects.toBe(error) + + expect(observe).toHaveBeenCalledOnce() + if (framed) { + expect(cancel).toHaveBeenCalledOnce() + await vi.waitFor(() => + expect((body as ReadableStream).locked).toBe(false), + ) + } + }, + ) + + it('continues framed patches without awaiting their post-processing', async () => { + let releaseGate!: () => void + const gate = new Promise((resolve) => { + releaseGate = resolve + }) + let resolveLastPatch!: () => void + const lastPatch = new Promise((resolve) => { + resolveLastPatch = resolve + }) + const result = { ok: true } + + serovalMocks.fromCrossJSON + .mockImplementationOnce(() => result) + .mockImplementationOnce(() => { + trackPostProcessPromise(gate) + }) + .mockImplementationOnce(() => { + releaseGate() + resolveLastPatch() + }) + + const body = new ReadableStream({ + start(controller) { + controller.enqueue(encodeJSONFrame('{}')) + controller.enqueue(encodeJSONFrame('{}')) + controller.enqueue(encodeJSONFrame('{}')) + controller.close() + }, + }) + + const request = runWithStartContext( + { startOptions: undefined } as any, + async () => + serverFnFetcher( + 'http://localhost/_serverFn/test', + [{ method: 'POST' }], + () => + new Response(body, { + headers: { + 'content-type': TSS_CONTENT_TYPE_FRAMED_VERSIONED, + [X_TSS_SERIALIZED]: 'true', + }, + }), + ), + ) + + await lastPatch + await expect(request).resolves.toBe(result) + await vi.waitFor(() => expect(body.locked).toBe(false)) + }) + + it.each(['invalid JSON', 'invalid patch', 'read failure'] as const)( + 'cancels the response and fails raw streams after %s', + async (failure) => { + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const cancel = vi.fn() + let controller!: ReadableStreamDefaultController + const body = new ReadableStream({ + start(value) { + controller = value + }, + cancel, + }) + const ready = createControlledPromise() + const dispose = toCrossJSONStream( + { + ready, + raw: new RawStream(new ReadableStream()), + }, + { + refs: new Map(), + plugins: [createRawStreamRPCPlugin(() => {})], + onParse(value) { + controller.enqueue(encodeJSONFrame(JSON.stringify(value))) + }, + }, + ) + + try { + const result = await runWithStartContext( + { startOptions: undefined } as any, + async () => + serverFnFetcher( + 'http://localhost/_serverFn/test', + [{ method: 'POST' }], + () => + new Response(body, { + headers: { + 'content-type': TSS_CONTENT_TYPE_FRAMED_VERSIONED, + [X_TSS_SERIALIZED]: 'true', + }, + }), + ), + ) + const rawReader = result.raw.getReader() + + ready.resolve('ready') + await expect(result.ready).resolves.toBe('ready') + const failures = Promise.allSettled([rawReader.read()]) + + const transportError = new Error('transport failed') + if (failure === 'read failure') { + controller.error(transportError) + } else { + controller.enqueue( + encodeJSONFrame(failure === 'invalid JSON' ? '{' : '{}'), + ) + } + + await vi.waitFor(() => expect(log).toHaveBeenCalledOnce()) + const error = log.mock.calls[0]![1] + if (failure === 'read failure') { + expect(error).toBe(transportError) + } else { + expect(error).toBeInstanceOf( + failure === 'invalid JSON' + ? SyntaxError + : SerovalDeserializationError, + ) + expect(cancel).toHaveBeenCalledExactlyOnceWith(error) + } + await expect(failures).resolves.toEqual([ + { status: 'rejected', reason: error }, + ]) + await expect(result.ready).resolves.toBe('ready') + rawReader.releaseLock() + await vi.waitFor(() => expect(body.locked).toBe(false)) + } finally { + dispose() + log.mockRestore() + } + }, + ) + + // Promises and streams that Seroval created from earlier records cannot be + // settled by the client after a transport failure without a Seroval API for + // aborting a cross-JSON deserialization session. + it.todo('rejects pending framed promises after a transport failure') + + it('cancels the response when the initial framed deserialization fails', async () => { + const error = new Error('initial deserialization failed') + serovalMocks.fromCrossJSON.mockImplementationOnce(() => { + throw error + }) + + const cancel = vi.fn() + let controller!: ReadableStreamDefaultController + const body = new ReadableStream({ + start(value) { + controller = value + }, + cancel, + }) + const dispose = toCrossJSONStream( + { value: 'first' }, + { + refs: new Map(), + onParse(value) { + controller.enqueue(encodeJSONFrame(JSON.stringify(value))) + }, + }, + ) + + try { + await expect( + runWithStartContext({ startOptions: undefined } as any, async () => + serverFnFetcher( + 'http://localhost/_serverFn/test', + [{ method: 'POST' }], + () => + new Response(body, { + headers: { + 'content-type': TSS_CONTENT_TYPE_FRAMED_VERSIONED, + [X_TSS_SERIALIZED]: 'true', + }, + }), + ), + ), + ).rejects.toBe(error) + expect(cancel).toHaveBeenCalledExactlyOnceWith(error) + await vi.waitFor(() => expect(body.locked).toBe(false)) + } finally { + dispose() + } + }) + + describe('createFrameDecoder', () => { + it('should throw synchronously when the input is already locked', () => { + const input = new ReadableStream() + const reader = input.getReader() + + try { + expect(() => createFrameDecoder(input)).toThrow() + } finally { + reader.releaseLock() + } + }) + + it('should ignore empty input chunks', async () => { + const input = new ReadableStream({ + start(controller) { + for (let index = 0; index < 1_000; index++) { + controller.enqueue(new Uint8Array()) + } + controller.enqueue(encodeJSONFrame('{"ok":true}')) + controller.close() + }, + }) + + const [chunks] = createFrameDecoder(input) + const reader = chunks.getReader() + await expect(reader.read()).resolves.toEqual({ + done: false, + value: '{"ok":true}', + }) + await expect(reader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('should reject unknown frame type', async () => { + const badFrame = encodeFrame(99, 0, new Uint8Array(0)) + let cancelReason: unknown + const input = new ReadableStream({ + start(controller) { + controller.enqueue(badFrame) + }, + cancel(reason) { + cancelReason = reason + }, + }) + + const [jsonChunks] = createFrameDecoder(input) + const reader = jsonChunks.getReader() + + await expect(reader.read()).rejects.toThrow('Invalid frame') + expect(cancelReason).toBeInstanceOf(Error) + expect(input.locked).toBe(false) + }) + + it('should reject raw frames with streamId 0', async () => { + const badChunk = encodeFrame(FRAME_TYPE_CHUNK, 0, new Uint8Array([1])) + const input = new ReadableStream({ + start(controller) { + controller.enqueue(badChunk) + controller.close() + }, + }) + + const [jsonChunks] = createFrameDecoder(input) + const reader = jsonChunks.getReader() + + await expect(reader.read()).rejects.toThrow('Invalid frame') + }) + + it('should reject JSON frames with non-zero streamId', async () => { + const badJson = encodeFrame( + FRAME_TYPE_JSON, + 1, + new TextEncoder().encode('{}\n'), + ) + const input = new ReadableStream({ + start(controller) { + controller.enqueue(badJson) + controller.close() + }, + }) + + const [jsonChunks] = createFrameDecoder(input) + const reader = jsonChunks.getReader() + + await expect(reader.read()).rejects.toThrow('Invalid frame') + }) + + it('should reject oversized frame payloads', async () => { + // Declare a payload length > MAX_FRAME_PAYLOAD_SIZE with no payload. + const headerOnly = new Uint8Array(FRAME_HEADER_SIZE) + const view = new DataView(headerOnly.buffer) + view.setUint8(0, FRAME_TYPE_JSON) + view.setUint32(1, 0, false) + view.setUint32(5, 16 * 1024 * 1024 + 1, false) + + const input = new ReadableStream({ + start(controller) { + controller.enqueue(headerOnly) + controller.close() + }, + }) + + const [jsonChunks] = createFrameDecoder(input) + const reader = jsonChunks.getReader() + + await expect(reader.read()).rejects.toThrow('Invalid frame') + }) + + it('should reject incomplete frames at end-of-stream', async () => { + const headerOnly = new Uint8Array(FRAME_HEADER_SIZE) + const view = new DataView(headerOnly.buffer) + view.setUint8(0, FRAME_TYPE_JSON) + view.setUint32(1, 0, false) + view.setUint32(5, 3, false) + + const input = new ReadableStream({ + start(controller) { + controller.enqueue(headerOnly) + controller.close() + }, + }) + + const [jsonChunks] = createFrameDecoder(input) + const reader = jsonChunks.getReader() + + await expect(reader.read()).rejects.toThrow('Incomplete frame') + }) + + it('should reject END frames with a payload', async () => { + const input = new ReadableStream({ + start(controller) { + controller.enqueue( + encodeFrame(FRAME_TYPE_END, 1, new Uint8Array([1])), + ) + }, + }) + + const [chunks] = createFrameDecoder(input) + await expect(chunks.getReader().read()).rejects.toThrow('Invalid frame') + }) + + it('should reject invalid getStream IDs', async () => { + const input = new ReadableStream({ pull() {} }) + const [chunks, getStream] = createFrameDecoder(input) + + for (const id of [0, -1, 1.5, 0x1_0000_0000, NaN, Infinity]) { + expect(() => getStream(id)).toThrow('Invalid raw stream ID') + } + const maxStream = getStream(0xffff_ffff) + expect(getStream(0xffff_ffff)).toBe(maxStream) + await chunks.cancel() + }) + + it('should reject frames after a raw stream has ended', async () => { + const firstEnd = encodeEndFrame(1) + const secondEnd = encodeEndFrame(1) + const input = new ReadableStream({ + start(controller) { + const frames = new Uint8Array(firstEnd.length + secondEnd.length) + frames.set(firstEnd) + frames.set(secondEnd, firstEnd.length) + controller.enqueue(frames) + }, + }) + + const [chunks] = createFrameDecoder(input) + await expect(chunks.getReader().read()).rejects.toThrow( + 'Raw stream already ended', + ) + }) + + it('rejects a header-only CHUNK for an ended stream without pulling its payload', async () => { + const chunkHeader = encodeChunkFrame(1, new Uint8Array()) + new DataView(chunkHeader.buffer).setUint32( + 5, + MAX_FRAME_PAYLOAD_SIZE, + false, + ) + const frames = [encodeEndFrame(1), chunkHeader] + let pulls = 0 + const input = new ReadableStream( + { + pull(controller) { + pulls++ + const frame = frames.shift() + if (!frame) { + throw new Error('Payload was pulled') + } + controller.enqueue(frame) + }, + }, + { highWaterMark: 0 }, + ) + + const [chunks] = createFrameDecoder(input) + await expect(chunks.getReader().read()).rejects.toThrow( + 'Raw stream already ended', + ) + expect(pulls).toBe(2) + }) + + it('returns stable closed streams after completion', async () => { + const input = new ReadableStream({ + start(controller) { + controller.close() + }, + }) + const [chunks, getStream] = createFrameDecoder(input) + + await expect(chunks.getReader().read()).resolves.toEqual({ + done: true, + value: undefined, + }) + const stream = getStream(1) + expect(getStream(1)).toBe(stream) + await expect(stream.getReader().read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('errors active and late streams after a fatal frame', async () => { + const json = encodeJSONFrame('{"ref":1}') + const malformed = encodeFrame(99, 0, new Uint8Array()) + const cancel = vi.fn() + const input = new ReadableStream({ + start(controller) { + const frames = new Uint8Array(json.length + malformed.length) + frames.set(json) + frames.set(malformed, json.length) + controller.enqueue(frames) + }, + cancel, + }) + const [chunks, getStream] = createFrameDecoder(input) + const jsonReader = chunks.getReader() + + await jsonReader.read() + const active = getStream(1) + await expect(jsonReader.read()).rejects.toThrow('Invalid frame') + await expect(active.getReader().read()).rejects.toThrow('Invalid frame') + const late = getStream(2) + expect(getStream(2)).toBe(late) + await expect(late.getReader().read()).rejects.toThrow('Invalid frame') + expect(cancel).toHaveBeenCalledOnce() + expect(input.locked).toBe(false) + }) + + it('errors a raw stream when input ends without END', async () => { + const json = encodeJSONFrame('{"ref":1}') + const chunk = encodeChunkFrame(1, new Uint8Array([1])) + const input = new ReadableStream({ + start(controller) { + const frames = new Uint8Array(json.length + chunk.length) + frames.set(json) + frames.set(chunk, json.length) + controller.enqueue(frames) + controller.close() + }, + }) + const [chunks, getStream] = createFrameDecoder(input) + const jsonReader = chunks.getReader() + await jsonReader.read() + const rawReader = getStream(1).getReader() + + await expect(rawReader.read()).resolves.toEqual({ + done: false, + value: new Uint8Array([1]), + }) + await expect(rawReader.read()).rejects.toThrow('Incomplete raw stream') + await expect(jsonReader.read()).rejects.toThrow('Incomplete raw stream') + }) + + it('accepts clean EOF for a cancelled raw stream', async () => { + let inputController!: ReadableStreamDefaultController + const input = new ReadableStream({ + start(controller) { + inputController = controller + }, + }) + const [chunks, getStream] = createFrameDecoder(input) + const jsonReader = chunks.getReader() + + inputController.enqueue(encodeJSONFrame('{"ref":1}')) + await jsonReader.read() + await getStream(1).cancel() + inputController.close() + + await expect(jsonReader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('accepts clean EOF after cancelling an unread stream that received END', async () => { + let inputController!: ReadableStreamDefaultController + let pulls = 0 + const frames = [ + encodeJSONFrame('{"ref":1}'), + encodeChunkFrame(1, new Uint8Array([1])), + encodeEndFrame(1), + ] + const input = new ReadableStream( + { + start(controller) { + inputController = controller + }, + pull(controller) { + pulls++ + const frame = frames.shift() + if (frame) { + controller.enqueue(frame) + } + }, + }, + { highWaterMark: 0 }, + ) + const [chunks, getStream] = createFrameDecoder(input) + const jsonReader = chunks.getReader() + + await expect(jsonReader.read()).resolves.toEqual({ + done: false, + value: '{"ref":1}', + }) + const rawStream = getStream(1) + await vi.waitFor(() => expect(pulls).toBe(4)) + await rawStream.cancel('unused') + inputController.close() + + await expect(jsonReader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('should cancel input when jsonChunks cancelled', async () => { + let cancelled = false + const input = new ReadableStream({ + pull() {}, + cancel() { + cancelled = true + }, + }) + + const [jsonChunks] = createFrameDecoder(input) + const reader = jsonChunks.getReader() + + await reader.cancel() + expect(cancelled).toBe(true) + }) + + it('does not decode a payload after JSON cancellation wins its read', async () => { + const first = encodeJSONFrame('{"first":true}') + const second = encodeJSONFrame('{"second":true}') + const firstInput = new Uint8Array(first.length + FRAME_HEADER_SIZE) + firstInput.set(first) + firstInput.set(second.subarray(0, FRAME_HEADER_SIZE), first.length) + + let pulls = 0 + let jsonReader!: ReadableStreamDefaultReader + const cancel = vi.fn() + const decode = vi.spyOn(TextDecoder.prototype, 'decode') + const input = new ReadableStream( + { + pull(controller) { + if (pulls++ === 0) { + controller.enqueue(firstInput) + } else { + queueMicrotask(() => void jsonReader.cancel('stop')) + controller.enqueue(second.subarray(FRAME_HEADER_SIZE)) + } + }, + cancel, + }, + { highWaterMark: 0 }, + ) + + try { + const [chunks] = createFrameDecoder(input) + jsonReader = chunks.getReader() + await expect(jsonReader.read()).resolves.toEqual({ + done: false, + value: '{"first":true}', + }) + decode.mockClear() + + await vi.waitFor(() => expect(input.locked).toBe(false)) + expect(decode).not.toHaveBeenCalled() + expect(cancel).toHaveBeenCalledWith('stop') + } finally { + decode.mockRestore() + } + }) + + it('continues decoding while a raw chunk is unread', async () => { + const frames = [ + encodeJSONFrame('{"ref":1}'), + encodeChunkFrame(1, new Uint8Array([1])), + encodeJSONFrame('{"after":true}'), + encodeEndFrame(1), + ] + let pulls = 0 + const input = new ReadableStream( + { + pull(controller) { + const frame = frames[pulls++] + if (frame) { + controller.enqueue(frame) + } else { + controller.close() + } + }, + }, + { highWaterMark: 0 }, + ) + + const [chunks, getStream] = createFrameDecoder(input) + const jsonReader = chunks.getReader() + await expect(jsonReader.read()).resolves.toEqual({ + done: false, + value: '{"ref":1}', + }) + const rawStream = getStream(1) + await expect(jsonReader.read()).resolves.toEqual({ + done: false, + value: '{"after":true}', + }) + + const rawReader = rawStream.getReader() + await expect(rawReader.read()).resolves.toEqual({ + done: false, + value: new Uint8Array([1]), + }) + await expect(rawReader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + expect(getStream(1)).toBe(rawStream) + }) + + it('keeps the multiplexed response active after one raw stream is cancelled', async () => { + const frames = [ + encodeJSONFrame('{"refs":[1,2]}'), + encodeChunkFrame(1, new Uint8Array([1])), + encodeChunkFrame(1, new Uint8Array([2])), + encodeEndFrame(1), + encodeChunkFrame(2, new Uint8Array([3])), + encodeEndFrame(2), + encodeJSONFrame('{"after":true}'), + ] + let pulls = 0 + const input = new ReadableStream( + { + pull(controller) { + const frame = frames[pulls++] + if (frame) { + controller.enqueue(frame) + } else { + controller.close() + } + }, + }, + { highWaterMark: 0 }, + ) + + const [chunks, getStream] = createFrameDecoder(input) + const jsonReader = chunks.getReader() + await jsonReader.read() + const blockingStream = getStream(1) + const otherReader = getStream(2).getReader() + const otherRead = otherReader.read() + await vi.waitFor(() => expect(pulls).toBe(frames.length)) + + await blockingStream.cancel('unused') + await expect(otherRead).resolves.toEqual({ + done: false, + value: new Uint8Array([3]), + }) + await expect(otherReader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + await expect(jsonReader.read()).resolves.toEqual({ + done: false, + value: '{"after":true}', + }) + await expect(jsonReader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + expect(getStream(1)).toBe(blockingStream) + await expect(blockingStream.getReader().read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('streams more than the old 16 MiB queue limit when consumed', async () => { + const payload = new Uint8Array(1024 * 1024) + let frame = 0 + const input = new ReadableStream( + { + pull(controller) { + if (frame++ === 0) { + controller.enqueue(encodeJSONFrame('{"ref":1}')) + } else if (frame <= 18) { + controller.enqueue(encodeChunkFrame(1, payload)) + } else if (frame === 19) { + controller.enqueue(encodeEndFrame(1)) + } else { + controller.close() + } + }, + }, + { highWaterMark: 0 }, + ) + + const [chunks, getStream] = createFrameDecoder(input) + const jsonReader = chunks.getReader() + await jsonReader.read() + const rawReader = getStream(1).getReader() + let bytes = 0 + for (;;) { + const next = await rawReader.read() + if (next.done) { + break + } + bytes += next.value.byteLength + } + + expect(bytes).toBe(17 * 1024 * 1024) + await expect(jsonReader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('cancelling JSON aborts the response while a raw chunk is unread', async () => { + let pulls = 0 + let inputCancelReason: unknown + const frames = [ + encodeJSONFrame('{"ref":1}'), + encodeChunkFrame(1, new Uint8Array([1])), + ] + const input = new ReadableStream( + { + pull(controller) { + const frame = frames[pulls++] + if (frame) { + controller.enqueue(frame) + } + }, + cancel(reason) { + inputCancelReason = reason + }, + }, + { highWaterMark: 0 }, + ) + + const [chunks, getStream] = createFrameDecoder(input) + const jsonReader = chunks.getReader() + await jsonReader.read() + const rawStream = getStream(1) + await vi.waitFor(() => expect(pulls).toBe(frames.length + 1)) + + const reason = 'stop' + await jsonReader.cancel(reason) + await expect(rawStream.getReader().read()).rejects.toBe(reason) + expect(inputCancelReason).toBe(reason) + await vi.waitFor(() => expect(input.locked).toBe(false)) + // A stream requested after cancellation fails the same way. + await expect(getStream(2).getReader().read()).rejects.toBe(reason) + }) + + it.each(['A first', 'B first'] as const)( + 'fails only the over-limit raw stream with %s frames', + async (order) => { + const aChunk = encodeChunkFrame(1, new Uint8Array(1024 * 1024)) + const aFrameCount = MAX_UNREAD_RAW_STREAM_BYTES / (1024 * 1024) + 2 + const aFrames = Array.from({ length: aFrameCount }, () => aChunk) + const bFrames = [ + encodeChunkFrame(2, Uint8Array.of(1, 2)), + encodeChunkFrame(2, Uint8Array.of(3, 4)), + encodeEndFrame(2), + ] + const frames = [ + encodeJSONFrame('{"refs":[1,2]}'), + ...(order === 'A first' ? aFrames : bFrames), + ...(order === 'A first' ? bFrames : aFrames), + encodeChunkFrame(1, Uint8Array.of(9)), + encodeEndFrame(1), + encodeJSONFrame('{"after":true}'), + ] + let pulls = 0 + const input = new ReadableStream( + { + pull(controller) { + const frame = frames[pulls++] + if (frame) { + controller.enqueue(frame) + } else { + controller.close() + } + }, + }, + { highWaterMark: 0 }, + ) + + const [chunks, getStream] = createFrameDecoder(input) + const jsonReader = chunks.getReader() + await expect(jsonReader.read()).resolves.toEqual({ + done: false, + value: '{"refs":[1,2]}', + }) + const aReader = getStream(1).getReader() + const bReader = getStream(2).getReader() + + await expect(readBytes(bReader)).resolves.toEqual( + Uint8Array.of(1, 2, 3, 4), + ) + await expect(jsonReader.read()).resolves.toEqual({ + done: false, + value: '{"after":true}', + }) + await expect(aReader.read()).rejects.toThrow( + 'Raw stream 1 has too many unread bytes', + ) + await expect(jsonReader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + expect(pulls).toBe(frames.length + 1) + }, + ) + + it('copies a small chunk instead of pinning its network buffer', async () => { + const network = new Uint8Array(4096) + const frame = encodeChunkFrame(1, Uint8Array.of(1, 2, 3)) + network.set(frame) + const input = new ReadableStream({ + start(controller) { + controller.enqueue(encodeJSONFrame('{}')) + controller.enqueue(network.subarray(0, frame.byteLength)) + controller.enqueue(encodeEndFrame(1)) + controller.close() + }, + }) + + const [chunks, getStream] = createFrameDecoder(input) + const raw = getStream(1).getReader() + await chunks.getReader().read() + const { value } = await raw.read() + expect(Array.from(value!)).toEqual([1, 2, 3]) + expect(value!.buffer.byteLength).toBe(3) + }) + + it('should reject too many raw streams', async () => { + // END frames create streams, even with no CHUNKs. + const frames: Array = [] + for (let i = 1; i <= 1025; i++) { + frames.push(encodeEndFrame(i)) + } + + const totalLen = frames.reduce((acc, f) => acc + f.length, 0) + const combined = new Uint8Array(totalLen) + let offset = 0 + for (const frame of frames) { + combined.set(frame, offset) + offset += frame.length + } + + const input = new ReadableStream({ + start(controller) { + controller.enqueue(combined) + controller.close() + }, + }) + + const [jsonChunks] = createFrameDecoder(input) + const reader = jsonChunks.getReader() + + await expect(reader.read()).rejects.toThrow('Too many raw streams') + }) + + it('rejects a header-only CHUNK for a 1025th stream without pulling its payload', async () => { + const chunkHeader = encodeChunkFrame(1025, new Uint8Array()) + new DataView(chunkHeader.buffer).setUint32( + 5, + MAX_FRAME_PAYLOAD_SIZE, + false, + ) + let releaseHeader!: () => void + const headerReady = new Promise((resolve) => { + releaseHeader = resolve + }) + let pulls = 0 + const input = new ReadableStream( + { + async pull(controller) { + pulls++ + if (pulls > 1) { + throw new Error('Payload was pulled') + } + await headerReady + controller.enqueue(chunkHeader) + }, + }, + { highWaterMark: 0 }, + ) + const [chunks, getStream] = createFrameDecoder(input) + for (let id = 1; id <= 1024; id++) { + getStream(id) + } + + releaseHeader() + await expect(chunks.getReader().read()).rejects.toThrow( + 'Too many raw streams', + ) + expect(pulls).toBe(1) + }) + + it('should count cancelled raw streams toward the stream limit', async () => { + const input = new ReadableStream({ pull() {} }) + const [chunks, getStream] = createFrameDecoder(input) + + for (let id = 1; id <= 1024; id++) { + await getStream(id).cancel() + } + + expect(() => getStream(1025)).toThrow('Too many raw streams') + await chunks.cancel() + }) + + it('should decode JSON frames', async () => { + const frame1 = encodeJSONFrame('{"line":1}') + const frame2 = encodeJSONFrame('{"line":2}') + + const combinedFrames = new Uint8Array(frame1.length + frame2.length) + combinedFrames.set(frame1, 0) + combinedFrames.set(frame2, frame1.length) + + const input = new ReadableStream({ + start(controller) { + controller.enqueue(combinedFrames) + controller.close() + }, + }) + + const [jsonChunks] = createFrameDecoder(input) + + const reader = jsonChunks.getReader() + const chunks: Array = [] + + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + chunks.push(value) + } + + expect(chunks).toEqual(['{"line":1}', '{"line":2}']) + }) + + it('should decode raw stream chunks', async () => { + const jsonFrame = encodeJSONFrame('{}') + const chunkFrame = encodeChunkFrame(5, new Uint8Array([1, 2, 3])) + const endFrame = encodeEndFrame(5) + + const combined = new Uint8Array( + jsonFrame.length + chunkFrame.length + endFrame.length, + ) + combined.set(jsonFrame, 0) + combined.set(chunkFrame, jsonFrame.length) + combined.set(endFrame, jsonFrame.length + chunkFrame.length) + + const input = new ReadableStream({ + start(controller) { + controller.enqueue(combined) + controller.close() + }, + }) + + const [jsonChunks, getOrCreateStream] = createFrameDecoder(input) + + // Pre-create the stream before consuming + const stream5 = getOrCreateStream(5) + + // Consume JSON first + const jsonReader = jsonChunks.getReader() + const { value: jsonValue } = await jsonReader.read() + expect(jsonValue).toBe('{}') + + // Read the raw stream + const rawReader = stream5.getReader() + const { value: rawValue, done: rawDone } = await rawReader.read() + + expect(rawDone).toBe(false) + expect(rawValue).toEqual(new Uint8Array([1, 2, 3])) + + const { done: finalDone } = await rawReader.read() + expect(finalDone).toBe(true) + }) + + it('should handle partial frames across chunks', async () => { + const frame = encodeJSONFrame('{"test":"data"}') + + // Split frame in the middle + const part1 = frame.slice(0, 5) + const part2 = frame.slice(5) + + const input = new ReadableStream({ + start(controller) { + controller.enqueue(part1) + controller.enqueue(part2) + controller.close() + }, + }) + + const [jsonChunks] = createFrameDecoder(input) + + const reader = jsonChunks.getReader() + const chunks: Array = [] + + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + chunks.push(value) + } + + expect(chunks).toEqual(['{"test":"data"}']) + }) + + it('should decode a frame from one input chunk', async () => { + const frame = encodeJSONFrame('{"fast":"path"}') + + const input = new ReadableStream({ + start(controller) { + controller.enqueue(frame) + controller.close() + }, + }) + + const [jsonChunks] = createFrameDecoder(input) + const reader = jsonChunks.getReader() + const { value } = await reader.read() + + expect(value).toBe('{"fast":"path"}') + }) + + it('should decode a header split across input chunks', async () => { + const frame = encodeJSONFrame('{"slow":"path"}') + + // Split at byte 3, then byte 6, then rest - header is 9 bytes + const part1 = frame.slice(0, 3) // first 3 bytes of header + const part2 = frame.slice(3, 6) // next 3 bytes of header + const part3 = frame.slice(6) // last 3 bytes of header + payload + + const input = new ReadableStream({ + start(controller) { + controller.enqueue(part1) + controller.enqueue(part2) + controller.enqueue(part3) + controller.close() + }, + }) + + const [jsonChunks] = createFrameDecoder(input) + const reader = jsonChunks.getReader() + const { value } = await reader.read() + + expect(value).toBe('{"slow":"path"}') + }) + + it('should handle header split at every byte boundary', async () => { + // Extreme case: each header byte in separate chunk + const frame = encodeJSONFrame('{"byte":"split"}') + + // Split into 9 single-byte chunks for header, then payload + const chunks: Array = [] + for (let i = 0; i < FRAME_HEADER_SIZE; i++) { + chunks.push(frame.slice(i, i + 1)) + } + chunks.push(frame.slice(FRAME_HEADER_SIZE)) // payload + + const input = new ReadableStream({ + start(controller) { + for (const chunk of chunks) { + controller.enqueue(chunk) + } + controller.close() + }, + }) + + const [jsonChunks] = createFrameDecoder(input) + const reader = jsonChunks.getReader() + const { value } = await reader.read() + + expect(value).toBe('{"byte":"split"}') + }) + + it('should handle multiple raw streams', async () => { + const jsonFrame = encodeJSONFrame('{}') + const chunk1 = encodeChunkFrame(1, new Uint8Array([10])) + const chunk2 = encodeChunkFrame(2, new Uint8Array([20])) + const end1 = encodeEndFrame(1) + const end2 = encodeEndFrame(2) + + const totalLen = + jsonFrame.length + + chunk1.length + + chunk2.length + + end1.length + + end2.length + const combined = new Uint8Array(totalLen) + let offset = 0 + for (const frame of [jsonFrame, chunk1, chunk2, end1, end2]) { + combined.set(frame, offset) + offset += frame.length + } + + const input = new ReadableStream({ + start(controller) { + controller.enqueue(combined) + controller.close() + }, + }) + + const [jsonChunks, getOrCreateStream] = createFrameDecoder(input) + + // Pre-create streams before consuming + const stream1 = getOrCreateStream(1) + const stream2 = getOrCreateStream(2) + + // Drain JSON + const jsonReader = jsonChunks.getReader() + await jsonReader.read() + + // Read stream 1 + const reader1 = stream1.getReader() + const { value: val1 } = await reader1.read() + expect(val1).toEqual(new Uint8Array([10])) + await expect(reader1.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + + // Read stream 2 + const reader2 = stream2.getReader() + const { value: val2 } = await reader2.read() + expect(val2).toEqual(new Uint8Array([20])) + await expect(reader2.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('should handle error frames for existing streams', async () => { + const jsonFrame = encodeJSONFrame('{}') + // Create a stream, then error it immediately + const chunkFrame = encodeChunkFrame(3, new Uint8Array([1])) + const errorFrame = encodeErrorFrame(3, 'Stream failed') + + const combined = new Uint8Array( + jsonFrame.length + chunkFrame.length + errorFrame.length, + ) + combined.set(jsonFrame, 0) + combined.set(chunkFrame, jsonFrame.length) + combined.set(errorFrame, jsonFrame.length + chunkFrame.length) + + const input = new ReadableStream({ + start(controller) { + controller.enqueue(combined) + controller.close() + }, + }) + + const [jsonChunks, getOrCreateStream] = createFrameDecoder(input) + + // Pre-create stream 3 + const stream3 = getOrCreateStream(3) + + // Drain JSON + const jsonReader = jsonChunks.getReader() + await jsonReader.read() + + const reader = stream3.getReader() + await expect(reader.read()).resolves.toEqual({ + done: false, + value: new Uint8Array([1]), + }) + await expect(reader.read()).rejects.toThrow('Stream failed') + expect(getOrCreateStream(3)).toBe(stream3) + await expect(jsonReader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('should preserve stream after END frame for late consumers', async () => { + const jsonFrame = encodeJSONFrame('{"streamRef":7}') + const chunkFrame = encodeChunkFrame(7, new Uint8Array([42, 43, 44])) + const endFrame = encodeEndFrame(7) + + const combined = new Uint8Array( + jsonFrame.length + chunkFrame.length + endFrame.length, + ) + combined.set(jsonFrame, 0) + combined.set(chunkFrame, jsonFrame.length) + combined.set(endFrame, jsonFrame.length + chunkFrame.length) + + const input = new ReadableStream({ + start(controller) { + controller.enqueue(combined) + controller.close() + }, + }) + + const [jsonChunks, getOrCreateStream] = createFrameDecoder(input) + + // The reference is admitted before its raw data, so the deserializer can + // obtain the stream without requiring the decoder to buffer it eagerly. + const jsonReader = jsonChunks.getReader() + await expect(jsonReader.read()).resolves.toEqual({ + done: false, + value: '{"streamRef":7}', + }) + const stream7 = getOrCreateStream(7) + + // The stream should still have the data that was enqueued + const rawReader = stream7.getReader() + const { value, done } = await rawReader.read() + + expect(done).toBe(false) + expect(value).toEqual(new Uint8Array([42, 43, 44])) + + // Next read should be done (stream was closed by END frame) + const { done: finalDone } = await rawReader.read() + expect(finalDone).toBe(true) + await expect(jsonReader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('should preserve chunks when the stream is obtained after its JSON reference', async () => { + const jsonFrame = encodeJSONFrame('{"ref":9}') + const chunkFrame1 = encodeChunkFrame(9, new Uint8Array([1, 2])) + const chunkFrame2 = encodeChunkFrame(9, new Uint8Array([3, 4])) + const endFrame = encodeEndFrame(9) + + const combined = new Uint8Array( + jsonFrame.length + + chunkFrame1.length + + chunkFrame2.length + + endFrame.length, + ) + let offset = 0 + for (const frame of [jsonFrame, chunkFrame1, chunkFrame2, endFrame]) { + combined.set(frame, offset) + offset += frame.length + } + + const input = new ReadableStream({ + start(controller) { + controller.enqueue(combined) + controller.close() + }, + }) + + const [jsonChunks, getOrCreateStream] = createFrameDecoder(input) + + const jsonReader = jsonChunks.getReader() + await expect(jsonReader.read()).resolves.toEqual({ + done: false, + value: '{"ref":9}', + }) + + const stream9 = getOrCreateStream(9) + const reader = stream9.getReader() + + const { value: v1 } = await reader.read() + expect(v1).toEqual(new Uint8Array([1, 2])) + + const { value: v2 } = await reader.read() + expect(v2).toEqual(new Uint8Array([3, 4])) + + const { done: finalDone } = await reader.read() + expect(finalDone).toBe(true) + await expect(jsonReader.read()).resolves.toEqual({ + done: true, + value: undefined, + }) + }) + + it('should reassemble a chunk payload that spans many small reads', async () => { + // A large binary payload delivered in tiny network reads exercises the + // cursor's exact-length assembly path. + const payload = new Uint8Array(300) + for (let i = 0; i < payload.length; i++) payload[i] = i % 256 + + const jsonFrame = encodeJSONFrame('{"ref":11}') + const chunkFrame = encodeChunkFrame(11, payload) + const endFrame = encodeEndFrame(11) + + const combined = new Uint8Array( + jsonFrame.length + chunkFrame.length + endFrame.length, + ) + combined.set(jsonFrame, 0) + combined.set(chunkFrame, jsonFrame.length) + combined.set(endFrame, jsonFrame.length + chunkFrame.length) + + const input = new ReadableStream({ + start(controller) { + // 7-byte reads: smaller than the 9-byte header and the payload, so + // both header and payload span multiple input chunks. + for (let i = 0; i < combined.length; i += 7) { + controller.enqueue(combined.subarray(i, i + 7)) + } + controller.close() + }, + }) + + const [jsonChunks, getOrCreateStream] = createFrameDecoder(input) + const stream11 = getOrCreateStream(11) + + const jsonReader = jsonChunks.getReader() + const { value: jsonValue } = await jsonReader.read() + expect(jsonValue).toBe('{"ref":11}') + + const rawReader = stream11.getReader() + const received: Array = [] + for (;;) { + const { done, value } = await rawReader.read() + if (done) { + break + } + received.push(...value) + } + expect(received).toEqual(Array.from(payload)) + }) + + it('reassembles a large chunk payload delivered one byte at a time', async () => { + // One-byte reads exercise repeated cursor advancement without repeated + // concatenation or rescanning. + const payload = new Uint8Array(200) + for (let i = 0; i < payload.length; i++) { + payload[i] = (i * 7) % 256 + } + + const jsonFrame = encodeJSONFrame('{"ref":21}') + const chunkFrame = encodeChunkFrame(21, payload) + const endFrame = encodeEndFrame(21) + + const combined = new Uint8Array( + jsonFrame.length + chunkFrame.length + endFrame.length, + ) + combined.set(jsonFrame, 0) + combined.set(chunkFrame, jsonFrame.length) + combined.set(endFrame, jsonFrame.length + chunkFrame.length) + + const input = new ReadableStream({ + start(controller) { + for (let i = 0; i < combined.length; i++) { + controller.enqueue(combined.subarray(i, i + 1)) + } + controller.close() + }, + }) + + const [jsonChunks, getOrCreateStream] = createFrameDecoder(input) + const stream21 = getOrCreateStream(21) + + const jsonReader = jsonChunks.getReader() + const { value: jsonValue } = await jsonReader.read() + expect(jsonValue).toBe('{"ref":21}') + + const rawReader = stream21.getReader() + const received: Array = [] + for (;;) { + const { done, value } = await rawReader.read() + if (done) { + break + } + received.push(...value) + } + expect(received).toEqual(Array.from(payload)) + }) + + it('decodes many frames when reads never align with frame boundaries', async () => { + // These 100-byte frames never align with the 7-byte input reads. + const FRAME_COUNT = 7 + const expected: Array = [] + const frames: Array = [] + for (let i = 0; i < FRAME_COUNT; i++) { + const payload = `frame-${i}`.padEnd(91, '.') // 91 bytes => 100-byte frame + expected.push(payload) + frames.push(encodeJSONFrame(payload)) + } + + const totalLen = frames.reduce((acc, f) => acc + f.length, 0) + const combined = new Uint8Array(totalLen) + let offset = 0 + for (const f of frames) { + combined.set(f, offset) + offset += f.length + } + + const input = new ReadableStream({ + start(controller) { + for (let i = 0; i < combined.length; i += 7) { + controller.enqueue(combined.subarray(i, i + 7)) + } + controller.close() + }, + }) + + const [jsonChunks] = createFrameDecoder(input) + const reader = jsonChunks.getReader() + const received: Array = [] + for (;;) { + const { done, value } = await reader.read() + if (done) { + break + } + received.push(value) + } + expect(received).toEqual(expected) + }) + }) +}) diff --git a/packages/start-client-core/tests/function-middleware-headers.test.ts b/packages/start-client-core/tests/function-middleware-headers.test.ts new file mode 100644 index 0000000000..56a732ff6b --- /dev/null +++ b/packages/start-client-core/tests/function-middleware-headers.test.ts @@ -0,0 +1,234 @@ +import { expect, test } from 'vitest' +import { runWithStartContext } from '@tanstack/start-storage-context' +import { createMiddleware } from '../src/createMiddleware' +import { executeMiddleware } from '../src/createServerFn' + +function runMiddleware( + middlewares: Parameters[0], + env: 'client' | 'server', + headers?: HeadersInit, +) { + return runWithStartContext( + { + getRouter() { + throw new Error('Function middleware does not need a router') + }, + request: new Request('http://localhost/_serverFn/header-test'), + startOptions: {}, + contextAfterGlobalMiddlewares: {}, + executedRequestMiddlewares: new Set(), + handlerType: 'serverFn', + }, + () => + executeMiddleware(middlewares, env, { + method: 'POST', + data: undefined, + serverFnMeta: { id: 'header-test' }, + context: { request: 'request-context' }, + headers, + }), + ) +} + +test('client next() provides headers when no headers were supplied', async () => { + let observedHeaders: HeadersInit | undefined + const middleware = createMiddleware({ type: 'function' }).client( + async ({ next }) => { + const result = await next() + observedHeaders = result.headers + return result + }, + ) + + const result = await runMiddleware([middleware], 'client') + + expect(observedHeaders).toBeDefined() + expect(Array.from(new Headers(observedHeaders))).toEqual([]) + expect(result.headers).toBe(observedHeaders) +}) + +test.each([ + ['client', 'omitted'], + ['server', 'omitted'], + ['client', 'empty'], + ['server', 'empty'], +] as const)( + '%s next() preserves context with %s sendContext', + async (env, sendContext) => { + const options = + sendContext === 'omitted' + ? { context: { hop: 'kept' } } + : { context: { hop: 'kept' }, sendContext: {} } + const assertResult = (result: { + context?: unknown + sendContext?: unknown + }) => { + expect(result.context).toEqual({ + request: 'request-context', + hop: 'kept', + }) + if (sendContext === 'omitted') { + expect(result.sendContext).toBeUndefined() + } else { + expect(result.sendContext).toBeDefined() + expect(result.sendContext).toEqual({}) + } + } + const middleware = createMiddleware({ type: 'function' }) + .client(async ({ next }) => { + const result = await next(options) + assertResult(result) + return result + }) + .server(async ({ next }) => { + const result = await next(options) + assertResult(result) + return result + }) + + const result = await runMiddleware([middleware], env) + + expect(result.error).toBeUndefined() + assertResult(result) + }, +) + +test('server middleware preserves context and sendContext without headers', async () => { + const first = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { first: 'one' }, sendContext: { firstReply: 'one' } }), + ) + const second = createMiddleware({ type: 'function' }) + .middleware([first]) + .server(({ context, next }) => { + expect(context.first).toBe('one') + return next({ + context: { second: 'two' }, + sendContext: { secondReply: 'two' }, + }) + }) + + const result = await runMiddleware([second], 'server') + + expect(result.context).toEqual({ + request: 'request-context', + first: 'one', + second: 'two', + }) + expect(result.sendContext).toEqual({ firstReply: 'one', secondReply: 'two' }) +}) + +test.each(['client', 'server'] as const)( + '%s middleware preserves explicitly supplied headers', + async (env) => { + const headers = new Headers({ 'x-call': 'preserved' }) + const middleware = createMiddleware({ type: 'function' }) + .client(({ next }) => next()) + .server(({ next }) => next()) + + const result = await runMiddleware([middleware], env, headers) + + expect(new Headers(result.headers).get('x-call')).toBe('preserved') + expect(headers.get('x-call')).toBe('preserved') + }, +) + +test('client middleware merges supplied headers without changing either input', async () => { + const headers = new Headers({ 'x-initial': 'one', 'x-shared': 'initial' }) + headers.append('set-cookie', 'first=one; Path=/') + const nextHeaders = new Headers({ 'x-next': 'two', 'x-shared': 'next' }) + nextHeaders.append('set-cookie', 'second=two; Path=/') + const originalHeaders = Array.from(headers) + const originalNextHeaders = Array.from(nextHeaders) + const middleware = createMiddleware({ type: 'function' }).client(({ next }) => + next({ headers: nextHeaders }), + ) + + const result = await runMiddleware([middleware], 'client', headers) + const merged = new Headers(result.headers) + + expect(merged.get('x-initial')).toBe('one') + expect(merged.get('x-next')).toBe('two') + expect(merged.get('x-shared')).toBe('next') + expect(merged.getSetCookie()).toEqual([ + 'first=one; Path=/', + 'second=two; Path=/', + ]) + expect(Array.from(headers)).toEqual(originalHeaders) + expect(Array.from(nextHeaders)).toEqual(originalNextHeaders) +}) + +test('client middleware can supply headers when the call supplied none', async () => { + const middleware = createMiddleware({ type: 'function' }).client(({ next }) => + next({ headers: { 'x-next': 'present' } }), + ) + + const result = await runMiddleware([middleware], 'client') + + expect(new Headers(result.headers).get('x-next')).toBe('present') +}) + +test.each(['client', 'server'] as const)( + '%s executor reads initial middleware options in order without repeating accessors', + async (env) => { + const reads: Array = [] + const ignoredSendContext = Object.freeze({ selected: 'first read' }) + const selectedSendContext = Object.freeze({ selected: 'second read' }) + const context = Object.freeze({ request: 'preserved' }) + const headers = new Headers({ 'x-initial': 'preserved' }) + const fetch = async () => new Response('unused') + let sendContextReads = 0 + + const result = await runWithStartContext( + { + getRouter() { + throw new Error('Function middleware does not need a router') + }, + request: new Request('http://localhost/_serverFn/accessor-test'), + startOptions: {}, + contextAfterGlobalMiddlewares: {}, + executedRequestMiddlewares: new Set(), + handlerType: 'serverFn', + }, + () => + executeMiddleware([], env, { + method: 'POST', + data: undefined, + serverFnMeta: { id: 'accessor-test' }, + get headers() { + reads.push('headers') + return headers + }, + get sendContext() { + reads.push('sendContext') + sendContextReads++ + return sendContextReads === 1 + ? ignoredSendContext + : selectedSendContext + }, + get context() { + reads.push('context') + return context + }, + get fetch() { + reads.push('fetch') + return fetch + }, + }), + ) + + expect(reads).toEqual([ + 'headers', + 'sendContext', + 'context', + 'fetch', + 'headers', + 'sendContext', + 'context', + 'fetch', + ]) + expect(result.sendContext).toBe(selectedSendContext) + expect(result.context).toBe(context) + expect(result.headers).toBe(headers) + expect(result.fetch).toBe(fetch) + }, +) diff --git a/packages/start-client-core/tests/function-middleware.bench.ts b/packages/start-client-core/tests/function-middleware.bench.ts new file mode 100644 index 0000000000..e4dce620a8 --- /dev/null +++ b/packages/start-client-core/tests/function-middleware.bench.ts @@ -0,0 +1,328 @@ +// @vitest-environment node + +import { afterAll, describe, expect, test } from 'vitest' +import { runWithStartContext } from '@tanstack/start-storage-context' +import { createMiddleware } from '../src/createMiddleware' +import { executeMiddleware } from '../src/createServerFn' +import type { StartStorageContext } from '@tanstack/start-storage-context' +import type { ServerFnMiddlewareOptions } from '../src/createServerFn' + +type SendContextMode = 'absent' | 'empty' | 'present' +type Context = Readonly> + +type Scenario = { + name: string + env: 'client' | 'server' + headers: 'absent' | 'supplied' + depth: 0 | 1 | 4 + initialSendContext: SendContextMode + nextSendContext: SendContextMode +} + +type NextOptions = { + context: Context + sendContext?: Context + headers?: Headers +} + +type InputOptions = Pick & + NextOptions & { + data: number + } + +type Input = { + options: Readonly + snapshot: ReturnType + storage: StartStorageContext +} + +const batchSize = 160 +const benchOptions = { warmupIterations: 100, time: 2_000, throws: true } +const sendContextScenarios: Array<{ + name: string + initial: SendContextMode + next: SendContextMode +}> = [ + { name: 'absent', initial: 'absent', next: 'absent' }, + { name: 'empty', initial: 'empty', next: 'empty' }, + { name: 'present', initial: 'present', next: 'present' }, + { name: 'empty-from-next', initial: 'absent', next: 'empty' }, + { name: 'present-from-next', initial: 'absent', next: 'present' }, +] + +const scenarios: Array = (['server', 'client'] as const).flatMap( + (env) => + (['absent', 'supplied'] as const).flatMap((headers) => + ([0, 1, 4] as const).flatMap((depth) => + sendContextScenarios + .filter((context) => depth > 0 || context.initial === context.next) + .map((context) => ({ + name: `${env}-headers-${headers}-send-${context.name}-layers-${depth}`, + env, + headers, + depth, + initialSendContext: context.initial, + nextSendContext: context.next, + })), + ), + ), +) + +function snapshotOptions(options: NextOptions) { + return { + keys: Object.keys(options), + context: { ...options.context }, + sendContext: + options.sendContext === undefined + ? undefined + : { ...options.sendContext }, + } +} + +function snapshotHeaders(headers: Headers) { + return { + headers, + entries: Array.from(headers), + cookies: headers.getSetCookie(), + } +} + +function createWorkload(scenario: Scenario) { + const suppliedHeaders = scenario.headers === 'supplied' + const initialHeaders = new Headers({ + 'x-initial': 'one', + 'x-shared': 'initial', + }) + initialHeaders.append('set-cookie', 'first=one; Path=/') + initialHeaders.append('set-cookie', 'second=two; Path=/') + const headerSnapshots = [snapshotHeaders(initialHeaders)] + const expectedHeaders = new Headers( + suppliedHeaders ? initialHeaders : undefined, + ) + const nextInputs: Array<{ + options: Readonly + snapshot: ReturnType + }> = [] + const middlewares = Array.from({ length: scenario.depth }, (_, index) => { + const nextOptions: NextOptions = { + context: Object.freeze({ [`hop${index}`]: index, shared: `hop${index}` }), + } + if (scenario.nextSendContext !== 'absent') { + nextOptions.sendContext = Object.freeze( + scenario.nextSendContext === 'empty' + ? {} + : { [`reply${index}`]: index, shared: `reply${index}` }, + ) + } + // Only client middleware can supply headers through its public next(). + if (scenario.env === 'client' && suppliedHeaders) { + const headers = new Headers({ + 'x-shared': `hop${index}`, + [`x-hop-${index}`]: String(index), + }) + headers.append('set-cookie', `hop${index}=${index}; Path=/`) + headerSnapshots.push(snapshotHeaders(headers)) + nextOptions.headers = headers + expectedHeaders.set('x-shared', `hop${index}`) + expectedHeaders.set(`x-hop-${index}`, String(index)) + expectedHeaders.append('set-cookie', `hop${index}=${index}; Path=/`) + } + nextInputs.push({ + options: Object.freeze(nextOptions), + snapshot: snapshotOptions(nextOptions), + }) + if (scenario.env === 'client') { + return createMiddleware({ type: 'function' }).client(({ next }) => + next(nextOptions), + ) + } + return createMiddleware({ type: 'function' }).server(({ next }) => + next(nextOptions), + ) + }) + const inputs = Array.from({ length: batchSize }, (_, index): Input => { + const options: InputOptions = { + method: 'POST', + data: index, + serverFnMeta: Object.freeze({ id: 'middleware-benchmark' }), + context: Object.freeze({ + seed: index, + trusted: 'server-context', + shared: 'initial', + }), + } + if (suppliedHeaders) { + options.headers = initialHeaders + } + if (scenario.initialSendContext !== 'absent') { + options.sendContext = Object.freeze( + scenario.initialSendContext === 'empty' + ? {} + : { initialReply: 'present', shared: 'initial' }, + ) + } + return { + options: Object.freeze(options), + snapshot: snapshotOptions(options), + storage: { + request: new Request( + `http://localhost/_serverFn/middleware-benchmark?i=${index}`, + ), + getRouter() { + throw new Error('Function middleware does not need a router') + }, + startOptions: {}, + contextAfterGlobalMiddlewares: {}, + executedRequestMiddlewares: new Set(), + handlerType: 'serverFn', + }, + } + }) + + // The client phase uses the real Start context used during SSR calls. + function invoke(input: Input) { + return runWithStartContext(input.storage, () => + executeMiddleware(middlewares, scenario.env, input.options), + ) + } + + async function verify() { + for (const input of inputs) { + const { options, snapshot } = input + const result = await invoke(input) + expect(result.error).toBeUndefined() + expect(result.data).toBe(options.data) + // Handler results and transport belong to the server-function benchmarks. + expect(result.result).toBeUndefined() + const context = { ...options.context } + const sendContext = { ...options.sendContext } + for (const next of nextInputs) { + Object.assign(context, next.options.context) + Object.assign(sendContext, next.options.sendContext) + } + expect({ ...result.context }).toEqual(context) + // Compare absent payload contents while preserving explicit empty objects. + expect({ ...result.sendContext }).toEqual(sendContext) + if (scenario.nextSendContext !== 'absent') { + expect(result.sendContext).toBeDefined() + } + if (scenario.env === 'client') { + expect(result.headers).toBeDefined() + } + const headers = new Headers(result.headers) + expect(Array.from(headers)).toEqual(Array.from(expectedHeaders)) + expect(headers.getSetCookie()).toEqual(expectedHeaders.getSetCookie()) + expect(snapshotOptions(options)).toEqual(snapshot) + } + for (const { options, snapshot } of nextInputs) { + expect(snapshotOptions(options)).toEqual(snapshot) + } + for (const { headers, entries, cookies } of headerSnapshots) { + expect(Array.from(headers)).toEqual(entries) + expect(headers.getSetCookie()).toEqual(cookies) + } + } + + async function batch() { + // Every call settles before the next; no work escapes the measured batch. + for (const input of inputs) { + await invoke(input) + } + } + + function invokeIndex(index: number) { + return invoke(inputs[index]!) + } + + return { verify, batch, invokeIndex } +} + +function createMixedWorkload(env: Scenario['env']) { + const absent = createWorkload({ + name: 'mixed-absent', + env, + headers: 'absent', + depth: 4, + initialSendContext: 'absent', + nextSendContext: 'absent', + }) + const supplied = createWorkload({ + name: 'mixed-supplied', + env, + headers: 'supplied', + depth: 4, + initialSendContext: 'present', + nextSendContext: 'present', + }) + + async function verify() { + await absent.verify() + await supplied.verify() + } + + async function batch() { + // Interleave 120 absent calls and 40 supplied calls in each 160-call batch. + for (let index = 0; index < batchSize; index++) { + await (index % 4 === 0 ? supplied : absent).invokeIndex(index) + } + } + + return { verify, batch } +} + +const workloads: Array< + ReturnType | ReturnType +> = [] + +afterAll(async () => { + for (const workload of workloads) { + await workload.verify() + } +}) + +for (const scenario of scenarios) { + describe(`function middleware ${scenario.name}`, () => { + let workload: ReturnType | undefined + + test('160 calls', async ({ bench }) => { + await bench( + '160 calls', + { + // Tinybench awaits beforeAll before warmup and measurement. Only + // selected cases allocate fixtures, and the measured callback + // contains no assertions. + beforeAll: async () => { + if (!workload) { + workload = createWorkload(scenario) + workloads.push(workload) + } + await workload.verify() + }, + }, + () => workload!.batch(), + ).run(benchOptions) + }) + }) +} + +for (const env of ['server', 'client'] as const) { + describe(`function middleware ${env}-mixed-75-absent-25-supplied-layers-4`, () => { + let workload: ReturnType | undefined + + test('160 calls', async ({ bench }) => { + await bench( + '160 calls', + { + beforeAll: async () => { + if (!workload) { + workload = createMixedWorkload(env) + workloads.push(workload) + } + await workload.verify() + }, + }, + () => workload!.batch(), + ).run(benchOptions) + }) + }) +} diff --git a/packages/start-client-core/tests/hydration-runtime.test.ts b/packages/start-client-core/tests/hydration-runtime.test.ts new file mode 100644 index 0000000000..577d329cd9 --- /dev/null +++ b/packages/start-client-core/tests/hydration-runtime.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it, vi } from 'vitest' +import { waitForHydrationPrefetchStrategy } from '../src/hydration/runtime' +import type { HydrationPrefetchStrategy } from '../src/hydration/types' + +describe('waitForHydrationPrefetchStrategy', () => { + it('cleans up a strategy that finishes during synchronous setup', async () => { + const abortController = new AbortController() + const cleanupHydrate = vi.fn() + const cleanupStrategy = vi.fn() + let hydrate = () => {} + + const strategy: HydrationPrefetchStrategy = { + _s: ({ prefetch }) => { + prefetch?.() + return cleanupStrategy + }, + } + + const result = waitForHydrationPrefetchStrategy(strategy, { + element: null, + signal: abortController.signal, + onHydrate: (listener) => { + hydrate = listener + return cleanupHydrate + }, + }) + + await expect(result).resolves.toBe('prefetch') + expect(cleanupHydrate).toHaveBeenCalledTimes(1) + expect(cleanupStrategy).toHaveBeenCalledTimes(1) + + hydrate() + abortController.abort() + expect(cleanupHydrate).toHaveBeenCalledTimes(1) + expect(cleanupStrategy).toHaveBeenCalledTimes(1) + }) + + it.each([ + ['abort', 'abort'], + ['hydrate', 'hydrate'], + ] as const)( + 'settles an abort/hydrate race with %s first and cleans up once', + async (winner, expectedReason) => { + const abortController = new AbortController() + const cleanupHydrate = vi.fn() + const cleanupStrategy = vi.fn() + let hydrate = () => {} + let prefetch = () => {} + + const strategy: HydrationPrefetchStrategy = { + _s: (context) => { + prefetch = context.prefetch ?? (() => {}) + return cleanupStrategy + }, + } + + const result = waitForHydrationPrefetchStrategy(strategy, { + element: null, + signal: abortController.signal, + onHydrate: (listener) => { + hydrate = listener + return cleanupHydrate + }, + }) + + if (winner === 'abort') { + abortController.abort() + hydrate() + } else { + hydrate() + abortController.abort() + } + prefetch() + + await expect(result).resolves.toBe(expectedReason) + expect(cleanupHydrate).toHaveBeenCalledTimes(1) + expect(cleanupStrategy).toHaveBeenCalledTimes(1) + }, + ) + + it('does not set up a strategy when the signal is already aborted', async () => { + const abortController = new AbortController() + abortController.abort() + const setup = vi.fn() + const onHydrate = vi.fn() + + const result = waitForHydrationPrefetchStrategy( + { _s: setup }, + { + element: null, + signal: abortController.signal, + onHydrate, + }, + ) + + await expect(result).resolves.toBe('abort') + expect(setup).not.toHaveBeenCalled() + expect(onHydrate).not.toHaveBeenCalled() + }) +}) diff --git a/packages/start-client-core/tests/hydration-visible.test.ts b/packages/start-client-core/tests/hydration-visible.test.ts new file mode 100644 index 0000000000..c0fbac0dfd --- /dev/null +++ b/packages/start-client-core/tests/hydration-visible.test.ts @@ -0,0 +1,127 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { visible } from '../src/hydration/visible' +import type { HydrationPrefetchStrategy } from '../src/hydration/types' + +class IntersectionObserverMock implements IntersectionObserver { + readonly root: Document | Element | null + readonly rootMargin: string + readonly scrollMargin: string + readonly thresholds: ReadonlyArray + readonly observe = vi.fn((_target: Element) => {}) + readonly unobserve = vi.fn((_target: Element) => {}) + readonly disconnect = vi.fn(() => {}) + + constructor( + readonly callback: IntersectionObserverCallback, + options: IntersectionObserverInit = {}, + ) { + this.root = options.root ?? null + this.rootMargin = options.rootMargin ?? '0px' + this.scrollMargin = options.scrollMargin ?? '0px' + this.thresholds = Array.isArray(options.threshold) + ? options.threshold + : [options.threshold ?? 0] + } + + takeRecords(): Array { + return [] + } + + emit(target: Element, isIntersecting = true) { + this.callback( + [{ target, isIntersecting } as IntersectionObserverEntry], + this, + ) + } +} + +describe('visible hydration strategy', () => { + let observers: Array + const cleanups: Array<() => void> = [] + + beforeEach(() => { + observers = [] + vi.stubGlobal( + 'IntersectionObserver', + class extends IntersectionObserverMock { + constructor( + callback: IntersectionObserverCallback, + options?: IntersectionObserverInit, + ) { + super(callback, options) + observers.push(this) + } + }, + ) + }) + + afterEach(() => { + cleanups.splice(0).forEach((cleanup) => cleanup()) + vi.unstubAllGlobals() + }) + + function observe( + strategy: HydrationPrefetchStrategy, + element: Element, + callback: () => void, + ) { + const cleanup = strategy._s?.({ element, prefetch: callback }) + if (cleanup) { + cleanups.push(cleanup) + } + return cleanup + } + + it('shares an observer and tracks multiple callbacks for one element', () => { + const element = document.createElement('div') + const first = vi.fn() + const second = vi.fn() + const strategy = visible({ rootMargin: '25px', threshold: [0, 0.5] }) + + const cleanupFirst = observe(strategy, element, first) + observe(strategy, element, second) + + expect(observers).toHaveLength(1) + expect(observers[0]!.observe).toHaveBeenCalledOnce() + expect(observers[0]!.observe).toHaveBeenCalledWith(element) + + cleanupFirst?.() + observers[0]!.emit(element) + + expect(first).not.toHaveBeenCalled() + expect(second).toHaveBeenCalledOnce() + expect(observers[0]!.unobserve).toHaveBeenCalledOnce() + expect(observers[0]!.unobserve).toHaveBeenCalledWith(element) + expect(observers[0]!.disconnect).toHaveBeenCalledOnce() + }) + + it('keeps a shared observer until every element is cleaned up', () => { + const firstElement = document.createElement('div') + const secondElement = document.createElement('div') + const options = { rootMargin: '50px', threshold: 0.25 } + + const cleanupFirst = observe(visible(options), firstElement, vi.fn()) + const cleanupSecond = observe(visible(options), secondElement, vi.fn()) + + expect(observers).toHaveLength(1) + expect(observers[0]!.observe).toHaveBeenCalledTimes(2) + + cleanupFirst?.() + expect(observers[0]!.unobserve).toHaveBeenCalledWith(firstElement) + expect(observers[0]!.disconnect).not.toHaveBeenCalled() + + cleanupSecond?.() + expect(observers[0]!.unobserve).toHaveBeenCalledWith(secondElement) + expect(observers[0]!.disconnect).toHaveBeenCalledOnce() + + const cleanupThird = observe( + visible(options), + document.createElement('div'), + vi.fn(), + ) + expect(observers).toHaveLength(2) + + cleanupThird?.() + expect(observers[1]!.disconnect).toHaveBeenCalledOnce() + }) +}) diff --git a/packages/start-client-core/tests/safeObjectMerge.test.ts b/packages/start-client-core/tests/safeObjectMerge.test.ts new file mode 100644 index 0000000000..354a633e55 --- /dev/null +++ b/packages/start-client-core/tests/safeObjectMerge.test.ts @@ -0,0 +1,37 @@ +import { expect, test } from 'vitest' +import { createNullProtoObject, safeObjectMerge } from '../src/safeObjectMerge' + +// JSON.parse creates `__proto__` as an own key, as a deserialized payload can. +const unsafe = JSON.parse( + '{"__proto__":{"polluted":true},"constructor":1,"kept":"source","prototype":2,"added":true}', +) + +test('safeObjectMerge copies own keys in order into a null-prototype object', () => { + const merged = safeObjectMerge>( + { first: 1, kept: 'target' }, + unsafe, + ) + + expect(Object.getPrototypeOf(merged)).toBeNull() + expect(Object.keys(merged)).toEqual(['first', 'kept', 'added']) + expect(merged.kept).toBe('source') + expect(({} as Record).polluted).toBeUndefined() +}) + +test('safeObjectMerge ignores a source that is not an object', () => { + const merged = safeObjectMerge>( + { first: 1 }, + 'source' as never, + ) + + expect(Object.keys(merged)).toEqual(['first']) +}) + +test('createNullProtoObject copies own keys without prototype keys', () => { + expect(Object.getPrototypeOf(createNullProtoObject())).toBeNull() + + const copy = createNullProtoObject(unsafe) + + expect(Object.getPrototypeOf(copy)).toBeNull() + expect(Object.keys(copy)).toEqual(['kept', 'added']) +}) diff --git a/packages/start-client-core/tsconfig.build.json b/packages/start-client-core/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/start-client-core/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/start-client-core/tsconfig.json b/packages/start-client-core/tsconfig.json index 0a0fe1f18a..8542a25320 100644 --- a/packages/start-client-core/tsconfig.json +++ b/packages/start-client-core/tsconfig.json @@ -3,7 +3,8 @@ "compilerOptions": { "jsx": "preserve", "jsxImportSource": "solid-js", - "module": "esnext" + "module": "esnext", + "types": ["node"] }, "include": ["src", "vite.config.ts"] } diff --git a/packages/start-client-core/vite.config.ts b/packages/start-client-core/vite.config.ts index 35832a2c49..71e163a1ed 100644 --- a/packages/start-client-core/vite.config.ts +++ b/packages/start-client-core/vite.config.ts @@ -1,27 +1,43 @@ import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/config/vite' +import { tanstackViteConfig } from '@tanstack/vite-config' import packageJson from './package.json' -const config = defineConfig({ - test: { - typecheck: { enabled: true }, - name: packageJson.name, - watch: false, - environment: 'jsdom', - }, -}) - -export default mergeConfig( - config, - tanstackViteConfig({ - srcDir: './src', - entry: [ - './src/index.tsx', - './src/fake-start-entry.ts', - './src/client/index.ts', - './src/client-rpc/index.ts', - ], - cjs: false, - externalDeps: ['#tanstack-start-entry', '#tanstack-router-entry'], - }), +export default defineConfig(({ command }) => + mergeConfig( + { + define: + command === 'build' + ? { + 'import.meta.hot': 'import.meta.hot', + } + : undefined, + test: { + typecheck: { enabled: true }, + name: packageJson.name, + watch: false, + environment: 'jsdom', + }, + }, + tanstackViteConfig({ + tsconfigPath: './tsconfig.build.json', + srcDir: './src', + entry: [ + './src/index.tsx', + './src/client/index.ts', + './src/client-rpc/index.ts', + './src/hydration/constants.ts', + './src/hydration.ts', + './src/hydration/runtime.ts', + './src/fake-entries/start.ts', + './src/fake-entries/router.ts', + './src/empty-plugin-adapters.ts', + ], + cjs: false, + externalDeps: [ + '#tanstack-start-entry', + '#tanstack-router-entry', + '#tanstack-start-plugin-adapters', + ], + }), + ), ) diff --git a/packages/start-fn-stubs/CHANGELOG.md b/packages/start-fn-stubs/CHANGELOG.md new file mode 100644 index 0000000000..e364ae973e --- /dev/null +++ b/packages/start-fn-stubs/CHANGELOG.md @@ -0,0 +1,23 @@ +# @tanstack/start-fn-stubs + +## 1.162.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +### Patch Changes + +- add createCsrfMiddleware based on Sec-Fetch-Site header, auto-apply to unconfigured servers, warn for others ([#7373](https://github.com/TanStack/router/pull/7373)) + +## 1.161.6 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +## 1.161.5 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) diff --git a/packages/start-fn-stubs/eslint.config.js b/packages/start-fn-stubs/eslint.config.js new file mode 100644 index 0000000000..f4c18ebca2 --- /dev/null +++ b/packages/start-fn-stubs/eslint.config.js @@ -0,0 +1,14 @@ +// @ts-check + +import rootConfig from '../../eslint.config.js' + +export default [ + ...rootConfig, + { + files: ['**/*.{ts,tsx}'], + }, + { + plugins: {}, + rules: {}, + }, +] diff --git a/packages/start-fn-stubs/package.json b/packages/start-fn-stubs/package.json new file mode 100644 index 0000000000..12621fefd7 --- /dev/null +++ b/packages/start-fn-stubs/package.json @@ -0,0 +1,67 @@ +{ + "name": "@tanstack/start-fn-stubs", + "version": "1.162.0", + "description": "Stub functions for TanStack Start isomorphic and environment-specific functions", + "author": "Tanner Linsley", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/TanStack/router.git", + "directory": "packages/start-fn-stubs" + }, + "homepage": "https://tanstack.com/start", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "keywords": [ + "tanstack", + "start", + "isomorphic", + "server", + "client" + ], + "scripts": { + "clean": "rimraf ./dist && rimraf ./coverage", + "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit", + "test:unit": "vitest", + "test:unit:dev": "vitest --watch", + "test:eslint": "eslint ./src", + "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", + "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", + "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", + "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", + "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", + "build": "vite build" + }, + "type": "module", + "types": "dist/esm/index.d.ts", + "exports": { + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + } + }, + "./package.json": "./package.json" + }, + "sideEffects": false, + "files": [ + "dist", + "src" + ], + "engines": { + "node": ">=22.12.0" + }, + "devDependencies": { + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" + } +} diff --git a/packages/start-fn-stubs/src/createIsomorphicFn.ts b/packages/start-fn-stubs/src/createIsomorphicFn.ts new file mode 100644 index 0000000000..695da54453 --- /dev/null +++ b/packages/start-fn-stubs/src/createIsomorphicFn.ts @@ -0,0 +1,67 @@ +// a function that can have different implementations on the client and server. +// implementations not provided will default to a no-op function. + +export type IsomorphicFn< + TArgs extends Array = [], + TServer = undefined, + TClient = undefined, +> = (...args: TArgs) => TServer | TClient + +export interface ServerOnlyFn< + TArgs extends Array, + TServer, +> extends IsomorphicFn { + client: ( + clientImpl: (...args: TArgs) => TClient, + ) => IsomorphicFn +} + +export interface ClientOnlyFn< + TArgs extends Array, + TClient, +> extends IsomorphicFn { + server: ( + serverImpl: (...args: TArgs) => TServer, + ) => IsomorphicFn +} + +export interface IsomorphicFnBase { + server: , TServer>( + serverImpl: (...args: TArgs) => TServer, + ) => ServerOnlyFn + client: , TClient>( + clientImpl: (...args: TArgs) => TClient, + ) => ClientOnlyFn +} + +// The Start compiler normally rewrites createIsomorphicFn() chains before they +// run. Some package tests/build steps execute this stub uncompiled though, for +// example while Vite loads server-side modules during a build. +// +// In those uncompiled contexts we need a real callable fallback, not just a +// chain-shaped object. These contexts are server-side, so once a .server() +// implementation is registered we keep using it even if .client() is chained +// later. Client bundles still get the correct client/no-op implementation +// because the compiler rewrites the original call chain before runtime. +export function createIsomorphicFn(): IsomorphicFnBase { + return createRuntimeFn(() => undefined) as any +} + +type RuntimeFallbackFn = (() => any) & { + server: (serverImpl: () => any) => RuntimeFallbackFn + client: (clientImpl: () => any) => RuntimeFallbackFn +} + +function createRuntimeFn( + fn: () => any, + serverImpl?: () => any, +): RuntimeFallbackFn { + return Object.assign(fn, { + server: (nextServerImpl: () => any) => { + return createRuntimeFn(nextServerImpl, nextServerImpl) + }, + client: (clientImpl: () => any) => { + return createRuntimeFn(serverImpl ?? clientImpl, serverImpl) + }, + }) +} diff --git a/packages/start-client-core/src/envOnly.ts b/packages/start-fn-stubs/src/envOnly.ts similarity index 100% rename from packages/start-client-core/src/envOnly.ts rename to packages/start-fn-stubs/src/envOnly.ts diff --git a/packages/start-fn-stubs/src/index.ts b/packages/start-fn-stubs/src/index.ts new file mode 100644 index 0000000000..5ca646d9d1 --- /dev/null +++ b/packages/start-fn-stubs/src/index.ts @@ -0,0 +1,9 @@ +export { + createIsomorphicFn, + type IsomorphicFn, + type ServerOnlyFn, + type ClientOnlyFn, + type IsomorphicFnBase, +} from './createIsomorphicFn' + +export { createServerOnlyFn, createClientOnlyFn } from './envOnly' diff --git a/packages/start-client-core/src/tests/createIsomorphicFn.test-d.ts b/packages/start-fn-stubs/tests/createIsomorphicFn.test-d.ts similarity index 93% rename from packages/start-client-core/src/tests/createIsomorphicFn.test-d.ts rename to packages/start-fn-stubs/tests/createIsomorphicFn.test-d.ts index 89f427d8c6..bb75a6311b 100644 --- a/packages/start-client-core/src/tests/createIsomorphicFn.test-d.ts +++ b/packages/start-fn-stubs/tests/createIsomorphicFn.test-d.ts @@ -1,12 +1,9 @@ import { expectTypeOf, test } from 'vitest' -import { createIsomorphicFn } from '../createIsomorphicFn' +import { createIsomorphicFn } from '../src/createIsomorphicFn' test('createIsomorphicFn with no implementations', () => { const fn = createIsomorphicFn() - expectTypeOf(fn).toBeCallableWith() - expectTypeOf(fn).returns.toBeUndefined() - expectTypeOf(fn).toHaveProperty('server') expectTypeOf(fn).toHaveProperty('client') }) diff --git a/packages/start-fn-stubs/tests/createIsomorphicFn.test.ts b/packages/start-fn-stubs/tests/createIsomorphicFn.test.ts new file mode 100644 index 0000000000..23e97908e6 --- /dev/null +++ b/packages/start-fn-stubs/tests/createIsomorphicFn.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { createIsomorphicFn } from '../src/createIsomorphicFn' + +describe('createIsomorphicFn runtime fallback', () => { + it('returns a callable server implementation', () => { + const fn = createIsomorphicFn().server(() => 'server') + + expect(fn()).toBe('server') + }) + + it('prefers the server implementation when both implementations are registered', () => { + const fn = createIsomorphicFn() + .server(() => 'server') + .client(() => 'client') + + expect(fn()).toBe('server') + }) + + it('returns a callable client-only implementation', () => { + const fn = createIsomorphicFn().client(() => 'client') + + expect(fn()).toBe('client') + }) +}) diff --git a/packages/start-client-core/src/tests/envOnly.test-d.ts b/packages/start-fn-stubs/tests/envOnly.test-d.ts similarity index 94% rename from packages/start-client-core/src/tests/envOnly.test-d.ts rename to packages/start-fn-stubs/tests/envOnly.test-d.ts index 4a47ddf946..dd83e4f561 100644 --- a/packages/start-client-core/src/tests/envOnly.test-d.ts +++ b/packages/start-fn-stubs/tests/envOnly.test-d.ts @@ -1,5 +1,5 @@ import { expectTypeOf, test } from 'vitest' -import { createClientOnlyFn, createServerOnlyFn } from '../envOnly' +import { createClientOnlyFn, createServerOnlyFn } from '../src/envOnly' const inputFn = () => 'output' diff --git a/packages/start-fn-stubs/tsconfig.build.json b/packages/start-fn-stubs/tsconfig.build.json new file mode 100644 index 0000000000..92be18587f --- /dev/null +++ b/packages/start-fn-stubs/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src" + }, + "include": ["src"] +} diff --git a/packages/start-fn-stubs/tsconfig.json b/packages/start-fn-stubs/tsconfig.json new file mode 100644 index 0000000000..0484835e6b --- /dev/null +++ b/packages/start-fn-stubs/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "module": "esnext" + }, + "include": ["src", "vite.config.ts"] +} diff --git a/packages/start-fn-stubs/vite.config.ts b/packages/start-fn-stubs/vite.config.ts new file mode 100644 index 0000000000..f1d7dfe7ca --- /dev/null +++ b/packages/start-fn-stubs/vite.config.ts @@ -0,0 +1,21 @@ +import { defineConfig, mergeConfig } from 'vitest/config' +import { tanstackViteConfig } from '@tanstack/vite-config' +import packageJson from './package.json' + +const config = defineConfig({ + test: { + typecheck: { enabled: true }, + name: packageJson.name, + watch: false, + }, +}) + +export default mergeConfig( + config, + tanstackViteConfig({ + tsconfigPath: './tsconfig.build.json', + srcDir: './src', + entry: './src/index.ts', + cjs: false, + }), +) diff --git a/packages/start-plugin-core/AGENTS.md b/packages/start-plugin-core/AGENTS.md new file mode 100644 index 0000000000..cd73bbf307 --- /dev/null +++ b/packages/start-plugin-core/AGENTS.md @@ -0,0 +1,7 @@ +# Start compiler and bundler integration + +- Virtual prefixes and query parameters can be part of a module's identity. Preserve them in resolution, loading, and module-cache keys; use `cleanId` only for physical-file matching, diagnostics, and file invalidation. Load compiler dependencies through the bundler host. +- For import-protection changes, read the [shared internals](src/import-protection/INTERNALS.md) and [Vite lifecycle](src/vite/import-protection-plugin/INTERNALS.md). Preserve adapter-specific deferral and survival checks; development has no build-time tree-shaking, and Vite's error/mock modes differ. Cover actual leaks and safe boundaries in cold/warm development and builds. +- Compiler output must match runtime contracts in `start-client-core`, `start-fn-stubs`, and `start-server-core`. For `createServerFn`, cover client, SSR caller, and server-provider output separately in [`tests/createServerFn/createServerFn.test.ts`](tests/createServerFn/createServerFn.test.ts). +- Use a built Start e2e app to validate generated imports and runtime behavior together; compiler snapshots alone do not exercise that integration. +- The shared compiler serves both Vite and Rsbuild. For shared compiler changes, check the relevant adapter suites in `tests/vite/` and `tests/rsbuild/`, plus affected Start e2e modes for build, server-function, or HMR behavior. diff --git a/packages/start-plugin-core/CHANGELOG.md b/packages/start-plugin-core/CHANGELOG.md new file mode 100644 index 0000000000..3d705069c1 --- /dev/null +++ b/packages/start-plugin-core/CHANGELOG.md @@ -0,0 +1,1315 @@ +# @tanstack/start-plugin-core + +## 1.171.57 + +### Patch Changes + +- [#8889](https://github.com/TanStack/router/pull/8889) [`3f22686`](https://github.com/TanStack/router/commit/3f226869e0af211ff7f1de5d7343e43462dbb101) - fix: Rsbuild dev SSR now includes stylesheet links when the server environment runs outside the build process, such as in workerd with `rsbuild-plugin-cloudflare`. The dev manifest is written into the server's manifest module instead of being stored on the build process's `globalThis`. + +- [#8892](https://github.com/TanStack/router/pull/8892) [`559c7de`](https://github.com/TanStack/router/commit/559c7ded6e2a6eeda3f91c80d8c03f4cfeb9a206) - fix: Rsbuild dev with React Server Components includes stylesheet links in SSR again. The client and server compile concurrently, so the server's manifest module is now rebuilt once the client build is available, as in production builds. + +## 1.171.56 + +### Patch Changes + +- [#8863](https://github.com/TanStack/router/pull/8863) [`01fab5a`](https://github.com/TanStack/router/commit/01fab5a6c8aed70d61d82c64bc344cbac66c240c) - The Rsbuild plugin keeps the app's `server.compress` setting instead of always setting it to `false`. Compression stays off by default: a compressed streamed page reaches the browser only once the stream ends. The optional `@rsbuild/core` peer is now `^2.0.5`, the first version whose compression keeps SSR response headers intact. + +- [#8805](https://github.com/TanStack/router/pull/8805) [`c5320d7`](https://github.com/TanStack/router/commit/c5320d7ca23eca82d720ac5629d2bad5cf7d9b02) - With `spa.enabled`, the Rsbuild dev server answers the SPA shell, as Vite's dev server does, instead of rendering the route and running its loaders on the server. + +- [#8871](https://github.com/TanStack/router/pull/8871) [`545a8d3`](https://github.com/TanStack/router/commit/545a8d3790989ca502153c3292c6b1e8063257f4) - Require `exsolve` `^1.1.3`: a failed lookup that exsolve caches no longer keeps its callers alive, so Start's cached failed lookups no longer hold on to each build's objects. Entry lookups bypass exsolve's process-wide cache, so a dev server restart finds an entry file (such as `src/start.ts`) created since. + +- [#8861](https://github.com/TanStack/router/pull/8861) [`da8c28c`](https://github.com/TanStack/router/commit/da8c28c498230a5730ce75b2693baeeb3ef68ac1) - Start's router options now reach the route generator and the code splitter as they do in a router app: + - Generator plugins given as `router.plugins` run ([#7768](https://github.com/TanStack/router/issues/7768)). Start's own generator plugins used to replace them. + - A function-form `router.routeTreeFileFooter` is called at every print of the route tree. Start's Vite plugin used to print its first result for the whole dev server. + - Start's Rsbuild plugin keeps `router.codeSplittingOptions.deleteNodes` for the server build. It used to drop the option there. + - Start's Vite plugin finds the client route tree by its exact module id ([#8839](https://github.com/TanStack/router/issues/8839)). With a regular-expression character in the project path, such as `+`, the client used to get the full route tree, server-only routes included; a file whose name differed from the route tree's by one character (`routeTree-gen.ts`) was replaced by the client route tree. + +- Updated dependencies [[`1ba19a0`](https://github.com/TanStack/router/commit/1ba19a04456983ee0f8adffd038b6b1194441e15), [`94f36c4`](https://github.com/TanStack/router/commit/94f36c4a9ecf3062b326a8eb772e73b00c0644d9), [`446ce1b`](https://github.com/TanStack/router/commit/446ce1b30650d85f1fc78f2d1ee42712e40b75c6), [`ad5b3b7`](https://github.com/TanStack/router/commit/ad5b3b7a0990eed7351d672ea6695d341108e0d6), [`533ca27`](https://github.com/TanStack/router/commit/533ca2704452f36c5fef5c5fe084554d9b5db1ab), [`13b6256`](https://github.com/TanStack/router/commit/13b625683030ea4ab359495ecda570e05e472587), [`b5e2ac9`](https://github.com/TanStack/router/commit/b5e2ac9c4cee4c5c6f464adc6cfddcddf6c84171), [`d250819`](https://github.com/TanStack/router/commit/d25081952dd04a5f5a44db7c8df5cbbf50fad054), [`f420d4a`](https://github.com/TanStack/router/commit/f420d4a6dacfaa81d306b7bbc9af8f1010d1a1bc), [`ff157f0`](https://github.com/TanStack/router/commit/ff157f0079982e90d62be7fdeecfb77e4fdcec69)]: + - @tanstack/router-plugin@1.169.0 + - @tanstack/router-generator@1.168.0 + - @tanstack/router-utils@1.163.0 + +## 1.171.55 + +### Patch Changes + +- [#8748](https://github.com/TanStack/router/pull/8748) [`ed55775`](https://github.com/TanStack/router/commit/ed5577593a749b8c7193cc7b5d945fd084bfac2f) - Skip the Rsbuild import-protection loader and its plugins when import protection is disabled, so modules no longer pass through the loader. + +- [#8750](https://github.com/TanStack/router/pull/8750) [`63a886d`](https://github.com/TanStack/router/commit/63a886da9040c4b039ea3bf5b3a841771375cddb) - Skip the server function resolver rebuild in Rsbuild dev when the resolver has not changed, so most edits no longer rebuild the whole server chunk graph. + +- [#8758](https://github.com/TanStack/router/pull/8758) [`d9b07e8`](https://github.com/TanStack/router/commit/d9b07e8d3b724cdbfac0aa2fba4c1f7a3a241100) - Stop resolving top-level calls such as `z.object()` whose receiver is not a namespace import. They can never be a `createServerOnlyFn` or `createClientOnlyFn` call, and resolving them made the dev compiler load and parse the receiver's module (all of zod, for example). + +- Updated dependencies [[`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c), [`647cb73`](https://github.com/TanStack/router/commit/647cb737a5622813d276d6042766692ca5ae67ed)]: + - @tanstack/router-core@1.171.39 + - @tanstack/router-plugin@1.168.48 + - @tanstack/start-server-core@1.169.45 + - @tanstack/router-generator@1.167.46 + +## 1.171.54 + +### Patch Changes + +- Updated dependencies [[`18154b1`](https://github.com/TanStack/router/commit/18154b1c45454a70aa77e9d6d27c8a6e0733d031)]: + - @tanstack/router-core@1.171.38 + - @tanstack/start-server-core@1.169.44 + - @tanstack/router-generator@1.167.45 + - @tanstack/router-plugin@1.168.47 + +## 1.171.53 + +### Patch Changes + +- [#8708](https://github.com/TanStack/router/pull/8708) [`fdc10fa`](https://github.com/TanStack/router/commit/fdc10fa13fbac758615f9a3d37075088d1cc1e1f) - Update `srvx` to `^1.0.0`. + +- Updated dependencies [[`71d9694`](https://github.com/TanStack/router/commit/71d9694da6346fbece2cda4ecde92b0b12a7ee08), [`923d98b`](https://github.com/TanStack/router/commit/923d98b18b6cd90b6219591e20e86115dc61048e)]: + - @tanstack/start-server-core@1.169.43 + - @tanstack/router-utils@1.162.4 + - @tanstack/router-generator@1.167.44 + - @tanstack/router-plugin@1.168.46 + +## 1.171.52 + +### Patch Changes + +- Updated dependencies [[`740b0ce`](https://github.com/TanStack/router/commit/740b0ce17737d1f7398740136acdbeabe80df7d8), [`d6ba115`](https://github.com/TanStack/router/commit/d6ba115d5751c75e20943f0062577cf17b446d82)]: + - @tanstack/start-server-core@1.169.42 + - @tanstack/router-core@1.171.37 + - @tanstack/router-generator@1.167.43 + - @tanstack/router-plugin@1.168.45 + +## 1.171.51 + +### Patch Changes + +- [#8694](https://github.com/TanStack/router/pull/8694) [`550f478`](https://github.com/TanStack/router/commit/550f47881070c0558a87e1acce7f38fbc85b9549) - Remove the deprecated `.inputValidator()` from `createServerFn` and `createMiddleware`. Use `.validator()`, which takes the same validator. + +- [#8692](https://github.com/TanStack/router/pull/8692) [`f3d7ee3`](https://github.com/TanStack/router/commit/f3d7ee3374c660e0fe82a03ac580a90ed2e2fa98) - Image and news sitemap entries are now emitted in their declared XML namespaces, so sitemaps with images or news are valid XML. + +- [#8695](https://github.com/TanStack/router/pull/8695) [`4104b8e`](https://github.com/TanStack/router/commit/4104b8ef11498706b5059c5a915f2ae47ffbc5ba) - Walk the static import graph when building route preloads so Rolldown and Rsbuild builds preload every dependency chunk, and derive Rsbuild chunk imports from the module graph so shared chunks no longer attach unrelated route CSS to the SSR response. + +- [#8696](https://github.com/TanStack/router/pull/8696) [`f243c61`](https://github.com/TanStack/router/commit/f243c61e95dae64fe04da4499c0c4ec44f26abae) - Require Vite 8 for Vite builds. Vite 7 is no longer supported. + +- [#8691](https://github.com/TanStack/router/pull/8691) [`19524cc`](https://github.com/TanStack/router/commit/19524ccdd75870ce1db2f324518eeb3f23cc0f97) - Publish only validated public page fields in pages.json and sitemap.xml so prerender headers and other private page data, including extra data returned by `prerender.onSuccess`, stay private. Invalid sitemap metadata returned by `prerender.onSuccess` now fails the build instead of being written to sitemap.xml without validation. + +- Updated dependencies [[`57bd1a9`](https://github.com/TanStack/router/commit/57bd1a92f9839af5bf773c3b36d039569fb1a41e), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`e66da18`](https://github.com/TanStack/router/commit/e66da18266859ab49e20a7b8c858232449ee5290), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5), [`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5)]: + - @tanstack/router-generator@1.167.42 + - @tanstack/router-core@1.171.36 + - @tanstack/start-server-core@1.169.41 + - @tanstack/router-plugin@1.168.44 + +## 1.171.50 + +### Patch Changes + +- [#7830](https://github.com/TanStack/router/pull/7830) [`4191640`](https://github.com/TanStack/router/commit/41916400b93fdb62189722266ed1d77ba9c26be9) - Fix dev SSR style collection to preserve CSS order without duplicating imported styles, while retaining styles from code-split routes. Keep layered imports from inline styles out of the global dev stylesheet. In bundled development, collect styles from a complete client bundle and load compiler dependencies through the bundler to avoid restarting client plugins. Preserve client hydration and reload SSR modules on file changes instead of clearing them on every request. + + Support newer Vite bundled dev versions by loading their separate client runtime before hydration and awaiting the client build through the updated environment API. + +- Updated dependencies [[`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`663282b`](https://github.com/TanStack/router/commit/663282b0ebbc494aee3595ed95867ee29d01938e)]: + - @tanstack/router-core@1.171.35 + - @tanstack/start-server-core@1.169.40 + - @tanstack/router-generator@1.167.41 + - @tanstack/router-plugin@1.168.43 + +## 1.171.49 + +### Patch Changes + +- [#8127](https://github.com/TanStack/router/pull/8127) [`41ebd28`](https://github.com/TanStack/router/commit/41ebd288677beacb8eb56953f5f8c26e9d33313e) - fix: use http scheme for sitemap xmlns per sitemaps.org spec + +- [#8533](https://github.com/TanStack/router/pull/8533) [`05223c2`](https://github.com/TanStack/router/commit/05223c2ada4d48af4b3881f10e3b6261898b2d40) - Defer sitemap and XML dependencies until sitemap generation is enabled to reduce Start plugin startup work. + +- Updated dependencies [[`d521abd`](https://github.com/TanStack/router/commit/d521abd71c69f1ff010bb3def4d417cb5fa058cb)]: + - @tanstack/router-core@1.171.34 + - @tanstack/start-server-core@1.169.39 + - @tanstack/router-generator@1.167.40 + - @tanstack/router-plugin@1.168.42 + +## 1.171.48 + +### Patch Changes + +- [#8297](https://github.com/TanStack/router/pull/8297) [`488d046`](https://github.com/TanStack/router/commit/488d046a907d330429e2c807ef95326dad87480f) - Update `seroval` and `seroval-plugins` from 1.6.2 to 1.6.7. This picks up the typed array length guard, the `maxBase64Length` and `compactArrayBufferViews` options, and the `isStream` export. + +- Updated dependencies [[`488d046`](https://github.com/TanStack/router/commit/488d046a907d330429e2c807ef95326dad87480f), [`e81845f`](https://github.com/TanStack/router/commit/e81845ff1e4fc66d4e4a87f086be65906f7adb94), [`0c1b5e3`](https://github.com/TanStack/router/commit/0c1b5e38de71b7e81bbf1fd81c73ee0cd68ffe47), [`3cdd1af`](https://github.com/TanStack/router/commit/3cdd1af04b3e2d6f777797ee7bddf285318dd9d2)]: + - @tanstack/router-core@1.171.33 + - @tanstack/start-server-core@1.169.38 + - @tanstack/router-generator@1.167.39 + - @tanstack/router-plugin@1.168.41 + +## 1.171.47 + +### Patch Changes + +- [#8202](https://github.com/TanStack/router/pull/8202) [`222300b`](https://github.com/TanStack/router/commit/222300b82fe6f2a5e7e7f460ae21a2e35c6230d7) - Fix the Rsbuild Start manifest dropping every route's stylesheets and preloads on Windows by normalizing rspack module paths to the POSIX form the generated route tree uses. + +## 1.171.46 + +### Patch Changes + +- Updated dependencies [[`cecae54`](https://github.com/TanStack/router/commit/cecae5440b8edaea77c5448fe3d74bbd20fe10a4), [`0103578`](https://github.com/TanStack/router/commit/01035782e53af9b929c784b94ddd64b95efb89c7), [`ce10dcd`](https://github.com/TanStack/router/commit/ce10dcd4d9d3d23738744e453205aad5c6dbd716), [`84936cc`](https://github.com/TanStack/router/commit/84936cc04530bba11059c57b293a794922bbc5aa), [`bbd2336`](https://github.com/TanStack/router/commit/bbd2336b8446de3f7dd85070895e7cf43980183e)]: + - @tanstack/router-core@1.171.32 + - @tanstack/router-generator@1.167.38 + - @tanstack/router-plugin@1.168.40 + - @tanstack/start-server-core@1.169.37 + +## 1.171.45 + +### Patch Changes + +- [#8204](https://github.com/TanStack/router/pull/8204) [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26) - Reduce per-request SSR overhead: abort settled route matches with one shared `AbortError`-shaped reason instead of building a stack-capturing `DOMException` per match, skip `JSON.parse` for search values that cannot start JSON, wait on request signals with one listener per wait, and keep resolved server-function modules in production builds instead of re-importing them on every call. + +- Updated dependencies [[`bc80866`](https://github.com/TanStack/router/commit/bc80866f6d6eb3e6f152ee3682eb783c96403e83), [`e561fa1`](https://github.com/TanStack/router/commit/e561fa1d7118e3d29267cc3b6ce1130d6581f387), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a1c8d1a`](https://github.com/TanStack/router/commit/a1c8d1aa759c227eae9601a030321ac4c53c24bd), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a0b2ad9`](https://github.com/TanStack/router/commit/a0b2ad99aee64af08d16b0e4ff26b3ba42a99f0a), [`1ca361b`](https://github.com/TanStack/router/commit/1ca361ba52a627d2f76ab33323bd83d1d0aa65a3)]: + - @tanstack/router-core@1.171.31 + - @tanstack/start-server-core@1.169.36 + - @tanstack/router-generator@1.167.37 + - @tanstack/router-plugin@1.168.39 + +## 1.171.44 + +### Patch Changes + +- [#8397](https://github.com/TanStack/router/pull/8397) [`ab99818`](https://github.com/TanStack/router/commit/ab99818225835a1553a9f3513cd2093ff1b257be) - Support Rsbuild 2.2: preserve function-based Rspack watch exclusions and regular-expression flags when adding monorepo build-output exclusions, and leave string-valued Babel loader options intact in the Solid Start plugin. + +## 1.171.43 + +### Patch Changes + +- Updated dependencies [[`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776), [`6cfb1e8`](https://github.com/TanStack/router/commit/6cfb1e8b564be282584765352250bf61747895ed), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`873c830`](https://github.com/TanStack/router/commit/873c830ccb2610a864ee697250e10fcc99772ffa), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`f151ab0`](https://github.com/TanStack/router/commit/f151ab018eede64ae849b77e68f3cdf31cb95cc5), [`bc57fa3`](https://github.com/TanStack/router/commit/bc57fa3f12450cf34c731450947c7c8f1ea05e58), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9448caa`](https://github.com/TanStack/router/commit/9448caa03a89076b9770631c356c0cc502802c09), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef)]: + - @tanstack/router-core@1.171.30 + - @tanstack/start-server-core@1.169.35 + - @tanstack/router-generator@1.167.36 + - @tanstack/router-plugin@1.168.38 + +## 1.171.42 + +### Patch Changes + +- Updated dependencies [[`d914b08`](https://github.com/TanStack/router/commit/d914b085bb4bf29ec18a531201e377c10681b661)]: + - @tanstack/start-server-core@1.169.34 + - @tanstack/router-generator@1.167.35 + +## 1.171.41 + +### Patch Changes + +- [#8300](https://github.com/TanStack/router/pull/8300) [`49bcd4d`](https://github.com/TanStack/router/commit/49bcd4db743dba4a783d5533a42a0f97a5721292) - Refresh compatible build and runtime dependencies. + +- [#8308](https://github.com/TanStack/router/pull/8308) [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8) - Validate navigation and redirect destinations, keep ambiguous relative URLs on the current origin, and constrain prerender requests and output paths. Prevent redirect headers from appearing in serialized server function response bodies. + + Preserve native form HTTP redirects, route error handling and masks for document redirects, and per-navigation destinations for shared loader redirects. Avoid redundant origin parsing and reduce link styling and server-rendering work. Configured origins must already be normalized. + + Keep blocked-link inactive props consistent during React hydration, honor explicit redirect Location headers before checking route options, and refresh Vue link state when destinations become internal. Reuse the protocol-relative URL check while parsing redirect schemes once. + + Reduce React link bundle size by sharing pathname comparisons, state-prop selection, and element creation. + + Share normalized pathname comparisons in Solid and Vue links to reduce bundle size. + +- [#8261](https://github.com/TanStack/router/pull/8261) [`919c397`](https://github.com/TanStack/router/commit/919c3971493374cccc963e75b9b2a4e98ebf878a) - Avoid unused build indexes and skip CSS content capture when inline CSS is disabled in Vite and Rsbuild. + +- Updated dependencies [[`f9836f1`](https://github.com/TanStack/router/commit/f9836f16f0e25b0a8495f5e01e3f303b1cbc8725), [`49bcd4d`](https://github.com/TanStack/router/commit/49bcd4db743dba4a783d5533a42a0f97a5721292), [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8), [`9871c06`](https://github.com/TanStack/router/commit/9871c0625806001d6bf373524821a00303438a91), [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9)]: + - @tanstack/router-core@1.171.29 + - @tanstack/router-plugin@1.168.37 + - @tanstack/router-generator@1.167.35 + - @tanstack/router-utils@1.162.3 + - @tanstack/start-server-core@1.169.33 + +## 1.171.40 + +### Patch Changes + +- [#8164](https://github.com/TanStack/router/pull/8164) [`37877da`](https://github.com/TanStack/router/commit/37877da166fe4ce055c7b85e138b6681ebd7e8b4) - Improve Rsbuild import protection performance by scanning the compilation graph once and deferring diagnostic work until a violation is found. + +- [#8251](https://github.com/TanStack/router/pull/8251) [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b) - Use URL.canParse for absolute URL checks in links, navigation, redirects, and build configuration. Preserve a URL constructor fallback for older browsers. + +- Updated dependencies [[`edf0e16`](https://github.com/TanStack/router/commit/edf0e16ebfe82ec6e8f68f403a1fda8de9e28889), [`2f20c00`](https://github.com/TanStack/router/commit/2f20c00224c5ba63467551914e0c37012588c4c2), [`28a5e45`](https://github.com/TanStack/router/commit/28a5e4504e4ea5cb1480667a4bea2588a53e110f), [`08eff50`](https://github.com/TanStack/router/commit/08eff50c447a154a3373909009e9e4375cea17ce), [`216c0c4`](https://github.com/TanStack/router/commit/216c0c48036fd1a33163b70dcabfed2b893808b0), [`2f91503`](https://github.com/TanStack/router/commit/2f9150309bc472f4a75cbe98adcdb50c76b12c7a), [`f0b5eda`](https://github.com/TanStack/router/commit/f0b5eda544606686a8a8d675a686ca1366428b96), [`50eafca`](https://github.com/TanStack/router/commit/50eafcaebbbedb6fde3b2816de7a0ace8cde4832), [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b), [`ee28348`](https://github.com/TanStack/router/commit/ee283480dfa51150a2e0b096a6eff94a89ff8b3f), [`c18e690`](https://github.com/TanStack/router/commit/c18e69081475a7c98f9d40bd0fe6da78ccb84598)]: + - @tanstack/router-core@1.171.28 + - @tanstack/router-generator@1.167.34 + - @tanstack/router-plugin@1.168.36 + - @tanstack/start-server-core@1.169.32 + +## 1.171.39 + +### Patch Changes + +- [#8135](https://github.com/TanStack/router/pull/8135) [`a0041bb`](https://github.com/TanStack/router/commit/a0041bb36e700b3263b894e4d1573d924383b56b) - Migrate the Rsbuild client chunk configuration to the v2 `splitChunks` option while preserving async-only chunk splitting. + +- Updated dependencies [[`fa65287`](https://github.com/TanStack/router/commit/fa652872812c9433ba8b9d9a285e51b535e7367c), [`cb281d7`](https://github.com/TanStack/router/commit/cb281d70c1f5fe780f9d07bc500ea3a284a4e04b)]: + - @tanstack/router-core@1.171.27 + - @tanstack/router-generator@1.167.33 + - @tanstack/router-plugin@1.168.35 + - @tanstack/start-server-core@1.169.31 + +## 1.171.38 + +### Patch Changes + +- Updated dependencies [[`3e016ac`](https://github.com/TanStack/router/commit/3e016ac84ffec8119f0c25cfdd1fb17e5292bd34)]: + - @tanstack/router-core@1.171.26 + - @tanstack/router-generator@1.167.32 + - @tanstack/router-plugin@1.168.34 + - @tanstack/start-server-core@1.169.30 + +## 1.171.37 + +### Patch Changes + +- Updated dependencies [[`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175), [`63d2cc9`](https://github.com/TanStack/router/commit/63d2cc9155ff5374112f7d067d0b278bafeb8486)]: + - @tanstack/router-core@1.171.25 + - @tanstack/router-generator@1.167.31 + - @tanstack/router-plugin@1.168.33 + - @tanstack/start-server-core@1.169.29 + +## 1.171.36 + +### Patch Changes + +- Updated dependencies [[`4c89b15`](https://github.com/TanStack/router/commit/4c89b15dd2b46491ee5e57985559bae8e31d62c2), [`cf6ab17`](https://github.com/TanStack/router/commit/cf6ab178b39e7628bf784759f384e0f4230e6d9e), [`bdaf73a`](https://github.com/TanStack/router/commit/bdaf73a4063ee2b02e3c9cc105ad10ce82a5a0ff)]: + - @tanstack/router-core@1.171.24 + - @tanstack/router-generator@1.167.30 + - @tanstack/router-plugin@1.168.32 + - @tanstack/start-server-core@1.169.28 + +## 1.171.35 + +### Patch Changes + +- Updated dependencies [[`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90)]: + - @tanstack/router-core@1.171.23 + - @tanstack/router-generator@1.167.29 + - @tanstack/router-plugin@1.168.31 + - @tanstack/start-server-core@1.169.27 + +## 1.171.34 + +### Patch Changes + +- Updated dependencies [[`7e93431`](https://github.com/TanStack/router/commit/7e93431ae9ff58c91c3c5ca10ffcb8414c1d0b13)]: + - @tanstack/router-core@1.171.22 + - @tanstack/router-generator@1.167.28 + - @tanstack/router-plugin@1.168.30 + - @tanstack/start-server-core@1.169.26 + +## 1.171.33 + +### Patch Changes + +- Updated dependencies [[`51138a8`](https://github.com/TanStack/router/commit/51138a824cea053738f125c4c95073bd6286ff05)]: + - @tanstack/router-core@1.171.21 + - @tanstack/router-generator@1.167.27 + - @tanstack/router-plugin@1.168.29 + - @tanstack/start-server-core@1.169.25 + +## 1.171.32 + +### Patch Changes + +- Updated dependencies [[`44a8c3e`](https://github.com/TanStack/router/commit/44a8c3e1d2af305064b2363d97fc7847c6f1a246), [`5253e70`](https://github.com/TanStack/router/commit/5253e70db2083d68a788fb7c9a043bb0c5518f2a)]: + - @tanstack/router-core@1.171.20 + - @tanstack/router-generator@1.167.26 + - @tanstack/router-plugin@1.168.28 + - @tanstack/start-server-core@1.169.24 + +## 1.171.31 + +### Patch Changes + +- Updated dependencies []: + - @tanstack/start-server-core@1.169.23 + - @tanstack/router-generator@1.167.25 + +## 1.171.30 + +### Patch Changes + +- Updated dependencies [[`ea3a665`](https://github.com/TanStack/router/commit/ea3a665d81cbb5074c2d77ec953255ab534e7db9)]: + - @tanstack/router-core@1.171.19 + - @tanstack/router-generator@1.167.25 + - @tanstack/router-plugin@1.168.27 + - @tanstack/start-server-core@1.169.22 + +## 1.171.29 + +### Patch Changes + +- Updated dependencies [[`84db4a8`](https://github.com/TanStack/router/commit/84db4a842311df3f7e58073f6f12aaf371aeb5c7), [`9cac62a`](https://github.com/TanStack/router/commit/9cac62a5c7f99ef070991ea6f1fa7e42c746d46b), [`6aefb33`](https://github.com/TanStack/router/commit/6aefb3392595a07a93f89301d7b5e3558ff9190c)]: + - @tanstack/router-core@1.171.18 + - @tanstack/start-server-core@1.169.21 + - @tanstack/router-generator@1.167.24 + - @tanstack/router-plugin@1.168.26 + +## 1.171.28 + +### Patch Changes + +- [#7962](https://github.com/TanStack/router/pull/7962) [`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5) - Update Seroval dependencies to version 1.6.2. + +- Updated dependencies [[`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5)]: + - @tanstack/router-core@1.171.17 + - @tanstack/start-server-core@1.169.20 + - @tanstack/router-generator@1.167.23 + - @tanstack/router-plugin@1.168.25 + +## 1.171.27 + +### Patch Changes + +- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: + - @tanstack/router-core@1.171.16 + - @tanstack/router-generator@1.167.22 + - @tanstack/router-plugin@1.168.24 + - @tanstack/start-server-core@1.169.19 + +## 1.171.26 + +### Patch Changes + +- [#7944](https://github.com/TanStack/router/pull/7944) [`65f7b7f`](https://github.com/TanStack/router/commit/65f7b7f791272f2ea581a1fe0fcd43183bc01162) - Use focused server entrypoints for shared constants and handler helpers so build tooling and framework renderers do not traverse the full Start server barrel. + +- Updated dependencies [[`65f7b7f`](https://github.com/TanStack/router/commit/65f7b7f791272f2ea581a1fe0fcd43183bc01162)]: + - @tanstack/start-server-core@1.169.18 + +## 1.171.25 + +### Patch Changes + +- [#7590](https://github.com/TanStack/router/pull/7590) [`7592555`](https://github.com/TanStack/router/commit/7592555b86c968efbc8c817ac0cf6fdae60aabe0) - Fix Rsbuild SSR asset URLs for `?url` imports by aligning server public asset paths with the client build. + +## 1.171.24 + +### Patch Changes + +- Updated dependencies [[`49f6863`](https://github.com/TanStack/router/commit/49f686324574ea65851317cbba084eb386a911c6)]: + - @tanstack/router-plugin@1.168.23 + +## 1.171.23 + +### Patch Changes + +- [#7844](https://github.com/TanStack/router/pull/7844) [`ffdd64e`](https://github.com/TanStack/router/commit/ffdd64e842acacbc9d368a4803a9e474e9f0c0ff) - Preserve exact Vite-resolved module IDs, including virtual prefixes and query variants, when the Start compiler recursively loads imports. Clean IDs only for file-oriented diagnostics and invalidation, and preserve existing query strings when adding compiler-owned lookup flags, so virtual modules such as import-protection mocks reach their plugin load hooks unchanged. + +## 1.171.22 + +### Patch Changes + +- Updated dependencies [[`78dd1a6`](https://github.com/TanStack/router/commit/78dd1a645dc1a9e9f4f649d9aff12005044d4fcc)]: + - @tanstack/router-generator@1.167.21 + - @tanstack/router-plugin@1.168.22 + +## 1.171.21 + +### Patch Changes + +- Updated dependencies [[`e56a677`](https://github.com/TanStack/router/commit/e56a67742da9021b009b8db0cdc8bfe99878c25b)]: + - @tanstack/router-generator@1.167.20 + - @tanstack/router-plugin@1.168.21 + +## 1.171.20 + +### Patch Changes + +- Updated dependencies [[`e2dd204`](https://github.com/TanStack/router/commit/e2dd2049cb42eb219d3b447b8605066d19d9c1fa)]: + - @tanstack/router-core@1.171.15 + - @tanstack/router-generator@1.167.19 + - @tanstack/router-plugin@1.168.20 + - @tanstack/start-server-core@1.169.17 + +## 1.171.19 + +### Patch Changes + +- Updated dependencies [[`9809a06`](https://github.com/TanStack/router/commit/9809a0619d4ed3fe8c2a393af5b9eca4b6c7695b)]: + - @tanstack/router-core@1.171.14 + - @tanstack/router-generator@1.167.18 + - @tanstack/router-plugin@1.168.19 + - @tanstack/start-server-core@1.169.16 + +## 1.171.18 + +### Patch Changes + +- [#7372](https://github.com/TanStack/router/pull/7372) [`e499164`](https://github.com/TanStack/router/commit/e499164c722841271af4aa2215483476bdb94c94) - Fix Rsbuild preview support for TanStack Start SSR. Preview always installs the SSR middleware; the `installDevServerMiddleware` option only applies to dev. + +- Updated dependencies [[`96eca43`](https://github.com/TanStack/router/commit/96eca43ab8ee21917a8075521bef6dcf15fc7a43)]: + - @tanstack/start-server-core@1.169.15 + - @tanstack/router-generator@1.167.17 + +## 1.171.17 + +### Patch Changes + +- [#7566](https://github.com/TanStack/router/pull/7566) [`9bebf8d`](https://github.com/TanStack/router/commit/9bebf8dc9f2bf74b680c065a5aa63d03b9622825) - Add `validator()` as the canonical server function and middleware validator method. Deprecate `inputValidator()` and emit compiler warnings for remaining uses. + +- Updated dependencies []: + - @tanstack/start-server-core@1.169.14 + +## 1.171.16 + +### Patch Changes + +- Updated dependencies [[`776d8ef`](https://github.com/TanStack/router/commit/776d8ef283e5bd9ffe97d43bc3a7f58064cd7e03)]: + - @tanstack/router-core@1.171.13 + - @tanstack/router-generator@1.167.17 + - @tanstack/router-plugin@1.168.18 + - @tanstack/start-server-core@1.169.13 + +## 1.171.15 + +### Patch Changes + +- Updated dependencies [[`df1076c`](https://github.com/TanStack/router/commit/df1076c03ae5a51ab384bebd4d6afda20fb6f107), [`837897f`](https://github.com/TanStack/router/commit/837897f0733b836dd63880546eec4c20cf06be59)]: + - @tanstack/router-core@1.171.12 + - @tanstack/router-plugin@1.168.17 + - @tanstack/router-generator@1.167.16 + - @tanstack/start-server-core@1.169.12 + +## 1.171.14 + +### Patch Changes + +- Updated dependencies [[`ac10815`](https://github.com/TanStack/router/commit/ac10815f387d25b15163ff711b4049e8f8482d01)]: + - @tanstack/router-core@1.171.11 + - @tanstack/router-generator@1.167.15 + - @tanstack/router-plugin@1.168.16 + - @tanstack/start-server-core@1.169.11 + +## 1.171.13 + +### Patch Changes + +- [#7552](https://github.com/TanStack/router/pull/7552) [`301f6ba`](https://github.com/TanStack/router/commit/301f6ba4599386edd6fb3b8423938c48eedb501f) - Fix Start compiler handling for TS-wrapped server/env-only function calls and safely remove unused imported server function handlers from client output. + +- Updated dependencies [[`301f6ba`](https://github.com/TanStack/router/commit/301f6ba4599386edd6fb3b8423938c48eedb501f), [`2cca73c`](https://github.com/TanStack/router/commit/2cca73c92262ffd96dac4e283c9f69fb37f4b43a), [`7a83e67`](https://github.com/TanStack/router/commit/7a83e67e6596fbef21cb0a88a7127f5935bed2ba), [`76b3d3b`](https://github.com/TanStack/router/commit/76b3d3b24522bd3d1d216674c441252c9b8f184c)]: + - @tanstack/router-utils@1.162.2 + - @tanstack/router-core@1.171.10 + - @tanstack/router-generator@1.167.14 + - @tanstack/router-plugin@1.168.15 + - @tanstack/start-server-core@1.169.10 + +## 1.171.12 + +### Patch Changes + +- [#7540](https://github.com/TanStack/router/pull/7540) [`8091918`](https://github.com/TanStack/router/commit/80919186cbdd0deb948b46fe328881a14a08f414) - Fix Rsbuild RSC builds so client directives in packages under `node_modules` are compiled and detected correctly. + +## 1.171.11 + +### Patch Changes + +- Updated dependencies [[`b4cd5af`](https://github.com/TanStack/router/commit/b4cd5af8d0f9d4aaa2d29095e6a261b9181bc778)]: + - @tanstack/router-core@1.171.9 + - @tanstack/router-generator@1.167.13 + - @tanstack/router-plugin@1.168.14 + - @tanstack/start-client-core@1.170.7 + - @tanstack/start-server-core@1.169.9 + +## 1.171.10 + +### Patch Changes + +- [#7509](https://github.com/TanStack/router/pull/7509) [`9cb7a00`](https://github.com/TanStack/router/commit/9cb7a003e6e5fa3706711870c7b10a5266356e3b) - feat(rsbuild): add RSC support + +- Updated dependencies [[`9cb7a00`](https://github.com/TanStack/router/commit/9cb7a003e6e5fa3706711870c7b10a5266356e3b)]: + - @tanstack/start-server-core@1.169.8 + +## 1.171.9 + +### Patch Changes + +- Updated dependencies [[`2f53749`](https://github.com/TanStack/router/commit/2f5374945e2138559a51464f45a5152eae67e1dd)]: + - @tanstack/router-core@1.171.8 + - @tanstack/router-generator@1.167.12 + - @tanstack/router-plugin@1.168.13 + - @tanstack/start-client-core@1.170.6 + - @tanstack/start-server-core@1.169.7 + +## 1.171.8 + +### Patch Changes + +- Updated dependencies [[`d1997b6`](https://github.com/TanStack/router/commit/d1997b66d7c24c1d64772bb8bab5caf9c6d9cc48)]: + - @tanstack/start-server-core@1.169.6 + - @tanstack/router-core@1.171.7 + - @tanstack/router-generator@1.167.11 + - @tanstack/router-plugin@1.168.12 + - @tanstack/start-client-core@1.170.5 + +## 1.171.7 + +### Patch Changes + +- [#7501](https://github.com/TanStack/router/pull/7501) [`9c09bca`](https://github.com/TanStack/router/commit/9c09bca59e9613e9a6fd9b7149b0737898e705d6) - fix(start): emit client entry scripts from the root route manifest. When `scriptFormat: 'iife'` and the entry chunk has static-import siblings (e.g. an extracted runtime via `optimization.runtimeChunk: 'single'`), the manifest now includes those async siblings before the async client entry in root route scripts, fixing hydration for IIFE bundles with extracted runtimes. + +- Updated dependencies [[`9c09bca`](https://github.com/TanStack/router/commit/9c09bca59e9613e9a6fd9b7149b0737898e705d6)]: + - @tanstack/start-server-core@1.169.5 + +## 1.171.6 + +### Patch Changes + +- Fix serialization adapter module resolution in TanStack Start. Vite dev now uses clean runtime-specific virtual module IDs instead of browser requests containing encoded null-byte virtual IDs, which avoids reverse proxy failures. When no serialization adapters are configured, Vite and Rsbuild now resolve `#tanstack-start-plugin-adapters` through the package empty-adapter fallback. ([#7484](https://github.com/TanStack/router/pull/7484)) + +- Publish matching TanStack Start dev server packages so fresh installs do not pair a Start plugin that no longer provides `tanstack-start-injected-head-scripts:v` with an older Start server runtime that still imports it. ([#7487](https://github.com/TanStack/router/pull/7487)) + +- Updated dependencies [[`a82cec6`](https://github.com/TanStack/router/commit/a82cec69474c366b36efdb3f43c4efe8311c485a), [`d8be4f8`](https://github.com/TanStack/router/commit/d8be4f8adf912128c96b7f83e9a6c49fb24b5eed)]: + - @tanstack/start-client-core@1.170.4 + - @tanstack/start-server-core@1.169.4 + +## 1.171.5 + +### Patch Changes + +- Add Vite bundled dev mode support for TanStack Start. Start now recognizes Vite's `experimental.bundledDev` opt-in, uses the bundled dev client entry in the dev manifest, keeps server requests pointed at the latest client build output, and preserves import-protection behavior for bundled client dev. ([#7482](https://github.com/TanStack/router/pull/7482)) + +## 1.171.4 + +### Patch Changes + +- Add support for Rsbuild client output formats, including module output by default and IIFE output for classic script environments. ([#7477](https://github.com/TanStack/router/pull/7477)) + + Client entry scripts and preloads are now represented as root route manifest assets, script preloads follow the manifest script format, and script asset cross-origin configuration uses the `script` key. The `transformAssets` script callback context now exposes only `kind: 'script'` and `url`, keeping script format handling internal to manifest rendering. + +- Fix Rsbuild server function metadata replay when Rspack restores modules from its persistent cache. ([#7477](https://github.com/TanStack/router/pull/7477)) + + Server function metadata is now stored on Rspack module build info and replayed from cached modules before resolver modules are rebuilt, preventing warm restarts from losing server function registrations. + +- Updated dependencies [[`51a97a1`](https://github.com/TanStack/router/commit/51a97a167fb3ef1b8ca70fbb63db635158f43509)]: + - @tanstack/router-core@1.171.6 + - @tanstack/start-server-core@1.169.3 + - @tanstack/router-generator@1.167.10 + - @tanstack/router-plugin@1.168.11 + - @tanstack/start-client-core@1.170.3 + +## 1.171.3 + +### Patch Changes + +- Updated dependencies [[`5268ba4`](https://github.com/TanStack/router/commit/5268ba4566233ea58880df85f167ad0401a93a46)]: + - @tanstack/router-core@1.171.5 + - @tanstack/router-generator@1.167.9 + - @tanstack/router-plugin@1.168.10 + - @tanstack/start-client-core@1.170.2 + - @tanstack/start-server-core@1.169.2 + +## 1.171.2 + +### Patch Changes + +- Updated dependencies [[`7df0d02`](https://github.com/TanStack/router/commit/7df0d02bfb1407b1f07731ef69af24e2f0e415d7)]: + - @tanstack/router-generator@1.167.8 + - @tanstack/router-plugin@1.168.9 + +## 1.171.1 + +### Patch Changes + +- Updated dependencies [[`0300f87`](https://github.com/TanStack/router/commit/0300f87ec5a7f878ffbe0b181acf84cba9139960), [`0300f87`](https://github.com/TanStack/router/commit/0300f87ec5a7f878ffbe0b181acf84cba9139960)]: + - @tanstack/router-core@1.171.4 + - @tanstack/router-generator@1.167.7 + - @tanstack/router-plugin@1.168.8 + - @tanstack/start-client-core@1.170.1 + - @tanstack/start-server-core@1.169.1 + +## 1.171.0 + +### Minor Changes + +- Add deferred Hydrate boundary support for TanStack Start. ([#7362](https://github.com/TanStack/router/pull/7362)) + + Hydrate boundaries can now be code-split by the Start compiler, preload their generated client chunks, preserve server-rendered fallback HTML, and replay interaction-triggered events after hydration. The compiler integration now uses a Start-owned compiler plugin for Hydrate virtual modules across Vite and Rsbuild, with dev invalidation for generated virtual modules. + + Shared AST utilities used by the router code-splitter and Hydrate virtual modules were moved into `@tanstack/router-utils` so both pipelines can retain referenced top-level declarations, unwrap local exports, and let dead-code elimination remove unused route module code. + +### Patch Changes + +- Updated dependencies [[`c0f439c`](https://github.com/TanStack/router/commit/c0f439c59b04b7e49a0ab3aa2a0c550f522949e5), [`5fa9e55`](https://github.com/TanStack/router/commit/5fa9e555f3a2edb5e45586623e6bcbfa7f7c7a6b)]: + - @tanstack/router-plugin@1.168.7 + - @tanstack/start-client-core@1.170.0 + - @tanstack/start-server-core@1.169.0 + - @tanstack/router-core@1.171.3 + - @tanstack/router-utils@1.162.1 + - @tanstack/router-generator@1.167.6 + +## 1.170.6 + +### Patch Changes + +- Updated dependencies [[`b60eb36`](https://github.com/TanStack/router/commit/b60eb36e59e8a468ee0742cbcf7f47aca1ff1c67)]: + - @tanstack/router-core@1.171.2 + - @tanstack/router-generator@1.167.5 + - @tanstack/router-plugin@1.168.6 + - @tanstack/start-client-core@1.169.4 + - @tanstack/start-server-core@1.168.4 + +## 1.170.5 + +### Patch Changes + +- Updated dependencies [[`8146db7`](https://github.com/TanStack/router/commit/8146db7e54f5d508f1fb7d3927edd0a2f71dc930)]: + - @tanstack/router-plugin@1.168.5 + +## 1.170.4 + +### Patch Changes + +- Updated dependencies [[`d9cf933`](https://github.com/TanStack/router/commit/d9cf9331b83fcbd2abfee75d839d862f9bb18e6b)]: + - @tanstack/router-core@1.171.1 + - @tanstack/router-generator@1.167.4 + - @tanstack/router-plugin@1.168.4 + - @tanstack/start-client-core@1.169.3 + - @tanstack/start-server-core@1.168.3 + +## 1.170.3 + +### Patch Changes + +- Updated dependencies [[`d533f87`](https://github.com/TanStack/router/commit/d533f87976704098a40b48f160b37c28c8182806)]: + - @tanstack/router-core@1.171.0 + - @tanstack/router-generator@1.167.3 + - @tanstack/router-plugin@1.168.3 + - @tanstack/start-client-core@1.169.2 + - @tanstack/start-server-core@1.168.2 + +## 1.170.2 + +### Patch Changes + +- Updated dependencies [[`742941e`](https://github.com/TanStack/router/commit/742941e2f1bf069c950d0a4985b2cd733639509e)]: + - @tanstack/router-generator@1.167.2 + - @tanstack/router-plugin@1.168.2 + +## 1.170.1 + +### Patch Changes + +- Add runtime-configurable inline CSS and opt-in CSS URL templates for transformAssets. ([#7380](https://github.com/TanStack/router/pull/7380)) + +- Updated dependencies [[`2387a2e`](https://github.com/TanStack/router/commit/2387a2eea0683004cc400b9f71bed5944eb60110)]: + - @tanstack/router-core@1.170.1 + - @tanstack/start-server-core@1.168.1 + - @tanstack/router-generator@1.167.1 + - @tanstack/router-plugin@1.168.1 + - @tanstack/start-client-core@1.169.1 + +## 1.170.0 + +### Minor Changes + +- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) + +### Patch Changes + +- add createCsrfMiddleware based on Sec-Fetch-Site header, auto-apply to unconfigured servers, warn for others ([#7373](https://github.com/TanStack/router/pull/7373)) + +- Updated dependencies [[`b1c061a`](https://github.com/TanStack/router/commit/b1c061aff9185cdf5fdc08c0136382a9dce0302f), [`038cd12`](https://github.com/TanStack/router/commit/038cd123b70bc6154d75abb6404a744c376f8f6a), [`201e150`](https://github.com/TanStack/router/commit/201e150bd1412bae2faa9ce53f0fefcb7574ac14), [`5ae2ae5`](https://github.com/TanStack/router/commit/5ae2ae5e0f8ce32e02667a482ea9be52a6150240)]: + - @tanstack/router-core@1.170.0 + - @tanstack/router-generator@1.167.0 + - @tanstack/router-plugin@1.168.0 + - @tanstack/router-utils@1.162.0 + - @tanstack/start-client-core@1.169.0 + - @tanstack/start-server-core@1.168.0 + +## 1.169.20 + +### Patch Changes + +- Updated dependencies [[`c5811aa`](https://github.com/TanStack/router/commit/c5811aacb59b69a8179f14cd9529a51b2206d504)]: + - @tanstack/router-generator@1.166.42 + - @tanstack/router-plugin@1.167.35 + +## 1.169.19 + +### Patch Changes + +- Update seroval dependencies to version 1.5.4. ([#7340](https://github.com/TanStack/router/pull/7340)) + +- Updated dependencies [[`35e88f0`](https://github.com/TanStack/router/commit/35e88f04996d71019a1868b7b06ecb4ddbc9df9e)]: + - @tanstack/router-core@1.169.2 + - @tanstack/start-client-core@1.168.2 + - @tanstack/start-server-core@1.167.30 + - @tanstack/router-generator@1.166.41 + - @tanstack/router-plugin@1.167.34 + +## 1.169.18 + +### Patch Changes + +- Parse plain TypeScript files without JSX when a filename is available, preventing angle-bracket type assertions from being interpreted as JSX during route and Start import-protection transforms. ([#7342](https://github.com/TanStack/router/pull/7342)) + +- Updated dependencies [[`056337e`](https://github.com/TanStack/router/commit/056337ef02ccbeaf45ec8533a227761be869e8f3)]: + - @tanstack/router-generator@1.166.40 + - @tanstack/router-plugin@1.167.33 + - @tanstack/router-utils@1.161.8 + +## 1.169.17 + +### Patch Changes + +- Updated dependencies [[`afa40ef`](https://github.com/TanStack/router/commit/afa40ef46c273c53646ba33f607fc618a07ffede)]: + - @tanstack/start-server-core@1.167.29 + +## 1.169.16 + +### Patch Changes + +- Updated dependencies [[`709627f`](https://github.com/TanStack/router/commit/709627f3dbc6d97daa547a1401ef42a53bc4be32)]: + - @tanstack/start-server-core@1.167.28 + +## 1.169.15 + +### Patch Changes + +- Updated dependencies [[`238ea4a`](https://github.com/TanStack/router/commit/238ea4a4998ab3a7fd528b317e1935766ac65df8)]: + - @tanstack/start-server-core@1.167.27 + +## 1.169.14 + +### Patch Changes + +- Replace global route metadata with explicit router plugin contexts so multiple router plugin instances cannot cross-transform route files. ([#7313](https://github.com/TanStack/router/pull/7313)) + +- Updated dependencies [[`96818b8`](https://github.com/TanStack/router/commit/96818b8ba5ead6f1f027094841330182aff415b2)]: + - @tanstack/router-plugin@1.167.32 + +## 1.169.13 + +### Patch Changes + +- Add compiler-driven RSC CSS auto-injection for Start RSC render APIs and wire it into the React Start Vite and Rsbuild adapters. This ensures same-file CSS module dependencies are discovered for `renderServerComponent`, `createCompositeComponent`, and JSX-based `renderToReadableStream` calls. ([#7310](https://github.com/TanStack/router/pull/7310)) + + Also add a configurable server function provider module directive hook used by the React Rsbuild RSC adapter to emit `"use server-entry"` only for extracted provider files. + +## 1.169.12 + +### Patch Changes + +- Updated dependencies [[`4a1e63f`](https://github.com/TanStack/router/commit/4a1e63f1d1230b1ed8234609acad4639d8982c13)]: + - @tanstack/router-core@1.169.1 + - @tanstack/router-generator@1.166.39 + - @tanstack/router-plugin@1.167.31 + - @tanstack/start-client-core@1.168.1 + - @tanstack/start-server-core@1.167.26 + +## 1.169.11 + +### Patch Changes + +- Updated dependencies [[`82b0613`](https://github.com/TanStack/router/commit/82b06132af776f74603ab27977cc277d6219a845)]: + - @tanstack/start-client-core@1.168.0 + - @tanstack/start-server-core@1.167.25 + +## 1.169.10 + +### Patch Changes + +- Ignore fully type-only imports and re-exports when collecting import-protection sources so type-only references to protected modules do not trigger violations. ([#7305](https://github.com/TanStack/router/pull/7305)) + +## 1.169.9 + +### Patch Changes + +- Sort server function manifest entries by ID before emitting the resolver module. The `serverFnsById` map is populated in source-file scan order, which varies across machines and incremental builds, producing non-deterministic key ordering in the emitted `__tanstack-start-server-fn-resolver-*.mjs` artifact. Stable alphabetic sorting ensures reproducible builds, consistent content hashes, and clean `git diff` on committed artifacts. ([#7287](https://github.com/TanStack/router/pull/7287)) + +## 1.169.8 + +### Patch Changes + +- Updated dependencies [[`c992495`](https://github.com/TanStack/router/commit/c992495bf4010ff4c3597bb1f3b1ba02594e857e)]: + - @tanstack/router-core@1.169.0 + - @tanstack/router-generator@1.166.38 + - @tanstack/router-plugin@1.167.30 + - @tanstack/start-client-core@1.167.22 + - @tanstack/start-server-core@1.167.24 + +## 1.169.7 + +### Patch Changes + +- Updated dependencies [[`b5c4183`](https://github.com/TanStack/router/commit/b5c4183ab8b44be8a75647b7f7b588ad7c146ece)]: + - @tanstack/router-core@1.168.18 + - @tanstack/router-generator@1.166.37 + - @tanstack/router-plugin@1.167.29 + - @tanstack/start-client-core@1.167.21 + - @tanstack/start-server-core@1.167.23 + +## 1.169.6 + +### Patch Changes + +- Updated dependencies [[`493148b`](https://github.com/TanStack/router/commit/493148bc5378b7f9de1544d87f6aaa425c12eb34)]: + - @tanstack/router-core@1.168.17 + - @tanstack/router-generator@1.166.36 + - @tanstack/router-plugin@1.167.28 + - @tanstack/start-client-core@1.167.20 + - @tanstack/start-server-core@1.167.22 + +## 1.169.5 + +### Patch Changes + +- Updated dependencies [[`a2ad394`](https://github.com/TanStack/router/commit/a2ad394598e2079ab4050ebb16bb03b31d69c32a)]: + - @tanstack/router-generator@1.166.35 + - @tanstack/router-plugin@1.167.27 + +## 1.169.4 + +### Patch Changes + +- Updated dependencies [[`8b97002`](https://github.com/TanStack/router/commit/8b97002af3f6d15204e60c55d3f5735b78bd7efe), [`8b97002`](https://github.com/TanStack/router/commit/8b97002af3f6d15204e60c55d3f5735b78bd7efe)]: + - @tanstack/start-client-core@1.167.19 + - @tanstack/router-plugin@1.167.26 + - @tanstack/start-server-core@1.167.21 + +## 1.169.3 + +### Patch Changes + +- Updated dependencies [[`1e371b6`](https://github.com/TanStack/router/commit/1e371b60f1832c158ff4953a4ae6c5ccfe8460b3)]: + - @tanstack/router-plugin@1.167.25 + +## 1.169.2 + +### Patch Changes + +- Add TanStack Start inline CSS manifest support for SSR so route styles can be embedded in the HTML response and hydrated without duplicate stylesheet links. ([#7253](https://github.com/TanStack/router/pull/7253)) + +- Updated dependencies [[`4d864ee`](https://github.com/TanStack/router/commit/4d864eebbd184265eabb563d326ab409c93feb17)]: + - @tanstack/router-core@1.168.16 + - @tanstack/start-server-core@1.167.20 + - @tanstack/router-generator@1.166.34 + - @tanstack/router-plugin@1.167.24 + - @tanstack/start-client-core@1.167.18 + +## 1.169.1 + +### Patch Changes + +- Fix CSS asset ordering so styles from imported chunks are emitted before route chunk styles. ([#7251](https://github.com/TanStack/router/pull/7251)) + +## 1.169.0 + +### Minor Changes + +- Split Start plugin core bundler APIs into explicit Vite and Rsbuild subpaths so projects only need the bundler they use. Mark both `vite` and `@rsbuild/core` peers as optional where Start exposes both integrations. ([#7249](https://github.com/TanStack/router/pull/7249)) + +## 1.168.0 + +### Minor Changes + +- rsbuild ([#7228](https://github.com/TanStack/router/pull/7228)) + +### Patch Changes + +- Updated dependencies [[`91a7089`](https://github.com/TanStack/router/commit/91a708989d00537a21911e74ff60bbfec8266295)]: + - @tanstack/router-plugin@1.167.23 + - @tanstack/router-utils@1.161.7 + - @tanstack/router-generator@1.166.33 + +## 1.167.35 + +### Patch Changes + +- Fix missing CSS module assets in TanStack Start production manifests when Vite `build.cssCodeSplit` is disabled. ([#7191](https://github.com/TanStack/router/pull/7191)) + +## 1.167.34 + +### Patch Changes + +- Updated dependencies [[`16f6892`](https://github.com/TanStack/router/commit/16f6892d6b7ceadf606677c5a40e743f29163aa6)]: + - @tanstack/router-core@1.168.15 + - @tanstack/router-generator@1.166.32 + - @tanstack/router-plugin@1.167.22 + - @tanstack/start-client-core@1.167.17 + - @tanstack/start-server-core@1.167.19 + +## 1.167.33 + +### Patch Changes + +- Fix Start virtual module resolution in pnpm workspaces by serving the client entry through a real Vite virtual module. ([#7178](https://github.com/TanStack/router/pull/7178)) + + Simplify Start virtual module handling by sharing a single `createVirtualModule` helper and collapsing internal `@tanstack/start-plugin-core` imports to the root export surface. + +## 1.167.32 + +### Patch Changes + +- Updated dependencies [[`328d7e5`](https://github.com/TanStack/router/commit/328d7e5ebc6b8074242a07d68ccafafb83e37a0e)]: + - @tanstack/router-generator@1.166.31 + - @tanstack/router-plugin@1.167.21 + +## 1.167.31 + +### Patch Changes + +- Updated dependencies [[`96ac2d8`](https://github.com/TanStack/router/commit/96ac2d8ed378340d63b88afeec3633e56e29b5f8)]: + - @tanstack/router-plugin@1.167.20 + +## 1.167.30 + +### Patch Changes + +- Updated dependencies [[`105d056`](https://github.com/TanStack/router/commit/105d05691a247779a63e7b688aa1207cce619339)]: + - @tanstack/router-generator@1.166.30 + - @tanstack/router-plugin@1.167.19 + +## 1.167.29 + +### Patch Changes + +- Updated dependencies [[`656a2a0`](https://github.com/TanStack/router/commit/656a2a040e79df7721d776e3751c8d634666570b)]: + - @tanstack/router-plugin@1.167.18 + +## 1.167.28 + +### Patch Changes + +- Updated dependencies [[`0e2c900`](https://github.com/TanStack/router/commit/0e2c9003c18ae07c09969189c028f277ea562a7a)]: + - @tanstack/start-server-core@1.167.18 + - @tanstack/router-core@1.168.14 + - @tanstack/router-generator@1.166.29 + - @tanstack/router-plugin@1.167.17 + - @tanstack/start-client-core@1.167.16 + +## 1.167.27 + +### Patch Changes + +- Reduce React Start SSR manifest payload size by omitting unmatched route assets from dehydrated router state while keeping start-manifest asset serialization deduplicated by shared object identity. ([#7157](https://github.com/TanStack/router/pull/7157)) + + This improves SSR HTML size for apps with many routes that share the same CSS assets and adds regression coverage for CSS module hydration, navigation, and start-manifest asset reuse. + +- Updated dependencies [[`812792f`](https://github.com/TanStack/router/commit/812792fbda3caf97b300770855cf5641252f413b)]: + - @tanstack/router-core@1.168.13 + - @tanstack/start-server-core@1.167.17 + - @tanstack/router-generator@1.166.28 + - @tanstack/router-plugin@1.167.16 + - @tanstack/start-client-core@1.167.15 + +## 1.167.26 + +### Patch Changes + +- Updated dependencies [[`8ec9ca9`](https://github.com/TanStack/router/commit/8ec9ca97b472779de878c2a6510f21deb24d386c)]: + - @tanstack/router-core@1.168.12 + - @tanstack/router-generator@1.166.27 + - @tanstack/router-plugin@1.167.15 + - @tanstack/start-client-core@1.167.14 + - @tanstack/start-server-core@1.167.16 + +## 1.167.25 + +### Patch Changes + +- Reuse previously discovered server function IDs across compiler instances so custom `generateFunctionId` values stay stable when duplicate IDs are deduplicated during build. ([#7153](https://github.com/TanStack/router/pull/7153)) + + This fixes cases where different build environments could assign different deduped IDs to the same server functions, which could cause requests to resolve to the wrong handler. + +## 1.167.24 + +### Patch Changes + +- Updated dependencies [[`6355bb7`](https://github.com/TanStack/router/commit/6355bb75f7637ba77f06a923c18fdaf37720bb48)]: + - @tanstack/start-server-core@1.167.15 + - @tanstack/router-plugin@1.167.14 + - @tanstack/router-core@1.168.11 + - @tanstack/router-generator@1.166.26 + - @tanstack/start-client-core@1.167.13 + +## 1.167.23 + +### Patch Changes + +- Updated dependencies [[`459057c`](https://github.com/TanStack/router/commit/459057cd2d90cff20d20e51d4964b0a8c950555e)]: + - @tanstack/start-client-core@1.167.12 + - @tanstack/start-server-core@1.167.14 + - @tanstack/router-plugin@1.167.13 + - @tanstack/router-core@1.168.10 + - @tanstack/router-generator@1.166.25 + +## 1.167.22 + +### Patch Changes + +- Updated dependencies [[`f8ac427`](https://github.com/TanStack/router/commit/f8ac427000c3fec99225926e72f9f2fc7a37231f)]: + - @tanstack/start-server-core@1.167.13 + - @tanstack/start-client-core@1.167.11 + +## 1.167.21 + +### Patch Changes + +- fix publishing ([`2d53c05`](https://github.com/TanStack/router/commit/2d53c056ef0b203de8a28bc92c24e8e604205d52)) + +- Updated dependencies [[`2d53c05`](https://github.com/TanStack/router/commit/2d53c056ef0b203de8a28bc92c24e8e604205d52)]: + - @tanstack/start-server-core@1.167.12 + +## 1.167.19 + +### Patch Changes + +- Republish the React Start RSC package chain so fresh installs resolve a `start-plugin-core` build that exports the subpaths used by `react-start-rsc`. ([`3384abc`](https://github.com/TanStack/router/commit/3384abcffd98a68eb254b11221834bcbcdebec31)) + +## 1.167.18 + +### Patch Changes + +- Updated dependencies [[`f7e9c5e`](https://github.com/TanStack/router/commit/f7e9c5e323793d1b28c96871819c265fd28ae397)]: + - @tanstack/start-client-core@1.167.10 + - @tanstack/start-server-core@1.167.10 + +## 1.167.17 + +### Patch Changes + +- Updated dependencies [[`796406d`](https://github.com/TanStack/router/commit/796406da66cfb12b518bb3ca326c9d541368fb06)]: + - @tanstack/router-core@1.168.9 + - @tanstack/router-generator@1.166.24 + - @tanstack/router-plugin@1.167.12 + - @tanstack/start-client-core@1.167.9 + - @tanstack/start-server-core@1.167.9 + +## 1.167.16 + +### Patch Changes + +- Updated dependencies [[`2d1ec86`](https://github.com/TanStack/router/commit/2d1ec865a446926f7db6e29dbbde82d265de6d36)]: + - @tanstack/router-core@1.168.8 + - @tanstack/router-generator@1.166.23 + - @tanstack/router-plugin@1.167.11 + - @tanstack/start-client-core@1.167.8 + - @tanstack/start-server-core@1.167.8 + +## 1.167.15 + +### Patch Changes + +- Updated dependencies [[`f8351a8`](https://github.com/TanStack/router/commit/f8351a8d7aa9f5a341377f96966451892acb39f1)]: + - @tanstack/router-plugin@1.167.10 + +## 1.167.14 + +### Patch Changes + +- Updated dependencies [[`6ee0e79`](https://github.com/TanStack/router/commit/6ee0e795b085651beb2f1ac6503cdbd7eaffedd1)]: + - @tanstack/router-core@1.168.7 + - @tanstack/router-generator@1.166.22 + - @tanstack/router-plugin@1.167.9 + - @tanstack/start-client-core@1.167.7 + - @tanstack/start-server-core@1.167.7 + +## 1.167.13 + +### Patch Changes + +- Updated dependencies [[`42c3f3b`](https://github.com/TanStack/router/commit/42c3f3b3a3a478fd6d6894310ef94b2d23794b8e)]: + - @tanstack/router-core@1.168.6 + - @tanstack/router-generator@1.166.21 + - @tanstack/router-plugin@1.167.8 + - @tanstack/start-client-core@1.167.6 + - @tanstack/start-server-core@1.167.6 + +## 1.167.12 + +### Patch Changes + +- Updated dependencies [[`70b2225`](https://github.com/TanStack/router/commit/70b222513720d99c6d44bd3f28d1e9b19dc91a43)]: + - @tanstack/router-generator@1.166.20 + - @tanstack/router-plugin@1.167.7 + +## 1.167.11 + +### Patch Changes + +- Updated dependencies [[`cf5f554`](https://github.com/TanStack/router/commit/cf5f5542476137a81515099ad740747e84512f9a)]: + - @tanstack/router-core@1.168.5 + - @tanstack/router-generator@1.166.19 + - @tanstack/router-plugin@1.167.6 + - @tanstack/start-client-core@1.167.5 + - @tanstack/start-server-core@1.167.5 + +## 1.167.10 + +### Patch Changes + +- Updated dependencies [[`71a8b68`](https://github.com/TanStack/router/commit/71a8b684c87c37fd4a033d99f5ba4a05c7a179f5)]: + - @tanstack/router-core@1.168.4 + - @tanstack/router-generator@1.166.18 + - @tanstack/router-plugin@1.167.5 + - @tanstack/start-client-core@1.167.4 + - @tanstack/start-server-core@1.167.4 + +## 1.167.9 + +### Patch Changes + +- Deduplicate CSS assets in the Start manifest so shared stylesheets are not repeated within a route entry or across an active parent-child route chain. ([#7030](https://github.com/TanStack/router/pull/7030)) + +## 1.167.8 + +### Patch Changes + +- feat: transformAssets ([#7023](https://github.com/TanStack/router/pull/7023)) + +- Updated dependencies [[`d81d21a`](https://github.com/TanStack/router/commit/d81d21ad05c9401bf54b24acd29401e1e4fd624c)]: + - @tanstack/router-core@1.168.3 + - @tanstack/start-server-core@1.167.3 + - @tanstack/router-generator@1.166.17 + - @tanstack/router-plugin@1.167.4 + - @tanstack/start-client-core@1.167.3 + +## 1.167.7 + +### Patch Changes + +- fix: streaming in vite preview ([#6828](https://github.com/TanStack/router/pull/6828)) + +## 1.167.6 + +### Patch Changes + +- Updated dependencies [[`c9e1855`](https://github.com/TanStack/router/commit/c9e18555f3a5531e96de8f574cfca9edcdb18e5c)]: + - @tanstack/start-client-core@1.167.2 + - @tanstack/start-server-core@1.167.2 + - @tanstack/router-core@1.168.2 + - @tanstack/router-generator@1.166.16 + - @tanstack/router-plugin@1.167.3 + +## 1.167.5 + +### Patch Changes + +- Updated dependencies [[`9351e99`](https://github.com/TanStack/router/commit/9351e997962d02ecc3f6f1791edd84e64361d27b)]: + - @tanstack/router-plugin@1.167.2 + +## 1.167.4 + +### Patch Changes + +- Updated dependencies [[`91cc628`](https://github.com/TanStack/router/commit/91cc62899b75ca920fe83c5ee7f3dbb5c71a523f)]: + - @tanstack/router-core@1.168.1 + - @tanstack/router-generator@1.166.15 + - @tanstack/router-plugin@1.167.1 + - @tanstack/start-client-core@1.167.1 + - @tanstack/start-server-core@1.167.1 + +## 1.167.3 + +### Patch Changes + +- Updated dependencies [[`0545239`](https://github.com/TanStack/router/commit/054523900b2ee19308e5a88417dadfc6923afe30)]: + - @tanstack/start-client-core@1.167.0 + - @tanstack/start-server-core@1.167.0 + - @tanstack/router-plugin@1.167.0 + - @tanstack/router-core@1.168.0 + - @tanstack/router-generator@1.166.14 + +## 1.167.2 + +### Patch Changes + +- fix(start-plugin-core): fix Vite 7/8 compat for bundler options ([#6985](https://github.com/TanStack/router/pull/6985)) + +## 1.167.1 + +### Patch Changes + +- Updated dependencies [[`5ff4f0b`](https://github.com/TanStack/router/commit/5ff4f0b8dce1fac2bb0b0bfe2684fc677a8ee505)]: + - @tanstack/router-core@1.167.5 + - @tanstack/router-generator@1.166.13 + - @tanstack/router-plugin@1.166.14 + - @tanstack/start-client-core@1.166.13 + - @tanstack/start-server-core@1.166.13 + +## 1.167.0 + +### Minor Changes + +- Support both Vite 7 (`rollupOptions`) and Vite 8 (`rolldownOptions`) by detecting the Vite version at runtime ([#6955](https://github.com/TanStack/router/pull/6955)) + +## 1.166.15 + +### Patch Changes + +- fix: write static server function cache to correct output directory when using Nitro ([#6940](https://github.com/TanStack/router/pull/6940)) + + `TSS_CLIENT_OUTPUT_DIR` was baked in via Vite's `define` at config time, before Nitro's `configEnvironment` hook changed the client `build.outDir`. This caused `staticServerFnCache` files to be written to `dist/client/` instead of the Nitro-managed `.output/public/` directory. + + Now `TSS_CLIENT_OUTPUT_DIR` is set as a runtime environment variable during prerendering using the resolved client output directory, so it correctly reflects any output directory changes made by deployment adapters like Nitro. + +- Updated dependencies [[`940151c`](https://github.com/TanStack/router/commit/940151cbed0c76c92a5cf196c0905b17a956ca7e)]: + - @tanstack/router-core@1.167.4 + - @tanstack/router-plugin@1.166.13 + - @tanstack/start-client-core@1.166.12 + - @tanstack/start-server-core@1.166.12 + - @tanstack/router-generator@1.166.12 + +## 1.166.14 + +### Patch Changes + +- Updated dependencies [[`32fcba7`](https://github.com/TanStack/router/commit/32fcba7b044b03f5901308b870f70b0b4910c220)]: + - @tanstack/router-core@1.167.3 + - @tanstack/router-generator@1.166.11 + - @tanstack/router-plugin@1.166.12 + - @tanstack/start-client-core@1.166.11 + - @tanstack/start-server-core@1.166.11 + +## 1.166.13 + +### Patch Changes + +- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) + +- Updated dependencies [[`838b0eb`](https://github.com/TanStack/router/commit/838b0eb9a8bbbb987a0a6972c1446e01423bbd7b)]: + - @tanstack/router-core@1.167.2 + - @tanstack/router-generator@1.166.10 + - @tanstack/router-plugin@1.166.11 + - @tanstack/router-utils@1.161.6 + - @tanstack/start-client-core@1.166.10 + - @tanstack/start-server-core@1.166.10 + +## 1.166.12 + +### Patch Changes + +- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) + +- Updated dependencies [[`ef9b241`](https://github.com/TanStack/router/commit/ef9b241f3cfe95cee40daa96da669f0ffd4a971a)]: + - @tanstack/start-client-core@1.166.9 + - @tanstack/start-server-core@1.166.9 + - @tanstack/router-generator@1.166.9 + - @tanstack/router-plugin@1.166.10 + - @tanstack/router-utils@1.161.5 + - @tanstack/router-core@1.167.1 + +## 1.166.11 + +### Patch Changes + +- fix: add `xmlns:xhtml` to generated sitemap ([#6920](https://github.com/TanStack/router/pull/6920)) + +## 1.166.10 + +### Patch Changes + +- Updated dependencies [[`6f297a2`](https://github.com/TanStack/router/commit/6f297a249424c0fd1c1a56aa4fc12c8217be7b6a)]: + - @tanstack/router-core@1.167.0 + - @tanstack/router-generator@1.166.8 + - @tanstack/router-plugin@1.166.9 + - @tanstack/start-client-core@1.166.8 + - @tanstack/start-server-core@1.166.8 + +## 1.166.9 + +### Patch Changes + +- Updated dependencies [[`6069eba`](https://github.com/TanStack/router/commit/6069eba64369dbddb0d8dccdb4407f0e1a82259e)]: + - @tanstack/router-plugin@1.166.8 + - @tanstack/router-generator@1.166.7 + +## 1.166.8 + +### Patch Changes + +- fix: keep CSS when referenced both statically and dynamically ([#6891](https://github.com/TanStack/router/pull/6891)) diff --git a/packages/start-plugin-core/package.json b/packages/start-plugin-core/package.json index a04573c0a9..1945ab7ba6 100644 --- a/packages/start-plugin-core/package.json +++ b/packages/start-plugin-core/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/start-plugin-core", - "version": "1.142.0", + "version": "1.171.57", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -27,19 +27,42 @@ "scripts": { "clean": "rimraf ./dist && rimraf ./coverage", "clean:snapshots": "rimraf **/*snapshot* --glob", - "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit", - "test:unit": "vitest", + "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit && pnpm test:integration", + "test:unit": "vitest --project unit", + "test:integration": "vitest --project integration", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts54": "node ../../node_modules/typescript54/lib/tsc.js", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "tsc", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, + "nx": { + "targets": { + "test:integration": { + "cache": true, + "dependsOn": [ + "^build", + "build", + { + "projects": [ + "@tanstack/react-start" + ], + "target": "build" + } + ], + "inputs": [ + "default", + "^production", + "dependentTaskOutputs" + ] + } + } + }, "type": "module", "types": "dist/esm/index.d.ts", "module": "dist/esm/index.js", @@ -50,6 +73,30 @@ "default": "./dist/esm/index.js" } }, + "./utils": { + "import": { + "types": "./dist/esm/utils.d.ts", + "default": "./dist/esm/utils.js" + } + }, + "./vite": { + "import": { + "types": "./dist/esm/vite/index.d.ts", + "default": "./dist/esm/vite/index.js" + } + }, + "./rsbuild": { + "import": { + "types": "./dist/esm/rsbuild/index.d.ts", + "default": "./dist/esm/rsbuild/index.js" + } + }, + "./rsbuild/types": { + "import": { + "types": "./dist/esm/rsbuild/types.d.ts", + "default": "./dist/esm/rsbuild/types.js" + } + }, "./package.json": "./package.json" }, "sideEffects": false, @@ -61,34 +108,52 @@ "node": ">=22.12.0" }, "dependencies": { - "@babel/code-frame": "7.26.2", - "@babel/core": "^7.26.8", - "@babel/types": "^7.26.8", - "@rolldown/pluginutils": "1.0.0-beta.40", + "@babel/code-frame": "7.29.7", + "@babel/core": "catalog:", + "@babel/types": "catalog:", + "@jridgewell/remapping": "^2.3.5", "@tanstack/router-core": "workspace:*", "@tanstack/router-generator": "workspace:*", "@tanstack/router-plugin": "workspace:*", "@tanstack/router-utils": "workspace:*", - "@tanstack/server-functions-plugin": "workspace:*", - "@tanstack/start-client-core": "workspace:*", "@tanstack/start-server-core": "workspace:*", - "babel-dead-code-elimination": "^1.0.9", - "cheerio": "^1.0.0", - "exsolve": "^1.0.7", - "pathe": "^2.0.3", - "srvx": "^0.9.8", - "tinyglobby": "^0.2.15", - "ufo": "^1.5.4", - "vitefu": "^1.1.1", - "xmlbuilder2": "^4.0.0", - "zod": "^3.24.2" + "exsolve": "^1.1.3", + "lightningcss": "^1.33.0", + "pathe": "catalog:", + "picomatch": "^4.0.7", + "seroval": "^1.6.7", + "source-map": "^0.7.6", + "srvx": "^1.0.0", + "tinyglobby": "catalog:", + "ufo": "^1.6.4", + "vitefu": "^1.1.3", + "xmlbuilder2": "^4.0.3", + "zod": "catalog:" }, "devDependencies": { + "@rsbuild/core": "catalog:", "@types/babel__code-frame": "^7.0.6", "@types/babel__core": "^7.20.5", - "vite": "^7.1.7" + "@types/node": ">=20", + "@types/picomatch": "^4.0.2", + "prettier": "^3.9.6", + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { - "vite": ">=7.0.0" + "@rsbuild/core": "^2.0.5", + "vite": ">=8.0.0" + }, + "peerDependenciesMeta": { + "@rsbuild/core": { + "optional": true + }, + "vite": { + "optional": true + } } } diff --git a/packages/start-plugin-core/src/build-sitemap.ts b/packages/start-plugin-core/src/build-sitemap.ts index fabb9f19d2..744096a2ff 100644 --- a/packages/start-plugin-core/src/build-sitemap.ts +++ b/packages/start-plugin-core/src/build-sitemap.ts @@ -1,8 +1,10 @@ import { writeFileSync } from 'node:fs' import path from 'node:path' import { create } from 'xmlbuilder2' +import { z } from 'zod' +import { pageBaseSchema } from './schema' import { createLogger } from './utils' -import type { TanStackStartOutputConfig } from './schema' +import type { PageBase, TanStackStartOutputConfig } from './schema' import type { XMLBuilder } from 'xmlbuilder2/lib/interfaces' export type SitemapUrl = { @@ -19,7 +21,7 @@ export type SitemapUrl = { | 'never' alternateRefs?: Array<{ href: string - hreflang?: string + hreflang: string }> images?: Array<{ loc: string @@ -40,10 +42,7 @@ export type SitemapData = { urls: Array } -function buildSitemapJson( - pages: TanStackStartOutputConfig['pages'], - host: string, -): SitemapData { +function buildSitemapJson(pages: Array, host: string): SitemapData { const slash = checkSlash(host) const urls: Array = pages @@ -168,8 +167,20 @@ export function buildSitemap({ logger.info('Building Sitemap...') - // Build the sitemap data - const sitemapData = buildSitemapJson(pages, host) + // Validate pages before writing anything. The schema strips private fields + // (prerender headers, extra data returned by `prerender.onSuccess`), so both + // public outputs are built from the same validated page data. + const publicPages = pages.map((page) => { + const result = pageBaseSchema.safeParse(page) + if (!result.success) { + throw new Error( + `Invalid sitemap data for page "${page.path}". Check the value returned by \`prerender.onSuccess\`.\n${z.prettifyError(result.error)}`, + { cause: result.error }, + ) + } + return result.data + }) + const sitemapData = buildSitemapJson(publicPages, host) // Generate output paths const xmlOutputPath = path.join(publicDir, outputPath) @@ -186,7 +197,7 @@ export function buildSitemap({ pagesOutputPath, JSON.stringify( { - pages, + pages: publicPages, host, lastBuilt: new Date().toISOString(), }, @@ -202,7 +213,10 @@ export function buildSitemap({ function createXml(elementName: 'urlset' | 'sitemapindex'): XMLBuilder { return create({ version: '1.0', encoding: 'UTF-8' }) .ele(elementName, { - xmlns: 'https://www.sitemaps.org/schemas/sitemap/0.9', + xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9', + 'xmlns:xhtml': 'http://www.w3.org/1999/xhtml', + 'xmlns:image': 'http://www.google.com/schemas/sitemap-image/1.1', + 'xmlns:news': 'http://www.google.com/schemas/sitemap-news/0.9', }) .com(`This file was automatically generated by TanStack Start.`) } diff --git a/packages/start-plugin-core/src/config-context.ts b/packages/start-plugin-core/src/config-context.ts new file mode 100644 index 0000000000..825860a595 --- /dev/null +++ b/packages/start-plugin-core/src/config-context.ts @@ -0,0 +1,138 @@ +import { + createNormalizedBasePaths, + createNormalizedOutputDirectories, + deriveRouterBasepath, + resolveStartEntryPlan, +} from './planning' +import type { TanStackStartOutputConfig } from './schema' +import type { + GetConfigFn, + ResolvedStartConfig, + TanStackStartCoreOptions, +} from './types' + +export interface StartConfigContext { + resolvedStartConfig: ResolvedStartConfig + getConfig: GetConfigFn + resolveEntries: () => ReturnType +} + +export function createStartConfigContext(opts: { + corePluginOpts: TanStackStartCoreOptions + startPluginOpts: TInputConfig | undefined + parseConfig: ( + opts: TInputConfig | undefined, + core: { framework: TanStackStartCoreOptions['framework'] }, + root: string, + ) => TanStackStartOutputConfig +}): StartConfigContext { + const resolvedStartConfig: ResolvedStartConfig = { + root: '', + startFilePath: undefined, + routerFilePath: '', + srcDirectory: '', + basePaths: { + publicBase: '', + assetBase: { + dev: '', + build: '', + }, + }, + outputDirectories: { + client: '', + server: '', + }, + } + + let startConfig: TanStackStartOutputConfig | null = null + let resolvedEntryPlanCache: + | ReturnType + | undefined + + function requireRoot(): string { + if (!resolvedStartConfig.root) { + throw new Error(`Cannot get config before root is resolved`) + } + + return resolvedStartConfig.root + } + + function getStartConfig(): TanStackStartOutputConfig { + if (!startConfig) { + startConfig = opts.parseConfig( + opts.startPluginOpts, + { framework: opts.corePluginOpts.framework }, + requireRoot(), + ) + } + + return startConfig + } + + function getResolvedEntryPlan() { + if (resolvedEntryPlanCache) { + return resolvedEntryPlanCache + } + + resolvedEntryPlanCache = resolveStartEntryPlan({ + root: requireRoot(), + startConfig: getStartConfig(), + defaultEntryPaths: opts.corePluginOpts.defaultEntryPaths, + }) + + Object.assign(resolvedStartConfig, { + srcDirectory: resolvedEntryPlanCache.srcDirectory, + startFilePath: resolvedEntryPlanCache.startFilePath, + routerFilePath: resolvedEntryPlanCache.routerFilePath, + }) + + return resolvedEntryPlanCache + } + + const getConfig: GetConfigFn = () => { + const startConfig = getStartConfig() + getResolvedEntryPlan() + + return { startConfig, resolvedStartConfig } + } + + function resolveEntries() { + return getResolvedEntryPlan() + } + + return { + resolvedStartConfig, + getConfig, + resolveEntries, + } +} + +export function applyResolvedBaseAndOutput(opts: { + resolvedStartConfig: ResolvedStartConfig + root: string + publicBase: string + clientOutputDirectory: string + serverOutputDirectory: string +}): void { + opts.resolvedStartConfig.root = opts.root + opts.resolvedStartConfig.basePaths = createNormalizedBasePaths({ + publicBase: opts.publicBase, + }) + opts.resolvedStartConfig.outputDirectories = + createNormalizedOutputDirectories({ + client: opts.clientOutputDirectory, + server: opts.serverOutputDirectory, + }) +} + +export function applyResolvedRouterBasepath(opts: { + resolvedStartConfig: ResolvedStartConfig + startConfig: TanStackStartOutputConfig +}): string { + const routerBasepath = deriveRouterBasepath({ + configuredBasepath: opts.startConfig.router.basepath, + publicBase: opts.resolvedStartConfig.basePaths.publicBase, + }) + opts.startConfig.router.basepath = routerBasepath + return routerBasepath +} diff --git a/packages/start-plugin-core/src/constants.ts b/packages/start-plugin-core/src/constants.ts index 854b4079a4..d31c9e8246 100644 --- a/packages/start-plugin-core/src/constants.ts +++ b/packages/start-plugin-core/src/constants.ts @@ -1,12 +1,16 @@ -export const VITE_ENVIRONMENT_NAMES = { +export const START_ENVIRONMENT_NAMES = { // 'ssr' is chosen as the name for the server environment to ensure backwards compatibility // with vite plugins that are not compatible with the new vite environment API (e.g. tailwindcss) server: 'ssr', client: 'client', } as const -export type ViteEnvironmentNames = - (typeof VITE_ENVIRONMENT_NAMES)[keyof typeof VITE_ENVIRONMENT_NAMES] +export type StartEnvironmentName = + (typeof START_ENVIRONMENT_NAMES)[keyof typeof START_ENVIRONMENT_NAMES] + +export const VITE_ENVIRONMENT_NAMES = START_ENVIRONMENT_NAMES + +export type ViteEnvironmentNames = StartEnvironmentName // for client and router: // if a user has a custom server/client entry point file, resolve.alias will point to this @@ -19,6 +23,10 @@ export const ENTRY_POINTS = { router: '#tanstack-router-entry', } as const +export const DEV_CLIENT_ENTRY = 'virtual:tanstack-start-dev-client-entry' + +export const SERVER_FN_LOOKUP = 'server-fn-module-lookup' + // matches // .ts, .tsx, .cts, .mts, .js, .jsx, .cjs, .mjs // with optional query params after diff --git a/packages/start-plugin-core/src/create-server-fn-plugin/compiler.ts b/packages/start-plugin-core/src/create-server-fn-plugin/compiler.ts deleted file mode 100644 index 1fb95ee078..0000000000 --- a/packages/start-plugin-core/src/create-server-fn-plugin/compiler.ts +++ /dev/null @@ -1,523 +0,0 @@ -/* eslint-disable import/no-commonjs */ -import * as t from '@babel/types' -import { generateFromAst, parseAst } from '@tanstack/router-utils' -import babel from '@babel/core' -import { - deadCodeElimination, - findReferencedIdentifiers, -} from 'babel-dead-code-elimination' -import { handleCreateServerFn } from './handleCreateServerFn' -import { handleCreateMiddleware } from './handleCreateMiddleware' - -type Binding = - | { - type: 'import' - source: string - importedName: string - resolvedKind?: Kind - } - | { - type: 'var' - init: t.Expression | null - resolvedKind?: Kind - } - -type ExportEntry = - | { tag: 'Normal'; name: string } - | { tag: 'Default'; name: string } - | { tag: 'Namespace'; name: string; targetId: string } // for `export * as ns from './x'` - -type Kind = 'None' | `Root` | `Builder` | LookupKind - -export type LookupKind = 'ServerFn' | 'Middleware' - -const LookupSetup: Record< - LookupKind, - { candidateCallIdentifier: Set } -> = { - ServerFn: { candidateCallIdentifier: new Set(['handler']) }, - Middleware: { - candidateCallIdentifier: new Set(['server', 'client', 'createMiddlewares']), - }, -} - -export type LookupConfig = { - libName: string - rootExport: string -} -interface ModuleInfo { - id: string - code: string - ast: ReturnType - bindings: Map - exports: Map -} - -export class ServerFnCompiler { - private moduleCache = new Map() - private initialized = false - private validLookupKinds: Set - constructor( - private options: { - env: 'client' | 'server' - directive: string - lookupConfigurations: Array - lookupKinds: Set - loadModule: (id: string) => Promise - resolveId: (id: string, importer?: string) => Promise - }, - ) { - this.validLookupKinds = options.lookupKinds - } - - private async init(id: string) { - await Promise.all( - this.options.lookupConfigurations.map(async (config) => { - const libId = await this.options.resolveId(config.libName, id) - if (!libId) { - throw new Error(`could not resolve "${config.libName}"`) - } - let rootModule = this.moduleCache.get(libId) - if (!rootModule) { - // insert root binding - rootModule = { - ast: null as any, - bindings: new Map(), - exports: new Map(), - code: '', - id: libId, - } - this.moduleCache.set(libId, rootModule) - } - - rootModule.exports.set(config.rootExport, { - tag: 'Normal', - name: config.rootExport, - }) - rootModule.exports.set('*', { - tag: 'Namespace', - name: config.rootExport, - targetId: libId, - }) - rootModule.bindings.set(config.rootExport, { - type: 'var', - init: t.identifier(config.rootExport), - resolvedKind: `Root` satisfies Kind, - }) - this.moduleCache.set(libId, rootModule) - }), - ) - - this.initialized = true - } - - public ingestModule({ code, id }: { code: string; id: string }) { - const ast = parseAst({ code }) - - const bindings = new Map() - const exports = new Map() - - // we are only interested in top-level bindings, hence we don't traverse the AST - // instead we only iterate over the program body - for (const node of ast.program.body) { - if (t.isImportDeclaration(node)) { - const source = node.source.value - for (const s of node.specifiers) { - if (t.isImportSpecifier(s)) { - const importedName = t.isIdentifier(s.imported) - ? s.imported.name - : s.imported.value - bindings.set(s.local.name, { type: 'import', source, importedName }) - } else if (t.isImportDefaultSpecifier(s)) { - bindings.set(s.local.name, { - type: 'import', - source, - importedName: 'default', - }) - } else if (t.isImportNamespaceSpecifier(s)) { - bindings.set(s.local.name, { - type: 'import', - source, - importedName: '*', - }) - } - } - } else if (t.isVariableDeclaration(node)) { - for (const decl of node.declarations) { - if (t.isIdentifier(decl.id)) { - bindings.set(decl.id.name, { - type: 'var', - init: decl.init ?? null, - }) - } - } - } else if (t.isExportNamedDeclaration(node)) { - // export const foo = ... - if (node.declaration) { - if (t.isVariableDeclaration(node.declaration)) { - for (const d of node.declaration.declarations) { - if (t.isIdentifier(d.id)) { - exports.set(d.id.name, { tag: 'Normal', name: d.id.name }) - bindings.set(d.id.name, { type: 'var', init: d.init ?? null }) - } - } - } - } - for (const sp of node.specifiers) { - if (t.isExportNamespaceSpecifier(sp)) { - exports.set(sp.exported.name, { - tag: 'Namespace', - name: sp.exported.name, - targetId: node.source?.value || '', - }) - } - // export { local as exported } - else if (t.isExportSpecifier(sp)) { - const local = sp.local.name - const exported = t.isIdentifier(sp.exported) - ? sp.exported.name - : sp.exported.value - exports.set(exported, { tag: 'Normal', name: local }) - } - } - } else if (t.isExportDefaultDeclaration(node)) { - const d = node.declaration - if (t.isIdentifier(d)) { - exports.set('default', { tag: 'Default', name: d.name }) - } else { - const synth = '__default_export__' - bindings.set(synth, { type: 'var', init: d as t.Expression }) - exports.set('default', { tag: 'Default', name: synth }) - } - } - } - - const info: ModuleInfo = { code, id, ast, bindings, exports } - this.moduleCache.set(id, info) - return info - } - - public invalidateModule(id: string) { - return this.moduleCache.delete(id) - } - - public async compile({ code, id }: { code: string; id: string }) { - if (!this.initialized) { - await this.init(id) - } - const { bindings, ast } = this.ingestModule({ code, id }) - const candidates = this.collectCandidates(bindings) - if (candidates.length === 0) { - // this hook will only be invoked if there is `.handler(` | `.server(` | `.client(` in the code, - // so not discovering a handler candidate is rather unlikely, but maybe possible? - return null - } - - // let's find out which of the candidates are actually server functions - const toRewrite: Array<{ - callExpression: t.CallExpression - kind: LookupKind - }> = [] - for (const handler of candidates) { - const kind = await this.resolveExprKind(handler, id) - if (this.validLookupKinds.has(kind as LookupKind)) { - toRewrite.push({ callExpression: handler, kind: kind as LookupKind }) - } - } - if (toRewrite.length === 0) { - return null - } - - const pathsToRewrite: Array<{ - nodePath: babel.NodePath - kind: LookupKind - }> = [] - babel.traverse(ast, { - CallExpression(path) { - const found = toRewrite.findIndex((h) => path.node === h.callExpression) - if (found !== -1) { - pathsToRewrite.push({ nodePath: path, kind: toRewrite[found]!.kind }) - // delete from toRewrite - toRewrite.splice(found, 1) - } - }, - }) - - if (toRewrite.length > 0) { - throw new Error( - `Internal error: could not find all paths to rewrite. please file an issue`, - ) - } - - const refIdents = findReferencedIdentifiers(ast) - - pathsToRewrite.map((p) => { - if (p.kind === 'ServerFn') { - handleCreateServerFn(p.nodePath, { - env: this.options.env, - code, - directive: this.options.directive, - }) - } else { - handleCreateMiddleware(p.nodePath, { env: this.options.env }) - } - }) - - deadCodeElimination(ast, refIdents) - - return generateFromAst(ast, { - sourceMaps: true, - sourceFileName: id, - filename: id, - }) - } - - // collects all candidate CallExpressions at top-level - private collectCandidates(bindings: Map) { - const candidates: Array = [] - - for (const binding of bindings.values()) { - if (binding.type === 'var') { - const handler = isCandidateCallExpression( - binding.init, - this.validLookupKinds, - ) - if (handler) { - candidates.push(handler) - } - } - } - return candidates - } - - private async resolveIdentifierKind( - ident: string, - id: string, - visited = new Set(), - ): Promise { - const info = await this.getModuleInfo(id) - - const binding = info.bindings.get(ident) - if (!binding) { - return 'None' - } - if (binding.resolvedKind) { - return binding.resolvedKind - } - - // TODO improve cycle detection? should we throw here instead of returning 'None'? - // prevent cycles - const vKey = `${id}:${ident}` - if (visited.has(vKey)) { - return 'None' - } - visited.add(vKey) - - const resolvedKind = await this.resolveBindingKind(binding, id, visited) - binding.resolvedKind = resolvedKind - return resolvedKind - } - - private async resolveBindingKind( - binding: Binding, - fileId: string, - visited = new Set(), - ): Promise { - if (binding.resolvedKind) { - return binding.resolvedKind - } - if (binding.type === 'import') { - const target = await this.options.resolveId(binding.source, fileId) - if (!target) { - return 'None' - } - - const importedModule = await this.getModuleInfo(target) - - const moduleExport = importedModule.exports.get(binding.importedName) - if (!moduleExport) { - return 'None' - } - const importedBinding = importedModule.bindings.get(moduleExport.name) - if (!importedBinding) { - return 'None' - } - if (importedBinding.resolvedKind) { - return importedBinding.resolvedKind - } - - const resolvedKind = await this.resolveBindingKind( - importedBinding, - importedModule.id, - visited, - ) - importedBinding.resolvedKind = resolvedKind - return resolvedKind - } - - const resolvedKind = await this.resolveExprKind( - binding.init, - fileId, - visited, - ) - binding.resolvedKind = resolvedKind - return resolvedKind - } - - private async resolveExprKind( - expr: t.Expression | null, - fileId: string, - visited = new Set(), - ): Promise { - if (!expr) { - return 'None' - } - - let result: Kind = 'None' - - if (t.isCallExpression(expr)) { - if (!t.isExpression(expr.callee)) { - return 'None' - } - const calleeKind = await this.resolveCalleeKind( - expr.callee, - fileId, - visited, - ) - if (calleeKind !== 'None') { - if (calleeKind === `Root` || calleeKind === `Builder`) { - return `Builder` - } - for (const kind of this.validLookupKinds) { - if (calleeKind === kind) { - return kind - } - } - } - } else if (t.isMemberExpression(expr) && t.isIdentifier(expr.property)) { - result = await this.resolveCalleeKind(expr.object, fileId, visited) - } - - if (result === 'None' && t.isIdentifier(expr)) { - result = await this.resolveIdentifierKind(expr.name, fileId, visited) - } - - if (result === 'None' && t.isTSAsExpression(expr)) { - result = await this.resolveExprKind(expr.expression, fileId, visited) - } - if (result === 'None' && t.isTSNonNullExpression(expr)) { - result = await this.resolveExprKind(expr.expression, fileId, visited) - } - if (result === 'None' && t.isParenthesizedExpression(expr)) { - result = await this.resolveExprKind(expr.expression, fileId, visited) - } - - return result - } - - private async resolveCalleeKind( - callee: t.Expression, - fileId: string, - visited = new Set(), - ): Promise { - if (t.isIdentifier(callee)) { - return this.resolveIdentifierKind(callee.name, fileId, visited) - } - - if (t.isMemberExpression(callee) && t.isIdentifier(callee.property)) { - const prop = callee.property.name - - if ( - this.validLookupKinds.has('ServerFn') && - LookupSetup['ServerFn'].candidateCallIdentifier.has(prop) - ) { - const base = await this.resolveExprKind(callee.object, fileId, visited) - if (base === 'Root' || base === 'Builder') { - return 'ServerFn' - } - return 'None' - } else if ( - this.validLookupKinds.has('Middleware') && - LookupSetup['Middleware'].candidateCallIdentifier.has(prop) - ) { - const base = await this.resolveExprKind(callee.object, fileId, visited) - if (base === 'Root' || base === 'Builder' || base === 'Middleware') { - return 'Middleware' - } - return 'None' - } - // Check if the object is a namespace import - if (t.isIdentifier(callee.object)) { - const info = await this.getModuleInfo(fileId) - const binding = info.bindings.get(callee.object.name) - if ( - binding && - binding.type === 'import' && - binding.importedName === '*' - ) { - // resolve the property from the target module - const targetModuleId = await this.options.resolveId( - binding.source, - fileId, - ) - if (targetModuleId) { - const targetModule = await this.getModuleInfo(targetModuleId) - const exportEntry = targetModule.exports.get(callee.property.name) - if (exportEntry) { - const exportedBinding = targetModule.bindings.get( - exportEntry.name, - ) - if (exportedBinding) { - return await this.resolveBindingKind( - exportedBinding, - targetModule.id, - visited, - ) - } - } - } else { - return 'None' - } - } - } - return this.resolveExprKind(callee.object, fileId, visited) - } - - // handle nested expressions - return this.resolveExprKind(callee, fileId, visited) - } - - private async getModuleInfo(id: string) { - let cached = this.moduleCache.get(id) - if (cached) { - return cached - } - - await this.options.loadModule(id) - - cached = this.moduleCache.get(id) - if (!cached) { - throw new Error(`could not load module info for ${id}`) - } - return cached - } -} - -function isCandidateCallExpression( - node: t.Node | null | undefined, - lookupKinds: Set, -): undefined | t.CallExpression { - if (!t.isCallExpression(node)) return undefined - - const callee = node.callee - if (!t.isMemberExpression(callee) || !t.isIdentifier(callee.property)) { - return undefined - } - for (const kind of lookupKinds) { - if (LookupSetup[kind].candidateCallIdentifier.has(callee.property.name)) { - return node - } - } - - return undefined -} diff --git a/packages/start-plugin-core/src/create-server-fn-plugin/handleCreateMiddleware.ts b/packages/start-plugin-core/src/create-server-fn-plugin/handleCreateMiddleware.ts deleted file mode 100644 index 1da0bd6969..0000000000 --- a/packages/start-plugin-core/src/create-server-fn-plugin/handleCreateMiddleware.ts +++ /dev/null @@ -1,82 +0,0 @@ -import * as t from '@babel/types' -import { getRootCallExpression } from '../start-compiler-plugin/utils' -import type * as babel from '@babel/core' - -export function handleCreateMiddleware( - path: babel.NodePath, - opts: { - env: 'client' | 'server' - }, -) { - const rootCallExpression = getRootCallExpression(path) - - // if (debug) - // console.info( - // 'Handling createMiddleware call expression:', - // rootCallExpression.toString(), - // ) - - const callExpressionPaths = { - middleware: null as babel.NodePath | null, - inputValidator: null as babel.NodePath | null, - client: null as babel.NodePath | null, - server: null as babel.NodePath | null, - } - - const validMethods = Object.keys(callExpressionPaths) - - rootCallExpression.traverse({ - MemberExpression(memberExpressionPath) { - if (t.isIdentifier(memberExpressionPath.node.property)) { - const name = memberExpressionPath.node.property - .name as keyof typeof callExpressionPaths - - if ( - validMethods.includes(name) && - memberExpressionPath.parentPath.isCallExpression() - ) { - callExpressionPaths[name] = memberExpressionPath.parentPath - } - } - }, - }) - - if (callExpressionPaths.inputValidator) { - const innerInputExpression = - callExpressionPaths.inputValidator.node.arguments[0] - - if (!innerInputExpression) { - throw new Error( - 'createMiddleware().inputValidator() must be called with a validator!', - ) - } - - // If we're on the client, remove the validator call expression - if (opts.env === 'client') { - if ( - t.isMemberExpression(callExpressionPaths.inputValidator.node.callee) - ) { - callExpressionPaths.inputValidator.replaceWith( - callExpressionPaths.inputValidator.node.callee.object, - ) - } - } - } - - const serverFnPath = callExpressionPaths.server?.get( - 'arguments.0', - ) as babel.NodePath - - if ( - callExpressionPaths.server && - serverFnPath.node && - opts.env === 'client' - ) { - // If we're on the client, remove the server call expression - if (t.isMemberExpression(callExpressionPaths.server.node.callee)) { - callExpressionPaths.server.replaceWith( - callExpressionPaths.server.node.callee.object, - ) - } - } -} diff --git a/packages/start-plugin-core/src/create-server-fn-plugin/handleCreateServerFn.ts b/packages/start-plugin-core/src/create-server-fn-plugin/handleCreateServerFn.ts deleted file mode 100644 index 140a4fbdce..0000000000 --- a/packages/start-plugin-core/src/create-server-fn-plugin/handleCreateServerFn.ts +++ /dev/null @@ -1,157 +0,0 @@ -import * as t from '@babel/types' -import { - codeFrameError, - getRootCallExpression, -} from '../start-compiler-plugin/utils' -import type * as babel from '@babel/core' - -export function handleCreateServerFn( - path: babel.NodePath, - opts: { - env: 'client' | 'server' - code: string - directive: string - }, -) { - // Traverse the member expression and find the call expressions for - // the validator, handler, and middleware methods. Check to make sure they - // are children of the createServerFn call expression. - - const validMethods = ['middleware', 'inputValidator', 'handler'] as const - type ValidMethods = (typeof validMethods)[number] - const callExpressionPaths: Record< - ValidMethods, - babel.NodePath | null - > = { - middleware: null, - inputValidator: null, - handler: null, - } - - const rootCallExpression = getRootCallExpression(path) - - // if (debug) - // console.info( - // 'Handling createServerFn call expression:', - // rootCallExpression.toString(), - // ) - - // Check if the call is assigned to a variable - if (!rootCallExpression.parentPath.isVariableDeclarator()) { - throw new Error('createServerFn must be assigned to a variable!') - } - - // Get the identifier name of the variable - const variableDeclarator = rootCallExpression.parentPath.node - const existingVariableName = (variableDeclarator.id as t.Identifier).name - - rootCallExpression.traverse({ - MemberExpression(memberExpressionPath) { - if (t.isIdentifier(memberExpressionPath.node.property)) { - const name = memberExpressionPath.node.property.name as ValidMethods - - if ( - validMethods.includes(name) && - memberExpressionPath.parentPath.isCallExpression() - ) { - callExpressionPaths[name] = memberExpressionPath.parentPath - } - } - }, - }) - - if (callExpressionPaths.inputValidator) { - const innerInputExpression = - callExpressionPaths.inputValidator.node.arguments[0] - - if (!innerInputExpression) { - throw new Error( - 'createServerFn().inputValidator() must be called with a validator!', - ) - } - - // If we're on the client, remove the validator call expression - if (opts.env === 'client') { - if ( - t.isMemberExpression(callExpressionPaths.inputValidator.node.callee) - ) { - callExpressionPaths.inputValidator.replaceWith( - callExpressionPaths.inputValidator.node.callee.object, - ) - } - } - } - - // First, we need to move the handler function to a nested function call - // that is applied to the arguments passed to the server function. - - const handlerFnPath = callExpressionPaths.handler?.get( - 'arguments.0', - ) as babel.NodePath - - if (!callExpressionPaths.handler || !handlerFnPath.node) { - throw codeFrameError( - opts.code, - path.node.callee.loc!, - `createServerFn must be called with a "handler" property!`, - ) - } - - const handlerFn = handlerFnPath.node - - // So, the way we do this is we give the handler function a way - // to access the serverFn ctx on the server via function scope. - // The 'use server' extracted function will be called with the - // payload from the client, then use the scoped serverFn ctx - // to execute the handler function. - // This way, we can do things like data and middleware validation - // in the __execute function without having to AST transform the - // handler function too much itself. - - // .handler((optsOut, ctx) => { - // return ((optsIn) => { - // 'use server' - // ctx.__execute(handlerFn, optsIn) - // })(optsOut) - // }) - - // If the handler function is an identifier and we're on the client, we need to - // remove the bound function from the file. - // If we're on the server, you can leave it, since it will get referenced - // as a second argument. - - if (t.isIdentifier(handlerFn)) { - if (opts.env === 'client') { - // Find the binding for the handler function - const binding = handlerFnPath.scope.getBinding(handlerFn.name) - // Remove it - if (binding) { - binding.path.remove() - } - } - // If the env is server, just leave it alone - } - - handlerFnPath.replaceWith( - t.arrowFunctionExpression( - [t.identifier('opts'), t.identifier('signal')], - t.blockStatement( - // Everything in here is server-only, since the client - // will strip out anything in the 'use server' directive. - [ - t.returnStatement( - t.callExpression( - t.identifier(`${existingVariableName}.__executeServer`), - [t.identifier('opts'), t.identifier('signal')], - ), - ), - ], - [t.directive(t.directiveLiteral(opts.directive))], - ), - ), - ) - - if (opts.env === 'server') { - callExpressionPaths.handler.node.arguments.push(handlerFn) - } -} diff --git a/packages/start-plugin-core/src/create-server-fn-plugin/plugin.ts b/packages/start-plugin-core/src/create-server-fn-plugin/plugin.ts deleted file mode 100644 index 7afd4f9432..0000000000 --- a/packages/start-plugin-core/src/create-server-fn-plugin/plugin.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { TRANSFORM_ID_REGEX } from '../constants' -import { ServerFnCompiler } from './compiler' -import type { LookupConfig, LookupKind } from './compiler' -import type { CompileStartFrameworkOptions } from '../start-compiler-plugin/compilers' -import type { PluginOption } from 'vite' - -function cleanId(id: string): string { - return id.split('?')[0]! -} - -const LookupKindsPerEnv: Record<'client' | 'server', Set> = { - client: new Set(['Middleware', 'ServerFn'] as const), - server: new Set(['ServerFn'] as const), -} - -const getLookupConfigurationsForEnv = ( - env: 'client' | 'server', - framework: CompileStartFrameworkOptions, -): Array => { - const createServerFnConfig: LookupConfig = { - libName: `@tanstack/${framework}-start`, - rootExport: 'createServerFn', - } - if (env === 'client') { - return [ - { - libName: `@tanstack/${framework}-start`, - rootExport: 'createMiddleware', - }, - { - libName: `@tanstack/${framework}-start`, - rootExport: 'createStart', - }, - - createServerFnConfig, - ] - } else { - return [createServerFnConfig] - } -} -const SERVER_FN_LOOKUP = 'server-fn-module-lookup' -export function createServerFnPlugin(opts: { - framework: CompileStartFrameworkOptions - directive: string - environments: Array<{ name: string; type: 'client' | 'server' }> -}): PluginOption { - const compilers: Record = {} - - function perEnvServerFnPlugin(environment: { - name: string - type: 'client' | 'server' - }): PluginOption { - // in server environments, we don't transform middleware calls - const transformCodeFilter = - environment.type === 'client' - ? [/\.\s*handler\(/, /\.\s*createMiddleware\(\)/] - : [/\.\s*handler\(/] - - return { - name: `tanstack-start-core::server-fn:${environment.name}`, - enforce: 'pre', - applyToEnvironment(env) { - return env.name === environment.name - }, - transform: { - filter: { - id: { - exclude: new RegExp(`${SERVER_FN_LOOKUP}$`), - include: TRANSFORM_ID_REGEX, - }, - code: { - include: transformCodeFilter, - }, - }, - async handler(code, id) { - let compiler = compilers[this.environment.name] - if (!compiler) { - compiler = new ServerFnCompiler({ - env: environment.type, - directive: opts.directive, - lookupKinds: LookupKindsPerEnv[environment.type], - lookupConfigurations: getLookupConfigurationsForEnv( - environment.type, - opts.framework, - ), - loadModule: async (id: string) => { - if (this.environment.mode === 'build') { - const loaded = await this.load({ id }) - if (!loaded.code) { - throw new Error(`could not load module ${id}`) - } - compiler!.ingestModule({ code: loaded.code, id }) - } else if (this.environment.mode === 'dev') { - /** - * in dev, vite does not return code from `ctx.load()` - * so instead, we need to take a different approach - * we must force vite to load the module and run it through the vite plugin pipeline - * we can do this by using the `fetchModule` method - * the `captureServerFnModuleLookupPlugin` captures the module code via its transform hook and invokes analyzeModuleAST - */ - await this.environment.fetchModule( - id + '?' + SERVER_FN_LOOKUP, - ) - } else { - throw new Error( - `could not load module ${id}: unknown environment mode ${this.environment.mode}`, - ) - } - }, - resolveId: async (source: string, importer?: string) => { - const r = await this.resolve(source, importer) - if (r) { - if (!r.external) { - return cleanId(r.id) - } - } - return null - }, - }) - compilers[this.environment.name] = compiler - } - - id = cleanId(id) - const result = await compiler.compile({ id, code }) - return result - }, - }, - - hotUpdate(ctx) { - const compiler = compilers[this.environment.name] - - ctx.modules.forEach((m) => { - if (m.id) { - const deleted = compiler?.invalidateModule(m.id) - if (deleted) { - m.importers.forEach((importer) => { - if (importer.id) { - compiler?.invalidateModule(importer.id) - } - }) - } - } - }) - }, - } - } - - return [ - ...opts.environments.map(perEnvServerFnPlugin), - { - name: 'tanstack-start-core:capture-server-fn-module-lookup', - // we only need this plugin in dev mode - apply: 'serve', - applyToEnvironment(env) { - return !!opts.environments.find((e) => e.name === env.name) - }, - transform: { - filter: { - id: new RegExp(`${SERVER_FN_LOOKUP}$`), - }, - handler(code, id) { - const compiler = compilers[this.environment.name] - compiler?.ingestModule({ code, id: cleanId(id) }) - }, - }, - }, - ] -} diff --git a/packages/start-plugin-core/src/dev-server-plugin/extract-html-scripts.ts b/packages/start-plugin-core/src/dev-server-plugin/extract-html-scripts.ts deleted file mode 100644 index 41e3ac44a9..0000000000 --- a/packages/start-plugin-core/src/dev-server-plugin/extract-html-scripts.ts +++ /dev/null @@ -1,19 +0,0 @@ -import * as cheerio from 'cheerio' - -export function extractHtmlScripts( - html: string, -): Array<{ content?: string; src?: string }> { - const $ = cheerio.load(html) - const scripts: Array<{ content?: string; src?: string }> = [] - - $('script').each((_, element) => { - const src = $(element).attr('src') - const content = $(element).html() ?? undefined - scripts.push({ - src, - content, - }) - }) - - return scripts -} diff --git a/packages/start-plugin-core/src/dev-server-plugin/plugin.ts b/packages/start-plugin-core/src/dev-server-plugin/plugin.ts deleted file mode 100644 index fccbfb09de..0000000000 --- a/packages/start-plugin-core/src/dev-server-plugin/plugin.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { isRunnableDevEnvironment } from 'vite' -import { VIRTUAL_MODULES } from '@tanstack/start-server-core' -import { NodeRequest, sendNodeResponse } from 'srvx/node' -import { ENTRY_POINTS, VITE_ENVIRONMENT_NAMES } from '../constants' -import { resolveViteId } from '../utils' -import { extractHtmlScripts } from './extract-html-scripts' -import type { Connect, DevEnvironment, PluginOption } from 'vite' -import type { TanStackStartOutputConfig } from '../schema' - -export function devServerPlugin({ - getConfig, -}: { - getConfig: () => { startConfig: TanStackStartOutputConfig } -}): PluginOption { - let isTest = false - - let injectedHeadScripts: string | undefined - - return [ - { - name: 'tanstack-start-core:dev-server', - config(_userConfig, { mode }) { - isTest = isTest ? isTest : mode === 'test' - }, - async configureServer(viteDevServer) { - if (isTest) { - return - } - - // Extract the scripts that Vite plugins would inject into the initial HTML - const templateHtml = `` - const transformedHtml = await viteDevServer.transformIndexHtml( - '/', - templateHtml, - ) - const scripts = extractHtmlScripts(transformedHtml) - injectedHeadScripts = scripts - .flatMap((script) => script.content ?? []) - .join(';') - - return () => { - const serverEnv = viteDevServer.environments[ - VITE_ENVIRONMENT_NAMES.server - ] as DevEnvironment | undefined - - if (!serverEnv) { - throw new Error( - `Server environment ${VITE_ENVIRONMENT_NAMES.server} not found`, - ) - } - const { startConfig } = getConfig() - const installMiddleware = startConfig.vite?.installDevServerMiddleware - if (installMiddleware === false) { - return - } - if (installMiddleware == undefined) { - // do not install middleware in middlewareMode by default - if (viteDevServer.config.server.middlewareMode) { - return - } - - // do not install middleware if SSR env in case another plugin already did - if ( - !isRunnableDevEnvironment(serverEnv) || - // do not check via `isFetchableDevEnvironment` since nitro does implement the `FetchableDevEnvironment` interface but not via inheritance (which this helper checks) - 'dispatchFetch' in serverEnv - ) { - return - } - } - - if (!isRunnableDevEnvironment(serverEnv)) { - throw new Error( - 'cannot install vite dev server middleware for TanStack Start since the SSR environment is not a RunnableDevEnvironment', - ) - } - - viteDevServer.middlewares.use(async (req, res) => { - // fix the request URL to match the original URL - // otherwise, the request URL will '/index.html' - if (req.originalUrl) { - req.url = req.originalUrl - } - const webReq = new NodeRequest({ req, res }) - - try { - // Import and resolve the request by running the server request entry point - // this request entry point must implement the `fetch` API as follows: - /** - * export default { - * fetch(req: Request): Promise - * } - */ - const serverEntry = await serverEnv.runner.import( - ENTRY_POINTS.server, - ) - const webRes = await serverEntry['default'].fetch(webReq) - - return sendNodeResponse(res, webRes) - } catch (e) { - console.error(e) - try { - viteDevServer.ssrFixStacktrace(e as Error) - } catch (_e) {} - - if ( - webReq.headers.get('content-type')?.includes('application/json') - ) { - return sendNodeResponse( - res, - new Response( - JSON.stringify( - { - status: 500, - error: 'Internal Server Error', - message: - 'An unexpected error occurred. Please try again later.', - timestamp: new Date().toISOString(), - }, - null, - 2, - ), - { - status: 500, - headers: { - 'Content-Type': 'application/json', - }, - }, - ), - ) - } - - return sendNodeResponse( - res, - new Response( - ` - - - - - Error - - - - - - `, - { - status: 500, - headers: { - 'Content-Type': 'text/html', - }, - }, - ), - ) - } - }) - } - }, - }, - { - name: 'tanstack-start-core:dev-server:injected-head-scripts', - sharedDuringBuild: true, - applyToEnvironment: (env) => env.config.consumer === 'server', - resolveId: { - filter: { id: new RegExp(VIRTUAL_MODULES.injectedHeadScripts) }, - handler(_id) { - return resolveViteId(VIRTUAL_MODULES.injectedHeadScripts) - }, - }, - load: { - filter: { - id: new RegExp(resolveViteId(VIRTUAL_MODULES.injectedHeadScripts)), - }, - handler() { - const mod = ` - export const injectedHeadScripts = ${JSON.stringify(injectedHeadScripts) || 'undefined'}` - return mod - }, - }, - }, - ] -} - -/** - * Formats error for SSR message in error overlay - * @param req - * @param error - * @returns - */ -function prepareError(req: Connect.IncomingMessage, error: unknown) { - const e = error as Error - return { - message: `An error occurred while server rendering ${req.url}:\n\n\t${ - typeof e === 'string' ? e : e.message - } `, - stack: typeof e === 'string' ? '' : e.stack, - } -} diff --git a/packages/start-plugin-core/src/hydrate-when-transform.ts b/packages/start-plugin-core/src/hydrate-when-transform.ts new file mode 100644 index 0000000000..d88ddb60d0 --- /dev/null +++ b/packages/start-plugin-core/src/hydrate-when-transform.ts @@ -0,0 +1,1004 @@ +import { relative } from 'node:path' +import crypto from 'node:crypto' +import babel from '@babel/core' +import * as t from '@babel/types' +import { + buildDeclarationMap, + buildDependencyGraph, + collectIdentifiersFromNode, + collectIdentifiersFromPattern, + collectLocalBindingsFromStatement, + deadCodeElimination, + expandTransitively, + findReferencedIdentifiers, + generateFromAst, + parseAst, + removeModuleLevelBindings, + retainModuleLevelDeclarations, + stripUnreferencedTopLevelExpressionStatements, + unwrapExportedDeclarations, +} from '@tanstack/router-utils' +import { tssHydrate } from './hydration-constants' +import { cleanId, codeFrameError } from './start-compiler/utils' +import type { + CompileStartFrameworkOptions, + StartCompilerPlugin, + StartCompilerTransformResult, +} from './types' + +export class MissingHydrateSourceError extends Error { + constructor(id: string) { + super( + `Missing Hydrate source for virtual module ${id}. The parent module must be transformed before its Hydrate child chunk is loaded.`, + ) + } +} + +/** + * Detection pattern used by the transform code filter to pre-scan files for + * `` JSX before any AST parsing happens. + */ +const HYDRATE_DETECTION_PATTERN = /\bHydrate\b/ + +function createBoundaryId(root: string, sourceId: string) { + const normalized = relative(root, sourceId).replaceAll('\\', '/') + const sourceHash = crypto + .createHash('sha1') + .update(normalized) + .digest('hex') + .slice(0, 10) + + return (index: number) => { + return `${index.toString(36)}_${sourceHash}` + } +} + +function getJSXElementName(node: t.JSXElement) { + const name = node.openingElement.name + return t.isJSXIdentifier(name) ? name.name : undefined +} + +function getJSXAttribute(node: t.JSXOpeningElement, name: string) { + for (const item of node.attributes) { + if (t.isJSXAttribute(item) && t.isJSXIdentifier(item.name, { name })) { + return item + } + } + + return undefined +} + +function getBooleanProp(node: t.JSXOpeningElement, name: string) { + const attr = getJSXAttribute(node, name) + if (!attr) return undefined + if (!attr.value) return true + if (t.isStringLiteral(attr.value)) return attr.value.value !== 'false' + if (t.isJSXExpressionContainer(attr.value)) { + if (t.isBooleanLiteral(attr.value.expression)) { + return attr.value.expression.value + } + } + return undefined +} + +function parseHydrateVirtualId(id: string) { + const queryIndex = id.indexOf('?') + const sourceId = cleanId(queryIndex === -1 ? id : id.slice(0, queryIndex)) + if (queryIndex === -1) { + return { sourceId, splitId: null, boundaryIndex: -1 } + } + + const rawQuery = id.slice(queryIndex + 1) + const params = new URLSearchParams(rawQuery) + const splitId = params.get(tssHydrate) + let boundaryIndex = -1 + if (splitId) { + const separatorIndex = splitId.indexOf('_') + if (separatorIndex > 0) { + const parsedIndex = Number.parseInt(splitId.slice(0, separatorIndex), 36) + if (Number.isInteger(parsedIndex)) { + boundaryIndex = parsedIndex + } + } + } + + return { + sourceId, + splitId, + boundaryIndex, + } +} + +function isObjectPropertyName( + property: t.ObjectMethod | t.ObjectProperty, + name: string, +) { + if (t.isIdentifier(property.key) && !property.computed) { + return property.key.name === name + } + + return t.isStringLiteral(property.key) && property.key.value === name +} + +function isReferenceInsideAnyNode( + referencePath: babel.NodePath, + nodes: ReadonlySet, +) { + if (nodes.has(referencePath.node)) return true + return Boolean(referencePath.findParent((parent) => nodes.has(parent.node))) +} + +function stripBindingsOnlyReferencedBy( + path: babel.NodePath, + node: t.Node, + seen = new Set(), + preserve = new Set(), +) { + stripBindingsOnlyReferencedByNodes(path.scope, [node], seen, preserve) +} + +function stripBindingsOnlyReferencedByNodes( + scope: babel.NodePath['scope'], + nodes: ReadonlyArray, + seen = new Set(), + preserve = new Set(), +) { + const nodeSet = new Set(nodes) + const names = new Set() + nodes.forEach((node) => { + collectIdentifiersFromNode(node).forEach((name) => names.add(name)) + }) + + for (const name of names) { + if (seen.has(name)) continue + if (preserve.has(name)) continue + const binding = scope.getBinding(name) + if (!binding?.constant) continue + if ( + binding.path.findParent( + (parentPath) => + parentPath.isExportNamedDeclaration() || + parentPath.isExportDefaultDeclaration(), + ) + ) { + continue + } + if (binding.referencePaths.length === 0) continue + if ( + !binding.referencePaths.every((referencePath) => + isReferenceInsideAnyNode(referencePath, nodeSet), + ) + ) { + continue + } + + seen.add(name) + + const declarationPath = binding.path.isVariableDeclarator() + ? binding.path + : binding.path.findParent((parentPath) => + parentPath.isVariableDeclarator(), + ) + const patternHasExternalReferences = + declarationPath?.isVariableDeclarator() && + !t.isIdentifier(declarationPath.node.id) && + collectIdentifiersFromPattern(declarationPath.node.id).some( + (bindingName) => { + if (bindingName === binding.identifier.name) return false + + const siblingBinding = binding.scope.getBinding(bindingName) + return siblingBinding?.referencePaths.some( + (referencePath) => + !isReferenceInsideAnyNode(referencePath, nodeSet), + ) + }, + ) + + if (patternHasExternalReferences) { + continue + } + + const bindingNode = binding.path.node + if (t.isVariableDeclarator(bindingNode) && bindingNode.init) { + stripBindingsOnlyReferencedByNodes( + binding.scope, + [bindingNode.init], + seen, + preserve, + ) + } else if ( + t.isFunctionDeclaration(bindingNode) || + t.isClassDeclaration(bindingNode) + ) { + stripBindingsOnlyReferencedByNodes( + binding.scope, + [bindingNode], + seen, + preserve, + ) + } + + if (binding.path.isVariableDeclarator()) { + const declarationPath = binding.path.parentPath + if ( + declarationPath.isVariableDeclaration() && + declarationPath.node.declarations.length === 1 + ) { + declarationPath.remove() + continue + } + + binding.path.remove() + continue + } + + if ( + binding.path.isImportSpecifier() || + binding.path.isImportDefaultSpecifier() || + binding.path.isImportNamespaceSpecifier() + ) { + const importPath = binding.path.parentPath + if ( + importPath.isImportDeclaration() && + importPath.node.specifiers.length === 1 + ) { + importPath.remove() + continue + } + + binding.path.remove() + continue + } + + binding.path.remove() + } +} + +function getSingleUseObjectExpressionBinding( + path: babel.NodePath, + identifier: t.Identifier, +) { + const binding = path.scope.getBinding(identifier.name) + if (!binding?.constant) return undefined + if (binding.referencePaths.length !== 1) return undefined + if (binding.referencePaths[0]?.node !== identifier) return undefined + if (!binding.path.isVariableDeclarator()) return undefined + const init = binding.path.node.init + return t.isObjectExpression(init) ? init : undefined +} + +function objectExpressionMayHaveProperty( + node: t.ObjectExpression, + name: string, +) { + return node.properties.some((property) => { + if (t.isSpreadElement(property)) return true + if (!t.isObjectMethod(property) && !t.isObjectProperty(property)) { + return true + } + if (property.computed) return true + return isObjectPropertyName(property, name) + }) +} + +function stripObjectExpressionProperty( + path: babel.NodePath, + node: t.ObjectExpression, + name: string, +) { + let modified = false + + node.properties = node.properties.filter((property) => { + if ( + (t.isObjectMethod(property) || t.isObjectProperty(property)) && + isObjectPropertyName(property, name) + ) { + stripBindingsOnlyReferencedBy( + path, + t.isObjectProperty(property) ? property.value : property.body, + ) + modified = true + return false + } + + return true + }) + + return modified +} + +function throwBoundaryError( + code: string, + path: babel.NodePath, + message: string, +): never { + if (path.node.loc) { + throw codeFrameError(code, path.node.loc, message) + } + throw new Error(message) +} + +function inspectSplitBoundary(options: { + code: string + path: babel.NodePath + validate?: boolean + collectCaptured?: boolean + nestedHydrate?: { + localName: string + } +}) { + const { path } = options + const capturedNames = options.collectCaptured ? new Set() : undefined + const nestedHydrate = options.nestedHydrate + let nestedBoundaryCount = 0 + + if (options.validate) { + for (const child of path.node.children) { + if ( + t.isJSXExpressionContainer(child) && + (t.isFunctionExpression(child.expression) || + t.isArrowFunctionExpression(child.expression)) + ) { + throwBoundaryError( + options.code, + path, + 'Hydrate cannot code-split function-as-children. Use split={false} for this boundary.', + ) + } + } + } + + const rootVisitors = { + JSXOpeningElement(openingPath: babel.NodePath) { + if (openingPath.node === path.node.openingElement) { + openingPath.skip() + } + }, + JSXClosingElement(closingPath: babel.NodePath) { + closingPath.skip() + }, + } + + const validateVisitors = options.validate + ? { + CallExpression(callPath: babel.NodePath) { + if (!t.isIdentifier(callPath.node.callee)) return + if (!/^use[A-Z0-9]/.test(callPath.node.callee.name)) return + + throwBoundaryError( + options.code, + path, + 'Hydrate cannot code-split JSX that calls hooks during render. Move the hook call into a child component or use split={false}.', + ) + }, + ThisExpression(thisPath: babel.NodePath) { + void thisPath + throwBoundaryError( + options.code, + path, + 'Hydrate cannot code-split JSX that captures this.', + ) + }, + Super(superPath: babel.NodePath) { + void superPath + throwBoundaryError( + options.code, + path, + 'Hydrate cannot code-split JSX that captures super.', + ) + }, + } + : {} + + const nestedHydrateVisitors = nestedHydrate + ? { + JSXElement(nestedPath: babel.NodePath) { + if (getJSXElementName(nestedPath.node) !== nestedHydrate.localName) { + return + } + + const split = getBooleanProp(nestedPath.node.openingElement, 'split') + if (split === false) return + + nestedBoundaryCount++ + }, + } + : {} + + const captureVisitors = capturedNames + ? { + Identifier(identifierPath: babel.NodePath) { + const parent = identifierPath.parent + if ( + t.isJSXOpeningElement(parent) || + t.isJSXClosingElement(parent) || + (t.isObjectProperty(parent, { key: identifierPath.node }) && + !parent.computed && + !parent.shorthand) || + (t.isMemberExpression(parent, { + property: identifierPath.node, + }) && + !parent.computed) + ) { + return + } + + const binding = identifierPath.scope.getBinding( + identifierPath.node.name, + ) + if (!binding) return + if (t.isProgram(binding.scope.block)) return + if ( + path.node === binding.scope.block || + path.isAncestor(binding.path) + ) + return + + capturedNames.add(identifierPath.node.name) + }, + JSXIdentifier(identifierPath: babel.NodePath) { + if (identifierPath.parentKey !== 'name') return + const name = identifierPath.node.name + if (!/^[A-Z]/.test(name)) return + const binding = identifierPath.scope.getBinding(name) + if (!binding) return + if (t.isProgram(binding.scope.block)) return + + capturedNames.add(name) + }, + } + : {} + + path.traverse({ + ...rootVisitors, + ...validateVisitors, + ...nestedHydrateVisitors, + ...captureVisitors, + }) + + return { + captured: capturedNames ? [...capturedNames].sort() : [], + nestedBoundaryCount, + } +} + +function getHydrateImport( + ast: t.File, + framework: CompileStartFrameworkOptions, +) { + const hydrateImportSource = `@tanstack/${framework}-start` + + for (const node of ast.program.body) { + if (!t.isImportDeclaration(node)) continue + if (node.source.value !== hydrateImportSource) continue + + for (const specifier of node.specifiers) { + if ( + t.isImportSpecifier(specifier) && + t.isIdentifier(specifier.imported, { name: 'Hydrate' }) + ) { + return { + hydrateLocalName: specifier.local.name, + } + } + } + } + + return undefined +} + +function getMeaningfulChildren( + children: Array, +) { + return children.filter( + (child) => !(t.isJSXText(child) && child.value.trim() === ''), + ) +} + +function transformHydrateAst(options: { + ast: t.File + code: string + id: string + root: string + env: 'client' | 'server' + framework: CompileStartFrameworkOptions + indexOffset?: number +}) { + if (!options.code.includes('Hydrate')) return null + + const hydrateImport = getHydrateImport(options.ast, options.framework) + if (!hydrateImport) return null + const { hydrateLocalName: localName } = hydrateImport + const sourceId = cleanId(options.id) + const getBoundaryId = createBoundaryId(options.root, sourceId) + + let nextBoundaryIndex = options.indexOffset ?? 0 + const state = { + modified: false, + extractedChildNodes: [] as Array, + capturedNames: new Set(), + } + let lazyIdent: t.Identifier | undefined + + babel.traverse(options.ast, { + Program(programPath) { + programPath.traverse({ + JSXElement(path) { + if (getJSXElementName(path.node) !== localName) return + + if (options.env === 'server') { + path.node.openingElement.attributes = + path.node.openingElement.attributes.filter((item) => { + if ( + t.isJSXAttribute(item) && + t.isJSXIdentifier(item.name, { name: 'fallback' }) + ) { + if (item.value) { + stripBindingsOnlyReferencedBy(path, item.value) + } + state.modified = true + return false + } + + if ( + t.isJSXSpreadAttribute(item) && + t.isObjectExpression(item.argument) + ) { + if ( + stripObjectExpressionProperty( + path, + item.argument, + 'fallback', + ) + ) { + state.modified = true + } + return item.argument.properties.length > 0 + } + + if ( + t.isJSXSpreadAttribute(item) && + t.isIdentifier(item.argument) + ) { + const init = getSingleUseObjectExpressionBinding( + path, + item.argument, + ) + if ( + init && + stripObjectExpressionProperty(path, init, 'fallback') + ) { + state.modified = true + } + } + + return true + }) + } + + const split = getBooleanProp(path.node.openingElement, 'split') + if (split === false) return + + const boundaryInspection = inspectSplitBoundary({ + code: options.code, + path, + validate: true, + collectCaptured: options.env === 'client', + ...(options.env === 'client' + ? { + nestedHydrate: { + localName, + }, + } + : {}), + }) + + const index = nextBoundaryIndex + nextBoundaryIndex += 1 + boundaryInspection.nestedBoundaryCount + const id = getBoundaryId(index) + const exportName = `H${index}` + + const existingHydrateId = getJSXAttribute( + path.node.openingElement, + 'h', + ) + if (existingHydrateId) { + existingHydrateId.value = t.stringLiteral(id) + } else { + path.node.openingElement.attributes.push( + t.jsxAttribute(t.jsxIdentifier('h'), t.stringLiteral(id)), + ) + } + state.modified = true + + if (options.env === 'server') return + + const needsPreloadProp = path.node.openingElement.attributes.some( + (attribute) => { + if (t.isJSXAttribute(attribute)) { + return t.isJSXIdentifier(attribute.name, { name: 'prefetch' }) + } + + if (t.isJSXSpreadAttribute(attribute)) { + if (t.isObjectExpression(attribute.argument)) { + return objectExpressionMayHaveProperty( + attribute.argument, + 'prefetch', + ) + } + + if (t.isIdentifier(attribute.argument)) { + const init = getSingleUseObjectExpressionBinding( + path, + attribute.argument, + ) + return init + ? objectExpressionMayHaveProperty(init, 'prefetch') + : true + } + + return true + } + + return false + }, + ) + const childReferenceNodes = getMeaningfulChildren(path.node.children) + + state.extractedChildNodes.push(...childReferenceNodes) + boundaryInspection.captured.forEach((name) => { + state.capturedNames.add(name) + }) + + if (!lazyIdent) { + lazyIdent = + programPath.scope.generateUidIdentifier('lazyRouteComponent') + programPath.unshiftContainer('body', [ + t.importDeclaration( + [ + t.importSpecifier( + lazyIdent, + t.identifier('lazyRouteComponent'), + ), + ], + t.stringLiteral(`@tanstack/${options.framework}-router`), + ), + ]) + } + + const importIdParams = new URLSearchParams() + importIdParams.set(tssHydrate, id) + const componentIdent = + programPath.scope.generateUidIdentifier(exportName) + const declarations = [ + t.variableDeclarator( + componentIdent, + t.callExpression(lazyIdent, [ + t.arrowFunctionExpression( + [], + t.callExpression(t.import(), [ + t.stringLiteral(`${sourceId}?${importIdParams.toString()}`), + ]), + ), + t.stringLiteral(exportName), + ]), + ), + ] + + let preloadIdent: t.Identifier | undefined + if (needsPreloadProp) { + preloadIdent = programPath.scope.generateUidIdentifier( + `${exportName}_preload`, + ) + declarations.push( + t.variableDeclarator( + preloadIdent, + t.memberExpression(componentIdent, t.identifier('preload')), + ), + ) + } + + programPath.unshiftContainer('body', [ + t.variableDeclaration('const', declarations), + ]) + if (preloadIdent) { + path.node.openingElement.attributes.push( + t.jsxAttribute( + t.jsxIdentifier('p'), + t.jsxExpressionContainer(preloadIdent), + ), + ) + } + + path.node.children = [ + t.jsxText('\n'), + t.jsxExpressionContainer( + t.jsxElement( + t.jsxOpeningElement( + t.jsxIdentifier(componentIdent.name), + boundaryInspection.captured.map((name) => + t.jsxAttribute( + t.jsxIdentifier(name), + t.jsxExpressionContainer(t.identifier(name)), + ), + ), + true, + ), + null, + [], + true, + ), + ), + t.jsxText('\n'), + ] + path.skip() + }, + }) + + if (state.extractedChildNodes.length > 0) { + stripBindingsOnlyReferencedByNodes( + programPath.scope, + state.extractedChildNodes, + new Set(), + state.capturedNames, + ) + } + + programPath.skip() + }, + }) + + if (!state.modified) return null + + return true +} + +function loadHydrateVirtualModule(options: { + id: string + root: string + code: string + framework: CompileStartFrameworkOptions +}) { + const { sourceId, splitId, boundaryIndex } = parseHydrateVirtualId(options.id) + if (!splitId || boundaryIndex < 0) return null + const getBoundaryId = createBoundaryId(options.root, sourceId) + + const ast = parseAst({ code: options.code, sourceFilename: sourceId }) + const hydrateImport = getHydrateImport(ast, options.framework) + if (!hydrateImport) return null + const { hydrateLocalName: localName } = hydrateImport + + let target: t.JSXElement | undefined + let targetIndex = -1 + let targetCaptured: Array = [] + let index = 0 + + babel.traverse(ast, { + JSXElement(path) { + if (getJSXElementName(path.node) !== localName) return + const split = getBooleanProp(path.node.openingElement, 'split') + if (split === false) return + + if (index === boundaryIndex) { + const id = getBoundaryId(index) + if (id !== splitId) { + path.stop() + return + } + targetCaptured = inspectSplitBoundary({ + code: options.code, + path, + collectCaptured: true, + }).captured + target = t.cloneNode(path.node, true) + targetIndex = index + path.stop() + return + } + index++ + }, + }) + + if (!target || targetIndex < 0) return null + + const children = target.children + const exportName = `H${targetIndex}` + const refIdents = findReferencedIdentifiers(ast) + + removeModuleLevelBindings(ast, new Set(['Route'])) + const localBindings = new Set() + for (const node of ast.program.body) { + collectLocalBindingsFromStatement(node, localBindings) + } + + const keepBindings = new Set() + const meaningfulChildren = getMeaningfulChildren(children) + let returnExpression: t.Expression | t.JSXElement | t.JSXFragment = + t.nullLiteral() + + if (meaningfulChildren.length === 1) { + const child = meaningfulChildren[0]! + if (t.isJSXExpressionContainer(child)) { + returnExpression = t.isJSXEmptyExpression(child.expression) + ? t.nullLiteral() + : child.expression + } else if (t.isJSXElement(child) || t.isJSXFragment(child)) { + returnExpression = child + } else if (t.isJSXText(child)) { + returnExpression = t.stringLiteral(child.value) + } + } else if (meaningfulChildren.length > 1) { + returnExpression = t.jsxFragment( + t.jsxOpeningFragment(), + t.jsxClosingFragment(), + children, + ) + } + for (const name of collectIdentifiersFromNode(returnExpression)) { + if (localBindings.has(name)) { + keepBindings.add(name) + } + } + + if (keepBindings.size > 0) { + expandTransitively( + keepBindings, + buildDependencyGraph(buildDeclarationMap(ast), localBindings), + ) + } + + retainModuleLevelDeclarations(ast, keepBindings) + unwrapExportedDeclarations(ast) + + ast.program.body.push( + t.exportNamedDeclaration( + t.functionDeclaration( + t.identifier(exportName), + targetCaptured.length > 0 + ? [ + t.objectPattern( + targetCaptured.map((name) => + t.objectProperty( + t.identifier(name), + t.identifier(name), + false, + true, + ), + ), + ), + ] + : [], + t.blockStatement([t.returnStatement(returnExpression)]), + ), + ), + ) + + deadCodeElimination(ast, refIdents) + stripUnreferencedTopLevelExpressionStatements(ast) + + const result = generateFromAst(ast, { + sourceMaps: true, + sourceFileName: options.id, + filename: options.id, + }) + return result +} + +export function createHydrateCompilerPlugin(): StartCompilerPlugin { + type SourceEntry = { + code: string + framework: CompileStartFrameworkOptions + virtualModules: Map + } + + const sourcesByEnvironment = new Map>() + + const getEnvironmentSources = (envName: string) => { + let sources = sourcesByEnvironment.get(envName) + if (!sources) { + sources = new Map() + sourcesByEnvironment.set(envName, sources) + } + return sources + } + + const setSource = ( + envName: string, + id: string, + code: string, + framework: CompileStartFrameworkOptions, + ) => { + const sourceId = cleanId(id) + const sources = getEnvironmentSources(envName) + const existing = sources.get(sourceId) + if (existing?.code === code && existing.framework === framework) { + return existing + } + + const entry = { + code, + framework, + virtualModules: new Map(), + } + sources.set(sourceId, entry) + return entry + } + + const getSourceEntry = (envName: string, id: string) => + sourcesByEnvironment.get(envName)?.get(cleanId(id)) + + const deleteSource = (envName: string, id: string) => { + sourcesByEnvironment.get(envName)?.delete(cleanId(id)) + } + + return { + name: 'tanstack-start-core:hydrate', + detect: HYDRATE_DETECTION_PATTERN, + virtualModuleIdPattern: new RegExp(`[?&]${tssHydrate}=`), + transformAst(context) { + const virtualModule = parseHydrateVirtualId(context.id) + const indexOffset = + virtualModule.boundaryIndex < 0 + ? undefined + : virtualModule.boundaryIndex + 1 + const result = transformHydrateAst({ + ast: context.ast, + code: context.code, + id: context.id, + root: context.root, + env: context.env, + framework: context.framework, + indexOffset, + }) + + if (result && virtualModule.boundaryIndex < 0) { + setSource(context.envName, context.id, context.code, context.framework) + } + + return !!result + }, + loadVirtualModule(context) { + const virtualModule = parseHydrateVirtualId(context.id) + if (!virtualModule.splitId || virtualModule.boundaryIndex < 0) { + return null + } + + const existingSourceEntry = getSourceEntry( + context.envName, + virtualModule.sourceId, + ) + const sourceEntry = + context.code === undefined + ? existingSourceEntry + : setSource( + context.envName, + virtualModule.sourceId, + context.code, + existingSourceEntry?.framework ?? + (context.code.includes('@tanstack/solid-start') + ? 'solid' + : 'react'), + ) + + if (!sourceEntry) { + throw new MissingHydrateSourceError(context.id) + } + + if (sourceEntry.virtualModules.has(context.id)) { + return sourceEntry.virtualModules.get(context.id)! + } + + const result = loadHydrateVirtualModule({ + code: sourceEntry.code, + id: context.id, + root: context.root, + framework: sourceEntry.framework, + }) + sourceEntry.virtualModules.set(context.id, result) + return result + }, + invalidateModule(context) { + deleteSource(context.envName, context.id) + }, + } +} diff --git a/packages/start-plugin-core/src/hydration-constants.ts b/packages/start-plugin-core/src/hydration-constants.ts new file mode 100644 index 0000000000..b79c20ffd3 --- /dev/null +++ b/packages/start-plugin-core/src/hydration-constants.ts @@ -0,0 +1 @@ +export const tssHydrate = 'tss-hydrate' diff --git a/packages/start-plugin-core/src/import-protection/INTERNALS.md b/packages/start-plugin-core/src/import-protection/INTERNALS.md new file mode 100644 index 0000000000..4f19e4bd7e --- /dev/null +++ b/packages/start-plugin-core/src/import-protection/INTERNALS.md @@ -0,0 +1,266 @@ +# Import Protection - Shared Internals + +## Overview + +`src/import-protection/` contains the adapter-independent core for TanStack +Start import protection. + +Its current structure is: + +- parse module code once per `TransformResult` +- derive a read-only `ImportAnalysis` object from that AST +- reuse that analysis for source extraction, import-specifier locations, mock + export discovery, named export discovery, and usage lookup +- keep AST mutation in a separate rewrite pass +- keep adapter lifecycle/state-machine behavior outside this directory + +The shared layer is responsible for correctness-sensitive logic that must stay +aligned between Vite and Rsbuild. + +## Shared Module Layout + +### `analysis.ts` + +The central shared analysis module. + +It builds and caches `ImportAnalysis` on `TransformResult.analysis`. + +`ImportAnalysis` contains: + +- parsed AST +- line index +- import sources in source order +- import specifier literal locations +- imported bindings by source +- mock export names by source +- named exports +- usage-position cache + +It exposes both result-based and code-based helpers: + +- `getOrCreateImportAnalysis(result)` +- `getImportSourcesFromResult(result)` +- `getImportSources(code)` +- `getImportSpecifierLocationFromResult(result, source)` +- `getMockExportNamesBySourceFromResult(result)` +- `getMockExportNamesBySource(code)` +- `getNamedExportsFromResult(result)` +- `getNamedExports(code)` +- `findPostCompileUsagePosFromResult(result, source)` +- `findPostCompileUsagePos(code, source)` +- `findOriginalUnsafeUsagePosFromResult(result, source, envType)` +- `findOriginalUnsafeUsagePos(code, source, envType)` +- `isValidExportName(name)` + +### `adapterUtils.ts` + +Contains small adapter-facing shared helpers for decisions that are identical in +Vite and Rsbuild. + +It currently owns: + +- environment type selection from `envTypeMap` +- environment rule selection from `compiledRules` +- normalized root-relative path calculation +- importer filtering via include/exclude/ignore/srcDirectory rules + +This keeps the adapters from duplicating the same targeting logic while still +leaving lifecycle-specific behavior in the adapter implementations. + +### `rewrite.ts` + +Contains the actual AST mutation pass for denied static imports and re-exports. + +It is intentionally separate from `analysis.ts`. + +Why: + +- analysis is read-only and cacheable +- rewrite mutates AST structure and generates code/maps +- keeping them separate prevents adapter code from depending on mutation when it + only needs inspection + +`rewriteDeniedImports()` rewrites denied static import/re-export edges to mock +module imports while preserving explicit bindings expected by the importer. + +### `sourceLocation.ts` + +Builds source locations and snippets from transformed code plus sourcemaps. + +It reuses shared analysis for two important lookups: + +- import-specifier positions in transformed code +- post-compile and original-source usage locations + +It also owns: + +- line-index helpers +- sourcemap normalization +- `sourcesContent` original-source selection +- import-location caching for traces +- code snippet formatting + +### `virtualModules.ts` + +Owns the shared mock module generators and payload encoding. + +This includes: + +- silent mock module code +- runtime diagnostic mock module code +- mock-edge module code with explicit named exports +- self-denial module generation for denied files +- marker module loading + +The adapter-specific transport of these modules is not handled here. + +### `defaults.ts`, `matchers.ts`, `utils.ts`, `trace.ts` + +These remain shared support layers: + +- `defaults.ts`: default deny/marker rules +- `matchers.ts`: compiled glob/regex matcher utilities +- `utils.ts`: path normalization, candidate generation, messages, defer logic, + generic helpers +- `trace.ts`: import graph, traces, snippet-aware message formatting + +## Analysis Lifetime And Cache Model + +The key cache decision is: analysis is cached per `TransformResult`, not +globally by source text. + +That means: + +- Vite can attach analysis to transform-cache results for the current module + version +- Rsbuild can attach analysis to transform results rebuilt from compilation or + preloaded during transform +- cache invalidation follows the host tool's normal module invalidation model +- long dev/HMR sessions do not accumulate an unbounded process-global AST cache + +The analysis object is read-only after creation, except for the internal +`usageByKey` memoization map. + +## Import Source Extraction + +`getImportSources()` is now AST-driven and returns sources in encountered order. + +It includes: + +- `import ... from 'x'` +- `export ... from 'x'` +- `export * from 'x'` +- `import('x')` +- dynamic import call forms supported by Babel's AST shape + +Adapter code that needs source extraction should call into `analysis.ts` +directly. + +## Mock Export Discovery + +Mock-edge modules need to know which named exports the importer expects. + +`analysis.ts` derives that from the importer AST by recording: + +- named import specifiers +- namespace member access +- default-import member access +- re-export specifiers + +This produces `mockExportNamesBySource`, which is a safe over-approximation of +the named exports the adapter should expose on a mock-edge module. + +## Named Export Discovery + +Self-denial needs the denied file's export surface. + +`getNamedExports()` and `getNamedExportsFromResult()` collect valid named +exports from: + +- function/class declarations +- variable declarations, including destructuring patterns +- export specifiers and aliases + +`default` is excluded from the named export list because the mock generators +handle default export separately. + +## Usage Lookup And Safe Boundaries + +Usage lookup is shared across adapters through `analysis.ts`. + +The walker: + +- tracks lexical/program/block/function bindings manually +- respects shadowing across nested scopes, block bindings, function params, and + `catch` params +- treats certain compiler-recognized boundaries as safe when looking for + original unsafe usage + +Safe boundary recognition is environment-specific: + +- client env safe boundaries: + - `createServerFn().handler(...)` + - `createMiddleware(...).server(...)` + - `createIsomorphicFn().server(...)` + - `createServerOnlyFn(...)` +- server env safe boundaries: + - `createClientOnlyFn(...)` + - `createIsomorphicFn().client(...)` + +This is the core shared logic that keeps both adapters aligned on cases like +`boundary-safe`, `factory-safe`, and `compiler-leak`. + +## Rewriting Versus Analysis + +Analysis and rewrite are intentionally separate. + +Reasons: + +- adapters frequently need inspection without mutation +- mutation wants a fresh, isolated AST/codegen pass +- read-only analysis is much easier to cache safely +- source-location helpers and usage lookup should not depend on whether a module + was rewritten + +The intended flow is: + +1. build or reuse `ImportAnalysis` +2. inspect/import-locate/trace as needed +3. if a denied-specifier rewrite is needed, run `rewriteDeniedImports()` + +## Adapter Contract + +The shared layer deliberately does not decide: + +- when a violation is discovered +- when it is reported versus deferred +- how dev/build lifecycle hooks work +- how virtual module ids/files are transported by the bundler +- how final compilation truth is obtained + +Those are adapter responsibilities. + +The shared layer does provide the primitives both adapters rely on: + +- rule helpers +- AST parsing +- analysis +- rewrite +- virtual module code generation +- source locations/snippets +- trace formatting + +## Maintainer Guidance + +When making future import-protection changes: + +1. If the behavior is about parsing, source extraction, export discovery, usage + lookup, source locations, rewrite mechanics, or mock codegen, it probably + belongs in `src/import-protection/`. +2. If the behavior is about hook timing, deferral, compilation truth, pending + queues, or environment-specific virtual-module transport, it probably belongs + in the adapter docs/code. +3. Prefer extending `ImportAnalysis` over adding new one-off parsers or wrapper + helpers. +4. Avoid reintroducing global source-text caches; cache on `TransformResult` + instead. diff --git a/packages/start-plugin-core/src/import-protection/adapterUtils.ts b/packages/start-plugin-core/src/import-protection/adapterUtils.ts new file mode 100644 index 0000000000..4893c504e4 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection/adapterUtils.ts @@ -0,0 +1,94 @@ +import { matchesAny } from './matchers' +import { isInsideDirectory, normalizeFilePath, relativizePath } from './utils' +import type { CompiledMatcher } from './matchers' + +export type ImportProtectionEnvType = 'client' | 'server' + +export interface ImportProtectionEnvRules { + specifiers: Array + files: Array + excludeFiles: Array +} + +/** + * Shared subset of adapter config used to decide which environment rules apply + * and whether an importer should be checked at all. + */ +export interface ImportProtectionAdapterConfig { + root: string + srcDirectory: string + compiledRules: { + client: ImportProtectionEnvRules + server: ImportProtectionEnvRules + } + includeMatchers: Array + excludeMatchers: Array + ignoreImporterMatchers: Array + envTypeMap: Map +} + +export function getImportProtectionRelativePath( + root: string, + absolutePath: string, +): string { + return relativizePath(normalizeFilePath(absolutePath), root) +} + +export function getImportProtectionEnvType( + config: Pick, + envName: string, +): ImportProtectionEnvType { + return config.envTypeMap.get(envName) ?? 'server' +} + +export function getImportProtectionRulesForEnvironment( + config: Pick, + envName: string, +): ImportProtectionEnvRules { + return getImportProtectionEnvType(config, envName) === 'client' + ? config.compiledRules.client + : config.compiledRules.server +} + +export function shouldCheckImportProtectionImporter( + config: Pick< + ImportProtectionAdapterConfig, + | 'root' + | 'srcDirectory' + | 'includeMatchers' + | 'excludeMatchers' + | 'ignoreImporterMatchers' + >, + importer: string, + cache?: Map, +): boolean { + const normalizedImporter = normalizeFilePath(importer) + + if (cache) { + const cached = cache.get(normalizedImporter) + if (cached !== undefined) { + return cached + } + } + + const relativePath = relativizePath(normalizedImporter, config.root) + + let result: boolean + if ( + (config.excludeMatchers.length > 0 && + matchesAny(relativePath, config.excludeMatchers)) || + (config.ignoreImporterMatchers.length > 0 && + matchesAny(relativePath, config.ignoreImporterMatchers)) + ) { + result = false + } else if (config.includeMatchers.length > 0) { + result = !!matchesAny(relativePath, config.includeMatchers) + } else if (config.srcDirectory) { + result = isInsideDirectory(normalizedImporter, config.srcDirectory) + } else { + result = true + } + + cache?.set(normalizedImporter, result) + return result +} diff --git a/packages/start-plugin-core/src/import-protection/analysis.ts b/packages/start-plugin-core/src/import-protection/analysis.ts new file mode 100644 index 0000000000..85f90b0a87 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection/analysis.ts @@ -0,0 +1,935 @@ +import * as t from '@babel/types' +import { parseAst } from '@tanstack/router-utils' + +import { buildLineIndex } from './sourceLocation' +import { getOrCreate } from './utils' +import type { LineIndex, TransformResult } from './sourceLocation' +import type { ParseAstResult } from '@tanstack/router-utils' + +export type UsagePos = { line: number; column0: number } + +type BoundaryEnv = 'client' | 'server' + +type ImportBindingInfo = { + importedLocalNames: Set +} + +type UsageCacheKey = `${BoundaryEnv | 'post'}::${string}` + +function mayContainImportOrExport(code: string): boolean { + return code.includes('import') || code.includes('export') +} + +export type ImportAnalysis = { + ast: ParseAstResult + lineIndex: LineIndex + importSourcesInOrder: Array + importSpecifierLocationIndex: Map + importBindingsBySource: Map + mockExportNamesBySource: Map> + namedExports: Array + usageByKey: Map +} + +function makeTransientResult( + code: string, + filename?: string, + perf?: TransformResult['perf'], +): TransformResult { + const result: TransformResult = { + code, + filename, + map: undefined, + originalCode: undefined, + } + + if (perf) { + result.perf = perf + } + + return result +} + +function getOrParseAst(result: TransformResult): ParseAstResult { + if (result.parsedAst) { + result.perf?.count('analysis.parseAst.cached') + return result.parsedAst + } + + const startedAt = result.perf ? performance.now() : 0 + result.perf?.count('analysis.parseAst.calls') + + try { + const ast = parseAst({ code: result.code, filename: result.filename }) + result.parsedAst = ast + return ast + } finally { + if (result.perf) { + result.perf.time('analysis.parseAst', startedAt) + } + } +} + +function getModuleExportName(node: t.Identifier | t.StringLiteral): string { + return t.isIdentifier(node) ? node.name : node.value +} + +function getStringLiteralValueStart(node: t.StringLiteral): number { + if (node.start == null) { + return -1 + } + + const raw = node.extra?.raw + if (typeof raw === 'string' && (raw.startsWith("'") || raw.startsWith('"'))) { + return node.start + 1 + } + + return node.start +} + +function isTypeOnlyImportDeclaration(node: t.ImportDeclaration): boolean { + if (node.importKind === 'type') return true + if (node.specifiers.length === 0) return false + + return node.specifiers.every( + (specifier) => + t.isImportSpecifier(specifier) && specifier.importKind === 'type', + ) +} + +function isTypeOnlyExportNamedDeclaration( + node: t.ExportNamedDeclaration, +): boolean { + if (node.exportKind === 'type') return true + if (!node.source || node.declaration || node.specifiers.length === 0) { + return false + } + + return node.specifiers.every( + (specifier) => + t.isExportSpecifier(specifier) && specifier.exportKind === 'type', + ) +} + +function collectIdentifiersFromPattern( + pattern: t.LVal, + add: (name: string) => void, +): void { + if (t.isIdentifier(pattern)) { + add(pattern.name) + } else if (t.isObjectPattern(pattern)) { + for (const prop of pattern.properties) { + if (t.isRestElement(prop)) { + collectIdentifiersFromPattern(prop.argument as t.LVal, add) + } else { + collectIdentifiersFromPattern(prop.value as t.LVal, add) + } + } + } else if (t.isArrayPattern(pattern)) { + for (const elem of pattern.elements) { + if (elem) collectIdentifiersFromPattern(elem as t.LVal, add) + } + } else if (t.isAssignmentPattern(pattern)) { + collectIdentifiersFromPattern(pattern.left, add) + } else if (t.isRestElement(pattern)) { + collectIdentifiersFromPattern(pattern.argument as t.LVal, add) + } +} + +export function isValidExportName(name: string): boolean { + if (name === 'default' || name.length === 0) return false + const first = name.charCodeAt(0) + if ( + !( + (first >= 65 && first <= 90) || + (first >= 97 && first <= 122) || + first === 95 || + first === 36 + ) + ) + return false + for (let i = 1; i < name.length; i++) { + const ch = name.charCodeAt(i) + if ( + !( + (ch >= 65 && ch <= 90) || + (ch >= 97 && ch <= 122) || + (ch >= 48 && ch <= 57) || + ch === 95 || + ch === 36 + ) + ) + return false + } + return true +} + +function buildImportAnalysis(result: TransformResult): ImportAnalysis { + const ast = getOrParseAst(result) + + const importSourcesInOrder: Array = [] + const importSpecifierLocationIndex = new Map() + const importBindingsBySource = new Map() + const memberBindingSources = new Map>() + const mockNamesBySource = new Map>() + const namedExports = new Set() + + const getBindingInfo = (source: string): ImportBindingInfo => + getOrCreate(importBindingsBySource, source, () => ({ + importedLocalNames: new Set(), + })) + + const addSpecifierLocation = (node: t.StringLiteral) => { + importSourcesInOrder.push(node.value) + + const index = getStringLiteralValueStart(node) + if (index === -1) { + return + } + + const prev = importSpecifierLocationIndex.get(node.value) + if (prev == null || index < prev) { + importSpecifierLocationIndex.set(node.value, index) + } + } + + const addMockName = (source: string, name: string) => { + if (name === 'default' || name.length === 0) return + getOrCreate(mockNamesBySource, source, () => new Set()).add(name) + } + + const addMemberBinding = (localName: string, source: string) => { + getOrCreate(memberBindingSources, localName, () => new Set()).add( + source, + ) + } + + const addNamedExport = (name: string) => { + if (name !== 'default' && name.length > 0) { + namedExports.add(name) + } + } + + const visit = (node: t.Node): void => { + if (t.isImportDeclaration(node)) { + const isTypeOnly = isTypeOnlyImportDeclaration(node) + if (!isTypeOnly) { + addSpecifierLocation(node.source) + const source = node.source.value + const bindingInfo = getBindingInfo(source) + for (const specifier of node.specifiers) { + if (t.isImportNamespaceSpecifier(specifier)) { + bindingInfo.importedLocalNames.add(specifier.local.name) + addMemberBinding(specifier.local.name, source) + continue + } + + if (t.isImportDefaultSpecifier(specifier)) { + bindingInfo.importedLocalNames.add(specifier.local.name) + addMemberBinding(specifier.local.name, source) + continue + } + + if (!t.isImportSpecifier(specifier)) continue + if (specifier.importKind === 'type') continue + + bindingInfo.importedLocalNames.add(specifier.local.name) + const importedName = getModuleExportName(specifier.imported) + if (importedName !== 'default') { + addMockName(source, importedName) + } + } + } + } else if (t.isExportNamedDeclaration(node)) { + const isTypeOnly = isTypeOnlyExportNamedDeclaration(node) + if (!isTypeOnly && node.source && t.isStringLiteral(node.source)) { + addSpecifierLocation(node.source) + } + + if (!isTypeOnly && node.source?.value) { + const source = node.source.value + for (const specifier of node.specifiers) { + if (!t.isExportSpecifier(specifier)) continue + if (specifier.exportKind === 'type') continue + addMockName(source, getModuleExportName(specifier.local)) + } + } + + if (!isTypeOnly) { + if (node.declaration) { + const decl = node.declaration + if (t.isFunctionDeclaration(decl) || t.isClassDeclaration(decl)) { + if (decl.id?.name) addNamedExport(decl.id.name) + } else if (t.isVariableDeclaration(decl)) { + for (const d of decl.declarations) { + collectIdentifiersFromPattern(d.id as t.LVal, addNamedExport) + } + } + } + + for (const specifier of node.specifiers) { + if (!t.isExportSpecifier(specifier)) continue + if (specifier.exportKind === 'type') continue + const exportedName = getModuleExportName(specifier.exported) + addNamedExport(exportedName) + } + } + } else if (t.isExportAllDeclaration(node)) { + if (node.exportKind !== 'type') { + addSpecifierLocation(node.source) + } + } else if (t.isImportExpression(node)) { + if (t.isStringLiteral(node.source)) { + addSpecifierLocation(node.source) + } + } else if (t.isCallExpression(node) && t.isImport(node.callee)) { + const sourceNode = node.arguments[0] + if (t.isStringLiteral(sourceNode)) { + addSpecifierLocation(sourceNode) + } + } else if ( + t.isMemberExpression(node) || + t.isOptionalMemberExpression(node) + ) { + const object = node.object + if (t.isIdentifier(object)) { + const sources = memberBindingSources.get(object.name) + if (sources) { + const property = node.property + for (const source of sources) { + if (!node.computed && t.isIdentifier(property)) { + addMockName(source, property.name) + } else if (node.computed && t.isStringLiteral(property)) { + addMockName(source, property.value) + } + } + } + } + } + + const keys = t.VISITOR_KEYS[node.type] + if (!keys) return + for (const key of keys) { + const child = (node as unknown as Record)[key] + if (Array.isArray(child)) { + for (const item of child) { + if (item && typeof item === 'object' && 'type' in item) { + visit(item as t.Node) + } + } + } else if (child && typeof child === 'object' && 'type' in child) { + visit(child as t.Node) + } + } + } + + visit(ast.program) + + const mockExportNamesBySource = new Map>() + for (const [source, names] of mockNamesBySource) { + mockExportNamesBySource.set(source, Array.from(names).sort()) + } + + const lineIndex = result.lineIndex ?? buildLineIndex(result.code) + result.lineIndex = lineIndex + + const analysis = { + ast, + lineIndex, + importSourcesInOrder, + importSpecifierLocationIndex, + importBindingsBySource, + mockExportNamesBySource, + namedExports: Array.from(namedExports).sort(), + usageByKey: new Map(), + } + + return analysis +} + +export function getOrCreateImportAnalysis( + result: TransformResult, +): ImportAnalysis { + if (!result.analysis) { + result.analysis = buildImportAnalysis(result) + } + + return result.analysis +} + +export function getImportSourcesFromResult( + result: TransformResult, +): Array { + if (!mayContainImportOrExport(result.code)) { + return [] + } + + return getOrCreateImportAnalysis(result).importSourcesInOrder +} + +export function getImportSources( + code: string, + filename?: string, + perf?: TransformResult['perf'], +): Array { + return getImportSourcesFromResult(makeTransientResult(code, filename, perf)) +} + +export function getImportSpecifierLocationFromResult( + result: TransformResult, + source: string, +): number { + return ( + getOrCreateImportAnalysis(result).importSpecifierLocationIndex.get( + source, + ) ?? -1 + ) +} + +export function getMockExportNamesBySourceFromResult( + result: TransformResult, +): Map> { + return getOrCreateImportAnalysis(result).mockExportNamesBySource +} + +export function getMockExportNamesBySource( + code: string, + filename?: string, + perf?: TransformResult['perf'], +): Map> { + return getMockExportNamesBySourceFromResult( + makeTransientResult(code, filename, perf), + ) +} + +export function getNamedExportsFromResult( + result: TransformResult, +): Array { + return getOrCreateImportAnalysis(result).namedExports +} + +export function getNamedExports( + code: string, + filename?: string, + perf?: TransformResult['perf'], +): Array { + return getNamedExportsFromResult(makeTransientResult(code, filename, perf)) +} + +function isCompilerSafeBoundaryCall( + call: t.CallExpression, + fnNode: t.Function, + envType: BoundaryEnv, +): boolean { + const directArgument = call.arguments.some((arg) => arg === fnNode) + if (!directArgument) { + return false + } + + const callee = call.callee + + if (t.isIdentifier(callee)) { + return envType === 'client' + ? callee.name === 'createServerOnlyFn' + : callee.name === 'createClientOnlyFn' + } + + if (!t.isMemberExpression(callee) || callee.computed) { + return false + } + + if (!t.isIdentifier(callee.property)) { + return false + } + + const prop = callee.property.name + const rootName = getCalleeRootName(callee.object) + + if (envType === 'client') { + if (prop === 'handler') { + return rootName === 'createServerFn' || /ServerFn$/.test(rootName ?? '') + } + + if (prop === 'server') { + return ( + rootName === 'createMiddleware' || + rootName === 'createIsomorphicFn' || + /Middleware$/.test(rootName ?? '') + ) + } + + return false + } + + if (prop === 'client') { + return rootName === 'createIsomorphicFn' + } + + return false +} + +function getCalleeRootName( + node: t.Expression | t.Super | t.V8IntrinsicIdentifier, +): string | undefined { + if (t.isIdentifier(node)) { + return node.name + } + + if (t.isCallExpression(node)) { + return getCalleeRootName(node.callee) + } + + if (t.isMemberExpression(node)) { + return getCalleeRootName(node.object) + } + + return undefined +} + +function getBoundNamesFromPattern(pattern: t.LVal, out: Set): void { + if (t.isIdentifier(pattern)) { + out.add(pattern.name) + } else if (t.isObjectPattern(pattern)) { + for (const prop of pattern.properties) { + if (t.isRestElement(prop)) { + getBoundNamesFromPattern(prop.argument as t.LVal, out) + } else { + getBoundNamesFromPattern(prop.value as t.LVal, out) + } + } + } else if (t.isArrayPattern(pattern)) { + for (const elem of pattern.elements) { + if (elem) getBoundNamesFromPattern(elem as t.LVal, out) + } + } else if (t.isAssignmentPattern(pattern)) { + getBoundNamesFromPattern(pattern.left, out) + } else if (t.isRestElement(pattern)) { + getBoundNamesFromPattern(pattern.argument as t.LVal, out) + } +} + +function addPatternBindingsIfTracked( + pattern: t.LVal, + tracked: Set, + out: Set, +): void { + const names = new Set() + getBoundNamesFromPattern(pattern, names) + for (const name of names) { + if (tracked.has(name)) { + out.add(name) + } + } +} + +function collectHoistedVarBindings( + node: t.Node, + tracked: Set, + out: Set, + isRoot = true, +): void { + if (!isRoot && t.isFunction(node)) { + return + } + + if (t.isVariableDeclaration(node) && node.kind === 'var') { + for (const decl of node.declarations) { + addPatternBindingsIfTracked(decl.id as t.LVal, tracked, out) + } + } + + const keys = t.VISITOR_KEYS[node.type] + if (!keys) return + for (const key of keys) { + const child = (node as unknown as Record)[key] + if (Array.isArray(child)) { + for (const item of child) { + if (item && typeof item === 'object' && 'type' in item) { + collectHoistedVarBindings(item as t.Node, tracked, out, false) + } + } + } else if (child && typeof child === 'object' && 'type' in child) { + collectHoistedVarBindings(child as t.Node, tracked, out, false) + } + } +} + +function collectProgramBindings( + program: t.Program, + tracked: Set, +): Set { + const bindings = new Set() + + for (const node of program.body) { + if (t.isVariableDeclaration(node)) { + for (const decl of node.declarations) { + addPatternBindingsIfTracked(decl.id as t.LVal, tracked, bindings) + } + continue + } + + if (t.isFunctionDeclaration(node) || t.isClassDeclaration(node)) { + if (node.id && tracked.has(node.id.name)) { + bindings.add(node.id.name) + } + } + } + + return bindings +} + +function collectBlockBindings( + block: t.BlockStatement, + tracked: Set, +): Set { + const bindings = new Set() + + for (const node of block.body) { + if (t.isVariableDeclaration(node) && node.kind !== 'var') { + for (const decl of node.declarations) { + addPatternBindingsIfTracked(decl.id as t.LVal, tracked, bindings) + } + continue + } + + if (t.isFunctionDeclaration(node) || t.isClassDeclaration(node)) { + if (node.id && tracked.has(node.id.name)) { + bindings.add(node.id.name) + } + } + } + + return bindings +} + +function collectFunctionBindings( + fn: t.Function, + tracked: Set, +): Set { + const bindings = new Set() + + if ( + (t.isFunctionDeclaration(fn) || t.isFunctionExpression(fn)) && + fn.id && + tracked.has(fn.id.name) + ) { + bindings.add(fn.id.name) + } + + for (const param of fn.params) { + addPatternBindingsIfTracked(param as t.LVal, tracked, bindings) + } + + if (t.isBlockStatement(fn.body)) { + collectHoistedVarBindings(fn.body, tracked, bindings) + } + + return bindings +} + +type UsageWalkContext = { + parents: Array + scopeStack: Array> +} + +function isShadowedByScope( + name: string, + scopeStack: Array>, +): boolean { + for (let i = scopeStack.length - 1; i >= 0; i--) { + if (scopeStack[i]?.has(name)) { + return true + } + } + return false +} + +function isBindingIdentifierInParent( + node: t.Identifier, + parent: t.Node | undefined, +): boolean { + if (!parent) return false + + if (t.isImportSpecifier(parent) || t.isImportDefaultSpecifier(parent)) { + return parent.local === node + } + if (t.isImportNamespaceSpecifier(parent)) { + return parent.local === node + } + if (t.isFunctionDeclaration(parent) || t.isFunctionExpression(parent)) { + return ( + parent.id === node || parent.params.includes(node as unknown as t.Pattern) + ) + } + if (t.isArrowFunctionExpression(parent)) { + return parent.params.includes(node as unknown as t.Pattern) + } + if (t.isClassDeclaration(parent) || t.isClassExpression(parent)) { + return parent.id === node + } + if (t.isVariableDeclarator(parent)) { + return parent.id === node + } + if (t.isCatchClause(parent)) { + return parent.param === node + } + + return false +} + +function isInsideCompilerSafeBoundaryNodes( + parents: Array, + envType: BoundaryEnv, +): boolean { + for (let i = parents.length - 1; i >= 0; i--) { + const node = parents[i]! + if (!t.isFunction(node)) { + continue + } + + const call = parents[i - 1] + if ( + call && + t.isCallExpression(call) && + isCompilerSafeBoundaryCall(call, node, envType) + ) { + return true + } + } + + return false +} + +function findUsagePosInAnalysis( + result: TransformResult, + source: string, + envType?: BoundaryEnv, +): UsagePos | undefined { + const analysis = getOrCreateImportAnalysis(result) + const cacheKey: UsageCacheKey = `${envType ?? 'post'}::${source}` + if (analysis.usageByKey.has(cacheKey)) { + return analysis.usageByKey.get(cacheKey) ?? undefined + } + + const imported = + analysis.importBindingsBySource.get(source)?.importedLocalNames + if (!imported || imported.size === 0) { + analysis.usageByKey.set(cacheKey, null) + return undefined + } + + let preferred: UsagePos | undefined + let anyUsage: UsagePos | undefined + + const visit = (node: t.Node, ctx: UsageWalkContext): void => { + if (preferred && anyUsage) { + return + } + + if (t.isProgram(node)) { + const nextCtx = { + parents: [...ctx.parents, node], + scopeStack: [...ctx.scopeStack, collectProgramBindings(node, imported)], + } + for (const child of node.body) { + visit(child, nextCtx) + } + return + } + + if (t.isFunction(node)) { + const functionCtx = { + parents: [...ctx.parents, node], + scopeStack: [ + ...ctx.scopeStack, + collectFunctionBindings(node, imported), + ], + } + + visit(node.body, functionCtx) + return + } + + if (t.isBlockStatement(node)) { + const nextCtx = { + parents: [...ctx.parents, node], + scopeStack: [...ctx.scopeStack, collectBlockBindings(node, imported)], + } + for (const child of node.body) { + visit(child, nextCtx) + } + return + } + + if (t.isCatchClause(node)) { + const bindings = new Set() + if (node.param) { + addPatternBindingsIfTracked(node.param as t.LVal, imported, bindings) + } + const nextCtx = { + parents: [...ctx.parents, node], + scopeStack: bindings.size + ? [...ctx.scopeStack, bindings] + : ctx.scopeStack, + } + visit(node.body, nextCtx) + return + } + + if ( + t.isForStatement(node) && + t.isVariableDeclaration(node.init) && + node.init.kind !== 'var' + ) { + const bindings = new Set() + for (const decl of node.init.declarations) { + addPatternBindingsIfTracked(decl.id as t.LVal, imported, bindings) + } + const nextCtx = { + parents: [...ctx.parents, node], + scopeStack: bindings.size + ? [...ctx.scopeStack, bindings] + : ctx.scopeStack, + } + visit(node.init, nextCtx) + if (node.test) visit(node.test, nextCtx) + if (node.update) visit(node.update, nextCtx) + visit(node.body, nextCtx) + return + } + + if ( + (t.isForInStatement(node) || t.isForOfStatement(node)) && + t.isVariableDeclaration(node.left) && + node.left.kind !== 'var' + ) { + const bindings = new Set() + for (const decl of node.left.declarations) { + addPatternBindingsIfTracked(decl.id as t.LVal, imported, bindings) + } + const nextCtx = { + parents: [...ctx.parents, node], + scopeStack: bindings.size + ? [...ctx.scopeStack, bindings] + : ctx.scopeStack, + } + visit(node.left, nextCtx) + visit(node.right, nextCtx) + visit(node.body, nextCtx) + return + } + + const nextParents = [...ctx.parents, node] + + if (t.isIdentifier(node)) { + const parent = ctx.parents[ctx.parents.length - 1] + if (imported.has(node.name)) { + if (!isBindingIdentifierInParent(node, parent)) { + if ( + !( + t.isObjectProperty(parent) && + parent.key === node && + !parent.computed && + !parent.shorthand + ) && + !( + t.isObjectMethod(parent) && + parent.key === node && + !parent.computed + ) && + !(t.isExportSpecifier(parent) && parent.exported === node) && + !isShadowedByScope(node.name, ctx.scopeStack) && + !( + envType && isInsideCompilerSafeBoundaryNodes(ctx.parents, envType) + ) + ) { + const loc = node.loc?.start + if (loc) { + const pos: UsagePos = { line: loc.line, column0: loc.column } + const isPreferred = + (t.isCallExpression(parent) && parent.callee === node) || + (t.isNewExpression(parent) && parent.callee === node) || + ((t.isMemberExpression(parent) || + t.isOptionalMemberExpression(parent)) && + parent.object === node) + + if (isPreferred) { + preferred ||= pos + } else { + anyUsage ||= pos + } + } + } + } + } + } + + if (t.isImportDeclaration(node)) { + return + } + + const keys = t.VISITOR_KEYS[node.type] + if (!keys) return + for (const key of keys) { + const child = (node as unknown as Record)[key] + if (Array.isArray(child)) { + for (const item of child) { + if (item && typeof item === 'object' && 'type' in item) { + visit(item as t.Node, { + parents: nextParents, + scopeStack: ctx.scopeStack, + }) + } + } + } else if (child && typeof child === 'object' && 'type' in child) { + visit(child as t.Node, { + parents: nextParents, + scopeStack: ctx.scopeStack, + }) + } + } + } + + visit(analysis.ast.program, { + parents: [], + scopeStack: [], + }) + + const pos = preferred ?? anyUsage ?? null + analysis.usageByKey.set(cacheKey, pos) + return pos ?? undefined +} + +export function findPostCompileUsagePosFromResult( + result: TransformResult, + source: string, +): UsagePos | undefined { + return findUsagePosInAnalysis(result, source) +} + +export function findPostCompileUsagePos( + code: string, + source: string, +): UsagePos | undefined { + return findPostCompileUsagePosFromResult(makeTransientResult(code), source) +} + +export function findOriginalUnsafeUsagePosFromResult( + result: TransformResult, + source: string, + envType: BoundaryEnv, +): UsagePos | undefined { + return findUsagePosInAnalysis(result, source, envType) +} + +export function findOriginalUnsafeUsagePos( + code: string, + source: string, + envType: BoundaryEnv, +): UsagePos | undefined { + return findOriginalUnsafeUsagePosFromResult( + makeTransientResult(code), + source, + envType, + ) +} diff --git a/packages/start-plugin-core/src/import-protection/constants.ts b/packages/start-plugin-core/src/import-protection/constants.ts new file mode 100644 index 0000000000..4186f6af49 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection/constants.ts @@ -0,0 +1,28 @@ +export const MOCK_MODULE_ID = 'tanstack-start-import-protection:mock' +export const MOCK_BUILD_PREFIX = 'tanstack-start-import-protection:mock:build:' +export const MOCK_EDGE_PREFIX = 'tanstack-start-import-protection:mock-edge:' +export const MOCK_RUNTIME_PREFIX = + 'tanstack-start-import-protection:mock-runtime:' +export const MARKER_PREFIX = 'tanstack-start-import-protection:marker:' + +export const IMPORT_PROTECTION_DEBUG = + process.env.TSR_IMPORT_PROTECTION_DEBUG === '1' || + process.env.TSR_IMPORT_PROTECTION_DEBUG === 'true' + +export const IMPORT_PROTECTION_DEBUG_FILTER = + process.env.TSR_IMPORT_PROTECTION_DEBUG_FILTER + +export const KNOWN_SOURCE_EXTENSIONS = new Set([ + '.ts', + '.tsx', + '.mts', + '.cts', + '.js', + '.jsx', + '.mjs', + '.cjs', + '.json', +]) + +/** Vite's browser-visible prefix for virtual modules (replaces `\0`). */ +export const VITE_BROWSER_VIRTUAL_PREFIX = '/@id/__x00__' diff --git a/packages/start-plugin-core/src/import-protection/defaults.ts b/packages/start-plugin-core/src/import-protection/defaults.ts new file mode 100644 index 0000000000..40bdffd630 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection/defaults.ts @@ -0,0 +1,47 @@ +import type { ImportProtectionEnvRules } from '../schema' +import type { Pattern } from './utils' + +export interface DefaultImportProtectionRules { + client: Required + server: Required +} + +const frameworks = ['react', 'solid', 'vue'] as const + +/** + * Returns the default import protection rules. + * + * All three framework variants are always included so that, e.g., a React + * project also denies `@tanstack/solid-start/server` imports. + */ +export function getDefaultImportProtectionRules(): DefaultImportProtectionRules { + const clientSpecifiers: Array = frameworks.map( + (fw) => `@tanstack/${fw}-start/server`, + ) + + return { + client: { + specifiers: clientSpecifiers, + files: ['**/*.server.*'], + excludeFiles: ['**/node_modules/**'], + }, + server: { + specifiers: [], + files: ['**/*.client.*'], + excludeFiles: ['**/node_modules/**'], + }, + } +} + +/** + * Marker module specifiers that restrict a file to a specific environment. + */ +export function getMarkerSpecifiers(): { + serverOnly: Array + clientOnly: Array +} { + return { + serverOnly: frameworks.map((fw) => `@tanstack/${fw}-start/server-only`), + clientOnly: frameworks.map((fw) => `@tanstack/${fw}-start/client-only`), + } +} diff --git a/packages/start-plugin-core/src/import-protection/extensionlessAbsoluteIdResolver.ts b/packages/start-plugin-core/src/import-protection/extensionlessAbsoluteIdResolver.ts new file mode 100644 index 0000000000..ec4037f721 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection/extensionlessAbsoluteIdResolver.ts @@ -0,0 +1,121 @@ +import { basename, dirname, extname, isAbsolute } from 'node:path' +import { resolveModulePath } from 'exsolve' + +import { KNOWN_SOURCE_EXTENSIONS } from './constants' +import { normalizeFilePath } from './utils' + +const FILE_RESOLUTION_EXTENSIONS = [...KNOWN_SOURCE_EXTENSIONS] + +type DepKey = `file:${string}` | `dir:${string}` + +/** + * Canonicalize extensionless absolute IDs like `/src/foo.server` to the + * physical file when possible. + * + * Keeps a small cache plus a reverse index so we can invalidate on HMR + * updates without clearing the whole map. + */ +export class ExtensionlessAbsoluteIdResolver { + private entries = new Map }>() + private keysByDep = new Map>() + + clear(): void { + this.entries.clear() + this.keysByDep.clear() + } + + /** + * Invalidate any cached entries that might be affected by changes to `id`. + * We invalidate both the file and its containing directory. + */ + invalidateByFile(id: string): void { + const file = normalizeFilePath(id) + this.invalidateDep(`file:${file}`) + if (isAbsolute(file)) { + this.invalidateDep(`dir:${dirname(file)}`) + } + } + + resolve(id: string): string { + const key = normalizeFilePath(id) + const cached = this.entries.get(key) + if (cached) return cached.value + + let result = key + let resolvedPhysical: string | undefined + + if (isAbsolute(key)) { + const ext = extname(key) + if (!FILE_RESOLUTION_EXTENSIONS.includes(ext)) { + const resolved = resolveModulePath(`./${basename(key)}`, { + from: dirname(key), + extensions: FILE_RESOLUTION_EXTENSIONS, + try: true, + }) + if (resolved) { + resolvedPhysical = resolved + result = normalizeFilePath(resolved) + } + } + } + + const resolvedFile = resolvedPhysical + ? normalizeFilePath(resolvedPhysical) + : undefined + + const deps = this.buildDepsForKey(key, resolvedFile) + this.entries.set(key, { value: result, deps }) + this.indexDeps(key, deps) + return result + } + + private invalidateDep(dep: DepKey): void { + const keys = this.keysByDep.get(dep) + if (!keys) return + + // Copy because deleting keys mutates indexes. + for (const key of Array.from(keys)) { + this.deleteKey(key) + } + } + + private buildDepsForKey(key: string, resolvedFile: string | undefined) { + const deps = new Set() + deps.add(`file:${key}`) + + if (isAbsolute(key)) { + deps.add(`dir:${dirname(key)}`) + } + if (resolvedFile) { + deps.add(`file:${resolvedFile}`) + } + + return deps + } + + private indexDeps(key: string, deps: Set): void { + for (const dep of deps) { + let keys = this.keysByDep.get(dep) + if (!keys) { + keys = new Set() + this.keysByDep.set(dep, keys) + } + keys.add(key) + } + } + + private deleteKey(key: string): void { + const entry = this.entries.get(key) + this.entries.delete(key) + if (!entry) return + + for (const dep of entry.deps) { + const keys = this.keysByDep.get(dep) + if (!keys) continue + keys.delete(key) + if (keys.size === 0) { + this.keysByDep.delete(dep) + } + } + } +} diff --git a/packages/start-plugin-core/src/import-protection/matchers.ts b/packages/start-plugin-core/src/import-protection/matchers.ts new file mode 100644 index 0000000000..a5dc23a957 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection/matchers.ts @@ -0,0 +1,63 @@ +import picomatch from 'picomatch' + +import type { Pattern } from './utils' + +export interface CompiledMatcher { + pattern: Pattern + literal?: string + test: (value: string) => boolean +} + +const globLikePatternRE = /[*?![\]{}()]/ + +export function isLiteralMatcherPattern(pattern: string): boolean { + return !globLikePatternRE.test(pattern) +} + +/** + * Compile a Pattern (string glob or RegExp) into a fast test function. + * String patterns use picomatch for full glob support (**, *, ?, braces, etc.). + * RegExp patterns are used as-is. + */ +export function compileMatcher(pattern: Pattern): CompiledMatcher { + if (pattern instanceof RegExp) { + // RegExp with `g` or `y` flags are stateful because `.test()` mutates + // `lastIndex`. Reset it to keep matcher evaluation deterministic. + return { + pattern, + test: (value: string) => { + pattern.lastIndex = 0 + return pattern.test(value) + }, + } + } + + if (isLiteralMatcherPattern(pattern)) { + return { + pattern, + literal: pattern, + test: (value: string) => value === pattern, + } + } + + const isMatch = picomatch(pattern, { dot: true }) + return { pattern, test: isMatch } +} + +export function compileMatchers( + patterns: Array, +): Array { + return patterns.map(compileMatcher) +} + +export function matchesAny( + value: string, + matchers: Array, +): CompiledMatcher | undefined { + for (const matcher of matchers) { + if (matcher.test(value)) { + return matcher + } + } + return undefined +} diff --git a/packages/start-plugin-core/src/import-protection/rewrite.ts b/packages/start-plugin-core/src/import-protection/rewrite.ts new file mode 100644 index 0000000000..fb7e190476 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection/rewrite.ts @@ -0,0 +1,228 @@ +import * as t from '@babel/types' +import { generateFromAst, parseAst } from '@tanstack/router-utils' + +import { MOCK_MODULE_ID } from './constants' +import type { SourceMapLike } from './sourceLocation' +import type { ParseAstResult } from '@tanstack/router-utils' + +function getModuleExportName(node: t.Identifier | t.StringLiteral): string { + return t.isIdentifier(node) ? node.name : node.value +} + +function toMemberExpressionProperty(name: string): { + property: t.Identifier | t.StringLiteral + computed: boolean +} { + return t.isValidIdentifier(name) + ? { property: t.identifier(name), computed: false } + : { property: t.stringLiteral(name), computed: true } +} + +function toModuleExportNameNode(name: string): t.Identifier | t.StringLiteral { + return t.isValidIdentifier(name) ? t.identifier(name) : t.stringLiteral(name) +} + +function createInternalReexportVarName( + localName: string, + mockIndex: number, + usedNames: Set, +): string { + const baseName = t.isValidIdentifier(localName) + ? `__tss_reexport_${localName}` + : `__tss_reexport_${mockIndex}` + + let candidate = baseName + let suffix = 0 + while (usedNames.has(candidate)) { + suffix++ + candidate = `${baseName}_${suffix}` + } + + usedNames.add(candidate) + return candidate +} + +/** + * Rewrite static imports/re-exports from denied sources using Babel AST transforms. + * + * Transforms: + * import { a as b, c } from 'denied' + * Into: + * import __tss_deny_0 from 'tanstack-start-import-protection:mock' + * const b = __tss_deny_0.a + * const c = __tss_deny_0.c + * + * Also handles: + * import def from 'denied' -> import def from mock + * import * as ns from 'denied' -> import ns from mock + * export { x } from 'denied' -> export const x = mock.x + * export * from 'denied' -> removed + * export { x as y } from 'denied' -> export const y = mock.x + */ +export function rewriteDeniedImports( + code: string, + id: string, + deniedSources: Set, + getMockModuleId: (source: string) => string = () => MOCK_MODULE_ID, +): { code: string; map?: SourceMapLike } | undefined { + return rewriteDeniedImportsFromAst( + parseAst({ code, filename: id }), + id, + deniedSources, + getMockModuleId, + ) +} + +function rewriteDeniedImportsFromAst( + ast: ParseAstResult, + id: string, + deniedSources: Set, + getMockModuleId: (source: string) => string = () => MOCK_MODULE_ID, +): { code: string; map?: SourceMapLike } | undefined { + let modified = false + let mockCounter = 0 + + // Walk program body in reverse so splice indices stay valid + for (let i = ast.program.body.length - 1; i >= 0; i--) { + const node = ast.program.body[i]! + + if (t.isImportDeclaration(node)) { + if (node.importKind === 'type') continue + if (!deniedSources.has(node.source.value)) continue + + const mockVar = `__tss_deny_${mockCounter++}` + const replacements: Array = [] + + replacements.push( + t.importDeclaration( + [t.importDefaultSpecifier(t.identifier(mockVar))], + t.stringLiteral(getMockModuleId(node.source.value)), + ), + ) + + for (const specifier of node.specifiers) { + if ( + t.isImportDefaultSpecifier(specifier) || + t.isImportNamespaceSpecifier(specifier) + ) { + replacements.push( + t.variableDeclaration('const', [ + t.variableDeclarator( + t.identifier(specifier.local.name), + t.identifier(mockVar), + ), + ]), + ) + } else if (t.isImportSpecifier(specifier)) { + if (specifier.importKind === 'type') continue + const importedName = getModuleExportName(specifier.imported) + const memberProperty = toMemberExpressionProperty(importedName) + replacements.push( + t.variableDeclaration('const', [ + t.variableDeclarator( + t.identifier(specifier.local.name), + t.memberExpression( + t.identifier(mockVar), + memberProperty.property, + memberProperty.computed, + ), + ), + ]), + ) + } + } + + ast.program.body.splice(i, 1, ...replacements) + modified = true + continue + } + + if (t.isExportNamedDeclaration(node) && node.source) { + if (node.exportKind === 'type') continue + if (!deniedSources.has(node.source.value)) continue + + const mockIndex = mockCounter++ + const mockVar = `__tss_deny_${mockIndex}` + const replacements: Array = [] + + replacements.push( + t.importDeclaration( + [t.importDefaultSpecifier(t.identifier(mockVar))], + t.stringLiteral(getMockModuleId(node.source.value)), + ), + ) + const usedInternalVars = new Set() + const exportSpecifiers: Array<{ + localName: string + exportedName: string + }> = [] + for (const specifier of node.specifiers) { + if (t.isExportSpecifier(specifier)) { + if (specifier.exportKind === 'type') continue + const localName = getModuleExportName(specifier.local) + const exportedName = getModuleExportName(specifier.exported) + const memberProperty = toMemberExpressionProperty(localName) + + const internalVar = createInternalReexportVarName( + localName, + mockIndex, + usedInternalVars, + ) + replacements.push( + t.variableDeclaration('const', [ + t.variableDeclarator( + t.identifier(internalVar), + t.memberExpression( + t.identifier(mockVar), + memberProperty.property, + memberProperty.computed, + ), + ), + ]), + ) + exportSpecifiers.push({ localName: internalVar, exportedName }) + } + } + + if (exportSpecifiers.length > 0) { + replacements.push( + t.exportNamedDeclaration( + null, + exportSpecifiers.map((s) => + t.exportSpecifier( + t.identifier(s.localName), + toModuleExportNameNode(s.exportedName), + ), + ), + ), + ) + } + + ast.program.body.splice(i, 1, ...replacements) + modified = true + continue + } + + if (t.isExportAllDeclaration(node)) { + if (node.exportKind === 'type') continue + if (!deniedSources.has(node.source.value)) continue + + ast.program.body.splice(i, 1) + modified = true + continue + } + } + + if (!modified) return undefined + + const result = generateFromAst(ast, { + sourceMaps: true, + sourceFileName: id, + filename: id, + }) + + return { + code: result.code, + ...(result.map ? { map: result.map as SourceMapLike } : {}), + } +} diff --git a/packages/start-plugin-core/src/import-protection/sourceLocation.ts b/packages/start-plugin-core/src/import-protection/sourceLocation.ts new file mode 100644 index 0000000000..ee346b327b --- /dev/null +++ b/packages/start-plugin-core/src/import-protection/sourceLocation.ts @@ -0,0 +1,610 @@ +import { SourceMapConsumer } from 'source-map' +import * as path from 'pathe' + +import { + findOriginalUnsafeUsagePosFromResult, + findPostCompileUsagePosFromResult, + getImportSpecifierLocationFromResult, +} from './analysis' +import { getOrCreate, normalizeFilePath } from './utils' +import type { ImportAnalysis } from './analysis' +import type { Loc } from './trace' +import type { ParseAstResult } from '@tanstack/router-utils' +import type { RawSourceMap } from 'source-map' + +// Source-map type compatible with both Rollup's SourceMap and source-map's +// RawSourceMap. Structural type avoids version: number vs string mismatch. + +/** + * Minimal source-map shape used throughout the import-protection plugin. + */ +export interface SourceMapLike { + file?: string + sourceRoot?: string + version: number | string + sources: Array + names: Array + sourcesContent?: Array + mappings: string +} + +export interface ImportProtectionPerfRecorder { + count: (name: string, value?: number) => void + time: (name: string, startedAt: number) => void +} + +// Transform result provider (replaces ctx.load() which doesn't work in dev) +export interface TransformResult { + code: string + filename?: string + map: SourceMapLike | undefined + originalCode: string | undefined + originalResult?: TransformResult + /** Precomputed line index for `code` (index → line/col). */ + lineIndex?: LineIndex + parsedAst?: ParseAstResult + analysis?: ImportAnalysis + perf?: ImportProtectionPerfRecorder +} + +/** + * Provides the transformed code and composed sourcemap for a module. + * + * Populated from a late-running transform hook. By the time `resolveId` + * fires for an import, the importer has already been fully transformed. + */ +export interface TransformResultProvider { + getTransformResult: (id: string) => TransformResult | undefined +} + +export interface ImportSpecifierLocationIndex { + find: FindImportSpecifierLocationIndex +} + +// Index → line/column conversion + +export type LineIndex = { + offsets: Array +} + +export function buildLineIndex(code: string): LineIndex { + const offsets: Array = [0] + for (let i = 0; i < code.length; i++) { + if (code.charCodeAt(i) === 10) { + offsets.push(i + 1) + } + } + return { offsets } +} + +function upperBound(values: Array, x: number): number { + let lo = 0 + let hi = values.length + while (lo < hi) { + const mid = (lo + hi) >> 1 + if (values[mid]! <= x) lo = mid + 1 + else hi = mid + } + return lo +} + +function indexToLineColWithIndex( + lineIndex: LineIndex, + idx: number, +): { line: number; column0: number } { + const offsets = lineIndex.offsets + const ub = upperBound(offsets, idx) + const lineIdx = Math.max(0, ub - 1) + const line = lineIdx + 1 + + const lineStart = offsets[lineIdx] ?? 0 + return { line, column0: Math.max(0, idx - lineStart) } +} + +export function indexToLineColumn( + lineIndex: LineIndex, + idx: number, +): { line: number; column: number } { + const { line, column0 } = indexToLineColWithIndex(lineIndex, idx) + return { + line, + column: column0 + 1, + } +} + +export function normalizeSourceMap(map: SourceMapLike | null | undefined): + | { + version: number + file: string + sourceRoot?: string + sources: Array + names: Array + sourcesContent?: Array + mappings: string + } + | undefined { + if (!map) { + return undefined + } + + return { + ...map, + version: Number(map.version), + file: map.file ?? '', + names: Array.isArray(map.names) ? map.names : [], + sourcesContent: + map.sourcesContent?.map((value) => value ?? '') ?? undefined, + } +} + +/** + * Pick the most-likely original source text for `importerFile` from + * a sourcemap that may contain multiple sources. + */ +export function pickOriginalCodeFromSourcesContent( + map: SourceMapLike | undefined, + importerFile: string, + root: string, +): string | undefined { + if (!map?.sourcesContent || map.sources.length === 0) { + return undefined + } + + const file = normalizeFilePath(importerFile) + const sourceRoot = map.sourceRoot + const fileSeg = file.split('/').filter(Boolean) + + const resolveBase = sourceRoot ? path.resolve(root, sourceRoot) : root + + let bestIdx = -1 + let bestScore = -1 + + for (let i = 0; i < map.sources.length; i++) { + const content = map.sourcesContent[i] + if (typeof content !== 'string') continue + + const src = map.sources[i] ?? '' + + const normalizedSrc = normalizeFilePath(src) + if (normalizedSrc === file) { + return content + } + + let resolved: string + if (!src) { + resolved = '' + } else if (path.isAbsolute(src)) { + resolved = normalizeFilePath(src) + } else { + resolved = normalizeFilePath(path.resolve(resolveBase, src)) + } + if (resolved === file) { + return content + } + + // Count matching path segments from the end. + const normalizedSrcSeg = normalizedSrc.split('/').filter(Boolean) + const resolvedSeg = + resolved !== normalizedSrc + ? resolved.split('/').filter(Boolean) + : normalizedSrcSeg + const score = Math.max( + segmentSuffixScore(normalizedSrcSeg, fileSeg), + segmentSuffixScore(resolvedSeg, fileSeg), + ) + + if (score > bestScore) { + bestScore = score + bestIdx = i + } + } + + if (bestIdx !== -1 && bestScore >= 1) { + return map.sourcesContent[bestIdx] ?? undefined + } + + return map.sourcesContent[0] ?? undefined +} + +/** Count matching path segments from the end of `aSeg` against `bSeg`. */ +function segmentSuffixScore(aSeg: Array, bSeg: Array): number { + let score = 0 + for ( + let i = aSeg.length - 1, j = bSeg.length - 1; + i >= 0 && j >= 0; + i--, j-- + ) { + if (aSeg[i] !== bSeg[j]) break + score++ + } + return score +} + +async function mapGeneratedToOriginal( + map: SourceMapLike | undefined, + generated: { line: number; column0: number }, + fallbackFile: string, +): Promise { + const fallback: Loc = { + file: fallbackFile, + line: generated.line, + column: generated.column0 + 1, + } + + if (!map) { + return fallback + } + + const consumer = await getSourceMapConsumer(map) + if (!consumer) return fallback + + try { + const orig = consumer.originalPositionFor({ + line: generated.line, + column: generated.column0, + }) + if (orig.line != null && orig.column != null) { + return { + file: orig.source ? normalizeFilePath(orig.source) : fallbackFile, + line: orig.line, + column: orig.column + 1, + } + } + } catch { + // Malformed sourcemap + } + + return fallback +} + +const consumerCache = new WeakMap>() + +function getOriginalCode( + result: TransformResult, + importerFile: string | undefined, + root: string | undefined, +): string | undefined { + if (result.originalCode === undefined && importerFile && root) { + const map = result.map + if (map?.sourcesContent) { + result.originalCode = pickOriginalCodeFromSourcesContent( + map, + importerFile, + root, + ) + } + } + + return result.originalCode +} + +function toRawSourceMap(map: SourceMapLike): RawSourceMap { + return { + ...map, + file: map.file ?? '', + version: Number(map.version), + sourcesContent: map.sourcesContent?.map((s) => s ?? '') ?? [], + } +} + +async function getSourceMapConsumer( + map: SourceMapLike, +): Promise { + const cached = consumerCache.get(map) + if (cached) return cached + + const promise = (async () => { + try { + return await new SourceMapConsumer(toRawSourceMap(map)) + } catch { + return null + } + })() + + consumerCache.set(map, promise) + return promise +} + +export type ImportLocEntry = { file?: string; line: number; column: number } + +/** + * Cache for import statement locations with reverse index for O(1) + * invalidation by file. Keys: `${importerFile}::${source}`. + */ +export class ImportLocCache { + private cache = new Map() + private reverseIndex = new Map>() + + has(key: string): boolean { + return this.cache.has(key) + } + + get(key: string): ImportLocEntry | null | undefined { + return this.cache.get(key) + } + + set(key: string, value: ImportLocEntry | null): void { + this.cache.set(key, value) + const file = key.slice(0, key.indexOf('::')) + getOrCreate(this.reverseIndex, file, () => new Set()).add(key) + } + + clear(): void { + this.cache.clear() + this.reverseIndex.clear() + } + + /** Remove all cache entries where the importer matches `file`. */ + deleteByFile(file: string): void { + const keys = this.reverseIndex.get(file) + if (keys) { + for (const key of keys) { + this.cache.delete(key) + } + this.reverseIndex.delete(file) + } + } +} + +export type FindImportSpecifierLocationIndex = ( + result: TransformResult, + source: string, +) => number + +export function getOrCreateOriginalTransformResult( + result: TransformResult, + importerFile?: string, + root?: string, +): TransformResult | undefined { + getOriginalCode(result, importerFile, root) + + if (!result.originalCode) { + return undefined + } + + if (!result.originalResult) { + result.originalResult = { + code: result.originalCode, + filename: result.filename, + map: undefined, + originalCode: result.originalCode, + } + + if (result.perf) { + result.originalResult.perf = result.perf + } + } + + return result.originalResult +} + +export function createImportSpecifierLocationIndex(): ImportSpecifierLocationIndex { + return { + find(result: TransformResult, source: string): number { + if (!result.code.includes(source)) { + return -1 + } + + return getImportSpecifierLocationFromResult(result, source) + }, + } +} + +/** + * Find the location of an import statement in a transformed module + * by searching the post-transform code and mapping back via sourcemap. + * Results are cached in `importLocCache`. + */ +export async function findImportStatementLocationFromTransformed( + provider: TransformResultProvider, + importerId: string, + source: string, + importLocCache: ImportLocCache, + findImportSpecifierLocationIndex: FindImportSpecifierLocationIndex, +): Promise { + const importerFile = normalizeFilePath(importerId) + const cacheKey = `${importerFile}::${source}` + if (importLocCache.has(cacheKey)) { + return importLocCache.get(cacheKey) ?? undefined + } + + try { + const res = provider.getTransformResult(importerId) + if (!res) { + importLocCache.set(cacheKey, null) + return undefined + } + + const { map } = res + + const lineIndex = + res.lineIndex ?? (res.lineIndex = buildLineIndex(res.code)) + + const idx = findImportSpecifierLocationIndex(res, source) + if (idx === -1) { + importLocCache.set(cacheKey, null) + return undefined + } + + const generated = indexToLineColWithIndex(lineIndex, idx) + const loc = await mapGeneratedToOriginal(map, generated, importerFile) + importLocCache.set(cacheKey, loc) + return loc + } catch { + importLocCache.set(cacheKey, null) + return undefined + } +} + +/** + * Find the first post-compile usage location for a denied import specifier. + * Best-effort: searches transformed code for non-import uses of imported + * bindings and maps back to original source via sourcemap. + */ +export async function findPostCompileUsageLocation( + provider: TransformResultProvider, + importerId: string, + source: string, +): Promise { + try { + const importerFile = normalizeFilePath(importerId) + const res = provider.getTransformResult(importerId) + if (!res) return undefined + const { code, map } = res + + if (!res.lineIndex) { + res.lineIndex = buildLineIndex(code) + } + + const pos = findPostCompileUsagePosFromResult(res, source) + if (!pos) return undefined + + return await mapGeneratedToOriginal(map, pos, importerFile) + } catch { + return undefined + } +} + +/** + * Best-effort original-source usage lookup for cases where a later transform + * removes or rewrites the import from emitted code but preserves the original + * source in `sourcesContent`. + */ +export function findOriginalUsageLocation( + provider: TransformResultProvider, + importerId: string, + source: string, + envType?: 'client' | 'server', + root?: string, +): Loc | undefined { + try { + const importerFile = normalizeFilePath(importerId) + const res = provider.getTransformResult(importerId) + if (!res) return undefined + const originalResult = getOrCreateOriginalTransformResult( + res, + importerFile, + root, + ) + if (!originalResult) return undefined + + const pos = envType + ? findOriginalUnsafeUsagePosFromResult(originalResult, source, envType) + : findPostCompileUsagePosFromResult(originalResult, source) + if (!pos) return undefined + + return { + file: importerFile, + line: pos.line, + column: pos.column0 + 1, + } + } catch { + return undefined + } +} + +/** + * Annotate each trace hop with the location of the import that created the + * edge (file:line:col). Skips steps that already have a location. + */ +export async function addTraceImportLocations( + provider: TransformResultProvider, + trace: Array<{ + file: string + specifier?: string + line?: number + column?: number + }>, + importLocCache: ImportLocCache, + findImportSpecifierLocationIndex: FindImportSpecifierLocationIndex, +): Promise { + for (const step of trace) { + if (!step.specifier) continue + if (step.line != null && step.column != null) continue + const loc = await findImportStatementLocationFromTransformed( + provider, + step.file, + step.specifier, + importLocCache, + findImportSpecifierLocationIndex, + ) + if (!loc) continue + step.line = loc.line + step.column = loc.column + } +} + +// Code snippet extraction (vitest-style context around a location) + +export interface CodeSnippet { + /** Source lines with line numbers, e.g. `[" 6 | import { getSecret } from './secret.server'", ...]` */ + lines: Array + /** The highlighted line (1-indexed original line number) */ + highlightLine: number + /** Clickable file:line reference */ + location: string +} + +/** + * Build a vitest-style code snippet showing lines surrounding a location. + * + * Prefers `originalCode` from the sourcemap's sourcesContent; falls back + * to transformed code when unavailable. + */ +export function buildCodeSnippet( + provider: TransformResultProvider, + moduleId: string, + loc: Loc, + contextLines: number = 2, + root?: string, +): CodeSnippet | undefined { + try { + const importerFile = normalizeFilePath(moduleId) + const res = provider.getTransformResult(moduleId) + if (!res) return undefined + + const sourceCode = getOriginalCode(res, importerFile, root) ?? res.code + const targetLine = loc.line // 1-indexed + const targetCol = loc.column // 1-indexed + + if (targetLine < 1) return undefined + + const allLines = sourceCode.split('\n') + // Strip trailing \r from \r\n line endings + for (let i = 0; i < allLines.length; i++) { + const line = allLines[i]! + if (line.endsWith('\r')) allLines[i] = line.slice(0, -1) + } + + const wantStart = Math.max(1, targetLine - contextLines) + const wantEnd = Math.min(allLines.length, targetLine + contextLines) + + if (targetLine > allLines.length) return undefined + + const lines = allLines.slice(wantStart - 1, wantEnd) + const gutterWidth = String(wantEnd).length + + const sourceFile = loc.file ?? importerFile + const snippetLines: Array = [] + for (let i = 0; i < lines.length; i++) { + const ln = wantStart + i + const lineContent = lines[i]! + const lineNumStr = String(ln).padStart(gutterWidth, ' ') + const marker = ln === targetLine ? '>' : ' ' + snippetLines.push(` ${marker} ${lineNumStr} | ${lineContent}`) + + if (ln === targetLine && targetCol > 0) { + const padding = ' '.repeat(targetCol - 1) + snippetLines.push(` ${' '.repeat(gutterWidth)} | ${padding}^`) + } + } + + return { + lines: snippetLines, + highlightLine: targetLine, + location: `${sourceFile}:${targetLine}:${targetCol}`, + } + } catch { + return undefined + } +} diff --git a/packages/start-plugin-core/src/import-protection/trace.ts b/packages/start-plugin-core/src/import-protection/trace.ts new file mode 100644 index 0000000000..d0c807ea03 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection/trace.ts @@ -0,0 +1,284 @@ +import { getOrCreate, relativizePath } from './utils' + +export interface TraceEdge { + importer: string + specifier?: string +} + +/** + * Per-environment reverse import graph. + * Maps a resolved module id to the set of modules that import it. + */ +export class ImportGraph { + /** + * resolvedId -> Map + * + * We use a Map instead of a Set of objects so edges dedupe correctly. + */ + readonly reverseEdges: Map> = + new Map() + + /** + * Forward-edge index: importer -> Set. + * + * Maintained alongside reverseEdges so that {@link invalidate} can remove + * all outgoing edges for a file in O(outgoing-edges) instead of scanning + * every reverse-edge map in the graph. + */ + private readonly forwardEdges: Map> = new Map() + + readonly entries: Set = new Set() + + addEdge(resolved: string, importer: string, specifier?: string): void { + getOrCreate(this.reverseEdges, resolved, () => new Map()).set( + importer, + specifier, + ) + getOrCreate(this.forwardEdges, importer, () => new Set()).add(resolved) + } + + /** Convenience for tests/debugging. */ + getEdges(resolved: string): Set | undefined { + const importers = this.reverseEdges.get(resolved) + if (!importers) return undefined + const out = new Set() + for (const [importer, specifier] of importers) { + out.add({ importer, specifier }) + } + return out + } + + addEntry(id: string): void { + this.entries.add(id) + } + + clear(): void { + this.reverseEdges.clear() + this.forwardEdges.clear() + this.entries.clear() + } + + invalidate(id: string): void { + // Remove all outgoing edges (id as importer) using the forward index. + const targets = this.forwardEdges.get(id) + if (targets) { + for (const resolved of targets) { + this.reverseEdges.get(resolved)?.delete(id) + } + this.forwardEdges.delete(id) + } + // Remove as a target (id as resolved module) + this.reverseEdges.delete(id) + } +} + +export interface TraceStep { + file: string + specifier?: string + line?: number + column?: number +} + +export interface Loc { + file?: string + line: number + column: number +} + +/** + * BFS from a node upward through reverse edges to find the shortest + * path to an entry module. + */ +export function buildTrace( + graph: ImportGraph, + startNode: string, + maxDepth: number = 20, +): Array { + // BFS upward (startNode -> importers -> ...) + const visited = new Set([startNode]) + const depthByNode = new Map([[startNode, 0]]) + + // For any importer we visit, store the "down" link back toward startNode. + // importer --(specifier)--> next + const down = new Map() + + const queue: Array = [startNode] + let qi = 0 + + let root: string | null = null + + while (qi < queue.length) { + const node = queue[qi++]! + const depth = depthByNode.get(node)! + const importers = graph.reverseEdges.get(node) + + if (node !== startNode) { + const isEntry = + graph.entries.has(node) || !importers || importers.size === 0 + if (isEntry) { + root = node + break + } + } + + if (depth >= maxDepth) { + continue + } + + if (!importers || importers.size === 0) { + continue + } + + for (const [importer, specifier] of importers) { + if (visited.has(importer)) continue + visited.add(importer) + depthByNode.set(importer, depth + 1) + down.set(importer, { next: node, specifier }) + queue.push(importer) + } + } + + // Best-effort: if we never found a root, just start from the original node. + if (!root) { + root = startNode + } + + const trace: Array = [] + let current = root + for (let i = 0; i <= maxDepth + 1; i++) { + const link = down.get(current) + trace.push({ file: current, specifier: link?.specifier }) + if (!link) break + current = link.next + } + + return trace +} + +export interface ViolationInfo { + env: string + envType: 'client' | 'server' + type: 'specifier' | 'file' | 'marker' + behavior: 'error' | 'mock' + pattern?: string | RegExp + specifier: string + importer: string + importerLoc?: Loc + resolved?: string + trace: Array + /** Vitest-style code snippet showing the offending usage in the leaf module. */ + snippet?: { + lines: Array + highlightLine: number + location: string + } +} + +/** + * Suggestion strings for server-only code leaking into client environments. + * Used by both `formatViolation` (terminal) and runtime mock modules (browser). + */ +export const CLIENT_ENV_SUGGESTIONS = [ + 'Use createServerFn().handler(() => ...) to keep the logic on the server and call it from the client via an RPC bridge', + 'Use createServerOnlyFn(() => ...) to mark it as server-only (it will throw if accidentally called from the client)', + 'Use createIsomorphicFn().client(() => ...).server(() => ...) to provide separate client and server implementations', + 'Move the server-only import out of this file into a separate .server.ts module that is not imported by any client code', +] as const + +/** + * Suggestion strings for client-only code leaking into server environments. + * The JSX-specific suggestion is conditionally prepended by `formatViolation`. + */ +export const SERVER_ENV_SUGGESTIONS = [ + 'Use createClientOnlyFn(() => ...) to mark it as client-only (returns undefined on the server)', + 'Use createIsomorphicFn().client(() => ...).server(() => ...) to provide separate client and server implementations', + 'Move the client-only import out of this file into a separate .client.ts module that is not imported by any server code', +] as const + +export function formatViolation(info: ViolationInfo, root: string): string { + const rel = (p: string) => relativizePath(p, root) + + const relLoc = (p: string, loc?: Loc) => { + const r = rel(p) + const file = loc?.file ? rel(loc.file) : r + return loc ? `${file}:${loc.line}:${loc.column}` : r + } + + const relTraceStep = (step: TraceStep): string => { + const file = rel(step.file) + if (step.line == null) return file + const col = step.column ?? 1 + return `${file}:${step.line}:${col}` + } + + const lines: Array = [] + lines.push(``) + lines.push(`[import-protection] Import denied in ${info.envType} environment`) + lines.push(``) + + if (info.type === 'specifier') { + lines.push(` Denied by specifier pattern: ${String(info.pattern)}`) + } else if (info.type === 'file') { + lines.push(` Denied by file pattern: ${String(info.pattern)}`) + } else { + lines.push( + ` Denied by marker: module is restricted to the opposite environment`, + ) + } + + lines.push(` Importer: ${relLoc(info.importer, info.importerLoc)}`) + lines.push(` Import: "${rel(info.specifier)}"`) + if (info.resolved) { + lines.push(` Resolved: ${rel(info.resolved)}`) + } + + if (info.trace.length > 0) { + lines.push(``) + lines.push(` Trace:`) + for (let i = 0; i < info.trace.length; i++) { + const step = info.trace[i]! + const isEntry = i === 0 + const tag = isEntry ? ' (entry)' : '' + const spec = step.specifier ? ` (import "${rel(step.specifier)}")` : '' + lines.push(` ${i + 1}. ${relTraceStep(step)}${tag}${spec}`) + } + } + + if (info.snippet) { + lines.push(``) + lines.push(` Code:`) + for (const snippetLine of info.snippet.lines) { + lines.push(snippetLine) + } + lines.push(``) + lines.push(` ${rel(info.snippet.location)}`) + } + + lines.push(``) + + // Add suggestions + if (info.envType === 'client') { + lines.push(` Suggestions:`) + for (const s of CLIENT_ENV_SUGGESTIONS) { + lines.push(` - ${s}`) + } + } else { + const snippetText = info.snippet?.lines.join('\n') ?? '' + const looksLikeJsx = + /<[A-Z]/.test(snippetText) || + (/\{.*\(.*\).*\}/.test(snippetText) && /}>...
    so it only renders in the browser after hydration`, + ) + } + for (const s of SERVER_ENV_SUGGESTIONS) { + lines.push(` - ${s}`) + } + } + + lines.push(``) + return lines.join('\n') +} diff --git a/packages/start-plugin-core/src/import-protection/utils.ts b/packages/start-plugin-core/src/import-protection/utils.ts new file mode 100644 index 0000000000..811539bd78 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection/utils.ts @@ -0,0 +1,223 @@ +import { + extname, + isAbsolute, + relative, + resolve as resolvePath, +} from 'node:path' +import { normalizePath } from '../utils' + +import { + IMPORT_PROTECTION_DEBUG, + IMPORT_PROTECTION_DEBUG_FILTER, + KNOWN_SOURCE_EXTENSIONS, +} from './constants' + +export type Pattern = string | RegExp + +export function dedupePatterns(patterns: Array): Array { + const out: Array = [] + const seen = new Set() + for (const p of patterns) { + const key = typeof p === 'string' ? `s:${p}` : `r:${p.toString()}` + if (seen.has(key)) continue + seen.add(key) + out.push(p) + } + return out +} + +export interface FileMatchers { + files: Array<{ pattern: Pattern; test: (value: string) => boolean }> + excludeFiles: Array<{ pattern: Pattern; test: (value: string) => boolean }> +} + +export function isFileExcluded( + relativePath: string, + matchers: Pick, +): boolean { + return ( + matchers.excludeFiles.length > 0 && + matchers.excludeFiles.some((matcher) => matcher.test(relativePath)) + ) +} + +export function checkFileDenial( + relativePath: string, + matchers: FileMatchers, +): FileMatchers['files'][number] | undefined { + if (isFileExcluded(relativePath, matchers)) { + return undefined + } + + return matchers.files.find((matcher) => matcher.test(relativePath)) +} + +export function dedupeViolationKey(info: { + type: string + importer: string + specifier: string + resolved?: string +}): string { + return `${info.type}:${info.importer}:${info.specifier}:${info.resolved ?? ''}` +} + +/** Strip both `?query` and `#hash` from a module ID. */ +export function stripQueryAndHash(id: string): string { + const q = id.indexOf('?') + const h = id.indexOf('#') + if (q === -1 && h === -1) return id + if (q === -1) return id.slice(0, h) + if (h === -1) return id.slice(0, q) + return id.slice(0, Math.min(q, h)) +} + +/** + * Strip Vite query/hash parameters and normalize the path in one step. + * + * Results are memoized because the same module IDs are processed many + * times across resolveId, transform, and trace-building hooks. + */ +const normalizeFilePathCache = new Map() +export function normalizeFilePath(id: string): string { + let result = normalizeFilePathCache.get(id) + if (result === undefined) { + result = normalizePath(stripQueryAndHash(id)) + normalizeFilePathCache.set(id, result) + } + return result +} + +/** Clear the memoization cache (call from buildStart to bound growth). */ +export function clearNormalizeFilePathCache(): void { + normalizeFilePathCache.clear() +} + +/** Get a value from a Map, creating it with `factory` if absent. */ +export function getOrCreate( + map: Map, + key: TKey, + factory: () => TValue, +): TValue { + let value = map.get(key) + if (value === undefined) { + value = factory() + map.set(key, value) + } + return value +} + +/** Make a path relative to `root`, keeping non-rooted paths as-is. */ +export function relativizePath(p: string, root: string): string { + if (!p.startsWith(root)) return p + const ch = p.charCodeAt(root.length) + // Must be followed by a separator or end-of-string to be a true child + if (ch !== 47 && !Number.isNaN(ch)) return p + return ch === 47 ? p.slice(root.length + 1) : p.slice(root.length) +} + +/** Log import-protection debug output when debug mode is enabled. */ +export function debugLog(...args: Array): void { + if (!IMPORT_PROTECTION_DEBUG) return + console.warn('[import-protection:debug]', ...args) +} + +/** Check if any value matches the configured debug filter (if present). */ +export function matchesDebugFilter(...values: Array): boolean { + const debugFilter = IMPORT_PROTECTION_DEBUG_FILTER + if (!debugFilter) return true + return values.some((v) => v.includes(debugFilter)) +} + +/** Strip `?query` (but not `#hash`) from a module ID. */ +export function stripQuery(id: string): string { + const queryIndex = id.indexOf('?') + return queryIndex === -1 ? id : id.slice(0, queryIndex) +} + +export function withoutKnownExtension(id: string): string { + const ext = extname(id) + return KNOWN_SOURCE_EXTENSIONS.has(ext) ? id.slice(0, -ext.length) : id +} + +/** + * Check whether `filePath` is contained inside `directory` using a + * boundary-safe comparison. A naïve `filePath.startsWith(directory)` + * would incorrectly treat `/app/src2/foo.ts` as inside `/app/src`. + */ +export function isInsideDirectory( + filePath: string, + directory: string, +): boolean { + const rel = relative(resolvePath(directory), resolvePath(filePath)) + return rel.length > 0 && !rel.startsWith('..') && !isAbsolute(rel) +} + +/** + * Decide whether a violation should be deferred for later verification + * rather than reported immediately. + * + * Build mode: always defer — generateBundle checks tree-shaking. + * Dev mock mode: always defer — edge-survival verifies whether the Start + * compiler strips the import (factory-safe pattern). All violation + * types and specifier formats are handled uniformly by the + * edge-survival mechanism in processPendingViolations. + * Dev error mode: never defer — throw immediately (no mock fallback). + */ +export function shouldDeferViolation(opts: { + isBuild: boolean + isDevMock: boolean +}): boolean { + return opts.isBuild || opts.isDevMock +} + +export function buildSourceCandidates( + source: string, + resolved: string | undefined, + root: string, +): Set { + const candidates = new Set() + const push = (value: string | undefined) => { + if (!value) return + candidates.add(value) + candidates.add(stripQuery(value)) + candidates.add(withoutKnownExtension(stripQuery(value))) + } + + push(source) + if (resolved) { + push(resolved) + const relativeResolved = relativizePath(resolved, root) + push(relativeResolved) + push(`./${relativeResolved}`) + push(`/${relativeResolved}`) + } + + return candidates +} + +export function buildResolutionCandidates(id: string): Array { + const normalized = normalizeFilePath(id) + const stripped = stripQuery(normalized) + + return [...new Set([id, normalized, stripped])] +} + +export function canonicalizeResolvedId( + id: string, + root: string, + resolveExtensionlessAbsoluteId: (value: string) => string, +): string { + const stripped = stripQuery(id) + let normalized = normalizeFilePath(stripped) + + if ( + !isAbsolute(normalized) && + !normalized.startsWith('.') && + !normalized.startsWith('\0') && + !/^[a-zA-Z]+:/.test(normalized) + ) { + normalized = normalizeFilePath(resolvePath(root, normalized)) + } + + return resolveExtensionlessAbsoluteId(normalized) +} diff --git a/packages/start-plugin-core/src/import-protection/virtualModules.ts b/packages/start-plugin-core/src/import-protection/virtualModules.ts new file mode 100644 index 0000000000..29b6878927 --- /dev/null +++ b/packages/start-plugin-core/src/import-protection/virtualModules.ts @@ -0,0 +1,303 @@ +import { + MARKER_PREFIX, + MOCK_BUILD_PREFIX, + MOCK_EDGE_PREFIX, + MOCK_MODULE_ID, + MOCK_RUNTIME_PREFIX, +} from './constants' +import { isValidExportName } from './analysis' +import { CLIENT_ENV_SUGGESTIONS } from './trace' +import { relativizePath } from './utils' +import type { ViolationInfo } from './trace' + +function toBase64Url(input: string): string { + return Buffer.from(input, 'utf8').toString('base64url') +} + +function fromBase64Url(input: string): string { + return Buffer.from(input, 'base64url').toString('utf8') +} + +type MockAccessMode = 'error' | 'warn' | 'off' + +export const RUNTIME_SUGGESTION_TEXT = + 'Fix: ' + + CLIENT_ENV_SUGGESTIONS.join('. ') + + '. To disable these runtime diagnostics, set importProtection.mockAccess: "off".' + +export function mockRuntimeModuleIdFromViolation( + info: ViolationInfo, + mode: MockAccessMode, + root: string, +): string { + if (mode === 'off') return MOCK_MODULE_ID + if (info.env !== 'client') return MOCK_MODULE_ID + + const rel = (p: string) => relativizePath(p, root) + const trace = info.trace.map((s) => { + const file = rel(s.file) + if (s.line == null) return file + return `${file}:${s.line}:${s.column ?? 1}` + }) + + const payload = { + env: info.env, + importer: info.importer, + specifier: info.specifier, + trace, + mode, + } + + return `${MOCK_RUNTIME_PREFIX}${toBase64Url(JSON.stringify(payload))}` +} + +export function makeMockEdgeModuleId( + exports: Array, + runtimeId: string, +): string { + const payload = { exports, runtimeId } + return `${MOCK_EDGE_PREFIX}${toBase64Url(JSON.stringify(payload))}` +} + +function generateMockCode(diagnostics?: { + meta: { + env: string + importer: string + specifier: string + trace: Array + } + mode: 'error' | 'warn' | 'off' +}): string { + const fnName = diagnostics ? '__createMock' : 'createMock' + const hasDiag = !!diagnostics + + const preamble = hasDiag + ? `const __meta = ${JSON.stringify(diagnostics.meta)}; +const __mode = ${JSON.stringify(diagnostics.mode)}; + +const __seen = new Set(); +function __report(action, accessPath) { + if (__mode === 'off') return; + const key = action + ':' + accessPath; + if (__seen.has(key)) return; + __seen.add(key); + + const traceLines = Array.isArray(__meta.trace) && __meta.trace.length + ? "\\n\\nTrace:\\n" + __meta.trace.map((t, i) => ' ' + (i + 1) + '. ' + String(t)).join('\\n') + : ''; + + const msg = + '[import-protection] Mocked import used in dev client\\n\\n' + + 'Denied import: "' + __meta.specifier + '"\\n' + + 'Importer: ' + __meta.importer + '\\n' + + 'Access: ' + accessPath + ' (' + action + ')' + + traceLines + + '\\n\\n' + ${JSON.stringify(RUNTIME_SUGGESTION_TEXT)}; + + const err = new Error(msg); + if (__mode === 'warn') { + console.warn(err); + } else { + console.error(err); + } +} +` + : '' + + const primitiveGetTraps = ` + if (prop === Symbol.toPrimitive) { + return () => { + ${hasDiag ? `__report('toPrimitive', name);` : ''} + return '[import-protection mock]'; + }; + } + if (prop === 'toString' || prop === 'valueOf' || prop === 'toJSON') { + return () => { + ${hasDiag ? `__report(String(prop), name);` : ''} + return '[import-protection mock]'; + }; + }` + + const applyBody = hasDiag + ? `__report('call', name + '()'); + return ${fnName}(name + '()');` + : `return ${fnName}(name + '()');` + + const constructBody = hasDiag + ? `__report('construct', 'new ' + name); + return ${fnName}('new ' + name);` + : `return ${fnName}('new ' + name);` + + const setTrap = hasDiag + ? ` + set(_target, prop) { + __report('set', name + '.' + String(prop)); + return true; + },` + : '' + + return ` +${preamble}/* @__NO_SIDE_EFFECTS__ */ +function ${fnName}(name) { + const fn = function () {}; + fn.prototype.name = name; + const children = Object.create(null); + const proxy = new Proxy(fn, { + get(_target, prop) { + if (prop === '__esModule') return true; + if (prop === 'default') return proxy; + if (prop === 'caller') return null; + if (prop === 'then') return (f) => Promise.resolve(f(proxy)); + if (prop === 'catch') return () => Promise.resolve(proxy); + if (prop === 'finally') return (f) => { f(); return Promise.resolve(proxy); };${primitiveGetTraps} + if (typeof prop === 'symbol') return undefined; + if (!(prop in children)) { + children[prop] = ${fnName}(name + '.' + prop); + } + return children[prop]; + }, + apply() { + ${applyBody} + }, + construct() { + ${constructBody} + },${setTrap} + }); + return proxy; +} +const mock = /* @__PURE__ */ ${fnName}('mock'); +export default mock; +` +} + +export function loadSilentMockModule(): { code: string } { + return { code: generateMockCode() } +} + +function filterExportNames(exports: ReadonlyArray): Array { + return exports.filter((n) => n.length > 0 && n !== 'default') +} + +function generateExportLines(names: ReadonlyArray): Array { + const lines: Array = [] + const stringExports: Array<{ alias: string; name: string }> = [] + + for (let i = 0; i < names.length; i++) { + const n = names[i]! + if (isValidExportName(n)) { + lines.push(`export const ${n} = mock.${n};`) + } else { + const alias = `__tss_str_${i}` + lines.push(`const ${alias} = mock[${JSON.stringify(n)}];`) + stringExports.push({ alias, name: n }) + } + } + + if (stringExports.length > 0) { + const reexports = stringExports + .map((s) => `${s.alias} as ${JSON.stringify(s.name)}`) + .join(', ') + lines.push(`export { ${reexports} };`) + } + + return lines +} + +export function generateSelfContainedMockModule(exportNames: Array): { + code: string +} { + const mockCode = generateMockCode() + const exportLines = generateExportLines(filterExportNames(exportNames)) + + return { + code: `${mockCode} +${exportLines.join('\n')} +`, + } +} + +export function generateDevSelfDenialModule( + exportNames: Array, + runtimeId: string, +): { code: string } { + const names = filterExportNames(exportNames) + const exportLines = generateExportLines(names) + + return { + code: `import mock from ${JSON.stringify(runtimeId)}; +${exportLines.join('\n')} +export default mock; +`, + } +} + +export function loadMockEdgeModule(encodedPayload: string): { code: string } { + let payload: { exports?: Array; runtimeId?: string } + + try { + payload = JSON.parse(fromBase64Url(encodedPayload)) as typeof payload + } catch { + payload = { exports: [] } + } + + const names = filterExportNames(payload.exports ?? []) + const runtimeId = + typeof payload.runtimeId === 'string' && payload.runtimeId.length > 0 + ? payload.runtimeId + : MOCK_MODULE_ID + const exportLines = generateExportLines(names) + + return { + code: `import mock from ${JSON.stringify(runtimeId)}; +${exportLines.join('\n')} +export default mock; +`, + } +} + +export function loadMockRuntimeModule(encodedPayload: string): { + code: string +} { + let payload: { + mode?: string + env?: string + importer?: string + specifier?: string + trace?: Array + } + + try { + payload = JSON.parse(fromBase64Url(encodedPayload)) as typeof payload + } catch { + payload = {} + } + + const mode: 'error' | 'warn' | 'off' = + payload.mode === 'warn' || payload.mode === 'off' ? payload.mode : 'error' + + return { + code: generateMockCode({ + meta: { + env: String(payload.env ?? ''), + importer: String(payload.importer ?? ''), + specifier: String(payload.specifier ?? ''), + trace: Array.isArray(payload.trace) ? payload.trace : [], + }, + mode, + }), + } +} + +const MARKER_MODULE_RESULT = { code: 'export {}' } as const + +export function loadMarkerModule(): { code: string } { + return MARKER_MODULE_RESULT +} + +export { + MARKER_PREFIX, + MOCK_BUILD_PREFIX, + MOCK_EDGE_PREFIX, + MOCK_MODULE_ID, + MOCK_RUNTIME_PREFIX, +} diff --git a/packages/start-plugin-core/src/index.ts b/packages/start-plugin-core/src/index.ts index df946192ae..a6ee23a345 100644 --- a/packages/start-plugin-core/src/index.ts +++ b/packages/start-plugin-core/src/index.ts @@ -1,6 +1,8 @@ export type { TanStackStartInputConfig } from './schema' - -export { TanStackStartVitePluginCore } from './plugin' -export { resolveViteId } from './utils' - -export { VITE_ENVIRONMENT_NAMES } from './constants' +export type { + StartCompilerImportTransform, + StartCompilerTransformCandidate, + StartCompilerTransformContext, + TanStackStartCoreOptions, +} from './types' +export { START_ENVIRONMENT_NAMES } from './constants' diff --git a/packages/start-plugin-core/src/planning.ts b/packages/start-plugin-core/src/planning.ts new file mode 100644 index 0000000000..11f25d14d3 --- /dev/null +++ b/packages/start-plugin-core/src/planning.ts @@ -0,0 +1,142 @@ +import { joinPaths } from '@tanstack/router-core' +import { join } from 'pathe' +import { resolveEntry } from './resolve-entries' +import type { TanStackStartOutputConfig } from './schema' +import type { + NormalizedBasePaths, + NormalizedOutputDirectories, + TanStackStartCoreOptions, +} from './types' + +export interface ResolvedStartEntryPlan { + srcDirectory: string + startFilePath: string | undefined + routerFilePath: string + entryPaths: { + client: string + server: string + start: string + router: string + } +} + +export function normalizePublicBase(base: string | undefined): string { + const resolvedBase = base ?? '/' + + if (URL.canParse(resolvedBase)) { + return resolvedBase + } + + return joinPaths(['/', resolvedBase, '/']) +} + +export function deriveRouterBasepath(opts: { + configuredBasepath: string | undefined + publicBase: string +}): string { + if (opts.configuredBasepath !== undefined) { + return opts.configuredBasepath + } + + if (URL.canParse(opts.publicBase)) { + return '/' + } + + return opts.publicBase.replace(/^\/|\/$/g, '') +} + +export function shouldRewriteDevBasepath(opts: { + command: 'serve' | 'build' + middlewareMode: boolean | undefined + routerBasepath: string + publicBase: string +}): boolean { + if (opts.command !== 'serve' || opts.middlewareMode) { + return false + } + + return !joinPaths(['/', opts.routerBasepath, '/']).startsWith( + joinPaths(['/', opts.publicBase, '/']), + ) +} + +export function createNormalizedBasePaths(opts: { + publicBase: string +}): NormalizedBasePaths { + return { + publicBase: opts.publicBase, + assetBase: { + dev: opts.publicBase, + build: opts.publicBase, + }, + } +} + +export function createNormalizedOutputDirectories(opts: { + client: string + server: string +}): NormalizedOutputDirectories { + return { + client: opts.client, + server: opts.server, + } +} + +export function createServerFnBasePath(opts: { + routerBasepath: string + serverFnBase: string +}): string { + return joinPaths(['/', opts.routerBasepath, opts.serverFnBase, '/']) +} + +export function resolveStartEntryPlan(opts: { + root: string + startConfig: TanStackStartOutputConfig + defaultEntryPaths: TanStackStartCoreOptions['defaultEntryPaths'] +}): ResolvedStartEntryPlan { + const srcDirectory = join(opts.root, opts.startConfig.srcDirectory) + + const startFilePath = resolveEntry({ + type: 'start entry', + configuredEntry: opts.startConfig.start.entry, + defaultEntry: 'start', + resolvedSrcDirectory: srcDirectory, + required: false, + }) + + const routerFilePath = resolveEntry({ + type: 'router entry', + configuredEntry: opts.startConfig.router.entry, + defaultEntry: 'router', + resolvedSrcDirectory: srcDirectory, + required: true, + }) + + const clientEntryPath = resolveEntry({ + type: 'client entry', + configuredEntry: opts.startConfig.client.entry, + defaultEntry: 'client', + resolvedSrcDirectory: srcDirectory, + required: false, + }) + + const serverEntryPath = resolveEntry({ + type: 'server entry', + configuredEntry: opts.startConfig.server.entry, + defaultEntry: 'server', + resolvedSrcDirectory: srcDirectory, + required: false, + }) + + return { + srcDirectory, + startFilePath, + routerFilePath, + entryPaths: { + client: clientEntryPath ?? opts.defaultEntryPaths.client, + server: serverEntryPath ?? opts.defaultEntryPaths.server, + start: startFilePath ?? opts.defaultEntryPaths.start, + router: routerFilePath, + }, + } +} diff --git a/packages/start-plugin-core/src/plugin.ts b/packages/start-plugin-core/src/plugin.ts deleted file mode 100644 index 310d7309cf..0000000000 --- a/packages/start-plugin-core/src/plugin.ts +++ /dev/null @@ -1,437 +0,0 @@ -import { joinPaths } from '@tanstack/router-core' -import { VIRTUAL_MODULES } from '@tanstack/start-server-core' -import { TanStackServerFnPlugin } from '@tanstack/server-functions-plugin' -import * as vite from 'vite' -import { crawlFrameworkPkgs } from 'vitefu' -import { join } from 'pathe' -import { escapePath } from 'tinyglobby' -import { startManifestPlugin } from './start-manifest-plugin/plugin' -import { startCompilerPlugin } from './start-compiler-plugin/plugin' -import { ENTRY_POINTS, VITE_ENVIRONMENT_NAMES } from './constants' -import { tanStackStartRouter } from './start-router-plugin/plugin' -import { loadEnvPlugin } from './load-env-plugin/plugin' -import { devServerPlugin } from './dev-server-plugin/plugin' -import { previewServerPlugin } from './preview-server-plugin/plugin' -import { parseStartConfig } from './schema' -import { resolveEntry } from './resolve-entries' -import { - getClientOutputDirectory, - getServerOutputDirectory, -} from './output-directory' -import { postServerBuild } from './post-server-build' -import { createServerFnPlugin } from './create-server-fn-plugin/plugin' -import type { ViteEnvironmentNames } from './constants' -import type { - TanStackStartInputConfig, - TanStackStartOutputConfig, -} from './schema' -import type { PluginOption } from 'vite' -import type { CompileStartFrameworkOptions } from './start-compiler-plugin/compilers' - -export interface TanStackStartVitePluginCoreOptions { - framework: CompileStartFrameworkOptions - defaultEntryPaths: { - client: string - server: string - start: string - } - serverFn?: { - directive?: string - ssr?: { - getServerFnById?: string - } - providerEnv?: string - } -} - -export interface ResolvedStartConfig { - root: string - startFilePath: string | undefined - routerFilePath: string - srcDirectory: string - viteAppBase: string -} - -export type GetConfigFn = () => { - startConfig: TanStackStartOutputConfig - resolvedStartConfig: ResolvedStartConfig -} - -function isFullUrl(str: string): boolean { - try { - new URL(str) - return true - } catch { - return false - } -} - -export function TanStackStartVitePluginCore( - corePluginOpts: TanStackStartVitePluginCoreOptions, - startPluginOpts: TanStackStartInputConfig, -): Array { - const resolvedStartConfig: ResolvedStartConfig = { - root: '', - startFilePath: undefined, - routerFilePath: '', - srcDirectory: '', - viteAppBase: '', - } - - const directive = corePluginOpts.serverFn?.directive ?? 'use server' - - let startConfig: TanStackStartOutputConfig | null - const getConfig: GetConfigFn = () => { - if (!resolvedStartConfig.root) { - throw new Error(`Cannot get config before root is resolved`) - } - if (!startConfig) { - startConfig = parseStartConfig( - startPluginOpts, - corePluginOpts, - resolvedStartConfig.root, - ) - } - return { startConfig, resolvedStartConfig } - } - - const capturedBundle: Partial< - Record - > = {} - - function getBundle(envName: ViteEnvironmentNames): vite.Rollup.OutputBundle { - const bundle = capturedBundle[envName] - if (!bundle) { - throw new Error(`No bundle captured for environment: ${envName}`) - } - return bundle - } - - const environments: Array<{ name: string; type: 'client' | 'server' }> = [ - { name: VITE_ENVIRONMENT_NAMES.client, type: 'client' }, - { name: VITE_ENVIRONMENT_NAMES.server, type: 'server' }, - ] - if ( - corePluginOpts.serverFn?.providerEnv && - !environments.find((e) => e.name === corePluginOpts.serverFn?.providerEnv) - ) { - environments.push({ - name: corePluginOpts.serverFn.providerEnv, - type: 'server', - }) - } - return [ - { - name: 'tanstack-start-core:config', - enforce: 'pre', - async config(viteConfig, { command }) { - resolvedStartConfig.viteAppBase = viteConfig.base ?? '/' - if (!isFullUrl(resolvedStartConfig.viteAppBase)) { - resolvedStartConfig.viteAppBase = joinPaths([ - '/', - viteConfig.base, - '/', - ]) - } - const root = viteConfig.root || process.cwd() - resolvedStartConfig.root = root - - const { startConfig } = getConfig() - if (startConfig.router.basepath === undefined) { - if (!isFullUrl(resolvedStartConfig.viteAppBase)) { - startConfig.router.basepath = - resolvedStartConfig.viteAppBase.replace(/^\/|\/$/g, '') - } else { - startConfig.router.basepath = '/' - } - } else { - if (command === 'serve' && !viteConfig.server?.middlewareMode) { - // when serving, we must ensure that router basepath and viteAppBase are aligned - if ( - !joinPaths(['/', startConfig.router.basepath, '/']).startsWith( - joinPaths(['/', resolvedStartConfig.viteAppBase, '/']), - ) - ) { - this.error( - '[tanstack-start]: During `vite dev`, `router.basepath` must start with the vite `base` config value', - ) - } - } - } - - const TSS_SERVER_FN_BASE = joinPaths([ - '/', - startConfig.router.basepath, - startConfig.serverFns.base, - '/', - ]) - const resolvedSrcDirectory = join(root, startConfig.srcDirectory) - resolvedStartConfig.srcDirectory = resolvedSrcDirectory - - const startFilePath = resolveEntry({ - type: 'start entry', - configuredEntry: startConfig.start.entry, - defaultEntry: 'start', - resolvedSrcDirectory, - required: false, - }) - resolvedStartConfig.startFilePath = startFilePath - - const routerFilePath = resolveEntry({ - type: 'router entry', - configuredEntry: startConfig.router.entry, - defaultEntry: 'router', - resolvedSrcDirectory, - required: true, - }) - resolvedStartConfig.routerFilePath = routerFilePath - - const clientEntryPath = resolveEntry({ - type: 'client entry', - configuredEntry: startConfig.client.entry, - defaultEntry: 'client', - resolvedSrcDirectory, - required: false, - }) - - const serverEntryPath = resolveEntry({ - type: 'server entry', - configuredEntry: startConfig.server.entry, - defaultEntry: 'server', - resolvedSrcDirectory, - required: false, - }) - - const clientAlias = vite.normalizePath( - clientEntryPath ?? corePluginOpts.defaultEntryPaths.client, - ) - const serverAlias = vite.normalizePath( - serverEntryPath ?? corePluginOpts.defaultEntryPaths.server, - ) - const startAlias = vite.normalizePath( - startFilePath ?? corePluginOpts.defaultEntryPaths.start, - ) - const routerAlias = vite.normalizePath(routerFilePath) - - const entryAliasConfiguration: Record< - (typeof ENTRY_POINTS)[keyof typeof ENTRY_POINTS], - string - > = { - [ENTRY_POINTS.client]: clientAlias, - [ENTRY_POINTS.server]: serverAlias, - [ENTRY_POINTS.start]: startAlias, - [ENTRY_POINTS.router]: routerAlias, - } - - const startPackageName = - `@tanstack/${corePluginOpts.framework}-start` as const - - // crawl packages that have start in "peerDependencies" - // see https://github.com/svitejs/vitefu/blob/d8d82fa121e3b2215ba437107093c77bde51b63b/src/index.js#L95-L101 - - // this is currently uncached; could be implemented similarly as vite handles lock file changes - // see https://github.com/vitejs/vite/blob/557f797d29422027e8c451ca50dd84bf8c41b5f0/packages/vite/src/node/optimizer/index.ts#L1282 - - const crawlFrameworkPkgsResult = await crawlFrameworkPkgs({ - root: process.cwd(), - isBuild: command === 'build', - isFrameworkPkgByJson(pkgJson) { - const peerDependencies = pkgJson['peerDependencies'] - - if (peerDependencies) { - if ( - startPackageName in peerDependencies || - '@tanstack/start-client-core' in peerDependencies - ) { - return true - } - } - - return false - }, - }) - - return { - // see https://vite.dev/config/shared-options.html#apptype - // this will prevent vite from injecting middlewares that we don't want - appType: viteConfig.appType ?? 'custom', - environments: { - [VITE_ENVIRONMENT_NAMES.client]: { - consumer: 'client', - build: { - rollupOptions: { - input: { - main: ENTRY_POINTS.client, - }, - }, - outDir: getClientOutputDirectory(viteConfig), - }, - optimizeDeps: { - exclude: crawlFrameworkPkgsResult.optimizeDeps.exclude, - // Ensure user code can be crawled for dependencies - entries: [clientAlias, routerAlias].map((entry) => - // Entries are treated as `tinyglobby` patterns so need to be escaped - escapePath(entry), - ), - }, - }, - [VITE_ENVIRONMENT_NAMES.server]: { - consumer: 'server', - build: { - ssr: true, - rollupOptions: { - input: - viteConfig.environments?.[VITE_ENVIRONMENT_NAMES.server] - ?.build?.rollupOptions?.input ?? serverAlias, - }, - outDir: getServerOutputDirectory(viteConfig), - commonjsOptions: { - include: [/node_modules/], - }, - copyPublicDir: - viteConfig.environments?.[VITE_ENVIRONMENT_NAMES.server] - ?.build?.copyPublicDir ?? false, - }, - optimizeDeps: { - // Ensure user code can be crawled for dependencies - entries: [serverAlias, startAlias, routerAlias].map((entry) => - // Entries are treated as `tinyglobby` patterns so need to be escaped - escapePath(entry), - ), - }, - }, - }, - - resolve: { - noExternal: [ - // ENTRY_POINTS.start, - '@tanstack/start**', - `@tanstack/${corePluginOpts.framework}-start**`, - ...crawlFrameworkPkgsResult.ssr.noExternal.sort(), - ], - alias: { - ...entryAliasConfiguration, - }, - }, - /* prettier-ignore */ - define: { - // define is an esbuild function that replaces the any instances of given keys with the given values - // i.e: __FRAMEWORK_NAME__ can be replaced with JSON.stringify("TanStack Start") - // This is not the same as injecting environment variables. - - ...defineReplaceEnv('TSS_SERVER_FN_BASE', TSS_SERVER_FN_BASE), - ...defineReplaceEnv('TSS_CLIENT_OUTPUT_DIR', getClientOutputDirectory(viteConfig)), - ...defineReplaceEnv('TSS_ROUTER_BASEPATH', startConfig.router.basepath), - ...(command === 'serve' ? defineReplaceEnv('TSS_SHELL', startConfig.spa?.enabled ? 'true' : 'false') : {}), - ...defineReplaceEnv('TSS_DEV_SERVER', command === 'serve' ? 'true' : 'false'), - }, - builder: { - sharedPlugins: true, - async buildApp(builder) { - const client = builder.environments[VITE_ENVIRONMENT_NAMES.client] - const server = builder.environments[VITE_ENVIRONMENT_NAMES.server] - - if (!client) { - throw new Error('Client environment not found') - } - - if (!server) { - throw new Error('SSR environment not found') - } - - if (!client.isBuilt) { - // Build the client bundle first - await builder.build(client) - } - if (!server.isBuilt) { - // Build the SSR bundle - await builder.build(server) - } - }, - }, - } - }, - buildApp: { - order: 'post', - async handler(builder) { - const { startConfig } = getConfig() - await postServerBuild({ builder, startConfig }) - }, - }, - }, - tanStackStartRouter(startPluginOpts, getConfig, corePluginOpts), - // N.B. TanStackStartCompilerPlugin must be before the TanStackServerFnPlugin - startCompilerPlugin({ framework: corePluginOpts.framework, environments }), - createServerFnPlugin({ - framework: corePluginOpts.framework, - directive, - environments, - }), - - TanStackServerFnPlugin({ - // This is the ID that will be available to look up and import - // our server function manifest and resolve its module - manifestVirtualImportId: VIRTUAL_MODULES.serverFnManifest, - directive, - generateFunctionId: startPluginOpts?.serverFns?.generateFunctionId, - callers: [ - { - envConsumer: 'client', - getRuntimeCode: () => - `import { createClientRpc } from '@tanstack/${corePluginOpts.framework}-start/client-rpc'`, - replacer: (d) => `createClientRpc('${d.functionId}')`, - envName: VITE_ENVIRONMENT_NAMES.client, - }, - { - envConsumer: 'server', - getRuntimeCode: () => - `import { createSsrRpc } from '@tanstack/${corePluginOpts.framework}-start/ssr-rpc'`, - envName: VITE_ENVIRONMENT_NAMES.server, - replacer: (d) => `createSsrRpc('${d.functionId}')`, - getServerFnById: corePluginOpts.serverFn?.ssr?.getServerFnById, - }, - ], - provider: { - getRuntimeCode: () => - `import { createServerRpc } from '@tanstack/${corePluginOpts.framework}-start/server-rpc'`, - replacer: (d) => `createServerRpc('${d.functionId}', ${d.fn})`, - envName: - corePluginOpts.serverFn?.providerEnv || VITE_ENVIRONMENT_NAMES.server, - }, - }), - loadEnvPlugin(), - startManifestPlugin({ - getClientBundle: () => getBundle(VITE_ENVIRONMENT_NAMES.client), - getConfig, - }), - devServerPlugin({ getConfig }), - previewServerPlugin(), - { - name: 'tanstack-start:core:capture-bundle', - applyToEnvironment(e) { - return ( - e.name === VITE_ENVIRONMENT_NAMES.client || - e.name === VITE_ENVIRONMENT_NAMES.server - ) - }, - enforce: 'post', - generateBundle(_options, bundle) { - const environment = this.environment.name as ViteEnvironmentNames - if (!Object.values(VITE_ENVIRONMENT_NAMES).includes(environment)) { - throw new Error(`Unknown environment: ${environment}`) - } - capturedBundle[environment] = bundle - }, - }, - ] -} - -function defineReplaceEnv( - key: TKey, - value: TValue, -): { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue } { - return { - [`process.env.${key}`]: JSON.stringify(value), - [`import.meta.env.${key}`]: JSON.stringify(value), - } as { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue } -} diff --git a/packages/start-plugin-core/src/post-build.ts b/packages/start-plugin-core/src/post-build.ts new file mode 100644 index 0000000000..d81a49bcab --- /dev/null +++ b/packages/start-plugin-core/src/post-build.ts @@ -0,0 +1,64 @@ +import { HEADERS } from '@tanstack/start-server-core/constants' +import type { TanStackStartOutputConfig } from './schema' + +export interface StartPostBuildAdapter { + getClientOutputDirectory: () => string + prerender: (startConfig: TanStackStartOutputConfig) => Promise +} + +export async function postBuild({ + startConfig, + adapter, +}: { + startConfig: TanStackStartOutputConfig + adapter: StartPostBuildAdapter +}) { + if (startConfig.prerender?.enabled !== false) { + startConfig.prerender = { + ...startConfig.prerender, + enabled: + startConfig.prerender?.enabled ?? + startConfig.pages.some((d) => + typeof d === 'string' ? false : !!d.prerender?.enabled, + ), + } + } + + if (startConfig.spa?.enabled) { + startConfig.prerender = { + ...startConfig.prerender, + enabled: true, + } + + const maskUrl = new URL(startConfig.spa.maskPath, 'http://localhost') + if (maskUrl.origin !== 'http://localhost') { + throw new Error('spa.maskPath must be a path (no protocol/host)') + } + + startConfig.pages.push({ + path: maskUrl.toString().replace('http://localhost', ''), + prerender: { + ...startConfig.spa.prerender, + headers: { + ...startConfig.spa.prerender.headers, + [HEADERS.TSS_SHELL]: 'true', + }, + }, + sitemap: { + exclude: true, + }, + }) + } + + if (startConfig.prerender.enabled) { + await adapter.prerender(startConfig) + } + + if (startConfig.sitemap?.enabled) { + const { buildSitemap } = await import('./build-sitemap') + buildSitemap({ + startConfig, + publicDir: adapter.getClientOutputDirectory(), + }) + } +} diff --git a/packages/start-plugin-core/src/post-server-build.ts b/packages/start-plugin-core/src/post-server-build.ts deleted file mode 100644 index 01c9f74667..0000000000 --- a/packages/start-plugin-core/src/post-server-build.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { HEADERS } from '@tanstack/start-server-core' -import { buildSitemap } from './build-sitemap' -import { VITE_ENVIRONMENT_NAMES } from './constants' -import { prerender } from './prerender' -import type { TanStackStartOutputConfig } from './schema' -import type { ViteBuilder } from 'vite' - -export async function postServerBuild({ - builder, - startConfig, -}: { - builder: ViteBuilder - startConfig: TanStackStartOutputConfig -}) { - // If the user has not set a prerender option, we need to set it to true - // if the pages array is not empty and has sub options requiring for prerendering - // If the user has explicitly set prerender.enabled, this should be respected - if (startConfig.prerender?.enabled !== false) { - startConfig.prerender = { - ...startConfig.prerender, - enabled: - startConfig.prerender?.enabled ?? - startConfig.pages.some((d) => - typeof d === 'string' ? false : !!d.prerender?.enabled, - ), - } - } - - // Setup the options for prerendering the SPA shell (i.e `src/routes/__root.tsx`) - if (startConfig.spa?.enabled) { - startConfig.prerender = { - ...startConfig.prerender, - enabled: true, - } - - const maskUrl = new URL(startConfig.spa.maskPath, 'http://localhost') - - startConfig.pages.push({ - path: maskUrl.toString().replace('http://localhost', ''), - prerender: { - ...startConfig.spa.prerender, - headers: { - ...startConfig.spa.prerender.headers, - [HEADERS.TSS_SHELL]: 'true', - }, - }, - sitemap: { - exclude: true, - }, - }) - } - - // Run the prerendering process - if (startConfig.prerender.enabled) { - await prerender({ - startConfig, - builder, - }) - } - - // Run the sitemap build process - if (startConfig.pages.length) { - buildSitemap({ - startConfig, - publicDir: - builder.environments[VITE_ENVIRONMENT_NAMES.client]?.config.build - .outDir ?? builder.config.build.outDir, - }) - } -} diff --git a/packages/start-plugin-core/src/prerender.ts b/packages/start-plugin-core/src/prerender.ts index ea6368109e..9510a9ab37 100644 --- a/packages/start-plugin-core/src/prerender.ts +++ b/packages/start-plugin-core/src/prerender.ts @@ -1,30 +1,34 @@ import { promises as fsp } from 'node:fs' import os from 'node:os' import path from 'pathe' -import { joinURL, withBase, withoutBase } from 'ufo' -import { VITE_ENVIRONMENT_NAMES } from './constants' +import { joinURL, withBase, withTrailingSlash, withoutBase } from 'ufo' import { createLogger } from './utils' import { Queue } from './queue' -import type { PreviewServer, ResolvedConfig, ViteBuilder } from 'vite' import type { Page, TanStackStartOutputConfig } from './schema' +const DEFAULT_RETRY_DELAY = 500 + +export interface PrerenderHandler { + getClientOutputDirectory: () => string + getOrigin?: () => string + request: (path: string, options?: RequestInit) => Promise + close?: () => Promise +} + export async function prerender({ startConfig, - builder, + handler, }: { startConfig: TanStackStartOutputConfig - builder: ViteBuilder + handler: PrerenderHandler }) { const logger = createLogger('prerender') logger.info('Prerendering pages...') - // If prerender is enabled if (startConfig.prerender?.enabled) { - // default to root page if no pages are defined let pages = startConfig.pages.length ? startConfig.pages : [{ path: '/' }] if (startConfig.prerender.autoStaticPathsDiscovery ?? true) { - // merge discovered static pages with user-defined pages const pagesMap = new Map(pages.map((item) => [item.path, item])) const discoveredPages = globalThis.TSS_PRERENDABLE_PATHS || [] @@ -40,57 +44,21 @@ export async function prerender({ startConfig.pages = pages } - const serverEnv = builder.environments[VITE_ENVIRONMENT_NAMES.server] + const routerBasePath = joinURL('/', startConfig.router.basepath ?? '') + const routerBaseUrl = new URL( + routerBasePath, + handler.getOrigin?.() ?? 'http://localhost', + ) - if (!serverEnv) { - throw new Error( - `Vite's "${VITE_ENVIRONMENT_NAMES.server}" environment not found`, - ) - } - - const clientEnv = builder.environments[VITE_ENVIRONMENT_NAMES.client] - if (!clientEnv) { - throw new Error( - `Vite's "${VITE_ENVIRONMENT_NAMES.client}" environment not found`, - ) - } - - const outputDir = clientEnv.config.build.outDir - - process.env.TSS_PRERENDERING = 'true' - - // Start Vite preview server instead of importing module - const previewServer = await startPreviewServer(serverEnv.config) - const baseUrl = getResolvedUrl(previewServer) - - const isRedirectResponse = (res: Response) => { - return res.status >= 300 && res.status < 400 && res.headers.get('location') - } - async function localFetch( - path: string, - options?: RequestInit, - maxRedirects: number = 5, - ): Promise { - const url = new URL(path, baseUrl) - const request = new Request(url, options) - const response = await fetch(request) - - if (isRedirectResponse(response) && maxRedirects > 0) { - const location = response.headers.get('location')! - if (location.startsWith('http://localhost') || location.startsWith('/')) { - const newUrl = location.replace('http://localhost', '') - return localFetch(newUrl, options, maxRedirects - 1) - } else { - logger.warn(`Skipping redirect to external location: ${location}`) - } - } - - return response - } + startConfig.pages = validateAndNormalizePrerenderPages( + startConfig.pages, + routerBaseUrl, + ) try { - // Crawl all pages - const pages = await prerenderPages({ outputDir }) + const pages = await prerenderPages({ + outputDir: handler.getClientOutputDirectory(), + }) logger.info(`Prerendered ${pages.length} pages:`) pages.forEach((page) => { @@ -98,14 +66,15 @@ export async function prerender({ }) } catch (error) { logger.error(error) + throw error } finally { - await previewServer.close() + await handler.close?.() } function extractLinks(html: string): Array { const linkRegex = /]+href=["']([^"']+)["'][^>]*>/g const links: Array = [] - let match + let match: RegExpExecArray | null while ((match = linkRegex.exec(html)) !== null) { const href = match[1] @@ -124,47 +93,53 @@ export async function prerender({ const concurrency = startConfig.prerender?.concurrency ?? os.cpus().length logger.info(`Concurrency: ${concurrency}`) const queue = new Queue({ concurrency }) - const routerBasePath = joinURL('/', startConfig.router.basepath ?? '') + + startConfig.pages = validateAndNormalizePrerenderPages( + startConfig.pages, + routerBaseUrl, + ) startConfig.pages.forEach((page) => addCrawlPageTask(page)) + if (queue.isSettled()) { + logger.info('No pages matched prerender filter; skipping.') + return Array.from(prerendered) + } + await queue.start() return Array.from(prerendered) function addCrawlPageTask(page: Page) { - // Was the page already seen? if (seen.has(page.path)) return - // Add the page to the seen set seen.add(page.path) if (page.fromCrawl) { startConfig.pages.push(page) } - // If not enabled, skip if (!(page.prerender?.enabled ?? true)) return - // If there is a filter link, check if the page should be prerendered - if (startConfig.prerender?.filter && !startConfig.prerender.filter(page)) + if ( + startConfig.prerender?.filter && + !startConfig.prerender.filter(page) + ) { return + } - // Resolve the merged default and page-specific prerender options const prerenderOptions = { ...startConfig.prerender, ...page.prerender, } - // Add the task queue.add(async () => { logger.info(`Crawling: ${page.path}`) const retries = retriesByPath.get(page.path) || 0 - try { - // Fetch the route - const res = await localFetch( - withBase(page.path, routerBasePath), + try { + const res = await requestWithRedirects( + withTrailingSlash(withBase(page.path, routerBasePath)), { headers: { ...(prerenderOptions.headers ?? {}), @@ -177,6 +152,7 @@ export async function prerender({ if (isRedirectResponse(res)) { logger.warn(`Max redirects reached for ${page.path}`) } + throw new Error(`Failed to fetch ${page.path}: ${res.statusText}`, { cause: res, }) @@ -186,7 +162,6 @@ export async function prerender({ prerenderOptions.outputPath || page.path ).split(/[?#]/)[0]! - // Guess route type and populate fileName const contentType = res.headers.get('content-type') || '' const isImplicitHTML = !cleanPagePath.endsWith('.html') && contentType.includes('html') @@ -200,17 +175,14 @@ export async function prerender({ let htmlPath: string if (isSpaShell) { - // For SPA shell, ignore autoSubfolderIndex option htmlPath = cleanPagePath + '.html' + } else if ( + cleanPagePath.endsWith('/') || + (prerenderOptions.autoSubfolderIndex ?? true) + ) { + htmlPath = joinURL(cleanPagePath, 'index.html') } else { - if ( - cleanPagePath.endsWith('/') || - (prerenderOptions.autoSubfolderIndex ?? true) - ) { - htmlPath = joinURL(cleanPagePath, 'index.html') - } else { - htmlPath = cleanPagePath + '.html' - } + htmlPath = cleanPagePath + '.html' } const filename = withoutBase( @@ -219,8 +191,19 @@ export async function prerender({ ) const html = await res.text() - - const filepath = path.join(outputDir, filename) + const resolvedOutputDir = path.resolve(outputDir) + const filepath = path.resolve(outputDir, filename.replace(/^\/+/, '')) + const outputPrefix = resolvedOutputDir.endsWith(path.sep) + ? resolvedOutputDir + : resolvedOutputDir + path.sep + if ( + filepath !== resolvedOutputDir && + !filepath.startsWith(outputPrefix) + ) { + throw new Error( + `Prerender output path must stay within the client output directory: ${filename}`, + ) + } await fsp.mkdir(path.dirname(filepath), { recursive: true, @@ -236,7 +219,6 @@ export async function prerender({ Object.assign(page, newPage) } - // Find new links if (prerenderOptions.crawlLinks ?? true) { const links = extractLinks(html) for (const link of links) { @@ -245,52 +227,148 @@ export async function prerender({ } } catch (error) { if (retries < (prerenderOptions.retryCount ?? 0)) { - logger.warn(`Encountered error, retrying: ${page.path} in 500ms`) - await new Promise((resolve) => - setTimeout(resolve, prerenderOptions.retryDelay), + const retryDelay = normalizeRetryDelay(prerenderOptions.retryDelay) + logger.warn( + `Encountered error, retrying: ${page.path} in ${retryDelay}ms`, ) + await new Promise((resolve) => setTimeout(resolve, retryDelay)) retriesByPath.set(page.path, retries + 1) addCrawlPageTask(page) - } else { - if (prerenderOptions.failOnError ?? true) { - throw error - } + } else if (prerenderOptions.failOnError ?? true) { + throw error } } }) } } -} -async function startPreviewServer( - viteConfig: ResolvedConfig, -): Promise { - const vite = await import('vite') + function normalizeRetryDelay(value: number | undefined): number { + const retryDelay = Number(value) - try { - return await vite.preview({ - configFile: viteConfig.configFile, - preview: { - port: 0, - open: false, - }, + if (!Number.isFinite(retryDelay) || retryDelay < 0) { + return DEFAULT_RETRY_DELAY + } + + return Math.trunc(retryDelay) + } + + async function requestWithRedirects( + requestPath: string, + options?: RequestInit, + maxRedirects: number = 5, + currentUrl = resolveInternalUrl(requestPath, routerBaseUrl, routerBaseUrl), + ): Promise { + const path = currentUrl && toPreviewPath(currentUrl, routerBaseUrl) + if (!path) { + throw new Error(`Prerender request path must be relative: ${requestPath}`) + } + + const response = await handler.request(path, { + ...options, + redirect: 'manual', }) - } catch (error) { - throw new Error( - 'Failed to start the Vite preview server for prerendering', - { - cause: error, - }, + + if (isRedirectResponse(response) && maxRedirects > 0) { + const location = response.headers.get('location')!.trim() + const url = resolveInternalUrl(location, currentUrl, routerBaseUrl) + const redirectPath = url && toPreviewPath(url, routerBaseUrl) + + if (url && redirectPath) { + return requestWithRedirects( + redirectPath, + options, + maxRedirects - 1, + url, + ) + } + + logger.warn(`Skipping redirect outside the preview basepath: ${location}`) + } + + return response + } +} + +function isRedirectResponse(res: Response) { + return ( + [301, 302, 303, 307, 308].includes(res.status) && + !!res.headers.get('location')?.trim() + ) +} + +function resolveInternalUrl( + href: string, + baseUrl: URL, + allowedOrigin: URL, +): URL | undefined { + try { + const url = new URL(href, baseUrl) + if ( + url.protocol !== allowedOrigin.protocol || + url.origin !== allowedOrigin.origin || + url.username || + url.password + ) { + return undefined + } + return url + } catch { + return undefined + } +} + +function toPreviewPath(url: URL, routerBaseUrl: URL): string | undefined { + const basepath = routerBaseUrl.pathname.replace(/\/$/, '') + if ( + basepath && + url.pathname !== basepath && + !url.pathname.startsWith(basepath + '/') + ) { + return undefined + } + if (url.pathname.startsWith('//')) { + return url.href + } + return url.pathname + url.search +} + +export function validateAndNormalizePrerenderPages( + pages: Array, + routerBaseUrl: URL, +): Array { + return pages.map((page) => { + let url: URL + try { + url = new URL(page.path, routerBaseUrl) + } catch (err) { + throw new Error(`prerender page path must be relative: ${page.path}`, { + cause: err, + }) + } + + if ( + url.protocol !== routerBaseUrl.protocol || + url.origin !== routerBaseUrl.origin || + url.username || + url.password + ) { + throw new Error(`prerender page path must be relative: ${page.path}`) + } + + const decodedPathname = decodeURIComponent(url.pathname) + const normalizedPath = decodedPathname + url.search + url.hash + const normalizedUrl = resolveInternalUrl( + normalizedPath, + routerBaseUrl, + routerBaseUrl, ) - } -} + if (!normalizedUrl) { + throw new Error(`prerender page path must be relative: ${page.path}`) + } -function getResolvedUrl(previewServer: PreviewServer): URL { - const baseUrl = previewServer.resolvedUrls?.local[0] - - if (!baseUrl) { - throw new Error('No resolved URL is available from the Vite preview server') - } - - return new URL(baseUrl) + return { + ...page, + path: normalizedPath, + } + }) } diff --git a/packages/start-plugin-core/src/preview-server-plugin/plugin.ts b/packages/start-plugin-core/src/preview-server-plugin/plugin.ts deleted file mode 100644 index 5322ef9443..0000000000 --- a/packages/start-plugin-core/src/preview-server-plugin/plugin.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { pathToFileURL } from 'node:url' -import { basename, extname, join } from 'pathe' -import { NodeRequest, sendNodeResponse } from 'srvx/node' -import { VITE_ENVIRONMENT_NAMES } from '../constants' -import { getServerOutputDirectory } from '../output-directory' -import type { Plugin } from 'vite' - -export function previewServerPlugin(): Plugin { - return { - name: 'tanstack-start-core:preview-server', - configurePreviewServer: { - // Run last so platform plugins (Cloudflare, Vercel, etc.) can register their handlers first - order: 'post', - handler(server) { - // Return a function so Vite's internal middlewares (static files, etc.) handle requests first. - // Our SSR handler only processes requests that nothing else handled. - return () => { - // Cache the server build to avoid re-importing on every request - let serverBuild: any = null - - server.middlewares.use(async (req, res, next) => { - try { - // Lazy load server build on first request - if (!serverBuild) { - // Derive output filename from input - const serverEnv = - server.config.environments[VITE_ENVIRONMENT_NAMES.server] - const serverInput = - serverEnv?.build.rollupOptions.input ?? 'server' - - if (typeof serverInput !== 'string') { - throw new Error('Invalid server input. Expected a string.') - } - - // Get basename without extension and add .js - const outputFilename = `${basename(serverInput, extname(serverInput))}.js` - const serverOutputDir = getServerOutputDirectory(server.config) - const serverEntryPath = join(serverOutputDir, outputFilename) - const imported = await import( - pathToFileURL(serverEntryPath).toString() - ) - - serverBuild = imported.default - } - - const webReq = new NodeRequest({ req, res }) - const webRes: Response = await serverBuild.fetch(webReq) - - // Temporary workaround - // Vite preview's compression middleware doesn't support flattened array headers that srvx sets - // Call writeHead() before srvx to avoid corruption - res.setHeaders(webRes.headers) - res.writeHead(webRes.status, webRes.statusText) - - return sendNodeResponse(res, webRes) - } catch (error) { - next(error) - } - }) - } - }, - }, - } -} diff --git a/packages/start-plugin-core/src/resolve-entries.ts b/packages/start-plugin-core/src/resolve-entries.ts index dd28815fa0..23eb4c651c 100644 --- a/packages/start-plugin-core/src/resolve-entries.ts +++ b/packages/start-plugin-core/src/resolve-entries.ts @@ -13,6 +13,10 @@ function resolveModule(opts: ResolveModuleOptions): string | undefined { from: opts.from, extensions: ['.ts', '.js', '.mts', '.mjs', '.tsx', '.jsx'], try: true, + // exsolve's default cache is process-wide and keeps misses: a dev server + // restart would not see an entry created since. The plugin already + // resolves the entries once per instance. + cache: false, }) } diff --git a/packages/start-plugin-core/src/rsbuild/COMPILER_ARCHITECTURE.md b/packages/start-plugin-core/src/rsbuild/COMPILER_ARCHITECTURE.md new file mode 100644 index 0000000000..a97c500b0d --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/COMPILER_ARCHITECTURE.md @@ -0,0 +1,199 @@ +# Rsbuild Compiler Architecture + +This document explains the TanStack Start compiler integration for Rsbuild and Rspack. It focuses on server-function discovery, Rspack cache interaction, and the resolver virtual module. + +## Goals + +The Rsbuild integration has to do three things at the same time: + +- Compile Start-specific source patterns such as server functions, isomorphic functions, middleware, and compiler virtual modules. +- Keep server-function metadata available when Rspack restores modules from its persistent cache and skips transforms. +- Generate the `#tanstack-start-server-fn-resolver` virtual module after the server-function registry is complete for the current compilation. + +The important point is that server-function discovery is a side effect of compilation. If Rspack restores a transformed module from persistent cache, the transform side effect does not run. We therefore store the discovered metadata on the Rspack module itself and replay it from `module.buildInfo`. + +## Main Files + +- `plugin.ts` wires the Rsbuild plugin phases, virtual modules, RSC hooks, compiler ordering, and resolver rebuild hooks. +- `start-compiler-host.ts` registers the Start compiler transforms, captures server-function metadata, writes metadata to Rspack `buildInfo`, and replays cached metadata. +- `start-compiler-metadata.ts` defines the string keys and types used by the metadata loader. +- `start-compiler-metadata-loader.ts` is the real Rspack loader that writes server-function metadata to the current module's `buildInfo`. +- `virtual-modules.ts` owns the resolver virtual module and writes updated virtual module content per Rsbuild environment. +- `../start-compiler/handleCreateServerFn.ts` discovers server functions while compiling caller modules. +- `../start-compiler/server-fn-resolver-module.ts` generates the resolver module from the current server-function registry. + +## Environments + +Start registers compiler work for each Rsbuild environment that can affect server-function metadata: + +- `client` discovers functions referenced from browser code and marks them client-accessible. +- `ssr` discovers functions reachable from the server-rendered route graph. +- A separate provider environment is included when server-function providers are not compiled in `ssr` and RSC is not enabled. + +The shared registry is `serverFnsById`. It is passed to `virtual-modules.ts`, which uses it to generate resolver module content. + +## Cold Transform Path + +`registerStartCompilerTransforms()` registers an `api.transform({ order: 'pre' })` transform for each Start compiler environment. + +When a matching module is compiled normally: + +1. Rsbuild runs the Start transform in the pre-loader phase. +2. The transform checks compiler virtual modules first. +3. It runs cheap code filters to skip files that cannot contain Start compiler patterns. +4. It lazily creates one `StartCompiler` per environment. +5. It detects which compiler features are present in the current code. +6. It serializes access to the per-environment `StartCompiler` through `runCompilerTask()`. +7. It calls `compiler.compile({ id, code, detectedKinds })`. +8. During compile, `handleCreateServerFn()` reports discovered server functions through `onServerFnsById`. +9. The transform stores the discovered server functions for this module in the environment's pending metadata map. + +The module ID used for transform metadata is `ctx.resource`. The metadata loader later reads `this.resource`. Using the same Rspack resource string keeps the handoff stable across resource queries. + +## Server-Function Discovery + +Server functions are discovered in caller modules, not in provider modules. In `handleCreateServerFn()`, each discovered function records: + +- `functionName`, the generated handler export name. +- `functionId`, the stable server-function ID. +- `filename`, the caller module ID. +- `extractedFilename`, the provider module ID with the server-function split query. +- `isClientReferenced`, whether client-origin calls are allowed. + +`onServerFnsById` merges discoveries into the shared `serverFnsById` registry. While a compile task is active, it also merges the same discoveries into that module's `activeServerFnMetadata` object. After compile finishes, that object becomes the metadata payload for the module. + +Per-environment compiler tasks are serialized because `StartCompiler` owns mutable module caches and because `activeServerFnMetadata` must only describe the module currently being compiled in that environment. + +## Loading And Resolving Modules + +The compiler sometimes needs to read or resolve imported modules while compiling a source file. + +`start-compiler-host.ts` uses two native Rsbuild/Rspack surfaces for this: + +- `ctx.resolve()` from the active Rsbuild transform context resolves module IDs. +- `compiler.inputFileSystem` reads source through Rspack's input filesystem. + +An `AsyncLocalStorage` value binds `loadModule` and `resolveId` back to the active transform context. That lets the compiler add dependencies to the current Rspack module without reaching into Rspack private resolver internals. + +## Why A Real Loader Is Used + +Rsbuild `api.transform()` is implemented as a loader, but its callback only exposes the transform context. It does not expose the current `NormalModule` or `module.buildInfo`. + +Rspack persists custom `module.buildInfo` fields. To write metadata there, Start installs a small real loader after the transform: + +1. `start-compiler-host.ts` adds a rule with `enforce: 'post'` for Start transformable modules. +2. The rule points to the emitted `start-compiler-metadata-loader.js` file. +3. The loader receives the environment's pending metadata map through loader options. +4. A public `NormalModule.getCompilationHooks(compilation).loader` hook adds a setter to the loader context. +5. The loader reads metadata for `this.resource` and calls the setter. +6. The setter writes to `module.buildInfo['tanstack.start.serverFns']`. + +Only string-keyed, JSON-serializable `buildInfo` fields are used. Rspack persists those fields with the module cache. Symbol keys and private cache internals are intentionally avoided. + +## Cache-Enabled And Cache-Disabled Behavior + +The metadata loader is installed regardless of `performance.buildCache`. + +When persistent cache is enabled, Rspack may later restore a module without rerunning the Start transform or the metadata loader. The `buildInfo` payload is then replayed from the cached module. + +When persistent cache is disabled, the same loader path still runs during normal compilation and writes in-memory `buildInfo`. Keeping one path avoids conditional behavior and keeps cold, watch, cache-disabled, and cache-enabled builds aligned. The overhead is one small post loader for modules that already match the Start transform test. + +The cache-specific part is not the loader itself. The cache-specific part is that Rspack can persist and later restore the `buildInfo` field. + +## Stale Metadata Clearing + +If a module previously contained server functions and then no longer produces metadata, the metadata loader writes an empty payload: + +```ts +{ version: 1, serverFnsById: {} } +``` + +This prevents stale server-function entries from surviving on a cached module's `buildInfo` after a file edit removes or renames server functions. + +## Warm Cache Replay + +Each relevant compiler installs a `finishMake` hook at stage `-20`. + +At that point Rspack has built or restored the module graph for the environment, and module `buildInfo` is available. The hook: + +1. Iterates over `compilation.modules`. +2. Reads `module.buildInfo['tanstack.start.serverFns']`. +3. Validates the payload with the versioned schema. +4. Merges valid module metadata into an environment snapshot. +5. Stores the snapshot in `serverFnsByEnvironment`. +6. Rebuilds the shared `serverFnsById` registry from all environment snapshots. +7. Notifies virtual modules that resolver content may have changed. + +The shared registry is rebuilt from snapshots instead of being append-only. This is what lets deleted or renamed server functions disappear after watch rebuilds or warm-cache restores. + +The pending transform-to-loader metadata maps are cleared on each Rspack `compile` hook. That prevents metadata discovered in an earlier compilation from being written to a later module when the transform no longer runs or no longer discovers server functions. + +## Why Snapshots Are Per Environment + +Each Rsbuild environment can see different information for the same file. For example, client and SSR caller environments can mark functions as client-accessible, while server and provider environments own server execution details. The merged registry preserves the broadest known access information. + +A single global replay pass would either drop another environment's metadata or keep stale metadata too long. The model is therefore: + +- Build one current snapshot per environment. +- Replace the shared registry with the union of all available snapshots. +- Regenerate resolver content from that shared registry. + +This keeps the global registry convergent while allowing Rspack environments to finish independently. + +## Resolver Rebuild Ordering + +The resolver virtual module must be rebuilt after cached metadata has been replayed. + +The ordering is: + +1. `finishMake` stage `-20`: replay `buildInfo` into environment snapshots and rebuild `serverFnsById`. +2. `finishMake` stage `-10`: write resolver virtual module content and rebuild modules that import the resolver. + +For non-RSC builds, each server-like environment that needs the resolver installs the stage `-10` rebuild hook. + +For RSC builds, the server environment installs the RSC resolver rebuild hook at stage `-10`. It generates provider-style resolver content because RSC server actions run inside the server/RSC environment and do not need the client-reference check in that resolver layer. + +## Compiler Ordering + +Non-RSC Rsbuild uses Rspack `MultiCompiler.setDependencies()` to make resolver-owning environments wait for metadata-producing environments. + +The intended order is: + +- `client` runs before every server-like environment. +- If a separate provider environment exists, the provider runs after `client`. +- If a separate provider environment exists, `ssr` runs after both `client` and the provider. + +That ordering prevents the `ssr` resolver module from being finalized before provider metadata is available. + +RSC builds intentionally do not add these dependencies. Rspack's native RSC coordinator interleaves server and client compilation phases. Adding MultiCompiler dependencies on top of it can deadlock the build. + +## Native APIs Used + +The implementation uses Rsbuild/Rspack integration points instead of cache internals: + +- Rsbuild `api.transform()` for source transforms. +- Rsbuild transform `ctx.resolve()` for module resolution. +- Rspack `compiler.inputFileSystem` for source reads. +- Rspack loaders for access to the loader pipeline. +- Rspack `NormalModule.getCompilationHooks(compilation).loader` to extend loader context. +- Rspack `module.buildInfo` for module-scoped persisted metadata. +- Rspack `compiler.hooks.finishMake` for module graph replay and resolver rebuild ordering. +- Rspack `compilation.rebuildModule()` through the local `rebuildModulesContaining()` helper. +- Rspack `MultiCompiler.setDependencies()` for non-RSC compiler ordering. +- Rspack `experiments.VirtualModulesPlugin` for virtual module content. + +The implementation avoids private persistent-cache files, direct cache mutation, direct `_module` access from loaders, global handoff state, and disabling module caching with `this.cacheable(false)`. + +## When A New Server Function Is Compiled + +For a new server function in a normal cold compile: + +1. Rsbuild sends the source module through the Start pre transform. +2. `StartCompiler.compile()` rewrites the caller module and discovers the server function. +3. `onServerFnsById` merges the function into `serverFnsById` and the active module metadata object. +4. The transform stores `{ version: 1, serverFnsById: discoveredServerFnsById }` in the environment metadata map under the module resource. +5. The post metadata loader runs for the same resource. +6. The loader writes that payload into `module.buildInfo['tanstack.start.serverFns']`. +7. Rspack owns the module from there. If persistent cache is enabled, Rspack persists the module and its string-keyed `buildInfo` with its normal cache machinery. +8. At `finishMake -20`, Start reads current module `buildInfo` and rebuilds the environment snapshot. +9. At `finishMake -10`, Start rewrites and rebuilds the resolver virtual module so runtime lookups can find the new function. diff --git a/packages/start-plugin-core/src/rsbuild/INTERNALS-import-protection.md b/packages/start-plugin-core/src/rsbuild/INTERNALS-import-protection.md new file mode 100644 index 0000000000..eca4051281 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/INTERNALS-import-protection.md @@ -0,0 +1,203 @@ +# Rsbuild Import Protection - Adapter Internals + +## Scope + +This document covers the Rsbuild-specific orchestration around the shared +import-protection core in `src/import-protection/INTERNALS.md`. + +Rsbuild owns: + +- post-transform enforcement through a Rspack post-loader +- virtual-module transport through `VirtualModulesPlugin` +- compilation-truth reporting in `processAssets` +- final graph reconstruction from Rspack compilation data + +Shared transform-time AST analysis, rewrite logic, source extraction, usage +lookup, source locations, trace formatting, and mock code generation are +described in the shared internals doc. + +## Mental Model + +Vite is primarily `resolveId`-driven. Rsbuild is primarily `transform` + +`processAssets`-driven. + +That difference explains most of the adapter divergence. + +Rsbuild does not emulate the Vite pending-queue state machine. It relies more +directly on post-transform code and final compilation truth. + +## Native Hook Shape + +Import protection is attached through Rsbuild hooks, not a dedicated mini-plugin +object: + +1. `onBeforeBuild` +2. `onBeforeDevCompile` +3. `modifyRspackConfig` +4. `processAssets(..., { stage: 'report' })` + +`modifyRspackConfig` installs both the virtual-modules plugin and the +environment-scoped import-protection post-loader. + +## State Model + +Per environment, Rsbuild keeps a smaller runtime state than Vite: + +- `resolveCache` +- `seenViolations` + +Shared adapter state contains: + +- `virtualModules` +- `vmPlugins` +- `readyVmPlugins` +- `pendingWrites` + +Notably absent compared to Vite: + +- no `pendingViolations` +- no `postTransformImports` +- no broad `deferredBuildViolations` +- no resolve-time dev reachability pipeline + +## Transform Phase + +Rsbuild enforcement runs after the Start compiler in a Rspack loader with +`enforce: 'post'`. The complete transform pipeline lives in +`import-protection-loader.ts`; mutable configuration and per-environment state +are passed through loader options. + +That matters because many compiler-safe imports are already stripped by the time +import protection runs. This naturally suppresses a large class of false +positives without a Vite-style pending verification pass. + +The transform phase is responsible for: + +- self-denial for forbidden files +- self-denial for marker-protected files in the wrong environment +- persisting detected marker metadata in Rspack `module.buildInfo` +- direct specifier rewrites to mock-edge modules + +The transform treats the code it receives as authoritative. It does not read, +parse, or analyze original source. Imports removed by the Start compiler are no +longer part of this phase; imports with unsafe client/server usage remain in the +transformed code and are checked normally. + +## Virtual Module Transport + +Rsbuild reuses the shared mock generators, but not the Vite id transport. + +Instead it writes environment-scoped virtual files under: + +```text +/node_modules/.virtual/import-protection// +``` + +The important forms are: + +- `mock-silent.mjs` +- `mock-runtime-.mjs` +- `mock-edge-.mjs` + +Writes may happen before the `VirtualModulesPlugin` instance is ready, so the +adapter queues them and flushes during compilation setup. + +## Reporting Phase + +`processAssets({ stage: 'report' })` is the authoritative reporting step. + +It reconstructs the final view of the compilation from Rspack data by: + +1. snapshotting each module and its outgoing connections +2. collecting specifier and file violations plus possible marker modules +3. deduplicating marker modules and validating their persisted metadata +4. returning early when no violations remain +5. building the `ImportGraph` and diagnostic indexes only when needed + +Each `RspackModuleGraphNode` stores a module and its imported modules. Missing and +errored target modules are skipped. +Connections are not filtered by `getActiveState()` because inactive connections +can still carry diagnostic evidence. Duplicate connections to the same target +module collapse to one. + +Snapshotting does not apply source-file eligibility. Intermediate modules remain +available for entry-to-violation traces, while the scanner applies importer and +rule checks. Normalized resource ids are used for rules, traces, and diagnostics; +`resourceResolveData.path` is preferred for original-source lookup. + +When violations exist, the adapter replays the snapshot to build `ImportGraph`; +it does not query outgoing connections again. A clean compilation avoids entry +traversal, graph indexes, and module-source loading. + +Diagnostic enrichment is lazy. The transform-result provider reads +`module.originalSource().sourceAndMap()` when available. It gets original code +from sourcemap `sourcesContent`, then falls back to +`compilation.inputFileSystem.readFile()`. Results and in-flight reads are cached +per module. + +Importer locations use this order: + +1. find unsafe usage in original code +2. find unsafe usage in compiled code +3. find the import statement in compiled, then original code + +Trace edges search compiled import statements. The adapter does not use +`dependency.loc`, which may identify a transformed declaration rather than the +actual import usage. + +This is the core Rsbuild-native replacement for Vite's `generateBundle` +verification plus dev pending-violation flow. + +## Source And Compilation APIs + +The Rsbuild adapter intentionally prefers native Rspack APIs where possible. + +Transform-time: + +- `loaderContext.resource` +- `loaderContext.resourcePath` +- `loaderContext.context` +- `loaderContext.resolve(...)` +- `loaderContext._module.buildInfo` + +`_module` is a deprecated Rspack loader-context API. It is used deliberately +because a loader invocation is bound to one exact module instance, including +its layer. Keying modules by resource would collapse distinct modules that use +the same resource in different layers. Do not add a resource-map fallback. + +Compilation-time: + +- `module.resourceResolveData?.resource` +- `module.resourceResolveData?.path` +- `module.identifier()` (normalized fallback) +- `module.buildInfo` +- `module.originalSource().sourceAndMap()` (confirmed diagnostics only) +- sourcemap `sourcesContent` +- `compilation.inputFileSystem.readFile()` (original-source fallback) +- `moduleGraph.getOutgoingConnectionsInOrder(module)` +- `connection.dependency.request` + +## Marker Handling + +Unlike Vite, Rsbuild does not introduce plugin-owned virtual marker modules for +normal operation. + +The real package marker files are source-level markers. The post-loader writes +`{ kind, source }` directly to its current `_module.buildInfo` before replacing +a wrong-environment module. The metadata therefore stays attached to the exact +resource-and-layer module and survives self-denial mocking and persistent-cache +restores. + +`processAssets` treats non-excluded, non-file-denied imports as possible marker +modules, then checks their `buildInfo`. It does not infer marker kind from final +dependency requests. + +## Practical Maintainer Rule + +When changing Rsbuild import protection, ask: + +1. Can the change be expressed in shared analysis/rewrite/mock codegen instead? +2. If it is adapter-specific, is it really about post-transform enforcement, + virtual-file transport, or compilation-time reporting? +3. Can final compilation truth answer the question more simply than adding a new + pending state machine? diff --git a/packages/start-plugin-core/src/rsbuild/import-protection-loader.ts b/packages/start-plugin-core/src/rsbuild/import-protection-loader.ts new file mode 100644 index 0000000000..eba703f121 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/import-protection-loader.ts @@ -0,0 +1,342 @@ +import remapping from '@jridgewell/remapping' + +import { matchesAny } from '../import-protection/matchers' +import { + getImportProtectionEnvType, + getImportProtectionRelativePath, +} from '../import-protection/adapterUtils' +import { + getImportSourcesFromResult, + getMockExportNamesBySourceFromResult, + getNamedExportsFromResult, +} from '../import-protection/analysis' +import { rewriteDeniedImports } from '../import-protection/rewrite' +import { normalizeSourceMap } from '../import-protection/sourceLocation' +import { + generateDevSelfDenialModule, + generateSelfContainedMockModule, +} from '../import-protection/virtualModules' +import { + canonicalizeResolvedId, + checkFileDenial, + normalizeFilePath, +} from '../import-protection/utils' +import { + IMPORT_PROTECTION_BUILD_INFO_FIELD, + ensureMockEdgeModule, + ensureRuntimeMockModule, + ensureSilentMockModule, + getOrCreateEnvState, + getRulesForEnvironment, + serializePattern, + shouldCheckImporterWithCache, +} from './import-protection' +import type { + EnvRuntimeState, + ImportProtectionMarker, + PerfCollector, + PluginConfig, + SharedState, +} from './import-protection' +import type { ExtensionlessAbsoluteIdResolver } from '../import-protection/extensionlessAbsoluteIdResolver' +import type { TransformResult } from '../import-protection/sourceLocation' +import type { SourceMapInput } from '@jridgewell/remapping' +import type { Rspack } from '@rsbuild/core' + +export interface ImportProtectionLoaderOptions { + config: PluginConfig + envName: string + envStates: Map + extensionlessResolver: ExtensionlessAbsoluteIdResolver + perf?: PerfCollector + shared: SharedState + shouldCheckImporterCache: Map +} + +type ImportProtectionLoaderContext = + Rspack.LoaderContext + +type ImportProtectionTransformResult = + | string + | { + code: string + map?: ReturnType | null + } + +async function resolveAgainstImporter(opts: { + envState: EnvRuntimeState + config: PluginConfig + context: string | null + importerId: string + source: string + resolve: ImportProtectionLoaderContext['resolve'] + extensionlessResolver: ExtensionlessAbsoluteIdResolver + perf?: PerfCollector +}): Promise { + const importerDir = + opts.context ?? opts.importerId.replace(/[/\\][^/\\]*$/, '') + const normalizedImporterDir = normalizeFilePath(importerDir) + const cacheKey = `${normalizedImporterDir}:${opts.source}` + + if (opts.envState.resolveCache.has(cacheKey)) { + opts.perf?.count('resolve.cached') + return opts.envState.resolveCache.get(cacheKey) ?? null + } + + const startedAt = opts.perf ? performance.now() : 0 + opts.perf?.count('resolve.calls') + const resolved = await new Promise((resolve, reject) => { + opts.resolve(importerDir, opts.source, (error, result) => { + if (error) { + reject(error) + return + } + + resolve(typeof result === 'string' ? result : null) + }) + }) + .catch(() => null) + .finally(() => { + if (opts.perf) { + opts.perf.time('resolve', startedAt) + } + }) + + if (!resolved) { + opts.envState.resolveCache.set(cacheKey, null) + return null + } + + const canonical = canonicalizeResolvedId( + resolved, + opts.config.root, + (value) => opts.extensionlessResolver.resolve(value), + ) + + opts.envState.resolveCache.set(cacheKey, canonical) + return canonical +} + +async function transformImportProtection( + loaderContext: ImportProtectionLoaderContext, + code: string, + options: ImportProtectionLoaderOptions, +): Promise { + const startedAt = options.perf ? performance.now() : 0 + const { config, envName, perf, shared } = options + perf?.count('transform.calls') + perf?.count(`transform.env.${envName}`) + + try { + const id = loaderContext.resource + delete loaderContext._module.buildInfo[IMPORT_PROTECTION_BUILD_INFO_FIELD] + + if (!config.enabled) { + return code + } + + const envType = getImportProtectionEnvType(config, envName) + const envState = getOrCreateEnvState(options.envStates, envName) + const file = normalizeFilePath(loaderContext.resourcePath) + + if ( + !shouldCheckImporterWithCache({ + config, + cache: options.shouldCheckImporterCache, + perf, + file, + }) + ) { + perf?.count('transform.skippedImporter') + return code + } + + const matchers = getRulesForEnvironment(config, envName) + const relativeFile = getImportProtectionRelativePath(config.root, file) + const transformResult: TransformResult = { + code, + filename: file, + map: undefined, + originalCode: undefined, + perf, + } + const importSources = getImportSourcesFromResult(transformResult) + perf?.count('transform.importSources', importSources.length) + + const serverOnlyMarker = importSources.find((source) => + config.markerSpecifiers.serverOnly.has(source), + ) + const clientOnlyMarker = importSources.find((source) => + config.markerSpecifiers.clientOnly.has(source), + ) + + if (serverOnlyMarker && clientOnlyMarker) { + throw new Error( + `[import-protection] File "${relativeFile}" has both server-only and client-only markers. This is not allowed.`, + ) + } + + const marker: ImportProtectionMarker | undefined = serverOnlyMarker + ? { kind: 'server', source: serverOnlyMarker } + : clientOnlyMarker + ? { kind: 'client', source: clientOnlyMarker } + : undefined + + if (marker) { + loaderContext._module.buildInfo[IMPORT_PROTECTION_BUILD_INFO_FIELD] = + marker + } + + const fileMatch = checkFileDenial(relativeFile, matchers) + const markerViolation = + (envType === 'client' && marker?.kind === 'server') || + (envType === 'server' && marker?.kind === 'client') + + if (fileMatch || markerViolation) { + let exportNames: Array = [] + + try { + exportNames = getNamedExportsFromResult(transformResult) + } catch { + exportNames = [] + } + + if (config.command === 'build') { + return generateSelfContainedMockModule(exportNames) + } + + const runtimeId = ensureRuntimeMockModule({ + shared, + envName, + mode: config.mockAccess, + env: envName, + importer: file, + specifier: relativeFile, + }) + + return generateDevSelfDenialModule(exportNames, runtimeId) + } + + const deniedSpecifierReplacements = new Map() + let exportsBySource: Map> | undefined + const getExportsBySource = () => { + if (exportsBySource) { + return exportsBySource + } + + try { + exportsBySource = getMockExportNamesBySourceFromResult(transformResult) + } catch { + exportsBySource = new Map>() + } + return exportsBySource + } + + for (const source of importSources) { + const specifierMatch = matchesAny(source, matchers.specifiers) + if (!specifierMatch) { + continue + } + + const resolved = await resolveAgainstImporter({ + envState, + config, + context: loaderContext.context, + importerId: id, + source, + resolve: loaderContext.resolve.bind(loaderContext), + extensionlessResolver: options.extensionlessResolver, + perf, + }) + + const runtimeId = + config.command === 'build' + ? ensureSilentMockModule(shared, envName) + : ensureRuntimeMockModule({ + shared, + envName, + mode: config.mockAccess, + env: envName, + importer: file, + specifier: source, + }) + + const replacement = ensureMockEdgeModule({ + shared, + envName, + payload: { + exports: getExportsBySource().get(source) ?? [], + runtimeId, + violation: { + env: envName, + envType, + importer: file, + specifier: source, + ...(resolved ? { resolved } : {}), + patternText: serializePattern(specifierMatch.pattern), + }, + }, + }) + + deniedSpecifierReplacements.set(source, replacement) + } + + if (deniedSpecifierReplacements.size === 0) { + return code + } + + const rewritten = rewriteDeniedImports( + code, + id, + new Set(deniedSpecifierReplacements.keys()), + (source) => deniedSpecifierReplacements.get(source) ?? source, + ) + + if (!rewritten) { + return code + } + + return { + code: rewritten.code, + map: normalizeSourceMap(rewritten.map) ?? null, + } + } finally { + if (perf) { + perf.time('transform', startedAt) + } + } +} + +const importProtectionLoader: Rspack.LoaderDefinition = + function (source, sourceMap): void { + const callback = this.async() + const options = this.getOptions() + + transformImportProtection(this, source, options).then( + (result) => { + if (typeof result === 'string') { + callback(null, result, sourceMap) + return + } + + const mergedMap = + sourceMap && result.map + ? remapping( + [result.map as SourceMapInput, sourceMap as SourceMapInput], + () => null, + ) + : (result.map ?? sourceMap) + + callback( + null, + result.code, + mergedMap as unknown as Exclude, + ) + }, + (error: unknown) => { + callback(error instanceof Error ? error : new Error(String(error))) + }, + ) + } + +export default importProtectionLoader diff --git a/packages/start-plugin-core/src/rsbuild/import-protection.ts b/packages/start-plugin-core/src/rsbuild/import-protection.ts new file mode 100644 index 0000000000..f9d46505e3 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/import-protection.ts @@ -0,0 +1,1726 @@ +import { writeFileSync } from 'node:fs' +import { dirname, extname, resolve as resolvePath } from 'node:path' +import { fileURLToPath } from 'node:url' + +import { + getDefaultImportProtectionRules, + getMarkerSpecifiers, +} from '../import-protection/defaults' +import { normalizePath } from '../utils' +import { ExtensionlessAbsoluteIdResolver } from '../import-protection/extensionlessAbsoluteIdResolver' +import { compileMatchers } from '../import-protection/matchers' +import { + getImportProtectionEnvType, + getImportProtectionRelativePath, + getImportProtectionRulesForEnvironment, + shouldCheckImportProtectionImporter, +} from '../import-protection/adapterUtils' +import { + ImportLocCache, + buildCodeSnippet, + createImportSpecifierLocationIndex, + findImportStatementLocationFromTransformed, + findOriginalUsageLocation, + findPostCompileUsageLocation, + normalizeSourceMap, + pickOriginalCodeFromSourcesContent, +} from '../import-protection/sourceLocation' +import { + ImportGraph, + buildTrace, + formatViolation, +} from '../import-protection/trace' +import { + loadMockEdgeModule, + loadMockRuntimeModule, + loadSilentMockModule, +} from '../import-protection/virtualModules' +import { + buildSourceCandidates, + clearNormalizeFilePathCache, + dedupePatterns, + dedupeViolationKey, + isFileExcluded, + normalizeFilePath, +} from '../import-protection/utils' +import type { + ImportProtectionBehavior, + ImportProtectionOptions, +} from '../schema' +import type { CompiledMatcher } from '../import-protection/matchers' +import type { FileMatchers } from '../import-protection/utils' +import type { + SourceMapLike, + TransformResult, + TransformResultProvider, +} from '../import-protection/sourceLocation' +import type { Loc, TraceStep, ViolationInfo } from '../import-protection/trace' +import type { CompileStartFrameworkOptions, GetConfigFn } from '../types' +import type { + ModifyRspackConfigFn, + RsbuildPluginAPI, + Rspack, + rspack as rspackNamespaceType, +} from '@rsbuild/core' + +type RspackNamespace = typeof rspackNamespaceType +type RspackVirtualModulesPlugin = Pick< + InstanceType, + 'writeModule' +> +type ProcessAssetsContext = Parameters< + Parameters[1] +>[0] +type ModifyRspackConfig = Parameters[0] +type ModifyRspackConfigUtils = Parameters[1] +type ImportProtectionRspackConfig = { + module: Pick + plugins: Array +} +type ImportProtectionModifyRspackConfigUtils = { + environment: Pick + rspack: { + experiments: { + VirtualModulesPlugin: new ( + modules: Record, + ) => RspackVirtualModulesPlugin + } + } +} +type ImportProtectionRsbuildPluginAPI = { + context: Pick + onBeforeBuild: (handler: () => void) => void + onBeforeDevCompile: (handler: () => void) => void + modifyRspackConfig: ( + handler: ( + config: ImportProtectionRspackConfig, + utils: ImportProtectionModifyRspackConfigUtils, + ) => void, + ) => void + processAssets: RsbuildPluginAPI['processAssets'] +} +type ImportProtectionGetConfigFn = () => { + startConfig: Pick['startConfig'], 'importProtection'> + resolvedStartConfig: Pick< + ReturnType['resolvedStartConfig'], + 'root' | 'srcDirectory' + > +} +type RspackCompilation = Rspack.Compilation +type RspackModule = Rspack.Module +type RspackDependency = Rspack.Dependency +type RspackInputFileSystem = NonNullable + +export type ImportProtectionMarkerKind = 'server' | 'client' +export interface ImportProtectionMarker { + kind: ImportProtectionMarkerKind + source: string +} + +export const IMPORT_PROTECTION_BUILD_INFO_FIELD = + 'tanstack.start.importProtection' + +type PerfTiming = { + count: number + totalMs: number + maxMs: number +} + +export type PerfCollector = { + count: (name: string, value?: number) => void + time: (name: string, startedAt: number) => void + flush: (root: string, envName: string, phase: string) => void +} + +function isPerfEnabled(): boolean { + return ( + process.env.TSR_IMPORT_PROTECTION_PERF === '1' || + process.env.TSR_IMPORT_PROTECTION_PERF === 'true' + ) +} + +function createPerfCollector(): PerfCollector { + const counters = new Map() + const timings = new Map() + const flushEnvironments = new Set() + let flushCount = 0 + + return { + count(name, value = 1) { + counters.set(name, (counters.get(name) ?? 0) + value) + }, + time(name, startedAt) { + const duration = performance.now() - startedAt + const timing = timings.get(name) + if (timing) { + timing.count++ + timing.totalMs += duration + timing.maxMs = Math.max(timing.maxMs, duration) + } else { + timings.set(name, { count: 1, totalMs: duration, maxMs: duration }) + } + }, + flush(root, envName, phase) { + flushCount++ + flushEnvironments.add(envName) + + const payload = { + adapter: 'rsbuild', + root, + phase, + flushCount, + flushEnvironments: Array.from(flushEnvironments).sort(), + counters: Object.fromEntries(counters), + timings: Object.fromEntries( + Array.from(timings, ([name, timing]) => [ + name, + { + count: timing.count, + totalMs: Number(timing.totalMs.toFixed(3)), + avgMs: Number((timing.totalMs / timing.count).toFixed(3)), + maxMs: Number(timing.maxMs.toFixed(3)), + }, + ]), + ), + } + + const file = process.env.TSR_IMPORT_PROTECTION_PERF_FILE + if (file) { + writeFileSync(file, `${JSON.stringify(payload, null, 2)}\n`) + } else { + console.warn( + `[import-protection:perf] ${JSON.stringify(payload, null, 2)}`, + ) + } + }, + } +} + +export interface EnvRules { + specifiers: Array + files: Array + excludeFiles: Array +} + +export interface PluginConfig { + enabled: boolean + root: string + command: 'build' | 'serve' + srcDirectory: string + framework: CompileStartFrameworkOptions + effectiveBehavior: ImportProtectionBehavior + mockAccess: 'error' | 'warn' | 'off' + logMode: 'once' | 'always' + maxTraceDepth: number + compiledRules: { + client: EnvRules + server: EnvRules + } + includeMatchers: Array + excludeMatchers: Array + ignoreImporterMatchers: Array + markerSpecifiers: { + serverOnly: Set + clientOnly: Set + } + envTypeMap: Map + onViolation?: ( + info: ViolationInfo, + ) => boolean | void | Promise +} + +export interface EnvRuntimeState { + resolveCache: Map + seenViolations: Set +} + +export interface SharedState { + root: string + virtualModules: Map + vmPlugins: Record + readyVmPlugins: Record + pendingWrites: Map> +} + +interface CompilationEdge { + importerModule: RspackModule + specifier?: string + resolved: string + resolvedModule: RspackModule +} + +interface CompilationEdgeIndex { + edges: Array + edgeByKey: Map + edgesByModules: Map> +} + +interface CompilationImportGraph { + importGraph: ImportGraph + edgeIndex: CompilationEdgeIndex +} + +interface CompilationTransformResultProvider { + getTransformResult: ( + module: RspackModule, + ) => Promise +} + +// An identity-only snapshot of one module's compilation connections. +// Derived paths, requests, locations, and diagnostic indexes live elsewhere. +interface CompilationImport { + dependency: RspackDependency + module: RspackModule +} + +interface RspackModuleGraphNode { + module: RspackModule + imports: Array +} + +interface MockEdgePayload { + exports: Array + runtimeId: string + violation: { + env: string + envType: 'client' | 'server' + importer: string + specifier: string + resolved?: string + patternText: string + } +} + +interface ModuleGraphEdge { + importer: RspackModule + module: RspackModule +} + +type CompilationViolation = + | { + type: 'specifier' + payload: MockEdgePayload + edge: ModuleGraphEdge + } + | { + type: 'file' + edge: ModuleGraphEdge + source: string + pattern: string | RegExp + } + | { + type: 'marker' + importer: RspackModule + source: string + } + +type ResolvedImportProtectionCheck = + | { type: 'file'; fileMatch: FileMatchers['files'][number] } + | { type: 'marker' } + +const IMPORT_PROTECTION_VIRTUAL_DIR = 'node_modules/.virtual/import-protection' +const MOCK_EDGE_FILE_PREFIX = 'mock-edge-' +const MOCK_RUNTIME_FILE_PREFIX = 'mock-runtime-' +const MOCK_SILENT_FILE = 'mock-silent.mjs' +const currentDir = dirname(fileURLToPath(import.meta.url)) +const importProtectionLoader = resolvePath( + currentDir, + 'import-protection-loader.js', +) + +function toBase64Url(input: unknown): string { + return Buffer.from(JSON.stringify(input), 'utf8').toString('base64url') +} + +function fromBase64Url(input: string): T { + return JSON.parse(Buffer.from(input, 'base64url').toString('utf8')) as T +} + +export function getRulesForEnvironment( + config: PluginConfig, + envName: string, +): EnvRules { + return getImportProtectionRulesForEnvironment(config, envName) as EnvRules +} + +export function serializePattern(pattern: string | RegExp): string { + return typeof pattern === 'string' ? pattern : pattern.toString() +} + +function dedupeKey(info: ViolationInfo): string { + return dedupeViolationKey(info) +} + +export function getRsbuildResolvedImportProtectionCheck( + relativeResolved: string, + matchers: FileMatchers, +): ResolvedImportProtectionCheck | undefined { + if (isFileExcluded(relativeResolved, matchers)) { + return undefined + } + + const fileMatch = matchers.files.find((matcher) => + matcher.test(relativeResolved), + ) + if (fileMatch) { + return { type: 'file', fileMatch } + } + + return { type: 'marker' } +} + +export function getOrCreateEnvState( + envStates: Map, + envName: string, +): EnvRuntimeState { + let env = envStates.get(envName) + + if (!env) { + env = { + resolveCache: new Map(), + seenViolations: new Set(), + } + envStates.set(envName, env) + } + + return env +} + +export function shouldCheckImporterWithCache(opts: { + config: PluginConfig + cache: Map + perf?: PerfCollector + file: string +}): boolean { + const normalizedFile = normalizeFilePath(opts.file) + const cached = opts.cache.get(normalizedFile) + if (cached !== undefined) { + opts.perf?.count('shouldCheckImporter.cached') + return cached + } + + const result = shouldCheckImportProtectionImporter( + opts.config, + normalizedFile, + ) + opts.cache.set(normalizedFile, result) + return result +} + +function getVirtualModulePath( + root: string, + envName: string, + filename: string, +): string { + return normalizePath( + resolvePath(root, IMPORT_PROTECTION_VIRTUAL_DIR, envName, filename), + ) +} + +function queuePendingWrite( + shared: SharedState, + envName: string, + filePath: string, + code: string, +): void { + let writes = shared.pendingWrites.get(envName) + if (!writes) { + writes = new Map() + shared.pendingWrites.set(envName, writes) + } + + writes.set(filePath, code) +} + +function tryWriteVirtualModule( + shared: SharedState, + envName: string, + filePath: string, + code: string, +): string { + const current = shared.virtualModules.get(filePath) + if (current === code) { + return filePath + } + + shared.virtualModules.set(filePath, code) + + const vmPlugin = shared.vmPlugins[envName] + if (!vmPlugin || !shared.readyVmPlugins[envName]) { + queuePendingWrite(shared, envName, filePath, code) + return filePath + } + + vmPlugin.writeModule(filePath, code) + return filePath +} + +function flushPendingWrites(shared: SharedState, envName: string): void { + const writes = shared.pendingWrites.get(envName) + if (!writes?.size || !shared.readyVmPlugins[envName]) { + return + } + + for (const [filePath, code] of writes) { + shared.vmPlugins[envName]?.writeModule(filePath, code) + writes.delete(filePath) + } + + if (writes.size === 0) { + shared.pendingWrites.delete(envName) + } +} + +export function ensureSilentMockModule( + shared: SharedState, + envName: string, +): string { + return tryWriteVirtualModule( + shared, + envName, + getVirtualModulePath(shared.root, envName, MOCK_SILENT_FILE), + loadSilentMockModule().code, + ) +} + +export function ensureRuntimeMockModule(opts: { + shared: SharedState + envName: string + mode: 'error' | 'warn' | 'off' + env: string + importer: string + specifier: string +}): string { + const encoded = toBase64Url({ + mode: opts.mode, + env: opts.env, + importer: opts.importer, + specifier: opts.specifier, + trace: [], + }) + + return tryWriteVirtualModule( + opts.shared, + opts.envName, + getVirtualModulePath( + opts.shared.root, + opts.envName, + `${MOCK_RUNTIME_FILE_PREFIX}${encoded}.mjs`, + ), + loadMockRuntimeModule(encoded).code, + ) +} + +export function ensureMockEdgeModule(opts: { + shared: SharedState + envName: string + payload: MockEdgePayload +}): string { + const encoded = toBase64Url(opts.payload) + + return tryWriteVirtualModule( + opts.shared, + opts.envName, + getVirtualModulePath( + opts.shared.root, + opts.envName, + `${MOCK_EDGE_FILE_PREFIX}${encoded}.mjs`, + ), + loadMockEdgeModule(encoded).code, + ) +} + +function getMockEdgePayloadFromFile( + filePath: string, +): MockEdgePayload | undefined { + const match = /(?:^|[\\/])mock-edge-([^/\\]+)\.mjs$/.exec(filePath) + if (!match) { + return undefined + } + + try { + return fromBase64Url(match[1]!) + } catch { + return undefined + } +} + +function getModuleResource(module: RspackModule): string { + const resourceResolveData = ( + module as RspackModule & { + resourceResolveData?: { path?: string; resource?: string } + } + ).resourceResolveData + + return normalizeFilePath( + resourceResolveData?.path ?? + resourceResolveData?.resource ?? + module.identifier(), + ) +} + +const IMPORT_PROTECTION_PARSEABLE_EXTENSIONS = new Set([ + '.ts', + '.tsx', + '.mts', + '.cts', + '.js', + '.jsx', + '.mjs', + '.cjs', +]) + +function isImportProtectionSourceFile(file: string | undefined): boolean { + if (!file) { + return false + } + + const extension = extname(normalizeFilePath(file)) + return ( + extension.length > 0 && + IMPORT_PROTECTION_PARSEABLE_EXTENSIONS.has(extension) + ) +} + +function readModuleSourceFromInputFileSystem( + inputFileSystem: RspackInputFileSystem | null, + file: string, +): Promise { + if (!inputFileSystem) { + return Promise.resolve(undefined) + } + + return new Promise((resolve) => { + inputFileSystem.readFile(file, (error, data) => { + if (error || data == null) { + resolve(undefined) + return + } + + resolve(String(data)) + }) + }) +} + +function buildTransformResultProvider(opts: { + root: string + perf?: PerfCollector + inputFileSystem: RspackInputFileSystem | null +}): CompilationTransformResultProvider { + const resultByModule = new WeakMap() + const loadingResultByModule = new WeakMap< + RspackModule, + Promise + >() + const missingSource = new WeakSet() + + async function loadModuleTransformResult( + module: RspackModule, + ): Promise { + opts.perf?.count('processAssets.provider.modulesLoaded') + const resource = getModuleResource(module) + let code: string | undefined + let map: SourceMapLike | undefined + + const source = module.originalSource() + if (source) { + const sourceAndMapStartedAt = opts.perf ? performance.now() : 0 + const sourceAndMap = source.sourceAndMap() + if (opts.perf) { + opts.perf.time( + 'processAssets.provider.sourceAndMap', + sourceAndMapStartedAt, + ) + } + code = String(sourceAndMap.source) + map = normalizeSourceMap(sourceAndMap.map as SourceMapLike | null) + } + + const originalCodeStartedAt = opts.perf ? performance.now() : 0 + let originalCode = map?.sourcesContent + ? pickOriginalCodeFromSourcesContent(map, resource, opts.root) + : undefined + if (originalCode === undefined) { + originalCode = await readModuleSourceFromInputFileSystem( + opts.inputFileSystem, + resource, + ) + if (originalCode !== undefined) { + opts.perf?.count('processAssets.provider.inputFileSystemReads') + } + } + if (opts.perf) { + opts.perf.time( + 'processAssets.provider.originalCode', + originalCodeStartedAt, + ) + } + + code ??= originalCode + if (code === undefined) { + missingSource.add(module) + return undefined + } + + const result: TransformResult = { + code, + filename: resource, + map, + originalCode, + perf: opts.perf, + } + resultByModule.set(module, result) + return result + } + + return { + getTransformResult(module) { + if (missingSource.has(module)) { + return Promise.resolve(undefined) + } + + const cached = resultByModule.get(module) + if (cached) { + return Promise.resolve(cached) + } + + const loading = loadingResultByModule.get(module) + if (loading) { + return loading + } + + const result = loadModuleTransformResult(module) + loadingResultByModule.set(module, result) + return result + }, + } +} + +function getCompilationEdgeKey( + importer: string, + resolved: string, + specifier: string | undefined, +): string { + return `${importer}\0${resolved}\0${specifier ?? ''}` +} + +function getCompilationModulesKey(importer: string, resolved: string): string { + return `${importer}\0${resolved}` +} + +function hasModuleError(module: RspackModule): boolean { + return 'error' in module && Boolean(module.error) +} + +function forEachEntryModule(opts: { + compilation: RspackCompilation + visitModule: (module: RspackModule) => void +}): void { + for (const entry of opts.compilation.entries.values()) { + for (const dependency of entry.dependencies) { + const connection = opts.compilation.moduleGraph.getConnection(dependency) + const module = connection?.module + if (!module || hasModuleError(module)) { + continue + } + opts.visitModule(module) + } + } +} + +function addEntryModulesToGraph(opts: { + compilation: RspackCompilation + importGraph: ImportGraph +}): void { + forEachEntryModule({ + compilation: opts.compilation, + visitModule(module) { + opts.importGraph.addEntry(getModuleResource(module)) + }, + }) +} + +function forEachModules(opts: { + compilation: RspackCompilation + modules: Array + visitNode: (node: RspackModuleGraphNode) => void +}): Array { + const nodes: Array = [] + + for (const module of opts.modules) { + if (hasModuleError(module)) { + continue + } + + const imports: Array = [] + const importIndexByModule = new WeakMap() + const connections = + opts.compilation.moduleGraph.getOutgoingConnectionsInOrder(module) + + for (const connection of connections) { + const connectedModule = connection.module + if (!connectedModule) { + continue + } + + // Only consider modules that are not errored + if (hasModuleError(connectedModule)) { + continue + } + + const existingImportIndex = importIndexByModule.get(connectedModule) + if (existingImportIndex !== undefined) { + continue + } + + importIndexByModule.set(connectedModule, imports.length) + + imports.push({ + dependency: connection.dependency, + module: connectedModule, + }) + } + + const node = { module, imports } + nodes.push(node) + opts.visitNode(node) + } + + return nodes +} + +interface MarkerCheckTarget { + importer: RspackModule + module: RspackModule +} + +type FileViolation = Extract + +interface CompilationViolationScanner { + visitEntry: (module: RspackModule) => void + visitNode: (node: RspackModuleGraphNode) => void + finish: () => Array +} + +function createCompilationViolationScanner(opts: { + config: PluginConfig + envType: 'client' | 'server' + matchers: FileMatchers + shouldCheckImporter: (importer: string) => boolean +}): CompilationViolationScanner { + const specifierViolations: Array = [] + const fileViolations: Array = [] + const markerCheckTargets: Array = [] + const mockPayloadByModule = new WeakMap< + RspackModule, + MockEdgePayload | null + >() + + const getMockPayload = (module: RspackModule) => { + const cached = mockPayloadByModule.get(module) + if (cached !== undefined) { + return cached ?? undefined + } + + const payload = getMockEdgePayloadFromFile(getModuleResource(module)) + mockPayloadByModule.set(module, payload ?? null) + return payload + } + + return { + visitEntry(module) { + markerCheckTargets.push({ importer: module, module }) + }, + visitNode(node) { + const importer = getModuleResource(node.module) + if (!isImportProtectionSourceFile(importer)) { + return + } + + const shouldCheckImporter = opts.shouldCheckImporter(importer) + + for (const imported of node.imports) { + const source = imported.dependency.request + + if (shouldCheckImporter) { + const payload = getMockPayload(imported.module) + if (payload?.violation.importer === importer) { + specifierViolations.push({ + type: 'specifier', + payload, + edge: { + importer: node.module, + module: imported.module, + }, + }) + } + } + + if (!source) { + continue + } + + const resolved = getModuleResource(imported.module) + const relativeResolved = getImportProtectionRelativePath( + opts.config.root, + resolved, + ) + const importProtectionCheck = getRsbuildResolvedImportProtectionCheck( + relativeResolved, + opts.matchers, + ) + if (!importProtectionCheck) { + continue + } + + if (importProtectionCheck.type === 'marker') { + markerCheckTargets.push({ + importer: node.module, + module: imported.module, + }) + continue + } + + if (shouldCheckImporter) { + fileViolations.push({ + type: 'file', + edge: { + importer: node.module, + module: imported.module, + }, + source, + pattern: importProtectionCheck.fileMatch.pattern, + }) + } + } + }, + finish() { + const violations = [...specifierViolations, ...fileViolations] + const checkedMarkerModules = new WeakSet() + + for (const target of markerCheckTargets) { + if (!opts.shouldCheckImporter(getModuleResource(target.importer))) { + continue + } + + if (checkedMarkerModules.has(target.module)) { + continue + } + checkedMarkerModules.add(target.module) + + const marker = getMarkerForModule(target.module) + const violatesMarker = + (opts.envType === 'client' && marker?.kind === 'server') || + (opts.envType === 'server' && marker?.kind === 'client') + if (!violatesMarker) { + continue + } + + violations.push({ + type: 'marker', + importer: target.module, + source: marker.source, + }) + } + + return violations + }, + } +} + +function buildCompilationImportGraph(opts: { + compilation: RspackCompilation + nodes: Array +}): CompilationImportGraph { + const importGraph = new ImportGraph() + const edges: Array = [] + const edgeByKey = new Map() + const edgesByModules = new Map>() + + addEntryModulesToGraph({ + compilation: opts.compilation, + importGraph, + }) + + for (const node of opts.nodes) { + const importer = getModuleResource(node.module) + for (const imported of node.imports) { + const resolved = getModuleResource(imported.module) + const specifier = imported.dependency.request + const edge = { + importerModule: node.module, + specifier, + resolved, + resolvedModule: imported.module, + } + edges.push(edge) + importGraph.addEdge(resolved, importer, specifier) + + const edgeKey = getCompilationEdgeKey(importer, resolved, specifier) + if (!edgeByKey.has(edgeKey)) { + edgeByKey.set(edgeKey, edge) + } + + const modulesKey = getCompilationModulesKey(importer, resolved) + const moduleEdges = edgesByModules.get(modulesKey) + if (moduleEdges) { + moduleEdges.push(edge) + } else { + edgesByModules.set(modulesKey, [edge]) + } + } + } + + return { + importGraph, + edgeIndex: { + edges, + edgeByKey, + edgesByModules, + }, + } +} + +function findCompilationEdge( + edgeIndex: CompilationEdgeIndex, + importer: string, + resolved: string, + specifier?: string, +): CompilationEdge | undefined { + if (specifier) { + const exact = edgeIndex.edgeByKey.get( + getCompilationEdgeKey(importer, resolved, specifier), + ) + if (exact) { + return exact + } + } + + return edgeIndex.edgesByModules.get( + getCompilationModulesKey(importer, resolved), + )?.[0] +} + +const compilationImportSpecifierLocationIndex = + createImportSpecifierLocationIndex() + +async function resolveImporterLocation(opts: { + config: PluginConfig + provider: CompilationTransformResultProvider + importer: string + importerModule: RspackModule + source: string + resolved?: string + transformedSources?: Array + envType: 'client' | 'server' +}): Promise { + const transformResult = await opts.provider.getTransformResult( + opts.importerModule, + ) + const provider: TransformResultProvider = { + getTransformResult: () => transformResult, + } + const originalResult: TransformResult | undefined = + transformResult?.originalCode !== undefined + ? { + code: transformResult.originalCode, + filename: transformResult.filename, + map: undefined, + originalCode: transformResult.originalCode, + perf: transformResult.perf, + } + : undefined + const originalProvider: TransformResultProvider = { + getTransformResult: () => originalResult, + } + const sourceCandidates = buildSourceCandidates( + opts.source, + opts.resolved, + opts.config.root, + ) + for (const transformedSource of opts.transformedSources ?? []) { + for (const candidate of buildSourceCandidates( + transformedSource, + undefined, + opts.config.root, + )) { + sourceCandidates.add(candidate) + } + } + + const importLocCache = new ImportLocCache() + const originalImportLocCache = new ImportLocCache() + for (const source of sourceCandidates) { + const loc = + findOriginalUsageLocation( + provider, + opts.importer, + source, + opts.envType, + opts.config.root, + ) ?? + (await findPostCompileUsageLocation(provider, opts.importer, source)) ?? + (await findImportStatementLocationFromTransformed( + provider, + opts.importer, + source, + importLocCache, + compilationImportSpecifierLocationIndex.find, + )) ?? + (await findImportStatementLocationFromTransformed( + originalProvider, + opts.importer, + source, + originalImportLocCache, + compilationImportSpecifierLocationIndex.find, + )) + if (loc) { + return loc + } + } + + return undefined +} + +async function resolveTraceEdgeLocation(opts: { + root: string + provider: CompilationTransformResultProvider + importLocCache: ImportLocCache + importer: string + edge: CompilationEdge + specifier?: string +}): Promise { + if (!opts.specifier) { + return undefined + } + + const transformResult = await opts.provider.getTransformResult( + opts.edge.importerModule, + ) + const provider: TransformResultProvider = { + getTransformResult: () => transformResult, + } + for (const source of buildSourceCandidates( + opts.specifier, + opts.edge.resolved, + opts.root, + )) { + const loc = await findImportStatementLocationFromTransformed( + provider, + opts.importer, + source, + opts.importLocCache, + compilationImportSpecifierLocationIndex.find, + ) + if (loc) { + return loc + } + } + + return undefined +} + +async function rebuildAndAnnotateTrace(opts: { + root: string + provider: CompilationTransformResultProvider + importGraph: ImportGraph + edgeIndex: CompilationEdgeIndex + importer: string + specifier: string + importerLoc?: Loc + maxTraceDepth: number +}): Promise> { + const trace = buildTrace(opts.importGraph, opts.importer, opts.maxTraceDepth) + const importLocCache = new ImportLocCache() + + for (let i = 0; i < trace.length - 1; i++) { + const step = trace[i]! + const next = trace[i + 1]! + const edge = findCompilationEdge( + opts.edgeIndex, + step.file, + next.file, + step.specifier, + ) + const loc = edge + ? await resolveTraceEdgeLocation({ + root: opts.root, + provider: opts.provider, + importLocCache, + importer: step.file, + edge, + specifier: edge.specifier ?? step.specifier, + }) + : undefined + if (loc) { + step.line = loc.line + step.column = loc.column + } + } + + if (trace.length > 0) { + const last = trace[trace.length - 1]! + if (!last.specifier) { + last.specifier = opts.specifier + } + if (opts.importerLoc && last.line == null) { + last.line = opts.importerLoc.line + last.column = opts.importerLoc.column + } + } + + return trace +} + +async function buildViolationInfo(opts: { + config: PluginConfig + provider: CompilationTransformResultProvider + importGraph: ImportGraph + edgeIndex: CompilationEdgeIndex + perf?: PerfCollector + envName: string + envType: 'client' | 'server' + importer: string + importerModule: RspackModule + source: string + resolved?: string + transformedSources?: Array + type: 'specifier' | 'file' | 'marker' + pattern?: string | RegExp +}): Promise { + const startedAt = opts.perf ? performance.now() : 0 + opts.perf?.count('violations.enriched') + + const importerLocStartedAt = opts.perf ? performance.now() : 0 + const importerLoc = await resolveImporterLocation({ + config: opts.config, + provider: opts.provider, + importer: opts.importer, + importerModule: opts.importerModule, + source: opts.source, + resolved: opts.resolved, + transformedSources: opts.transformedSources, + envType: opts.envType, + }) + if (opts.perf) { + opts.perf.time('violations.resolveImporterLocation', importerLocStartedAt) + } + + const traceStartedAt = opts.perf ? performance.now() : 0 + const trace = await rebuildAndAnnotateTrace({ + root: opts.config.root, + provider: opts.provider, + importGraph: opts.importGraph, + edgeIndex: opts.edgeIndex, + importer: opts.importer, + specifier: opts.source, + importerLoc, + maxTraceDepth: opts.config.maxTraceDepth, + }) + if (opts.perf) { + opts.perf.time('violations.trace', traceStartedAt) + } + + const snippetStartedAt = opts.perf ? performance.now() : 0 + const transformResult = importerLoc + ? await opts.provider.getTransformResult(opts.importerModule) + : undefined + const snippet = importerLoc + ? buildCodeSnippet( + { + getTransformResult: () => transformResult, + }, + opts.importer, + importerLoc, + ) + : undefined + if (opts.perf && importerLoc) { + opts.perf.time('violations.snippet', snippetStartedAt) + } + + const info = { + env: opts.envName, + envType: opts.envType, + behavior: opts.config.effectiveBehavior, + type: opts.type, + pattern: opts.pattern, + specifier: opts.source, + importer: opts.importer, + ...(opts.resolved ? { resolved: opts.resolved } : {}), + ...(importerLoc ? { importerLoc } : {}), + trace, + snippet, + } + + if (opts.perf) { + opts.perf.time('violations.enrich', startedAt) + } + + return info +} + +function getMarkerForModule( + module: RspackModule, +): ImportProtectionMarker | undefined { + const file = getModuleResource(module) + if (!isImportProtectionSourceFile(file)) { + return undefined + } + + const marker = module.buildInfo[IMPORT_PROTECTION_BUILD_INFO_FIELD] + if (!marker || typeof marker !== 'object') { + return undefined + } + + if (!('kind' in marker) || !('source' in marker)) { + return undefined + } + + if ( + (marker.kind !== 'server' && marker.kind !== 'client') || + typeof marker.source !== 'string' + ) { + return undefined + } + + return { + kind: marker.kind, + source: marker.source, + } +} + +async function reportViolation(opts: { + config: PluginConfig + envState: EnvRuntimeState + compilation: RspackCompilation + rspack: RspackNamespace + perf?: PerfCollector + info: ViolationInfo +}): Promise { + const key = dedupeKey(opts.info) + if ( + opts.config.logMode !== 'always' && + opts.envState.seenViolations.has(key) + ) { + opts.perf?.count('violations.deduped') + return + } + + opts.envState.seenViolations.add(key) + opts.perf?.count('violations.reported') + + if (opts.config.onViolation) { + const startedAt = opts.perf ? performance.now() : 0 + const result = await opts.config.onViolation(opts.info) + if (opts.perf) { + opts.perf.time('violations.onViolation', startedAt) + } + if (result === false) { + opts.perf?.count('violations.suppressed') + return + } + } + + const message = formatViolation(opts.info, opts.config.root) + const error = new opts.rspack.WebpackError(message) + + if (opts.config.effectiveBehavior === 'error') { + opts.compilation.errors.push(error) + } else { + opts.compilation.warnings.push(error) + } +} + +export function registerImportProtection( + api: ImportProtectionRsbuildPluginAPI, + opts: { + getConfig: ImportProtectionGetConfigFn + framework: CompileStartFrameworkOptions + environments: Array<{ name: string; type: 'client' | 'server' }> + }, +): void { + const perf = isPerfEnabled() ? createPerfCollector() : undefined + const extensionlessResolver = new ExtensionlessAbsoluteIdResolver() + const envStates = new Map() + const shouldCheckImporterCache = new Map() + const config: PluginConfig = { + enabled: true, + root: '', + command: api.context.action === 'dev' ? 'serve' : 'build', + srcDirectory: '', + framework: opts.framework, + effectiveBehavior: 'error', + mockAccess: 'error', + logMode: 'once', + maxTraceDepth: 20, + compiledRules: { + client: { + specifiers: [], + files: [], + excludeFiles: [], + }, + server: { + specifiers: [], + files: [], + excludeFiles: [], + }, + }, + includeMatchers: [], + excludeMatchers: [], + ignoreImporterMatchers: [], + markerSpecifiers: { + serverOnly: new Set(), + clientOnly: new Set(), + }, + envTypeMap: new Map(opts.environments.map((env) => [env.name, env.type])), + onViolation: undefined, + } + + const shared: SharedState = { + root: '', + virtualModules: new Map(), + vmPlugins: {}, + readyVmPlugins: {}, + pendingWrites: new Map(), + } + + function applyUserConfig(): void { + const { startConfig, resolvedStartConfig } = opts.getConfig() + + config.root = resolvedStartConfig.root + config.srcDirectory = resolvedStartConfig.srcDirectory + shared.root = resolvedStartConfig.root + + const userOpts: ImportProtectionOptions | undefined = + startConfig.importProtection + + if (userOpts?.enabled === false) { + config.enabled = false + return + } + + config.enabled = true + + const behavior = userOpts?.behavior + if (typeof behavior === 'string') { + config.effectiveBehavior = behavior + } else { + config.effectiveBehavior = + config.command === 'serve' + ? (behavior?.dev ?? 'mock') + : (behavior?.build ?? 'error') + } + + config.logMode = userOpts?.log ?? 'once' + config.mockAccess = userOpts?.mockAccess ?? 'error' + config.maxTraceDepth = userOpts?.maxTraceDepth ?? 20 + config.onViolation = userOpts?.onViolation + ? (info) => userOpts.onViolation?.(info) + : undefined + + const defaults = getDefaultImportProtectionRules() + const pick = (user: Array | undefined, fallback: Array) => + user ? [...user] : [...fallback] + + const clientSpecifiers = dedupePatterns([ + ...defaults.client.specifiers, + ...(userOpts?.client?.specifiers ?? []), + ]) + + config.compiledRules.client = { + specifiers: compileMatchers(clientSpecifiers), + files: compileMatchers( + pick(userOpts?.client?.files, defaults.client.files), + ), + excludeFiles: compileMatchers( + pick(userOpts?.client?.excludeFiles, defaults.client.excludeFiles), + ), + } + + config.compiledRules.server = { + specifiers: compileMatchers( + dedupePatterns( + pick(userOpts?.server?.specifiers, defaults.server.specifiers), + ), + ), + files: compileMatchers( + pick(userOpts?.server?.files, defaults.server.files), + ), + excludeFiles: compileMatchers( + pick(userOpts?.server?.excludeFiles, defaults.server.excludeFiles), + ), + } + + config.includeMatchers = compileMatchers(userOpts?.include ?? []) + config.excludeMatchers = compileMatchers(userOpts?.exclude ?? []) + config.ignoreImporterMatchers = compileMatchers( + userOpts?.ignoreImporters ?? [], + ) + + const markers = getMarkerSpecifiers() + config.markerSpecifiers = { + serverOnly: new Set(markers.serverOnly), + clientOnly: new Set(markers.clientOnly), + } + } + + function shouldCheckImporter(file: string): boolean { + return shouldCheckImporterWithCache({ + config, + cache: shouldCheckImporterCache, + perf, + file, + }) + } + + api.onBeforeBuild(() => { + const startedAt = perf ? performance.now() : 0 + applyUserConfig() + clearNormalizeFilePathCache() + extensionlessResolver.clear() + shouldCheckImporterCache.clear() + envStates.clear() + if (perf) { + perf.time('onBeforeBuild', startedAt) + } + }) + + api.onBeforeDevCompile(() => { + const startedAt = perf ? performance.now() : 0 + applyUserConfig() + clearNormalizeFilePathCache() + extensionlessResolver.clear() + shouldCheckImporterCache.clear() + + for (const envState of envStates.values()) { + envState.resolveCache.clear() + } + if (perf) { + perf.time('onBeforeDevCompile', startedAt) + } + }) + + api.modifyRspackConfig((rspackConfig, utils) => { + const startedAt = perf ? performance.now() : 0 + applyUserConfig() + + const envName = utils.environment.name + // When import protection is disabled, register nothing, as the Vite plugin + // does, so modules do not pass through the loader. + if ( + !config.enabled || + !opts.environments.some((environment) => environment.name === envName) + ) { + return + } + + const VMP = utils.rspack.experiments.VirtualModulesPlugin + const vmPlugin = new VMP({}) + + shared.vmPlugins[envName] = vmPlugin + shared.readyVmPlugins[envName] = false + + const rules = rspackConfig.module.rules ?? [] + rules.push({ + test: /\.[cm]?[tj]sx?$/, + enforce: 'post', + use: [ + { + loader: importProtectionLoader, + options: { + config, + envName, + envStates, + extensionlessResolver, + perf, + shared, + shouldCheckImporterCache, + }, + }, + ], + }) + rspackConfig.module.rules = rules + + rspackConfig.plugins.push(vmPlugin) + rspackConfig.plugins.push({ + apply(compiler: Rspack.Compiler) { + compiler.hooks.thisCompilation.tap( + 'TanStackStartImportProtectionVirtualModulesReady', + () => { + shared.readyVmPlugins[envName] = true + flushPendingWrites(shared, envName) + }, + ) + }, + }) + if (perf) { + perf.time('modifyRspackConfig', startedAt) + } + }) + + api.processAssets( + { + stage: 'report', + environments: opts.environments.map((environment) => environment.name), + }, + async (context: ProcessAssetsContext) => { + const envName = context.environment.name + const startedAt = perf ? performance.now() : 0 + perf?.count('processAssets.calls') + perf?.count(`processAssets.env.${envName}`) + + try { + if (!config.enabled) { + return + } + + const envType = getImportProtectionEnvType(config, envName) + const envState = getOrCreateEnvState(envStates, envName) + const matchers = getRulesForEnvironment(config, envName) + const allModules = Array.from(context.compilation.modules) + perf?.count('processAssets.modules.total', allModules.length) + + const violationScanner = createCompilationViolationScanner({ + config, + envType, + matchers, + shouldCheckImporter, + }) + forEachEntryModule({ + compilation: context.compilation, + visitModule: violationScanner.visitEntry, + }) + const forEachStartedAt = perf ? performance.now() : 0 + const moduleGraphNodes: Array = [] + forEachModules({ + compilation: context.compilation, + modules: allModules, + visitNode(node) { + moduleGraphNodes.push(node) + violationScanner.visitNode(node) + }, + }) + if (perf) { + perf.time('processAssets.forEachModules', forEachStartedAt) + perf.count('processAssets.modules.collected', moduleGraphNodes.length) + perf.count( + 'processAssets.imports.collected', + moduleGraphNodes.reduce( + (total, node) => total + node.imports.length, + 0, + ), + ) + } + + const candidateStartedAt = perf ? performance.now() : 0 + const candidates = violationScanner.finish() + if (perf) { + perf.time('processAssets.candidates.finish', candidateStartedAt) + perf.count('processAssets.candidates', candidates.length) + } + + if (candidates.length === 0) { + return + } + + const graphStartedAt = perf ? performance.now() : 0 + const { importGraph, edgeIndex } = buildCompilationImportGraph({ + compilation: context.compilation, + nodes: moduleGraphNodes, + }) + if (perf) { + perf.time('processAssets.importGraph.build', graphStartedAt) + perf.count('processAssets.importGraph.edges', edgeIndex.edges.length) + } + + let provider: CompilationTransformResultProvider | undefined + const getProvider = () => { + if (!provider) { + const providerStartedAt = perf ? performance.now() : 0 + provider = buildTransformResultProvider({ + root: config.root, + perf, + inputFileSystem: context.compilation.inputFileSystem, + }) + if (perf) { + perf.time('processAssets.provider.build', providerStartedAt) + } + } + return provider + } + + for (const candidate of candidates) { + let info: ViolationInfo + + if (candidate.type === 'specifier') { + const { payload } = candidate + info = await buildViolationInfo({ + config, + provider: getProvider(), + importGraph, + edgeIndex, + perf, + envName, + envType, + importer: payload.violation.importer, + importerModule: candidate.edge.importer, + source: payload.violation.specifier, + resolved: payload.violation.resolved, + transformedSources: [getModuleResource(candidate.edge.module)], + type: 'specifier', + pattern: payload.violation.patternText, + }) + } else if (candidate.type === 'marker') { + const importer = getModuleResource(candidate.importer) + info = await buildViolationInfo({ + config, + provider: getProvider(), + importGraph, + edgeIndex, + perf, + envName, + envType, + importer, + importerModule: candidate.importer, + source: candidate.source, + type: 'marker', + }) + } else { + const { edge, source } = candidate + const importer = getModuleResource(edge.importer) + const resolved = getModuleResource(edge.module) + info = await buildViolationInfo({ + config, + provider: getProvider(), + importGraph, + edgeIndex, + perf, + envName, + envType, + importer, + importerModule: edge.importer, + source, + resolved, + type: 'file', + pattern: candidate.pattern, + }) + } + + await reportViolation({ + config, + envState, + compilation: context.compilation, + rspack: context.compiler.rspack, + perf, + info, + }) + } + } finally { + if (perf) { + perf.time('processAssets', startedAt) + perf.flush(config.root, envName, 'processAssets') + } + } + }, + ) +} diff --git a/packages/start-plugin-core/src/rsbuild/index.ts b/packages/start-plugin-core/src/rsbuild/index.ts new file mode 100644 index 0000000000..46d1f1b58b --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/index.ts @@ -0,0 +1,9 @@ +export { RSBUILD_ENVIRONMENT_NAMES } from './planning' +export type { TanStackStartRsbuildPluginCoreOptions } from './types' +export type { TanStackStartRsbuildInputConfig } from './schema' +export type { + StartCompilerImportTransform, + StartCompilerTransformCandidate, + StartCompilerTransformContext, +} from '../types' +export { tanStackStartRsbuild } from './plugin' diff --git a/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts b/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts new file mode 100644 index 0000000000..a7dae0c379 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/normalized-client-build.ts @@ -0,0 +1,543 @@ +import { tsrSplit } from '@tanstack/router-plugin' +import { tssHydrate } from '../hydration-constants' +import { getCssAssetSource } from '../start-manifest-plugin/inlineCss' +import { RSBUILD_ENVIRONMENT_NAMES } from './planning' +import type { RsbuildPluginAPI, Rspack } from '@rsbuild/core' +import type { + GetConfigFn, + NormalizedClientBuild, + NormalizedClientChunk, +} from '../types' + +type ProcessAssetsContext = Parameters< + Parameters[1] +>[0] +type RspackCompilation = Rspack.Compilation +type RspackCompilationChunk = Rspack.Chunk +type RspackModule = Rspack.Module + +const backslashRegex = /\\/g + +/** + * Convert an OS native path to the POSIX form used by the generated route tree. + */ +function toPosixPath(filePath: string): string { + return filePath.replace(backslashRegex, '/') +} + +/** + * Extract route file paths from rspack module identifiers. + * + * In rspack, module identifiers contain query params similar to Vite's moduleIds. + * We look for the `tsr-split` query to identify route-split chunks. + */ +function getRouteFilePathsFromModules( + modules: Array, +): Array { + let routeFilePaths: Array | undefined + let seen: Set | undefined + + for (const mod of modules) { + const identifier = mod.identifier() + + // rspack module identifiers include loader prefixes separated by '!'. + // The actual file path (with query string) is after the last '!'. + // Example: "builtin:swc-loader??ruleSet[...]!.../transform.js??...!.../rsc-basic.tsx?tsr-split=component" + const lastBangIndex = identifier.lastIndexOf('!') + const resourcePart = + lastBangIndex >= 0 ? identifier.slice(lastBangIndex + 1) : identifier + + const queryIndex = resourcePart.indexOf('?') + if (queryIndex < 0) continue + + const query = resourcePart.slice(queryIndex + 1) + if (!query.includes(tsrSplit)) continue + if (!new URLSearchParams(query).has(tsrSplit)) continue + + const nameForCondition = mod.nameForCondition() + + // rspack reports module paths using the OS separator, while the generated route + // tree records every route `filePath` with POSIX separators. Normalize before the + // path becomes a manifest key, otherwise no route matches its chunk on Windows and + // every route loses its stylesheets and preloads. + const routeFilePath = toPosixPath( + nameForCondition ?? resourcePart.slice(0, queryIndex), + ) + + if (seen?.has(routeFilePath)) continue + + if (!routeFilePaths || !seen) { + routeFilePaths = [] + seen = new Set() + } + + routeFilePaths.push(routeFilePath) + seen.add(routeFilePath) + } + + return routeFilePaths ?? [] +} + +function getHydrationIdsFromModules( + modules: Array, +): Array { + let hydrationIds: Array | undefined + let seen: Set | undefined + + for (const mod of modules) { + const identifier = mod.identifier() + const lastBangIndex = identifier.lastIndexOf('!') + const resourcePart = + lastBangIndex >= 0 ? identifier.slice(lastBangIndex + 1) : identifier + + const queryIndex = resourcePart.indexOf('?') + if (queryIndex < 0) continue + + const query = resourcePart.slice(queryIndex + 1) + if (!query.includes(tssHydrate)) continue + + const hydrationId = new URLSearchParams(query).get(tssHydrate) + if (!hydrationId || seen?.has(hydrationId)) continue + + if (!hydrationIds || !seen) { + hydrationIds = [] + seen = new Set() + } + + hydrationIds.push(hydrationId) + seen.add(hydrationId) + } + + return hydrationIds ?? [] +} + +/** + * Returns true for Rspack/webpack HMR runtime chunks that should never be + * surfaced to the Start manifest. These files are emitted on every rebuild + * (e.g. `index..hot-update.mjs`) and must not be treated as the entry + * chunk, route preloads, or sibling imports. + */ +function isHotUpdateAsset(file: string): boolean { + return file.includes('.hot-update.') +} + +/** + * True for any JS/MJS asset that should be included in the manifest. + * Excludes HMR runtime patches. + */ +function isManifestJsAsset(file: string): boolean { + if (!file.endsWith('.js') && !file.endsWith('.mjs')) return false + return !isHotUpdateAsset(file) +} + +/** + * Get all JS file names from a chunk. + */ +function getChunkJsFiles(chunk: RspackCompilationChunk): Array { + const jsFiles: Array = [] + for (const file of chunk.files) { + if (isManifestJsAsset(file)) { + jsFiles.push(file) + } + } + return jsFiles +} + +/** + * Get unique CSS file names from both primary and auxiliary chunk assets. + */ +function getChunkCssFiles(chunk: RspackCompilationChunk): Array { + const cssFiles: Array = [] + const seen = new Set() + + for (const file of [...chunk.auxiliaryFiles, ...chunk.files]) { + if (file.endsWith('.css') && !seen.has(file)) { + seen.add(file) + cssFiles.push(file) + } + } + + return cssFiles +} + +/** + * Include inner modules so concatenation does not hide route metadata or + * static dependency edges. + */ +function getModulesIncludingConcatenated( + modules: Array, +): Array { + const allModules = new Set(modules) + for (const module of allModules) { + const concatenatedModules = ( + module as RspackModule & { modules?: Array } + ).modules + if (concatenatedModules) { + for (const concatenatedModule of concatenatedModules) { + allModules.add(concatenatedModule) + } + } + } + + return Array.from(allModules) +} + +/** + * Compute dynamicImports for a chunk by traversing its chunk groups' + * childrenIterable (async/dynamic import edges). + * + * In rspack, a chunk belongs to one or more ChunkGroups. Each ChunkGroup + * has childrenIterable — child ChunkGroups representing dynamic import() + * points. The JS files from those child groups' chunks are the + * dynamicImports (analogous to Rollup's OutputChunk.dynamicImports). + */ +function computeDynamicImports(chunk: RspackCompilationChunk): Array { + const dynamicImportFiles: Array = [] + const seen = new Set() + + for (const group of chunk.groupsIterable) { + for (const childGroup of group.childrenIterable) { + for (const childChunk of childGroup.chunks) { + for (const file of childChunk.files) { + if (isManifestJsAsset(file) && !seen.has(file)) { + seen.add(file) + dynamicImportFiles.push(file) + } + } + } + } + } + + return dynamicImportFiles +} + +/** + * Compute the emitted chunks reached by active static module dependencies. + * Dependencies nested in async blocks are deliberately excluded: those are + * represented by chunk-group children in `dynamicImports` instead. + */ +function computeStaticDependencyChunks( + compilation: RspackCompilation, + chunk: RspackCompilationChunk, + chunksOfModule: (module: RspackModule) => Array, +): Array { + const importedChunks: Array = [] + const seen = new Set([chunk]) + const modules = getModulesIncludingConcatenated( + compilation.chunkGraph.getChunkModules(chunk), + ) + const localModules = new Set(modules) + const runtime = Array.from(chunk.runtime) + // A shared chunk can belong to several route groups. Group membership + // limits where dependencies can be loaded from; it does not establish + // an import from the shared chunk back to every route in those groups. + // A chunk counts as available only when every group of this chunk (or + // one of its ancestors) has it: a module duplicated into each route's + // chunk is satisfied per group, by that group's own chunk, so neither + // route's chunk is a dependency of the shared chunk (#8780). + let availableChunks: Set | undefined + for (const group of chunk.groupsIterable) { + const groupChunks = new Set() + const ancestors = new Set([group]) + for (const ancestor of ancestors) { + for (const availableChunk of ancestor.chunks) { + groupChunks.add(availableChunk) + } + for (const parent of ancestor.getParents()) { + ancestors.add(parent) + } + } + if (availableChunks === undefined) { + availableChunks = groupChunks + } else { + for (const availableChunk of availableChunks) { + if (!groupChunks.has(availableChunk)) { + availableChunks.delete(availableChunk) + } + } + } + } + availableChunks ??= new Set() + + // Every connection to a module adds the same chunks, so a module counts + // once, from its first active connection (an inactive one adds nothing and + // leaves the module to a later active one). + const counted = new Set() + for (const module of modules) { + for (const dependency of module.dependencies) { + const connection = compilation.moduleGraph.getConnection(dependency) + const importedModule = connection?.module + if ( + !connection || + !importedModule || + localModules.has(importedModule) || + counted.has(importedModule) + ) { + continue + } + if (connection.getActiveState(runtime) === false) { + continue + } + counted.add(importedModule) + + for (const importedChunk of chunksOfModule(importedModule)) { + if (availableChunks.has(importedChunk) && !seen.has(importedChunk)) { + seen.add(importedChunk) + importedChunks.push(importedChunk) + } + } + } + } + + return importedChunks +} + +type GetStaticDependencyChunks = ( + chunk: RspackCompilationChunk, +) => Array + +/** + * Memoize static dependency resolution per chunk. Every chunk is resolved once + * for its own `imports`, and CSS-only chunks are resolved again from each + * importer that reaches them. A module's chunks are read once, for every chunk + * that imports it. Both memos live as long as the resolver, which is created + * per normalized compilation. + */ +function createStaticDependencyChunkResolver( + compilation: RspackCompilation, +): GetStaticDependencyChunks { + const cache = new Map>() + const moduleChunks = new Map>() + const chunksOfModule = (module: RspackModule) => { + let chunks = moduleChunks.get(module) + if (!chunks) { + chunks = Array.from( + compilation.chunkGraph.getModuleChunksIterable(module), + ) + moduleChunks.set(module, chunks) + } + return chunks + } + + return (chunk) => { + let importedChunks = cache.get(chunk) + if (!importedChunks) { + importedChunks = computeStaticDependencyChunks( + compilation, + chunk, + chunksOfModule, + ) + cache.set(chunk, importedChunks) + } + return importedChunks + } +} + +/** + * Collect CSS from dependency chunks that have no JavaScript asset of their + * own, preserving dependency-before-importer order across nested CSS chunks. + */ +function computeCssOnlyDependencyFiles( + getStaticDependencyChunks: GetStaticDependencyChunks, + chunks: Array, +): Array { + const cssFiles: Array = [] + const seenChunks = new Set() + const seenFiles = new Set() + + const visit = (chunk: RspackCompilationChunk) => { + if (seenChunks.has(chunk) || getChunkJsFiles(chunk).length > 0) { + return + } + seenChunks.add(chunk) + + for (const importedChunk of getStaticDependencyChunks(chunk)) { + visit(importedChunk) + } + + for (const cssFile of getChunkCssFiles(chunk)) { + if (!seenFiles.has(cssFile)) { + seenFiles.add(cssFile) + cssFiles.push(cssFile) + } + } + } + + for (const chunk of chunks) { + visit(chunk) + } + + return cssFiles +} + +/** + * Normalize an rspack compilation into a NormalizedClientBuild. + * + * Iterates ALL chunks in the compilation (initial + async), not just + * entrypoint chunks, to ensure route-split async chunks are included. + */ +export function normalizeRspackClientBuild( + compilation: RspackCompilation, + inlineCssEnabled = false, +): NormalizedClientBuild { + const chunksByFileName = new Map() + let cssContentByFileName: Map | undefined + let entryChunkFileName: string | undefined + + // Collect all initial JS file names from the main entry for computing + // the entry chunk's `imports` (vendor/shared sibling chunks). + const entrypoint = compilation.entrypoints.get('index') + const initialJsFileNames: Array = [] + const entryChunkSet = new Set() + if (entrypoint) { + for (const chunk of entrypoint.chunks) { + entryChunkSet.add(chunk) + for (const file of chunk.files) { + if (isManifestJsAsset(file)) { + initialJsFileNames.push(file) + } + } + } + } + + const getStaticDependencyChunks = + createStaticDependencyChunkResolver(compilation) + + // Iterate ALL chunks (initial + async) to capture route-split chunks + for (const chunk of compilation.chunks) { + const modules = getModulesIncludingConcatenated( + compilation.chunkGraph.getChunkModules(chunk), + ) + const routeFilePaths = getRouteFilePathsFromModules(modules) + const hydrationIds = getHydrationIdsFromModules(modules) + const cssFiles = getChunkCssFiles(chunk) + + // The entry chunk is the one named 'index' in the 'index' entrypoint + const isEntryChunk = chunk.name === 'index' && entryChunkSet.has(chunk) + + const jsFiles = getChunkJsFiles(chunk) + if (jsFiles.length === 0) continue + + // Compute dynamicImports from chunk group children + const dynamicImports = computeDynamicImports(chunk) + const staticDependencyChunks = getStaticDependencyChunks(chunk) + const dependencyCssFiles = computeCssOnlyDependencyFiles( + getStaticDependencyChunks, + staticDependencyChunks, + ).filter((cssFile) => !cssFiles.includes(cssFile)) + if (dependencyCssFiles.length > 0) { + cssFiles.unshift(...dependencyCssFiles) + } + + for (const file of jsFiles) { + // For the entry chunk, `imports` contains all sibling initial chunks + // (vendor/shared). For other chunks, it contains the emitted chunks + // reached through active static module dependencies. + const imports = isEntryChunk + ? initialJsFileNames.filter((f) => f !== file) + : staticDependencyChunks.flatMap(getChunkJsFiles) + + const normalizedChunk: NormalizedClientChunk = { + fileName: file, + isEntry: isEntryChunk, + imports, + dynamicImports, + css: [], + routeFilePaths, + hydrationIds, + } + + chunksByFileName.set(file, normalizedChunk) + + if (isEntryChunk && !entryChunkFileName) { + entryChunkFileName = file + } + } + + for (const cssFile of cssFiles) { + for (const file of jsFiles) { + const existing = chunksByFileName.get(file) + if (existing && !existing.css.includes(cssFile)) { + existing.css.push(cssFile) + } + } + } + } + + if (!entryChunkFileName) { + throw new Error('No entry file found in rspack client build') + } + + if (inlineCssEnabled) { + cssContentByFileName = new Map() + for (const asset of compilation.getAssets()) { + if (!asset.name.endsWith('.css')) { + continue + } + + const css = getCssAssetSource(asset.source.source()) + if (css !== undefined) { + cssContentByFileName.set(asset.name, css) + } + } + } + + // In RSC mode, CSS from server components is associated with the 'rsc' + // client entry chunk (not the main 'index' entry). The manifest builder + // merges the entry chunk's CSS into __root__, so by appending RSC CSS + // to the entry chunk, those stylesheets get loaded on all pages. + // CSS may appear in either `files` or `auxiliaryFiles` depending on + // rspack's CSS extraction strategy. + const rscEntrypoint = compilation.entrypoints.get('rsc') + + if (rscEntrypoint && entryChunkFileName) { + const mainEntryChunk = chunksByFileName.get(entryChunkFileName) + if (mainEntryChunk) { + for (const rscChunk of rscEntrypoint.chunks) { + const allFiles = [...rscChunk.files, ...rscChunk.auxiliaryFiles] + for (const file of allFiles) { + if (file.endsWith('.css') && !mainEntryChunk.css.includes(file)) { + mainEntryChunk.css.push(file) + } + } + } + } + } + + return { + entryChunkFileName, + chunksByFileName, + cssContentByFileName, + } +} + +/** + * Registers a processAssets hook to capture the client build stats + * after compilation. Returns a getter for the captured build. + */ +export function registerClientBuildCapture( + api: RsbuildPluginAPI, + getConfig: GetConfigFn, +): { + getClientBuild: () => NormalizedClientBuild | undefined +} { + let clientBuild: NormalizedClientBuild | undefined + + api.processAssets( + { + stage: 'report', + environments: [RSBUILD_ENVIRONMENT_NAMES.client], + }, + (context: ProcessAssetsContext) => { + clientBuild = normalizeRspackClientBuild( + context.compilation, + api.context.action !== 'dev' && + getConfig().startConfig.server.build.inlineCss.enabled, + ) + }, + ) + + return { + getClientBuild: () => clientBuild, + } +} diff --git a/packages/start-plugin-core/src/rsbuild/planning.ts b/packages/start-plugin-core/src/rsbuild/planning.ts new file mode 100644 index 0000000000..5461213194 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/planning.ts @@ -0,0 +1,269 @@ +import { createRequire } from 'node:module' +import { join } from 'pathe' +import { mergeRsbuildConfig } from '@rsbuild/core' +import { ENTRY_POINTS } from '../constants' +import type { EnvironmentConfig } from '@rsbuild/core' +import type { ResolvedStartEntryPlan } from '../planning' +import type { RsbuildEnvironmentOverrides } from './types' +import type { ScriptFormat } from '@tanstack/router-core' + +const require = createRequire(import.meta.url) + +export const RSBUILD_ENVIRONMENT_NAMES = { + client: 'client', + server: 'ssr', +} as const + +/** + * Rspack layer names for the rsbuild RSC layered model. + * These match the canonical names from `rspack.experiments.rsc.Layers`. + */ +export const RSBUILD_RSC_LAYERS = { + /** React Server Components layer — uses `react-server` resolve condition */ + rsc: 'react-server-components', + /** Server-Side Rendering layer — standard Node resolve */ + ssr: 'server-side-rendering', +} as const + +export const RSBUILD_CLIENT_ASSETS_DIR = 'assets' + +export type RsbuildEnvironmentName = + (typeof RSBUILD_ENVIRONMENT_NAMES)[keyof typeof RSBUILD_ENVIRONMENT_NAMES] + +type RsbuildDistPath = NonNullable['distPath'] +type RsbuildDistPathObject = Exclude + +function createPublicAssetDistPath(root: string): RsbuildDistPathObject { + return { + root, + css: `${RSBUILD_CLIENT_ASSETS_DIR}/css`, + cssAsync: `${RSBUILD_CLIENT_ASSETS_DIR}/css/async`, + svg: `${RSBUILD_CLIENT_ASSETS_DIR}/svg`, + font: `${RSBUILD_CLIENT_ASSETS_DIR}/font`, + wasm: `${RSBUILD_CLIENT_ASSETS_DIR}/wasm`, + image: `${RSBUILD_CLIENT_ASSETS_DIR}/image`, + media: `${RSBUILD_CLIENT_ASSETS_DIR}/media`, + assets: `${RSBUILD_CLIENT_ASSETS_DIR}/assets`, + } +} + +function createClientAssetDistPath(root: string): RsbuildDistPathObject { + return { + ...createPublicAssetDistPath(root), + js: `${RSBUILD_CLIENT_ASSETS_DIR}/js`, + jsAsync: `${RSBUILD_CLIENT_ASSETS_DIR}/js/async`, + } +} + +export interface RsbuildResolvedEntryAliases { + client: string + server: string + start: string + router: string + alias: Record<(typeof ENTRY_POINTS)[keyof typeof ENTRY_POINTS], string> +} + +export function createRsbuildResolvedEntryAliases(opts: { + entryPaths: ResolvedStartEntryPlan['entryPaths'] +}): RsbuildResolvedEntryAliases { + const client = normalizeEntryPath(opts.entryPaths.client) + const server = normalizeEntryPath(opts.entryPaths.server) + const start = normalizeEntryPath(opts.entryPaths.start) + const router = normalizeEntryPath(opts.entryPaths.router) + + return { + client, + server, + start, + router, + alias: { + [ENTRY_POINTS.client]: client, + [ENTRY_POINTS.server]: server, + [ENTRY_POINTS.start]: start, + [ENTRY_POINTS.router]: router, + }, + } +} + +export interface RsbuildEnvironmentPlanResult { + environments: Record + alias: Record +} + +export function createRsbuildEnvironmentPlan(opts: { + root: string + entryAliases: RsbuildResolvedEntryAliases + clientOutputDirectory: string + serverOutputDirectory: string + publicBase: string + serverFnProviderEnv: string + environmentOverrides?: RsbuildEnvironmentOverrides + scriptFormat?: ScriptFormat + rsc?: boolean | undefined + dev?: boolean | undefined +}): RsbuildEnvironmentPlanResult { + const alias = { + ...opts.entryAliases.alias, + ...(opts.rsc + ? { + 'react-server-dom-rspack/server$': resolveFromRoot( + 'react-server-dom-rspack/server.node', + opts.root, + ), + } + : {}), + } + const environmentOverrides = opts.environmentOverrides ?? {} + const scriptFormat = opts.scriptFormat ?? 'module' + const clientOutputModule = scriptFormat === 'module' + const userClientOutputModule = + environmentOverrides.client?.output?.module ?? + environmentOverrides.all?.output?.module + + if ( + typeof userClientOutputModule === 'boolean' && + userClientOutputModule !== clientOutputModule + ) { + throw new Error( + 'TanStack Start rsbuild.client.output controls environments.client.output.module. Remove environments.client.output.module or set rsbuild.client.output to match it.', + ) + } + + return { + environments: { + [RSBUILD_ENVIRONMENT_NAMES.client]: mergeRsbuildConfig( + { + source: { + entry: { + index: { + import: opts.entryAliases.client, + html: false, + }, + }, + }, + output: { + target: 'web', + module: clientOutputModule, + distPath: createClientAssetDistPath(opts.clientOutputDirectory), + assetPrefix: opts.publicBase, + }, + resolve: { + alias, + }, + // Only split async chunks (route code-splitting). Keep all initial + // vendor/shared code inlined in the entry chunk so the SSR HTML only + // needs the single client entry bootstrap. + splitChunks: { + preset: 'none', + chunks: 'async', + }, + }, + environmentOverrides.all, + environmentOverrides.client, + ), + [RSBUILD_ENVIRONMENT_NAMES.server]: mergeRsbuildConfig( + { + source: { + entry: { + index: { + import: opts.entryAliases.server, + html: false, + ...(opts.rsc ? { layer: RSBUILD_RSC_LAYERS.ssr } : {}), + }, + }, + }, + output: { + target: 'node', + // Rsbuild's dev `loadBundle()` path evaluates ESM via vm.SourceTextModule, + // which requires `--experimental-vm-modules`. Emit CJS for the dev + // server bundle so SSR works without extra Node flags. + ...(opts.dev ? { module: false } : {}), + distPath: createPublicAssetDistPath(opts.serverOutputDirectory), + assetPrefix: opts.publicBase, + }, + resolve: { + alias, + }, + ...(opts.rsc + ? { + splitChunks: { + preset: 'single-vendor', + }, + } + : {}), + }, + environmentOverrides.all, + environmentOverrides.server, + ), + // When provider is a separate environment (not layered RSC), + // create a third environment. With the layered RSC setup this branch + // is not taken because provider maps to the same `ssr` environment. + ...(opts.serverFnProviderEnv !== RSBUILD_ENVIRONMENT_NAMES.server && + !opts.rsc + ? { + [opts.serverFnProviderEnv]: mergeRsbuildConfig( + { + source: { + entry: { + index: { + import: opts.entryAliases.server, + html: false, + }, + }, + }, + output: { + target: 'node', + ...(opts.dev ? { module: false } : {}), + distPath: createPublicAssetDistPath( + `${opts.serverOutputDirectory}/${opts.serverFnProviderEnv}`, + ), + assetPrefix: opts.publicBase, + }, + resolve: { + alias, + }, + }, + environmentOverrides.all, + environmentOverrides.provider, + ), + } + : {}), + }, + alias, + } +} + +export function resolveRsbuildOutputDirectory(opts: { + distPath: RsbuildDistPath | undefined + rootDistPath: RsbuildDistPath | undefined + fallback: string + subdirectory: string +}): string { + if (typeof opts.distPath === 'string') { + return opts.distPath + } + + if (typeof opts.distPath?.root === 'string') { + return opts.distPath.root + } + + if (typeof opts.rootDistPath === 'string') { + return join(opts.rootDistPath, opts.subdirectory) + } + + if (typeof opts.rootDistPath?.root === 'string') { + return join(opts.rootDistPath.root, opts.subdirectory) + } + + return opts.fallback +} + +function normalizeEntryPath(path: string) { + return path.includes('\\') ? path.replaceAll('\\', '/') : path +} + +function resolveFromRoot(specifier: string, root: string): string { + return require.resolve(specifier, { + paths: [root], + }) +} diff --git a/packages/start-plugin-core/src/rsbuild/plugin.ts b/packages/start-plugin-core/src/rsbuild/plugin.ts new file mode 100644 index 0000000000..c4660728b4 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/plugin.ts @@ -0,0 +1,890 @@ +import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs' +import { dirname, isAbsolute, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { joinURL } from 'ufo' +import { + applyResolvedBaseAndOutput, + applyResolvedRouterBasepath, + createStartConfigContext, +} from '../config-context' +import { normalizePath } from '../utils' +import { createServerFnBasePath, normalizePublicBase } from '../planning' +import { addWorkspaceWatchIgnored } from './watch-ignored' +import { parseStartConfig, rsbuildClientOutputSchema } from './schema' +import { + RSBUILD_CLIENT_ASSETS_DIR, + RSBUILD_ENVIRONMENT_NAMES, + RSBUILD_RSC_LAYERS, + createRsbuildEnvironmentPlan, + createRsbuildResolvedEntryAliases, + resolveRsbuildOutputDirectory, +} from './planning' +import { registerStartCompilerTransforms } from './start-compiler-host' +import { registerImportProtection } from './import-protection' +import { + START_MANIFEST_PLACEHOLDER, + registerVirtualModules, +} from './virtual-modules' +import { createServerSetup } from './server-middleware' +import { registerClientBuildCapture } from './normalized-client-build' +import { tapServerFnResolverRebuild } from './server-fn-resolver-rebuild' +import { registerRouterPlugins } from './start-router-plugin' +import { postBuildWithRsbuild } from './post-build' +import { enableSwcReactServerComponents } from './swc-rsc' +import type { ServerFn } from '../start-compiler/types' +import type { TanStackStartRsbuildPluginCoreOptions } from './types' +import type { + ModifyRspackConfigFn, + RsbuildDevServer, + RsbuildPlugin, + RsbuildPluginAPI, + Rspack, + rspack as rspackNamespaceType, +} from '@rsbuild/core' +import type { TanStackStartRsbuildInputConfig } from './schema' +import type { ScriptFormat } from '@tanstack/router-core' + +// Detect whether this plugin source is running from inside the TanStack +// Router monorepo (packages/start-plugin-core/src/rsbuild/plugin.ts). When +// installed from npm in a user app, the path structure is different and +// this evaluates to false. Used to gate dev-only workarounds that only +// matter when workspace package dists are symlinked into node_modules. +const currentDir = dirname(fileURLToPath(import.meta.url)) +const isInsideRouterMonoRepo = (() => { + // src layout: /packages/start-plugin-core/src/rsbuild → 4 levels up + // dist layout (CJS/ESM): /packages/start-plugin-core/dist//rsbuild + // → also 4 levels up + const candidate = resolve(currentDir, '../../../../') + return candidate.endsWith('/packages') || candidate.endsWith('\\packages') +})() + +type RspackNamespace = typeof rspackNamespaceType +type RscPluginPair = ReturnType< + NonNullable['createPlugins'] +> +type RspackConfig = Parameters[0] +type RspackCompiler = Rspack.Compiler +type RspackCompilationExtended = Rspack.Compilation +type RspackAsset = ReturnType[number] + +export function tanStackStartRsbuild( + corePluginOpts: TanStackStartRsbuildPluginCoreOptions, + startPluginOpts: TanStackStartRsbuildInputConfig = {}, +): RsbuildPlugin { + const rscOpts = corePluginOpts.rsc + const rscEnabled = Boolean(rscOpts) + + const configContext = createStartConfigContext({ + corePluginOpts, + startPluginOpts, + parseConfig: parseStartConfig, + }) + const { getConfig, resolvedStartConfig } = configContext + const serverFnProviderEnv = corePluginOpts.providerEnvironmentName + const ssrIsProvider = corePluginOpts.ssrIsProvider + const scriptFormat = rsbuildClientOutputSchema.parse( + startPluginOpts.rsbuild?.client?.output ?? 'module', + ) satisfies ScriptFormat + + // RSC plugin instances — created lazily when rspack namespace is available + let rscPlugins: RscPluginPair | undefined + + // Reference to the dev server for RSC HMR socket writes + let devServerRef: Pick | null = null + const serverFnsById: Record = {} + let updateServerFnResolver: (() => void) | undefined + + return { + name: 'tanstack-start-rsbuild', + setup(api: RsbuildPluginAPI) { + const startCompilerEnvironments = [ + { name: RSBUILD_ENVIRONMENT_NAMES.client, type: 'client' as const }, + { name: RSBUILD_ENVIRONMENT_NAMES.server, type: 'server' as const }, + ...(serverFnProviderEnv !== RSBUILD_ENVIRONMENT_NAMES.server && + !rscEnabled + ? [{ name: serverFnProviderEnv, type: 'server' as const }] + : []), + ] + const startCompilerServerEnvironmentNames = startCompilerEnvironments + .filter((env) => env.type === 'server') + .map((env) => env.name) + + // --------------------------------------------------------------- + // 1. modifyRsbuildConfig — resolve config, set up environments + // --------------------------------------------------------------- + api.modifyRsbuildConfig((rsbuildConfig, { mergeRsbuildConfig }) => { + // Rsbuild passes `root` on as written; its resolved root (against its + // `cwd`) is `rootPath`. Canonical (no trailing separator), as the + // virtual modules' paths must match Rspack's module paths. + const root = resolve( + typeof rsbuildConfig.root === 'string' && + isAbsolute(rsbuildConfig.root) + ? rsbuildConfig.root + : api.context.rootPath, + ) + + const serverBase = rsbuildConfig.server?.base + const assetPrefix = rsbuildConfig.output?.assetPrefix + const publicBase = normalizePublicBase( + typeof serverBase === 'string' + ? serverBase + : typeof assetPrefix === 'string' && assetPrefix !== 'auto' + ? assetPrefix + : undefined, + ) + const rootDistPath = rsbuildConfig.output?.distPath + const clientDistPath = + rsbuildConfig.environments?.[RSBUILD_ENVIRONMENT_NAMES.client]?.output + ?.distPath + const serverDistPath = + rsbuildConfig.environments?.[RSBUILD_ENVIRONMENT_NAMES.server]?.output + ?.distPath + + applyResolvedBaseAndOutput({ + resolvedStartConfig, + root, + publicBase, + clientOutputDirectory: resolveRsbuildOutputDirectory({ + distPath: clientDistPath, + rootDistPath, + fallback: 'dist/client', + subdirectory: 'client', + }), + serverOutputDirectory: resolveRsbuildOutputDirectory({ + distPath: serverDistPath, + rootDistPath, + fallback: 'dist/server', + subdirectory: 'server', + }), + }) + + const { startConfig } = getConfig() + const routerBasepath = applyResolvedRouterBasepath({ + resolvedStartConfig, + startConfig, + }) + + const resolvedEntryPlan = configContext.resolveEntries() + const isDev = api.context.action === 'dev' + const isPreview = api.context.action === 'preview' + + const entryAliases = createRsbuildResolvedEntryAliases({ + entryPaths: resolvedEntryPlan.entryPaths, + }) + + const environmentPlan = createRsbuildEnvironmentPlan({ + root, + entryAliases, + clientOutputDirectory: resolvedStartConfig.outputDirectories.client, + serverOutputDirectory: resolvedStartConfig.outputDirectories.server, + publicBase: resolvedStartConfig.basePaths.publicBase, + serverFnProviderEnv, + environmentOverrides: corePluginOpts.rsbuild?.environments, + scriptFormat, + rsc: rscOpts, + dev: isDev, + }) + const serverFnBase = createServerFnBasePath({ + routerBasepath, + serverFnBase: startConfig.serverFns.base, + }) + const inlineCssEnabled = + !isDev && startConfig.server.build.inlineCss.enabled + + return mergeRsbuildConfig(rsbuildConfig, { + source: { + ...(rscEnabled + ? { + include: [ + // RSC needs SWC to inspect package code in node_modules so directives such as "use client" can be discovered. + // This follows Rsbuild's documented broad include form for compiling node_modules, with core-js excluded: + // https://rsbuild.rs/config/source/include#compile-node_modules + // + // TODO: Once the Rspack rule matching needed here is ready, narrow this to React-aware packages, for example via + // descriptionData: { "peerDependencies.react": /./ }, so unrelated dependencies are not sent through swc-loader. + { + not: /[\\/]core-js[\\/]/, + }, + ], + } + : {}), + define: { + 'process.env.TSS_SERVER_FN_BASE': JSON.stringify(serverFnBase), + 'import.meta.env.TSS_SERVER_FN_BASE': + JSON.stringify(serverFnBase), + 'process.env.TSS_ROUTER_BASEPATH': JSON.stringify(routerBasepath), + 'import.meta.env.TSS_ROUTER_BASEPATH': + JSON.stringify(routerBasepath), + // In dev, SPA mode answers the shell (as Vite's dev server); + // a build leaves it to the prerendered shell (#8543) + ...(isDev + ? { + 'process.env.TSS_SHELL': JSON.stringify( + startConfig.spa?.enabled ? 'true' : 'false', + ), + 'import.meta.env.TSS_SHELL': JSON.stringify( + startConfig.spa?.enabled ? 'true' : 'false', + ), + } + : {}), + 'process.env.TSS_DEV_SERVER': JSON.stringify( + isDev ? 'true' : 'false', + ), + 'import.meta.env.TSS_DEV_SERVER': JSON.stringify( + isDev ? 'true' : 'false', + ), + // Rsbuild dev already injects emitted CSS asset hrefs, so keep + // Start's synthetic `/@tanstack-start/styles.css` path disabled. + 'process.env.TSS_DEV_SSR_STYLES_ENABLED': JSON.stringify('false'), + 'import.meta.env.TSS_DEV_SSR_STYLES_ENABLED': + JSON.stringify('false'), + 'process.env.TSS_DEV_SSR_STYLES_BASEPATH': JSON.stringify( + resolvedStartConfig.basePaths.publicBase, + ), + 'import.meta.env.TSS_DEV_SSR_STYLES_BASEPATH': JSON.stringify( + resolvedStartConfig.basePaths.publicBase, + ), + 'process.env.TSS_INLINE_CSS_ENABLED': JSON.stringify( + inlineCssEnabled ? 'true' : 'false', + ), + 'import.meta.env.TSS_INLINE_CSS_ENABLED': JSON.stringify( + inlineCssEnabled ? 'true' : 'false', + ), + 'process.env.TSS_DISABLE_CSRF_MIDDLEWARE_WARNING': JSON.stringify( + startConfig.serverFns.disableCsrfMiddlewareWarning + ? 'true' + : 'false', + ), + 'import.meta.env.TSS_DISABLE_CSRF_MIDDLEWARE_WARNING': + JSON.stringify( + startConfig.serverFns.disableCsrfMiddlewareWarning + ? 'true' + : 'false', + ), + }, + }, + server: { + ...(rsbuildConfig.server?.printUrls === undefined || + rsbuildConfig.server.printUrls === true + ? { printUrls: ({ urls }: { urls: Array }) => urls } + : {}), + // Off unless the app turns it on (#8544): compressed SSR streams + // reach the browser only when they end (the SSR middleware's + // srvx response does not flush the compression middleware), and + // @rsbuild/core < 2.0.5 corrupted the SSR response headers. + // `rsbuildConfig` already holds Rsbuild's default (`true`), so + // read the app's own config. + ...(api.getRsbuildConfig('original').server?.compress === undefined + ? { compress: false } + : {}), + // SSR apps render every route on the server — disable HTML + // fallback so rsbuild doesn't intercept /_serverFn/ URLs. + htmlFallback: false, + // server.setup returned callback runs after built-in middleware + // but BEFORE fallback middleware — the ideal slot for SSR. + // Preview always installs the middleware since it is the only SSR + // handler; dev can opt out when a custom server hosts SSR. + ...(isPreview || + (isDev && + startPluginOpts.rsbuild?.installDevServerMiddleware !== false) + ? { + setup: createServerSetup({ + serverFnBasePath: serverFnBase, + serverOutputDirectory: + resolvedStartConfig.outputDirectories.server, + publicBase: resolvedStartConfig.basePaths.publicBase, + }), + } + : {}), + }, + ...(isDev + ? { + dev: { + lazyCompilation: false, + ...(rscEnabled ? { liveReload: false } : {}), + }, + } + : {}), + environments: environmentPlan.environments, + resolve: { + alias: environmentPlan.alias, + }, + }) + }) + + // --------------------------------------------------------------- + // 2. StartCompiler transforms — server fns, isomorphic fns, etc. + // --------------------------------------------------------------- + registerStartCompilerTransforms(api, { + framework: corePluginOpts.framework, + // modifyRsbuildConfig copies rsbuildConfig.root into resolvedStartConfig.root, + // so defer this read until transform time instead of falling back to + // process.cwd() during plugin setup. + root: () => resolvedStartConfig.root || process.cwd(), + environments: startCompilerEnvironments, + providerEnvName: serverFnProviderEnv, + generateFunctionId: startPluginOpts.serverFns?.generateFunctionId, + compilerTransforms: corePluginOpts.compilerTransforms, + serverFnProviderModuleDirectives: + corePluginOpts.serverFnProviderModuleDirectives, + serverFnsById, + onServerFnsByIdChange: () => { + updateServerFnResolver?.() + }, + }) + + registerImportProtection(api, { + getConfig, + framework: corePluginOpts.framework, + environments: startCompilerEnvironments, + }) + + // --------------------------------------------------------------- + // 3. Virtual modules — manifest, server fn resolver, adapters, + // RSC runtime, RSC HMR + // --------------------------------------------------------------- + const virtualModuleState = registerVirtualModules(api, { + getRoot: () => resolvedStartConfig.root, + getConfig, + serverFnsById, + providerEnvName: serverFnProviderEnv, + ssrIsProvider, + serializationAdapters: corePluginOpts.serializationAdapters, + getDevClientEntryUrl: (publicBase: string) => + joinURL(publicBase, RSBUILD_CLIENT_ASSETS_DIR, 'js/index.js'), + rscEnabled, + scriptFormat, + }) + updateServerFnResolver = virtualModuleState.updateServerFnResolver + + if (!rscEnabled) { + api.modifyRspackConfig((config, utils) => { + if ( + !startCompilerServerEnvironmentNames.includes( + utils.environment.name, + ) + ) { + return + } + + const environmentName = utils.environment.name + config.plugins.push({ + apply(compiler: RspackCompiler) { + tapServerFnResolverRebuild(compiler, { + name: 'TanStackStartServerFnResolverRebuild', + updateResolver: () => { + virtualModuleState.updateServerFnResolver() + }, + getResolverWriteCount: () => + virtualModuleState.getServerFnResolverWriteCount( + environmentName, + ), + rebuildResolver: (compilation) => + rebuildModulesContaining( + compilation, + virtualModuleState.serverFnResolverPath, + ), + }) + }, + }) + }) + } + + // --------------------------------------------------------------- + // 4. Client build stats capture via processAssets + // --------------------------------------------------------------- + const { getClientBuild } = registerClientBuildCapture(api, getConfig) + + // --------------------------------------------------------------- + // 4b. Server manifest module generation (build only) + // For ordinary multi-environment builds, Rsbuild can compile the + // server environment after the client environment finishes. Generate + // the final manifest as module source in that phase instead of + // patching emitted server assets afterwards. + // --------------------------------------------------------------- + if (api.context.action !== 'dev') { + // (read when a module is transformed: the virtual paths need the resolved root) + const matchesManifestPath = (id: string) => + normalizePath(id) === normalizePath(virtualModuleState.manifestPath) + + api.transform( + { + test: (id: string) => matchesManifestPath(id), + environments: [RSBUILD_ENVIRONMENT_NAMES.server], + }, + ({ code }) => { + const clientBuild = getClientBuild() + + if (clientBuild) { + return virtualModuleState.generateManifestContent(clientBuild) + } + + if (!rscEnabled) { + throw new Error( + 'TanStack Start could not generate the rsbuild server manifest before the client build completed', + ) + } + + // RSC builds cannot express the required client -> server ordering + // through MultiCompiler dependencies, so keep the placeholder for + // the RSC-only asset-patching fallback below. + return code + }, + ) + } + + // --------------------------------------------------------------- + // 5. Router plugin wiring (generator + code splitter) + // --------------------------------------------------------------- + registerRouterPlugins(api, { + getConfig, + corePluginOpts, + startPluginOpts, + }) + + // --------------------------------------------------------------- + // 6. Dev SSR middleware — registered via server.setup in + // modifyRsbuildConfig above (returned callback runs after + // built-ins but before fallback middleware) + // --------------------------------------------------------------- + + // --------------------------------------------------------------- + // 6b. Dev watcher: ignore workspace package `dist/**` directories. + // + // In a real user app, `@tanstack/react-router` and friends live + // inside `node_modules/` and are ignored by Rspack's default + // watcher. In this monorepo, pnpm symlinks them to + // `packages/*/dist` (realpath outside node_modules), so the + // watcher follows them and treats their dist files as live + // sources. If anything rewrites those files during dev, Rspack + // sees transient half-written modules and fails to resolve + // relative imports between them. + // + // Only apply this in monorepo development. In user apps this + // is a no-op — their `node_modules/@tanstack/*/dist/**` is + // already ignored by Rspack's default watchOptions. + // --------------------------------------------------------------- + if (isInsideRouterMonoRepo && api.context.action === 'dev') { + api.modifyRspackConfig((config) => { + const workspaceDistRealpaths = resolveWorkspacePackageDistRealpaths() + if (workspaceDistRealpaths.length === 0) return + + config.watchOptions = { + ...(config.watchOptions ?? {}), + ignored: addWorkspaceWatchIgnored( + config.watchOptions?.ignored, + workspaceDistRealpaths, + ), + } + }) + } + + // --------------------------------------------------------------- + // 7. RSC: rspack layer rules + native RSC plugins + // When RSC is enabled, we add: + // - issuerLayer rule for react-server condition propagation + // - SWC reactServerComponents: true + // - rspack ServerPlugin (server env) / ClientPlugin (client env) + // The Coordinator inside createPlugins() handles compilation + // ordering (server→client→server-actions) automatically. + // --------------------------------------------------------------- + if (rscEnabled) { + api.modifyRspackConfig((config, utils) => { + const envName = utils.environment.name + const isServerEnv = envName === RSBUILD_ENVIRONMENT_NAMES.server + const isClientEnv = envName === RSBUILD_ENVIRONMENT_NAMES.client + + // Create RSC plugin pair lazily (once per build) + if (!rscPlugins) { + rscPlugins = utils.rspack.experiments.rsc.createPlugins() + } + + if (isServerEnv) { + // --- issuerLayer rule: modules imported from RSC layer + // get react-server resolve condition --- + const moduleRules = (config.module.rules ??= []) + const root = resolvedStartConfig.root || process.cwd() + + // Split server-fn provider modules are the actual RSC execution + // boundary in Start's layered model. They must compile in the + // RSC layer so React and react-server-dom-rspack resolve their + // react-server exports without forcing the whole SSR graph into + // react-server conditions. + moduleRules.push({ + resourceQuery: /(?:^|[?&])tss-serverfn-split(?:&|$)/, + layer: RSBUILD_RSC_LAYERS.rsc, + resolve: { + conditionNames: ['react-server', '...'], + }, + }) + + // All modules imported from the RSC layer inherit + // the react-server condition (transitive propagation), except + // route split virtual modules. Those remain ordinary SSR/client + // route code; only `?tsr-shared=1` modules may be shared with the + // provider subtree. + moduleRules.push({ + issuerLayer: RSBUILD_RSC_LAYERS.rsc, + resourceQuery: { + not: [/(?:^|[?&])tsr-split(?:=|&|$)/], + }, + resolve: { + conditionNames: ['react-server', '...'], + }, + }) + + // The RSC ServerPlugin injects imports like + // `react-server-dom-rspack/server` into transformed modules. + // Some modules in the server graph resolve from real package paths + // outside the app root, so relying on the default relative + // `node_modules` lookup is not enough. Seed resolve.modules with the + // app root explicitly, without package-manager-specific heuristics. + seedResolveModules(config, [`${root}/node_modules`, 'node_modules']) + + // Add ServerPlugin with HMR callback + config.plugins.push( + new rscPlugins.ServerPlugin({ + cssLink: { + precedence: false, + props: { + 'data-rsc-css-href': '', + }, + }, + onServerComponentChanges: () => { + // Send rsc:update to connected clients for HMR + devServerRef?.sockWrite('custom', { + event: 'rsc:update', + }) + }, + }), + ) + + config.plugins.push({ + apply(compiler: RspackCompiler) { + tapServerFnResolverRebuild(compiler, { + name: 'TanStackStartRscServerFnResolverRebuild', + updateResolver: () => { + virtualModuleState.tryUpdateServerFnResolver( + virtualModuleState.generateCurrentResolverContent(true), + ) + }, + getResolverWriteCount: () => + virtualModuleState.getServerFnResolverWriteCount( + RSBUILD_ENVIRONMENT_NAMES.server, + ), + rebuildResolver: (compilation) => + rebuildModulesContaining( + compilation, + virtualModuleState.serverFnResolverPath, + ), + }) + }, + }) + + config.plugins.push({ + apply(compiler: RspackCompiler) { + // Dev manifest write count this compiler last rebuilt from. + let rebuiltAtWriteCount: number | undefined + + compiler.hooks.finishMake.tapPromise( + { + name: 'TanStackStartRscManifestRebuild', + // The native RSC ServerPlugin completes the client-entry + // handoff during its finishMake hook. Rebuild the manifest + // after that point so it reflects the client build: the + // build transform emits the final source instead of the + // placeholder, and dev picks up a manifest written while + // this compilation was already running. + stage: 10, + }, + async (compilation: RspackCompilationExtended) => { + const clientBuild = getClientBuild() + + if (!clientBuild) { + return + } + + virtualModuleState.updateManifest(clientBuild) + + if (api.context.action === 'dev') { + // Only rebuild when the manifest changed: rebuilding an + // unchanged module can rebuild the whole chunk graph. + const writeCount = + virtualModuleState.getDevManifestWriteCount() + if (writeCount === rebuiltAtWriteCount) { + return + } + rebuiltAtWriteCount = writeCount + } + + await rebuildModulesContaining( + compilation, + virtualModuleState.manifestPath, + ) + }, + ) + }, + }) + } + + if (isClientEnv) { + // Add ClientPlugin — the Coordinator links it to the + // ServerPlugin's compilation state + config.plugins.push(new rscPlugins.ClientPlugin()) + } + + // --- SWC reactServerComponents --- + // Enable RSC directive detection where the native RSC plugins need it. + // In the server build, scope it to the actual RSC provider subtree so + // ordinary route-split modules (e.g. ?tsr-split=component) stay out of + // RSC validation unless they are really imported by a provider module. + if (isServerEnv) { + enableSwcReactServerComponents(config, 'rsc-subtree') + } else if (isClientEnv) { + enableSwcReactServerComponents(config, 'all') + } + }) + + // Capture dev server reference for RSC HMR socket writes + if (api.context.action === 'dev') { + api.onBeforeStartDevServer(({ server }) => { + devServerRef = server + }) + } + } + + // --------------------------------------------------------------- + // 8. Build ordering — client must complete before server starts + // so that the manifest virtual module has real client build stats. + // Uses rspack MultiCompiler.setDependencies() under the hood. + // + // IMPORTANT: When RSC is enabled we must NOT set dependencies. + // The RSC Coordinator already orchestrates server↔client + // compilation ordering by interleaving phases within compiler + // hooks. Adding setDependencies(server, [client]) on top of + // the Coordinator creates a deadlock: MultiCompiler blocks + // the server compiler until client is `done`, but the + // Coordinator blocks the client's `make` hook until the + // server's entries phase completes — neither can start. + // --------------------------------------------------------------- + if (!rscEnabled) { + api.onAfterCreateCompiler(({ compiler }) => { + // MultiCompiler has a `compilers` array; single compiler does not + if ('compilers' in compiler) { + for (const environmentName of startCompilerServerEnvironmentNames) { + const serverCompiler = compiler.compilers.find( + (c) => c.name === environmentName, + ) + if (serverCompiler) { + const dependencies: Array = [ + RSBUILD_ENVIRONMENT_NAMES.client, + ] + if ( + environmentName === RSBUILD_ENVIRONMENT_NAMES.server && + serverFnProviderEnv !== RSBUILD_ENVIRONMENT_NAMES.server + ) { + dependencies.push(serverFnProviderEnv) + } + + compiler.setDependencies(serverCompiler, dependencies) + } + } + } + }) + } + + // --------------------------------------------------------------- + // 8b. Manifest asset replacement fallback (RSC build only) + // Rsbuild's native RSC coordinator interleaves server and client + // compilers, so the server manifest module can compile before Start's + // normalized client build stats exist. Keep final replacement in the + // server asset pipeline, after the client processAssets capture has a + // chance to run. + // --------------------------------------------------------------- + if (api.context.action !== 'dev' && rscEnabled) { + const manifestPlaceholderLiteral = JSON.stringify( + START_MANIFEST_PLACEHOLDER, + ) + api.modifyRspackConfig((config, utils) => { + if (utils.environment.name !== RSBUILD_ENVIRONMENT_NAMES.server) + return + + config.plugins.push({ + apply(compiler: RspackCompiler) { + compiler.hooks.compilation.tap( + 'TanStackStartManifestReplace', + (compilation: RspackCompilationExtended) => { + compilation.hooks.processAssets.tap( + { + name: 'TanStackStartManifestReplace', + stage: + utils.rspack.Compilation + .PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE, + }, + () => { + let assetsWithPlaceholder: + | Array<{ asset: RspackAsset; sourceStr: string }> + | undefined + + for (const asset of compilation.getAssets()) { + if (!asset.name.endsWith('.js')) { + continue + } + + const sourceStr = String(asset.source.source()) + if (!sourceStr.includes(manifestPlaceholderLiteral)) { + continue + } + + if (!assetsWithPlaceholder) { + assetsWithPlaceholder = [] + } + assetsWithPlaceholder.push({ + asset, + sourceStr, + }) + } + + if (!assetsWithPlaceholder) { + return + } + + const clientBuild = getClientBuild() + if (!clientBuild) { + throw new Error( + 'TanStack Start could not replace the rsbuild RSC server manifest placeholder because the client build was unavailable', + ) + } + + const manifestValueLiteral = + virtualModuleState.generateManifestValueLiteral( + clientBuild, + ) + + for (const { + asset, + sourceStr, + } of assetsWithPlaceholder) { + compilation.updateAsset( + asset.name, + new utils.rspack.sources.RawSource( + sourceStr.replace( + manifestPlaceholderLiteral, + manifestValueLiteral, + ), + ), + ) + } + }, + ) + }, + ) + }, + }) + }) + } + + // --------------------------------------------------------------- + // 9. After client env compiles — refresh resolver + manifest + // --------------------------------------------------------------- + api.onAfterEnvironmentCompile(({ environment }) => { + if (environment.name !== RSBUILD_ENVIRONMENT_NAMES.client) return + + virtualModuleState.updateServerFnResolver() + + const clientBuild = getClientBuild() + if (clientBuild) { + virtualModuleState.updateManifest(clientBuild) + } + }) + + if (api.context.action === 'build') { + api.onAfterBuild(async () => { + const { startConfig } = getConfig() + + await postBuildWithRsbuild({ + startConfig, + clientOutputDirectory: resolvedStartConfig.outputDirectories.client, + serverOutputDirectory: resolvedStartConfig.outputDirectories.server, + }) + }) + } + }, + } +} + +function seedResolveModules( + config: RspackConfig, + entries: Array, +): void { + const resolveModules = (config.resolve.modules ??= []) + + for (const entry of entries) { + if (!resolveModules.includes(entry)) { + resolveModules.push(entry) + } + } +} + +function rebuildModulesContaining( + compilation: RspackCompilationExtended, + identifierFragment: string, +): Promise { + const rebuilds: Array> = [] + for (const mod of compilation.modules) { + if (!mod.identifier().includes(identifierFragment)) { + continue + } + + rebuilds.push( + new Promise((resolve, reject) => { + compilation.rebuildModule(mod, (err: Error | null) => { + if (err) reject(err) + else resolve() + }) + }), + ) + } + + return rebuilds.length === 0 + ? Promise.resolve() + : Promise.all(rebuilds).then(() => undefined) +} + +/** + * Return the realpath of every packages//dist directory in the + * TanStack Router monorepo. Only meaningful when called from inside the + * monorepo — in user apps, callers should guard with + * `isInsideRouterMonoRepo` before invoking this. + */ +function resolveWorkspacePackageDistRealpaths(): Array { + // currentDir points at either /packages/start-plugin-core/src/rsbuild + // or /packages/start-plugin-core/dist//rsbuild. Four levels up + // lands on /packages in both layouts. + const packagesDir = resolve(currentDir, '../../../../') + if (!existsSync(packagesDir)) return [] + + let entries: Array + try { + entries = readdirSync(packagesDir) + } catch { + return [] + } + + const dists: Array = [] + for (const entry of entries) { + const distPath = join(packagesDir, entry, 'dist') + try { + if (!statSync(distPath).isDirectory()) continue + } catch { + continue + } + try { + dists.push(realpathSync(distPath)) + } catch { + dists.push(distPath) + } + } + + return dists +} diff --git a/packages/start-plugin-core/src/rsbuild/post-build.ts b/packages/start-plugin-core/src/rsbuild/post-build.ts new file mode 100644 index 0000000000..2590ec9931 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/post-build.ts @@ -0,0 +1,96 @@ +import { join } from 'pathe' +import { postBuild } from '../post-build' +import { prerender } from '../prerender' +import type { PrerenderHandler } from '../prerender' +import type { TanStackStartOutputConfig } from '../schema' + +export async function postBuildWithRsbuild({ + startConfig, + clientOutputDirectory, + serverOutputDirectory, +}: { + startConfig: TanStackStartOutputConfig + clientOutputDirectory: string + serverOutputDirectory: string +}) { + await postBuild({ + startConfig, + adapter: { + getClientOutputDirectory() { + return clientOutputDirectory + }, + prerender(startConfig) { + return prerender({ + startConfig, + handler: createRsbuildPrerenderHandler({ + clientOutputDirectory, + serverOutputDirectory, + }), + }) + }, + }, + }) +} + +function createRsbuildPrerenderHandler({ + clientOutputDirectory, + serverOutputDirectory, +}: { + clientOutputDirectory: string + serverOutputDirectory: string +}): PrerenderHandler { + process.env.TSS_PRERENDERING = 'true' + process.env.TSS_CLIENT_OUTPUT_DIR = clientOutputDirectory + + let requestHandlerPromise: + | Promise< + (request: Request, opts?: unknown) => Promise | Response + > + | undefined + + return { + getClientOutputDirectory() { + return clientOutputDirectory + }, + async request(path, options) { + const requestHandler = await getRequestHandler() + const url = new URL(path, 'http://localhost') + + return requestHandler( + new Request(url, { + ...options, + redirect: 'manual', + }), + ) + }, + } + + function getRequestHandler() { + if (!requestHandlerPromise) { + requestHandlerPromise = loadRequestHandler(serverOutputDirectory) + } + + return requestHandlerPromise + } +} + +async function loadRequestHandler(serverOutputDirectory: string) { + const { pathToFileURL } = await import('node:url') + const serverEntryUrl = pathToFileURL( + join(serverOutputDirectory, 'index.js'), + ).toString() + const serverModule = await import(serverEntryUrl) + const handler = serverModule.default + + if (typeof handler === 'function') { + return handler as (request: Request) => Promise | Response + } + + if (handler && typeof handler.fetch === 'function') { + return (request: Request) => handler.fetch(request) + } + + throw new Error( + `Unable to resolve a request handler from Rsbuild server bundle at ${serverEntryUrl}`, + ) +} diff --git a/packages/start-plugin-core/src/rsbuild/schema.ts b/packages/start-plugin-core/src/rsbuild/schema.ts new file mode 100644 index 0000000000..86194e309c --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/schema.ts @@ -0,0 +1,54 @@ +import { z } from 'zod' +import { + parseStartConfig as parseCoreStartConfig, + tanstackStartOptionsObjectSchema, +} from '../schema' +import type { CompileStartFrameworkOptions } from '../types' +import type { InlineCssInputOptions } from '../schema' + +export const rsbuildClientOutputSchema = z.enum(['module', 'iife']) + +export const tanstackStartRsbuildOptionsSchema = + tanstackStartOptionsObjectSchema + .extend({ + rsbuild: z + .object({ + installDevServerMiddleware: z.boolean().optional(), + client: z + .object({ + output: rsbuildClientOutputSchema.optional().default('module'), + }) + .optional() + .prefault({}), + }) + .optional(), + }) + .optional() + .prefault({}) + +export function parseStartConfig( + opts: z.input, + corePluginOpts: { framework: CompileStartFrameworkOptions }, + root: string, +) { + tanstackStartRsbuildOptionsSchema.parse(opts) + const { rsbuild: _rsbuild, ...coreOptions } = opts ?? {} + + return parseCoreStartConfig(coreOptions, corePluginOpts, root) +} + +export type TanStackStartRsbuildInputConfig = z.input< + typeof tanstackStartRsbuildOptionsSchema +> & { + rsbuild?: { + installDevServerMiddleware?: boolean + client?: { + output?: z.input + } + } + server?: { + build?: { + inlineCss?: InlineCssInputOptions + } + } +} diff --git a/packages/start-plugin-core/src/rsbuild/server-fn-resolver-rebuild.ts b/packages/start-plugin-core/src/rsbuild/server-fn-resolver-rebuild.ts new file mode 100644 index 0000000000..75c54ecf93 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/server-fn-resolver-rebuild.ts @@ -0,0 +1,53 @@ +import type { Rspack } from '@rsbuild/core' + +export interface ServerFnResolverRebuildOptions { + /** Name of the finishMake tap. */ + name: string + /** Writes the current resolver content to its virtual module. */ + updateResolver: () => void + /** Returns how many times this environment's resolver has been written. */ + getResolverWriteCount: () => number + /** Rebuilds the resolver module in the given compilation. */ + rebuildResolver: (compilation: Rspack.Compilation) => Promise +} + +/** + * Rebuilds the server function resolver module at finishMake stage -10, + * after stage -20 has refreshed the server function registry. + * + * Skips the rebuild when the resolver has not been written since this + * compiler last rebuilt it. In development the resolver is written only when + * its content changes. Rebuilding an unchanged resolver can make Rspack + * rebuild the whole chunk graph. + */ +export function tapServerFnResolverRebuild( + compiler: Rspack.Compiler, + options: ServerFnResolverRebuildOptions, +): void { + // Write count of the resolver content this compiler last rebuilt from. + let rebuiltAtWriteCount: number | undefined + + compiler.hooks.finishMake.tapPromise( + { name: options.name, stage: -10 }, + async (compilation) => { + options.updateResolver() + + // Child compilers copy finishMake taps from their parent. Child + // compilations always rebuild and do not change this compiler's state. + if (compilation.compiler !== compiler) { + await options.rebuildResolver(compilation) + return + } + + // Read the count before the rebuild reads the resolver, so a write + // that lands during the rebuild causes another rebuild next time. + const writeCount = options.getResolverWriteCount() + if (writeCount === rebuiltAtWriteCount) { + return + } + + await options.rebuildResolver(compilation) + rebuiltAtWriteCount = writeCount + }, + ) +} diff --git a/packages/start-plugin-core/src/rsbuild/server-middleware.ts b/packages/start-plugin-core/src/rsbuild/server-middleware.ts new file mode 100644 index 0000000000..70e2f234ce --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/server-middleware.ts @@ -0,0 +1,217 @@ +import { resolve } from 'node:path' +import { pathToFileURL } from 'node:url' +import { NodeRequest, sendNodeResponse } from 'srvx/node' +import { joinURL } from 'ufo' +import { RSBUILD_ENVIRONMENT_NAMES } from './planning' +import type { IncomingMessage, ServerResponse } from 'node:http' +import type { RsbuildConfig } from '@rsbuild/core' + +type ServerSetupFn = Extract< + NonNullable['setup']>, + (...args: Array) => any +> +type ServerSetupContext = Parameters[0] +type SSRMiddleware = ( + req: IncomingMessage & { originalUrl?: string }, + res: ServerResponse, + next: (error?: unknown) => void, +) => Promise +type FetchHandler = (req: Request) => Promise | Response + +type ServerEntry = + | FetchHandler + | { + fetch?: FetchHandler + } + +function resolveFetchHandler(serverEntry: ServerEntry): FetchHandler { + if (typeof serverEntry === 'function') { + return serverEntry + } + + if (typeof serverEntry.fetch === 'function') { + return serverEntry.fetch.bind(serverEntry) + } + + throw new Error( + 'Unable to resolve a request handler from Rsbuild server bundle', + ) +} + +function getPublicBasePathname(publicBase: string): string { + try { + return new URL(publicBase, 'http://localhost').pathname + } catch { + return publicBase + } +} + +function restorePreviewUrl(opts: { + req: IncomingMessage & { originalUrl?: string } + publicBase: string +}) { + if (opts.req.originalUrl) { + opts.req.url = opts.req.originalUrl + } + + const publicBasePathname = getPublicBasePathname(opts.publicBase) + if (publicBasePathname === '/') { + return + } + + const url = opts.req.url ?? '/' + if (url.startsWith(publicBasePathname)) { + return + } + + opts.req.url = joinURL(publicBasePathname, url) +} + +async function loadDevFetchHandler( + context: ServerSetupContext, +): Promise { + if (context.action !== 'dev') { + throw new Error('Cannot load Rsbuild dev SSR bundle outside dev mode') + } + + const ssrEnv = context.server.environments[RSBUILD_ENVIRONMENT_NAMES.server] + + if (!ssrEnv) { + throw new Error( + `SSR environment "${RSBUILD_ENVIRONMENT_NAMES.server}" not found`, + ) + } + + const serverEntry = await ssrEnv.loadBundle<{ default: ServerEntry }>('index') + return resolveFetchHandler(serverEntry.default) +} + +/** + * Returns a `server.setup` function for rsbuild v2. + * + * Two middleware positions are used: + * + * 1. **Setup body** (BEFORE built-ins): Intercepts `/_serverFn/` URLs so + * they never reach rsbuild's htmlFallback/htmlCompletion middleware, + * which can swallow long base64 function IDs. + * + * 2. **Returned callback** (AFTER built-ins, BEFORE fallback): Handles + * all remaining SSR requests (page navigations). This position lets + * rsbuild's asset middleware serve compiled JS/CSS first. + * + * The middleware choreography is shared by dev and preview. The server entry + * loader differs: dev reads from Rsbuild's in-memory environment so rebuilds + * are reflected immediately, while preview lazy-imports the production server + * bundle from disk. + * + * See rsbuild source: devMiddlewares.ts `applyDefaultMiddlewares()` and + * previewServer.ts `startPreviewServer()`. + */ +export function createServerSetup(opts: { + serverFnBasePath: string + serverOutputDirectory: string + publicBase: string +}): ServerSetupFn { + let previewFetchHandlerPromise: Promise | undefined + + const getPreviewFetchHandler = () => { + if (!previewFetchHandlerPromise) { + previewFetchHandlerPromise = loadPreviewFetchHandler( + opts.serverOutputDirectory, + ) + } + + return previewFetchHandlerPromise + } + + return (context) => { + const serverFnBase = opts.serverFnBasePath + + const handleSSR: SSRMiddleware = async (req, res, next) => { + try { + const fetchHandler = + context.action === 'dev' + ? await loadDevFetchHandler(context) + : await getPreviewFetchHandler() + + if (context.action === 'preview') { + // Rsbuild preview's base middleware strips server.base before the + // returned setup callback runs. Put it back before creating the Web + // Request so Start's router sees the same URL shape as build/custom + // servers. The early server-fn middleware runs before that base + // middleware, so avoid prepending when the URL already has the base. + restorePreviewUrl({ req, publicBase: opts.publicBase }) + } else if (req.originalUrl) { + // Restore the original URL (rsbuild may rewrite to /index.html) + req.url = req.originalUrl + } + + const webReq = new NodeRequest({ req, res }) + const webRes = await fetchHandler(webReq) + return sendNodeResponse(res, webRes) + } catch (e) { + console.error('[tanstack-start] SSR error:', e) + + const webReq = new NodeRequest({ req, res }) + if (webReq.headers.get('content-type')?.includes('application/json')) { + return sendNodeResponse( + res, + new Response( + JSON.stringify( + { + status: 500, + error: 'Internal Server Error', + message: + 'An unexpected error occurred. Please try again later.', + timestamp: new Date().toISOString(), + }, + null, + 2, + ), + { + status: 500, + headers: { 'Content-Type': 'application/json' }, + }, + ), + ) + } + + return next(e) + } + } + + // Position 1: BEFORE built-ins — intercept server function calls + // early so they are not swallowed by htmlFallback or assetsMiddleware. + context.server.middlewares.use(async (req, res, next) => { + const url = req.url || '/' + if (url.startsWith(serverFnBase)) { + return handleSSR(req, res, next) + } + return next() + }) + + // Position 2: AFTER built-ins, before fallback — SSR catch-all for + // page navigations. Assets are already handled by rsbuild middleware. + return () => { + context.server.middlewares.use(handleSSR) + } + } +} + +async function loadPreviewFetchHandler( + serverOutputDirectory: string, +): Promise { + const serverEntryPath = resolve(serverOutputDirectory, 'index.js') + const imported = (await import( + pathToFileURL(serverEntryPath).toString() + )) as { default: ServerEntry } + + try { + return resolveFetchHandler(imported.default) + } catch (error) { + throw new Error( + `Unable to resolve a request handler from Rsbuild server bundle at ${serverEntryPath}`, + { cause: error }, + ) + } +} diff --git a/packages/start-plugin-core/src/rsbuild/start-compiler-host.ts b/packages/start-plugin-core/src/rsbuild/start-compiler-host.ts new file mode 100644 index 0000000000..3cd1725fa0 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/start-compiler-host.ts @@ -0,0 +1,502 @@ +import { AsyncLocalStorage } from 'node:async_hooks' +import { dirname, resolve } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' +import { z } from 'zod' +import { TRANSFORM_ID_REGEX } from '../constants' +import { detectKindsInCode } from '../start-compiler/compiler' +import { getTransformCodeFilterForEnv } from '../start-compiler/config' +import { + createStartCompiler, + loadCompilerVirtualModule, + matchesCodeFilters, + mergeServerFnsById, +} from '../start-compiler/host' +import { cleanId } from '../start-compiler/utils' +import { createHydrateCompilerPlugin } from '../hydrate-when-transform' +import { + SERVER_FN_BUILD_INFO_CONTEXT_KEY, + SERVER_FN_BUILD_INFO_FIELD, +} from './start-compiler-metadata' +import type { RsbuildPluginAPI, Rspack } from '@rsbuild/core' +import type { + ServerFnBuildInfo, + ServerFnBuildInfoLoaderContext, +} from './start-compiler-metadata' +import type { + CompileStartFrameworkOptions, + StartCompilerImportTransform, + StartCompilerPlugin, + StartCompilerTransformResult, +} from '../types' +import type { + DevServerFnModuleSpecifierEncoder, + GenerateFunctionIdFnOptional, + ServerFn, +} from '../start-compiler/types' + +type RsbuildTransformContext = Parameters< + Parameters[1] +>[0] +type WarnableRsbuildTransformContext = RsbuildTransformContext & { + emitWarning?: (warning: Error) => void +} +type RsbuildInputFileSystem = NonNullable +type ServerFnMetadataById = Map +type StartCompilerEnvironment = { + name: string + type: 'client' | 'server' +} + +const serverFnSchema = z.object({ + functionName: z.string(), + functionId: z.string(), + extractedFilename: z.string(), + filename: z.string(), + isClientReferenced: z.boolean().optional(), +}) + +const serverFnBuildInfoSchema = z.object({ + version: z.literal(1), + serverFnsById: z.record(z.string(), serverFnSchema), +}) + +/** + * In Rsbuild dev, use file:// URLs for absolute server function paths. + * These are directly importable by Node's ESM VM runner without any bundler + * path conventions (unlike Vite's /@id/ prefix). + */ +const rsbuildDevServerFnModuleSpecifierEncoder: DevServerFnModuleSpecifierEncoder = + ({ extractedFilename }) => pathToFileURL(extractedFilename).href + +const currentDir = dirname(fileURLToPath(import.meta.url)) +const metadataLoaderFilename = 'start-compiler-metadata-loader.js' +const EMPTY_SERVER_FN_BUILD_INFO: ServerFnBuildInfo = { + version: 1, + serverFnsById: {}, +} + +function resolveMetadataLoader(): string { + return resolve(currentDir, metadataLoaderFilename) +} + +function readServerFnBuildInfo( + module: Rspack.Module, +): Record | null { + const result = serverFnBuildInfoSchema.safeParse( + module.buildInfo[SERVER_FN_BUILD_INFO_FIELD], + ) + if (!result.success) { + return null + } + + return result.data.serverFnsById +} + +function setServerFnBuildInfoLoaderContext( + loaderContext: Rspack.LoaderContext & ServerFnBuildInfoLoaderContext, + module: Rspack.Module, +) { + loaderContext[SERVER_FN_BUILD_INFO_CONTEXT_KEY] = (metadata) => { + if (metadata) { + module.buildInfo[SERVER_FN_BUILD_INFO_FIELD] = metadata + } else if (module.buildInfo[SERVER_FN_BUILD_INFO_FIELD]) { + module.buildInfo[SERVER_FN_BUILD_INFO_FIELD] = EMPTY_SERVER_FN_BUILD_INFO + } + } +} + +function warnTransformContext( + ctx: WarnableRsbuildTransformContext, + message: string, +): void { + ctx.emitWarning?.(new Error(message)) +} + +export interface StartCompilerHostOptions { + framework: CompileStartFrameworkOptions + root: string | (() => string) + environments: Array + providerEnvName: string + generateFunctionId?: GenerateFunctionIdFnOptional + compilerTransforms?: Array | undefined + compilerPlugins?: Array | undefined + serverFnProviderModuleDirectives?: ReadonlyArray | undefined + serverFnsById?: Record + onServerFnsByIdChange?: () => void +} + +/** + * Registers the shared StartCompiler as rsbuild transforms for client + ssr environments. + * + * Uses `api.transform()` to hook into the rsbuild loader pipeline, and the + * transform context's native `resolve()` for module resolution. + */ +export function registerStartCompilerTransforms( + api: RsbuildPluginAPI, + opts: StartCompilerHostOptions, +): { + serverFnsById: Record +} { + const compilers = new Map>() + // Serialize access to each StartCompiler's mutable per-environment caches. + const compilerQueues = new Map>() + const inputFileSystems = new Map() + const transformContextStorage = + new AsyncLocalStorage() + const serverFnMetadataByEnvironment = new Map() + const serverFnsByEnvironment = new Map>() + const serverFnsById = opts.serverFnsById ?? {} + const getRoot = () => + typeof opts.root === 'function' ? opts.root() : opts.root + const getServerFnMetadata = (environmentName: string) => { + let metadataById = serverFnMetadataByEnvironment.get(environmentName) + + if (!metadataById) { + metadataById = new Map() + serverFnMetadataByEnvironment.set(environmentName, metadataById) + } + + return metadataById + } + const runCompilerTask = async ( + environmentName: string, + task: () => Promise, + ): Promise => { + const previous = compilerQueues.get(environmentName) ?? Promise.resolve() + const next = previous.catch(() => undefined).then(task) + + compilerQueues.set( + environmentName, + next.then( + () => undefined, + () => undefined, + ), + ) + + return next + } + + const replaceServerFnsByIdFromEnvironmentSnapshots = () => { + const nextServerFnsById: Record = {} + + for (const snapshot of serverFnsByEnvironment.values()) { + mergeServerFnsById(nextServerFnsById, snapshot) + } + + for (const key of Object.keys(serverFnsById)) { + delete serverFnsById[key] + } + + Object.assign(serverFnsById, nextServerFnsById) + opts.onServerFnsByIdChange?.() + } + const compilerPlugins = [ + createHydrateCompilerPlugin(), + ...(opts.compilerPlugins ?? []), + ] + + const isDev = api.context.action === 'dev' + const mode = isDev ? 'dev' : 'build' + const metadataLoader = resolveMetadataLoader() + + const environments = opts.environments + + // Rspack persistent cache restores modules without re-running api.transform. + // Keep server function modules cacheable by writing discovered metadata into + // buildInfo from a real loader, then replaying it from cached modules. + api.modifyRspackConfig((config, utils) => { + if (!environments.some((env) => env.name === utils.environment.name)) { + return + } + + const rules = config.module.rules ?? [] + rules.push({ + test: TRANSFORM_ID_REGEX[0], + enforce: 'post', + use: [ + { + loader: metadataLoader, + options: { + metadataById: getServerFnMetadata(utils.environment.name), + }, + }, + ], + }) + config.module.rules = rules + }) + + for (const env of environments) { + const compilerTransforms = + env.name === opts.providerEnvName ? opts.compilerTransforms : undefined + const envCodeFilters = getTransformCodeFilterForEnv(env.type, { + compilerTransforms, + compilerPlugins, + }) + const serverFnProviderModuleDirectives = + env.name === opts.providerEnvName + ? opts.serverFnProviderModuleDirectives + : undefined + let activeServerFnMetadata: Record | undefined + const onServerFnsById = (d: Record) => { + mergeServerFnsById(serverFnsById, d) + + if (activeServerFnMetadata) { + mergeServerFnsById(activeServerFnMetadata, d) + } + + opts.onServerFnsByIdChange?.() + } + + api.transform( + { + test: TRANSFORM_ID_REGEX[0], + environments: [env.name], + order: 'pre', + }, + async (ctx: RsbuildTransformContext) => { + return transformContextStorage.run(ctx, async () => { + const code = ctx.code + let nextCode = code + let previousResult: { + code: string + map: StartCompilerTransformResult['map'] + } | null = null + const id = ctx.resource + const root = getRoot() + + const virtualResult = loadCompilerVirtualModule(compilerPlugins, { + code, + id, + root, + env: env.type, + envName: env.name, + }) + if (virtualResult) { + nextCode = virtualResult.code + previousResult = { + code: virtualResult.code, + map: virtualResult.map ?? null, + } + } + + // Quick string-level check: does this file contain any patterns for this env? + if (!matchesCodeFilters(nextCode, envCodeFilters)) { + return previousResult ?? nextCode + } + + let compiler = compilers.get(env.name) + if (!compiler) { + compiler = createStartCompiler({ + env: env.type, + envName: env.name, + root, + mode, + framework: opts.framework, + providerEnvName: opts.providerEnvName, + generateFunctionId: opts.generateFunctionId, + compilerTransforms, + compilerPlugins, + serverFnProviderModuleDirectives, + onServerFnsById, + getKnownServerFns: () => serverFnsById, + encodeModuleSpecifierInDev: isDev + ? rsbuildDevServerFnModuleSpecifierEncoder + : undefined, + loadModule: async (moduleId: string) => { + const activeCtx = transformContextStorage.getStore() + if (!activeCtx) { + throw new Error( + `could not load module ${moduleId}: missing active rsbuild transform context for ${env.name}`, + ) + } + + const inputFileSystem = inputFileSystems.get(env.name) + if (!inputFileSystem) { + throw new Error( + `could not load module ${moduleId}: missing rspack input filesystem for ${env.name}`, + ) + } + + const cleanedId = cleanId(moduleId) + activeCtx.addDependency(cleanedId) + const loaded = await readFileFromInputFileSystem( + inputFileSystem, + cleanedId, + ) + const moduleCode = Buffer.isBuffer(loaded) + ? loaded.toString('utf8') + : loaded + + compiler!.ingestModule({ code: moduleCode, id: cleanedId }) + }, + resolveId: async ( + source: string, + importer?: string, + ): Promise => { + const activeCtx = transformContextStorage.getStore() + if (!activeCtx) { + throw new Error( + `could not resolve ${source}: missing active rsbuild transform context for ${env.name}`, + ) + } + + const context = importer + ? importer.replace(/[/\\][^/\\]*$/, '') + : getRoot() + + return await new Promise((resolve, reject) => { + activeCtx.resolve(context, source, (error, resolved) => { + if (error) { + reject(error) + return + } + + if (!resolved) { + resolve(null) + return + } + + resolve(cleanId(resolved)) + }) + }) + }, + }) + compilers.set(env.name, compiler) + } + + const detectedKinds = detectKindsInCode(nextCode, env.type, { + compilerTransforms, + }) + const discoveredServerFnsById: Record = {} + const result = await runCompilerTask(env.name, async () => { + activeServerFnMetadata = discoveredServerFnsById + + try { + return await compiler.compile({ + id, + code: nextCode, + detectedKinds, + warn: (message) => warnTransformContext(ctx, message), + }) + } finally { + activeServerFnMetadata = undefined + } + }) + + getServerFnMetadata(env.name).set(id, { + version: 1, + serverFnsById: discoveredServerFnsById, + }) + + if (result) { + return { + code: result.code, + map: result.map ?? null, + } + } + + return previousResult ?? nextCode + }) + }, + ) + } + + api.modifyRspackConfig((config, utils) => { + if (!environments.some((env) => env.name === utils.environment.name)) { + return + } + + config.plugins.push({ + apply(compiler: Rspack.Compiler) { + if (compiler.inputFileSystem) { + inputFileSystems.set(utils.environment.name, compiler.inputFileSystem) + } + + compiler.hooks.compilation.tap( + 'TanStackStartCompilerMetadataLoaderContext', + (compilation) => { + utils.rspack.NormalModule.getCompilationHooks( + compilation, + ).loader.tap( + 'TanStackStartCompilerMetadataLoaderContext', + (loaderContext, module) => { + setServerFnBuildInfoLoaderContext(loaderContext, module) + }, + ) + }, + ) + + compiler.hooks.compile.tap('TanStackStartCompilerMetadataCleanup', () => + getServerFnMetadata(utils.environment.name).clear(), + ) + + compiler.hooks.finishMake.tap( + { + name: 'TanStackStartCompilerCachedServerFnMetadata', + stage: -20, + }, + (compilation) => { + const restoredServerFnsById: Record = {} + + for (const module of compilation.modules) { + const metadata = readServerFnBuildInfo(module) + if (!metadata) { + continue + } + + mergeServerFnsById(restoredServerFnsById, metadata) + } + + serverFnsByEnvironment.set( + utils.environment.name, + restoredServerFnsById, + ) + replaceServerFnsByIdFromEnvironmentSnapshots() + }, + ) + + compiler.hooks.watchRun.tap( + 'TanStackStartCompilerModuleInvalidation', + (watchCompiler) => { + const startCompiler = compilers.get(utils.environment.name) + + if (!startCompiler) { + return + } + + for (const file of watchCompiler.modifiedFiles ?? []) { + startCompiler.invalidateModule(file) + } + + for (const file of watchCompiler.removedFiles ?? []) { + startCompiler.invalidateModule(file) + } + }, + ) + }, + }) + }) + + return { serverFnsById } +} + +function readFileFromInputFileSystem( + inputFileSystem: RsbuildInputFileSystem, + file: string, +): Promise { + return new Promise((resolve, reject) => { + inputFileSystem.readFile(file, (error, data) => { + if (error) { + reject(error) + return + } + + if (data == null) { + reject(new Error(`could not read module source for ${file}`)) + return + } + + resolve(data) + }) + }) +} diff --git a/packages/start-plugin-core/src/rsbuild/start-compiler-metadata-loader.ts b/packages/start-plugin-core/src/rsbuild/start-compiler-metadata-loader.ts new file mode 100644 index 0000000000..89a22d82cd --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/start-compiler-metadata-loader.ts @@ -0,0 +1,22 @@ +import { SERVER_FN_BUILD_INFO_CONTEXT_KEY } from './start-compiler-metadata' +import type { Rspack } from '@rsbuild/core' +import type { + ServerFnBuildInfoLoaderContext, + ServerFnMetadataLoaderOptions, +} from './start-compiler-metadata' + +const tanStackStartCompilerMetadataLoader: Rspack.LoaderDefinition< + ServerFnMetadataLoaderOptions, + ServerFnBuildInfoLoaderContext +> = function (source, map): void { + const { metadataById } = this.getOptions() + const id = this.resource + const metadata = metadataById.get(id) + const setBuildInfo = this[SERVER_FN_BUILD_INFO_CONTEXT_KEY] + + setBuildInfo?.(metadata ?? null) + + this.callback(null, source, map) +} + +export default tanStackStartCompilerMetadataLoader diff --git a/packages/start-plugin-core/src/rsbuild/start-compiler-metadata.ts b/packages/start-plugin-core/src/rsbuild/start-compiler-metadata.ts new file mode 100644 index 0000000000..dfa6119246 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/start-compiler-metadata.ts @@ -0,0 +1,20 @@ +import type { ServerFn } from '../start-compiler/types' + +export const SERVER_FN_BUILD_INFO_FIELD = 'tanstack.start.serverFns' +export const SERVER_FN_BUILD_INFO_CONTEXT_KEY = + 'tanstack.start.setServerFnBuildInfo' + +export type ServerFnBuildInfo = { + version: 1 + serverFnsById: Record +} + +export type SetServerFnBuildInfo = (metadata: ServerFnBuildInfo | null) => void + +export type ServerFnBuildInfoLoaderContext = { + [SERVER_FN_BUILD_INFO_CONTEXT_KEY]?: SetServerFnBuildInfo +} + +export type ServerFnMetadataLoaderOptions = { + metadataById: Map +} diff --git a/packages/start-plugin-core/src/rsbuild/start-router-plugin.ts b/packages/start-plugin-core/src/rsbuild/start-router-plugin.ts new file mode 100644 index 0000000000..7c3106be28 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/start-router-plugin.ts @@ -0,0 +1,70 @@ +import { createRouterPluginContext } from '@tanstack/router-plugin/context' +import { + TanStackRouterCodeSplitterRspack, + TanStackRouterGeneratorRspack, +} from '@tanstack/router-plugin/rspack' +import { startGeneratorConfig } from '../start-router-plugin/generator-config' +import { RSBUILD_ENVIRONMENT_NAMES } from './planning' +import type { RsbuildPluginAPI } from '@rsbuild/core' +import type { GetConfigFn, TanStackStartCoreOptions } from '../types' +import type { TanStackStartRsbuildInputConfig } from './schema' + +/** + * Registers the TanStack Router generator and code-splitter plugins + * as rspack plugins via `modifyRspackConfig`. + * + * The router-plugin package exports rspack-compatible unplugin wrappers: + * - TanStackRouterGeneratorRspack: file-based route generation + * - TanStackRouterCodeSplitterRspack: route code splitting + */ +export function registerRouterPlugins( + api: RsbuildPluginAPI, + opts: { + getConfig: GetConfigFn + corePluginOpts: TanStackStartCoreOptions + startPluginOpts: TanStackStartRsbuildInputConfig + }, +): void { + const routerPluginContext = createRouterPluginContext() + + api.modifyRspackConfig((config, utils) => { + const envName = utils.environment.name + const { startConfig } = opts.getConfig() + const routerConfig = startConfig.router + + // Generator only runs once — register for the client environment + if (envName === RSBUILD_ENVIRONMENT_NAMES.client) { + const generatorPlugin = TanStackRouterGeneratorRspack( + startGeneratorConfig({ + getConfig: opts.getConfig, + corePluginOpts: opts.corePluginOpts, + prerender: opts.startPluginOpts.prerender?.enabled === true, + }), + routerPluginContext, + ) + utils.appendPlugins(generatorPlugin) + } + + if ( + envName === RSBUILD_ENVIRONMENT_NAMES.client || + envName === RSBUILD_ENVIRONMENT_NAMES.server + ) { + const isClient = envName === RSBUILD_ENVIRONMENT_NAMES.client + const splitterPlugin = TanStackRouterCodeSplitterRspack( + { + ...routerConfig, + target: opts.corePluginOpts.framework, + codeSplittingOptions: { + ...routerConfig.codeSplittingOptions, + deleteNodes: isClient + ? ['ssr', 'server', 'headers'] + : routerConfig.codeSplittingOptions?.deleteNodes, + addHmr: isClient, + }, + }, + routerPluginContext, + ) + utils.appendPlugins(splitterPlugin) + } + }) +} diff --git a/packages/start-plugin-core/src/rsbuild/swc-rsc.ts b/packages/start-plugin-core/src/rsbuild/swc-rsc.ts new file mode 100644 index 0000000000..534a7860bb --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/swc-rsc.ts @@ -0,0 +1,174 @@ +import { RSBUILD_RSC_LAYERS } from './planning' +import type { ModifyRspackConfigFn, Rspack } from '@rsbuild/core' + +type RspackConfig = Parameters[0] +type RspackRule = Rspack.RuleSetRule +type Falsy = false | 0 | '' | null | undefined + +/** + * Walk the rspack config's module.rules and inject + * `rspackExperiments.reactServerComponents: true` into SWC loaders. + * + * Recurses into `oneOf` arrays because rsbuild nests the main SWC loader + * inside a `oneOf` rule (e.g. separate branches for asset/source vs + * javascript/auto). Without recursion, only the mimetype-based fallback + * SWC rule gets the flag, leaving most .js/.ts files without RSC + * directive detection. + */ +export function enableSwcReactServerComponents( + config: RspackConfig, + scope: 'all' | 'rsc-subtree', +): void { + const isRspackRule = ( + rule: NonNullable[number], + ): rule is RspackRule => !!rule && rule !== '...' + const getRuleLoaders = (rule: RspackRule) => { + const { use } = rule + if (!use) { + return [] + } + + const loaders = + typeof use === 'function' ? [] : Array.isArray(use) ? use : [use] + // Rspack allows falsy entries in `use` for conditionally disabled loaders. + return loaders.filter( + (loader): loader is Exclude => !!loader, + ) + } + const getLoaderPath = ( + loader: ReturnType[number], + ): string | undefined => (typeof loader === 'string' ? loader : loader.loader) + const cloneLoader = ( + loader: ReturnType[number], + ): ReturnType[number] => { + if (typeof loader === 'string') { + return loader + } + + const options = loader.options + return { + ...loader, + ...(options && typeof options === 'object' && !Array.isArray(options) + ? { + options: { + ...options, + ...(options.rspackExperiments && + typeof options.rspackExperiments === 'object' && + !Array.isArray(options.rspackExperiments) + ? { + rspackExperiments: { + ...options.rspackExperiments, + }, + } + : {}), + }, + } + : {}), + } + } + const cloneRuleUse = (use: RspackRule['use']): RspackRule['use'] => { + if (!use || typeof use === 'function') { + return use + } + + if (Array.isArray(use)) { + return use.map((loader) => + loader ? cloneLoader(loader) : loader, + ) as RspackRule['use'] + } + + return cloneLoader(use) as RspackRule['use'] + } + const cloneRspackRule = (rule: RspackRule): RspackRule => { + return { + ...rule, + use: cloneRuleUse(rule.use), + resolve: rule.resolve ? { ...rule.resolve } : rule.resolve, + oneOf: Array.isArray(rule.oneOf) + ? rule.oneOf.map((childRule) => + isRspackRule(childRule) ? cloneRspackRule(childRule) : childRule, + ) + : rule.oneOf, + } as unknown as RspackRule + } + const rootRules = (config.module.rules ??= []).filter(isRspackRule) + + function processRules(rules = rootRules): void { + for (const rule of rules) { + processRules( + Array.isArray(rule.oneOf) ? rule.oneOf.filter(isRspackRule) : [], + ) + + const hasSwcLoader = getRuleLoaders(rule).some((loader) => + Boolean(getLoaderPath(loader)?.includes('swc-loader')), + ) + if (!hasSwcLoader) continue + + const enableReactServerComponentsOnRule = (nextRule: RspackRule) => { + for (const loader of getRuleLoaders(nextRule)) { + if (typeof loader === 'string') { + continue + } + + const loaderPath = getLoaderPath(loader) + if (!loaderPath || !loaderPath.includes('swc-loader')) { + continue + } + + const options = + loader.options && typeof loader.options === 'object' + ? loader.options + : (loader.options = {}) + const experiments = + options.rspackExperiments && + typeof options.rspackExperiments === 'object' + ? options.rspackExperiments + : (options.rspackExperiments = {}) + const current = experiments.reactServerComponents + + experiments.reactServerComponents = + current === true || current == null + ? {} + : typeof current === 'object' && + current !== null && + !Array.isArray(current) + ? { ...current } + : {} + } + } + + if (scope === 'all') { + enableReactServerComponentsOnRule(rule) + continue + } + + const originalRule = cloneRspackRule(rule) + const providerRule = cloneRspackRule(originalRule) + providerRule.resourceQuery = /(?:^|[?&])tss-serverfn-split(?:&|$)/ + enableReactServerComponentsOnRule(providerRule) + + const routeSplitRule = cloneRspackRule(originalRule) + routeSplitRule.resourceQuery = /(?:^|[?&])tsr-split(?:=|&|$)/ + const routeSplitConditionNames = originalRule.resolve?.conditionNames + routeSplitRule.resolve = { + ...originalRule.resolve, + conditionNames: Array.isArray(routeSplitConditionNames) + ? routeSplitConditionNames.includes('...') + ? [...routeSplitConditionNames] + : ['...', ...routeSplitConditionNames] + : ['...'], + } + + const subtreeRule = cloneRspackRule(originalRule) + subtreeRule.issuerLayer = RSBUILD_RSC_LAYERS.rsc + enableReactServerComponentsOnRule(subtreeRule) + + for (const key of Object.keys(rule) as Array) { + delete rule[key] + } + rule.oneOf = [providerRule, routeSplitRule, subtreeRule, originalRule] + } + } + + processRules() +} diff --git a/packages/start-plugin-core/src/rsbuild/types.ts b/packages/start-plugin-core/src/rsbuild/types.ts new file mode 100644 index 0000000000..fa10d65f64 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/types.ts @@ -0,0 +1,20 @@ +import type { EnvironmentConfig } from '@rsbuild/core' +import type { TanStackStartCoreOptions } from '../types' + +export interface RsbuildEnvironmentOverrides { + all?: EnvironmentConfig | undefined + client?: EnvironmentConfig | undefined + server?: EnvironmentConfig | undefined + provider?: EnvironmentConfig | undefined +} + +export interface RsbuildCoreOptions { + environments?: RsbuildEnvironmentOverrides | undefined +} + +export type TanStackStartRsbuildPluginCoreOptions = TanStackStartCoreOptions & { + providerEnvironmentName: string + ssrIsProvider: boolean + rsbuild?: RsbuildCoreOptions | undefined + rsc?: boolean | undefined +} diff --git a/packages/start-plugin-core/src/rsbuild/virtual-modules.ts b/packages/start-plugin-core/src/rsbuild/virtual-modules.ts new file mode 100644 index 0000000000..c5e28e96c7 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/virtual-modules.ts @@ -0,0 +1,642 @@ +import { VIRTUAL_MODULES } from '@tanstack/start-server-core/virtual-modules' +import { generateSerializationAdaptersModule } from '../serialization-adapters-module' +import { generateServerFnResolverModule } from '../start-compiler/server-fn-resolver-module' +import { buildStartManifest } from '../start-manifest-plugin/manifestBuilder' +import { escapeRegExp } from '../utils' +import { RSBUILD_ENVIRONMENT_NAMES } from './planning' +import type { + RsbuildPluginAPI, + rspack as rspackNamespaceType, +} from '@rsbuild/core' +import type { + GetConfigFn, + NormalizedClientBuild, + SerializationAdapterConfig, +} from '../types' +import type { InlineCssOptions } from '../start-manifest-plugin/manifestBuilder' +import type { ServerFn } from '../start-compiler/types' +import type { ScriptFormat } from '@tanstack/router-core' + +type RspackNamespace = typeof rspackNamespaceType +type RspackVirtualModulesPlugin = InstanceType< + RspackNamespace['experiments']['VirtualModulesPlugin'] +> + +// Virtual module IDs for RSC (must match what react-start-rsc imports) +const RSC_RUNTIME_VIRTUAL_ID = 'virtual:tanstack-rsc-runtime' +const RSC_HMR_VIRTUAL_ID = 'virtual:tanstack-rsc-hmr' +const RSC_BROWSER_DECODE_VIRTUAL_ID = 'virtual:tanstack-rsc-browser-decode' +const RSC_SSR_DECODE_VIRTUAL_ID = 'virtual:tanstack-rsc-ssr-decode' +export const START_MANIFEST_PLACEHOLDER = '__TSS_START_MANIFEST_PLACEHOLDER__' +/** + * VirtualModulesPlugin resolves module paths relative to compiler.context. + * Prefix them under the app root so they are unique and watcher-friendly. + */ +function virtualPath(root: string, moduleId: string): string { + // VirtualModulesPlugin resolves paths relative to compiler.context (root). + // Use a recognizable prefix to avoid collisions with real files. + const sanitized = moduleId.replace(/[:#]/g, '_') + return `${root}/node_modules/.virtual/${sanitized}.js` +} + +export interface VirtualModuleState { + /** Call to update manifest content after client build completes */ + updateManifest: (clientBuild: NormalizedClientBuild) => void + /** Number of times the dev manifest module was written */ + getDevManifestWriteCount: () => number + /** Call to update server fn resolver content after compilation discovers fns */ + updateServerFnResolver: () => void + /** Write explicit server resolver content; queues if env not ready */ + tryUpdateServerFnResolver: (content: string) => void + /** Number of times the server fn resolver was written for an environment */ + getServerFnResolverWriteCount: (environmentName: string) => number + /** Get the virtual path for a given module ID */ + getVirtualPath: (moduleId: string) => string + /** Generate resolver module content from current serverFnsById state. + * When forProvider=true, generates without isClientReferenced checks (RSC layer). */ + generateCurrentResolverContent: (forProvider?: boolean) => string + /** The absolute virtual path of the server fn resolver module */ + serverFnResolverPath: string + /** The absolute virtual path of the manifest module */ + manifestPath: string + /** Generate manifest module content from a given client build */ + generateManifestContent: (clientBuild: NormalizedClientBuild) => string + /** Generate the serialized manifest value literal for asset patching */ + generateManifestValueLiteral: (clientBuild: NormalizedClientBuild) => string + /** VirtualModulesPlugin instances keyed by environment name */ + vmPlugins: Record +} + +// --------------------------------------------------------------------------- +// Manifest module codegen +// --------------------------------------------------------------------------- + +function getScriptFormatProperty(scriptFormat: ScriptFormat): string { + return scriptFormat === 'iife' ? ` scriptFormat: 'iife',\n` : '' +} + +function getEntryScriptAttrs( + entryUrl: string, + scriptFormat: ScriptFormat, +): string { + return scriptFormat === 'module' + ? `{ type: 'module', async: true, src: '${entryUrl}' }` + : `{ async: true, src: '${entryUrl}' }` +} + +/** + * Dev manifest used until the first client build completes. The server bundle + * may run outside the build process (e.g. in workerd), so the real manifest is + * written into this module rather than shared through build-process globals. + */ +function generateFallbackManifestModuleDev( + devClientEntryUrl: string, + scriptFormat: ScriptFormat, +): string { + const scriptFormatProperty = getScriptFormatProperty(scriptFormat) + return `export const tsrStartManifest = () => ({ +${scriptFormatProperty} routes: { + __root__: { + preloads: ['${devClientEntryUrl}'], + scripts: [{ attrs: ${getEntryScriptAttrs(devClientEntryUrl, scriptFormat)} }], + }, + }, +})` +} + +function serializeStartManifestData( + clientBuild: NormalizedClientBuild, + publicBase: string, + inlineCss: InlineCssOptions, + scriptFormat: ScriptFormat, +): string { + return JSON.stringify( + buildStartManifest({ + clientBuild, + routeTreeRoutes: globalThis.TSS_ROUTES_MANIFEST, + basePath: publicBase, + inlineCss, + scriptFormat, + }), + ) +} + +function generateManifestModuleBuild( + clientBuild: NormalizedClientBuild | undefined, + publicBase: string, + _devClientEntryUrl: string, + inlineCss: InlineCssOptions, + scriptFormat: ScriptFormat, +): string { + if (!clientBuild) { + return `const tsrStartManifestData = ${JSON.stringify(START_MANIFEST_PLACEHOLDER)} +export const tsrStartManifest = () => tsrStartManifestData` + } + + return `export const tsrStartManifest = () => (${serializeStartManifestData(clientBuild, publicBase, inlineCss, scriptFormat)})` +} + +/** + * Generate virtual:tanstack-rsc-runtime content. + * In the RSC layer this re-exports from react-server-dom-rspack/server. + * In other layers it provides stubs that throw. + */ +function generateRscRuntimeModule(isRscLayer: boolean): string { + if (isRscLayer) { + // Re-export the RSC runtime functions from react-server-dom-rspack/server. + // NOTE: `createFromReadableStream` is a CLIENT-side API — it's NOT exported + // by react-server-dom-rspack/server. The RSC layer never needs it (RSC + // renders TO streams, doesn't decode FROM them). We provide a stub that + // throws so the export surface stays consistent across bundlers. + return `export { renderToReadableStream, createTemporaryReferenceSet, decodeReply, decodeAction, decodeFormState } from 'react-server-dom-rspack/server' +export function createFromReadableStream() { throw new Error('createFromReadableStream is not available in RSC environment (use SSR or browser decode instead)'); } +// loadServerAction is provided by the RSC entry, not react-server-dom-rspack +import { getServerFnById } from '#tanstack-start-server-fn-resolver' +export const loadServerAction = async (id) => getServerFnById(id, { origin: 'server' })` + } + + // In other layers, provide stubs that throw + return ` +export function renderToReadableStream() { throw new Error('renderToReadableStream can only be used in RSC environment'); } +export function createFromReadableStream() { throw new Error('createFromReadableStream can only be used in RSC environment'); } +export function createTemporaryReferenceSet() { throw new Error('createTemporaryReferenceSet can only be used in RSC environment'); } +export function decodeReply() { throw new Error('decodeReply can only be used in RSC environment'); } +export function loadServerAction() { throw new Error('loadServerAction can only be used in RSC environment'); } +export function decodeAction() { throw new Error('decodeAction can only be used in RSC environment'); } +export function decodeFormState() { throw new Error('decodeFormState can only be used in RSC environment'); } +` +} + +/** + * Generate virtual:tanstack-rsc-hmr content. + * In the client env during dev, listens for rsc:update WebSocket events + * and invalidates the router. In all other contexts, exports nothing. + */ +function generateRscHmrModule(isClientEnv: boolean, isDev: boolean): string { + if (!isClientEnv || !isDev) { + return 'export function setupRscHmr() {}' + } + + // Rsbuild dev server delivers custom WebSocket events through + // import.meta.webpackHot.on(event, cb). The server-side + // sockWrite('custom', { event: 'rsc:update' }) maps directly to that. + return ` +// RSC HMR listener for rsbuild dev server +// Listens for 'rsc:update' custom events sent via sockWrite +export function setupRscHmr() { + let __invalidateQueued = false + + function __queueInvalidate() { + if (__invalidateQueued) return + __invalidateQueued = true + queueMicrotask(async () => { + __invalidateQueued = false + try { + const router = window.__TSR_ROUTER__ + if (!router) { + console.warn('[rsc:hmr] No router found on window.__TSR_ROUTER__') + return + } + await router.invalidate() + } catch (e) { + console.warn('[rsc:hmr] Failed to invalidate router:', e) + } + }) + } + + if (import.meta.webpackHot) { + import.meta.webpackHot.on('rsc:update', () => { + __queueInvalidate() + }) + } +} +` +} + +// --------------------------------------------------------------------------- +// Main registration +// --------------------------------------------------------------------------- + +export interface RegisterVirtualModulesOptions { + /** The resolved project root (read when the first Rspack config is built, after `modifyRsbuildConfig`). */ + getRoot: () => string + getConfig: GetConfigFn + serverFnsById: Record + providerEnvName: string + ssrIsProvider: boolean + serializationAdapters: Array | undefined + /** + * Get the URL at which the rsbuild dev server serves the client entry JS. + * Called lazily inside modifyRspackConfig when getConfig() is available. + * Example return: '/assets/js/index.js' + */ + getDevClientEntryUrl: (publicBase: string) => string + /** Whether RSC virtual modules should be registered. */ + rscEnabled?: boolean | undefined + scriptFormat: ScriptFormat +} + +/** + * Registers virtual modules for the rsbuild adapter using VirtualModulesPlugin. + * + * Creates one VirtualModulesPlugin per environment and registers them via + * `modifyBundlerChain`. Provides update functions to refresh content dynamically. + */ +export function registerVirtualModules( + api: RsbuildPluginAPI, + opts: RegisterVirtualModulesOptions, +): VirtualModuleState { + const isDev = api.context.action === 'dev' + // Virtual module paths keyed by module ID, under the resolved root (never `process.cwd()`) + let resolvedPaths: + | { + manifest: string + serverFnResolver: string + pluginAdapters: string + rsc: { + rscRuntime: string + rscHmr: string + rscBrowserDecode: string + rscSsrDecode: string + } | null + } + | undefined + const pathsOf = () => { + if (!resolvedPaths) { + const root = opts.getRoot() + resolvedPaths = { + manifest: virtualPath(root, VIRTUAL_MODULES.startManifest), + serverFnResolver: virtualPath(root, VIRTUAL_MODULES.serverFnResolver), + pluginAdapters: virtualPath(root, VIRTUAL_MODULES.pluginAdapters), + rsc: opts.rscEnabled + ? { + rscRuntime: virtualPath(root, RSC_RUNTIME_VIRTUAL_ID), + rscHmr: virtualPath(root, RSC_HMR_VIRTUAL_ID), + rscBrowserDecode: virtualPath( + root, + RSC_BROWSER_DECODE_VIRTUAL_ID, + ), + rscSsrDecode: virtualPath(root, RSC_SSR_DECODE_VIRTUAL_ID), + } + : null, + } + } + return resolvedPaths + } + + // Track VirtualModulesPlugin instances per environment for dynamic updates + const vmPlugins: Record = {} + const readyVmPlugins: Record = {} + const pendingWrites = new Map>() + + let clientBuild: NormalizedClientBuild | undefined + let lastDevManifestContent: string | undefined + let devManifestWriteCount = 0 + const lastResolverContentByEnvironment: Record = + {} + const resolverWriteCountByEnvironment: Record = {} + const hasSeparateProviderEnvironment = + !opts.rscEnabled && + opts.providerEnvName !== RSBUILD_ENVIRONMENT_NAMES.server + const hasSerializationAdapters = Boolean(opts.serializationAdapters?.length) + + function isProviderEnvironment(environmentName: string): boolean { + return environmentName === opts.providerEnvName + } + + function needsServerFnResolver(environmentName: string): boolean { + return ( + environmentName === RSBUILD_ENVIRONMENT_NAMES.server || + (hasSeparateProviderEnvironment && isProviderEnvironment(environmentName)) + ) + } + + function generateResolverContent(environmentName: string): string { + return generateServerFnResolverModule({ + serverFnsById: opts.serverFnsById, + includeClientReferencedCheck: !isProviderEnvironment(environmentName), + useStaticImports: Boolean(opts.rscEnabled && isDev), + memoizeModules: !isDev, + }) + } + + function writeResolverContent(environmentName: string, content: string) { + if ( + !isDev || + content !== lastResolverContentByEnvironment[environmentName] + ) { + lastResolverContentByEnvironment[environmentName] = content + resolverWriteCountByEnvironment[environmentName] = + (resolverWriteCountByEnvironment[environmentName] ?? 0) + 1 + tryWriteModule(environmentName, pathsOf().serverFnResolver, content) + } + } + + function queuePendingWrite( + environmentName: string, + filePath: string, + content: string, + ) { + let writes = pendingWrites.get(environmentName) + if (!writes) { + writes = new Map() + pendingWrites.set(environmentName, writes) + } + writes.set(filePath, content) + } + + function tryWriteModule( + environmentName: string, + filePath: string, + content: string, + ) { + const vmPlugin = vmPlugins[environmentName] + if (!vmPlugin || !readyVmPlugins[environmentName]) { + queuePendingWrite(environmentName, filePath, content) + return false + } + + vmPlugin.writeModule(filePath, content) + return true + } + + function flushPendingWrites(environmentName: string) { + if (!readyVmPlugins[environmentName]) { + return + } + + const writes = pendingWrites.get(environmentName) + if (!writes?.size) { + return + } + + for (const [filePath, content] of writes) { + if (!tryWriteModule(environmentName, filePath, content)) { + return + } + writes.delete(filePath) + } + + if (writes.size === 0) { + pendingWrites.delete(environmentName) + } + } + + // NOTE: getConfig() is deferred — it must NOT be called until modifyRsbuildConfig + // has resolved (which sets resolvedStartConfig.root). All access to resolvedStartConfig + // happens inside modifyRspackConfig (which runs after modifyRsbuildConfig) or + // inside update callbacks (which run even later during/after compilation). + + // Generate initial content for each virtual module per environment + function getInitialContent(environmentName: string): Record { + // Safe to call getConfig() here — this runs inside modifyRspackConfig + const { resolvedStartConfig, startConfig } = opts.getConfig() + const paths = pathsOf() + const rscPaths = paths.rsc + const isServerEnv = environmentName === RSBUILD_ENVIRONMENT_NAMES.server + const isClientEnv = environmentName === RSBUILD_ENVIRONMENT_NAMES.client + const content: Record = {} + + // Manifest — only meaningful for server env + if (isServerEnv) { + const devClientEntryUrl = opts.getDevClientEntryUrl( + resolvedStartConfig.basePaths.publicBase, + ) + content[paths.manifest] = isDev + ? generateFallbackManifestModuleDev( + devClientEntryUrl, + opts.scriptFormat, + ) + : generateManifestModuleBuild( + clientBuild, + resolvedStartConfig.basePaths.publicBase, + devClientEntryUrl, + startConfig.server.build.inlineCss, + opts.scriptFormat, + ) + } else { + content[paths.manifest] = 'export default {}' + } + + // Server fn resolver — SSR and provider environments + if (needsServerFnResolver(environmentName)) { + content[paths.serverFnResolver] = generateResolverContent(environmentName) + } else { + // Client doesn't need the resolver but needs a valid module + content[paths.serverFnResolver] = 'export {}' + } + + if (hasSerializationAdapters) { + // Plugin adapters — both environments get environment-specific content + content[paths.pluginAdapters] = generateSerializationAdaptersModule({ + adapters: opts.serializationAdapters, + runtime: + environmentName === RSBUILD_ENVIRONMENT_NAMES.client + ? 'client' + : 'server', + }) + } + + // --- RSC virtual modules --- + if (rscPaths) { + // virtual:tanstack-rsc-runtime + // In the server env, this provides the RSC runtime for the RSC layer. + // The virtual module content is the same regardless of layer since + // rspack layers handle module isolation. The RSC entry imports this + // and the react-server condition on the RSC layer resolves + // react-server-dom-rspack/server correctly. + if (isServerEnv) { + // Server env gets the real RSC runtime (used by RSC layer) + content[rscPaths.rscRuntime] = generateRscRuntimeModule(true) + } else { + // Client env gets stubs + content[rscPaths.rscRuntime] = generateRscRuntimeModule(false) + } + + // virtual:tanstack-rsc-hmr + content[rscPaths.rscHmr] = generateRscHmrModule(isClientEnv, isDev) + content[rscPaths.rscBrowserDecode] = isClientEnv + ? `export * from '@tanstack/react-start/rsbuild/browser-decode'` + : `export function createFromReadableStream() { throw new Error('RSC browser decode is only available in the client environment') } +export function createFromFetch() { throw new Error('RSC browser decode is only available in the client environment') }` + content[rscPaths.rscSsrDecode] = isServerEnv + ? `export { setOnClientReference, createFromReadableStream } from '@tanstack/react-start/rsbuild/ssr-decode'` + : `export function setOnClientReference() {} +export function createFromReadableStream() { throw new Error('RSC SSR decode is only available in the server environment') }` + } + + return content + } + + // Build a map from virtual module IDs to their virtual file paths. + // Scheme-like IDs are rewritten with NormalModuleReplacementPlugin because + // rspack validates request schemes before normal alias resolution. + const aliasMapOf = (): Record => { + const paths = pathsOf() + const aliasMap: Record = { + [VIRTUAL_MODULES.startManifest]: paths.manifest, + [VIRTUAL_MODULES.serverFnResolver]: paths.serverFnResolver, + } + if (hasSerializationAdapters) { + aliasMap[VIRTUAL_MODULES.pluginAdapters] = paths.pluginAdapters + } + if (paths.rsc) { + aliasMap[RSC_RUNTIME_VIRTUAL_ID] = paths.rsc.rscRuntime + aliasMap[RSC_HMR_VIRTUAL_ID] = paths.rsc.rscHmr + aliasMap[RSC_BROWSER_DECODE_VIRTUAL_ID] = paths.rsc.rscBrowserDecode + aliasMap[RSC_SSR_DECODE_VIRTUAL_ID] = paths.rsc.rscSsrDecode + } + return aliasMap + } + + // Register VirtualModulesPlugin per environment via modifyRspackConfig + api.modifyRspackConfig((config, utils) => { + const envName = utils.environment.name + const initialContent = getInitialContent(envName) + + // Create VirtualModulesPlugin instance + const VMP = utils.rspack.experiments.VirtualModulesPlugin + const vmPlugin = new VMP(initialContent) + vmPlugins[envName] = vmPlugin + readyVmPlugins[envName] = false + config.plugins.push(vmPlugin) + config.plugins.push({ + apply(compiler: { + hooks: { + thisCompilation: { tap: (name: string, handler: () => void) => void } + } + }) { + compiler.hooks.thisCompilation.tap( + 'TanStackStartFlushPendingVirtualModules', + () => { + readyVmPlugins[envName] = true + flushPendingWrites(envName) + }, + ) + }, + }) + + // Rewrite scheme-like IDs to the VirtualModulesPlugin-backed file paths. + const aliasMap = aliasMapOf() + for (const [moduleId, virtualFilePath] of Object.entries(aliasMap)) { + const NMR = utils.rspack.NormalModuleReplacementPlugin + config.plugins.push( + new NMR(new RegExp(`^${escapeRegExp(moduleId)}$`), virtualFilePath), + ) + } + + const resolve = config.resolve + const resolveAlias = (resolve.alias ??= {}) as Record + for (const [moduleId, virtualFilePath] of Object.entries(aliasMap)) { + if (moduleId !== VIRTUAL_MODULES.startManifest) { + resolveAlias[moduleId] = virtualFilePath + } + } + }) + + return { + get serverFnResolverPath() { + return pathsOf().serverFnResolver + }, + get manifestPath() { + return pathsOf().manifest + }, + vmPlugins, + + generateCurrentResolverContent(forProvider?: boolean): string { + return generateResolverContent( + forProvider ? opts.providerEnvName : RSBUILD_ENVIRONMENT_NAMES.server, + ) + }, + + generateManifestContent(newClientBuild: NormalizedClientBuild): string { + const { resolvedStartConfig, startConfig } = opts.getConfig() + const devClientEntryUrl = opts.getDevClientEntryUrl( + resolvedStartConfig.basePaths.publicBase, + ) + return generateManifestModuleBuild( + newClientBuild, + resolvedStartConfig.basePaths.publicBase, + devClientEntryUrl, + !isDev + ? startConfig.server.build.inlineCss + : { enabled: false, transformAssets: false }, + opts.scriptFormat, + ) + }, + + generateManifestValueLiteral( + newClientBuild: NormalizedClientBuild, + ): string { + const { resolvedStartConfig, startConfig } = opts.getConfig() + return serializeStartManifestData( + newClientBuild, + resolvedStartConfig.basePaths.publicBase, + !isDev + ? startConfig.server.build.inlineCss + : { enabled: false, transformAssets: false }, + opts.scriptFormat, + ) + }, + + updateManifest(newClientBuild: NormalizedClientBuild) { + clientBuild = newClientBuild + if (!isDev) { + return + } + + // Safe to call getConfig() here — runs after client build + const { resolvedStartConfig } = opts.getConfig() + const content = `export const tsrStartManifest = () => (${serializeStartManifestData( + clientBuild, + resolvedStartConfig.basePaths.publicBase, + { enabled: false, transformAssets: false }, + opts.scriptFormat, + )})` + // Only rewrite on change: each write rebuilds the server environment. + if (content !== lastDevManifestContent) { + lastDevManifestContent = content + devManifestWriteCount++ + tryWriteModule( + RSBUILD_ENVIRONMENT_NAMES.server, + pathsOf().manifest, + content, + ) + } + }, + + updateServerFnResolver() { + const updateEnvironment = (environmentName: string) => { + if (!needsServerFnResolver(environmentName)) { + return + } + + writeResolverContent( + environmentName, + generateResolverContent(environmentName), + ) + } + + updateEnvironment(RSBUILD_ENVIRONMENT_NAMES.server) + if (hasSeparateProviderEnvironment) { + updateEnvironment(opts.providerEnvName) + } + }, + + tryUpdateServerFnResolver(content: string) { + writeResolverContent(RSBUILD_ENVIRONMENT_NAMES.server, content) + }, + + getDevManifestWriteCount(): number { + return devManifestWriteCount + }, + + getServerFnResolverWriteCount(environmentName: string): number { + return resolverWriteCountByEnvironment[environmentName] ?? 0 + }, + + getVirtualPath(moduleId: string): string { + return virtualPath(opts.getRoot(), moduleId) + }, + } +} diff --git a/packages/start-plugin-core/src/rsbuild/watch-ignored.ts b/packages/start-plugin-core/src/rsbuild/watch-ignored.ts new file mode 100644 index 0000000000..e5b85f5e04 --- /dev/null +++ b/packages/start-plugin-core/src/rsbuild/watch-ignored.ts @@ -0,0 +1,24 @@ +import { escapeRegExp } from '../utils' +import type { Rspack } from '@rsbuild/core' + +type WatchIgnored = NonNullable['ignored'] + +export function addWorkspaceWatchIgnored( + ignored: WatchIgnored, + directories: Array, +): WatchIgnored { + const workspace = new RegExp( + directories.map((path) => `^${escapeRegExp(path)}(?:[\\\\/]|$)`).join('|'), + ) + if (typeof ignored === 'function') { + return (entry) => ignored(entry) || workspace.test(entry) + } + if (typeof ignored === 'string') { + return [ignored, ...directories] + } + if (Array.isArray(ignored)) { + return [...ignored, ...directories] + } + const original = ignored ?? /[\\/](?:\.git|node_modules)[\\/]/ + return new RegExp(`${original.source}|${workspace.source}`, original.flags) +} diff --git a/packages/start-plugin-core/src/schema.ts b/packages/start-plugin-core/src/schema.ts index 7dec32effd..413ac4673f 100644 --- a/packages/start-plugin-core/src/schema.ts +++ b/packages/start-plugin-core/src/schema.ts @@ -1,17 +1,67 @@ import path from 'node:path' import { z } from 'zod' import { configSchema, getConfig } from '@tanstack/router-plugin' -import type { TanStackStartVitePluginCoreOptions } from './plugin' +import type { CompileStartFrameworkOptions } from './types' const tsrConfig = configSchema - .omit({ autoCodeSplitting: true, target: true, verboseFileRoutes: true }) + .omit({ autoCodeSplitting: true, target: true }) .partial() +// --- Import Protection Schema --- + +const patternSchema = z.union([z.string(), z.instanceof(RegExp)]) + +const importProtectionBehaviorSchema = z.enum(['error', 'mock']) + +const importProtectionEnvRulesSchema = z.object({ + specifiers: z.array(patternSchema).optional(), + files: z.array(patternSchema).optional(), + excludeFiles: z.array(patternSchema).optional(), +}) + +const importProtectionOptionsSchema = z + .object({ + enabled: z.boolean().optional(), + behavior: z + .union([ + importProtectionBehaviorSchema, + z.object({ + dev: importProtectionBehaviorSchema.optional(), + build: importProtectionBehaviorSchema.optional(), + }), + ]) + .optional(), + /** + * In `behavior: 'mock'`, control whether mocked imports emit a runtime + * console diagnostic when accessed. + * + * - 'error': console.error(new Error(...)) (default) + * - 'warn': console.warn(new Error(...)) + * - 'off': disable runtime diagnostics + */ + mockAccess: z.enum(['error', 'warn', 'off']).optional(), + onViolation: z + .custom< + (violation: unknown) => boolean | void | Promise + >((value) => typeof value === 'function') + .optional(), + include: z.array(patternSchema).optional(), + exclude: z.array(patternSchema).optional(), + client: importProtectionEnvRulesSchema.optional(), + server: importProtectionEnvRulesSchema.optional(), + ignoreImporters: z.array(patternSchema).optional(), + maxTraceDepth: z.number().optional(), + log: z.enum(['once', 'always']).optional(), + }) + .optional() + export function parseStartConfig( opts: z.input, - corePluginOpts: TanStackStartVitePluginCoreOptions, + corePluginOpts: { framework: CompileStartFrameworkOptions }, root: string, ) { + const rawOptions = opts ?? {} + const rawRouterOptions = rawOptions.router ?? {} const options = tanstackStartOptionsSchema.parse(opts) const srcDirectory = options.srcDirectory @@ -19,13 +69,13 @@ export function parseStartConfig( const routesDirectory = path.resolve( root, srcDirectory, - options.router.routesDirectory ?? 'routes', + rawRouterOptions.routesDirectory ?? 'routes', ) const generatedRouteTree = path.resolve( root, srcDirectory, - options.router.generatedRouteTree ?? 'routeTree.gen.ts', + rawRouterOptions.generatedRouteTree ?? 'routeTree.gen.ts', ) return { @@ -81,7 +131,7 @@ const pageSitemapOptionsSchema = z.object({ .optional(), }) -const pageBaseSchema = z.object({ +export const pageBaseSchema = z.object({ path: z.string(), sitemap: pageSitemapOptionsSchema.optional(), fromCrawl: z.boolean().optional(), @@ -95,14 +145,12 @@ const pagePrerenderOptionsSchema = z.object({ retryCount: z.number().optional(), retryDelay: z.number().optional(), onSuccess: z - .function() - .args( - z.object({ - page: pageBaseSchema, - html: z.string(), - }), - ) - .returns(z.any()) + .custom< + (result: { + page: z.infer + html: string + }) => unknown + >((value) => typeof value === 'function') .optional(), headers: z.record(z.string(), z.string()).optional(), }) @@ -112,7 +160,7 @@ const spaSchema = z.object({ maskPath: z.string().optional().default('/'), prerender: pagePrerenderOptionsSchema .optional() - .default({}) + .prefault({}) .transform((opts) => ({ outputPath: opts.outputPath ?? '/_shell', crawlLinks: false, @@ -122,86 +170,154 @@ const spaSchema = z.object({ })), }) +const inlineCssSchema = z + .union([ + z.boolean(), + z.object({ + /** + * Inline route CSS into the server-rendered HTML response. + * + * @experimental This option is experimental! + */ + enabled: z.boolean().optional().default(true), + /** + * Emit build-time templates that allow `transformAssets` to rewrite + * `url(...)` references inside inlined CSS at runtime. + */ + transformAssets: z.boolean().optional().default(false), + }), + ]) + .optional() + .default(false) + .transform((value) => { + if (typeof value === 'boolean') { + return { enabled: value, transformAssets: false } + } + + return value + }) + +export type InlineCssInputOptions = z.input + const pageSchema = pageBaseSchema.extend({ prerender: pagePrerenderOptionsSchema.optional(), }) -const tanstackStartOptionsSchema = z - .object({ - srcDirectory: z.string().optional().default('src'), - start: z - .object({ - entry: z.string().optional(), - }) - .optional() - .default({}), - router: z - .object({ - entry: z.string().optional(), - basepath: z.string().optional(), - }) - .and(tsrConfig.optional().default({})) - .optional() - .default({}), - client: z - .object({ - entry: z.string().optional(), - base: z.string().optional().default('/_build'), - }) - .optional() - .default({}), - server: z - .object({ - entry: z.string().optional(), - }) - .optional() - .default({}), - serverFns: z - .object({ - base: z.string().optional().default('/_serverFn'), - generateFunctionId: z - .function() - .args( - z.object({ - filename: z.string(), - functionName: z.string(), - }), - ) - .returns(z.string().optional()) - .optional(), - }) - .optional() - .default({}), - pages: z.array(pageSchema).optional().default([]), - sitemap: z - .object({ - enabled: z.boolean().optional().default(true), - host: z.string().optional(), - outputPath: z.string().optional().default('sitemap.xml'), - }) - .optional(), - prerender: z - .object({ - enabled: z.boolean().optional(), - concurrency: z.number().optional(), - filter: z.function().args(pageSchema).returns(z.any()).optional(), - failOnError: z.boolean().optional(), - autoStaticPathsDiscovery: z.boolean().optional(), - maxRedirects: z.number().min(0).optional(), - }) - .and(pagePrerenderOptionsSchema.optional()) - .optional(), - spa: spaSchema.optional(), - vite: z - .object({ installDevServerMiddleware: z.boolean().optional() }) - .optional(), - }) - .optional() - .default({}) +export const tanstackStartOptionsObjectSchema = z.object({ + srcDirectory: z.string().optional().default('src'), + start: z + .object({ + entry: z.string().optional(), + }) + .optional() + .prefault({}), + router: z + .object({ + entry: z.string().optional(), + basepath: z.string().optional(), + }) + .and(tsrConfig.optional().prefault({})) + .optional() + .prefault({}), + client: z + .object({ + entry: z.string().optional(), + base: z.string().optional().default('/_build'), + }) + .optional() + .prefault({}), + server: z + .object({ + entry: z.string().optional(), + build: z + .object({ + staticNodeEnv: z.boolean().optional().default(true), + /** + * Inline route CSS into the server-rendered HTML response. + * + * @experimental This option is experimental! + */ + inlineCss: inlineCssSchema, + }) + .optional() + .prefault({}), + }) + .optional() + .prefault({}), + serverFns: z + .object({ + base: z.string().optional().default('/_serverFn'), + disableCsrfMiddlewareWarning: z.boolean().optional().default(false), + generateFunctionId: z + .custom< + (opts: { + filename: string + functionName: string + }) => string | undefined + >((value) => typeof value === 'function') + .optional(), + }) + .optional() + .prefault({}), + pages: z.array(pageSchema).optional().default([]), + sitemap: z + .object({ + enabled: z.boolean().optional().default(true), + host: z.string().optional(), + outputPath: z.string().optional().default('sitemap.xml'), + }) + .optional(), + prerender: z + .object({ + enabled: z.boolean().optional(), + concurrency: z.number().optional(), + filter: z + .custom< + (page: z.infer) => unknown + >((value) => typeof value === 'function') + .optional(), + failOnError: z.boolean().optional(), + autoStaticPathsDiscovery: z.boolean().optional(), + maxRedirects: z.number().min(0).optional(), + }) + .and(pagePrerenderOptionsSchema.optional()) + .optional(), + dev: z + .object({ + ssrStyles: z + .object({ + enabled: z.boolean().optional().default(true), + basepath: z.string().optional(), + }) + .optional() + .prefault({}), + }) + .optional() + .prefault({}), + spa: spaSchema.optional(), + importProtection: importProtectionOptionsSchema, +}) +export const tanstackStartOptionsSchema = tanstackStartOptionsObjectSchema + .optional() + .prefault({}) + +export type PageBase = z.infer export type Page = z.infer -export type TanStackStartInputConfig = z.input< - typeof tanstackStartOptionsSchema +type TanStackStartOptionsInput = NonNullable< + z.input > + +export type TanStackStartInputConfig = TanStackStartOptionsInput export type TanStackStartOutputConfig = ReturnType + +export type ImportProtectionBehavior = z.infer< + typeof importProtectionBehaviorSchema +> +export type ImportProtectionEnvRules = z.infer< + typeof importProtectionEnvRulesSchema +> +export type ImportProtectionOptions = z.input< + typeof importProtectionOptionsSchema +> diff --git a/packages/start-plugin-core/src/serialization-adapters-module.ts b/packages/start-plugin-core/src/serialization-adapters-module.ts new file mode 100644 index 0000000000..39813b3e02 --- /dev/null +++ b/packages/start-plugin-core/src/serialization-adapters-module.ts @@ -0,0 +1,82 @@ +import type { SerializationAdapterConfig } from './types' + +export const EMPTY_SERIALIZATION_ADAPTERS_MODULE = `export const pluginSerializationAdapters = [] +export const hasPluginAdapters = false` + +interface ResolvedAdapterModule { + module: string + export: string + isFactory: boolean + index: number +} + +export function resolveSerializationAdaptersForRuntime(opts: { + adapters: Array | undefined + runtime: 'client' | 'server' +}): Array { + if (!opts.adapters?.length) { + return [] + } + + const resolvedAdapters: Array = [] + + for (let i = 0; i < opts.adapters.length; i++) { + const adapter = opts.adapters[i]! + + if ('module' in adapter) { + resolvedAdapters.push({ + module: adapter.module, + export: adapter.export, + isFactory: adapter.isFactory ?? true, + index: i, + }) + continue + } + + const runtimeAdapter = + opts.runtime === 'client' ? adapter.client : adapter.server + + if (!runtimeAdapter) { + continue + } + + resolvedAdapters.push({ + module: runtimeAdapter.module, + export: runtimeAdapter.export, + isFactory: runtimeAdapter.isFactory ?? true, + index: i, + }) + } + + return resolvedAdapters +} + +export function generateSerializationAdaptersModule(opts: { + adapters: Array | undefined + runtime: 'client' | 'server' +}): string { + const resolvedAdapters = resolveSerializationAdaptersForRuntime(opts) + + if (resolvedAdapters.length === 0) { + return EMPTY_SERIALIZATION_ADAPTERS_MODULE + } + + const imports = resolvedAdapters + .map( + (adapter) => + `import { ${adapter.export} as adapter${adapter.index} } from '${adapter.module}'`, + ) + .join('\n') + + const items = resolvedAdapters + .map((adapter) => + adapter.isFactory + ? `...(Array.isArray(adapter${adapter.index}()) ? adapter${adapter.index}() : [adapter${adapter.index}()])` + : `adapter${adapter.index}`, + ) + .join(', ') + + return `${imports} +export const pluginSerializationAdapters = [${items}] +export const hasPluginAdapters = true` +} diff --git a/packages/start-plugin-core/src/start-compiler-plugin/compilers.ts b/packages/start-plugin-core/src/start-compiler-plugin/compilers.ts deleted file mode 100644 index a23583574c..0000000000 --- a/packages/start-plugin-core/src/start-compiler-plugin/compilers.ts +++ /dev/null @@ -1,187 +0,0 @@ -import * as babel from '@babel/core' -import * as t from '@babel/types' - -import { - deadCodeElimination, - findReferencedIdentifiers, -} from 'babel-dead-code-elimination' -import { generateFromAst, parseAst } from '@tanstack/router-utils' -import { handleCreateMiddleware } from '../create-server-fn-plugin/handleCreateMiddleware' -import { transformFuncs } from './constants' -import { handleCreateIsomorphicFnCallExpression } from './isomorphicFn' -import { - handleCreateClientOnlyFnCallExpression, - handleCreateServerOnlyFnCallExpression, -} from './envOnly' -import type { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils' - -export type CompileStartFrameworkOptions = 'react' | 'solid' | 'vue' - -type Identifiers = { [K in (typeof transformFuncs)[number]]: IdentifierConfig } - -export function compileStartOutputFactory( - framework: CompileStartFrameworkOptions, -) { - return function compileStartOutput(opts: CompileOptions): GeneratorResult { - const identifiers: Partial = { - createServerOnlyFn: { - name: 'createServerOnlyFn', - handleCallExpression: handleCreateServerOnlyFnCallExpression, - paths: [], - }, - createClientOnlyFn: { - name: 'createClientOnlyFn', - handleCallExpression: handleCreateClientOnlyFnCallExpression, - paths: [], - }, - createIsomorphicFn: { - name: 'createIsomorphicFn', - handleCallExpression: handleCreateIsomorphicFnCallExpression, - paths: [], - }, - } - - // createMiddleware only performs modifications in the client environment - // so we can avoid executing this on the server - if (opts.env === 'client') { - identifiers.createMiddleware = { - name: 'createMiddleware', - handleCallExpression: handleCreateMiddleware, - paths: [], - } - } - - const ast = parseAst(opts) - - const doDce = opts.dce ?? true - // find referenced identifiers *before* we transform anything - const refIdents = doDce ? findReferencedIdentifiers(ast) : undefined - - const validImportSources = [ - `@tanstack/${framework}-start`, - '@tanstack/start-client-core', - ] - babel.traverse(ast, { - Program: { - enter(programPath) { - programPath.traverse({ - ImportDeclaration: (path) => { - if (!validImportSources.includes(path.node.source.value)) { - return - } - - // handle a destructured imports being renamed like "import { createServerFn as myCreateServerFn } from '@tanstack/react-start';" - path.node.specifiers.forEach((specifier) => { - transformFuncs.forEach((identifierKey) => { - const identifier = identifiers[identifierKey] - if (!identifier) { - return - } - if ( - specifier.type === 'ImportSpecifier' && - specifier.imported.type === 'Identifier' - ) { - if (specifier.imported.name === identifierKey) { - identifier.name = specifier.local.name - } - } - - // handle namespace imports like "import * as TanStackStart from '@tanstack/react-start';" - if (specifier.type === 'ImportNamespaceSpecifier') { - identifier.name = `${specifier.local.name}.${identifierKey}` - } - }) - }) - }, - CallExpression: (path) => { - transformFuncs.forEach((identifierKey) => { - const identifier = identifiers[identifierKey] - if (!identifier) { - return - } - // Check to see if the call expression is a call to the - // identifiers[identifierKey].name - if ( - t.isIdentifier(path.node.callee) && - path.node.callee.name === identifier.name - ) { - // The identifier could be a call to the original function - // in the source code. If this is case, we need to ignore it. - // Check the scope to see if the identifier is a function declaration. - // if it is, then we can ignore it. - - if ( - path.scope.getBinding(identifier.name)?.path.node.type === - 'FunctionDeclaration' - ) { - return - } - - return identifier.paths.push(path) - } - - // handle namespace imports like "import * as TanStackStart from '@tanstack/react-start';" - // which are then called like "TanStackStart.createServerFn()" - if (t.isMemberExpression(path.node.callee)) { - if ( - t.isIdentifier(path.node.callee.object) && - t.isIdentifier(path.node.callee.property) - ) { - const callname = [ - path.node.callee.object.name, - path.node.callee.property.name, - ].join('.') - - if (callname === identifier.name) { - identifier.paths.push(path) - } - } - } - - return - }) - }, - }) - - transformFuncs.forEach((identifierKey) => { - const identifier = identifiers[identifierKey] - if (!identifier) { - return - } - identifier.paths.forEach((path) => { - identifier.handleCallExpression( - path as babel.NodePath, - opts, - ) - }) - }) - }, - }, - }) - - if (doDce) { - deadCodeElimination(ast, refIdents) - } - - return generateFromAst(ast, { - sourceMaps: true, - sourceFileName: opts.filename, - filename: opts.filename, - }) - } -} - -export type CompileOptions = ParseAstOptions & { - env: 'server' | 'client' - dce?: boolean - filename: string -} - -export type IdentifierConfig = { - name: string - handleCallExpression: ( - path: babel.NodePath, - opts: CompileOptions, - ) => void - paths: Array -} diff --git a/packages/start-plugin-core/src/start-compiler-plugin/constants.ts b/packages/start-plugin-core/src/start-compiler-plugin/constants.ts deleted file mode 100644 index 08f171d1e9..0000000000 --- a/packages/start-plugin-core/src/start-compiler-plugin/constants.ts +++ /dev/null @@ -1,6 +0,0 @@ -export const transformFuncs = [ - 'createServerOnlyFn', - 'createClientOnlyFn', - 'createIsomorphicFn', - 'createMiddleware', -] as const diff --git a/packages/start-plugin-core/src/start-compiler-plugin/envOnly.ts b/packages/start-plugin-core/src/start-compiler-plugin/envOnly.ts deleted file mode 100644 index c3c0a00f1c..0000000000 --- a/packages/start-plugin-core/src/start-compiler-plugin/envOnly.ts +++ /dev/null @@ -1,58 +0,0 @@ -import * as t from '@babel/types' -import type * as babel from '@babel/core' - -import type { CompileOptions } from './compilers' - -function capitalize(str: string) { - if (!str) return '' - return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase() -} - -function buildEnvOnlyCallExpressionHandler(env: 'client' | 'server') { - return function envOnlyCallExpressionHandler( - path: babel.NodePath, - opts: CompileOptions, - ) { - // if (debug) - // console.info(`Handling ${env}Only call expression:`, path.toString()) - - const isEnvMatch = - env === 'client' ? opts.env === 'client' : opts.env === 'server' - - if (isEnvMatch) { - // extract the inner function from the call expression - const innerInputExpression = path.node.arguments[0] - - if (!t.isExpression(innerInputExpression)) { - throw new Error( - `${env}Only() functions must be called with a function!`, - ) - } - - path.replaceWith(innerInputExpression) - return - } - - // If we're on the wrong environment, replace the call expression - // with a function that always throws an error. - path.replaceWith( - t.arrowFunctionExpression( - [], - t.blockStatement([ - t.throwStatement( - t.newExpression(t.identifier('Error'), [ - t.stringLiteral( - `create${capitalize(env)}OnlyFn() functions can only be called on the ${env}!`, - ), - ]), - ), - ]), - ), - ) - } -} - -export const handleCreateServerOnlyFnCallExpression = - buildEnvOnlyCallExpressionHandler('server') -export const handleCreateClientOnlyFnCallExpression = - buildEnvOnlyCallExpressionHandler('client') diff --git a/packages/start-plugin-core/src/start-compiler-plugin/isomorphicFn.ts b/packages/start-plugin-core/src/start-compiler-plugin/isomorphicFn.ts deleted file mode 100644 index b9b68e678a..0000000000 --- a/packages/start-plugin-core/src/start-compiler-plugin/isomorphicFn.ts +++ /dev/null @@ -1,78 +0,0 @@ -import * as t from '@babel/types' -import { getRootCallExpression } from './utils' -import type * as babel from '@babel/core' - -import type { CompileOptions } from './compilers' - -export function handleCreateIsomorphicFnCallExpression( - path: babel.NodePath, - opts: CompileOptions, -) { - const rootCallExpression = getRootCallExpression(path) - - // if (debug) - // console.info( - // 'Handling createIsomorphicFn call expression:', - // rootCallExpression.toString(), - // ) - - const callExpressionPaths = { - client: null as babel.NodePath | null, - server: null as babel.NodePath | null, - } - - const validMethods = Object.keys(callExpressionPaths) - - rootCallExpression.traverse({ - MemberExpression(memberExpressionPath) { - if (t.isIdentifier(memberExpressionPath.node.property)) { - const name = memberExpressionPath.node.property - .name as keyof typeof callExpressionPaths - - if ( - validMethods.includes(name) && - memberExpressionPath.parentPath.isCallExpression() - ) { - callExpressionPaths[name] = memberExpressionPath.parentPath - } - } - }, - }) - - if ( - validMethods.every( - (method) => - !callExpressionPaths[method as keyof typeof callExpressionPaths], - ) - ) { - const variableId = rootCallExpression.parentPath.isVariableDeclarator() - ? rootCallExpression.parentPath.node.id - : null - console.warn( - 'createIsomorphicFn called without a client or server implementation!', - 'This will result in a no-op function.', - 'Variable name:', - t.isIdentifier(variableId) ? variableId.name : 'unknown', - ) - } - - const envCallExpression = callExpressionPaths[opts.env] - - if (!envCallExpression) { - // if we don't have an implementation for this environment, default to a no-op - rootCallExpression.replaceWith( - t.arrowFunctionExpression([], t.blockStatement([])), - ) - return - } - - const innerInputExpression = envCallExpression.node.arguments[0] - - if (!t.isExpression(innerInputExpression)) { - throw new Error( - `createIsomorphicFn().${opts.env}(func) must be called with a function!`, - ) - } - - rootCallExpression.replaceWith(innerInputExpression) -} diff --git a/packages/start-plugin-core/src/start-compiler-plugin/plugin.ts b/packages/start-plugin-core/src/start-compiler-plugin/plugin.ts deleted file mode 100644 index 8d8ed6cd61..0000000000 --- a/packages/start-plugin-core/src/start-compiler-plugin/plugin.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { fileURLToPath, pathToFileURL } from 'node:url' -import { createRequire } from 'node:module' -import { logDiff } from '@tanstack/router-utils' - -import { VIRTUAL_MODULES } from '@tanstack/start-server-core' -import { normalizePath } from 'vite' -import path from 'pathe' -import { makeIdFiltersToMatchWithQuery } from '@rolldown/pluginutils' -import { TRANSFORM_ID_REGEX } from '../constants' -import { compileStartOutputFactory } from './compilers' -import { transformFuncs } from './constants' -import type { Plugin, PluginOption } from 'vite' -import type { CompileStartFrameworkOptions } from './compilers' - -const debug = - process.env.TSR_VITE_DEBUG && - ['true', 'start-plugin'].includes(process.env.TSR_VITE_DEBUG) - -export type TanStackStartViteOptions = { - globalMiddlewareEntry: string -} - -const tokenRegex = new RegExp(transformFuncs.join('|')) - -const require = createRequire(import.meta.url) - -function resolveRuntimeFiles(opts: { package: string; files: Array }) { - const pkgRoot = resolvePackage(opts.package) - const basePath = path.join(pkgRoot, 'dist', 'esm') - return opts.files.map((file) => normalizePath(path.join(basePath, file))) -} - -function resolvePackage(packageName: string): string { - const pkgRoot = path.dirname(require.resolve(packageName + '/package.json')) - return pkgRoot -} - -const transformFilter = { - code: tokenRegex, - id: { - include: TRANSFORM_ID_REGEX, - exclude: [ - VIRTUAL_MODULES.serverFnManifest, - // N.B. the following files either just re-export or provide the runtime implementation of those functions - // we do not want to include them in the transformation - // however, those packages (especially start-client-core ATM) also USE these functions - // (namely `createIsomorphicFn` in `packages/start-client-core/src/getRouterInstance.ts`) and thus need to be transformed - ...makeIdFiltersToMatchWithQuery([ - ...resolveRuntimeFiles({ - package: '@tanstack/start-client-core', - files: [ - 'index.js', - 'createIsomorphicFn.js', - 'envOnly.js', - 'serverFnFetcher.js', - 'createStart.js', - 'createMiddleware.js', - ], - }), - ...resolveRuntimeFiles({ - package: '@tanstack/start-server-core', - files: ['index.js', 'server-functions-handler.js'], - }), - ]), - ], - }, -} - -export function startCompilerPlugin(opts: { - framework: CompileStartFrameworkOptions - environments: Array<{ name: string; type: 'client' | 'server' }> -}): PluginOption { - const compileStartOutput = compileStartOutputFactory(opts.framework) - - function perEnvCompilerPlugin(environment: { - name: string - type: 'client' | 'server' - }): Plugin { - return { - name: `tanstack-start-core:compiler:${environment.name}`, - enforce: 'pre', - applyToEnvironment(env) { - return env.name === environment.name - }, - transform: { - filter: transformFilter, - handler(code, id) { - const url = pathToFileURL(id) - url.searchParams.delete('v') - id = fileURLToPath(url).replace(/\\/g, '/') - - if (debug) console.info(`${environment.name} Compiling Start: `, id) - - const compiled = compileStartOutput({ - code, - filename: id, - env: environment.type, - }) - - if (debug) { - logDiff(code, compiled.code) - console.log('Output:\n', compiled.code + '\n\n') - } - - return compiled - }, - }, - } - } - return opts.environments.map(perEnvCompilerPlugin) -} diff --git a/packages/start-plugin-core/src/start-compiler-plugin/utils.ts b/packages/start-plugin-core/src/start-compiler-plugin/utils.ts deleted file mode 100644 index dcfa6014a2..0000000000 --- a/packages/start-plugin-core/src/start-compiler-plugin/utils.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { codeFrameColumns } from '@babel/code-frame' -import type * as t from '@babel/types' -import type * as babel from '@babel/core' - -export function getRootCallExpression(path: babel.NodePath) { - // Find the highest callExpression parent - let rootCallExpression: babel.NodePath = path - - // Traverse up the chain of CallExpressions - while (rootCallExpression.parentPath.isMemberExpression()) { - const parent = rootCallExpression.parentPath - if (parent.parentPath.isCallExpression()) { - rootCallExpression = parent.parentPath - } - } - - return rootCallExpression -} - -export function codeFrameError( - code: string, - loc: { - start: { line: number; column: number } - end: { line: number; column: number } - }, - message: string, -) { - const frame = codeFrameColumns( - code, - { - start: loc.start, - end: loc.end, - }, - { - highlightCode: true, - message, - }, - ) - - return new Error(frame) -} diff --git a/packages/start-plugin-core/src/start-compiler/compiler.ts b/packages/start-plugin-core/src/start-compiler/compiler.ts new file mode 100644 index 0000000000..13193f7249 --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler/compiler.ts @@ -0,0 +1,2044 @@ +import crypto from 'node:crypto' +import * as t from '@babel/types' +import { + deadCodeElimination, + extractModuleInfoFromAst, + findReferencedIdentifiers, + generateFromAst, + getVariableDeclaratorForExpressionPath, + parseAst, + unwrapExpression, +} from '@tanstack/router-utils' +import babel from '@babel/core' +import { handleCreateServerFn } from './handleCreateServerFn' +import { handleCreateMiddleware } from './handleCreateMiddleware' +import { handleCreateIsomorphicFn } from './handleCreateIsomorphicFn' +import { handleEnvOnlyFn } from './handleEnvOnly' +import { handleClientOnlyJSX } from './handleClientOnlyJSX' +import { cleanId } from './utils' +import { + customIdCheck, + customIdError, + customIdWarning, +} from './server-fn-id-check' +import type { + CompilationContext, + DevServerFnModuleSpecifierEncoder, + MethodChainPaths, + RewriteCandidate, + ServerFn, +} from './types' +import type { ModuleInfoBinding } from '@tanstack/router-utils' +import type { + CompileStartFrameworkOptions, + StartCompilerEnvironment, + StartCompilerImportTransform, + StartCompilerPlugin, + StartCompilerTransformResult, +} from '../types' + +type Binding = ModuleInfoBinding & { + resolvedKind?: Kind +} + +type ImportBinding = Extract + +type Kind = 'None' | `Root` | `Builder` | LookupKind +type ParsedAst = ReturnType +type StartCompilerAstPlugin = StartCompilerPlugin & { + transformAst: NonNullable +} + +export type BuiltInLookupKind = + | 'ServerFn' + | 'Middleware' + | 'IsomorphicFn' + | 'ServerOnlyFn' + | 'ClientOnlyFn' + | 'ClientOnlyJSX' + +export type ExternalLookupKind = `External:${string}` + +export type LookupKind = BuiltInLookupKind | ExternalLookupKind + +// Detection strategy for each kind +type MethodChainSetup = { + type: 'methodChain' + candidateCallIdentifier: Set +} +type DirectCallSetup = { + type: 'directCall' + // The factory function name used to create this kind (e.g., 'createServerOnlyFn') + factoryNames: Set +} +type JSXSetup = { type: 'jsx'; componentName: string } + +function isLookupKind(kind: Kind): kind is LookupKind { + return kind in BuiltInLookupSetup || isExternalLookupKind(kind) +} + +export function getExternalLookupKind( + transform: StartCompilerImportTransform, +): ExternalLookupKind { + return `External:${transform.name}` +} + +function isExternalLookupKind(kind: Kind): kind is ExternalLookupKind { + return typeof kind === 'string' && kind.startsWith('External:') +} + +export function isCompilerTransformEnabledForEnv( + transform: StartCompilerImportTransform, + env: StartCompilerEnvironment, +): boolean { + return isStartCompilerEnvironmentEnabled(transform.environment, env) +} + +export function isStartCompilerPluginEnabledForEnv( + plugin: StartCompilerPlugin, + env: StartCompilerEnvironment, +): boolean { + return isStartCompilerEnvironmentEnabled(plugin.environment, env) +} + +function isStartCompilerEnvironmentEnabled( + environment: + | StartCompilerEnvironment + | Array + | undefined, + env: StartCompilerEnvironment, +): boolean { + if (!environment) return true + if (Array.isArray(environment)) { + return environment.includes(env) + } + return environment === env +} + +const BuiltInLookupSetup: Record< + BuiltInLookupKind, + MethodChainSetup | DirectCallSetup | JSXSetup +> = { + ServerFn: { + type: 'methodChain', + candidateCallIdentifier: new Set(['handler']), + }, + Middleware: { + type: 'methodChain', + candidateCallIdentifier: new Set(['server', 'client', 'createMiddlewares']), + }, + IsomorphicFn: { + type: 'methodChain', + candidateCallIdentifier: new Set(['server', 'client']), + }, + ServerOnlyFn: { + type: 'directCall', + factoryNames: new Set(['createServerOnlyFn']), + }, + ClientOnlyFn: { + type: 'directCall', + factoryNames: new Set(['createClientOnlyFn']), + }, + ClientOnlyJSX: { type: 'jsx', componentName: 'ClientOnly' }, +} + +// Single source of truth for detecting which kinds are present in code +// These patterns are used for: +// 1. Pre-scanning code to determine which kinds to look for (before AST parsing) +// 2. Deriving the plugin's transform code filter +export const KindDetectionPatterns: Record = { + ServerFn: /\bcreateServerFn\b|\.\s*handler\s*\(/, + Middleware: /createMiddleware/, + IsomorphicFn: /createIsomorphicFn/, + ServerOnlyFn: /createServerOnlyFn/, + ClientOnlyFn: /createClientOnlyFn/, + ClientOnlyJSX: / +> = { + client: new Set([ + 'Middleware', + 'ServerFn', + 'IsomorphicFn', + 'ServerOnlyFn', + 'ClientOnlyFn', + ] as const), + server: new Set([ + 'ServerFn', + 'IsomorphicFn', + 'ServerOnlyFn', + 'ClientOnlyFn', + 'ClientOnlyJSX', // Only transform on server to remove children + ] as const), +} + +export function getLookupKindsForEnv( + env: 'client' | 'server', + opts?: { + compilerTransforms?: Array | undefined + }, +): Set { + const kinds: Set = new Set(LookupKindsPerEnv[env]) + for (const transform of opts?.compilerTransforms ?? []) { + if (isCompilerTransformEnabledForEnv(transform, env)) { + kinds.add(getExternalLookupKind(transform)) + } + } + return kinds +} + +/** + * Handler type for processing candidates of a specific kind. + * The kind is passed as the third argument to allow shared handlers (like handleEnvOnlyFn). + */ +type KindHandler = ( + candidates: Array, + context: CompilationContext, + kind: BuiltInLookupKind, +) => void + +/** + * Registry mapping each LookupKind to its handler function. + * When adding a new kind, add its handler here. + */ +const BuiltInKindHandlers: Record< + Exclude, + KindHandler +> = { + ServerFn: handleCreateServerFn, + Middleware: handleCreateMiddleware, + IsomorphicFn: handleCreateIsomorphicFn, + ServerOnlyFn: handleEnvOnlyFn, + ClientOnlyFn: handleEnvOnlyFn, + // ClientOnlyJSX is handled separately via JSX traversal, not here +} + +const BuiltInKindHandlerOrder: Array< + Exclude +> = ['ServerFn', 'Middleware', 'IsomorphicFn', 'ServerOnlyFn', 'ClientOnlyFn'] + +// All lookup kinds as an array for iteration with proper typing +const AllBuiltInLookupKinds = Object.keys( + BuiltInLookupSetup, +) as Array + +/** + * Detects which LookupKinds are present in the code using string matching. + * This is a fast pre-scan before AST parsing to limit the work done during compilation. + */ +export function detectKindsInCode( + code: string, + env: 'client' | 'server', + opts?: { + compilerTransforms?: Array | undefined + }, +): Set { + const detected = new Set() + const validForEnv = getLookupKindsForEnv(env, opts) + + for (const kind of AllBuiltInLookupKinds) { + const pattern = KindDetectionPatterns[kind] + pattern.lastIndex = 0 + if (validForEnv.has(kind) && pattern.test(code)) { + detected.add(kind) + } + } + + for (const transform of opts?.compilerTransforms ?? []) { + if (!isCompilerTransformEnabledForEnv(transform, env)) continue + transform.detect.lastIndex = 0 + if (transform.detect.test(code)) { + detected.add(getExternalLookupKind(transform)) + } + } + + return detected +} + +// Pre-computed map: identifier name -> Set for fast candidate detection (method chain only) +// Multiple kinds can share the same identifier (e.g., 'server' and 'client' are used by both Middleware and IsomorphicFn) +const IdentifierToKinds = new Map>() +for (const kind of AllBuiltInLookupKinds) { + const setup = BuiltInLookupSetup[kind] + if (setup.type === 'methodChain') { + for (const id of setup.candidateCallIdentifier) { + let kinds = IdentifierToKinds.get(id) + if (!kinds) { + kinds = new Set() + IdentifierToKinds.set(id, kinds) + } + kinds.add(kind) + } + } +} + +function getLookupSetup( + kind: LookupKind, + externalLookupSetup?: Map, +): MethodChainSetup | DirectCallSetup | JSXSetup | undefined { + if (kind in BuiltInLookupSetup) { + return BuiltInLookupSetup[kind as BuiltInLookupKind] + } + + if (isExternalLookupKind(kind)) { + return externalLookupSetup?.get(kind) + } + + return undefined +} + +export type LookupConfig = { + libName: string + rootExport: string + kind: LookupKind | 'Root' // 'Root' for builder pattern, LookupKind for direct call +} + +interface ExportResolution { + moduleInfo: ModuleInfo + localName: string + binding: Binding +} + +interface ModuleInfo { + id: string + bindings: Map + // Maps exported name → local binding name + exports: Map + // Track `export * from './module'` declarations for re-export resolution + reExportAllSources: Array +} + +/** + * Checks if all kinds in the set are guaranteed to be top-level only. + * Only ServerFn is always declared at module level (must be assigned to a variable). + * Middleware, IsomorphicFn, ServerOnlyFn, ClientOnlyFn can be nested inside functions. + * When all kinds are top-level-only, we can use a fast scan instead of full traversal. + */ +function areAllKindsTopLevelOnly(kinds: Set): boolean { + return kinds.size === 1 && kinds.has('ServerFn') +} + +/** + * Checks if we need to detect JSX elements (e.g., ). + */ +function needsJSXDetection( + kinds: Set, + externalLookupSetup?: Map, +): boolean { + for (const kind of kinds) { + if (getLookupSetup(kind, externalLookupSetup)?.type === 'jsx') { + return true + } + } + return false +} + +/** + * Checks if a CallExpression is a direct-call candidate for NESTED detection. + * Returns true if the callee is a known factory function name. + * This is stricter than top-level detection because we need to filter out + * invocations of existing server functions (e.g., `myServerFn()`). + */ +function isNestedDirectCallCandidate( + node: t.CallExpression, + lookupKinds: Set, + externalLookupSetup?: Map, +): boolean { + let calleeName: string | undefined + if (t.isIdentifier(node.callee)) { + calleeName = node.callee.name + } else if ( + t.isMemberExpression(node.callee) && + t.isIdentifier(node.callee.property) + ) { + calleeName = node.callee.property.name + } + if (!calleeName) return false + for (const kind of lookupKinds) { + if (isExternalLookupKind(kind)) continue + const setup = getLookupSetup(kind, externalLookupSetup) + if (setup?.type === 'directCall' && setup.factoryNames.has(calleeName)) { + return true + } + } + return false +} + +function isSimpleDirectCallExpression(node: t.CallExpression): boolean { + return ( + t.isIdentifier(node.callee) || + (t.isMemberExpression(node.callee) && + t.isIdentifier(node.callee.object) && + t.isIdentifier(node.callee.property)) + ) +} + +function isTopLevelDirectCallCandidateNode(node: t.CallExpression): boolean { + return isSimpleDirectCallExpression(node) +} + +function getPotentialCandidateCallExpression( + node: t.Expression | null | undefined, +): t.CallExpression | null { + if (!node) { + return null + } + + const unwrapped = unwrapExpression(node) + return t.isCallExpression(unwrapped) ? unwrapped : null +} + +/** + * Checks if a CallExpression path is a top-level direct-call candidate. + * Top-level means the call is the init of a VariableDeclarator at program level. + * We accept any simple identifier call or namespace call at top level + * (e.g., `createServerOnlyFn()`, `TanStackStart.createServerOnlyFn()`) and let + * resolution verify it. This handles renamed imports. + */ +function isTopLevelDirectCallCandidate( + path: babel.NodePath, +): boolean { + const node = path.node + + // Must be a simple identifier call or namespace call + if (!isSimpleDirectCallExpression(node)) { + return false + } + + // Must be top-level: VariableDeclarator -> VariableDeclaration -> Program + // or VariableDeclarator -> VariableDeclaration -> ExportNamedDeclaration -> Program. + const variableDeclarator = getVariableDeclaratorForExpressionPath( + path as babel.NodePath, + ) + if (!variableDeclarator) { + return false + } + + const variableDeclaration = variableDeclarator.parentPath + if (!variableDeclaration.isVariableDeclaration()) { + return false + } + + const parent = variableDeclaration.parentPath + return ( + parent.isProgram() || + (parent.isExportNamedDeclaration() && parent.parentPath.isProgram()) + ) +} + +/** + * Whether the call is `receiver.method()` with a receiver that is not a + * namespace import, e.g. `z.object()` with `import { z } from 'zod'`. + * + * Resolution gives such a call the kind of the receiver itself, which only + * yields a direct-call candidate when the receiver is a factory and the code + * calls one of its properties (`createServerOnlyFn.bind()`). Skipping these + * calls saves loading the receiver's module (all of zod, here) only to learn + * that `z` is not a Start factory. + */ +function isMemberCallOnNonNamespaceReceiver( + node: t.CallExpression, + bindings: Map, +): boolean { + if ( + !t.isMemberExpression(node.callee) || + !t.isIdentifier(node.callee.object) + ) { + return false + } + + const binding = bindings.get(node.callee.object.name) + return !(binding?.type === 'import' && binding.importedName === '*') +} + +function isDirectCallCandidateForKind( + kind: Exclude, + externalLookupSetup?: Map, +): boolean { + return getLookupSetup(kind, externalLookupSetup)?.type === 'directCall' +} + +function hasBuiltInDirectCallKinds(kinds: Set): boolean { + for (const kind of kinds) { + if (isExternalLookupKind(kind)) continue + if (BuiltInLookupSetup[kind].type === 'directCall') return true + } + return false +} + +function hasExternalLookupKinds(kinds: Set): boolean { + for (const kind of kinds) { + if (isExternalLookupKind(kind)) return true + } + return false +} + +interface ExternalDirectCallCandidates { + identifiers: Map + namespaces: Map> +} + +interface CallExpressionCandidate { + path: babel.NodePath + /** Set when import scanning already proved the call's lookup kind. */ + kind?: Exclude +} + +function hasExternalDirectCallCandidates( + candidates: ExternalDirectCallCandidates, +): boolean { + return candidates.identifiers.size > 0 || candidates.namespaces.size > 0 +} + +function getExternalDirectCallCandidateKind( + path: babel.NodePath, + candidates: ExternalDirectCallCandidates, +): ExternalLookupKind | undefined { + const node = path.node + + if (t.isIdentifier(node.callee)) { + const kind = candidates.identifiers.get(node.callee.name) + if (!kind) return undefined + + const binding = path.scope.getBinding(node.callee.name) + return binding?.path.isImportSpecifier() ? kind : undefined + } + + if ( + t.isMemberExpression(node.callee) && + t.isIdentifier(node.callee.object) && + t.isIdentifier(node.callee.property) + ) { + const kind = candidates.namespaces + .get(node.callee.object.name) + ?.get(node.callee.property.name) + if (!kind) return undefined + + const binding = path.scope.getBinding(node.callee.object.name) + return binding?.path.isImportNamespaceSpecifier() ? kind : undefined + } + + return undefined +} + +export class StartCompiler { + private moduleCache = new Map() + private initialized = false + private validLookupKinds: Set + private externalTransformsByKind = new Map< + ExternalLookupKind, + StartCompilerImportTransform + >() + private externalLookupSetup = new Map() + private compilerPlugins: Array + private externalDirectCallKindsBySource = new Map< + string, + Map + >() + private resolveIdCache = new Map() + private exportResolutionCache = new Map< + string, + Map + >() + // Fast lookup for direct imports from known libraries (e.g., '@tanstack/react-start') + // Maps: libName → (exportName → Kind) + // This allows O(1) resolution for the common case without async resolveId calls + private knownRootImports = new Map>() + + // For generating unique function IDs in production builds + private entryIdToFunctionId = new Map() + private functionIds = new Set() + + constructor( + private options: { + env: 'client' | 'server' + envName: string + root: string + lookupConfigurations: Array + lookupKinds: Set + loadModule: (id: string) => Promise + resolveId: (id: string, importer?: string) => Promise + /** + * In 'build' mode, resolution results are cached for performance. + * In 'dev' mode (default), caching is disabled to avoid invalidation complexity with HMR. + */ + mode?: 'dev' | 'build' + /** + * The framework being used (e.g., 'react', 'solid'). + */ + framework: CompileStartFrameworkOptions + /** + * The Vite environment name for the server function provider. + */ + providerEnvName: string + /** + * Custom function ID generator (optional, defaults to hash-based). + */ + generateFunctionId?: (opts: { + filename: string + functionName: string + }) => string | undefined + /** + * Callback when server functions are discovered. + * Called after each file is compiled with its new functions. + */ + onServerFnsById?: (d: Record) => void + compilerTransforms?: Array | undefined + compilerPlugins?: Array | undefined + serverFnProviderModuleDirectives?: ReadonlyArray | undefined + warn?: (message: string) => void + /** + * Returns the currently known server functions from previous builds. + * Used by server callers to look up canonical extracted filenames. + */ + getKnownServerFns: () => Record + devServerFnModuleSpecifierEncoder?: DevServerFnModuleSpecifierEncoder + }, + ) { + this.validLookupKinds = options.lookupKinds + this.compilerPlugins = (options.compilerPlugins ?? []).filter((plugin) => + isStartCompilerPluginEnabledForEnv(plugin, options.env), + ) + + for (const transform of options.compilerTransforms ?? []) { + const kind = getExternalLookupKind(transform) + if (!this.validLookupKinds.has(kind)) continue + + this.externalTransformsByKind.set(kind, transform) + + const factoryNames = new Set() + for (const entry of transform.imports) { + factoryNames.add(entry.rootExport) + + let rootExports = this.externalDirectCallKindsBySource.get( + entry.libName, + ) + if (!rootExports) { + rootExports = new Map() + this.externalDirectCallKindsBySource.set(entry.libName, rootExports) + } + rootExports.set(entry.rootExport, kind) + } + + this.externalLookupSetup.set(kind, { + type: 'directCall', + factoryNames, + }) + } + } + + /** + * Generates a unique function ID for a server function. + * In dev mode, uses a base64-encoded JSON with file path and export name. + * In build mode, uses SHA256 hash or custom generator. + */ + private generateFunctionId( + opts: { + filename: string + functionName: string + variableName: string + extractedFilename: string + }, + warn: ((message: string) => void) | undefined, + ): string { + if (this.mode === 'dev') { + // In dev, encode the file path and export name for direct lookup. + // Each bundler adapter supplies its own strategy for encoding + // module specifiers that work with its dev server runtime. + const encodeModuleSpecifier = + this.options.devServerFnModuleSpecifierEncoder + if (!encodeModuleSpecifier) { + throw new Error( + 'devServerFnModuleSpecifierEncoder is required in dev mode.', + ) + } + const file = encodeModuleSpecifier({ + extractedFilename: opts.extractedFilename, + root: this.options.root, + }) + + const serverFn = { + file, + export: opts.functionName, + } + return Buffer.from(JSON.stringify(serverFn), 'utf8').toString('base64url') + } + + // Production build: use custom generator or hash + const entryId = `${opts.filename}--${opts.functionName}` + let functionId = this.entryIdToFunctionId.get(entryId) + if (functionId === undefined) { + const knownFn = Object.values(this.options.getKnownServerFns()).find( + (serverFn) => + serverFn.functionName === opts.functionName && + serverFn.extractedFilename === opts.extractedFilename, + ) + + if (knownFn) { + functionId = knownFn.functionId + } + + if (functionId === undefined && this.options.generateFunctionId) { + functionId = this.options.generateFunctionId({ + filename: opts.filename, + functionName: opts.functionName, + }) + if (functionId) { + const subject = { + name: opts.variableName, + functionName: opts.functionName, + rootRel: opts.filename, + } + const check = customIdCheck(functionId) + if (check === 'error') { + throw new Error(customIdError(subject, functionId)) + } + if (check === 'deprecated') { + warn?.(customIdWarning(subject, functionId)) + } + } + } + if (!functionId) { + functionId = crypto.createHash('sha256').update(entryId).digest('hex') + } + // Deduplicate in case the generated id conflicts with an existing id + if (this.functionIds.has(functionId)) { + let deduplicatedId + let iteration = 0 + do { + deduplicatedId = `${functionId}_${++iteration}` + } while (this.functionIds.has(deduplicatedId)) + functionId = deduplicatedId + } + this.entryIdToFunctionId.set(entryId, functionId) + this.functionIds.add(functionId) + } + return functionId + } + + private get mode(): 'dev' | 'build' { + return this.options.mode ?? 'dev' + } + + private getExternalDirectCallCandidates( + kinds: Set, + moduleInfo: ModuleInfo, + ): ExternalDirectCallCandidates { + const identifiers = new Map() + const namespaces = new Map>() + + if (this.externalDirectCallKindsBySource.size === 0) { + return { identifiers, namespaces } + } + + for (const [localName, binding] of moduleInfo.bindings) { + if (binding.type !== 'import') continue + + const rootExports = this.externalDirectCallKindsBySource.get( + binding.source, + ) + if (!rootExports) continue + + if (binding.importedName === '*') { + const namespaceExports = new Map() + for (const [rootExport, kind] of rootExports) { + if (kinds.has(kind)) { + namespaceExports.set(rootExport, kind) + } + } + if (namespaceExports.size > 0) { + namespaces.set(localName, namespaceExports) + } + } else { + const kind = rootExports.get(binding.importedName) + if (kind && kinds.has(kind)) { + identifiers.set(localName, kind) + } + } + } + + return { identifiers, namespaces } + } + + private async resolveIdCached(id: string, importer?: string) { + if (this.mode === 'dev') { + return this.options.resolveId(id, importer) + } + + const cacheKey = importer ? `${importer}::${id}` : id + const cached = this.resolveIdCache.get(cacheKey) + if (cached !== undefined) { + return cached + } + const resolved = await this.options.resolveId(id, importer) + this.resolveIdCache.set(cacheKey, resolved) + return resolved + } + + private getExportResolutionCache(moduleId: string) { + let cache = this.exportResolutionCache.get(moduleId) + if (!cache) { + cache = new Map() + this.exportResolutionCache.set(moduleId, cache) + } + return cache + } + + private init() { + // Register internal stub package exports for recognition. + // These don't need module resolution - only the knownRootImports fast path. + this.knownRootImports.set( + '@tanstack/start-fn-stubs', + new Map([ + ['createIsomorphicFn', 'IsomorphicFn'], + ['createServerOnlyFn', 'ServerOnlyFn'], + ['createClientOnlyFn', 'ClientOnlyFn'], + ]), + ) + + // Register start-client-core exports for internal package usage. + // These don't need module resolution - only the knownRootImports fast path. + this.knownRootImports.set( + '@tanstack/start-client-core', + new Map([ + ['createServerFn', 'Root'], + ['createIsomorphicFn', 'IsomorphicFn'], + ['createServerOnlyFn', 'ServerOnlyFn'], + ['createClientOnlyFn', 'ClientOnlyFn'], + ['createMiddleware', 'Middleware'], + ['createStart', 'Root'], + ]), + ) + + for (const config of this.options.lookupConfigurations) { + // Populate the fast lookup map for direct imports (by package name) + // This allows O(1) recognition of imports from known packages. + let libExports = this.knownRootImports.get(config.libName) + if (!libExports) { + libExports = new Map() + this.knownRootImports.set(config.libName, libExports) + } + libExports.set(config.rootExport, config.kind) + + // For JSX lookups (e.g., ClientOnlyJSX), we only need the knownRootImports + // fast path to verify imports. Skip synthetic root module setup. + if (config.kind !== 'Root') { + const setup = getLookupSetup(config.kind, this.externalLookupSetup) + if (setup?.type === 'jsx') { + continue + } + } + + // Root lookup metadata is synthetic package-level state, not a real + // resolved module. Keep the ID stable across bundlers and export-map + // behavior by always keying it to the package specifier itself. + const libId = config.libName + + let rootModule = this.moduleCache.get(libId) + if (!rootModule) { + // insert root binding + rootModule = { + bindings: new Map(), + exports: new Map(), + id: libId, + reExportAllSources: [], + } + this.moduleCache.set(libId, rootModule) + } + + rootModule.exports.set(config.rootExport, config.rootExport) + rootModule.exports.set('*', config.rootExport) + rootModule.bindings.set(config.rootExport, { + type: 'var', + init: null, // Not needed since resolvedKind is set + resolvedKind: config.kind satisfies Kind, + }) + this.moduleCache.set(libId, rootModule) + } + + this.initialized = true + } + + /** + * Extracts bindings and exports from an already-parsed AST. + */ + private extractModuleInfo( + ast: ReturnType, + id: string, + ): ModuleInfo { + const extracted = extractModuleInfoFromAst(ast) + + const info: ModuleInfo = { + id, + bindings: new Map(extracted.bindings), + exports: extracted.exports, + reExportAllSources: extracted.reExportAllSources, + } + this.moduleCache.set(id, info) + return info + } + + public ingestModule({ + code, + id, + parserFilename, + }: { + code: string + id: string + parserFilename?: string + }) { + const ast = parseAst({ code, filename: parserFilename ?? cleanId(id) }) + const info = this.extractModuleInfo(ast, id) + return { info, ast } + } + + public invalidateModule(id: string) { + return this.invalidateModules([id]).size > 0 + } + + public invalidateModules(ids: Iterable): Set { + const normalizedIds = new Set() + + for (const id of ids) { + normalizedIds.add(cleanId(id)) + + for (const plugin of this.compilerPlugins) { + plugin.invalidateModule?.({ id, envName: this.options.envName }) + } + } + + const deletedModuleIds = new Set() + if (normalizedIds.size === 0) { + return deletedModuleIds + } + + for (const moduleId of Array.from(this.moduleCache.keys())) { + const normalizedModuleId = cleanId(moduleId) + if (normalizedIds.has(normalizedModuleId)) { + this.moduleCache.delete(moduleId) + deletedModuleIds.add(normalizedModuleId) + } + } + + // Root import metadata is synthetic compiler state and should survive HMR. + // The stale dev state lives in per-module resolvedKind memoization. + for (const [moduleId, moduleInfo] of this.moduleCache) { + if (this.knownRootImports.has(moduleId)) { + continue + } + + for (const binding of moduleInfo.bindings.values()) { + binding.resolvedKind = undefined + } + } + + // Build-mode caches are cheap to rebuild and may point at removed entries. + this.resolveIdCache.clear() + this.exportResolutionCache.clear() + + return deletedModuleIds + } + + public async getTransitiveImporters( + ids: string | Iterable, + ): Promise> { + const discoveredImporters = new Set() + const pendingTargets = + typeof ids === 'string' + ? [cleanId(ids)] + : Array.from(ids, (id) => cleanId(id)) + const visitedTargets = new Set() + const resolveCache = new Map>() + const importersByTarget = new Map>() + + const resolveSource = (source: string, importer: string) => { + const cacheKey = `${importer}::${source}` + let resolved = resolveCache.get(cacheKey) + + if (!resolved) { + resolved = this.resolveIdCached(source, importer) + resolveCache.set(cacheKey, resolved) + } + + return resolved + } + + await Promise.all( + Array.from(this.moduleCache.values()).map(async (moduleInfo) => { + if (this.knownRootImports.has(moduleInfo.id)) { + return + } + + const moduleId = cleanId(moduleInfo.id) + const importSources = new Set(moduleInfo.reExportAllSources) + + for (const binding of moduleInfo.bindings.values()) { + if (binding.type === 'import') { + importSources.add(binding.source) + } + } + + await Promise.all( + Array.from(importSources, async (source) => { + const resolved = await resolveSource(source, moduleInfo.id) + if (!resolved) return + + const targetId = cleanId(resolved) + if (targetId === moduleId) return + + let importers = importersByTarget.get(targetId) + if (!importers) { + importers = new Set() + importersByTarget.set(targetId, importers) + } + importers.add(moduleId) + }), + ) + }), + ) + + while (pendingTargets.length > 0) { + const targetId = pendingTargets.pop()! + + if (visitedTargets.has(targetId)) { + continue + } + + visitedTargets.add(targetId) + + for (const importerId of importersByTarget.get(targetId) ?? []) { + if (discoveredImporters.has(importerId)) { + continue + } + + discoveredImporters.add(importerId) + pendingTargets.push(importerId) + } + } + + return discoveredImporters + } + + public async compile({ + code, + id, + parserFilename, + detectedKinds, + warn, + }: { + code: string + id: string + parserFilename?: string + /** Pre-detected kinds present in this file. If not provided, all valid kinds are checked. */ + detectedKinds?: Set + warn?: (message: string) => void + }) { + if (!this.initialized) { + await this.init() + } + + // Use detected kinds if provided, otherwise fall back to all valid kinds for this env + const fileKinds = detectedKinds + ? new Set([...detectedKinds].filter((k) => this.validLookupKinds.has(k))) + : this.validLookupKinds + + const astTransformPlugins = this.getAstTransformPluginsForCode(code) + // Always parse and extract module info upfront. + // This ensures the module is cached for import resolution even if no candidates are found. + const ast = this.ingestModule({ code, id, parserFilename }).ast + const warnFn = warn ?? this.options.warn + let astHasChanges = false + + builtInTransforms: { + // Early exit if no built-in or import transforms need this file. + if (fileKinds.size === 0) { + break builtInTransforms + } + + const hasExternalKinds = hasExternalLookupKinds(fileKinds) + const checkDirectCalls = + hasBuiltInDirectCallKinds(fileKinds) || + (fileKinds.has('ServerFn') && + !hasExternalKinds && + hasBuiltInDirectCallKinds(this.validLookupKinds)) + // Optimization: ServerFn is always a top-level declaration (must be assigned to a variable). + // If the file only has ServerFn, we can skip full AST traversal and only visit + // the specific top-level declarations that have candidates. + const canUseFastPath = areAllKindsTopLevelOnly(fileKinds) + + // Single-pass traversal to: + // 1. Collect candidate paths (only candidates, not all CallExpressions) + // 2. Build a map for looking up paths of nested calls in method chains + const candidatePaths: Array = [] + // Map for nested chain lookup - only populated for CallExpressions that are + // part of a method chain (callee.object is a CallExpression) + const chainCallPaths = new Map< + t.CallExpression, + babel.NodePath + >() + + // JSX candidates (e.g., ) + const jsxCandidatePaths: Array> = [] + const checkJSX = needsJSXDetection(fileKinds, this.externalLookupSetup) + // Get module info that was just cached by ingestModule + const moduleInfo = this.moduleCache.get(id)! + const externalDirectCallCandidates = this.getExternalDirectCallCandidates( + fileKinds, + moduleInfo, + ) + const checkExternalDirectCalls = hasExternalDirectCallCandidates( + externalDirectCallCandidates, + ) + + if (canUseFastPath) { + // Fast path: only visit top-level statements that have potential candidates + + // Collect indices of top-level statements that contain candidates + const candidateIndices: Array = [] + for (let i = 0; i < ast.program.body.length; i++) { + const node = ast.program.body[i]! + let declarations: Array | undefined + + if (t.isVariableDeclaration(node)) { + declarations = node.declarations + } else if (t.isExportNamedDeclaration(node) && node.declaration) { + if (t.isVariableDeclaration(node.declaration)) { + declarations = node.declaration.declarations + } + } + + if (declarations) { + for (const decl of declarations) { + const init = getPotentialCandidateCallExpression(decl.init) + if (init) { + if ( + isMethodChainCandidate(init, fileKinds) || + (checkDirectCalls && isTopLevelDirectCallCandidateNode(init)) + ) { + candidateIndices.push(i) + break // Only need to mark this statement once + } + } + } + } + } + + // Early exit: no potential candidates found at top level + if (candidateIndices.length === 0) { + break builtInTransforms + } + + // Targeted traversal: only visit the specific statements that have candidates + // This is much faster than traversing the entire AST + babel.traverse(ast, { + Program(programPath) { + const bodyPaths = programPath.get('body') + for (const idx of candidateIndices) { + const stmtPath = bodyPaths[idx] + if (!stmtPath) continue + + // Traverse only this statement's subtree + stmtPath.traverse({ + CallExpression(path) { + const node = path.node + const parent = path.parent + + // Check if this call is part of a larger chain (inner call) + if ( + t.isMemberExpression(parent) && + t.isCallExpression(path.parentPath.parent) + ) { + chainCallPaths.set(node, path) + return + } + + // Method chain pattern + if (isMethodChainCandidate(node, fileKinds)) { + candidatePaths.push({ path }) + return + } + + if (checkExternalDirectCalls) { + const kind = getExternalDirectCallCandidateKind( + path, + externalDirectCallCandidates, + ) + if (kind) { + candidatePaths.push({ path, kind }) + return + } + } + + if ( + isTopLevelDirectCallCandidate(path) && + !isMemberCallOnNonNamespaceReceiver( + node, + moduleInfo.bindings, + ) + ) { + candidatePaths.push({ path }) + } + }, + }) + } + // Stop traversal after processing Program + programPath.stop() + }, + }) + } else { + // Normal path: full traversal for non-fast-path kinds + babel.traverse(ast, { + CallExpression: (path) => { + const node = path.node + const parent = path.parent + + // Check if this call is part of a larger chain (inner call) + // If so, store it for method chain lookup but don't treat as candidate + if ( + t.isMemberExpression(parent) && + t.isCallExpression(path.parentPath.parent) + ) { + // This is an inner call in a chain - store for later lookup + chainCallPaths.set(node, path) + return + } + + // Pattern 1: Method chain pattern (.handler(), .server(), .client(), etc.) + if (isMethodChainCandidate(node, fileKinds)) { + candidatePaths.push({ path }) + return + } + + // External direct-call transforms are import-bound. Direct imports + // already identify the transform kind, so skip async import tracing. + if (checkExternalDirectCalls) { + const kind = getExternalDirectCallCandidateKind( + path, + externalDirectCallCandidates, + ) + if (kind) { + candidatePaths.push({ path, kind }) + return + } + } + + if ( + checkDirectCalls && + isTopLevelDirectCallCandidate(path) && + !isMemberCallOnNonNamespaceReceiver(node, moduleInfo.bindings) + ) { + candidatePaths.push({ path }) + return + } + + // Pattern 2: Direct call pattern + if (checkDirectCalls) { + if ( + isNestedDirectCallCandidate( + node, + fileKinds, + this.externalLookupSetup, + ) + ) { + candidatePaths.push({ path }) + return + } + } + }, + // Pattern 3: JSX element pattern (e.g., ) + // Collect JSX elements where the component is imported from a known package + // and resolves to a JSX kind (e.g., ClientOnly from @tanstack/react-router) + JSXElement: (path) => { + if (!checkJSX) return + + const openingElement = path.node.openingElement + const nameNode = openingElement.name + + // Only handle simple identifier names (not namespaced or member expressions) + if (!t.isJSXIdentifier(nameNode)) return + + const componentName = nameNode.name + const binding = moduleInfo.bindings.get(componentName) + + // Must be an import binding from a known package + if (!binding || binding.type !== 'import') return + + // Verify the import source is a known TanStack router package + const knownExports = this.knownRootImports.get(binding.source) + if (!knownExports) return + + // Verify the imported name resolves to a JSX kind (e.g., ClientOnlyJSX) + const kind = knownExports.get(binding.importedName) + if (kind !== 'ClientOnlyJSX') return + + jsxCandidatePaths.push(path) + }, + }) + } + + if (candidatePaths.length === 0 && jsxCandidatePaths.length === 0) { + break builtInTransforms + } + + // Resolve only candidates whose import scan did not already prove the kind. + const resolvedCandidates: Array<{ + path: babel.NodePath + kind: Kind + }> = [] + const unresolvedCandidates: Array = [] + + for (const candidate of candidatePaths) { + if (candidate.kind) { + resolvedCandidates.push({ + path: candidate.path, + kind: candidate.kind, + }) + } else { + unresolvedCandidates.push(candidate) + } + } + + if (unresolvedCandidates.length > 0) { + resolvedCandidates.push( + ...(await Promise.all( + unresolvedCandidates.map(async (candidate) => ({ + path: candidate.path, + kind: await this.resolveExprKind(candidate.path.node, id), + })), + )), + ) + } + + // Filter to valid candidates + const validCandidates = resolvedCandidates.filter(({ path, kind }) => { + if ( + !this.validLookupKinds.has( + kind as Exclude, + ) + ) { + return false + } + + if ( + isLookupKind(kind) && + kind !== 'ClientOnlyJSX' && + !isMethodChainCandidate(path.node, fileKinds) + ) { + return isDirectCallCandidateForKind(kind, this.externalLookupSetup) + } + + return true + }) as Array<{ + path: babel.NodePath + kind: Exclude + }> + + if (validCandidates.length === 0 && jsxCandidatePaths.length === 0) { + break builtInTransforms + } + + // Process valid candidates to collect method chains + const pathsToRewrite: Array<{ + path: babel.NodePath + kind: Exclude + methodChain: MethodChainPaths + }> = [] + + for (const { path, kind } of validCandidates) { + const node = path.node + + // Collect method chain paths by walking DOWN from root through the chain + const methodChain: MethodChainPaths = { + middleware: null, + validator: null, + handler: null, + server: null, + client: null, + } + + // Walk down the call chain using nodes, look up paths from map + let currentNode: t.CallExpression = node + let currentPath: babel.NodePath = path + + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (true) { + const callee = currentNode.callee + if (!t.isMemberExpression(callee)) { + break + } + + // Record method chain path if it's a known method + if (t.isIdentifier(callee.property)) { + const name = callee.property.name as keyof MethodChainPaths + if (name in methodChain) { + // Get first argument path + const args = currentPath.get('arguments') + const firstArgPath = + Array.isArray(args) && args.length > 0 + ? (args[0] ?? null) + : null + methodChain[name] = { + callPath: currentPath, + firstArgPath, + } + } + } + + // Move to the inner call (the object of the member expression) + if (!t.isCallExpression(callee.object)) { + break + } + currentNode = callee.object + // Look up path from chain map, or use candidate path if not found + const nextPath = chainCallPaths.get(currentNode) + if (!nextPath) { + break + } + currentPath = nextPath + } + + pathsToRewrite.push({ path, kind, methodChain }) + } + + const refIdents = findReferencedIdentifiers(ast) + + const context: CompilationContext = { + ast, + id, + code, + env: this.options.env, + envName: this.options.envName, + mode: this.mode, + root: this.options.root, + framework: this.options.framework, + providerEnvName: this.options.providerEnvName, + types: t, + parseExpression: (expressionCode) => + babel.template.expression(expressionCode, { + placeholderPattern: false, + })(), + warn: warnFn, + + generateFunctionId: (opts) => this.generateFunctionId(opts, warnFn), + getKnownServerFns: this.options.getKnownServerFns, + serverFnProviderModuleDirectives: + this.options.serverFnProviderModuleDirectives, + onServerFnsById: this.options.onServerFnsById, + } + + // Group candidates by kind for batch processing + const candidatesByKind = new Map< + Exclude, + Array + >() + + for (const { path: candidatePath, kind, methodChain } of pathsToRewrite) { + const candidate: RewriteCandidate = { path: candidatePath, methodChain } + const existing = candidatesByKind.get(kind) + if (existing) { + existing.push(candidate) + } else { + candidatesByKind.set(kind, [candidate]) + } + } + + // External transforms run before built-ins by default so they can augment + // user handlers before server function extraction clones provider bodies. + this.runExternalTransforms('pre', candidatesByKind, context) + + for (const kind of BuiltInKindHandlerOrder) { + const candidates = candidatesByKind.get(kind) + if (!candidates) continue + const handler = BuiltInKindHandlers[kind] + handler(candidates, context, kind) + } + + this.runExternalTransforms('post', candidatesByKind, context) + + // Handle JSX candidates (e.g., ) + // Validation was already done during traversal - just call the handler + for (const jsxPath of jsxCandidatePaths) { + handleClientOnlyJSX(jsxPath, { env: 'server' }) + } + + deadCodeElimination(ast, refIdents) + astHasChanges = true + } + + if (astTransformPlugins.length > 0) { + astHasChanges = + this.runAstTransforms({ + ast, + code, + id, + transforms: astTransformPlugins, + warn: warnFn, + }) || astHasChanges + } + + return astHasChanges ? this.generateResultFromAst(ast, code, id) : null + } + + private generateResultFromAst( + ast: ParsedAst, + sourceCode: string, + id: string, + ): StartCompilerTransformResult { + const result = generateFromAst(ast, { + sourceMaps: true, + sourceFileName: id, + filename: id, + }) + + // @babel/generator does not populate sourcesContent because it only has + // the AST, not the original text. Without this, Vite's composed sourcemap + // omits the original source, causing downstream consumers to fall back to + // the compiled output and fail to resolve original line numbers. + if (result.map) { + result.map.sourcesContent = [sourceCode] + } + + return result + } + + private getAstTransformPluginsForCode( + code: string, + ): Array { + return this.compilerPlugins.filter( + (plugin): plugin is StartCompilerAstPlugin => { + if (!plugin.transformAst) return false + if (!plugin.detect) return true + plugin.detect.lastIndex = 0 + return plugin.detect.test(code) + }, + ) + } + + private runAstTransforms({ + ast, + code, + id, + transforms, + warn, + }: { + ast: ParsedAst + code: string + id: string + transforms: Array + warn?: (message: string) => void + }): boolean { + let modified = false + + for (const plugin of transforms) { + const context = { + ast, + code, + id, + env: this.options.env, + envName: this.options.envName, + mode: this.mode, + root: this.options.root, + framework: this.options.framework, + providerEnvName: this.options.providerEnvName, + types: t, + parseExpression: (expressionCode: string) => + babel.template.expression(expressionCode, { + placeholderPattern: false, + })(), + warn, + } + + modified = plugin.transformAst(context) || modified + } + + return modified + } + + private runExternalTransforms( + order: 'pre' | 'post', + candidatesByKind: Map< + Exclude, + Array + >, + context: CompilationContext, + ) { + for (const [kind, transform] of this.externalTransformsByKind) { + if ((transform.order ?? 'pre') !== order) continue + + const candidates = candidatesByKind.get(kind) + if (!candidates) continue + + transform.transform(candidates, context) + } + } + + private async resolveIdentifierKind( + ident: string, + id: string, + visited = new Set(), + ): Promise { + const info = await this.getModuleInfo(id) + + const binding = info.bindings.get(ident) + if (!binding) { + return 'None' + } + if (binding.resolvedKind) { + return binding.resolvedKind + } + + // TODO improve cycle detection? should we throw here instead of returning 'None'? + // prevent cycles + const vKey = `${id}:${ident}` + if (visited.has(vKey)) { + return 'None' + } + visited.add(vKey) + + const resolvedKind = await this.resolveBindingKind(binding, id, visited) + binding.resolvedKind = resolvedKind + return resolvedKind + } + + /** + * Recursively find an export in a module, following `export * from` chains. + * Returns the module info and binding if found, or undefined if not found. + */ + private async findExportInModule( + moduleInfo: ModuleInfo, + exportName: string, + visitedModules = new Set(), + ): Promise { + const isBuildMode = this.mode === 'build' + + // Check cache first (only for top-level calls in build mode) + if (isBuildMode && visitedModules.size === 0) { + const moduleCache = this.exportResolutionCache.get(moduleInfo.id) + if (moduleCache) { + const cached = moduleCache.get(exportName) + if (cached !== undefined) { + return cached ?? undefined + } + } + } + + // Prevent infinite loops in circular re-exports + if (visitedModules.has(moduleInfo.id)) { + return undefined + } + visitedModules.add(moduleInfo.id) + + // First check direct exports + const localBindingName = moduleInfo.exports.get(exportName) + if (localBindingName) { + const binding = moduleInfo.bindings.get(localBindingName) + if (binding) { + const result = { moduleInfo, localName: localBindingName, binding } + // Cache the result (build mode only) + if (isBuildMode) { + this.getExportResolutionCache(moduleInfo.id).set(exportName, result) + } + return result + } + } + + // If not found, recursively check re-export-all sources in parallel + // Valid code won't have duplicate exports across chains, so first match wins + if (moduleInfo.reExportAllSources.length > 0) { + const results = await Promise.all( + moduleInfo.reExportAllSources.map(async (reExportSource) => { + const reExportTarget = await this.resolveIdCached( + reExportSource, + moduleInfo.id, + ) + + if (reExportTarget) { + const reExportModule = await this.getModuleInfo(reExportTarget) + return this.findExportInModule( + reExportModule, + exportName, + visitedModules, + ) + } + return undefined + }), + ) + // Return the first valid result + for (const result of results) { + if (result) { + // Cache the result (build mode only) + if (isBuildMode) { + this.getExportResolutionCache(moduleInfo.id).set(exportName, result) + } + return result + } + } + } + + // Cache negative result (build mode only) + if (isBuildMode) { + this.getExportResolutionCache(moduleInfo.id).set(exportName, null) + } + return undefined + } + + private async resolveBindingTarget( + resolution: ExportResolution, + visited = new Set(), + ): Promise { + const key = `${resolution.moduleInfo.id}:${resolution.localName}` + if (visited.has(key)) { + return undefined + } + visited.add(key) + + if (resolution.binding.type !== 'import') { + return resolution + } + + const target = await this.resolveIdCached( + resolution.binding.source, + resolution.moduleInfo.id, + ) + if (!target) { + return undefined + } + + const importedModule = await this.getModuleInfo(target) + const found = await this.findExportInModule( + importedModule, + resolution.binding.importedName, + ) + if (!found) { + return undefined + } + + return this.resolveBindingTarget(found, visited) + } + + private async resolveKnownImportKind( + binding: ImportBinding, + resolved?: ExportResolution, + ): Promise { + const directKind = + this.knownRootImports.get(binding.source)?.get(binding.importedName) ?? + 'None' + if (directKind !== 'None') { + return directKind + } + + if (!resolved) { + return 'None' + } + + for (const [source, rootExports] of this.knownRootImports) { + const kind = rootExports.get(binding.importedName) + if (!kind) { + continue + } + + let targetId: string | null + try { + targetId = await this.resolveIdCached(source, resolved.moduleInfo.id) + } catch { + continue + } + + if (!targetId) { + continue + } + + try { + const rootModule = await this.getModuleInfo(targetId) + const found = await this.findExportInModule( + rootModule, + binding.importedName, + ) + const target = found + ? ((await this.resolveBindingTarget(found)) ?? found) + : undefined + + // Match by resolved binding identity, not by export name alone. + if ( + target && + resolved.moduleInfo.id === target.moduleInfo.id && + resolved.localName === target.localName + ) { + return kind + } + } catch { + continue + } + } + + return 'None' + } + + private async resolveImportKind( + binding: ImportBinding, + fileId: string, + visited: Set, + ): Promise { + const directKnownKind = await this.resolveKnownImportKind(binding) + if (directKnownKind !== 'None') { + binding.resolvedKind = directKnownKind + return directKnownKind + } + + if (binding.importedName === '*') { + return 'None' + } + + const target = await this.resolveIdCached(binding.source, fileId) + if (!target) { + return 'None' + } + + const importedModule = await this.getModuleInfo(target) + const found = await this.findExportInModule( + importedModule, + binding.importedName, + ) + if (!found) { + return 'None' + } + + const knownKind = await this.resolveKnownImportKind(binding, found) + if (knownKind !== 'None') { + found.binding.resolvedKind = knownKind + binding.resolvedKind = knownKind + return knownKind + } + + if (found.binding.resolvedKind) { + return found.binding.resolvedKind + } + + // Import aliases can form cycles, e.g. A re-exports from B while B + // re-exports from A. Track the exported binding before following it. + const vKey = `${found.moduleInfo.id}:${found.localName}` + if (visited.has(vKey)) { + return 'None' + } + visited.add(vKey) + + const resolvedKind = await this.resolveBindingKind( + found.binding, + found.moduleInfo.id, + visited, + ) + found.binding.resolvedKind = resolvedKind + return resolvedKind + } + + private async resolveBindingKind( + binding: Binding, + fileId: string, + visited = new Set(), + ): Promise { + if (binding.resolvedKind) { + return binding.resolvedKind + } + if (binding.type === 'import') { + return this.resolveImportKind(binding, fileId, visited) + } + + const resolvedKind = await this.resolveExprKind( + binding.init, + fileId, + visited, + ) + // When a var binding's init is a call to a directCall factory + // (e.g., `const myFn = createServerOnlyFn(() => ...)`), the binding holds + // the RESULT of the factory, not the factory itself. Clear the kind so + // `myFn()` isn't incorrectly matched as a directCall candidate. + // We only clear when the init is a CallExpression — an alias like + // `const createSO = createServerOnlyFn` should still propagate the kind. + if ( + isLookupKind(resolvedKind) && + getLookupSetup(resolvedKind, this.externalLookupSetup)?.type === + 'directCall' && + binding.init && + t.isCallExpression(unwrapExpression(binding.init)) + ) { + binding.resolvedKind = 'None' + return 'None' + } + binding.resolvedKind = resolvedKind + return resolvedKind + } + + private async resolveExprKind( + expr: t.Expression | null, + fileId: string, + visited = new Set(), + ): Promise { + if (!expr) { + return 'None' + } + + expr = unwrapExpression(expr) + + let result: Kind = 'None' + + if (t.isCallExpression(expr)) { + if (!t.isExpression(expr.callee)) { + return 'None' + } + const calleeKind = await this.resolveCalleeKind( + expr.callee, + fileId, + visited, + ) + if (calleeKind === 'Root' || calleeKind === 'Builder') { + return 'Builder' + } + // For method chain patterns (callee is MemberExpression like .server() or .client()), + // return the resolved kind if valid + if (t.isMemberExpression(expr.callee)) { + if (this.validLookupKinds.has(calleeKind as LookupKind)) { + return calleeKind + } + } + // For direct calls (callee is Identifier like createServerOnlyFn()), + // trust calleeKind if it resolved to a valid LookupKind. This means + // resolveBindingKind successfully traced the import back to + // @tanstack/start-fn-stubs (via fast path or slow path through re-exports). + // This handles both direct imports from @tanstack/react-start and imports + // from intermediate packages that re-export from @tanstack/start-client-core. + if (t.isIdentifier(expr.callee)) { + if (this.validLookupKinds.has(calleeKind as LookupKind)) { + return calleeKind + } + } + } else if (t.isMemberExpression(expr) && t.isIdentifier(expr.property)) { + result = await this.resolveCalleeKind(expr.object, fileId, visited) + } + + if (result === 'None' && t.isIdentifier(expr)) { + result = await this.resolveIdentifierKind(expr.name, fileId, visited) + } + + return result + } + + private async resolveCalleeKind( + callee: t.Expression, + fileId: string, + visited = new Set(), + ): Promise { + if (t.isIdentifier(callee)) { + return this.resolveIdentifierKind(callee.name, fileId, visited) + } + + if (t.isMemberExpression(callee) && t.isIdentifier(callee.property)) { + const prop = callee.property.name + + // Check if this property matches any method chain pattern + const possibleKinds = IdentifierToKinds.get(prop) + if (possibleKinds) { + // Resolve base expression ONCE and reuse for all pattern checks + const base = await this.resolveExprKind(callee.object, fileId, visited) + + // Check each possible kind that uses this identifier + for (const kind of possibleKinds) { + if (!this.validLookupKinds.has(kind)) continue + + if (kind === 'ServerFn') { + if (base === 'Root' || base === 'Builder') { + return 'ServerFn' + } + } else if (kind === 'Middleware') { + if ( + base === 'Root' || + base === 'Builder' || + base === 'Middleware' + ) { + return 'Middleware' + } + } else if (kind === 'IsomorphicFn') { + if ( + base === 'Root' || + base === 'Builder' || + base === 'IsomorphicFn' + ) { + return 'IsomorphicFn' + } + } + } + } + + // Check if the object is a namespace import + if (t.isIdentifier(callee.object)) { + const info = await this.getModuleInfo(fileId) + const binding = info.bindings.get(callee.object.name) + if ( + binding && + binding.type === 'import' && + binding.importedName === '*' + ) { + return this.resolveImportKind( + { + type: 'import', + source: binding.source, + importedName: callee.property.name, + }, + fileId, + visited, + ) + } + } + return this.resolveExprKind(callee.object, fileId, visited) + } + + // handle nested expressions + return this.resolveExprKind(callee, fileId, visited) + } + + private async getModuleInfo(id: string) { + let cached = this.moduleCache.get(id) + if (cached) { + return cached + } + + await this.options.loadModule(id) + + cached = this.moduleCache.get(id) + if (!cached) { + throw new Error(`could not load module info for ${id}`) + } + return cached + } +} + +/** + * Checks if a CallExpression has a method chain pattern that matches any of the lookup kinds. + * E.g., `.handler()`, `.server()`, `.client()`, `.createMiddlewares()` + */ +function isMethodChainCandidate( + node: t.CallExpression, + lookupKinds: Set, +): boolean { + const callee = node.callee + if (!t.isMemberExpression(callee) || !t.isIdentifier(callee.property)) { + return false + } + + // Use pre-computed map for O(1) lookup + // IdentifierToKinds maps identifier -> Set to handle shared identifiers + const possibleKinds = IdentifierToKinds.get(callee.property.name) + if (possibleKinds) { + // Check if any of the possible kinds are in the valid lookup kinds + for (const kind of possibleKinds) { + if (lookupKinds.has(kind)) { + return true + } + } + } + + return false +} diff --git a/packages/start-plugin-core/src/start-compiler/config.ts b/packages/start-plugin-core/src/start-compiler/config.ts new file mode 100644 index 0000000000..387343bad9 --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler/config.ts @@ -0,0 +1,119 @@ +import { + KindDetectionPatterns, + getExternalLookupKind, + getLookupKindsForEnv, + isCompilerTransformEnabledForEnv, + isStartCompilerPluginEnabledForEnv, +} from './compiler' +import type { BuiltInLookupKind, LookupConfig } from './compiler' +import type { + CompileStartFrameworkOptions, + StartCompilerImportTransform, + StartCompilerPlugin, +} from '../types' + +export function getTransformCodeFilterForEnv( + env: 'client' | 'server', + opts?: { + compilerTransforms?: Array | undefined + compilerPlugins?: Array | undefined + }, +): Array { + const validKinds = getLookupKindsForEnv(env, opts) + const patterns: Array = [] + + for (const [kind, pattern] of Object.entries(KindDetectionPatterns) as Array< + [BuiltInLookupKind, RegExp] + >) { + if (validKinds.has(kind)) { + patterns.push(pattern) + } + } + + for (const transform of opts?.compilerTransforms ?? []) { + if (isCompilerTransformEnabledForEnv(transform, env)) { + patterns.push(transform.detect) + } + } + + for (const plugin of opts?.compilerPlugins ?? []) { + if (plugin.detect && isStartCompilerPluginEnabledForEnv(plugin, env)) { + patterns.push(plugin.detect) + } + } + + return patterns +} + +export function getLookupConfigurationsForEnv( + env: 'client' | 'server', + framework: CompileStartFrameworkOptions, + opts?: { + compilerTransforms?: Array | undefined + }, +): Array { + const commonConfigs: Array = [ + { + libName: `@tanstack/${framework}-start`, + rootExport: 'createServerFn', + kind: 'Root', + }, + { + libName: `@tanstack/${framework}-start`, + rootExport: 'createIsomorphicFn', + kind: 'IsomorphicFn', + }, + { + libName: `@tanstack/${framework}-start`, + rootExport: 'createServerOnlyFn', + kind: 'ServerOnlyFn', + }, + { + libName: `@tanstack/${framework}-start`, + rootExport: 'createClientOnlyFn', + kind: 'ClientOnlyFn', + }, + ] + + const externalConfigs: Array = [] + for (const transform of opts?.compilerTransforms ?? []) { + if (!isCompilerTransformEnabledForEnv(transform, env)) continue + + const kind = getExternalLookupKind(transform) + for (const imported of transform.imports) { + externalConfigs.push({ + libName: imported.libName, + rootExport: imported.rootExport, + kind, + }) + } + } + + if (env === 'client') { + return [ + { + libName: `@tanstack/${framework}-start`, + rootExport: 'createMiddleware', + kind: 'Root', + }, + { + libName: `@tanstack/${framework}-start`, + rootExport: 'createStart', + kind: 'Root', + }, + ...commonConfigs, + ...externalConfigs, + ] + } + + const serverConfigs: Array = [ + ...commonConfigs, + { + libName: `@tanstack/${framework}-router`, + rootExport: 'ClientOnly', + kind: 'ClientOnlyJSX', + }, + ] + + return [...serverConfigs, ...externalConfigs] +} diff --git a/packages/start-plugin-core/src/start-compiler/handleClientOnlyJSX.ts b/packages/start-plugin-core/src/start-compiler/handleClientOnlyJSX.ts new file mode 100644 index 0000000000..9676e4b7bd --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler/handleClientOnlyJSX.ts @@ -0,0 +1,32 @@ +import type * as t from '@babel/types' +import type * as babel from '@babel/core' + +/** + * Handles JSX elements on the server side. + * + * On the server, the children of should be removed since they + * are client-only code. Only the fallback prop (if present) will be rendered. + * + * Transform: + * }>{clientOnlyContent} + * Into: + * } /> + * + * Or if no fallback: + * {clientOnlyContent} + * Into: + * + */ +export function handleClientOnlyJSX( + path: babel.NodePath, + _opts: { env: 'server' }, +): void { + const element = path.node + + // Remove all children - they are client-only code + element.children = [] + + // Make it a self-closing element since there are no children + element.openingElement.selfClosing = true + element.closingElement = null +} diff --git a/packages/start-plugin-core/src/start-compiler/handleCreateIsomorphicFn.ts b/packages/start-plugin-core/src/start-compiler/handleCreateIsomorphicFn.ts new file mode 100644 index 0000000000..8331a00849 --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler/handleCreateIsomorphicFn.ts @@ -0,0 +1,38 @@ +import * as t from '@babel/types' +import type { CompilationContext, RewriteCandidate } from './types' + +/** + * Handles createIsomorphicFn transformations for a batch of candidates. + * + * @param candidates - All IsomorphicFn candidates to process + * @param context - The compilation context + */ +export function handleCreateIsomorphicFn( + candidates: Array, + context: CompilationContext, +): void { + for (const candidate of candidates) { + const { path, methodChain } = candidate + + // Get the environment-specific call (.client() or .server()) + const envCallInfo = + context.env === 'client' ? methodChain.client : methodChain.server + + if (!envCallInfo) { + // No implementation for this environment - replace with no-op + path.replaceWith(t.arrowFunctionExpression([], t.blockStatement([]))) + continue + } + + // Extract the function argument from the environment-specific call + const innerFn = envCallInfo.firstArgPath?.node + + if (!t.isExpression(innerFn)) { + throw new Error( + `createIsomorphicFn().${context.env}(func) must be called with a function!`, + ) + } + + path.replaceWith(innerFn) + } +} diff --git a/packages/start-plugin-core/src/start-compiler/handleCreateMiddleware.ts b/packages/start-plugin-core/src/start-compiler/handleCreateMiddleware.ts new file mode 100644 index 0000000000..22575ccc50 --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler/handleCreateMiddleware.ts @@ -0,0 +1,39 @@ +import { stripMethodCall } from './utils' +import type { CompilationContext, RewriteCandidate } from './types' + +/** + * Handles createMiddleware transformations for a batch of candidates. + * + * @param candidates - All Middleware candidates to process + * @param context - The compilation context + */ +export function handleCreateMiddleware( + candidates: Array, + context: CompilationContext, +): void { + if (context.env === 'server') { + throw new Error('handleCreateMiddleware should not be called on the server') + } + + for (const candidate of candidates) { + const { validator, server } = candidate.methodChain + + if (validator) { + const innerInputExpression = validator.callPath.node.arguments[0] + + if (!innerInputExpression) { + throw new Error( + 'createMiddleware().validator() must be called with a validator!', + ) + } + + // remove the validator call expression + stripMethodCall(validator.callPath) + } + + if (server) { + // remove the server call expression + stripMethodCall(server.callPath) + } + } +} diff --git a/packages/start-plugin-core/src/start-compiler/handleCreateServerFn.ts b/packages/start-plugin-core/src/start-compiler/handleCreateServerFn.ts new file mode 100644 index 0000000000..dd152bdaa4 --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler/handleCreateServerFn.ts @@ -0,0 +1,532 @@ +import * as t from '@babel/types' +import babel from '@babel/core' +import { hasKeys } from '@tanstack/router-core' +import { getVariableDeclaratorForExpressionPath } from '@tanstack/router-utils' +import path from 'pathe' +import { cleanId, codeFrameError, stripMethodCall } from './utils' +import type { CompilationContext, RewriteCandidate, ServerFn } from './types' +import type { CompileStartFrameworkOptions } from '../types' + +const TSS_SERVERFN_SPLIT_PARAM = 'tss-serverfn-split' + +const providerHmrAcceptTemplate = babel.template.statements( + ` +if (import.meta.hot) { + import.meta.hot.accept(() => {}) +} +if (import.meta.webpackHot) { + import.meta.webpackHot.accept(() => {}) +} +`, + { + placeholderPattern: false, + }, +) + +// ============================================================================ +// Pre-compiled babel templates (compiled once at module load time) +// ============================================================================ + +// Template for provider files: createServerRpc(serverFnMeta, fn) +const serverRpcTemplate = babel.template.expression( + `createServerRpc(%%serverFnMeta%%, %%fn%%)`, +) + +// Template for client caller files: createClientRpc(functionId) +const clientRpcTemplate = babel.template.expression( + `createClientRpc(%%functionId%%)`, +) + +// Template for SSR caller files: createSsrRpc(functionId) +const ssrRpcManifestTemplate = babel.template.expression( + `createSsrRpc(%%functionId%%)`, +) + +// ============================================================================ +// Runtime code cache (cached per framework to avoid repeated AST generation) +// ============================================================================ + +type RuntimeCodeType = 'provider' | 'client' | 'ssr' +type FrameworkRuntimeCache = Record +const RuntimeCodeCache = new Map< + CompileStartFrameworkOptions, + FrameworkRuntimeCache +>() + +function getCachedRuntimeCode( + framework: CompileStartFrameworkOptions, + type: RuntimeCodeType, +): t.Statement { + let cache = RuntimeCodeCache.get(framework) + if (!cache) { + cache = { + provider: babel.template.ast( + `import { createServerRpc } from '@tanstack/${framework}-start/server-rpc'`, + { placeholderPattern: false }, + ) as t.Statement, + client: babel.template.ast( + `import { createClientRpc } from '@tanstack/${framework}-start/client-rpc'`, + { placeholderPattern: false }, + ) as t.Statement, + ssr: babel.template.ast( + `import { createSsrRpc } from '@tanstack/${framework}-start/ssr-rpc'`, + { placeholderPattern: false }, + ) as t.Statement, + } + RuntimeCodeCache.set(framework, cache) + } + return cache[type] +} + +/** + * Environment-specific configuration for server function transformation. + * This is computed internally based on the compilation context. + */ +interface EnvConfig { + /** Whether this environment is a client environment */ + isClientEnvironment: boolean + /** The runtime code type to use for imports */ + runtimeCodeType: RuntimeCodeType +} + +/** + * Gets the environment configuration for the current compilation context. + */ +function getEnvConfig( + context: CompilationContext, + isProviderFile: boolean, +): EnvConfig { + const { env } = context + + if (isProviderFile) { + return { + isClientEnvironment: false, + runtimeCodeType: 'provider', + } + } + + if (env === 'client') { + return { + isClientEnvironment: true, + runtimeCodeType: 'client', + } + } + + // Server caller (SSR) + return { + isClientEnvironment: false, + runtimeCodeType: 'ssr', + } +} + +/** + * Builds the serverFnMeta object literal AST node. + * The object contains: { id, name, filename } + */ +function buildServerFnMetaObject( + functionId: string, + variableName: string, + filename: string, +): t.ObjectExpression { + return t.objectExpression([ + t.objectProperty(t.identifier('id'), t.stringLiteral(functionId)), + t.objectProperty(t.identifier('name'), t.stringLiteral(variableName)), + t.objectProperty(t.identifier('filename'), t.stringLiteral(filename)), + ]) +} + +/** + * Generates the RPC stub expression for provider files. + * Uses pre-compiled template for performance. + */ +function generateProviderRpcStub( + serverFnMeta: t.ObjectExpression, + fn: t.Expression, +): t.Expression { + return serverRpcTemplate({ + serverFnMeta, + fn, + }) +} + +/** + * Generates the RPC stub expression for caller files. + * Uses pre-compiled templates for performance. + * Note: Client and SSR callers only receive the functionId string, not the full metadata. + */ +function generateCallerRpcStub( + functionId: string, + envConfig: EnvConfig, +): t.Expression { + const functionIdLiteral = t.stringLiteral(functionId) + + if (envConfig.runtimeCodeType === 'client') { + return clientRpcTemplate({ + functionId: functionIdLiteral, + }) + } + + return ssrRpcManifestTemplate({ + functionId: functionIdLiteral, + }) +} + +/** + * Handles createServerFn transformations for a batch of candidates. + * + * This function performs extraction and replacement of server functions + * + * For caller files (non-provider): + * - Replaces the server function with an RPC stub + * - Does not include the handler function body + * + * For provider files: + * - Creates an extractedFn that calls __executeServer + * - Modifies .handler() to pass (extractedFn, serverFn) - two arguments + * + * @param candidates - All ServerFn candidates to process + * @param context - The compilation context with helpers and mutable state + * @returns Result containing runtime code to add, or null if no candidates processed + */ +export function handleCreateServerFn( + candidates: Array, + context: CompilationContext, +) { + if (candidates.length === 0) { + return + } + + const isProviderFile = context.id.includes(TSS_SERVERFN_SPLIT_PARAM) + if (isProviderFile && context.serverFnProviderModuleDirectives) { + ensureDirectivePrologue( + context.ast, + context.serverFnProviderModuleDirectives, + ) + } + + // Get environment-specific configuration + const envConfig = getEnvConfig(context, isProviderFile) + + // Track function names to ensure uniqueness within this file + const functionNameSet = new Set() + + const exportNames = new Set() + const serverFnsById: Record = {} + + const [baseFilename] = context.id.split('?') as [string] + const extractedFilename = `${baseFilename}?${TSS_SERVERFN_SPLIT_PARAM}` + const relativeFilename = path.relative(context.root, baseFilename) + const knownFns = context.getKnownServerFns() + const cleanedContextId = cleanId(context.id) + + for (const candidate of candidates) { + const { path: candidatePath, methodChain } = candidate + const { validator, handler } = methodChain + + const candidateVariableDeclarator = getVariableDeclaratorForExpressionPath( + candidatePath as babel.NodePath, + ) + + // Check if the call is assigned to a variable + if (!candidateVariableDeclarator) { + throw new Error('createServerFn must be assigned to a variable!') + } + + // Get the identifier name of the variable + const variableDeclarator = candidateVariableDeclarator.node + if (!t.isIdentifier(variableDeclarator.id)) { + throw codeFrameError( + context.code, + variableDeclarator.id.loc!, + 'createServerFn must be assigned to a simple identifier, not a destructuring pattern', + ) + } + const existingVariableName = variableDeclarator.id.name + + // Generate unique function name with _createServerFn_handler suffix + // The function name is derived from the variable name + let functionName = `${existingVariableName}_createServerFn_handler` + while (functionNameSet.has(functionName)) { + functionName = incrementFunctionNameVersion(functionName) + } + functionNameSet.add(functionName) + + // Generate function ID using pre-computed relative filename + const functionId = context.generateFunctionId({ + filename: relativeFilename, + functionName, + variableName: existingVariableName, + extractedFilename, + }) + + // Check if this function was already discovered by the client build + const knownFn = knownFns[functionId] + // A server function is client-referenced when: + // 1. We're in the client (browser) environment, OR + // 2. It was already discovered by another environment (knownFn), OR + // 3. We're in an SSR caller environment — any server function reachable from + // SSR module graph is callable via client navigation HTTP requests + const isClientReferenced = + envConfig.isClientEnvironment || + !!knownFn || + envConfig.runtimeCodeType === 'ssr' + + // Use canonical extracted filename from known functions if available + const canonicalExtractedFilename = + knownFn?.extractedFilename ?? extractedFilename + + // Handle validators - remove on client + if (validator) { + const innerInputExpression = validator.callPath.node.arguments[0] + + if (!innerInputExpression) { + throw new Error( + 'createServerFn().validator() must be called with a validator!', + ) + } + + // If we're on the client, remove the validator call expression + if (context.env === 'client') { + stripMethodCall(validator.callPath) + } + } + + const handlerFnPath = handler?.firstArgPath + + if (!handler || !handlerFnPath?.node) { + throw codeFrameError( + context.code, + candidatePath.node.callee.loc!, + `createServerFn must be called with a "handler" property!`, + ) + } + + // Validate the handler argument is an expression (not a SpreadElement, etc.) + if (!t.isExpression(handlerFnPath.node)) { + throw codeFrameError( + context.code, + handlerFnPath.node.loc!, + `handler() must be called with an expression, not a ${handlerFnPath.node.type}`, + ) + } + + const handlerFn = handlerFnPath.node + + // Register function only from caller files (not provider files) + // to avoid duplicates - provider files process the same functions + + if (!isProviderFile) { + serverFnsById[functionId] = { + functionName, + functionId, + filename: cleanedContextId, + extractedFilename: canonicalExtractedFilename, + isClientReferenced, + } + } + + if (isProviderFile) { + // PROVIDER FILE: This is the extracted file that contains the actual implementation + // We need to: + // 1. Create an extractedFn that calls __executeServer + // 2. Modify .handler() to pass (extractedFn, serverFn) - two arguments + // + // Expected output format: + // const extractedFn = createServerRpc({id, name, filename}, (opts) => varName.__executeServer(opts)); + // const varName = createServerFn().handler(extractedFn, originalHandler); + + // Build the arrow function: (opts) => varName.__executeServer(opts) + // The signal parameter is passed through to allow abort signal propagation + const executeServerArrowFn = t.arrowFunctionExpression( + [t.identifier('opts')], + t.callExpression( + t.memberExpression( + t.identifier(existingVariableName), + t.identifier('__executeServer'), + ), + [t.identifier('opts')], + ), + ) + + // Build the serverFnMeta object + const serverFnMeta = buildServerFnMetaObject( + functionId, + existingVariableName, + relativeFilename, + ) + + // Generate the replacement using pre-compiled template + const extractedFnInit = generateProviderRpcStub( + serverFnMeta, + executeServerArrowFn, + ) + + // Build the extracted function statement + const extractedFnStatement = t.variableDeclaration('const', [ + t.variableDeclarator(t.identifier(functionName), extractedFnInit), + ]) + + // Find the variable declaration statement containing our createServerFn + const variableDeclaration = candidateVariableDeclarator.parentPath + if (!variableDeclaration.isVariableDeclaration()) { + throw new Error( + 'Expected createServerFn to be in a VariableDeclaration', + ) + } + + // Insert the extracted function statement before the variable declaration + variableDeclaration.insertBefore(extractedFnStatement) + + // Modify the .handler() call to pass two arguments: (extractedFn, serverFn) + // The handlerFnPath.node contains the original serverFn + const extractedFnIdentifier = t.identifier(functionName) + const serverFnNode = t.cloneNode(handlerFn, true) + + // Replace handler's arguments with [extractedFn, serverFn] + handler.callPath.node.arguments = [extractedFnIdentifier, serverFnNode] + + // Only export the extracted handler (e.g., myFn_createServerFn_handler) + // The manifest and all import paths only look up this suffixed name. + // The original variable (e.g., myFn) stays in the file but is not exported + // since it's only used internally. + exportNames.add(functionName) + } else { + // CALLER FILE: This file calls the server function but doesn't contain the implementation + // We need to: + // 1. Remove the handler function body (it will be in the provider file) + // 2. Replace the handler argument with an RPC stub + // + // IMPORTANT: We must keep the createServerFn().handler(extractedFn) structure + // so that the client middleware chain can unwrap the {result, error, context} response. + // + // Expected output format: + // const myFn = createServerFn().handler(createClientRpc("id")) + // or + // const myFn = createServerFn().handler(createSsrRpc("id")) + + // Generate the RPC stub using pre-compiled templates + // Note: Caller files only pass functionId, not the full serverFnMeta + const rpcStub = generateCallerRpcStub(functionId, envConfig) + + // Replace ONLY the handler argument with the RPC stub + // Keep the createServerFn().handler() wrapper intact for client middleware + handlerFnPath.replaceWith(rpcStub) + } + } + + // For provider files, add exports for all extracted functions + if (isProviderFile) { + // Remove all existing exports first + safeRemoveExports(context.ast) + + // Export all server function related variables from exportNames + // These were populated by handleCreateServerFn: + // 1. Extracted handlers: const fn_createServerFn_handler = createServerRpc(...) + // 2. Original variables: const fn = createServerFn().handler(...) + if (exportNames.size > 0) { + context.ast.program.body.push( + t.exportNamedDeclaration( + undefined, + Array.from(exportNames).map((name) => + t.exportSpecifier(t.identifier(name), t.identifier(name)), + ), + ), + ) + } + + if (context.mode === 'dev') { + context.ast.program.body.push(...providerHmrAcceptTemplate()) + } + } + + // Notify about discovered functions (only for non-provider files) + if (!isProviderFile && hasKeys(serverFnsById) && context.onServerFnsById) { + context.onServerFnsById(serverFnsById) + } + + // Add runtime import using cached AST node + const runtimeCode = getCachedRuntimeCode( + context.framework, + envConfig.runtimeCodeType, + ) + context.ast.program.body.unshift(t.cloneNode(runtimeCode)) +} + +/** + * Makes an identifier safe for use as a JavaScript identifier. + */ +function makeIdentifierSafe(identifier: string): string { + return identifier + .replace(/[^a-zA-Z0-9_$]/g, '_') // Replace unsafe chars with underscore + .replace(/^[0-9]/, '_$&') // Prefix leading number with underscore + .replace(/^\$/, '_$') // Prefix leading $ with underscore + .replace(/_{2,}/g, '_') // Collapse multiple underscores + .replace(/^_|_$/g, '') // Trim leading/trailing underscores +} + +/** + * Increments the version number suffix on a function name. + */ +function incrementFunctionNameVersion(functionName: string): string { + const [realReferenceName, count] = functionName.split(/_(\d+)$/) + const resolvedCount = Number(count || '0') + const suffix = `_${resolvedCount + 1}` + return makeIdentifierSafe(realReferenceName!) + suffix +} + +/** + * Removes all exports from the AST while preserving the declarations. + * Used for provider files where we want to re-export only the server functions. + */ +function safeRemoveExports(ast: t.File): void { + ast.program.body = ast.program.body.flatMap((node) => { + if ( + t.isExportNamedDeclaration(node) || + t.isExportDefaultDeclaration(node) + ) { + if ( + t.isFunctionDeclaration(node.declaration) || + t.isClassDeclaration(node.declaration) || + t.isVariableDeclaration(node.declaration) + ) { + // do not remove export if it is an anonymous function / class, + // otherwise this would produce a syntax error + if ( + t.isFunctionDeclaration(node.declaration) || + t.isClassDeclaration(node.declaration) + ) { + if (!node.declaration.id) { + return node + } + } + return node.declaration + } else if (node.declaration === null) { + // remove e.g. `export { RouteComponent as component }` + return [] + } + } + return node + }) +} + +function ensureDirectivePrologue( + ast: t.File, + directiveValues: ReadonlyArray, +): void { + const directives = ast.program.directives + const existingDirectives = new Set( + directives.map((directive) => directive.value.value), + ) + const missingDirectives: Array = [] + + for (const directiveValue of directiveValues) { + if (!directiveValue || existingDirectives.has(directiveValue)) continue + + existingDirectives.add(directiveValue) + missingDirectives.push(directiveValue) + } + + for (let i = missingDirectives.length - 1; i >= 0; i--) { + directives.unshift(t.directive(t.directiveLiteral(missingDirectives[i]!))) + } +} diff --git a/packages/start-plugin-core/src/start-compiler/handleEnvOnly.ts b/packages/start-plugin-core/src/start-compiler/handleEnvOnly.ts new file mode 100644 index 0000000000..1fa6ab21cf --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler/handleEnvOnly.ts @@ -0,0 +1,56 @@ +import * as t from '@babel/types' +import type { CompilationContext, RewriteCandidate } from './types' +import type { LookupKind } from './compiler' + +function capitalize(str: string) { + if (!str) return '' + return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase() +} + +/** + * Handles serverOnly/clientOnly function transformations for a batch of candidates. + * + * @param candidates - All EnvOnly candidates to process (all same kind) + * @param context - The compilation context + * @param kind - The specific kind (ServerOnlyFn or ClientOnlyFn) + */ +export function handleEnvOnlyFn( + candidates: Array, + context: CompilationContext, + kind: LookupKind, +): void { + const targetEnv = kind === 'ClientOnlyFn' ? 'client' : 'server' + + for (const candidate of candidates) { + const { path } = candidate + + if (context.env === targetEnv) { + // Matching environment - extract the inner function + const innerFn = path.node.arguments[0] + + if (!t.isExpression(innerFn)) { + throw new Error( + `create${capitalize(targetEnv)}OnlyFn() must be called with a function!`, + ) + } + + path.replaceWith(innerFn) + } else { + // Wrong environment - replace with a function that throws an error + path.replaceWith( + t.arrowFunctionExpression( + [], + t.blockStatement([ + t.throwStatement( + t.newExpression(t.identifier('Error'), [ + t.stringLiteral( + `create${capitalize(targetEnv)}OnlyFn() functions can only be called on the ${targetEnv}!`, + ), + ]), + ), + ]), + ), + ) + } + } +} diff --git a/packages/start-plugin-core/src/start-compiler/host.ts b/packages/start-plugin-core/src/start-compiler/host.ts new file mode 100644 index 0000000000..d6953f51f9 --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler/host.ts @@ -0,0 +1,138 @@ +import { StartCompiler, getLookupKindsForEnv } from './compiler' +import { getLookupConfigurationsForEnv } from './config' +import type { + CompileStartFrameworkOptions, + StartCompilerImportTransform, + StartCompilerPlugin, + StartCompilerTransformResult, + StartCompilerVirtualModuleContext, +} from '../types' +import type { + DevServerFnModuleSpecifierEncoder, + GenerateFunctionIdFnOptional, + ServerFn, +} from './types' + +export interface CreateStartCompilerOptions { + env: 'client' | 'server' + envName: string + root: string + framework: CompileStartFrameworkOptions + providerEnvName: string + mode: 'dev' | 'build' + generateFunctionId?: GenerateFunctionIdFnOptional + compilerTransforms?: Array | undefined + compilerPlugins?: Array | undefined + serverFnProviderModuleDirectives?: ReadonlyArray | undefined + warn?: (message: string) => void + onServerFnsById?: (d: Record) => void + getKnownServerFns: () => Record + encodeModuleSpecifierInDev?: DevServerFnModuleSpecifierEncoder + loadModule: (id: string) => Promise + resolveId: (id: string, importer?: string) => Promise +} + +export function createStartCompiler( + options: CreateStartCompilerOptions, +): StartCompiler { + return new StartCompiler({ + env: options.env, + envName: options.envName, + root: options.root, + lookupKinds: getLookupKindsForEnv(options.env, { + compilerTransforms: options.compilerTransforms, + }), + lookupConfigurations: getLookupConfigurationsForEnv( + options.env, + options.framework, + { compilerTransforms: options.compilerTransforms }, + ), + mode: options.mode, + framework: options.framework, + providerEnvName: options.providerEnvName, + generateFunctionId: options.generateFunctionId, + onServerFnsById: options.onServerFnsById, + compilerTransforms: options.compilerTransforms, + compilerPlugins: options.compilerPlugins, + serverFnProviderModuleDirectives: options.serverFnProviderModuleDirectives, + warn: options.warn, + getKnownServerFns: options.getKnownServerFns, + devServerFnModuleSpecifierEncoder: options.encodeModuleSpecifierInDev, + loadModule: options.loadModule, + resolveId: options.resolveId, + }) +} + +export function mergeServerFnsById( + current: Record, + next: Record, +): void { + for (const [id, fn] of Object.entries(next)) { + const existing = current[id] + + if (existing) { + current[id] = { + ...fn, + isClientReferenced: + existing.isClientReferenced || fn.isClientReferenced, + } + continue + } + + current[id] = fn + } +} + +export function matchesCodeFilters( + code: string, + filters: ReadonlyArray, +): boolean { + for (const pattern of filters) { + pattern.lastIndex = 0 + if (pattern.test(code)) { + return true + } + } + + return false +} + +export function createCompilerVirtualModuleIdPattern( + compilerPlugins: ReadonlyArray, +) { + const patterns = compilerPlugins + .map((plugin) => plugin.virtualModuleIdPattern) + .filter((pattern): pattern is RegExp => !!pattern) + + if (patterns.length === 0) { + return undefined + } + + return new RegExp( + patterns.map((pattern) => `(?:${pattern.source})`).join('|'), + ) +} + +export function loadCompilerVirtualModule( + compilerPlugins: ReadonlyArray, + context: StartCompilerVirtualModuleContext, +): StartCompilerTransformResult | null { + for (const compilerPlugin of compilerPlugins) { + const pattern = compilerPlugin.virtualModuleIdPattern + if (!pattern) { + continue + } + + pattern.lastIndex = 0 + if (!pattern.test(context.id)) { + continue + } + + const result = compilerPlugin.loadVirtualModule?.(context) + if (result) { + return result + } + } + + return null +} diff --git a/packages/start-plugin-core/src/start-compiler/server-fn-id-check.ts b/packages/start-plugin-core/src/start-compiler/server-fn-id-check.ts new file mode 100644 index 0000000000..7ddaafce5b --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler/server-fn-id-check.ts @@ -0,0 +1,75 @@ +/** + * Which ids a custom `serverFns.generateFunctionId` may return. The client + * puts the id after `TSS_SERVER_FN_BASE` unencoded and the server reads that + * path segment back, so an id has to survive that trip whole. + */ + +interface CustomIdSubject { + /** The server function's variable name. */ + name: string + /** The `functionName` the generator received. */ + functionName: string + /** The defining file, relative to the root. */ + rootRel: string +} + +/** + * `error`: the id never reached its handler: a character that splits or + * ends the path or that a client percent-encodes, a dot segment, which URL + * parsing removes, or a percent-encoding the server decodes to another id + * or rejects (`readBack`). `deprecated`: an ASCII character outside RFC + * 3986's unreserved set and `$`, which reaches the server but which proxies + * and servers may encode or normalise. + */ +export function customIdCheck(id: string): 'ok' | 'deprecated' | 'error' { + if ( + id === '.' || + id === '..' || + /[^\x21-\x7e]|["#/<>?\\^`{}]/.test(id) || + (id.includes('%') && readBack(id) !== id) + ) { + return 'error' + } + return /^[A-Za-z0-9\-._~$]+$/.test(id) ? 'ok' : 'deprecated' +} + +/** + * The id the server reads from the URL of an id holding `%`: the request + * URL's path, decoded as Start's server does when the path holds `%` + * (router-core `getNormalizedURL`, `decodePath`: `decodeURI` keeping `%25` + * and `%5C`, then control characters and `"<>\`{}` encoded again) and + * parsed again; `undefined` when the decode throws (the server answers 400). + */ +function readBack(id: string): string | undefined { + const base = '/_/' + const { pathname } = new URL(base + id, 'http://localhost') + let decoded = '' + try { + for (const part of pathname.split(/(%25|%5C)/i)) { + decoded += /^%(25|5C)$/i.test(part) + ? part + : decodeURI(part).replace( + // eslint-disable-next-line no-control-regex + /[\x00-\x1f\x7f"<>`{}]/g, + (ch) => + `%${ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`, + ) + } + } catch { + return undefined + } + const read = new URL(decoded, 'http://localhost').pathname + return read.startsWith(base) + ? read.slice(base.length).split('/')[0] + : undefined +} + +/** The build error of a custom id `customIdCheck` refuses. */ +export function customIdError(fn: CustomIdSubject, id: string): string { + return `[tanstack-start] serverFns.generateFunctionId returned ${JSON.stringify(id)} for the server function ${fn.name} (functionName "${fn.functionName}") of ${fn.rootRel}. A server function id is one path segment of its URL: it cannot hold whitespace, control or non-ASCII characters or any of " # / < > ? \\ ^ \` { }, cannot be "." or "..", and cannot hold a percent-encoding the server reads as another id ("%41") or rejects. Use ASCII letters, digits, "-", ".", "_", "~" and "$".` +} + +/** The build warning of a custom id `customIdCheck` deprecates. */ +export function customIdWarning(fn: CustomIdSubject, id: string): string { + return `[tanstack-start] serverFns.generateFunctionId returned ${JSON.stringify(id)} for the server function ${fn.name} (functionName "${fn.functionName}") of ${fn.rootRel}. Server function ids with characters other than ASCII letters, digits, "-", ".", "_", "~" and "$" are deprecated, and the next major version of TanStack Start rejects them: proxies and servers may encode or normalise them in the URL.` +} diff --git a/packages/start-plugin-core/src/start-compiler/server-fn-resolver-module.ts b/packages/start-plugin-core/src/start-compiler/server-fn-resolver-module.ts new file mode 100644 index 0000000000..2d50376a39 --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler/server-fn-resolver-module.ts @@ -0,0 +1,79 @@ +import type { ServerFn } from './types' + +interface GenerateServerFnResolverModuleOptions { + serverFnsById: Record + includeClientReferencedCheck: boolean + useStaticImports?: boolean + /** + * Keep each imported module on its manifest entry after the first call. + * Only safe when modules cannot be hot-replaced (production builds). + */ + memoizeModules?: boolean +} + +export function generateServerFnResolverModule( + opts: GenerateServerFnResolverModuleOptions, +): string { + const staticImports: Array = [] + const manifest = Object.entries(opts.serverFnsById) + // Keep generated source stable for content-addressed caches. + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([id, fn], index) => { + const moduleRef = `serverFnModule${index}` + const filename = JSON.stringify(fn.extractedFilename) + if (opts.useStaticImports) { + staticImports.push(`import * as ${moduleRef} from ${filename}`) + } + const moduleAccess = opts.useStaticImports + ? `module: ${moduleRef}` + : `importer: () => import(${filename})` + const clientReferenced = opts.includeClientReferencedCheck + ? `,\n isClientReferenced: ${fn.isClientReferenced ?? true}` + : '' + + // (a custom id can hold `'`) + return `'${id.replace(/[\\']/g, '\\$&')}': { + functionName: '${fn.functionName}', + ${moduleAccess}${clientReferenced} + }` + }) + .join(',\n ') + + const clientReferencedCheck = opts.includeClientReferencedCheck + ? ` + if (access.origin === 'client' && !serverFnInfo.isClientReferenced) { + throw new Error('Server function not accessible from client: ' + id) + } +` + : '' + // Every import() goes through the ESM loader; a resolved production module + // can be kept on the manifest entry instead. + const resolveModule = opts.memoizeModules + ? 'serverFnInfo.module ??= await serverFnInfo.importer()' + : 'serverFnInfo.module ?? (await serverFnInfo.importer())' + + return ` +${staticImports.join('\n')} +const manifest = { + ${manifest} +} + +export async function getServerFnById(id, access) { + const serverFnInfo = manifest[id] + if (!serverFnInfo) { + throw new Error('Server function info not found for ' + id) + } +${clientReferencedCheck} + const fnModule = ${resolveModule} + if (!fnModule) { + throw new Error('Server function module not resolved for ' + id) + } + const action = fnModule[serverFnInfo.functionName] + if (!action) { + throw new Error('Server function module export not resolved for serverFn ID: ' + id) + } + return action +} + +` +} diff --git a/packages/start-plugin-core/src/start-compiler/types.ts b/packages/start-plugin-core/src/start-compiler/types.ts new file mode 100644 index 0000000000..91b39f5f8a --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler/types.ts @@ -0,0 +1,135 @@ +import type * as babel from '@babel/core' +import type * as t from '@babel/types' +import type { StartCompilerTransformContext } from '../types' + +/** + * Context passed to all plugin handlers during compilation. + * Contains both read-only input data and mutable state that handlers update. + */ +export interface CompilationContext extends StartCompilerTransformContext { + /** Generate a unique function ID */ + generateFunctionId: GenerateFunctionIdFn + /** Get known server functions from previous builds (e.g., client build) */ + getKnownServerFns: () => Record + /** Module-level directives to add to extracted server function provider files. */ + serverFnProviderModuleDirectives: ReadonlyArray | undefined + + /** + * Callback when server functions are discovered. + * Called after each file is compiled with its new functions. + */ + onServerFnsById: ((d: Record) => void) | undefined +} + +/** + * Batched plugin handler signature. + * Receives ALL candidates of a specific kind in one call. + * Mutates the CompilationContext directly. + */ +export type BatchedPluginHandler = ( + candidates: Array, + context: CompilationContext, + opts: TOpts, +) => void + +/** + * Info about a method call in the chain, including the call expression path + * and the path to its first argument (if any). + */ +export interface MethodCallInfo { + callPath: babel.NodePath + /** Path to the first argument, or null if no arguments */ + firstArgPath: babel.NodePath | null +} + +/** + * Pre-collected method chain paths for a root call expression. + * This avoids needing to traverse the AST again in handlers. + */ +export interface MethodChainPaths { + middleware: MethodCallInfo | null + validator: MethodCallInfo | null + handler: MethodCallInfo | null + server: MethodCallInfo | null + client: MethodCallInfo | null +} + +export type MethodChainKey = keyof MethodChainPaths + +/** + * Information about a candidate that needs to be rewritten. + */ +export interface RewriteCandidate { + path: babel.NodePath + methodChain: MethodChainPaths +} + +/** + * Represents an extracted server function that has been registered. + * Used for manifest generation and tracking function metadata. + */ +export interface ServerFn { + /** The unique name used to export this function */ + functionName: string + /** The unique ID for this function (used in RPC calls) */ + functionId: string + /** The filename with query param where the extracted implementation lives */ + extractedFilename: string + /** The original source filename */ + filename: string + /** + * True when this function was discovered by the client build. + * Used to restrict HTTP access to only client-referenced functions. + */ + isClientReferenced?: boolean +} + +/** + * Function type for generating unique function IDs. + */ +export type GenerateFunctionIdFn = (opts: { + filename: string + functionName: string + /** The server function's variable name, for diagnostics. */ + variableName: string + extractedFilename: string +}) => string + +/** + * Optional version that allows returning undefined to use default ID generation. + */ +export type GenerateFunctionIdFnOptional = ( + opts: Omit< + Parameters[0], + 'extractedFilename' | 'variableName' + >, +) => string | undefined + +/** + * Function type for generating replacement code for server functions. + * Used internally by handleCreateServerFn. + */ +export type DevServerFnModuleSpecifierEncoder = (opts: { + extractedFilename: string + root: string +}) => string + +export type ReplacerFn = (opts: { + /** Placeholder for the original function expression */ + fn: string + /** The filename where the extracted implementation lives */ + extractedFilename: string + /** The original source filename */ + filename: string + /** The unique function ID */ + functionId: string + /** The export name for this function */ + functionName: string + /** True if this is the source/provider file (has the implementation) */ + isSourceFn: boolean + /** + * True when this function was already discovered by a previous build (e.g., client). + * For SSR callers, this means the function is in the manifest. + */ + isClientReferenced: boolean +}) => string diff --git a/packages/start-plugin-core/src/start-compiler/utils.ts b/packages/start-plugin-core/src/start-compiler/utils.ts new file mode 100644 index 0000000000..384a13113d --- /dev/null +++ b/packages/start-plugin-core/src/start-compiler/utils.ts @@ -0,0 +1,59 @@ +import { codeFrameColumns } from '@babel/code-frame' +import * as t from '@babel/types' +import type babel from '@babel/core' + +export function codeFrameError( + code: string, + loc: { + start: { line: number; column: number } + end: { line: number; column: number } + }, + message: string, +) { + const frame = codeFrameColumns( + code, + { + start: loc.start, + end: loc.end, + }, + { + highlightCode: true, + message, + }, + ) + + return new Error(frame) +} + +/** + * Converts a bundler module ID to its physical-file identity for diagnostics, + * filesystem matching, and file-based invalidation. + * + * Do not use this for IDs passed to resolve/load hooks or as module cache keys: + * virtual prefixes and queries can be part of the module's semantic identity. + */ +export function cleanId(id: string): string { + // Remove null byte prefix used by Vite/Rollup for virtual modules + if (id.startsWith('\0')) { + id = id.slice(1) + } + const queryIndex = id.indexOf('?') + return queryIndex === -1 ? id : id.substring(0, queryIndex) +} + +/** + * Strips a method call by replacing it with its callee object. + * E.g., `foo().bar()` -> `foo()` + * + * This is a common pattern used when removing method calls from chains + * (e.g., removing .server() from middleware on client, or .validator() on client). + * + * @param callPath - The path to the CallExpression to strip + */ +export function stripMethodCall( + callPath: babel.NodePath, +): void { + if (t.isMemberExpression(callPath.node.callee)) { + callPath.replaceWith(callPath.node.callee.object) + } +} diff --git a/packages/start-plugin-core/src/start-manifest-plugin/inlineCss.ts b/packages/start-plugin-core/src/start-manifest-plugin/inlineCss.ts new file mode 100644 index 0000000000..bf87de9bfe --- /dev/null +++ b/packages/start-plugin-core/src/start-manifest-plugin/inlineCss.ts @@ -0,0 +1,203 @@ +import { transform } from 'lightningcss' + +export interface InlineCssTemplate { + strings: Array + urls: Array +} + +export interface InlineCssResult { + css: string + template?: InlineCssTemplate +} + +const cssUrlPattern = + /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)"']*?))\s*\)|@import\s+(?:url\(\s*(?:"([^"]*)"|'([^']*)'|([^)"']*?))\s*\)|"([^"]*)"|'([^']*)')/gi + +function createInlineCssUrlPlaceholder(index: number) { + return `__TSS INLINE CSS URL ${index}__` +} + +function isRelativeCssUrl(url: string) { + if (!url) return false + if (url.startsWith('#')) return false + if (url.startsWith('/')) return false + if (/^[a-z][a-z\d+.-]*:/i.test(url)) return false + return true +} + +export function shouldRebaseInlineCssUrls(css: string) { + return shouldProcessInlineCssUrls(css, false) +} + +function shouldTransformInlineCssUrl(url: string) { + if (!url) return false + if (url.startsWith('#')) return false + if (url.startsWith('//')) return false + if (/^[a-z][a-z\d+.-]*:/i.test(url)) return false + return true +} + +function shouldProcessInlineCssUrls(css: string, templates: boolean) { + cssUrlPattern.lastIndex = 0 + + for (const match of css.matchAll(cssUrlPattern)) { + const url = ( + match[1] ?? + match[2] ?? + match[3] ?? + match[4] ?? + match[5] ?? + match[6] ?? + match[7] ?? + match[8] ?? + '' + ).trim() + + if (templates ? shouldTransformInlineCssUrl(url) : isRelativeCssUrl(url)) { + return true + } + } + + return false +} + +function rebaseCssUrl(url: string, cssHref: string) { + if (!isRelativeCssUrl(url)) { + return url + } + + const fakeOrigin = 'http://tanstack.local' + const resolved = new URL(url, new URL(cssHref, fakeOrigin)) + + if (resolved.origin === fakeOrigin) { + return `${resolved.pathname}${resolved.search}${resolved.hash}` + } + + return resolved.href +} + +export function rebaseInlineCssUrls(options: { css: string; cssHref: string }) { + return processInlineCssUrls(options).css +} + +export function processInlineCssUrls(options: { + css: string + cssHref: string + templates?: boolean +}): InlineCssResult { + const css = options.css.trim() + const templates = options.templates === true + + if (!shouldProcessInlineCssUrls(css, templates)) { + return { css } + } + + const urls: Array = [] + + const result = transform({ + filename: options.cssHref, + code: Buffer.from(css), + minify: true, + visitor: { + Url(url) { + if (!shouldTransformInlineCssUrl(url.url)) { + return url + } + + const rebasedUrl = rebaseCssUrl(url.url, options.cssHref) + + if (templates) { + urls.push(rebasedUrl) + return { + ...url, + url: createInlineCssUrlPlaceholder(urls.length - 1), + } + } + + return { + ...url, + url: rebasedUrl, + } + }, + Rule: { + import(rule: any) { + if (!shouldTransformInlineCssUrl(rule.value.url)) { + return rule + } + + const rebasedUrl = rebaseCssUrl(rule.value.url, options.cssHref) + if (templates) { + urls.push(rebasedUrl) + } + + const value = { + url: templates + ? createInlineCssUrlPlaceholder(urls.length - 1) + : rebasedUrl, + loc: rule.value.loc, + ...(rule.value.media ? { media: rule.value.media } : {}), + ...(rule.value.layer ? { layer: rule.value.layer } : {}), + ...(rule.value.supports ? { supports: rule.value.supports } : {}), + } + + return { + ...rule, + value, + } + }, + }, + }, + }) + + const transformedCss = Buffer.from(result.code).toString('utf8') + + if (!templates || urls.length === 0) { + return { css: transformedCss } + } + + return createInlineCssTemplate(transformedCss, urls) +} + +function createInlineCssTemplate( + cssWithPlaceholders: string, + urls: Array, +): InlineCssResult { + const strings: Array = [] + let css = '' + let cursor = 0 + + for (let index = 0; index < urls.length; index++) { + const placeholder = createInlineCssUrlPlaceholder(index) + const placeholderIndex = cssWithPlaceholders.indexOf(placeholder, cursor) + + if (placeholderIndex === -1) { + throw new Error( + `TanStack Start inlineCss could not find CSS URL placeholder: ${placeholder}`, + ) + } + + const staticPart = cssWithPlaceholders.slice(cursor, placeholderIndex) + strings.push(staticPart) + css += staticPart + urls[index] + cursor = placeholderIndex + placeholder.length + } + + const finalStaticPart = cssWithPlaceholders.slice(cursor) + strings.push(finalStaticPart) + css += finalStaticPart + + return { + css, + template: { + strings, + urls, + }, + } +} + +export function getCssAssetSource(source: unknown) { + if (typeof source === 'string') return source + if (source instanceof Uint8Array) return Buffer.from(source).toString('utf8') + if (source == null) return undefined + return String(source) +} diff --git a/packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts b/packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts new file mode 100644 index 0000000000..d5339f2983 --- /dev/null +++ b/packages/start-plugin-core/src/start-manifest-plugin/manifestBuilder.ts @@ -0,0 +1,848 @@ +/* eslint-disable @typescript-eslint/prefer-for-of */ +import { serialize } from 'seroval' +import { joinURL } from 'ufo' +import { + getStylesheetHref, + resolveManifestAssetLink, + resolveManifestCssLink, + rootRouteId, +} from '@tanstack/router-core' +import { processInlineCssUrls } from './inlineCss' +import type { + ManifestAssetLink, + ManifestCssLink, + ManifestScript, + ScriptFormat, +} from '@tanstack/router-core' +import type { InlineCssTemplate } from './inlineCss' +import type { NormalizedClientBuild, NormalizedClientChunk } from '../types' + +type RouteTreeRoute = { + filePath?: string + preloads?: Array + scripts?: Array + css?: Array + children?: Array +} + +type RouteTreeRoutes = Record + +type AdditionalRouteManifestEntry = ManifestCssLink | ManifestScript + +interface ScannedClientChunks { + entryChunk: NormalizedClientChunk + chunksByFileName: ReadonlyMap + routeChunksByFilePath: ReadonlyMap> +} + +interface ManifestAssetResolvers { + getAssetPath: (fileName: string) => string + getChunkPreloads: (chunk: NormalizedClientChunk) => Array + getChunkCssAssets: (chunk: NormalizedClientChunk) => Array + getStylesheetLink: (cssFile: string) => ManifestCssLink +} + +interface StaticImportClosure { + /** File names reachable through static imports, in discovery order. */ + fileNames: Array + /** Chunks reachable through static imports, dependencies before importers. */ + dependenciesFirst: Array +} + +type DedupeRoute = { + preloads?: Array + scripts?: Array + css?: Array + children?: Array +} + +export interface StartManifest { + scriptFormat?: ScriptFormat + routes: Record + inlineCss?: { + styles: Record + templates?: Record + } +} + +export interface InlineCssOptions { + enabled: boolean + transformAssets: boolean +} + +export function appendUniqueStrings( + target: Array | undefined, + source: Array, +) { + // Similar to Set.prototype.union, but for ordered arrays. + // It preserves first-seen order and returns the original target array when + // source contributes no new values, which avoids extra allocations. + if (source.length === 0) { + return target + } + + if (!target || target.length === 0) { + return source + } + + const seen = new Set(target) + let result: Array | undefined + + for (const value of source) { + if (seen.has(value)) { + continue + } + + seen.add(value) + if (!result) { + result = target.slice() + } + result.push(value) + } + + return result ?? target +} + +function appendUniqueStylesheets( + target: Array | undefined, + source: Array, +) { + if (source.length === 0) { + return target + } + + if (!target || target.length === 0) { + return source + } + + const seen = new Set(target.map(getStylesheetIdentity)) + let result: Array | undefined + + for (const stylesheet of source) { + const identity = getStylesheetIdentity(stylesheet) + if (seen.has(identity)) { + continue + } + + seen.add(identity) + if (!result) { + result = target.slice() + } + result.push(stylesheet) + } + + return result ?? target +} + +function getStylesheetIdentity(attrs: ManifestCssLink) { + const resolved = resolveManifestCssLink(attrs) + return `${resolved.href}\0${resolved.crossOrigin ?? ''}` +} + +function getScriptIdentity(script: ManifestScript) { + return JSON.stringify({ + attrs: normalizeAttrs(script.attrs), + children: script.children ?? null, + }) +} + +function normalizeAttrs(attrs: Record | undefined) { + if (!attrs) { + return null + } + + const entries = Object.entries(attrs) + if (entries.length === 0) { + return null + } + + entries.sort(([left], [right]) => left.localeCompare(right)) + return Object.fromEntries(entries) +} + +function mergeRouteChunkData(options: { + route: RouteTreeRoute + chunk: NormalizedClientChunk + getChunkCssAssets: (chunk: NormalizedClientChunk) => Array + getChunkPreloads: (chunk: NormalizedClientChunk) => Array +}) { + const stylesheets = options.getChunkCssAssets(options.chunk) + const chunkPreloads = options.getChunkPreloads(options.chunk) + + appendRouteStylesheets(options.route, stylesheets) + options.route.preloads = appendUniqueStrings( + options.route.preloads, + chunkPreloads, + ) +} + +function appendRouteStylesheets( + route: RouteTreeRoute, + stylesheets: Array, +) { + if (stylesheets.length === 0) { + return + } + + route.css = appendUniqueStylesheets(route.css, stylesheets) +} + +function appendRouteScripts( + route: RouteTreeRoute, + scripts: Array, +) { + if (scripts.length === 0) { + return + } + + route.scripts = [...(route.scripts ?? []), ...scripts] +} + +function buildScript(src: string, scriptFormat: ScriptFormat): ManifestScript { + return { + attrs: { + ...(scriptFormat === 'module' ? { type: 'module' } : {}), + async: true, + src, + }, + } +} + +function appendEntryChunkScripts(options: { + route: RouteTreeRoute + chunk: NormalizedClientChunk + scriptFormat: ScriptFormat + getAssetPath: (fileName: string) => string +}) { + const scripts: Array = [] + + if (options.scriptFormat === 'iife') { + for (let i = 0; i < options.chunk.imports.length; i++) { + scripts.push( + buildScript( + options.getAssetPath(options.chunk.imports[i]!), + options.scriptFormat, + ), + ) + } + } + + scripts.push( + buildScript( + options.getAssetPath(options.chunk.fileName), + options.scriptFormat, + ), + ) + + appendRouteScripts(options.route, scripts) +} + +function appendAdditionalRouteEntries( + route: RouteTreeRoute, + entries: ReadonlyArray, +) { + if (entries.length === 0) { + return + } + + const stylesheets: Array = [] + const scripts: Array = [] + + for (const entry of entries) { + if (typeof entry === 'string' || 'href' in entry) { + stylesheets.push(entry) + } else { + scripts.push(entry) + } + } + + appendRouteStylesheets(route, stylesheets) + appendRouteScripts(route, scripts) +} + +export function buildStartManifest(options: { + clientBuild: NormalizedClientBuild + routeTreeRoutes: RouteTreeRoutes + basePath: string + inlineCss?: InlineCssOptions + scriptFormat?: ScriptFormat + additionalRouteAssets?: Partial< + Record> + > +}): StartManifest { + const scannedChunks = scanClientChunks(options.clientBuild) + const assetResolvers = createManifestAssetResolvers( + options.basePath, + scannedChunks.chunksByFileName, + ) + + const routes = buildRouteManifestRoutes({ + routeTreeRoutes: options.routeTreeRoutes, + routeChunksByFilePath: scannedChunks.routeChunksByFilePath, + chunksByFileName: scannedChunks.chunksByFileName, + entryChunk: scannedChunks.entryChunk, + assetResolvers, + additionalRouteAssets: options.additionalRouteAssets, + }) + + appendEntryChunkScripts({ + route: routes[rootRouteId]!, + chunk: scannedChunks.entryChunk, + scriptFormat: options.scriptFormat ?? 'module', + getAssetPath: assetResolvers.getAssetPath, + }) + + dedupeNestedRouteManifestEntries(rootRouteId, routes[rootRouteId]!, routes) + + // Prune routes with no manifest data + for (const routeId in routes) { + const route = routes[routeId]! + const hasScripts = route.scripts && route.scripts.length > 0 + const hasCssLinks = route.css && route.css.length > 0 + const hasPreloads = route.preloads && route.preloads.length > 0 + if (!hasScripts && !hasCssLinks && !hasPreloads) { + delete routes[routeId] + } + } + + const result: StartManifest = { + routes, + } + + if (options.scriptFormat === 'iife') { + result.scriptFormat = 'iife' + } + + if (options.inlineCss?.enabled) { + result.inlineCss = buildInlineCssManifestData({ + routes, + basePath: options.basePath, + cssContentByFileName: options.clientBuild.cssContentByFileName, + transformAssets: options.inlineCss.transformAssets, + }) + } + + return result +} + +export function serializeStartManifest(startManifest: StartManifest) { + return serialize(startManifest) +} + +export function scanClientChunks( + clientBuild: NormalizedClientBuild, +): ScannedClientChunks { + const entryChunk = clientBuild.chunksByFileName.get( + clientBuild.entryChunkFileName, + ) + + if (!entryChunk) { + throw new Error(`Missing entry chunk: ${clientBuild.entryChunkFileName}`) + } + + const routeChunksByFilePath = new Map>() + + for (const chunk of clientBuild.chunksByFileName.values()) { + if (chunk.routeFilePaths.length > 0) { + for (const routeFilePath of chunk.routeFilePaths) { + let chunks = routeChunksByFilePath.get(routeFilePath) + if (chunks === undefined) { + chunks = [] + routeChunksByFilePath.set(routeFilePath, chunks) + } + chunks.push(chunk) + } + } + } + + return { + entryChunk, + chunksByFileName: clientBuild.chunksByFileName, + routeChunksByFilePath, + } +} + +export function createManifestAssetResolvers( + basePath: string, + chunksByFileName: ReadonlyMap, +): ManifestAssetResolvers { + const assetPathByFileName = new Map() + const stylesheetLinkByFileName = new Map() + const closureByChunk = new Map() + const preloadsByChunk = new Map>() + const cssAssetsByChunk = new Map< + NormalizedClientChunk, + Array + >() + + const getAssetPath = (fileName: string) => { + const cachedPath = assetPathByFileName.get(fileName) + if (cachedPath) { + return cachedPath + } + + const assetPath = joinURL(basePath, fileName) + assetPathByFileName.set(fileName, assetPath) + return assetPath + } + + const getStylesheetLink = (cssFile: string) => { + const cachedLink = stylesheetLinkByFileName.get(cssFile) + if (cachedLink) { + return cachedLink + } + + const href = getAssetPath(cssFile) + const link = href satisfies ManifestCssLink + + stylesheetLinkByFileName.set(cssFile, link) + return link + } + + // One depth-first walk over the static import graph serves both preloads and + // stylesheets. `imports` lists direct imports only, so transitive chunks are + // only reached by walking the graph. The walk records the file names it + // discovers for preloads and the chunks in post-order so dependency CSS + // precedes importer CSS. Cycles are cut by the seen set, so every chunk in a + // cycle still sees the whole cycle from its own walk. + const getStaticImportClosure = (chunk: NormalizedClientChunk) => { + const cachedClosure = closureByChunk.get(chunk) + if (cachedClosure) { + return cachedClosure + } + + const seen = new Set([chunk.fileName]) + const fileNames: Array = [] + const dependenciesFirst: Array = [] + const stack: Array<{ chunk: NormalizedClientChunk; index: number }> = [ + { chunk, index: 0 }, + ] + + while (stack.length > 0) { + const frame = stack[stack.length - 1]! + + if (frame.index < frame.chunk.imports.length) { + const fileName = frame.chunk.imports[frame.index++]! + if (seen.has(fileName)) { + continue + } + + seen.add(fileName) + fileNames.push(fileName) + + const importedChunk = chunksByFileName.get(fileName) + if (importedChunk) { + stack.push({ chunk: importedChunk, index: 0 }) + } + continue + } + + stack.pop() + dependenciesFirst.push(frame.chunk) + } + + const closure = { fileNames, dependenciesFirst } + closureByChunk.set(chunk, closure) + return closure + } + + const getChunkPreloads = (chunk: NormalizedClientChunk) => { + const cachedPreloads = preloadsByChunk.get(chunk) + if (cachedPreloads) { + return cachedPreloads + } + + const { fileNames } = getStaticImportClosure(chunk) + const preloads = [getAssetPath(chunk.fileName)] + + for (let i = 0; i < fileNames.length; i++) { + preloads.push(getAssetPath(fileNames[i]!)) + } + + preloadsByChunk.set(chunk, preloads) + return preloads + } + + const getChunkCssAssets = (chunk: NormalizedClientChunk) => { + const cachedLinks = cssAssetsByChunk.get(chunk) + if (cachedLinks) { + return cachedLinks + } + + const { dependenciesFirst } = getStaticImportClosure(chunk) + const links: Array = [] + const seenLinks = new Set() + + for (let i = 0; i < dependenciesFirst.length; i++) { + for (const cssFile of dependenciesFirst[i]!.css) { + const link = getStylesheetLink(cssFile) + if (!seenLinks.has(link)) { + seenLinks.add(link) + links.push(link) + } + } + } + + cssAssetsByChunk.set(chunk, links) + return links + } + + return { + getAssetPath, + getChunkPreloads, + getChunkCssAssets, + getStylesheetLink, + } +} + +function buildInlineCssManifestData(options: { + routes: Record + basePath: string + cssContentByFileName: ReadonlyMap | undefined + transformAssets: boolean +}): StartManifest['inlineCss'] { + const stylesheetHrefs = new Set() + + for (const route of Object.values(options.routes)) { + for (const link of route.css ?? []) { + stylesheetHrefs.add(getStylesheetHref(link)) + } + } + + if (stylesheetHrefs.size === 0) { + return { styles: {} } + } + + if (!options.cssContentByFileName) { + throw new Error( + 'TanStack Start inlineCss is enabled, but the client build did not provide CSS content', + ) + } + + const styles: Record = {} + let templates: Record | undefined + const missingHrefs = new Set(stylesheetHrefs) + + for (const [cssFile, css] of options.cssContentByFileName) { + const cssHref = joinURL(options.basePath, cssFile) + if (!stylesheetHrefs.has(cssHref)) { + continue + } + + const result = processInlineCssUrls({ + css, + cssHref, + templates: options.transformAssets, + }) + + styles[cssHref] = result.css + if (result.template) { + templates ||= {} + templates[cssHref] = result.template + } + missingHrefs.delete(cssHref) + } + + if (missingHrefs.size > 0) { + throw new Error( + `TanStack Start inlineCss could not find CSS content for: ${Array.from( + missingHrefs, + ).join(', ')}`, + ) + } + + return { + styles, + ...(templates ? { templates } : {}), + } +} + +export function buildRouteManifestRoutes(options: { + routeTreeRoutes: RouteTreeRoutes + routeChunksByFilePath: ReadonlyMap< + string, + ReadonlyArray + > + chunksByFileName: ReadonlyMap + entryChunk: NormalizedClientChunk + assetResolvers: ManifestAssetResolvers + additionalRouteAssets?: Partial< + Record> + > +}) { + const routes: Record = {} + const getChunkCssAssets = options.assetResolvers.getChunkCssAssets + + for (const [routeId, route] of Object.entries(options.routeTreeRoutes)) { + if (!route.filePath) { + if (routeId === rootRouteId) { + routes[routeId] = { ...route } + continue + } + + throw new Error(`expected filePath to be set for ${routeId}`) + } + + const chunks = options.routeChunksByFilePath.get(route.filePath) + if (!chunks) { + routes[routeId] = { ...route } + continue + } + + const existing = routes[routeId] + const targetRoute = (routes[routeId] = existing ? existing : { ...route }) + + for (const chunk of chunks) { + mergeRouteChunkData({ + route: targetRoute, + chunk, + getChunkCssAssets, + getChunkPreloads: options.assetResolvers.getChunkPreloads, + }) + + if (routeId !== rootRouteId) { + mergeReachableHydrationChunkData({ + route: targetRoute, + chunk, + chunksByFileName: options.chunksByFileName, + getChunkCssAssets, + }) + } + } + } + + const rootRoute = (routes[rootRouteId] = routes[rootRouteId] || {}) + const rootRouteTreeRoute = options.routeTreeRoutes[rootRouteId] + const rootRouteChunks = rootRouteTreeRoute?.filePath + ? options.routeChunksByFilePath.get(rootRouteTreeRoute.filePath) + : undefined + + if (rootRouteChunks) { + for (const chunk of rootRouteChunks) { + mergeReachableHydrationChunkData({ + route: rootRoute, + chunk, + chunksByFileName: options.chunksByFileName, + getChunkCssAssets, + }) + } + } + + mergeRouteChunkData({ + route: rootRoute, + chunk: options.entryChunk, + getChunkCssAssets, + getChunkPreloads: options.assetResolvers.getChunkPreloads, + }) + + if (options.additionalRouteAssets) { + for (const [routeId, assets] of Object.entries( + options.additionalRouteAssets, + )) { + if (!assets || assets.length === 0) { + continue + } + + if (!(routeId in options.routeTreeRoutes)) { + throw new Error( + `expected additionalRouteAssets routeId to exist in routeTreeRoutes: ${routeId}`, + ) + } + + const route = (routes[routeId] = routes[routeId] || {}) + appendAdditionalRouteEntries(route, assets) + } + } + + return routes +} + +function mergeReachableHydrationChunkData(options: { + route: RouteTreeRoute + chunk: NormalizedClientChunk + chunksByFileName: ReadonlyMap + getChunkCssAssets: (chunk: NormalizedClientChunk) => Array +}) { + const visitedStaticChunks = new Set() + const mergedHydrationChunks = new Set() + + const mergeHydrationChunk = (chunk: NormalizedClientChunk) => { + if (mergedHydrationChunks.has(chunk.fileName)) { + return + } + mergedHydrationChunks.add(chunk.fileName) + + appendRouteStylesheets(options.route, options.getChunkCssAssets(chunk)) + + for (const dynamicImport of chunk.dynamicImports) { + const dynamicChunk = options.chunksByFileName.get(dynamicImport) + if (dynamicChunk?.hydrationIds.length) { + mergeHydrationChunk(dynamicChunk) + } + } + } + + const visitStaticChunk = (chunk: NormalizedClientChunk) => { + if (visitedStaticChunks.has(chunk.fileName)) { + return + } + visitedStaticChunks.add(chunk.fileName) + + for (const importedFileName of chunk.imports) { + const importedChunk = options.chunksByFileName.get(importedFileName) + if (importedChunk) { + visitStaticChunk(importedChunk) + } + } + + for (const dynamicImport of chunk.dynamicImports) { + const dynamicChunk = options.chunksByFileName.get(dynamicImport) + if (dynamicChunk?.hydrationIds.length) { + mergeHydrationChunk(dynamicChunk) + } + } + } + + visitStaticChunk(options.chunk) +} + +function dedupeNestedRouteManifestEntries( + routeId: string, + route: DedupeRoute, + routesById: Record, + seenPreloads = new Set(), + seenScripts = new Set(), + seenStylesheets = new Set(), +) { + let routePreloads = route.preloads + let routeScripts = route.scripts + let routeStylesheets = route.css + + if (routePreloads && routePreloads.length > 0) { + let dedupedPreloads: Array | undefined + + for (let i = 0; i < routePreloads.length; i++) { + const preload = routePreloads[i]! + const preloadHref = resolveManifestAssetLink(preload).href + + if (seenPreloads.has(preloadHref)) { + if (dedupedPreloads === undefined) { + dedupedPreloads = routePreloads.slice(0, i) + } + continue + } + + seenPreloads.add(preloadHref) + + if (dedupedPreloads) { + dedupedPreloads.push(preload) + } + } + + if (dedupedPreloads) { + routePreloads = dedupedPreloads + route.preloads = dedupedPreloads + } + } + + if (routeScripts && routeScripts.length > 0) { + let dedupedScripts: Array | undefined + + for (let i = 0; i < routeScripts.length; i++) { + const script = routeScripts[i]! + const identity = getScriptIdentity(script) + + if (seenScripts.has(identity)) { + if (dedupedScripts === undefined) { + dedupedScripts = routeScripts.slice(0, i) + } + continue + } + + seenScripts.add(identity) + + if (dedupedScripts) { + dedupedScripts.push(script) + } + } + + if (dedupedScripts) { + routeScripts = dedupedScripts + if (dedupedScripts.length > 0) { + route.scripts = dedupedScripts + } else { + delete route.scripts + } + } + } + + if (routeStylesheets && routeStylesheets.length > 0) { + let dedupedStylesheets: Array | undefined + + for (let i = 0; i < routeStylesheets.length; i++) { + const stylesheet = routeStylesheets[i]! + const identity = getStylesheetIdentity(stylesheet) + + if (seenStylesheets.has(identity)) { + if (dedupedStylesheets === undefined) { + dedupedStylesheets = routeStylesheets.slice(0, i) + } + continue + } + + seenStylesheets.add(identity) + + if (dedupedStylesheets) { + dedupedStylesheets.push(stylesheet) + } + } + + if (dedupedStylesheets) { + routeStylesheets = dedupedStylesheets + if (dedupedStylesheets.length > 0) { + route.css = dedupedStylesheets + } else { + delete route.css + } + } + } + + if (route.children) { + for (const childRouteId of route.children) { + const childRoute = routesById[childRouteId] + + if (!childRoute) { + throw new Error( + `Route tree references child route ${childRouteId} from ${routeId}, but no route entry was found`, + ) + } + + dedupeNestedRouteManifestEntries( + childRouteId, + childRoute, + routesById, + seenPreloads, + seenScripts, + seenStylesheets, + ) + } + } + + if (routePreloads) { + for (let i = routePreloads.length - 1; i >= 0; i--) { + seenPreloads.delete(resolveManifestAssetLink(routePreloads[i]!).href) + } + } + + if (routeScripts) { + for (let i = routeScripts.length - 1; i >= 0; i--) { + seenScripts.delete(getScriptIdentity(routeScripts[i]!)) + } + } + + if (routeStylesheets) { + for (let i = routeStylesheets.length - 1; i >= 0; i--) { + seenStylesheets.delete(getStylesheetIdentity(routeStylesheets[i]!)) + } + } +} diff --git a/packages/start-plugin-core/src/start-manifest-plugin/plugin.ts b/packages/start-plugin-core/src/start-manifest-plugin/plugin.ts deleted file mode 100644 index 059116839a..0000000000 --- a/packages/start-plugin-core/src/start-manifest-plugin/plugin.ts +++ /dev/null @@ -1,280 +0,0 @@ -import { joinURL } from 'ufo' -import { rootRouteId } from '@tanstack/router-core' -import { VIRTUAL_MODULES } from '@tanstack/start-server-core' -import { tsrSplit } from '@tanstack/router-plugin' -import { resolveViteId } from '../utils' -import { ENTRY_POINTS } from '../constants' -import type { GetConfigFn } from '../plugin' -import type { PluginOption, Rollup } from 'vite' -import type { Manifest, RouterManagedTag } from '@tanstack/router-core' - -const getCSSRecursively = ( - chunk: Rollup.OutputChunk, - chunksByFileName: Map, - basePath: string, - cache: Map>, - visited = new Set(), -) => { - if (visited.has(chunk)) { - return [] - } - visited.add(chunk) - const cachedResult = cache.get(chunk) - if (cachedResult) { - return cachedResult - } - const result: Array = [] - - // Get all css imports from the file - for (const cssFile of chunk.viteMetadata?.importedCss ?? []) { - result.push({ - tag: 'link', - attrs: { - rel: 'stylesheet', - href: joinURL(basePath, cssFile), - type: 'text/css', - }, - }) - } - - // Recursively get CSS from imports - for (const importedFileName of chunk.imports) { - const importedChunk = chunksByFileName.get(importedFileName) - if (importedChunk) { - result.push( - ...getCSSRecursively( - importedChunk, - chunksByFileName, - basePath, - cache, - visited, - ), - ) - } - } - - cache.set(chunk, result) - return result -} - -const resolvedModuleId = resolveViteId(VIRTUAL_MODULES.startManifest) -export function startManifestPlugin(opts: { - getClientBundle: () => Rollup.OutputBundle - getConfig: GetConfigFn -}): PluginOption { - return { - name: 'tanstack-start:start-manifest-plugin', - enforce: 'pre', - resolveId: { - filter: { id: new RegExp(VIRTUAL_MODULES.startManifest) }, - handler(id) { - if (id === VIRTUAL_MODULES.startManifest) { - return resolvedModuleId - } - return undefined - }, - }, - load: { - filter: { - id: new RegExp(resolvedModuleId), - }, - handler(id) { - const { resolvedStartConfig } = opts.getConfig() - if (id === resolvedModuleId) { - if (this.environment.config.consumer !== 'server') { - // this will ultimately fail the build if the plugin is used outside the server environment - // TODO: do we need special handling for `serve`? - return `export default {}` - } - - // If we're in development, return a dummy manifest - if (this.environment.config.command === 'serve') { - return `export const tsrStartManifest = () => ({ - routes: {}, - clientEntry: '${joinURL(resolvedStartConfig.viteAppBase, '@id', ENTRY_POINTS.client)}', - })` - } - - // This the manifest pulled from the generated route tree and later used by the Router. - // i.e what's located in `src/routeTree.gen.ts` - const routeTreeRoutes = globalThis.TSS_ROUTES_MANIFEST - - const cssPerChunkCache = new Map< - Rollup.OutputChunk, - Array - >() - - // This is where hydration will start, from when the SSR'd page reaches the browser. - let entryFile: Rollup.OutputChunk | undefined - - const clientBundle = opts.getClientBundle() - const chunksByFileName = new Map() - - const routeChunks: Record< - string /** fullPath of route file **/, - Array - > = {} - for (const bundleEntry of Object.values(clientBundle)) { - if (bundleEntry.type === 'chunk') { - chunksByFileName.set(bundleEntry.fileName, bundleEntry) - if (bundleEntry.isEntry) { - if (entryFile) { - throw new Error( - `multiple entries detected: ${entryFile.fileName} ${bundleEntry.fileName}`, - ) - } - entryFile = bundleEntry - } - const routePieces = bundleEntry.moduleIds.flatMap((m) => { - const [id, query] = m.split('?') - if (id === undefined) { - throw new Error('expected id to be defined') - } - if (query === undefined) { - return [] - } - const searchParams = new URLSearchParams(query) - const split = searchParams.get(tsrSplit) - - if (split !== null) { - return { - id, - split, - } - } - return [] - }) - if (routePieces.length > 0) { - routePieces.forEach((r) => { - let array = routeChunks[r.id] - if (array === undefined) { - array = [] - routeChunks[r.id] = array - } - array.push(bundleEntry) - }) - } - } - } - - const manifest: Manifest = { routes: {} } - // Add preloads to the routes from the vite manifest - Object.entries(routeTreeRoutes).forEach(([routeId, v]) => { - if (!v.filePath) { - throw new Error(`expected filePath to be set for ${routeId}`) - } - const chunks = routeChunks[v.filePath] - if (chunks) { - chunks.forEach((chunk) => { - // Map the relevant imports to their route paths, - // so that it can be imported in the browser. - const preloads = chunk.imports.map((d) => { - const preloadPath = joinURL( - resolvedStartConfig.viteAppBase, - d, - ) - return preloadPath - }) - - // Since this is the most important JS entry for the route, - // it should be moved to the front of the preloads so that - // it has the best chance of being loaded first. - preloads.unshift( - joinURL(resolvedStartConfig.viteAppBase, chunk.fileName), - ) - - const assets = getCSSRecursively( - chunk, - chunksByFileName, - resolvedStartConfig.viteAppBase, - cssPerChunkCache, - ) - - manifest.routes[routeId] = { - ...v, - assets, - preloads, - } - }) - } else { - manifest.routes[routeId] = v - } - }) - - if (!entryFile) { - throw new Error('No entry file found') - } - - manifest.routes[rootRouteId] = manifest.routes[rootRouteId] || {} - manifest.routes[rootRouteId].preloads = [ - joinURL(resolvedStartConfig.viteAppBase, entryFile.fileName), - ...entryFile.imports.map((d) => - joinURL(resolvedStartConfig.viteAppBase, d), - ), - ] - - // Gather all the CSS files from the entry file in - // the `css` key and add them to the root route - const entryCssAssetsList = getCSSRecursively( - entryFile, - chunksByFileName, - resolvedStartConfig.viteAppBase, - cssPerChunkCache, - ) - - manifest.routes[rootRouteId].assets = [ - ...(manifest.routes[rootRouteId].assets || []), - ...entryCssAssetsList, - ] - - const recurseRoute = ( - route: { - preloads?: Array - children?: Array - }, - seenPreloads = {} as Record, - ) => { - route.preloads = route.preloads?.filter((preload) => { - if (seenPreloads[preload]) { - return false - } - seenPreloads[preload] = true - return true - }) - - if (route.children) { - route.children.forEach((child) => { - const childRoute = manifest.routes[child]! - recurseRoute(childRoute, { ...seenPreloads }) - }) - } - } - - recurseRoute(manifest.routes[rootRouteId]) - - // Filter out routes that have neither assets nor preloads - Object.keys(manifest.routes).forEach((routeId) => { - const route = manifest.routes[routeId]! - const hasAssets = route.assets && route.assets.length > 0 - const hasPreloads = route.preloads && route.preloads.length > 0 - if (!hasAssets && !hasPreloads) { - delete routeTreeRoutes[routeId] - } - }) - - const startManifest = { - routes: manifest.routes, - clientEntry: joinURL( - resolvedStartConfig.viteAppBase, - entryFile.fileName, - ), - } - - return `export const tsrStartManifest = () => (${JSON.stringify(startManifest)})` - } - - return undefined - }, - }, - } -} diff --git a/packages/start-plugin-core/src/start-router-plugin/generator-config.ts b/packages/start-plugin-core/src/start-router-plugin/generator-config.ts new file mode 100644 index 0000000000..3d3e5ea086 --- /dev/null +++ b/packages/start-plugin-core/src/start-router-plugin/generator-config.ts @@ -0,0 +1,41 @@ +import path from 'pathe' +import { buildRouteTreeFileFooterFromConfig } from './route-tree-footer' +import { routesManifestPlugin } from './generator-plugins/routes-manifest-plugin' +import { prerenderRoutesPlugin } from './generator-plugins/prerender-routes-plugin' +import type { GeneratorPlugin } from '@tanstack/router-generator' +import type { Config } from '@tanstack/router-plugin' +import type { GetConfigFn, TanStackStartCoreOptions } from '../types' + +/** + * The route generator configuration of a Start app, the same for the Vite + * and Rsbuild plugins: the app's router options as the Start config parsed + * them, the framework's target, Start's route tree footer (the router and + * Start config types, then the app's own lines; computed at every print, as + * a router app's function-form `routeTreeFileFooter` is), and the generator + * plugins: the client route tree (Vite), the routes manifest, prerendering + * when enabled, and the app's own (#7768). + */ +export function startGeneratorConfig(opts: { + getConfig: GetConfigFn + corePluginOpts: TanStackStartCoreOptions + prerender: boolean + clientRouteTree?: GeneratorPlugin +}): Config { + const router = opts.getConfig().startConfig.router + return { + ...router, + target: opts.corePluginOpts.framework, + routeTreeFileFooter: () => + buildRouteTreeFileFooterFromConfig({ + generatedRouteTreePath: path.resolve(router.generatedRouteTree), + getConfig: opts.getConfig, + corePluginOpts: opts.corePluginOpts, + }), + plugins: [ + ...(opts.clientRouteTree ? [opts.clientRouteTree] : []), + routesManifestPlugin(), + ...(opts.prerender ? [prerenderRoutesPlugin()] : []), + ...(router.plugins ?? []), + ], + } +} diff --git a/packages/start-plugin-core/src/start-router-plugin/plugin.ts b/packages/start-plugin-core/src/start-router-plugin/plugin.ts deleted file mode 100644 index 4543eac384..0000000000 --- a/packages/start-plugin-core/src/start-router-plugin/plugin.ts +++ /dev/null @@ -1,253 +0,0 @@ -import { - tanStackRouterCodeSplitter, - tanstackRouterAutoImport, - tanstackRouterGenerator, -} from '@tanstack/router-plugin/vite' -import { normalizePath } from 'vite' -import path from 'pathe' -import { VITE_ENVIRONMENT_NAMES } from '../constants' -import { routesManifestPlugin } from './generator-plugins/routes-manifest-plugin' -import { prerenderRoutesPlugin } from './generator-plugins/prerender-routes-plugin' -import { pruneServerOnlySubtrees } from './pruneServerOnlySubtrees' -import { SERVER_PROP } from './constants' -import type { - Generator, - GeneratorPlugin, - RouteNode, -} from '@tanstack/router-generator' -import type { DevEnvironment, Plugin, PluginOption } from 'vite' -import type { TanStackStartInputConfig } from '../schema' -import type { GetConfigFn, TanStackStartVitePluginCoreOptions } from '../plugin' - -function isServerOnlyNode(node: RouteNode | undefined) { - if (!node?.createFileRouteProps) { - return false - } - return ( - node.createFileRouteProps.has(SERVER_PROP) && - node.createFileRouteProps.size === 1 - ) -} - -function moduleDeclaration({ - startFilePath, - routerFilePath, - corePluginOpts, - generatedRouteTreePath, -}: { - startFilePath: string | undefined - routerFilePath: string - corePluginOpts: TanStackStartVitePluginCoreOptions - generatedRouteTreePath: string -}): string { - function getImportPath(absolutePath: string) { - let relativePath = path.relative( - path.dirname(generatedRouteTreePath), - absolutePath, - ) - - if (!relativePath.startsWith('.')) { - relativePath = './' + relativePath - } - - // convert to POSIX-style for ESM imports (important on Windows) - relativePath = relativePath.split(path.sep).join('/') - return relativePath - } - - const result: Array = [ - `import type { getRouter } from '${getImportPath(routerFilePath)}'`, - ] - if (startFilePath) { - result.push( - `import type { startInstance } from '${getImportPath(startFilePath)}'`, - ) - } - // make sure we import something from start to get the server route declaration merge - else { - result.push( - `import type { createStart } from '@tanstack/${corePluginOpts.framework}-start'`, - ) - } - result.push( - `declare module '@tanstack/${corePluginOpts.framework}-start' { - interface Register { - ssr: true - router: Awaited>`, - ) - if (startFilePath) { - result.push( - ` config: Awaited>`, - ) - } - result.push(` } -}`) - - return result.join('\n') -} - -export function tanStackStartRouter( - startPluginOpts: TanStackStartInputConfig, - getConfig: GetConfigFn, - corePluginOpts: TanStackStartVitePluginCoreOptions, -): Array { - const getGeneratedRouteTreePath = () => { - const { startConfig } = getConfig() - return path.resolve(startConfig.router.generatedRouteTree) - } - - let clientEnvironment: DevEnvironment | null = null - function invalidate() { - if (!clientEnvironment) { - return - } - - const mod = clientEnvironment.moduleGraph.getModuleById( - getGeneratedRouteTreePath(), - ) - if (mod) { - clientEnvironment.moduleGraph.invalidateModule(mod) - } - clientEnvironment.hot.send({ type: 'full-reload', path: '*' }) - } - - let generatorInstance: Generator | null = null - - const clientTreeGeneratorPlugin: GeneratorPlugin = { - name: 'start-client-tree-plugin', - init({ generator }) { - generatorInstance = generator - }, - afterTransform({ node, prevNode }) { - if (isServerOnlyNode(node) !== isServerOnlyNode(prevNode)) { - invalidate() - } - }, - } - - let routeTreeFileFooter: Array | null = null - - function getRouteTreeFileFooter() { - if (routeTreeFileFooter) { - return routeTreeFileFooter - } - const { startConfig, resolvedStartConfig } = getConfig() - const ogRouteTreeFileFooter = startConfig.router.routeTreeFileFooter - if (ogRouteTreeFileFooter) { - if (Array.isArray(ogRouteTreeFileFooter)) { - routeTreeFileFooter = ogRouteTreeFileFooter - } else { - routeTreeFileFooter = ogRouteTreeFileFooter() - } - } - routeTreeFileFooter = [ - moduleDeclaration({ - generatedRouteTreePath: getGeneratedRouteTreePath(), - corePluginOpts, - startFilePath: resolvedStartConfig.startFilePath, - routerFilePath: resolvedStartConfig.routerFilePath, - }), - ...(routeTreeFileFooter ?? []), - ] - return routeTreeFileFooter - } - - let resolvedGeneratedRouteTreePath: string | null = null - const clientTreePlugin: Plugin = { - name: 'tanstack-start:route-tree-client-plugin', - enforce: 'pre', - applyToEnvironment: (env) => env.name === VITE_ENVIRONMENT_NAMES.client, - configureServer(server) { - clientEnvironment = server.environments[VITE_ENVIRONMENT_NAMES.client] - }, - config() { - type LoadObjectHook = Extract< - typeof clientTreePlugin.load, - { filter?: unknown } - > - resolvedGeneratedRouteTreePath = normalizePath( - getGeneratedRouteTreePath(), - ) - ;(clientTreePlugin.load as LoadObjectHook).filter = { - id: { include: new RegExp(resolvedGeneratedRouteTreePath) }, - } - }, - - load: { - filter: { - // this will be set in the config hook above since it relies on `config` hook being called first - }, - async handler() { - if (!generatorInstance) { - throw new Error('Generator instance not initialized') - } - const crawlingResult = await generatorInstance.getCrawlingResult() - if (!crawlingResult) { - throw new Error('Crawling result not available') - } - const prunedAcc = pruneServerOnlySubtrees(crawlingResult) - const acc = { - ...crawlingResult.acc, - ...prunedAcc, - } - const buildResult = generatorInstance.buildRouteTree({ - ...crawlingResult, - acc, - config: { - // importRoutesUsingAbsolutePaths: true, - // addExtensions: true, - disableTypes: true, - enableRouteTreeFormatting: false, - routeTreeFileHeader: [], - routeTreeFileFooter: [], - }, - }) - return { code: buildResult.routeTreeContent, map: null } - }, - }, - } - return [ - clientTreePlugin, - tanstackRouterGenerator(() => { - const routerConfig = getConfig().startConfig.router - const plugins = [clientTreeGeneratorPlugin, routesManifestPlugin()] - if (startPluginOpts?.prerender?.enabled === true) { - plugins.push(prerenderRoutesPlugin()) - } - return { - ...routerConfig, - target: corePluginOpts.framework, - routeTreeFileFooter: getRouteTreeFileFooter, - plugins, - } - }), - tanStackRouterCodeSplitter(() => { - const routerConfig = getConfig().startConfig.router - return { - ...routerConfig, - codeSplittingOptions: { - ...routerConfig.codeSplittingOptions, - deleteNodes: ['ssr', 'server', 'headers'], - addHmr: true, - }, - plugin: { - vite: { environmentName: VITE_ENVIRONMENT_NAMES.client }, - }, - } - }), - tanStackRouterCodeSplitter(() => { - const routerConfig = getConfig().startConfig.router - return { - ...routerConfig, - codeSplittingOptions: { - ...routerConfig.codeSplittingOptions, - addHmr: false, - }, - plugin: { - vite: { environmentName: VITE_ENVIRONMENT_NAMES.server }, - }, - } - }), - tanstackRouterAutoImport(startPluginOpts?.router), - ] -} diff --git a/packages/start-plugin-core/src/start-router-plugin/route-tree-footer.ts b/packages/start-plugin-core/src/start-router-plugin/route-tree-footer.ts new file mode 100644 index 0000000000..c56ffbf90d --- /dev/null +++ b/packages/start-plugin-core/src/start-router-plugin/route-tree-footer.ts @@ -0,0 +1,99 @@ +import path from 'pathe' +import type { GetConfigFn, TanStackStartCoreOptions } from '../types' + +function buildRouteTreeFileFooter(opts: { + generatedRouteTreePath: string + startFilePath: string | undefined + routerFilePath: string + framework: TanStackStartCoreOptions['framework'] + userFooter?: Array | (() => Array) +}): Array { + function getImportPath(absolutePath: string) { + let relativePath = path.relative( + path.dirname(opts.generatedRouteTreePath), + absolutePath, + ) + + if (!relativePath.startsWith('.')) { + relativePath = './' + relativePath + } + + return relativePath.split(path.sep).join('/') + } + + function appendFooterBlock(lines: Array, block: string) { + if (!block) { + return + } + + if (lines.length > 0) { + lines[lines.length - 1] += `\n${block}` + return + } + + lines.push(block) + } + + const footer: Array = [] + + appendFooterBlock( + footer, + `import type { getRouter } from '${getImportPath(opts.routerFilePath)}'`, + ) + + if (opts.startFilePath) { + appendFooterBlock( + footer, + `import type { startInstance } from '${getImportPath(opts.startFilePath)}'`, + ) + } else { + appendFooterBlock( + footer, + `import type { createStart } from '@tanstack/${opts.framework}-start'`, + ) + } + + appendFooterBlock( + footer, + `declare module '@tanstack/${opts.framework}-start' { + interface Register { + ssr: true + router: Awaited>`, + ) + + if (opts.startFilePath) { + appendFooterBlock( + footer, + ` config: Awaited>`, + ) + } + + appendFooterBlock( + footer, + ` } +}`, + ) + + if (opts.userFooter) { + footer.push( + ...(Array.isArray(opts.userFooter) ? opts.userFooter : opts.userFooter()), + ) + } + + return footer +} + +export function buildRouteTreeFileFooterFromConfig(opts: { + generatedRouteTreePath: string + getConfig: GetConfigFn + corePluginOpts: TanStackStartCoreOptions +}): Array { + const { startConfig, resolvedStartConfig } = opts.getConfig() + return buildRouteTreeFileFooter({ + generatedRouteTreePath: opts.generatedRouteTreePath, + startFilePath: resolvedStartConfig.startFilePath, + routerFilePath: resolvedStartConfig.routerFilePath, + framework: opts.corePluginOpts.framework, + userFooter: startConfig.router.routeTreeFileFooter, + }) +} diff --git a/packages/start-plugin-core/src/types.ts b/packages/start-plugin-core/src/types.ts new file mode 100644 index 0000000000..db94e343d5 --- /dev/null +++ b/packages/start-plugin-core/src/types.ts @@ -0,0 +1,157 @@ +import type * as babel from '@babel/core' +import type * as t from '@babel/types' +import type { GeneratorResult } from '@tanstack/router-utils' +import type { TanStackStartOutputConfig } from './schema' + +export type CompileStartFrameworkOptions = 'react' | 'solid' | 'vue' + +export type ServerFnLookupAccess = { origin: 'client' } | { origin: 'server' } + +export type SerializationRuntime = 'client' | 'server' + +export interface SerializationAdapterModuleRef { + module: string + export: string + isFactory?: boolean +} + +export type SerializationAdapterByRuntime = Partial< + Record +> + +export type SerializationAdapterConfig = + | SerializationAdapterModuleRef + | SerializationAdapterByRuntime + +export type StartCompilerEnvironment = 'client' | 'server' + +export interface StartCompilerImportTransformImport { + libName: string + rootExport: string +} + +export interface StartCompilerTransformCandidate { + path: babel.NodePath +} + +export interface StartCompilerTransformContext { + readonly ast: t.File + readonly code: string + readonly id: string + readonly env: StartCompilerEnvironment + readonly envName: string + readonly mode: 'dev' | 'build' + readonly root: string + readonly framework: CompileStartFrameworkOptions + readonly providerEnvName: string + readonly types: typeof t + parseExpression: (code: string) => t.Expression + warn?: (message: string) => void +} + +export interface StartCompilerImportTransform { + name: string + environment?: + | StartCompilerEnvironment + | Array + | undefined + imports: Array + detect: RegExp + order?: 'pre' | 'post' | undefined + transform: ( + candidates: Array, + context: StartCompilerTransformContext, + ) => void +} + +export interface StartCompilerTransformResult { + code: string + map?: GeneratorResult['map'] | null +} + +export interface StartCompilerVirtualModuleContext { + readonly id: string + readonly root: string + readonly env: StartCompilerEnvironment + readonly envName: string + readonly code?: string +} + +export interface StartCompilerPlugin { + name: string + environment?: + | StartCompilerEnvironment + | Array + | undefined + detect?: RegExp | undefined + virtualModuleIdPattern?: RegExp | undefined + transformAst?: ( + context: StartCompilerTransformContext, + ) => boolean | null | undefined + loadVirtualModule?: ( + context: StartCompilerVirtualModuleContext, + ) => StartCompilerTransformResult | null + invalidateModule?: (context: { id: string; envName: string }) => void +} + +export interface NormalizedBasePaths { + publicBase: string + assetBase: { + dev: string + build: string + } +} + +export interface NormalizedOutputDirectories { + client: string + server: string +} + +export interface NormalizedClientChunk { + fileName: string + isEntry: boolean + /** + * Chunks this chunk imports statically. Rolldown and Rsbuild report direct + * imports only, so consumers must walk the graph to reach transitive chunks + * instead of treating the list as complete. + */ + imports: Array + dynamicImports: Array + css: Array + routeFilePaths: Array + hydrationIds: Array +} + +export interface NormalizedClientBuild { + entryChunkFileName: string + chunksByFileName: ReadonlyMap + cssContentByFileName?: ReadonlyMap +} + +export interface TanStackStartCoreOptions { + framework: CompileStartFrameworkOptions + defaultEntryPaths: { + client: string + server: string + start: string + } + providerEnvironmentName: string + ssrIsProvider: boolean + serializationAdapters?: Array | undefined + compilerTransforms?: Array | undefined + serverFnProviderModuleDirectives?: ReadonlyArray | undefined +} + +export interface ResolvedStartConfig { + root: string + startFilePath: string | undefined + routerFilePath: string + srcDirectory: string + basePaths: NormalizedBasePaths + outputDirectories: NormalizedOutputDirectories +} + +export type GetConfigFn = () => { + startConfig: TanStackStartOutputConfig + resolvedStartConfig: ResolvedStartConfig +} diff --git a/packages/start-plugin-core/src/utils.ts b/packages/start-plugin-core/src/utils.ts index 252712ef66..2fb1bb5b69 100644 --- a/packages/start-plugin-core/src/utils.ts +++ b/packages/start-plugin-core/src/utils.ts @@ -1,7 +1,30 @@ +import path from 'node:path' + +const isWindows: boolean = + typeof process !== 'undefined' && process.platform === 'win32' +const windowsSlashRE = /\\/g + +/** + * Read `build.rolldownOptions` from a build config. Vite 8 still accepts + * `build.rollupOptions` as a deprecated alias, and a user config can reach a + * plugin before Vite maps it. + */ +export function getBundlerOptions(build: any): any { + return build?.rolldownOptions ?? build?.rollupOptions +} + export function resolveViteId(id: string) { return `\0${id}` } +export function createIdFilter(ids: Array): RegExp { + return new RegExp(`^(?:${ids.map(escapeRegExp).join('|')})$`) +} + +export function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + export function createLogger(prefix: string) { const label = `[${prefix}]` return { @@ -12,3 +35,11 @@ export function createLogger(prefix: string) { error: (...args: any) => console.error(label, ...args), } } + +function slash(path: string): string { + return path.replace(windowsSlashRE, '/') +} + +export function normalizePath(id: string): string { + return path.posix.normalize(isWindows ? slash(id) : id) +} diff --git a/packages/start-plugin-core/src/vite/bundled-dev.ts b/packages/start-plugin-core/src/vite/bundled-dev.ts new file mode 100644 index 0000000000..a60be55efb --- /dev/null +++ b/packages/start-plugin-core/src/vite/bundled-dev.ts @@ -0,0 +1,7 @@ +import type { DevEnvironment } from 'vite' + +export async function ensureLatestClientBuild(environment: DevEnvironment) { + // Vite has no public API for awaiting bundled client output in custom SSR + // (vitejs/vite#22991). Bracket access allows using its private engine here. + await environment.bundledDev!['devEngine'].ensureLatestBuildOutput() +} diff --git a/packages/start-plugin-core/src/vite/createVirtualModule.ts b/packages/start-plugin-core/src/vite/createVirtualModule.ts new file mode 100644 index 0000000000..1c076a3c7c --- /dev/null +++ b/packages/start-plugin-core/src/vite/createVirtualModule.ts @@ -0,0 +1,50 @@ +import { createIdFilter, resolveViteId } from '../utils' +import type { Plugin } from 'vite' + +type VirtualModuleLoadHandler = ( + this: any, + id: string, +) => string | null | undefined | Promise + +export function createVirtualModule(opts: { + name: string + moduleId: string + load: VirtualModuleLoadHandler + apply?: Plugin['apply'] + applyToEnvironment?: Plugin['applyToEnvironment'] + enforce?: Plugin['enforce'] + sharedDuringBuild?: boolean +}): Plugin { + // Encode '#' as '%23' in the resolved ID to avoid browser treating it as URL fragment. + // The browser requests /@id/__x00__%23tanstack-start-plugin-adapters instead of + // /@id/__x00__#tanstack-start-plugin-adapters (which would truncate at #). + const resolvedId = resolveViteId(opts.moduleId.replaceAll('#', '%23')) + + return { + name: opts.name, + apply: opts.apply, + applyToEnvironment: opts.applyToEnvironment, + enforce: opts.enforce, + sharedDuringBuild: opts.sharedDuringBuild, + resolveId: { + filter: { id: createIdFilter([opts.moduleId]) }, + handler(id) { + if (id === opts.moduleId) { + return resolvedId + } + + return undefined + }, + }, + load: { + filter: { id: createIdFilter([resolvedId]) }, + handler(id) { + if (id !== resolvedId) { + return undefined + } + + return opts.load.call(this, id) + }, + }, + } +} diff --git a/packages/start-plugin-core/src/vite/dev-server-plugin/dev-styles.ts b/packages/start-plugin-core/src/vite/dev-server-plugin/dev-styles.ts new file mode 100644 index 0000000000..0470d8c1e4 --- /dev/null +++ b/packages/start-plugin-core/src/vite/dev-server-plugin/dev-styles.ts @@ -0,0 +1,402 @@ +/** + * CSS collection for dev mode. + * Crawls the Vite module graph to collect CSS from the router entry and all its dependencies. + */ +import path from 'node:path' +import type { DevEnvironment, EnvironmentModuleNode, Rollup } from 'vite' + +// CSS file extensions supported by Vite +const CSS_FILE_REGEX = + /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/ +// URL params that indicate CSS should not be injected (e.g., ?url, ?inline) +const CSS_SIDE_EFFECT_FREE_PARAMS = ['url', 'inline', 'raw', 'inline-css'] + +// Marker to find the CSS string in Vite's transformed output +const VITE_CSS_MARKER = 'const __vite__css = ' + +const ESCAPE_CSS_COMMENT_START_REGEX = /\/\*/g +const ESCAPE_CSS_COMMENT_END_REGEX = /\*\//g +const NO_DEPENDENCIES: ReadonlyArray = [] +const cssTransformCache = new WeakMap() + +function isCssFile(file: string): boolean { + return CSS_FILE_REGEX.test(file) +} + +function hasCssSideEffectFreeParam(url: string): boolean { + const queryString = url.split('?')[1] + if (!queryString) { + return false + } + + const params = new URLSearchParams(queryString) + return CSS_SIDE_EFFECT_FREE_PARAMS.some( + (param) => + params.get(param) === '' && + !url.includes(`?${param}=`) && + !url.includes(`&${param}=`), + ) +} + +/** + * Resolve a file path to a Vite dev server URL. + * Files within the root directory use relative paths, files outside use /@fs prefix. + */ +function resolveDevUrl(rootDirectory: string, filePath: string): string { + const normalizedPath = filePath.replace(/\\/g, '/') + const relativePath = path.posix.relative( + rootDirectory.replace(/\\/g, '/'), + normalizedPath, + ) + const isWithinRoot = + !relativePath.startsWith('..') && !path.isAbsolute(relativePath) + + if (isWithinRoot) { + return path.posix.join('/', relativePath) + } + // Files outside root need /@fs prefix + return path.posix.join('/@fs', normalizedPath) +} + +export type DevStylesEnvironment = Pick & { + moduleGraph: Pick +} + +export interface CollectDevStylesOptions { + serverEnvironment: DevStylesEnvironment + rootDirectory: string + entries: Array + loadCssContents: (url: string) => Promise +} + +/** + * Collect CSS content from the module graph starting from the given entry points. + */ +export async function collectDevStyles( + opts: CollectDevStylesOptions, +): Promise { + const { serverEnvironment, rootDirectory, entries, loadCssContents } = opts + + const orderedCssNodes = await collectCssNodes( + serverEnvironment, + entries.map((entry) => resolveDevUrl(rootDirectory, entry)), + ) + + // Promise.all keeps graph order while loading the CSS concurrently. + const cssResults = await Promise.all( + orderedCssNodes.map((node) => loadCssContents(node.url)), + ) + + return formatCss( + orderedCssNodes.map((node) => node.url), + cssResults, + ) +} + +/** + * Resolve entry nodes and their dependency graph in parallel, then linearize the + * completed graph synchronously. This keeps I/O concurrent without making + * Promise resolution timing part of the CSS cascade order. + */ +async function collectCssNodes( + environment: DevStylesEnvironment, + entryUrls: Array, +): Promise> { + const entryNodes = await Promise.all( + entryUrls.map((entryUrl) => resolveEntry(environment, entryUrl)), + ) + const dependencies = new Map< + EnvironmentModuleNode, + ReadonlyArray + >() + const discovered = new Set() + const dependencyLookups = new Map< + string, + Promise + >() + + function getDependency( + url: string, + ): Promise { + let lookup = dependencyLookups.get(url) + if (!lookup) { + lookup = environment.moduleGraph.getModuleByUrl(url) + dependencyLookups.set(url, lookup) + } + return lookup + } + + async function discover(node: EnvironmentModuleNode): Promise { + if (discovered.has(node)) { + return + } + discovered.add(node) + + const nodeDependencies = await resolveModuleDeps(node, getDependency) + dependencies.set(node, nodeDependencies) + await Promise.all(nodeDependencies.map(discover)) + } + + await Promise.all( + entryNodes.map((node) => (node ? discover(node) : Promise.resolve())), + ) + + return orderCssNodes( + entryNodes, + (node) => node.url, + (node) => dependencies.get(node) ?? [], + ) +} + +function orderCssNodes( + entryNodes: Array, + getUrl: (node: T) => string, + getDependencies: (node: T) => ReadonlyArray, +): Array { + const orderedCssNodes: Array = [] + const ordered = new Set() + const stack = [...entryNodes].reverse() + + while (stack.length > 0) { + const node = stack.pop() + if (!node || ordered.has(node)) { + continue + } + ordered.add(node) + const url = getUrl(node) + if (isCssFile(url) && !hasCssSideEffectFreeParam(url)) { + orderedCssNodes.push(node) + } + + const nodeDependencies = getDependencies(node) + for (let i = nodeDependencies.length - 1; i >= 0; i--) { + stack.push(nodeDependencies[i]) + } + } + + return orderedCssNodes +} + +async function resolveEntry( + environment: DevStylesEnvironment, + entryUrl: string, +): Promise { + let node = await environment.moduleGraph.getModuleByUrl(entryUrl) + + // Only transform if needed so transformResult.deps is available for crawling. + if (!node?.transformResult) { + try { + await environment.transformRequest(entryUrl) + } catch { + // ignore - module might not exist yet + } + node = await environment.moduleGraph.getModuleByUrl(entryUrl) + } + + return node +} + +/** + * Resolve a module's direct dependencies in graph order. + * Uses transformResult.deps for URL-based lookups and importedModules for + * already-resolved nodes. + */ +async function resolveModuleDeps( + node: EnvironmentModuleNode, + getDependency: (url: string) => Promise, +): Promise> { + // Vite's client transform already includes CSS @imports in the parent CSS. + // Following either dependency source here would append the imported CSS again. + if (isCssFile(node.url)) { + return NO_DEPENDENCIES + } + + const depUrls = node.transformResult?.deps ?? [] + const importedModules = + node.importedModules.size > 0 + ? Array.from(node.importedModules) + : NO_DEPENDENCIES + + // Fast path: no deps and no imports + if (depUrls.length === 0 && importedModules.length === 0) { + return NO_DEPENDENCIES + } + + const resolvedDeps = await Promise.all(depUrls.map(getDependency)) + const orderedDependencies: Array = [] + const added = new Set() + + for (const dependency of resolvedDeps) { + if (dependency && !added.has(dependency)) { + added.add(dependency) + orderedDependencies.push(dependency) + } + } + + // Also traverse importedModules for non-CSS modules. This catches + // code-split chunks (e.g. ?tsr-split=component) that are not in deps, as + // well as already-resolved nodes. Vite inlines CSS @imports into the + // transformed parent stylesheet, so traversing a CSS module's importedModules + // would collect and append those stylesheets a second time. + for (const dependency of importedModules) { + if (!added.has(dependency)) { + added.add(dependency) + orderedDependencies.push(dependency) + } + } + + return orderedDependencies +} + +export async function fetchCssFromModule( + environment: DevStylesEnvironment, + url: string, +): Promise { + // Vite embeds the CSS text in the client environment's transform result. + // The SSR environment is only used for dependency discovery. + const node = await environment.moduleGraph.getModuleByUrl(url) + const cachedTransform = node?.transformResult + if (cachedTransform?.code) { + return extractCssFromTransform(cachedTransform) + } + + // Otherwise request a fresh transform + try { + const transformResult = await environment.transformRequest(url) + if (!transformResult?.code) { + return undefined + } + + return extractCssFromTransform(transformResult) + } catch { + // Preprocessor partials (e.g., Sass files with mixins) can't compile in isolation. + // The root stylesheet that @imports them will contain the compiled CSS. + return undefined + } +} + +function extractCssFromTransform(transformResult: { + code: string +}): string | undefined { + const cachedCss = cssTransformCache.get(transformResult) + if (cachedCss !== undefined) { + return cachedCss ?? undefined + } + + const css = extractCssFromCode(transformResult.code) + cssTransformCache.set(transformResult, css ?? null) + return css +} + +/** + * Extract CSS content from Vite's transformed CSS module code. + * + * Vite embeds CSS into the module as a JS string via `JSON.stringify(cssContent)`, + * e.g. `const __vite__css = ${JSON.stringify('...css...')}`. + * + * We locate that JSON string literal and run `JSON.parse` on it to reverse the + * escaping (\\n, \\t, \\", \\\\, \\uXXXX, etc.). + */ +export function extractCssFromCode(code: string): string | undefined { + const startIdx = code.indexOf(VITE_CSS_MARKER) + if (startIdx === -1) { + return undefined + } + + const valueStart = startIdx + VITE_CSS_MARKER.length + // Vite emits `const __vite__css = ${JSON.stringify(cssContent)}` which always + // produces double-quoted JSON string literals. + if (code.charCodeAt(valueStart) !== 34) { + return undefined + } + + const codeLength = code.length + let i = valueStart + 1 + while (i < codeLength) { + const charCode = code.charCodeAt(i) + // 34 = '"' + if (charCode === 34) { + try { + return JSON.parse(code.slice(valueStart, i + 1)) + } catch { + return undefined + } + } + // 92 = '\\' + if (charCode === 92) { + i += 2 + } else { + i++ + } + } + + return undefined +} + +/** Join available styles in graph order, labeling each with its source URL. */ +function formatCss( + urls: ReadonlyArray, + cssResults: ReadonlyArray, +): string | undefined { + const parts: Array = [] + for (let i = 0; i < cssResults.length; i++) { + const css = cssResults[i] + if (!css) { + continue + } + const escapedFileName = urls[i]!.replace( + ESCAPE_CSS_COMMENT_START_REGEX, + '/\\*', + ).replace(ESCAPE_CSS_COMMENT_END_REGEX, '*\\/') + parts.push(`\n/* ${escapedFileName} */\n${css}`) + } + return parts.length > 0 ? parts.join('\n') : undefined +} + +/** Snapshot the completed bundle without retaining its plugin context or JS. */ +export function captureBundledDevStyles( + graph: Pick, + rootDirectory: string, +) { + const css = new Map() + const dependencies = new Map>() + for (const id of graph.getModuleIds()) { + const info = graph.getModuleInfo(id) + if (!info) { + continue + } + // CSS transforms already contain their @imports. + if (isCssFile(id)) { + if (!hasCssSideEffectFreeParam(id) && info.code) { + const contents = extractCssFromCode(info.code) + if (contents) { + css.set(id, contents) + } + } + } else { + dependencies.set(id, [ + ...info.importedIds, + ...info.dynamicallyImportedIds, + ]) + } + } + return { rootDirectory, css, dependencies } +} + +export function collectBundledDevStyles( + snapshot: ReturnType | undefined, + entries: Array, +): string | undefined { + if (!snapshot) { + return undefined + } + const nodes = orderCssNodes( + entries.map((entry) => entry.replace(/\\/g, '/')), + (id) => id, + (id) => snapshot.dependencies.get(id) ?? [], + ) + return formatCss( + nodes.map((id) => resolveDevUrl(snapshot.rootDirectory, id)), + nodes.map((id) => snapshot.css.get(id)), + ) +} diff --git a/packages/start-plugin-core/src/vite/dev-server-plugin/plugin.ts b/packages/start-plugin-core/src/vite/dev-server-plugin/plugin.ts new file mode 100644 index 0000000000..4f0b2e632a --- /dev/null +++ b/packages/start-plugin-core/src/vite/dev-server-plugin/plugin.ts @@ -0,0 +1,323 @@ +import { isRunnableDevEnvironment } from 'vite' +import { NodeRequest, sendNodeResponse } from 'srvx/node' +import { ENTRY_POINTS, VITE_ENVIRONMENT_NAMES } from '../../constants' +import { ensureLatestClientBuild } from '../bundled-dev' +import { + captureBundledDevStyles, + collectBundledDevStyles, + collectDevStyles, + fetchCssFromModule, +} from './dev-styles' +import type { Connect, DevEnvironment, PluginOption } from 'vite' +import type { GetConfigFn } from '../../types' + +export function devServerPlugin({ + getConfig: _getConfig, + devSsrStylesEnabled, + installDevServerMiddleware, +}: { + getConfig: GetConfigFn + devSsrStylesEnabled: boolean + installDevServerMiddleware: boolean | undefined +}): PluginOption { + let isTest = false + let bundledDev = false + let bundledStyles: ReturnType | undefined + + return [ + { + name: 'tanstack-start-core:dev-server', + perEnvironmentWatchChangeDuringDev: true, + config(_userConfig, { mode }) { + isTest = isTest ? isTest : mode === 'test' + }, + configEnvironment(name, _config, { command }) { + if ( + command === 'serve' && + devSsrStylesEnabled && + name === VITE_ENVIRONMENT_NAMES.client + ) { + // Bundled dev needs code-split CSS before a browser requests chunks. + // Declare this even if a later config hook enables bundled dev. + return { + build: { + rolldownOptions: { + experimental: { devMode: { lazy: false } }, + }, + }, + } + } + return undefined + }, + configResolved(config) { + bundledDev = + config.command === 'serve' && !!config.experimental.bundledDev + }, + generateBundle() { + if ( + bundledDev && + devSsrStylesEnabled && + this.environment.name === VITE_ENVIRONMENT_NAMES.client + ) { + bundledStyles = captureBundledDevStyles( + this, + this.environment.config.root, + ) + } + }, + watchChange: { + order: 'post', + sequential: true, + handler(id) { + if ( + bundledDev && + this.environment.name === VITE_ENVIRONMENT_NAMES.server && + this.environment.mode === 'dev' + ) { + // Vite skips server HMR hooks in bundled dev. Invalidate changed + // transforms before notifying local or external SSR module runners. + this.environment.moduleGraph.onFileChange(id) + this.environment.hot.send({ type: 'full-reload', triggeredBy: id }) + } + }, + }, + configureServer(viteDevServer) { + if (isTest) { + return + } + + const clientEnv = + viteDevServer.environments[VITE_ENVIRONMENT_NAMES.client] + + // CSS middleware registered in PRE-PHASE (before Vite's internal middlewares) + // This ensures it handles /@tanstack-start/styles.css before any catch-all middleware + // from other plugins (like nitro) that may be registered in the post-phase. + // This makes the CSS endpoint work regardless of plugin order in the Vite config. + // We check pathname.endsWith() to handle basepaths (e.g., /my-app/@tanstack-start/styles.css) + // since pre-phase runs before Vite's base middleware strips the basepath. + if (devSsrStylesEnabled) { + viteDevServer.middlewares.use(async (req, res, next) => { + const url = req.url ?? '' + const pathname = url.split('?')[0] + if (!pathname?.endsWith('/@tanstack-start/styles.css')) { + return next() + } + + try { + // Parse route IDs from query param + const urlObj = new URL(url, 'http://localhost') + const routesParam = urlObj.searchParams.get('routes') + const ids = routesParam ? routesParam.split(',') : [] + + // Build entries list from route file paths + const entries: Array = [] + + // Look up route file paths from manifest + // Only routes registered in the manifest are used - this prevents path injection + const routesManifest = (globalThis as any).TSS_ROUTES_MANIFEST as + | Record }> + | undefined + + if (routesManifest && ids.length > 0) { + for (const routeId of ids) { + const route = routesManifest[routeId] + if (route?.filePath) { + entries.push(route.filePath) + } + } + } + + let css = '' + if (entries.length > 0) { + if (bundledDev) { + // Wait for the bundled client's completed graph without + // starting Vite's separate normal client container. + await ensureLatestClientBuild(clientEnv) + css = collectBundledDevStyles(bundledStyles, entries) ?? '' + } else { + css = + (await collectDevStyles({ + serverEnvironment: + viteDevServer.environments[ + VITE_ENVIRONMENT_NAMES.server + ], + rootDirectory: viteDevServer.config.root, + entries, + loadCssContents: (url) => + fetchCssFromModule( + viteDevServer.environments[ + VITE_ENVIRONMENT_NAMES.client + ], + url, + ), + })) ?? '' + } + } + + res.setHeader('Content-Type', 'text/css') + res.setHeader('Cache-Control', 'no-store') + res.end(css) + } catch (e) { + // Log error but still return valid CSS response to avoid MIME type issues + console.error('[tanstack-start] Error collecting dev styles:', e) + res.setHeader('Content-Type', 'text/css') + res.setHeader('Cache-Control', 'no-store') + res.end( + `/* Error collecting styles: ${e instanceof Error ? e.message : String(e)} */`, + ) + } + }) + } + + if (viteDevServer.config.experimental.bundledDev) { + // Vite's bundled dev client watches sources separately, but Start still + // needs the SSR environment's module graph to see route/server edits. + viteDevServer.watcher.add(viteDevServer.config.root) + } + + return () => { + const serverEnv = viteDevServer.environments[ + VITE_ENVIRONMENT_NAMES.server + ] as DevEnvironment | undefined + + if (!serverEnv) { + throw new Error( + `Server environment ${VITE_ENVIRONMENT_NAMES.server} not found`, + ) + } + + const installMiddleware = installDevServerMiddleware + if (installMiddleware === false) { + return + } + if (installMiddleware == undefined) { + // do not install middleware in middlewareMode by default + if (viteDevServer.config.server.middlewareMode) { + return + } + + // do not install middleware if SSR env in case another plugin already did + if ( + !isRunnableDevEnvironment(serverEnv) || + // do not check via `isFetchableDevEnvironment` since nitro does implement the `FetchableDevEnvironment` interface but not via inheritance (which this helper checks) + 'dispatchFetch' in serverEnv + ) { + return + } + } + + if (!isRunnableDevEnvironment(serverEnv)) { + throw new Error( + 'cannot install vite dev server middleware for TanStack Start since the SSR environment is not a RunnableDevEnvironment', + ) + } + viteDevServer.middlewares.use(async (req, res) => { + // fix the request URL to match the original URL + // otherwise, the request URL will '/index.html' + if (req.originalUrl) { + req.url = req.originalUrl + } + const webReq = new NodeRequest({ req, res }) + + try { + const serverRunner = serverEnv.runner + + // Import and resolve the request by running the server request entry point + // this request entry point must implement the `fetch` API as follows: + /** + * export default { + * fetch(req: Request): Promise + * } + */ + if (viteDevServer.config.experimental.bundledDev) { + await ensureLatestClientBuild(clientEnv) + } + + const serverEntry = await serverRunner.import(ENTRY_POINTS.server) + const webRes = await serverEntry['default'].fetch(webReq) + + return sendNodeResponse(res, webRes) + } catch (e) { + console.error(e) + try { + viteDevServer.ssrFixStacktrace(e as Error) + } catch {} + + if ( + webReq.headers.get('content-type')?.includes('application/json') + ) { + return sendNodeResponse( + res, + new Response( + JSON.stringify( + { + status: 500, + error: 'Internal Server Error', + message: + 'An unexpected error occurred. Please try again later.', + timestamp: new Date().toISOString(), + }, + null, + 2, + ), + { + status: 500, + headers: { + 'Content-Type': 'application/json', + }, + }, + ), + ) + } + + return sendNodeResponse( + res, + new Response( + ` + + + + + Error + + + + + + `, + { + status: 500, + headers: { + 'Content-Type': 'text/html', + }, + }, + ), + ) + } + }) + } + }, + }, + ] +} + +/** + * Formats error for SSR message in error overlay + * @param req + * @param error + * @returns + */ +function prepareError(req: Connect.IncomingMessage, error: unknown) { + const e = error as Error + return { + message: `An error occurred while server rendering ${req.url}:\n\n\t${ + typeof e === 'string' ? e : e.message + } `, + stack: typeof e === 'string' ? '' : e.stack, + } +} diff --git a/packages/start-plugin-core/src/vite/import-protection-plugin/INTERNALS.md b/packages/start-plugin-core/src/vite/import-protection-plugin/INTERNALS.md new file mode 100644 index 0000000000..ec3abd7f18 --- /dev/null +++ b/packages/start-plugin-core/src/vite/import-protection-plugin/INTERNALS.md @@ -0,0 +1,580 @@ +# Vite Import Protection - Adapter Internals + +## Scope + +This document covers the Vite-specific orchestration around the shared +import-protection core in `src/import-protection/INTERNALS.md`. + +Vite owns: + +- `resolveId`-first violation discovery. +- Dev and build deferral decisions tied to Vite lifecycle hooks. +- Per-environment state that bridges resolve-time data with transform-time data. +- The transform-cache plugin and post-transform graph bookkeeping. +- Selective diagnostic sourcemap capture while transformed code is in plugin scope. +- Vite virtual-module id resolution and loading. +- Bundle-time survival checks in `generateBundle`. +- Opt-in perf counters and timings for this adapter. + +Shared AST analysis, rewrite logic, source extraction, mock export discovery, +usage lookup, source locations, and mock code generation live under +`src/import-protection`. + +## Plugin Shape + +`importProtectionPlugin()` returns two Vite plugins: + +1. `tanstack-start-core:import-protection` +2. `tanstack-start-core:import-protection-transform-cache` + +The first plugin owns resolve-time detection, virtual-module resolution, +reporting decisions, build survival checks, dev-server capture, HMR invalidation, +and perf flushing. + +The second plugin owns transformed-result caching, selective diagnostic sourcemap +capture, self-denial transforms, post-transform import graph updates, dev +pending-violation verification, and dev import rewrites. + +Both plugins use `applyToEnvironment()` and only run for Start environments: + +- `client` +- `ssr` +- the optional provider environment when it differs from `ssr` + +The adapter resolves client/server semantics from `config.envTypeMap`; Vite's +server environment is named `ssr`, but import protection reports it as the +`server` boundary. + +## Hook Filters + +The Vite adapter uses hook filters to reduce avoidable JS hook calls: + +- `resolveId.filter.id.exclude` skips most `\0` and `virtual:` ids, while still + allowing import-protection virtual ids through. +- `load.filter.id` only handles resolved import-protection virtual-module ids. +- `transform.filter.id.include` limits transform-cache work to JS/TS module ids + matching `/\.[cm]?[tj]sx?($|\?)/`. + +The runtime checks still keep defensive early returns for internal virtual ids +and out-of-scope importers. + +## Why Vite Uses Two Plugins + +Vite discovers many violations in `resolveId`, but accurate source locations and +post-transform graph truth require code that only exists later. + +The adapter splits responsibilities: + +- `resolveId` detects, classifies, defers or reports, records graph edges, and + substitutes mock ids where needed. +- The later transform hook caches plugin-input code, selectively captures + diagnostic sourcemaps, self-denies files, computes post-transform imports, and + processes pending violations. + +The transform-cache plugin runs after `enforce: 'pre'` hooks, including the Start +compiler. This means it sees the code as it enters this plugin after upstream +transforms, not the file read from disk. + +## State Model + +Per environment, Vite keeps `EnvState` with: + +- `graph`: an `ImportGraph` of source and post-transform edges. +- `mockExportsByImporter`: parsed export names for denied specifier mock modules. +- `resolveCache`: successful `this.resolve()` results keyed by importer/source. +- `resolveCacheByFile`: reverse index for invalidating resolve-cache keys. +- `importLocCache`: cached import-statement locations. +- `seenViolations`: dedupe state and retroactive-marker guard keys. +- `serverFnLookupModules`: modules known to be pre-transform lookup variants. +- `transformResultCache`: transformed code plus optional diagnostic sourcemap. +- `transformResultKeysByFile`: all cached ids for a physical file, including split variants. +- `transformResultProvider`: lookup facade used by diagnostic helpers. +- `postTransformImports`: resolved imports found after the Start compiler ran. +- `pendingViolations`: dev mock violations awaiting edge/reachability verification. +- `deferredBuildViolations`: build violations awaiting tree-shaking survival checks. + +Cross-environment shared state is intentionally small: + +- `fileMarkerKind`: normalized file path to `server` or `client` marker kind. + +This state model is larger than the Rsbuild adapter because Vite must bridge +resolve-time detection with later transform and bundle verification. + +## Lifecycle Hooks + +`configResolved` initializes adapter config from Vite and Start config: + +- root, command, bundled dev mode, and source directory. +- behavior, log mode, mock access mode, max trace depth, and `onViolation`. +- default and user import-protection rules compiled into matchers. +- marker specifiers for server-only and client-only modules. +- include, exclude, and ignored-importer matchers. + +`configureServer` stores the dev server so traces can fall back to Vite's +per-environment module graph on warm starts. + +`buildStart` clears bounded and unbounded caches, clears shared marker state, +and registers known Start entries for every configured environment. + +`hotUpdate` invalidates every file-scoped cache for changed modules: + +- extensionless absolute-id resolution. +- shared marker state for the file. +- import-location cache entries. +- resolve cache entries indexed by that file. +- import graph edges where the file is importer or resolved target. +- mock export cache for the file. +- server-fn lookup state for the file. +- pending violations for the file. +- transform-result cache entries and post-transform imports for all variants. + +`closeBundle` flushes cumulative opt-in perf output when perf collection is +enabled. + +## Detection Flow + +The Vite adapter is `resolveId`-driven. + +That means it may see violations before: + +- the Start compiler removes safe-boundary imports. +- tree-shaking removes false-positive edges. +- transformed importer code is available. + +For `resolveId` calls with no importer, the adapter records entry roots and then +flushes pending violations because reachability may now have new roots. In +bundled client dev, source entries inside `srcDirectory` are not added as entry +roots because that would make every source module appear reachable. + +For imported modules, `resolveId` does this in order: + +- Resolve import-protection virtual ids via `resolveInternalVirtualModuleId()`. +- Ignore unrelated `\0` and `virtual:` sources. +- Normalize the importer and classify direct `SERVER_FN_LOOKUP` resolves. +- In bundled client dev, add route modules under `src/routes` as source roots. +- Treat direct lookup modules, transitive lookup modules, and Vite scan resolves + as pre-transform resolves. +- Avoid recording source graph edges for server-fn lookup modules because those + variants contain uncompiled code. +- Detect marker imports before importer-scope checks so marker files can set + shared `fileMarkerKind`. +- Skip importers outside import-protection scope after marker handling. +- Check denied specifiers before resolving the import. +- Resolve imports through `this.resolve()` when needed, cache successful results, + and canonicalize resolved ids. +- Add graph edges for authoritative resolves when the importer is not a + server-fn lookup module. +- Check resolved file-denial rules and resolved marker-file conflicts. +- Dispatch violations through `reportOrDeferViolation()`. + +`this.resolve()` calls are counted and timed when perf collection is enabled. +Only successful resolves are cached; `null` results are not cached because they +can be order-dependent across importer variants such as split route ids. + +## Marker Handling + +Marker imports are imports of framework marker modules such as +`@tanstack/react-start/server-only` and `@tanstack/react-start/client-only`. + +When `resolveId` sees a marker import, it: + +- Records the normalized importer file in `shared.fileMarkerKind`. +- Throws immediately if a file has both server-only and client-only markers. +- Builds a marker violation if the current environment is the opposite boundary. +- Returns a marker virtual module for normal marker imports. +- In build mode, returns a unique build mock id for a deferred marker violation + so `generateBundle` can check whether the importer survived. + +Marker conflicts can also be discovered after resolving a normal import. If the +resolved target file was previously marked for the opposite environment, +`buildMarkerViolationFromResolvedImport()` creates the marker violation. + +Cold-start ordering can resolve module A importing module B before module B's +marker import has run. When B's marker is later recorded, the adapter +retroactively checks known importers in the graph, creates deferred marker +violations for matching importers, and immediately runs pending-violation +processing. + +## Deferral Policy + +The shared helper reduces to: + +```ts +shouldDefer = isBuild || isDevMock +``` + +Adapter meaning: + +- Dev plus error reports immediately for non-pre-transform resolves. +- Dev plus error silences pre-transform resolves because imports inside compiler + safe boundaries may not have been stripped yet, and there is no deferred + verification path in this mode. +- Dev plus mock stores `pendingViolations`, then verifies later with + post-transform edge survival and reachability. +- Build plus mock and build plus error store `deferredBuildViolations`, then + verify in `generateBundle` after tree-shaking. + +This is the main Vite-specific state machine difference from Rsbuild. + +## Lightweight Violations + +`buildViolationInfo()` creates a lightweight `ViolationInfo` record. + +The lightweight record contains: + +- environment name and boundary type. +- effective behavior. +- importer and specifier. +- violation type, pattern, and resolved path when known. +- an optional trace override. + +It intentionally does not compute expensive diagnostic data. + +Deferred work includes: + +- trace reconstruction. +- source-location lookup. +- code snippets. +- source-map mapping. +- AST usage analysis for the reported location. + +This work runs in `enrichViolationInfo()` only when a violation is about to be +emitted or passed to `onViolation`. Violations suppressed by edge survival, +reachability, or tree-shaking are never enriched. + +## Diagnostic Candidates + +A diagnostic candidate is a transformed module that is likely to need original +source diagnostics later. + +This is not a confirmed violation. It is only a cheap transform-time decision +about whether to capture the composed sourcemap while Vite/Rolldown still makes +`this.getCombinedSourcemap()` safely available. + +`shouldCaptureDiagnosticSourceMap()` returns `true` when the transformed code +contains import/export syntax and appears to reference import-protection inputs: + +- The code contains the opposite-boundary filename token, `.server` for client + environments or `.client` for server environments. +- The code contains any configured marker specifier. +- The code contains a literal denied specifier pattern. +- A custom non-literal specifier matcher is configured. +- A file matcher is a `RegExp` or does not contain the simple boundary token. + +The predicate intentionally does not parse import source literals with regexes. +For default rules, the fast path is substring checks for `import`/`export`, +`.server`, `.client`, marker specifiers, and default framework specifier strings. +For custom non-literal rules, it captures more broadly for modules with +import/export syntax rather than attempting a second import parser. + +`captureDiagnosticSourceMap()` is best effort: + +- It does nothing if the transform result already has a map. +- It calls `this.getCombinedSourcemap()` only for diagnostic candidates or a + confirmed dev mock file violation found during the transform import-resolution loop. +- It stores the map on the cached `TransformResult` when capture succeeds. +- It ignores capture failures; diagnostics then fall back to transformed-code + locations and snippets when possible. +- It records perf counters by reason, currently `candidate` and `devViolation`. + +The adapter does not read original files from disk for diagnostics. Original +source text comes only from the code and sourcemaps that reach this plugin. + +## Original Code And Snippets + +The transform cache stores transformed code for every in-scope transformed module +that is not self-denied. It stores a composed sourcemap only when selective +diagnostic capture succeeds. + +`sourceLocation` derives original code lazily: + +- `getOriginalCode()` reads `map.sourcesContent` only on demand. +- `pickOriginalCodeFromSourcesContent()` picks the best source by exact file, + resolved source path, suffix segment score, and finally the first source. +- `getOrCreateOriginalTransformResult()` creates an original-source transform + result only when original code exists. +- The derived original result is cached on the transform result. + +Importer locations prefer the most useful usage site rather than the import +statement. The lookup order is: + +1. First post-compile usage of the denied binding, mapped through the sourcemap. +2. Original-source unsafe usage from `sourcesContent`, excluding compiler-safe boundary callbacks. +3. Transformed import-statement location, mapped through the sourcemap. + +Before lookup, enrichment builds multiple source candidates from the original +specifier, resolved paths, root-relative paths, extensionless paths, and +importer-relative paths. + +When a location is found, diagnostics include a vitest-style `Code:` snippet +around that line. Snippets prefer original source from `sourcesContent` when it +is available. If original source is unavailable, snippets use transformed code. +If no location is found, the violation still reports without a snippet. + +## Trace Construction + +Trace construction is lazy and runs during enrichment. + +The adapter normally rebuilds traces from its own `ImportGraph`. In dev serve, +it may prefer Vite's per-environment `moduleGraph` when that graph produces a +longer trace. This helps warm-start cases where Vite skipped some `resolveId` +calls. + +Trace steps are annotated with import-statement locations from transformed-code +data when available. The leaf step falls back to the resolved importer location +if the trace did not already have a location. + +## Runtime Mock Diagnostics + +Dev client mocks can embed a runtime diagnostic payload in the virtual module +id. The payload includes: + +- environment name. +- importer. +- specifier. +- runtime mock access mode. +- the trace currently present on `ViolationInfo`. + +Because dev mock violations are substituted during silent deferral, the runtime +mock id is often created before lazy enrichment. Browser runtime diagnostics are +therefore access diagnostics, not the canonical source trace. The authoritative +trace and snippet are produced later when a pending violation is confirmed and +emitted to terminal output. + +Self-denial runtime mocks currently carry an empty trace payload because they are +created directly from the denied file's own transform. + +## Dev Strategy + +### Dev Plus Error + +Vite throws immediately for non-pre-transform violations in `resolveId`. + +This mode can still produce known false positives because there is no dev-server +tree-shaking phase. Pre-transform resolve paths like `SERVER_FN_LOOKUP` are +silenced because they fire before compiler stripping and have no later deferred +verification path in error mode. + +### Dev Plus Mock + +Vite defers all violations into `pendingViolations`. + +Later, the transform-cache plugin: + +1. Self-denies files when the transformed file itself violates file rules. +2. Caches transformed code and any selectively captured diagnostic sourcemap. +3. Resolves import sources from the transformed code. +4. Records `postTransformImports` under each full normalized Vite id, preserving + unsplit routes and code-split variants separately. +5. Adds import graph edges from transformed-code imports for warm-start traces. +6. Maps import-protection mock-edge ids back to physical paths for edge survival. +7. Detects file violations missed by warm-start `resolveId` cache hits. +8. Rewrites denied imports to mock replacements in dev mock mode. +9. Runs `processPendingViolations()` after each transform-cache update. + +Pending verification uses edge survival and reachability. + +`filterEdgeSurvival()` returns: + +- `all-stripped` when post-transform imports prove every pending violation was removed. +- `await-transform` when pre-transform violations need transform data first. +- active violations plus whether edge-survival data was applied. + +`checkPostTransformReachability()` returns: + +- `reachable` when a live path reaches a registered entry. +- `unreachable` when all known live paths are cut off. +- `unknown` when some graph edges still lack transform data. + +In dev serve with `unknown` reachability, the adapter can conservatively emit +confirmed-surviving violations or in-scope file violations when pre-transform +data is not involved. + +Bundled client dev also verifies post-transform reachability, so raw compiler +lookup imports cannot make a stripped import chain appear reachable. Because +child transforms can run before their route/importer edges are known, a surviving +violation that is currently unreachable stays pending instead of being dropped. +The bundled dev `generateBundle` hook verifies pending violations again after +all importer edges are recorded. + +## Build Strategy + +Vite build uses mock-first, verify-later behavior. + +At resolve time, `reportOrDeferViolation()` calls `handleViolation()` silently to +obtain the replacement id and stores a `DeferredBuildViolation`. + +Build replacements differ by violation type: + +- File violations return the physical resolved path; self-denial later replaces + that file's content. +- Specifier violations return a mock-edge virtual module whose payload references + a unique build mock runtime id. +- Marker violations return a mock-edge virtual module whose payload references a + unique build mock runtime id when the direct marker import violates the current + environment. + +At `generateBundle`, the adapter builds a set of module ids that survived +tree-shaking. It normalizes multiple forms for comparison: + +- raw bundle module id. +- normalized id with query/hash stripped. +- root-relative path. +- internal `\0` virtual id. +- browser `__x00__` virtual id. + +Survival checks differ by violation type: + +- File violations check whether the physical resolved path survived after + self-denial replaced that module's content. +- Specifier violations check whether the mock-edge module id survived. +- Marker violations check whether the importer survived, including all + transform-result variant ids for that importer. + +Only surviving violations are enriched. After `onViolation` allows them: + +- Build plus error fails on the first real surviving violation. +- Build plus mock warns once per dedupe key. +- Non-surviving violations are suppressed as tree-shaken false positives. + +## Self-Denial In Vite + +For file-based violations, `resolveId` does not return a virtual mock id. +Instead it returns the physical file path, and the transform-cache plugin +independently decides whether that file is denied in the current environment. + +This Vite-specific choice exists for two reasons: + +- It avoids cross-environment cache contamination in shared resolver caches. +- It avoids cold-start export-resolution issues when importer AST data is not + yet available. + +Self-denial runs before normal transform-result caching. + +Build self-denial returns a self-contained mock module generated from exports +parsed from the denied file's code. + +Dev self-denial returns a mock module generated from the denied file's exports. +For client-env self-denial with runtime mock access enabled, that mock references +a runtime diagnostic module. For server-env self-denial, or when mock access is +off, `mockRuntimeModuleIdFromViolation()` resolves to the silent mock module. +The runtime diagnostic id is built from the denied file itself and currently has +an empty trace payload. + +Because self-denial exits the transform hook early, self-denied files do not go +through the normal transform-result cache path for that environment. + +## Mock Export Resolution + +Specifier and marker mocks need explicit named exports so ESM imports continue +to link. + +`resolveExportsForDeniedSpecifier()` runs only while handling a violation. It +tries, in order: + +- cached export maps for the importer. +- transformed importer code from `transformResultProvider`. +- `ctx.getModuleInfo(importerIdHint)?.code` as a fallback. +- AST parsing through `getMockExportNamesBySource()`. +- resolver-based aliases that index source keys by resolved physical ids. + +The result is cached in `mockExportsByImporter` and used by `makeMockEdgeModuleId()`. + +## Virtual Modules + +The shared mock generators use abstract ids without Vite's resolved `\0` prefix, +such as: + +- `tanstack-start-import-protection:mock` +- `tanstack-start-import-protection:mock:build:` +- `tanstack-start-import-protection:mock-edge:` +- `tanstack-start-import-protection:mock-runtime:` +- `tanstack-start-import-protection:marker:` + +The Vite adapter adds: + +- a resolved `\0` prefix via `resolveViteId(...)`. +- browser-prefixed ids via `__x00__` for virtual ids that pass through browser import paths. +- `resolveInternalVirtualModuleId()` for normalizing import-protection virtual ids in `resolveId`. +- `loadResolvedVirtualModule()` for serving generated virtual module code in `load`. + +The generated module contents are shared. The id transport is Vite-specific. + +## Warm-Start Considerations + +Vite can skip `resolveId` on warm cache hits. + +The adapter compensates by: + +- caching transformed code under both normalized Vite id and physical file path. +- tracking all transform-result keys per physical file. +- resolving transformed import sources in the transform-cache plugin. +- recording post-transform imports for edge-survival checks. +- adding graph edges from transformed imports for trace accuracy. +- detecting dev mock file violations that `resolveId` missed on warm starts. +- falling back to Vite's module graph for longer dev traces. + +Pre-transform lookup variants are explicitly excluded from post-transform +liveness data because they contain uncompiled code. + +## Perf Instrumentation + +Perf collection is opt-in: + +```sh +TSR_IMPORT_PROTECTION_PERF=1 +TSR_IMPORT_PROTECTION_PERF=true +``` + +When enabled, the adapter records counters and timings for: + +- `resolveId` calls. +- transform-cache calls. +- `this.resolve()` calls from resolve and transform paths. +- transform import analysis. +- shared AST parsing performed by import analysis and diagnostic lookup. +- number of import sources found in transform-cache. +- violations detected. +- violations enriched. +- diagnostic sourcemap capture by reason. +- diagnostic sourcemap capture timing. + +Output is written as cumulative JSON to `TSR_IMPORT_PROTECTION_PERF_FILE` when +set. Without that file, output is logged on each `closeBundle()`. The payload +includes `flushCount` and `flushEnvironments` so multi-environment builds can be +checked for full coverage. + +When perf is disabled, the adapter only keeps a single `perf` variable that is +`undefined`; hot paths use optional chaining and do not allocate counters or +timers. + +## Diagnostic Visibility Tests + +The import-protection e2e suite parses terminal and build output to verify +violations, traces, and snippets. + +The suite checks: + +- Violations are parseable from logs. +- Build error output contains a trace. +- Warm dev traces include line numbers. +- Offending usage snippets are present for representative violations. +- Compiler-processed modules can still report original-source snippets when + sourcemap `sourcesContent` is captured. + +Browser runtime mock access diagnostics are separate from terminal diagnostics. +They should not be treated as carrying the enriched canonical trace or snippet +unless a test explicitly asserts that behavior. + +## Maintainer Rules + +When changing Vite import protection, ask: + +1. Is this really about Vite lifecycle timing or state? +2. If not, should it move into the shared import-protection core? +3. If yes, does it belong in resolve-time detection, transform-cache handling, + diagnostic enrichment, or bundle-time verification? +4. Does the change do avoidable source-map, AST, trace, or snippet work before a + violation is confirmed? +5. Does the change preserve the distinction between source graph evidence, + post-transform evidence, and bundle survival evidence? diff --git a/packages/start-plugin-core/src/vite/import-protection-plugin/plugin.ts b/packages/start-plugin-core/src/vite/import-protection-plugin/plugin.ts new file mode 100644 index 0000000000..dcbec56655 --- /dev/null +++ b/packages/start-plugin-core/src/vite/import-protection-plugin/plugin.ts @@ -0,0 +1,2380 @@ +import { writeFileSync } from 'node:fs' +import { normalizePath } from 'vite' +import { dirname, relative } from 'pathe' + +import { escapeRegExp, resolveViteId } from '../../utils' +import { SERVER_FN_LOOKUP, VITE_ENVIRONMENT_NAMES } from '../../constants' +import { hasIdQueryFlag } from '../module-id' +import { + ImportGraph, + buildTrace, + formatViolation, +} from '../../import-protection/trace' +import { + getDefaultImportProtectionRules, + getMarkerSpecifiers, +} from '../../import-protection/defaults' +import { compileMatchers, matchesAny } from '../../import-protection/matchers' +import { + getImportProtectionEnvType, + getImportProtectionRelativePath, + getImportProtectionRulesForEnvironment, + shouldCheckImportProtectionImporter, +} from '../../import-protection/adapterUtils' +import { + buildResolutionCandidates, + buildSourceCandidates, + canonicalizeResolvedId, + checkFileDenial, + clearNormalizeFilePathCache, + debugLog, + dedupePatterns, + dedupeViolationKey, + getOrCreate, + isFileExcluded, + isInsideDirectory, + matchesDebugFilter, + normalizeFilePath, + relativizePath, + shouldDeferViolation, +} from '../../import-protection/utils' +import { + getImportSourcesFromResult, + getMockExportNamesBySource, + getNamedExports, +} from '../../import-protection/analysis' +import { rewriteDeniedImports } from '../../import-protection/rewrite' +import { ExtensionlessAbsoluteIdResolver } from '../../import-protection/extensionlessAbsoluteIdResolver' +import { + IMPORT_PROTECTION_DEBUG, + VITE_BROWSER_VIRTUAL_PREFIX, +} from '../../import-protection/constants' +import { + ImportLocCache, + addTraceImportLocations, + buildCodeSnippet, + createImportSpecifierLocationIndex, + findImportStatementLocationFromTransformed, + findOriginalUsageLocation, + findPostCompileUsageLocation, + normalizeSourceMap, +} from '../../import-protection/sourceLocation' +import { + MOCK_BUILD_PREFIX, + generateDevSelfDenialModule, + generateSelfContainedMockModule, + getResolvedVirtualModuleMatchers, + loadResolvedVirtualModule, + makeMockEdgeModuleId, + mockRuntimeModuleIdFromViolation, + resolveInternalVirtualModuleId, + resolvedMarkerVirtualModuleId, +} from './virtualModules' +import type { PluginOption, ViteDevServer } from 'vite' +import type { + Loc, + TraceStep, + ViolationInfo, +} from '../../import-protection/trace' +import type { + SourceMapLike, + TransformResult, + TransformResultProvider, +} from '../../import-protection/sourceLocation' +import type { ImportProtectionOptions } from '../../schema' +import type { + EnvRules, + EnvState, + HandleViolationResult, + ImportProtectionPluginOptions, + ModuleGraphNode, + PendingViolation, + PluginConfig, + SharedState, + ViolationReporter, +} from './types' + +export type { ImportProtectionPluginOptions } from './types' + +type PerfTiming = { + count: number + totalMs: number + maxMs: number +} + +type PerfCollector = { + count: (name: string, value?: number) => void + time: (name: string, startedAt: number) => void + flush: (root: string, envName: string) => void +} + +function isPerfEnabled(): boolean { + return ( + process.env.TSR_IMPORT_PROTECTION_PERF === '1' || + process.env.TSR_IMPORT_PROTECTION_PERF === 'true' + ) +} + +function createPerfCollector(): PerfCollector { + const counters = new Map() + const timings = new Map() + const flushEnvironments = new Set() + let flushCount = 0 + + return { + count(name, value = 1) { + counters.set(name, (counters.get(name) ?? 0) + value) + }, + time(name, startedAt) { + const duration = performance.now() - startedAt + const timing = timings.get(name) + if (timing) { + timing.count++ + timing.totalMs += duration + timing.maxMs = Math.max(timing.maxMs, duration) + } else { + timings.set(name, { count: 1, totalMs: duration, maxMs: duration }) + } + }, + flush(root, envName) { + flushCount++ + flushEnvironments.add(envName) + + const payload = { + root, + flushCount, + flushEnvironments: Array.from(flushEnvironments).sort(), + counters: Object.fromEntries(counters), + timings: Object.fromEntries( + Array.from(timings, ([name, timing]) => [ + name, + { + count: timing.count, + totalMs: Number(timing.totalMs.toFixed(3)), + avgMs: Number((timing.totalMs / timing.count).toFixed(3)), + maxMs: Number(timing.maxMs.toFixed(3)), + }, + ]), + ), + } + + const file = process.env.TSR_IMPORT_PROTECTION_PERF_FILE + if (file) { + writeFileSync(file, `${JSON.stringify(payload, null, 2)}\n`) + } else { + console.warn( + `[import-protection:perf] ${JSON.stringify(payload, null, 2)}`, + ) + } + }, + } +} + +export function importProtectionPlugin( + opts: ImportProtectionPluginOptions, +): PluginOption { + let devServer: ViteDevServer | null = null + const perf = isPerfEnabled() ? createPerfCollector() : undefined + const extensionlessIdResolver = new ExtensionlessAbsoluteIdResolver() + const resolveExtensionlessAbsoluteId = (id: string) => + extensionlessIdResolver.resolve(id) + const importSpecifierLocationIndex = createImportSpecifierLocationIndex() + + /** + * Build an import trace using Vite's per-environment module graph, which + * is authoritative even on warm starts when the plugin's own ImportGraph + * may be incomplete (Vite skips resolveId for cached modules). + */ + function buildTraceFromModuleGraph( + envName: string, + env: EnvState, + targetFile: string, + ): Array | null { + if (!devServer) return null + const environment = devServer.environments[envName] + if (!environment) return null + + const file = normalizeFilePath(targetFile) + const start = environment.moduleGraph.getModuleById(file) + if (!start) return null + + // Resolve a module graph node to its normalized file path once and + // cache the result so BFS + reconstruction don't recompute. + const nodeIds = new Map() + function nodeId(n: ModuleGraphNode): string { + let cached = nodeIds.get(n) + if (cached === undefined) { + cached = n.id + ? normalizeFilePath(n.id) + : n.url + ? normalizeFilePath(n.url) + : '' + nodeIds.set(n, cached) + } + return cached + } + + const queue: Array = [start] + const visited = new Set([start]) + const parent = new Map() + + let entryRoot: ModuleGraphNode | null = null + let fallbackRoot: ModuleGraphNode | null = null + let qi = 0 + while (qi < queue.length) { + const node = queue[qi++]! + const id = nodeId(node) + + if (id && env.graph.entries.has(id)) { + entryRoot = node + break + } + + const importers = node.importers + if (importers.size === 0) { + if (!fallbackRoot) fallbackRoot = node + continue + } + + for (const imp of importers) { + if (visited.has(imp)) continue + visited.add(imp) + parent.set(imp, node) + queue.push(imp) + } + } + + const root = entryRoot ?? fallbackRoot + + if (!root) return null + + // Reconstruct: root -> ... -> start + const chain: Array = [] + let cur: ModuleGraphNode | undefined = root + for (let i = 0; i < config.maxTraceDepth + 2 && cur; i++) { + chain.push(cur) + if (cur === start) break + cur = parent.get(cur) + } + + const steps: Array = [] + for (let i = 0; i < chain.length; i++) { + const id = nodeId(chain[i]!) + if (!id) continue + let specifier: string | undefined + if (i + 1 < chain.length) { + const nextId = nodeId(chain[i + 1]!) + if (nextId) { + specifier = env.graph.reverseEdges.get(nextId)?.get(id) + } + } + steps.push(specifier ? { file: id, specifier } : { file: id }) + } + + return steps.length ? steps : null + } + + const config: PluginConfig = { + enabled: true, + root: '', + command: 'build', + bundledDev: false, + srcDirectory: '', + framework: opts.framework, + effectiveBehavior: 'error', + mockAccess: 'error', + logMode: 'once', + maxTraceDepth: 20, + compiledRules: { + client: { specifiers: [], files: [], excludeFiles: [] }, + server: { specifiers: [], files: [], excludeFiles: [] }, + }, + includeMatchers: [], + excludeMatchers: [], + ignoreImporterMatchers: [], + markerSpecifiers: { serverOnly: new Set(), clientOnly: new Set() }, + envTypeMap: new Map(opts.environments.map((e) => [e.name, e.type])), + onViolation: undefined, + } + + const envStates = new Map() + const shared: SharedState = { fileMarkerKind: new Map() } + + function shouldCaptureDiagnosticSourceMap( + code: string, + envType: 'client' | 'server', + matchers: EnvRules, + ): boolean { + const hasImportOrExport = code.includes('import') || code.includes('export') + if (!hasImportOrExport) { + return false + } + + const boundaryToken = envType === 'client' ? '.server' : '.client' + if (code.includes(boundaryToken)) { + return true + } + + for (const marker of config.markerSpecifiers.serverOnly) { + if (code.includes(marker)) { + return true + } + } + for (const marker of config.markerSpecifiers.clientOnly) { + if (code.includes(marker)) { + return true + } + } + + let needsSourceScan = false + for (const matcher of matchers.specifiers) { + if (matcher.literal !== undefined) { + if (code.includes(matcher.literal)) { + return true + } + continue + } + + needsSourceScan = true + } + + for (const matcher of matchers.files) { + if ( + matcher.pattern instanceof RegExp || + !matcher.pattern.includes(boundaryToken) + ) { + needsSourceScan = true + break + } + } + + // Custom non-literal rules cannot be checked with safe substring tests. + // Capture broadly for modules with import/export syntax rather than trying + // to parse import source literals with a regex. + return needsSourceScan + } + + function captureDiagnosticSourceMap( + result: TransformResult, + getCombinedSourcemap: () => SourceMapLike | null | undefined, + reason: string, + ): void { + if (result.map) { + return + } + + const startedAt = perf ? performance.now() : 0 + try { + const map = getCombinedSourcemap() + if (map) { + result.map = map + perf?.count(`sourcemap.captured.${reason}`) + } + } catch { + perf?.count(`sourcemap.captureFailed.${reason}`) + } finally { + if (perf) { + perf.time('sourcemap.capture', startedAt) + } + } + } + + /** + * Build the best available source trace for a module and enrich each step + * with line/column locations. The plugin's own ImportGraph is preferred; + * Vite's moduleGraph is only a dev fallback for warm starts where Vite may + * skip resolveId for cached modules. + * + * Shared by {@link buildViolationInfo} and {@link processPendingViolations}. + */ + async function rebuildAndAnnotateTrace( + provider: TransformResultProvider, + env: EnvState, + envName: string, + normalizedImporter: string, + specifier: string, + importerLoc: Loc | undefined, + traceOverride?: Array, + ): Promise> { + let trace = + traceOverride ?? + buildTrace(env.graph, normalizedImporter, config.maxTraceDepth) + + if (config.command === 'serve') { + const mgTrace = buildTraceFromModuleGraph( + envName, + env, + normalizedImporter, + ) + if (mgTrace && mgTrace.length > trace.length) { + trace = mgTrace + } + } + await addTraceImportLocations( + provider, + trace, + env.importLocCache, + importSpecifierLocationIndex.find, + ) + + if (trace.length > 0) { + const last = trace[trace.length - 1]! + if (!last.specifier) last.specifier = specifier + if (importerLoc && last.line == null) { + last.line = importerLoc.line + last.column = importerLoc.column + } + } + + return trace + } + + /** + * Build a lightweight {@link ViolationInfo} record. + * + * Diagnostic-only work (trace, source-map lookup, snippets, AST usage + * analysis) is intentionally deferred until the violation is about to be + * reported. + */ + function buildViolationInfo( + envName: string, + envType: 'client' | 'server', + normalizedImporter: string, + source: string, + overrides: Omit< + ViolationInfo, + | 'env' + | 'envType' + | 'behavior' + | 'specifier' + | 'importer' + | 'trace' + | 'snippet' + | 'importerLoc' + >, + traceOverride?: Array, + ): ViolationInfo { + perf?.count('violations.detected') + return { + env: envName, + envType, + behavior: config.effectiveBehavior, + specifier: source, + importer: normalizedImporter, + trace: traceOverride ?? [], + ...overrides, + } + } + + async function enrichViolationInfo( + provider: TransformResultProvider, + env: EnvState, + envName: string, + envType: 'client' | 'server', + importer: string, + info: ViolationInfo, + traceOverride?: Array, + ): Promise { + const startedAt = perf ? performance.now() : 0 + perf?.count('violations.enriched') + + const resolved = info.resolved + const sourceCandidates = buildSourceCandidates( + info.specifier, + resolved, + config.root, + ) + addImporterRelativeSourceCandidates(sourceCandidates, importer, resolved) + + if (!info.importerLoc) { + const loc = await resolveImporterLocation( + provider, + env, + envType, + importer, + sourceCandidates, + ) + if (loc) { + info.importerLoc = loc + info.snippet = buildCodeSnippet( + provider, + importer, + loc, + undefined, + config.root, + ) + } + } else if (!info.snippet) { + info.snippet = buildCodeSnippet( + provider, + importer, + info.importerLoc, + undefined, + config.root, + ) + } + + if (traceOverride || info.trace.length === 0) { + info.trace = await rebuildAndAnnotateTrace( + provider, + env, + envName, + info.importer, + info.specifier, + info.importerLoc, + traceOverride, + ) + } + + if (perf) { + perf.time('violation.enrich', startedAt) + } + } + + async function resolveImporterLocation( + provider: TransformResultProvider, + env: EnvState, + envType: 'client' | 'server', + importer: string, + sourceCandidates: Iterable, + ): Promise { + for (const candidate of sourceCandidates) { + const loc = + (await findPostCompileUsageLocation(provider, importer, candidate)) || + findOriginalUsageLocation( + provider, + importer, + candidate, + envType, + config.root, + ) || + (await findImportStatementLocationFromTransformed( + provider, + importer, + candidate, + env.importLocCache, + importSpecifierLocationIndex.find, + )) + if (loc) return loc + } + return undefined + } + + function addImporterRelativeSourceCandidates( + candidates: Set, + importer: string, + resolved: string | undefined, + ): void { + if (!resolved) { + return + } + + const importerFile = normalizeFilePath(importer) + const resolvedFile = normalizeFilePath(resolved) + const relativeSource = normalizePath( + relative(dirname(importerFile), resolvedFile), + ) + + if (!relativeSource) { + return + } + + const importSource = relativeSource.startsWith('.') + ? relativeSource + : `./${relativeSource}` + + for (const candidate of buildSourceCandidates( + importSource, + undefined, + config.root, + )) { + candidates.add(candidate) + } + } + + /** + * Check if a resolved import violates marker restrictions (e.g. importing + * a server-only module in the client env). If so, build and return the + * {@link ViolationInfo} — the caller is responsible for reporting/deferring. + * + * Returns `undefined` when the resolved import has no marker conflict. + */ + function buildMarkerViolationFromResolvedImport( + envName: string, + envType: 'client' | 'server', + importer: string, + source: string, + resolvedId: string, + traceOverride?: Array, + ): ViolationInfo | undefined { + const normalizedResolvedId = normalizeFilePath(resolvedId) + const markerKind = shared.fileMarkerKind.get(normalizedResolvedId) + const violates = + (envType === 'client' && markerKind === 'server') || + (envType === 'server' && markerKind === 'client') + if (!violates) return undefined + + const normalizedImporter = normalizeFilePath(importer) + + return buildViolationInfo( + envName, + envType, + normalizedImporter, + source, + { + type: 'marker', + resolved: normalizedResolvedId, + }, + traceOverride, + ) + } + + function buildFileViolationInfo( + envName: string, + envType: 'client' | 'server', + normalizedImporter: string, + source: string, + resolvedPath: string, + pattern: string | RegExp, + traceOverride?: Array, + ): ViolationInfo { + return buildViolationInfo( + envName, + envType, + normalizedImporter, + source, + { + type: 'file', + pattern, + resolved: resolvedPath, + }, + traceOverride, + ) + } + + function getRulesForEnvironment(envName: string): EnvRules { + return getImportProtectionRulesForEnvironment(config, envName) as EnvRules + } + + const environmentNames = new Set([ + VITE_ENVIRONMENT_NAMES.client, + VITE_ENVIRONMENT_NAMES.server, + ]) + if (opts.providerEnvName !== VITE_ENVIRONMENT_NAMES.server) { + environmentNames.add(opts.providerEnvName) + } + + /** Get (or lazily create) the per-env state for the given environment name. */ + function getEnv(envName: string): EnvState { + let envState = envStates.get(envName) + if (!envState) { + const transformResultCache = new Map() + envState = { + graph: new ImportGraph(), + mockExportsByImporter: new Map(), + resolveCache: new Map(), + resolveCacheByFile: new Map(), + importLocCache: new ImportLocCache(), + seenViolations: new Set(), + transformResultCache, + transformResultKeysByFile: new Map(), + transformResultProvider: { + getTransformResult(id: string) { + const fullKey = normalizePath(id) + const exact = transformResultCache.get(fullKey) + if (exact) return exact + const strippedKey = normalizeFilePath(id) + return strippedKey !== fullKey + ? transformResultCache.get(strippedKey) + : undefined + }, + }, + postTransformImports: new Map(), + serverFnLookupModules: new Set(), + pendingViolations: new Map(), + deferredBuildViolations: [], + } + envStates.set(envName, envState) + } + return envState + } + + /** + * Search a parsed export-names map for an entry matching any of the + * specifier candidates. Returns matching names or empty array. + */ + function findExportsInMap( + exportMap: Map>, + candidates: Array, + ): Array { + for (const candidate of candidates) { + const hit = exportMap.get(candidate) + if (hit && hit.length > 0) return hit + } + return [] + } + + /** + * Build deduped resolution candidates for a module ID, including the + * extensionless absolute path when the ID looks like a file path. + */ + function buildIdCandidates(id: string, extra?: string): Array { + const set = new Set(buildResolutionCandidates(id)) + if (extra) { + for (const c of buildResolutionCandidates(extra)) set.add(c) + set.add(resolveExtensionlessAbsoluteId(extra)) + } + return Array.from(set) + } + + /** + * Resolve which named exports the importer needs from a denied specifier, + * so mock-edge modules can provide explicit ESM named exports. + * + * Tries multiple strategies: cached export maps, AST parsing, and + * resolver-based comparison. + */ + async function resolveExportsForDeniedSpecifier( + env: EnvState, + ctx: ViolationReporter, + info: ViolationInfo, + importerIdHint?: string, + ): Promise> { + const importerFile = normalizeFilePath(info.importer) + const specifierCandidates = buildIdCandidates(info.specifier, info.resolved) + + // Only parse AST when a violation occurs (this function is only called + // while handling a violation). Cache per-importer to avoid repeated parses + // across multiple violations. + let parsedBySource = env.mockExportsByImporter.get(importerFile) + if (!parsedBySource) { + // Try transform-cache result first, then moduleInfo fallback. + const importerCode = + env.transformResultProvider.getTransformResult(importerFile)?.code ?? + (importerIdHint && ctx.getModuleInfo + ? (ctx.getModuleInfo(importerIdHint)?.code ?? undefined) + : undefined) + if (typeof importerCode !== 'string' || importerCode.length === 0) + return [] + + try { + parsedBySource = getMockExportNamesBySource( + importerCode, + importerFile, + perf, + ) + + // Also index by resolved physical IDs so later lookups match. + await recordMockExportsForImporter( + env, + importerFile, + parsedBySource, + async (src) => { + const cacheKey = `${importerFile}:${src}` + if (env.resolveCache.has(cacheKey)) { + return env.resolveCache.get(cacheKey) ?? undefined + } + if (!ctx.resolve) return undefined + const resolved = await ctx.resolve(src, info.importer, { + skipSelf: true, + }) + if (!resolved || resolved.external) return undefined + return resolved.id + }, + ) + + // Keep the parsed-by-source map for direct lookups. + parsedBySource = + env.mockExportsByImporter.get(importerFile) ?? parsedBySource + } catch { + return [] + } + } + + // 1. Direct candidate match + const direct = findExportsInMap(parsedBySource, specifierCandidates) + if (direct.length > 0) return direct + + // 2. Resolve each source key and compare candidates. + const candidateSet = new Set(specifierCandidates) + for (const [sourceKey, names] of parsedBySource) { + if (!names.length) continue + + const resolvedId = await resolveSourceKey( + env, + ctx, + importerFile, + sourceKey, + info.importer, + ) + if (!resolvedId) continue + + const resolvedCandidates = buildIdCandidates(resolvedId) + resolvedCandidates.push(resolveExtensionlessAbsoluteId(resolvedId)) + if (resolvedCandidates.some((v) => candidateSet.has(v))) { + return names + } + } + + return [] + } + + /** Best-effort resolve a source key using the cache or ctx.resolve. */ + async function resolveSourceKey( + env: EnvState, + ctx: ViolationReporter, + importerFile: string, + sourceKey: string, + importerId: string, + ): Promise { + const cacheKey = `${importerFile}:${sourceKey}` + if (env.resolveCache.has(cacheKey)) { + return env.resolveCache.get(cacheKey) ?? undefined + } + if (!ctx.resolve) return undefined + try { + const resolved = await ctx.resolve(sourceKey, importerId, { + skipSelf: true, + }) + if (!resolved || resolved.external) return undefined + return resolved.id + } catch { + return undefined + } + } + + async function recordMockExportsForImporter( + env: EnvState, + importerId: string, + namesBySource: Map>, + resolveSource: (source: string) => Promise, + ): Promise { + const importerFile = normalizeFilePath(importerId) + + if (namesBySource.size === 0) return + + const resolvedAliases = new Map>() + for (const [source, names] of namesBySource) { + try { + const resolvedId = await resolveSource(source) + if (!resolvedId) continue + + resolvedAliases.set(normalizeFilePath(resolvedId), names) + resolvedAliases.set(resolveExtensionlessAbsoluteId(resolvedId), names) + } catch { + // Best-effort only + } + } + + for (const [source, names] of resolvedAliases) { + namesBySource.set(source, names) + } + + const existing = env.mockExportsByImporter.get(importerFile) + if (!existing) { + env.mockExportsByImporter.set(importerFile, namesBySource) + return + } + + for (const [source, names] of namesBySource) { + const prev = existing.get(source) + if (!prev) { + existing.set(source, names) + continue + } + + const union = new Set([...prev, ...names]) + existing.set(source, Array.from(union).sort()) + } + } + + const shouldCheckImporterCache = new Map() + function shouldCheckImporter(importer: string): boolean { + return shouldCheckImportProtectionImporter( + config, + importer, + shouldCheckImporterCache, + ) + } + + function dedupeKey(info: ViolationInfo): string { + return dedupeViolationKey(info) + } + + function hasSeen(env: EnvState, key: string): boolean { + if (config.logMode === 'always') return false + if (env.seenViolations.has(key)) return true + env.seenViolations.add(key) + return false + } + + function getRelativePath(absolutePath: string): string { + return getImportProtectionRelativePath(config.root, absolutePath) + } + + /** Reset all caches on an EnvState (called from buildStart). */ + function clearEnvState(envState: EnvState): void { + envState.resolveCache.clear() + envState.resolveCacheByFile.clear() + envState.importLocCache.clear() + envState.seenViolations.clear() + envState.transformResultCache.clear() + envState.transformResultKeysByFile.clear() + envState.postTransformImports.clear() + envState.serverFnLookupModules.clear() + envState.pendingViolations.clear() + envState.deferredBuildViolations.length = 0 + envState.graph.clear() + envState.mockExportsByImporter.clear() + } + + /** Invalidate all env-level caches that reference a specific file. */ + function invalidateFileFromEnv(envState: EnvState, file: string): void { + envState.importLocCache.deleteByFile(file) + + // Resolve cache (keyed "importer:source") + const resolveKeys = envState.resolveCacheByFile.get(file) + if (resolveKeys) { + for (const key of resolveKeys) envState.resolveCache.delete(key) + envState.resolveCacheByFile.delete(file) + } + + envState.graph.invalidate(file) + envState.mockExportsByImporter.delete(file) + envState.serverFnLookupModules.delete(file) + envState.pendingViolations.delete(file) + + // Transform result cache + post-transform imports + const transformKeys = envState.transformResultKeysByFile.get(file) + if (transformKeys) { + for (const key of transformKeys) { + envState.transformResultCache.delete(key) + envState.postTransformImports.delete(key) + } + envState.transformResultKeysByFile.delete(file) + } else { + envState.transformResultCache.delete(file) + envState.postTransformImports.delete(file) + } + } + + /** Store a transform result under both the cacheKey and physical file path. */ + function cacheTransformResult( + envState: EnvState, + file: string, + cacheKey: string, + result: TransformResult, + ): void { + envState.transformResultCache.set(cacheKey, result) + const keySet = getOrCreate( + envState.transformResultKeysByFile, + file, + () => new Set(), + ) + keySet.add(cacheKey) + if (cacheKey !== file) { + envState.transformResultCache.set(file, result) + keySet.add(file) + } + } + + /** Register known Start entrypoints as trace roots for all environments. */ + function registerEntries(): void { + const { resolvedStartConfig } = opts.getConfig() + for (const envDef of opts.environments) { + const envState = getEnv(envDef.name) + if (resolvedStartConfig.routerFilePath) { + envState.graph.addEntry( + normalizePath(resolvedStartConfig.routerFilePath), + ) + } + if (resolvedStartConfig.startFilePath) { + envState.graph.addEntry( + normalizePath(resolvedStartConfig.startFilePath), + ) + } + } + } + + /** + * Get the merged set of post-transform imports for a file, checking all + * code-split variants. Returns `null` if no post-transform data exists + * yet (transform hasn't run). + * + * Skips `SERVER_FN_LOOKUP` variants because they contain untransformed + * code — the Start compiler excludes them. + */ + function getPostTransformImports( + env: EnvState, + file: string, + ): Set | null { + const keySet = env.transformResultKeysByFile.get(file) + let merged: Set | null = null + + if (keySet) { + for (const k of keySet) { + if (hasIdQueryFlag(k, SERVER_FN_LOOKUP)) continue + const imports = env.postTransformImports.get(k) + if (imports) { + if (!merged) merged = new Set(imports) + else for (const v of imports) merged.add(v) + } + } + } + + // Fallback: direct file-path key + if (!merged) { + const imports = env.postTransformImports.get(file) + if (imports) merged = new Set(imports) + } + + return merged + } + + /** + * Check whether an import edge from `parent` to `target` survived + * post-transform compilation. + * + * Returns: + * - `'live'` — target appears in a non-lookup variant's post-transform imports + * - `'dead'` — post-transform data exists but target is absent (compiler stripped it) + * - `'pending'` — transform ran but import data not yet posted + * - `'no-data'` — transform never ran (warm-start cached module) + */ + function checkEdgeLiveness( + env: EnvState, + parent: string, + target: string, + ): 'live' | 'dead' | 'pending' | 'no-data' { + const keySet = env.transformResultKeysByFile.get(parent) + let anyVariantCached = false + + if (keySet) { + for (const k of keySet) { + if (hasIdQueryFlag(k, SERVER_FN_LOOKUP)) continue + const imports = env.postTransformImports.get(k) + if (imports) { + anyVariantCached = true + if (imports.has(target)) return 'live' + } + } + } + + if (!anyVariantCached) { + const imports = env.postTransformImports.get(parent) + if (imports) return imports.has(target) ? 'live' : 'dead' + const hasTransformResult = + env.transformResultCache.has(parent) || + (keySet ? keySet.size > 0 : false) + return hasTransformResult ? 'pending' : 'no-data' + } + + return 'dead' + } + + function checkPostTransformReachability( + env: EnvState, + file: string, + ): 'reachable' | 'unreachable' | 'unknown' { + const visited = new Set() + const queue: Array = [file] + let hasUnknownEdge = false + let qi = 0 + + while (qi < queue.length) { + const current = queue[qi++]! + if (visited.has(current)) { + continue + } + visited.add(current) + + if (env.graph.entries.has(current)) { + return 'reachable' + } + + const importers = env.graph.reverseEdges.get(current) + if (!importers) continue + + for (const [parent] of importers) { + if (visited.has(parent)) continue + const liveness = checkEdgeLiveness(env, parent, current) + if (liveness === 'live' || liveness === 'no-data') { + // Live edge or warm-start (no transform data) — follow it + queue.push(parent) + } else if (liveness === 'pending') { + hasUnknownEdge = true + } + // 'dead' — edge was stripped by compiler, skip + } + } + + return hasUnknownEdge ? 'unknown' : 'unreachable' + } + + /** + * Filter pending violations using edge-survival data. Returns the subset + * of violations whose resolved import survived the Start compiler (or all + * violations when no post-transform data is available yet). + * + * Returns `undefined` when all violations were stripped or when we must wait + * for post-transform data before proceeding. + */ + function filterEdgeSurvival( + env: EnvState, + file: string, + violations: Array, + ): + | { active: Array; edgeSurvivalApplied: boolean } + | 'all-stripped' + | 'await-transform' { + const postTransform = getPostTransformImports(env, file) + + if (postTransform) { + const surviving = violations.filter( + (pv) => !pv.info.resolved || postTransform.has(pv.info.resolved), + ) + if (surviving.length === 0) return 'all-stripped' + env.pendingViolations.set(file, surviving) + return { active: surviving, edgeSurvivalApplied: true } + } + + // Pre-transform violations need edge-survival verification first. + if (violations.some((pv) => pv.fromPreTransformResolve)) { + return 'await-transform' + } + + return { active: violations, edgeSurvivalApplied: false } + } + + /** + * Process pending violations for the given environment. Called from the + * transform-cache hook after each module transform is cached, because new + * transform data may allow us to confirm or discard pending violations. + * + * @param warnFn - `this.warn` from the transform hook context + */ + async function processPendingViolations( + env: EnvState, + warnFn: (msg: string) => void, + ): Promise { + if (env.pendingViolations.size === 0) return + + const toDelete: Array = [] + + for (const [file, violations] of env.pendingViolations) { + const filtered = filterEdgeSurvival(env, file, violations) + + if (filtered === 'all-stripped') { + toDelete.push(file) + continue + } + if (filtered === 'await-transform') continue + + const { active, edgeSurvivalApplied } = filtered + const isBundledClientDev = + config.command === 'serve' && + config.bundledDev && + active.some((pv) => pv.info.envType === 'client') + // Wait for entries before running reachability. registerEntries() + // populates entries at buildStart; resolveId(!importer) may add more. + let status: 'reachable' | 'unreachable' | 'unknown' + if (env.graph.entries.size > 0) { + status = checkPostTransformReachability(env, file) + } else { + status = 'unknown' + } + + if (status === 'reachable') { + for (const pv of active) { + await emitPendingViolation(env, warnFn, pv) + } + toDelete.push(file) + } else if (status === 'unreachable') { + if (isBundledClientDev) { + // Bundled dev can transform a child before its route/importer has + // recorded the source edge. Keep confirmed-surviving violations + // pending until a real source importer makes them reachable. + continue + } + toDelete.push(file) + } else if (config.command === 'serve') { + // 'unknown' reachability — some graph edges lack transform data. + // When edge-survival was applied, surviving violations are confirmed + // real. Without it (warm start), emit conservatively. + let emittedAny = false + for (const pv of active) { + if (pv.fromPreTransformResolve) continue + + const shouldEmit = + edgeSurvivalApplied || + (pv.info.type === 'file' && + !!pv.info.resolved && + isInsideDirectory(pv.info.resolved, config.srcDirectory)) + + if (shouldEmit) { + emittedAny = + (await emitPendingViolation(env, warnFn, pv)) || emittedAny + } + } + + if (emittedAny) { + toDelete.push(file) + } + } + // 'unknown' — keep pending for next transform-cache invocation. + } + + for (const file of toDelete) { + env.pendingViolations.delete(file) + } + } + + async function emitPendingViolation( + env: EnvState, + warnFn: (msg: string) => void, + pv: PendingViolation, + ): Promise { + if (hasSeen(env, dedupeKey(pv.info))) { + return false + } + + await enrichViolationInfo( + env.transformResultProvider, + env, + pv.info.env, + pv.info.envType, + pv.info.importer, + pv.info, + ) + + if (config.onViolation) { + const result = await config.onViolation(pv.info) + if (result === false) return false + } + + warnFn(formatViolation(pv.info, config.root)) + return true + } + + /** + * Record a violation as pending for later confirmation via graph + * reachability. Called from `resolveId` when `shouldDefer` is true. + */ + function deferViolation( + env: EnvState, + importerFile: string, + info: ViolationInfo, + isPreTransformResolve?: boolean, + ): void { + getOrCreate(env.pendingViolations, importerFile, () => []).push({ + info, + fromPreTransformResolve: isPreTransformResolve, + }) + } + + /** Counter for generating unique per-violation mock module IDs in build mode. */ + let buildViolationCounter = 0 + + async function handleViolation( + ctx: ViolationReporter, + env: EnvState, + info: ViolationInfo, + importerIdHint?: string, + violationOpts?: { silent?: boolean }, + ): Promise { + if (!violationOpts?.silent) { + await enrichViolationInfo( + env.transformResultProvider, + env, + info.env, + info.envType, + importerIdHint ?? info.importer, + info, + ) + + if (config.onViolation) { + const result = await config.onViolation(info) + if (result === false) return undefined + } + + if (config.effectiveBehavior === 'error') { + // Dev+error: throw immediately. + // Always throw on error — do NOT deduplicate via hasSeen(). + // Rollup may resolve the same specifier multiple times (e.g. + // commonjs--resolver's nested this.resolve() fires before + // getResolveStaticDependencyPromises). If we record the key + // on the first (nested) throw, the second (real) resolve + // silently returns undefined and the build succeeds — which + // is the bug this fixes. + // + // Build mode never reaches here — all build violations are + // deferred via shouldDefer and handled silently. + return ctx.error(formatViolation(info, config.root)) + } + + if (!hasSeen(env, dedupeKey(info))) { + ctx.warn(formatViolation(info, config.root)) + } + } else if ( + config.effectiveBehavior === 'error' && + config.command !== 'build' + ) { + return undefined + } + + // File violations: return resolved path — the self-denial transform + // will replace the file's content with a mock module. This avoids + // virtual module IDs that could leak across environments via + // third-party resolver caches. + if (info.type === 'file') return info.resolved + + // Non-file violations (specifier/marker): create mock-edge module. + // Dev mode uses a runtime diagnostics ID; build mode uses a unique + // per-violation ID so generateBundle can check tree-shaking survival. + const exports = await resolveExportsForDeniedSpecifier( + env, + ctx, + info, + importerIdHint, + ) + const baseMockId = + config.command === 'serve' + ? mockRuntimeModuleIdFromViolation(info, config.mockAccess, config.root) + : `${MOCK_BUILD_PREFIX}${buildViolationCounter++}` + return resolveViteId(makeMockEdgeModuleId(exports, baseMockId)) + } + + /** + * Unified violation dispatch: either defers or reports immediately. + * + * When `shouldDefer` is true (dev mock + build modes), calls + * `handleViolation` silently to obtain the mock module ID, then stores + * the violation for later verification: + * - Dev mock mode: all violations are deferred to `pendingViolations` + * for edge-survival and graph-reachability checking via + * `processPendingViolations`. + * - Build mode (mock + error): defers to `deferredBuildViolations` for + * tree-shaking verification in `generateBundle`. + * + * Otherwise reports immediately (dev error mode). Pre-transform + * resolves are silenced in error mode because they fire before the + * compiler runs and there is no deferred verification path. + * + * Returns the mock module ID / resolve result from `handleViolation`. + */ + async function reportOrDeferViolation( + ctx: ViolationReporter, + env: EnvState, + importerFile: string, + importerIdHint: string | undefined, + info: ViolationInfo, + shouldDefer: boolean, + isPreTransformResolve: boolean, + ): Promise { + if (shouldDefer) { + const result = await handleViolation(ctx, env, info, importerIdHint, { + silent: true, + }) + + if (config.command === 'build') { + // Build mode: store for generateBundle tree-shaking check. + // The mock-edge module ID is returned as a plain string. + const mockId = result ?? '' + env.deferredBuildViolations.push({ + info, + mockModuleId: mockId, + // For marker violations, check importer survival instead of mock. + checkModuleId: info.type === 'marker' ? info.importer : undefined, + }) + } else { + // Dev mock: store for graph-reachability check. + deferViolation(env, importerFile, info, isPreTransformResolve) + await processPendingViolations(env, ctx.warn.bind(ctx)) + } + + return result + } + + // Non-deferred path: dev error mode only. + // Pre-transform resolves are silenced because they fire before the + // compiler runs — imports inside `.server()` callbacks haven't been + // stripped yet and error mode has no deferred verification. + return handleViolation(ctx, env, info, importerIdHint, { + silent: isPreTransformResolve, + }) + } + + return [ + { + name: 'tanstack-start-core:import-protection', + enforce: 'pre', + + applyToEnvironment(env) { + if (!config.enabled) return false + // Start's environments are named `client` and `ssr` (not `server`), plus + // an optional serverFn provider environment (eg `rsc`) when configured. + return environmentNames.has(env.name) + }, + + configResolved(viteConfig) { + config.root = viteConfig.root + config.command = viteConfig.command + config.bundledDev = !!viteConfig.experimental.bundledDev + + const { startConfig, resolvedStartConfig } = opts.getConfig() + config.srcDirectory = resolvedStartConfig.srcDirectory + + const userOpts: ImportProtectionOptions | undefined = + startConfig.importProtection + + if (userOpts?.enabled === false) { + config.enabled = false + return + } + + config.enabled = true + + const behavior = userOpts?.behavior + if (typeof behavior === 'string') { + config.effectiveBehavior = behavior + } else { + config.effectiveBehavior = + viteConfig.command === 'serve' + ? (behavior?.dev ?? 'mock') + : (behavior?.build ?? 'error') + } + + config.logMode = userOpts?.log ?? 'once' + config.mockAccess = userOpts?.mockAccess ?? 'error' + config.maxTraceDepth = userOpts?.maxTraceDepth ?? 20 + if (userOpts?.onViolation) { + const fn = userOpts.onViolation + config.onViolation = (info) => fn(info) + } + + const defaults = getDefaultImportProtectionRules() + // Use user-provided patterns when available, otherwise defaults. + const pick = (user: Array | undefined, fallback: Array) => + user ? [...user] : [...fallback] + + // Client specifier denies always include framework defaults even + // when the user provides a custom list. + const clientSpecifiers = dedupePatterns([ + ...defaults.client.specifiers, + ...(userOpts?.client?.specifiers ?? []), + ]) + + config.compiledRules.client = { + specifiers: compileMatchers(clientSpecifiers), + files: compileMatchers( + pick(userOpts?.client?.files, defaults.client.files), + ), + excludeFiles: compileMatchers( + pick(userOpts?.client?.excludeFiles, defaults.client.excludeFiles), + ), + } + config.compiledRules.server = { + specifiers: compileMatchers( + dedupePatterns( + pick(userOpts?.server?.specifiers, defaults.server.specifiers), + ), + ), + files: compileMatchers( + pick(userOpts?.server?.files, defaults.server.files), + ), + excludeFiles: compileMatchers( + pick(userOpts?.server?.excludeFiles, defaults.server.excludeFiles), + ), + } + + config.includeMatchers = compileMatchers(userOpts?.include ?? []) + config.excludeMatchers = compileMatchers(userOpts?.exclude ?? []) + config.ignoreImporterMatchers = compileMatchers( + userOpts?.ignoreImporters ?? [], + ) + + // Marker specifiers + const markers = getMarkerSpecifiers() + config.markerSpecifiers = { + serverOnly: new Set(markers.serverOnly), + clientOnly: new Set(markers.clientOnly), + } + }, + + configureServer(server) { + devServer = server + }, + + buildStart() { + if (!config.enabled) return + // Clear memoization caches that grow unboundedly across builds + clearNormalizeFilePathCache() + extensionlessIdResolver.clear() + shouldCheckImporterCache.clear() + + // Clear per-env caches + for (const envState of envStates.values()) { + clearEnvState(envState) + } + + // Clear shared state + shared.fileMarkerKind.clear() + + registerEntries() + }, + + hotUpdate(ctx) { + if (!config.enabled) return + // Invalidate caches for updated files + for (const mod of ctx.modules) { + if (mod.id) { + const id = mod.id + const importerFile = normalizeFilePath(id) + + // Invalidate extensionless-resolution cache entries affected by this file. + extensionlessIdResolver.invalidateByFile(importerFile) + shared.fileMarkerKind.delete(importerFile) + + // Invalidate per-env caches + for (const envState of envStates.values()) { + invalidateFileFromEnv(envState, importerFile) + } + } + } + }, + + resolveId: { + filter: { + id: { + exclude: [ + /^\0(?!tanstack-start-import-protection:)/, + /^virtual:(?!tanstack-start-import-protection:)/, + ], + }, + }, + async handler(source, importer, _options) { + perf?.count('resolveId.calls') + const envName = this.environment.name + const env = getEnv(envName) + const envType = getImportProtectionEnvType(config, envName) + const isScanResolve = !!(_options as Record).scan + + if (IMPORT_PROTECTION_DEBUG) { + const importerPath = importer + ? normalizeFilePath(importer) + : '(entry)' + const isEntryResolve = !importer + const filtered = + process.env.TSR_IMPORT_PROTECTION_DEBUG_FILTER === 'entry' + ? isEntryResolve + : matchesDebugFilter(source, importerPath) + if (filtered) { + debugLog('resolveId', { + env: envName, + envType, + source, + importer: importerPath, + isEntryResolve, + command: config.command, + }) + } + } + + // Internal virtual modules (mock:build:N, mock-edge, mock-runtime, marker) + const internalVirtualId = resolveInternalVirtualModuleId(source) + if (internalVirtualId) return internalVirtualId + + if (!importer) { + const normalizedSource = normalizeFilePath(source) + const isBundledClientSourceEntry = + config.command === 'serve' && + config.bundledDev && + envType === 'client' && + isInsideDirectory(normalizedSource, config.srcDirectory) + + if (!isBundledClientSourceEntry) { + env.graph.addEntry(source) + } + // Flush pending violations now that an additional entry is known + // and reachability analysis may have new roots. + await processPendingViolations(env, this.warn.bind(this)) + return undefined + } + + if (source.startsWith('\0') || source.startsWith('virtual:')) { + return undefined + } + + const normalizedImporter = normalizeFilePath(importer) + const isDirectLookup = hasIdQueryFlag(importer, SERVER_FN_LOOKUP) + const isBundledClientDev = + config.command === 'serve' && + config.bundledDev && + envType === 'client' + + if (isBundledClientDev) { + const routesDirectory = normalizePath( + `${config.srcDirectory}/routes`, + ) + if (isInsideDirectory(normalizedImporter, routesDirectory)) { + env.graph.addEntry(normalizedImporter) + } + } + + if (isDirectLookup) { + env.serverFnLookupModules.add(normalizedImporter) + } + + const isServerFnPreTransformResolve = + isDirectLookup || env.serverFnLookupModules.has(normalizedImporter) + const isPreTransformResolve = + isServerFnPreTransformResolve || isScanResolve + const shouldRecordGraphEdge = !isServerFnPreTransformResolve + + // Dev mock mode: defer all violations (including pre-transform + // resolves) until post-transform data is available, then + // confirm/discard via graph reachability. + // Build mode (both mock and error): defer violations until + // generateBundle so tree-shaking can eliminate false positives. + const isDevMock = + config.command === 'serve' && config.effectiveBehavior === 'mock' + const isBuild = config.command === 'build' + const shouldDefer = shouldDeferViolation({ isBuild, isDevMock }) + + type PluginResolveResult = NonNullable< + Awaited> + > + + const resolveAgainstImporter = async (): Promise<{ + id: string + result: PluginResolveResult + } | null> => { + const startedAt = perf ? performance.now() : 0 + perf?.count('thisResolve.calls') + let primary: PluginResolveResult | null = null + try { + const resolveOptions: Parameters[2] = { + custom: _options.custom, + isEntry: _options.isEntry, + skipSelf: true, + } + if ('attributes' in _options) { + const resolveOptionsWithAttributes = + resolveOptions as typeof resolveOptions & { + attributes?: unknown + } + resolveOptionsWithAttributes.attributes = _options.attributes + } + primary = await this.resolve(source, importer, resolveOptions) + } finally { + if (perf) { + perf.time('thisResolve', startedAt) + } + } + if (primary) { + return { + id: canonicalizeResolvedId( + primary.id, + config.root, + resolveExtensionlessAbsoluteId, + ), + result: primary, + } + } + + return null + } + + // Check if this is a marker import + const markerKind = config.markerSpecifiers.serverOnly.has(source) + ? ('server' as const) + : config.markerSpecifiers.clientOnly.has(source) + ? ('client' as const) + : undefined + + if (markerKind) { + const existing = shared.fileMarkerKind.get(normalizedImporter) + if (existing && existing !== markerKind) { + this.error( + `[import-protection] File "${getRelativePath(normalizedImporter)}" has both server-only and client-only markers. This is not allowed.`, + ) + } + shared.fileMarkerKind.set(normalizedImporter, markerKind) + + const violatesEnv = + (envType === 'client' && markerKind === 'server') || + (envType === 'server' && markerKind === 'client') + + if (violatesEnv) { + const info = buildViolationInfo( + envName, + envType, + normalizedImporter, + source, + { + type: 'marker', + }, + ) + const markerResult = await reportOrDeferViolation( + this, + env, + normalizedImporter, + importer, + info, + shouldDefer, + isPreTransformResolve, + ) + + // In build mode, if the violation was deferred, return the unique + // build mock ID instead of the marker module. This lets + // generateBundle check whether the importer (and thus its marker + // import) survived tree-shaking. The mock is side-effect-free just + // like the marker module, and the bare import has no bindings, so + // replacing it is transparent. + if (isBuild && markerResult != null) { + return markerResult + } + } + + // Retroactive marker violation detection: on cold starts, module + // A may import module B before B's marker is set (because B hasn't + // been processed yet). When B's marker is set (here), + // retroactively check all known importers of B in the graph and + // create deferred marker violations for them. Without this, + // cold-start ordering can miss marker violations that warm starts + // detect (warm starts see markers early from cached transforms). + // + // Uses lightweight `deferViolation` to avoid heavy side effects + // (mock module creation, export resolution). Immediately calls + // `processPendingViolations` to flush the deferred violations, + // because the marker resolveId fires during Vite's import + // analysis (after our transform hook) — there may be no + // subsequent transform invocation to flush them. + // + // Guarded by `violatesEnv` (per-environment) plus a per-env + // seen-set. The marker is shared across environments but each + // env's graph has its own edges; this ensures the check runs + // at most once per (env, module) pair. + const envRetroKey = `retro-marker:${normalizedImporter}` + if (violatesEnv && !env.seenViolations.has(envRetroKey)) { + env.seenViolations.add(envRetroKey) + let retroDeferred = false + const importersMap = + env.graph.reverseEdges.get(normalizedImporter) + if (importersMap && importersMap.size > 0) { + for (const [importerFile, specifier] of importersMap) { + if (!specifier) continue + if (!shouldCheckImporter(importerFile)) continue + const markerInfo = buildMarkerViolationFromResolvedImport( + envName, + envType, + importerFile, + specifier, + normalizedImporter, + ) + if (markerInfo) { + deferViolation( + env, + importerFile, + markerInfo, + isPreTransformResolve, + ) + retroDeferred = true + } + } + } + if (retroDeferred) { + await processPendingViolations(env, this.warn.bind(this)) + } + } + + return markerKind === 'server' + ? resolvedMarkerVirtualModuleId('server') + : resolvedMarkerVirtualModuleId('client') + } + + // Check if the importer is within our scope + if (!shouldCheckImporter(normalizedImporter)) { + return undefined + } + + const matchers = getRulesForEnvironment(envName) + + // 1. Specifier-based denial + const specifierMatch = matchesAny(source, matchers.specifiers) + if (specifierMatch) { + if (shouldRecordGraphEdge) { + env.graph.addEdge(source, normalizedImporter, source) + } + const info = buildViolationInfo( + envName, + envType, + normalizedImporter, + source, + { + type: 'specifier', + pattern: specifierMatch.pattern, + }, + ) + + // Resolve the specifier so edge-survival can verify whether + // the import survives the Start compiler transform (e.g. + // factory-safe pattern strips imports inside .server() callbacks). + if (shouldDefer && !info.resolved) { + try { + const resolvedForInfo = await resolveAgainstImporter() + if (resolvedForInfo) { + info.resolved = resolvedForInfo.id + } + } catch { + // Non-fatal: edge-survival will skip unresolved specifiers + } + } + + return reportOrDeferViolation( + this, + env, + normalizedImporter, + importer, + info, + shouldDefer, + isPreTransformResolve, + ) + } + + // 2. Resolve the import (cached) + const cacheKey = `${normalizedImporter}:${source}` + let resolved: string | null + let passThroughResult: PluginResolveResult | null = null + + if (env.resolveCache.has(cacheKey)) { + resolved = env.resolveCache.get(cacheKey) ?? null + } else { + const resolution = await resolveAgainstImporter() + resolved = resolution?.id ?? null + passThroughResult = resolution?.result ?? null + + // Only cache successful resolves. Null resolves can be + // order-dependent across importer variants (e.g. code-split + // `?tsr-split=...` ids) and may poison later lookups. + if (resolved !== null) { + env.resolveCache.set(cacheKey, resolved) + getOrCreate( + env.resolveCacheByFile, + normalizedImporter, + () => new Set(), + ).add(cacheKey) + } + } + + if (resolved) { + const relativePath = getRelativePath(resolved) + + // Propagate pre-transform status transitively + if (isServerFnPreTransformResolve) { + env.serverFnLookupModules.add(resolved) + } + + if (shouldRecordGraphEdge) { + env.graph.addEdge(resolved, normalizedImporter, source) + } + + // Skip file-based and marker-based denial for resolved paths that + // match the per-environment `excludeFiles` patterns. By default + // this includes `**/node_modules/**` so that third-party packages + // using `.client.` / `.server.` in their filenames (e.g. react-tweet + // exports `index.client.js`) are not treated as user-authored + // environment boundaries. Users can override `excludeFiles` per + // environment to narrow or widen this exclusion. + const isExcludedFile = isFileExcluded(relativePath, matchers) + + if (!isExcludedFile) { + const fileMatch = matchers.files.find((matcher) => + matcher.test(relativePath), + ) + + if (fileMatch) { + const info = buildFileViolationInfo( + envName, + envType, + normalizedImporter, + source, + resolved, + fileMatch.pattern, + ) + return reportOrDeferViolation( + this, + env, + normalizedImporter, + importer, + info, + shouldDefer, + isPreTransformResolve, + ) + } + + const markerInfo = buildMarkerViolationFromResolvedImport( + envName, + envType, + importer, + source, + resolved, + ) + if (markerInfo) { + return reportOrDeferViolation( + this, + env, + normalizedImporter, + importer, + markerInfo, + shouldDefer, + isPreTransformResolve, + ) + } + } + + if (passThroughResult) { + return passThroughResult + } + } + + return undefined + }, + }, + + load: { + filter: { + id: new RegExp( + getResolvedVirtualModuleMatchers().map(escapeRegExp).join('|'), + ), + }, + handler(id) { + if (IMPORT_PROTECTION_DEBUG) { + if (matchesDebugFilter(id)) { + debugLog('load:handler', { + env: this.environment.name, + id: normalizePath(id), + }) + } + } + + return loadResolvedVirtualModule(id) + }, + }, + + async generateBundle(_options, bundle) { + const envName = this.environment.name + const env = envStates.get(envName) + if (!env) { + return + } + if (config.command === 'serve' && config.bundledDev) { + // Child transforms can finish before their importers. Verify pending + // violations once the completed bundle has recorded every edge. + await processPendingViolations(env, this.warn.bind(this)) + } + if (env.deferredBuildViolations.length === 0) { + return + } + + const candidateCache = new Map>() + const toModuleIdCandidates = (id: string): Array => { + let cached = candidateCache.get(id) + if (cached) return cached + + const out = new Set() + const normalized = normalizeFilePath(id) + out.add(id) + out.add(normalized) + out.add(relativizePath(normalized, config.root)) + + if (normalized.startsWith(VITE_BROWSER_VIRTUAL_PREFIX)) { + const internal = `\0${normalized.slice(VITE_BROWSER_VIRTUAL_PREFIX.length)}` + out.add(internal) + out.add(relativizePath(normalizeFilePath(internal), config.root)) + } + + if (normalized.startsWith('\0')) { + const browser = `${VITE_BROWSER_VIRTUAL_PREFIX}${normalized.slice(1)}` + out.add(browser) + out.add(relativizePath(normalizeFilePath(browser), config.root)) + } + + cached = Array.from(out) + candidateCache.set(id, cached) + return cached + } + + // Collect all module IDs that survived tree-shaking in this bundle. + const survivingModules = new Set() + for (const chunk of Object.values(bundle)) { + if (chunk.type === 'chunk') { + for (const moduleId of Object.keys(chunk.modules)) { + for (const candidate of toModuleIdCandidates(moduleId)) { + survivingModules.add(candidate) + } + } + } + } + + const didModuleSurvive = (moduleId: string): boolean => + toModuleIdCandidates(moduleId).some((candidate) => + survivingModules.has(candidate), + ) + + // Check each deferred violation: if its check module survived + // in the bundle, the import was NOT tree-shaken — real leak. + const realViolations: Array = [] + for (const { + info, + mockModuleId, + checkModuleId, + } of env.deferredBuildViolations) { + let survived: boolean + if (checkModuleId != null) { + // Marker violation: check if the importer survived + // (marker is about the file's directive, not a binding). + // Include transform-result keys (e.g. code-split variants) + // to cover all bundle representations of the importer. + const importerVariantIds = new Set([info.importer]) + const importerKeys = env.transformResultKeysByFile.get( + normalizeFilePath(info.importer), + ) + if (importerKeys) { + for (const key of importerKeys) { + importerVariantIds.add(key) + } + } + survived = false + for (const importerId of importerVariantIds) { + if (didModuleSurvive(importerId)) { + survived = true + break + } + } + } else { + // File/specifier violation: check if the mock module survived. + survived = didModuleSurvive(mockModuleId) + } + + if (!survived) continue + + await enrichViolationInfo( + env.transformResultProvider, + env, + info.env, + info.envType, + info.importer, + info, + ) + + if (config.onViolation) { + const result = await config.onViolation(info) + if (result === false) continue + } + + realViolations.push(info) + } + + if (realViolations.length === 0) return + + if (config.effectiveBehavior === 'error') { + // Error mode: fail the build on the first real violation. + this.error(formatViolation(realViolations[0]!, config.root)) + } else { + // Mock mode: warn for each surviving violation. + const seen = new Set() + for (const info of realViolations) { + const key = dedupeKey(info) + if (!seen.has(key)) { + seen.add(key) + this.warn(formatViolation(info, config.root)) + } + } + } + }, + + closeBundle() { + const envName = this.environment.name + perf?.count('closeBundle.calls') + perf?.count(`closeBundle.env.${envName}`) + perf?.flush(config.root, envName) + }, + }, + { + // Captures transformed code + composed sourcemap for location mapping. + // Runs after all `enforce: 'pre'` hooks (including the Start compiler). + // Only files under `srcDirectory` are cached. + name: 'tanstack-start-core:import-protection-transform-cache', + + applyToEnvironment(env) { + if (!config.enabled) return false + return environmentNames.has(env.name) + }, + + transform: { + filter: { + id: { + include: [/\.[cm]?[tj]sx?($|\?)/], + }, + }, + async handler(code, id) { + perf?.count('transform.calls') + const envName = this.environment.name + const file = normalizeFilePath(id) + const envType = getImportProtectionEnvType(config, envName) + const matchers = getRulesForEnvironment(envName) + const isBuild = config.command === 'build' + + if (IMPORT_PROTECTION_DEBUG) { + if (matchesDebugFilter(file)) { + debugLog('transform-cache', { + env: envName, + id: normalizePath(id), + file, + }) + } + } + + if (!shouldCheckImporter(file)) { + return undefined + } + + // Self-denial: if this file is denied in the current environment + // (e.g. a `.server` file transformed in the client environment), + // replace its entire content with a mock module. + // + // This is the core mechanism for preventing cross-environment + // cache contamination: resolveId never returns virtual module + // IDs for file-based violations, so there is nothing for + // third-party resolver caches (e.g. vite-tsconfig-paths) to + // leak across environments. Each environment's transform + // independently decides whether the file is denied. + // + // In dev mode, this also solves the cold-start problem where + // the importer's AST is unavailable for export resolution: + // the denied file's own source code is always available here, + // so we parse its exports directly. + const selfFileMatch = checkFileDenial(getRelativePath(file), matchers) + if (selfFileMatch) { + // Parse exports once — shared by build and dev paths. + // Falls back to empty list on non-standard syntax. + let exportNames: Array = [] + try { + exportNames = getNamedExports(code, file, perf) + } catch { + // Parsing may fail on non-standard syntax + } + + if (isBuild) { + return generateSelfContainedMockModule(exportNames) + } + + // Dev mode: generate a mock that imports mock-runtime for + // runtime diagnostics (error/warn on property access). + const runtimeId = mockRuntimeModuleIdFromViolation( + { + type: 'file', + env: envType, + envType, + behavior: + config.effectiveBehavior === 'error' ? 'error' : 'mock', + importer: file, + specifier: relativizePath(file, config.root), + resolved: file, + pattern: selfFileMatch.pattern, + trace: [], + }, + config.mockAccess, + config.root, + ) + return generateDevSelfDenialModule(exportNames, runtimeId) + } + + const cacheKey = normalizePath(id) + + const envState = getEnv(envName) + const isServerFnLookup = hasIdQueryFlag(id, SERVER_FN_LOOKUP) + + // Propagate SERVER_FN_LOOKUP status before import-analysis + if (isServerFnLookup) { + envState.serverFnLookupModules.add(file) + } + + const result: TransformResult = { + code, + filename: file, + map: undefined, + originalCode: undefined, + } + + if (perf) { + result.perf = perf + } + + if (shouldCaptureDiagnosticSourceMap(code, envType, matchers)) { + captureDiagnosticSourceMap( + result, + () => this.getCombinedSourcemap(), + 'candidate', + ) + } + + cacheTransformResult(envState, file, cacheKey, result) + + // Build mode: only self-denial (above) and transform caching are + // needed. All violations are detected and deferred in resolveId; + // self-denial replaces denied file content; generateBundle checks + // tree-shaking survival. The import resolution loop below is + // dev-mode only — it resolves imports for graph reachability, + // catches violations missed on warm starts (where Vite caches + // resolveId), and rewrites denied imports to mock modules. + if (isBuild) return undefined + + // Dev mode: resolve imports, populate graph, detect violations, + // and rewrite denied imports. + const isDevMock = config.effectiveBehavior === 'mock' + const importAnalysisStartedAt = perf ? performance.now() : 0 + const importSources = getImportSourcesFromResult(result) + if (perf) { + perf.time('transform.importAnalysis', importAnalysisStartedAt) + } + perf?.count('transform.importSources', importSources.length) + const resolvedChildren = new Set() + const deniedSourceReplacements = new Map() + for (const src of importSources) { + try { + const startedAt = perf ? performance.now() : 0 + perf?.count('transform.thisResolve.calls') + const resolved = await this.resolve(src, id, { skipSelf: true }) + if (perf) { + perf.time('transform.thisResolve', startedAt) + } + if (resolved && !resolved.external) { + const resolvedPath = canonicalizeResolvedId( + resolved.id, + config.root, + resolveExtensionlessAbsoluteId, + ) + + resolvedChildren.add(resolvedPath) + + // When the resolved ID is a mock-module (from our + // resolveId returning a mock-edge ID), postTransformImports + // would only contain the mock ID. Edge-survival needs the + // real physical path so pending violations can be matched. + // + // For relative specifiers we can compute the physical path + // directly. For bare/alias specifiers, look up the real + // resolved path from the pending violations that were + // already stored by resolveId before this transform ran. + if (resolved.id.includes('tanstack-start-import-protection:')) { + let physicalPath: string | undefined + // Look up real resolved path from pending violations + const pending = envState.pendingViolations.get(file) + if (pending) { + const match = pending.find( + (pv) => pv.info.specifier === src && pv.info.resolved, + ) + if (match) physicalPath = match.info.resolved + } + if (physicalPath && physicalPath !== resolvedPath) { + resolvedChildren.add(physicalPath) + envState.graph.addEdge(physicalPath, file, src) + } + } + + // Populate import graph edges for warm-start trace accuracy + envState.graph.addEdge(resolvedPath, file, src) + + if (isDevMock) { + const relativePath = getRelativePath(resolvedPath) + const fileMatch = checkFileDenial(relativePath, matchers) + + if (fileMatch) { + captureDiagnosticSourceMap( + result, + () => this.getCombinedSourcemap(), + 'devViolation', + ) + + const info = buildFileViolationInfo( + envName, + envType, + file, + src, + resolvedPath, + fileMatch.pattern, + ) + + const replacement = await reportOrDeferViolation( + this, + envState, + file, + id, + info, + isDevMock, + isServerFnLookup, + ) + + if (replacement) { + deniedSourceReplacements.set( + src, + replacement.startsWith('\0') + ? VITE_BROWSER_VIRTUAL_PREFIX + replacement.slice(1) + : replacement, + ) + } + } + } + } + } catch { + // Non-fatal + } + } + // A split component's imports must not replace the unsplit route's + // imports. Reachability merges the separately cached variants. + envState.postTransformImports.set(cacheKey, resolvedChildren) + + await processPendingViolations(envState, this.warn.bind(this)) + + if (deniedSourceReplacements.size > 0) { + try { + const rewritten = rewriteDeniedImports( + code, + id, + new Set(deniedSourceReplacements.keys()), + (source: string) => + deniedSourceReplacements.get(source) ?? source, + ) + + if (!rewritten) { + return undefined + } + + const normalizedMap = rewritten.map + ? normalizeSourceMap(rewritten.map) + : { + version: 3, + file: id, + names: [], + sources: [id], + sourcesContent: [code], + mappings: '', + } + + return { + code: rewritten.code, + map: normalizedMap, + } + } catch { + // Non-fatal: keep original code when rewrite fails. + } + } + + return undefined + }, + }, + }, + ] satisfies Array +} diff --git a/packages/start-plugin-core/src/vite/import-protection-plugin/types.ts b/packages/start-plugin-core/src/vite/import-protection-plugin/types.ts new file mode 100644 index 0000000000..21691783ea --- /dev/null +++ b/packages/start-plugin-core/src/vite/import-protection-plugin/types.ts @@ -0,0 +1,104 @@ +import type { CompileStartFrameworkOptions, GetConfigFn } from '../../types' +import type { ImportProtectionBehavior } from '../../schema' +import type { CompiledMatcher } from '../../import-protection/matchers' +import type { ImportGraph, ViolationInfo } from '../../import-protection/trace' +import type { + ImportLocCache, + TransformResult, + TransformResultProvider, +} from '../../import-protection/sourceLocation' + +/** Compiled deny/exclude patterns for one environment (client or server). */ +export interface EnvRules { + specifiers: Array + files: Array + excludeFiles: Array +} + +export interface PluginConfig { + enabled: boolean + root: string + command: 'build' | 'serve' + bundledDev: boolean + srcDirectory: string + framework: CompileStartFrameworkOptions + effectiveBehavior: ImportProtectionBehavior + mockAccess: 'error' | 'warn' | 'off' + logMode: 'once' | 'always' + maxTraceDepth: number + compiledRules: { + client: EnvRules + server: EnvRules + } + includeMatchers: Array + excludeMatchers: Array + ignoreImporterMatchers: Array + markerSpecifiers: { serverOnly: Set; clientOnly: Set } + envTypeMap: Map + onViolation?: ( + info: ViolationInfo, + ) => boolean | void | Promise +} + +export interface EnvState { + graph: ImportGraph + mockExportsByImporter: Map>> + resolveCache: Map + resolveCacheByFile: Map> + importLocCache: ImportLocCache + seenViolations: Set + serverFnLookupModules: Set + transformResultCache: Map + transformResultKeysByFile: Map> + transformResultProvider: TransformResultProvider + postTransformImports: Map> + pendingViolations: Map> + deferredBuildViolations: Array +} + +export interface PendingViolation { + info: ViolationInfo + /** True when the violation originates from a pre-transform resolveId call + * (e.g. server-fn lookup). These need edge-survival verification because + * the Start compiler may strip the import later. */ + fromPreTransformResolve?: boolean +} + +export interface DeferredBuildViolation { + info: ViolationInfo + mockModuleId: string + checkModuleId?: string +} + +export interface SharedState { + fileMarkerKind: Map +} + +export interface ImportProtectionPluginOptions { + getConfig: GetConfigFn + framework: CompileStartFrameworkOptions + environments: Array<{ name: string; type: 'client' | 'server' }> + providerEnvName: string +} + +export type ModuleGraphNode = { + id?: string | null + url?: string + importers: Set +} + +export type ViolationReporter = { + warn: (msg: string) => void + error: (msg: string) => never + resolve?: ( + source: string, + importer?: string, + options?: { + skipSelf?: boolean + custom?: Record + }, + ) => Promise<{ id: string; external?: boolean | 'absolute' } | null> + getModuleInfo?: (id: string) => { code?: string | null } | null +} + +export type HandleViolationResult = string | undefined diff --git a/packages/start-plugin-core/src/vite/import-protection-plugin/virtualModules.ts b/packages/start-plugin-core/src/vite/import-protection-plugin/virtualModules.ts new file mode 100644 index 0000000000..d27612c38b --- /dev/null +++ b/packages/start-plugin-core/src/vite/import-protection-plugin/virtualModules.ts @@ -0,0 +1,122 @@ +import { resolveViteId } from '../../utils' +import { + MARKER_PREFIX, + MOCK_BUILD_PREFIX, + MOCK_EDGE_PREFIX, + MOCK_MODULE_ID, + MOCK_RUNTIME_PREFIX, + RUNTIME_SUGGESTION_TEXT, + generateDevSelfDenialModule, + generateSelfContainedMockModule, + loadMarkerModule, + loadMockEdgeModule, + loadMockRuntimeModule, + loadSilentMockModule, + makeMockEdgeModuleId, + mockRuntimeModuleIdFromViolation, +} from '../../import-protection/virtualModules' +import { VITE_BROWSER_VIRTUAL_PREFIX } from '../../import-protection/constants' + +const RESOLVED_MOCK_MODULE_ID = resolveViteId(MOCK_MODULE_ID) +const RESOLVED_MOCK_BUILD_PREFIX = resolveViteId(MOCK_BUILD_PREFIX) +const RESOLVED_MOCK_EDGE_PREFIX = resolveViteId(MOCK_EDGE_PREFIX) +const RESOLVED_MOCK_RUNTIME_PREFIX = resolveViteId(MOCK_RUNTIME_PREFIX) +const RESOLVED_MARKER_PREFIX = resolveViteId(MARKER_PREFIX) +const RESOLVED_MARKER_SERVER_ONLY = resolveViteId(`${MARKER_PREFIX}server-only`) +const RESOLVED_MARKER_CLIENT_ONLY = resolveViteId(`${MARKER_PREFIX}client-only`) + +export function resolvedMarkerVirtualModuleId( + kind: 'server' | 'client', +): string { + return kind === 'server' + ? RESOLVED_MARKER_SERVER_ONLY + : RESOLVED_MARKER_CLIENT_ONLY +} + +export function getResolvedVirtualModuleMatchers(): ReadonlyArray { + return RESOLVED_VIRTUAL_MODULE_MATCHERS +} + +const RESOLVED_VIRTUAL_MODULE_MATCHERS = [ + RESOLVED_MOCK_MODULE_ID, + RESOLVED_MOCK_BUILD_PREFIX, + RESOLVED_MOCK_EDGE_PREFIX, + RESOLVED_MOCK_RUNTIME_PREFIX, + RESOLVED_MARKER_PREFIX, +] as const + +const RESOLVE_PREFIX_PAIRS = [ + [MOCK_EDGE_PREFIX, RESOLVED_MOCK_EDGE_PREFIX], + [MOCK_RUNTIME_PREFIX, RESOLVED_MOCK_RUNTIME_PREFIX], + [MOCK_BUILD_PREFIX, RESOLVED_MOCK_BUILD_PREFIX], + [MARKER_PREFIX, RESOLVED_MARKER_PREFIX], +] as const + +export function resolveInternalVirtualModuleId( + source: string, +): string | undefined { + if (source.startsWith(VITE_BROWSER_VIRTUAL_PREFIX)) { + return resolveInternalVirtualModuleId( + `\0${source.slice(VITE_BROWSER_VIRTUAL_PREFIX.length)}`, + ) + } + + if (source === MOCK_MODULE_ID || source === RESOLVED_MOCK_MODULE_ID) { + return RESOLVED_MOCK_MODULE_ID + } + + for (const [unresolvedPrefix, resolvedPrefix] of RESOLVE_PREFIX_PAIRS) { + if (source.startsWith(unresolvedPrefix)) { + return resolveViteId(source) + } + + if (source.startsWith(resolvedPrefix)) { + return source + } + } + + return undefined +} + +export function loadResolvedVirtualModule( + id: string, +): { code: string } | undefined { + if (id === RESOLVED_MOCK_MODULE_ID) { + return loadSilentMockModule() + } + + if (id.startsWith(RESOLVED_MOCK_BUILD_PREFIX)) { + return loadSilentMockModule() + } + + if (id.startsWith(RESOLVED_MOCK_EDGE_PREFIX)) { + return loadMockEdgeModule(id.slice(RESOLVED_MOCK_EDGE_PREFIX.length)) + } + + if (id.startsWith(RESOLVED_MOCK_RUNTIME_PREFIX)) { + return loadMockRuntimeModule(id.slice(RESOLVED_MOCK_RUNTIME_PREFIX.length)) + } + + if (id.startsWith(RESOLVED_MARKER_PREFIX)) { + return loadMarkerModule() + } + + return undefined +} + +export { + MARKER_PREFIX, + MOCK_BUILD_PREFIX, + MOCK_EDGE_PREFIX, + MOCK_MODULE_ID, + MOCK_RUNTIME_PREFIX, + RUNTIME_SUGGESTION_TEXT, + generateDevSelfDenialModule, + generateSelfContainedMockModule, + loadMarkerModule, + loadMockEdgeModule, + loadMockRuntimeModule, + loadSilentMockModule, + makeMockEdgeModuleId, + mockRuntimeModuleIdFromViolation, +} diff --git a/packages/start-plugin-core/src/vite/index.ts b/packages/start-plugin-core/src/vite/index.ts new file mode 100644 index 0000000000..d50bb40981 --- /dev/null +++ b/packages/start-plugin-core/src/vite/index.ts @@ -0,0 +1,13 @@ +export type { + TanStackStartVitePluginCoreOptions, + ViteRscForwardSsrResolverStrategy, +} from './types' +export type { TanStackStartViteInputConfig } from './schema' +export type { + StartCompilerImportTransform, + StartCompilerTransformCandidate, + StartCompilerTransformContext, +} from '../types' +export { START_ENVIRONMENT_NAMES, VITE_ENVIRONMENT_NAMES } from '../constants' +export { createVirtualModule } from './createVirtualModule' +export { tanStackStartVite } from './plugin' diff --git a/packages/start-plugin-core/src/load-env-plugin/plugin.ts b/packages/start-plugin-core/src/vite/load-env-plugin/plugin.ts similarity index 100% rename from packages/start-plugin-core/src/load-env-plugin/plugin.ts rename to packages/start-plugin-core/src/vite/load-env-plugin/plugin.ts diff --git a/packages/start-plugin-core/src/vite/module-id.ts b/packages/start-plugin-core/src/vite/module-id.ts new file mode 100644 index 0000000000..ef2ad98f10 --- /dev/null +++ b/packages/start-plugin-core/src/vite/module-id.ts @@ -0,0 +1,31 @@ +/** Checks for a query parameter without rewriting the opaque module ID. */ +export function hasIdQueryFlag(id: string, flag: string): boolean { + const queryIndex = id.indexOf('?') + if (queryIndex === -1) { + return false + } + + return new URLSearchParams(id.slice(queryIndex + 1)).has(flag) +} + +/** Appends an owned query flag without normalizing the existing query. */ +export function appendIdQueryFlag(id: string, flag: string): string { + if (!id.includes('?')) { + return `${id}?${flag}` + } + + const separator = id.endsWith('&') ? '' : '&' + return `${id}${separator}${flag}` +} + +/** Removes the owned query flag appended by {@link appendIdQueryFlag}. */ +export function removeIdQueryFlag(id: string, flag: string): string { + for (const separator of ['?', '&']) { + const suffix = `${separator}${flag}` + if (id.endsWith(suffix)) { + return id.slice(0, -suffix.length) + } + } + + return id +} diff --git a/packages/start-plugin-core/src/output-directory.ts b/packages/start-plugin-core/src/vite/output-directory.ts similarity index 87% rename from packages/start-plugin-core/src/output-directory.ts rename to packages/start-plugin-core/src/vite/output-directory.ts index aa1655433f..ea215d4841 100644 --- a/packages/start-plugin-core/src/output-directory.ts +++ b/packages/start-plugin-core/src/vite/output-directory.ts @@ -1,6 +1,6 @@ import { join } from 'pathe' -import { VITE_ENVIRONMENT_NAMES } from './constants' -import type { ViteEnvironmentNames } from './constants' +import { VITE_ENVIRONMENT_NAMES } from '../constants' +import type { ViteEnvironmentNames } from '../constants' import type * as vite from 'vite' export function getClientOutputDirectory( diff --git a/packages/start-plugin-core/src/vite/planning.ts b/packages/start-plugin-core/src/vite/planning.ts new file mode 100644 index 0000000000..fa11b98c47 --- /dev/null +++ b/packages/start-plugin-core/src/vite/planning.ts @@ -0,0 +1,242 @@ +import { normalizePath } from 'vite' +import { join } from 'pathe' +import { escapePath } from 'tinyglobby' +import { + DEV_CLIENT_ENTRY, + ENTRY_POINTS, + START_ENVIRONMENT_NAMES, +} from '../constants' +import { getBundlerOptions } from '../utils' +import type { CompileStartFrameworkOptions } from '../types' +import type { ResolvedStartEntryPlan } from '../planning' +import type * as vite from 'vite' + +export interface ViteResolvedEntryAliases { + client: string + server: string + start: string + router: string + alias: Record<(typeof ENTRY_POINTS)[keyof typeof ENTRY_POINTS], string> +} + +export function createViteResolvedEntryAliases(opts: { + entryPaths: ResolvedStartEntryPlan['entryPaths'] +}): ViteResolvedEntryAliases { + const client = normalizePath(opts.entryPaths.client) + const server = normalizePath(opts.entryPaths.server) + const start = normalizePath(opts.entryPaths.start) + const router = normalizePath(opts.entryPaths.router) + + return { + client, + server, + start, + router, + alias: { + [ENTRY_POINTS.client]: client, + [ENTRY_POINTS.server]: server, + [ENTRY_POINTS.start]: start, + [ENTRY_POINTS.router]: router, + }, + } +} + +export function createViteConfigPlan(opts: { + viteConfig: vite.UserConfig + command: 'serve' | 'build' + framework: CompileStartFrameworkOptions + entryAliases: ViteResolvedEntryAliases + clientOutputDirectory: string + serverOutputDirectory: string + serverFnProviderEnv: string + optimizeDepsExclude: Array + noExternal: Array +}) { + return { + environments: { + [START_ENVIRONMENT_NAMES.client]: { + consumer: 'client', + build: { + rolldownOptions: { + input: { + index: + opts.command === 'serve' + ? DEV_CLIENT_ENTRY + : ENTRY_POINTS.client, + }, + }, + outDir: opts.clientOutputDirectory, + }, + optimizeDeps: { + exclude: opts.optimizeDepsExclude, + entries: escapeEntries([ + opts.entryAliases.client, + opts.entryAliases.router, + ]), + }, + }, + [START_ENVIRONMENT_NAMES.server]: { + consumer: 'server', + build: { + ssr: true, + rolldownOptions: { + input: + getBundlerOptions( + opts.viteConfig.environments?.[START_ENVIRONMENT_NAMES.server] + ?.build, + )?.input ?? opts.entryAliases.server, + }, + outDir: opts.serverOutputDirectory, + commonjsOptions: { + include: [/node_modules/], + }, + copyPublicDir: + opts.viteConfig.environments?.[START_ENVIRONMENT_NAMES.server] + ?.build?.copyPublicDir ?? false, + }, + optimizeDeps: { + entries: escapeEntries([ + opts.entryAliases.server, + opts.entryAliases.start, + opts.entryAliases.router, + ]), + }, + }, + ...(opts.serverFnProviderEnv !== START_ENVIRONMENT_NAMES.server && { + [opts.serverFnProviderEnv]: { + build: { + outDir: join(opts.serverOutputDirectory, opts.serverFnProviderEnv), + }, + optimizeDeps: { + entries: escapeEntries([opts.entryAliases.router]), + }, + }, + }), + }, + resolve: { + noExternal: [ + '@tanstack/start**', + `@tanstack/${opts.framework}-start**`, + ...opts.noExternal, + ], + alias: { + ...opts.entryAliases.alias, + }, + }, + } satisfies Pick +} + +export function createViteDefineConfig(opts: { + command: 'serve' | 'build' + mode: string | undefined + serverFnBase: string + routerBasepath: string + spaEnabled: boolean | undefined + devSsrStylesEnabled: boolean + devSsrStylesBasepath: string + inlineCssEnabled: boolean + staticNodeEnv: boolean + disableCsrfMiddlewareWarning: boolean +}) { + return { + ...defineReplaceEnv('TSS_SERVER_FN_BASE', opts.serverFnBase), + ...defineReplaceEnv('TSS_ROUTER_BASEPATH', opts.routerBasepath), + ...(opts.command === 'serve' + ? defineReplaceEnv('TSS_SHELL', opts.spaEnabled ? 'true' : 'false') + : {}), + ...defineReplaceEnv( + 'TSS_DEV_SERVER', + opts.command === 'serve' ? 'true' : 'false', + ), + ...defineReplaceEnv( + 'TSS_DEV_SSR_STYLES_ENABLED', + opts.devSsrStylesEnabled ? 'true' : 'false', + ), + ...defineReplaceEnv( + 'TSS_DEV_SSR_STYLES_BASEPATH', + opts.devSsrStylesBasepath, + ), + ...defineReplaceEnv( + 'TSS_INLINE_CSS_ENABLED', + opts.inlineCssEnabled ? 'true' : 'false', + ), + ...defineReplaceEnv( + 'TSS_DISABLE_CSRF_MIDDLEWARE_WARNING', + opts.disableCsrfMiddlewareWarning ? 'true' : 'false', + ), + ...(opts.command === 'build' && opts.staticNodeEnv + ? { + 'process.env.NODE_ENV': JSON.stringify( + process.env.NODE_ENV || opts.mode || 'production', + ), + } + : {}), + } satisfies NonNullable +} + +export async function buildStartViteEnvironments(opts: { + builder: vite.ViteBuilder + providerEnvironmentName: string + ssrIsProvider: boolean +}) { + const client = getRequiredBuilderEnvironment( + opts.builder, + START_ENVIRONMENT_NAMES.client, + 'Client environment not found', + ) + const server = getRequiredBuilderEnvironment( + opts.builder, + START_ENVIRONMENT_NAMES.server, + 'SSR environment not found', + ) + + if (!client.isBuilt) { + await opts.builder.build(client) + } + + if (!server.isBuilt) { + await opts.builder.build(server) + } + + if (opts.ssrIsProvider) { + return + } + + const providerEnv = getRequiredBuilderEnvironment( + opts.builder, + opts.providerEnvironmentName, + `Provider environment "${opts.providerEnvironmentName}" not found`, + ) + + if (!providerEnv.isBuilt) { + await opts.builder.build(providerEnv) + } +} + +function escapeEntries(entries: Array) { + return entries.map((entry) => escapePath(entry)) +} + +function defineReplaceEnv( + key: TKey, + value: TValue, +): { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue } { + return { + [`process.env.${key}`]: JSON.stringify(value), + [`import.meta.env.${key}`]: JSON.stringify(value), + } as { [P in `process.env.${TKey}` | `import.meta.env.${TKey}`]: TValue } +} + +function getRequiredBuilderEnvironment( + builder: vite.ViteBuilder, + environmentName: string, + errorMessage: string, +) { + const environment = builder.environments[environmentName] + + if (!environment) { + throw new Error(errorMessage) + } + + return environment +} diff --git a/packages/start-plugin-core/src/vite/plugin.ts b/packages/start-plugin-core/src/vite/plugin.ts new file mode 100644 index 0000000000..5e5bca4a2e --- /dev/null +++ b/packages/start-plugin-core/src/vite/plugin.ts @@ -0,0 +1,282 @@ +import { realpathSync } from 'node:fs' +import { resolve } from 'node:path' +import { crawlFrameworkPkgs } from 'vitefu' +import { + applyResolvedBaseAndOutput, + applyResolvedRouterBasepath, + createStartConfigContext, +} from '../config-context' +import { START_ENVIRONMENT_NAMES } from '../constants' +import { + createServerFnBasePath, + normalizePublicBase, + shouldRewriteDevBasepath, +} from '../planning' +import { importProtectionPlugin } from './import-protection-plugin/plugin' +import { startCompilerPlugin } from './start-compiler-plugin/plugin' +import { loadEnvPlugin } from './load-env-plugin/plugin' +import { + buildStartViteEnvironments, + createViteConfigPlan, + createViteDefineConfig, + createViteResolvedEntryAliases, +} from './planning' +import { devServerPlugin } from './dev-server-plugin/plugin' +import { previewServerPlugin } from './preview-server-plugin/plugin' +import { + createDevBaseRewritePlugin, + createDevClientEntryPlugin, + createPostBuildPlugin, +} from './plugins' +import { parseStartConfig } from './schema' +import { startManifestPlugin } from './start-manifest-plugin/plugin' +import { tanStackStartRouter } from './start-router-plugin/plugin' +import { + getClientOutputDirectory, + getServerOutputDirectory, +} from './output-directory' +import { postServerBuild } from './post-server-build' +import { serializationAdaptersPlugin } from './serialization-adapters-plugin' +import type { + TanStackStartVitePluginCoreOptions, + ViteRscForwardSsrResolverStrategy, +} from './types' +import type { TanStackStartViteInputConfig } from './schema' +import type { PluginOption } from 'vite' + +export function tanStackStartVite( + corePluginOpts: TanStackStartVitePluginCoreOptions, + startPluginOpts: TanStackStartViteInputConfig | undefined, +): Array { + const normalizedStartPluginOpts = startPluginOpts ?? {} + + const configContext = createStartConfigContext({ + corePluginOpts, + startPluginOpts: normalizedStartPluginOpts, + parseConfig: parseStartConfig, + }) + const { getConfig, resolvedStartConfig } = configContext + const serverFnProviderEnv = corePluginOpts.providerEnvironmentName + const ssrIsProvider = corePluginOpts.ssrIsProvider + + // When the router basepath and vite base are misaligned during dev, + // we install a URL rewrite middleware instead of erroring. + let needsDevBaseRewrite = false + + const environments: Array<{ + name: string + type: 'client' | 'server' + getServerFnById?: string + }> = [ + { name: START_ENVIRONMENT_NAMES.client, type: 'client' }, + { + name: START_ENVIRONMENT_NAMES.server, + type: 'server', + getServerFnById: + corePluginOpts.ssrResolverStrategy.type === 'vite-rsc-forward' + ? createViteRscForwarder(corePluginOpts.ssrResolverStrategy) + : undefined, + }, + ] + if ( + serverFnProviderEnv !== START_ENVIRONMENT_NAMES.server && + !environments.find((e) => e.name === serverFnProviderEnv) + ) { + environments.push({ + name: serverFnProviderEnv, + type: 'server', + }) + } + return [ + { + name: 'tanstack-start-core:config', + enforce: 'pre', + async config(viteConfig, { command }) { + const publicBase = normalizePublicBase(viteConfig.base) + applyResolvedBaseAndOutput({ + resolvedStartConfig, + root: viteConfig.root || process.cwd(), + publicBase, + clientOutputDirectory: getClientOutputDirectory(viteConfig), + serverOutputDirectory: getServerOutputDirectory(viteConfig), + }) + const { startConfig } = getConfig() + const routerBasepath = applyResolvedRouterBasepath({ + resolvedStartConfig, + startConfig, + }) + + if ( + shouldRewriteDevBasepath({ + command, + middlewareMode: Boolean(viteConfig.server?.middlewareMode), + routerBasepath, + publicBase: resolvedStartConfig.basePaths.publicBase, + }) + ) { + // The router basepath and vite base are misaligned. + // Instead of erroring, we install a dev-server middleware that + // rewrites incoming request URLs to prepend the vite base prefix. + // This allows users to have e.g. base: '/_ui/' for asset URLs + // while keeping router basepath at '/' for page navigation. + needsDevBaseRewrite = true + } + + const TSS_SERVER_FN_BASE = createServerFnBasePath({ + routerBasepath, + serverFnBase: startConfig.serverFns.base, + }) + const resolvedEntryPlan = configContext.resolveEntries() + + const entryAliases = createViteResolvedEntryAliases({ + entryPaths: resolvedEntryPlan.entryPaths, + }) + + const startPackageName = + `@tanstack/${corePluginOpts.framework}-start` as const + + // crawl packages that have start in "peerDependencies" + // see https://github.com/svitejs/vitefu/blob/d8d82fa121e3b2215ba437107093c77bde51b63b/src/index.js#L95-L101 + + // this is currently uncached; could be implemented similarly as vite handles lock file changes + // see https://github.com/vitejs/vite/blob/557f797d29422027e8c451ca50dd84bf8c41b5f0/packages/vite/src/node/optimizer/index.ts#L1282 + + const crawlFrameworkPkgsResult = await crawlFrameworkPkgs({ + // (the configured root, which can be relative: resolved as Vite does, + // then physical, as Vite resolves the app's imports from there) + root: realpathSync( + viteConfig.root ? resolve(viteConfig.root) : process.cwd(), + ), + isBuild: command === 'build', + isFrameworkPkgByJson(pkgJson) { + const peerDependencies = pkgJson['peerDependencies'] + + if (peerDependencies) { + if ( + startPackageName in peerDependencies || + '@tanstack/start-client-core' in peerDependencies + ) { + return true + } + } + + return false + }, + }) + + const viteConfigPlan = createViteConfigPlan({ + viteConfig, + command, + framework: corePluginOpts.framework, + entryAliases, + clientOutputDirectory: resolvedStartConfig.outputDirectories.client, + serverOutputDirectory: resolvedStartConfig.outputDirectories.server, + serverFnProviderEnv, + optimizeDepsExclude: crawlFrameworkPkgsResult.optimizeDeps.exclude, + noExternal: crawlFrameworkPkgsResult.ssr.noExternal.sort(), + }) + + return { + // see https://vite.dev/config/shared-options.html#apptype + // this will prevent vite from injecting middlewares that we don't want + appType: viteConfig.appType ?? 'custom', + environments: viteConfigPlan.environments, + resolve: viteConfigPlan.resolve, + define: createViteDefineConfig({ + command, + mode: viteConfig.mode, + serverFnBase: TSS_SERVER_FN_BASE, + routerBasepath, + spaEnabled: startConfig.spa?.enabled, + devSsrStylesEnabled: startConfig.dev.ssrStyles.enabled, + devSsrStylesBasepath: + startConfig.dev.ssrStyles.basepath ?? + resolvedStartConfig.basePaths.publicBase, + inlineCssEnabled: + command === 'build' && startConfig.server.build.inlineCss.enabled, + staticNodeEnv: startConfig.server.build.staticNodeEnv, + disableCsrfMiddlewareWarning: + startConfig.serverFns.disableCsrfMiddlewareWarning, + }), + builder: { + sharedPlugins: true, + async buildApp(builder) { + await buildStartViteEnvironments({ + builder, + providerEnvironmentName: serverFnProviderEnv, + ssrIsProvider, + }) + }, + }, + } + }, + }, + createPostBuildPlugin({ + getConfig, + postServerBuild, + }), + // Server function plugin handles: + // 1. Identifying createServerFn().handler() calls + // 2. Extracting server functions to separate modules + // 3. Replacing call sites with RPC stubs + // 4. Generating the server function manifest + // Also handles createIsomorphicFn, createServerOnlyFn, createClientOnlyFn, createMiddleware + startCompilerPlugin({ + framework: corePluginOpts.framework, + environments, + generateFunctionId: + normalizedStartPluginOpts.serverFns?.generateFunctionId, + compilerTransforms: corePluginOpts.compilerTransforms, + serverFnProviderModuleDirectives: + corePluginOpts.serverFnProviderModuleDirectives, + providerEnvName: serverFnProviderEnv, + }), + importProtectionPlugin({ + getConfig, + framework: corePluginOpts.framework, + environments, + providerEnvName: serverFnProviderEnv, + }), + tanStackStartRouter(normalizedStartPluginOpts, getConfig, corePluginOpts), + loadEnvPlugin(), + createDevClientEntryPlugin({ + framework: corePluginOpts.framework, + getClientEntry: () => configContext.resolveEntries().entryPaths.client, + }), + startManifestPlugin({ + getConfig, + }), + // When the vite base and router basepath are misaligned (e.g. base: '/_ui/', basepath: '/'), + // install a middleware that rewrites incoming request URLs to prepend the vite base prefix. + // This allows Vite's internal base middleware to accept the requests, then strips the prefix + // before passing to the SSR handler. + // Registered BEFORE devServerPlugin so this middleware is added to the Connect stack first, + // ensuring all subsequent middlewares (CSS, SSR, etc.) see the rewritten URL. + createDevBaseRewritePlugin({ + shouldRewriteDevBase: () => needsDevBaseRewrite, + resolvedStartConfig, + }), + devServerPlugin({ + getConfig, + devSsrStylesEnabled: + normalizedStartPluginOpts.dev?.ssrStyles?.enabled ?? true, + installDevServerMiddleware: + normalizedStartPluginOpts.vite?.installDevServerMiddleware, + }), + previewServerPlugin(), + ...(corePluginOpts.serializationAdapters?.length + ? [ + serializationAdaptersPlugin({ + adapters: corePluginOpts.serializationAdapters, + }), + ] + : []), + ] +} + +function createViteRscForwarder(strategy: ViteRscForwardSsrResolverStrategy) { + return `export async function getServerFnById(id, access) { + const m = await import.meta.viteRsc.loadModule(${JSON.stringify(strategy.sourceEnvironmentName)}, ${JSON.stringify(strategy.sourceEntry)}) + return m[${JSON.stringify(strategy.exportName)}](id, access) +}` +} diff --git a/packages/start-plugin-core/src/vite/plugins.ts b/packages/start-plugin-core/src/vite/plugins.ts new file mode 100644 index 0000000000..59b6d1a580 --- /dev/null +++ b/packages/start-plugin-core/src/vite/plugins.ts @@ -0,0 +1,137 @@ +import { normalizePath } from 'vite' +import { DEV_CLIENT_ENTRY } from '../constants' +import { createVirtualModule } from './createVirtualModule' +import type { + CompileStartFrameworkOptions, + GetConfigFn, + ResolvedStartConfig, +} from '../types' +import type { PluginOption, ViteBuilder } from 'vite' + +export function createDevClientEntryPlugin(opts: { + framework: CompileStartFrameworkOptions + getClientEntry: () => string +}): PluginOption { + return createVirtualModule({ + name: 'tanstack-start-core:dev-client-entry', + moduleId: DEV_CLIENT_ENTRY, + enforce: 'pre', + async load() { + const clientEntryId = normalizePath(opts.getClientEntry()).replaceAll( + '\\', + '/', + ) + const clientEntry = JSON.stringify(clientEntryId) + + if ( + this.environment.mode === 'dev' && + this.environment.config.experimental.bundledDev + ) { + // Bundled dev imports the hydration entry from this virtual module. + // Its package's sideEffects: false can otherwise remove that import, + // leaving only SSR HTML. Preserve the entry's initialization calls. + const resolvedEntry = await this.resolve(clientEntryId) + const entry = await this.load({ + id: resolvedEntry?.id ?? clientEntryId, + }) + entry.moduleSideEffects = true + } + + if (shouldInjectReactRefreshPreamble(this.environment, opts.framework)) { + const reactRefresh = await this.resolve?.('/@react-refresh') + + if (!reactRefresh) { + throw new Error( + 'TanStack Start React dev mode requires the React Refresh runtime, but /@react-refresh could not be resolved. Add @vitejs/plugin-react or another compatible React Refresh Vite plugin to your Vite config.', + ) + } + + return ( + getReactRefreshPreambleCode(reactRefresh.id) + + `\nawait import(${clientEntry})` + ) + } + + return `import ${clientEntry}` + }, + }) +} + +function shouldInjectReactRefreshPreamble( + environment: ReactRefreshEnvironment | undefined, + framework: CompileStartFrameworkOptions, +) { + const config = environment?.config + + return ( + framework === 'react' && + config?.command === 'serve' && + config.consumer === 'client' && + config.server?.hmr !== false + ) +} + +interface ReactRefreshEnvironment { + config?: { + command?: string + consumer?: string + server?: { + hmr?: boolean + } + } +} + +function getReactRefreshPreambleCode(reactRefreshId: string) { + return `import { injectIntoGlobalHook } from ${JSON.stringify(reactRefreshId)}; +injectIntoGlobalHook(window); +window.$RefreshReg$ = () => {}; +window.$RefreshSig$ = () => (type) => type; +window.__vite_plugin_react_preamble_installed__ = true;` +} + +export function createPostBuildPlugin(opts: { + getConfig: GetConfigFn + postServerBuild: (opts: { + startConfig: ReturnType['startConfig'] + builder: ViteBuilder + }) => Promise +}): PluginOption { + return { + name: 'tanstack-start-core:post-build', + enforce: 'post', + buildApp: { + order: 'post', + async handler(builder) { + const { startConfig } = opts.getConfig() + await opts.postServerBuild({ builder, startConfig }) + }, + }, + } +} + +export function createDevBaseRewritePlugin(opts: { + shouldRewriteDevBase: () => boolean + resolvedStartConfig: ResolvedStartConfig +}): PluginOption { + return { + name: 'tanstack-start-core:dev-base-rewrite', + configureServer(server) { + if (!opts.shouldRewriteDevBase()) { + return + } + + const basePrefix = opts.resolvedStartConfig.basePaths.publicBase.replace( + /\/$/, + '', + ) + + server.middlewares.use((req, _res, next) => { + if (req.url && !req.url.startsWith(basePrefix)) { + req.url = basePrefix + req.url + } + + next() + }) + }, + } +} diff --git a/packages/start-plugin-core/src/vite/post-server-build.ts b/packages/start-plugin-core/src/vite/post-server-build.ts new file mode 100644 index 0000000000..2e74b7635d --- /dev/null +++ b/packages/start-plugin-core/src/vite/post-server-build.ts @@ -0,0 +1,28 @@ +import { postBuild } from '../post-build' +import { getClientOutputDirectory } from './output-directory' +import { prerenderWithVite } from './prerender' +import type { TanStackStartOutputConfig } from '../schema' +import type { ViteBuilder } from 'vite' + +export async function postServerBuild({ + builder, + startConfig, +}: { + builder: ViteBuilder + startConfig: TanStackStartOutputConfig +}) { + await postBuild({ + startConfig, + adapter: { + getClientOutputDirectory() { + return getClientOutputDirectory(builder.config) + }, + prerender(startConfig) { + return prerenderWithVite({ + startConfig, + builder, + }) + }, + }, + }) +} diff --git a/packages/start-plugin-core/src/vite/prerender.ts b/packages/start-plugin-core/src/vite/prerender.ts new file mode 100644 index 0000000000..5d1838e43a --- /dev/null +++ b/packages/start-plugin-core/src/vite/prerender.ts @@ -0,0 +1,93 @@ +import { VITE_ENVIRONMENT_NAMES } from '../constants' +import { prerender } from '../prerender' +import type { PrerenderHandler } from '../prerender' +import type { TanStackStartOutputConfig } from '../schema' +import type { PreviewServer, ResolvedConfig, ViteBuilder } from 'vite' + +export async function prerenderWithVite({ + startConfig, + builder, +}: { + startConfig: TanStackStartOutputConfig + builder: ViteBuilder +}) { + const serverEnv = builder.environments[VITE_ENVIRONMENT_NAMES.server] + + if (!serverEnv) { + throw new Error( + `Vite's "${VITE_ENVIRONMENT_NAMES.server}" environment not found`, + ) + } + + const clientEnv = builder.environments[VITE_ENVIRONMENT_NAMES.client] + if (!clientEnv) { + throw new Error( + `Vite's "${VITE_ENVIRONMENT_NAMES.client}" environment not found`, + ) + } + + const outputDir = clientEnv.config.build.outDir + + process.env.TSS_PRERENDERING = 'true' + process.env.TSS_CLIENT_OUTPUT_DIR = outputDir + + const previewServer = await startPreviewServer(serverEnv.config) + const baseUrl = getResolvedUrl(previewServer) + + const handler: PrerenderHandler = { + getClientOutputDirectory() { + return outputDir + }, + getOrigin() { + return baseUrl.origin + }, + request(path, options) { + const url = new URL(path, baseUrl) + if (url.origin !== baseUrl.origin) { + throw new Error(`Prerender request URL must be relative: ${path}`) + } + return fetch(new Request(url, options)) + }, + close() { + return previewServer.close() + }, + } + + return prerender({ + startConfig, + handler, + }) +} + +async function startPreviewServer( + viteConfig: ResolvedConfig, +): Promise { + const vite = await import('vite') + + try { + return await vite.preview({ + configFile: viteConfig.configFile, + preview: { + port: 0, + open: false, + }, + }) + } catch (error) { + throw new Error( + 'Failed to start the Vite preview server for prerendering', + { + cause: error, + }, + ) + } +} + +function getResolvedUrl(previewServer: PreviewServer): URL { + const baseUrl = previewServer.resolvedUrls?.local[0] + + if (!baseUrl) { + throw new Error('No resolved URL is available from the Vite preview server') + } + + return new URL(baseUrl) +} diff --git a/packages/start-plugin-core/src/vite/preview-server-plugin/plugin.ts b/packages/start-plugin-core/src/vite/preview-server-plugin/plugin.ts new file mode 100644 index 0000000000..1541d9edfb --- /dev/null +++ b/packages/start-plugin-core/src/vite/preview-server-plugin/plugin.ts @@ -0,0 +1,73 @@ +import { pathToFileURL } from 'node:url' +import { basename, extname, join } from 'pathe' +import { NodeRequest, sendNodeResponse } from 'srvx/node' +import { joinURL } from 'ufo' +import { VITE_ENVIRONMENT_NAMES } from '../../constants' +import { getServerOutputDirectory } from '../output-directory' +import { getBundlerOptions } from '../../utils' +import type { Plugin } from 'vite' + +export function previewServerPlugin(): Plugin { + return { + name: 'tanstack-start-core:preview-server', + configurePreviewServer: { + // Run last so platform plugins (Cloudflare, Vercel, etc.) can register their handlers first + order: 'post', + handler(server) { + // Return a function so Vite's internal middlewares (static files, etc.) handle requests first. + // Our SSR handler only processes requests that nothing else handled. + return () => { + // Cache the server build to avoid re-importing on every request + let serverBuild: any = null + + server.middlewares.use(async (req, res, next) => { + try { + // Lazy load server build on first request + if (!serverBuild) { + // Derive output filename from input + const serverEnv = + server.config.environments[VITE_ENVIRONMENT_NAMES.server] + const serverInput = + getBundlerOptions(serverEnv?.build)?.input ?? 'server' + + if (typeof serverInput !== 'string') { + throw new Error('Invalid server input. Expected a string.') + } + + // Get basename without extension and add .js + const outputFilename = `${basename(serverInput, extname(serverInput))}.js` + const serverOutputDir = getServerOutputDirectory(server.config) + const serverEntryPath = join(serverOutputDir, outputFilename) + const imported = await import( + pathToFileURL(serverEntryPath).toString() + ) + + serverBuild = imported.default + } + + // Prepend base path to request URL to match routing setup + req.url = joinURL(server.config.base, req.url ?? '/') + + const webReq = new NodeRequest({ req, res }) + const webRes: Response = await serverBuild.fetch(webReq) + + if (webRes.headers.get('content-type')?.startsWith('text/html')) { + res.setHeader('content-encoding', 'identity') + } + + // Temporary workaround + // Vite preview's compression middleware doesn't support flattened array headers that srvx sets + // Call writeHead() before srvx to avoid corruption + res.setHeaders(webRes.headers) + res.writeHead(webRes.status, webRes.statusText) + + return sendNodeResponse(res, webRes) + } catch (error) { + next(error) + } + }) + } + }, + }, + } +} diff --git a/packages/start-plugin-core/src/vite/schema.ts b/packages/start-plugin-core/src/vite/schema.ts new file mode 100644 index 0000000000..c142245fc0 --- /dev/null +++ b/packages/start-plugin-core/src/vite/schema.ts @@ -0,0 +1,37 @@ +import { z } from 'zod' +import { + parseStartConfig as parseCoreStartConfig, + tanstackStartOptionsObjectSchema, +} from '../schema' +import type { CompileStartFrameworkOptions } from '../types' +import type { InlineCssInputOptions } from '../schema' + +export const tanstackStartViteOptionsSchema = tanstackStartOptionsObjectSchema + .extend({ + vite: z + .object({ installDevServerMiddleware: z.boolean().optional() }) + .optional(), + }) + .optional() + .prefault({}) + +export function parseStartConfig( + opts: z.input, + corePluginOpts: { framework: CompileStartFrameworkOptions }, + root: string, +) { + tanstackStartViteOptionsSchema.parse(opts) + const { vite: _vite, ...coreOptions } = opts ?? {} + + return parseCoreStartConfig(coreOptions, corePluginOpts, root) +} + +export type TanStackStartViteInputConfig = z.input< + typeof tanstackStartViteOptionsSchema +> & { + server?: { + build?: { + inlineCss?: InlineCssInputOptions + } + } +} diff --git a/packages/start-plugin-core/src/vite/serialization-adapters-plugin.ts b/packages/start-plugin-core/src/vite/serialization-adapters-plugin.ts new file mode 100644 index 0000000000..26eb92c5ca --- /dev/null +++ b/packages/start-plugin-core/src/vite/serialization-adapters-plugin.ts @@ -0,0 +1,86 @@ +import { VIRTUAL_MODULES } from '@tanstack/start-server-core/virtual-modules' +import { generateSerializationAdaptersModule } from '../serialization-adapters-module' +import { START_ENVIRONMENT_NAMES } from '../constants' +import { createIdFilter } from '../utils' +import type { SerializationAdapterConfig } from '../types' +import type { PluginOption } from 'vite' + +const CLIENT_MODULE_ID = 'virtual:tanstack-start-plugin-adapters/client' +const SERVER_MODULE_ID = 'virtual:tanstack-start-plugin-adapters/server' +const BUILD_CLIENT_MODULE_ID = `\0${CLIENT_MODULE_ID}` +const BUILD_SERVER_MODULE_ID = `\0${SERVER_MODULE_ID}` +const MODULE_IDS = [ + CLIENT_MODULE_ID, + SERVER_MODULE_ID, + BUILD_CLIENT_MODULE_ID, + BUILD_SERVER_MODULE_ID, +] + +const moduleIdFilter = createIdFilter(MODULE_IDS) +const resolveIdFilter = createIdFilter([ + VIRTUAL_MODULES.pluginAdapters, + ...MODULE_IDS, +]) + +export function serializationAdaptersPlugin(opts: { + adapters: Array | undefined +}): PluginOption { + return { + name: 'tanstack-start:plugin-adapters', + enforce: 'pre', + resolveId: { + filter: { id: resolveIdFilter }, + handler(id) { + if (getRuntime(id)) { + return id + } + + if (id !== VIRTUAL_MODULES.pluginAdapters) { + return undefined + } + + const runtime = + this.environment.name === START_ENVIRONMENT_NAMES.client + ? 'client' + : 'server' + + return getModuleId(runtime, this.environment.config.command) + }, + }, + load: { + filter: { id: moduleIdFilter }, + handler(id) { + const runtime = getRuntime(id) + if (!runtime) { + return undefined + } + + return generateSerializationAdaptersModule({ + adapters: opts.adapters, + runtime, + }) + }, + }, + } +} + +function getModuleId(runtime: 'client' | 'server', command: string) { + if (runtime === 'client') { + return command === 'serve' ? CLIENT_MODULE_ID : BUILD_CLIENT_MODULE_ID + } + + return command === 'serve' ? SERVER_MODULE_ID : BUILD_SERVER_MODULE_ID +} + +function getRuntime(id: string): 'client' | 'server' | undefined { + switch (id) { + case CLIENT_MODULE_ID: + case BUILD_CLIENT_MODULE_ID: + return 'client' + case SERVER_MODULE_ID: + case BUILD_SERVER_MODULE_ID: + return 'server' + default: + return undefined + } +} diff --git a/packages/start-plugin-core/src/vite/start-compiler-plugin/hot-update.ts b/packages/start-plugin-core/src/vite/start-compiler-plugin/hot-update.ts new file mode 100644 index 0000000000..5ff7e04773 --- /dev/null +++ b/packages/start-plugin-core/src/vite/start-compiler-plugin/hot-update.ts @@ -0,0 +1,24 @@ +import type { EnvironmentModuleNode } from 'vite' + +export function mergeHotUpdateModules( + currentModules: Array, + additionalModules: Array, +): Array | undefined { + if (additionalModules.length === 0) { + return undefined + } + + const mergedModules = currentModules.slice() + const seenModules = new Set(currentModules) + + for (const mod of additionalModules) { + if (seenModules.has(mod)) { + continue + } + + seenModules.add(mod) + mergedModules.push(mod) + } + + return mergedModules +} diff --git a/packages/start-plugin-core/src/vite/start-compiler-plugin/module-specifier.ts b/packages/start-plugin-core/src/vite/start-compiler-plugin/module-specifier.ts new file mode 100644 index 0000000000..1324894f68 --- /dev/null +++ b/packages/start-plugin-core/src/vite/start-compiler-plugin/module-specifier.ts @@ -0,0 +1,41 @@ +import type { DevServerFnModuleSpecifierEncoder } from '../../start-compiler/types' + +export function createViteDevServerFnModuleSpecifierEncoder( + root: string, +): DevServerFnModuleSpecifierEncoder { + const normalizedRoot = root.replace(/\\/g, '/') + const rootWithTrailingSlash = normalizedRoot.endsWith('/') + ? normalizedRoot + : `${normalizedRoot}/` + + return ({ extractedFilename }) => { + const normalizedFile = extractedFilename.replace(/\\/g, '/') + + if (normalizedFile.startsWith(rootWithTrailingSlash)) { + return `/${normalizedFile.slice(rootWithTrailingSlash.length)}` + } + + return normalizedFile.startsWith('/') + ? `/@fs${normalizedFile}` + : `/@fs/${normalizedFile}` + } +} + +export function decodeViteDevServerModuleSpecifier( + moduleSpecifier: string, +): string { + let sourceFile = moduleSpecifier + + if (sourceFile.startsWith('/@id/')) { + sourceFile = sourceFile.slice('/@id/'.length) + } else if (sourceFile.startsWith('/@fs/')) { + sourceFile = sourceFile.slice('/@fs'.length) + sourceFile = sourceFile.replace(/^\/([A-Za-z]:\/)/, '$1') + } else if (sourceFile.startsWith('/')) { + sourceFile = sourceFile.slice(1) + } + + const queryIndex = sourceFile.indexOf('?') + + return queryIndex === -1 ? sourceFile : sourceFile.slice(0, queryIndex) +} diff --git a/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts b/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts new file mode 100644 index 0000000000..3a93e286d1 --- /dev/null +++ b/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts @@ -0,0 +1,690 @@ +import { VIRTUAL_MODULES } from '@tanstack/start-server-core/virtual-modules' +import { resolve as resolvePath } from 'pathe' +import { + SERVER_FN_LOOKUP, + TRANSFORM_ID_REGEX, + VITE_ENVIRONMENT_NAMES, +} from '../../constants' +import { detectKindsInCode } from '../../start-compiler/compiler' +import { getTransformCodeFilterForEnv } from '../../start-compiler/config' +import { + createCompilerVirtualModuleIdPattern, + createStartCompiler, + loadCompilerVirtualModule, + mergeServerFnsById, +} from '../../start-compiler/host' +import { generateServerFnResolverModule } from '../../start-compiler/server-fn-resolver-module' +import { cleanId } from '../../start-compiler/utils' +import { createVirtualModule } from '../createVirtualModule' +import { + MissingHydrateSourceError, + createHydrateCompilerPlugin, +} from '../../hydrate-when-transform' +import { resolveViteId } from '../../utils' +import { appendIdQueryFlag, removeIdQueryFlag } from '../module-id' +import { + createViteDevServerFnModuleSpecifierEncoder, + decodeViteDevServerModuleSpecifier, +} from './module-specifier' +import { mergeHotUpdateModules } from './hot-update' +import type { + CompileStartFrameworkOptions, + StartCompilerImportTransform, + StartCompilerPlugin, +} from '../../types' +import type { + GenerateFunctionIdFnOptional, + ServerFn, +} from '../../start-compiler/types' +import type { + DevEnvironment, + Environment, + EnvironmentModuleNode, + PluginOption, +} from 'vite' + +// Re-export from shared constants for backwards compatibility +export { SERVER_FN_LOOKUP } + +const validateServerFnIdVirtualModule = `virtual:tanstack-start-validate-server-fn-id` +const TSS_SERVERFN_SPLIT_PARAM = 'tss-serverfn-split' + +type ModuleInvalidationEnvironment = { + moduleGraph: { + getModulesByFile: (file: string) => Set | undefined + invalidateModule: ( + mod: EnvironmentModuleNode, + seen?: Set, + ) => void + } +} + +type ViteModuleLoadOptions = { + devId?: string + load: (options: { id: string }) => Promise<{ code?: string | null } | null> + error: (message: string) => never +} + +async function loadViteModuleFromEnvironment( + environment: Environment, + id: string, + opts: ViteModuleLoadOptions, +): Promise { + if ( + environment.mode === 'build' || + (environment.mode === 'dev' && + environment.config.experimental.bundledDev && + environment.name === VITE_ENVIRONMENT_NAMES.client) + ) { + // Bundled dev must load through its current driver; transformRequest starts + // a separate client container and can reset the compiler mid-transform. + const loaded = await opts.load({ + id: environment.mode === 'dev' ? (opts.devId ?? id) : id, + }) + return loaded?.code ?? '' + } + + if (environment.mode === 'dev') { + await environment.transformRequest(opts.devId ?? id) + return undefined + } + + opts.error( + `could not load module ${id}: unknown environment mode ${environment.mode}`, + ) +} + +function invalidateMatchingFileModules( + environment: ModuleInvalidationEnvironment, + ids: Iterable, + shouldInvalidate: (mod: EnvironmentModuleNode) => boolean, +) { + const seen = new Set() + const invalidatedModules: Array = [] + + for (const id of ids) { + const fileModules = environment.moduleGraph.getModulesByFile(cleanId(id)) + + if (!fileModules) { + continue + } + + for (const fileModule of fileModules) { + if (!shouldInvalidate(fileModule)) { + continue + } + + environment.moduleGraph.invalidateModule(fileModule, seen) + invalidatedModules.push(fileModule) + } + } + + return invalidatedModules +} + +function invalidateServerFnProviderModules( + environment: { + moduleGraph: { + getModulesByFile: (file: string) => Set | undefined + invalidateModule: ( + mod: EnvironmentModuleNode, + seen?: Set, + ) => void + } + }, + ids: Iterable, +) { + return invalidateMatchingFileModules( + environment, + ids, + (fileModule) => fileModule.id?.includes(TSS_SERVERFN_SPLIT_PARAM) ?? false, + ) +} + +function invalidateServerFnLookupModules( + environment: ModuleInvalidationEnvironment, + ids: Iterable, +) { + invalidateMatchingFileModules( + environment, + ids, + (fileModule) => fileModule.id?.includes(SERVER_FN_LOOKUP) ?? false, + ) +} + +function invalidateCompilerVirtualModules( + environment: ModuleInvalidationEnvironment, + ids: Iterable, + pattern: RegExp | undefined, +) { + if (!pattern) { + return [] + } + + return invalidateMatchingFileModules(environment, ids, (fileModule) => { + if (!fileModule.id) { + return false + } + + pattern.lastIndex = 0 + return pattern.test(fileModule.id) + }) +} + +function getServerFnProviderIds(ids: Iterable) { + const providerIds = new Set() + + for (const id of ids) { + const cleanedId = cleanId(id) + providerIds.add(`${cleanedId}?${TSS_SERVERFN_SPLIT_PARAM}`) + } + + return providerIds +} + +function invalidateModuleNodes( + environment: { + moduleGraph: { + invalidateModule: ( + mod: EnvironmentModuleNode, + seen?: Set, + ) => void + } + }, + modules: Iterable, +) { + const seen = new Set() + + for (const mod of modules) { + environment.moduleGraph.invalidateModule(mod, seen) + } +} + +function getDevServerFnValidatorModule(): string { + return ` +export async function getServerFnById(id, _access) { + const validateIdImport = ${JSON.stringify(validateServerFnIdVirtualModule)} + '?id=' + id + await import(/* @vite-ignore */ '/@id/__x00__' + validateIdImport) + const decoded = Buffer.from(id, 'base64url').toString('utf8') + const devServerFn = JSON.parse(decoded) + const mod = await import(/* @vite-ignore */ devServerFn.file) + return mod[devServerFn.export] +} +` +} + +function parseIdQuery(id: string): { + filename: string + query: { + [k: string]: string + } +} { + if (!id.includes('?')) return { filename: id, query: {} } + const [filename, rawQuery] = id.split(`?`, 2) as [string, string] + const query = Object.fromEntries(new URLSearchParams(rawQuery)) + return { filename, query } +} + +export interface StartCompilerPluginOptions { + framework: CompileStartFrameworkOptions + environments: Array<{ + name: string + type: 'client' | 'server' + getServerFnById?: string + }> + /** + * Custom function ID generator (optional). + */ + generateFunctionId?: GenerateFunctionIdFnOptional + compilerTransforms?: Array | undefined + compilerPlugins?: Array | undefined + serverFnProviderModuleDirectives?: ReadonlyArray | undefined + /** + * The Vite environment name for the server function provider. + */ + providerEnvName: string +} + +export function startCompilerPlugin( + opts: StartCompilerPluginOptions, +): PluginOption { + const compilers = new Map>() + const compilerPlugins = [ + createHydrateCompilerPlugin(), + ...(opts.compilerPlugins ?? []), + ] + const compilerVirtualModuleIdPattern = + createCompilerVirtualModuleIdPattern(compilerPlugins) + const environmentByName = new Map( + opts.environments.map((environment) => [environment.name, environment]), + ) + + // Shared registry of server functions across all environments + const serverFnsById: Record = {} + + const onServerFnsById = (d: Record) => { + mergeServerFnsById(serverFnsById, d) + } + + let root = process.cwd() + let bundledDev = false + // Determine which environments need the resolver (getServerFnById) + // SSR environment always needs the resolver for server-side calls + // Provider environment needs it for the actual implementation + const ssrEnvName = VITE_ENVIRONMENT_NAMES.server + + // SSR is the provider when the provider environment is the default server environment + const ssrIsProvider = opts.providerEnvName === ssrEnvName + + // Environments that need the resolver: SSR (for server calls) and provider (for implementation) + const appliedResolverEnvironments = new Set( + ssrIsProvider ? [opts.providerEnvName] : [ssrEnvName, opts.providerEnvName], + ) + + function perEnvServerFnPlugin(environment: { + name: string + type: 'client' | 'server' + }): PluginOption { + const compilerTransforms = + environment.name === opts.providerEnvName + ? opts.compilerTransforms + : undefined + const serverFnProviderModuleDirectives = + environment.name === opts.providerEnvName + ? opts.serverFnProviderModuleDirectives + : undefined + // Derive transform code filter from KindDetectionPatterns (single source of truth) + const transformCodeFilter = getTransformCodeFilterForEnv(environment.type, { + compilerTransforms, + compilerPlugins, + }) + function invalidateCompilerState( + viteEnvironment: DevEnvironment, + modules: Array, + ) { + const compiler = compilers.get(viteEnvironment.name) + const idsToInvalidate = new Set() + const transitiveCompilerImportersToInvalidate = new Set() + const importerModulesToInvalidate = new Set() + const changedIds: Array = [] + + modules.forEach((m) => { + if (m.id) { + idsToInvalidate.add(m.id) + changedIds.push(m.id) + } + }) + + const deletedIds = compiler?.invalidateModules(changedIds) ?? new Set() + + modules.forEach((m) => { + if (m.id) { + if (deletedIds.has(cleanId(m.id))) { + transitiveCompilerImportersToInvalidate.add(cleanId(m.id)) + + m.importers.forEach((importer) => { + if (importer.id) { + idsToInvalidate.add(importer.id) + importerModulesToInvalidate.add(importer) + transitiveCompilerImportersToInvalidate.add( + cleanId(importer.id), + ) + } + }) + } + } + }) + + const finishHotUpdate = async () => { + if ( + environment.type === 'server' && + compiler && + transitiveCompilerImportersToInvalidate.size > 0 + ) { + const seenImporters = new Set(transitiveCompilerImportersToInvalidate) + const nestedImporters = + await compiler.getTransitiveImporters(seenImporters) + + for (const nestedImporterId of nestedImporters) { + seenImporters.add(nestedImporterId) + } + + for (const importerId of seenImporters) { + idsToInvalidate.add(importerId) + } + compiler.invalidateModules(seenImporters) + } + + invalidateModuleNodes(viteEnvironment, importerModulesToInvalidate) + invalidateServerFnLookupModules(viteEnvironment, idsToInvalidate) + const compilerVirtualModules = invalidateCompilerVirtualModules( + viteEnvironment, + idsToInvalidate, + compilerVirtualModuleIdPattern, + ) + + if (environment.type !== 'server') { + return mergeHotUpdateModules(modules, compilerVirtualModules) + } + + invalidateModuleNodes(viteEnvironment, modules) + + const providerIdsToInvalidate = getServerFnProviderIds(idsToInvalidate) + compiler?.invalidateModules(providerIdsToInvalidate) + + const providerModules = invalidateServerFnProviderModules( + viteEnvironment, + [...idsToInvalidate, ...providerIdsToInvalidate], + ) + + return mergeHotUpdateModules(modules, [ + ...compilerVirtualModules, + ...providerModules, + ]) + } + + return finishHotUpdate() + } + + return { + name: `tanstack-start-core::server-fn:${environment.name}`, + enforce: 'pre', + perEnvironmentWatchChangeDuringDev: true, + applyToEnvironment(env) { + return env.name === environment.name + }, + configResolved(config) { + root = config.root + bundledDev = !!config.experimental.bundledDev + }, + buildStart() { + if ( + this.environment.mode === 'build' || + (bundledDev && + this.environment.name === VITE_ENVIRONMENT_NAMES.client) + ) { + // Vite app builds can run multiple Rolldown build phases with fresh + // plugin drivers. The compiler host closes over this hook context for + // load/resolve, so do not reuse it after a previous driver was closed. + compilers.delete(this.environment.name) + } + }, + async watchChange(id) { + if (bundledDev && this.environment.mode === 'dev') { + if (environment.type === 'server') { + await invalidateCompilerState( + this.environment, + Array.from( + this.environment.moduleGraph.getModulesByFile(id) ?? [], + ), + ) + } else { + compilers.get(this.environment.name)?.invalidateModule(id) + } + } + }, + transform: { + filter: { + id: { + exclude: new RegExp(`${SERVER_FN_LOOKUP}$`), + include: TRANSFORM_ID_REGEX, + }, + code: { + include: transformCodeFilter, + }, + }, + async handler(code, id) { + let compiler = compilers.get(this.environment.name) + + if (!compiler) { + // Default to 'dev' mode for unknown environments (conservative: no caching) + const mode = this.environment.mode === 'build' ? 'build' : 'dev' + + compiler = createStartCompiler({ + env: environment.type, + envName: environment.name, + root, + mode, + framework: opts.framework, + providerEnvName: opts.providerEnvName, + generateFunctionId: opts.generateFunctionId, + compilerTransforms, + compilerPlugins, + serverFnProviderModuleDirectives, + onServerFnsById, + getKnownServerFns: () => serverFnsById, + encodeModuleSpecifierInDev: + mode === 'dev' + ? createViteDevServerFnModuleSpecifierEncoder(root) + : undefined, + loadModule: async (id: string) => { + const code = await loadViteModuleFromEnvironment( + this.environment, + id, + { + load: (options) => this.load(options), + error: (message) => this.error(message), + devId: appendIdQueryFlag(id, SERVER_FN_LOOKUP), + }, + ) + if (code !== undefined) { + compiler!.ingestModule({ code, id }) + } + }, + + resolveId: async (source: string, importer?: string) => { + const r = await this.resolve(source, importer) + + if (r) { + if (!r.external) { + // Keep the resolved ID intact because it is passed back to + // Vite's load hook. Virtual-module prefixes and queries are + // part of that load identity, not compiler-only metadata. + return r.id + } + } + + return null + }, + }) + + compilers.set(this.environment.name, compiler) + } + + // Detect which kinds are present in this file before parsing + const detectedKinds = detectKindsInCode(code, environment.type, { + compilerTransforms, + }) + + const result = await compiler.compile({ + id, + code, + detectedKinds, + warn: (message) => this.warn(message), + }) + + return result + }, + }, + + hotUpdate(ctx) { + return invalidateCompilerState(this.environment, ctx.modules) + }, + } + } + + return [ + ...opts.environments.map(perEnvServerFnPlugin), + { + name: 'tanstack-start-core:capture-server-fn-module-lookup', + // we only need this plugin in dev mode + apply: 'serve', + applyToEnvironment(env) { + return !!opts.environments.find((e) => e.name === env.name) + }, + transform: { + filter: { + id: new RegExp(`${SERVER_FN_LOOKUP}$`), + }, + handler(code, id) { + if ( + bundledDev && + this.environment.name === VITE_ENVIRONMENT_NAMES.client + ) { + // The bundled load returns its code directly to the compiler host. + return + } + const compiler = compilers.get(this.environment.name) + compiler?.ingestModule({ + code, + id: removeIdQueryFlag(id, SERVER_FN_LOOKUP), + }) + }, + }, + }, + { + name: 'tanstack-start-core:compiler-virtual-module', + enforce: 'pre', + load: { + filter: { + id: compilerVirtualModuleIdPattern ?? /$^/, + }, + async handler(id) { + const environment = environmentByName.get(this.environment.name) + if (!environment || !compilerVirtualModuleIdPattern) { + return null + } + + const loadVirtualModule = () => + loadCompilerVirtualModule(compilerPlugins, { + id, + root, + env: environment.type, + envName: this.environment.name, + }) + + try { + return loadVirtualModule() + } catch (error) { + if (!(error instanceof MissingHydrateSourceError)) { + throw error + } + } + + const sourceId = cleanId(id) + await loadViteModuleFromEnvironment(this.environment, sourceId, { + load: (options) => this.load(options), + error: (message) => this.error(message), + }) + + return loadVirtualModule() + }, + }, + }, + // Validate server function ID in dev mode + { + name: 'tanstack-start-core:validate-server-fn-id', + apply: 'serve', + load: { + filter: { + id: new RegExp(resolveViteId(validateServerFnIdVirtualModule)), + }, + async handler(id) { + const parsed = parseIdQuery(id) + const fnId = parsed.query.id + if (fnId && serverFnsById[fnId]) { + return `export {}` + } + + // ID not yet registered — the source file may not have been + // transformed in this dev session yet (e.g. cold restart with + // cached client). Try to decode the ID, discover the source + // file, trigger its compilation, and re-check. + if (fnId) { + try { + const decoded = JSON.parse( + Buffer.from(fnId, 'base64url').toString('utf8'), + ) + if ( + typeof decoded.file === 'string' && + typeof decoded.export === 'string' + ) { + // Use the Vite when to decode the module specifier + // back to the original source file path. + const sourceFile = decodeViteDevServerModuleSpecifier( + decoded.file, + ) + + if (sourceFile) { + // Resolve to absolute path + const absPath = resolvePath(root, sourceFile) + + // Trigger transform of the source file in this environment, + // which will compile createServerFn calls and populate + // serverFnsById as a side effect. + if (this.environment.mode !== 'dev') { + this.error( + `could not validate server function ID ${fnId}: unknown environment mode ${this.environment.mode}`, + ) + } + + await this.environment.transformRequest( + `${absPath}?${SERVER_FN_LOOKUP}`, + ) + + // Re-check after lazy compilation + if (serverFnsById[fnId]) { + return `export {}` + } + } + } + } catch { + // Decoding or fetching failed — fall through to error + } + } + + this.error(`Invalid server function ID: ${fnId}`) + }, + }, + }, + // Manifest plugin for server environments + createVirtualModule({ + name: 'tanstack-start-core:server-fn-resolver', + moduleId: VIRTUAL_MODULES.serverFnResolver, + enforce: 'pre', + applyToEnvironment: (env) => { + return appliedResolverEnvironments.has(env.name) + }, + load() { + if (this.environment.name !== opts.providerEnvName) { + const mod = opts.environments.find( + (e) => e.name === this.environment.name, + )?.getServerFnById + if (mod) { + return mod + } + + this.error( + `No getServerFnById implementation found for caller environment: ${this.environment.name}`, + ) + } + + if (this.environment.mode !== 'build') { + return getDevServerFnValidatorModule() + } + + // When SSR is the provider, server-only-referenced functions aren't in the manifest, + // so no isClientReferenced check is needed. + // When SSR is NOT the provider (custom provider env), server-only-referenced + // functions ARE in the manifest and need the isClientReferenced check to + // block direct client HTTP requests to server-only-referenced functions. + return generateServerFnResolverModule({ + serverFnsById, + includeClientReferencedCheck: !ssrIsProvider, + // Only production builds reach this branch. + memoizeModules: true, + }) + }, + }), + ] +} diff --git a/packages/start-plugin-core/src/vite/start-manifest-plugin/normalized-client-build.ts b/packages/start-plugin-core/src/vite/start-manifest-plugin/normalized-client-build.ts new file mode 100644 index 0000000000..0c85fe2eb5 --- /dev/null +++ b/packages/start-plugin-core/src/vite/start-manifest-plugin/normalized-client-build.ts @@ -0,0 +1,160 @@ +import { tsrSplit } from '@tanstack/router-plugin' +import { tssHydrate } from '../../hydration-constants' +import { getCssAssetSource } from '../../start-manifest-plugin/inlineCss' +import type { Rollup } from 'vite' +import type { NormalizedClientBuild, NormalizedClientChunk } from '../../types' + +export function normalizeViteClientChunk( + chunk: Rollup.OutputChunk, +): NormalizedClientChunk { + return { + fileName: chunk.fileName, + isEntry: chunk.isEntry, + imports: chunk.imports, + dynamicImports: chunk.dynamicImports, + css: Array.from(chunk.viteMetadata?.importedCss ?? []), + routeFilePaths: getRouteFilePathsFromModuleIds(chunk.moduleIds), + hydrationIds: getHydrationIdsFromModuleIds(chunk.moduleIds), + } +} + +export function normalizeViteClientChunks( + clientBundle: Rollup.OutputBundle, +): ReadonlyMap { + const chunksByFileName = new Map() + + for (const fileName in clientBundle) { + const bundleEntry = clientBundle[fileName]! + if (bundleEntry.type !== 'chunk') { + continue + } + + const normalizedChunk = normalizeViteClientChunk(bundleEntry) + chunksByFileName.set(normalizedChunk.fileName, normalizedChunk) + } + + return chunksByFileName +} + +export function normalizeViteClientBuild( + clientBundle: Rollup.OutputBundle, + inlineCssEnabled = false, +): NormalizedClientBuild { + let entryChunkFileName: string | undefined + const chunksByFileName = normalizeViteClientChunks(clientBundle) + let cssContentByFileName: Map | undefined + + for (const chunk of chunksByFileName.values()) { + if (chunk.isEntry) { + if (entryChunkFileName) { + throw new Error( + `multiple entries detected: ${entryChunkFileName} ${chunk.fileName}`, + ) + } + entryChunkFileName = chunk.fileName + } + } + + if (inlineCssEnabled) { + cssContentByFileName = new Map() + for (const fileName in clientBundle) { + if (!fileName.endsWith('.css')) { + continue + } + + const bundleEntry = clientBundle[fileName]! + if (bundleEntry.type !== 'asset') { + continue + } + + const css = getCssAssetSource(bundleEntry.source) + if (css !== undefined) { + cssContentByFileName.set(fileName, css) + } + } + } + + if (!entryChunkFileName) { + throw new Error('No entry file found') + } + + return { + entryChunkFileName, + chunksByFileName, + cssContentByFileName, + } +} + +export function getRouteFilePathsFromModuleIds(moduleIds: Array) { + let routeFilePaths: Array | undefined + let seenRouteFilePaths: Set | undefined + + for (const moduleId of moduleIds) { + const queryIndex = moduleId.indexOf('?') + + if (queryIndex < 0) { + continue + } + + const query = moduleId.slice(queryIndex + 1) + + if (!query.includes(tsrSplit)) { + continue + } + + if (!new URLSearchParams(query).has(tsrSplit)) { + continue + } + + const routeFilePath = moduleId.slice(0, queryIndex) + + if (seenRouteFilePaths?.has(routeFilePath)) { + continue + } + + if (routeFilePaths === undefined || seenRouteFilePaths === undefined) { + routeFilePaths = [] + seenRouteFilePaths = new Set() + } + + routeFilePaths.push(routeFilePath) + seenRouteFilePaths.add(routeFilePath) + } + + return routeFilePaths ?? [] +} + +export function getHydrationIdsFromModuleIds(moduleIds: Array) { + let hydrationIds: Array | undefined + let seen: Set | undefined + + for (const moduleId of moduleIds) { + const queryIndex = moduleId.indexOf('?') + + if (queryIndex < 0) { + continue + } + + const query = moduleId.slice(queryIndex + 1) + + if (!query.includes(tssHydrate)) { + continue + } + + const hydrationId = new URLSearchParams(query).get(tssHydrate) + + if (!hydrationId || seen?.has(hydrationId)) { + continue + } + + if (hydrationIds === undefined || seen === undefined) { + hydrationIds = [] + seen = new Set() + } + + hydrationIds.push(hydrationId) + seen.add(hydrationId) + } + + return hydrationIds ?? [] +} diff --git a/packages/start-plugin-core/src/vite/start-manifest-plugin/plugin.ts b/packages/start-plugin-core/src/vite/start-manifest-plugin/plugin.ts new file mode 100644 index 0000000000..03e84c32c2 --- /dev/null +++ b/packages/start-plugin-core/src/vite/start-manifest-plugin/plugin.ts @@ -0,0 +1,191 @@ +import { joinURL } from 'ufo' +import { VIRTUAL_MODULES } from '@tanstack/start-server-core/virtual-modules' +import { rootRouteId } from '@tanstack/router-core' +import { DEV_CLIENT_ENTRY, START_ENVIRONMENT_NAMES } from '../../constants' +import { + buildStartManifest, + serializeStartManifest, +} from '../../start-manifest-plugin/manifestBuilder' +import { createVirtualModule } from '../createVirtualModule' +import { normalizeViteClientBuild } from './normalized-client-build' +import type { GetConfigFn, NormalizedClientBuild } from '../../types' +import type { PluginOption, Rollup } from 'vite' + +type StartManifestEnvironment = { + config: { + command: string + environments?: Record + } +} + +export function startManifestPlugin(opts: { + getConfig: GetConfigFn +}): PluginOption { + let clientBuild: NormalizedClientBuild | undefined + let cssCodeSplitDisabledFileName: string | undefined + let devClientRuntime: string | undefined + + return [ + { + name: 'tanstack-start:start-manifest-capture-client-build', + applyToEnvironment(environment) { + return environment.name === START_ENVIRONMENT_NAMES.client + }, + enforce: 'post', + configureServer(server) { + // Vite's separate bundled dev runtime must run before the client entry. + // Use its SSR output API once available (vitejs/vite#22991). + devClientRuntime = server.environments[START_ENVIRONMENT_NAMES.client] + .bundledDev + ? joinURL(server.config.base, 'bundledDevClient.mjs') + : undefined + }, + generateBundle(_options, bundle) { + if (this.environment.name !== START_ENVIRONMENT_NAMES.client) { + throw new Error( + `Unexpected environment for client build capture: ${this.environment.name}`, + ) + } + + clientBuild = normalizeViteClientBuild( + bundle, + opts.getConfig().startConfig.server.build.inlineCss.enabled, + ) + cssCodeSplitDisabledFileName = getAssetFileNameByName( + bundle, + 'style.css', + ) + }, + }, + createVirtualModule({ + name: 'tanstack-start:start-manifest-plugin', + moduleId: VIRTUAL_MODULES.startManifest, + enforce: 'pre', + load() { + const { resolvedStartConfig, startConfig } = opts.getConfig() + const clientEntry = getDevClientEntry({ + basePath: resolvedStartConfig.basePaths.publicBase, + bundledDev: isClientBundledDev(this.environment), + }) + + if (this.environment.name !== START_ENVIRONMENT_NAMES.server) { + return getEmptyStartManifestModule(clientEntry, devClientRuntime) + } + + if (this.environment.config.command === 'serve') { + return getEmptyStartManifestModule(clientEntry, devClientRuntime) + } + + const routeTreeRoutes = globalThis.TSS_ROUTES_MANIFEST + // TODO this needs further discussion with vite-rsc, this is a temporary workaround + // If the client bundle isn't available yet (e.g., during RSC scan builds), + // return a dummy manifest. The real manifest will be generated in the actual build. + if (!clientBuild) { + return getEmptyStartManifestModule(clientEntry) + } + const startManifest = buildStartManifest({ + clientBuild, + routeTreeRoutes, + basePath: resolvedStartConfig.basePaths.publicBase, + inlineCss: startConfig.server.build.inlineCss, + additionalRouteAssets: getViteAdditionalRouteAssets({ + cssCodeSplitDisabledFileName, + basePath: resolvedStartConfig.basePaths.publicBase, + cssCodeSplit: this.environment.config.build.cssCodeSplit, + }), + }) + + return `export const tsrStartManifest = () => (${serializeStartManifest(startManifest)})` + }, + }), + ] +} + +function getViteAdditionalRouteAssets(options: { + cssCodeSplitDisabledFileName: string | undefined + basePath: string + cssCodeSplit: boolean | undefined +}) { + if (options.cssCodeSplit !== false) { + return undefined + } + + if (!options.cssCodeSplitDisabledFileName) { + throw new Error( + "TanStack Start could not find Vite's generated `style.css` manifest entry while `build.cssCodeSplit` is disabled", + ) + } + + return { + [rootRouteId]: [ + joinURL(options.basePath, options.cssCodeSplitDisabledFileName), + ], + } +} + +function getAssetFileNameByName( + bundle: Rollup.OutputBundle, + assetName: string, +) { + for (const fileName in bundle) { + const bundleEntry = bundle[fileName]! + + if (bundleEntry.type !== 'asset') { + continue + } + + if (bundleEntry.name === assetName) { + return fileName + } + + if ('names' in bundleEntry && bundleEntry.names.includes(assetName)) { + return fileName + } + } + + return undefined +} + +function getEmptyStartManifestModule( + clientEntry: string, + clientRuntime?: string, +) { + if (clientRuntime) { + const entries = [clientRuntime, clientEntry] + return `export const tsrStartManifest = () => (${serializeStartManifest({ + routes: { + [rootRouteId]: { + preloads: entries, + scripts: entries.map((src) => ({ + attrs: { type: 'module', async: false, src }, + })), + }, + }, + })})` + } + + return `export const tsrStartManifest = () => ({ + routes: { + __root__: { + preloads: ['${clientEntry}'], + scripts: [{ attrs: { type: 'module', async: true, src: '${clientEntry}' } }], + }, + }, + })` +} + +function getDevClientEntry(opts: { basePath: string; bundledDev: boolean }) { + if (opts.bundledDev) { + return joinURL(opts.basePath, 'assets', 'index.js') + } + + return joinURL(opts.basePath, '@id', DEV_CLIENT_ENTRY) +} + +function isClientBundledDev(environment: StartManifestEnvironment) { + return ( + environment.config.command === 'serve' && + environment.config.environments?.[START_ENVIRONMENT_NAMES.client] + ?.isBundled === true + ) +} diff --git a/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts b/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts new file mode 100644 index 0000000000..8df06af4f5 --- /dev/null +++ b/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts @@ -0,0 +1,179 @@ +import { createRouterPluginContext } from '@tanstack/router-plugin/context' +import { + tanStackRouterCodeSplitter, + tanstackRouterGenerator, +} from '@tanstack/router-plugin/vite' +import path from 'pathe' +import { normalizePath } from 'vite' +import { VITE_ENVIRONMENT_NAMES } from '../../constants' +import { startGeneratorConfig } from '../../start-router-plugin/generator-config' +import { pruneServerOnlySubtrees } from '../../start-router-plugin/pruneServerOnlySubtrees' +import { SERVER_PROP } from '../../start-router-plugin/constants' +import { escapeRegExp } from '../../utils' +import type { GetConfigFn } from '../../types' +import type { TanStackStartVitePluginCoreOptions } from '../types' +import type { + Generator, + GeneratorPlugin, + RouteNode, +} from '@tanstack/router-generator' +import type { DevEnvironment, Plugin, PluginOption } from 'vite' +import type { TanStackStartInputConfig } from '../../schema' + +function isServerOnlyNode(node: RouteNode | undefined) { + if (!node?.createFileRouteProps) { + return false + } + return ( + node.createFileRouteProps.has(SERVER_PROP) && + node.createFileRouteProps.size === 1 + ) +} + +export function tanStackStartRouter( + startPluginOpts: TanStackStartInputConfig, + getConfig: GetConfigFn, + corePluginOpts: TanStackStartVitePluginCoreOptions, +): Array { + const routerPluginContext = createRouterPluginContext() + + const getGeneratedRouteTreePath = () => { + const { startConfig } = getConfig() + return path.resolve(startConfig.router.generatedRouteTree) + } + + let clientEnvironment: DevEnvironment | null = null + function invalidate() { + if (!clientEnvironment) { + return + } + + const mod = clientEnvironment.moduleGraph.getModuleById( + getGeneratedRouteTreePath(), + ) + if (mod) { + clientEnvironment.moduleGraph.invalidateModule(mod) + } + clientEnvironment.hot.send({ type: 'full-reload', path: '*' }) + } + + let generatorInstance: Generator | null = null + + const clientTreeGeneratorPlugin: GeneratorPlugin = { + name: 'start-client-tree-plugin', + init({ generator }) { + generatorInstance = generator + }, + afterTransform({ node, prevNode }) { + if (isServerOnlyNode(node) !== isServerOnlyNode(prevNode)) { + invalidate() + } + }, + } + + let resolvedGeneratedRouteTreePath: string | null = null + const clientTreePlugin: Plugin = { + name: 'tanstack-start:route-tree-client-plugin', + enforce: 'pre', + applyToEnvironment: (env) => env.name === VITE_ENVIRONMENT_NAMES.client, + configureServer(server) { + clientEnvironment = server.environments[VITE_ENVIRONMENT_NAMES.client] + }, + config() { + type LoadObjectHook = Extract< + typeof clientTreePlugin.load, + { filter?: unknown } + > + resolvedGeneratedRouteTreePath = normalizePath( + getGeneratedRouteTreePath(), + ) + // The route tree module itself, by its exact id (a query aside) + ;(clientTreePlugin.load as LoadObjectHook).filter = { + id: { + include: new RegExp( + `^${escapeRegExp(resolvedGeneratedRouteTreePath)}(?:\\?.*)?$`, + ), + }, + } + }, + + load: { + filter: { + // this will be set in the config hook above since it relies on `config` hook being called first + }, + async handler(id) { + if ( + normalizePath(id.replace(/\?.*$/, '')) !== + resolvedGeneratedRouteTreePath + ) { + return null + } + if (!generatorInstance) { + throw new Error('Generator instance not initialized') + } + const crawlingResult = await generatorInstance.getCrawlingResult() + if (!crawlingResult) { + throw new Error('Crawling result not available') + } + const prunedAcc = pruneServerOnlySubtrees(crawlingResult) + const acc = { + ...crawlingResult.acc, + ...prunedAcc, + } + const buildResult = generatorInstance.buildRouteTree({ + ...crawlingResult, + acc, + config: { + // importRoutesUsingAbsolutePaths: true, + // addExtensions: true, + disableTypes: true, + enableRouteTreeFormatting: false, + routeTreeFileHeader: [], + routeTreeFileFooter: [], + }, + }) + return { code: buildResult.routeTreeContent, map: null } + }, + }, + } + return [ + clientTreePlugin, + tanstackRouterGenerator( + () => + startGeneratorConfig({ + getConfig, + corePluginOpts, + prerender: startPluginOpts.prerender?.enabled === true, + clientRouteTree: clientTreeGeneratorPlugin, + }), + routerPluginContext, + ), + tanStackRouterCodeSplitter(() => { + const routerConfig = getConfig().startConfig.router + return { + ...routerConfig, + codeSplittingOptions: { + ...routerConfig.codeSplittingOptions, + deleteNodes: ['ssr', 'server', 'headers'], + addHmr: true, + }, + plugin: { + vite: { environmentName: VITE_ENVIRONMENT_NAMES.client }, + }, + } + }, routerPluginContext), + tanStackRouterCodeSplitter(() => { + const routerConfig = getConfig().startConfig.router + return { + ...routerConfig, + codeSplittingOptions: { + ...routerConfig.codeSplittingOptions, + addHmr: false, + }, + plugin: { + vite: { environmentName: VITE_ENVIRONMENT_NAMES.server }, + }, + } + }, routerPluginContext), + ] +} diff --git a/packages/start-plugin-core/src/vite/types.ts b/packages/start-plugin-core/src/vite/types.ts new file mode 100644 index 0000000000..4b98551268 --- /dev/null +++ b/packages/start-plugin-core/src/vite/types.ts @@ -0,0 +1,18 @@ +import type { TanStackStartCoreOptions } from '../types' + +export interface ViteRscForwardSsrResolverStrategy { + type: 'vite-rsc-forward' + sourceEnvironmentName: string + sourceEntry: string + exportName: 'getServerFnById' +} + +export type SsrResolverStrategy = + | { type: 'default' } + | ViteRscForwardSsrResolverStrategy + +export type TanStackStartVitePluginCoreOptions = TanStackStartCoreOptions & { + providerEnvironmentName: string + ssrIsProvider: boolean + ssrResolverStrategy: SsrResolverStrategy +} diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/clientOnlyJSX.test.ts b/packages/start-plugin-core/tests/clientOnlyJSX/clientOnlyJSX.test.ts new file mode 100644 index 0000000000..fa48668a38 --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/clientOnlyJSX.test.ts @@ -0,0 +1,105 @@ +import { readFile, readdir } from 'node:fs/promises' +import path from 'node:path' +import { describe, expect, test } from 'vitest' + +import { + detectKindsInCode, + StartCompiler, +} from '../../src/start-compiler/compiler' +import { formatSnapshot } from '../format-snapshot' + +// Default test options for StartCompiler +function getDefaultTestOptions(env: 'client' | 'server') { + const envName = env === 'client' ? 'client' : 'ssr' + return { + envName, + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + } +} + +async function compile(opts: { + env: 'client' | 'server' + code: string + id: string +}) { + const compiler = new StartCompiler({ + ...opts, + ...getDefaultTestOptions(opts.env), + loadModule: async () => { + // do nothing in test + }, + lookupKinds: new Set(['ClientOnlyJSX']), + lookupConfigurations: [ + // ClientOnly JSX component from TanStack router packages + { + libName: '@tanstack/react-router', + rootExport: 'ClientOnly', + kind: 'ClientOnlyJSX', + }, + ], + getKnownServerFns: () => ({}), + resolveId: async (id) => { + return id + }, + }) + const result = await compiler.compile({ + code: opts.code, + id: opts.id, + }) + return result +} + +async function getFilenames() { + return await readdir(path.resolve(import.meta.dirname, './test-files')) +} + +describe('ClientOnlyJSX compiles correctly', async () => { + const filenames = await getFilenames() + + describe.each(filenames)('should handle "%s"', async (filename) => { + const file = await readFile( + path.resolve(import.meta.dirname, `./test-files/${filename}`), + ) + const code = file.toString() + + // ClientOnlyJSX is only transformed on server + test(`should compile for ${filename} server`, async () => { + const compiledResult = await compile({ + env: 'server', + code, + id: filename, + }) + + if (compiledResult) { + await expect( + await formatSnapshot(compiledResult.code, filename), + ).toMatchFileSnapshot(`./snapshots/server/${filename}`) + } else { + // No transformation - for files where ClientOnly is not from TanStack + await expect('no-transform').toMatchFileSnapshot( + `./snapshots/server/${filename}`, + ) + } + }) + }) + + test('ClientOnlyJSX should not be detected on client', () => { + const code = ` + import { ClientOnly } from '@tanstack/react-router' + test + ` + const detectedKinds = detectKindsInCode(code, 'client') + expect(detectedKinds.has('ClientOnlyJSX')).toBe(false) + }) + + test('ClientOnlyJSX should be detected on server', () => { + const code = ` + import { ClientOnly } from '@tanstack/react-router' + test + ` + const detectedKinds = detectKindsInCode(code, 'server') + expect(detectedKinds.has('ClientOnlyJSX')).toBe(true) + }) +}) diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyBasic.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyBasic.tsx new file mode 100644 index 0000000000..96de7844f6 --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyBasic.tsx @@ -0,0 +1,8 @@ +import { ClientOnly } from '@tanstack/react-router' +export function MyComponent() { + return ( +
    + Loading...
    } /> +
    + ) +} diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyMultiple.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyMultiple.tsx new file mode 100644 index 0000000000..6b95090d3f --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyMultiple.tsx @@ -0,0 +1,10 @@ +import { ClientOnly } from '@tanstack/react-router' +export function MyComponent() { + return ( +
    + Loading video...} /> +

    Some server content

    + Loading audio...} /> +
    + ) +} diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNested.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNested.tsx new file mode 100644 index 0000000000..f3d5d3b526 --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNested.tsx @@ -0,0 +1,8 @@ +import { ClientOnly } from '@tanstack/react-router' +export function MyComponent() { + return ( +
    + Outer loading
    } /> +
    + ) +} diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNoFallback.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNoFallback.tsx new file mode 100644 index 0000000000..40551a6dad --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNoFallback.tsx @@ -0,0 +1,8 @@ +import { ClientOnly } from '@tanstack/react-router' +export function MyComponent() { + return ( +
    + +
    + ) +} diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNotFromTanstack.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNotFromTanstack.tsx new file mode 100644 index 0000000000..b35c36ab1b --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyNotFromTanstack.tsx @@ -0,0 +1 @@ +no-transform \ No newline at end of file diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyRenamed.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyRenamed.tsx new file mode 100644 index 0000000000..9a537448b0 --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyRenamed.tsx @@ -0,0 +1,9 @@ +// Test: ClientOnly imported with an alias should still be transformed +import { ClientOnly as CO } from '@tanstack/react-router' +export function MyComponent() { + return ( +
    + Loading...
    } /> +
    + ) +} diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyWrongImportName.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyWrongImportName.tsx new file mode 100644 index 0000000000..b35c36ab1b --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/snapshots/server/clientOnlyWrongImportName.tsx @@ -0,0 +1 @@ +no-transform \ No newline at end of file diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyBasic.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyBasic.tsx new file mode 100644 index 0000000000..29cc888830 --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyBasic.tsx @@ -0,0 +1,13 @@ +import { ClientOnly } from '@tanstack/react-router' +import { Chart } from 'heavy-chart-library' +import { formatData } from './utils' + +export function MyComponent() { + return ( +
    + Loading...
    }> + + +
    + ) +} diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyMultiple.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyMultiple.tsx new file mode 100644 index 0000000000..f3712aa7b3 --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyMultiple.tsx @@ -0,0 +1,17 @@ +import { ClientOnly } from '@tanstack/react-router' +import { VideoPlayer } from 'video-player-lib' +import { AudioVisualizer } from 'audio-viz-lib' + +export function MyComponent() { + return ( +
    + Loading video...}> + + +

    Some server content

    + Loading audio...}> + + +
    + ) +} diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyNested.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyNested.tsx new file mode 100644 index 0000000000..222def8795 --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyNested.tsx @@ -0,0 +1,16 @@ +import { ClientOnly } from '@tanstack/react-router' + +export function MyComponent() { + return ( +
    + Outer loading
    }> +
    + Outer content + Inner loading}> + Inner client only + +
    + +
    + ) +} diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyNoFallback.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyNoFallback.tsx new file mode 100644 index 0000000000..a76c0fde46 --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyNoFallback.tsx @@ -0,0 +1,12 @@ +import { ClientOnly } from '@tanstack/react-router' +import { HeavyAnimation } from 'animation-library' + +export function MyComponent() { + return ( +
    + + + +
    + ) +} diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyNotFromTanstack.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyNotFromTanstack.tsx new file mode 100644 index 0000000000..06fc40a1b9 --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyNotFromTanstack.tsx @@ -0,0 +1,12 @@ +// This should NOT be transformed because ClientOnly is not from @tanstack/*-router +import { ClientOnly } from 'some-other-package' + +export function MyComponent() { + return ( +
    + Loading...
    }> +
    This should remain as-is
    + +
    + ) +} diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyRenamed.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyRenamed.tsx new file mode 100644 index 0000000000..311c9e1b86 --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyRenamed.tsx @@ -0,0 +1,13 @@ +// Test: ClientOnly imported with an alias should still be transformed +import { ClientOnly as CO } from '@tanstack/react-router' +import { WindowSize } from './WindowSize' + +export function MyComponent() { + return ( +
    + Loading...
    }> + + +
    + ) +} diff --git a/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyWrongImportName.tsx b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyWrongImportName.tsx new file mode 100644 index 0000000000..4bd777c079 --- /dev/null +++ b/packages/start-plugin-core/tests/clientOnlyJSX/test-files/clientOnlyWrongImportName.tsx @@ -0,0 +1,11 @@ +// Test: A different component imported from TanStack should NOT be transformed +// even if aliased to "ClientOnly" - we check the original import name +import { Link as ClientOnly } from '@tanstack/react-router' + +export function MyComponent() { + return ( +
    + Go to About +
    + ) +} diff --git a/packages/start-plugin-core/tests/compiler.test.ts b/packages/start-plugin-core/tests/compiler.test.ts new file mode 100644 index 0000000000..68e193204f --- /dev/null +++ b/packages/start-plugin-core/tests/compiler.test.ts @@ -0,0 +1,1597 @@ +import { describe, expect, test } from 'vitest' +import { + StartCompiler, + detectKindsInCode, + getLookupKindsForEnv, +} from '../src/start-compiler/compiler' +import { getLookupConfigurationsForEnv } from '../src/start-compiler/config' +import type { LookupConfig, LookupKind } from '../src/start-compiler/compiler' +import type { StartCompilerImportTransform } from '../src/types' + +// Default test options for StartCompiler +function getDefaultTestOptions(env: 'client' | 'server') { + const envName = env === 'client' ? 'client' : 'ssr' + return { + envName, + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + } +} + +// Helper to create a compiler with all kinds enabled +function createFullCompiler( + env: 'client' | 'server', + opts?: { + serverFnProviderModuleDirectives?: ReadonlyArray | undefined + }, +) { + const lookupKinds: Set = + env === 'client' + ? new Set([ + 'ServerFn', + 'Middleware', + 'IsomorphicFn', + 'ServerOnlyFn', + 'ClientOnlyFn', + ]) + : new Set(['ServerFn', 'IsomorphicFn', 'ServerOnlyFn', 'ClientOnlyFn']) + + const lookupConfigurations: Array = [ + { + libName: '@tanstack/react-start', + rootExport: 'createServerFn', + kind: 'Root', + }, + { + libName: '@tanstack/react-start', + rootExport: 'createMiddleware', + kind: 'Root', + }, + { + libName: '@tanstack/react-start', + rootExport: 'createIsomorphicFn', + kind: 'IsomorphicFn', + }, + { + libName: '@tanstack/react-start', + rootExport: 'createServerOnlyFn', + kind: 'ServerOnlyFn', + }, + { + libName: '@tanstack/react-start', + rootExport: 'createClientOnlyFn', + kind: 'ClientOnlyFn', + }, + ] + + return new StartCompiler({ + env, + ...getDefaultTestOptions(env), + lookupKinds, + lookupConfigurations, + getKnownServerFns: () => ({}), + loadModule: async () => {}, + resolveId: async (id) => id, + mode: 'build', + serverFnProviderModuleDirectives: opts?.serverFnProviderModuleDirectives, + }) +} + +function createExternalTransformCompiler() { + const compilerTransforms: Array = [ + { + name: 'test-render-option-injection', + environment: 'server', + imports: [ + { + libName: '@example/runtime', + rootExport: 'renderThing', + }, + ], + detect: /\brenderThing\b/, + transform: (candidates, context) => { + const t = context.types + for (const candidate of candidates) { + const args = candidate.path.node.arguments + if (args.length !== 1) continue + args.push( + t.objectExpression([ + t.objectProperty( + t.identifier('injected'), + context.parseExpression('loadThing()'), + ), + ]), + ) + } + }, + }, + ] + + return new StartCompiler({ + env: 'server', + envName: 'server', + root: '/test', + framework: 'react', + providerEnvName: 'server', + lookupKinds: getLookupKindsForEnv('server', { compilerTransforms }), + lookupConfigurations: getLookupConfigurationsForEnv('server', 'react', { + compilerTransforms, + }), + getKnownServerFns: () => ({}), + loadModule: async () => {}, + resolveId: async (id) => id, + mode: 'build', + compilerTransforms, + }) +} + +describe('detectKindsInCode', () => { + describe('detects individual kinds correctly', () => { + test('detects ServerFn via .handler(', () => { + const code = ` + import { createServerFn } from '@tanstack/react-start' + const fn = createServerFn().handler(() => 'hello') + ` + expect(detectKindsInCode(code, 'client')).toEqual(new Set(['ServerFn'])) + expect(detectKindsInCode(code, 'server')).toEqual(new Set(['ServerFn'])) + }) + + test('detects Middleware', () => { + const code = ` + import { createMiddleware } from '@tanstack/react-start' + const mw = createMiddleware().server(({ next }) => next()) + ` + // Middleware is only valid on client + expect(detectKindsInCode(code, 'client')).toEqual(new Set(['Middleware'])) + expect(detectKindsInCode(code, 'server')).toEqual(new Set()) + }) + + test('detects IsomorphicFn', () => { + const code = ` + import { createIsomorphicFn } from '@tanstack/react-start' + const fn = createIsomorphicFn().client(() => 'c').server(() => 's') + ` + expect(detectKindsInCode(code, 'client')).toEqual( + new Set(['IsomorphicFn']), + ) + expect(detectKindsInCode(code, 'server')).toEqual( + new Set(['IsomorphicFn']), + ) + }) + + test('detects ServerOnlyFn', () => { + const code = ` + import { createServerOnlyFn } from '@tanstack/react-start' + const fn = createServerOnlyFn(() => 'server only') + ` + expect(detectKindsInCode(code, 'client')).toEqual( + new Set(['ServerOnlyFn']), + ) + expect(detectKindsInCode(code, 'server')).toEqual( + new Set(['ServerOnlyFn']), + ) + }) + + test('detects ClientOnlyFn', () => { + const code = ` + import { createClientOnlyFn } from '@tanstack/react-start' + const fn = createClientOnlyFn(() => 'client only') + ` + expect(detectKindsInCode(code, 'client')).toEqual( + new Set(['ClientOnlyFn']), + ) + expect(detectKindsInCode(code, 'server')).toEqual( + new Set(['ClientOnlyFn']), + ) + }) + + test('resets external transform regex state between detections', () => { + const compilerTransforms: Array = [ + { + name: 'global-detect', + environment: 'server', + imports: [{ libName: '@example/runtime', rootExport: 'renderThing' }], + detect: /\brenderThing\b/g, + transform: () => {}, + }, + ] + const code = ` + import { renderThing } from '@example/runtime' + renderThing() + ` + + expect(detectKindsInCode(code, 'server', { compilerTransforms })).toEqual( + new Set(['External:global-detect']), + ) + expect(detectKindsInCode(code, 'server', { compilerTransforms })).toEqual( + new Set(['External:global-detect']), + ) + }) + }) + + describe('detects multiple kinds in same file', () => { + test('detects ServerFn and IsomorphicFn', () => { + const code = ` + import { createServerFn, createIsomorphicFn } from '@tanstack/react-start' + const serverFn = createServerFn().handler(() => 'hello') + const isoFn = createIsomorphicFn().client(() => 'client') + ` + expect(detectKindsInCode(code, 'client')).toEqual( + new Set(['ServerFn', 'IsomorphicFn']), + ) + }) + + test('detects all kinds on client', () => { + const code = ` + import { createServerFn, createMiddleware, createIsomorphicFn, createServerOnlyFn, createClientOnlyFn } from '@tanstack/react-start' + const a = createServerFn().handler(() => {}) + const b = createMiddleware().server(({ next }) => next()) + const c = createIsomorphicFn() + const d = createServerOnlyFn(() => {}) + const e = createClientOnlyFn(() => {}) + ` + expect(detectKindsInCode(code, 'client')).toEqual( + new Set([ + 'ServerFn', + 'Middleware', + 'IsomorphicFn', + 'ServerOnlyFn', + 'ClientOnlyFn', + ]), + ) + }) + + test('detects all valid kinds on server (excludes Middleware)', () => { + const code = ` + import { createServerFn, createMiddleware, createIsomorphicFn, createServerOnlyFn, createClientOnlyFn } from '@tanstack/react-start' + const a = createServerFn().handler(() => {}) + const b = createMiddleware().server(({ next }) => next()) + const c = createIsomorphicFn() + const d = createServerOnlyFn(() => {}) + const e = createClientOnlyFn(() => {}) + ` + // Middleware should NOT be detected on server + expect(detectKindsInCode(code, 'server')).toEqual( + new Set(['ServerFn', 'IsomorphicFn', 'ServerOnlyFn', 'ClientOnlyFn']), + ) + }) + }) + + describe('handles edge cases', () => { + test('returns empty set for code with no matching patterns', () => { + const code = ` + const foo = 'bar' + function hello() { return 'world' } + ` + expect(detectKindsInCode(code, 'client')).toEqual(new Set()) + expect(detectKindsInCode(code, 'server')).toEqual(new Set()) + }) + + test('handles .handler with whitespace variations', () => { + const code1 = `fn.handler(() => {})` + const code2 = `fn.handler (() => {})` + const code3 = `fn.handler\n(() => {})` + const code4 = `fn.handler\t(() => {})` + + expect(detectKindsInCode(code1, 'client')).toEqual(new Set(['ServerFn'])) + expect(detectKindsInCode(code2, 'client')).toEqual(new Set(['ServerFn'])) + expect(detectKindsInCode(code3, 'client')).toEqual(new Set(['ServerFn'])) + expect(detectKindsInCode(code4, 'client')).toEqual(new Set(['ServerFn'])) + }) + + test('handles whitespace between . and handler (reformatted code)', () => { + // When Vite/Babel reformats code, the dot can end up on a previous line + const code1 = `fn.\nhandler(() => {})` + const code2 = `fn.\n handler(() => {})` + const code3 = `fn. \n handler(() => {})` + + expect(detectKindsInCode(code1, 'client')).toEqual(new Set(['ServerFn'])) + expect(detectKindsInCode(code2, 'client')).toEqual(new Set(['ServerFn'])) + expect(detectKindsInCode(code3, 'client')).toEqual(new Set(['ServerFn'])) + }) + + test('detects createServerFn() call directly', () => { + // The pattern should match createServerFn() calls, not just .handler() + const code = ` + import { createServerFn } from '@tanstack/react-start' + const fn = createServerFn() + ` + expect(detectKindsInCode(code, 'client')).toEqual(new Set(['ServerFn'])) + }) + + test('does not false positive on similar function names', () => { + // Only exact createServerFn( should match, not variations + const code = ` + const fn = createServerFnExample() + const fn2 = createServerFnLike() + const fn3 = mycreateServerFn() + const fn4 = _createServerFn() + ` + expect(detectKindsInCode(code, 'client')).toEqual(new Set()) + }) + + test('does not false positive on similar names', () => { + const code = ` + const myCreateServerFn = () => {} + const createServerFnLike = () => {} + // But this should match: + createServerFn().handler(() => {}) + ` + // Should only match because of .handler(, not because of variable names + expect(detectKindsInCode(code, 'client')).toEqual(new Set(['ServerFn'])) + }) + }) +}) + +describe('compiler handles multiple files with different kinds', () => { + test('single compiler instance correctly processes files with different kinds in succession', async () => { + const compiler = createFullCompiler('client') + + // File 1: ServerFn only + const result1 = await compiler.compile({ + code: ` + import { createServerFn } from '@tanstack/react-start' + export const fn = createServerFn().handler(() => 'hello') + `, + id: 'file1.ts', + + detectedKinds: new Set(['ServerFn']), + }) + expect(result1).not.toBeNull() + expect(result1!.code).toContain('createClientRpc') // Client should have RPC stub + expect(result1!.code).not.toContain('createMiddleware') + expect(result1!.code).not.toContain('createIsomorphicFn') + + // File 2: Middleware only + const result2 = await compiler.compile({ + code: ` + import { createMiddleware } from '@tanstack/react-start' + export const mw = createMiddleware().server(({ next }) => { + console.log('server only') + return next() + }) + `, + id: 'file2.ts', + + detectedKinds: new Set(['Middleware']), + }) + expect(result2).not.toBeNull() + // .server() should be stripped on client + expect(result2!.code).not.toContain('console.log') + expect(result2!.code).not.toContain('createServerFn') + + // File 3: IsomorphicFn only + const result3 = await compiler.compile({ + code: ` + import { createIsomorphicFn } from '@tanstack/react-start' + export const fn = createIsomorphicFn() + .client(() => 'client-value') + .server(() => 'server-value') + `, + id: 'file3.ts', + + detectedKinds: new Set(['IsomorphicFn']), + }) + expect(result3).not.toBeNull() + // Client should have client implementation + expect(result3!.code).toContain('client-value') + expect(result3!.code).not.toContain('server-value') + + // File 4: ServerOnlyFn only + const result4 = await compiler.compile({ + code: ` + import { createServerOnlyFn } from '@tanstack/react-start' + export const fn = createServerOnlyFn(() => 'server only value') + `, + id: 'file4.ts', + + detectedKinds: new Set(['ServerOnlyFn']), + }) + expect(result4).not.toBeNull() + // Client should have error throw + expect(result4!.code).toContain('throw new Error') + expect(result4!.code).not.toContain('server only value') + + // File 5: Mix of ServerFn and IsomorphicFn + const result5 = await compiler.compile({ + code: ` + import { createServerFn, createIsomorphicFn } from '@tanstack/react-start' + export const serverFn = createServerFn().handler(() => 'hello') + export const isoFn = createIsomorphicFn().client(() => 'client-iso') + `, + id: 'file5.ts', + + detectedKinds: new Set(['ServerFn', 'IsomorphicFn']), + }) + expect(result5).not.toBeNull() + expect(result5!.code).toContain('createClientRpc') // ServerFn RPC + expect(result5!.code).toContain('client-iso') // IsomorphicFn client impl + }) + + test('compiler works correctly when processing same kind multiple times', async () => { + const compiler = createFullCompiler('client') + + // First file with IsomorphicFn + const result1 = await compiler.compile({ + code: ` + import { createIsomorphicFn } from '@tanstack/react-start' + export const fn1 = createIsomorphicFn().client(() => 'first') + `, + id: 'first.ts', + + detectedKinds: new Set(['IsomorphicFn']), + }) + expect(result1!.code).toContain('first') + + // Second file with different IsomorphicFn + const result2 = await compiler.compile({ + code: ` + import { createIsomorphicFn } from '@tanstack/react-start' + export const fn2 = createIsomorphicFn().client(() => 'second') + `, + id: 'second.ts', + + detectedKinds: new Set(['IsomorphicFn']), + }) + expect(result2!.code).toContain('second') + expect(result2!.code).not.toContain('first') // Should not leak from previous file + }) + + test('server environment excludes Middleware from detected kinds', async () => { + const compiler = createFullCompiler('server') + + // Even if Middleware is in detectedKinds, server env should ignore it + const result = await compiler.compile({ + code: ` + import { createMiddleware } from '@tanstack/react-start' + export const mw = createMiddleware().server(({ next }) => next()) + `, + id: 'middleware.ts', + + // Intentionally including Middleware even though it's server env + detectedKinds: new Set(['Middleware']), + }) + // Should return null since Middleware is not valid on server + expect(result).toBeNull() + }) +}) + +describe('compiler handles external import transforms', () => { + test('runs configured direct-call transforms before server function extraction', async () => { + const compiler = createExternalTransformCompiler() + + const result = await compiler.compile({ + code: ` + import { createServerFn } from '@tanstack/react-start' + import { renderThing as renderAlias } from '@example/runtime' + + export const getComponent = createServerFn({ method: 'GET' }).handler(async () => { + return renderAlias() + }) + `, + id: '/test/src/routes/card.tsx?tss-serverfn-split', + }) + + expect(result).not.toBeNull() + expect(result!.code).toContain('injected: loadThing()') + expect(result!.code).toContain('renderAlias(,') + }) + + test('runs configured direct-call transforms for namespace imports', async () => { + const compiler = createExternalTransformCompiler() + + const result = await compiler.compile({ + code: ` + import * as runtime from '@example/runtime' + + export const component = runtime.renderThing() + `, + id: '/test/src/routes/card.tsx', + }) + + expect(result).not.toBeNull() + expect(result!.code).toContain('injected: loadThing()') + expect(result!.code).toContain('runtime.renderThing(,') + }) + + test('does not run external transforms for shadowed import names', async () => { + const compiler = createExternalTransformCompiler() + + const result = await compiler.compile({ + code: ` + import { renderThing } from '@example/runtime' + + export function component() { + const renderThing = (node: React.ReactNode) => node + return renderThing() + } + `, + id: '/test/src/routes/card.tsx', + }) + + expect(result).toBeNull() + }) + + // Source: @vitejs/plugin-rsc transform fixtures (per row) + test.each([ + { + // hoist/function-hoist-block.js: block-level functions are block scoped + name: 'past a function declared in a nested block', + body: `{ + function renderThing() {} + } + return renderThing()`, + transformed: true, + }, + { + // scope/param-default-var-hoisting.js + name: 'in a parameter default next to a var of the same name', + params: `element = renderThing()`, + body: `var renderThing = null + return element`, + transformed: true, + }, + { + // hoist/catch-binding-shadow.js + name: 'in a try block whose catch parameter shadows it', + body: `try { + return renderThing() + } catch (renderThing) { + return renderThing + }`, + transformed: true, + }, + { + // hoist/var-hoist-block.js + name: 'after a var in a nested block shadows it', + body: `if (Math.random() < 2) { + var renderThing = (element) => element + } + return renderThing()`, + transformed: false, + }, + { + // scope/fn-decl-hoisting.js + name: 'before a hoisted function declaration shadows it', + body: `return renderThing() + function renderThing(element) { + return element + }`, + transformed: false, + }, + { + // scope/catch-param.js + name: 'in a catch block whose parameter shadows it', + body: `try { + throw (element) => element + } catch (renderThing) { + return renderThing() + }`, + transformed: false, + }, + ])( + 'runs external transforms on a call $name only if it reads the import', + async ({ params = '', body, transformed }) => { + const compiler = createExternalTransformCompiler() + + // The top-level call keeps the module transformed in every row. + const result = await compiler.compile({ + code: ` + import { renderThing } from '@example/runtime' + export const transformed = renderThing() + export function render(${params}) { + ${body} + } + `, + id: '/test/src/routes/card.tsx', + }) + + expect(result).not.toBeNull() + const renderStart = result!.code.indexOf('function render(') + expect(renderStart).toBeGreaterThanOrEqual(0) + const render = result!.code.slice(renderStart) + expect(render.includes('injected: loadThing()')).toBe(transformed) + }, + ) +}) + +describe('server function provider module directives', () => { + test.each([ + 'export const Route = { component: Page }', + 'export function Route() { return Page() }', + 'export default function Route() { return Page() }', + ])( + 'removes browser-only dependencies of stripped exports: %s', + async (route) => { + const compiler = createFullCompiler('server') + const result = await compiler.compile({ + code: ` + import { createServerFn } from '@tanstack/react-start' + export const getMessage = createServerFn().handler(() => 'server message') + const browserState = { window } + function Page() { return browserState } + ${route} + `, + id: '/test/src/routes/message.tsx?tss-serverfn-split', + }) + + expect(result).not.toBeNull() + expect(result!.code).toContain('server message') + expect(result!.code).toContain('createServerRpc') + expect(result!.code).not.toContain('window') + expect(result!.code).not.toContain('browserState') + expect(result!.code).not.toContain('Page') + expect(result!.code).not.toContain('Route') + }, + ) + + const code = ` + import { createServerFn } from '@tanstack/react-start' + + export const getMessage = createServerFn({ method: 'GET' }).handler(() => { + return 'hello' + }) + ` + + test('does not add module directives without compiler configuration', async () => { + const compiler = createFullCompiler('server') + + const result = await compiler.compile({ + code, + id: '/test/src/routes/message.tsx?tss-serverfn-split', + }) + + expect(result).not.toBeNull() + expect(result!.code).not.toContain('"use server-entry"') + }) + + test('adds configured module directives to provider files only', async () => { + const compiler = createFullCompiler('server', { + serverFnProviderModuleDirectives: ['use server-entry'], + }) + + const providerResult = await compiler.compile({ + code, + id: '/test/src/routes/message.tsx?tss-serverfn-split', + }) + const callerResult = await compiler.compile({ + code, + id: '/test/src/routes/message.tsx', + }) + + expect(providerResult).not.toBeNull() + expect(providerResult!.code).toContain('"use server-entry";') + expect(callerResult).not.toBeNull() + expect(callerResult!.code).not.toContain('"use server-entry"') + }) +}) + +describe('edge cases for detectedKinds', () => { + test('empty detectedKinds returns null (no candidates to process)', async () => { + const compiler = createFullCompiler('client') + + const result = await compiler.compile({ + code: ` + // This file somehow passed Vite filter but has no actual kinds + const foo = 'bar' + // Maybe a false positive match like "handler(" in a comment + // .handler( in string + `, + id: 'empty.ts', + + detectedKinds: new Set(), // Empty set + }) + + expect(result).toBeNull() + }) + + test('detectedKinds not provided falls back to all valid kinds', async () => { + const compiler = createFullCompiler('client') + + // When detectedKinds is not provided, should check all valid kinds + const result = await compiler.compile({ + code: ` + import { createIsomorphicFn } from '@tanstack/react-start' + export const fn = createIsomorphicFn().client(() => 'works') + `, + id: 'no-detected.ts', + + // No detectedKinds provided + }) + + expect(result).not.toBeNull() + expect(result!.code).toContain('works') + }) + + test('detectedKinds with invalid kinds for env are filtered out', async () => { + const compiler = createFullCompiler('server') + + // Passing Middleware (invalid for server) along with valid kind + const result = await compiler.compile({ + code: ` + import { createIsomorphicFn } from '@tanstack/react-start' + export const fn = createIsomorphicFn().server(() => 'server-impl') + `, + id: 'filtered.ts', + + detectedKinds: new Set(['Middleware', 'IsomorphicFn']), // Middleware should be filtered + }) + + expect(result).not.toBeNull() + expect(result!.code).toContain('server-impl') + }) +}) + +test('ingestModule handles empty code gracefully', () => { + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + lookupKinds: new Set(['ServerFn']), + lookupConfigurations: [], + getKnownServerFns: () => ({}), + loadModule: async () => {}, + resolveId: async (id) => id, + }) + + // Should not throw when ingesting empty module + expect(() => { + compiler.ingestModule({ code: '', id: 'empty-types.ts' }) + }).not.toThrow() + + // Should also handle whitespace-only modules + expect(() => { + compiler.ingestModule({ code: ' \n\t ', id: 'whitespace.ts' }) + }).not.toThrow() +}) + +test('compile caches modules without detected candidates for transitive importer traversal', async () => { + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + lookupKinds: new Set(['ServerFn']), + lookupConfigurations: [], + getKnownServerFns: () => ({}), + loadModule: async () => {}, + resolveId: async (source, importer) => { + if (source === './leaf' && importer === '/src/plain.ts') { + return '/src/leaf.ts' + } + + if (source === './plain' && importer === '/src/parent.ts') { + return '/src/plain.ts' + } + + return null + }, + }) + + await compiler.compile({ + id: '/src/plain.ts', + code: ` + import { value } from './leaf' + export const plain = value + `, + detectedKinds: new Set(), + }) + + await compiler.compile({ + id: '/src/parent.ts', + code: ` + import { plain } from './plain' + export const parent = plain + `, + detectedKinds: new Set(), + }) + + expect(await compiler.getTransitiveImporters('/src/leaf.ts')).toEqual( + new Set(['/src/plain.ts', '/src/parent.ts']), + ) + expect(await compiler.getTransitiveImporters(['/src/leaf.ts'])).toEqual( + new Set(['/src/plain.ts', '/src/parent.ts']), + ) +}) + +describe('calling result of createServerOnlyFn/createClientOnlyFn', () => { + // This tests the fix for https://github.com/TanStack/router/issues/6643 + // When a file has both createServerFn and createServerOnlyFn, and the result + // of createServerOnlyFn is invoked (e.g., `const result = myServerOnlyFn()`), + // the compiler should NOT treat that invocation as a ServerOnlyFn candidate. + // The var binding holds the RESULT of the factory, not the factory itself. + + test('invocation of createServerOnlyFn result is not treated as a candidate', async () => { + const compiler = createFullCompiler('server') + + const code = ` + import { createServerFn, createServerOnlyFn } from '@tanstack/react-start' + + const createRandomNumber = createServerOnlyFn(() => Math.floor(Math.random() * 100)) + const randomNumber = createRandomNumber() + + export const personServerFn = createServerFn({ method: 'GET' }) + .handler(({ data: name }) => { + return { name, randomNumber } + }) + ` + + // Should NOT throw "createServerOnlyFn() must be called with a function!" + // The main file output is the split-file version (createServerFn splits the handler), + // so we just verify it compiles without error and produces valid output. + const result = await compiler.compile({ code, id: 'test-6643.ts' }) + expect(result).not.toBeNull() + // The output should contain the personServerFn export (with SSR RPC reference) + expect(result!.code).toContain('personServerFn') + }) + + test('invocation of createClientOnlyFn result is not treated as a candidate', async () => { + const compiler = createFullCompiler('client') + + const code = ` + import { createClientOnlyFn, createServerFn } from '@tanstack/react-start' + + const getWindowWidth = createClientOnlyFn(() => window.innerWidth) + const width = getWindowWidth() + + export const personServerFn = createServerFn({ method: 'GET' }) + .handler(({ data: name }) => { + return { name } + }) + ` + + const result = await compiler.compile({ code, id: 'test-6643-client.ts' }) + expect(result).not.toBeNull() + expect(result!.code).toContain('window.innerWidth') + expect(result!.code).toContain('getWindowWidth()') + }) + + test('re-exported createServerOnlyFn still resolves correctly', async () => { + // Ensure the fix doesn't break re-export chain resolution (issue #6583) + const virtualModules: Record = { + '@tanstack/start-client-core': ` + export { createServerOnlyFn } from '@tanstack/start-fn-stubs' + `, + } + + const compiler: StartCompiler = new StartCompiler({ + env: 'server', + envName: 'ssr', + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + lookupKinds: new Set(['ServerOnlyFn', 'ClientOnlyFn']), + lookupConfigurations: [], + getKnownServerFns: () => ({}), + loadModule: async (id) => { + const code = virtualModules[id] + if (code) { + compiler.ingestModule({ code, id }) + } + }, + resolveId: async (id) => { + return virtualModules[id] ? id : null + }, + }) + + const code = ` + import { createServerOnlyFn } from '@tanstack/start-client-core' + const myFn = createServerOnlyFn(() => 'server-only-value') + ` + + const result = await compiler.compile({ code, id: 'reexport-test.ts' }) + expect(result).not.toBeNull() + expect(result!.code).toContain('server-only-value') + }) + + test('aliased factory is still detected as a candidate', async () => { + // `const createSO = createServerOnlyFn` is an alias, not an invocation. + // `createSO(() => ...)` should still be treated as ServerOnlyFn. + const compiler = createFullCompiler('server') + + const code = ` + import { createServerOnlyFn } from '@tanstack/react-start' + + const createSO = createServerOnlyFn + const myFn = createSO(() => 'aliased-server-only') + ` + + const result = await compiler.compile({ code, id: 'alias-test.ts' }) + expect(result).not.toBeNull() + // The factory should be unwrapped on server env + expect(result!.code).toContain('aliased-server-only') + }) +}) + +describe('re-export chain resolution', () => { + // This tests the fix for https://github.com/TanStack/router/issues/6583 + // Third-party packages may import from @tanstack/start-client-core (which re-exports + // from @tanstack/start-fn-stubs) rather than directly from @tanstack/react-start. + // The compiler should correctly resolve these imports via the slow path. + + // Virtual module contents for simulating the re-export chain: + // @third-party/lib -> @tanstack/start-client-core -> @tanstack/start-fn-stubs + // + // Note: We don't need a virtual module for @tanstack/start-fn-stubs because + // init() hardcodes it in knownRootImports. When the slow path resolution reaches + // that package, it uses the fast path lookup and never needs to parse the module. + const virtualModules: Record = { + // The client-core package that re-exports from stubs + '@tanstack/start-client-core': ` + export { createIsomorphicFn, createServerOnlyFn, createClientOnlyFn } from '@tanstack/start-fn-stubs' + `, + // A third-party package that imports from start-client-core + '@third-party/lib': ` + import { createIsomorphicFn, createClientOnlyFn } from '@tanstack/start-client-core' + + export const getThemeData = createIsomorphicFn() + .client(() => 'client-theme') + .server(() => 'server-theme') + + export const initClientFeature = createClientOnlyFn(() => { + console.log('client only initialization') + return 'initialized' + }) + `, + } + + function createCompilerWithVirtualModules(env: 'client' | 'server') { + const envName = env === 'client' ? 'client' : 'ssr' + const lookupKinds: Set = new Set([ + 'IsomorphicFn', + 'ServerOnlyFn', + 'ClientOnlyFn', + ]) + + // Note: We use empty lookupConfigurations because this test is specifically + // testing the slow path resolution through re-export chains. The compiler + // should still work because @tanstack/start-fn-stubs is hardcoded in + // knownRootImports during init(). + const compiler: StartCompiler = new StartCompiler({ + env, + envName, + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + lookupKinds, + lookupConfigurations: [], + getKnownServerFns: () => ({}), + loadModule: async (id) => { + const code = virtualModules[id] + if (code) { + compiler.ingestModule({ code, id }) + } + }, + resolveId: async (id) => { + return virtualModules[id] ? id : null + }, + }) + + return compiler + } + + const testCases: Array<{ + env: 'client' | 'server' + fn: string + shouldContain: Array + shouldNotContain: Array + }> = [ + { + env: 'client', + fn: 'createIsomorphicFn', + shouldContain: ['client-theme'], + shouldNotContain: ['server-theme'], + }, + { + env: 'server', + fn: 'createIsomorphicFn', + shouldContain: ['server-theme'], + shouldNotContain: ['client-theme'], + }, + { + env: 'client', + fn: 'createClientOnlyFn', + shouldContain: ['client only initialization'], + shouldNotContain: [], + }, + { + env: 'server', + fn: 'createClientOnlyFn', + shouldContain: ['throw new Error'], + shouldNotContain: ['client only initialization'], + }, + ] + + test.each(testCases)( + 'resolves $fn via re-export chain on $env', + async ({ env, shouldContain, shouldNotContain }) => { + const compiler = createCompilerWithVirtualModules(env) + const code = virtualModules['@third-party/lib']! + + const result = await compiler.compile({ + code, + id: '@third-party/lib', + }) + + expect(result).not.toBeNull() + for (const str of shouldContain) { + expect(result!.code).toContain(str) + } + for (const str of shouldNotContain) { + expect(result!.code).not.toContain(str) + } + }, + ) + + test('handles deeper re-export chains', async () => { + // Add another level to the chain + const deeperVirtualModules: Record = { + ...virtualModules, + // Another intermediate package + '@another-intermediate/pkg': ` + export { createIsomorphicFn } from '@tanstack/start-client-core' + `, + '@deep-third-party/lib': ` + import { createIsomorphicFn } from '@another-intermediate/pkg' + export const deepFn = createIsomorphicFn() + .client(() => 'deep-client') + .server(() => 'deep-server') + `, + } + + const compiler: StartCompiler = new StartCompiler({ + env: 'client', + envName: 'client', + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + lookupKinds: new Set(['IsomorphicFn', 'ServerOnlyFn', 'ClientOnlyFn']), + lookupConfigurations: [], + getKnownServerFns: () => ({}), + loadModule: async (id) => { + const code = deeperVirtualModules[id] + if (code) { + compiler.ingestModule({ code, id }) + } + }, + resolveId: async (id) => { + return deeperVirtualModules[id] ? id : null + }, + }) + + const result = await compiler.compile({ + code: deeperVirtualModules['@deep-third-party/lib']!, + id: '@deep-third-party/lib', + }) + + expect(result).not.toBeNull() + expect(result!.code).toContain('deep-client') + expect(result!.code).not.toContain('deep-server') + }) + + test.each([ + { + name: 'named re-export cycle', + virtualModules: { + './factory-a': ` + export { createServerOnlyFn } from './factory-b' + `, + './factory-b': ` + export { createServerOnlyFn } from './factory-a' + `, + }, + }, + { + name: 'import alias cycle', + virtualModules: { + './factory-a': ` + import { createServerOnlyFn } from './factory-b' + export { createServerOnlyFn } + `, + './factory-b': ` + import { createServerOnlyFn } from './factory-a' + export { createServerOnlyFn } + `, + }, + }, + { + name: 'export-star cycle', + virtualModules: { + './factory-a': ` + export * from './factory-b' + `, + './factory-b': ` + export * from './factory-a' + `, + }, + }, + ])('handles circular import chain: $name', async ({ virtualModules }) => { + const compiler: StartCompiler = new StartCompiler({ + env: 'server', + envName: 'ssr', + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + lookupKinds: new Set(['ServerOnlyFn']), + lookupConfigurations: [], + getKnownServerFns: () => ({}), + loadModule: async (id) => { + const code = virtualModules[id as keyof typeof virtualModules] + if (code) { + compiler.ingestModule({ code, id }) + } + }, + resolveId: async (id) => { + return id in virtualModules ? id : null + }, + mode: 'build', + }) + + const result = await compiler.compile({ + id: 'circular-import-test.ts', + code: ` + import { createServerOnlyFn } from './factory-a' + const myFn = createServerOnlyFn(() => 'server-only-value') + `, + }) + + expect(result).toBeNull() + }) + + test('ingestModule populates module metadata for later resolution', async () => { + const compiler: StartCompiler = new StartCompiler({ + env: 'server', + envName: 'ssr', + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + lookupKinds: new Set(['ServerOnlyFn']), + lookupConfigurations: [], + getKnownServerFns: () => ({}), + loadModule: async () => {}, + resolveId: async (id) => { + return id === '@tanstack/start-client-core' ? id : null + }, + mode: 'build', + }) + + compiler.ingestModule({ + id: '@tanstack/start-client-core', + code: ` + export { createServerOnlyFn } from '@tanstack/start-fn-stubs' + `, + }) + + const result = await compiler.compile({ + id: 'cached-module-test.ts', + code: ` + import { createServerOnlyFn } from '@tanstack/start-client-core' + const myFn = createServerOnlyFn(() => 'cached-server-only-value') + `, + }) + + expect(result).not.toBeNull() + expect(result!.code).toContain('cached-server-only-value') + }) + + test('invalidateModule clears cached module resolution state', async () => { + const virtualModules: Record = { + './factory': ` + export { createServerOnlyFn } from './factory-inner' + `, + './factory-inner': ` + export { createServerOnlyFn } from '@tanstack/start-fn-stubs' + `, + } + + const compiler: StartCompiler = new StartCompiler({ + env: 'server', + envName: 'ssr', + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + lookupKinds: new Set(['ServerOnlyFn', 'ClientOnlyFn']), + lookupConfigurations: [], + getKnownServerFns: () => ({}), + loadModule: async (id) => { + const code = virtualModules[id] + if (code) { + compiler.ingestModule({ code, id }) + } + }, + resolveId: async (id) => { + return virtualModules[id] ? id : null + }, + mode: 'build', + }) + + const source = ` + import { createServerOnlyFn } from './factory' + const myFn = createServerOnlyFn(() => 'server-only-value') + ` + + const initialResult = await compiler.compile({ + id: 'transitive-invalidation-test.ts', + code: source, + }) + + expect(initialResult).not.toBeNull() + expect(initialResult!.code).toContain('server-only-value') + expect(initialResult!.code).not.toContain('throw new Error') + + virtualModules['./factory-inner'] = ` + export { createClientOnlyFn as createServerOnlyFn } from '@tanstack/start-fn-stubs' + ` + + expect(compiler.invalidateModule('./factory-inner')).toBe(true) + + const updatedResult = await compiler.compile({ + id: 'transitive-invalidation-test.ts', + code: source, + }) + + expect(updatedResult).not.toBeNull() + expect(updatedResult!.code).toContain('throw new Error') + expect(updatedResult!.code).not.toContain('server-only-value') + }) + + test('invalidateModule preserves root lookup metadata while clearing importer memoization', async () => { + const virtualModules: Record = { + './factory': ` + export { createServerOnlyFn } from './factory-inner' + `, + './factory-inner': ` + export { createServerOnlyFn } from '@tanstack/start-fn-stubs' + `, + } + + const compiler: StartCompiler = new StartCompiler({ + env: 'server', + envName: 'ssr', + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + lookupKinds: new Set(['ServerOnlyFn', 'ClientOnlyFn']), + lookupConfigurations: [ + { + libName: '@tanstack/react-start', + rootExport: 'createServerOnlyFn', + kind: 'ServerOnlyFn', + }, + { + libName: '@tanstack/react-start', + rootExport: 'createClientOnlyFn', + kind: 'ClientOnlyFn', + }, + ], + getKnownServerFns: () => ({}), + loadModule: async (id) => { + const code = virtualModules[id] + if (code) { + compiler.ingestModule({ code, id }) + } + }, + resolveId: async (id) => { + return virtualModules[id] ? id : null + }, + }) + + const source = ` + import { createServerOnlyFn } from './factory' + const myFn = createServerOnlyFn(() => 'server-only-value') + ` + + const initialResult = await compiler.compile({ + id: 'memoized-invalidation-test.ts', + code: source, + }) + + expect(initialResult).not.toBeNull() + expect(initialResult!.code).toContain('server-only-value') + + virtualModules['./factory-inner'] = ` + export { createClientOnlyFn as createServerOnlyFn } from '@tanstack/start-fn-stubs' + ` + + expect(compiler.invalidateModule('./factory-inner')).toBe(true) + + const updatedResult = await compiler.compile({ + id: 'memoized-invalidation-test.ts', + code: source, + }) + + expect(updatedResult).not.toBeNull() + expect(updatedResult!.code).toContain('throw new Error') + expect(updatedResult!.code).not.toContain('server-only-value') + }) + + test('recompiles aliased env-only direct calls when only server function syntax is detected', async () => { + const virtualModules: Record = { + './factory': ` + export { createServerOnlyFn } from '@tanstack/start-fn-stubs' + `, + } + + const compiler: StartCompiler = new StartCompiler({ + env: 'server', + envName: 'ssr', + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + mode: 'build', + lookupKinds: new Set(['ServerFn', 'ServerOnlyFn', 'ClientOnlyFn']), + lookupConfigurations: [ + { + libName: '@tanstack/react-start', + rootExport: 'createServerFn', + kind: 'Root', + }, + ], + getKnownServerFns: () => ({}), + loadModule: async (id) => { + const code = virtualModules[id] + if (code) { + compiler.ingestModule({ code, id }) + } + }, + resolveId: async (id) => { + return virtualModules[id] ? id : null + }, + }) + + const source = ` + import { createServerFn } from '@tanstack/react-start' + import { createServerOnlyFn as createServerFnHmrFactory } from './factory' + + const serverOnlyImpl = createServerFnHmrFactory(() => 'server-only-value') + + export const serverFn = createServerFn().handler(async () => { + return serverOnlyImpl() + }) + ` + + const providerId = 'aliased-env-only-server-fn.ts?tss-serverfn-split' + + const initialResult = await compiler.compile({ + id: providerId, + code: source, + detectedKinds: new Set(['ServerFn']), + }) + + expect(initialResult).not.toBeNull() + expect(initialResult!.code).toContain('server-only-value') + expect(initialResult!.code).not.toContain('throw new Error') + + virtualModules['./factory'] = ` + export { createClientOnlyFn as createServerOnlyFn } from '@tanstack/start-fn-stubs' + ` + + expect(compiler.invalidateModule('./factory')).toBe(true) + + const updatedResult = await compiler.compile({ + id: providerId, + code: source, + detectedKinds: new Set(['ServerFn']), + }) + + expect(updatedResult).not.toBeNull() + expect(updatedResult!.code).toContain('throw new Error') + expect(updatedResult!.code).not.toContain('server-only-value') + }) +}) + +test('leaves unrelated SSR middleware chains to the bundler when a server function factory is present', async () => { + const compiler = new StartCompiler({ + ...getDefaultTestOptions('server'), + env: 'server', + mode: 'build', + lookupKinds: getLookupKindsForEnv('server'), + lookupConfigurations: getLookupConfigurationsForEnv('server', 'react'), + getKnownServerFns: () => ({}), + resolveId: async () => { + throw new Error( + 'SSR host has no package import conditions for this unrelated binding', + ) + }, + loadModule: async () => { + throw new Error('Unexpected compiler dependency load') + }, + }) + const code = `import { createMiddleware, createServerFn } from '@tanstack/react-start'; +const middleware = createMiddleware({ type: 'function' }).server(({ next }) => next({ context: { role: 'admin' } })); +export const factory = createServerFn().middleware([middleware]);` + await expect( + compiler.compile({ + id: '/test/auth-wrapper.ts', + code, + detectedKinds: detectKindsInCode(code, 'server'), + }), + ).resolves.toBeNull() +}) + +describe.each(['build', 'dev'] as const)( + 'top-level member calls in %s mode', + (mode) => { + function createCompilerWithModules( + env: 'client' | 'server', + virtualModules: Record, + ) { + const resolved: Array = [] + const loaded: Array = [] + const compiler: StartCompiler = new StartCompiler({ + ...getDefaultTestOptions(env), + env, + mode, + devServerFnModuleSpecifierEncoder: ({ extractedFilename, root }) => + `/@id${extractedFilename.slice(root.length)}`, + lookupKinds: getLookupKindsForEnv(env), + lookupConfigurations: getLookupConfigurationsForEnv(env, 'react'), + getKnownServerFns: () => ({}), + resolveId: async (id) => { + resolved.push(id) + return id in virtualModules ? id : null + }, + loadModule: async (id) => { + loaded.push(id) + const code = virtualModules[id] + if (code) { + compiler.ingestModule({ code, id }) + } + }, + }) + return { compiler, resolved, loaded } + } + + describe.each(['fast', 'full'] as const)('%s traversal', (traversal) => { + // An isomorphic function requires full traversal; server functions alone + // use the compiler's fast path. Let normal code detection choose the path. + const traversalCode = + traversal === 'full' + ? `import { createIsomorphicFn } from '@tanstack/react-start' + export const iso = createIsomorphicFn().client(() => 'client').server(() => 'server')` + : '' + + test.each(['client', 'ssr', 'provider'] as const)( + 'does not resolve or load named-import receivers in %s output', + async (output) => { + const env = output === 'client' ? 'client' : 'server' + const { compiler, resolved, loaded } = createCompilerWithModules( + env, + { + zod: `export const z = { object: (shape) => shape, string: () => ({}) }`, + './api': `export const api = { users: () => [] }`, + }, + ) + const code = ` + ${traversalCode} + import { createServerFn } from '@tanstack/react-start' + import { z } from 'zod' + import { api } from './api' + + const Input = z.object({ id: z.string() }) + const users = api.users() + + export const getUser = createServerFn() + .validator(Input) + .handler(async ({ data }) => ({ id: data.id, users })) + ` + + const result = await compiler.compile({ + id: + '/test/get-user.ts' + + (output === 'provider' ? '?tss-serverfn-split' : ''), + code, + detectedKinds: detectKindsInCode(code, env), + }) + + expect(result).not.toBeNull() + const rpc = { + client: 'createClientRpc', + ssr: 'createSsrRpc', + provider: 'createServerRpc', + } + expect(result!.code).toContain(rpc[output]) + expect(resolved).toEqual([]) + expect(loaded).toEqual([]) + }, + ) + + test.each(['client', 'server'] as const)( + 'still compiles a renamed env-only factory called through a namespace import on %s', + async (env) => { + const { compiler } = createCompilerWithModules(env, { + './factory': `export { createServerOnlyFn as serverOnly } from '@tanstack/start-fn-stubs'`, + }) + const code = ` + ${traversalCode} + import { createServerFn } from '@tanstack/react-start' + import * as factory from './factory' + + export const impl = factory.serverOnly(() => 'server-only-value') + + export const fn = createServerFn().handler(async () => impl()) + ` + + const result = await compiler.compile({ + id: '/test/namespace-factory.ts', + code, + detectedKinds: detectKindsInCode(code, env), + }) + + expect(result).not.toBeNull() + if (env === 'server') { + expect(result!.code).toContain('server-only-value') + expect(result!.code).not.toContain('factory.serverOnly') + } else { + expect(result!.code).not.toContain('server-only-value') + expect(result!.code).toContain('throw new Error') + } + }, + ) + }) + }, +) + +test.each([ + `(createServerOnlyFn)(() => 'server-value')`, + `(createIsomorphicFn)().server(() => 'server-value').client(() => 'client-value')`, + `(createIsomorphicFn().server(() => 'server-value')).client(() => 'client-value')`, +])( + 'compiles transparent parentheses around native call chains: %s', + async (expression) => { + const compiler = createFullCompiler('server') + const result = await compiler.compile({ + id: '/test/parenthesized.ts', + code: `import { createServerOnlyFn, createIsomorphicFn } from '@tanstack/react-start'; export const fn = ${expression}`, + }) + + expect(result).not.toBeNull() + const evaluate = new Function( + `${result!.code.replace(/^import .+;$/gm, '').replace(/\bexport (?=const)/g, '')}\nreturn fn`, + ) + expect(evaluate()()).toBe('server-value') + }, +) + +test('compiles a server function through a parenthesized namespace receiver', async () => { + const compiler = createFullCompiler('client') + const result = await compiler.compile({ + id: '/test/namespace-parenthesized.ts', + code: `import * as Start from '@tanstack/react-start'; export const fn = (Start).createServerFn().handler(() => 'private-server-body')`, + }) + expect(result).not.toBeNull() + expect(result!.code).not.toContain('private-server-body') + expect(result!.code).toContain('createClientRpc') +}) + +// The compiler currently mistakes the local parameter for the namespace import. +// Keep the intended behavior executable until binding resolution is corrected. +test.fails( + 'preserves a shadowed parenthesized namespace receiver', + async () => { + const compiler = createFullCompiler('client') + const code = `import * as Start from '@tanstack/react-start'; export function fn(Start) { return (Start).createServerFn().handler(() => 'local-runtime-body') }` + const result = await compiler.compile({ + id: '/test/shadowed-namespace.ts', + code, + }) + const output = result?.code ?? code + expect(output).toContain('local-runtime-body') + expect(output).not.toContain('createClientRpc') + }, +) + +test.each([ + `(Start).createServerOnlyFn(() => 'private-server-body')`, + `(Start).createIsomorphicFn().server(() => 'private-server-body').client(() => 'client-value')`, + `(Start).createMiddleware().server(() => 'private-server-body')`, +])( + 'removes server-only code through a parenthesized namespace: %s', + async (expression) => { + const compiler = createFullCompiler('client') + const result = await compiler.compile({ + id: '/test/namespace-builtins.ts', + code: `import * as Start from '@tanstack/react-start'; export const fn = ${expression}`, + }) + expect(result).not.toBeNull() + expect(result!.code).not.toContain('private-server-body') + }, +) diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/createIsomorphicFn.test.ts b/packages/start-plugin-core/tests/createIsomorphicFn/createIsomorphicFn.test.ts index ef65d23d0d..0b6a5aa26a 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/createIsomorphicFn.test.ts +++ b/packages/start-plugin-core/tests/createIsomorphicFn/createIsomorphicFn.test.ts @@ -1,32 +1,57 @@ import { readFile, readdir } from 'node:fs/promises' import path from 'node:path' -import { afterAll, describe, expect, test, vi } from 'vitest' +import { describe, expect, test } from 'vitest' -import { compileStartOutputFactory } from '../../src/start-compiler-plugin/compilers' +import { StartCompiler } from '../../src/start-compiler/compiler' +import { formatSnapshot } from '../format-snapshot' -const compileStartOutput = compileStartOutputFactory('react') +// Default test options for StartCompiler +function getDefaultTestOptions(env: 'client' | 'server') { + const envName = env === 'client' ? 'client' : 'ssr' + return { + envName, + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + } +} + +async function compile(opts: { + env: 'client' | 'server' + code: string + id: string +}) { + const compiler = new StartCompiler({ + ...opts, + ...getDefaultTestOptions(opts.env), + loadModule: async () => { + // do nothing in test + }, + lookupKinds: new Set(['IsomorphicFn']), + lookupConfigurations: [ + { + libName: `@tanstack/react-start`, + rootExport: 'createIsomorphicFn', + kind: 'IsomorphicFn', + }, + ], + getKnownServerFns: () => ({}), + resolveId: async (id) => { + return id + }, + }) + const result = await compiler.compile({ + code: opts.code, + id: opts.id, + }) + return result +} async function getFilenames() { return await readdir(path.resolve(import.meta.dirname, './test-files')) } describe('createIsomorphicFn compiles correctly', async () => { - const noImplWarning = - 'createIsomorphicFn called without a client or server implementation!' - - const originalConsoleWarn = console.warn - const consoleSpy = vi.spyOn(console, 'warn').mockImplementation((...args) => { - // we want to avoid sending this warning to the console, we know about it - if (args[0] === noImplWarning) { - return - } - originalConsoleWarn(...args) - }) - - afterAll(() => { - consoleSpy.mockRestore() - }) - const filenames = await getFilenames() describe.each(filenames)('should handle "%s"', async (filename) => { @@ -38,55 +63,38 @@ describe('createIsomorphicFn compiles correctly', async () => { test.each(['client', 'server'] as const)( `should compile for ${filename} %s`, async (env) => { - const compiledResult = compileStartOutput({ + const compiledResult = await compile({ env, code, - filename, - dce: false, + id: filename, }) - await expect(compiledResult.code).toMatchFileSnapshot( - `./snapshots/${env}/${filename}`, - ) + await expect( + await formatSnapshot(compiledResult!.code, filename), + ).toMatchFileSnapshot(`./snapshots/${env}/${filename}`) }, ) }) - test('should error if implementation not provided', () => { - expect(() => { - compileStartOutput({ + + test('should error if implementation not provided', async () => { + await expect( + compile({ env: 'client', code: ` import { createIsomorphicFn } from '@tanstack/react-start' const clientOnly = createIsomorphicFn().client()`, - filename: 'no-fn.ts', - dce: false, - }) - }).toThrowError() - expect(() => { - compileStartOutput({ + id: 'no-fn.ts', + }), + ).rejects.toThrowError() + + await expect( + compile({ env: 'server', code: ` import { createIsomorphicFn } from '@tanstack/react-start' const serverOnly = createIsomorphicFn().server()`, - filename: 'no-fn.ts', - dce: false, - }) - }).toThrowError() - }) - test('should warn to console if no implementations provided', () => { - compileStartOutput({ - env: 'client', - code: ` - import { createIsomorphicFn } from '@tanstack/react-start' - const noImpl = createIsomorphicFn()`, - filename: 'no-fn.ts', - dce: false, - }) - expect(consoleSpy).toHaveBeenCalledWith( - noImplWarning, - 'This will result in a no-op function.', - 'Variable name:', - 'noImpl', - ) + id: 'no-fn.ts', + }), + ).rejects.toThrowError() }) }) diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/call-at-module-level.ts b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/call-at-module-level.ts new file mode 100644 index 0000000000..7e8ade3201 --- /dev/null +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/call-at-module-level.ts @@ -0,0 +1,5 @@ +const getEnvironment = () => { + console.log('[CLIENT] getEnvironment called') + return 'client' +} +const moduleLevel = getEnvironment() diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx index 837195fb9c..20fbb3d4dc 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructured.tsx @@ -1,16 +1,13 @@ -import { createIsomorphicFn } from '@tanstack/react-start'; -const noImpl = () => {}; -const serverOnlyFn = () => {}; -const clientOnlyFn = () => 'client'; -const serverThenClientFn = () => 'client'; -const clientThenServerFn = () => 'client'; -function abstractedServerFn() { - return 'server'; -} -const serverOnlyFnAbstracted = () => {}; +import { createIsomorphicFn } from '@tanstack/react-start' +const noImpl = createIsomorphicFn() +const serverOnlyFn = () => {} +const clientOnlyFn = () => 'client' +const serverThenClientFn = () => 'client' +const clientThenServerFn = () => 'client' +const serverOnlyFnAbstracted = () => {} function abstractedClientFn() { - return 'client'; + return 'client' } -const clientOnlyFnAbstracted = abstractedClientFn; -const serverThenClientFnAbstracted = abstractedClientFn; -const clientThenServerFnAbstracted = abstractedClientFn; \ No newline at end of file +const clientOnlyFnAbstracted = abstractedClientFn +const serverThenClientFnAbstracted = abstractedClientFn +const clientThenServerFnAbstracted = abstractedClientFn diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx index 4f0230416d..d8f76d94b0 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnDestructuredRename.tsx @@ -1,16 +1,13 @@ -import { createIsomorphicFn as isomorphicFn } from '@tanstack/react-start'; -const noImpl = () => {}; -const serverOnlyFn = () => {}; -const clientOnlyFn = () => 'client'; -const serverThenClientFn = () => 'client'; -const clientThenServerFn = () => 'client'; -function abstractedServerFn() { - return 'server'; -} -const serverOnlyFnAbstracted = () => {}; +import { createIsomorphicFn as isomorphicFn } from '@tanstack/react-start' +const noImpl = isomorphicFn() +const serverOnlyFn = () => {} +const clientOnlyFn = () => 'client' +const serverThenClientFn = () => 'client' +const clientThenServerFn = () => 'client' +const serverOnlyFnAbstracted = () => {} function abstractedClientFn() { - return 'client'; + return 'client' } -const clientOnlyFnAbstracted = abstractedClientFn; -const serverThenClientFnAbstracted = abstractedClientFn; -const clientThenServerFnAbstracted = abstractedClientFn; \ No newline at end of file +const clientOnlyFnAbstracted = abstractedClientFn +const serverThenClientFnAbstracted = abstractedClientFn +const clientThenServerFnAbstracted = abstractedClientFn diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnFactory.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnFactory.tsx new file mode 100644 index 0000000000..08772a9178 --- /dev/null +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnFactory.tsx @@ -0,0 +1,22 @@ +import { createIsomorphicFn } from '@tanstack/react-start' +// Isomorphic function factory - returns a createIsomorphicFn with .client() and .server() calls +export function createPlatformFn(platform: string) { + return () => `client-${platform}` +} +// Arrow function factory with only server implementation +export const createServerImplFn = (name: string) => { + return () => {} +} +// Arrow function factory with only client implementation +export const createClientImplFn = (name: string) => { + return () => { + console.log(`Client: ${name}`) + return `client-${name}` + } +} +// Factory returning no-implementation isomorphic fn +export function createNoImplFn() { + return createIsomorphicFn() +} +// Top-level isomorphic fn for comparison +export const topLevelIsomorphicFn = () => 'client' diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnInline.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnInline.tsx new file mode 100644 index 0000000000..28930701bd --- /dev/null +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnInline.tsx @@ -0,0 +1,33 @@ +// Create and immediately invoke isomorphic fn inside a function +export function getPlatformValue() { + const fn = () => 'client-value' + return fn() +} +// Arrow function that creates and invokes isomorphic fn +export const getEnvironment = () => { + const envFn = () => 'running on client' + return envFn() +} +// Create isomorphic fn inline without assigning to variable +export function getDirectValue() { + return (() => 'direct-client')() +} +// Multiple isomorphic fns created and used in same function +export function getMultipleValues() { + const first = () => 'first-client' + const second = () => 'second-client' + return { first: first(), second: second() } +} +// Isomorphic fn with server-only implementation used inline +export function getServerOnlyValue() { + const fn = () => {} + return fn() +} +// Isomorphic fn with client-only implementation used inline +export function getClientOnlyValue() { + const fn = () => { + console.log('client side effect') + return 'client-only-value' + } + return fn() +} diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx index 296ccdbe24..f8604d9723 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/client/createIsomorphicFnStarImport.tsx @@ -1,16 +1,13 @@ -import * as TanStackStart from '@tanstack/react-start'; -const noImpl = () => {}; -const serverOnlyFn = () => {}; -const clientOnlyFn = () => 'client'; -const serverThenClientFn = () => 'client'; -const clientThenServerFn = () => 'client'; -function abstractedServerFn() { - return 'server'; -} -const serverOnlyFnAbstracted = () => {}; +import * as TanStackStart from '@tanstack/react-start' +const noImpl = TanStackStart.createIsomorphicFn() +const serverOnlyFn = () => {} +const clientOnlyFn = () => 'client' +const serverThenClientFn = () => 'client' +const clientThenServerFn = () => 'client' +const serverOnlyFnAbstracted = () => {} function abstractedClientFn() { - return 'client'; + return 'client' } -const clientOnlyFnAbstracted = abstractedClientFn; -const serverThenClientFnAbstracted = abstractedClientFn; -const clientThenServerFnAbstracted = abstractedClientFn; \ No newline at end of file +const clientOnlyFnAbstracted = abstractedClientFn +const serverThenClientFnAbstracted = abstractedClientFn +const clientThenServerFnAbstracted = abstractedClientFn diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/call-at-module-level.ts b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/call-at-module-level.ts new file mode 100644 index 0000000000..66c327f562 --- /dev/null +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/call-at-module-level.ts @@ -0,0 +1,5 @@ +const getEnvironment = () => { + console.log('[SERVER] getEnvironment called') + return 'server' +} +const moduleLevel = getEnvironment() diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx index 1656889e53..ee54120ca1 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructured.tsx @@ -1,16 +1,13 @@ -import { createIsomorphicFn } from '@tanstack/react-start'; -const noImpl = () => {}; -const serverOnlyFn = () => 'server'; -const clientOnlyFn = () => {}; -const serverThenClientFn = () => 'server'; -const clientThenServerFn = () => 'server'; +import { createIsomorphicFn } from '@tanstack/react-start' +const noImpl = createIsomorphicFn() +const serverOnlyFn = () => 'server' +const clientOnlyFn = () => {} +const serverThenClientFn = () => 'server' +const clientThenServerFn = () => 'server' function abstractedServerFn() { - return 'server'; + return 'server' } -const serverOnlyFnAbstracted = abstractedServerFn; -function abstractedClientFn() { - return 'client'; -} -const clientOnlyFnAbstracted = () => {}; -const serverThenClientFnAbstracted = abstractedServerFn; -const clientThenServerFnAbstracted = abstractedServerFn; \ No newline at end of file +const serverOnlyFnAbstracted = abstractedServerFn +const clientOnlyFnAbstracted = () => {} +const serverThenClientFnAbstracted = abstractedServerFn +const clientThenServerFnAbstracted = abstractedServerFn diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx index a46f061a45..11289136e9 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnDestructuredRename.tsx @@ -1,16 +1,13 @@ -import { createIsomorphicFn as isomorphicFn } from '@tanstack/react-start'; -const noImpl = () => {}; -const serverOnlyFn = () => 'server'; -const clientOnlyFn = () => {}; -const serverThenClientFn = () => 'server'; -const clientThenServerFn = () => 'server'; +import { createIsomorphicFn as isomorphicFn } from '@tanstack/react-start' +const noImpl = isomorphicFn() +const serverOnlyFn = () => 'server' +const clientOnlyFn = () => {} +const serverThenClientFn = () => 'server' +const clientThenServerFn = () => 'server' function abstractedServerFn() { - return 'server'; + return 'server' } -const serverOnlyFnAbstracted = abstractedServerFn; -function abstractedClientFn() { - return 'client'; -} -const clientOnlyFnAbstracted = () => {}; -const serverThenClientFnAbstracted = abstractedServerFn; -const clientThenServerFnAbstracted = abstractedServerFn; \ No newline at end of file +const serverOnlyFnAbstracted = abstractedServerFn +const clientOnlyFnAbstracted = () => {} +const serverThenClientFnAbstracted = abstractedServerFn +const clientThenServerFnAbstracted = abstractedServerFn diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnFactory.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnFactory.tsx new file mode 100644 index 0000000000..c1ec1e79f5 --- /dev/null +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnFactory.tsx @@ -0,0 +1,22 @@ +import { createIsomorphicFn } from '@tanstack/react-start' +// Isomorphic function factory - returns a createIsomorphicFn with .client() and .server() calls +export function createPlatformFn(platform: string) { + return () => `server-${platform}` +} +// Arrow function factory with only server implementation +export const createServerImplFn = (name: string) => { + return () => { + console.log(`Server: ${name}`) + return `server-${name}` + } +} +// Arrow function factory with only client implementation +export const createClientImplFn = (name: string) => { + return () => {} +} +// Factory returning no-implementation isomorphic fn +export function createNoImplFn() { + return createIsomorphicFn() +} +// Top-level isomorphic fn for comparison +export const topLevelIsomorphicFn = () => 'server' diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnInline.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnInline.tsx new file mode 100644 index 0000000000..c2b0d07284 --- /dev/null +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnInline.tsx @@ -0,0 +1,33 @@ +// Create and immediately invoke isomorphic fn inside a function +export function getPlatformValue() { + const fn = () => 'server-value' + return fn() +} +// Arrow function that creates and invokes isomorphic fn +export const getEnvironment = () => { + const envFn = () => 'running on server' + return envFn() +} +// Create isomorphic fn inline without assigning to variable +export function getDirectValue() { + return (() => 'direct-server')() +} +// Multiple isomorphic fns created and used in same function +export function getMultipleValues() { + const first = () => 'first-server' + const second = () => 'second-server' + return { first: first(), second: second() } +} +// Isomorphic fn with server-only implementation used inline +export function getServerOnlyValue() { + const fn = () => { + console.log('server side effect') + return 'server-only-value' + } + return fn() +} +// Isomorphic fn with client-only implementation used inline +export function getClientOnlyValue() { + const fn = () => {} + return fn() +} diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx index dc3ad9af04..6a1c429167 100644 --- a/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx +++ b/packages/start-plugin-core/tests/createIsomorphicFn/snapshots/server/createIsomorphicFnStarImport.tsx @@ -1,16 +1,13 @@ -import * as TanStackStart from '@tanstack/react-start'; -const noImpl = () => {}; -const serverOnlyFn = () => 'server'; -const clientOnlyFn = () => {}; -const serverThenClientFn = () => 'server'; -const clientThenServerFn = () => 'server'; +import * as TanStackStart from '@tanstack/react-start' +const noImpl = TanStackStart.createIsomorphicFn() +const serverOnlyFn = () => 'server' +const clientOnlyFn = () => {} +const serverThenClientFn = () => 'server' +const clientThenServerFn = () => 'server' function abstractedServerFn() { - return 'server'; + return 'server' } -const serverOnlyFnAbstracted = abstractedServerFn; -function abstractedClientFn() { - return 'client'; -} -const clientOnlyFnAbstracted = () => {}; -const serverThenClientFnAbstracted = abstractedServerFn; -const clientThenServerFnAbstracted = abstractedServerFn; \ No newline at end of file +const serverOnlyFnAbstracted = abstractedServerFn +const clientOnlyFnAbstracted = () => {} +const serverThenClientFnAbstracted = abstractedServerFn +const clientThenServerFnAbstracted = abstractedServerFn diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/test-files/call-at-module-level.ts b/packages/start-plugin-core/tests/createIsomorphicFn/test-files/call-at-module-level.ts new file mode 100644 index 0000000000..ee017d7f59 --- /dev/null +++ b/packages/start-plugin-core/tests/createIsomorphicFn/test-files/call-at-module-level.ts @@ -0,0 +1,13 @@ +import { createIsomorphicFn } from '@tanstack/react-start' + +const getEnvironment = createIsomorphicFn() + .server(() => { + console.log('[SERVER] getEnvironment called') + return 'server' + }) + .client(() => { + console.log('[CLIENT] getEnvironment called') + return 'client' + }) + +const moduleLevel = getEnvironment() diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/test-files/createIsomorphicFnFactory.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/test-files/createIsomorphicFnFactory.tsx new file mode 100644 index 0000000000..3974ce77f0 --- /dev/null +++ b/packages/start-plugin-core/tests/createIsomorphicFn/test-files/createIsomorphicFnFactory.tsx @@ -0,0 +1,34 @@ +import { createIsomorphicFn } from '@tanstack/react-start' + +// Isomorphic function factory - returns a createIsomorphicFn with .client() and .server() calls +export function createPlatformFn(platform: string) { + return createIsomorphicFn() + .client(() => `client-${platform}`) + .server(() => `server-${platform}`) +} + +// Arrow function factory with only server implementation +export const createServerImplFn = (name: string) => { + return createIsomorphicFn().server(() => { + console.log(`Server: ${name}`) + return `server-${name}` + }) +} + +// Arrow function factory with only client implementation +export const createClientImplFn = (name: string) => { + return createIsomorphicFn().client(() => { + console.log(`Client: ${name}`) + return `client-${name}` + }) +} + +// Factory returning no-implementation isomorphic fn +export function createNoImplFn() { + return createIsomorphicFn() +} + +// Top-level isomorphic fn for comparison +export const topLevelIsomorphicFn = createIsomorphicFn() + .client(() => 'client') + .server(() => 'server') diff --git a/packages/start-plugin-core/tests/createIsomorphicFn/test-files/createIsomorphicFnInline.tsx b/packages/start-plugin-core/tests/createIsomorphicFn/test-files/createIsomorphicFnInline.tsx new file mode 100644 index 0000000000..1b4145bf9c --- /dev/null +++ b/packages/start-plugin-core/tests/createIsomorphicFn/test-files/createIsomorphicFnInline.tsx @@ -0,0 +1,55 @@ +import { createIsomorphicFn } from '@tanstack/react-start' + +// Create and immediately invoke isomorphic fn inside a function +export function getPlatformValue() { + const fn = createIsomorphicFn() + .client(() => 'client-value') + .server(() => 'server-value') + return fn() +} + +// Arrow function that creates and invokes isomorphic fn +export const getEnvironment = () => { + const envFn = createIsomorphicFn() + .server(() => 'running on server') + .client(() => 'running on client') + return envFn() +} + +// Create isomorphic fn inline without assigning to variable +export function getDirectValue() { + return createIsomorphicFn() + .client(() => 'direct-client') + .server(() => 'direct-server')() +} + +// Multiple isomorphic fns created and used in same function +export function getMultipleValues() { + const first = createIsomorphicFn() + .client(() => 'first-client') + .server(() => 'first-server') + + const second = createIsomorphicFn() + .client(() => 'second-client') + .server(() => 'second-server') + + return { first: first(), second: second() } +} + +// Isomorphic fn with server-only implementation used inline +export function getServerOnlyValue() { + const fn = createIsomorphicFn().server(() => { + console.log('server side effect') + return 'server-only-value' + }) + return fn() +} + +// Isomorphic fn with client-only implementation used inline +export function getClientOnlyValue() { + const fn = createIsomorphicFn().client(() => { + console.log('client side effect') + return 'client-only-value' + }) + return fn() +} diff --git a/packages/start-plugin-core/tests/createMiddleware-create-server-fn-plugin/createMiddleware.test.ts b/packages/start-plugin-core/tests/createMiddleware-create-server-fn-plugin/createMiddleware.test.ts deleted file mode 100644 index 088ff31281..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-create-server-fn-plugin/createMiddleware.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { readFile, readdir } from 'node:fs/promises' -import path from 'node:path' -import { describe, expect, test } from 'vitest' -import { ServerFnCompiler } from '../../src/create-server-fn-plugin/compiler' - -async function getFilenames() { - return await readdir(path.resolve(import.meta.dirname, './test-files')) -} - -async function compile(opts: { - env: 'client' | 'server' - code: string - id: string -}) { - const compiler = new ServerFnCompiler({ - ...opts, - loadModule: async (id) => { - // do nothing in test - }, - lookupKinds: new Set(['Middleware']), - lookupConfigurations: [ - { - libName: `@tanstack/react-start`, - rootExport: 'createMiddleware', - }, - { - libName: `@tanstack/react-start`, - rootExport: 'createStart', - }, - ], - resolveId: async (id) => { - return id - }, - directive: 'use server', - }) - const result = await compiler.compile({ code: opts.code, id: opts.id }) - return result -} - -describe('createMiddleware compiles correctly', async () => { - const filenames = await getFilenames() - - describe.each(filenames)('should handle "%s"', async (filename) => { - const file = await readFile( - path.resolve(import.meta.dirname, `./test-files/${filename}`), - ) - const code = file.toString() - - test.each(['client', 'server'] as const)( - `should compile for ${filename} %s`, - async (env) => { - const result = await compile({ env, code, id: filename }) - - await expect(result!.code).toMatchFileSnapshot( - `./snapshots/${env}/${filename}`, - ) - }, - ) - }) -}) diff --git a/packages/start-plugin-core/tests/createMiddleware-create-server-fn-plugin/snapshots/client/createStart.tsx b/packages/start-plugin-core/tests/createMiddleware-create-server-fn-plugin/snapshots/client/createStart.tsx deleted file mode 100644 index 8c3a7fc205..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-create-server-fn-plugin/snapshots/client/createStart.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { createStart } from '@tanstack/react-start'; -export const startInstance = createStart(() => {}); -export const serverFnMw = startInstance.createMiddleware({ - type: 'function' -}).client(({ - next -}) => { - console.log('client mw'); - return next(); -}); -export const requestMw = startInstance.createMiddleware({ - type: 'request' -}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-create-server-fn-plugin/snapshots/server/createStart.tsx b/packages/start-plugin-core/tests/createMiddleware-create-server-fn-plugin/snapshots/server/createStart.tsx deleted file mode 100644 index 3d8e28ea5a..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-create-server-fn-plugin/snapshots/server/createStart.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import { createStart } from '@tanstack/react-start'; -export const startInstance = createStart(() => {}); -export const serverFnMw = startInstance.createMiddleware({ - type: 'function' -}).server(({ - next -}) => { - console.log('server mw'); - return next({ - context: { - admin: 'admin' - } - }); -}).client(({ - next -}) => { - console.log('client mw'); - return next(); -}); -export const requestMw = startInstance.createMiddleware({ - type: 'request' -}).server(({ - next -}) => { - return next({ - context: { - requestMw: 'yes' - } - }); -}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/createMiddleware.test.ts b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/createMiddleware.test.ts deleted file mode 100644 index b1c2cb3c41..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/createMiddleware.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { readFile, readdir } from 'node:fs/promises' -import path from 'node:path' -import { describe, expect, test } from 'vitest' -import { compileStartOutputFactory } from '../../src/start-compiler-plugin/compilers' - -const compileStartOutput = compileStartOutputFactory('react') - -async function getFilenames() { - return await readdir(path.resolve(import.meta.dirname, './test-files')) -} - -describe('createMiddleware compiles correctly', async () => { - const filenames = await getFilenames() - - describe.each(filenames)('should handle "%s"', async (filename) => { - const file = await readFile( - path.resolve(import.meta.dirname, `./test-files/${filename}`), - ) - const code = file.toString() - - test.each(['client', 'server'] as const)( - `should compile for ${filename} %s`, - async (env) => { - const compiledResult = compileStartOutput({ - env, - code, - filename, - dce: false, - }) - - await expect(compiledResult.code).toMatchFileSnapshot( - `./snapshots/${env}/${filename}`, - ) - }, - ) - }) -}) diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/create-function-middleware.ts b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/create-function-middleware.ts deleted file mode 100644 index 7f39c06036..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/create-function-middleware.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start'; -import { foo } from '@some/lib'; -export const fnMw = createMiddleware({ - type: 'function' -}).client(() => { - console.log('client'); -}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareDestructured.tsx b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareDestructured.tsx deleted file mode 100644 index c513c274c5..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareDestructured.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start'; -import { z } from 'zod'; -export const withUseServer = createMiddleware({ - id: 'test' -}); -export const withoutUseServer = createMiddleware({ - id: 'test' -}); -export const withVariable = createMiddleware({ - id: 'test' -}); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = createMiddleware({ - id: 'test' -}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareDestructuredRename.tsx b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareDestructuredRename.tsx deleted file mode 100644 index 4ab09a9933..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareDestructuredRename.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { createMiddleware as middlewareFn } from '@tanstack/react-start'; -import { z } from 'zod'; -export const withUseServer = middlewareFn({ - id: 'test' -}); -export const withoutUseServer = middlewareFn({ - id: 'test' -}); -export const withVariable = middlewareFn({ - id: 'test' -}); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = middlewareFn({ - id: 'test' -}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareStarImport.tsx b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareStarImport.tsx deleted file mode 100644 index 7253e9510c..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareStarImport.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import * as TanStackStart from '@tanstack/react-start'; -import { z } from 'zod'; -export const withUseServer = TanStackStart.createMiddleware({ - id: 'test' -}); -export const withoutUseServer = TanStackStart.createMiddleware({ - id: 'test' -}); -export const withVariable = TanStackStart.createMiddleware({ - id: 'test' -}); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = TanStackStart.createMiddleware({ - id: 'test' -}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareValidator.tsx b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareValidator.tsx deleted file mode 100644 index 280dc3a067..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/createMiddlewareValidator.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start'; -import { z } from 'zod'; -export const withUseServer = createMiddleware({ - id: 'test' -}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/factory.ts b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/factory.ts deleted file mode 100644 index f5e43fb22a..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/client/factory.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start'; -import { getCookie } from '@tanstack/react-start/server'; -interface AuthMiddlewareOptions { - allowUnauthenticated?: boolean; -} -interface AuthContext { - session: { - id: string; - } | null; -} -export const createAuthMiddleware = (opts: AuthMiddlewareOptions = { - allowUnauthenticated: false -}) => createMiddleware({ - type: 'function' -}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/create-function-middleware.ts b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/create-function-middleware.ts deleted file mode 100644 index ee74b628fb..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/create-function-middleware.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start'; -import { foo } from '@some/lib'; -export const fnMw = createMiddleware({ - type: 'function' -}).server(({ - next -}) => { - console.log('server'); - foo(); - return next(); -}).client(() => { - console.log('client'); -}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/createMiddlewareDestructured.tsx b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/createMiddlewareDestructured.tsx deleted file mode 100644 index 8e1ddd8950..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/createMiddlewareDestructured.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start'; -import { z } from 'zod'; -export const withUseServer = createMiddleware({ - id: 'test' -}).server(async function () { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withoutUseServer = createMiddleware({ - id: 'test' -}).server(async () => { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withVariable = createMiddleware({ - id: 'test' -}).server(abstractedFunction); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = createMiddleware({ - id: 'test' -}).server(zodValidator(z.number(), input => { - return { - 'you gave': input - }; -})); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/createMiddlewareDestructuredRename.tsx b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/createMiddlewareDestructuredRename.tsx deleted file mode 100644 index 210d8df8e6..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/createMiddlewareDestructuredRename.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { createMiddleware as middlewareFn } from '@tanstack/react-start'; -import { z } from 'zod'; -export const withUseServer = middlewareFn({ - id: 'test' -}).server(async function () { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withoutUseServer = middlewareFn({ - id: 'test' -}).server(async () => { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withVariable = middlewareFn({ - id: 'test' -}).server(abstractedFunction); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = middlewareFn({ - id: 'test' -}).server(zodValidator(z.number(), input => { - return { - 'you gave': input - }; -})); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/createMiddlewareStarImport.tsx b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/createMiddlewareStarImport.tsx deleted file mode 100644 index 13e09f0ec2..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/createMiddlewareStarImport.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import * as TanStackStart from '@tanstack/react-start'; -import { z } from 'zod'; -export const withUseServer = TanStackStart.createMiddleware({ - id: 'test' -}).server(async function () { - 'use server'; - - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withoutUseServer = TanStackStart.createMiddleware({ - id: 'test' -}).server(async () => { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withVariable = TanStackStart.createMiddleware({ - id: 'test' -}).server(abstractedFunction); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = TanStackStart.createMiddleware({ - id: 'test' -}).server(zodValidator(z.number(), input => { - return { - 'you gave': input - }; -})); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/createMiddlewareValidator.tsx b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/createMiddlewareValidator.tsx deleted file mode 100644 index a530254087..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/createMiddlewareValidator.tsx +++ /dev/null @@ -1,7 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start'; -import { z } from 'zod'; -export const withUseServer = createMiddleware({ - id: 'test' -}).inputValidator(z.number()).server(({ - input -}) => input + 1); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/factory.ts b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/factory.ts deleted file mode 100644 index 5b1c2f3709..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/snapshots/server/factory.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start'; -import { getCookie } from '@tanstack/react-start/server'; -interface AuthMiddlewareOptions { - allowUnauthenticated?: boolean; -} -interface AuthContext { - session: { - id: string; - } | null; -} -export const createAuthMiddleware = (opts: AuthMiddlewareOptions = { - allowUnauthenticated: false -}) => createMiddleware({ - type: 'function' -}).server(({ - next -}) => { - const token = getCookie('session'); - if (!token) { - if (!opts.allowUnauthenticated) { - throw new Error('Unauthorized'); - } - return next({ - context: { - session: null - } - }); - } - - // ... token validation should be here - - return next({ - context: { - session: { - id: (Math.random() * 1000).toString() - } - } - }); -}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/createMiddlewareValidator.tsx b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/createMiddlewareValidator.tsx deleted file mode 100644 index bed1406646..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/createMiddlewareValidator.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start' -import { z } from 'zod' - -export const withUseServer = createMiddleware({ - id: 'test', -}) - .inputValidator(z.number()) - .server(({ input }) => input + 1) diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/factory.ts b/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/factory.ts deleted file mode 100644 index 4abd567628..0000000000 --- a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/factory.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { createMiddleware } from '@tanstack/react-start' -import { getCookie } from '@tanstack/react-start/server' - -interface AuthMiddlewareOptions { - allowUnauthenticated?: boolean -} - -interface AuthContext { - session: { id: string } | null -} - -export const createAuthMiddleware = ( - opts: AuthMiddlewareOptions = { allowUnauthenticated: false }, -) => - createMiddleware({ type: 'function' }).server(({ next }) => { - const token = getCookie('session') - if (!token) { - if (!opts.allowUnauthenticated) { - throw new Error('Unauthorized') - } - - return next({ - context: { - session: null, - }, - }) - } - - // ... token validation should be here - - return next({ - context: { - session: { - id: (Math.random() * 1000).toString(), - }, - }, - }) - }) diff --git a/packages/start-plugin-core/tests/createMiddleware/createMiddleware.test.ts b/packages/start-plugin-core/tests/createMiddleware/createMiddleware.test.ts new file mode 100644 index 0000000000..94af6ed65e --- /dev/null +++ b/packages/start-plugin-core/tests/createMiddleware/createMiddleware.test.ts @@ -0,0 +1,295 @@ +import { readFile, readdir } from 'node:fs/promises' +import path from 'node:path' +import { describe, expect, test, vi } from 'vitest' +import { StartCompiler } from '../../src/start-compiler/compiler' +import { formatSnapshot } from '../format-snapshot' + +// Default test options for StartCompiler +function getDefaultTestOptions(env: 'client' | 'server') { + const envName = env === 'client' ? 'client' : 'ssr' + return { + envName, + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + } +} + +async function getFilenames() { + return await readdir(path.resolve(import.meta.dirname, './test-files')) +} + +async function compile(opts: { + env: 'client' | 'server' + code: string + id: string +}) { + const compiler = new StartCompiler({ + ...opts, + ...getDefaultTestOptions(opts.env), + loadModule: async () => { + // do nothing in test + }, + lookupKinds: new Set(['Middleware']), + lookupConfigurations: [ + { + libName: `@tanstack/react-start`, + rootExport: 'createMiddleware', + kind: 'Root', + }, + { + libName: `@tanstack/react-start`, + rootExport: 'createStart', + kind: 'Root', + }, + ], + getKnownServerFns: () => ({}), + resolveId: async (id) => { + return id + }, + }) + const result = await compiler.compile({ + code: opts.code, + id: opts.id, + }) + return result +} + +describe('createMiddleware compiles correctly', async () => { + const filenames = await getFilenames() + + describe.each(filenames)('should handle "%s"', async (filename) => { + const file = await readFile( + path.resolve(import.meta.dirname, `./test-files/${filename}`), + ) + const code = file.toString() + + // Note: Middleware compilation only happens on the client + test(`should compile for ${filename} client`, async () => { + const result = await compile({ env: 'client', code, id: filename }) + + await expect( + await formatSnapshot(result!.code, filename), + ).toMatchFileSnapshot(`./snapshots/client/${filename}`) + }) + }) + + test('should compile validator method', async () => { + const code = ` + import { createMiddleware } from '@tanstack/react-start' + const myMiddleware = createMiddleware({ type: 'function' }) + .validator((input: string) => input) + .server(async ({ next }) => { + return next() + })` + + const result = await compile({ + env: 'client', + code, + id: 'test.ts', + }) + + expect(await formatSnapshot(result!.code, 'test.ts')) + .toMatchInlineSnapshot(` + "import { createMiddleware } from '@tanstack/react-start' + const myMiddleware = createMiddleware({ type: 'function' }) + " + `) + }) + + test('should use fast path for direct imports from known library (no extra resolveId calls)', async () => { + const code = ` + import { createMiddleware } from '@tanstack/react-start' + const myMiddleware = createMiddleware().server(async ({ next }) => { + return next() + })` + + const resolveIdMock = vi.fn(async (id: string) => id) + + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + loadModule: async () => {}, + lookupKinds: new Set(['Middleware']), + lookupConfigurations: [ + { + libName: '@tanstack/react-start', + rootExport: 'createMiddleware', + kind: 'Root', + }, + ], + getKnownServerFns: () => ({}), + resolveId: resolveIdMock, + }) + + await compiler.compile({ + code, + id: 'test.ts', + }) + + // Direct known-library imports use the knownRootImports fast path, so they + // do not need resolveId. + expect(resolveIdMock).not.toHaveBeenCalled() + }) + + test('should use slow path for factory pattern (resolveId called for import resolution)', async () => { + // This simulates a factory pattern where createMiddleware is re-exported from a local file + const factoryCode = ` + import { createFooMiddleware } from './factory' + const myMiddleware = createFooMiddleware().server(async ({ next }) => { + return next() + })` + + const resolveIdMock = vi.fn(async (id: string) => id) + + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + loadModule: async (id) => { + // Simulate the factory module being loaded + if (id === './factory') { + compiler.ingestModule({ + code: ` + import { createMiddleware } from '@tanstack/react-start' + export const createFooMiddleware = createMiddleware + `, + id: './factory', + }) + } + }, + lookupKinds: new Set(['Middleware']), + lookupConfigurations: [ + { + libName: '@tanstack/react-start', + rootExport: 'createMiddleware', + kind: 'Root', + }, + ], + getKnownServerFns: () => ({}), + resolveId: resolveIdMock, + }) + + await compiler.compile({ + code: factoryCode, + id: 'test.ts', + }) + + // resolveId should only be called for './factory'. Direct known-library + // imports use the knownRootImports fast path. + // + // Note: The factory module's import from '@tanstack/react-start' ALSO uses + // the fast path (knownRootImports), so no additional resolveId call is needed there. + expect(resolveIdMock).toHaveBeenCalledTimes(1) + expect(resolveIdMock).toHaveBeenNthCalledWith(1, './factory', 'test.ts') + }) + + test('should resolve createMiddleware from start-client-core implementation file', async () => { + const virtualModules: Record = { + '@tanstack/start-client-core': ` + export { createMiddleware } from './createMiddleware' + export { createIsomorphicFn } from '@tanstack/start-fn-stubs' + `, + '/virtual/compiler-known/middleware-factory.ts': ` + export const createMiddleware = () => ({ + server: () => createMiddleware(), + }) + `, + } + + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + loadModule: async (id) => { + const code = virtualModules[id] + if (code) { + compiler.ingestModule({ code, id }) + } + }, + lookupKinds: new Set(['Middleware', 'IsomorphicFn']), + lookupConfigurations: [], + getKnownServerFns: () => ({}), + resolveId: async (source) => { + if (source === '@tanstack/start-client-core') { + return '@tanstack/start-client-core' + } + + if (source === './createMiddleware') { + return '/virtual/compiler-known/middleware-factory.ts' + } + + return null + }, + }) + + const result = await compiler.compile({ + id: '/repo/packages/start-client-core/src/createCsrfMiddleware.ts', + code: ` + import { createIsomorphicFn } from '@tanstack/start-fn-stubs' + import { createMiddleware } from './createMiddleware' + + const innerCreateCsrfMiddleware = () => { + return createMiddleware().server(() => 'server-only-middleware') + } + + export const createCsrfMiddleware = createIsomorphicFn() + .server(innerCreateCsrfMiddleware) + `, + }) + + expect(result).not.toBeNull() + expect(result!.code).not.toContain('server-only-middleware') + expect(result!.code).not.toContain('createIsomorphicFn') + }) + + test('should resolve namespace createMiddleware from start-client-core implementation file', async () => { + const virtualModules: Record = { + '@tanstack/start-client-core': ` + export { createMiddleware } from './createMiddleware' + `, + '/virtual/compiler-known/middleware-factory.ts': ` + export const createMiddleware = () => ({ + server: () => createMiddleware(), + }) + `, + } + + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + loadModule: async (id) => { + const code = virtualModules[id] + if (code) { + compiler.ingestModule({ code, id }) + } + }, + lookupKinds: new Set(['Middleware']), + lookupConfigurations: [], + getKnownServerFns: () => ({}), + resolveId: async (source) => { + if (source === '@tanstack/start-client-core') { + return '@tanstack/start-client-core' + } + + if (source === './createMiddleware') { + return '/virtual/compiler-known/middleware-factory.ts' + } + + return null + }, + }) + + const result = await compiler.compile({ + id: '/repo/packages/start-client-core/src/internal.ts', + code: ` + import * as middlewareModule from './createMiddleware' + + export const middleware = middlewareModule.createMiddleware().server(() => { + return 'server-only-middleware' + }) + `, + }) + + expect(result).not.toBeNull() + expect(result!.code).not.toContain('server-only-middleware') + }) +}) diff --git a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/create-function-middleware.ts b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/create-function-middleware.ts new file mode 100644 index 0000000000..73d5910eef --- /dev/null +++ b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/create-function-middleware.ts @@ -0,0 +1,4 @@ +import { createMiddleware } from '@tanstack/react-start' +export const fnMw = createMiddleware({ type: 'function' }).client(() => { + console.log('client') +}) diff --git a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx new file mode 100644 index 0000000000..c3497f072b --- /dev/null +++ b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareDestructured.tsx @@ -0,0 +1,5 @@ +import { createMiddleware } from '@tanstack/react-start' +export const withUseServer = createMiddleware({ id: 'test' }) +export const withoutUseServer = createMiddleware({ id: 'test' }) +export const withVariable = createMiddleware({ id: 'test' }) +export const withZodValidator = createMiddleware({ id: 'test' }) diff --git a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx new file mode 100644 index 0000000000..70d3921bda --- /dev/null +++ b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareDestructuredRename.tsx @@ -0,0 +1,5 @@ +import { createMiddleware as middlewareFn } from '@tanstack/react-start' +export const withUseServer = middlewareFn({ id: 'test' }) +export const withoutUseServer = middlewareFn({ id: 'test' }) +export const withVariable = middlewareFn({ id: 'test' }) +export const withZodValidator = middlewareFn({ id: 'test' }) diff --git a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx new file mode 100644 index 0000000000..f997f40fe0 --- /dev/null +++ b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareStarImport.tsx @@ -0,0 +1,5 @@ +import * as TanStackStart from '@tanstack/react-start' +export const withUseServer = TanStackStart.createMiddleware({ id: 'test' }) +export const withoutUseServer = TanStackStart.createMiddleware({ id: 'test' }) +export const withVariable = TanStackStart.createMiddleware({ id: 'test' }) +export const withZodValidator = TanStackStart.createMiddleware({ id: 'test' }) diff --git a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx new file mode 100644 index 0000000000..773e990702 --- /dev/null +++ b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createMiddlewareValidator.tsx @@ -0,0 +1,2 @@ +import { createMiddleware } from '@tanstack/react-start' +export const withUseServer = createMiddleware({ id: 'test' }) diff --git a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createStart.tsx b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createStart.tsx new file mode 100644 index 0000000000..b2bde33436 --- /dev/null +++ b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/createStart.tsx @@ -0,0 +1,9 @@ +import { createStart } from '@tanstack/react-start' +export const startInstance = createStart(() => {}) +export const serverFnMw = startInstance + .createMiddleware({ type: 'function' }) + .client(({ next }) => { + console.log('client mw') + return next() + }) +export const requestMw = startInstance.createMiddleware({ type: 'request' }) diff --git a/packages/start-plugin-core/tests/createMiddleware/snapshots/client/middleware-factory.ts b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/middleware-factory.ts new file mode 100644 index 0000000000..0e51f2f369 --- /dev/null +++ b/packages/start-plugin-core/tests/createMiddleware/snapshots/client/middleware-factory.ts @@ -0,0 +1,11 @@ +import { createMiddleware } from '@tanstack/react-start' +// Middleware factory function - returns a middleware with .server() call +export function createPublicRateLimitMiddleware(keySuffix) { + return createMiddleware({ type: 'function' }) +} +// Arrow function factory +export const createAuthMiddleware = (requiredRole) => { + return createMiddleware({ type: 'function' }) +} +// Top-level middleware for comparison +export const topLevelMiddleware = createMiddleware({ id: 'topLevel' }) diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/create-function-middleware.ts b/packages/start-plugin-core/tests/createMiddleware/test-files/create-function-middleware.ts similarity index 100% rename from packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/create-function-middleware.ts rename to packages/start-plugin-core/tests/createMiddleware/test-files/create-function-middleware.ts diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/createMiddlewareDestructured.tsx b/packages/start-plugin-core/tests/createMiddleware/test-files/createMiddlewareDestructured.tsx similarity index 100% rename from packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/createMiddlewareDestructured.tsx rename to packages/start-plugin-core/tests/createMiddleware/test-files/createMiddlewareDestructured.tsx diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/createMiddlewareDestructuredRename.tsx b/packages/start-plugin-core/tests/createMiddleware/test-files/createMiddlewareDestructuredRename.tsx similarity index 100% rename from packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/createMiddlewareDestructuredRename.tsx rename to packages/start-plugin-core/tests/createMiddleware/test-files/createMiddlewareDestructuredRename.tsx diff --git a/packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/createMiddlewareStarImport.tsx b/packages/start-plugin-core/tests/createMiddleware/test-files/createMiddlewareStarImport.tsx similarity index 100% rename from packages/start-plugin-core/tests/createMiddleware-start-compiler-plugin/test-files/createMiddlewareStarImport.tsx rename to packages/start-plugin-core/tests/createMiddleware/test-files/createMiddlewareStarImport.tsx diff --git a/packages/start-plugin-core/tests/createMiddleware/test-files/createMiddlewareValidator.tsx b/packages/start-plugin-core/tests/createMiddleware/test-files/createMiddlewareValidator.tsx new file mode 100644 index 0000000000..894bf4608f --- /dev/null +++ b/packages/start-plugin-core/tests/createMiddleware/test-files/createMiddlewareValidator.tsx @@ -0,0 +1,8 @@ +import { createMiddleware } from '@tanstack/react-start' +import { z } from 'zod' + +export const withUseServer = createMiddleware({ + id: 'test', +}) + .validator(z.number()) + .server(({ input }) => input + 1) diff --git a/packages/start-plugin-core/tests/createMiddleware-create-server-fn-plugin/test-files/createStart.tsx b/packages/start-plugin-core/tests/createMiddleware/test-files/createStart.tsx similarity index 100% rename from packages/start-plugin-core/tests/createMiddleware-create-server-fn-plugin/test-files/createStart.tsx rename to packages/start-plugin-core/tests/createMiddleware/test-files/createStart.tsx diff --git a/packages/start-plugin-core/tests/createMiddleware/test-files/middleware-factory.ts b/packages/start-plugin-core/tests/createMiddleware/test-files/middleware-factory.ts new file mode 100644 index 0000000000..a306dbf371 --- /dev/null +++ b/packages/start-plugin-core/tests/createMiddleware/test-files/middleware-factory.ts @@ -0,0 +1,41 @@ +import { createMiddleware } from '@tanstack/react-start' + +// Middleware factory function - returns a middleware with .server() call +export function createPublicRateLimitMiddleware(keySuffix) { + return createMiddleware({ type: 'function' }).server( + async ({ next, data }) => { + const key = keySuffix ? `ip:${keySuffix}` : 'ip:default' + const finalKey = typeof data === 'string' ? `ip:${data}` : key + + const { success } = await rateLimit({ key: finalKey }) + + if (!success) { + throw new Error('Too many requests') + } + + return next() + }, + ) +} + +// Arrow function factory +export const createAuthMiddleware = (requiredRole) => { + return createMiddleware({ type: 'function' }).server(async ({ next }) => { + const user = await getUser() + if (!user) { + throw new Error('Unauthorized') + } + if (requiredRole && user.role !== requiredRole) { + throw new Error('Forbidden') + } + return next() + }) +} + +// Top-level middleware for comparison +export const topLevelMiddleware = createMiddleware({ + id: 'topLevel', +}).server(async ({ next }) => { + console.log('top level') + return next() +}) diff --git a/packages/start-plugin-core/tests/createServerFn/caller-dead-code.test.ts b/packages/start-plugin-core/tests/createServerFn/caller-dead-code.test.ts new file mode 100644 index 0000000000..07c7a2f2cf --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/caller-dead-code.test.ts @@ -0,0 +1,591 @@ +import { describe, expect, test } from 'vitest' +import { + callProvider, + compileAll, + compileCode, + evaluateModule, + importSources, +} from '../regression-helpers' +import { declarationOf, getModuleErrors } from '../validate-module' +import type { ModuleStub } from '../regression-helpers' + +// Client and SSR callers replace a server fn handler with an RPC, then drop +// the module code only the handler read, so server-only imports never reach +// them. Code the callers still read must survive with its values. + +const head = `import { createServerFn } from '@tanstack/react-start'\n` +const dbServer = `export const db = { x: () => 'x' }` + +describe('callers drop a server import only the handler reads', () => { + // Source: Next.js server-actions fixtures server-graph/6 (shadowed bindings) + test.each([ + { + name: 'a handler local shadows an import the client uses', + code: `import { db } from './db.server' +import { format } from './format' +export const label = format('x') +export const fn = createServerFn().handler(async () => { + const format = (value: unknown) => \`local:\${value}\` + return format(db.x()) +})`, + client: ['./format'], + provider: ['./db.server'], + expected: 'local:x', + }, + { + name: 'a handler parameter shadows an import the client uses', + code: `import { db } from './db.server' +export const fn = createServerFn().handler(async ({ data: db }: { data: string }) => db) +export const clientDb = db`, + client: ['./db.server'], + provider: [], + expected: 'param', + }, + ])('when $name', async ({ code, client, provider, expected }) => { + const compiled = await compileAll(`${head}${code}`) + expect(importSources(compiled.client)).toEqual(client) + expect(importSources(compiled.provider)).toEqual(provider) + expect( + await callProvider( + compiled.provider, + 'fn', + { './db.server': dbServer }, + 'param', + ), + ).toBe(expected) + }) + + // Each snippet uses the name `db` in a position that is not a reference to + // the import the handler reads. + test.each<{ + name: string + code: string + stubs?: Record + check?: (client: Record) => void + }>([ + { + // Source: @vitejs/plugin-rsc scope/label.js + name: 'a label', + code: `export function loop() { + db: for (const item of [1, 2]) { + if (item) { + break db + } + } + return 'loop' +}`, + check: (client) => expect(client.loop()).toBe('loop'), + }, + { + // Source: @vitejs/plugin-rsc scope/object-expr-vs-pattern.js + name: 'an object key and a pattern key', + code: `export const options = { db: 'key' } +export const pick = ({ db: local }) => local`, + check: (client) => expect(client.pick(client.options)).toBe('key'), + }, + { + // Source: @vitejs/plugin-rsc scope/member-expr.js + name: 'a member property', + code: `export const read = (object) => object.db`, + check: (client) => expect(client.read({ db: 'member' })).toBe('member'), + }, + { + // Source: @vitejs/plugin-rsc scope/method-definition.js, + // scope/property-definition.js; typescript-eslint private-identifier.js + name: 'method, field and private names', + code: `export const api = { db() { return 'method' } } +export class Store { + db = 'field' + #db = 'private' + static db() { + return 'static' + } + read() { + return [this.db, this.#db] + } +}`, + check: (client) => { + expect(client.api.db()).toBe('method') + expect(client.Store.db()).toBe('static') + expect(new client.Store().read()).toEqual(['field', 'private']) + }, + }, + { + // Source: @vitejs/plugin-rsc scope/export-specifier.js + name: 'an export alias', + code: `const local = 'alias' +export { local as db }`, + check: (client) => expect(client.db).toBe('alias'), + }, + { + // Source: @vitejs/plugin-rsc scope/destructuring-assignment.js + name: 'a destructuring assignment key', + code: `let bound +;({ db: bound } = { db: 'assigned' }) +export { bound }`, + check: (client) => expect(client.bound).toBe('assigned'), + }, + { + // Source: @vitejs/plugin-rsc scope/catch-param.js + name: 'a catch parameter', + code: `export function safe() { + try { + throw 'caught' + } catch (db) { + return db + } +}`, + check: (client) => expect(client.safe()).toBe('caught'), + }, + { + // Source: @vitejs/plugin-rsc scope/fn-expr-name.js, scope/class-expr-self.js + name: 'function and class expression names', + code: `export const self = function db() { + return db +} +export const Self = class db { + static self() { + return db + } +}`, + check: (client) => { + expect(client.self()).toBe(client.self) + expect(client.Self.self()).toBe(client.Self) + }, + }, + { + // Source: @vitejs/plugin-rsc scope/var-hoisting.js, scope/fn-decl-hoisting.js + name: 'hoisted var and function declarations', + code: `export function hoistedVar() { + { + var db = 'var' + } + return db +} +export function hoistedFunction() { + return db() + function db() { + return 'function' + } +}`, + check: (client) => { + expect(client.hoistedVar()).toBe('var') + expect(client.hoistedFunction()).toBe('function') + }, + }, + { + // Source: @vitejs/plugin-rsc scope/let-const-block.js, + // scope/shadowing-block.js; typescript-eslint block/scope.js + name: 'loop, switch and static block declarations', + code: `export function loops() { + const out = [] + for (let db = 0; db < 1; db++) out.push(db) + for (const db of ['of']) out.push(db) + for (const db in { in: 1 }) out.push(db) + return out +} +export function choose(key) { + switch (key) { + case 1: + return 'one' + default: + const db = 'switch' + return db + } +} +export class Block { + static value + static { + const db = 'static' + Block.value = db + } +}`, + check: (client) => { + expect(client.loops()).toEqual([0, 'of', 'in']) + expect(client.choose(2)).toBe('switch') + expect(client.Block.value).toBe('static') + }, + }, + { + // Source: @vitejs/plugin-rsc scope/destructured-params.js, + // scope/param-defaults.js; typescript-eslint readable-ref-param-shadow.js + name: 'parameters, accessor parameters and defaults reading them', + code: `export const params = (db, other = db) => other +export const accessors = { + stored: '', + set value(db) { + this.stored = db + }, +} +export function rest(...db) { + return db +}`, + check: (client) => { + expect(client.params('param')).toBe('param') + client.accessors.value = 'set' + expect(client.accessors.stored).toBe('set') + expect(client.rest(1, 2)).toEqual([1, 2]) + }, + }, + { + // Source: @vitejs/plugin-rsc scope/import-meta.js + name: 'an import.meta property', + code: `export const meta = typeof import.meta.db`, + check: (client) => expect(client.meta).toBe('undefined'), + }, + { + // Source: @vitejs/plugin-rsc hoist/reexport-import-not-bound.js + name: 'a re-export', + code: `export { db } from './other'`, + stubs: { './other': `export const db = 'other'` }, + check: (client) => expect(client.db).toBe('other'), + }, + { + // Source: typescript-eslint ts-module/namespace.js, ts-module/scope.js + name: 'a namespace member', + code: `export namespace Repo { + export const db = 'namespace' + export const read = () => db +}`, + check: (client) => expect(client.Repo.read()).toBe('namespace'), + }, + { + // Source: typescript-eslint type-declaration/interface1.js, type1.js, + // function-declaration/type-parameters + name: 'type positions', + code: `export interface Row { + db: string +} +export type Shape = { db: number } +export function identity(value: db): db { + return value +}`, + check: (client) => expect(client.identity('id')).toBe('id'), + }, + { + // Source: typescript-eslint jsx/attribute.js, jsx/namespaced-attribute.js, + // jsx/component-intrinsic-name.js, jsx/this-jsxidentifier.js + name: 'JSX attribute names, intrinsic tags and this members', + code: `export const element = +export const intrinsic = +export const namespaced = +export class View { + db = () => null + render() { + return + } +}`, + }, + ])( + 'when client code uses its name in $name', + async ({ code, stubs = {}, check }) => { + const client = await compileCode( + 'client', + `${head}import { db } from './db.server' +export const fn = createServerFn().handler(async () => db.x()) +${code}`, + ) + expect(await getModuleErrors(client!)).toEqual([]) + expect(importSources(client!)).toEqual(Object.keys(stubs)) + check?.(await evaluateModule(client!, stubs)) + }, + ) + + // Source: SolidStart compile.spec.ts "removes an import when only type + // specifiers remain", "preserves live value specifiers from a mixed + // import"; babel-dead-code-elimination "import" > "mixed default and named" + test.each([ + { + name: 'only type specifiers remain', + code: `import { type Session, verify } from './server-module'`, + callers: [], + }, + { + name: 'a named client specifier remains', + code: `import verify, { type Session, clientValue } from './server-module' +export const value = clientValue`, + callers: ['./server-module'], + }, + { + name: 'a default client specifier remains', + code: `import clientDefault, { type Session, verify } from './server-module' +export const value = clientDefault`, + callers: ['./server-module'], + }, + ])( + 'when it shares a mixed import in which $name', + async ({ code, callers }) => { + const compiled = await compileAll(`${head}${code} +export const fn = createServerFn().handler(async (): Promise => verify())`) + for (const caller of [compiled.client, compiled.ssr]) { + expect(importSources(caller)).toEqual(callers) + expect(caller).not.toMatch(/\bverify\b/) + } + expect(compiled.provider).not.toMatch(/\bclient(?:Value|Default)\b/) + expect( + await callProvider(compiled.provider, 'fn', { + './server-module': `export const clientValue = 'client'; export const verify = () => 'verified'; export default verify`, + }), + ).toBe('verified') + }, + ) + + // Source: Next.js server-actions fixtures server-graph/47, /58 + test('when the handler only reads it through a validator or a middleware', async () => { + const compiled = + await compileAll(`import { createMiddleware, createServerFn } from '@tanstack/react-start' +import { db } from './db.server' +import { schema } from './schema.server' +const auth = createMiddleware({ type: 'function' }) + .client(async ({ next }) => next()) + .server(async ({ next }) => next({ context: { user: await db.user() } })) +export const fn = createServerFn() + .middleware([auth]) + .validator((data: unknown) => schema.parse(data)) + .handler(async () => 'ok')`) + expect(importSources(compiled.client)).toEqual([]) + expect(importSources(compiled.provider)).toEqual([ + './db.server', + './schema.server', + ]) + }) +}) + +// Source: @vitejs/plugin-rsc hoist/function-hoist-block.js, +// scope/param-default-var-hoisting.js, hoist/shadow-partial-if-block-over-global.js, +// hoist/catch-binding-shadow.js +test.each([ + { + name: 'past a function declared in a nested block', + code: `export function read() { + { + function store() {} + } + return store.value +}`, + }, + { + name: 'from a parameter default next to a var of the same name', + code: `export function read(value = store.value) { + var store = 'local' + return value +}`, + }, + { + name: 'after a block that shadows it', + code: `export function read() { + if (Math.random() > 2) { + const store = { value: 'local' } + return store.value + } + return store.value +}`, + }, + { + name: 'in a try block whose catch parameter shadows it', + code: `export function read() { + try { + return store.value + } catch (store) { + return store + } +}`, + }, +])('client code that reads an import $name keeps it', async ({ code }) => { + const client = await compileCode( + 'client', + `${head}import { store } from './store' +import { db } from './db.server' +export const fn = createServerFn().handler(async () => db.x()) +${code}`, + ) + expect(importSources(client!)).toEqual(['./store']) + const module = await evaluateModule(client!, { + './store': `export const store = { value: 'store' }`, + }) + expect(module.read()).toBe('store') +}) + +describe('destructurings shared by the handler and client code', () => { + // Source: Next.js server-actions fixtures server-graph/6, client-graph/3 + test.each<{ + name: string + code: string + stubs: Record + clientValue: unknown + handlerValue: unknown + }>([ + { + name: 'an array pattern', + code: `import { values } from './values' +const [serverOnly, shared] = values +export const clientValue = shared +export const fn = createServerFn().handler(async () => serverOnly)`, + stubs: { './values': `export const values = ['server', 'shared']` }, + clientValue: 'shared', + handlerValue: 'server', + }, + { + // Dropping the handler-only `secretKey` would move it into the rest. + name: 'an object pattern whose rest the client uses', + code: `import { config } from './config' +const { secretKey, ...publicConfig } = config +export const clientValue = publicConfig +export const fn = createServerFn().handler(async () => secretKey)`, + stubs: { + './config': `export const config = { secretKey: 'key', theme: 'dark' }`, + }, + clientValue: { theme: 'dark' }, + handlerValue: 'key', + }, + ])( + 'keep their values in every output for $name', + async ({ code, stubs, clientValue, handlerValue }) => { + const compiled = await compileAll(`${head}${code}`) + const client = await evaluateModule(compiled.client, stubs) + expect(client.clientValue).toEqual(clientValue) + expect(await callProvider(compiled.provider, 'fn', stubs)).toEqual( + handlerValue, + ) + }, + ) + + // When one binding of a destructuring stays live, the elements of the + // handler-only bindings are pruned, including what their default values or + // computed keys read. + // Source: Next.js server-actions fixtures server-graph/6, /43 + test.each([ + { + name: 'an object pattern default', + code: `import { readSecret } from './secrets.server' +const { apiKey = readSecret(), theme } = config`, + }, + { + name: 'an array pattern default', + code: `import { readSecret } from './secrets.server' +const [apiKey = readSecret(), theme] = config.list`, + }, + { + name: 'a computed key', + code: `import { secretKeyName } from './secrets.server' +const { [secretKeyName]: apiKey, theme } = config`, + }, + { + name: 'a nested pattern default', + code: `import { readSecret } from './secrets.server' +const { db: { apiKey = readSecret() } = {}, theme } = config`, + }, + ])( + 'drop a server import read by $name of a handler-only binding', + async ({ code }) => { + const compiled = + await compileAll(`${head}import { config } from './config' +${code} +export const fn = createServerFn().handler(async () => apiKey) +export const currentTheme = theme`) + expect(importSources(compiled.client)).toEqual(['./config']) + const client = await evaluateModule(compiled.client, { + './config': `export const config = { theme: 'dark', list: [undefined, 'dark'] }`, + }) + expect(client.currentTheme).toBe('dark') + }, + ) +}) + +describe('declarations only the handler needs', () => { + // Source: babel-dead-code-elimination "SCC dead code elimination" (mutual + // recursion, self-recursive functions, unexported circular references) + test('callers drop handler-only cycles and default parameters but keep cycles nothing used', async () => { + const compiled = + await compileAll(`${head}import { secret, defaultId } from './secret.server' +function walk(n: number): number { return n > 0 ? walkBack(n - 1) : secret.length } +function walkBack(n: number): number { return n > 0 ? walk(n - 1) : 0 } +const loop = (n: number): number => (n > 0 ? loop(n - 1) : 0) +function load(id = defaultId()) { return id } +function unusedA(): number { return unusedB() } +function unusedB(): number { return unusedA() } +export const fn = createServerFn().handler(async () => [walk(3), loop(2), load()])`) + for (const caller of [compiled.client, compiled.ssr]) { + expect(importSources(caller)).toEqual([]) + for (const name of ['walk', 'walkBack', 'loop', 'load']) { + expect(caller).not.toMatch(declarationOf(name)) + } + } + for (const name of ['walk', 'walkBack', 'loop', 'load']) { + expect(compiled.provider).toMatch(declarationOf(name)) + } + for (const output of [compiled.client, compiled.ssr, compiled.provider]) { + expect(output).toMatch(declarationOf('unusedA')) + expect(output).toMatch(declarationOf('unusedB')) + } + }) + + // Source: babel-dead-code-elimination "assignment" + test('callers keep handler-read bindings that top-level statements assign', async () => { + const compiled = await compileAll(`${head}let x: string +x = 'x-assigned' +y = 'y-assigned' +var y: string +export const fn = createServerFn().handler(async () => [x, y])`) + // An assignment left without its declaration throws in a module. + await evaluateModule(compiled.client) + await evaluateModule(compiled.ssr) + expect(await callProvider(compiled.provider, 'fn')).toEqual([ + 'x-assigned', + 'y-assigned', + ]) + }) + + // Source: babel-dead-code-elimination "repeated elimination" + test('callers drop a binding only the handler writes and keep a declarator a kept sibling reads', async () => { + const compiled = + await compileAll(`${head}import { serverValue } from './db.server' +let hits = 0 +let a = serverValue(), clientCopy = a +export const fn = createServerFn().handler(async () => { + hits++ + return a +}) +export const clientB = clientCopy`) + for (const caller of [compiled.client, compiled.ssr]) { + expect(caller).not.toMatch(declarationOf('hits')) + expect(caller).toMatch(declarationOf('a')) + expect(importSources(caller)).toEqual(['./db.server']) + } + expect(compiled.provider).toMatch(declarationOf('hits')) + expect(compiled.provider).not.toContain('clientCopy') + }) + + // Source: babel-dead-code-elimination "variable" > "within for...in", + // "within for...of" (var bindings declared inside nested statements) + test('callers drop handler-only vars declared inside top-level statements', async () => { + const calls = ['openFlag', 'connect', 'readMode', 'readLabel', 'createPool'] + const compiled = + await compileAll(`${head}import { ${calls.join(', ')} } from './db.server' +if (typeof window === 'undefined') { + var flag = openFlag() +} +try { + var conn = connect() +} catch {} +switch (process.env.MODE) { + case 'x': + var mode = readMode() +} +outer: { + var labeled = readLabel() + break outer +} +for (var i = 0, pool = createPool(); i < 1; i++) {} +export const fn = createServerFn().handler(async () => [flag, conn, mode, labeled, pool])`) + for (const caller of [compiled.client, compiled.ssr]) { + expect(importSources(caller)).toEqual([]) + for (const call of calls) { + expect(caller).not.toContain(call) + } + } + for (const call of calls) { + expect(compiled.provider).toContain(`${call}()`) + } + }) +}) diff --git a/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts b/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts index fca2dd0242..e80f292891 100644 --- a/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts +++ b/packages/start-plugin-core/tests/createServerFn/createServerFn.test.ts @@ -1,19 +1,44 @@ import { readFile, readdir } from 'node:fs/promises' import path from 'node:path' -import { describe, expect, test } from 'vitest' -import { ServerFnCompiler } from '../../src/create-server-fn-plugin/compiler' +import { stripVTControlCharacters } from 'node:util' +import { describe, expect, test, vi } from 'vitest' +import { StartCompiler } from '../../src/start-compiler/compiler' +import { formatSnapshot } from '../format-snapshot' + +// Default test options for StartCompiler +function getDefaultTestOptions(env: 'client' | 'server') { + const envName = env === 'client' ? 'client' : 'ssr' + return { + envName, + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + } +} async function getFilenames() { return await readdir(path.resolve(import.meta.dirname, './test-files')) } +const TSS_SERVERFN_SPLIT_PARAM = 'tss-serverfn-split' + async function compile(opts: { env: 'client' | 'server' code: string - id: string + parserFilename?: string + isProviderFile: boolean + mode: 'dev' | 'build' }) { - const compiler = new ServerFnCompiler({ + // Use an absolute path inside the test root to ensure consistent filename output + let id = '/test/src/test.ts' + + if (opts.isProviderFile) { + id += `?${TSS_SERVERFN_SPLIT_PARAM}` + } + + const compiler = new StartCompiler({ ...opts, + ...getDefaultTestOptions(opts.env), loadModule: async (id) => { // do nothing in test }, @@ -22,14 +47,19 @@ async function compile(opts: { { libName: `@tanstack/react-start`, rootExport: 'createServerFn', + kind: 'Root', }, ], + getKnownServerFns: () => ({}), resolveId: async (id) => { return id }, - directive: 'use server', }) - const result = await compiler.compile({ code: opts.code, id: opts.id }) + const result = await compiler.compile({ + code: opts.code, + id, + parserFilename: opts.parserFilename, + }) return result } @@ -42,18 +72,86 @@ describe('createServerFn compiles correctly', async () => { ) const code = file.toString() - test.each(['client', 'server'] as const)( - `should compile for ${filename} %s`, - async (env) => { - const result = await compile({ env, code, id: filename }) + test.each([ + { type: 'client', isProviderFile: false }, + { type: 'server', isProviderFile: false }, + { type: 'server', isProviderFile: true }, + ] as const)(`should compile for ${filename} %s`, async (env) => { + const result = await compile({ + env: env.type, + isProviderFile: env.isProviderFile, + code, + parserFilename: `/test/src/${filename}`, + mode: 'build', + }) - await expect(result!.code).toMatchFileSnapshot( - `./snapshots/${env}/${filename}`, - ) - }, - ) + const folder = + env.type === 'client' + ? 'client' + : env.isProviderFile + ? 'server-provider' + : 'server-caller' + await expect( + await formatSnapshot(result!.code, filename), + ).toMatchFileSnapshot(`./snapshots/${folder}/${filename}`) + }) }) + test('should compile validator method', async () => { + const code = ` + import { createServerFn } from '@tanstack/react-start' + const myServerFn = createServerFn() + .validator((input: string) => input) + .handler(({ input }) => input)` + + const compiledResultClient = await compile({ + code, + env: 'client', + isProviderFile: false, + mode: 'build', + }) + + expect(await formatSnapshot(compiledResultClient!.code, 'test.ts')) + .toMatchInlineSnapshot(` + "import { createClientRpc } from '@tanstack/react-start/client-rpc' + import { createServerFn } from '@tanstack/react-start' + const myServerFn = createServerFn().handler( + createClientRpc( + '2c205add8e6755de551521133ddff3d48859b1631add5f1bbe5c48a5664f319b', + ), + ) + " + `) + }) + + // Editors count \n, \r\n, a lone \r, U+2028 and U+2029 as line + // terminators, so diagnostic locations must count every one. + test.each([ + ['\\n', '\n'], + ['\\r\\n', '\r\n'], + ['a lone \\r', '\r'], + ['U+2028', '\u2028'], + ['U+2029', '\u2029'], + ])( + 'reports the location of a diagnostic with %s line endings', + async (_name, eol) => { + const error = await compile({ + code: [ + `import { createServerFn } from '@tanstack/react-start'`, + `export const { fn } = createServerFn().handler(async () => 1)`, + ].join(eol), + env: 'client', + isProviderFile: false, + mode: 'build', + }).catch((caught: unknown) => caught) + + expect(error).toBeInstanceOf(Error) + expect(stripVTControlCharacters((error as Error).message)).toMatch( + /> 2 \| export const \{ fn \} = createServerFn\(\)/, + ) + }, + ) + test('should work with identifiers of functions', async () => { const code = ` import { createServerFn } from '@tanstack/react-start' @@ -63,37 +161,175 @@ describe('createServerFn compiles correctly', async () => { const myServerFn = createServerFn().handler(myFunc)` const compiledResultClient = await compile({ - id: 'test.ts', code, env: 'client', + isProviderFile: false, + mode: 'build', }) - const compiledResultServer = await compile({ - id: 'test.ts', + // Server caller (route file - no split param) + // Should NOT have the second argument since implementation comes from extracted chunk + const compiledResultServerCaller = await compile({ code, env: 'server', + isProviderFile: false, + mode: 'build', }) - expect(compiledResultClient!.code).toMatchInlineSnapshot(` - "import { createServerFn } from '@tanstack/react-start'; - const myServerFn = createServerFn().handler((opts, signal) => { - "use server"; + // Server provider (extracted file - has split param) + // Should HAVE the second argument since this is the implementation file + const compiledResultServerProvider = await compile({ + code, + env: 'server', + isProviderFile: true, + mode: 'build', + }) - return myServerFn.__executeServer(opts, signal); - });" - `) + expect(await formatSnapshot(compiledResultClient!.code, 'test.ts')) + .toMatchInlineSnapshot(` + "import { createClientRpc } from '@tanstack/react-start/client-rpc' + import { createServerFn } from '@tanstack/react-start' + const myServerFn = createServerFn().handler( + createClientRpc( + '2c205add8e6755de551521133ddff3d48859b1631add5f1bbe5c48a5664f319b', + ), + ) + " + `) - expect(compiledResultServer!.code).toMatchInlineSnapshot(` - "import { createServerFn } from '@tanstack/react-start'; - const myFunc = () => { - return 'hello from the server'; - }; - const myServerFn = createServerFn().handler((opts, signal) => { - "use server"; + // Server caller: no second argument (implementation from extracted chunk) + expect(await formatSnapshot(compiledResultServerCaller!.code, 'test.ts')) + .toMatchInlineSnapshot(` + "import { createSsrRpc } from '@tanstack/react-start/ssr-rpc' + import { createServerFn } from '@tanstack/react-start' + const myServerFn = createServerFn().handler( + createSsrRpc( + '2c205add8e6755de551521133ddff3d48859b1631add5f1bbe5c48a5664f319b', + ), + ) + " + `) - return myServerFn.__executeServer(opts, signal); - }, myFunc);" - `) + // Server provider: has second argument (this is the implementation file) + expect(await formatSnapshot(compiledResultServerProvider!.code, 'test.ts')) + .toMatchInlineSnapshot(` + "import { createServerRpc } from '@tanstack/react-start/server-rpc' + import { createServerFn } from '@tanstack/react-start' + const myFunc = () => { + return 'hello from the server' + } + const myServerFn_createServerFn_handler = createServerRpc( + { + id: '2c205add8e6755de551521133ddff3d48859b1631add5f1bbe5c48a5664f319b', + name: 'myServerFn', + filename: 'src/test.ts', + }, + (opts) => myServerFn.__executeServer(opts), + ) + const myServerFn = createServerFn().handler( + myServerFn_createServerFn_handler, + myFunc, + ) + export { myServerFn_createServerFn_handler } + " + `) + }) + + test('should remove imports used only as caller handler identifiers', async () => { + const code = ` + import { createServerFn } from '@tanstack/react-start' + import { getUsers } from './server' + + export const getUsersFn = createServerFn().handler(getUsers) + ` + + const compiledResult = await compile({ + code, + env: 'client', + isProviderFile: false, + mode: 'build', + }) + + expect(await formatSnapshot(compiledResult!.code, 'test.ts')) + .toMatchInlineSnapshot(` + "import { createClientRpc } from '@tanstack/react-start/client-rpc' + import { createServerFn } from '@tanstack/react-start' + export const getUsersFn = createServerFn().handler( + createClientRpc( + 'a78c63d4bb3c0b10a8b70902c73611fbf0b9229e0807b065c03c939f9c0ce100', + ), + ) + " + `) + }) + + test('should not remove handler identifier bindings that are still referenced', async () => { + const code = ` + import { createServerFn } from '@tanstack/react-start' + import { getUsers } from './server' + + export const getUsersFn = createServerFn().handler(getUsers) + console.log(getUsers) + ` + + const compiledResult = await compile({ + code, + env: 'client', + isProviderFile: false, + mode: 'build', + }) + + expect(await formatSnapshot(compiledResult!.code, 'test.ts')) + .toMatchInlineSnapshot(` + "import { createClientRpc } from '@tanstack/react-start/client-rpc' + import { createServerFn } from '@tanstack/react-start' + import { getUsers } from './server' + export const getUsersFn = createServerFn().handler( + createClientRpc( + 'a78c63d4bb3c0b10a8b70902c73611fbf0b9229e0807b065c03c939f9c0ce100', + ), + ) + console.log(getUsers) + " + `) + }) + + test('should compile server functions wrapped in TypeScript as expressions', async () => { + const code = ` + import { createServerFn } from '@tanstack/react-start' + + export const getUsersFn = createServerFn().handler(() => 'server') as any + ` + + const compiledResult = await compile({ + code, + env: 'client', + isProviderFile: false, + mode: 'build', + }) + + expect(compiledResult).not.toBeNull() + expect(compiledResult!.code).toContain('createClientRpc') + expect(compiledResult!.code).not.toContain('server') + }) + + test('should compile server functions wrapped in TypeScript satisfies expressions', async () => { + const code = ` + import { createServerFn } from '@tanstack/react-start' + + export const getUsersFn = createServerFn().handler(() => 'server') satisfies unknown + ` + + const compiledResult = await compile({ + code, + env: 'client', + isProviderFile: false, + mode: 'build', + }) + + expect(compiledResult).not.toBeNull() + expect(compiledResult!.code).toContain('createClientRpc') + expect(compiledResult!.code).not.toContain('server') }) test('should use dce by default', async () => { @@ -110,50 +346,556 @@ describe('createServerFn compiles correctly', async () => { // Client const compiledResult = await compile({ - id: 'test.ts', code, env: 'client', + isProviderFile: false, + mode: 'build', }) - expect(compiledResult!.code).toMatchInlineSnapshot(` - "import { createServerFn } from '@tanstack/react-start'; - export const exportedFn = createServerFn().handler((opts, signal) => { - "use server"; + expect(await formatSnapshot(compiledResult!.code, 'test.ts')) + .toMatchInlineSnapshot(` + "import { createClientRpc } from '@tanstack/react-start/client-rpc' + import { createServerFn } from '@tanstack/react-start' + export const exportedFn = createServerFn().handler( + createClientRpc( + 'c306c96e9256c7604f2a6022c4c94eb89f863274c022bc45b03970f067ea9864', + ), + ) + const nonExportedFn = createServerFn().handler( + createClientRpc( + 'f4403dc0b18e216dfe0a9711cab028bc1b9768175daa9236d7115e29c99d76c2', + ), + ) + " + `) - return exportedFn.__executeServer(opts, signal); - }); - const nonExportedFn = createServerFn().handler((opts, signal) => { - "use server"; - - return nonExportedFn.__executeServer(opts, signal); - });" - `) - - // Server - const compiledResultServer = await compile({ - id: 'test.ts', + // Server caller (route file) - no second argument + const compiledResultServerCaller = await compile({ code, env: 'server', + isProviderFile: false, + mode: 'build', }) - expect(compiledResultServer!.code).toMatchInlineSnapshot(` - "import { createServerFn } from '@tanstack/react-start'; - const exportedVar = 'exported'; - export const exportedFn = createServerFn().handler((opts, signal) => { - "use server"; + expect(await formatSnapshot(compiledResultServerCaller!.code, 'test.ts')) + .toMatchInlineSnapshot(` + "import { createSsrRpc } from '@tanstack/react-start/ssr-rpc' + import { createServerFn } from '@tanstack/react-start' + export const exportedFn = createServerFn().handler( + createSsrRpc( + 'c306c96e9256c7604f2a6022c4c94eb89f863274c022bc45b03970f067ea9864', + ), + ) + const nonExportedFn = createServerFn().handler( + createSsrRpc( + 'f4403dc0b18e216dfe0a9711cab028bc1b9768175daa9236d7115e29c99d76c2', + ), + ) + " + `) - return exportedFn.__executeServer(opts, signal); - }, async () => { - return exportedVar; - }); - const nonExportedVar = 'non-exported'; - const nonExportedFn = createServerFn().handler((opts, signal) => { - "use server"; + // Server provider (extracted file) - has second argument + const compiledResultServerProvider = await compile({ + code, + env: 'server', + isProviderFile: true, + mode: 'build', + }) - return nonExportedFn.__executeServer(opts, signal); - }, async () => { - return nonExportedVar; - });" - `) + expect(await formatSnapshot(compiledResultServerProvider!.code, 'test.ts')) + .toMatchInlineSnapshot(` + "import { createServerRpc } from '@tanstack/react-start/server-rpc' + import { createServerFn } from '@tanstack/react-start' + const exportedVar = 'exported' + const exportedFn_createServerFn_handler = createServerRpc( + { + id: 'c306c96e9256c7604f2a6022c4c94eb89f863274c022bc45b03970f067ea9864', + name: 'exportedFn', + filename: 'src/test.ts', + }, + (opts) => exportedFn.__executeServer(opts), + ) + const exportedFn = createServerFn().handler( + exportedFn_createServerFn_handler, + async () => { + return exportedVar + }, + ) + const nonExportedVar = 'non-exported' + const nonExportedFn_createServerFn_handler = createServerRpc( + { + id: 'f4403dc0b18e216dfe0a9711cab028bc1b9768175daa9236d7115e29c99d76c2', + name: 'nonExportedFn', + filename: 'src/test.ts', + }, + (opts) => nonExportedFn.__executeServer(opts), + ) + const nonExportedFn = createServerFn().handler( + nonExportedFn_createServerFn_handler, + async () => { + return nonExportedVar + }, + ) + export { + exportedFn_createServerFn_handler, + nonExportedFn_createServerFn_handler, + } + " + `) + }) + + test('should use fast path for direct imports from known library (no extra resolveId calls)', async () => { + const code = ` + import { createServerFn } from '@tanstack/react-start' + const myServerFn = createServerFn().handler(async () => { + return 'hello' + })` + + const resolveIdMock = vi.fn(async (id: string) => id) + + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + loadModule: async () => {}, + lookupKinds: new Set(['ServerFn']), + lookupConfigurations: [ + { + libName: '@tanstack/react-start', + rootExport: 'createServerFn', + kind: 'Root', + }, + ], + getKnownServerFns: () => ({}), + resolveId: resolveIdMock, + mode: 'build', + }) + + await compiler.compile({ + code, + id: '/test/src/test.ts', + }) + + // Direct known-library imports use the knownRootImports fast path, so they + // do not need resolveId. + expect(resolveIdMock).not.toHaveBeenCalled() + }) + + test('should use slow path for factory pattern (resolveId called for import resolution)', async () => { + // This simulates a factory pattern where createServerFn is re-exported from a local file + const factoryCode = ` + import { createFooServerFn } from './factory' + const myServerFn = createFooServerFn().handler(async () => { + return 'hello' + })` + + const resolveIdMock = vi.fn(async (id: string) => id) + + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + loadModule: async (id) => { + // Simulate the factory module being loaded + if (id === './factory') { + compiler.ingestModule({ + code: ` + import { createServerFn } from '@tanstack/react-start' + export const createFooServerFn = createServerFn + `, + id: './factory', + }) + } + }, + lookupKinds: new Set(['ServerFn']), + lookupConfigurations: [ + { + libName: '@tanstack/react-start', + rootExport: 'createServerFn', + kind: 'Root', + }, + ], + getKnownServerFns: () => ({}), + resolveId: resolveIdMock, + mode: 'build', + }) + + await compiler.compile({ + code: factoryCode, + id: '/test/src/test.ts', + }) + + // resolveId should only be called for './factory'. Direct known-library + // imports use the knownRootImports fast path. + // + // Note: The factory module's import from '@tanstack/react-start' ALSO uses + // the fast path (knownRootImports), so no additional resolveId call is needed there. + expect(resolveIdMock).toHaveBeenCalledTimes(1) + expect(resolveIdMock).toHaveBeenNthCalledWith( + 1, + './factory', + '/test/src/test.ts', + ) + }) + + test('keeps query-bearing virtual module identities distinct', async () => { + const publicFactoryId = '\0virtual:server-fn-factory?variant=public' + const implementationFactoryId = + '\0virtual:server-fn-factory?variant=implementation' + const virtualModules: Record = { + [publicFactoryId]: ` + import { createIssueServerFn } from 'virtual:server-fn-factory?variant=implementation' + export { createIssueServerFn } + `, + [implementationFactoryId]: ` + import { createServerFn } from '@tanstack/react-start' + export const createIssueServerFn = createServerFn + `, + } + const loadedIds: Array = [] + + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + mode: 'build', + loadModule: async (id) => { + loadedIds.push(id) + const code = virtualModules[id] + if (code) { + compiler.ingestModule({ code, id }) + } + }, + lookupKinds: new Set(['ServerFn']), + lookupConfigurations: [ + { + libName: '@tanstack/react-start', + rootExport: 'createServerFn', + kind: 'Root', + }, + ], + getKnownServerFns: () => ({}), + resolveId: async (source) => { + if (source.startsWith('virtual:server-fn-factory?')) { + return `\0${source}` + } + + return null + }, + }) + + const result = await compiler.compile({ + id: '/test/src/test.ts', + code: ` + import { createIssueServerFn } from 'virtual:server-fn-factory?variant=public' + const issueServerFn = createIssueServerFn().handler(async () => 'ok') + `, + }) + + expect(result).not.toBeNull() + expect(result!.code).toContain('createClientRpc') + expect(loadedIds).toEqual([publicFactoryId, implementationFactoryId]) + }) + + test('should resolve local named re-exports of createServerFn', async () => { + const code = ` + import { createFooServerFn } from './factory' + const myServerFn = createFooServerFn().handler(async () => { + return 'hello' + })` + + const resolveIdMock = vi.fn(async (id: string) => id) + + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + loadModule: async (id) => { + if (id === './factory') { + compiler.ingestModule({ + code: ` + export { createServerFn as createFooServerFn } from '@tanstack/react-start' + `, + id: './factory', + }) + } + }, + lookupKinds: new Set(['ServerFn']), + lookupConfigurations: [ + { + libName: '@tanstack/react-start', + rootExport: 'createServerFn', + kind: 'Root', + }, + ], + getKnownServerFns: () => ({}), + resolveId: resolveIdMock, + mode: 'build', + }) + + const result = await compiler.compile({ + code, + id: '/test/src/test.ts', + }) + + expect(result).not.toBeNull() + expect(result!.code).toContain('createClientRpc') + expect(resolveIdMock).toHaveBeenCalledTimes(1) + expect(resolveIdMock).toHaveBeenNthCalledWith( + 1, + './factory', + '/test/src/test.ts', + ) + }) + + test('should resolve export-star re-export chains of createServerFn', async () => { + const code = ` + import { createFooServerFn } from './factory' + const myServerFn = createFooServerFn().handler(async () => { + return 'hello' + })` + + const resolveIdMock = vi.fn(async (id: string) => id) + + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + loadModule: async (id) => { + if (id === './factory') { + compiler.ingestModule({ + code: ` + export * from './factory-inner' + `, + id: './factory', + }) + } + + if (id === './factory-inner') { + compiler.ingestModule({ + code: ` + export { createServerFn as createFooServerFn } from '@tanstack/react-start' + `, + id: './factory-inner', + }) + } + }, + lookupKinds: new Set(['ServerFn']), + lookupConfigurations: [ + { + libName: '@tanstack/react-start', + rootExport: 'createServerFn', + kind: 'Root', + }, + ], + getKnownServerFns: () => ({}), + resolveId: resolveIdMock, + mode: 'build', + }) + + const result = await compiler.compile({ + code, + id: '/test/src/test.ts', + }) + + expect(result).not.toBeNull() + expect(result!.code).toContain('createClientRpc') + expect(resolveIdMock).toHaveBeenCalledTimes(2) + expect(resolveIdMock).toHaveBeenNthCalledWith( + 1, + './factory', + '/test/src/test.ts', + ) + expect(resolveIdMock).toHaveBeenNthCalledWith( + 2, + './factory-inner', + './factory', + ) + }) + + test('reuses deduped custom IDs across compiler instances', async () => { + const serverFnsById: Record< + string, + { + functionName: string + functionId: string + extractedFilename: string + filename: string + isClientReferenced?: boolean + } + > = {} + + function createCompiler() { + return new StartCompiler({ + env: 'server', + ...getDefaultTestOptions('server'), + mode: 'build', + loadModule: async () => {}, + lookupKinds: new Set(['ServerFn']), + lookupConfigurations: [ + { + libName: '@tanstack/react-start', + rootExport: 'createServerFn', + kind: 'Root', + }, + ], + resolveId: async (id) => id, + generateFunctionId: ({ functionName }) => + functionName === 'greetUser_createServerFn_handler' + ? 'constant_id' + : undefined, + getKnownServerFns: () => serverFnsById, + onServerFnsById: (discovered) => { + Object.assign(serverFnsById, discovered) + }, + }) + } + + const firstCompiler = createCompiler() + await firstCompiler.compile({ + code: ` + import { createServerFn } from '@tanstack/react-start' + export const greetUser = createServerFn().handler(async () => 'first') + `, + id: '/test/src/submit-post-formdata.tsx', + }) + + await firstCompiler.compile({ + code: ` + import { createServerFn } from '@tanstack/react-start' + export const greetUser = createServerFn().handler(async () => 'second') + `, + id: '/test/src/formdata-redirect/index.tsx', + }) + + expect( + Object.values(serverFnsById) + .map((serverFn) => serverFn.functionId) + .sort(), + ).toEqual(['constant_id', 'constant_id_1']) + + const secondCompiler = createCompiler() + const firstResult = await secondCompiler.compile({ + code: ` + import { createServerFn } from '@tanstack/react-start' + export const greetUser = createServerFn().handler(async () => 'first') + `, + id: '/test/src/submit-post-formdata.tsx', + }) + + const secondResult = await secondCompiler.compile({ + code: ` + import { createServerFn } from '@tanstack/react-start' + export const greetUser = createServerFn().handler(async () => 'second') + `, + id: '/test/src/formdata-redirect/index.tsx', + }) + + expect(firstResult!.code).toContain('createSsrRpc("constant_id"') + expect(secondResult!.code).toContain('createSsrRpc("constant_id_1"') + }) + + // The client puts the id in the URL unencoded and the server reads that + // path segment back: a `/`, `#` or `?` cut it short (the call ran another + // server function of the file or none), a client percent-encodes `"`, + // `\`, whitespace, control and non-ASCII characters, URL parsing removes + // dot segments, and the server decodes a percent-encoding to another id or + // rejects it. + test.each([ + 'users/get', + 'users#get', + 'users?get', + 'users"get', + 'users\\get', + 'users get', + 'users\u0007get', + 'utilisateurs-é', + '..', + 'users%41get', + 'x%c3%a9', + '%2E', + 'users%zz', + ])( + 'a custom id the URL never carries whole fails the build: %j', + async (id) => { + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + mode: 'build', + loadModule: async () => {}, + lookupKinds: new Set(['ServerFn']), + lookupConfigurations: [ + { + libName: '@tanstack/react-start', + rootExport: 'createServerFn', + kind: 'Root', + }, + ], + resolveId: async (id) => id, + generateFunctionId: () => id, + getKnownServerFns: () => ({}), + }) + await expect( + compiler.compile({ + code: ` + import { createServerFn } from '@tanstack/react-start' + export const getUser = createServerFn().handler(async () => 'user') + `, + id: '/test/src/users.ts', + }), + ).rejects.toThrow( + `[tanstack-start] serverFns.generateFunctionId returned ${JSON.stringify(id)} for the server function getUser (functionName "getUser_createServerFn_handler") of src/users.ts.`, + ) + }, + ) + + test('should resolve createServerFn from the same binding as a known root export', async () => { + const virtualModules: Record = { + '@tanstack/start-client-core': ` + export { createServerFn } from './createServerFn' + `, + '/virtual/compiler-known/server-fn-factory.ts': ` + export const createServerFn = () => ({ + handler: () => createServerFn(), + }) + `, + } + + const compiler = new StartCompiler({ + env: 'client', + ...getDefaultTestOptions('client'), + root: '/test', + mode: 'build', + loadModule: async (id) => { + const code = virtualModules[id] + if (code) { + compiler.ingestModule({ code, id }) + } + }, + lookupKinds: new Set(['ServerFn']), + lookupConfigurations: [], + getKnownServerFns: () => ({}), + resolveId: async (source) => { + if (source === '@tanstack/start-client-core') { + return '@tanstack/start-client-core' + } + + if (source === './createServerFn') { + return '/virtual/compiler-known/server-fn-factory.ts' + } + + return null + }, + }) + + const result = await compiler.compile({ + id: '/test/src/internal-server-fn.ts', + code: ` + import { createServerFn } from './createServerFn' + + export const getMessage = createServerFn().handler(() => { + return 'server-only-value' + }) + `, + }) + + expect(result).not.toBeNull() + expect(result!.code).toContain('createClientRpc') + expect(result!.code).not.toContain('server-only-value') }) }) diff --git a/packages/start-plugin-core/tests/createServerFn/declaration-sites.test.ts b/packages/start-plugin-core/tests/createServerFn/declaration-sites.test.ts new file mode 100644 index 0000000000..f42a13cdba --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/declaration-sites.test.ts @@ -0,0 +1,122 @@ +import { expect, test } from 'vitest' +import { compileFor, outputs } from '../regression-helpers' +import { getModuleErrors } from '../validate-module' + +const head = `import { createServerFn } from '@tanstack/react-start'\n` +const top = `export const top = createServerFn().handler(async () => 'top')\n` +const inFunction = `export function make() { + const fn = createServerFn().handler(async () => 'nested') + return fn +}` +const inSwitchCase = `export function pick(kind: string) { + switch (kind) { + case 'a': + const fn = createServerFn().handler(async () => 'nested') + return fn + } +}` + +// A `createServerFn` declared below the module top level must not produce an +// invalid module, and top-level server fns next to it are still extracted. +// Rejecting it with a compile error is valid too, but not crashing on it. +// Known limitation on main: only module-level declarations are extracted; the +// nested one is left untransformed, so its handler ships to the client. Which +// nested server fns are extracted is left open here. +test.each([ + { name: 'a function', code: inFunction, topLevel: [] }, + { + name: 'a switch case inside a function', + code: inSwitchCase, + topLevel: [], + }, + { + name: 'a switch case at the module top level', + code: `switch (import.meta.env.MODE) { + case 'a': + const fn = createServerFn().handler(async () => 'nested') + console.log(fn) +}`, + topLevel: [], + }, + { + name: 'a function next to a top-level one', + code: `${top}${inFunction}`, + topLevel: ['top'], + }, + { + name: 'a switch case next to a top-level one', + code: `${top}${inSwitchCase}`, + topLevel: ['top'], + }, +])( + 'a server fn declared in $name compiles to valid modules or is rejected', + async ({ code, topLevel }) => { + const errors: Record> = {} + for (const output of outputs) { + let result: Awaited> + try { + result = await compileFor(output, `${head}${code}`) + } catch (error) { + expect((error as Error).message, output).not.toMatch( + /Expected createServerFn declaration in a statement list/, + ) + continue + } + errors[output] = + result.code === null ? [] : await getModuleErrors(result.code) + if (output === 'client') { + const extractedNames = Object.values(result.serverFns).map( + (fn) => fn.functionName, + ) + expect(extractedNames).toEqual( + expect.arrayContaining( + topLevel.map((name) => `${name}_createServerFn_handler`), + ), + ) + } + } + for (const [output, moduleErrors] of Object.entries(errors)) { + expect(moduleErrors, output).toEqual([]) + } + }, +) + +// A server fn must be a variable initializer; anywhere else it is rejected +// in every output instead of being shipped untransformed. +// Known limitation on main: with createServerFn as the only factory import +// these modules are returned untransformed, so the extra import is needed. +const rejectionHead = `import { createServerFn, createServerOnlyFn } from '@tanstack/react-start'\n` +test.each([ + { + name: 'an object property', + code: `export const api = { read: createServerFn().handler(async () => 1) }`, + error: 'createServerFn must be assigned to a variable!', + }, + { + name: 'a class field', + code: `export class Api { read = createServerFn().handler(async () => 1) }`, + error: 'createServerFn must be assigned to a variable!', + }, + { + name: 'an anonymous default export', + code: `export default createServerFn().handler(async () => 1)`, + error: 'createServerFn must be assigned to a variable!', + }, + { + name: 'an assignment', + code: `export let fn\nfn = createServerFn().handler(async () => 1)`, + error: 'createServerFn must be assigned to a variable!', + }, + { + name: 'a validator call without a validator', + code: `export const fn = createServerFn().validator().handler(async () => 1)`, + error: 'createServerFn().validator() must be called with a validator!', + }, +])('rejects $name', async ({ code, error }) => { + for (const output of outputs) { + await expect( + compileFor(output, `${rejectionHead}${code}`), + output, + ).rejects.toThrow(error) + } +}) diff --git a/packages/start-plugin-core/tests/createServerFn/exports-and-directives.test.ts b/packages/start-plugin-core/tests/createServerFn/exports-and-directives.test.ts new file mode 100644 index 0000000000..7f16dd2cc7 --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/exports-and-directives.test.ts @@ -0,0 +1,421 @@ +import { describe, expect, test } from 'vitest' +import { + callProvider, + compileAll, + compileCode, + compileFor, + evaluateModule, + importSources, +} from '../regression-helpers' + +// Callers keep the module's exports, with each server fn replaced by an RPC; +// the provider module only exports the extracted handlers. Module directives, +// ids and module formats must survive both rewrites. + +const head = `import { createServerFn } from '@tanstack/react-start'\n` + +/** `functionName -> functionId` of the server fns a compilation reported. */ +function idsByName(serverFns: Record) { + return Object.fromEntries( + Object.entries(serverFns).map(([id, fn]) => [fn.functionName, id]), + ) +} + +describe('export forms', () => { + // Source: Next.js server-actions fixtures server-graph/9, /12, /13, /29, + // /66, /69, client-graph/4, /15 + test('callers keep every export form and the provider exports only the handlers', async () => { + const compiled = + await compileAll(`${head}const a = createServerFn().handler(async () => 'a') +const b = createServerFn().handler(async () => 'b') +const c = createServerFn().handler(async () => 'c') +export const d = createServerFn().handler(async () => 'd'), + notAServerFn = 1 +export let e = createServerFn().handler(async () => 'e') +export var f = createServerFn().handler(async () => 'f') +export { a as default, b as '📙', c as as }`) + const ids = idsByName(compiled.serverFns) + const exported = { + default: 'a', + '📙': 'b', + as: 'c', + d: 'd', + e: 'e', + f: 'f', + } + for (const [output, rpc] of [ + ['client', 'client'], + ['ssr', 'ssr'], + ] as const) { + const module = await evaluateModule(compiled[output]) + expect({ ...module }).toEqual({ + notAServerFn: 1, + ...Object.fromEntries( + Object.entries(exported).map(([name, local]) => [ + name, + { rpc: { [rpc]: ids[`${local}_createServerFn_handler`] } }, + ]), + ), + }) + } + const provider = await evaluateModule(compiled.provider) + const locals = ['a', 'b', 'c', 'd', 'e', 'f'] + expect(Object.keys(provider).sort()).toEqual( + locals.map((local) => `${local}_createServerFn_handler`), + ) + for (const local of locals) { + expect(await callProvider(provider, local)).toBe(local) + } + }) + + // Source: Next.js server-actions fixtures client-graph/1, server-graph/10, /11, /15 + test.each([ + `export default async function () {\n return fn()\n}`, + `export default class {\n call() {\n return fn()\n }\n}`, + ])('an anonymous default export next to a server fn: %s', async (code) => { + const { client, provider } = await compileAll( + `${head}export const fn = createServerFn().handler(async () => 1)\n${code}`, + ) + expect((await evaluateModule(client)).default).toBeTypeOf('function') + expect(await callProvider(provider, 'fn')).toBe(1) + }) + + // Source: @vitejs/plugin-rsc source-map/wrap-export/local-export-before-declaration.js + test('an export list before the server fn declaration', async () => { + const compiled = await compileAll(`${head}export { fn, fn as alias } +const fn = createServerFn().handler(async () => 'fn')`) + const client = await evaluateModule(compiled.client) + expect(client.alias).toBe(client.fn) + expect(client.fn.rpc).toHaveProperty('client') + expect(await callProvider(compiled.provider, 'fn')).toBe('fn') + }) + + // Source: @vitejs/plugin-rsc source-map/wrap-export/dependent-declarators.js + test('a server fn built from a sibling declarator', async () => { + const compiled = await compileAll(`${head}import { db } from './db.server' +export const base = createServerFn(), fn = base.handler(async () => db.x())`) + expect(importSources(compiled.client)).toEqual([]) + expect( + await callProvider(compiled.provider, 'fn', { + './db.server': `export const db = { x: () => 'x' }`, + }), + ).toBe('x') + }) + + // Source: @vitejs/plugin-rsc wrap-export.test.ts "re-export simple", + // "re-export rename", "re-export all simple", "re-export all rename" + test('re-exports stay in the callers', async () => { + const compiled = await compileAll(`${head}export { x } from './dep' +export { x as y } from './dep' +export * from './star' +export * as ns from './dep' +export const fn = createServerFn().handler(async () => 'fn')`) + const stubs = { + './dep': `export const x = 'x'`, + './star': `export const starred = 'starred'`, + } + for (const caller of [compiled.client, compiled.ssr]) { + const module = await evaluateModule(caller, stubs) + expect(Object.keys(module).sort()).toEqual([ + 'fn', + 'ns', + 'starred', + 'x', + 'y', + ]) + expect([module.x, module.y, module.starred, module.ns.x]).toEqual([ + 'x', + 'x', + 'starred', + 'x', + ]) + } + expect(await callProvider(compiled.provider, 'fn', stubs)).toBe('fn') + }) + + // JSON modules only load with their `type: 'json'` attribute. + // Source: @vitejs/plugin-rsc source-map/wrap-export/reexport-attributes.js; + // Turbopack tree-shaker analyzer/import-with-clause + test('import attributes are kept on the imports and re-exports each output keeps', async () => { + const compiled = + await compileAll(`${head}import config from './config.json' with { type: 'json' } +import secrets from './secrets.json' with { type: 'json' } +export { default as data } from './data.json' with { type: 'json' } +export const theme = config.theme +export const fn = createServerFn().handler(async () => secrets.key)`) + const stubs = { + './config.json': `{ "theme": "dark" }`, + './data.json': `{ "data": true }`, + './secrets.json': `{ "key": "s3cret" }`, + } + for (const caller of [compiled.client, compiled.ssr]) { + expect(importSources(caller)).toEqual(['./config.json', './data.json']) + const module = await evaluateModule(caller, stubs) + expect([module.theme, module.data]).toEqual(['dark', { data: true }]) + } + expect(await callProvider(compiled.provider, 'fn', stubs)).toBe('s3cret') + }) + + // Source: Next.js server-actions fixtures server-graph/60, /62, /68, /72 + test('TypeScript-only exports and an enum next to a server fn', async () => { + const { provider } = + await compileAll(`${head}import type { Stuff } from './stuff' +export type X = string +export { type A } from './a' +export type { B } from './b' +export type * from './c' +export type { Foo } +type Foo = string +export interface I {} +export enum E { + A = 'a', +} +export declare const declared: number +export default interface D {} +export const fn = createServerFn().handler(async (): Promise => E.A)`) + expect(await callProvider(provider, 'fn')).toBe('a') + }) + + // Source: Next.js server-actions fixtures client-graph/2 + test('side-effect imports and top-level statements stay in every output', async () => { + const compiled = await compileAll(`${head}import './polyfill' +console.log('side-effect-marker') +export const fn = createServerFn().handler(async () => 'fn')`) + for (const output of [compiled.client, compiled.ssr, compiled.provider]) { + expect(importSources(output)).toEqual(['./polyfill']) + expect(output).toContain('side-effect-marker') + } + }) + + test('redeclared var server fns get distinct versioned handler names', async () => { + const code = `${head}var fn = createServerFn().handler(async () => 1) +var fn = createServerFn().handler(async () => 2) +export { fn }` + const { serverFns } = await compileFor('client', code) + const names = ['fn_createServerFn_handler', 'fn_createServerFn_handler_1'] + expect(Object.keys(idsByName(serverFns)).sort()).toEqual(names) + const provider = await evaluateModule( + (await compileCode('provider', code))!, + ) + expect(Object.keys(provider).sort()).toEqual(names) + }) +}) + +describe('directives', () => { + // Source: Next.js server-actions fixtures server-graph/8 + test('handler directives stay in the provider', async () => { + const { provider } = + await compileAll(`${head}export const fn = createServerFn().handler(async function () { + 'use strict' + 'use server' + return 1 +})`) + expect(provider).toMatch(/(["'])use strict\1;?\s*(["'])use server\2/) + expect(await callProvider(provider, 'fn')).toBe(1) + }) + + // Source: Next.js server-actions fixtures server-graph/3, /4; + // @vitejs/plugin-rsc utils.test.ts "recognizes directive prologues" + test.each([ + { prologue: `'use client'\n`, directives: ['use client'] }, + { prologue: `// app/send.ts\n'use server'\n`, directives: ['use server'] }, + { + prologue: `'use strict'\n'use client'\n`, + directives: ['use strict', 'use client'], + }, + ])( + 'module directives stay first in the callers: $directives', + async ({ prologue, directives }) => { + const code = `${prologue}${head}export const fn = createServerFn().handler(async () => 1)` + const prologuePattern = new RegExp( + String.raw`^(?:\s*//[^\n]*\n)*` + + directives + .map((directive) => String.raw`\s*['"]${directive}['"];?`) + .join(''), + ) + for (const output of ['client', 'ssr'] as const) { + expect(await compileCode(output, code)).toMatch(prologuePattern) + } + }, + ) + + // `serverFnProviderModuleDirectives` start the provider's prologue once, + // ahead of the generated imports. + // Source: @vitejs/plugin-rsc utils.test.ts "recognizes directive prologues" + test.each([`'use server'\n`, `'use strict'\n'use server'\n`])( + 'a provider whose prologue already has the configured directive keeps one: %j', + async (prologue) => { + const provider = await compileCode( + 'provider', + `${prologue}${head}export const fn = createServerFn().handler(async () => 1)`, + { directives: ['use server', '', 'use server'] }, + ) + expect(provider).toMatch( + /^(?:\s*(["'])use strict\1;?)?\s*(["'])use server\2/, + ) + expect(provider!.match(/["']use server["']/g)).toHaveLength(1) + }, + ) + + test.each([`import './setup'\n'use server'\n`, `('use server')\n`])( + 'a "use server" string outside the prologue is not the configured directive: %j', + async (prologue) => { + const provider = await compileCode( + 'provider', + `${prologue}${head}export const fn = createServerFn().handler(async () => 1)`, + { directives: ['use server'] }, + ) + expect(provider).toMatch(/^\s*(["'])use server\1/) + }, + ) +}) + +describe('server function ids', () => { + const decodeDevId = (id: string) => + JSON.parse(Buffer.from(id, 'base64url').toString('utf8')) + + test('dev ids encode the provider module and the handler export', async () => { + const { serverFns } = await compileFor( + 'client', + `${head}export const getPosts = createServerFn().handler(async () => [])`, + { mode: 'dev' }, + ) + expect(Object.keys(serverFns).map(decodeDevId)).toEqual([ + { + file: '/@id/src/module.tsx?tss-serverfn-split', + export: 'getPosts_createServerFn_handler', + }, + ]) + }) + + test('dev providers export the handler and accept HMR updates', async () => { + const provider = await compileCode( + 'provider', + `${head}export const getPosts = createServerFn().handler(async () => 'posts')`, + { mode: 'dev' }, + ) + expect(provider).toContain('import.meta.hot.accept(') + expect(provider).toContain('import.meta.webpackHot.accept(') + expect(await callProvider(provider!, 'getPosts')).toBe('posts') + }) + + /** `functionName -> functionId` of the server fns in `code`. */ + async function idsOf( + code: string, + options: Parameters[2] = {}, + ) { + return idsByName( + (await compileFor('client', `${head}${code}`, options)).serverFns, + ) + } + + // Source: SolidStart compile.spec.ts "keeps ids of existing functions when a + // function is added above them", "keeps production ids stable ..." + test.each(['build', 'dev'] as const)( + '%s: ids of existing server fns survive adding one above them', + async (mode) => { + const existing = `export const load = createServerFn().handler(async () => 1) +export const save = createServerFn().handler(async () => 2)` + const before = await idsOf(existing, { mode }) + const after = await idsOf( + `export const added = createServerFn().handler(async () => 0)\n${existing}`, + { mode }, + ) + expect(Object.keys(after)).toHaveLength(3) + expect(after).toMatchObject(before) + }, + ) + + // Source: SolidStart compile.spec.ts "does not ship source names in production ids" + test('build ids do not ship source names', async () => { + const [id] = Object.values( + await idsOf( + `export const loadSecretReport = createServerFn().handler(async () => 1)`, + ), + ) + for (const text of [ + id!, + Buffer.from(id!, 'base64url').toString('latin1'), + ]) { + expect(text).not.toMatch(/loadSecretReport|module|src/) + } + }) + + // Source: SolidStart compile.spec.ts "tells apart two functions that share a + // name", "keeps client and server ids aligned" + test('server fns that share a name in different files get distinct ids the provider uses', async () => { + const code = `${head}export const load = createServerFn().handler(async () => 1)` + const ids: Array = [] + for (const id of ['/test/src/a.tsx', '/test/src/b/a.tsx']) { + const [functionId] = Object.keys( + (await compileFor('client', code, { id })).serverFns, + ) + const provider = await evaluateModule( + (await compileCode('provider', code, { id }))!, + ) + expect(provider.load_createServerFn_handler.meta.id).toBe(functionId) + ids.push(functionId!) + } + expect(new Set(ids).size).toBe(2) + }) + + // Source: Next.js server-actions fixtures server-graph/66, client-graph/15 + test('non-ASCII and symbol-like server fn names', async () => { + const names = ['ñandú', '𝑓', 'ᾩ', '$', '_', '$fn'] + const compiled = await compileAll( + head + + names + .map( + (name) => + `export const ${name} = createServerFn().handler(async () => '${name}')`, + ) + .join('\n'), + ) + expect(Object.keys(idsByName(compiled.serverFns)).sort()).toEqual( + names.map((name) => `${name}_createServerFn_handler`).sort(), + ) + const provider = await evaluateModule(compiled.provider) + for (const name of names) { + expect(provider[`${name}_createServerFn_handler`].meta.name).toBe(name) + expect(await callProvider(provider, name)).toBe(name) + } + }) +}) + +describe('module formats', () => { + // The provider appends its exports after the last statement. + // Source: Waku vite-plugin-allow-server.test.ts "transforms with trailing + // comment without new lines" + test.each([ + { end: '\n// trailing', mode: 'build' }, + { end: '\r\n// trailing', mode: 'build' }, + { end: '\n// trailing', mode: 'dev' }, + ] as const)( + '$mode: a provider for a module ending in a line comment without a newline: $end', + async ({ end, mode }) => { + const provider = await compileCode( + 'provider', + `${head}export const fn = createServerFn().handler(async () => 'handler')${end}`, + { mode }, + ) + expect(await callProvider(provider!, 'fn')).toBe('handler') + }, + ) + + // .cts/.mts sources are TypeScript without JSX. + // Source: @vitejs/plugin-rsc cjs.test.ts (fixtures/cjs) + test.each(['/test/src/fn.cts', '/test/src/fn.mts'])( + '%s may use angle-bracket type assertions', + async (id) => { + const { code, serverFns } = await compileFor( + 'client', + `${head}import { db } from './db.server' +const n = (1 as unknown) +export const fn = createServerFn().handler(async () => [n, db.x()])`, + { id }, + ) + expect(Object.keys(serverFns)).toHaveLength(1) + expect(importSources(code!)).toEqual([]) + }, + ) +}) diff --git a/packages/start-plugin-core/tests/createServerFn/handler-scope.test.ts b/packages/start-plugin-core/tests/createServerFn/handler-scope.test.ts new file mode 100644 index 0000000000..2f94d1b465 --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/handler-scope.test.ts @@ -0,0 +1,363 @@ +import { expect, test } from 'vitest' +import { + callProvider, + compileAll, + compileCode, + evaluateModule, + importSources, +} from '../regression-helpers' + +// The provider module runs the extracted handler: it must keep every module +// binding the handler closes over, however the handler is written and +// however its scopes shadow module names. + +const head = `import { createServerFn } from '@tanstack/react-start'\n` +const dbServer = `export const db = { x: () => 'x', y: () => 'y' }` + +// Source: Next.js server-actions fixtures server-graph/5, /6, /16 +test('the provider keeps every kind of module binding the handler reads', async () => { + const { client, provider } = + await compileAll(`${head}import * as ns from './ns' +var counter = 4 +class Repo { + static get() { + return 'repo' + } +} +enum Role { + Admin = 'admin', +} +export const fn = createServerFn().handler(async () => [ns.x, counter, Repo.get(), Role.Admin])`) + expect(importSources(client)).toEqual([]) + expect( + await callProvider(provider, 'fn', { './ns': `export const x = 'ns'` }), + ).toEqual(['ns', 4, 'repo', 'admin']) +}) + +test.each<{ + name: string + code: string + expected: unknown + read?: (value: any) => Promise +}>([ + { + // Source: Next.js server-actions fixtures server-graph/7, /44 + name: 'a named function expression', + code: `export const fn = createServerFn().handler(async function deleteItem() { + return deleteItem.name + db.x() +})`, + expected: 'deleteItemx', + }, + { + // Source: Next.js server-actions fixtures server-graph/59 + name: 'a function using this, arguments and new.target', + code: `export const fn = createServerFn().handler(async function (this: unknown) { + return [typeof this, arguments.length, new.target === undefined, db.x()] +})`, + expected: ['undefined', 1, true, 'x'], + }, + { + // Source: Next.js server-actions fixtures server-graph/14 (streaming) + name: 'an async generator', + code: `export const fn = createServerFn().handler(async function* () { + yield db.x() + yield 'done' +})`, + read: async (iterator: AsyncIterable) => { + const values: Array = [] + for await (const value of iterator) { + values.push(value) + } + return values + }, + expected: ['x', 'done'], + }, + { + // Source: Next.js server-actions fixtures server-graph/31 + name: 'an object literal method', + code: `export const fn = createServerFn().handler({ + async f() { + return db.x() + }, +}.f)`, + expected: 'x', + }, + { + // Source: Next.js server-actions fixtures server-graph/21, /26 + name: 'a wrapper call', + code: `import { withAuth } from './auth.server' +export const fn = createServerFn().handler(withAuth(async () => db.x()))`, + expected: 'auth:x', + }, + { + // Source: Next.js server-actions fixtures server-graph/25 + name: 'a function declared after the server fn', + code: `export const fn = createServerFn().handler(impl) +async function impl() { + return inner() + async function inner() { + return db.x() + } +}`, + expected: 'x', + }, + { + // Source: Next.js server-actions fixtures server-graph/28, /30 + name: 'a call of a server fn declared later', + code: `export const fn = createServerFn().handler(async () => (await later()) + db.x()) +export const later = createServerFn().handler(async () => 'later:')`, + expected: 'later:x', + }, + { + name: 'a parenthesized non-null initializer', + code: `export const fn = (createServerFn().handler(async () => db.x()))!`, + expected: 'x', + }, +])( + 'the handler can be $name', + async ({ code, expected, read = async (value) => value }) => { + const compiled = await compileAll( + `${head}import { db } from './db.server'\n${code}`, + ) + for (const caller of [compiled.client, compiled.ssr]) { + expect(importSources(caller)).toEqual([]) + } + const value = await callProvider(compiled.provider, 'fn', { + './db.server': dbServer, + './auth.server': `export const withAuth = (fn) => async (opts) => 'auth:' + (await fn(opts))`, + }) + expect(await read(value)).toEqual(expected) + }, +) + +// Each handler reads the module binding `value` (or `key`) through a scope +// that also declares, or seems to declare, the same name. +test.each<{ name: string; code: string; data?: unknown; expected: unknown }>([ + { + // Source: @vitejs/plugin-rsc hoist/function-hoist-block.js (block-level + // functions are block scoped in modules) + name: 'past a function declared in a nested block', + code: `const value = 'outer' +export const fn = createServerFn().handler(async () => { + const seen = value + { + function value() {} + } + return seen +})`, + expected: 'outer', + }, + { + // Source: @vitejs/plugin-rsc hoist/catch-binding-shadow.js + name: 'past a catch parameter of the same name', + code: `const value = { message: 'outer' } +export const fn = createServerFn().handler(async () => { + const readOuter = () => value.message + try { + throw new Error('inner') + } catch (value) { + return [value.message, readOuter()] + } +})`, + expected: ['inner', 'outer'], + }, + { + // Source: @vitejs/plugin-rsc hoist/class-declaration-in-body.js + name: 'from a class declared in the handler', + code: `const value = 'outer' +export const fn = createServerFn().handler(async () => { + class Helper { + run() { + return value + } + } + return new Helper().run() +})`, + expected: 'outer', + }, + { + // Source: @vitejs/plugin-rsc hoist/computed-destructuring-key-captures-outer-binding.js + name: 'through a computed destructuring key', + code: `const key = 'value' +export const fn = createServerFn().handler(async ({ data }) => { + const { [key]: picked } = data + return picked +})`, + data: { value: 'picked' }, + expected: 'picked', + }, + { + // Source: @vitejs/plugin-rsc hoist/destructured-param-default-bound.js + name: 'from a destructured parameter default', + code: `const value = 'outer' +export const fn = createServerFn().handler(async ({ data: { x = value } = {} }) => x)`, + expected: 'outer', + }, + { + // Source: @vitejs/plugin-rsc scope/param-default-var-hoisting.js + // (parameter defaults do not see var declarations of the body) + name: 'from a parameter default next to a var of the same name', + code: `const value = 'outer' +export const fn = createServerFn().handler(async ({ data = value }) => { + var value = 'inner' + return [data, value] +})`, + expected: ['outer', 'inner'], + }, + { + // Source: @vitejs/plugin-rsc hoist/shadow-partial-if-block-over-outer-local.js + name: 'past a block that shadows it in one branch', + code: `const value = 'outer' +export const fn = createServerFn().handler(async () => { + const pick = (flag: boolean) => { + if (flag) { + const value = 'inner' + return value + } + return value + } + return [pick(true), pick(false)] +})`, + expected: ['inner', 'outer'], + }, + { + // Source: @vitejs/plugin-rsc scope/let-const-block.js; + // typescript-eslint class/declaration/static-block.js + name: 'next to loop, switch and static block locals of the same name', + code: `const value = 'outer' +export const fn = createServerFn().handler(async ({ data }) => { + const out = [] + for (let value = 0; value < 1; value++) out.push(value) + switch (data) { + case 1: { + const value = 'case' + out.push(value) + } + default: + out.push(value) + } + class Block { + static read + static { + Block.read = value + } + } + out.push(Block.read) + return out +})`, + data: 1, + expected: [0, 'case', 'outer', 'outer'], + }, + { + // Source: @vitejs/plugin-rsc hoist/self-ref-inner-shadow.js + name: 'next to an inner function expression named like the server fn', + code: `const value = 1 +export const fn = createServerFn().handler(async ({ data }) => { + const result = (function fn(m) { + return m > 0 ? fn(m - 1) : 0 + })(data) + return value + result +})`, + data: 3, + expected: 1, + }, + { + // Source: @vitejs/plugin-rsc hoist/methods.js + name: 'as computed method names', + code: `const key = 'computed' +export const fn = createServerFn().handler(async () => { + const api = { async [key]() {} } + class Actions { + static async [key]() { + return 'static' + } + } + return [Object.keys(api), await Actions[key]()] +})`, + expected: [['computed'], 'static'], + }, + { + // Source: @vitejs/plugin-rsc scope/label.js (labels are not references) + name: 'next to a label of the same name', + code: `const value = 'outer' +export const fn = createServerFn().handler(async () => { + value: for (const item of [1, 2]) { + if (item) { + break value + } + } + return value +})`, + expected: 'outer', + }, + { + // Source: React Compiler fixtures (tagged templates) + name: 'as a template tag', + code: `const value = (strings: TemplateStringsArray, n: number) => strings[0] + n +export const fn = createServerFn().handler(async () => value\`id-\${1}\`)`, + expected: 'id-1', + }, + { + // Source: React Compiler fixtures (shorthand properties) + name: 'as a shorthand property', + code: `const value = 'outer' +export const fn = createServerFn().handler(async () => ({ value }))`, + expected: { value: 'outer' }, + }, +])( + 'the provider keeps a module binding the handler reads $name', + async ({ code, data, expected }) => { + const provider = await compileCode('provider', `${head}${code}`) + expect(await callProvider(provider!, 'fn', {}, data)).toEqual(expected) + }, +) + +// Source: @vitejs/plugin-rsc hoist/self-ref-nested-function.js, +// hoist/direct-recursion-self-binding.js +test('a handler can call its own server fn', async () => { + const provider = await compileCode( + 'provider', + `${head}export const fn = createServerFn().handler(async ({ data }) => + data > 0 ? fn({ data: data - 1 }) : 'done')`, + ) + expect(await callProvider(provider!, 'fn', {}, 2)).toBe('done') +}) + +// Source: @vitejs/plugin-rsc hoist/captured-local-assignment.js, +// wrap-export.test.ts "preserve reference" +test('a handler and client code can both update an exported let', async () => { + const compiled = await compileAll(`${head}export let count = 0 +export function changeCount() { + count += 1 + return count +} +export const bump = createServerFn().handler(async () => ++count)`) + const client = await evaluateModule(compiled.client) + expect(client.changeCount()).toBe(1) + expect(client.count).toBe(1) + const provider = await evaluateModule(compiled.provider) + expect(await callProvider(provider, 'bump')).toBe(1) + expect(await callProvider(provider, 'bump')).toBe(2) +}) + +// Source: Next.js server-actions fixtures server-graph/27 +test('exported helpers the handler uses stay declared in the provider', async () => { + const { provider } = await compileAll(`${head}import { db } from './db.server' +export async function load() { + return db.x() +} +export default function helper() { + return db.y() +} +export class Repo { + static z() { + return 'z' + } +} +const local = () => 'w' +export { local as alias } +export const fn = createServerFn().handler(async () => [await load(), helper(), Repo.z(), local()])`) + expect( + await callProvider(provider, 'fn', { './db.server': dbServer }), + ).toEqual(['x', 'y', 'z', 'w']) +}) diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx index c308ef0512..88e8607da2 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnDestructured.tsx @@ -1,50 +1,39 @@ -import { createServerFn } from '@tanstack/react-start'; -export const withUseServer = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withUseServer.__executeServer(opts, signal); -}); -export const withArrowFunction = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withArrowFunction.__executeServer(opts, signal); -}); +import { createClientRpc } from '@tanstack/react-start/client-rpc' +import { createServerFn } from '@tanstack/react-start' +export const withUseServer = createServerFn({ method: 'GET' }).handler( + createClientRpc( + 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', + ), +) +export const withArrowFunction = createServerFn({ method: 'GET' }).handler( + createClientRpc( + 'a311dfd9a6554bc0bb9371ef4fbc72c852d0b5532829a2613a29157b8595a793', + ), +) export const withArrowFunctionAndFunction = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withArrowFunctionAndFunction.__executeServer(opts, signal); -}); -export const withoutUseServer = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withoutUseServer.__executeServer(opts, signal); -}); -export const withVariable = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withVariable.__executeServer(opts, signal); -}); -export const withZodValidator = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withZodValidator.__executeServer(opts, signal); -}); -export const withValidatorFn = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withValidatorFn.__executeServer(opts, signal); -}); \ No newline at end of file + method: 'GET', +}).handler( + createClientRpc( + 'dbe1f77c6ea7590bce3212a75b06d3cee83b425bcf493014cb47462ef725e36e', + ), +) +export const withoutUseServer = createServerFn({ method: 'GET' }).handler( + createClientRpc( + 'c0d9fdeb2b01aafecc782f439416b86f666cb5334ac9a934546b177e5698bbb2', + ), +) +export const withVariable = createServerFn({ method: 'GET' }).handler( + createClientRpc( + '7d36cb30c30bd688b9773bd7f85a0d51d83f868255e127605e4f236615fefe70', + ), +) +export const withZodValidator = createServerFn({ method: 'GET' }).handler( + createClientRpc( + '43606a369c85444a332f701d6399564b6a3691aabab63dfc9a0b7c341fb798f3', + ), +) +export const withValidatorFn = createServerFn({ method: 'GET' }).handler( + createClientRpc( + '5cf922ac733d835fee496964cbf0b4b4067cb43d51f2efa484d072e6bb7dae44', + ), +) diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx index 2419360ce2..34e0c452b6 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnDestructuredRename.tsx @@ -1,29 +1,22 @@ -import { createServerFn as serverFn } from '@tanstack/react-start'; -export const withUseServer = serverFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withUseServer.__executeServer(opts, signal); -}); -export const withoutUseServer = serverFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withoutUseServer.__executeServer(opts, signal); -}); -export const withVariable = serverFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withVariable.__executeServer(opts, signal); -}); -export const withZodValidator = serverFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withZodValidator.__executeServer(opts, signal); -}); \ No newline at end of file +import { createClientRpc } from '@tanstack/react-start/client-rpc' +import { createServerFn as serverFn } from '@tanstack/react-start' +export const withUseServer = serverFn({ method: 'GET' }).handler( + createClientRpc( + 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', + ), +) +export const withoutUseServer = serverFn({ method: 'GET' }).handler( + createClientRpc( + 'c0d9fdeb2b01aafecc782f439416b86f666cb5334ac9a934546b177e5698bbb2', + ), +) +export const withVariable = serverFn({ method: 'GET' }).handler( + createClientRpc( + '7d36cb30c30bd688b9773bd7f85a0d51d83f868255e127605e4f236615fefe70', + ), +) +export const withZodValidator = serverFn({ method: 'GET' }).handler( + createClientRpc( + '43606a369c85444a332f701d6399564b6a3691aabab63dfc9a0b7c341fb798f3', + ), +) diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx index b308d505f2..2cea070645 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnStarImport.tsx @@ -1,29 +1,30 @@ -import * as TanStackStart from '@tanstack/react-start'; +import { createClientRpc } from '@tanstack/react-start/client-rpc' +import * as TanStackStart from '@tanstack/react-start' export const withUseServer = TanStackStart.createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withUseServer.__executeServer(opts, signal); -}); + method: 'GET', +}).handler( + createClientRpc( + 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', + ), +) export const withoutUseServer = TanStackStart.createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withoutUseServer.__executeServer(opts, signal); -}); + method: 'GET', +}).handler( + createClientRpc( + 'c0d9fdeb2b01aafecc782f439416b86f666cb5334ac9a934546b177e5698bbb2', + ), +) export const withVariable = TanStackStart.createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withVariable.__executeServer(opts, signal); -}); + method: 'GET', +}).handler( + createClientRpc( + '7d36cb30c30bd688b9773bd7f85a0d51d83f868255e127605e4f236615fefe70', + ), +) export const withZodValidator = TanStackStart.createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withZodValidator.__executeServer(opts, signal); -}); \ No newline at end of file + method: 'GET', +}).handler( + createClientRpc( + '43606a369c85444a332f701d6399564b6a3691aabab63dfc9a0b7c341fb798f3', + ), +) diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnValidator.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnValidator.tsx index 5896ad8c1d..97253672a6 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnValidator.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/client/createServerFnValidator.tsx @@ -1,8 +1,7 @@ -import { createServerFn } from '@tanstack/react-start'; -export const withUseServer = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withUseServer.__executeServer(opts, signal); -}); \ No newline at end of file +import { createClientRpc } from '@tanstack/react-start/client-rpc' +import { createServerFn } from '@tanstack/react-start' +export const withUseServer = createServerFn({ method: 'GET' }).handler( + createClientRpc( + 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', + ), +) diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/client/factory.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/client/factory.tsx index fe95c7e47e..889c1fbf4e 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/client/factory.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/client/factory.tsx @@ -1,45 +1,34 @@ -import { createServerFn, createMiddleware } from '@tanstack/react-start'; -const authMiddleware = createMiddleware({ - type: 'function' -}).server(({ - next -}) => { - return next({ - context: { - auth: 'auth' - } - }); -}); -const adminMiddleware = createMiddleware({ - type: 'function' -}).server(({ - next -}) => { - return next({ - context: { - admin: 'admin' - } - }); -}); -export const createAuthServerFn = createServerFn().middleware([authMiddleware]); -const createAdminServerFn = createAuthServerFn().middleware([adminMiddleware]); -export const myAuthedFn = createAuthServerFn().handler((opts, signal) => { - "use server"; - - return myAuthedFn.__executeServer(opts, signal); -}); -export const deleteUserFn = createAdminServerFn().handler((opts, signal) => { - "use server"; - - return deleteUserFn.__executeServer(opts, signal); -}); +import { createClientRpc } from '@tanstack/react-start/client-rpc' +import { createServerFn, createMiddleware } from '@tanstack/react-start' +const authMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => { + return next({ context: { auth: 'auth' } }) + }, +) +const adminMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => { + return next({ context: { admin: 'admin' } }) + }, +) +export const createAuthServerFn = createServerFn().middleware([authMiddleware]) +const createAdminServerFn = createAuthServerFn().middleware([adminMiddleware]) +export const myAuthedFn = createAuthServerFn().handler( + createClientRpc( + '3bb88b23926fa224cea3dcfb877026757733d95b42e3b66cf7f06bb89dab06a3', + ), +) +export const deleteUserFn = createAdminServerFn().handler( + createClientRpc( + '44d9483a9412daaacaa5a8aee6b02294333a0e61b5d3b17ba6bcb34fd2bdce31', + ), +) function createFakeFn() { return { - handler: cb => { - return cb(); - } - }; + handler: (cb) => { + return cb() + }, + } } const x = createFakeFn().handler(() => { - return 'fakeFn'; -}); \ No newline at end of file + return 'fakeFn' +}) diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/client/isomorphic-fns.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/client/isomorphic-fns.tsx index 1de861275b..8e09a57d37 100644 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/client/isomorphic-fns.tsx +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/client/isomorphic-fns.tsx @@ -1,55 +1,49 @@ -import { createFileRoute } from '@tanstack/react-router'; -import { createIsomorphicFn, createServerFn } from '@tanstack/react-start'; -import { useState } from 'react'; -const getEnv = createIsomorphicFn().server(() => 'server').client(() => 'client'); -const getServerEnv = createServerFn().handler((opts, signal) => { - "use server"; - - return getServerEnv.__executeServer(opts, signal); -}); -const getEcho = createIsomorphicFn().server((input: string) => 'server received ' + input).client(input => 'client received ' + input); -const getServerEcho = createServerFn().handler((opts, signal) => { - "use server"; - - return getServerEcho.__executeServer(opts, signal); -}); +import { createClientRpc } from '@tanstack/react-start/client-rpc' +import { createFileRoute } from '@tanstack/react-router' +import { createIsomorphicFn, createServerFn } from '@tanstack/react-start' +import { useState } from 'react' +const getEnv = createIsomorphicFn() + .server(() => 'server') + .client(() => 'client') +const getServerEnv = createServerFn().handler( + createClientRpc( + '6049dd46bc00e0980e387f3e74924b40e92f37634a3fe74a1a1facda9e9207c2', + ), +) +const getEcho = createIsomorphicFn() + .server((input: string) => 'server received ' + input) + .client((input) => 'client received ' + input) +const getServerEcho = createServerFn().handler( + createClientRpc( + 'ebb82e0293952b7b1dde3f664dec4c139471c046d06d4dc4ca172f4f45e386d1', + ), +) export const Route = createFileRoute('/isomorphic-fns')({ component: RouteComponent, loader() { - return { - envOnLoad: getEnv() - }; - } -}); + return { envOnLoad: getEnv() } + }, +}) function RouteComponent() { - const { - envOnLoad - } = Route.useLoaderData(); - const [results, setResults] = useState>>(); + const { envOnLoad } = Route.useLoaderData() + const [results, setResults] = useState>>() async function handleClick() { - const envOnClick = getEnv(); - const echo = getEcho('hello'); - const [serverEnv, serverEcho] = await Promise.all([getServerEnv(), getServerEcho({ - data: 'hello' - })]); - setResults({ - envOnClick, - echo, - serverEnv, - serverEcho - }); + const envOnClick = getEnv() + const echo = getEcho('hello') + const [serverEnv, serverEcho] = await Promise.all([ + getServerEnv(), + getServerEcho({ data: 'hello' }), + ]) + setResults({ envOnClick, echo, serverEnv, serverEcho }) } - const { - envOnClick, - echo, - serverEnv, - serverEcho - } = results || {}; - return
    + const { envOnClick, echo, serverEnv, serverEcho } = results || {} + return ( +
    - {!!results &&
    + {!!results && ( +

    getEnv

    @@ -69,6 +63,8 @@ function RouteComponent() { When we called the function on the client it returned:
    {JSON.stringify(echo)}
    -
    } -
    ; -} \ No newline at end of file +
    + )} +
    + ) +} diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnDestructured.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnDestructured.tsx new file mode 100644 index 0000000000..efa8f395d5 --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnDestructured.tsx @@ -0,0 +1,42 @@ +import { createSsrRpc } from '@tanstack/react-start/ssr-rpc' +import { createServerFn } from '@tanstack/react-start' +import { z } from 'zod' +export const withUseServer = createServerFn({ method: 'GET' }).handler( + createSsrRpc( + 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', + ), +) +export const withArrowFunction = createServerFn({ method: 'GET' }).handler( + createSsrRpc( + 'a311dfd9a6554bc0bb9371ef4fbc72c852d0b5532829a2613a29157b8595a793', + ), +) +export const withArrowFunctionAndFunction = createServerFn({ + method: 'GET', +}).handler( + createSsrRpc( + 'dbe1f77c6ea7590bce3212a75b06d3cee83b425bcf493014cb47462ef725e36e', + ), +) +export const withoutUseServer = createServerFn({ method: 'GET' }).handler( + createSsrRpc( + 'c0d9fdeb2b01aafecc782f439416b86f666cb5334ac9a934546b177e5698bbb2', + ), +) +export const withVariable = createServerFn({ method: 'GET' }).handler( + createSsrRpc( + '7d36cb30c30bd688b9773bd7f85a0d51d83f868255e127605e4f236615fefe70', + ), +) +export const withZodValidator = createServerFn({ method: 'GET' }).handler( + createSsrRpc( + '43606a369c85444a332f701d6399564b6a3691aabab63dfc9a0b7c341fb798f3', + ), +) +export const withValidatorFn = createServerFn({ method: 'GET' }) + .validator(z.number()) + .handler( + createSsrRpc( + '5cf922ac733d835fee496964cbf0b4b4067cb43d51f2efa484d072e6bb7dae44', + ), + ) diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnDestructuredRename.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnDestructuredRename.tsx new file mode 100644 index 0000000000..7088a4bc69 --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnDestructuredRename.tsx @@ -0,0 +1,22 @@ +import { createSsrRpc } from '@tanstack/react-start/ssr-rpc' +import { createServerFn as serverFn } from '@tanstack/react-start' +export const withUseServer = serverFn({ method: 'GET' }).handler( + createSsrRpc( + 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', + ), +) +export const withoutUseServer = serverFn({ method: 'GET' }).handler( + createSsrRpc( + 'c0d9fdeb2b01aafecc782f439416b86f666cb5334ac9a934546b177e5698bbb2', + ), +) +export const withVariable = serverFn({ method: 'GET' }).handler( + createSsrRpc( + '7d36cb30c30bd688b9773bd7f85a0d51d83f868255e127605e4f236615fefe70', + ), +) +export const withZodValidator = serverFn({ method: 'GET' }).handler( + createSsrRpc( + '43606a369c85444a332f701d6399564b6a3691aabab63dfc9a0b7c341fb798f3', + ), +) diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnStarImport.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnStarImport.tsx new file mode 100644 index 0000000000..899aaf3d0d --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnStarImport.tsx @@ -0,0 +1,30 @@ +import { createSsrRpc } from '@tanstack/react-start/ssr-rpc' +import * as TanStackStart from '@tanstack/react-start' +export const withUseServer = TanStackStart.createServerFn({ + method: 'GET', +}).handler( + createSsrRpc( + 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', + ), +) +export const withoutUseServer = TanStackStart.createServerFn({ + method: 'GET', +}).handler( + createSsrRpc( + 'c0d9fdeb2b01aafecc782f439416b86f666cb5334ac9a934546b177e5698bbb2', + ), +) +export const withVariable = TanStackStart.createServerFn({ + method: 'GET', +}).handler( + createSsrRpc( + '7d36cb30c30bd688b9773bd7f85a0d51d83f868255e127605e4f236615fefe70', + ), +) +export const withZodValidator = TanStackStart.createServerFn({ + method: 'GET', +}).handler( + createSsrRpc( + '43606a369c85444a332f701d6399564b6a3691aabab63dfc9a0b7c341fb798f3', + ), +) diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnValidator.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnValidator.tsx new file mode 100644 index 0000000000..e1d136311b --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/createServerFnValidator.tsx @@ -0,0 +1,10 @@ +import { createSsrRpc } from '@tanstack/react-start/ssr-rpc' +import { createServerFn } from '@tanstack/react-start' +import { z } from 'zod' +export const withUseServer = createServerFn({ method: 'GET' }) + .validator(z.number()) + .handler( + createSsrRpc( + 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', + ), + ) diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/factory.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/factory.tsx new file mode 100644 index 0000000000..ab19c3e1f8 --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/factory.tsx @@ -0,0 +1,34 @@ +import { createSsrRpc } from '@tanstack/react-start/ssr-rpc' +import { createServerFn, createMiddleware } from '@tanstack/react-start' +const authMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => { + return next({ context: { auth: 'auth' } }) + }, +) +const adminMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => { + return next({ context: { admin: 'admin' } }) + }, +) +export const createAuthServerFn = createServerFn().middleware([authMiddleware]) +const createAdminServerFn = createAuthServerFn().middleware([adminMiddleware]) +export const myAuthedFn = createAuthServerFn().handler( + createSsrRpc( + '3bb88b23926fa224cea3dcfb877026757733d95b42e3b66cf7f06bb89dab06a3', + ), +) +export const deleteUserFn = createAdminServerFn().handler( + createSsrRpc( + '44d9483a9412daaacaa5a8aee6b02294333a0e61b5d3b17ba6bcb34fd2bdce31', + ), +) +function createFakeFn() { + return { + handler: (cb) => { + return cb() + }, + } +} +const x = createFakeFn().handler(() => { + return 'fakeFn' +}) diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/isomorphic-fns.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/isomorphic-fns.tsx new file mode 100644 index 0000000000..cfefad2bfb --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-caller/isomorphic-fns.tsx @@ -0,0 +1,72 @@ +import { createSsrRpc } from '@tanstack/react-start/ssr-rpc' +import { createFileRoute } from '@tanstack/react-router' +import { createIsomorphicFn, createServerFn } from '@tanstack/react-start' +import { useState } from 'react' +const getEnv = createIsomorphicFn() + .server(() => 'server') + .client(() => 'client') +const getServerEnv = createServerFn().handler( + createSsrRpc( + '6049dd46bc00e0980e387f3e74924b40e92f37634a3fe74a1a1facda9e9207c2', + ), +) +const getEcho = createIsomorphicFn() + .server((input: string) => 'server received ' + input) + .client((input) => 'client received ' + input) +const getServerEcho = createServerFn() + .validator((input: string) => input) + .handler( + createSsrRpc( + 'ebb82e0293952b7b1dde3f664dec4c139471c046d06d4dc4ca172f4f45e386d1', + ), + ) +export const Route = createFileRoute('/isomorphic-fns')({ + component: RouteComponent, + loader() { + return { envOnLoad: getEnv() } + }, +}) +function RouteComponent() { + const { envOnLoad } = Route.useLoaderData() + const [results, setResults] = useState>>() + async function handleClick() { + const envOnClick = getEnv() + const echo = getEcho('hello') + const [serverEnv, serverEcho] = await Promise.all([ + getServerEnv(), + getServerEcho({ data: 'hello' }), + ]) + setResults({ envOnClick, echo, serverEnv, serverEcho }) + } + const { envOnClick, echo, serverEnv, serverEcho } = results || {} + return ( +
    + + {!!results && ( +
    +

    + getEnv +

    + When we called the function on the server it returned: +
    {JSON.stringify(serverEnv)}
    + When we called the function on the client it returned: +
    {JSON.stringify(envOnClick)}
    + When we called the function during SSR it returned: +
    {JSON.stringify(envOnLoad)}
    +
    +

    + echo +

    + When we called the function on the server it returned: +
    +            {JSON.stringify(serverEcho)}
    +          
    + When we called the function on the client it returned: +
    {JSON.stringify(echo)}
    +
    + )} +
    + ) +} diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnDestructured.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnDestructured.tsx new file mode 100644 index 0000000000..3bc4879c14 --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnDestructured.tsx @@ -0,0 +1,126 @@ +import { createServerRpc } from '@tanstack/react-start/server-rpc' +import { createServerFn } from '@tanstack/react-start' +import { z } from 'zod' +const withUseServer_createServerFn_handler = createServerRpc( + { + id: 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', + name: 'withUseServer', + filename: 'src/test.ts', + }, + (opts) => withUseServer.__executeServer(opts), +) +const withUseServer = createServerFn({ method: 'GET' }).handler( + withUseServer_createServerFn_handler, + async function () { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) + }, +) +const withArrowFunction_createServerFn_handler = createServerRpc( + { + id: 'a311dfd9a6554bc0bb9371ef4fbc72c852d0b5532829a2613a29157b8595a793', + name: 'withArrowFunction', + filename: 'src/test.ts', + }, + (opts) => withArrowFunction.__executeServer(opts), +) +const withArrowFunction = createServerFn({ method: 'GET' }).handler( + withArrowFunction_createServerFn_handler, + async () => null, +) +const withArrowFunctionAndFunction_createServerFn_handler = createServerRpc( + { + id: 'dbe1f77c6ea7590bce3212a75b06d3cee83b425bcf493014cb47462ef725e36e', + name: 'withArrowFunctionAndFunction', + filename: 'src/test.ts', + }, + (opts) => withArrowFunctionAndFunction.__executeServer(opts), +) +const withArrowFunctionAndFunction = createServerFn({ method: 'GET' }).handler( + withArrowFunctionAndFunction_createServerFn_handler, + async () => test(), +) +const withoutUseServer_createServerFn_handler = createServerRpc( + { + id: 'c0d9fdeb2b01aafecc782f439416b86f666cb5334ac9a934546b177e5698bbb2', + name: 'withoutUseServer', + filename: 'src/test.ts', + }, + (opts) => withoutUseServer.__executeServer(opts), +) +const withoutUseServer = createServerFn({ method: 'GET' }).handler( + withoutUseServer_createServerFn_handler, + async () => { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) + }, +) +const withVariable_createServerFn_handler = createServerRpc( + { + id: '7d36cb30c30bd688b9773bd7f85a0d51d83f868255e127605e4f236615fefe70', + name: 'withVariable', + filename: 'src/test.ts', + }, + (opts) => withVariable.__executeServer(opts), +) +const withVariable = createServerFn({ method: 'GET' }).handler( + withVariable_createServerFn_handler, + abstractedFunction, +) +async function abstractedFunction() { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +} +function zodValidator( + schema: TSchema, + fn: (input: z.output) => TResult, +) { + return async (input: unknown) => { + return fn(schema.parse(input)) + } +} +const withZodValidator_createServerFn_handler = createServerRpc( + { + id: '43606a369c85444a332f701d6399564b6a3691aabab63dfc9a0b7c341fb798f3', + name: 'withZodValidator', + filename: 'src/test.ts', + }, + (opts) => withZodValidator.__executeServer(opts), +) +const withZodValidator = createServerFn({ method: 'GET' }).handler( + withZodValidator_createServerFn_handler, + zodValidator(z.number(), (input) => { + return { 'you gave': input } + }), +) +const withValidatorFn_createServerFn_handler = createServerRpc( + { + id: '5cf922ac733d835fee496964cbf0b4b4067cb43d51f2efa484d072e6bb7dae44', + name: 'withValidatorFn', + filename: 'src/test.ts', + }, + (opts) => withValidatorFn.__executeServer(opts), +) +const withValidatorFn = createServerFn({ method: 'GET' }) + .validator(z.number()) + .handler(withValidatorFn_createServerFn_handler, async ({ input }) => { + return null + }) +export { + withUseServer_createServerFn_handler, + withArrowFunction_createServerFn_handler, + withArrowFunctionAndFunction_createServerFn_handler, + withoutUseServer_createServerFn_handler, + withVariable_createServerFn_handler, + withZodValidator_createServerFn_handler, + withValidatorFn_createServerFn_handler, +} diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnDestructuredRename.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnDestructuredRename.tsx new file mode 100644 index 0000000000..775c32b645 --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnDestructuredRename.tsx @@ -0,0 +1,86 @@ +import { createServerRpc } from '@tanstack/react-start/server-rpc' +import { createServerFn as serverFn } from '@tanstack/react-start' +import { z } from 'zod' +const withUseServer_createServerFn_handler = createServerRpc( + { + id: 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', + name: 'withUseServer', + filename: 'src/test.ts', + }, + (opts) => withUseServer.__executeServer(opts), +) +const withUseServer = serverFn({ method: 'GET' }).handler( + withUseServer_createServerFn_handler, + async function () { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) + }, +) +const withoutUseServer_createServerFn_handler = createServerRpc( + { + id: 'c0d9fdeb2b01aafecc782f439416b86f666cb5334ac9a934546b177e5698bbb2', + name: 'withoutUseServer', + filename: 'src/test.ts', + }, + (opts) => withoutUseServer.__executeServer(opts), +) +const withoutUseServer = serverFn({ method: 'GET' }).handler( + withoutUseServer_createServerFn_handler, + async () => { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) + }, +) +const withVariable_createServerFn_handler = createServerRpc( + { + id: '7d36cb30c30bd688b9773bd7f85a0d51d83f868255e127605e4f236615fefe70', + name: 'withVariable', + filename: 'src/test.ts', + }, + (opts) => withVariable.__executeServer(opts), +) +const withVariable = serverFn({ method: 'GET' }).handler( + withVariable_createServerFn_handler, + abstractedFunction, +) +async function abstractedFunction() { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +} +function zodValidator( + schema: TSchema, + fn: (input: z.output) => TResult, +) { + return async (input: unknown) => { + return fn(schema.parse(input)) + } +} +const withZodValidator_createServerFn_handler = createServerRpc( + { + id: '43606a369c85444a332f701d6399564b6a3691aabab63dfc9a0b7c341fb798f3', + name: 'withZodValidator', + filename: 'src/test.ts', + }, + (opts) => withZodValidator.__executeServer(opts), +) +const withZodValidator = serverFn({ method: 'GET' }).handler( + withZodValidator_createServerFn_handler, + zodValidator(z.number(), (input) => { + return { 'you gave': input } + }), +) +export { + withUseServer_createServerFn_handler, + withoutUseServer_createServerFn_handler, + withVariable_createServerFn_handler, + withZodValidator_createServerFn_handler, +} diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnStarImport.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnStarImport.tsx new file mode 100644 index 0000000000..bc18c08855 --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnStarImport.tsx @@ -0,0 +1,88 @@ +import { createServerRpc } from '@tanstack/react-start/server-rpc' +import * as TanStackStart from '@tanstack/react-start' +import { z } from 'zod' +const withUseServer_createServerFn_handler = createServerRpc( + { + id: 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', + name: 'withUseServer', + filename: 'src/test.ts', + }, + (opts) => withUseServer.__executeServer(opts), +) +const withUseServer = TanStackStart.createServerFn({ method: 'GET' }).handler( + withUseServer_createServerFn_handler, + async function () { + 'use server' + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) + }, +) +const withoutUseServer_createServerFn_handler = createServerRpc( + { + id: 'c0d9fdeb2b01aafecc782f439416b86f666cb5334ac9a934546b177e5698bbb2', + name: 'withoutUseServer', + filename: 'src/test.ts', + }, + (opts) => withoutUseServer.__executeServer(opts), +) +const withoutUseServer = TanStackStart.createServerFn({ + method: 'GET', +}).handler(withoutUseServer_createServerFn_handler, async () => { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +}) +const withVariable_createServerFn_handler = createServerRpc( + { + id: '7d36cb30c30bd688b9773bd7f85a0d51d83f868255e127605e4f236615fefe70', + name: 'withVariable', + filename: 'src/test.ts', + }, + (opts) => withVariable.__executeServer(opts), +) +const withVariable = TanStackStart.createServerFn({ method: 'GET' }).handler( + withVariable_createServerFn_handler, + abstractedFunction, +) +async function abstractedFunction() { + console.info('Fetching posts...') + await new Promise((r) => setTimeout(r, 500)) + return axios + .get>('https://jsonplaceholder.typicode.com/posts') + .then((r) => r.data.slice(0, 10)) +} +function zodValidator( + schema: TSchema, + fn: (input: z.output) => TResult, +) { + return async (input: unknown) => { + return fn(schema.parse(input)) + } +} +const withZodValidator_createServerFn_handler = createServerRpc( + { + id: '43606a369c85444a332f701d6399564b6a3691aabab63dfc9a0b7c341fb798f3', + name: 'withZodValidator', + filename: 'src/test.ts', + }, + (opts) => withZodValidator.__executeServer(opts), +) +const withZodValidator = TanStackStart.createServerFn({ + method: 'GET', +}).handler( + withZodValidator_createServerFn_handler, + zodValidator(z.number(), (input) => { + return { 'you gave': input } + }), +) +export { + withUseServer_createServerFn_handler, + withoutUseServer_createServerFn_handler, + withVariable_createServerFn_handler, + withZodValidator_createServerFn_handler, +} diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnValidator.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnValidator.tsx new file mode 100644 index 0000000000..f62fa718d6 --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/createServerFnValidator.tsx @@ -0,0 +1,15 @@ +import { createServerRpc } from '@tanstack/react-start/server-rpc' +import { createServerFn } from '@tanstack/react-start' +import { z } from 'zod' +const withUseServer_createServerFn_handler = createServerRpc( + { + id: 'b6fe31e85836ae6c65d8ab262dd1af6a68620aeef609029d50127f4cceaaf320', + name: 'withUseServer', + filename: 'src/test.ts', + }, + (opts) => withUseServer.__executeServer(opts), +) +const withUseServer = createServerFn({ method: 'GET' }) + .validator(z.number()) + .handler(withUseServer_createServerFn_handler, ({ input }) => input + 1) +export { withUseServer_createServerFn_handler } diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/factory.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/factory.tsx new file mode 100644 index 0000000000..26298edd56 --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/factory.tsx @@ -0,0 +1,56 @@ +import { createServerRpc } from '@tanstack/react-start/server-rpc' +import { createServerFn, createMiddleware } from '@tanstack/react-start' +const authMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => { + return next({ context: { auth: 'auth' } }) + }, +) +const adminMiddleware = createMiddleware({ type: 'function' }).server( + ({ next }) => { + return next({ context: { admin: 'admin' } }) + }, +) +const createAuthServerFn = createServerFn().middleware([authMiddleware]) +const createAdminServerFn = createAuthServerFn().middleware([adminMiddleware]) +const myAuthedFn_createServerFn_handler = createServerRpc( + { + id: '3bb88b23926fa224cea3dcfb877026757733d95b42e3b66cf7f06bb89dab06a3', + name: 'myAuthedFn', + filename: 'src/test.ts', + }, + (opts) => myAuthedFn.__executeServer(opts), +) +const myAuthedFn = createAuthServerFn().handler( + myAuthedFn_createServerFn_handler, + () => { + return 'myAuthedFn' + }, +) +const deleteUserFn_createServerFn_handler = createServerRpc( + { + id: '44d9483a9412daaacaa5a8aee6b02294333a0e61b5d3b17ba6bcb34fd2bdce31', + name: 'deleteUserFn', + filename: 'src/test.ts', + }, + (opts) => deleteUserFn.__executeServer(opts), +) +const deleteUserFn = createAdminServerFn().handler( + deleteUserFn_createServerFn_handler, + () => { + return 'deleteUserFn' + }, +) +function createFakeFn() { + return { + handler: (cb) => { + return cb() + }, + } +} +const x = createFakeFn().handler(() => { + return 'fakeFn' +}) +export { + myAuthedFn_createServerFn_handler, + deleteUserFn_createServerFn_handler, +} diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/isomorphic-fns.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/isomorphic-fns.tsx new file mode 100644 index 0000000000..3ae8622683 --- /dev/null +++ b/packages/start-plugin-core/tests/createServerFn/snapshots/server-provider/isomorphic-fns.tsx @@ -0,0 +1,35 @@ +import { createServerRpc } from '@tanstack/react-start/server-rpc' +import { createIsomorphicFn, createServerFn } from '@tanstack/react-start' +const getEnv = createIsomorphicFn() + .server(() => 'server') + .client(() => 'client') +const getServerEnv_createServerFn_handler = createServerRpc( + { + id: '6049dd46bc00e0980e387f3e74924b40e92f37634a3fe74a1a1facda9e9207c2', + name: 'getServerEnv', + filename: 'src/test.ts', + }, + (opts) => getServerEnv.__executeServer(opts), +) +const getServerEnv = createServerFn().handler( + getServerEnv_createServerFn_handler, + () => getEnv(), +) +const getEcho = createIsomorphicFn() + .server((input: string) => 'server received ' + input) + .client((input) => 'client received ' + input) +const getServerEcho_createServerFn_handler = createServerRpc( + { + id: 'ebb82e0293952b7b1dde3f664dec4c139471c046d06d4dc4ca172f4f45e386d1', + name: 'getServerEcho', + filename: 'src/test.ts', + }, + (opts) => getServerEcho.__executeServer(opts), +) +const getServerEcho = createServerFn() + .validator((input: string) => input) + .handler(getServerEcho_createServerFn_handler, ({ data }) => getEcho(data)) +export { + getServerEnv_createServerFn_handler, + getServerEcho_createServerFn_handler, +} diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server/createServerFnDestructured.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server/createServerFnDestructured.tsx deleted file mode 100644 index 0f0c5f651d..0000000000 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server/createServerFnDestructured.tsx +++ /dev/null @@ -1,77 +0,0 @@ -import { createServerFn } from '@tanstack/react-start'; -import { z } from 'zod'; -export const withUseServer = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withUseServer.__executeServer(opts, signal); -}, async function () { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withArrowFunction = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withArrowFunction.__executeServer(opts, signal); -}, async () => null); -export const withArrowFunctionAndFunction = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withArrowFunctionAndFunction.__executeServer(opts, signal); -}, async () => test()); -export const withoutUseServer = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withoutUseServer.__executeServer(opts, signal); -}, async () => { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withVariable = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withVariable.__executeServer(opts, signal); -}, abstractedFunction); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withZodValidator.__executeServer(opts, signal); -}, zodValidator(z.number(), input => { - return { - 'you gave': input - }; -})); -export const withValidatorFn = createServerFn({ - method: 'GET' -}).inputValidator(z.number()).handler((opts, signal) => { - "use server"; - - return withValidatorFn.__executeServer(opts, signal); -}, async ({ - input -}) => { - return null; -}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server/createServerFnDestructuredRename.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server/createServerFnDestructuredRename.tsx deleted file mode 100644 index 358c28448d..0000000000 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server/createServerFnDestructuredRename.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import { createServerFn as serverFn } from '@tanstack/react-start'; -import { z } from 'zod'; -export const withUseServer = serverFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withUseServer.__executeServer(opts, signal); -}, async function () { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withoutUseServer = serverFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withoutUseServer.__executeServer(opts, signal); -}, async () => { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withVariable = serverFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withVariable.__executeServer(opts, signal); -}, abstractedFunction); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = serverFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withZodValidator.__executeServer(opts, signal); -}, zodValidator(z.number(), input => { - return { - 'you gave': input - }; -})); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx deleted file mode 100644 index 44f6733072..0000000000 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server/createServerFnStarImport.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import * as TanStackStart from '@tanstack/react-start'; -import { z } from 'zod'; -export const withUseServer = TanStackStart.createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withUseServer.__executeServer(opts, signal); -}, async function () { - 'use server'; - - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withoutUseServer = TanStackStart.createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withoutUseServer.__executeServer(opts, signal); -}, async () => { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -}); -export const withVariable = TanStackStart.createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withVariable.__executeServer(opts, signal); -}, abstractedFunction); -async function abstractedFunction() { - console.info('Fetching posts...'); - await new Promise(r => setTimeout(r, 500)); - return axios.get>('https://jsonplaceholder.typicode.com/posts').then(r => r.data.slice(0, 10)); -} -function zodValidator(schema: TSchema, fn: (input: z.output) => TResult) { - return async (input: unknown) => { - return fn(schema.parse(input)); - }; -} -export const withZodValidator = TanStackStart.createServerFn({ - method: 'GET' -}).handler((opts, signal) => { - "use server"; - - return withZodValidator.__executeServer(opts, signal); -}, zodValidator(z.number(), input => { - return { - 'you gave': input - }; -})); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server/createServerFnValidator.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server/createServerFnValidator.tsx deleted file mode 100644 index 1ca81b0260..0000000000 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server/createServerFnValidator.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { createServerFn } from '@tanstack/react-start'; -import { z } from 'zod'; -export const withUseServer = createServerFn({ - method: 'GET' -}).inputValidator(z.number()).handler((opts, signal) => { - "use server"; - - return withUseServer.__executeServer(opts, signal); -}, ({ - input -}) => input + 1); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server/factory.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server/factory.tsx deleted file mode 100644 index 388e9761c3..0000000000 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server/factory.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import { createServerFn, createMiddleware } from '@tanstack/react-start'; -const authMiddleware = createMiddleware({ - type: 'function' -}).server(({ - next -}) => { - return next({ - context: { - auth: 'auth' - } - }); -}); -const adminMiddleware = createMiddleware({ - type: 'function' -}).server(({ - next -}) => { - return next({ - context: { - admin: 'admin' - } - }); -}); -export const createAuthServerFn = createServerFn().middleware([authMiddleware]); -const createAdminServerFn = createAuthServerFn().middleware([adminMiddleware]); -export const myAuthedFn = createAuthServerFn().handler((opts, signal) => { - "use server"; - - return myAuthedFn.__executeServer(opts, signal); -}, () => { - return 'myAuthedFn'; -}); -export const deleteUserFn = createAdminServerFn().handler((opts, signal) => { - "use server"; - - return deleteUserFn.__executeServer(opts, signal); -}, () => { - return 'deleteUserFn'; -}); -function createFakeFn() { - return { - handler: cb => { - return cb(); - } - }; -} -const x = createFakeFn().handler(() => { - return 'fakeFn'; -}); \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createServerFn/snapshots/server/isomorphic-fns.tsx b/packages/start-plugin-core/tests/createServerFn/snapshots/server/isomorphic-fns.tsx deleted file mode 100644 index 08e55500c9..0000000000 --- a/packages/start-plugin-core/tests/createServerFn/snapshots/server/isomorphic-fns.tsx +++ /dev/null @@ -1,76 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router'; -import { createIsomorphicFn, createServerFn } from '@tanstack/react-start'; -import { useState } from 'react'; -const getEnv = createIsomorphicFn().server(() => 'server').client(() => 'client'); -const getServerEnv = createServerFn().handler((opts, signal) => { - "use server"; - - return getServerEnv.__executeServer(opts, signal); -}, () => getEnv()); -const getEcho = createIsomorphicFn().server((input: string) => 'server received ' + input).client(input => 'client received ' + input); -const getServerEcho = createServerFn().inputValidator((input: string) => input).handler((opts, signal) => { - "use server"; - - return getServerEcho.__executeServer(opts, signal); -}, ({ - data -}) => getEcho(data)); -export const Route = createFileRoute('/isomorphic-fns')({ - component: RouteComponent, - loader() { - return { - envOnLoad: getEnv() - }; - } -}); -function RouteComponent() { - const { - envOnLoad - } = Route.useLoaderData(); - const [results, setResults] = useState>>(); - async function handleClick() { - const envOnClick = getEnv(); - const echo = getEcho('hello'); - const [serverEnv, serverEcho] = await Promise.all([getServerEnv(), getServerEcho({ - data: 'hello' - })]); - setResults({ - envOnClick, - echo, - serverEnv, - serverEcho - }); - } - const { - envOnClick, - echo, - serverEnv, - serverEcho - } = results || {}; - return
    - - {!!results &&
    -

    - getEnv -

    - When we called the function on the server it returned: -
    {JSON.stringify(serverEnv)}
    - When we called the function on the client it returned: -
    {JSON.stringify(envOnClick)}
    - When we called the function during SSR it returned: -
    {JSON.stringify(envOnLoad)}
    -
    -

    - echo -

    - When we called the function on the server it returned: -
    -            {JSON.stringify(serverEcho)}
    -          
    - When we called the function on the client it returned: -
    {JSON.stringify(echo)}
    -
    } -
    ; -} \ No newline at end of file diff --git a/packages/start-plugin-core/tests/createServerFn/test-files/createServerFnDestructured.tsx b/packages/start-plugin-core/tests/createServerFn/test-files/createServerFnDestructured.tsx index c0b78ded9e..b1c5e9edf2 100644 --- a/packages/start-plugin-core/tests/createServerFn/test-files/createServerFnDestructured.tsx +++ b/packages/start-plugin-core/tests/createServerFn/test-files/createServerFnDestructured.tsx @@ -61,7 +61,7 @@ export const withZodValidator = createServerFn({ export const withValidatorFn = createServerFn({ method: 'GET', }) - .inputValidator(z.number()) + .validator(z.number()) .handler(async ({ input }) => { return null }) diff --git a/packages/start-plugin-core/tests/createServerFn/test-files/createServerFnValidator.tsx b/packages/start-plugin-core/tests/createServerFn/test-files/createServerFnValidator.tsx index 80cb70fddb..6c0eda77f3 100644 --- a/packages/start-plugin-core/tests/createServerFn/test-files/createServerFnValidator.tsx +++ b/packages/start-plugin-core/tests/createServerFn/test-files/createServerFnValidator.tsx @@ -4,5 +4,5 @@ import { z } from 'zod' export const withUseServer = createServerFn({ method: 'GET', }) - .inputValidator(z.number()) + .validator(z.number()) .handler(({ input }) => input + 1) diff --git a/packages/start-plugin-core/tests/createServerFn/test-files/isomorphic-fns.tsx b/packages/start-plugin-core/tests/createServerFn/test-files/isomorphic-fns.tsx index 773a2e5329..2c7bbc4a8f 100644 --- a/packages/start-plugin-core/tests/createServerFn/test-files/isomorphic-fns.tsx +++ b/packages/start-plugin-core/tests/createServerFn/test-files/isomorphic-fns.tsx @@ -13,7 +13,7 @@ const getEcho = createIsomorphicFn() .client((input) => 'client received ' + input) const getServerEcho = createServerFn() - .inputValidator((input: string) => input) + .validator((input: string) => input) .handler(({ data }) => getEcho(data)) export const Route = createFileRoute('/isomorphic-fns')({ diff --git a/packages/start-plugin-core/tests/createVirtualModule.test.ts b/packages/start-plugin-core/tests/createVirtualModule.test.ts new file mode 100644 index 0000000000..bca42afd36 --- /dev/null +++ b/packages/start-plugin-core/tests/createVirtualModule.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, test } from 'vitest' +import { createVirtualModule } from '../src/vite/createVirtualModule' + +describe('createVirtualModule', () => { + test('resolves and loads the default vite virtual id', () => { + const plugin = createVirtualModule({ + name: 'test-virtual', + moduleId: 'virtual:test-module', + load() { + return 'export const ok = true' + }, + }) + + expect((plugin as any).resolveId.handler('virtual:test-module')).toBe( + '\0virtual:test-module', + ) + expect((plugin as any).load.handler('\0virtual:test-module')).toBe( + 'export const ok = true', + ) + }) + + test('encodes hashes in resolved vite ids', () => { + const plugin = createVirtualModule({ + name: 'test-hash-module-id', + moduleId: '#virtual:test-module', + load() { + return 'export {}' + }, + }) + + expect((plugin as any).resolveId.handler('#virtual:test-module')).toBe( + '\0%23virtual:test-module', + ) + expect((plugin as any).load.handler('\0%23virtual:test-module')).toBe( + 'export {}', + ) + }) +}) diff --git a/packages/start-plugin-core/tests/csrf-warning-config.test.ts b/packages/start-plugin-core/tests/csrf-warning-config.test.ts new file mode 100644 index 0000000000..abe28087d0 --- /dev/null +++ b/packages/start-plugin-core/tests/csrf-warning-config.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, test } from 'vitest' +import { parseStartConfig as parseViteStartConfig } from '../src/vite/schema' +import { parseStartConfig as parseRsbuildStartConfig } from '../src/rsbuild/schema' +import { createViteDefineConfig } from '../src/vite/planning' + +const root = process.cwd() +const corePluginOpts = { framework: 'react' as const } + +describe('disableCsrfMiddlewareWarning plugin config', () => { + test('is accepted by the vite plugin config', () => { + const config = parseViteStartConfig( + { + serverFns: { + disableCsrfMiddlewareWarning: true, + }, + }, + corePluginOpts, + root, + ) + + expect(config.serverFns.disableCsrfMiddlewareWarning).toBe(true) + }) + + test('is accepted by the rsbuild plugin config', () => { + const config = parseRsbuildStartConfig( + { + serverFns: { + disableCsrfMiddlewareWarning: true, + }, + }, + corePluginOpts, + root, + ) + + expect(config.serverFns.disableCsrfMiddlewareWarning).toBe(true) + }) + + test('defaults to false', () => { + const config = parseViteStartConfig({}, corePluginOpts, root) + + expect(config.serverFns.disableCsrfMiddlewareWarning).toBe(false) + }) + + test('emits the vite define used by the server runtime', () => { + const define = createViteDefineConfig({ + command: 'serve', + mode: 'development', + serverFnBase: '/_serverFn', + routerBasepath: '/', + spaEnabled: true, + devSsrStylesEnabled: true, + devSsrStylesBasepath: '/', + inlineCssEnabled: false, + staticNodeEnv: true, + disableCsrfMiddlewareWarning: true, + }) + + expect(define['process.env.TSS_DISABLE_CSRF_MIDDLEWARE_WARNING']).toBe( + JSON.stringify('true'), + ) + expect(define['import.meta.env.TSS_DISABLE_CSRF_MIDDLEWARE_WARNING']).toBe( + JSON.stringify('true'), + ) + }) +}) diff --git a/packages/start-plugin-core/tests/entry-planning.test.ts b/packages/start-plugin-core/tests/entry-planning.test.ts new file mode 100644 index 0000000000..b8a71675a1 --- /dev/null +++ b/packages/start-plugin-core/tests/entry-planning.test.ts @@ -0,0 +1,116 @@ +import { + mkdtempSync, + mkdirSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { normalize } from 'pathe' +import { afterEach, describe, expect, test } from 'vitest' +import { resolveStartEntryPlan } from '../src/planning' +import { parseStartConfig as parseRsbuildStartConfig } from '../src/rsbuild/schema' +import { parseStartConfig as parseViteStartConfig } from '../src/vite/schema' + +const corePluginOpts = { framework: 'react' as const } +const defaultEntryPaths = { + client: '/virtual/default-client', + server: '/virtual/default-server', + start: '/virtual/default-start', +} +const roots = new Set() + +function createRoot() { + const root = mkdtempSync(join(tmpdir(), 'tanstack-start-entry-')) + roots.add(root) + mkdirSync(join(root, 'src')) + writeFileSync(join(root, 'src', 'router.ts'), 'export {}\n') + return root +} + +afterEach(() => { + for (const root of roots) { + rmSync(root, { recursive: true, force: true }) + } + roots.clear() +}) + +describe('server entry planning', () => { + test.each([ + ['vite', parseViteStartConfig], + ['rsbuild', parseRsbuildStartConfig], + ])( + 'uses the default server entry for %s when none is configured', + (_, parse) => { + const root = createRoot() + const startConfig = parse({}, corePluginOpts, root) + + const plan = resolveStartEntryPlan({ + root, + startConfig, + defaultEntryPaths, + }) + + expect(plan.entryPaths.server).toBe(defaultEntryPaths.server) + }, + ) + + test.each([ + ['vite', parseViteStartConfig], + ['rsbuild', parseRsbuildStartConfig], + ])('resolves a custom server entry for %s from srcDirectory', (_, parse) => { + const root = createRoot() + const serverEntry = join(root, 'src', 'server-entry.ts') + writeFileSync(serverEntry, 'export default {}\n') + const startConfig = parse( + { + server: { + entry: './server-entry.ts', + }, + }, + corePluginOpts, + root, + ) + + const plan = resolveStartEntryPlan({ + root, + startConfig, + defaultEntryPaths, + }) + + expect(plan.entryPaths.server).toBe(normalize(realpathSync(serverEntry))) + }) + + test.each([ + ['vite', parseViteStartConfig], + ['rsbuild', parseRsbuildStartConfig], + ])( + 'resolves a custom server entry for %s from a custom srcDirectory', + (_, parse) => { + const root = createRoot() + mkdirSync(join(root, 'app')) + writeFileSync(join(root, 'app', 'router.ts'), 'export {}\n') + const serverEntry = join(root, 'app', 'server-entry.ts') + writeFileSync(serverEntry, 'export default {}\n') + const startConfig = parse( + { + srcDirectory: 'app', + server: { + entry: './server-entry.ts', + }, + }, + corePluginOpts, + root, + ) + + const plan = resolveStartEntryPlan({ + root, + startConfig, + defaultEntryPaths, + }) + + expect(plan.entryPaths.server).toBe(normalize(realpathSync(serverEntry))) + }, + ) +}) diff --git a/packages/start-plugin-core/tests/envOnly/envOnly.test.ts b/packages/start-plugin-core/tests/envOnly/envOnly.test.ts index d68a546fb9..4c18f2da81 100644 --- a/packages/start-plugin-core/tests/envOnly/envOnly.test.ts +++ b/packages/start-plugin-core/tests/envOnly/envOnly.test.ts @@ -2,9 +2,55 @@ import { readFile, readdir } from 'node:fs/promises' import path from 'node:path' import { describe, expect, test } from 'vitest' -import { compileStartOutputFactory } from '../../src/start-compiler-plugin/compilers' +import { StartCompiler } from '../../src/start-compiler/compiler' +import { formatSnapshot } from '../format-snapshot' -const compileStartOutput = compileStartOutputFactory('react') +// Default test options for StartCompiler +function getDefaultTestOptions(env: 'client' | 'server') { + const envName = env === 'client' ? 'client' : 'ssr' + return { + envName, + root: '/test', + framework: 'react' as const, + providerEnvName: 'ssr', + } +} + +async function compile(opts: { + env: 'client' | 'server' + code: string + id: string +}) { + const compiler = new StartCompiler({ + ...opts, + ...getDefaultTestOptions(opts.env), + loadModule: async () => { + // do nothing in test + }, + lookupKinds: new Set(['ServerOnlyFn', 'ClientOnlyFn']), + lookupConfigurations: [ + { + libName: `@tanstack/react-start`, + rootExport: 'createServerOnlyFn', + kind: 'ServerOnlyFn', + }, + { + libName: `@tanstack/react-start`, + rootExport: 'createClientOnlyFn', + kind: 'ClientOnlyFn', + }, + ], + getKnownServerFns: () => ({}), + resolveId: async (id) => { + return id + }, + }) + const result = await compiler.compile({ + code: opts.code, + id: opts.id, + }) + return result +} async function getFilenames() { return await readdir(path.resolve(import.meta.dirname, './test-files')) @@ -22,39 +68,38 @@ describe('envOnly functions compile correctly', async () => { test.each(['client', 'server'] as const)( `should compile for ${filename} %s`, async (env) => { - const compiledResult = compileStartOutput({ + const compiledResult = await compile({ env, code, - filename, - dce: false, + id: filename, }) - await expect(compiledResult.code).toMatchFileSnapshot( - `./snapshots/${env}/${filename}`, - ) + await expect( + await formatSnapshot(compiledResult!.code, filename), + ).toMatchFileSnapshot(`./snapshots/${env}/${filename}`) }, ) }) - test('should error if implementation not provided', () => { - expect(() => { - compileStartOutput({ + + test('should error if implementation not provided', async () => { + await expect( + compile({ env: 'client', code: ` import { createClientOnlyFn } from '@tanstack/react-start' const fn = createClientOnlyFn()`, - filename: 'no-fn.ts', - dce: false, - }) - }).toThrowError() - expect(() => { - compileStartOutput({ + id: 'no-fn.ts', + }), + ).rejects.toThrowError() + + await expect( + compile({ env: 'server', code: ` import { createServerOnlyFn } from '@tanstack/react-start' const fn = createServerOnlyFn()`, - filename: 'no-fn.ts', - dce: false, - }) - }).toThrowError() + id: 'no-fn.ts', + }), + ).rejects.toThrowError() }) }) diff --git a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyDestructured.tsx b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyDestructured.tsx index d94dcb06dd..8c97577305 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyDestructured.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyDestructured.tsx @@ -1,5 +1,6 @@ -import { createServerOnlyFn, createClientOnlyFn } from '@tanstack/react-start'; const serverFunc = () => { - throw new Error("createServerOnlyFn() functions can only be called on the server!"); -}; -const clientFunc = () => 'client'; \ No newline at end of file + throw new Error( + 'createServerOnlyFn() functions can only be called on the server!', + ) +} +const clientFunc = () => 'client' diff --git a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx index c3c0e21f6a..8c97577305 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyDestructuredRename.tsx @@ -1,5 +1,6 @@ -import { createServerOnlyFn as serverFn, createClientOnlyFn as clientFn } from '@tanstack/react-start'; const serverFunc = () => { - throw new Error("createServerOnlyFn() functions can only be called on the server!"); -}; -const clientFunc = () => 'client'; \ No newline at end of file + throw new Error( + 'createServerOnlyFn() functions can only be called on the server!', + ) +} +const clientFunc = () => 'client' diff --git a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyExportedAlias.tsx b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyExportedAlias.tsx new file mode 100644 index 0000000000..cad8d612c9 --- /dev/null +++ b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyExportedAlias.tsx @@ -0,0 +1,10 @@ +export const fn = () => { + throw new Error( + 'createServerOnlyFn() functions can only be called on the server!', + ) +} +export const wrappedFn = (() => { + throw new Error( + 'createServerOnlyFn() functions can only be called on the server!', + ) +}) as () => string diff --git a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyFactory.tsx b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyFactory.tsx new file mode 100644 index 0000000000..b226e30116 --- /dev/null +++ b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyFactory.tsx @@ -0,0 +1,34 @@ +// Server-only function factory +export function createServerFactory(name: string) { + return () => { + throw new Error( + 'createServerOnlyFn() functions can only be called on the server!', + ) + } +} +// Client-only function factory +export function createClientFactory(name: string) { + return () => { + console.log(`Client only: ${name}`) + return `client-${name}` + } +} +// Arrow function server factory +export const createServerArrowFactory = (prefix: string) => { + return () => { + throw new Error( + 'createServerOnlyFn() functions can only be called on the server!', + ) + } +} +// Arrow function client factory +export const createClientArrowFactory = (prefix: string) => { + return () => `${prefix}-client` +} +// Top-level for comparison +export const topLevelServerFn = () => { + throw new Error( + 'createServerOnlyFn() functions can only be called on the server!', + ) +} +export const topLevelClientFn = () => 'client' diff --git a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyStarImport.tsx b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyStarImport.tsx index adafc67ab1..8c97577305 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyStarImport.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/client/envOnlyStarImport.tsx @@ -1,5 +1,6 @@ -import * as TanstackStart from '@tanstack/react-start'; const serverFunc = () => { - throw new Error("createServerOnlyFn() functions can only be called on the server!"); -}; -const clientFunc = () => 'client'; \ No newline at end of file + throw new Error( + 'createServerOnlyFn() functions can only be called on the server!', + ) +} +const clientFunc = () => 'client' diff --git a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyDestructured.tsx b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyDestructured.tsx index 7feb328db6..924d8d2442 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyDestructured.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyDestructured.tsx @@ -1,5 +1,6 @@ -import { createServerOnlyFn, createClientOnlyFn } from '@tanstack/react-start'; -const serverFunc = () => 'server'; +const serverFunc = () => 'server' const clientFunc = () => { - throw new Error("createClientOnlyFn() functions can only be called on the client!"); -}; \ No newline at end of file + throw new Error( + 'createClientOnlyFn() functions can only be called on the client!', + ) +} diff --git a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx index 8d8bdac72c..924d8d2442 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyDestructuredRename.tsx @@ -1,5 +1,6 @@ -import { createServerOnlyFn as serverFn, createClientOnlyFn as clientFn } from '@tanstack/react-start'; -const serverFunc = () => 'server'; +const serverFunc = () => 'server' const clientFunc = () => { - throw new Error("createClientOnlyFn() functions can only be called on the client!"); -}; \ No newline at end of file + throw new Error( + 'createClientOnlyFn() functions can only be called on the client!', + ) +} diff --git a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyExportedAlias.tsx b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyExportedAlias.tsx new file mode 100644 index 0000000000..078c324406 --- /dev/null +++ b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyExportedAlias.tsx @@ -0,0 +1,2 @@ +export const fn = () => 'server-only-value' +export const wrappedFn = (() => 'wrapped-server-only-value') as () => string diff --git a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyFactory.tsx b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyFactory.tsx new file mode 100644 index 0000000000..fdb022bc0d --- /dev/null +++ b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyFactory.tsx @@ -0,0 +1,34 @@ +// Server-only function factory +export function createServerFactory(name: string) { + return () => { + console.log(`Server only: ${name}`) + return `server-${name}` + } +} +// Client-only function factory +export function createClientFactory(name: string) { + return () => { + throw new Error( + 'createClientOnlyFn() functions can only be called on the client!', + ) + } +} +// Arrow function server factory +export const createServerArrowFactory = (prefix: string) => { + return () => `${prefix}-server` +} +// Arrow function client factory +export const createClientArrowFactory = (prefix: string) => { + return () => { + throw new Error( + 'createClientOnlyFn() functions can only be called on the client!', + ) + } +} +// Top-level for comparison +export const topLevelServerFn = () => 'server' +export const topLevelClientFn = () => { + throw new Error( + 'createClientOnlyFn() functions can only be called on the client!', + ) +} diff --git a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyStarImport.tsx b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyStarImport.tsx index ce13e85125..924d8d2442 100644 --- a/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyStarImport.tsx +++ b/packages/start-plugin-core/tests/envOnly/snapshots/server/envOnlyStarImport.tsx @@ -1,5 +1,6 @@ -import * as TanstackStart from '@tanstack/react-start'; -const serverFunc = () => 'server'; +const serverFunc = () => 'server' const clientFunc = () => { - throw new Error("createClientOnlyFn() functions can only be called on the client!"); -}; \ No newline at end of file + throw new Error( + 'createClientOnlyFn() functions can only be called on the client!', + ) +} diff --git a/packages/start-plugin-core/tests/envOnly/test-files/envOnlyExportedAlias.tsx b/packages/start-plugin-core/tests/envOnly/test-files/envOnlyExportedAlias.tsx new file mode 100644 index 0000000000..1d51d5dd4f --- /dev/null +++ b/packages/start-plugin-core/tests/envOnly/test-files/envOnlyExportedAlias.tsx @@ -0,0 +1,4 @@ +import { createServerOnlyFn as so } from '@tanstack/react-start' + +export const fn = so(() => 'server-only-value') +export const wrappedFn = so(() => 'wrapped-server-only-value') as () => string diff --git a/packages/start-plugin-core/tests/envOnly/test-files/envOnlyFactory.tsx b/packages/start-plugin-core/tests/envOnly/test-files/envOnlyFactory.tsx new file mode 100644 index 0000000000..a1223a6aee --- /dev/null +++ b/packages/start-plugin-core/tests/envOnly/test-files/envOnlyFactory.tsx @@ -0,0 +1,31 @@ +import { createServerOnlyFn, createClientOnlyFn } from '@tanstack/react-start' + +// Server-only function factory +export function createServerFactory(name: string) { + return createServerOnlyFn(() => { + console.log(`Server only: ${name}`) + return `server-${name}` + }) +} + +// Client-only function factory +export function createClientFactory(name: string) { + return createClientOnlyFn(() => { + console.log(`Client only: ${name}`) + return `client-${name}` + }) +} + +// Arrow function server factory +export const createServerArrowFactory = (prefix: string) => { + return createServerOnlyFn(() => `${prefix}-server`) +} + +// Arrow function client factory +export const createClientArrowFactory = (prefix: string) => { + return createClientOnlyFn(() => `${prefix}-client`) +} + +// Top-level for comparison +export const topLevelServerFn = createServerOnlyFn(() => 'server') +export const topLevelClientFn = createClientOnlyFn(() => 'client') diff --git a/packages/start-plugin-core/tests/format-snapshot.ts b/packages/start-plugin-core/tests/format-snapshot.ts new file mode 100644 index 0000000000..d152094bea --- /dev/null +++ b/packages/start-plugin-core/tests/format-snapshot.ts @@ -0,0 +1,69 @@ +import { format } from 'prettier' +import { parsers } from 'prettier/plugins/typescript' +import type { ParserOptions } from 'prettier' + +/** + * Formats compiler output before it is compared with a file snapshot, so that + * snapshots record the emitted program instead of the layout choices of the + * code generator (object wrapping, blank lines, parentheses around JSX, ...). + * + * Comments are kept: they are part of the output. Output that does not parse + * is returned unchanged. + */ +export async function formatSnapshot(code: string, filepath: string) { + try { + return await format(await removeBlankLines(code, filepath), { + filepath, + parser: 'typescript', + semi: false, + singleQuote: true, + trailingComma: 'all', + // Do not keep an object expanded because the generator printed it + // over several lines. + objectWrap: 'collapse', + }) + } catch { + return code + } +} + +/** + * Prettier keeps single blank lines from its input. Outside template literals, + * line breaks are not significant, so blank lines can be dropped. + */ +async function removeBlankLines(code: string, filepath: string) { + const parser = parsers.typescript + const ast = await parser.parse(code, { filepath } as ParserOptions) + const templateRanges: Array<[number, number]> = [] + const visit = (node: unknown): void => { + if (Array.isArray(node)) { + node.forEach(visit) + return + } + if (!node || typeof node !== 'object') { + return + } + if ((node as { type?: unknown }).type === 'TemplateElement') { + templateRanges.push([parser.locStart(node), parser.locEnd(node)]) + } + for (const [key, value] of Object.entries(node)) { + if (key !== 'loc' && key !== 'range') { + visit(value) + } + } + } + visit(ast) + + const lines: Array = [] + let lineStart = 0 + for (const line of code.split('\n')) { + const isInTemplate = templateRanges.some( + ([start, end]) => start < lineStart && lineStart < end, + ) + if (line.trim() !== '' || isInTemplate) { + lines.push(line) + } + lineStart += line.length + 1 + } + return lines.join('\n') +} diff --git a/packages/start-plugin-core/tests/hydrate-captures.test.ts b/packages/start-plugin-core/tests/hydrate-captures.test.ts new file mode 100644 index 0000000000..c9b98c7b4e --- /dev/null +++ b/packages/start-plugin-core/tests/hydrate-captures.test.ts @@ -0,0 +1,309 @@ +import { expect, test } from 'vitest' +import { + compileFirstChunk, + compileHydrate, + evaluateModule, + getChunkIds, + getChunkParams, + hydrateParentStubs, + loadChunk, + renderChunk, +} from './regression-helpers' +import { declarationOf, getModuleErrors } from './validate-module' + +// `` moves its children into a chunk component at module level. The +// locals of the enclosing scopes the children read become props of that +// component, under the same names; module bindings move along with the +// children; names the children declare themselves are not captured. React +// keeps the `key` and `ref` props for itself, so no captured local here is +// named like them. + +const head = `import { Hydrate } from '@tanstack/react-start'\n` + +/** Compiles for the client, checks every module and returns the single chunk. */ +async function compileChunk(code: string) { + const { parent, chunks } = await compileHydrate('client', `${head}${code}`) + expect(chunks).toHaveLength(1) + for (const module of [parent, chunks[0]!]) { + expect(await getModuleErrors(module)).toEqual([]) + } + return { parent, chunk: chunks[0]! } +} + +test.each<{ + name: string + children: string + params: Array + expected: string +}>([ + { + // Source: @vitejs/plugin-rsc hoist/function-hoist-block.js + name: 'past a function declared in a nested block', + children: `{(() => { + const seen = value + { + function value() {} + } + return seen +})()}`, + params: ['value'], + expected: '

    outer

    ', + }, + { + // Source: @vitejs/plugin-rsc scope/param-default-var-hoisting.js + name: 'from a parameter default next to a var of the same name', + children: `{((seen = value) => { + var value = 'inner' + return seen + ':' + value +})()}`, + params: ['value'], + expected: '

    outer:inner

    ', + }, + { + // Source: @vitejs/plugin-rsc scope/label.js + name: 'next to a label of the same name', + children: `{(() => { + value: for (const item of [1]) { + if (item) { + break value + } + } + return value +})()}`, + params: ['value'], + expected: '

    outer

    ', + }, + { + // Source: @vitejs/plugin-rsc hoist/computed-destructuring-key-captures-outer-binding.js + name: 'through a computed destructuring key', + children: `{(({ [field]: picked }) => picked)({ value })}`, + params: ['field', 'value'], + expected: '

    outer

    ', + }, + { + // Source: @vitejs/plugin-rsc hoist/var-hoist-block.js, hoist/shadow-var-nested-block.js + name: 'unless a var in a nested block shadows them', + children: `{(() => { + if (field) { + var value = 'inner' + } + return value +})()}`, + params: ['field'], + expected: '

    inner

    ', + }, + { + // Source: SolidStart compile.spec.ts "allows `this` and `arguments` in a + // function expression" + name: 'except the arguments of a function expression', + children: `{(function (..._args: Array) { + return arguments.length +})(1, 2)}`, + params: [], + expected: '

    2

    ', + }, +])( + 'client: the children capture locals $name', + async ({ children, params, expected }) => { + const { chunk } = await compileChunk(`export function Page() { + const value = 'outer' + const field = 'value' + return

    ${children}

    +}`) + expect(getChunkParams(chunk)).toEqual(params) + expect(await renderChunk(chunk, { value: 'outer', field: 'value' })).toBe( + expected, + ) + }, +) + +// Source: @vitejs/plugin-rsc hoist/function-hoist-block.js (module-level binding) +test('client: a module binding read past a block-level function moves into the chunk', async () => { + const { chunk } = await compileChunk(`const value = 'module' +export function Page() { + return

    {(() => { + const seen = value + { + function value() {} + } + return seen +})()}

    +}`) + expect(getChunkParams(chunk)).toEqual([]) + expect(await renderChunk(chunk)).toBe('

    module

    ') +}) + +// Source: Qwik optimizer should_not_auto_export_var_shadowed_in_catch +test('client: a catch parameter is captured', async () => { + const { chunk } = await compileChunk(`export function Page() { + try { + throw new Error('caught') + } catch (error) { + return

    {error.message}

    + } +}`) + expect(getChunkParams(chunk)).toEqual(['error']) + expect(await renderChunk(chunk, { error: new Error('caught') })).toBe( + '

    caught

    ', + ) +}) + +// Source: Qwik optimizer should_transform_handler_in_for_of_loop +test('client: a destructured loop variable and a block-scoped local are captured, module helpers move', async () => { + const { parent, chunk } = await compileChunk(`function Row({ v }) { + return
  • {v}
  • +} +export function Page({ entries }) { + const out = [] + for (const [key, value] of entries) { + const label = key + '-' + out.push() + } + return
      {out}
    +}`) + expect(getChunkParams(chunk)).toEqual(['label', 'value']) + // The helper only the children use leaves the parent with them. + expect(parent).not.toMatch(declarationOf('Row')) + expect(await renderChunk(chunk, { label: 'a-', value: 1 })).toBe( + '
  • a-1
  • ', + ) +}) + +// Source: Qwik optimizer jsx_tag_names_are_not_segment_uses, +// jsx_lowercase_tag_outside_segments, jsx_tag_named_like_inlined_const +test.each([ + { + scope: 'module', + code: `const div = sideEffect('div') +console.log(div) +export function Page() { + return
    x
    +}`, + }, + { + scope: 'component', + code: `export function Page() { + const div = sideEffect('div') + console.log(div) + return
    x
    +}`, + }, +])( + 'client: a $scope binding named like an intrinsic tag is not captured', + async ({ code }) => { + const { chunk } = await compileChunk(code) + expect(chunk).not.toContain('sideEffect') + expect(getChunkParams(chunk)).toEqual([]) + expect(await renderChunk(chunk)).toBe('
    x
    ') + }, +) + +// Source: Qwik optimizer local_shadowing_destructured_prop, +// should_not_auto_export_var_shadowed_in_catch +test('client: names the children declare themselves are not captured', async () => { + const { chunk } = await compileChunk(`export function Page({ value }) { + const x = 'outer' + console.log(x) + return + { const value = e.target.value; return value }} /> +

    {(() => { try { throw new Error('e') } catch (err) { const x = 'catch:' + err.message; return x } })()}

    +
    +}`) + expect(getChunkParams(chunk)).toEqual(['value']) + expect(await renderChunk(chunk, { value: 'v' })).toBe( + '

    catch:e

    ', + ) +}) + +// Source: Qwik optimizer example_functional_component_capture_props, +// example_spread_jsx, should_convert_rest_props +test('client: destructured params with defaults and rests, and spread props, are captured', async () => { + const { chunk } = + await compileChunk(`function Child(props) { return {props.a + props.extra} } +export function Page({ a: [b = 1], ...c }) { + const extra = '!' + return

    {b}

    +}`) + expect(getChunkParams(chunk)).toEqual(['b', 'c', 'extra']) + expect(await renderChunk(chunk, { b: 1, c: { a: 'A' }, extra: '!' })).toBe( + '

    1

    A!', + ) +}) + +// Split children move to a module-level chunk component, so only runtime +// values may become props. +// Source: Qwik optimizer should_wrap_type_asserted_variables_in_template; +// SolidStart compile.spec.ts "does not read type annotations as captured values" +test('client: local types used by the children are not captured', async () => { + const { chunk } = await compileChunk(`import type { Shape } from './types' +function format(value: T) { return String(value) } +function List(props: { items: Array }) { return
      {props.items.length}
    } +export function Page({ v }: { v: unknown }) { + type Local = string + interface Box { value: Local } + return items={[v] as Array} />

    {format(v as Local) + (v satisfies unknown as Box['value'] as Shape)}

    +}`) + expect(getChunkParams(chunk)).toEqual(['v']) + expect(await renderChunk(chunk, { v: 'x' })).toBe('
      1

    xx

    ') +}) + +// Source: Qwik optimizer example_qwik_conflict, import_collision_with_renaming +test('client: generated names do not collide with user bindings or imports', async () => { + const { parent, chunk } = + await compileChunk(`import { lazyRouteComponent } from '@tanstack/react-router' +const _lazyRouteComponent = 'user' +export const Lazy = lazyRouteComponent(() => import('./other')) +export function Page() { + const _H0 = 'local' + const _H0_preload = 'preload' + return

    {_lazyRouteComponent + _H0 + _H0_preload}

    +}`) + // The lazy chunk component must not be shadowed by the captured locals. + const module = await evaluateModule(parent, hydrateParentStubs) + expect(module.Page()).toBe('[lazy(_H0=local,_H0_preload=preload)]') + expect( + await renderChunk(chunk, { _H0: 'local', _H0_preload: 'preload' }), + ).toBe('

    userlocalpreload

    ') +}) + +// Source: Qwik optimizer example_capture_imports, example_qwik_conflict +test('client: a captured local shadowing an import or module binding wins inside the children only', async () => { + const { chunk } = await compileChunk(`import { label } from './labels' +import { Row } from './row' +const value = 'module' +function Show() { return {value + ':' + label} } +export function Page() { + const label = 'local' + const value = 'local-value' + return {value} +}`) + expect(getChunkParams(chunk)).toEqual(['label', 'value']) + expect( + await renderChunk( + chunk, + { label: 'local', value: 'local-value' }, + { + './labels': { label: 'imported' }, + './row': { Row: ({ text }: { text: string }) => `${text}` }, + }, + ), + ).toBe('localmodule:importedlocal-value') +}) + +// Source: Qwik optimizer nested_segment_param_does_not_collide_with_captured_props +test('client: a nested boundary receives the captures of its enclosing boundary', async () => { + const { parent, chunks, plugin } = await compileHydrate( + 'client', + `${head}export function Page({ isOpen, fee }) { + const label = 'fee' + return

    {label + ':' + (isOpen ? fee : 0)}

    +}`, + ) + expect(getChunkParams(chunks[0]!)).toEqual(['fee', 'isOpen', 'label']) + const outer = await compileFirstChunk(plugin, parent) + const inner = loadChunk(plugin, 'client', getChunkIds(outer.code!)[0]!) + expect(getChunkParams(inner!)).toEqual(['fee', 'isOpen', 'label']) + expect( + await renderChunk(inner!, { label: 'fee', isOpen: true, fee: 5 }), + ).toBe('

    fee:5

    ') +}) diff --git a/packages/start-plugin-core/tests/hydrate-split-modules.test.ts b/packages/start-plugin-core/tests/hydrate-split-modules.test.ts new file mode 100644 index 0000000000..cb62a7d1bd --- /dev/null +++ b/packages/start-plugin-core/tests/hydrate-split-modules.test.ts @@ -0,0 +1,643 @@ +import { afterEach, describe, expect, test } from 'vitest' +import { createHydrateCompilerPlugin } from '../src/hydrate-when-transform' +import { + compileCode, + compileFirstChunk, + compileHydrate, + evaluateHydrateParent, + evaluateModule, + getBoundaryIds, + getChunkComponent, + getChunkIds, + hydrateParentStubs, + importSources, + loadChunk, + parentImportSources, + renderChunk, +} from './regression-helpers' +import { declarationOf, getModuleErrors } from './validate-module' + +// On the client `` children move into a lazily loaded chunk module +// and the parent renders the chunk component in their place; on the server +// the children render inline and the client-only `fallback` is stripped. +// Both modules must stay valid and behave like the original source. + +const head = `import { Hydrate } from '@tanstack/react-start'\n` + +describe('the parent module', () => { + const widgetPage = `${head}import { visible } from '@tanstack/react-start/hydration' +import { Chart, FallbackPane } from './widgets' +import { formatValue } from './format' +const chartTitle = formatValue('Revenue') +export function Page() { + return }> +}` + + test('client: bindings only the split children use leave the parent', async () => { + const { parent, chunks } = await compileHydrate('client', widgetPage) + expect(chunks[0]).toMatch(declarationOf('chartTitle')) + expect(parent).not.toMatch(declarationOf('chartTitle')) + expect(parent).not.toMatch(/\bChart\b/) + expect(importSources(parent)).toEqual(['./widgets']) + }) + + test('server: bindings only the stripped fallback uses are removed', async () => { + const { parent } = await compileHydrate('server', widgetPage) + expect(parent).not.toContain('FallbackPane') + }) + + test("client: 'use client' stays first in the parent module and the split chunk", async () => { + const { parent, chunks } = await compileHydrate( + 'client', + `'use client' +${head}import { Chart } from './chart' +export function Page() { + return +}`, + ) + expect(parent).toMatch(/^\s*['"]use client['"]/) + expect(chunks[0]).toMatch(/^\s*['"]use client['"]/) + }) + + test('client: a self-closing Hydrate with a children prop renders nothing next to its boundary', async () => { + const { parent } = await compileHydrate( + 'client', + `${head}import { idle } from '@tanstack/react-start/hydration' +import { Chart } from './chart' +export function Page() { + return
    } />
    +}`, + ) + expect(await getModuleErrors(parent)).toEqual([]) + const module = await evaluateModule(parent, { + ...hydrateParentStubs, + './chart': { Chart: () => 'chart' }, + }) + // Whether the children prop renders inline or from the chunk, nothing + // may render next to the boundary. + expect(module.Page()).toMatch( + /^
    \[(?:chart|lazy\(\))\]<\/section>$/, + ) + }) + + test('client: a stale h attribute is replaced by the generated boundary id', async () => { + const { parent } = await compileHydrate( + 'client', + `${head}export function Page() { + return

    child

    +}`, + ) + expect(parent).not.toContain('stale') + expect(getBoundaryIds(parent)).toHaveLength(1) + }) + + // String values of `split` are accepted too, for untyped or JS callers. + test('client: split="false" keeps function-as-children in place', async () => { + const parent = await compileCode( + 'client', + `${head}export function Page() { + return {() =>

    child

    }
    +}`, + { compilerPlugins: [createHydrateCompilerPlugin()] }, + ) + expect(parent).toBeNull() + }) + + test.each(['split', 'split="true"'])( + 'client: %s splits the children', + async (split) => { + const { chunks } = await compileHydrate( + 'client', + `${head}export function Page() { + return

    child

    +}`, + ) + expect(chunks).toHaveLength(1) + expect(await renderChunk(chunks[0]!)).toBe('

    child

    ') + }, + ) + + // An object spread into one boundary only is stripped of its fallback; a + // shared or computed object may be observed elsewhere and is kept. + test.each([ + { + name: 'used once', + code: `const opts = { fallback:

    server-fallback

    , when: true } +export function Page() { return

    child

    }`, + kept: false, + }, + { + name: 'shared by two boundaries', + code: `const opts = { fallback:

    server-fallback

    } +export function Page() { return <>

    a

    b

    }`, + kept: true, + }, + { + name: 'returned by a call', + code: `const makeOpts = () => ({ fallback:

    server-fallback

    }) +const opts = makeOpts() +export function Page() { return

    child

    }`, + kept: true, + }, + ])( + 'server: a fallback in a spread object $name is kept: $kept', + async ({ code, kept }) => { + const { parent } = await compileHydrate('server', `${head}${code}`) + expect(await getModuleErrors(parent)).toEqual([]) + expect(parent.includes('server-fallback')).toBe(kept) + }, + ) + + // Source: Qwik optimizer example_functional_component_capture_props + test('server: params used only by the fallback keep later params in place', async () => { + const { parent } = await compileHydrate( + 'server', + `${head}export function List({ items }) { + return
      {items.map((item, i) => {item}

      }>
    • {i}
    • )}
    +} +export function Card(label, body) { + return {label}

    }>

    {body}

    +}`, + ) + const module = await evaluateModule(parent, hydrateParentStubs) + expect(module.List({ items: ['a', 'b'] })).toBe( + '
      [
    • 0
    • ][
    • 1
    • ]
    ', + ) + expect(module.Card('L', 'B')).toBe('[

    B

    ]') + }) + + // Source: Qwik optimizer should_transform_handler_in_for_of_loop + test('server: a loop variable used only by the fallback keeps the module valid', async () => { + const { parent } = await compileHydrate( + 'server', + `${head}export function List({ xs }) { + const out = [] + for (const x of xs) out.push({x}

    }>

    child

    ) + return out +}`, + ) + expect(await getModuleErrors(parent)).toEqual([]) + }) + + // Source: Qwik optimizer should_keep_non_migrated_binding_from_shared_destructuring_declarator + test('server: a destructuring shared by the fallback and the children keeps the children binding', async () => { + const { parent } = await compileHydrate( + 'server', + `${head}export function Page(props) { + const { a, b } = props + return {a}

    }>

    {b}

    +}`, + ) + const module = await evaluateModule(parent, hydrateParentStubs) + expect(module.Page({ a: 'A', b: 'B' })).toBe('[

    B

    ]') + }) + + // Source: Qwik optimizer example_mutable_children, issue_5008 + test('client: boundaries in conditionals and callbacks load the chunk the server id names', async () => { + const code = `${head}export function Page({ flag, items }) { + return
    + {flag ?

    yes

    :

    no

    } + {flag &&

    and

    } + {items.map(function (item, idx) { return

    {'fn' + item}

    })} + {items.map((item) =>

    {'arrow' + item}

    )} +
    +} +export function Other({ early }) { + if (early) { return

    early

    } + return

    late

    +}` + const server = await compileHydrate('server', code) + const { parent, plugin } = await compileHydrate('client', code) + const serverIds = getBoundaryIds(server.parent) + expect(getBoundaryIds(parent)).toEqual(serverIds) + const rendered: Array = [] + for (const id of serverIds) { + const chunkId = getChunkIds(parent).find((chunk) => + chunk.endsWith(`=${id}`), + ) + rendered.push( + await renderChunk(loadChunk(plugin, 'client', chunkId!)!, { + item: 'x', + }), + ) + } + expect(rendered).toEqual([ + '

    yes

    ', + '

    no

    ', + '

    and

    ', + '

    fnx

    ', + '

    arrowx

    ', + '

    early

    ', + '

    late

    ', + ]) + }) + + // Source: Qwik optimizer example_strip_exports_used + test.each([ + { + name: 'an exported server fn also called by the parent', + code: `import { Hydrate, createServerFn } from '@tanstack/react-start' +export const greet = createServerFn().handler(async () => 'greet-handler-marker') +export function Page() { + return <> +}`, + }, + { + name: 'a private server fn only called by the children', + code: `import { Hydrate, createServerFn } from '@tanstack/react-start' +const greet = createServerFn().handler(async () => 'greet-handler-marker') +export function Page() { + return +}`, + }, + ])( + 'client: $name calls the provider id from the split chunk', + async ({ code }) => { + const { parent, plugin } = await compileHydrate('client', code) + const compiled = await compileFirstChunk(plugin, parent) + const chunk = + compiled.code ?? loadChunk(plugin, 'client', getChunkIds(parent)[0]!)! + expect(await getModuleErrors(chunk)).toEqual([]) + expect(chunk).not.toContain('greet-handler-marker') + const provider = await evaluateModule( + (await compileCode('provider', code))!, + ) + // The chunk compiles its own caller of the provider, or imports the + // parent's caller. + const ids = Object.keys(compiled.serverFns) + if (ids.length > 0) { + expect(ids).toEqual([provider.greet_createServerFn_handler.meta.id]) + } else { + expect(parentImportSources(chunk)).not.toEqual([]) + } + }, + ) +}) + +describe('the split chunk', () => { + test.each([ + { name: 'entities', text: '& & &', rendered: '& & &' }, + { + name: 'multi-line text with entities', + text: '\n Fish &\n Chips ©\n ', + rendered: 'Fish & Chips ©', + }, + ])( + 'client: a text-only child renders like JSX text: $name', + async ({ text, rendered }) => { + const { chunks } = await compileHydrate( + 'client', + `${head}export function Page() { + return ${text} +}`, + ) + // Whitespace collapsing aside, the text must render like the + // server-rendered JSX text. + const output = await renderChunk(chunks[0]!) + expect(output.replace(/\s+/g, ' ').trim()).toBe(rendered) + }, + ) + + test('client: children may contain return statements', async () => { + const { chunks } = await compileHydrate( + 'client', + `${head}const letters = ['a', 'b'] +export function Page() { + return
      {letters.map((letter) => { const upper = letter.toUpperCase(); return
    • {upper}
    • })}
    +}`, + ) + expect(await getModuleErrors(chunks[0]!)).toEqual([]) + expect(await renderChunk(chunks[0]!)).toBe('
    • A
    • B
    ') + }) + + // Leaving such a boundary unsplit is valid too. + test('client: empty and comment-only boundaries load chunks that render nothing', async () => { + const { parent, chunks } = await compileHydrate( + 'client', + `${head}export function Page() { + return
    {/* nothing */}
    +}`, + ) + expect(await getModuleErrors(parent)).toEqual([]) + expect(chunks.length).toBeLessThanOrEqual(2) + for (const chunk of chunks) { + expect(await getModuleErrors(chunk)).toEqual([]) + expect(await renderChunk(chunk)).toBeNull() + } + }) + + test('client: chunk ids stay loadable when the same source is compiled again', async () => { + const source = `${head}export function Page() { + return

    chunk-marker

    +}` + const { parent, plugin } = await compileHydrate('client', source) + const [id] = getChunkIds(parent) + expect(loadChunk(plugin, 'client', id!)).toContain('chunk-marker') + await compileCode('client', source, { compilerPlugins: [plugin] }) + expect(loadChunk(plugin, 'client', id!)).toContain('chunk-marker') + // Unknown boundaries and ids without a split id are not Hydrate chunks. + expect(loadChunk(plugin, 'client', id!.replace(/=0_/, '=5_'))).toBeNull() + expect( + loadChunk(plugin, 'client', '/test/src/module.tsx?other=1'), + ).toBeNull() + }) + + // Source: Qwik optimizer example_capture_imports, + // jsx_member_tag_object_is_captured, example_jsx + test('client: default, namespace and aliased imports and namespaced names in the children', async () => { + const { chunks } = await compileHydrate( + 'client', + `${head}import Chart from './chart' +import * as UI from './ui' +import { format as fmt, default as theme } from './format' +export function Page() { + return +}`, + ) + expect(await getModuleErrors(chunks[0]!)).toEqual([]) + expect( + await renderChunk( + chunks[0]!, + {}, + { + './chart': { default: () => '' }, + './ui': { + Button: ({ label }: { label: string }) => + ``, + }, + './format': { + format: (value: string) => `[${value}]`, + default: 'dark', + }, + }, + ), + ).toBe('') + }) + + // Source: Qwik optimizer should_handle_dangerously_set_inner_html + test('client: string attributes keep their value', async () => { + const element = `I'm an h1!" }} />` + const { chunks } = await compileHydrate( + 'client', + `${head}export function Page() { + return ${element} +}`, + ) + // Render the props instead of the element. + const propsRuntime = `const __Fragment = null +const __jsx = (type, props) => JSON.stringify(props) +` + const expected = await evaluateModule( + `export const H0 = () => ${element}`, + {}, + propsRuntime, + ) + const module = await evaluateModule(chunks[0]!, {}, propsRuntime) + expect(getChunkComponent(module)({})).toBe(expected.H0()) + }) + + // Source: Qwik optimizer example_default_export + test('client: an anonymous default-exported component splits its boundary', async () => { + const { parent, chunks } = await compileHydrate( + 'client', + `${head}const label = 'default' +export default () =>

    {label}

    `, + ) + expect(await getModuleErrors(parent)).toEqual([]) + expect(await renderChunk(chunks[0]!)).toBe('

    default

    ') + }) + + // Source: Qwik optimizer example_invalid_references, + // should_migrate_destructured_binding_with_imported_dependency + test('client: a module-level destructuring of an import moves into the chunk with the import', async () => { + const { chunks } = await compileHydrate( + 'client', + `${head}import { source } from './lib' +const fallback = 'd' +const [a, { b = fallback, ...rest }] = source +export function Page() { + return

    {[a, b, JSON.stringify(rest)].join('|')}

    +}`, + ) + expect(await getModuleErrors(chunks[0]!)).toEqual([]) + expect( + await renderChunk( + chunks[0]!, + {}, + { './lib': { source: ['A', { extra: 'x' }] } }, + ), + ).toBe('

    A|d|{"extra":"x"}

    ') + }) + + // Source: Qwik optimizer should_preserve_let_when_migrated_into_segment + test('client: a module-level let used only by the children stays mutable', async () => { + const { chunks } = await compileHydrate( + 'client', + `${head}let renders = 0 +export function Page() { + return

    {++renders}

    +}`, + ) + const component = getChunkComponent(await evaluateModule(chunks[0]!)) + expect(component({})).toBe('

    1

    ') + expect(component({})).toBe('

    2

    ') + }) + + // Source: Qwik optimizer should_keep_non_migrated_binding_from_shared_destructuring_declarator + // (+ _array_destructuring_declarator, _with_rest) + test.each([ + { name: 'object', declaration: `const { a, b } = { a: 'A', b: 'B' }` }, + { name: 'array', declaration: `const [a, b] = ['A', 'B']` }, + { name: 'rest', declaration: `const { a, ...b } = { a: 'A', c: 'B' }` }, + ])( + 'client: an $name destructuring shared by the parent and the children keeps both bindings', + async ({ declaration }) => { + const { parent, chunks, plugin } = await compileHydrate( + 'client', + `${head}${declaration} +export const fromRoot = () => JSON.stringify(b) +export function Page() { + return

    {a}

    +}`, + ) + const { module, parentModuleStubs } = await evaluateHydrateParent( + plugin, + parent, + ) + expect(module.fromRoot()).toContain('B') + expect( + await renderChunk(chunks[0]!, {}, await parentModuleStubs(chunks[0]!)), + ).toBe('

    A

    ') + }, + ) + + // Source: Qwik optimizer should_keep_root_var_used_by_export_decl_and_qrl, + // example_segment_variable_migration, + // variable_migration_transitive_dep_used_by_other_segment + test('client: helpers shared by two boundaries and an export stay available to each', async () => { + const { parent, chunks, plugin } = await compileHydrate( + 'client', + `${head}const scrollState = (el) => ({ x: el.x, y: el.y }) +const saveScroll = (s) => s.x + s.y +const bigHelper = (el) => saveScroll(scrollState(el)) +export const direct = saveScroll(scrollState({ x: 1, y: 1 })) +export function App() { + return <>

    {bigHelper({ x: 1, y: 2 })}

    {scrollState({ x: 3, y: 4 }).y}

    +}`, + ) + expect(chunks).toHaveLength(2) + const { module, parentModuleStubs } = await evaluateHydrateParent( + plugin, + parent, + ) + expect(module.direct).toBe(2) + const render = async (chunk: string) => + renderChunk(chunk, {}, await parentModuleStubs(chunk)) + expect(await render(chunks[0]!)).toBe('

    3

    ') + expect(await render(chunks[1]!)).toBe('

    4

    ') + }) + + // Source: Qwik optimizer example_ts_enums (TypeScript-only declaration forms) + test('client: an overloaded function used by the children keeps its implementation', async () => { + const { chunks } = await compileHydrate( + 'client', + `${head}function label(value: string): string +function label(value: number): string +function label(value: unknown) { return 'label:' + String(value) } +export function Page() { + return

    {label(1)}

    +}`, + ) + expect(await getModuleErrors(chunks[0]!)).toEqual([]) + expect(await renderChunk(chunks[0]!)).toBe('

    label:1

    ') + }) + + /** A page whose split child renders `Widget`, declared by `body`. */ + const widgetPage = (body: string) => `${head}${body} +export function Page(props) { + return +}` + + // A component the children render moves into the chunk with the module + // bindings it reads. + // Source: React Compiler fixtures (per row) + test.each([ + { + // try-catch-* fixtures + name: 'a catch parameter shadowing a module binding', + body: `const error = 'module' +function Widget() { + let caught + try { + throw 'thrown' + } catch (error) { + caught = error + } + return

    {caught}-{error}

    +}`, + expected: '

    thrown-module

    ', + }, + { + // fn-name-no-leak-to-nested-arrow.js + name: 'a named function expression shadowing a module binding', + body: `const helper = () => 'module' +function Widget() { + const local = function helper(n) { + return n > 0 ? helper(n - 1) : 'local' + } + return

    {local(2)}/{helper()}

    +}`, + expected: '

    local/module

    ', + }, + { + // destructure-*-default fixtures + name: 'parameter defaults reading module bindings', + body: `const fallback = 'fb' +function Widget({ title = fallback, items: [first = fallback.toUpperCase()] = [] }) { + return

    {title}{first}

    +}`, + expected: '

    fbFB

    ', + }, + { + // hoisting-simple-function-declaration.js + name: 'a hoisted local function reading a module binding declared later', + body: `function Widget() { + const x = format() + function format() { + return prefix + 'x' + } + return

    {x}

    +} +const prefix = 'p-'`, + expected: '

    p-x

    ', + }, + { + // class fixtures (static blocks, private fields) + name: 'a local class with a static block and a private field', + body: `const base = 2 +function Widget() { + class Counter { + static start + static { + Counter.start = base * 2 + } + #n = Counter.start + get n() { + return this.#n + } + } + return

    {new Counter().n}

    +}`, + expected: '

    4

    ', + }, + ])( + 'client: the chunk renders like the original with $name', + async ({ body, expected }) => { + const { chunks } = await compileHydrate('client', widgetPage(body)) + expect(await getModuleErrors(chunks[0]!)).toEqual([]) + expect(await renderChunk(chunks[0]!, { props: {} })).toBe(expected) + }, + ) + + describe('side effects of the component bodies it moves', () => { + afterEach(() => { + delete (globalThis as { __hydrateCalls?: unknown }).__hydrateCalls + }) + + // An unused local initialized by a hook call or another side effect must + // still run when the chunk renders. + // Source: React Compiler fixtures react-namespace.js, + // unused-optional-method-assigned-to-variable.js, error.todo-reassign-const.js + test.each([ + { name: 'a call', initializer: `useTracked('call')` }, + { name: 'an optional call', initializer: `useTracked?.('optional')` }, + { + name: 'a member read of a call', + initializer: `useTracked('member').length`, + }, + ])( + 'client: an unused local initialized by $name still runs', + async ({ initializer }) => { + const { chunks } = await compileHydrate( + 'client', + widgetPage(`function useTracked(label) { + globalThis.__hydrateCalls.push(label) + return label +} +function Widget() { + const unused = ${initializer} + return

    widget

    +}`), + ) + const calls: Array = [] + ;(globalThis as { __hydrateCalls?: Array }).__hydrateCalls = + calls + expect(await renderChunk(chunks[0]!, { props: {} })).toBe( + '

    widget

    ', + ) + expect(calls).toHaveLength(1) + }, + ) + }) +}) diff --git a/packages/start-plugin-core/tests/hydrate-when-transform.test.ts b/packages/start-plugin-core/tests/hydrate-when-transform.test.ts new file mode 100644 index 0000000000..442482bd86 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrate-when-transform.test.ts @@ -0,0 +1,706 @@ +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import * as t from '@babel/types' +import { generateFromAst, parseAst } from '@tanstack/router-utils' +import { describe, expect, test } from 'vitest' +import { createHydrateCompilerPlugin } from '../src/hydrate-when-transform' +import type { CompileStartFrameworkOptions } from '../src/types' + +const root = '/repo' +const id = '/repo/src/routes/about.tsx' + +type HydrateBoundary = { + id: string + exportName: string + index: number +} + +function getHydrateBoundariesFromCode(code: string): Array { + const boundaries: Array = [] + const hydrateImportPattern = + /import\("([^"]*[?&]tss-hydrate=[^"]*)"\),\s*"([^"]+)"/g + let match: RegExpExecArray | null + + while ((match = hydrateImportPattern.exec(code))) { + const importId = match[1]! + const queryIndex = importId.indexOf('?') + const params = new URLSearchParams(importId.slice(queryIndex + 1)) + const boundaryId = params.get('tss-hydrate') + const separatorIndex = boundaryId?.indexOf('_') ?? -1 + const index = + boundaryId && separatorIndex > 0 + ? Number.parseInt(boundaryId.slice(0, separatorIndex), 36) + : Number.NaN + + if (boundaryId && Number.isInteger(index)) { + boundaries.push({ + id: boundaryId, + exportName: match[2]!, + index, + }) + } + } + + return boundaries.sort((a, b) => a.index - b.index) +} + +function virtualHydrateId( + file: string, + boundary: Pick, +) { + const params = new URLSearchParams() + params.set('tss-hydrate', boundary.id) + return `${file}?${params.toString()}` +} + +function withSourceHash(id: string, sourceHash: string) { + const separatorIndex = id.indexOf('_') + return `${id.slice(0, separatorIndex + 1)}${sourceHash}` +} + +function compileHydrate(options: { + code: string + id: string + root: string + env: 'client' | 'server' + envName?: string + framework?: CompileStartFrameworkOptions + plugin?: ReturnType +}) { + const plugin = options.plugin ?? createHydrateCompilerPlugin() + const envName = options.envName ?? options.env + const ast = parseAst({ code: options.code, sourceFilename: options.id }) + const result = plugin.transformAst?.({ + ast, + code: options.code, + id: options.id, + root: options.root, + env: options.env, + envName, + mode: 'dev', + framework: options.framework ?? 'react', + providerEnvName: 'ssr', + types: t, + parseExpression: (expressionCode) => t.identifier(expressionCode), + }) + if (!result) return null + + const generated = generateFromAst(ast, { + sourceMaps: true, + sourceFileName: options.id, + filename: options.id, + }) + + return { + code: generated.code, + map: generated.map, + boundaries: getHydrateBoundariesFromCode(generated.code), + plugin, + } +} + +function loadVirtualHydrateModule(options: { + code: string + id: string + root: string + envName?: string +}) { + const plugin = createHydrateCompilerPlugin() + return plugin.loadVirtualModule?.({ + code: options.code, + id: options.id, + root: options.root, + env: 'client', + envName: options.envName ?? 'client', + }) +} + +describe('Hydrate compiler transform', () => { + test.each(['client', 'server'] as const)( + 'resolves spread props declared after their containing function in %s output', + (env) => { + const result = compileHydrate({ + code: `import { Hydrate } from '@tanstack/react-start' +export function Page() { return

    child

    } +const props = { when: true, fallback:

    server-fallback

    }`, + id, + root, + env, + }) + expect(result).not.toBeNull() + expect(result?.code).toContain('when: true') + if (env === 'client') { + expect(result?.code).not.toContain('.preload') + expect(result?.code).toContain('server-fallback') + } else { + expect(result?.code).not.toContain('server-fallback') + } + }, + ) + + test.each(['client', 'server'] as const)( + 'respects parenthesized split={false} in %s output', + (env) => { + const result = compileHydrate({ + code: `import { Hydrate } from '@tanstack/react-start'; export function Page() { return {() =>

    child

    }
    }`, + id, + root, + env, + }) + expect(result).toBeNull() + }, + ) + + test.each(['{...({ fallback:

    server-fallback

    })}', '{...(props)}'])( + 'strips fallback from a parenthesized spread %s', + (spread) => { + const result = compileHydrate({ + code: `import { Hydrate } from '@tanstack/react-start'; ${spread.includes('props') ? 'const props = ({ fallback:

    server-fallback

    });' : ''} export function Page() { return

    child

    }`, + id, + root, + env: 'server', + }) + expect(result).not.toBeNull() + expect(result?.code).not.toContain('server-fallback') + }, + ) + + test('strips a statically computed fallback property from server output', () => { + const result = compileHydrate({ + code: `import { Hydrate } from '@tanstack/react-start'; export function Page() { return server-fallback

    }}>

    child

    }`, + id, + root, + env: 'server', + }) + expect(result).not.toBeNull() + expect(result?.code).not.toContain('server-fallback') + }) + + test.each(['{...({ when: true })}', '{...(props)}'])( + 'avoids generating a preload callback for known props %s', + (spread) => { + const result = compileHydrate({ + code: `import { Hydrate } from '@tanstack/react-start'; const props = ({ when: true }); export function Page() { return

    child

    }`, + id, + root, + env: 'client', + }) + expect(result).not.toBeNull() + expect(result?.code).not.toContain('.preload') + }, + ) + + test.each([ + ['{(() =>

    child

    )}', /function-as-children/], + ['{(useThing)()}', /hooks/], + ])('rejects parenthesized unsafe extraction %s', (child, message) => { + expect(() => + compileHydrate({ + code: `import { Hydrate } from '@tanstack/react-start'; export function Page() { return ${child} }`, + id, + root, + env: 'client', + }), + ).toThrow(message) + }) + + test('splits Hydrate children behind a lazy import', () => { + const result = compileHydrate({ + code: ` + import { Hydrate } from '@tanstack/react-start' + import { visible } from '@tanstack/react-start/hydration' + + export function Page() { + return ( + + + + ) + } + + function Widget(props: { title: string }) { + return

    {props.title}

    + } + `, + id, + root, + env: 'client', + }) + + expect(result?.code).toContain('lazyRouteComponent') + expect(result?.code).toContain('tss-hydrate=') + expect(result?.code).not.toContain('tss-hydrate-index') + expect(result?.code).not.toContain('createElement') + expect(result?.code).toContain('h=') + expect(result?.code).not.toContain('p=') + }) + + test('uses the Solid Router import source for Solid Hydrate boundaries', () => { + const result = compileHydrate({ + code: ` + import { Hydrate } from '@tanstack/solid-start' + import { visible } from '@tanstack/solid-start/hydration' + + export function Page() { + return ( + + + + ) + } + + function Widget(props: { title: string }) { + return

    {props.title}

    + } + `, + id, + root, + env: 'client', + framework: 'solid', + }) + + expect(result?.code).toContain( + 'lazyRouteComponent } from "@tanstack/solid-router"', + ) + expect(result?.code).toContain('tss-hydrate=') + expect(result?.code).toContain('h=') + expect(result?.code).not.toContain('p=') + }) + + test('rejects function-as-children unless the boundary opts out of splitting', () => { + expect(() => + compileHydrate({ + code: ` + import { Hydrate } from '@tanstack/react-start' + import { idle } from '@tanstack/react-start/hydration' + + export function Page() { + return ( + + {() =>

    child

    } +
    + ) + } + `, + id, + root, + env: 'client', + }), + ).toThrow(/function-as-children/) + }) + + test('rejects hook calls that would be moved into an extracted component', () => { + expect(() => + compileHydrate({ + code: ` + import { Hydrate } from '@tanstack/react-start' + import { idle } from '@tanstack/react-start/hydration' + + function useThing() { + return 'thing' + } + + export function Page() { + return ( + +

    {useThing()}

    +
    + ) + } + `, + id, + root, + env: 'client', + }), + ).toThrow(/hooks/) + }) + + test('strips Hydrate fallback from the server transform', () => { + const result = compileHydrate({ + code: ` + import { Hydrate } from '@tanstack/react-start' + import { idle, visible } from '@tanstack/react-start/hydration' + + const spreadProps = { + when: visible(), + fallback:
    bound
    , + } + + export function Page() { + return ( + <> + fallback
    } + > + + + inline
    } + > + + + spread, + }} + > + + + + + + + ) + } + + function Widget(props: { title: string }) { + return

    {props.title}

    + } + `, + id, + root, + env: 'server', + }) + + expect(result?.code).not.toContain('fallback=') + expect(result?.code).not.toContain('fallback:') + expect(result?.code).not.toContain('server-fallback') + expect(result?.code).not.toContain('server-inline') + expect(result?.code).not.toContain('server-spread') + expect(result?.code).not.toContain('server-bound-spread') + expect(result?.code).toContain('h=') + expect(result?.code).toContain('') + expect(result?.code).toContain('') + expect(result?.code).toContain('') + expect(result?.code).toContain('') + }) + + test('supports nested Hydrate boundaries in extracted virtual modules', () => { + const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-')) + const file = join(dir, 'route.tsx') + const code = ` + import { Hydrate } from '@tanstack/react-start' + import { interaction, visible } from '@tanstack/react-start/hydration' + + const unused = 'remove me' + + export function Page() { + return ( + +
    + + + +
    +
    + ) + } + ` + const firstPass = compileHydrate({ + code, + id: file, + root: dir, + env: 'client', + }) + expect(firstPass?.boundaries).toHaveLength(1) + + const virtualId = virtualHydrateId(file, firstPass!.boundaries[0]!) + const virtualModule = loadVirtualHydrateModule({ + code, + id: virtualId, + root: dir, + }) + expect(virtualModule?.code).not.toContain('remove me') + + const boundaryIndex = firstPass!.boundaries[0]!.index + const nestedPass = compileHydrate({ + code: virtualModule!.code, + id: virtualId, + root: dir, + env: 'client', + }) + + expect(boundaryIndex).toBe(0) + expect(nestedPass?.code).toContain('H1') + expect(nestedPass?.code).toContain('tss-hydrate=') + }) + + test('keeps sibling boundary ids stable after nested boundaries', () => { + const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-')) + const file = join(dir, 'route.tsx') + const code = ` + import { Hydrate } from '@tanstack/react-start' + import { idle, interaction, visible } from '@tanstack/react-start/hydration' + + export function Page() { + return ( + <> + +
    + + + +
    +
    + +

    Sibling

    +
    + + ) + } + ` + const firstPass = compileHydrate({ + code, + id: file, + root: dir, + env: 'client', + }) + expect( + firstPass?.boundaries.map((boundary) => boundary.exportName), + ).toEqual(['H0', 'H2']) + + const siblingBoundary = firstPass!.boundaries[1]! + const virtualId = virtualHydrateId(file, siblingBoundary) + const boundaryIndex = siblingBoundary.index + const virtualModule = loadVirtualHydrateModule({ + code, + id: virtualId, + root: dir, + }) + const parentVirtualId = virtualHydrateId(file, firstPass!.boundaries[0]!) + const parentVirtualModule = loadVirtualHydrateModule({ + code, + id: parentVirtualId, + root: dir, + }) + const nestedPass = compileHydrate({ + code: parentVirtualModule!.code, + id: parentVirtualId, + root: dir, + env: 'client', + }) + const serverPass = compileHydrate({ + code, + id: file, + root: dir, + env: 'server', + }) + + expect(boundaryIndex).toBe(2) + expect(virtualModule?.code).toContain('Sibling') + expect(virtualModule?.code).not.toContain('Nested') + expect(nestedPass?.boundaries[0]?.exportName).toBe('H1') + expect(serverPass?.code).toContain(firstPass!.boundaries[0]!.id) + expect(serverPass?.code).toContain(nestedPass!.boundaries[0]!.id) + expect(serverPass?.code).toContain(siblingBoundary.id) + }) + + test('loads virtual modules from supplied bundler code instead of the filesystem', () => { + const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-')) + const file = join(dir, 'route.tsx') + const oldCode = ` + import { Hydrate } from '@tanstack/react-start' + import { visible } from '@tanstack/react-start/hydration' + + export function Page() { + return

    Old

    + } + ` + const nextCode = oldCode.replace('Old', 'New') + const firstPass = compileHydrate({ + code: oldCode, + id: file, + root: dir, + env: 'client', + }) + const virtualModule = loadVirtualHydrateModule({ + code: nextCode, + id: virtualHydrateId(file, firstPass!.boundaries[0]!), + root: dir, + }) + + expect(virtualModule?.code).toContain('New') + expect(virtualModule?.code).not.toContain('Old') + }) + + test('captures identifiers used by shorthand objects and computed members', () => { + const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-')) + const file = join(dir, 'route.tsx') + const code = ` + import { Hydrate } from '@tanstack/react-start' + import { visible } from '@tanstack/react-start/hydration' + + export function Page() { + const key = 'name' + const items = { name: 'Ada' } + return ( + + + + ) + } + + function Widget(props: { data: { key: string; value: string } }) { + return

    {props.data.value}

    + } + ` + const firstPass = compileHydrate({ + code, + id: file, + root: dir, + env: 'client', + }) + const virtualModule = loadVirtualHydrateModule({ + code, + id: virtualHydrateId(file, firstPass!.boundaries[0]!), + root: dir, + }) + + expect(virtualModule?.code).toContain('export function H0({') + expect(virtualModule?.code).toContain('items') + expect(virtualModule?.code).toContain('key') + expect(virtualModule?.code).toContain('items[key]') + }) + + test('unwraps exported declarations needed by extracted virtual modules', () => { + const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-')) + const file = join(dir, 'route.tsx') + const code = ` + import { createFileRoute } from '@tanstack/react-router' + import { Hydrate } from '@tanstack/react-start' + import { visible } from '@tanstack/react-start/hydration' + + export const Route = createFileRoute('/test')({ + component: Page, + }) + + export const label = 'Ada' + + export const Widget = () => { + return

    {label}

    + } + + function Page() { + return + } + ` + const firstPass = compileHydrate({ + code, + id: file, + root: dir, + env: 'client', + }) + const virtualModule = loadVirtualHydrateModule({ + code, + id: virtualHydrateId(file, firstPass!.boundaries[0]!), + root: dir, + }) + + expect(virtualModule?.code).toContain('const Widget') + expect(virtualModule?.code).toContain('const label') + expect(virtualModule?.code).toContain('') + expect(virtualModule?.code).not.toContain('export const Widget') + expect(virtualModule?.code).not.toContain('createFileRoute') + expect(virtualModule?.code).not.toContain('const Route') + }) + + test('invalidates cached Hydrate source for virtual module loads', () => { + const dir = mkdtempSync(join(tmpdir(), 'hydrate-when-')) + const file = join(dir, 'route.tsx') + const oldCode = ` + import { Hydrate } from '@tanstack/react-start' + import { visible } from '@tanstack/react-start/hydration' + + export function Page() { + return

    Old

    + } + ` + const nextCode = oldCode.replace('Old', 'New') + const envName = 'client' + const plugin = createHydrateCompilerPlugin() + const transformed = compileHydrate({ + code: oldCode, + id: file, + root: dir, + env: 'client', + envName, + plugin, + }) + const virtualId = virtualHydrateId(file, transformed!.boundaries[0]!) + + expect( + transformed!.plugin.loadVirtualModule?.({ + id: virtualId, + root: dir, + env: 'client', + envName, + })?.code, + ).toContain('Old') + + transformed!.plugin.invalidateModule?.({ id: file, envName }) + expect(() => + transformed!.plugin.loadVirtualModule?.({ + id: virtualId, + root: dir, + env: 'client', + envName, + }), + ).toThrow(/Missing Hydrate source/) + + const updated = compileHydrate({ + code: nextCode, + id: file, + root: dir, + env: 'client', + envName, + plugin, + }) + + expect( + updated!.plugin.loadVirtualModule?.({ + id: virtualId, + root: dir, + env: 'client', + envName, + })?.code, + ).toContain('New') + }) + + test('rejects virtual module ids whose source hash does not match', () => { + const code = ` + import { Hydrate } from '@tanstack/react-start' + import { idle, visible } from '@tanstack/react-start/hydration' + + export function Page() { + return ( + <> +

    First

    +

    Second

    + + ) + } + ` + const firstPass = compileHydrate({ + code, + id, + root, + env: 'client', + }) + const mismatchedId = virtualHydrateId(id, { + id: withSourceHash(firstPass!.boundaries[0]!.id, 'mismatch'), + index: firstPass!.boundaries[0]!.index, + }) + + expect( + new URLSearchParams(mismatchedId.split('?')[1]).get('tss-hydrate'), + ).toMatch(/_mismatch$/) + expect( + loadVirtualHydrateModule({ code, id: mismatchedId, root }), + ).toBeNull() + }) +}) diff --git a/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenFunctionChild.tsx b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenFunctionChild.tsx new file mode 100644 index 0000000000..a2560a6197 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenFunctionChild.tsx @@ -0,0 +1,6 @@ +import { Hydrate } from '@tanstack/react-start' +import { idle } from '@tanstack/react-start/hydration' + +export function Page() { + return {() =>

    child

    }
    +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenHookCall.tsx b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenHookCall.tsx new file mode 100644 index 0000000000..1e89bb7303 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenHookCall.tsx @@ -0,0 +1,14 @@ +import { Hydrate } from '@tanstack/react-start' +import { idle } from '@tanstack/react-start/hydration' + +function useThing() { + return 'thing' +} + +export function Page() { + return ( + +

    {useThing()}

    +
    + ) +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenSuperCapture.tsx b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenSuperCapture.tsx new file mode 100644 index 0000000000..63b91b0239 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenSuperCapture.tsx @@ -0,0 +1,16 @@ +import { Hydrate } from '@tanstack/react-start' +import { idle } from '@tanstack/react-start/hydration' + +class Base { + title = 'super' +} + +export class Page extends Base { + render() { + return ( + +

    {super.title}

    +
    + ) + } +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenThisCapture.tsx b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenThisCapture.tsx new file mode 100644 index 0000000000..5f7b3df606 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/error-files/hydrateWhenThisCapture.tsx @@ -0,0 +1,14 @@ +import { Hydrate } from '@tanstack/react-start' +import { idle } from '@tanstack/react-start/hydration' + +export class Page { + title = 'this' + + render() { + return ( + +

    {this.title}

    +
    + ) + } +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/hydrateWhen.test.ts b/packages/start-plugin-core/tests/hydrateWhen/hydrateWhen.test.ts new file mode 100644 index 0000000000..d47bc3972d --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/hydrateWhen.test.ts @@ -0,0 +1,313 @@ +import { readFile, readdir } from 'node:fs/promises' +import { traverse } from '@babel/core' +import * as t from '@babel/types' +import { generateFromAst, parseAst } from '@tanstack/router-utils' +import path from 'pathe' +import { describe, expect, test } from 'vitest' +import { createHydrateCompilerPlugin } from '../../src/hydrate-when-transform' +import { formatSnapshot } from '../format-snapshot' + +const fixtureRoot = path.resolve(import.meta.dirname, './test-files') +const errorRoot = path.resolve(import.meta.dirname, './error-files') + +function fixtureId(filename: string) { + return path.join(fixtureRoot, filename) +} + +// Replace the fixture root before formatting so that line breaks do not +// depend on where the repository is checked out. +async function normalizeSnapshotCode(code: string, filename: string) { + return await formatSnapshot( + code.split(fixtureRoot).join(''), + filename, + ) +} + +async function readFixture(filename: string) { + return await readFile(fixtureId(filename), 'utf8') +} + +async function getFilenames(dirname: string) { + return (await readdir(dirname)) + .filter((filename) => filename.endsWith('.tsx')) + .sort() +} + +type HydrateBoundary = { + id: string + exportName: string + index: number +} + +function getHydrateBoundariesFromCode(code: string): Array { + const boundaries: Array = [] + const hydrateImportPattern = + /import\("([^"]*[?&]tss-hydrate=[^"]*)"\),\s*"([^"]+)"/g + let match: RegExpExecArray | null + + while ((match = hydrateImportPattern.exec(code))) { + const importId = match[1]! + const queryIndex = importId.indexOf('?') + const params = new URLSearchParams(importId.slice(queryIndex + 1)) + const boundaryId = params.get('tss-hydrate') + const separatorIndex = boundaryId?.indexOf('_') ?? -1 + const index = + boundaryId && separatorIndex > 0 + ? Number.parseInt(boundaryId.slice(0, separatorIndex), 36) + : Number.NaN + + if (boundaryId && Number.isInteger(index)) { + boundaries.push({ + id: boundaryId, + exportName: match[2]!, + index, + }) + } + } + + return boundaries.sort((a, b) => a.index - b.index) +} + +function compile(opts: { + env: 'client' | 'server' + code: string + id: string + root?: string +}) { + const options = { + ...opts, + root: opts.root ?? fixtureRoot, + } + const plugin = createHydrateCompilerPlugin() + const ast = parseAst({ code: options.code, sourceFilename: options.id }) + const result = plugin.transformAst?.({ + ast, + code: options.code, + id: options.id, + root: options.root, + env: options.env, + envName: options.env, + mode: 'dev', + framework: 'react', + providerEnvName: 'ssr', + types: t, + parseExpression: (expressionCode) => t.identifier(expressionCode), + }) + if (!result) return null + + const generated = generateFromAst(ast, { + sourceMaps: true, + sourceFileName: options.id, + filename: options.id, + }) + + return { + code: generated.code, + map: generated.map, + boundaries: getHydrateBoundariesFromCode(generated.code), + } +} + +function loadVirtualHydrateModule(options: { + code: string + id: string + root: string +}) { + return createHydrateCompilerPlugin().loadVirtualModule?.({ + code: options.code, + id: options.id, + root: options.root, + env: 'client', + envName: 'client', + }) +} + +function virtualHydrateId( + file: string, + boundary: Pick, +) { + const params = new URLSearchParams() + params.set('tss-hydrate', boundary.id) + return `${file}?${params.toString()}` +} + +describe('Hydrate compiler transform fixtures', async () => { + const filenames = await getFilenames(fixtureRoot) + + describe.each(filenames)('should handle "%s"', async (filename) => { + const code = await readFixture(filename) + const id = fixtureId(filename) + + test(`should compile ${filename} for client`, async () => { + const result = compile({ env: 'client', code, id }) + + await expect( + result + ? await normalizeSnapshotCode(result.code, filename) + : 'no-transform', + ).toMatchFileSnapshot(`./snapshots/client/${filename}`) + }) + + test(`should compile ${filename} for server`, async () => { + const result = compile({ env: 'server', code, id }) + + await expect( + result + ? await normalizeSnapshotCode(result.code, filename) + : 'no-transform', + ).toMatchFileSnapshot(`./snapshots/server/${filename}`) + }) + }) + + test('generated lazy names do not shadow existing global references', () => { + const code = `import { Hydrate } from '@tanstack/react-start'; export const before = _H0; export function Page() { return
    }` + const compiled = compile({ + env: 'client', + code, + id: fixtureId('global.tsx'), + })! + const output = parseAst({ code: compiled.code }) + const globalReferences: Array = [] + traverse(output, { + ReferencedIdentifier(path) { + if (path.node.name === '_H0' && !path.scope.hasBinding('_H0', true)) { + globalReferences.push(path.node.name) + } + }, + }) + expect(globalReferences).toEqual(['_H0']) + }) + + test('retains captured local components and values across extraction', async () => { + const code = ` + import { Hydrate } from '@tanstack/react-start' + export function Page({ name }) { + const count = 1 + const Local = () => {name} + return {name} + } + ` + const id = fixtureId('captured.tsx') + const compiled = compile({ env: 'client', code, id })! + expect(compiled.code).toContain('Local={Local}') + expect(compiled.code).toContain('count={count}') + expect(compiled.code).toContain('name={name}') + expect(compiled.code).toContain('const count = 1') + expect(compiled.code).toContain('const Local') + const loaded = await loadVirtualHydrateModule({ + code, + id: virtualHydrateId(id, compiled.boundaries[0]!), + root: fixtureRoot, + }) + expect(loaded).toBeTruthy() + const output = parseAst({ code: loaded!.code }) + const capturedReferences = new Set() + traverse(output, { + Program(path) { + expect(path.scope.getBinding('Page')).toBeUndefined() + }, + ReferencedIdentifier(path) { + if (['Local', 'count', 'name'].includes(path.node.name)) { + capturedReferences.add(path.node.name) + expect(path.scope.hasBinding(path.node.name, true)).toBe(true) + } + }, + }) + expect([...capturedReferences].sort()).toEqual(['Local', 'count', 'name']) + }) + + test('should extract virtual modules and keep nested ids stable', async () => { + const filename = 'hydrateWhenNested.tsx' + const code = await readFixture(filename) + const id = fixtureId(filename) + const firstPass = compile({ env: 'client', code, id }) + + expect( + firstPass?.boundaries.map((boundary) => boundary.exportName), + ).toEqual(['H0', 'H2']) + + for (const boundary of firstPass!.boundaries) { + const virtualId = virtualHydrateId(id, boundary) + const loaded = loadVirtualHydrateModule({ + code, + id: virtualId, + root: fixtureRoot, + }) + + await expect( + loaded + ? await normalizeSnapshotCode(loaded.code, filename) + : 'no-virtual-module', + ).toMatchFileSnapshot( + `./snapshots/virtual/${filename}.${boundary.exportName}.tsx`, + ) + } + + const parentBoundary = firstPass!.boundaries[0]! + const parentVirtualId = virtualHydrateId(id, parentBoundary) + const parentVirtualModule = loadVirtualHydrateModule({ + code, + id: parentVirtualId, + root: fixtureRoot, + }) + const nestedPass = compile({ + code: parentVirtualModule!.code, + id: parentVirtualId, + env: 'client', + }) + + await expect( + nestedPass + ? await normalizeSnapshotCode(nestedPass.code, filename) + : 'no-transform', + ).toMatchFileSnapshot(`./snapshots/virtual/${filename}.H0.client.tsx`) + }) +}) + +describe('Hydrate compiler extraction errors', async () => { + const errorCases = [ + { + filename: 'hydrateWhenFunctionChild.tsx', + message: /function-as-children/, + }, + { + filename: 'hydrateWhenHookCall.tsx', + message: /hooks/, + }, + { + filename: 'hydrateWhenThisCapture.tsx', + message: /captures this/, + }, + { + filename: 'hydrateWhenSuperCapture.tsx', + message: /captures super/, + }, + ] as const + + describe.each(errorCases)('$filename', async ({ filename, message }) => { + const code = await readFile(path.join(errorRoot, filename), 'utf8') + const id = path.join(errorRoot, filename) + + test('should reject unsafe client extraction', () => { + expect(() => + compile({ + code, + id, + root: errorRoot, + env: 'client', + }), + ).toThrow(message) + }) + + test('should reject unsafe server extraction', () => { + expect(() => + compile({ + code, + id, + root: errorRoot, + env: 'server', + }), + ).toThrow(message) + }) + }) +}) diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenBasic.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenBasic.tsx new file mode 100644 index 0000000000..5f057addab --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenBasic.tsx @@ -0,0 +1,24 @@ +const _H = _lazyRouteComponent( + () => import('/hydrateWhenBasic.tsx?tss-hydrate=0_3cf0187f82'), + 'H0', + ), + _H0_preload = _H.preload +import { lazyRouteComponent as _lazyRouteComponent } from '@tanstack/react-router' +import { Hydrate } from '@tanstack/react-start' +import { idle, visible } from '@tanstack/react-start/hydration' +import { FallbackPane } from './widgets' +export function Page() { + return ( +
    + } + h="0_3cf0187f82" + p={_H0_preload} + > + {<_H />} + +
    + ) +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenMultiple.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenMultiple.tsx new file mode 100644 index 0000000000..34203df6ad --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenMultiple.tsx @@ -0,0 +1,33 @@ +const _H3 = _lazyRouteComponent( + () => + import('/hydrateWhenMultiple.tsx?tss-hydrate=2_21aa371e0f'), + 'H2', +) +const _H2 = _lazyRouteComponent( + () => + import('/hydrateWhenMultiple.tsx?tss-hydrate=1_21aa371e0f'), + 'H1', +) +const _H = _lazyRouteComponent( + () => + import('/hydrateWhenMultiple.tsx?tss-hydrate=0_21aa371e0f'), + 'H0', +) +import { lazyRouteComponent as _lazyRouteComponent } from '@tanstack/react-router' +import { Hydrate } from '@tanstack/react-start' +import { load, media, visible } from '@tanstack/react-start/hydration' +export function Page() { + return ( + <> + + {<_H />} + + + {<_H2 />} + + + {<_H3 />} + + + ) +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNested.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNested.tsx new file mode 100644 index 0000000000..adec83789c --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNested.tsx @@ -0,0 +1,24 @@ +const _H2 = _lazyRouteComponent( + () => import('/hydrateWhenNested.tsx?tss-hydrate=2_466696e41d'), + 'H2', +) +const _H = _lazyRouteComponent( + () => import('/hydrateWhenNested.tsx?tss-hydrate=0_466696e41d'), + 'H0', +) +import { lazyRouteComponent as _lazyRouteComponent } from '@tanstack/react-router' +import { Hydrate } from '@tanstack/react-start' +import { idle, visible } from '@tanstack/react-start/hydration' +const unused = 'remove me from virtual modules' +export function Page() { + return ( + <> + + {<_H />} + + + {<_H2 />} + + + ) +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNever.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNever.tsx new file mode 100644 index 0000000000..c2af676fa4 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNever.tsx @@ -0,0 +1,14 @@ +const _H = _lazyRouteComponent( + () => import('/hydrateWhenNever.tsx?tss-hydrate=0_b752509d76'), + 'H0', +) +import { lazyRouteComponent as _lazyRouteComponent } from '@tanstack/react-router' +import { Hydrate } from '@tanstack/react-start' +import { never } from '@tanstack/react-start/hydration' +export function Page() { + return ( + + {<_H />} + + ) +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNoImport.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNoImport.tsx new file mode 100644 index 0000000000..b35c36ab1b --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNoImport.tsx @@ -0,0 +1 @@ +no-transform \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNotFromTanstack.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNotFromTanstack.tsx new file mode 100644 index 0000000000..b35c36ab1b --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenNotFromTanstack.tsx @@ -0,0 +1 @@ +no-transform \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenObjectFallback.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenObjectFallback.tsx new file mode 100644 index 0000000000..a0353594f2 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenObjectFallback.tsx @@ -0,0 +1,47 @@ +const _H3 = _lazyRouteComponent( + () => + import('/hydrateWhenObjectFallback.tsx?tss-hydrate=2_7f4dc3aa80'), + 'H2', +) +const _H2 = _lazyRouteComponent( + () => + import('/hydrateWhenObjectFallback.tsx?tss-hydrate=1_7f4dc3aa80'), + 'H1', +) +const _H = _lazyRouteComponent( + () => + import('/hydrateWhenObjectFallback.tsx?tss-hydrate=0_7f4dc3aa80'), + 'H0', +) +import { lazyRouteComponent as _lazyRouteComponent } from '@tanstack/react-router' +import { Hydrate } from '@tanstack/react-start' +import { idle, visible } from '@tanstack/react-start/hydration' +const spreadProps = { + when: visible(), + fallback:
    Bound
    , +} +export function Page() { + return ( + <> + Direct
    } + h="0_7f4dc3aa80" + > + {<_H />} +
    + Inline, + }} + h="1_7f4dc3aa80" + > + {<_H2 />} + + + {<_H3 />} + + + ) +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenPrefetchState.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenPrefetchState.tsx new file mode 100644 index 0000000000..05028ec03b --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenPrefetchState.tsx @@ -0,0 +1,30 @@ +const _H = _lazyRouteComponent( + () => + import('/hydrateWhenPrefetchState.tsx?tss-hydrate=0_24b5f958eb'), + 'H0', + ), + _H0_preload = _H.preload +import { lazyRouteComponent as _lazyRouteComponent } from '@tanstack/react-router' +import { useState } from 'react' +import { Hydrate } from '@tanstack/react-start' +import { interaction } from '@tanstack/react-start/hydration' +export function Page() { + const [status, setStatus] = useState('idle') + const [, setUnusedStatus] = useState('idle') + return ( +
    +

    {status}

    + { + setStatus('prefetched') + setUnusedStatus('prefetched') + }} + h="0_24b5f958eb" + p={_H0_preload} + > + {<_H />} + +
    + ) +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenRenamed.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenRenamed.tsx new file mode 100644 index 0000000000..509b2b988b --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenRenamed.tsx @@ -0,0 +1,14 @@ +const _H = _lazyRouteComponent( + () => import('/hydrateWhenRenamed.tsx?tss-hydrate=0_f555ef3ac2'), + 'H0', +) +import { lazyRouteComponent as _lazyRouteComponent } from '@tanstack/react-router' +import { Hydrate as HW } from '@tanstack/react-start' +import { interaction } from '@tanstack/react-start/hydration' +export function Page() { + return ( + + {<_H />} + + ) +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalse.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalse.tsx new file mode 100644 index 0000000000..b35c36ab1b --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalse.tsx @@ -0,0 +1 @@ +no-transform \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalseFunctionChild.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalseFunctionChild.tsx new file mode 100644 index 0000000000..b35c36ab1b --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenSplitFalseFunctionChild.tsx @@ -0,0 +1 @@ +no-transform \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenWrongImportName.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenWrongImportName.tsx new file mode 100644 index 0000000000..b35c36ab1b --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/client/hydrateWhenWrongImportName.tsx @@ -0,0 +1 @@ +no-transform \ No newline at end of file diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenBasic.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenBasic.tsx new file mode 100644 index 0000000000..71896aa304 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenBasic.tsx @@ -0,0 +1,18 @@ +import { Hydrate } from '@tanstack/react-start' +import { idle, visible } from '@tanstack/react-start/hydration' +import { Chart } from './widgets' +import { formatValue } from './format' +const chartTitle = formatValue('Revenue') +export function Page() { + return ( +
    + + + +
    + ) +} diff --git a/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenMultiple.tsx b/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenMultiple.tsx new file mode 100644 index 0000000000..92bb4f9a26 --- /dev/null +++ b/packages/start-plugin-core/tests/hydrateWhen/snapshots/server/hydrateWhenMultiple.tsx @@ -0,0 +1,26 @@ +import { Hydrate } from '@tanstack/react-start' +import { load, media, visible } from '@tanstack/react-start/hydration' +function Summary() { + return
    Summary
    +} +function Comments() { + return
    Comments
    +} +function Footer() { + return
    Footer
    +} +export function Page() { + return ( + <> + + + + + + + +
    + Preferences ( 'https://jsonplaceholder.typicode.com/users/' + params.id, ) - return json({ + return Response.json({ id: res.data.id, name: res.data.name, email: res.data.email, }) } catch (e) { console.error(e) - return json({ error: 'User not found' }, { status: 404 }) + return Response.json({ error: 'User not found' }, { status: 404 }) } }, }, diff --git a/examples/react/start-basic-react-query/src/routes/api/users.ts b/examples/react/start-basic-react-query/src/routes/api/users.ts index 0e290833bb..68fbdfcff0 100644 --- a/examples/react/start-basic-react-query/src/routes/api/users.ts +++ b/examples/react/start-basic-react-query/src/routes/api/users.ts @@ -1,5 +1,4 @@ import { createFileRoute } from '@tanstack/react-router' -import { json } from '@tanstack/react-start' import axios from 'redaxios' import type { User } from '../../utils/users' @@ -12,7 +11,7 @@ export const Route = createFileRoute('/api/users')({ 'https://jsonplaceholder.typicode.com/users', ) const list = res.data.slice(0, 10) - return json( + return Response.json( list.map((u) => ({ id: u.id, name: u.name, email: u.email })), ) }, diff --git a/examples/react/start-basic-react-query/src/routes/deferred.tsx b/examples/react/start-basic-react-query/src/routes/deferred.tsx index 0380f79aca..11af82ed27 100644 --- a/examples/react/start-basic-react-query/src/routes/deferred.tsx +++ b/examples/react/start-basic-react-query/src/routes/deferred.tsx @@ -1,6 +1,5 @@ import { createFileRoute } from '@tanstack/react-router' import { queryOptions, useSuspenseQuery } from '@tanstack/react-query' -import {} from '@tanstack/react-router' import { Suspense, useState } from 'react' const deferredQueryOptions = () => diff --git a/examples/react/start-basic-react-query/src/routes/preferences.tsx b/examples/react/start-basic-react-query/src/routes/preferences.tsx new file mode 100644 index 0000000000..603257fc0f --- /dev/null +++ b/examples/react/start-basic-react-query/src/routes/preferences.tsx @@ -0,0 +1,68 @@ +import { + useMutation, + useQueryClient, + useSuspenseQuery, +} from '@tanstack/react-query' +import { createFileRoute, useHydrated } from '@tanstack/react-router' +import { useServerFn } from '@tanstack/react-start' +import { readerNameOptions, saveReaderName } from '../utils/preferences' + +export const Route = createFileRoute('/preferences')({ + loader: async ({ context }) => { + await context.queryClient.query(readerNameOptions) + }, + headers: () => ({ 'Cache-Control': 'private, no-store' }), + head: () => ({ meta: [{ title: 'Reader preferences' }] }), + component: Preferences, +}) + +function Preferences() { + const { data: name } = useSuspenseQuery(readerNameOptions) + const queryClient = useQueryClient() + const save = useServerFn(saveReaderName) + const hydrated = useHydrated() + const mutation = useMutation({ + mutationFn: (name: string) => save({ data: name }), + onSuccess: () => + queryClient.invalidateQueries({ queryKey: readerNameOptions.queryKey }), + }) + + return ( +
    +

    Reader preferences

    +

    Hello, {name}

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

    Could not save your name. Try again.

    + ) : null} +
    +
    + ) +} diff --git a/examples/react/start-basic-react-query/src/start.ts b/examples/react/start-basic-react-query/src/start.ts new file mode 100644 index 0000000000..5fb1e247fb --- /dev/null +++ b/examples/react/start-basic-react-query/src/start.ts @@ -0,0 +1,9 @@ +import { createCsrfMiddleware, createStart } from '@tanstack/react-start' + +export const startInstance = createStart(() => ({ + requestMiddleware: [ + createCsrfMiddleware({ + filter: (ctx) => ctx.handlerType === 'serverFn', + }), + ], +})) diff --git a/examples/react/start-basic-react-query/src/styles/app.css b/examples/react/start-basic-react-query/src/styles/app.css index c36c737cd4..37c1f5a6e2 100644 --- a/examples/react/start-basic-react-query/src/styles/app.css +++ b/examples/react/start-basic-react-query/src/styles/app.css @@ -1,4 +1,4 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @layer base { *, diff --git a/examples/react/start-basic-react-query/src/utils/posts.tsx b/examples/react/start-basic-react-query/src/utils/posts.tsx index a95e9dce27..dc6979005e 100644 --- a/examples/react/start-basic-react-query/src/utils/posts.tsx +++ b/examples/react/start-basic-react-query/src/utils/posts.tsx @@ -25,7 +25,7 @@ export const postsQueryOptions = () => }) export const fetchPost = createServerFn({ method: 'GET' }) - .inputValidator((d: string) => d) + .validator((d: string) => d) .handler(async ({ data }) => { console.info(`Fetching post with id ${data}...`) const post = await axios diff --git a/examples/react/start-basic-react-query/src/utils/preferences.ts b/examples/react/start-basic-react-query/src/utils/preferences.ts new file mode 100644 index 0000000000..74c33e5848 --- /dev/null +++ b/examples/react/start-basic-react-query/src/utils/preferences.ts @@ -0,0 +1,34 @@ +import { queryOptions } from '@tanstack/react-query' +import { createServerFn } from '@tanstack/react-start' +import { + getCookie, + setCookie, + setResponseHeader, +} from '@tanstack/react-start/server' + +export const getReaderName = createServerFn({ method: 'GET' }).handler(() => { + setResponseHeader('Cache-Control', 'private, no-store') + return getCookie('reader-name') || 'Guest' +}) + +export const saveReaderName = createServerFn({ method: 'POST' }) + .validator((name: string) => { + if (typeof name !== 'string' || !name.trim() || name.length > 40) { + throw new Error('Enter a name between 1 and 40 characters') + } + return name.trim() + }) + .handler(({ data }) => { + setResponseHeader('Cache-Control', 'private, no-store') + setCookie('reader-name', data, { + httpOnly: true, + sameSite: 'lax', + secure: process.env.NODE_ENV === 'production', + path: '/', + }) + }) + +export const readerNameOptions = queryOptions({ + queryKey: ['reader-name'], + queryFn: () => getReaderName(), +}) diff --git a/examples/react/start-basic-react-query/tests/preferences.spec.ts b/examples/react/start-basic-react-query/tests/preferences.spec.ts new file mode 100644 index 0000000000..309c402798 --- /dev/null +++ b/examples/react/start-basic-react-query/tests/preferences.spec.ts @@ -0,0 +1,67 @@ +import { expect, test } from '@playwright/test' + +test('concurrent SSR requests keep the same query key isolated by request', async ({ + request, +}) => { + const names = ['Lucia', 'Omar', 'Maya', 'Felix'] + const responses = await Promise.all( + names.map((name) => + request.get('/preferences', { + headers: { Cookie: `reader-name=${name}` }, + }), + ), + ) + for (const [index, response] of responses.entries()) { + expect(response.status()).toBe(200) + expect(response.headers()['cache-control']).toContain('no-store') + const html = await response.text() + expect(html).toContain(names[index]) + for (const other of names.filter((_, otherIndex) => otherIndex !== index)) { + expect(html).not.toContain(other) + } + } +}) + +test('hydration reuses SSR data and mutation invalidation refetches once', async ({ + page, +}) => { + const reads: string[] = [] + page.on('request', (request) => { + if ( + request.method() === 'GET' && + new URL(request.url()).pathname.startsWith('/_serverFn/') + ) { + reads.push(request.url()) + } + }) + await page.goto('/preferences') + await expect(page.getByTestId('reader-name')).toHaveText('Hello, Guest') + await expect(page.getByLabel('Display name')).toBeEnabled() + await page.waitForLoadState('networkidle') + expect(reads).toHaveLength(0) + + await page.getByLabel('Display name').fill('Ada') + const mutation = page.waitForRequest((request) => request.method() === 'POST') + await page.getByRole('button', { name: 'Save name' }).click() + await expect(page.getByTestId('reader-name')).toHaveText('Hello, Ada') + await expect(page.getByRole('button', { name: 'Save name' })).toBeEnabled() + await page.waitForLoadState('networkidle') + expect(reads).toHaveLength(1) + + const savedRequest = await mutation + const headers = await savedRequest.allHeaders() + delete headers['content-length'] + headers.origin = 'https://untrusted.example' + headers['sec-fetch-site'] = 'cross-site' + const denied = await page.request.post(savedRequest.url(), { + headers, + data: savedRequest.postData() ?? '', + }) + expect(denied.status()).toBe(403) + + await page.reload() + await expect(page.getByTestId('reader-name')).toHaveText('Hello, Ada') + await expect(page.getByLabel('Display name')).toBeEnabled() + await page.waitForLoadState('networkidle') + expect(reads).toHaveLength(1) +}) diff --git a/examples/react/start-basic-react-query/tsconfig.json b/examples/react/start-basic-react-query/tsconfig.json index 3a9fb7cd71..cef9369516 100644 --- a/examples/react/start-basic-react-query/tsconfig.json +++ b/examples/react/start-basic-react-query/tsconfig.json @@ -13,7 +13,6 @@ "target": "ES2022", "allowJs": true, "forceConsistentCasingInFileNames": true, - "baseUrl": ".", "paths": { "~/*": ["./src/*"] }, diff --git a/examples/react/start-basic-react-query/vite.config.ts b/examples/react/start-basic-react-query/vite.config.ts index f10c86e79f..ed6799764a 100644 --- a/examples/react/start-basic-react-query/vite.config.ts +++ b/examples/react/start-basic-react-query/vite.config.ts @@ -1,17 +1,14 @@ import { tanstackStart } from '@tanstack/react-start/plugin/vite' import { defineConfig } from 'vite' -import tsConfigPaths from 'vite-tsconfig-paths' import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' export default defineConfig({ server: { port: 3000, }, - plugins: [ - tsConfigPaths({ - projects: ['./tsconfig.json'], - }), - tanstackStart(), - viteReact(), - ], + resolve: { + tsconfigPaths: true, + }, + plugins: [tailwindcss(), tanstackStart(), viteReact()], }) diff --git a/examples/react/start-basic-rsbuild/.devcontainer/devcontainer.json b/examples/react/start-basic-rsbuild/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-basic-rsbuild/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-basic-rsbuild/.gitignore b/examples/react/start-basic-rsbuild/.gitignore new file mode 100644 index 0000000000..1f189d9bc0 --- /dev/null +++ b/examples/react/start-basic-rsbuild/.gitignore @@ -0,0 +1,19 @@ +node_modules +package-lock.json +yarn.lock + +.DS_Store +.cache +.env +.vercel +dist +/build/ +/api/ +/server/build +/public/build# Sentry Config File +.env.sentry-build-plugin +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ +.tanstack diff --git a/examples/react/start-basic-rsc/.prettierignore b/examples/react/start-basic-rsbuild/.prettierignore similarity index 100% rename from examples/react/start-basic-rsc/.prettierignore rename to examples/react/start-basic-rsbuild/.prettierignore diff --git a/examples/react/start-basic-rsbuild/.vscode/settings.json b/examples/react/start-basic-rsbuild/.vscode/settings.json new file mode 100644 index 0000000000..00b5278e58 --- /dev/null +++ b/examples/react/start-basic-rsbuild/.vscode/settings.json @@ -0,0 +1,11 @@ +{ + "files.watcherExclude": { + "**/routeTree.gen.ts": true + }, + "search.exclude": { + "**/routeTree.gen.ts": true + }, + "files.readonlyInclude": { + "**/routeTree.gen.ts": true + } +} diff --git a/examples/react/start-basic-rsbuild/README.md b/examples/react/start-basic-rsbuild/README.md new file mode 100644 index 0000000000..64117c915b --- /dev/null +++ b/examples/react/start-basic-rsbuild/README.md @@ -0,0 +1,36 @@ +# TanStack Start - Basic Rsbuild Example + +This is the basic TanStack Start Rsbuild example, demonstrating the fundamentals of building applications with TanStack Router and TanStack Start. + +- [TanStack Router Docs](https://tanstack.com/router) + +It's deployed automagically with Netlify! + +- [Netlify](https://netlify.com/) + +## Start a new project based on this example + +To start a new project based on this example, run: + +```sh +npx gitpick TanStack/router/tree/main/examples/react/start-basic-rsbuild start-basic-rsbuild +``` + +## Getting Started + +From your terminal: + +```sh +pnpm install +pnpm dev +``` + +This starts your app in development mode, rebuilding assets on file changes. + +## Build + +To build the app for production: + +```sh +pnpm build +``` diff --git a/examples/react/start-basic-rsbuild/package.json b/examples/react/start-basic-rsbuild/package.json new file mode 100644 index 0000000000..bea4ba26ef --- /dev/null +++ b/examples/react/start-basic-rsbuild/package.json @@ -0,0 +1,33 @@ +{ + "name": "tanstack-start-example-basic-rsbuild", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "rsbuild dev --port 3000", + "build": "rsbuild build && tsc --noEmit", + "preview": "rsbuild preview", + "start": "srvx --prod -s ../client dist/server/index.js" + }, + "dependencies": { + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", + "react": "^19.2.3", + "react-dom": "^19.2.3", + "tailwind-merge": "^3.6.0", + "zod": "^4.4.3" + }, + "devDependencies": { + "@rsbuild/core": "^2.3.1", + "@rsbuild/plugin-react": "^2.0.0", + "@rsbuild/plugin-tailwindcss": "^2.0.3", + "@types/node": "25.0.9", + "@types/react": "^19.2.8", + "@types/react-dom": "^19.2.3", + "srvx": "^1.0.0", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2" + } +} diff --git a/e2e/react-start/basic-rsc/public/android-chrome-192x192.png b/examples/react/start-basic-rsbuild/public/android-chrome-192x192.png similarity index 100% rename from e2e/react-start/basic-rsc/public/android-chrome-192x192.png rename to examples/react/start-basic-rsbuild/public/android-chrome-192x192.png diff --git a/e2e/react-start/basic-rsc/public/android-chrome-512x512.png b/examples/react/start-basic-rsbuild/public/android-chrome-512x512.png similarity index 100% rename from e2e/react-start/basic-rsc/public/android-chrome-512x512.png rename to examples/react/start-basic-rsbuild/public/android-chrome-512x512.png diff --git a/e2e/react-start/basic-rsc/public/apple-touch-icon.png b/examples/react/start-basic-rsbuild/public/apple-touch-icon.png similarity index 100% rename from e2e/react-start/basic-rsc/public/apple-touch-icon.png rename to examples/react/start-basic-rsbuild/public/apple-touch-icon.png diff --git a/e2e/react-start/basic-rsc/public/favicon-16x16.png b/examples/react/start-basic-rsbuild/public/favicon-16x16.png similarity index 100% rename from e2e/react-start/basic-rsc/public/favicon-16x16.png rename to examples/react/start-basic-rsbuild/public/favicon-16x16.png diff --git a/e2e/react-start/basic-rsc/public/favicon-32x32.png b/examples/react/start-basic-rsbuild/public/favicon-32x32.png similarity index 100% rename from e2e/react-start/basic-rsc/public/favicon-32x32.png rename to examples/react/start-basic-rsbuild/public/favicon-32x32.png diff --git a/e2e/react-start/basic-rsc/public/favicon.ico b/examples/react/start-basic-rsbuild/public/favicon.ico similarity index 100% rename from e2e/react-start/basic-rsc/public/favicon.ico rename to examples/react/start-basic-rsbuild/public/favicon.ico diff --git a/e2e/react-start/basic-rsc/public/favicon.png b/examples/react/start-basic-rsbuild/public/favicon.png similarity index 100% rename from e2e/react-start/basic-rsc/public/favicon.png rename to examples/react/start-basic-rsbuild/public/favicon.png diff --git a/e2e/react-start/basic-rsc/public/site.webmanifest b/examples/react/start-basic-rsbuild/public/site.webmanifest similarity index 100% rename from e2e/react-start/basic-rsc/public/site.webmanifest rename to examples/react/start-basic-rsbuild/public/site.webmanifest diff --git a/examples/react/start-basic-rsbuild/rsbuild.config.ts b/examples/react/start-basic-rsbuild/rsbuild.config.ts new file mode 100644 index 0000000000..3705696818 --- /dev/null +++ b/examples/react/start-basic-rsbuild/rsbuild.config.ts @@ -0,0 +1,17 @@ +import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' +import { defineConfig } from '@rsbuild/core' +import { pluginReact } from '@rsbuild/plugin-react' +import { pluginTailwindcss } from '@rsbuild/plugin-tailwindcss' + +export default defineConfig({ + server: { + port: 3000, + }, + plugins: [ + pluginTailwindcss(), + pluginReact(), + tanstackStart({ + srcDirectory: 'src', + }), + ], +}) diff --git a/examples/react/start-basic-rsbuild/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-rsbuild/src/components/DefaultCatchBoundary.tsx new file mode 100644 index 0000000000..4a22649ed4 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/components/DefaultCatchBoundary.tsx @@ -0,0 +1,51 @@ +import { + ErrorComponent, + Link, + useLocation, + useRouter, +} from '@tanstack/react-router' +import type { ErrorComponentProps } from '@tanstack/react-router' + +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + + console.error('DefaultCatchBoundary Error:', error) + + return ( +
    + +
    + + {isRoot ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
    +
    + ) +} diff --git a/e2e/react-start/basic-rsc/src/components/NotFound.tsx b/examples/react/start-basic-rsbuild/src/components/NotFound.tsx similarity index 100% rename from e2e/react-start/basic-rsc/src/components/NotFound.tsx rename to examples/react/start-basic-rsbuild/src/components/NotFound.tsx diff --git a/examples/react/start-basic-rsbuild/src/components/PostError.tsx b/examples/react/start-basic-rsbuild/src/components/PostError.tsx new file mode 100644 index 0000000000..271f2d1de1 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/components/PostError.tsx @@ -0,0 +1,6 @@ +import { ErrorComponent } from '@tanstack/react-router' +import type { ErrorComponentProps } from '@tanstack/react-router' + +export function PostErrorComponent({ error }: ErrorComponentProps) { + return +} diff --git a/examples/react/start-basic-rsbuild/src/components/UserError.tsx b/examples/react/start-basic-rsbuild/src/components/UserError.tsx new file mode 100644 index 0000000000..af5d0c6f16 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/components/UserError.tsx @@ -0,0 +1,6 @@ +import { ErrorComponent } from '@tanstack/react-router' +import type { ErrorComponentProps } from '@tanstack/react-router' + +export function UserErrorComponent({ error }: ErrorComponentProps) { + return +} diff --git a/examples/react/start-basic-rsbuild/src/env.d.ts b/examples/react/start-basic-rsbuild/src/env.d.ts new file mode 100644 index 0000000000..b0ac762b09 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/start-basic-rsbuild/src/routeTree.gen.ts b/examples/react/start-basic-rsbuild/src/routeTree.gen.ts new file mode 100644 index 0000000000..57b849492d --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routeTree.gen.ts @@ -0,0 +1,447 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' +import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, +} as any) +const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ + id: '/customScript.js', + path: '/customScript.js', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, +} as any) +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, +} as any) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/customScript.js': typeof CustomScriptDotjsRoute + '/deferred': typeof DeferredRoute + '/posts': typeof PostsRouteWithChildren + '/redirect': typeof RedirectRoute + '/users': typeof UsersRouteWithChildren + '/api/users': typeof ApiUsersRouteWithChildren + '/posts/$postId': typeof PostsPostIdRoute + '/users/$userId': typeof UsersUserIdRoute + '/posts/': typeof PostsIndexRoute + '/users/': typeof UsersIndexRoute + '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute + '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute + '/api/users/$userId': typeof ApiUsersUserIdRoute + '/posts/$postId/deep': typeof PostsPostIdDeepRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/customScript.js': typeof CustomScriptDotjsRoute + '/deferred': typeof DeferredRoute + '/redirect': typeof RedirectRoute + '/api/users': typeof ApiUsersRouteWithChildren + '/posts/$postId': typeof PostsPostIdRoute + '/users/$userId': typeof UsersUserIdRoute + '/posts': typeof PostsIndexRoute + '/users': typeof UsersIndexRoute + '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute + '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute + '/api/users/$userId': typeof ApiUsersUserIdRoute + '/posts/$postId/deep': typeof PostsPostIdDeepRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren + '/customScript.js': typeof CustomScriptDotjsRoute + '/deferred': typeof DeferredRoute + '/posts': typeof PostsRouteWithChildren + '/redirect': typeof RedirectRoute + '/users': typeof UsersRouteWithChildren + '/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren + '/api/users': typeof ApiUsersRouteWithChildren + '/posts/$postId': typeof PostsPostIdRoute + '/users/$userId': typeof UsersUserIdRoute + '/posts/': typeof PostsIndexRoute + '/users/': typeof UsersIndexRoute + '/_pathlessLayout/_nested-layout/route-a': typeof PathlessLayoutNestedLayoutRouteARoute + '/_pathlessLayout/_nested-layout/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute + '/api/users/$userId': typeof ApiUsersUserIdRoute + '/posts_/$postId/deep': typeof PostsPostIdDeepRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/customScript.js' + | '/deferred' + | '/posts' + | '/redirect' + | '/users' + | '/api/users' + | '/posts/$postId' + | '/users/$userId' + | '/posts/' + | '/users/' + | '/route-a' + | '/route-b' + | '/api/users/$userId' + | '/posts/$postId/deep' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/customScript.js' + | '/deferred' + | '/redirect' + | '/api/users' + | '/posts/$postId' + | '/users/$userId' + | '/posts' + | '/users' + | '/route-a' + | '/route-b' + | '/api/users/$userId' + | '/posts/$postId/deep' + id: + | '__root__' + | '/' + | '/_pathlessLayout' + | '/customScript.js' + | '/deferred' + | '/posts' + | '/redirect' + | '/users' + | '/_pathlessLayout/_nested-layout' + | '/api/users' + | '/posts/$postId' + | '/users/$userId' + | '/posts/' + | '/users/' + | '/_pathlessLayout/_nested-layout/route-a' + | '/_pathlessLayout/_nested-layout/route-b' + | '/api/users/$userId' + | '/posts_/$postId/deep' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren + CustomScriptDotjsRoute: typeof CustomScriptDotjsRoute + DeferredRoute: typeof DeferredRoute + PostsRoute: typeof PostsRouteWithChildren + RedirectRoute: typeof RedirectRoute + UsersRoute: typeof UsersRouteWithChildren + ApiUsersRoute: typeof ApiUsersRouteWithChildren + PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/customScript.js': { + id: '/customScript.js' + path: '/customScript.js' + fullPath: '/customScript.js' + preLoaderRoute: typeof CustomScriptDotjsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute + } + '/_pathlessLayout/_nested-layout/route-b': { + id: '/_pathlessLayout/_nested-layout/route-b' + path: '/route-b' + fullPath: '/route-b' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute + } + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +interface PathlessLayoutNestedLayoutRouteChildren { + PathlessLayoutNestedLayoutRouteARoute: typeof PathlessLayoutNestedLayoutRouteARoute + PathlessLayoutNestedLayoutRouteBRoute: typeof PathlessLayoutNestedLayoutRouteBRoute +} + +const PathlessLayoutNestedLayoutRouteChildren: PathlessLayoutNestedLayoutRouteChildren = + { + PathlessLayoutNestedLayoutRouteARoute: + PathlessLayoutNestedLayoutRouteARoute, + PathlessLayoutNestedLayoutRouteBRoute: + PathlessLayoutNestedLayoutRouteBRoute, + } + +const PathlessLayoutNestedLayoutRouteWithChildren = + PathlessLayoutNestedLayoutRoute._addFileChildren( + PathlessLayoutNestedLayoutRouteChildren, + ) + +interface PathlessLayoutRouteChildren { + PathlessLayoutNestedLayoutRoute: typeof PathlessLayoutNestedLayoutRouteWithChildren +} + +const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { + PathlessLayoutNestedLayoutRoute: PathlessLayoutNestedLayoutRouteWithChildren, +} + +const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( + PathlessLayoutRouteChildren, +) + +interface PostsRouteChildren { + PostsPostIdRoute: typeof PostsPostIdRoute + PostsIndexRoute: typeof PostsIndexRoute +} + +const PostsRouteChildren: PostsRouteChildren = { + PostsPostIdRoute: PostsPostIdRoute, + PostsIndexRoute: PostsIndexRoute, +} + +const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) + +interface UsersRouteChildren { + UsersUserIdRoute: typeof UsersUserIdRoute + UsersIndexRoute: typeof UsersIndexRoute +} + +const UsersRouteChildren: UsersRouteChildren = { + UsersUserIdRoute: UsersUserIdRoute, + UsersIndexRoute: UsersIndexRoute, +} + +const UsersRouteWithChildren = UsersRoute._addFileChildren(UsersRouteChildren) + +interface ApiUsersRouteChildren { + ApiUsersUserIdRoute: typeof ApiUsersUserIdRoute +} + +const ApiUsersRouteChildren: ApiUsersRouteChildren = { + ApiUsersUserIdRoute: ApiUsersUserIdRoute, +} + +const ApiUsersRouteWithChildren = ApiUsersRoute._addFileChildren( + ApiUsersRouteChildren, +) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + PathlessLayoutRoute: PathlessLayoutRouteWithChildren, + CustomScriptDotjsRoute: CustomScriptDotjsRoute, + DeferredRoute: DeferredRoute, + PostsRoute: PostsRouteWithChildren, + RedirectRoute: RedirectRoute, + UsersRoute: UsersRouteWithChildren, + ApiUsersRoute: ApiUsersRouteWithChildren, + PostsPostIdDeepRoute: PostsPostIdDeepRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/examples/react/start-basic-rsbuild/src/router.tsx b/examples/react/start-basic-rsbuild/src/router.tsx new file mode 100644 index 0000000000..f380f73be7 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/router.tsx @@ -0,0 +1,15 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' +import { NotFound } from './components/NotFound' + +export function getRouter() { + const router = createRouter({ + routeTree, + defaultPreload: 'intent', + defaultErrorComponent: DefaultCatchBoundary, + defaultNotFoundComponent: () => , + scrollRestoration: true, + }) + return router +} diff --git a/examples/react/start-basic-rsbuild/src/routes/__root.tsx b/examples/react/start-basic-rsbuild/src/routes/__root.tsx new file mode 100644 index 0000000000..6d4aed1fe0 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/__root.tsx @@ -0,0 +1,130 @@ +import { + HeadContent, + Link, + Scripts, + createRootRoute, +} from '@tanstack/react-router' +import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' +import * as React from 'react' +import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' +import { NotFound } from '~/components/NotFound' +import appCss from '~/styles/app.css?url' +import { seo } from '~/utils/seo' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { + charSet: 'utf-8', + }, + { + name: 'viewport', + content: 'width=device-width, initial-scale=1', + }, + ...seo({ + title: + 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', + description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, + }), + ], + links: [ + { rel: 'stylesheet', href: appCss }, + { + rel: 'apple-touch-icon', + sizes: '180x180', + href: '/apple-touch-icon.png', + }, + { + rel: 'icon', + type: 'image/png', + sizes: '32x32', + href: '/favicon-32x32.png', + }, + { + rel: 'icon', + type: 'image/png', + sizes: '16x16', + href: '/favicon-16x16.png', + }, + { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, + { rel: 'icon', href: '/favicon.ico' }, + ], + scripts: [ + { + src: '/customScript.js', + type: 'text/javascript', + }, + ], + }), + errorComponent: DefaultCatchBoundary, + notFoundComponent: () => , + shellComponent: RootDocument, +}) + +function RootDocument({ children }: { children: React.ReactNode }) { + return ( + + + + + +
    + + Home + {' '} + + Posts + {' '} + + Users + {' '} + + Pathless Layout + {' '} + + Deferred + {' '} + + This Route Does Not Exist + +
    +
    + {children} + + + + + ) +} diff --git a/examples/react/start-basic-rsc/src/routes/_pathlessLayout.tsx b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout.tsx similarity index 100% rename from examples/react/start-basic-rsc/src/routes/_pathlessLayout.tsx rename to examples/react/start-basic-rsbuild/src/routes/_pathlessLayout.tsx diff --git a/examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout.tsx b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout.tsx similarity index 93% rename from examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout.tsx rename to examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout.tsx index c5bcffd5a4..9a48b73a46 100644 --- a/examples/react/start-basic-rsc/src/routes/_pathlessLayout/_nested-layout.tsx +++ b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout.tsx @@ -7,7 +7,7 @@ export const Route = createFileRoute('/_pathlessLayout/_nested-layout')({ function LayoutComponent() { return (
    -
    I'm a nested pathless layout
    +
    I'm a nested layout
    { + console.info(`Fetching users by id=${params.userId}... @`, request.url) + try { + const res = await fetch( + 'https://jsonplaceholder.typicode.com/users/' + params.userId, + ) + if (!res.ok) { + throw new Error('Failed to fetch user') + } + + const user = (await res.json()) as User + + return Response.json({ + id: user.id, + name: user.name, + email: user.email, + }) + } catch (e) { + console.error(e) + return Response.json({ error: 'User not found' }, { status: 404 }) + } + }, + }, + }, +}) diff --git a/examples/react/start-basic-rsbuild/src/routes/api/users.ts b/examples/react/start-basic-rsbuild/src/routes/api/users.ts new file mode 100644 index 0000000000..4cecd01852 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/api/users.ts @@ -0,0 +1,63 @@ +import { createFileRoute } from '@tanstack/react-router' +import { getRequestHeaders } from '@tanstack/react-start/server' +import { createMiddleware } from '@tanstack/react-start' +import type { User } from '~/utils/users' + +const userLoggerMiddleware = createMiddleware().server(async ({ next }) => { + console.info('In: /users') + console.info('Request Headers:', getRequestHeaders()) + const result = await next() + result.response.headers.set('x-users', 'true') + console.info('Out: /users') + return result +}) + +const testParentMiddleware = createMiddleware().server(async ({ next }) => { + console.info('In: testParentMiddleware') + const result = await next() + result.response.headers.set('x-test-parent', 'true') + console.info('Out: testParentMiddleware') + return result +}) + +const testMiddleware = createMiddleware() + .middleware([testParentMiddleware]) + .server(async ({ next }) => { + console.info('In: testMiddleware') + const result = await next() + result.response.headers.set('x-test', 'true') + + // if (Math.random() > 0.5) { + // throw new Response(null, { + // status: 302, + // headers: { Location: 'https://www.google.com' }, + // }) + // } + + console.info('Out: testMiddleware') + return result + }) + +export const Route = createFileRoute('/api/users')({ + server: { + middleware: [testMiddleware, userLoggerMiddleware], + handlers: { + GET: async ({ request }) => { + console.info('GET /api/users @', request.url) + console.info('Fetching users... @', request.url) + const res = await fetch('https://jsonplaceholder.typicode.com/users') + if (!res.ok) { + throw new Error('Failed to fetch users') + } + + const data = (await res.json()) as Array + + const list = data.slice(0, 10) + + return Response.json( + list.map((u) => ({ id: u.id, name: u.name, email: u.email })), + ) + }, + }, + }, +}) diff --git a/examples/react/start-basic-rsbuild/src/routes/customScript[.]js.ts b/examples/react/start-basic-rsbuild/src/routes/customScript[.]js.ts new file mode 100644 index 0000000000..811471ac15 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/customScript[.]js.ts @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/customScript.js')({ + server: { + handlers: { + GET: () => { + return new Response('console.log("Hello from customScript.js!")', { + headers: { + 'Content-Type': 'application/javascript', + }, + }) + }, + }, + }, +}) diff --git a/examples/react/start-basic-rsbuild/src/routes/deferred.tsx b/examples/react/start-basic-rsbuild/src/routes/deferred.tsx new file mode 100644 index 0000000000..f3e09d1d4e --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/deferred.tsx @@ -0,0 +1,62 @@ +import { Await, createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { Suspense, useState } from 'react' + +const personServerFn = createServerFn({ method: 'GET' }) + .validator((d: string) => d) + .handler(({ data: name }) => { + return { name, randomNumber: Math.floor(Math.random() * 100) } + }) + +const slowServerFn = createServerFn({ method: 'GET' }) + .validator((d: string) => d) + .handler(async ({ data: name }) => { + await new Promise((r) => setTimeout(r, 1000)) + return { name, randomNumber: Math.floor(Math.random() * 100) } + }) + +export const Route = createFileRoute('/deferred')({ + loader: async () => { + return { + deferredStuff: new Promise((r) => + setTimeout(() => r('Hello deferred!'), 2000), + ), + deferredPerson: slowServerFn({ data: 'Tanner Linsley' }), + person: await personServerFn({ data: 'John Doe' }), + } + }, + component: Deferred, +}) + +function Deferred() { + const [count, setCount] = useState(0) + const { deferredStuff, deferredPerson, person } = Route.useLoaderData() + + return ( +
    +
    + {person.name} - {person.randomNumber} +
    + Loading person...
    }> + ( +
    + {data.name} - {data.randomNumber} +
    + )} + /> + + Loading stuff...
    }> +

    {data}

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

    Welcome Home!!!

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

    {post.title}

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

    {post.title}

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

    {user.name}

    +
    {user.email}
    + +
    + ) +} diff --git a/examples/react/start-basic-rsbuild/src/routes/users.index.tsx b/examples/react/start-basic-rsbuild/src/routes/users.index.tsx new file mode 100644 index 0000000000..27d136987e --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/users.index.tsx @@ -0,0 +1,19 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/users/')({ + component: UsersIndexComponent, +}) + +function UsersIndexComponent() { + return ( +
    + ) +} diff --git a/examples/react/start-basic-rsbuild/src/routes/users.tsx b/examples/react/start-basic-rsbuild/src/routes/users.tsx new file mode 100644 index 0000000000..64ca3ce156 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/users.tsx @@ -0,0 +1,49 @@ +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' +import type { User } from '../utils/users' + +export const Route = createFileRoute('/users')({ + loader: async () => { + const res = await fetch('/api/users') + + if (!res.ok) { + throw new Error('Unexpected status code') + } + + const data = await res.json() + + return data as Array + }, + component: UsersComponent, +}) + +function UsersComponent() { + const users = Route.useLoaderData() + + return ( +
    +
      + {[ + ...users, + { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, + ].map((user) => { + return ( +
    • + +
      {user.name}
      + +
    • + ) + })} +
    +
    + +
    + ) +} diff --git a/examples/react/start-basic-rsbuild/src/styles/app.css b/examples/react/start-basic-rsbuild/src/styles/app.css new file mode 100644 index 0000000000..37c1f5a6e2 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/styles/app.css @@ -0,0 +1,30 @@ +@import 'tailwindcss' source('../'); + +@layer base { + *, + ::after, + ::before, + ::backdrop, + ::file-selector-button { + border-color: var(--color-gray-200, currentcolor); + } +} + +@layer base { + html { + color-scheme: light dark; + } + + * { + @apply border-gray-200 dark:border-gray-800; + } + + html, + body { + @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; + } + + .using-mouse * { + outline: none !important; + } +} diff --git a/examples/react/start-basic-rsbuild/src/utils/loggingMiddleware.tsx b/examples/react/start-basic-rsbuild/src/utils/loggingMiddleware.tsx new file mode 100644 index 0000000000..3ea9a06439 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/utils/loggingMiddleware.tsx @@ -0,0 +1,41 @@ +import { createMiddleware } from '@tanstack/react-start' + +const preLogMiddleware = createMiddleware({ type: 'function' }) + .client(async (ctx) => { + const clientTime = new Date() + + return ctx.next({ + context: { + clientTime, + }, + sendContext: { + clientTime, + }, + }) + }) + .server(async (ctx) => { + const serverTime = new Date() + + return ctx.next({ + sendContext: { + serverTime, + durationToServer: + serverTime.getTime() - ctx.context.clientTime.getTime(), + }, + }) + }) + +export const logMiddleware = createMiddleware({ type: 'function' }) + .middleware([preLogMiddleware]) + .client(async (ctx) => { + const res = await ctx.next() + + const now = new Date() + console.log('Client Req/Res:', { + duration: now.getTime() - res.context.clientTime.getTime(), + durationToServer: res.context.durationToServer, + durationFromServer: now.getTime() - res.context.serverTime.getTime(), + }) + + return res + }) diff --git a/examples/react/start-basic-rsbuild/src/utils/posts.tsx b/examples/react/start-basic-rsbuild/src/utils/posts.tsx new file mode 100644 index 0000000000..ea7dd0a721 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/utils/posts.tsx @@ -0,0 +1,40 @@ +import { notFound } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' + +export type PostType = { + id: number + title: string + body: string +} + +export const fetchPost = createServerFn({ method: 'POST' }) + .validator((d: string) => d) + .handler(async ({ data }) => { + console.info(`Fetching post with id ${data}...`) + const res = await fetch( + `https://jsonplaceholder.typicode.com/posts/${data}`, + ) + if (!res.ok) { + if (res.status === 404) { + throw notFound() + } + + throw new Error('Failed to fetch post') + } + + const post = await res.json() + + return post as PostType + }) + +export const fetchPosts = createServerFn().handler(async () => { + console.info('Fetching posts...') + const res = await fetch('https://jsonplaceholder.typicode.com/posts') + if (!res.ok) { + throw new Error('Failed to fetch posts') + } + + const posts = await res.json() + + return (posts as Array).slice(0, 10) +}) diff --git a/examples/react/start-basic-rsc/src/utils/seo.ts b/examples/react/start-basic-rsbuild/src/utils/seo.ts similarity index 100% rename from examples/react/start-basic-rsc/src/utils/seo.ts rename to examples/react/start-basic-rsbuild/src/utils/seo.ts diff --git a/examples/react/start-basic-rsbuild/src/utils/users.tsx b/examples/react/start-basic-rsbuild/src/utils/users.tsx new file mode 100644 index 0000000000..7ba645b383 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/utils/users.tsx @@ -0,0 +1,5 @@ +export type User = { + id: number + name: string + email: string +} diff --git a/examples/react/start-basic-rsbuild/tsconfig.json b/examples/react/start-basic-rsbuild/tsconfig.json new file mode 100644 index 0000000000..cc479423a1 --- /dev/null +++ b/examples/react/start-basic-rsbuild/tsconfig.json @@ -0,0 +1,21 @@ +{ + "include": ["**/*.ts", "**/*.tsx", "**/*.d.ts"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2024"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2024", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true + } +} diff --git a/examples/react/start-basic-rsc/.devcontainer/devcontainer.json b/examples/react/start-basic-rsc/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-basic-rsc/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-basic-rsc/.gitignore b/examples/react/start-basic-rsc/.gitignore deleted file mode 100644 index 3c8e6870b3..0000000000 --- a/examples/react/start-basic-rsc/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -node_modules -package-lock.json -yarn.lock - -.DS_Store -.cache -.env -.vercel -.output -/build/ -/api/ -/server/build -/public/build# Sentry Config File -.env.sentry-build-plugin diff --git a/examples/react/start-basic-rsc/README.md b/examples/react/start-basic-rsc/README.md deleted file mode 100644 index 494e34f03f..0000000000 --- a/examples/react/start-basic-rsc/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# TanStack Start - RSC Example - -This site is built with TanStack Router and React Server Components! - -- [TanStack Router Docs](https://tanstack.com/router) - -## Start a new project based on this example - -To start a new project based on this example, run: - -```sh -npx gitpick TanStack/router/tree/main/examples/react/start-basic-rsc start-basic-rsc -``` - -## Deployment - -It's deployed automagically with Netlify! - -- [Netlify](https://netlify.com/) - -## Getting Started - -From your terminal: - -```sh -pnpm install -pnpm dev -``` - -## Build - -Build for production: - -```sh -pnpm build -``` - -## About This Example - -This example demonstrates: - -- React Server Components (RSC) with TanStack Start -- Server-side rendering diff --git a/examples/react/start-basic-rsc/package.json b/examples/react/start-basic-rsc/package.json deleted file mode 100644 index 90d1f9142e..0000000000 --- a/examples/react/start-basic-rsc/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "tanstack-start-example-basic-rsc", - "private": true, - "sideEffects": false, - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "exit 0; vite build", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" - }, - "dependencies": { - "@babel/plugin-syntax-typescript": "^7.25.9", - "@tanstack/react-router": "^1.141.8", - "@tanstack/react-router-devtools": "^1.141.8", - "@tanstack/react-start": "^1.142.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwind-merge": "^2.6.0" - }, - "devDependencies": { - "@types/react": "^19.0.8", - "@types/react-dom": "^19.0.3", - "@vitejs/plugin-react": "^4.3.4", - "postcss": "^8.5.1", - "autoprefixer": "^10.4.20", - "tailwindcss": "^3.4.17", - "typescript": "^5.7.2", - "vite": "^7.1.7", - "vite-tsconfig-paths": "^5.1.4" - }, - "overrides": { - "react": "0.0.0-experimental-035a41c4e-20230704", - "react-dom": "0.0.0-experimental-035a41c4e-20230704" - } -} diff --git a/examples/react/start-basic-rsc/postcss.config.mjs b/examples/react/start-basic-rsc/postcss.config.mjs deleted file mode 100644 index 2e7af2b7f1..0000000000 --- a/examples/react/start-basic-rsc/postcss.config.mjs +++ /dev/null @@ -1,6 +0,0 @@ -export default { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -} diff --git a/examples/react/start-basic-rsc/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-rsc/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index 15f316681c..0000000000 --- a/examples/react/start-basic-rsc/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { - ErrorComponent, - Link, - rootRouteId, - useMatch, - useRouter, -} from '@tanstack/react-router' -import type { ErrorComponentProps } from '@tanstack/react-router' - -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useMatch({ - strict: false, - select: (state) => state.id === rootRouteId, - }) - - console.error(error) - - return ( -
    - -
    - - {isRoot ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
    -
    - ) -} diff --git a/examples/react/start-basic-rsc/src/components/NotFound.tsx b/examples/react/start-basic-rsc/src/components/NotFound.tsx deleted file mode 100644 index 7b54fa5680..0000000000 --- a/examples/react/start-basic-rsc/src/components/NotFound.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link } from '@tanstack/react-router' - -export function NotFound({ children }: { children?: any }) { - return ( -
    -
    - {children ||

    The page you are looking for does not exist.

    } -
    -

    - - - Start Over - -

    -
    - ) -} diff --git a/examples/react/start-basic-rsc/src/routeTree.gen.ts b/examples/react/start-basic-rsc/src/routeTree.gen.ts deleted file mode 100644 index 2f5748f578..0000000000 --- a/examples/react/start-basic-rsc/src/routeTree.gen.ts +++ /dev/null @@ -1,262 +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 PostsRouteImport } from './routes/posts' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as IndexRouteImport } from './routes/index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' - -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/posts': typeof PostsRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/posts/': typeof PostsIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/posts/$postId': typeof PostsPostIdRoute - '/posts': typeof PostsIndexRoute - '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/posts/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren - '/posts': typeof PostsRouteWithChildren - '/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren - '/posts/$postId': typeof PostsPostIdRoute - '/posts/': typeof PostsIndexRoute - '/_pathlessLayout/_nested-layout/route-a': typeof PathlessLayoutNestedLayoutRouteARoute - '/_pathlessLayout/_nested-layout/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute - '/posts_/$postId/deep': typeof PostsPostIdDeepRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/posts' - | '/posts/$postId' - | '/posts/' - | '/route-a' - | '/route-b' - | '/posts/$postId/deep' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/posts/$postId' - | '/posts' - | '/route-a' - | '/route-b' - | '/posts/$postId/deep' - id: - | '__root__' - | '/' - | '/_pathlessLayout' - | '/posts' - | '/_pathlessLayout/_nested-layout' - | '/posts/$postId' - | '/posts/' - | '/_pathlessLayout/_nested-layout/route-a' - | '/_pathlessLayout/_nested-layout/route-b' - | '/posts_/$postId/deep' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren - PostsRoute: typeof PostsRouteWithChildren - PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/_nested-layout/route-b': { - id: '/_pathlessLayout/_nested-layout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } - } -} - -interface PathlessLayoutNestedLayoutRouteChildren { - PathlessLayoutNestedLayoutRouteARoute: typeof PathlessLayoutNestedLayoutRouteARoute - PathlessLayoutNestedLayoutRouteBRoute: typeof PathlessLayoutNestedLayoutRouteBRoute -} - -const PathlessLayoutNestedLayoutRouteChildren: PathlessLayoutNestedLayoutRouteChildren = - { - PathlessLayoutNestedLayoutRouteARoute: - PathlessLayoutNestedLayoutRouteARoute, - PathlessLayoutNestedLayoutRouteBRoute: - PathlessLayoutNestedLayoutRouteBRoute, - } - -const PathlessLayoutNestedLayoutRouteWithChildren = - PathlessLayoutNestedLayoutRoute._addFileChildren( - PathlessLayoutNestedLayoutRouteChildren, - ) - -interface PathlessLayoutRouteChildren { - PathlessLayoutNestedLayoutRoute: typeof PathlessLayoutNestedLayoutRouteWithChildren -} - -const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { - PathlessLayoutNestedLayoutRoute: PathlessLayoutNestedLayoutRouteWithChildren, -} - -const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( - PathlessLayoutRouteChildren, -) - -interface PostsRouteChildren { - PostsPostIdRoute: typeof PostsPostIdRoute - PostsIndexRoute: typeof PostsIndexRoute -} - -const PostsRouteChildren: PostsRouteChildren = { - PostsPostIdRoute: PostsPostIdRoute, - PostsIndexRoute: PostsIndexRoute, -} - -const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - PathlessLayoutRoute: PathlessLayoutRouteWithChildren, - PostsRoute: PostsRouteWithChildren, - PostsPostIdDeepRoute: PostsPostIdDeepRoute, -} -export const routeTree = rootRouteImport - ._addFileChildren(rootRouteChildren) - ._addFileTypes() - -import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' -declare module '@tanstack/react-start' { - interface Register { - router: Awaited> - } -} diff --git a/examples/react/start-basic-rsc/src/router.tsx b/examples/react/start-basic-rsc/src/router.tsx deleted file mode 100644 index f648dfcf8c..0000000000 --- a/examples/react/start-basic-rsc/src/router.tsx +++ /dev/null @@ -1,22 +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() { - const router = createRouter({ - routeTree, - defaultPreload: 'intent', - defaultErrorComponent: DefaultCatchBoundary, - defaultNotFoundComponent: () => , - scrollRestoration: true, - }) - - return router -} - -declare module '@tanstack/react-router' { - interface Register { - router: ReturnType - } -} diff --git a/examples/react/start-basic-rsc/src/routes/__root.tsx b/examples/react/start-basic-rsc/src/routes/__root.tsx deleted file mode 100644 index 0a5e0bf370..0000000000 --- a/examples/react/start-basic-rsc/src/routes/__root.tsx +++ /dev/null @@ -1,125 +0,0 @@ -/// -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' -import * as React from 'react' -import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' -import { NotFound } from '~/components/NotFound' -import appCss from '~/styles/app.css?url' -import { seo } from '~/utils/seo' - -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { - charSet: 'utf-8', - }, - { - name: 'viewport', - content: 'width=device-width, initial-scale=1', - }, - ...seo({ - title: - 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', - description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, - }), - ], - links: [ - { rel: 'stylesheet', href: appCss }, - { - rel: 'apple-touch-icon', - sizes: '180x180', - href: '/apple-touch-icon.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '32x32', - href: '/favicon-32x32.png', - }, - { - rel: 'icon', - type: 'image/png', - sizes: '16x16', - href: '/favicon-16x16.png', - }, - { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, - { rel: 'icon', href: '/favicon.ico' }, - ], - }), - errorComponent: (props) => { - return ( - - - - ) - }, - notFoundComponent: () => , - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - ) -} - -function RootDocument({ children }: { children: React.ReactNode }) { - return ( - - - - - -
    - - Home - {' '} - - Posts - - - Pathless Layout - - - This Route Does Not Exist - -
    -
    - {/* {children} */} - {children} - - - - - ) -} diff --git a/examples/react/start-basic-rsc/src/routes/index.tsx b/examples/react/start-basic-rsc/src/routes/index.tsx deleted file mode 100644 index d531858f8c..0000000000 --- a/examples/react/start-basic-rsc/src/routes/index.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
    -

    Welcome Home!

    -
    - ) -} diff --git a/examples/react/start-basic-rsc/src/routes/posts.$postId.tsx b/examples/react/start-basic-rsc/src/routes/posts.$postId.tsx deleted file mode 100644 index f3dba9bfd3..0000000000 --- a/examples/react/start-basic-rsc/src/routes/posts.$postId.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { ErrorComponent, Link, createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { fetchPost } from '../utils/posts' -import type { ErrorComponentProps } from '@tanstack/react-router' -import { NotFound } from '~/components/NotFound' - -const renderPost = createServerFn({ method: 'GET' }) - .inputValidator((postId: string) => postId) - .handler(async ({ data }) => { - const post = await fetchPost(data) - - return ( -
    -

    {post.title}

    -
    {post.body}
    - - Deep View - -
    - ) - }) - -export const Route = createFileRoute('/posts/$postId')({ - loader: async ({ params: { postId } }) => renderPost({ data: postId }), - errorComponent: PostErrorComponent, - component: PostComponent, - notFoundComponent: () => { - return Post not found - }, -}) - -export function PostErrorComponent({ error }: ErrorComponentProps) { - return -} - -function PostComponent() { - return Route.useLoaderData() -} diff --git a/examples/react/start-basic-rsc/src/routes/posts.index.tsx b/examples/react/start-basic-rsc/src/routes/posts.index.tsx deleted file mode 100644 index c659274567..0000000000 --- a/examples/react/start-basic-rsc/src/routes/posts.index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -export const Route = createFileRoute('/posts/')({ - component: PostsIndexComponent, -}) - -function PostsIndexComponent() { - return
    Select a post.
    -} diff --git a/examples/react/start-basic-rsc/src/routes/posts.tsx b/examples/react/start-basic-rsc/src/routes/posts.tsx deleted file mode 100644 index a3ef2a2e20..0000000000 --- a/examples/react/start-basic-rsc/src/routes/posts.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createServerFn, renderRsc } from '@tanstack/react-start' -import { renderPosts } from '~/utils/renderPosts' - -export const serverRenderPosts = createServerFn({ method: 'GET' }).handler( - renderPosts, -) - -export const Route = createFileRoute('/posts')({ - loader: async () => serverRenderPosts(), - component: PostsComponent, -}) - -function PostsComponent() { - return renderRsc(Route.useLoaderData()) -} diff --git a/examples/react/start-basic-rsc/src/routes/posts_.$postId.deep.tsx b/examples/react/start-basic-rsc/src/routes/posts_.$postId.deep.tsx deleted file mode 100644 index 13d368cf9c..0000000000 --- a/examples/react/start-basic-rsc/src/routes/posts_.$postId.deep.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' -import { fetchPost } from '../utils/posts' -import { PostErrorComponent } from './posts.$postId' - -export const Route = createFileRoute('/posts_/$postId/deep')({ - loader: async ({ params: { postId } }) => fetchPost(postId), - errorComponent: PostErrorComponent, - component: PostDeepComponent, -}) - -function PostDeepComponent() { - const post = Route.useLoaderData() - - return ( -
    - - ← All Posts - -

    {post.title}

    -
    {post.body}
    -
    - ) -} diff --git a/examples/react/start-basic-rsc/src/styles/app.css b/examples/react/start-basic-rsc/src/styles/app.css deleted file mode 100644 index c53c870665..0000000000 --- a/examples/react/start-basic-rsc/src/styles/app.css +++ /dev/null @@ -1,22 +0,0 @@ -@tailwind base; -@tailwind components; -@tailwind utilities; - -@layer base { - html { - color-scheme: light dark; - } - - * { - @apply border-gray-200 dark:border-gray-800; - } - - html, - body { - @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; - } - - .using-mouse * { - outline: none !important; - } -} diff --git a/examples/react/start-basic-rsc/src/utils/posts.tsx b/examples/react/start-basic-rsc/src/utils/posts.tsx deleted file mode 100644 index 16fc1744e6..0000000000 --- a/examples/react/start-basic-rsc/src/utils/posts.tsx +++ /dev/null @@ -1,35 +0,0 @@ -// import { notFound } from '@tanstack/react-router' -// import { createServerFn } from '@tanstack/react-start' -import axios from 'redaxios' - -export type PostType = { - id: string - title: string - body: string -} - -export const fetchPost = async (postId: string) => { - 'use server' - console.info(`Fetching post with id ${postId}...`) - await new Promise((r) => setTimeout(r, 500)) - const post = await axios - .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) - .then((r) => r.data) - .catch((err) => { - if (err.status === 404) { - // throw notFound() - } - throw err - }) - - return post -} - -export const fetchPosts = async () => { - 'use server' - console.info('Fetching posts...') - await new Promise((r) => setTimeout(r, 500)) - return axios - .get>('https://jsonplaceholder.typicode.com/posts') - .then((r) => r.data.slice(0, 10)) -} diff --git a/examples/react/start-basic-rsc/src/utils/renderPosts.tsx b/examples/react/start-basic-rsc/src/utils/renderPosts.tsx deleted file mode 100644 index 37c0661217..0000000000 --- a/examples/react/start-basic-rsc/src/utils/renderPosts.tsx +++ /dev/null @@ -1,63 +0,0 @@ -'use server' - -import React from 'react' -import { fetchPosts } from './posts' - -export async function renderPosts() { - const posts = await fetchPosts() - - posts.state = posts.state || { - status: 'pending', - promise: Promise.resolve(), - } - - return ( -
    -
      - {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }]?.map( - (post) => { - return ( -
    • - {post.title.substring(0, 20)} - {/* -
      {post.title.substring(0, 20)}
      - */} -
    • - ) - }, - )} -
    -
    - Loading...
    }> - - -

    ; + data: Data; + pluginArgs: PluginArgs; +}; +type PagesPluginFunction = Record, PluginArgs = unknown> = (context: EventPluginContext) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; } // Copyright (c) 2022-2023 Cloudflare, Inc. // Licensed under the Apache 2.0 license found in the LICENSE file or at: // https://opensource.org/licenses/Apache-2.0 -declare module 'cloudflare:pipelines' { - export abstract class PipelineTransformationEntrypoint< - Env = unknown, - I extends PipelineRecord = PipelineRecord, - O extends PipelineRecord = PipelineRecord, - > { - protected env: Env - protected ctx: ExecutionContext - constructor(ctx: ExecutionContext, env: Env) - /** - * run recieves an array of PipelineRecord which can be - * transformed and returned to the pipeline - * @param records Incoming records from the pipeline to be transformed - * @param metadata Information about the specific pipeline calling the transformation entrypoint - * @returns A promise containing the transformed PipelineRecord array - */ - public run(records: I[], metadata: PipelineBatchMetadata): Promise - } - export type PipelineRecord = Record - export type PipelineBatchMetadata = { - pipelineId: string - pipelineName: string - } - export interface Pipeline { - /** - * The Pipeline interface represents the type of a binding to a Pipeline - * - * @param records The records to send to the pipeline - */ - send(records: T[]): Promise - } +declare module "cloudflare:pipelines" { + export abstract class PipelineTransformationEntrypoint { + protected env: Env; + protected ctx: ExecutionContext; + constructor(ctx: ExecutionContext, env: Env); + /** + * run receives an array of PipelineRecord which can be + * transformed and returned to the pipeline + * @param records Incoming records from the pipeline to be transformed + * @param metadata Information about the specific pipeline calling the transformation entrypoint + * @returns A promise containing the transformed PipelineRecord array + */ + public run(records: I[], metadata: PipelineBatchMetadata): Promise; + } + export type PipelineRecord = Record; + export type PipelineBatchMetadata = { + pipelineId: string; + pipelineName: string; + }; + export interface Pipeline { + /** + * The Pipeline interface represents the type of a binding to a Pipeline + * + * @param records The records to send to the pipeline + */ + send(records: T[]): Promise; + } } // PubSubMessage represents an incoming PubSub message. // The message includes metadata about the broker, the client, and the payload // itself. // https://developers.cloudflare.com/pub-sub/ interface PubSubMessage { - // Message ID - readonly mid: number - // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT - readonly broker: string - // The MQTT topic the message was sent on. - readonly topic: string - // The client ID of the client that published this message. - readonly clientId: string - // The unique identifier (JWT ID) used by the client to authenticate, if token - // auth was used. - readonly jti?: string - // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker - // received the message from the client. - readonly receivedAt: number - // An (optional) string with the MIME type of the payload, if set by the - // client. - readonly contentType: string - // Set to 1 when the payload is a UTF-8 string - // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 - readonly payloadFormatIndicator: number - // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. - // You can use payloadFormatIndicator to inspect this before decoding. - payload: string | Uint8Array + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; } // JsonWebKey extended by kid parameter interface JsonWebKeyWithKid extends JsonWebKey { - // Key Identifier of the JWK - readonly kid: string + // Key Identifier of the JWK + readonly kid: string; } interface RateLimitOptions { - key: string + key: string; } interface RateLimitOutcome { - success: boolean + success: boolean; } interface RateLimit { - /** - * Rate limit a request based on the provided options. - * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ - * @returns A promise that resolves with the outcome of the rate limit. - */ - limit(options: RateLimitOptions): Promise + /** + * Rate limit a request based on the provided options. + * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ + * @returns A promise that resolves with the outcome of the rate limit. + */ + limit(options: RateLimitOptions): Promise; } // Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need // to referenced by `Fetcher`. This is included in the "importable" version of the types which // strips all `module` blocks. declare namespace Rpc { - // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. - // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. - // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to - // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) - export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND' - export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND' - export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND' - export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND' - export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND' - export interface RpcTargetBranded { - [__RPC_TARGET_BRAND]: never - } - export interface WorkerEntrypointBranded { - [__WORKER_ENTRYPOINT_BRAND]: never - } - export interface DurableObjectBranded { - [__DURABLE_OBJECT_BRAND]: never - } - export interface WorkflowEntrypointBranded { - [__WORKFLOW_ENTRYPOINT_BRAND]: never - } - export type EntrypointBranded = - | WorkerEntrypointBranded - | DurableObjectBranded - | WorkflowEntrypointBranded - // Types that can be used through `Stub`s - export type Stubable = RpcTargetBranded | ((...args: any[]) => any) - // Types that can be passed over RPC - // The reason for using a generic type here is to build a serializable subset of structured - // cloneable composite types. This allows types defined with the "interface" keyword to pass the - // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. - type Serializable = + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND'; + export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND'; + export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND'; + export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND'; + export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND'; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export interface WorkflowEntrypointBranded { + [__WORKFLOW_ENTRYPOINT_BRAND]: never; + } + export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + // The reason for using a generic type here is to build a serializable subset of structured + // cloneable composite types. This allows types defined with the "interface" keyword to pass the + // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. + type Serializable = // Structured cloneables - | BaseType + BaseType // Structured cloneable composites - | Map< - T extends Map ? Serializable : never, - T extends Map ? Serializable : never - > - | Set ? Serializable : never> - | ReadonlyArray ? Serializable : never> - | { - [K in keyof T]: K extends number | string ? Serializable : never - } + | Map ? Serializable : never, T extends Map ? Serializable : never> | Set ? Serializable : never> | ReadonlyArray ? Serializable : never> | { + [K in keyof T]: K extends number | string ? Serializable : never; + } // Special types - | Stub + | Stub // Serialized as stubs, see `Stubify` - | Stubable - // Base type for all RPC stubs, including common memory management methods. - // `T` is used as a marker type for unwrapping `Stub`s later. - interface StubBase extends Disposable { - [__RPC_STUB_BRAND]: T - dup(): this - } - export type Stub = Provider & StubBase - // This represents all the types that can be sent as-is over an RPC boundary - type BaseType = - | void - | undefined - | null - | boolean - | number - | bigint - | string - | TypedArray - | ArrayBuffer - | DataView - | Date - | Error - | RegExp - | ReadableStream - | WritableStream - | Request - | Response - | Headers - // Recursively rewrite all `Stubable` types with `Stub`s - // prettier-ignore - type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // This represents all the types that can be sent as-is over an RPC boundary + type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream | WritableStream | Request | Response | Headers; + // Recursively rewrite all `Stubable` types with `Stub`s + // prettier-ignore + type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { [key: string | number]: any; } ? { [K in keyof T]: Stubify; } : T; - // Recursively rewrite all `Stub`s with the corresponding `T`s. - // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: - // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. - // prettier-ignore - type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + // prettier-ignore + type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { [key: string | number]: unknown; } ? { [K in keyof T]: Unstubify; } : T; - type UnstubifyAll = { - [I in keyof A]: Unstubify - } - // Utility type for adding `Provider`/`Disposable`s to `object` types only. - // Note `unknown & T` is equivalent to `T`. - type MaybeProvider = T extends object ? Provider : unknown - type MaybeDisposable = T extends object ? Disposable : unknown - // Type for method return or property on an RPC interface. - // - Stubable types are replaced by stubs. - // - Serializable types are passed by value, with stubable types replaced by stubs - // and a top-level `Disposer`. - // Everything else can't be passed over PRC. - // Technically, we use custom thenables here, but they quack like `Promise`s. - // Intersecting with `(Maybe)Provider` allows pipelining. - // prettier-ignore - type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never; - // Type for method or property on an RPC interface. - // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. - // Unwrapping `Stub`s allows calling with `Stubable` arguments. - // For properties, rewrite types to be `Result`s. - // In each case, unwrap `Promise`s. - type MethodOrProperty = V extends (...args: infer P) => infer R - ? (...args: UnstubifyAll